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