Skip to main content

ag_contracts/
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    /// Proposes an initial graph or asks clarification without launching nodes.
40    GraphProposal,
41    /// Reconcile review-request metadata using a direct typed result.
42    ReviewMetadata,
43    /// Starts a fresh interactive session turn with no prior context.
44    SessionStart,
45    /// Resumes an interactive session turn.
46    SessionResume,
47    /// Runs one utility prompt with utility protocol requirements.
48    ///
49    /// Callers may route this through an isolated one-shot channel or through
50    /// an existing session channel when the utility work needs provider
51    /// conversation continuity without normal post-turn auto-commit handling.
52    UtilityPrompt,
53    /// Reads provider account metadata without creating an agent turn.
54    AccountRead,
55}
56
57impl AgentRequestKind {
58    /// Returns the protocol request profile derived from this request kind.
59    #[must_use]
60    pub fn protocol_profile(&self) -> ProtocolRequestProfile {
61        match self {
62            Self::SessionStart | Self::SessionResume => ProtocolRequestProfile::SessionTurn,
63            Self::FocusedReview => ProtocolRequestProfile::FocusedReview,
64            Self::GraphProposal => ProtocolRequestProfile::GraphProposal,
65            Self::ReviewMetadata => ProtocolRequestProfile::ReviewMetadata,
66            Self::UtilityPrompt | Self::AccountRead => ProtocolRequestProfile::UtilityPrompt,
67        }
68    }
69
70    /// Returns whether this request resumes a prior interactive session turn.
71    #[must_use]
72    pub fn is_resume(&self) -> bool {
73        matches!(self, Self::SessionResume)
74    }
75}
76
77/// Agent prompt state prepared for one provider turn.
78#[derive(Clone, Debug, Default, Eq, PartialEq)]
79pub struct AgentDefinitionPrompt {
80    current: Option<String>,
81    update: AgentDefinitionPromptUpdate,
82}
83
84impl AgentDefinitionPrompt {
85    /// Creates one active agent, marking whether delta-mode providers
86    /// must receive its body as an update.
87    #[must_use]
88    pub fn active(prompt: String, changed: bool) -> Self {
89        let update = if changed {
90            AgentDefinitionPromptUpdate::Set(prompt.clone())
91        } else {
92            AgentDefinitionPromptUpdate::Unchanged
93        };
94
95        Self {
96            current: Some(prompt),
97            update,
98        }
99    }
100
101    /// Creates a cleared agent state.
102    ///
103    /// `changed` is true when retained context previously held active agent
104    /// instructions and must be told to discard them, including on bootstrap.
105    #[must_use]
106    pub fn cleared(changed: bool) -> Self {
107        Self {
108            current: None,
109            update: if changed {
110                AgentDefinitionPromptUpdate::Clear
111            } else {
112                AgentDefinitionPromptUpdate::Unchanged
113            },
114        }
115    }
116
117    /// Returns the current agent body for a full bootstrap.
118    #[must_use]
119    pub fn current(&self) -> Option<&str> {
120        self.current.as_deref()
121    }
122
123    /// Returns the instruction update to apply when continuing context.
124    pub fn update(&self) -> &AgentDefinitionPromptUpdate {
125        &self.update
126    }
127}
128
129/// Agent change for a provider-managed conversation or retained native history.
130#[derive(Clone, Debug, Default, Eq, PartialEq)]
131pub enum AgentDefinitionPromptUpdate {
132    /// Clear agent behavior that was active on the previous turn.
133    Clear,
134    /// Apply a new or edited agent body.
135    Set(String),
136    /// Reuse the agent behavior already present in provider context.
137    #[default]
138    Unchanged,
139}
140
141/// Continuation state for one provider-agnostic agent turn.
142///
143/// The concrete representation keeps provider-runtime recovery details out of
144/// [`TurnRequest`] while allowing CLI channels to consume only replay text.
145#[derive(Clone, Debug)]
146pub struct TurnContinuation {
147    kind: TurnContinuationKind,
148    usage_checkpoint: Option<String>,
149}
150
151impl TurnContinuation {
152    /// Creates continuation state for a fresh turn with no prior context.
153    #[must_use]
154    pub fn fresh() -> Self {
155        Self {
156            kind: TurnContinuationKind::Fresh,
157            usage_checkpoint: None,
158        }
159    }
160
161    /// Creates continuation state for a stateless turn that replays prior text.
162    #[must_use]
163    pub fn replaying(replay_transcript: String) -> Self {
164        Self {
165            kind: TurnContinuationKind::Replay { replay_transcript },
166            usage_checkpoint: None,
167        }
168    }
169
170    /// Carries the totals of the [`crate::TurnUsage::checkpoint`] the
171    /// conversation this turn continues left, from which the agent derives
172    /// this turn's own usage.
173    #[must_use]
174    pub fn with_usage_checkpoint(mut self, usage_checkpoint: Option<String>) -> Self {
175        self.usage_checkpoint = usage_checkpoint;
176
177        self
178    }
179
180    /// Returns the usage checkpoint totals of the conversation this turn
181    /// continues, when the host stored one.
182    #[must_use]
183    pub fn usage_checkpoint(&self) -> Option<&str> {
184        self.usage_checkpoint.as_deref()
185    }
186
187    /// Creates continuation state for a provider runtime that may resume a
188    /// native conversation and reconstruct context from a live transcript.
189    #[must_use]
190    pub fn provider(
191        live_transcript: Option<Arc<dyn LiveTranscript>>,
192        persisted_instruction_conversation_id: Option<String>,
193        provider_conversation_id: Option<String>,
194        replay_transcript: Option<String>,
195    ) -> Self {
196        Self {
197            kind: TurnContinuationKind::Provider {
198                live_transcript,
199                persisted_instruction_conversation_id,
200                provider_conversation_id,
201                replay_transcript,
202            },
203            usage_checkpoint: None,
204        }
205    }
206
207    /// Returns replayable transcript text when this turn carries it.
208    #[must_use]
209    pub fn replay_transcript(&self) -> Option<&str> {
210        match &self.kind {
211            TurnContinuationKind::Fresh => None,
212            TurnContinuationKind::Provider {
213                replay_transcript, ..
214            } => replay_transcript.as_deref(),
215            TurnContinuationKind::Replay { replay_transcript } => Some(replay_transcript.as_str()),
216        }
217    }
218
219    /// Returns the provider-native conversation identifier when available.
220    #[must_use]
221    pub fn provider_conversation_id(&self) -> Option<&str> {
222        match &self.kind {
223            TurnContinuationKind::Provider {
224                provider_conversation_id,
225                ..
226            } => provider_conversation_id.as_deref(),
227            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
228        }
229    }
230
231    /// Returns the conversation identifier that received the instruction
232    /// bootstrap when available.
233    #[must_use]
234    pub fn persisted_instruction_conversation_id(&self) -> Option<&str> {
235        match &self.kind {
236            TurnContinuationKind::Provider {
237                persisted_instruction_conversation_id,
238                ..
239            } => persisted_instruction_conversation_id.as_deref(),
240            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
241        }
242    }
243
244    /// Consumes continuation state for a runtime adapter.
245    pub fn into_parts(self) -> TurnContinuationParts {
246        match self.kind {
247            TurnContinuationKind::Fresh => TurnContinuationParts::default(),
248            TurnContinuationKind::Replay { replay_transcript } => TurnContinuationParts {
249                replay_transcript: Some(replay_transcript),
250                ..TurnContinuationParts::default()
251            },
252            TurnContinuationKind::Provider {
253                live_transcript,
254                persisted_instruction_conversation_id,
255                provider_conversation_id,
256                replay_transcript,
257            } => TurnContinuationParts {
258                live_transcript,
259                persisted_instruction_conversation_id,
260                provider_conversation_id,
261                replay_transcript,
262            },
263        }
264    }
265}
266
267#[derive(Clone, Debug)]
268enum TurnContinuationKind {
269    Fresh,
270    Provider {
271        live_transcript: Option<Arc<dyn LiveTranscript>>,
272        persisted_instruction_conversation_id: Option<String>,
273        provider_conversation_id: Option<String>,
274        replay_transcript: Option<String>,
275    },
276    Replay {
277        replay_transcript: String,
278    },
279}
280
281/// Owned continuation inputs consumed by a runtime adapter.
282#[derive(Default)]
283pub struct TurnContinuationParts {
284    /// Current replay projection, when supplied by the host.
285    pub live_transcript: Option<Arc<dyn LiveTranscript>>,
286    /// Conversation that received the current instructions.
287    pub persisted_instruction_conversation_id: Option<String>,
288    /// Opaque runtime conversation identifier.
289    pub provider_conversation_id: Option<String>,
290    /// Durable transcript to replay after a runtime restart.
291    pub replay_transcript: Option<String>,
292}
293
294/// Input payload for one provider-agnostic agent turn.
295#[derive(Debug, Clone)]
296pub struct TurnRequest {
297    /// Whether the turn compacts the session's earlier turns once they nearly
298    /// fill the model's context window. Only in-process harness turns
299    /// compact; other agents manage their own context and ignore it.
300    pub context_compaction: ContextCompaction,
301    /// Prior context needed to continue this turn.
302    pub continuation: TurnContinuation,
303    /// Resolved harness policy. The worker replaces this with its configured
304    /// policy before dispatch; application callers supply the default value.
305    pub execution_policy: crate::ExecutionPolicy,
306    /// Session worktree folder where the agent runs.
307    pub folder: PathBuf,
308    /// Which dependency caches sandboxed commands of an in-process harness
309    /// turn use. Agents that run without the native sandbox ignore it.
310    pub host_caches: HostCacheSharing,
311    /// Main repository checkout that must remain read-only during the turn,
312    /// when Agentty can resolve it.
313    pub main_checkout_root: Option<PathBuf>,
314    /// Provider-specific model identifier.
315    pub model: String,
316    /// Filesystem and command permission policy for this turn.
317    pub permission_mode: PermissionMode,
318    /// Agent prompt state resolved from the session worktree.
319    pub agent_profile: AgentDefinitionPrompt,
320    /// Structured prompt payload for the turn.
321    pub prompt: TurnPrompt,
322    /// Shared provider-call ceiling, including retries and protocol repairs.
323    pub provider_call_budget: Option<crate::ProviderCallBudget>,
324    /// Reasoning effort preference for the turn.
325    ///
326    /// Ignored by providers/models that do not support reasoning effort.
327    pub reasoning_level: ReasoningLevel,
328    /// Canonical request kind that drives transport behavior and protocol
329    /// semantics for this turn.
330    pub request_kind: AgentRequestKind,
331    /// Preferred amount of detail in user-facing session responses.
332    pub response_style: ResponseStyle,
333    /// Response-speed preference for the turn.
334    pub speed_mode: SpeedMode,
335}
336
337/// Which dependency caches (Cargo, Go, pip, npm) sandboxed harness commands
338/// use.
339#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
340pub enum HostCacheSharing {
341    /// Copies in the session's own temporary directory, which host tools
342    /// and other sessions never read.
343    #[default]
344    PerSession,
345    /// The host's own caches, which commands can then write, so a session
346    /// could tamper with packages that other sessions and the host's own
347    /// builds later use.
348    Shared,
349}
350
351impl HostCacheSharing {
352    /// Returns the sharing a persisted on/off toggle selects.
353    #[must_use]
354    pub fn from_enabled(enabled: bool) -> Self {
355        if enabled {
356            Self::Shared
357        } else {
358            Self::PerSession
359        }
360    }
361
362    /// Returns whether commands use the host's own caches.
363    #[must_use]
364    pub fn is_shared(self) -> bool {
365        self == Self::Shared
366    }
367}
368
369/// How a turn handles a session context that outgrows the model's window.
370#[derive(Clone, Debug, Default, Eq, PartialEq)]
371pub enum ContextCompaction {
372    /// The turn never compacts; history that no longer fits is left out of
373    /// its requests, oldest first.
374    #[default]
375    Off,
376    /// The turn first summarizes earlier turns into a checkpoint that later
377    /// requests carry in their place.
378    Automatic {
379        /// Model that writes the summary, such as the user's Default Fast
380        /// Model, or `None` for [`TurnRequest::model`]. Harness turns also
381        /// use [`TurnRequest::model`] when this model cannot serve
382        /// summaries.
383        summary_model: Option<String>,
384    },
385}
386
387/// Incremental event emitted during one agent turn.
388///
389/// Events are sent through an [`mpsc::UnboundedSender`] as the turn
390/// progresses, enabling transient loader updates and structured activity
391/// delivery without appending partial answers into the persisted transcript.
392#[derive(Clone, Debug, PartialEq)]
393pub enum TurnEvent {
394    /// Provider-observed tool or skill lifecycle snapshot.
395    Activity(crate::ActivityEvent),
396    /// A streamed thinking/planning or tool-status fragment shown in the
397    /// transient loader.
398    ThoughtDelta(String),
399    /// Model output streamed by an in-process harness turn, shown
400    /// transiently until the turn result is persisted.
401    Output(crate::OutputEvent),
402    /// Something about how the turn ran that the user should know, such as
403    /// a compaction of the session's earlier context.
404    Notice(crate::TurnNotice),
405    /// Cumulative usage of the turn so far, sent after each model request
406    /// whose usage the backend reports while the turn runs. The final
407    /// [`TurnResult::usage`] supersedes it.
408    UsageUpdated(crate::TurnUsage),
409    /// The turn failed with an error description.
410    Failed(String),
411    /// A child process PID update.
412    ///
413    /// Announces a running or retained runtime (`Some(pid)`) or clears it
414    /// when the runtime shuts down (`None`). Consumers update resource
415    /// accounting. Cancellation belongs to the runtime owner; hosts must not
416    /// signal a sampled accounting PID.
417    PidUpdate(Option<u32>),
418}
419
420/// Normalized result returned when one agent turn completes successfully.
421#[derive(Debug)]
422pub struct TurnResult {
423    /// Parsed agent response containing structured protocol messages.
424    pub assistant_message: AgentResponse,
425    /// Whether the provider reset its context to complete this turn.
426    pub context_reset: bool,
427    /// Content-free JSON report of an in-process harness turn: per-request
428    /// usage, context fitting, corrections, and tool activity. Other agents
429    /// return `None`.
430    pub harness_report: Option<String>,
431    /// Provider-native conversation identifier observed after the turn.
432    ///
433    /// App-server providers return this so the worker can persist it for
434    /// future runtime restarts. CLI channels always return `None`.
435    /// Opaque runtime conversation identifier.
436    pub provider_conversation_id: Option<String>,
437    /// Tokens and estimated charge of every model the turn used, as its
438    /// backend reported them.
439    pub usage: crate::TurnUsage,
440}
441
442/// Opaque reference to an active agent session.
443pub struct SessionRef {
444    /// Stable session identifier.
445    pub session_id: String,
446}
447
448/// Input payload for initiating a new agent session.
449pub struct StartSessionRequest {
450    /// Session worktree folder.
451    pub folder: PathBuf,
452    /// Stable session identifier.
453    pub session_id: String,
454}
455
456/// Typed error returned by [`AgentChannel`] operations.
457///
458/// Discriminates failure causes so the app layer can route errors without
459/// parsing formatted messages.
460#[derive(Debug, thiserror::Error)]
461pub enum AgentError {
462    /// An infrastructure or lifecycle failure reported by the runtime adapter.
463    #[error("{0}")]
464    Runtime(String),
465
466    /// A CLI backend command or process execution failure.
467    #[error("{0}")]
468    Backend(String),
469
470    /// The user explicitly interrupted the active turn.
471    #[error("{0}")]
472    InterruptedByUser(String),
473
474    /// A subprocess IO error such as a spawn failure or unavailable pipe.
475    #[error("{0}")]
476    Io(String),
477}
478
479/// Provider-agnostic session channel for executing agent turns.
480///
481/// Implementations bridge a specific transport - CLI subprocess or app-server
482/// RPC - to the unified [`TurnEvent`] stream consumed by session workers. The
483/// trait is object-safe so it can be held as `Arc<dyn AgentChannel>`.
484#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
485pub trait AgentChannel: Send + Sync {
486    /// Initialises a provider session for the given session identifier.
487    ///
488    /// Implementations that do not maintain persistent sessions return
489    /// immediately with a [`SessionRef`] wrapping the supplied identifier.
490    fn start_session(
491        &self,
492        req: StartSessionRequest,
493    ) -> AgentFuture<Result<SessionRef, AgentError>>;
494
495    /// Executes one prompt turn and streams incremental events to `events`.
496    ///
497    /// Implementations may emit [`TurnEvent::ThoughtDelta`] values for
498    /// transient loader updates. Final transcript output is derived from the
499    /// returned [`TurnResult`] after the turn finishes.
500    /// Dropping the returned future must release its owned execution resources;
501    /// cancellation callers will not poll the future again to drain it.
502    ///
503    /// # Errors
504    /// Returns [`AgentError`] when the turn cannot be executed (spawn failure,
505    /// transport error) or is interrupted by a signal.
506    fn run_turn(
507        &self,
508        session_id: String,
509        req: TurnRequest,
510        events: mpsc::UnboundedSender<TurnEvent>,
511    ) -> AgentFuture<Result<TurnResult, AgentError>>;
512
513    /// Delivers one user prompt to the in-flight interactive session turn for
514    /// `session_id`, so the agent reads it before that turn ends.
515    ///
516    /// `Ok` means the provider accepted the prompt into the running turn; the
517    /// caller then owns recording it in the transcript. Any error leaves the
518    /// prompt undelivered so callers can submit it as a later turn. Only
519    /// session-start and session-resume turns accept steering; utility and
520    /// review turns reject it. The default reports that the harness cannot
521    /// steer.
522    ///
523    /// # Errors
524    /// Returns [`AgentError::Runtime`] when the harness cannot steer, no
525    /// interactive turn is running, or the provider rejects the prompt.
526    fn steer_turn(
527        &self,
528        session_id: String,
529        prompt: TurnPrompt,
530    ) -> AgentFuture<Result<(), AgentError>> {
531        // Nothing is delivered; callers keep their own copy for a later turn.
532        drop((session_id, prompt));
533
534        Box::pin(async {
535            Err(AgentError::Runtime(
536                "This agent cannot receive messages during a turn".to_string(),
537            ))
538        })
539    }
540
541    /// Tears down the provider session associated with `session_id`.
542    ///
543    /// Cancellation must be idempotent and must never start an unpolled turn.
544    /// Implementations release persistent resources or cancel active CLI turns.
545    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>>;
546}
547
548#[cfg(test)]
549#[path = "contract_test.rs"]
550mod tests;