Skip to main content

ag_agent/app_server/
contract.rs

1//! Shared app-server contracts and request/response types.
2
3use std::future::Future;
4use std::path::PathBuf;
5use std::pin::Pin;
6use std::sync::Arc;
7
8use ag_contracts::{
9    AgentRequestKind, LiveTranscript, PermissionMode, PersonalityPrompt, ReasoningLevel, SpeedMode,
10};
11use ag_protocol::TurnPrompt;
12use tokio::sync::mpsc;
13
14use crate::app_server::AppServerError;
15
16/// Boxed async result used by [`AppServerClient`] trait methods.
17pub type AppServerFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
18
19/// Boxed async result that can borrow values from the current call frame.
20pub(crate) type BorrowedAppServerFuture<'scope, T> =
21    Pin<Box<dyn Future<Output = T> + Send + 'scope>>;
22
23/// Incremental event emitted during one app-server turn.
24///
25/// The caller receives these events through an [`mpsc::UnboundedSender`]
26/// channel while the turn is in progress, enabling real-time streaming of
27/// agent output and progress updates to the UI.
28#[derive(Clone, Debug, PartialEq)]
29pub enum AppServerStreamEvent {
30    /// Runtime process available before executing a turn or retry.
31    PidUpdate(Option<u32>),
32    /// Assistant text received while a turn is running.
33    AssistantMessage {
34        /// Text payload emitted by the provider.
35        message: String,
36        /// Optional provider phase label for this assistant item.
37        ///
38        /// Codex `item/completed` agent messages may include `phase` values
39        /// (for example, from multi-phase prompting flows). Providers that do
40        /// not expose phases set this to `None`.
41        phase: Option<String>,
42        /// Whether `message` is a partial delta chunk that should be appended
43        /// inline without paragraph spacing.
44        is_delta: bool,
45    },
46    /// An `item/started` event produced a progress description.
47    ProgressUpdate(String),
48}
49
50/// Input payload for one app-server turn execution.
51#[derive(Clone)]
52pub struct AppServerTurnRequest {
53    /// Worker-selected policy, preserved across runtime restarts and repairs.
54    pub execution_policy: ag_contracts::ExecutionPolicy,
55    /// Session worktree folder where the provider runtime executes.
56    pub folder: PathBuf,
57    /// Live in-memory transcript source updated by the streaming consumer.
58    ///
59    /// When set, restart-and-retry reads the latest accumulated transcript
60    /// from this source instead of the queued snapshot, ensuring content
61    /// streamed before the crash is included in the replay prompt.
62    pub live_transcript: Option<Arc<dyn LiveTranscript>>,
63    /// Main repository checkout that must remain read-only during the turn,
64    /// when Agentty can resolve it.
65    pub main_checkout_root: Option<PathBuf>,
66    /// Provider-specific model identifier.
67    pub model: String,
68    /// Filesystem and command permission policy for this turn.
69    pub permission_mode: PermissionMode,
70    /// Persisted provider-native conversation id that already received the
71    /// full instruction bootstrap, when available.
72    pub persisted_instruction_conversation_id: Option<String>,
73    /// Personality prompt state resolved for this turn.
74    pub personality: PersonalityPrompt,
75    /// Structured prompt payload for this turn.
76    pub prompt: TurnPrompt,
77    /// Optional shared limit, charged for every underlying attempt and retry.
78    pub provider_call_budget: Option<ag_contracts::ProviderCallBudget>,
79    /// Provider-native thread/session id used to resume context in a newly
80    /// started runtime.
81    pub provider_conversation_id: Option<String>,
82    /// Reasoning effort preference for this turn.
83    ///
84    /// Ignored by providers/models that do not support reasoning effort.
85    pub reasoning_level: ReasoningLevel,
86    /// Replayable transcript text captured when the turn was queued.
87    pub replay_transcript: Option<String>,
88    /// Canonical request kind that drives transport behavior and protocol
89    /// semantics for this turn.
90    pub request_kind: AgentRequestKind,
91    /// Stable agentty session id.
92    pub session_id: String,
93    /// Response-speed preference for this turn.
94    pub speed_mode: SpeedMode,
95}
96
97/// Normalized result for one app-server turn.
98#[derive(Debug)]
99pub struct AppServerTurnResponse {
100    /// Final assistant payload returned by the provider runtime.
101    pub assistant_message: String,
102    /// Whether the provider reset its native context during the turn.
103    pub context_reset: bool,
104    /// Input token count reported for the completed turn.
105    pub input_tokens: u64,
106    /// Output token count reported for the completed turn.
107    pub output_tokens: u64,
108    /// Provider runtime process identifier when retained after the turn.
109    /// Cleared once a non-retained runtime has shut down.
110    pub pid: Option<u32>,
111    /// Provider-native thread/session id observed after the turn.
112    pub provider_conversation_id: Option<String>,
113}
114
115/// Persistent app-server session boundary used by session workers.
116#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
117pub trait AppServerClient: Send + Sync {
118    /// Executes one prompt turn for a session and returns normalized output.
119    /// Implementations must charge `provider_call_budget` before each
120    /// underlying provider attempt, including restart retries.
121    ///
122    /// Intermediate events (agent messages, progress updates) are sent through
123    /// `stream_tx` as they arrive, enabling the caller to display streaming
124    /// output before the turn completes.
125    fn run_turn(
126        &self,
127        request: AppServerTurnRequest,
128        stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
129    ) -> AppServerFuture<Result<AppServerTurnResponse, AppServerError>>;
130
131    /// Runs with fresh conversation context, reusing the process when the
132    /// provider supports resetting context. The fallback restarts the runtime.
133    /// It waits for shutdown to finish before invoking `run_turn`, borrowing
134    /// the client until the returned future completes or is dropped.
135    /// Callers must omit provider conversation IDs and replay context.
136    fn run_isolated_turn<'client>(
137        &'client self,
138        request: AppServerTurnRequest,
139        stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
140    ) -> Pin<Box<dyn Future<Output = Result<AppServerTurnResponse, AppServerError>> + Send + 'client>>
141    {
142        Box::pin(async move {
143            self.shutdown_session(request.session_id.clone()).await;
144            self.run_turn(request, stream_tx).await
145        })
146    }
147
148    /// Continues the current conversation and retains a successful runtime
149    /// for later pooled submissions. Clients without pooling support fall
150    /// back to their ordinary turn lifecycle.
151    fn run_retained_turn(
152        &self,
153        request: AppServerTurnRequest,
154        stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
155    ) -> AppServerFuture<Result<AppServerTurnResponse, AppServerError>> {
156        self.run_turn(request, stream_tx)
157    }
158
159    /// Stops and forgets a session runtime, if one exists.
160    fn shutdown_session(&self, session_id: String) -> AppServerFuture<()>;
161}