1use 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
21type AppServerClientFactory =
24 fn(Option<Arc<dyn AppServerClient>>) -> Option<Arc<dyn AppServerClient>>;
25
26pub fn create_backend(kind: AgentKind) -> Box<dyn AgentBackend> {
28 (provider_descriptor(kind).backend_factory)()
29}
30
31pub 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
39pub(crate) fn parse_response(kind: AgentKind, stdout: &str, stderr: &str) -> ParsedResponse {
41 (provider_descriptor(kind).parse_response)(stdout, stderr)
42}
43
44pub(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
55pub fn transport_mode(kind: AgentKind) -> AgentTransport {
57 provider_descriptor(kind).transport
58}
59
60pub(crate) fn prompt_transport(kind: AgentKind) -> AgentPromptTransport {
62 provider_descriptor(kind).prompt_transport
63}
64
65pub(crate) fn protocol_schema_instruction_mode(kind: AgentKind) -> ProtocolSchemaInstructionMode {
72 provider_descriptor(kind).protocol_schema_instruction_mode
73}
74
75pub(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
99pub(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
116pub(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
136struct 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
208fn 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 fn test_transport_mode_reports_expected_transport_by_provider() {
229 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 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_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 fn test_prompt_transport_reports_expected_mode_by_provider() {
252 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 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_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 fn test_protocol_schema_instruction_mode_reports_expected_mode_by_provider() {
275 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 fn test_parse_turn_response_rejects_invalid_payload() {
297 let raw_response = "plain response";
299
300 for kind in [
301 AgentKind::Antigravity,
302 AgentKind::Claude,
303 AgentKind::Codex,
304 AgentKind::Gemini,
305 ] {
306 let error =
308 parse_turn_response(kind, raw_response, ProtocolRequestProfile::SessionTurn)
309 .expect_err("plain response should fail strict protocol parsing");
310
311 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 fn test_parse_turn_response_fills_missing_summary_for_session_turn() {
322 let raw_response = r#"{"answer":"done","questions":[],"summary":null}"#;
324
325 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_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 fn test_is_app_server_thought_chunk_reports_codex_phase_labels() {
348 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}