| 1 | use std::collections::{BTreeSet, HashSet}; |
| 2 | |
| 3 | use serde_json::{Map, Value}; |
| 4 | |
| 5 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 6 | pub struct ParsedDialects { |
| 7 | pub default_profile: String, |
| 8 | pub custom_allowed: Vec<String>, |
| 9 | pub profiles: Vec<ParsedProfile>, |
| 10 | pub bindings: Vec<ParsedBinding>, |
| 11 | } |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 14 | pub struct ParsedProfile { |
| 15 | pub id: String, |
| 16 | pub endpoint_path: String, |
| 17 | pub protocol_headers: String, |
| 18 | pub store: String, |
| 19 | pub include: String, |
| 20 | pub instructions: String, |
| 21 | pub max_output_tokens: String, |
| 22 | pub sampling: String, |
| 23 | pub effort_mapping: String, |
| 24 | pub shape: String, |
| 25 | pub summary: String, |
| 26 | pub encrypted_state: String, |
| 27 | pub plain_reasoning: String, |
| 28 | pub system_role: String, |
| 29 | pub envelope: String, |
| 30 | pub namespace: Option<String>, |
| 31 | pub parallel_calls: String, |
| 32 | pub malformed_json: String, |
| 33 | pub unknown_event: String, |
| 34 | pub done_marker: String, |
| 35 | pub completion: String, |
| 36 | pub incomplete: String, |
| 37 | pub cache_fields: String, |
| 38 | pub reasoning_fields: String, |
| 39 | pub audio_fields: String, |
| 40 | pub function_tools: String, |
| 41 | pub server_side_tools: String, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct ParsedBinding { |
| 46 | pub provider_kind: String, |
| 47 | pub endpoint_key: Option<String>, |
| 48 | pub urls: Option<Vec<String>>, |
| 49 | pub profile: String, |
| 50 | } |
| 51 | |
| 52 | const FORBIDDEN_KEYS: &[&str] = &[ |
| 53 | "authorization", |
| 54 | "api_key", |
| 55 | "api-key", |
| 56 | "token", |
| 57 | "access_token", |
| 58 | "account_id", |
| 59 | "account-id", |
| 60 | "secret", |
| 61 | "password", |
| 62 | "credential", |
| 63 | "bearer", |
| 64 | ]; |
| 65 | |
| 66 | pub fn parse(raw: &str) -> Result<ParsedDialects, String> { |
| 67 | let value: Value = serde_json::from_str(raw).map_err(|err| format!("invalid JSON: {err}"))?; |
| 68 | reject_secrets(&value, "responses dialects")?; |
| 69 | let root = as_object(&value, "responses dialects")?; |
| 70 | keys_exact( |
| 71 | root, |
| 72 | "responses dialects", |
| 73 | &[ |
| 74 | "schema_version", |
| 75 | "default_profile", |
| 76 | "custom_allowed_profiles", |
| 77 | "profiles", |
| 78 | "bindings", |
| 79 | ], |
| 80 | )?; |
| 81 | let version = root |
| 82 | .get("schema_version") |
| 83 | .and_then(Value::as_u64) |
| 84 | .ok_or("schema_version must be 1")?; |
| 85 | if version != 1 { |
| 86 | return Err(format!("unsupported responses dialect schema {version}")); |
| 87 | } |
| 88 | let profiles = root |
| 89 | .get("profiles") |
| 90 | .and_then(Value::as_array) |
| 91 | .ok_or("profiles must be an array")?; |
| 92 | if profiles.is_empty() { |
| 93 | return Err("profiles must not be empty".to_string()); |
| 94 | } |
| 95 | let mut parsed_profiles = Vec::with_capacity(profiles.len()); |
| 96 | let mut ids = BTreeSet::new(); |
| 97 | for (index, profile) in profiles.iter().enumerate() { |
| 98 | let profile = parse_profile(profile, index)?; |
| 99 | if !ids.insert(profile.id.clone()) { |
| 100 | return Err(format!("duplicate profile id `{}`", profile.id)); |
| 101 | } |
| 102 | parsed_profiles.push(profile); |
| 103 | } |
| 104 | let default_profile = req_str(root, "responses dialects", "default_profile")?; |
| 105 | if !valid_id(default_profile) { |
| 106 | return Err(format!("invalid default profile id `{default_profile}`")); |
| 107 | } |
| 108 | let default_profile = default_profile.to_string(); |
| 109 | let Some(default) = parsed_profiles |
| 110 | .iter() |
| 111 | .find(|profile| profile.id == default_profile) |
| 112 | else { |
| 113 | return Err(format!( |
| 114 | "default profile `{default_profile}` does not exist" |
| 115 | )); |
| 116 | }; |
| 117 | if default.endpoint_path != "versioned_responses" |
| 118 | || default.encrypted_state == "account_api_model_scoped" |
| 119 | { |
| 120 | return Err("default profile must be an ordinary versioned responses dialect".to_string()); |
| 121 | } |
| 122 | let allowed_values = root |
| 123 | .get("custom_allowed_profiles") |
| 124 | .and_then(Value::as_array) |
| 125 | .ok_or("custom_allowed_profiles must be an array")?; |
| 126 | if allowed_values.is_empty() { |
| 127 | return Err("custom_allowed_profiles must not be empty".to_string()); |
| 128 | } |
| 129 | let mut custom_allowed = Vec::with_capacity(allowed_values.len()); |
| 130 | let mut seen_allowed = BTreeSet::new(); |
| 131 | for value in allowed_values { |
| 132 | let id = value |
| 133 | .as_str() |
| 134 | .filter(|id| valid_id(id)) |
| 135 | .ok_or("custom_allowed_profiles entries must be profile ids")?; |
| 136 | if !seen_allowed.insert(id.to_string()) { |
| 137 | return Err(format!("duplicate custom allowed profile `{id}`")); |
| 138 | } |
| 139 | let Some(profile) = parsed_profiles.iter().find(|profile| profile.id == id) else { |
| 140 | return Err(format!("custom allowed profile `{id}` does not exist")); |
| 141 | }; |
| 142 | if !custom_safe(profile) { |
| 143 | return Err(format!( |
| 144 | "profile `{id}` cannot be selected by a custom provider" |
| 145 | )); |
| 146 | } |
| 147 | custom_allowed.push(id.to_string()); |
| 148 | } |
| 149 | if !custom_allowed.iter().any(|id| id == &default_profile) { |
| 150 | return Err("default profile must be allowed for custom providers".to_string()); |
| 151 | } |
| 152 | let bindings = root |
| 153 | .get("bindings") |
| 154 | .and_then(Value::as_array) |
| 155 | .ok_or("bindings must be an array")?; |
| 156 | if bindings.is_empty() { |
| 157 | return Err("bindings must not be empty".to_string()); |
| 158 | } |
| 159 | let mut parsed_bindings = Vec::with_capacity(bindings.len()); |
| 160 | for (index, binding) in bindings.iter().enumerate() { |
| 161 | parsed_bindings.push(parse_binding(binding, index, &parsed_profiles)?); |
| 162 | } |
| 163 | for left in 0..parsed_bindings.len() { |
| 164 | for right in (left + 1)..parsed_bindings.len() { |
| 165 | if !binding_pair_ok(&parsed_bindings[left], &parsed_bindings[right]) { |
| 166 | return Err(format!( |
| 167 | "responses profile bindings overlap for {}", |
| 168 | parsed_bindings[left].provider_kind |
| 169 | )); |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | for profile in &parsed_profiles { |
| 174 | if profile.endpoint_path != "unversioned_responses" { |
| 175 | continue; |
| 176 | } |
| 177 | if custom_allowed.iter().any(|id| id == &profile.id) || profile.id == default_profile { |
| 178 | return Err(format!( |
| 179 | "unversioned profile `{}` cannot be a default or custom profile", |
| 180 | profile.id |
| 181 | )); |
| 182 | } |
| 183 | let bound = parsed_bindings.iter().any(|binding| { |
| 184 | binding.profile == profile.id |
| 185 | && binding.urls.as_ref().is_some_and(|urls| !urls.is_empty()) |
| 186 | }); |
| 187 | if !bound { |
| 188 | return Err(format!( |
| 189 | "unversioned profile `{}` requires an exact base url binding", |
| 190 | profile.id |
| 191 | )); |
| 192 | } |
| 193 | } |
| 194 | Ok(ParsedDialects { |
| 195 | default_profile, |
| 196 | custom_allowed, |
| 197 | profiles: parsed_profiles, |
| 198 | bindings: parsed_bindings, |
| 199 | }) |
| 200 | } |
| 201 | |
| 202 | pub fn codegen(doc: &ParsedDialects) -> String { |
| 203 | let mut out = String::from("// Generated from responses_dialects.json. Do not edit.\n"); |
| 204 | out.push_str("const BUILTIN_PROFILES: &[ResponsesDialectProfile] = &[\n"); |
| 205 | for profile in &doc.profiles { |
| 206 | out.push_str(&emit_profile(profile)); |
| 207 | out.push_str(",\n"); |
| 208 | } |
| 209 | out.push_str("];\nconst BUILTIN_BINDINGS: &[ResponsesProfileBinding] = &[\n"); |
| 210 | for binding in &doc.bindings { |
| 211 | out.push_str(&emit_binding(binding)); |
| 212 | out.push_str(",\n"); |
| 213 | } |
| 214 | out.push_str( |
| 215 | "];\nconst DEFAULT_PROFILE_ID: ResponsesProfileId = ResponsesProfileId::from_static(", |
| 216 | ); |
| 217 | out.push_str(&format!("{:?}", doc.default_profile)); |
| 218 | out.push_str(");\nconst CUSTOM_ALLOWED_PROFILES: &[ResponsesProfileId] = &[\n"); |
| 219 | for id in &doc.custom_allowed { |
| 220 | out.push_str(" ResponsesProfileId::from_static("); |
| 221 | out.push_str(&format!("{id:?}")); |
| 222 | out.push_str("),\n"); |
| 223 | } |
| 224 | out.push_str("];\n"); |
| 225 | out |
| 226 | } |
| 227 | |
| 228 | fn emit_profile(profile: &ParsedProfile) -> String { |
| 229 | let namespace = match &profile.namespace { |
| 230 | Some(namespace) => format!("Some({namespace:?})"), |
| 231 | None => "None".to_string(), |
| 232 | }; |
| 233 | format!( |
| 234 | "ResponsesDialectProfile {{ |
| 235 | id: ResponsesProfileId::from_static({id:?}), |
| 236 | endpoint: ResponsesEndpointPolicy {{ path: {path} }}, |
| 237 | headers: ResponsesHeaderPolicy {{ protocol_headers: {headers} }}, |
| 238 | request: ResponsesRequestPolicy {{ |
| 239 | store: {store}, |
| 240 | include: {include}, |
| 241 | instructions: {instructions}, |
| 242 | max_output_tokens: {max_output_tokens}, |
| 243 | sampling: {sampling}, |
| 244 | }}, |
| 245 | reasoning: ResponsesReasoningPolicy {{ |
| 246 | effort_mapping: {effort}, |
| 247 | shape: {shape}, |
| 248 | summary: {summary}, |
| 249 | }}, |
| 250 | replay: ResponsesReplayPolicy {{ |
| 251 | encrypted_state: {encrypted}, |
| 252 | plain_reasoning: {plain}, |
| 253 | system_role: {system_role}, |
| 254 | }}, |
| 255 | tools: ResponsesToolPolicy {{ |
| 256 | envelope: {envelope}, |
| 257 | namespace: {namespace}, |
| 258 | parallel_calls: {parallel}, |
| 259 | }}, |
| 260 | stream: ResponsesStreamPolicy {{ |
| 261 | malformed_json: {malformed}, |
| 262 | unknown_event: {unknown_event}, |
| 263 | done_marker: {done_marker}, |
| 264 | completion: {completion}, |
| 265 | incomplete: {incomplete}, |
| 266 | }}, |
| 267 | usage: ResponsesUsagePolicy {{ |
| 268 | cache_fields: {cache_fields}, |
| 269 | reasoning_fields: {reasoning_fields}, |
| 270 | audio_fields: {audio_fields}, |
| 271 | }}, |
| 272 | capabilities: ResponsesCapabilityPolicy {{ |
| 273 | function_tools: {function_tools}, |
| 274 | server_side_tools: {server_side_tools}, |
| 275 | }}, |
| 276 | }}", |
| 277 | id = profile.id, |
| 278 | path = variant("path", &profile.endpoint_path), |
| 279 | headers = variant("headers", &profile.protocol_headers), |
| 280 | store = variant("store", &profile.store), |
| 281 | include = variant("include", &profile.include), |
| 282 | instructions = variant("instructions", &profile.instructions), |
| 283 | max_output_tokens = variant("max_output_tokens", &profile.max_output_tokens), |
| 284 | sampling = variant("sampling", &profile.sampling), |
| 285 | effort = variant("effort", &profile.effort_mapping), |
| 286 | shape = variant("shape", &profile.shape), |
| 287 | summary = variant("summary", &profile.summary), |
| 288 | encrypted = variant("encrypted", &profile.encrypted_state), |
| 289 | plain = variant("plain", &profile.plain_reasoning), |
| 290 | system_role = variant("system_role", &profile.system_role), |
| 291 | envelope = variant("envelope", &profile.envelope), |
| 292 | parallel = variant("parallel", &profile.parallel_calls), |
| 293 | malformed = variant("malformed", &profile.malformed_json), |
| 294 | unknown_event = variant("unknown_event", &profile.unknown_event), |
| 295 | done_marker = variant("done_marker", &profile.done_marker), |
| 296 | completion = variant("completion", &profile.completion), |
| 297 | incomplete = variant("incomplete", &profile.incomplete), |
| 298 | cache_fields = variant("cache_fields", &profile.cache_fields), |
| 299 | reasoning_fields = variant("reasoning_fields", &profile.reasoning_fields), |
| 300 | audio_fields = variant("audio_fields", &profile.audio_fields), |
| 301 | function_tools = variant("function_tools", &profile.function_tools), |
| 302 | server_side_tools = variant("server_side_tools", &profile.server_side_tools), |
| 303 | ) |
| 304 | } |
| 305 | |
| 306 | fn emit_binding(binding: &ParsedBinding) -> String { |
| 307 | let endpoint = match &binding.endpoint_key { |
| 308 | Some(endpoint) => format!("Some({endpoint:?})"), |
| 309 | None => "None".to_string(), |
| 310 | }; |
| 311 | let urls = match &binding.urls { |
| 312 | Some(urls) => format!( |
| 313 | "Some(&[{}])", |
| 314 | urls.iter() |
| 315 | .map(|url| format!("{url:?}")) |
| 316 | .collect::<Vec<_>>() |
| 317 | .join(", ") |
| 318 | ), |
| 319 | None => "None".to_string(), |
| 320 | }; |
| 321 | format!( |
| 322 | "ResponsesProfileBinding {{ |
| 323 | provider_kind: crate::ProviderKind::{kind}, |
| 324 | endpoint_key: {endpoint}, |
| 325 | base_urls: {urls}, |
| 326 | profile_id: ResponsesProfileId::from_static({profile:?}), |
| 327 | }}", |
| 328 | kind = binding.provider_kind, |
| 329 | profile = binding.profile, |
| 330 | ) |
| 331 | } |
| 332 | |
| 333 | fn variant(group: &str, value: &str) -> &'static str { |
| 334 | match (group, value) { |
| 335 | ("path", "versioned_responses") => "ResponsesPathPolicy::VersionedResponses", |
| 336 | ("path", "unversioned_responses") => "ResponsesPathPolicy::UnversionedResponses", |
| 337 | ("headers", "standard_json") => "ProtocolHeaderPolicy::StandardJson", |
| 338 | ("store", "explicit_false") => "StorePolicy::ExplicitFalse", |
| 339 | ("store", "omit") => "StorePolicy::Omit", |
| 340 | ("include", "encrypted_reasoning") => "IncludePolicy::EncryptedReasoning", |
| 341 | ("include", "omit") => "IncludePolicy::Omit", |
| 342 | ("instructions", "top_level") => "InstructionsPlacement::TopLevel", |
| 343 | ("instructions", "leading_system_input") => "InstructionsPlacement::LeadingSystemInput", |
| 344 | ("max_output_tokens", "when_positive") => "OutputTokenFieldPolicy::WhenPositive", |
| 345 | ("max_output_tokens", "omit") => "OutputTokenFieldPolicy::Omit", |
| 346 | ("sampling", "temperature_and_top_p") => "SamplingPolicy::TemperatureAndTopP", |
| 347 | ("sampling", "omit") => "SamplingPolicy::Omit", |
| 348 | ("effort", "openai_compatible") => "ReasoningEffortMapping::OpenaiCompatible", |
| 349 | ("effort", "codex") => "ReasoningEffortMapping::Codex", |
| 350 | ("effort", "deepseek") => "ReasoningEffortMapping::Deepseek", |
| 351 | ("shape", "effort_with_summary") => "ReasoningRequestShape::EffortWithSummary", |
| 352 | ("shape", "effort_only") => "ReasoningRequestShape::EffortOnly", |
| 353 | ("summary", "auto") => "ReasoningSummaryPolicy::Auto", |
| 354 | ("summary", "omit") => "ReasoningSummaryPolicy::Omit", |
| 355 | ("encrypted", "provider_api_model_scoped") => { |
| 356 | "EncryptedReasoningReplayPolicy::ProviderApiModelScoped" |
| 357 | } |
| 358 | ("encrypted", "account_api_model_scoped") => { |
| 359 | "EncryptedReasoningReplayPolicy::AccountApiModelScoped" |
| 360 | } |
| 361 | ("encrypted", "disabled") => "EncryptedReasoningReplayPolicy::Disabled", |
| 362 | ("plain", "ignore") => "PlainReasoningReplayPolicy::Ignore", |
| 363 | ("plain", "plain_text") => "PlainReasoningReplayPolicy::PlainText", |
| 364 | ("plain", "plain_text_with_tool_placeholder") => { |
| 365 | "PlainReasoningReplayPolicy::PlainTextWithToolPlaceholder" |
| 366 | } |
| 367 | ("system_role", "preserve") => "SystemRoleReplayPolicy::Preserve", |
| 368 | ("system_role", "system_to_developer") => "SystemRoleReplayPolicy::SystemToDeveloper", |
| 369 | ("envelope", "function_array") => "ToolEnvelopePolicy::FunctionArray", |
| 370 | ("envelope", "namespace_wrapped") => "ToolEnvelopePolicy::NamespaceWrapped", |
| 371 | ("parallel", "allow") => "ParallelToolCallPolicy::Allow", |
| 372 | ("parallel", "disallow") => "ParallelToolCallPolicy::Disallow", |
| 373 | ("malformed", "fail") => "MalformedEventPolicy::Fail", |
| 374 | ("malformed", "skip_with_diagnostic") => "MalformedEventPolicy::SkipWithDiagnostic", |
| 375 | ("unknown_event", "ignore") => "UnknownEventPolicy::Ignore", |
| 376 | ("unknown_event", "fail") => "UnknownEventPolicy::Fail", |
| 377 | ("done_marker", "terminal") => "DoneMarkerPolicy::Terminal", |
| 378 | ("done_marker", "ignore") => "DoneMarkerPolicy::Ignore", |
| 379 | ("completion", "accept_documented_terminal_events") => { |
| 380 | "CompletionPolicy::AcceptDocumentedTerminalEvents" |
| 381 | } |
| 382 | ("completion", "require_successful_response_completed") => { |
| 383 | "CompletionPolicy::RequireSuccessfulResponseCompleted" |
| 384 | } |
| 385 | ("incomplete", "preserve_provider_incomplete_result") => { |
| 386 | "IncompleteResponsePolicy::PreserveProviderIncompleteResult" |
| 387 | } |
| 388 | ("incomplete", "fail") => "IncompleteResponsePolicy::Fail", |
| 389 | ("cache_fields", "top_level_then_nested_fallback") => { |
| 390 | "CacheUsageFieldPolicy::TopLevelThenNestedFallback" |
| 391 | } |
| 392 | ("reasoning_fields", "output_tokens_details") => { |
| 393 | "ReasoningUsageFieldPolicy::OutputTokensDetails" |
| 394 | } |
| 395 | ("audio_fields", "nested_details") => "AudioUsageFieldPolicy::NestedDetails", |
| 396 | ("function_tools", "supported") => "FunctionToolCapability::Supported", |
| 397 | ("function_tools", "unsupported") => "FunctionToolCapability::Unsupported", |
| 398 | ("server_side_tools", "route_and_adapter_gated") => { |
| 399 | "ServerSideToolCapability::RouteAndAdapterGated" |
| 400 | } |
| 401 | ("server_side_tools", "unsupported") => "ServerSideToolCapability::Unsupported", |
| 402 | _ => unreachable!("validator accepted an unknown responses dialect value"), |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | fn parse_profile(value: &Value, index: usize) -> Result<ParsedProfile, String> { |
| 407 | let at = format!("profiles[{index}]"); |
| 408 | let map = as_object(value, &at)?; |
| 409 | keys_exact( |
| 410 | map, |
| 411 | &at, |
| 412 | &[ |
| 413 | "id", |
| 414 | "endpoint", |
| 415 | "headers", |
| 416 | "request", |
| 417 | "reasoning", |
| 418 | "replay", |
| 419 | "tools", |
| 420 | "stream", |
| 421 | "usage", |
| 422 | "capabilities", |
| 423 | ], |
| 424 | )?; |
| 425 | let id = req_str(map, &at, "id")?; |
| 426 | if !valid_id(id) { |
| 427 | return Err(format!("{at} has invalid id `{id}`")); |
| 428 | } |
| 429 | let endpoint = nested(map, &at, "endpoint", &["path"])?; |
| 430 | let headers = nested(map, &at, "headers", &["protocol_headers"])?; |
| 431 | let request = nested( |
| 432 | map, |
| 433 | &at, |
| 434 | "request", |
| 435 | &[ |
| 436 | "store", |
| 437 | "include", |
| 438 | "instructions", |
| 439 | "max_output_tokens", |
| 440 | "sampling", |
| 441 | ], |
| 442 | )?; |
| 443 | let reasoning = nested( |
| 444 | map, |
| 445 | &at, |
| 446 | "reasoning", |
| 447 | &["effort_mapping", "shape", "summary"], |
| 448 | )?; |
| 449 | let replay = nested( |
| 450 | map, |
| 451 | &at, |
| 452 | "replay", |
| 453 | &["encrypted_state", "plain_reasoning", "system_role"], |
| 454 | )?; |
| 455 | let tools = nested( |
| 456 | map, |
| 457 | &at, |
| 458 | "tools", |
| 459 | &["envelope", "namespace", "parallel_calls"], |
| 460 | )?; |
| 461 | let stream = nested( |
| 462 | map, |
| 463 | &at, |
| 464 | "stream", |
| 465 | &[ |
| 466 | "malformed_json", |
| 467 | "unknown_event", |
| 468 | "done_marker", |
| 469 | "completion", |
| 470 | "incomplete", |
| 471 | ], |
| 472 | )?; |
| 473 | let usage = nested( |
| 474 | map, |
| 475 | &at, |
| 476 | "usage", |
| 477 | &["cache_fields", "reasoning_fields", "audio_fields"], |
| 478 | )?; |
| 479 | let capabilities = nested( |
| 480 | map, |
| 481 | &at, |
| 482 | "capabilities", |
| 483 | &["function_tools", "server_side_tools"], |
| 484 | )?; |
| 485 | let endpoint_path = enum_str( |
| 486 | &endpoint, |
| 487 | &format!("{at}.endpoint"), |
| 488 | "path", |
| 489 | &["versioned_responses", "unversioned_responses"], |
| 490 | )?; |
| 491 | let shape = enum_str( |
| 492 | &reasoning, |
| 493 | &format!("{at}.reasoning"), |
| 494 | "shape", |
| 495 | &["effort_with_summary", "effort_only"], |
| 496 | )?; |
| 497 | let summary = enum_str( |
| 498 | &reasoning, |
| 499 | &format!("{at}.reasoning"), |
| 500 | "summary", |
| 501 | &["auto", "omit"], |
| 502 | )?; |
| 503 | match (shape, summary) { |
| 504 | ("effort_with_summary", "auto") | ("effort_only", "omit") => {} |
| 505 | _ => { |
| 506 | return Err(format!( |
| 507 | "{at} reasoning shape `{shape}` does not match summary `{summary}`" |
| 508 | )); |
| 509 | } |
| 510 | } |
| 511 | let envelope = enum_str( |
| 512 | &tools, |
| 513 | &format!("{at}.tools"), |
| 514 | "envelope", |
| 515 | &["function_array", "namespace_wrapped"], |
| 516 | )?; |
| 517 | let namespace = optional_namespace(&tools, &format!("{at}.tools"))?; |
| 518 | match (envelope, namespace.as_deref()) { |
| 519 | ("namespace_wrapped", Some(namespace)) if valid_id(namespace) => {} |
| 520 | ("function_array", None) => {} |
| 521 | _ => { |
| 522 | return Err(format!( |
| 523 | "{at} tool namespace does not match envelope `{envelope}`" |
| 524 | )); |
| 525 | } |
| 526 | } |
| 527 | let encrypted_state = enum_str( |
| 528 | &replay, |
| 529 | &format!("{at}.replay"), |
| 530 | "encrypted_state", |
| 531 | &[ |
| 532 | "provider_api_model_scoped", |
| 533 | "account_api_model_scoped", |
| 534 | "disabled", |
| 535 | ], |
| 536 | )?; |
| 537 | Ok(ParsedProfile { |
| 538 | id: id.to_string(), |
| 539 | endpoint_path: endpoint_path.to_string(), |
| 540 | protocol_headers: enum_str( |
| 541 | &headers, |
| 542 | &format!("{at}.headers"), |
| 543 | "protocol_headers", |
| 544 | &["standard_json"], |
| 545 | )? |
| 546 | .to_string(), |
| 547 | store: enum_str( |
| 548 | &request, |
| 549 | &format!("{at}.request"), |
| 550 | "store", |
| 551 | &["explicit_false", "omit"], |
| 552 | )? |
| 553 | .to_string(), |
| 554 | include: enum_str( |
| 555 | &request, |
| 556 | &format!("{at}.request"), |
| 557 | "include", |
| 558 | &["encrypted_reasoning", "omit"], |
| 559 | )? |
| 560 | .to_string(), |
| 561 | instructions: enum_str( |
| 562 | &request, |
| 563 | &format!("{at}.request"), |
| 564 | "instructions", |
| 565 | &["top_level", "leading_system_input"], |
| 566 | )? |
| 567 | .to_string(), |
| 568 | max_output_tokens: enum_str( |
| 569 | &request, |
| 570 | &format!("{at}.request"), |
| 571 | "max_output_tokens", |
| 572 | &["when_positive", "omit"], |
| 573 | )? |
| 574 | .to_string(), |
| 575 | sampling: enum_str( |
| 576 | &request, |
| 577 | &format!("{at}.request"), |
| 578 | "sampling", |
| 579 | &["temperature_and_top_p", "omit"], |
| 580 | )? |
| 581 | .to_string(), |
| 582 | effort_mapping: enum_str( |
| 583 | &reasoning, |
| 584 | &format!("{at}.reasoning"), |
| 585 | "effort_mapping", |
| 586 | &["openai_compatible", "codex", "deepseek"], |
| 587 | )? |
| 588 | .to_string(), |
| 589 | shape: shape.to_string(), |
| 590 | summary: summary.to_string(), |
| 591 | encrypted_state: encrypted_state.to_string(), |
| 592 | plain_reasoning: enum_str( |
| 593 | &replay, |
| 594 | &format!("{at}.replay"), |
| 595 | "plain_reasoning", |
| 596 | &["ignore", "plain_text", "plain_text_with_tool_placeholder"], |
| 597 | )? |
| 598 | .to_string(), |
| 599 | system_role: enum_str( |
| 600 | &replay, |
| 601 | &format!("{at}.replay"), |
| 602 | "system_role", |
| 603 | &["preserve", "system_to_developer"], |
| 604 | )? |
| 605 | .to_string(), |
| 606 | envelope: envelope.to_string(), |
| 607 | namespace, |
| 608 | parallel_calls: enum_str( |
| 609 | &tools, |
| 610 | &format!("{at}.tools"), |
| 611 | "parallel_calls", |
| 612 | &["allow", "disallow"], |
| 613 | )? |
| 614 | .to_string(), |
| 615 | malformed_json: enum_str( |
| 616 | &stream, |
| 617 | &format!("{at}.stream"), |
| 618 | "malformed_json", |
| 619 | &["fail", "skip_with_diagnostic"], |
| 620 | )? |
| 621 | .to_string(), |
| 622 | unknown_event: enum_str( |
| 623 | &stream, |
| 624 | &format!("{at}.stream"), |
| 625 | "unknown_event", |
| 626 | &["ignore", "fail"], |
| 627 | )? |
| 628 | .to_string(), |
| 629 | done_marker: enum_str( |
| 630 | &stream, |
| 631 | &format!("{at}.stream"), |
| 632 | "done_marker", |
| 633 | &["terminal", "ignore"], |
| 634 | )? |
| 635 | .to_string(), |
| 636 | completion: enum_str( |
| 637 | &stream, |
| 638 | &format!("{at}.stream"), |
| 639 | "completion", |
| 640 | &[ |
| 641 | "accept_documented_terminal_events", |
| 642 | "require_successful_response_completed", |
| 643 | ], |
| 644 | )? |
| 645 | .to_string(), |
| 646 | incomplete: enum_str( |
| 647 | &stream, |
| 648 | &format!("{at}.stream"), |
| 649 | "incomplete", |
| 650 | &["preserve_provider_incomplete_result", "fail"], |
| 651 | )? |
| 652 | .to_string(), |
| 653 | cache_fields: enum_str( |
| 654 | &usage, |
| 655 | &format!("{at}.usage"), |
| 656 | "cache_fields", |
| 657 | &["top_level_then_nested_fallback"], |
| 658 | )? |
| 659 | .to_string(), |
| 660 | reasoning_fields: enum_str( |
| 661 | &usage, |
| 662 | &format!("{at}.usage"), |
| 663 | "reasoning_fields", |
| 664 | &["output_tokens_details"], |
| 665 | )? |
| 666 | .to_string(), |
| 667 | audio_fields: enum_str( |
| 668 | &usage, |
| 669 | &format!("{at}.usage"), |
| 670 | "audio_fields", |
| 671 | &["nested_details"], |
| 672 | )? |
| 673 | .to_string(), |
| 674 | function_tools: enum_str( |
| 675 | &capabilities, |
| 676 | &format!("{at}.capabilities"), |
| 677 | "function_tools", |
| 678 | &["supported", "unsupported"], |
| 679 | )? |
| 680 | .to_string(), |
| 681 | server_side_tools: enum_str( |
| 682 | &capabilities, |
| 683 | &format!("{at}.capabilities"), |
| 684 | "server_side_tools", |
| 685 | &["route_and_adapter_gated", "unsupported"], |
| 686 | )? |
| 687 | .to_string(), |
| 688 | }) |
| 689 | } |
| 690 | |
| 691 | fn parse_binding( |
| 692 | value: &Value, |
| 693 | index: usize, |
| 694 | profiles: &[ParsedProfile], |
| 695 | ) -> Result<ParsedBinding, String> { |
| 696 | let at = format!("bindings[{index}]"); |
| 697 | let map = as_object(value, &at)?; |
| 698 | keys_exact( |
| 699 | map, |
| 700 | &at, |
| 701 | &[ |
| 702 | "provider_kind", |
| 703 | "protocol", |
| 704 | "endpoint_key", |
| 705 | "base_url_match", |
| 706 | "profile", |
| 707 | ], |
| 708 | )?; |
| 709 | let provider_kind = req_str(map, &at, "provider_kind")?; |
| 710 | if !provider_kind.chars().all(|ch| ch.is_ascii_alphanumeric()) { |
| 711 | return Err(format!("{at} has invalid provider kind `{provider_kind}`")); |
| 712 | } |
| 713 | let protocol = req_str(map, &at, "protocol")?; |
| 714 | if protocol != "responses" { |
| 715 | return Err(format!("{at} protocol must be responses")); |
| 716 | } |
| 717 | let endpoint_key = match map.get("endpoint_key") { |
| 718 | None => None, |
| 719 | Some(Value::String(endpoint)) if valid_id(endpoint.as_str()) => Some(endpoint.clone()), |
| 720 | _ => return Err(format!("{at}.endpoint_key must be a profile-style id")), |
| 721 | }; |
| 722 | let profile = req_str(map, &at, "profile")?; |
| 723 | if !profiles.iter().any(|item| item.id == profile) { |
| 724 | return Err(format!("{at} references unknown profile `{profile}`")); |
| 725 | } |
| 726 | let urls = parse_url_match(map.get("base_url_match").unwrap_or(&Value::Null), &at)?; |
| 727 | Ok(ParsedBinding { |
| 728 | provider_kind: provider_kind.to_string(), |
| 729 | endpoint_key, |
| 730 | urls, |
| 731 | profile: profile.to_string(), |
| 732 | }) |
| 733 | } |
| 734 | |
| 735 | fn parse_url_match(value: &Value, at: &str) -> Result<Option<Vec<String>>, String> { |
| 736 | let at = format!("{at}.base_url_match"); |
| 737 | let map = as_object(value, &at)?; |
| 738 | let kind = req_str(map, &at, "type")?; |
| 739 | match kind { |
| 740 | "any" => { |
| 741 | keys_exact(map, &at, &["type"])?; |
| 742 | Ok(None) |
| 743 | } |
| 744 | "exact_normalized" => { |
| 745 | keys_exact(map, &at, &["type", "urls"])?; |
| 746 | let urls = map |
| 747 | .get("urls") |
| 748 | .and_then(Value::as_array) |
| 749 | .ok_or_else(|| format!("{at}.urls must be an array"))?; |
| 750 | if urls.is_empty() { |
| 751 | return Err(format!("{at}.urls must not be empty")); |
| 752 | } |
| 753 | let mut parsed = Vec::with_capacity(urls.len()); |
| 754 | let mut seen = HashSet::new(); |
| 755 | for url in urls { |
| 756 | let url = url |
| 757 | .as_str() |
| 758 | .ok_or_else(|| format!("{at}.urls entries must be strings"))?; |
| 759 | if url.is_empty() |
| 760 | || url |
| 761 | .chars() |
| 762 | .any(|ch| ch.is_whitespace() || matches!(ch, '?' | '#' | '@')) |
| 763 | || !url.starts_with("https://") |
| 764 | || url != url.trim_end_matches('/').to_ascii_lowercase() |
| 765 | { |
| 766 | return Err(format!( |
| 767 | "{at} url `{url}` is not an exact normalized https url" |
| 768 | )); |
| 769 | } |
| 770 | if !seen.insert(url.to_string()) { |
| 771 | return Err(format!("{at} repeats url `{url}`")); |
| 772 | } |
| 773 | parsed.push(url.to_string()); |
| 774 | } |
| 775 | Ok(Some(parsed)) |
| 776 | } |
| 777 | _ => Err(format!("{at} has unknown match `{kind}`")), |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | fn custom_safe(profile: &ParsedProfile) -> bool { |
| 782 | profile.encrypted_state != "account_api_model_scoped" |
| 783 | && profile.endpoint_path != "unversioned_responses" |
| 784 | && profile.envelope != "namespace_wrapped" |
| 785 | } |
| 786 | |
| 787 | fn binding_pair_ok(left: &ParsedBinding, right: &ParsedBinding) -> bool { |
| 788 | if !bindings_overlap(left, right) { |
| 789 | return true; |
| 790 | } |
| 791 | strictly_more_specific(left, right) || strictly_more_specific(right, left) |
| 792 | } |
| 793 | |
| 794 | fn bindings_overlap(left: &ParsedBinding, right: &ParsedBinding) -> bool { |
| 795 | if left.provider_kind != right.provider_kind { |
| 796 | return false; |
| 797 | } |
| 798 | if let (Some(left_endpoint), Some(right_endpoint)) = (&left.endpoint_key, &right.endpoint_key) |
| 799 | && left_endpoint != right_endpoint |
| 800 | { |
| 801 | return false; |
| 802 | } |
| 803 | match (&left.urls, &right.urls) { |
| 804 | (Some(left_urls), Some(right_urls)) => left_urls.iter().any(|url| right_urls.contains(url)), |
| 805 | _ => true, |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | fn strictly_more_specific(specific: &ParsedBinding, general: &ParsedBinding) -> bool { |
| 810 | specificity(specific) > specificity(general) && constraints_fit(specific, general) |
| 811 | } |
| 812 | |
| 813 | fn specificity(binding: &ParsedBinding) -> u8 { |
| 814 | u8::from(binding.endpoint_key.is_some()) + u8::from(binding.urls.is_some()) |
| 815 | } |
| 816 | |
| 817 | fn constraints_fit(specific: &ParsedBinding, general: &ParsedBinding) -> bool { |
| 818 | if let Some(endpoint) = &general.endpoint_key |
| 819 | && specific.endpoint_key.as_ref() != Some(endpoint) |
| 820 | { |
| 821 | return false; |
| 822 | } |
| 823 | if let Some(general_urls) = &general.urls { |
| 824 | let Some(specific_urls) = &specific.urls else { |
| 825 | return false; |
| 826 | }; |
| 827 | if specific_urls.iter().any(|url| !general_urls.contains(url)) { |
| 828 | return false; |
| 829 | } |
| 830 | } |
| 831 | true |
| 832 | } |
| 833 | |
| 834 | fn nested( |
| 835 | map: &Map<String, Value>, |
| 836 | at: &str, |
| 837 | key: &str, |
| 838 | fields: &[&str], |
| 839 | ) -> Result<Map<String, Value>, String> { |
| 840 | let value = map |
| 841 | .get(key) |
| 842 | .ok_or_else(|| format!("{at} is missing `{key}`"))?; |
| 843 | let child = as_object(value, &format!("{at}.{key}"))?; |
| 844 | keys_exact(child, &format!("{at}.{key}"), fields)?; |
| 845 | Ok(child.clone()) |
| 846 | } |
| 847 | |
| 848 | fn optional_namespace(map: &Map<String, Value>, at: &str) -> Result<Option<String>, String> { |
| 849 | match map.get("namespace") { |
| 850 | None => Err(format!("{at} is missing `namespace`")), |
| 851 | Some(Value::Null) => Ok(None), |
| 852 | Some(Value::String(namespace)) if !namespace.is_empty() => Ok(Some(namespace.clone())), |
| 853 | _ => Err(format!("{at}.namespace must be a string or null")), |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | fn enum_str<'a>( |
| 858 | map: &'a Map<String, Value>, |
| 859 | at: &str, |
| 860 | key: &str, |
| 861 | allowed: &[&str], |
| 862 | ) -> Result<&'a str, String> { |
| 863 | let value = req_str(map, at, key)?; |
| 864 | if allowed.contains(&value) { |
| 865 | Ok(value) |
| 866 | } else { |
| 867 | Err(format!("{at}.{key} has unknown value `{value}`")) |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | fn req_str<'a>(map: &'a Map<String, Value>, at: &str, key: &str) -> Result<&'a str, String> { |
| 872 | match map.get(key) { |
| 873 | Some(Value::String(value)) if !value.is_empty() => Ok(value), |
| 874 | Some(_) => Err(format!("{at}.{key} must be a non-empty string")), |
| 875 | None => Err(format!("{at} is missing `{key}`")), |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | fn as_object<'a>(value: &'a Value, at: &str) -> Result<&'a Map<String, Value>, String> { |
| 880 | value |
| 881 | .as_object() |
| 882 | .ok_or_else(|| format!("{at} must be an object")) |
| 883 | } |
| 884 | |
| 885 | fn keys_exact(map: &Map<String, Value>, at: &str, allowed: &[&str]) -> Result<(), String> { |
| 886 | for key in map.keys() { |
| 887 | if !allowed.contains(&key.as_str()) { |
| 888 | return Err(format!("{at} has unknown field `{key}`")); |
| 889 | } |
| 890 | } |
| 891 | Ok(()) |
| 892 | } |
| 893 | |
| 894 | fn valid_id(value: &str) -> bool { |
| 895 | let mut chars = value.chars(); |
| 896 | match chars.next() { |
| 897 | Some(first) if first.is_ascii_lowercase() => {} |
| 898 | _ => return false, |
| 899 | } |
| 900 | chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_') |
| 901 | } |
| 902 | |
| 903 | fn reject_secrets(value: &Value, at: &str) -> Result<(), String> { |
| 904 | match value { |
| 905 | Value::Object(map) => { |
| 906 | for (key, child) in map { |
| 907 | if FORBIDDEN_KEYS |
| 908 | .iter() |
| 909 | .any(|forbidden| key.eq_ignore_ascii_case(forbidden)) |
| 910 | { |
| 911 | return Err(format!("{at}.{key} is not allowed in a responses profile")); |
| 912 | } |
| 913 | reject_secrets(child, &format!("{at}.{key}"))?; |
| 914 | } |
| 915 | Ok(()) |
| 916 | } |
| 917 | Value::Array(items) => { |
| 918 | for (index, child) in items.iter().enumerate() { |
| 919 | reject_secrets(child, &format!("{at}[{index}]"))?; |
| 920 | } |
| 921 | Ok(()) |
| 922 | } |
| 923 | Value::String(text) => { |
| 924 | let lower = text.to_ascii_lowercase(); |
| 925 | if lower.contains("bearer ") || lower.starts_with("sk-") { |
| 926 | Err(format!("{at} contains a credential-like value")) |
| 927 | } else { |
| 928 | Ok(()) |
| 929 | } |
| 930 | } |
| 931 | _ => Ok(()), |
| 932 | } |
| 933 | } |
| 934 |