| 1 | use super::*; |
| 2 | use anyhow::bail; |
| 3 | |
| 4 | pub(crate) fn captured(state: &AppState) -> Result<Arc<dyn RuntimeOwnerFrontend>> { |
| 5 | state |
| 6 | .owner_frontend |
| 7 | .clone() |
| 8 | .context("the captured Runtime native services are unavailable; refusing another owner") |
| 9 | } |
| 10 | |
| 11 | pub(crate) async fn execute( |
| 12 | owner: &Arc<dyn RuntimeOwnerFrontend>, |
| 13 | request: RuntimeOwnerRequest, |
| 14 | ) -> Result<Value> { |
| 15 | tokio::time::timeout(Duration::from_secs(30), owner.execute(request)) |
| 16 | .await |
| 17 | .context("native owner deadline expired; outcome may be committed, no automatic replay")? |
| 18 | } |
| 19 | |
| 20 | pub(crate) async fn runtime_catalog_models( |
| 21 | owner: &Arc<dyn RuntimeOwnerFrontend>, |
| 22 | provider: &str, |
| 23 | provider_id: Option<&str>, |
| 24 | ) -> Result<Vec<Value>> { |
| 25 | let mut models = Vec::new(); |
| 26 | let mut cursor = None; |
| 27 | let mut cursors = std::collections::HashSet::new(); |
| 28 | let mut ids = std::collections::HashSet::new(); |
| 29 | let mut total = None; |
| 30 | for _ in 0..40 { |
| 31 | let catalog = execute( |
| 32 | owner, |
| 33 | RuntimeOwnerRequest::ProviderModels { |
| 34 | provider: provider.to_owned(), |
| 35 | provider_id: provider_id.map(str::to_owned), |
| 36 | cursor: cursor.clone(), |
| 37 | }, |
| 38 | ) |
| 39 | .await?; |
| 40 | anyhow::ensure!( |
| 41 | catalog.get("provider").and_then(Value::as_str) == Some(provider) |
| 42 | && catalog.get("model_provider_id").unwrap_or(&Value::Null) == &json!(provider_id), |
| 43 | "Runtime model catalog changed provider identity" |
| 44 | ); |
| 45 | let count = catalog |
| 46 | .get("total") |
| 47 | .and_then(Value::as_u64) |
| 48 | .context("Runtime model catalog omitted its total")?; |
| 49 | anyhow::ensure!( |
| 50 | count <= 10_000 && total.is_none_or(|total| total == count), |
| 51 | "Runtime model catalog size changed or exceeds its limit" |
| 52 | ); |
| 53 | total = Some(count); |
| 54 | let entries = catalog |
| 55 | .get("models") |
| 56 | .and_then(Value::as_array) |
| 57 | .context("Runtime model catalog omitted its models")?; |
| 58 | anyhow::ensure!( |
| 59 | entries.len() <= 250, |
| 60 | "Runtime model catalog page exceeds its limit" |
| 61 | ); |
| 62 | for entry in entries { |
| 63 | let id = entry |
| 64 | .get("id") |
| 65 | .and_then(Value::as_str) |
| 66 | .filter(|id| !id.is_empty()) |
| 67 | .context("Runtime model catalog contains an invalid model")?; |
| 68 | anyhow::ensure!( |
| 69 | ids.insert(id.to_string()), |
| 70 | "Runtime model catalog repeated a model" |
| 71 | ); |
| 72 | models.push(entry.clone()); |
| 73 | } |
| 74 | anyhow::ensure!( |
| 75 | models.len() as u64 <= count, |
| 76 | "Runtime model catalog exceeds its total" |
| 77 | ); |
| 78 | match catalog.get("nextCursor") { |
| 79 | None | Some(Value::Null) => { |
| 80 | anyhow::ensure!( |
| 81 | models.len() as u64 == count, |
| 82 | "Runtime model catalog is incomplete" |
| 83 | ); |
| 84 | return Ok(models); |
| 85 | } |
| 86 | Some(Value::String(next)) if !next.is_empty() && next.len() <= 1_368 => { |
| 87 | anyhow::ensure!( |
| 88 | !entries.is_empty() && models.len() < count as usize, |
| 89 | "Runtime model catalog continuation is invalid" |
| 90 | ); |
| 91 | anyhow::ensure!( |
| 92 | cursors.insert(next.clone()), |
| 93 | "Runtime model catalog cursor repeated" |
| 94 | ); |
| 95 | cursor = Some(next.clone()); |
| 96 | } |
| 97 | _ => bail!("Runtime model catalog cursor is invalid"), |
| 98 | } |
| 99 | } |
| 100 | bail!("Runtime model catalog exceeded its page limit") |
| 101 | } |
| 102 | |
| 103 | pub(crate) async fn runtime_app_models(state: &AppState) -> Result<Vec<Value>> { |
| 104 | let owner = captured(state)?; |
| 105 | let providers = execute(&owner, RuntimeOwnerRequest::Providers).await?; |
| 106 | let providers = providers |
| 107 | .get("providers") |
| 108 | .and_then(Value::as_array) |
| 109 | .context("Runtime provider catalog is invalid")?; |
| 110 | anyhow::ensure!( |
| 111 | providers.len() <= 256, |
| 112 | "Runtime provider catalog exceeds its limit" |
| 113 | ); |
| 114 | let mut models = Vec::new(); |
| 115 | let mut routes = std::collections::HashSet::new(); |
| 116 | for provider in providers { |
| 117 | if !provider |
| 118 | .get("has_model_catalog") |
| 119 | .and_then(Value::as_bool) |
| 120 | .context("Runtime provider omitted its catalog availability")? |
| 121 | { |
| 122 | continue; |
| 123 | } |
| 124 | let kind = provider |
| 125 | .get("id") |
| 126 | .and_then(Value::as_str) |
| 127 | .context("Runtime provider omitted its identity")?; |
| 128 | let parsed: codewhale_config::ProviderKind = |
| 129 | serde_json::from_value(json!(kind)).context("Runtime provider kind is unsupported")?; |
| 130 | anyhow::ensure!( |
| 131 | kind == parsed.as_str() |
| 132 | || codewhale_config::descriptors::compatibility_for_id(kind) |
| 133 | .is_some_and(|compatibility| compatibility.kind == parsed), |
| 134 | "Runtime provider kind is not a recognized wire identity" |
| 135 | ); |
| 136 | let provider_id = match provider.get("model_provider_id") { |
| 137 | None | Some(Value::Null) => None, |
| 138 | Some(Value::String(id)) if !id.is_empty() => Some(id.as_str()), |
| 139 | _ => bail!("Runtime configured provider identity is invalid"), |
| 140 | }; |
| 141 | if !routes.insert((kind.to_string(), provider_id.map(str::to_string))) { |
| 142 | continue; |
| 143 | } |
| 144 | for mut model in runtime_catalog_models(&owner, kind, provider_id).await? { |
| 145 | let id = model |
| 146 | .get("id") |
| 147 | .and_then(Value::as_str) |
| 148 | .context("Runtime model identity is invalid")?; |
| 149 | let compatibility_aliases = if parsed != codewhale_config::ProviderKind::Custom |
| 150 | && provider_id.is_none_or(|identity| identity == kind) |
| 151 | { |
| 152 | codewhale_config::route::aliases_for_wire_model(parsed, id) |
| 153 | } else { |
| 154 | Vec::new() |
| 155 | }; |
| 156 | let capabilities: codewhale_config::route::RouteCapabilities = |
| 157 | match model.pointer("/facts/capabilities") { |
| 158 | None | Some(Value::Null) => Default::default(), |
| 159 | Some(value) => serde_json::from_value(value.clone()) |
| 160 | .context("Runtime model capabilities are invalid")?, |
| 161 | }; |
| 162 | let row = model |
| 163 | .as_object_mut() |
| 164 | .context("Runtime model entry is invalid")?; |
| 165 | row.insert("provider".into(), serde_json::to_value(parsed)?); |
| 166 | row.insert("model_provider_id".into(), json!(provider_id)); |
| 167 | row.insert("aliases".into(), json!(compatibility_aliases)); |
| 168 | row.insert( |
| 169 | "supports_tools".into(), |
| 170 | json!( |
| 171 | capabilities.native_tool_calls |
| 172 | == codewhale_config::route::CapabilityState::Supported |
| 173 | ), |
| 174 | ); |
| 175 | row.insert( |
| 176 | "supports_reasoning".into(), |
| 177 | json!( |
| 178 | capabilities.reasoning == codewhale_config::route::CapabilityState::Supported |
| 179 | ), |
| 180 | ); |
| 181 | row.insert("capabilities".into(), serde_json::to_value(capabilities)?); |
| 182 | models.push(model); |
| 183 | anyhow::ensure!( |
| 184 | models.len() <= 100_000, |
| 185 | "Runtime model catalog exceeds the response limit" |
| 186 | ); |
| 187 | } |
| 188 | } |
| 189 | Ok(models) |
| 190 | } |
| 191 | |
| 192 | pub(crate) async fn require_output_limited_model( |
| 193 | owner: &Arc<dyn RuntimeOwnerFrontend>, |
| 194 | requested_model: Option<&str>, |
| 195 | ) -> Result<()> { |
| 196 | let providers = execute(owner, RuntimeOwnerRequest::Providers).await?; |
| 197 | let current = providers |
| 198 | .get("current") |
| 199 | .and_then(Value::as_str) |
| 200 | .context("Runtime provider is unavailable")?; |
| 201 | let current_id = match providers.get("current_provider_id") { |
| 202 | None | Some(Value::Null) => None, |
| 203 | Some(Value::String(id)) if !id.is_empty() => Some(id.as_str()), |
| 204 | _ => bail!("Runtime configured provider identity is invalid"), |
| 205 | }; |
| 206 | let provider = providers |
| 207 | .get("providers") |
| 208 | .and_then(Value::as_array) |
| 209 | .and_then(|providers| { |
| 210 | providers.iter().find(|provider| { |
| 211 | provider.get("id").and_then(Value::as_str) == Some(current) |
| 212 | && provider.get("model_provider_id").and_then(Value::as_str) == current_id |
| 213 | }) |
| 214 | }) |
| 215 | .context("Runtime provider is unavailable")?; |
| 216 | let model = requested_model |
| 217 | .or_else(|| provider.get("default_model").and_then(Value::as_str)) |
| 218 | .context("maxOutputTokens requires an exact model")?; |
| 219 | if model.trim().is_empty() || model.eq_ignore_ascii_case("auto") { |
| 220 | bail!("maxOutputTokens requires an exact model"); |
| 221 | } |
| 222 | if !current |
| 223 | .bytes() |
| 224 | .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') |
| 225 | { |
| 226 | bail!("Runtime provider identity is invalid"); |
| 227 | } |
| 228 | let catalog = runtime_catalog_models(owner, current, current_id).await?; |
| 229 | let entry = catalog |
| 230 | .iter() |
| 231 | .find(|entry| entry.get("id").and_then(Value::as_str) == Some(model)) |
| 232 | .context("Output-limit support is unknown for the selected Runtime model")?; |
| 233 | anyhow::ensure!( |
| 234 | entry.get("output_token_limit").and_then(Value::as_str) == Some("supported"), |
| 235 | "The selected Runtime model does not support maxOutputTokens" |
| 236 | ); |
| 237 | Ok(()) |
| 238 | } |
| 239 |