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};
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 /// Structured prompt payload for this turn.
64 pub prompt: TurnPrompt,
65 /// Canonical request kind that drives transport behavior and protocol
66 /// semantics for this turn.
67 pub request_kind: AgentRequestKind,
68 /// Replayable transcript text captured when the turn was queued.
69 pub replay_transcript: Option<String>,
70 /// Provider-native thread/session id used to resume context in a newly
71 /// started runtime.
72 pub provider_conversation_id: Option<String>,
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 /// Reasoning effort preference for this turn.
77 ///
78 /// Ignored by providers/models that do not support reasoning effort.
79 pub reasoning_level: ReasoningLevel,
80 /// Stable agentty session id.
81 pub session_id: String,
82}
83
84/// Normalized result for one app-server turn.
85#[derive(Debug)]
86pub struct AppServerTurnResponse {
87 pub assistant_message: String,
88 pub context_reset: bool,
89 pub input_tokens: u64,
90 pub output_tokens: u64,
91 pub pid: Option<u32>,
92 /// Provider-native thread/session id observed after the turn.
93 pub provider_conversation_id: Option<String>,
94}
95
96/// Persistent app-server session boundary used by session workers.
97#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
98pub trait AppServerClient: Send + Sync {
99 /// Executes one prompt turn for a session and returns normalized output.
100 ///
101 /// Intermediate events (agent messages, progress updates) are sent through
102 /// `stream_tx` as they arrive, enabling the caller to display streaming
103 /// output before the turn completes.
104 fn run_turn(
105 &self,
106 request: AppServerTurnRequest,
107 stream_tx: mpsc::UnboundedSender<AppServerStreamEvent>,
108 ) -> AppServerFuture<Result<AppServerTurnResponse, AppServerError>>;
109
110 /// Stops and forgets a session runtime, if one exists.
111 fn shutdown_session(&self, session_id: String) -> AppServerFuture<()>;
112}