Skip to main content

ag_agent/channel/
contract.rs

1//! Shared channel trait and provider turn request/result contracts.
2
3use std::fmt;
4use std::future::Future;
5use std::path::PathBuf;
6use std::pin::Pin;
7use std::sync::Arc;
8
9use ag_protocol::{AgentResponse, ProtocolRequestProfile, TurnPrompt};
10use tokio::sync::mpsc;
11
12use crate::model::agent::ReasoningLevel;
13use crate::model::permission::PermissionMode;
14use crate::model::session::{ResponseStyle, SpeedMode};
15
16/// Boxed async result used by [`AgentChannel`] trait methods.
17pub type AgentFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
18
19/// Live transcript projection used when a provider runtime needs replay text.
20pub trait LiveTranscript: fmt::Debug + Send + Sync {
21    /// Returns the latest replayable transcript text, when any content exists.
22    fn replay_text(&self) -> Option<String>;
23}
24
25/// Turn initiation mode for [`TurnRequest`].
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum AgentRequestKind {
28    /// Runs one focused code review with a direct structured review response.
29    FocusedReview,
30    /// Starts a fresh interactive session turn with no prior context.
31    SessionStart,
32    /// Resumes an interactive session turn.
33    SessionResume,
34    /// Runs one utility prompt with utility protocol requirements.
35    ///
36    /// Callers may route this through an isolated one-shot channel or through
37    /// an existing session channel when the utility work needs provider
38    /// conversation continuity without normal post-turn auto-commit handling.
39    UtilityPrompt,
40    /// Reads provider account metadata without creating an agent turn.
41    AccountRead,
42}
43
44impl AgentRequestKind {
45    /// Returns the protocol request profile derived from this request kind.
46    #[must_use]
47    pub fn protocol_profile(&self) -> ProtocolRequestProfile {
48        match self {
49            Self::SessionStart | Self::SessionResume => ProtocolRequestProfile::SessionTurn,
50            Self::FocusedReview => ProtocolRequestProfile::FocusedReview,
51            Self::UtilityPrompt | Self::AccountRead => ProtocolRequestProfile::UtilityPrompt,
52        }
53    }
54
55    /// Returns whether this request resumes a prior interactive session turn.
56    #[must_use]
57    pub fn is_resume(&self) -> bool {
58        matches!(self, Self::SessionResume)
59    }
60}
61
62/// Continuation state for one provider-agnostic agent turn.
63///
64/// The concrete representation keeps provider-runtime recovery details out of
65/// [`TurnRequest`] while allowing CLI channels to consume only replay text.
66#[derive(Clone, Debug)]
67pub struct TurnContinuation {
68    kind: TurnContinuationKind,
69}
70
71/// Personality prompt state prepared for one provider turn.
72#[derive(Clone, Debug, Default, Eq, PartialEq)]
73pub struct PersonalityPrompt {
74    current: Option<String>,
75    update: PersonalityPromptUpdate,
76}
77
78impl PersonalityPrompt {
79    /// Creates one active personality, marking whether delta-mode providers
80    /// must receive its body as an update.
81    #[must_use]
82    pub fn active(prompt: String, changed: bool) -> Self {
83        let update = if changed {
84            PersonalityPromptUpdate::Set(prompt.clone())
85        } else {
86            PersonalityPromptUpdate::Unchanged
87        };
88
89        Self {
90            current: Some(prompt),
91            update,
92        }
93    }
94
95    /// Creates a cleared personality state.
96    ///
97    /// `changed` is true when a delta-mode provider previously held active
98    /// personality instructions and must be told to discard them.
99    #[must_use]
100    pub fn cleared(changed: bool) -> Self {
101        Self {
102            current: None,
103            update: if changed {
104                PersonalityPromptUpdate::Clear
105            } else {
106                PersonalityPromptUpdate::Unchanged
107            },
108        }
109    }
110
111    /// Returns the current personality body for a full bootstrap.
112    #[must_use]
113    pub fn current(&self) -> Option<&str> {
114        self.current.as_deref()
115    }
116
117    pub(crate) fn update(&self) -> &PersonalityPromptUpdate {
118        &self.update
119    }
120}
121
122/// Delta-mode personality change for a provider-managed conversation.
123#[derive(Clone, Debug, Default, Eq, PartialEq)]
124pub(crate) enum PersonalityPromptUpdate {
125    /// Clear personality behavior that was active on the previous turn.
126    Clear,
127    /// Apply a new or edited personality body.
128    Set(String),
129    /// Reuse the personality behavior already present in provider context.
130    #[default]
131    Unchanged,
132}
133
134impl TurnContinuation {
135    /// Creates continuation state for a fresh turn with no prior context.
136    #[must_use]
137    pub fn fresh() -> Self {
138        Self {
139            kind: TurnContinuationKind::Fresh,
140        }
141    }
142
143    /// Creates continuation state for a stateless turn that replays prior text.
144    #[must_use]
145    pub fn replaying(replay_transcript: String) -> Self {
146        Self {
147            kind: TurnContinuationKind::Replay { replay_transcript },
148        }
149    }
150
151    /// Creates continuation state for a provider runtime that may resume a
152    /// native conversation and reconstruct context from a live transcript.
153    #[must_use]
154    pub fn provider(
155        live_transcript: Option<Arc<dyn LiveTranscript>>,
156        persisted_instruction_conversation_id: Option<String>,
157        provider_conversation_id: Option<String>,
158        replay_transcript: Option<String>,
159    ) -> Self {
160        Self {
161            kind: TurnContinuationKind::Provider {
162                live_transcript,
163                persisted_instruction_conversation_id,
164                provider_conversation_id,
165                replay_transcript,
166            },
167        }
168    }
169
170    /// Returns replayable transcript text when this turn carries it.
171    #[must_use]
172    pub fn replay_transcript(&self) -> Option<&str> {
173        match &self.kind {
174            TurnContinuationKind::Fresh => None,
175            TurnContinuationKind::Provider {
176                replay_transcript, ..
177            } => replay_transcript.as_deref(),
178            TurnContinuationKind::Replay { replay_transcript } => Some(replay_transcript.as_str()),
179        }
180    }
181
182    /// Returns the provider-native conversation identifier when available.
183    #[must_use]
184    pub fn provider_conversation_id(&self) -> Option<&str> {
185        match &self.kind {
186            TurnContinuationKind::Provider {
187                provider_conversation_id,
188                ..
189            } => provider_conversation_id.as_deref(),
190            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
191        }
192    }
193
194    /// Returns the conversation identifier that received the instruction
195    /// bootstrap when available.
196    #[must_use]
197    pub fn persisted_instruction_conversation_id(&self) -> Option<&str> {
198        match &self.kind {
199            TurnContinuationKind::Provider {
200                persisted_instruction_conversation_id,
201                ..
202            } => persisted_instruction_conversation_id.as_deref(),
203            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
204        }
205    }
206
207    pub(crate) fn into_parts(self) -> TurnContinuationParts {
208        match self.kind {
209            TurnContinuationKind::Fresh => TurnContinuationParts::default(),
210            TurnContinuationKind::Replay { replay_transcript } => TurnContinuationParts {
211                replay_transcript: Some(replay_transcript),
212                ..TurnContinuationParts::default()
213            },
214            TurnContinuationKind::Provider {
215                live_transcript,
216                persisted_instruction_conversation_id,
217                provider_conversation_id,
218                replay_transcript,
219            } => TurnContinuationParts {
220                live_transcript,
221                persisted_instruction_conversation_id,
222                provider_conversation_id,
223                replay_transcript,
224            },
225        }
226    }
227}
228
229#[derive(Clone, Debug)]
230enum TurnContinuationKind {
231    Fresh,
232    Provider {
233        live_transcript: Option<Arc<dyn LiveTranscript>>,
234        persisted_instruction_conversation_id: Option<String>,
235        provider_conversation_id: Option<String>,
236        replay_transcript: Option<String>,
237    },
238    Replay {
239        replay_transcript: String,
240    },
241}
242
243#[derive(Default)]
244pub(crate) struct TurnContinuationParts {
245    pub(crate) live_transcript: Option<Arc<dyn LiveTranscript>>,
246    pub(crate) persisted_instruction_conversation_id: Option<String>,
247    pub(crate) provider_conversation_id: Option<String>,
248    pub(crate) replay_transcript: Option<String>,
249}
250
251/// Input payload for one provider-agnostic agent turn.
252#[derive(Debug, Clone)]
253pub struct TurnRequest {
254    /// Prior context needed to continue this turn.
255    pub continuation: TurnContinuation,
256    /// Session worktree folder where the agent runs.
257    pub folder: PathBuf,
258    /// Main repository checkout that must remain read-only during the turn,
259    /// when Agentty can resolve it.
260    pub main_checkout_root: Option<PathBuf>,
261    /// Provider-specific model identifier.
262    pub model: String,
263    /// Filesystem and command permission policy for this turn.
264    pub permission_mode: PermissionMode,
265    /// Personality prompt state resolved from the session worktree.
266    pub personality: PersonalityPrompt,
267    /// Structured prompt payload for the turn.
268    pub prompt: TurnPrompt,
269    /// Reasoning effort preference for the turn.
270    ///
271    /// Ignored by providers/models that do not support reasoning effort.
272    pub reasoning_level: ReasoningLevel,
273    /// Canonical request kind that drives transport behavior and protocol
274    /// semantics for this turn.
275    pub request_kind: AgentRequestKind,
276    /// Preferred amount of detail in user-facing session responses.
277    pub response_style: ResponseStyle,
278    /// Response-speed preference for the turn.
279    pub speed_mode: SpeedMode,
280}
281
282/// Incremental event emitted during one agent turn.
283///
284/// Events are sent through an [`mpsc::UnboundedSender`] as the turn
285/// progresses, enabling transient loader updates without appending partial turn
286/// output into the persisted transcript.
287#[derive(Clone, Debug, PartialEq)]
288pub enum TurnEvent {
289    /// A streamed thinking/planning or tool-status fragment shown in the
290    /// transient loader.
291    ThoughtDelta(String),
292    /// The turn completed successfully with final token counts.
293    Completed {
294        /// Whether the provider reset its context for this turn.
295        context_reset: bool,
296        /// Input token count for the turn.
297        input_tokens: u64,
298        /// Output token count for the turn.
299        output_tokens: u64,
300    },
301    /// The turn failed with an error description.
302    Failed(String),
303    /// A child process PID update.
304    ///
305    /// Announces a running or retained runtime (`Some(pid)`) or clears it
306    /// when the runtime shuts down (`None`). Consumers update resource
307    /// accounting. Only CLI transports may use this
308    /// PID for cancellation signals; app-server cancellation belongs to the
309    /// runtime owner and must not signal an accounting PID.
310    PidUpdate(Option<u32>),
311}
312
313/// Normalized result returned when one agent turn completes successfully.
314#[derive(Debug)]
315pub struct TurnResult {
316    /// Parsed agent response containing structured protocol messages.
317    pub assistant_message: AgentResponse,
318    /// Whether the provider reset its context to complete this turn.
319    pub context_reset: bool,
320    /// Input token count for the turn.
321    pub input_tokens: u64,
322    /// Output token count for the turn.
323    pub output_tokens: u64,
324    /// Provider-native conversation identifier observed after the turn.
325    ///
326    /// App-server providers return this so the worker can persist it for
327    /// future runtime restarts. CLI channels always return `None`.
328    pub provider_conversation_id: Option<String>,
329}
330
331/// Opaque reference to an active agent session.
332pub struct SessionRef {
333    /// Stable session identifier.
334    pub session_id: String,
335}
336
337/// Input payload for initiating a new agent session.
338pub struct StartSessionRequest {
339    /// Session worktree folder.
340    pub folder: PathBuf,
341    /// Stable session identifier.
342    pub session_id: String,
343}
344
345/// Typed error returned by [`AgentChannel`] operations.
346///
347/// Discriminates failure causes so the app layer can route errors without
348/// parsing formatted messages.
349#[derive(Debug, thiserror::Error)]
350pub enum AgentError {
351    /// An app-server infrastructure failure propagated from a persistent
352    /// provider runtime.
353    #[error(transparent)]
354    AppServer(#[from] crate::app_server::AppServerError),
355
356    /// A CLI backend command or process execution failure.
357    #[error("{0}")]
358    Backend(String),
359
360    /// The user explicitly interrupted the active turn.
361    #[error("{0}")]
362    InterruptedByUser(String),
363
364    /// A subprocess IO error such as a spawn failure or unavailable pipe.
365    #[error("{0}")]
366    Io(String),
367}
368
369/// Provider-agnostic session channel for executing agent turns.
370///
371/// Implementations bridge a specific transport - CLI subprocess or app-server
372/// RPC - to the unified [`TurnEvent`] stream consumed by session workers. The
373/// trait is object-safe so it can be held as `Arc<dyn AgentChannel>`.
374#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
375pub trait AgentChannel: Send + Sync {
376    /// Initialises a provider session for the given session identifier.
377    ///
378    /// Implementations that do not maintain persistent sessions return
379    /// immediately with a [`SessionRef`] wrapping the supplied identifier.
380    fn start_session(
381        &self,
382        req: StartSessionRequest,
383    ) -> AgentFuture<Result<SessionRef, AgentError>>;
384
385    /// Executes one prompt turn and streams incremental events to `events`.
386    ///
387    /// Implementations may emit [`TurnEvent::ThoughtDelta`] values for
388    /// transient loader updates. Final transcript output is derived from the
389    /// returned [`TurnResult`] after the turn finishes.
390    ///
391    /// # Errors
392    /// Returns [`AgentError`] when the turn cannot be executed (spawn failure,
393    /// transport error) or is interrupted by a signal.
394    fn run_turn(
395        &self,
396        session_id: String,
397        req: TurnRequest,
398        events: mpsc::UnboundedSender<TurnEvent>,
399    ) -> AgentFuture<Result<TurnResult, AgentError>>;
400
401    /// Tears down the provider session associated with `session_id`.
402    ///
403    /// Implementations that do not maintain persistent sessions treat this as
404    /// a no-op and always return `Ok(())`.
405    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>>;
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn test_personality_prompt_tracks_active_change_and_clear_state() {
414        // Arrange / Act
415        let changed = PersonalityPrompt::active("Review carefully.".to_string(), true);
416        let unchanged = PersonalityPrompt::active("Review carefully.".to_string(), false);
417        let cleared = PersonalityPrompt::cleared(true);
418        let empty = PersonalityPrompt::cleared(false);
419
420        // Assert
421        assert_eq!(changed.current(), Some("Review carefully."));
422        assert_eq!(
423            changed.update(),
424            &PersonalityPromptUpdate::Set("Review carefully.".to_string())
425        );
426        assert_eq!(unchanged.update(), &PersonalityPromptUpdate::Unchanged);
427        assert_eq!(cleared.current(), None);
428        assert_eq!(cleared.update(), &PersonalityPromptUpdate::Clear);
429        assert_eq!(empty.update(), &PersonalityPromptUpdate::Unchanged);
430    }
431
432    #[test]
433    fn test_turn_continuation_fresh_has_no_context() {
434        // Arrange / Act
435        let continuation = TurnContinuation::fresh();
436
437        // Assert
438        assert_eq!(continuation.replay_transcript(), None);
439        assert_eq!(continuation.provider_conversation_id(), None);
440        assert_eq!(continuation.persisted_instruction_conversation_id(), None);
441    }
442
443    #[test]
444    fn test_turn_continuation_replaying_exposes_transcript_only() {
445        // Arrange
446        let continuation = TurnContinuation::replaying("prior turn".to_string());
447
448        // Act
449        let parts = continuation.clone().into_parts();
450
451        // Assert
452        assert_eq!(continuation.replay_transcript(), Some("prior turn"));
453        assert_eq!(continuation.provider_conversation_id(), None);
454        assert!(parts.live_transcript.is_none());
455        assert_eq!(parts.persisted_instruction_conversation_id, None);
456        assert_eq!(parts.provider_conversation_id, None);
457        assert_eq!(parts.replay_transcript.as_deref(), Some("prior turn"));
458    }
459
460    #[test]
461    fn test_turn_continuation_provider_exposes_persisted_context() {
462        // Arrange / Act
463        let continuation = TurnContinuation::provider(
464            None,
465            Some("instruction-1".to_string()),
466            Some("thread-1".to_string()),
467            Some("prior turn".to_string()),
468        );
469
470        // Assert
471        assert_eq!(continuation.replay_transcript(), Some("prior turn"));
472        assert_eq!(continuation.provider_conversation_id(), Some("thread-1"));
473        assert_eq!(
474            continuation.persisted_instruction_conversation_id(),
475            Some("instruction-1")
476        );
477    }
478
479    #[test]
480    /// Ensures session request kinds derive the session-turn protocol
481    /// profile.
482    fn test_agent_request_kind_session_variants_use_session_protocol_profile() {
483        // Arrange
484        let start = AgentRequestKind::SessionStart;
485        let resume = AgentRequestKind::SessionResume;
486
487        // Act
488        let start_profile = start.protocol_profile();
489        let resume_profile = resume.protocol_profile();
490
491        // Assert
492        assert_eq!(start_profile, ProtocolRequestProfile::SessionTurn);
493        assert_eq!(resume_profile, ProtocolRequestProfile::SessionTurn);
494    }
495
496    #[test]
497    /// Ensures utility prompts derive the utility protocol profile.
498    fn test_agent_request_kind_utility_prompt_uses_utility_protocol_profile() {
499        // Arrange
500        let request_kind = AgentRequestKind::UtilityPrompt;
501
502        // Act
503        let protocol_profile = request_kind.protocol_profile();
504
505        // Assert
506        assert_eq!(protocol_profile, ProtocolRequestProfile::UtilityPrompt);
507    }
508
509    #[test]
510    fn focused_review_request_uses_focused_review_protocol_profile() {
511        // Arrange
512        let request_kind = AgentRequestKind::FocusedReview;
513
514        // Act
515        let protocol_profile = request_kind.protocol_profile();
516
517        // Assert
518        assert_eq!(protocol_profile, ProtocolRequestProfile::FocusedReview);
519    }
520
521    #[test]
522    /// Ensures account-read requests are non-session utility requests.
523    fn test_agent_request_kind_account_read_uses_utility_protocol_profile() {
524        // Arrange
525        let request_kind = AgentRequestKind::AccountRead;
526
527        // Act
528        let protocol_profile = request_kind.protocol_profile();
529
530        // Assert
531        assert_eq!(protocol_profile, ProtocolRequestProfile::UtilityPrompt);
532    }
533}