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