use std::sync::Arc;
use ag_protocol::{
AgentResponse, ProtocolRequestProfile, ProtocolSchemaInstructionMode,
format_protocol_parse_debug_details, parse_protocol_response_strict,
};
use ag_session::AgentKind;
use serde_json::Value;
use super::backend::{
AgentBackend, AgentBackendError, AgentPromptTransport, AgentTransport, AppServerThoughtPolicy,
BuildCommandRequest,
};
use super::cli::execution::CliTurnSteering;
use super::cli::stdin::StdinSteering;
use super::prompt;
use super::response_parser::ParsedResponse;
use crate::app_server::{AppServerClient, TurnSteeringInbox};
type AppServerClientFactory =
fn(Option<Arc<dyn AppServerClient>>) -> Option<Arc<dyn AppServerClient>>;
pub fn create_backend(kind: AgentKind) -> Box<dyn AgentBackend> {
(provider_descriptor(kind).backend_factory)()
}
pub fn create_app_server_client(
kind: AgentKind,
default_client: Option<Arc<dyn AppServerClient>>,
) -> Option<Arc<dyn AppServerClient>> {
(provider_descriptor(kind).app_server_client_factory)(default_client)
}
pub(crate) fn parse_response(kind: AgentKind, stdout: &str, stderr: &str) -> ParsedResponse {
(provider_descriptor(kind).parse_response)(stdout, stderr)
}
pub(crate) fn parse_stream_payload(kind: AgentKind, payload: &Value) -> Option<(String, bool)> {
(provider_descriptor(kind).parse_stream_payload)(payload)
}
pub fn transport_mode(kind: AgentKind) -> AgentTransport {
provider_descriptor(kind).transport
}
pub fn supports_turn_steering(kind: AgentKind) -> bool {
provider_descriptor(kind).turn_steering
}
pub(crate) fn prompt_transport(kind: AgentKind) -> AgentPromptTransport {
provider_descriptor(kind).prompt_transport
}
pub(crate) fn protocol_schema_instruction_mode(kind: AgentKind) -> ProtocolSchemaInstructionMode {
provider_descriptor(kind).protocol_schema_instruction_mode
}
pub(crate) fn parse_turn_response(
kind: AgentKind,
response_text: &str,
protocol_profile: ProtocolRequestProfile,
) -> Result<AgentResponse, String> {
parse_protocol_response_strict(response_text, protocol_profile).map_err(|error| {
format!(
"Agent output did not match the required JSON schema from {kind}: \
{error}\nprotocol_profile: {protocol_profile:?}\ndebug_details:\n{}",
format_protocol_parse_debug_details(response_text)
)
})
}
pub(crate) fn is_app_server_thought_chunk(
kind: AgentKind,
is_delta: bool,
phase: Option<&str>,
) -> bool {
if !is_delta {
return false;
}
match provider_descriptor(kind).app_server_thought_policy {
AppServerThoughtPolicy::None => false,
AppServerThoughtPolicy::PhaseLabel => phase.is_some_and(is_codex_thought_phase_label),
}
}
pub(crate) fn build_command_stdin_payload(
kind: AgentKind,
request: BuildCommandRequest<'_>,
) -> Result<Option<Vec<u8>>, AgentBackendError> {
let protocol_schema_instruction_mode = protocol_schema_instruction_mode(kind);
match prompt_transport(kind) {
AgentPromptTransport::Argv => Ok(None),
AgentPromptTransport::StreamJsonStdin => {
prompt::build_cli_prompt_text(request, protocol_schema_instruction_mode, "Claude")
.map(|prompt_text| Some(super::claude::stream_json_user_message(&prompt_text)))
}
}
}
pub(crate) fn cli_turn_steering(
kind: AgentKind,
inbox: Arc<TurnSteeringInbox>,
) -> Option<CliTurnSteering> {
match prompt_transport(kind) {
AgentPromptTransport::Argv => None,
AgentPromptTransport::StreamJsonStdin => Some(CliTurnSteering {
is_turn_end: super::claude::is_turn_result,
stdin: StdinSteering {
encode_prompt: super::claude::encode_steering_prompt,
inbox,
},
}),
}
}
struct AgentProviderDescriptor {
app_server_client_factory: AppServerClientFactory,
app_server_thought_policy: AppServerThoughtPolicy,
backend_factory: fn() -> Box<dyn AgentBackend>,
parse_response: fn(&str, &str) -> ParsedResponse,
parse_stream_payload: fn(&Value) -> Option<(String, bool)>,
prompt_transport: AgentPromptTransport,
protocol_schema_instruction_mode: ProtocolSchemaInstructionMode,
transport: AgentTransport,
turn_steering: bool,
}
fn provider_descriptor(kind: AgentKind) -> AgentProviderDescriptor {
match kind {
AgentKind::Antigravity => AgentProviderDescriptor {
app_server_client_factory: |default_client| {
Some(default_client.unwrap_or_else(|| {
Arc::new(super::app_server::RealAntigravityClient::new())
as Arc<dyn AppServerClient>
}))
},
app_server_thought_policy: AppServerThoughtPolicy::None,
backend_factory: || Box::new(super::antigravity::AntigravityBackend::new()),
parse_response: super::response_parser::parse_antigravity_response_with_fallback,
parse_stream_payload: super::response_parser::parse_antigravity_stream_payload,
prompt_transport: AgentPromptTransport::Argv,
protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
transport: AgentTransport::AppServer,
turn_steering: false,
},
AgentKind::Claude => AgentProviderDescriptor {
app_server_client_factory: |_default_client| None,
app_server_thought_policy: AppServerThoughtPolicy::None,
backend_factory: || Box::new(super::claude::ClaudeBackend),
parse_response: super::response_parser::parse_claude_response_with_fallback,
parse_stream_payload: super::response_parser::parse_claude_stream_payload,
prompt_transport: AgentPromptTransport::StreamJsonStdin,
protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
transport: AgentTransport::Cli,
turn_steering: true,
},
AgentKind::Codex => AgentProviderDescriptor {
app_server_client_factory: |default_client| {
Some(default_client.unwrap_or_else(|| {
Arc::new(super::app_server::RealCodexAppServerClient::new())
as Arc<dyn AppServerClient>
}))
},
app_server_thought_policy: AppServerThoughtPolicy::PhaseLabel,
backend_factory: || Box::new(super::codex::CodexBackend),
parse_response: super::response_parser::parse_codex_response_with_fallback,
parse_stream_payload: super::response_parser::parse_codex_stream_payload,
prompt_transport: AgentPromptTransport::Argv,
protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
transport: AgentTransport::AppServer,
turn_steering: true,
},
AgentKind::Harness => AgentProviderDescriptor {
app_server_client_factory: |_default_client| None,
app_server_thought_policy: AppServerThoughtPolicy::None,
backend_factory: || Box::new(super::harness::HarnessBackend),
parse_response: super::harness::parse_response,
parse_stream_payload: super::harness::parse_stream_payload,
prompt_transport: AgentPromptTransport::Argv,
protocol_schema_instruction_mode: ProtocolSchemaInstructionMode::TransportSchema,
transport: AgentTransport::Native,
turn_steering: false,
},
}
}
fn is_codex_thought_phase_label(phase: &str) -> bool {
let normalized_phase = phase.trim();
normalized_phase.eq_ignore_ascii_case("thinking")
|| normalized_phase.eq_ignore_ascii_case("plan")
|| normalized_phase.eq_ignore_ascii_case("reasoning")
|| normalized_phase.eq_ignore_ascii_case("thought")
}
#[cfg(test)]
#[path = "provider_test.rs"]
mod tests;