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    /// Personality prompt state resolved for this turn.
70    pub personality: PersonalityPrompt,
71    /// Structured prompt payload for this turn.
72    pub prompt: TurnPrompt,
73    /// Canonical request kind that drives transport behavior and protocol
74    /// semantics for this turn.
75    pub request_kind: AgentRequestKind,
76    /// Replayable transcript text captured when the turn was queued.
77    pub replay_transcript: Option<String>,
78    /// Provider-native thread/session id used to resume context in a newly
79    /// started runtime.
80    pub provider_conversation_id: Option<String>,
81    /// Persisted provider-native conversation id that already received the
82    /// full instruction bootstrap, when available.
83    pub persisted_instruction_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    /// Stable agentty session id.
89    pub session_id: String,
90    /// Response-speed preference for this turn.
91    pub speed_mode: SpeedMode,
92}
93
94/// Normalized result for one app-server turn.
95#[derive(Debug)]
96pub struct AppServerTurnResponse {
97    /// Final assistant payload returned by the provider runtime.
98    pub assistant_message: String,
99    /// Whether the provider reset its native context during the turn.
100    pub context_reset: bool,
101    /// Input token count reported for the completed turn.
102    pub input_tokens: u64,
103    /// Output token count reported for the completed turn.
104    pub output_tokens: u64,
105    /// Provider runtime process identifier when retained after the turn.
106    /// Cleared once a non-retained runtime has shut down.
107    pub pid: Option<u32>,
108    /// Provider-native thread/session id observed after the turn.
109    pub provider_conversation_id: Option<String>,
110}
111
112/// Persistent app-server session boundary used by session workers.
113#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
114pub trait AppServerClient: Send + Sync {
115    /// Executes one prompt turn for a session and returns normalized output.
116    ///
117    /// Intermediate events (agent messages, progress updates) are sent through
118    /// `stream_tx` as they arrive, enabling the caller to display streaming
119    /// output before the turn completes.
120    fn run_turn(
121        &self,
122        request: AppServerTurnRequest,
123        stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
124    ) -> AppServerFuture<Result<AppServerTurnResponse, AppServerError>>;
125
126    /// Stops and forgets a session runtime, if one exists.
127    fn shutdown_session(&self, session_id: String) -> AppServerFuture<()>;
128}