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