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;
14
15/// Boxed async result used by [`AppServerClient`] trait methods.
16pub type AppServerFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
17
18/// Boxed async result that can borrow values from the current call frame.
19pub(crate) type BorrowedAppServerFuture<'scope, T> =
20    Pin<Box<dyn Future<Output = T> + Send + 'scope>>;
21
22/// Incremental event emitted during one app-server turn.
23///
24/// The caller receives these events through an [`mpsc::UnboundedSender`]
25/// channel while the turn is in progress, enabling real-time streaming of
26/// agent output and progress updates to the UI.
27#[derive(Clone, Debug, PartialEq)]
28pub enum AppServerStreamEvent {
29    /// Assistant text received while a turn is running.
30    AssistantMessage {
31        /// Text payload emitted by the provider.
32        message: String,
33        /// Optional provider phase label for this assistant item.
34        ///
35        /// Codex `item/completed` agent messages may include `phase` values
36        /// (for example, from multi-phase prompting flows). Providers that do
37        /// not expose phases set this to `None`.
38        phase: Option<String>,
39        /// Whether `message` is a partial delta chunk that should be appended
40        /// inline without paragraph spacing.
41        is_delta: bool,
42    },
43    /// An `item/started` event produced a progress description.
44    ProgressUpdate(String),
45}
46
47/// Input payload for one app-server turn execution.
48#[derive(Clone)]
49pub struct AppServerTurnRequest {
50    /// Session worktree folder where the provider runtime executes.
51    pub folder: PathBuf,
52    /// Live in-memory transcript source updated by the streaming consumer.
53    ///
54    /// When set, restart-and-retry reads the latest accumulated transcript
55    /// from this source instead of the queued snapshot, ensuring content
56    /// streamed before the crash is included in the replay prompt.
57    pub live_transcript: Option<Arc<dyn LiveTranscript>>,
58    /// Main repository checkout that must remain read-only during the turn,
59    /// when Agentty can resolve it.
60    pub main_checkout_root: Option<PathBuf>,
61    /// Provider-specific model identifier.
62    pub model: String,
63    /// Personality prompt state resolved for this turn.
64    pub personality: PersonalityPrompt,
65    /// Structured prompt payload for this turn.
66    pub prompt: TurnPrompt,
67    /// Canonical request kind that drives transport behavior and protocol
68    /// semantics for this turn.
69    pub request_kind: AgentRequestKind,
70    /// Replayable transcript text captured when the turn was queued.
71    pub replay_transcript: Option<String>,
72    /// Provider-native thread/session id used to resume context in a newly
73    /// started runtime.
74    pub provider_conversation_id: Option<String>,
75    /// Persisted provider-native conversation id that already received the
76    /// full instruction bootstrap, when available.
77    pub persisted_instruction_conversation_id: Option<String>,
78    /// Reasoning effort preference for this turn.
79    ///
80    /// Ignored by providers/models that do not support reasoning effort.
81    pub reasoning_level: ReasoningLevel,
82    /// Stable agentty session id.
83    pub session_id: String,
84}
85
86/// Normalized result for one app-server turn.
87#[derive(Debug)]
88pub struct AppServerTurnResponse {
89    /// Final assistant payload returned by the provider runtime.
90    pub assistant_message: String,
91    /// Whether the provider reset its native context during the turn.
92    pub context_reset: bool,
93    /// Input token count reported for the completed turn.
94    pub input_tokens: u64,
95    /// Output token count reported for the completed turn.
96    pub output_tokens: u64,
97    /// Provider runtime process identifier when available.
98    pub pid: Option<u32>,
99    /// Provider-native thread/session id observed after the turn.
100    pub provider_conversation_id: Option<String>,
101}
102
103/// Persistent app-server session boundary used by session workers.
104#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
105pub trait AppServerClient: Send + Sync {
106    /// Executes one prompt turn for a session and returns normalized output.
107    ///
108    /// Intermediate events (agent messages, progress updates) are sent through
109    /// `stream_tx` as they arrive, enabling the caller to display streaming
110    /// output before the turn completes.
111    fn run_turn(
112        &self,
113        request: AppServerTurnRequest,
114        stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
115    ) -> AppServerFuture<Result<AppServerTurnResponse, AppServerError>>;
116
117    /// Stops and forgets a session runtime, if one exists.
118    fn shutdown_session(&self, session_id: String) -> AppServerFuture<()>;
119}