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, AgentKind, AgentModel, AgentSelection, CreateTaskRequest,
12 ReasoningLevel, 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 /// [`crate::Session::graph_question_target`] of the graph questions the
60 /// answers are for, as the snapshot the answers were entered on
61 /// reported it. `None` answers the questions of the session's own turn.
62 /// The host refuses answers for graph work other than the one pending
63 /// now, even when it asks the same questions.
64 pub graph_question_target: Option<String>,
65}
66
67/// One encoded image a frontend sends with a chat message, whose bytes the
68/// host writes to its own prompt-image directory and attaches to the turn.
69///
70/// Only PNG and JPEG files are accepted, recognized by their signature, so
71/// the host never trusts a name or media type the sender chose.
72#[derive(Clone, Debug, Eq, PartialEq)]
73pub struct MessageImage {
74 data: Vec<u8>,
75 format: MessageImageFormat,
76}
77
78impl MessageImage {
79 /// Wraps the encoded bytes of one PNG or JPEG image.
80 ///
81 /// # Errors
82 /// Returns an error when `data` is neither a PNG nor a JPEG file.
83 pub fn new(data: Vec<u8>) -> Result<Self, SessionError> {
84 let format = MessageImageFormat::of(&data).ok_or_else(|| {
85 SessionError::Operation("Only PNG and JPEG images can be attached".to_string())
86 })?;
87
88 Ok(Self { data, format })
89 }
90
91 /// Returns the encoded image bytes.
92 #[must_use]
93 pub fn data(&self) -> &[u8] {
94 &self.data
95 }
96
97 /// Returns the image's file format.
98 #[must_use]
99 pub fn format(&self) -> MessageImageFormat {
100 self.format
101 }
102
103 /// Returns the encoded image bytes, consuming the image.
104 #[must_use]
105 pub fn into_data(self) -> Vec<u8> {
106 self.data
107 }
108}
109
110/// File format of one [`MessageImage`].
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
112pub enum MessageImageFormat {
113 /// A JPEG image.
114 Jpeg,
115 /// A PNG image.
116 Png,
117}
118
119impl MessageImageFormat {
120 /// Returns the file extension the host stores the image under.
121 #[must_use]
122 pub fn extension(self) -> &'static str {
123 match self {
124 Self::Jpeg => "jpg",
125 Self::Png => "png",
126 }
127 }
128
129 /// Recognizes the format of `data` by its file signature.
130 fn of(data: &[u8]) -> Option<Self> {
131 const JPEG_SIGNATURE: &[u8] = &[0xFF, 0xD8, 0xFF];
132 const PNG_SIGNATURE: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
133
134 if data.starts_with(PNG_SIGNATURE) {
135 Some(Self::Png)
136 } else if data.starts_with(JPEG_SIGNATURE) {
137 Some(Self::Jpeg)
138 } else {
139 None
140 }
141 }
142}
143
144/// Idempotent turn submitted to one session.
145#[derive(Clone, Debug, Eq, PartialEq)]
146pub struct DurableMessageRequest {
147 /// Agent-facing prompt.
148 pub message: String,
149 /// Stable operation identifier reused when delivery is retried.
150 pub operation_id: String,
151 /// Whether the machine-authored prompt is shown in the human transcript.
152 pub visibility: DurableMessageVisibility,
153}
154
155/// Transcript treatment for one durable prompt.
156#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
157pub enum DurableMessageVisibility {
158 /// Deliver generated context without displaying it as user chat.
159 #[default]
160 Hidden,
161 /// Display the submitted instruction in session history.
162 Visible,
163}
164
165/// Operation a host may choose to serve to frontends that check
166/// [`SessionService::supports`] first, such as remote control.
167///
168/// A frontend offers an operation only when the host reports it, so adding a
169/// variant never exposes an operation that an existing host has not opted
170/// into.
171#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
172#[non_exhaustive]
173pub enum SessionOperation {
174 /// Creating a session in the active project through
175 /// [`SessionBackend::create_session`].
176 CreateSession,
177 /// Describing the active project through
178 /// [`SessionBackend::host_context`].
179 HostContext,
180 /// Merging a review-ready session through
181 /// [`SessionBackend::merge_session`].
182 MergeSession,
183 /// Reading a session's changes through
184 /// [`SessionBackend::get_session_diff`].
185 SessionDiff,
186 /// Listing the files and directories in the active project's checkout
187 /// through [`SessionBackend::list_project_files`], for drafting a new
188 /// session before it has a worktree.
189 ProjectFiles,
190 /// Listing the files and directories in a session's worktree through
191 /// [`SessionBackend::list_session_files`].
192 SessionFiles,
193 /// Stopping a running turn through [`SessionBackend::stop_turn`].
194 StopTurn,
195 /// Rebasing a session branch onto its base branch through
196 /// [`SessionBackend::rebase_session`].
197 RebaseSession,
198 /// Changing a session's model, reasoning, style, or speed through
199 /// [`SessionBackend::update_session_settings`].
200 SessionSettings,
201 /// Publishing a session to its existing branch, or under its default name
202 /// the first time, and creating or refreshing its review request through
203 /// [`SessionBackend::create_review_request`].
204 PublishSession,
205 /// Reporting the active project's branch, its distance from upstream,
206 /// and its latest sync through [`SessionBackend::project_status`].
207 ProjectStatus,
208 /// Syncing the active project's branch with its upstream through
209 /// [`SessionBackend::sync_project`].
210 SyncProject,
211 /// Reading a session's graph proposal and execution graphs through
212 /// [`SessionBackend::session_graphs`], and summarizing them in
213 /// [`Session::graph`].
214 Graphs,
215 /// Acting on a session's execution graph as its inspector does, bound
216 /// to the snapshot a [`SessionBackend::session_graphs`] read returned,
217 /// through [`SessionBackend::act_on_session_graph`].
218 GraphActions,
219 /// Generating a graph proposal for a task, as the host's own graph
220 /// command does, through [`SessionBackend::generate_graph_proposal`].
221 /// Nothing launches until a reply approves the proposal.
222 GenerateGraphProposal,
223 /// Sending a chat message with images through
224 /// [`SessionBackend::send_message_with_images`].
225 MessageImages,
226 /// Listing the host's projects through [`SessionBackend::list_projects`],
227 /// and serving a [`ProjectScope::Project`] to the methods that take a
228 /// [`ProjectScope`], such as [`SessionBackend::project_sessions`].
229 Projects,
230}
231
232/// Project that a request which takes a project is for.
233///
234/// The active project is the one the host's own frontend has open, read when
235/// the host serves the request, so a frontend that sends
236/// [`ProjectScope::Active`] follows the host when it switches projects. A
237/// host serves another project only when it supports
238/// [`SessionOperation::Projects`] and lists that project in
239/// [`SessionBackend::list_projects`].
240#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
241pub enum ProjectScope {
242 /// The host's active project when it serves the request.
243 #[default]
244 Active,
245 /// The listed project with this identifier, whether or not it is
246 /// active.
247 Project(i64),
248}
249
250impl ProjectScope {
251 /// Refuses every scope but [`Self::Active`], for hosts that serve only
252 /// their active project.
253 fn require_active(self) -> Result<(), SessionError> {
254 match self {
255 Self::Active => Ok(()),
256 Self::Project(_) => Err(SessionError::Operation(
257 "Host serves only its active project".to_string(),
258 )),
259 }
260 }
261}
262
263/// One project a host lists, as its project switcher shows it.
264#[derive(Clone, Debug, Eq, PartialEq)]
265pub struct HostProject {
266 /// Sessions of the project still in an active lifecycle state.
267 pub active_session_count: u32,
268 /// Identifier a [`ProjectScope::Project`] names the project by.
269 pub id: i64,
270 /// Whether the project is the host's active project.
271 pub is_active: bool,
272 /// Display name of the project.
273 pub name: String,
274}
275
276/// One project's session list and status.
277///
278/// A host that names the project in `project_id` read the list and the
279/// status together, so both describe that project even when the host
280/// switches projects meanwhile. Without `project_id`, they were read one
281/// after the other, and a switch between the two reads can pair one
282/// project's sessions with another project's status.
283#[derive(Clone, Debug, Eq, PartialEq)]
284pub struct ProjectSessions {
285 /// The project's listed sessions in the host's display order, with list
286 /// stats when the host provides them.
287 pub entries: Vec<SessionListEntry>,
288 /// Identifier of the project both the list and the status belong to;
289 /// `None` when the host does not say which project it is and did not
290 /// read them together.
291 pub project_id: Option<i64>,
292 /// The project's branch, distance from upstream, and latest sync;
293 /// `None` when the host does not report project status.
294 pub status: Option<HostProjectStatus>,
295}
296
297/// Settings to change on one session; `None` keeps a setting as it is.
298#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
299pub struct SessionSettingsChange {
300 /// Agent to run `model`, as the terminal's `/model` picks one before the
301 /// model; `None` keeps the session's own agent. It names an agent only
302 /// together with `model`, since agents share model ids.
303 pub agent: Option<AgentKind>,
304 /// Model to switch to, run by `agent`.
305 pub model: Option<AgentModel>,
306 /// Reasoning level to use for later turns.
307 pub reasoning_level: Option<ReasoningLevel>,
308 /// Response style to use for later turns.
309 pub response_style: Option<ResponseStyle>,
310 /// Response speed to use for later turns.
311 pub speed_mode: Option<SpeedMode>,
312}
313
314/// One file a session's diff changes.
315#[derive(Clone, Debug, Eq, PartialEq)]
316pub struct SessionDiffFile {
317 /// Lines the file's patch adds.
318 pub added_lines: u64,
319 /// Lines the file's patch removes.
320 pub deleted_lines: u64,
321 /// Path before a rename, or `None` when the path did not change.
322 pub old_path: Option<String>,
323 /// The file's unified diff, including its `diff --git` header.
324 pub patch: String,
325 /// Path after the change; a deleted file keeps its old path.
326 pub path: String,
327 /// How the change affects the file.
328 pub status: SessionDiffFileStatus,
329}
330
331/// How a session's diff changes one file.
332#[derive(Clone, Copy, Debug, Eq, PartialEq)]
333pub enum SessionDiffFileStatus {
334 /// The file is new.
335 Added,
336 /// The file is removed.
337 Deleted,
338 /// The file's contents or mode changed.
339 Modified,
340 /// The file moved, possibly with changes.
341 Renamed,
342}
343
344/// One file or directory in a session's worktree or the active project's
345/// checkout.
346#[derive(Clone, Debug, Eq, PartialEq)]
347pub struct SessionFileEntry {
348 /// Whether the entry is a directory.
349 pub is_dir: bool,
350 /// Path relative to the listed root, with `/` separators.
351 pub path: String,
352}
353
354/// The project a host creates new sessions in, and how it creates them.
355#[derive(Clone, Debug, Eq, PartialEq)]
356pub struct HostContext {
357 /// Branch new sessions start from.
358 pub base_branch: String,
359 /// Model a new session in the first of `session_modes` starts with: the
360 /// harness model when only Harness sessions are offered, otherwise the
361 /// regular agent's default.
362 pub default_model: AgentModel,
363 /// Agents and models a session can switch to now, in display order, as
364 /// the terminal's `/model` offers them; each gives the model's id and
365 /// name.
366 pub models: Vec<AgentSelection>,
367 /// Identifier of the project described, which new sessions requested
368 /// for it are created in: the active project unless the request named
369 /// another through [`ProjectScope::Project`].
370 pub project_id: i64,
371 /// Display name of the project described.
372 pub project_name: String,
373 /// Creation modes the host can serve now, in display order, each with
374 /// the agent and model its new sessions start with.
375 pub session_modes: Vec<HostSessionMode>,
376}
377
378/// One creation mode a host serves, and how its new sessions start.
379#[derive(Clone, Debug, Eq, PartialEq)]
380pub struct HostSessionMode {
381 /// Agent and model a new session in this mode starts with.
382 pub agent: AgentSelection,
383 /// Creation mode.
384 pub mode: CreateSessionMode,
385 /// Reasoning level a new session in this mode starts with.
386 pub reasoning_level: ReasoningLevel,
387 /// Response style a new session in this mode starts with.
388 pub response_style: ResponseStyle,
389 /// Response-speed preference a new session in this mode starts with.
390 pub speed_mode: SpeedMode,
391}
392
393/// One of the host's projects, the active one unless a request named another,
394/// as a session list shows it.
395#[derive(Clone, Debug, Eq, PartialEq)]
396pub struct HostProjectStatus {
397 /// Commits the branch is ahead of and behind its upstream, in that
398 /// order, as of the host's latest fetch; `None` when the host has not
399 /// compared them.
400 pub ahead_behind: Option<(u32, u32)>,
401 /// Branch the project's checkout is on, which new sessions start from;
402 /// `None` when it has none, such as a detached `HEAD`.
403 pub branch: Option<String>,
404 /// Display name of the project.
405 pub project_name: String,
406 /// Latest explicit sync of this project, while the host still shows it.
407 pub sync: Option<HostProjectSync>,
408}
409
410/// One explicit sync of a project's branch with its upstream.
411#[derive(Clone, Debug, Eq, PartialEq)]
412pub struct HostProjectSync {
413 /// Branch the sync updates.
414 pub branch: String,
415 /// How far the sync has come.
416 pub phase: HostProjectSyncPhase,
417}
418
419/// How far an explicit project sync has come.
420#[derive(Clone, Debug, Eq, PartialEq)]
421pub enum HostProjectSyncPhase {
422 /// The host is pulling, rebasing, or pushing.
423 Running,
424 /// An agent is resolving the conflicts of this many files.
425 ResolvingConflicts {
426 /// Files the rebase left in conflict.
427 conflicted_file_count: usize,
428 },
429 /// The branch matches its upstream.
430 Complete {
431 /// Commits pulled from upstream, when the host counted them.
432 pulled_commits: Option<u32>,
433 /// Local commits pushed upstream, when the host counted them.
434 pushed_commits: Option<u32>,
435 /// Files whose conflicts the agent resolved.
436 resolved_conflict_count: usize,
437 },
438 /// The host did not start the sync, such as while a merge runs or the
439 /// checkout has uncommitted changes.
440 Blocked {
441 /// Why the sync could not start.
442 message: String,
443 },
444 /// Git, authentication, or conflict resolution failed.
445 Failed {
446 /// Why the sync failed.
447 message: String,
448 },
449}
450
451/// Host implementation boundary for session persistence and workflows.
452///
453/// The trait is object-safe so agent loops and background workflows can hold a
454/// programmatic session capability without depending on a concrete frontend.
455#[async_trait]
456pub trait SessionBackend: Send + Sync {
457 /// Reports whether the host serves `operation` to frontends that ask
458 /// first. Hosts serve none unless they opt in.
459 fn supports(&self, operation: SessionOperation) -> bool {
460 let _ = operation;
461
462 false
463 }
464
465 /// Reserves generation without waiting for model completion.
466 async fn generate_graph_proposal(
467 &self,
468 request: crate::GenerateGraphProposalRequest,
469 ) -> Result<(), SessionError> {
470 let _ = request;
471 Err(SessionError::Operation(
472 "Host does not support graph proposals".into(),
473 ))
474 }
475
476 /// Reads retained state without generating or launching work.
477 async fn get_graph_proposal(
478 &self,
479 id: &str,
480 ) -> Result<Option<crate::GraphProposalState>, SessionError> {
481 let _ = id;
482 Err(SessionError::Operation(
483 "Host does not support graph proposals".into(),
484 ))
485 }
486
487 /// Applies an explicit action to the exact inspected version.
488 async fn act_on_graph_proposal(
489 &self,
490 id: &str,
491 version: u32,
492 action: crate::GraphProposalAction,
493 ) -> Result<(), SessionError> {
494 let _ = (id, version, action);
495 Err(SessionError::Operation(
496 "Host does not support graph proposals".into(),
497 ))
498 }
499
500 /// Reads durable progress without launching or retrying work.
501 async fn get_execution_graph(
502 &self,
503 graph_id: &str,
504 ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
505 let _ = graph_id;
506
507 Err(SessionError::Operation(
508 "Host does not support execution graphs".into(),
509 ))
510 }
511
512 /// Reads a session's graphs, its latest proposal, and the selected
513 /// graph's live progress and outputs, without launching or changing any
514 /// work.
515 async fn session_graphs(
516 &self,
517 request: crate::SessionGraphsRequest,
518 ) -> Result<crate::SessionGraphs, SessionError> {
519 let _ = request;
520
521 Err(SessionError::Operation(
522 "Host does not support execution graphs".into(),
523 ))
524 }
525
526 /// Applies one inspector action to a session's graph, as the host's own
527 /// inspector would with the same node or output selected, only while the
528 /// graph still matches the snapshot the action was chosen from.
529 async fn act_on_session_graph(
530 &self,
531 request: crate::SessionGraphActionRequest,
532 ) -> Result<(), SessionError> {
533 let _ = request;
534
535 Err(SessionError::Operation(
536 "Host does not support execution graph actions".into(),
537 ))
538 }
539
540 /// Closes graph admission durably, then signals its owned workers.
541 async fn cancel_execution_graph(
542 &self,
543 request: crate::GraphControlRequest,
544 ) -> Result<(), SessionError> {
545 let _ = request;
546
547 Err(SessionError::Operation(
548 "Host does not support execution graphs".into(),
549 ))
550 }
551
552 /// Explicitly restarts dispatch without replaying admitted executions.
553 async fn resume_execution_graph(
554 &self,
555 request: crate::ResumeExecutionGraphRequest,
556 ) -> Result<(), SessionError> {
557 let _ = request;
558
559 Err(SessionError::Operation(
560 "Host does not support execution graphs".into(),
561 ))
562 }
563
564 /// Records an explicit increase of one budget's provider calls, then
565 /// releases nodes waiting for that credit.
566 async fn extend_execution_graph_budget(
567 &self,
568 request: crate::ExtendGraphBudgetRequest,
569 ) -> Result<(), SessionError> {
570 let _ = request;
571
572 Err(SessionError::Operation(
573 "Host does not support execution graphs".into(),
574 ))
575 }
576
577 /// Authorizes one new attempt against an exact failed/question execution.
578 async fn continue_execution_graph_node(
579 &self,
580 request: crate::ContinueGraphNodeRequest,
581 ) -> Result<(), SessionError> {
582 let _ = request;
583
584 Err(SessionError::Operation(
585 "Host does not support execution graphs".into(),
586 ))
587 }
588
589 /// Saves and starts a static graph. Existing admitted nodes are never
590 /// replayed. Named budgets are fixed at first launch and their spending is
591 /// recorded durably, so relaunching never replenishes them.
592 async fn start_execution_graph(
593 &self,
594 request: StartExecutionGraphRequest,
595 ) -> Result<(), SessionError> {
596 let _ = request;
597
598 Err(SessionError::Operation(
599 "Host does not support execution graphs".into(),
600 ))
601 }
602
603 /// Records explicit acceptance of an exact graph output and wakes ready
604 /// dependents. Model output must never call this trusted host boundary.
605 async fn accept_execution_graph_result(
606 &self,
607 reference: crate::GraphResultRef,
608 ) -> Result<(), SessionError> {
609 let _ = reference;
610
611 Err(SessionError::Operation(
612 "Host does not support execution graphs".into(),
613 ))
614 }
615 /// Admits a role-bound attempt with its own isolated conversation.
616 async fn submit_agent_task(
617 &self,
618 session_id: &SessionId,
619 request: crate::SubmitAgentTaskRequest,
620 ) -> Result<(), SessionError> {
621 let _ = (session_id, request);
622
623 Err(SessionError::Operation(
624 "Host does not support role-aware tasks".to_string(),
625 ))
626 }
627
628 /// Reads isolated task responses without exposing host storage types.
629 async fn get_agent_task_history(
630 &self,
631 task_id: &str,
632 ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
633 let _ = task_id;
634
635 Err(SessionError::Operation(
636 "Host does not support role-aware tasks".to_string(),
637 ))
638 }
639
640 /// Explicitly accepts a standalone Planner response by producing version.
641 async fn accept_agent_plan(
642 &self,
643 _session_id: &SessionId,
644 _request: AcceptTaskPlanRequest,
645 ) -> Result<(), SessionError> {
646 Err(SessionError::Operation(
647 "Host does not support plan acceptance".into(),
648 ))
649 }
650
651 /// Persists an outcome without execution. Older hosts may omit support.
652 async fn create_task(
653 &self,
654 _session_id: &SessionId,
655 _request: CreateTaskRequest,
656 ) -> Result<(), SessionError> {
657 Err(SessionError::Operation(
658 "Host does not support tasks".to_string(),
659 ))
660 }
661
662 /// Lists a session's tasks, including unattempted and completed outcomes.
663 async fn list_tasks(&self, _session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
664 Err(SessionError::Operation(
665 "Host does not support tasks".to_string(),
666 ))
667 }
668
669 /// Admits an explicit task attempt. Older hosts may omit task support.
670 async fn submit_task(
671 &self,
672 _session_id: &SessionId,
673 _request: SubmitTaskRequest,
674 ) -> Result<(), SessionError> {
675 Err(SessionError::Operation(
676 "Host does not support tasks".to_string(),
677 ))
678 }
679
680 /// Loads the desired outcome and retained attempt history.
681 async fn get_task(&self, _task_id: &str) -> Result<Option<Task>, SessionError> {
682 Err(SessionError::Operation(
683 "Host does not support tasks".to_string(),
684 ))
685 }
686
687 /// Explicitly accepts the task outcome after all attempts have settled.
688 async fn complete_task(&self, _task_id: &str) -> Result<(), SessionError> {
689 Err(SessionError::Operation(
690 "Host does not support tasks".to_string(),
691 ))
692 }
693
694 /// Lists the projects the host serves frontends, in the order its
695 /// project switcher shows them: the active project and every project
696 /// the switcher offers. Hosts that serve only their active project
697 /// report it as an error.
698 async fn list_projects(&self) -> Result<Vec<HostProject>, SessionError> {
699 Err(SessionError::Operation(
700 "Host does not list its projects".to_string(),
701 ))
702 }
703
704 /// Describes the active project new sessions are created in. Older hosts
705 /// may omit it.
706 async fn host_context(&self) -> Result<HostContext, SessionError> {
707 Err(SessionError::Operation(
708 "Host does not describe its project".to_string(),
709 ))
710 }
711
712 /// Describes `scope`'s project, which new sessions requested for it are
713 /// created in. Hosts that serve only their active project answer
714 /// [`ProjectScope::Active`] with [`Self::host_context`] and refuse every
715 /// other scope.
716 async fn host_context_for(&self, scope: ProjectScope) -> Result<HostContext, SessionError> {
717 scope.require_active()?;
718
719 self.host_context().await
720 }
721
722 /// Reports the active project's branch, its distance from upstream, and
723 /// its latest explicit sync. Older hosts may omit it.
724 async fn project_status(&self) -> Result<HostProjectStatus, SessionError> {
725 Err(SessionError::Operation(
726 "Host does not report its project status".to_string(),
727 ))
728 }
729
730 /// Lists `scope`'s sessions with the project's status in one call. A
731 /// host that reads both together names the project in
732 /// [`ProjectSessions::project_id`]. Hosts that serve only their active
733 /// project answer [`ProjectScope::Active`] with
734 /// [`Self::list_session_entries`] and then, when they support
735 /// [`SessionOperation::ProjectStatus`], [`Self::project_status`], without
736 /// naming the project, and refuse every other scope.
737 async fn project_sessions(&self, scope: ProjectScope) -> Result<ProjectSessions, SessionError> {
738 scope.require_active()?;
739
740 let entries = self.list_session_entries().await?;
741 let status = if self.supports(SessionOperation::ProjectStatus) {
742 Some(self.project_status().await?)
743 } else {
744 None
745 };
746
747 Ok(ProjectSessions {
748 entries,
749 project_id: None,
750 status,
751 })
752 }
753
754 /// Starts or queues a sync of the active project's branch with its
755 /// upstream: a pull with rebase, then a push, with agent-assisted
756 /// conflict resolution. The host acknowledges admission and reports
757 /// progress through [`Self::project_status`]. Older hosts may omit
758 /// support.
759 async fn sync_project(&self) -> Result<(), SessionError> {
760 Err(SessionError::Operation(
761 "Host does not support syncing its project".to_string(),
762 ))
763 }
764
765 /// Starts or queues a sync of `scope`'s branch with its upstream, as
766 /// [`Self::sync_project`] does for the active project. Hosts that serve
767 /// only their active project answer [`ProjectScope::Active`] with
768 /// [`Self::sync_project`] and refuse every other scope.
769 async fn sync_project_for(&self, scope: ProjectScope) -> Result<(), SessionError> {
770 scope.require_active()?;
771
772 self.sync_project().await
773 }
774
775 /// Creates one session and returns its stable identifier.
776 async fn create_session(
777 &self,
778 request: CreateSessionRequest,
779 ) -> Result<SessionId, SessionError>;
780
781 /// Loads one complete session aggregate, including settings and messages.
782 async fn get_session(&self, session_id: &SessionId) -> Result<Option<Session>, SessionError>;
783
784 /// Loads the files a session changes against its base branch, or `None`
785 /// when the host has not loaded the session. Hosts that do not serve
786 /// diffs report it as an error.
787 async fn get_session_diff(
788 &self,
789 session_id: &SessionId,
790 ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
791 let _ = session_id;
792
793 Err(SessionError::Operation(
794 "Host does not serve session diffs".to_string(),
795 ))
796 }
797
798 /// Lists the files and directories in a session's worktree, directories
799 /// first, or `None` when the host has not loaded the session. Hosts that
800 /// do not serve file listings report it as an error.
801 async fn list_session_files(
802 &self,
803 session_id: &SessionId,
804 ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
805 let _ = session_id;
806
807 Err(SessionError::Operation(
808 "Host does not serve session files".to_string(),
809 ))
810 }
811
812 /// Lists the files and directories in the active project's checkout,
813 /// directories first. Hosts that do not serve project file listings
814 /// report it as an error.
815 async fn list_project_files(&self) -> Result<Vec<SessionFileEntry>, SessionError> {
816 Err(SessionError::Operation(
817 "Host does not serve project files".to_string(),
818 ))
819 }
820
821 /// Lists the files and directories in `scope`'s checkout, directories
822 /// first. Hosts that serve only their active project answer
823 /// [`ProjectScope::Active`] with [`Self::list_project_files`] and refuse
824 /// every other scope.
825 async fn list_project_files_for(
826 &self,
827 scope: ProjectScope,
828 ) -> Result<Vec<SessionFileEntry>, SessionError> {
829 scope.require_active()?;
830
831 self.list_project_files().await
832 }
833
834 /// Lists the host's loaded sessions in its display order. Older hosts
835 /// may omit listing support.
836 async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
837 Err(SessionError::Operation(
838 "Host does not support session listing".to_string(),
839 ))
840 }
841
842 /// Lists the host's loaded sessions in its display order, with the
843 /// figures a dense list shows. Hosts that do not provide them return
844 /// [`Self::list_sessions`] without stats.
845 async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
846 let summaries = self.list_sessions().await?;
847
848 Ok(summaries.into_iter().map(SessionListEntry::from).collect())
849 }
850
851 /// Reports whether the host lists `session_id`: whether the session
852 /// appears in the session list of a project the host lists. Frontends
853 /// that may reach only listed sessions ask before acting on one. Hosts
854 /// that list only their active project answer whether
855 /// [`Self::list_sessions`] contains it.
856 async fn is_session_listed(&self, session_id: &SessionId) -> Result<bool, SessionError> {
857 let summaries = self.list_sessions().await?;
858
859 Ok(summaries.iter().any(|summary| &summary.id == session_id))
860 }
861
862 /// Sends one text message, starting, resuming, or queueing as appropriate.
863 async fn send_message(
864 &self,
865 session_id: &SessionId,
866 message: String,
867 ) -> Result<(), SessionError>;
868
869 /// Sends one message with images, which the host stores itself and
870 /// attaches as `[Image #n]`, numbered in `images` order from 1. A
871 /// placeholder `message` lacks is appended to it. Older hosts may omit
872 /// support.
873 async fn send_message_with_images(
874 &self,
875 session_id: &SessionId,
876 message: String,
877 images: Vec<MessageImage>,
878 ) -> Result<(), SessionError> {
879 let _ = (session_id, message, images);
880
881 Err(SessionError::Operation(
882 "Host does not support images in messages".to_string(),
883 ))
884 }
885
886 /// Submits a durable turn without entering the lossy live-chat
887 /// queue used while an ordinary user turn is active.
888 async fn submit_durable_message(
889 &self,
890 session_id: &SessionId,
891 request: DurableMessageRequest,
892 ) -> Result<(), SessionError>;
893
894 /// Answers the complete current clarification-question set.
895 async fn answer_questions(
896 &self,
897 session_id: &SessionId,
898 request: AnswerQuestionsRequest,
899 ) -> Result<(), SessionError>;
900
901 /// Cancels one session through the host lifecycle workflow.
902 async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
903
904 /// Stops the session's running turn and returns the session to review,
905 /// keeping its worktree and changes. Older hosts may omit support.
906 async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
907 let _ = session_id;
908
909 Err(SessionError::Operation(
910 "Host does not support stopping a turn".to_string(),
911 ))
912 }
913
914 /// Starts or queues a rebase of the session branch onto its base
915 /// branch; a conflict starts an agent-assisted resolution turn. Older
916 /// hosts may omit support.
917 async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
918 let _ = session_id;
919
920 Err(SessionError::Operation(
921 "Host does not support syncing a session branch".to_string(),
922 ))
923 }
924
925 /// Changes the session's settings for later turns. A model or speed
926 /// change waits while the session still has accepted work. Older hosts
927 /// may omit support.
928 async fn update_session_settings(
929 &self,
930 session_id: &SessionId,
931 change: SessionSettingsChange,
932 ) -> Result<(), SessionError> {
933 let _ = (session_id, change);
934
935 Err(SessionError::Operation(
936 "Host does not support changing session settings".to_string(),
937 ))
938 }
939
940 /// Requests merge processing for one review-ready session.
941 async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError>;
942
943 /// Queues publication of one session branch and creates or refreshes its
944 /// review request.
945 async fn create_review_request(
946 &self,
947 session_id: &SessionId,
948 ) -> Result<ReviewRequest, SessionError>;
949}
950
951/// Stable programmatic facade for session lifecycle operations.
952#[derive(Clone)]
953pub struct SessionService {
954 backend: Arc<dyn SessionBackend>,
955}
956
957/// Explicit static-graph launch, separate from ordinary chat.
958#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
959pub struct StartExecutionGraphRequest {
960 /// Validated immutable snapshot to save before admitting nodes.
961 pub graph: crate::ExecutionGraph,
962 /// Provider calls shared by nodes naming the same budget, including
963 /// repairs. These limits cannot be replenished by redelivering an
964 /// active launch.
965 pub provider_call_limits: std::collections::BTreeMap<String, usize>,
966}
967
968impl SessionService {
969 /// Generates a proposal through the host's bounded worker workflow.
970 ///
971 /// # Errors
972 /// Returns admission, permissions, or persistence errors.
973 pub async fn generate_graph_proposal(
974 &self,
975 request: crate::GenerateGraphProposalRequest,
976 ) -> Result<(), SessionError> {
977 self.backend.generate_graph_proposal(request).await
978 }
979
980 /// Queries pending, restored, or approved state without execution.
981 ///
982 /// # Errors
983 /// Returns query delivery or persistence errors.
984 pub async fn get_graph_proposal(
985 &self,
986 id: &str,
987 ) -> Result<Option<crate::GraphProposalState>, SessionError> {
988 self.backend.get_graph_proposal(id).await
989 }
990
991 /// Answers the complete question set on an exact proposal version.
992 ///
993 /// # Errors
994 /// Returns stale-version, incomplete-answer, or generation-limit errors.
995 pub async fn answer_graph_proposal(
996 &self,
997 id: &str,
998 version: u32,
999 answers: Vec<String>,
1000 ) -> Result<(), SessionError> {
1001 self.backend
1002 .act_on_graph_proposal(id, version, crate::GraphProposalAction::Answer(answers))
1003 .await
1004 }
1005
1006 /// Regenerates within the original captured generation ceiling.
1007 ///
1008 /// # Errors
1009 /// Returns stale-version, approved-proposal, or exhausted-limit errors.
1010 pub async fn regenerate_graph_proposal(
1011 &self,
1012 id: &str,
1013 version: u32,
1014 ) -> Result<(), SessionError> {
1015 self.backend
1016 .act_on_graph_proposal(id, version, crate::GraphProposalAction::Regenerate)
1017 .await
1018 }
1019
1020 /// Regenerates with user feedback, including its images, added to the
1021 /// generation history, within the original captured generation ceiling.
1022 ///
1023 /// # Errors
1024 /// Returns stale-version, empty-feedback, approved-proposal, or
1025 /// exhausted-limit errors.
1026 pub async fn revise_graph_proposal(
1027 &self,
1028 id: &str,
1029 version: u32,
1030 feedback: TurnPrompt,
1031 ) -> Result<(), SessionError> {
1032 self.backend
1033 .act_on_graph_proposal(id, version, crate::GraphProposalAction::Revise(feedback))
1034 .await
1035 }
1036
1037 /// Approves the exact preview before dispatch. Redelivery never dispatches.
1038 ///
1039 /// # Errors
1040 /// Returns stale-version, resolution, permissions, or publication errors.
1041 pub async fn approve_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
1042 self.backend
1043 .act_on_graph_proposal(id, version, crate::GraphProposalAction::Approve)
1044 .await
1045 }
1046
1047 /// Cancels a pending proposal and any active generating utility.
1048 ///
1049 /// # Errors
1050 /// Returns stale-version or already-approved errors.
1051 pub async fn cancel_graph_proposal(&self, id: &str, version: u32) -> Result<(), SessionError> {
1052 self.backend
1053 .act_on_graph_proposal(id, version, crate::GraphProposalAction::Cancel)
1054 .await
1055 }
1056
1057 /// Reads graph/node progress and immutable execution history.
1058 ///
1059 /// # Errors
1060 /// Returns failed persistence or query delivery errors.
1061 pub async fn get_execution_graph(
1062 &self,
1063 graph_id: &str,
1064 ) -> Result<Option<crate::ExecutionGraphProgress>, SessionError> {
1065 self.backend.get_execution_graph(graph_id).await
1066 }
1067
1068 /// Reads a session's graphs as an inspector shows them: every graph,
1069 /// the latest proposal with its preview, and the selected graph with
1070 /// its live progress and the selected node's outputs.
1071 ///
1072 /// # Errors
1073 /// Rejects a `graph_id` of another session, and returns failed
1074 /// persistence or query delivery errors.
1075 pub async fn session_graphs(
1076 &self,
1077 request: crate::SessionGraphsRequest,
1078 ) -> Result<crate::SessionGraphs, SessionError> {
1079 self.backend.session_graphs(request).await
1080 }
1081
1082 /// Accepts an output, cancels, resumes, or retries a graph, replies to
1083 /// one of its nodes, or adds provider calls to its spent budget, as the
1084 /// graph's inspector does.
1085 ///
1086 /// # Errors
1087 /// Rejects a graph of another session, a graph that changed since
1088 /// `request.snapshot` was read, an action that snapshot does not offer,
1089 /// an empty reply, and a budget increase outside
1090 /// `1..=`[`crate::ExtendGraphBudgetRequest::MAX_ADDITIONAL_CALLS`], and
1091 /// returns failed admission or delivery errors.
1092 pub async fn act_on_session_graph(
1093 &self,
1094 request: crate::SessionGraphActionRequest,
1095 ) -> Result<(), SessionError> {
1096 self.backend.act_on_session_graph(request).await
1097 }
1098
1099 /// Permanently cancels this graph without canceling unrelated session work.
1100 ///
1101 /// # Errors
1102 /// Rejects missing/stale graphs and failed durable cancellation.
1103 pub async fn cancel_execution_graph(
1104 &self,
1105 request: crate::GraphControlRequest,
1106 ) -> Result<(), SessionError> {
1107 self.backend.cancel_execution_graph(request).await
1108 }
1109
1110 /// Resumes dispatch explicitly; failed nodes still require a new action.
1111 ///
1112 /// # Errors
1113 /// Rejects canceled/stale graphs, graphs without recorded launch limits,
1114 /// or ineligible sessions.
1115 pub async fn resume_execution_graph(
1116 &self,
1117 request: crate::ResumeExecutionGraphRequest,
1118 ) -> Result<(), SessionError> {
1119 self.backend.resume_execution_graph(request).await
1120 }
1121
1122 /// Adds provider calls to one launched budget through a recorded,
1123 /// idempotent extension; the launch limits stay unchanged.
1124 ///
1125 /// # Errors
1126 /// Rejects stale, completed, or canceled graphs, unknown budgets,
1127 /// amounts outside `1..=ExtendGraphBudgetRequest::MAX_ADDITIONAL_CALLS`,
1128 /// conflicting action identities, and failed persistence.
1129 pub async fn extend_execution_graph_budget(
1130 &self,
1131 request: crate::ExtendGraphBudgetRequest,
1132 ) -> Result<(), SessionError> {
1133 self.backend.extend_execution_graph_budget(request).await
1134 }
1135
1136 /// Retries a failed node or answers its exact settled clarification set.
1137 ///
1138 /// # Errors
1139 /// Rejects stale sources, partial answers, conflicting action identities,
1140 /// canceled graphs, and failed persistence or delivery.
1141 pub async fn continue_execution_graph_node(
1142 &self,
1143 request: crate::ContinueGraphNodeRequest,
1144 ) -> Result<(), SessionError> {
1145 self.backend.continue_execution_graph_node(request).await
1146 }
1147
1148 /// Starts an explicit static graph without waiting for model execution.
1149 ///
1150 /// # Errors
1151 /// Rejects unsupported profiles, stale/conflicting identities, missing
1152 /// budgets, ineligible sessions, and failed persistence or delivery.
1153 pub async fn start_execution_graph(
1154 &self,
1155 request: StartExecutionGraphRequest,
1156 ) -> Result<(), SessionError> {
1157 self.backend.start_execution_graph(request).await
1158 }
1159
1160 /// Accepts one exact validated output and releases its acceptance gate.
1161 ///
1162 /// # Errors
1163 /// Rejects stale or unvalidated references and failed persistence.
1164 pub async fn accept_execution_graph_result(
1165 &self,
1166 reference: crate::GraphResultRef,
1167 ) -> Result<(), SessionError> {
1168 self.backend.accept_execution_graph_result(reference).await
1169 }
1170
1171 /// Accepts a standalone Planner version from durable task history.
1172 ///
1173 /// # Errors
1174 /// Returns an error for stale/ineligible versions or failed persistence.
1175 pub async fn accept_agent_plan(
1176 &self,
1177 session_id: &SessionId,
1178 request: AcceptTaskPlanRequest,
1179 ) -> Result<(), SessionError> {
1180 self.backend.accept_agent_plan(session_id, request).await
1181 }
1182
1183 /// Creates an owned session capability backed by a shared host handle.
1184 pub fn new(backend: Arc<dyn SessionBackend>) -> Self {
1185 Self { backend }
1186 }
1187
1188 /// Admits an isolated role-bound attempt, acknowledging durable admission.
1189 /// Identical redeliveries do not execute again. Task completion is
1190 /// explicit.
1191 ///
1192 /// # Errors
1193 /// Returns an error for invalid input, unaccepted implementation plans,
1194 /// conflicting identity, or a session unable to accept work.
1195 pub async fn submit_agent_task(
1196 &self,
1197 session_id: &SessionId,
1198 request: crate::SubmitAgentTaskRequest,
1199 ) -> Result<(), SessionError> {
1200 self.backend.submit_agent_task(session_id, request).await
1201 }
1202
1203 /// Reads the task's own responses. Attempt status remains authoritative.
1204 ///
1205 /// # Errors
1206 /// Returns an error when the host cannot load the isolated conversation.
1207 pub async fn get_agent_task_history(
1208 &self,
1209 task_id: &str,
1210 ) -> Result<Option<crate::TaskAgentHistory>, SessionError> {
1211 self.backend.get_agent_task_history(task_id).await
1212 }
1213
1214 /// Persists a task with zero attempts in an existing session, regardless
1215 /// of its execution status. Does not start work or change session state.
1216 /// Identical creation requests preserve the task and its history.
1217 ///
1218 /// # Errors
1219 /// Returns an error for empty inputs, conflicting identity, a missing
1220 /// session, or a host that cannot persist tasks.
1221 pub async fn create_task(
1222 &self,
1223 session_id: &SessionId,
1224 request: CreateTaskRequest,
1225 ) -> Result<(), SessionError> {
1226 self.backend.create_task(session_id, request).await
1227 }
1228
1229 /// Lists all tasks owned by a session in creation order, including their
1230 /// attempt histories in one snapshot. Equal timestamps retain insertion
1231 /// order. Returns an empty list for a missing session or one without tasks.
1232 ///
1233 /// # Errors
1234 /// Returns an error when the host cannot read tasks.
1235 pub async fn list_tasks(&self, session_id: &SessionId) -> Result<Vec<Task>, SessionError> {
1236 self.backend.list_tasks(session_id).await
1237 }
1238
1239 /// Admits one task attempt through the existing serialized session worker.
1240 /// Creates the task atomically if it does not already exist.
1241 /// Acceptance does not wait for execution or imply task completion.
1242 /// Identical deliveries are acknowledged without running again.
1243 ///
1244 /// # Errors
1245 /// Returns an error for conflicting identity, an unavailable host, a
1246 /// completed task, or a session that cannot accept a new durable turn.
1247 pub async fn submit_task(
1248 &self,
1249 session_id: &SessionId,
1250 request: SubmitTaskRequest,
1251 ) -> Result<(), SessionError> {
1252 self.backend.submit_task(session_id, request).await
1253 }
1254
1255 /// Loads a task and all its attempts from durable storage.
1256 ///
1257 /// # Errors
1258 /// Returns an error when the host cannot read tasks.
1259 pub async fn get_task(&self, task_id: &str) -> Result<Option<Task>, SessionError> {
1260 self.backend.get_task(task_id).await
1261 }
1262
1263 /// Explicitly accepts the outcome. Successful model execution alone never
1264 /// completes a task. Repeated completion retains its original timestamp.
1265 ///
1266 /// # Errors
1267 /// Returns an error if the task is missing, an attempt is unfinished, or
1268 /// the host cannot persist completion.
1269 pub async fn complete_task(&self, task_id: &str) -> Result<(), SessionError> {
1270 self.backend.complete_task(task_id).await
1271 }
1272
1273 /// Reports whether the host serves `operation` to frontends that ask
1274 /// first.
1275 #[must_use]
1276 pub fn supports(&self, operation: SessionOperation) -> bool {
1277 self.backend.supports(operation)
1278 }
1279
1280 /// Lists the projects the host serves frontends, in the order its
1281 /// project switcher shows them. The listed projects are the host's
1282 /// active project, the one its own frontend has open, and every other
1283 /// project its switcher offers; a [`ProjectScope::Project`] reaches only
1284 /// these.
1285 ///
1286 /// # Errors
1287 /// Returns an error when the host does not list its projects or cannot
1288 /// load them.
1289 pub async fn list_projects(&self) -> Result<Vec<HostProject>, SessionError> {
1290 self.backend.list_projects().await
1291 }
1292
1293 /// Describes the active project new sessions are created in.
1294 ///
1295 /// # Errors
1296 /// Returns an error when the host does not describe its project or
1297 /// cannot load its defaults.
1298 pub async fn host_context(&self) -> Result<HostContext, SessionError> {
1299 self.backend.host_context().await
1300 }
1301
1302 /// Describes `scope`'s project, which new sessions requested for it are
1303 /// created in. [`ProjectScope::Active`] means the host's active project
1304 /// when the host serves the request.
1305 ///
1306 /// # Errors
1307 /// Returns an error when the host does not describe its project, does
1308 /// not list the named project or serve other projects, or cannot load
1309 /// the project's defaults.
1310 pub async fn host_context_for(&self, scope: ProjectScope) -> Result<HostContext, SessionError> {
1311 self.backend.host_context_for(scope).await
1312 }
1313
1314 /// Reports the active project's branch, its distance from upstream, and
1315 /// its latest explicit sync.
1316 ///
1317 /// # Errors
1318 /// Returns an error when the host does not report its project status.
1319 pub async fn project_status(&self) -> Result<HostProjectStatus, SessionError> {
1320 self.backend.project_status().await
1321 }
1322
1323 /// Lists `scope`'s listed sessions in the host's display order, with
1324 /// the project's status when the host reports it. Both describe the
1325 /// same project when [`ProjectSessions::project_id`] names it.
1326 /// [`ProjectScope::Active`] means the host's active project when the
1327 /// host serves the request.
1328 ///
1329 /// # Errors
1330 /// Returns an error when the host cannot list sessions or report the
1331 /// project's status, or does not list the named project or serve other
1332 /// projects.
1333 pub async fn project_sessions(
1334 &self,
1335 scope: ProjectScope,
1336 ) -> Result<ProjectSessions, SessionError> {
1337 self.backend.project_sessions(scope).await
1338 }
1339
1340 /// Starts or queues a sync of the active project's branch with its
1341 /// upstream. The host acknowledges admission; [`Self::project_status`]
1342 /// reports the progress and the outcome.
1343 ///
1344 /// # Errors
1345 /// Returns an error when the host cannot start the sync now, such as
1346 /// while a merge runs, or does not support syncing its project.
1347 pub async fn sync_project(&self) -> Result<(), SessionError> {
1348 self.backend.sync_project().await
1349 }
1350
1351 /// Starts or queues a sync of `scope`'s branch with its upstream. The
1352 /// host acknowledges admission; [`Self::project_sessions`] reports the
1353 /// progress and the outcome. [`ProjectScope::Active`] means the host's
1354 /// active project when the host serves the request.
1355 ///
1356 /// # Errors
1357 /// Returns an error when the host cannot start the sync now, does not
1358 /// support syncing, or does not list the named project or serve other
1359 /// projects.
1360 pub async fn sync_project_for(&self, scope: ProjectScope) -> Result<(), SessionError> {
1361 self.backend.sync_project_for(scope).await
1362 }
1363
1364 /// Creates one session and returns its stable identifier.
1365 ///
1366 /// # Errors
1367 /// Returns an error when the host cannot create the requested session.
1368 pub async fn create_session(
1369 &self,
1370 request: CreateSessionRequest,
1371 ) -> Result<SessionId, SessionError> {
1372 self.backend.create_session(request).await
1373 }
1374
1375 /// Loads one complete session aggregate by identifier.
1376 ///
1377 /// # Errors
1378 /// Returns an error when persisted data cannot be loaded or decoded.
1379 pub async fn get_session(
1380 &self,
1381 session_id: &SessionId,
1382 ) -> Result<Option<Session>, SessionError> {
1383 self.backend.get_session(session_id).await
1384 }
1385
1386 /// Loads the files one session changes against its base branch, or
1387 /// `None` when the host has not loaded the session.
1388 ///
1389 /// # Errors
1390 /// Returns an error when the host does not serve diffs or cannot compute
1391 /// or load this one.
1392 pub async fn get_session_diff(
1393 &self,
1394 session_id: &SessionId,
1395 ) -> Result<Option<Vec<SessionDiffFile>>, SessionError> {
1396 self.backend.get_session_diff(session_id).await
1397 }
1398
1399 /// Lists the files and directories in one session's worktree,
1400 /// directories first, or `None` when the host has not loaded the
1401 /// session.
1402 ///
1403 /// # Errors
1404 /// Returns an error when the host does not serve file listings or cannot
1405 /// read this one.
1406 pub async fn list_session_files(
1407 &self,
1408 session_id: &SessionId,
1409 ) -> Result<Option<Vec<SessionFileEntry>>, SessionError> {
1410 self.backend.list_session_files(session_id).await
1411 }
1412
1413 /// Lists the files and directories in the active project's checkout,
1414 /// directories first.
1415 ///
1416 /// # Errors
1417 /// Returns an error when the host does not serve project file listings
1418 /// or cannot read the checkout.
1419 pub async fn list_project_files(&self) -> Result<Vec<SessionFileEntry>, SessionError> {
1420 self.backend.list_project_files().await
1421 }
1422
1423 /// Lists the files and directories in `scope`'s checkout, directories
1424 /// first. [`ProjectScope::Active`] means the host's active project when
1425 /// the host serves the request.
1426 ///
1427 /// # Errors
1428 /// Returns an error when the host does not serve project file listings,
1429 /// does not list the named project or serve other projects, or cannot
1430 /// read the checkout.
1431 pub async fn list_project_files_for(
1432 &self,
1433 scope: ProjectScope,
1434 ) -> Result<Vec<SessionFileEntry>, SessionError> {
1435 self.backend.list_project_files_for(scope).await
1436 }
1437
1438 /// Lists the host's loaded sessions in its display order.
1439 ///
1440 /// # Errors
1441 /// Returns an error when the host cannot list sessions.
1442 pub async fn list_sessions(&self) -> Result<Vec<SessionSummary>, SessionError> {
1443 self.backend.list_sessions().await
1444 }
1445
1446 /// Lists the host's loaded sessions in its display order, with list
1447 /// stats when the host provides them.
1448 ///
1449 /// # Errors
1450 /// Returns an error when the host cannot list sessions.
1451 pub async fn list_session_entries(&self) -> Result<Vec<SessionListEntry>, SessionError> {
1452 self.backend.list_session_entries().await
1453 }
1454
1455 /// Reports whether the host lists `session_id`. A session is listed
1456 /// while it appears in the session list of a project the host lists, as
1457 /// [`Self::project_sessions`] would return it; frontends that may reach
1458 /// only listed sessions check this before acting on one.
1459 ///
1460 /// # Errors
1461 /// Returns an error when the host cannot list sessions or resolve the
1462 /// session's project.
1463 pub async fn is_session_listed(&self, session_id: &SessionId) -> Result<bool, SessionError> {
1464 self.backend.is_session_listed(session_id).await
1465 }
1466
1467 /// Sends a text message to one session.
1468 ///
1469 /// # Errors
1470 /// Returns an error when the session cannot accept or enqueue the message.
1471 pub async fn send_message(
1472 &self,
1473 session_id: &SessionId,
1474 message: impl Into<String> + Send,
1475 ) -> Result<(), SessionError> {
1476 self.backend.send_message(session_id, message.into()).await
1477 }
1478
1479 /// Sends a message with images to one session. The host attaches the
1480 /// images as `[Image #n]`, numbered in `images` order from 1.
1481 ///
1482 /// # Errors
1483 /// Returns an error when the host does not take images in messages, or
1484 /// the session cannot accept or enqueue the message.
1485 pub async fn send_message_with_images(
1486 &self,
1487 session_id: &SessionId,
1488 message: impl Into<String> + Send,
1489 images: Vec<MessageImage>,
1490 ) -> Result<(), SessionError> {
1491 self.backend
1492 .send_message_with_images(session_id, message.into(), images)
1493 .await
1494 }
1495
1496 /// Submits one durable turn directly to the serialized worker.
1497 ///
1498 /// # Errors
1499 /// Returns an error when the session is busy or cannot accept the turn.
1500 pub async fn submit_durable_message(
1501 &self,
1502 session_id: &SessionId,
1503 request: DurableMessageRequest,
1504 ) -> Result<(), SessionError> {
1505 self.backend
1506 .submit_durable_message(session_id, request)
1507 .await
1508 }
1509
1510 /// Answers the complete current clarification-question set.
1511 ///
1512 /// # Errors
1513 /// Returns an error when the answers are stale, incomplete, or cannot be
1514 /// enqueued as a follow-up turn.
1515 pub async fn answer_questions(
1516 &self,
1517 session_id: &SessionId,
1518 request: AnswerQuestionsRequest,
1519 ) -> Result<(), SessionError> {
1520 self.backend.answer_questions(session_id, request).await
1521 }
1522
1523 /// Cancels one session through its host lifecycle workflow.
1524 ///
1525 /// # Errors
1526 /// Returns an error when the session does not exist or cannot be canceled
1527 /// in its current state.
1528 pub async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1529 self.backend.cancel_session(session_id).await
1530 }
1531
1532 /// Stops the session's running turn and returns the session to review.
1533 /// Unlike [`Self::cancel_session`], the worktree and its changes stay;
1534 /// messages queued behind the turn are discarded.
1535 ///
1536 /// # Errors
1537 /// Returns an error when the session does not exist, has no running
1538 /// turn, or the host does not support stopping a turn.
1539 pub async fn stop_turn(&self, session_id: &SessionId) -> Result<(), SessionError> {
1540 self.backend.stop_turn(session_id).await
1541 }
1542
1543 /// Starts or queues a rebase of the session branch onto its base branch.
1544 /// The host acknowledges admission; a conflict starts an agent-assisted
1545 /// resolution turn.
1546 ///
1547 /// # Errors
1548 /// Returns an error when the session does not exist, cannot be rebased in
1549 /// its current state, or the host does not support syncing.
1550 pub async fn rebase_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1551 self.backend.rebase_session(session_id).await
1552 }
1553
1554 /// Changes the session's model, reasoning, style, or speed for later
1555 /// turns, where the terminal's composer could change them.
1556 ///
1557 /// The host refuses the whole change, applying none of it, when the
1558 /// session's status has no composer, the model is not one the session's
1559 /// agent offers, or fast mode does not suit the model the session will
1560 /// have. It then applies the model, reasoning, style, and speed in that
1561 /// order. Reasoning and style apply at once; a model or speed change
1562 /// waits while the session still has accepted work. Changes are not
1563 /// transactional: when one fails to apply, the ones before it stay
1564 /// applied.
1565 ///
1566 /// # Errors
1567 /// Returns an error when the session does not exist or its status has no
1568 /// composer, a model is not available to it, fast mode does not suit the
1569 /// resulting model, switching or persisting a setting fails, or the host
1570 /// does not support the change.
1571 pub async fn update_session_settings(
1572 &self,
1573 session_id: &SessionId,
1574 change: SessionSettingsChange,
1575 ) -> Result<(), SessionError> {
1576 self.backend
1577 .update_session_settings(session_id, change)
1578 .await
1579 }
1580
1581 /// Requests merge processing for one session.
1582 ///
1583 /// # Errors
1584 /// Returns an error when the session is not mergeable or queueing fails.
1585 pub async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
1586 self.backend.merge_session(session_id).await
1587 }
1588
1589 /// Queues publication of one session and creates or refreshes its review
1590 /// request.
1591 ///
1592 /// # Errors
1593 /// Returns an error when queueing, branch publication, forge access, or
1594 /// persistence fails.
1595 pub async fn create_review_request(
1596 &self,
1597 session_id: &SessionId,
1598 ) -> Result<ReviewRequest, SessionError> {
1599 self.backend.create_review_request(session_id).await
1600 }
1601}
1602
1603#[cfg(test)]
1604#[path = "service_test.rs"]
1605mod tests;