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