| 1 | use std::path::{Path, PathBuf}; |
| 2 | |
| 3 | use axum::Json; |
| 4 | use axum::extract::{Query, State}; |
| 5 | use serde::Deserialize; |
| 6 | use serde_json::{Value, json}; |
| 7 | |
| 8 | use codewhale_engine::project_context::{ |
| 9 | InstructionBudgets, InstructionSettings, assemble_instruction_block, |
| 10 | capture_instruction_context, estimate_instruction_tokens, |
| 11 | }; |
| 12 | use codewhale_engine::runtime_threads::ThreadRecord; |
| 13 | use codewhale_runtime::config::Config; |
| 14 | use codewhale_skills::{SkillListingConfig, SkillSource}; |
| 15 | |
| 16 | use super::context::{STANDING_MAX_ITEMS, inert_text, standing_display_path}; |
| 17 | use super::{ApiError, RuntimeApiState}; |
| 18 | |
| 19 | #[derive(Deserialize)] |
| 20 | #[serde(deny_unknown_fields)] |
| 21 | pub(super) struct CustomizationsQuery { |
| 22 | workspace: PathBuf, |
| 23 | thread_id: Option<String>, |
| 24 | } |
| 25 | |
| 26 | fn denied() -> ApiError { |
| 27 | ApiError::forbidden("workspace is unknown or outside the selected thread") |
| 28 | .with_code("workspace_mismatch") |
| 29 | } |
| 30 | |
| 31 | pub(super) async fn get( |
| 32 | State(state): State<RuntimeApiState>, |
| 33 | Query(query): Query<CustomizationsQuery>, |
| 34 | ) -> Result<Json<Value>, ApiError> { |
| 35 | #[cfg(any(test, feature = "test-support"))] |
| 36 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 37 | tokio::task::spawn_blocking(move || { |
| 38 | #[cfg(any(test, feature = "test-support"))] |
| 39 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 40 | let same_recorded_root = |recorded: &Path, canonical: &Path| { |
| 41 | use codewhale_util::path_identity::metadata_is_link_or_reparse; |
| 42 | |
| 43 | recorded == canonical |
| 44 | || (recorded.is_absolute() |
| 45 | && std::fs::symlink_metadata(recorded).is_ok_and(|metadata| { |
| 46 | metadata.is_dir() && !metadata_is_link_or_reparse(&metadata) |
| 47 | }) |
| 48 | && recorded.canonicalize().is_ok_and(|path| path == canonical)) |
| 49 | }; |
| 50 | if !query.workspace.is_absolute() { |
| 51 | return Err(denied()); |
| 52 | } |
| 53 | let canonical = query.workspace.canonicalize().map_err(|_| denied())?; |
| 54 | let scope = { |
| 55 | let scopes = state.workspace_scopes.scopes.lock(); |
| 56 | scopes.get(&query.workspace).cloned().or_else(|| { |
| 57 | scopes |
| 58 | .values() |
| 59 | .find(|scope| scope.canonical == canonical) |
| 60 | .cloned() |
| 61 | }) |
| 62 | }; |
| 63 | if let Some(scope) = &scope { |
| 64 | if scope.canonical != canonical { |
| 65 | return Err(denied()); |
| 66 | } |
| 67 | scope.validate_sync().map_err(|_| denied())?; |
| 68 | } |
| 69 | |
| 70 | let thread = query |
| 71 | .thread_id |
| 72 | .as_deref() |
| 73 | .map(|id| state.runtime_threads.read_thread_record(id)) |
| 74 | .transpose() |
| 75 | .map_err(|_| denied())?; |
| 76 | if let Some(thread) = &thread { |
| 77 | if !scope |
| 78 | .as_ref() |
| 79 | .is_some_and(|scope| scope.lexical == thread.workspace) |
| 80 | && !same_recorded_root(&thread.workspace, &canonical) |
| 81 | { |
| 82 | return Err(denied()); |
| 83 | } |
| 84 | } else if scope.is_none() |
| 85 | && !codewhale_runtime::config::is_workspace_trusted(&canonical) |
| 86 | && !state |
| 87 | .runtime_threads |
| 88 | .has_recorded_workspace(|recorded| same_recorded_root(recorded, &canonical)) |
| 89 | .map_err(|_| denied())? |
| 90 | { |
| 91 | return Err(denied()); |
| 92 | } |
| 93 | let (workspace, directory) = |
| 94 | codewhale_util::workspace_dir::open_pinned_workspace_directory(&canonical) |
| 95 | .map_err(|_| denied())?; |
| 96 | if workspace != canonical |
| 97 | || scope.as_ref().is_some_and(|scope| { |
| 98 | !codewhale_util::files::same_file(&scope.directory, &directory).unwrap_or(false) |
| 99 | }) |
| 100 | { |
| 101 | return Err(denied()); |
| 102 | } |
| 103 | |
| 104 | let config = state.config.read().clone(); |
| 105 | let (window, instruction_window, output) = route_budget(&config, thread.as_ref()); |
| 106 | let settings = InstructionSettings::from_config(&config); |
| 107 | let mut homes = settings.home.iter().cloned().collect::<Vec<_>>(); |
| 108 | if let Some(canonical) = homes.first().and_then(|home| home.canonicalize().ok()) |
| 109 | && !homes.contains(&canonical) |
| 110 | { |
| 111 | homes.push(canonical); |
| 112 | } |
| 113 | let rules = measure_rules( |
| 114 | &workspace, |
| 115 | &config, |
| 116 | &settings, |
| 117 | &homes, |
| 118 | instruction_window, |
| 119 | output, |
| 120 | )?; |
| 121 | let plugins = state |
| 122 | .plugin_discovery |
| 123 | .inspect_registry_for_workspace(&workspace); |
| 124 | let skills = measure_skills(&workspace, &config, &plugins, window); |
| 125 | let (agents, agents_complete) = measure_agents(&workspace, &config, &plugins); |
| 126 | let mcp_tools = thread.as_ref().and_then(|thread| { |
| 127 | let mut estimate = state |
| 128 | .runtime_threads |
| 129 | .latest_prepared_mcp_tools(thread, &workspace, &directory)?; |
| 130 | for row in &mut estimate.items { |
| 131 | row.server = inert_text(&row.server); |
| 132 | } |
| 133 | Some(json!({ |
| 134 | "basis": "last_prepared_request", |
| 135 | "turn_id": thread.latest_turn_id, |
| 136 | "step": estimate.step, |
| 137 | "tokens": estimate.tokens, |
| 138 | "items": estimate.items, |
| 139 | })) |
| 140 | }); |
| 141 | let mut not_measured = Vec::new(); |
| 142 | if mcp_tools.is_none() { |
| 143 | not_measured.push("mcp_tools"); |
| 144 | } |
| 145 | if !agents_complete { |
| 146 | not_measured.push("agents"); |
| 147 | } |
| 148 | |
| 149 | let (reopened, current) = |
| 150 | codewhale_util::workspace_dir::open_workspace_directory(&query.workspace) |
| 151 | .map_err(|_| denied())?; |
| 152 | if reopened != workspace |
| 153 | || !codewhale_util::files::same_file(&directory, ¤t).map_err(|_| denied())? |
| 154 | { |
| 155 | return Err(denied()); |
| 156 | } |
| 157 | if let Some(scope) = &scope { |
| 158 | scope.validate_sync().map_err(|_| denied())?; |
| 159 | } |
| 160 | Ok(Json(json!({ |
| 161 | "schema_version": 1, |
| 162 | "workspace": workspace, |
| 163 | "estimated": true, |
| 164 | "estimator": "conservative_ascii_div3_non_ascii_scalar", |
| 165 | "rules": rules, |
| 166 | "skills": skills, |
| 167 | "agents": agents, |
| 168 | "mcp_tools": mcp_tools, |
| 169 | "not_measured": not_measured, |
| 170 | }))) |
| 171 | }) |
| 172 | .await |
| 173 | .map_err(|_| ApiError::internal("workspace customizations inspection failed"))? |
| 174 | } |
| 175 | |
| 176 | fn route_budget( |
| 177 | config: &Config, |
| 178 | thread: Option<&ThreadRecord>, |
| 179 | ) -> (Option<u32>, Option<usize>, Option<usize>) { |
| 180 | let explicit_route = thread.filter(|thread| { |
| 181 | thread.model_provider_id.is_some() |
| 182 | || thread |
| 183 | .model_provider |
| 184 | .as_deref() |
| 185 | .is_some_and(|kind| !kind.trim().is_empty()) |
| 186 | }); |
| 187 | let identity = if let Some(thread) = explicit_route { |
| 188 | config.resolve_persisted_provider_identity( |
| 189 | thread.model_provider.as_deref(), |
| 190 | thread.model_provider_id.as_deref(), |
| 191 | ) |
| 192 | } else { |
| 193 | config.active_provider_identity() |
| 194 | }; |
| 195 | let route = identity.ok().and_then(|identity| { |
| 196 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 197 | config, |
| 198 | &identity, |
| 199 | thread |
| 200 | .map(|thread| thread.model.as_str()) |
| 201 | .filter(|model| !model.trim().eq_ignore_ascii_case("auto")), |
| 202 | ) |
| 203 | .ok() |
| 204 | }); |
| 205 | let Some(route) = route else { |
| 206 | return (None, None, None); |
| 207 | }; |
| 208 | let limits = codewhale_engine::route_budget::known_route_limits(route.candidate.limits()); |
| 209 | let output = codewhale_engine::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 210 | route.identity.provider, |
| 211 | &route.model, |
| 212 | limits, |
| 213 | Some(route.context_window.tokens), |
| 214 | None, |
| 215 | thread |
| 216 | .and_then(|thread| thread.reasoning_effort.as_deref()) |
| 217 | .or_else(|| route.config.reasoning_effort()), |
| 218 | ); |
| 219 | ( |
| 220 | Some(route.context_window.tokens), |
| 221 | route.context_window.instruction_budget_tokens(), |
| 222 | Some(output as usize), |
| 223 | ) |
| 224 | } |
| 225 | |
| 226 | fn measure_rules( |
| 227 | workspace: &Path, |
| 228 | config: &Config, |
| 229 | settings: &InstructionSettings, |
| 230 | homes: &[PathBuf], |
| 231 | window: Option<usize>, |
| 232 | output: Option<usize>, |
| 233 | ) -> Result<Value, ApiError> { |
| 234 | let configured = config |
| 235 | .instructions_paths() |
| 236 | .into_iter() |
| 237 | .map(Into::into) |
| 238 | .collect::<Vec<_>>(); |
| 239 | let budgets = InstructionBudgets::resolve(Some(&settings.budget), window, output) |
| 240 | .map_err(ApiError::internal)?; |
| 241 | let mut context = capture_instruction_context(workspace, &configured, settings); |
| 242 | let assembly = assemble_instruction_block(&mut context, &[], &budgets); |
| 243 | let roots = [workspace.to_path_buf()]; |
| 244 | let items = assembly |
| 245 | .notices |
| 246 | .iter() |
| 247 | .take(STANDING_MAX_ITEMS) |
| 248 | .map(|notice| { |
| 249 | let scope = notice.scope.as_str(); |
| 250 | let path = notice.path.as_deref().map_or_else( |
| 251 | || notice.origin.as_str().to_string(), |
| 252 | |path| standing_display_path(path, scope == "global", &roots, homes), |
| 253 | ); |
| 254 | json!({ |
| 255 | "path": path, |
| 256 | "scope": scope, |
| 257 | "tokens": notice.tokens_kept, |
| 258 | "action": notice.action.as_str(), |
| 259 | }) |
| 260 | }) |
| 261 | .collect::<Vec<_>>(); |
| 262 | Ok(json!({ |
| 263 | "tokens": assembly.global_tokens.saturating_add(assembly.project_tokens), |
| 264 | "budget_tokens": budgets.global_tokens.saturating_add(budgets.project_tokens), |
| 265 | "refused": budgets.first_refused_loss(&assembly.notices).is_some(), |
| 266 | "items_omitted": assembly.notices.len().saturating_sub(items.len()), |
| 267 | "items": items, |
| 268 | })) |
| 269 | } |
| 270 | |
| 271 | fn measure_skills( |
| 272 | workspace: &Path, |
| 273 | config: &Config, |
| 274 | plugins: &codewhale_plugins::PluginRegistry, |
| 275 | window_tokens: Option<u32>, |
| 276 | ) -> Value { |
| 277 | let skills_dir = config.skills_dir(); |
| 278 | let skills_config = config.skills_config(); |
| 279 | let registry = codewhale_skills::discover_for_workspace( |
| 280 | workspace, |
| 281 | Some(&skills_dir), |
| 282 | &skills_config, |
| 283 | Some(plugins), |
| 284 | ) |
| 285 | .into_enabled(); |
| 286 | let settings = codewhale_runtime::settings::Settings::load_read_only().unwrap_or_default(); |
| 287 | let locale = codewhale_localization::resolve_locale(&settings.locale).tag(); |
| 288 | let listing = SkillListingConfig::from_config(&skills_config); |
| 289 | let always = codewhale_skills::render_always_loaded_skills( |
| 290 | ®istry, |
| 291 | &skills_config.always_load_names(), |
| 292 | &skills_config.bundled, |
| 293 | ); |
| 294 | let measurement = codewhale_skills::measure_available_skills_index( |
| 295 | ®istry, |
| 296 | locale, |
| 297 | workspace, |
| 298 | Some(&skills_dir), |
| 299 | listing, |
| 300 | listing.budget_chars(window_tokens), |
| 301 | &always.loaded_names, |
| 302 | ); |
| 303 | let owned_skills = codewhale_runtime::config::owned_skills_dir(); |
| 304 | let project_root = |
| 305 | (!codewhale_util::files::workspace_is_user_home(workspace)).then_some(workspace); |
| 306 | let items = measurement |
| 307 | .items |
| 308 | .iter() |
| 309 | .take(STANDING_MAX_ITEMS) |
| 310 | .filter_map(|item| { |
| 311 | let skill = registry.get(item.name)?; |
| 312 | let (scope, plugin) = match &skill.source { |
| 313 | SkillSource::Plugin { plugin_id, .. } => ("plugin", Some(inert_text(plugin_id))), |
| 314 | SkillSource::Native |
| 315 | if owned_skills.as_deref().is_some_and(|dir| { |
| 316 | codewhale_skills::is_bundled_copy(&skill.path, &skill.name, dir) |
| 317 | }) => |
| 318 | { |
| 319 | ("built_in", None) |
| 320 | } |
| 321 | SkillSource::Native |
| 322 | if project_root.is_some_and(|root| skill.path.starts_with(root)) => |
| 323 | { |
| 324 | ("project", None) |
| 325 | } |
| 326 | SkillSource::Native => ("global", None), |
| 327 | }; |
| 328 | Some(json!({ |
| 329 | "name": inert_text(item.name), |
| 330 | "scope": scope, |
| 331 | "plugin": plugin, |
| 332 | "description": bounded_description(skill.description_for_locale(locale)), |
| 333 | "tokens": item.tokens, |
| 334 | "state": item.state, |
| 335 | })) |
| 336 | }) |
| 337 | .collect::<Vec<_>>(); |
| 338 | json!({ |
| 339 | "tokens": measurement.tokens, |
| 340 | "budget_tokens": measurement.budget_tokens, |
| 341 | "estimator": "characters_div4", |
| 342 | "excluded": measurement.excluded, |
| 343 | "shortened": measurement.shortened, |
| 344 | "names_only": measurement.names_only, |
| 345 | "items_omitted": measurement.items.len().saturating_sub(items.len()), |
| 346 | "items": items, |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | fn measure_agents( |
| 351 | workspace: &Path, |
| 352 | config: &Config, |
| 353 | plugins: &codewhale_plugins::PluginRegistry, |
| 354 | ) -> (Option<Value>, bool) { |
| 355 | let roster = codewhale_engine::fleet::identity::load_effective_roster( |
| 356 | &config.fleet_config(), |
| 357 | workspace, |
| 358 | Some(plugins), |
| 359 | ); |
| 360 | if roster.load_error().is_some() { |
| 361 | return (None, false); |
| 362 | } |
| 363 | let mut complete = roster.profile_load_issues().is_empty(); |
| 364 | let mut total = 0; |
| 365 | let mut measured = 0_usize; |
| 366 | let mut items = Vec::new(); |
| 367 | for member in roster.members() { |
| 368 | if member.native_preset.is_some() { |
| 369 | complete = false; |
| 370 | continue; |
| 371 | } |
| 372 | measured += 1; |
| 373 | let tokens = member |
| 374 | .profile |
| 375 | .role |
| 376 | .instructions |
| 377 | .as_deref() |
| 378 | .map_or(0, estimate_instruction_tokens); |
| 379 | total += tokens; |
| 380 | if items.len() < STANDING_MAX_ITEMS { |
| 381 | items.push(json!({ |
| 382 | "name": inert_text(&member.id), |
| 383 | "scope": member.origin.to_string(), |
| 384 | "description": bounded_description( |
| 385 | member.description.as_deref() |
| 386 | .or(member.profile.role.description.as_deref()) |
| 387 | .unwrap_or_default() |
| 388 | ), |
| 389 | "tokens": tokens, |
| 390 | })); |
| 391 | } |
| 392 | } |
| 393 | ( |
| 394 | Some(json!({ |
| 395 | "tokens": total, |
| 396 | "items_omitted": measured.saturating_sub(items.len()), |
| 397 | "items": items, |
| 398 | })), |
| 399 | complete, |
| 400 | ) |
| 401 | } |
| 402 | |
| 403 | fn bounded_description(description: &str) -> String { |
| 404 | inert_text(&description.chars().take(512).collect::<String>()) |
| 405 | } |
| 406 | |
| 407 | #[cfg(test)] |
| 408 | mod tests { |
| 409 | use super::*; |
| 410 | use codewhale_engine::project_context::{InstructionBudgetConfig, InstructionBudgetPolicy}; |
| 411 | |
| 412 | #[test] |
| 413 | fn workspace_customizations_refuse_policy_reports_measured_rule_loss() -> anyhow::Result<()> { |
| 414 | let workspace = tempfile::tempdir()?; |
| 415 | std::fs::write( |
| 416 | workspace.path().join("AGENTS.md"), |
| 417 | "instruction ".repeat(500), |
| 418 | )?; |
| 419 | let config = Config::default(); |
| 420 | let mut settings = InstructionSettings { |
| 421 | budget: InstructionBudgetConfig { |
| 422 | project_budget_tokens: Some(20), |
| 423 | policy: Some(InstructionBudgetPolicy::Refuse), |
| 424 | ..Default::default() |
| 425 | }, |
| 426 | home: None, |
| 427 | ..Default::default() |
| 428 | }; |
| 429 | let measure = |settings: &InstructionSettings| { |
| 430 | measure_rules(workspace.path(), &config, settings, &[], None, None) |
| 431 | .expect("rule measurement") |
| 432 | }; |
| 433 | |
| 434 | assert_eq!(measure(&settings)["refused"], true); |
| 435 | settings.budget.policy = Some(InstructionBudgetPolicy::Trim); |
| 436 | assert_eq!(measure(&settings)["refused"], false); |
| 437 | settings.budget.policy = Some(InstructionBudgetPolicy::Refuse); |
| 438 | settings.budget.project_budget_tokens = None; |
| 439 | assert_eq!(measure(&settings)["refused"], false); |
| 440 | Ok(()) |
| 441 | } |
| 442 | } |
| 443 |