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    /// Milestone of the shared task the session works on, carried into
336    /// every interactive session turn as fenced reference data, never as
337    /// instructions. Other request kinds ignore it.
338    pub task_milestone: Option<TaskMilestone>,
339}
340
341/// The milestone a session's shared task belongs to: a higher-level goal
342/// that people or agents of the same account wrote, which helps the agent
343/// align its work. Every field is untrusted text; adapters fence and
344/// neutralize it before it reaches a prompt.
345#[derive(Clone, Debug, Eq, PartialEq)]
346pub struct TaskMilestone {
347    /// What the milestone sets out to achieve; may be empty.
348    pub goal: String,
349    /// Milestone number within its project.
350    pub number: u64,
351    /// Milestone title.
352    pub title: String,
353}
354
355impl TaskMilestone {
356    /// Longest goal, in characters.
357    pub const MAX_GOAL_CHARS: usize = 4000;
358    /// Longest title, in characters.
359    pub const MAX_TITLE_CHARS: usize = 200;
360}
361
362/// Which dependency caches (Cargo, Go, pip, npm) sandboxed harness commands
363/// use.
364#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
365pub enum HostCacheSharing {
366    /// Copies in the session's own temporary directory, which host tools
367    /// and other sessions never read.
368    #[default]
369    PerSession,
370    /// The host's own caches, which commands can then write, so a session
371    /// could tamper with packages that other sessions and the host's own
372    /// builds later use.
373    Shared,
374}
375
376impl HostCacheSharing {
377    /// Returns the sharing a persisted on/off toggle selects.
378    #[must_use]
379    pub fn from_enabled(enabled: bool) -> Self {
380        if enabled {
381            Self::Shared
382        } else {
383            Self::PerSession
384        }
385    }
386
387    /// Returns whether commands use the host's own caches.
388    #[must_use]
389    pub fn is_shared(self) -> bool {
390        self == Self::Shared
391    }
392}
393
394/// How a turn handles a session context that outgrows the model's window.
395#[derive(Clone, Debug, Default, Eq, PartialEq)]
396pub enum ContextCompaction {
397    /// The turn never compacts; history that no longer fits is left out of
398    /// its requests, oldest first.
399    #[default]
400    Off,
401    /// The turn first summarizes earlier turns into a checkpoint that later
402    /// requests carry in their place.
403    Automatic {
404        /// Model that writes the summary, such as the user's Default Fast
405        /// Model, or `None` for [`TurnRequest::model`]. Harness turns also
406        /// use [`TurnRequest::model`] when this model cannot serve
407        /// summaries.
408        summary_model: Option<String>,
409    },
410}
411
412/// Incremental event emitted during one agent turn.
413///
414/// Events are sent through an [`mpsc::UnboundedSender`] as the turn
415/// progresses, enabling transient loader updates and structured activity
416/// delivery without appending partial answers into the persisted transcript.
417#[derive(Clone, Debug, PartialEq)]
418pub enum TurnEvent {
419    /// Provider-observed tool or skill lifecycle snapshot.
420    Activity(crate::ActivityEvent),
421    /// A streamed thinking/planning or tool-status fragment shown in the
422    /// transient loader.
423    ThoughtDelta(String),
424    /// Model output streamed by an in-process harness turn, shown
425    /// transiently until the turn result is persisted.
426    Output(crate::OutputEvent),
427    /// Something about how the turn ran that the user should know, such as
428    /// a compaction of the session's earlier context.
429    Notice(crate::TurnNotice),
430    /// Cumulative usage of the turn so far, sent after each model request
431    /// whose usage the backend reports while the turn runs. The final
432    /// [`TurnResult::usage`] supersedes it.
433    UsageUpdated(crate::TurnUsage),
434    /// The turn failed with an error description.
435    Failed(String),
436    /// A child process PID update.
437    ///
438    /// Announces a running or retained runtime (`Some(pid)`) or clears it
439    /// when the runtime shuts down (`None`). Consumers update resource
440    /// accounting. Cancellation belongs to the runtime owner; hosts must not
441    /// signal a sampled accounting PID.
442    PidUpdate(Option<u32>),
443}
444
445/// Normalized result returned when one agent turn completes successfully.
446#[derive(Debug)]
447pub struct TurnResult {
448    /// Parsed agent response containing structured protocol messages.
449    pub assistant_message: AgentResponse,
450    /// Whether the provider reset its context to complete this turn.
451    pub context_reset: bool,
452    /// Content-free JSON report of an in-process harness turn: per-request
453    /// usage, context fitting, corrections, and tool activity. Other agents
454    /// return `None`.
455    pub harness_report: Option<String>,
456    /// Provider-native conversation identifier observed after the turn.
457    ///
458    /// App-server providers return this so the worker can persist it for
459    /// future runtime restarts. CLI channels always return `None`.
460    /// Opaque runtime conversation identifier.
461    pub provider_conversation_id: Option<String>,
462    /// Tokens and estimated charge of every model the turn used, as its
463    /// backend reported them.
464    pub usage: crate::TurnUsage,
465}
466
467/// Opaque reference to an active agent session.
468pub struct SessionRef {
469    /// Stable session identifier.
470    pub session_id: String,
471}
472
473/// Input payload for initiating a new agent session.
474pub struct StartSessionRequest {
475    /// Session worktree folder.
476    pub folder: PathBuf,
477    /// Stable session identifier.
478    pub session_id: String,
479}
480
481/// Typed error returned by [`AgentChannel`] operations.
482///
483/// Discriminates failure causes so the app layer can route errors without
484/// parsing formatted messages.
485#[derive(Debug, thiserror::Error)]
486pub enum AgentError {
487    /// An infrastructure or lifecycle failure reported by the runtime adapter.
488    #[error("{0}")]
489    Runtime(String),
490
491    /// A CLI backend command or process execution failure.
492    #[error("{0}")]
493    Backend(String),
494
495    /// The user explicitly interrupted the active turn.
496    #[error("{0}")]
497    InterruptedByUser(String),
498
499    /// A subprocess IO error such as a spawn failure or unavailable pipe.
500    #[error("{0}")]
501    Io(String),
502}
503
504/// Provider-agnostic session channel for executing agent turns.
505///
506/// Implementations bridge a specific transport - CLI subprocess or app-server
507/// RPC - to the unified [`TurnEvent`] stream consumed by session workers. The
508/// trait is object-safe so it can be held as `Arc<dyn AgentChannel>`.
509#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
510pub trait AgentChannel: Send + Sync {
511    /// Initialises a provider session for the given session identifier.
512    ///
513    /// Implementations that do not maintain persistent sessions return
514    /// immediately with a [`SessionRef`] wrapping the supplied identifier.
515    fn start_session(
516        &self,
517        req: StartSessionRequest,
518    ) -> AgentFuture<Result<SessionRef, AgentError>>;
519
520    /// Executes one prompt turn and streams incremental events to `events`.
521    ///
522    /// Implementations may emit [`TurnEvent::ThoughtDelta`] values for
523    /// transient loader updates. Final transcript output is derived from the
524    /// returned [`TurnResult`] after the turn finishes.
525    /// Dropping the returned future must release its owned execution resources;
526    /// cancellation callers will not poll the future again to drain it.
527    ///
528    /// # Errors
529    /// Returns [`AgentError`] when the turn cannot be executed (spawn failure,
530    /// transport error) or is interrupted by a signal.
531    fn run_turn(
532        &self,
533        session_id: String,
534        req: TurnRequest,
535        events: mpsc::UnboundedSender<TurnEvent>,
536    ) -> AgentFuture<Result<TurnResult, AgentError>>;
537
538    /// Delivers one user prompt to the in-flight interactive session turn for
539    /// `session_id`, so the agent reads it before that turn ends.
540    ///
541    /// `Ok` means the provider accepted the prompt into the running turn; the
542    /// caller then owns recording it in the transcript. Any error leaves the
543    /// prompt undelivered so callers can submit it as a later turn. Only
544    /// session-start and session-resume turns accept steering; utility and
545    /// review turns reject it. The default reports that the harness cannot
546    /// steer.
547    ///
548    /// # Errors
549    /// Returns [`AgentError::Runtime`] when the harness cannot steer, no
550    /// interactive turn is running, or the provider rejects the prompt.
551    fn steer_turn(
552        &self,
553        session_id: String,
554        prompt: TurnPrompt,
555    ) -> AgentFuture<Result<(), AgentError>> {
556        // Nothing is delivered; callers keep their own copy for a later turn.
557        drop((session_id, prompt));
558
559        Box::pin(async {
560            Err(AgentError::Runtime(
561                "This agent cannot receive messages during a turn".to_string(),
562            ))
563        })
564    }
565
566    /// Tears down the provider session associated with `session_id`.
567    ///
568    /// Cancellation must be idempotent and must never start an unpolled turn.
569    /// Implementations release persistent resources or cancel active CLI turns.
570    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>>;
571}
572
573#[cfg(test)]
574#[path = "contract_test.rs"]
575mod tests;