Skip to main content

ag_agent/agent/
provider.rs

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