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