Skip to main content

ag_agent/agent/
provider.rs

1//! Shared provider registry and transport policy descriptors.
2
3use std::sync::Arc;
4
5use ag_protocol::{
6    AgentResponse, ProtocolRequestProfile, ProtocolSchemaInstructionMode,
7    format_protocol_parse_debug_details, parse_protocol_response_strict,
8};
9
10use super::backend::{
11    AgentBackend, AgentBackendError, AgentPromptTransport, AgentTransport, AppServerThoughtPolicy,
12    BuildCommandRequest,
13};
14use super::prompt;
15use super::response_parser::ParsedResponse;
16use crate::app_server::AppServerClient;
17use crate::model::agent::AgentKind;
18
19/// Factory hook used to build or override provider-specific app-server
20/// clients.
21type AppServerClientFactory =
22    fn(Option<Arc<dyn AppServerClient>>) -> Option<Arc<dyn AppServerClient>>;
23
24/// Creates the backend implementation for the selected agent provider.
25pub fn create_backend(kind: AgentKind) -> Box<dyn AgentBackend> {
26    (provider_descriptor(kind).backend_factory)()
27}
28
29/// Returns the app-server client for the selected provider when applicable.
30pub fn create_app_server_client(
31    kind: AgentKind,
32    default_client: Option<Arc<dyn AppServerClient>>,
33) -> Option<Arc<dyn AppServerClient>> {
34    (provider_descriptor(kind).app_server_client_factory)(default_client)
35}
36
37/// Parses provider output and returns final response content and usage stats.
38pub(crate) fn parse_response(kind: AgentKind, stdout: &str, stderr: &str) -> ParsedResponse {
39    (provider_descriptor(kind).parse_response)(stdout, stderr)
40}
41
42/// Parses one stream line into incremental text and content classification.
43///
44/// Returns `(text, is_response_content)` where `is_response_content` is `true`
45/// for model-authored content and `false` for progress updates.
46pub(crate) fn parse_stream_output_line(
47    kind: AgentKind,
48    stdout_line: &str,
49) -> Option<(String, bool)> {
50    (provider_descriptor(kind).parse_stream_output_line)(stdout_line)
51}
52
53/// Returns transport mode for the selected provider.
54pub fn transport_mode(kind: AgentKind) -> AgentTransport {
55    provider_descriptor(kind).transport
56}
57
58/// Returns whether the provider expects prompts through stdin.
59pub(crate) fn prompt_transport(kind: AgentKind) -> AgentPromptTransport {
60    provider_descriptor(kind).prompt_transport
61}
62
63/// Returns whether bootstrap prompts should include schema text for the
64/// selected provider.
65///
66/// Providers that enforce Agentty's response shape natively still receive
67/// policy and field-routing instructions, but skip the large prompt-side JSON
68/// Schema to avoid redundant tokens.
69pub(crate) fn protocol_schema_instruction_mode(kind: AgentKind) -> ProtocolSchemaInstructionMode {
70    provider_descriptor(kind).protocol_schema_instruction_mode
71}
72
73/// Parses one final assistant payload strictly against the shared protocol and
74/// normalizes it for the active request profile.
75///
76/// # Errors
77/// Returns a descriptive error when provider output does not match the
78/// required protocol JSON. The error carries the parse reason and derived
79/// diagnostics only: turn errors are rendered into the session transcript, so
80/// quoting the payload would print raw provider output into the chat.
81pub(crate) fn parse_turn_response(
82    kind: AgentKind,
83    response_text: &str,
84    protocol_profile: ProtocolRequestProfile,
85) -> Result<AgentResponse, String> {
86    parse_protocol_response_strict(response_text, protocol_profile).map_err(|error| {
87        format!(
88            "Agent output did not match the required JSON schema from {kind}: \
89             {error}\nprotocol_profile: {protocol_profile:?}\ndebug_details:\n{}",
90            format_protocol_parse_debug_details(response_text)
91        )
92    })
93}
94
95/// Returns whether one app-server assistant chunk should be treated as
96/// thought text instead of transcript output.
97pub(crate) fn is_app_server_thought_chunk(
98    kind: AgentKind,
99    is_delta: bool,
100    phase: Option<&str>,
101) -> bool {
102    if !is_delta {
103        return false;
104    }
105
106    match provider_descriptor(kind).app_server_thought_policy {
107        AppServerThoughtPolicy::None => false,
108        AppServerThoughtPolicy::PhaseLabel => phase.is_some_and(is_codex_thought_phase_label),
109    }
110}
111
112/// Builds one optional stdin payload for providers that stream prompts instead
113/// of sending them through argv.
114///
115/// # Errors
116/// Returns an error when provider-specific prompt rendering fails.
117pub(crate) fn build_command_stdin_payload(
118    kind: AgentKind,
119    request: BuildCommandRequest<'_>,
120) -> Result<Option<Vec<u8>>, AgentBackendError> {
121    let protocol_schema_instruction_mode = protocol_schema_instruction_mode(kind);
122
123    match prompt_transport(kind) {
124        AgentPromptTransport::Argv => Ok(None),
125        AgentPromptTransport::Stdin => {
126            prompt::build_prompt_stdin_payload(request, protocol_schema_instruction_mode, "Claude")
127                .map(Some)
128        }
129    }
130}
131
132/// One backend/provider descriptor containing construction and parsing hooks.
133struct AgentProviderDescriptor {
134    app_server_client_factory: AppServerClientFactory,
135    app_server_thought_policy: AppServerThoughtPolicy,
136    backend_factory: fn() -> Box<dyn AgentBackend>,
137    parse_response: fn(&str, &str) -> ParsedResponse,
138    parse_stream_output_line: fn(&str) -> Option<(String, bool)>,
139    prompt_transport: AgentPromptTransport,
140    protocol_schema_instruction_mode: ProtocolSchemaInstructionMode,
141    transport: AgentTransport,
142}
143
144fn provider_descriptor(kind: AgentKind) -> AgentProviderDescriptor {
145    match kind {
146        AgentKind::Antigravity => AgentProviderDescriptor {
147            app_server_client_factory: |default_client| {
148                Some(default_client.unwrap_or_else(|| {
149                    Arc::new(super::app_server::RealAntigravityClient::new())
150                        as Arc<dyn AppServerClient>
151                }))
152            },
153            app_server_thought_policy: AppServerThoughtPolicy::None,
154            backend_factory: || Box::new(super::antigravity::AntigravityBackend::new()),
155            parse_response: super::response_parser::parse_antigravity_response_with_fallback,
156            parse_stream_output_line: super::response_parser::parse_antigravity_stream_output_line,
157            prompt_transport: AgentPromptTransport::Argv,
158            protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
159            transport: AgentTransport::AppServer,
160        },
161        AgentKind::Gemini => AgentProviderDescriptor {
162            app_server_client_factory: |default_client| {
163                Some(default_client.unwrap_or_else(|| {
164                    Arc::new(super::app_server::RealGeminiAcpClient::new())
165                        as Arc<dyn AppServerClient>
166                }))
167            },
168            app_server_thought_policy: AppServerThoughtPolicy::None,
169            backend_factory: || Box::new(super::gemini::GeminiBackend),
170            parse_response: super::response_parser::parse_gemini_response_with_fallback,
171            parse_stream_output_line: super::response_parser::parse_gemini_stream_output_line,
172            prompt_transport: AgentPromptTransport::Argv,
173            protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
174            transport: AgentTransport::AppServer,
175        },
176        AgentKind::Claude => AgentProviderDescriptor {
177            app_server_client_factory: |_default_client| None,
178            app_server_thought_policy: AppServerThoughtPolicy::None,
179            backend_factory: || Box::new(super::claude::ClaudeBackend),
180            parse_response: super::response_parser::parse_claude_response_with_fallback,
181            parse_stream_output_line: super::response_parser::parse_claude_stream_output_line,
182            prompt_transport: AgentPromptTransport::Stdin,
183            protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
184            transport: AgentTransport::Cli,
185        },
186        AgentKind::Codex => AgentProviderDescriptor {
187            app_server_client_factory: |default_client| {
188                Some(default_client.unwrap_or_else(|| {
189                    Arc::new(super::app_server::RealCodexAppServerClient::new())
190                        as Arc<dyn AppServerClient>
191                }))
192            },
193            app_server_thought_policy: AppServerThoughtPolicy::PhaseLabel,
194            backend_factory: || Box::new(super::codex::CodexBackend),
195            parse_response: super::response_parser::parse_codex_response_with_fallback,
196            parse_stream_output_line: super::response_parser::parse_codex_stream_output_line,
197            prompt_transport: AgentPromptTransport::Argv,
198            protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
199            transport: AgentTransport::AppServer,
200        },
201    }
202}
203
204/// Returns whether one Codex phase label denotes thought/planning text.
205///
206/// Phase matching is case-insensitive so provider variants such as `Thinking`
207/// and `PLAN` continue to route to thought deltas.
208fn is_codex_thought_phase_label(phase: &str) -> bool {
209    let normalized_phase = phase.trim();
210
211    normalized_phase.eq_ignore_ascii_case("thinking")
212        || normalized_phase.eq_ignore_ascii_case("plan")
213        || normalized_phase.eq_ignore_ascii_case("reasoning")
214        || normalized_phase.eq_ignore_ascii_case("thought")
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    /// Ensures transport capability is provided by infra backend descriptors,
223    /// not domain enums.
224    fn test_transport_mode_reports_expected_transport_by_provider() {
225        // Arrange
226        let antigravity_kind = AgentKind::Antigravity;
227        let claude_kind = AgentKind::Claude;
228        let codex_kind = AgentKind::Codex;
229        let gemini_kind = AgentKind::Gemini;
230
231        // Act
232        let antigravity_transport = transport_mode(antigravity_kind);
233        let claude_transport = transport_mode(claude_kind);
234        let codex_transport = transport_mode(codex_kind);
235        let gemini_transport = transport_mode(gemini_kind);
236
237        // Assert
238        assert_eq!(antigravity_transport, AgentTransport::AppServer);
239        assert_eq!(claude_transport, AgentTransport::Cli);
240        assert_eq!(codex_transport, AgentTransport::AppServer);
241        assert_eq!(gemini_transport, AgentTransport::AppServer);
242    }
243
244    #[test]
245    /// Ensures prompt delivery is also derived from the shared provider
246    /// descriptor.
247    fn test_prompt_transport_reports_expected_mode_by_provider() {
248        // Arrange
249        let antigravity_kind = AgentKind::Antigravity;
250        let claude_kind = AgentKind::Claude;
251        let codex_kind = AgentKind::Codex;
252        let gemini_kind = AgentKind::Gemini;
253
254        // Act
255        let antigravity_transport = prompt_transport(antigravity_kind);
256        let claude_transport = prompt_transport(claude_kind);
257        let codex_transport = prompt_transport(codex_kind);
258        let gemini_transport = prompt_transport(gemini_kind);
259
260        // Assert
261        assert_eq!(antigravity_transport, AgentPromptTransport::Argv);
262        assert_eq!(claude_transport, AgentPromptTransport::Stdin);
263        assert_eq!(codex_transport, AgentPromptTransport::Argv);
264        assert_eq!(gemini_transport, AgentPromptTransport::Argv);
265    }
266
267    #[test]
268    /// Ensures provider schema capabilities are derived from the shared
269    /// descriptor.
270    fn test_protocol_schema_instruction_mode_reports_expected_mode_by_provider() {
271        // Arrange / Act / Assert
272        assert_eq!(
273            protocol_schema_instruction_mode(AgentKind::Antigravity),
274            ProtocolSchemaInstructionMode::TransportSchema
275        );
276        assert_eq!(
277            protocol_schema_instruction_mode(AgentKind::Gemini),
278            ProtocolSchemaInstructionMode::PromptSchema
279        );
280        assert_eq!(
281            protocol_schema_instruction_mode(AgentKind::Claude),
282            ProtocolSchemaInstructionMode::TransportSchema
283        );
284        assert_eq!(
285            protocol_schema_instruction_mode(AgentKind::Codex),
286            ProtocolSchemaInstructionMode::TransportSchema
287        );
288    }
289
290    #[test]
291    /// Ensures providers reject malformed final protocol payloads.
292    fn test_parse_turn_response_rejects_invalid_payload() {
293        // Arrange
294        let raw_response = "plain response";
295
296        for kind in [
297            AgentKind::Antigravity,
298            AgentKind::Claude,
299            AgentKind::Codex,
300            AgentKind::Gemini,
301        ] {
302            // Act
303            let error =
304                parse_turn_response(kind, raw_response, ProtocolRequestProfile::SessionTurn)
305                    .expect_err("plain response should fail strict protocol parsing");
306
307            // Assert
308            assert!(error.contains("debug_details:"));
309            assert!(error.contains("first_non_whitespace_char: 'p'"));
310            assert!(error.contains("direct_json_error_location: line 1, column 1"));
311        }
312    }
313
314    #[test]
315    /// Ensures Codex app-server phase labels map to thought deltas through the
316    /// shared provider descriptor.
317    fn test_is_app_server_thought_chunk_reports_codex_phase_labels() {
318        // Arrange / Act / Assert
319        assert!(is_app_server_thought_chunk(
320            AgentKind::Codex,
321            true,
322            Some("thinking"),
323        ));
324        assert!(!is_app_server_thought_chunk(
325            AgentKind::Gemini,
326            true,
327            Some("thinking"),
328        ));
329    }
330}