Skip to main content

ag_runtime/
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::{PermissionMode, ReasoningLevel, ResponseStyle, SpeedMode};
13
14/// Normalizes one provider-native conversation id for persisted bootstrap
15/// reuse tracking.
16pub fn normalize_instruction_conversation_id(
17    provider_conversation_id: Option<&str>,
18) -> Option<String> {
19    provider_conversation_id
20        .map(str::trim)
21        .filter(|value| !value.is_empty())
22        .map(ToString::to_string)
23}
24
25/// Boxed async result used by [`AgentChannel`] trait methods.
26pub type AgentFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
27
28/// Live transcript projection used when a provider runtime needs replay text.
29pub trait LiveTranscript: fmt::Debug + Send + Sync {
30    /// Returns the latest replayable transcript text, when any content exists.
31    fn replay_text(&self) -> Option<String>;
32}
33
34/// Turn initiation mode for [`TurnRequest`].
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum AgentRequestKind {
37    /// Runs one focused code review with a direct structured review response.
38    FocusedReview,
39    /// Starts a fresh interactive session turn with no prior context.
40    SessionStart,
41    /// Resumes an interactive session turn.
42    SessionResume,
43    /// Runs one utility prompt with utility protocol requirements.
44    ///
45    /// Callers may route this through an isolated one-shot channel or through
46    /// an existing session channel when the utility work needs provider
47    /// conversation continuity without normal post-turn auto-commit handling.
48    UtilityPrompt,
49    /// Reads provider account metadata without creating an agent turn.
50    AccountRead,
51}
52
53impl AgentRequestKind {
54    /// Returns the protocol request profile derived from this request kind.
55    #[must_use]
56    pub fn protocol_profile(&self) -> ProtocolRequestProfile {
57        match self {
58            Self::SessionStart | Self::SessionResume => ProtocolRequestProfile::SessionTurn,
59            Self::FocusedReview => ProtocolRequestProfile::FocusedReview,
60            Self::UtilityPrompt | Self::AccountRead => ProtocolRequestProfile::UtilityPrompt,
61        }
62    }
63
64    /// Returns whether this request resumes a prior interactive session turn.
65    #[must_use]
66    pub fn is_resume(&self) -> bool {
67        matches!(self, Self::SessionResume)
68    }
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    /// Returns the instruction update to apply when continuing context.
118    pub fn update(&self) -> &PersonalityPromptUpdate {
119        &self.update
120    }
121}
122
123/// Delta-mode personality change for a provider-managed conversation.
124#[derive(Clone, Debug, Default, Eq, PartialEq)]
125pub enum PersonalityPromptUpdate {
126    /// Clear personality behavior that was active on the previous turn.
127    Clear,
128    /// Apply a new or edited personality body.
129    Set(String),
130    /// Reuse the personality behavior already present in provider context.
131    #[default]
132    Unchanged,
133}
134
135/// Continuation state for one provider-agnostic agent turn.
136///
137/// The concrete representation keeps provider-runtime recovery details out of
138/// [`TurnRequest`] while allowing CLI channels to consume only replay text.
139#[derive(Clone, Debug)]
140pub struct TurnContinuation {
141    kind: TurnContinuationKind,
142}
143
144impl TurnContinuation {
145    /// Creates continuation state for a fresh turn with no prior context.
146    #[must_use]
147    pub fn fresh() -> Self {
148        Self {
149            kind: TurnContinuationKind::Fresh,
150        }
151    }
152
153    /// Creates continuation state for a stateless turn that replays prior text.
154    #[must_use]
155    pub fn replaying(replay_transcript: String) -> Self {
156        Self {
157            kind: TurnContinuationKind::Replay { replay_transcript },
158        }
159    }
160
161    /// Creates continuation state for a provider runtime that may resume a
162    /// native conversation and reconstruct context from a live transcript.
163    #[must_use]
164    pub fn provider(
165        live_transcript: Option<Arc<dyn LiveTranscript>>,
166        persisted_instruction_conversation_id: Option<String>,
167        provider_conversation_id: Option<String>,
168        replay_transcript: Option<String>,
169    ) -> Self {
170        Self {
171            kind: TurnContinuationKind::Provider {
172                live_transcript,
173                persisted_instruction_conversation_id,
174                provider_conversation_id,
175                replay_transcript,
176            },
177        }
178    }
179
180    /// Returns replayable transcript text when this turn carries it.
181    #[must_use]
182    pub fn replay_transcript(&self) -> Option<&str> {
183        match &self.kind {
184            TurnContinuationKind::Fresh => None,
185            TurnContinuationKind::Provider {
186                replay_transcript, ..
187            } => replay_transcript.as_deref(),
188            TurnContinuationKind::Replay { replay_transcript } => Some(replay_transcript.as_str()),
189        }
190    }
191
192    /// Returns the provider-native conversation identifier when available.
193    #[must_use]
194    pub fn provider_conversation_id(&self) -> Option<&str> {
195        match &self.kind {
196            TurnContinuationKind::Provider {
197                provider_conversation_id,
198                ..
199            } => provider_conversation_id.as_deref(),
200            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
201        }
202    }
203
204    /// Returns the conversation identifier that received the instruction
205    /// bootstrap when available.
206    #[must_use]
207    pub fn persisted_instruction_conversation_id(&self) -> Option<&str> {
208        match &self.kind {
209            TurnContinuationKind::Provider {
210                persisted_instruction_conversation_id,
211                ..
212            } => persisted_instruction_conversation_id.as_deref(),
213            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
214        }
215    }
216
217    /// Consumes continuation state for a runtime adapter.
218    pub fn into_parts(self) -> TurnContinuationParts {
219        match self.kind {
220            TurnContinuationKind::Fresh => TurnContinuationParts::default(),
221            TurnContinuationKind::Replay { replay_transcript } => TurnContinuationParts {
222                replay_transcript: Some(replay_transcript),
223                ..TurnContinuationParts::default()
224            },
225            TurnContinuationKind::Provider {
226                live_transcript,
227                persisted_instruction_conversation_id,
228                provider_conversation_id,
229                replay_transcript,
230            } => TurnContinuationParts {
231                live_transcript,
232                persisted_instruction_conversation_id,
233                provider_conversation_id,
234                replay_transcript,
235            },
236        }
237    }
238}
239
240#[derive(Clone, Debug)]
241enum TurnContinuationKind {
242    Fresh,
243    Provider {
244        live_transcript: Option<Arc<dyn LiveTranscript>>,
245        persisted_instruction_conversation_id: Option<String>,
246        provider_conversation_id: Option<String>,
247        replay_transcript: Option<String>,
248    },
249    Replay {
250        replay_transcript: String,
251    },
252}
253
254/// Owned continuation inputs consumed by a runtime adapter.
255#[derive(Default)]
256pub struct TurnContinuationParts {
257    /// Current replay projection, when supplied by the host.
258    pub live_transcript: Option<Arc<dyn LiveTranscript>>,
259    /// Conversation that received the current instructions.
260    pub persisted_instruction_conversation_id: Option<String>,
261    /// Opaque runtime conversation identifier.
262    pub provider_conversation_id: Option<String>,
263    /// Durable transcript to replay after a runtime restart.
264    pub replay_transcript: Option<String>,
265}
266
267/// Input payload for one provider-agnostic agent turn.
268#[derive(Debug, Clone)]
269pub struct TurnRequest {
270    /// Prior context needed to continue this turn.
271    pub continuation: TurnContinuation,
272    /// Session worktree folder where the agent runs.
273    pub folder: PathBuf,
274    /// Main repository checkout that must remain read-only during the turn,
275    /// when Agentty can resolve it.
276    pub main_checkout_root: Option<PathBuf>,
277    /// Provider-specific model identifier.
278    pub model: String,
279    /// Filesystem and command permission policy for this turn.
280    pub permission_mode: PermissionMode,
281    /// Personality prompt state resolved from the session worktree.
282    pub personality: PersonalityPrompt,
283    /// Structured prompt payload for the turn.
284    pub prompt: TurnPrompt,
285    /// Reasoning effort preference for the turn.
286    ///
287    /// Ignored by providers/models that do not support reasoning effort.
288    pub reasoning_level: ReasoningLevel,
289    /// Canonical request kind that drives transport behavior and protocol
290    /// semantics for this turn.
291    pub request_kind: AgentRequestKind,
292    /// Preferred amount of detail in user-facing session responses.
293    pub response_style: ResponseStyle,
294    /// Response-speed preference for the turn.
295    pub speed_mode: SpeedMode,
296}
297
298/// Incremental event emitted during one agent turn.
299///
300/// Events are sent through an [`mpsc::UnboundedSender`] as the turn
301/// progresses, enabling transient loader updates without appending partial turn
302/// output into the persisted transcript.
303#[derive(Clone, Debug, PartialEq)]
304pub enum TurnEvent {
305    /// A streamed thinking/planning or tool-status fragment shown in the
306    /// transient loader.
307    ThoughtDelta(String),
308    /// The turn completed successfully with final token counts.
309    Completed {
310        /// Whether the provider reset its context for this turn.
311        context_reset: bool,
312        /// Input token count for the turn.
313        input_tokens: u64,
314        /// Output token count for the turn.
315        output_tokens: u64,
316    },
317    /// The turn failed with an error description.
318    Failed(String),
319    /// A child process PID update.
320    ///
321    /// Announces a running or retained runtime (`Some(pid)`) or clears it
322    /// when the runtime shuts down (`None`). Consumers update resource
323    /// accounting. Cancellation belongs to the runtime owner; hosts must not
324    /// signal a sampled accounting PID.
325    PidUpdate(Option<u32>),
326}
327
328/// Normalized result returned when one agent turn completes successfully.
329#[derive(Debug)]
330pub struct TurnResult {
331    /// Parsed agent response containing structured protocol messages.
332    pub assistant_message: AgentResponse,
333    /// Whether the provider reset its context to complete this turn.
334    pub context_reset: bool,
335    /// Input token count for the turn.
336    pub input_tokens: u64,
337    /// Output token count for the turn.
338    pub output_tokens: u64,
339    /// Provider-native conversation identifier observed after the turn.
340    ///
341    /// App-server providers return this so the worker can persist it for
342    /// future runtime restarts. CLI channels always return `None`.
343    /// Opaque runtime conversation identifier.
344    pub provider_conversation_id: Option<String>,
345}
346
347/// Opaque reference to an active agent session.
348pub struct SessionRef {
349    /// Stable session identifier.
350    pub session_id: String,
351}
352
353/// Input payload for initiating a new agent session.
354pub struct StartSessionRequest {
355    /// Session worktree folder.
356    pub folder: PathBuf,
357    /// Stable session identifier.
358    pub session_id: String,
359}
360
361/// Typed error returned by [`AgentChannel`] operations.
362///
363/// Discriminates failure causes so the app layer can route errors without
364/// parsing formatted messages.
365#[derive(Debug, thiserror::Error)]
366pub enum AgentError {
367    /// An infrastructure or lifecycle failure reported by the runtime adapter.
368    #[error("{0}")]
369    Runtime(String),
370
371    /// A CLI backend command or process execution failure.
372    #[error("{0}")]
373    Backend(String),
374
375    /// The user explicitly interrupted the active turn.
376    #[error("{0}")]
377    InterruptedByUser(String),
378
379    /// A subprocess IO error such as a spawn failure or unavailable pipe.
380    #[error("{0}")]
381    Io(String),
382}
383
384/// Provider-agnostic session channel for executing agent turns.
385///
386/// Implementations bridge a specific transport - CLI subprocess or app-server
387/// RPC - to the unified [`TurnEvent`] stream consumed by session workers. The
388/// trait is object-safe so it can be held as `Arc<dyn AgentChannel>`.
389#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
390pub trait AgentChannel: Send + Sync {
391    /// Initialises a provider session for the given session identifier.
392    ///
393    /// Implementations that do not maintain persistent sessions return
394    /// immediately with a [`SessionRef`] wrapping the supplied identifier.
395    fn start_session(
396        &self,
397        req: StartSessionRequest,
398    ) -> AgentFuture<Result<SessionRef, AgentError>>;
399
400    /// Executes one prompt turn and streams incremental events to `events`.
401    ///
402    /// Implementations may emit [`TurnEvent::ThoughtDelta`] values for
403    /// transient loader updates. Final transcript output is derived from the
404    /// returned [`TurnResult`] after the turn finishes.
405    /// Dropping the returned future must release its owned execution resources;
406    /// cancellation callers will not poll the future again to drain it.
407    ///
408    /// # Errors
409    /// Returns [`AgentError`] when the turn cannot be executed (spawn failure,
410    /// transport error) or is interrupted by a signal.
411    fn run_turn(
412        &self,
413        session_id: String,
414        req: TurnRequest,
415        events: mpsc::UnboundedSender<TurnEvent>,
416    ) -> AgentFuture<Result<TurnResult, AgentError>>;
417
418    /// Tears down the provider session associated with `session_id`.
419    ///
420    /// Cancellation must be idempotent and must never start an unpolled turn.
421    /// Implementations release persistent resources or cancel active CLI turns.
422    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>>;
423}
424
425#[cfg(test)]
426#[path = "contract_test.rs"]
427mod tests;