| 1 | use axum::Json; |
| 2 | use axum::extract::{Path, State}; |
| 3 | use serde::Serialize; |
| 4 | |
| 5 | use super::{ApiError, RuntimeApiState, map_thread_err}; |
| 6 | |
| 7 | /// Live context-window posture for one thread — the facts a usage |
| 8 | /// panel cannot reconstruct from turn receipts. `input_tokens` is the same |
| 9 | /// conservative estimate the in-app context meter shows; `billed_input_tokens` |
| 10 | /// is the last provider-counted prompt size when one exists. |
| 11 | /// |
| 12 | /// All numeric fields are nullable: a route that cannot express a bounded |
| 13 | /// window reports `null`. Static windows retain their resolution source, |
| 14 | /// including a named unverified fallback. `live: false` marks responses where |
| 15 | /// the engine could not be loaded and only the stored route resolved. |
| 16 | #[derive(Debug, Serialize)] |
| 17 | pub(super) struct ThreadContextResponse { |
| 18 | thread_id: String, |
| 19 | model: String, |
| 20 | provider: Option<String>, |
| 21 | model_provider_id: Option<String>, |
| 22 | /// `true` when the numbers came from the loaded engine (live estimate + |
| 23 | /// route limits); `false` when only the store-recorded route resolved. |
| 24 | live: bool, |
| 25 | window_tokens: Option<u64>, |
| 26 | window_source: Option<&'static str>, |
| 27 | input_tokens: Option<u64>, |
| 28 | billed_input_tokens: Option<u64>, |
| 29 | output_cap_tokens: Option<u64>, |
| 30 | input_budget_ceiling: Option<u64>, |
| 31 | available_input_tokens: Option<u64>, |
| 32 | compaction_trigger_tokens: Option<u64>, |
| 33 | usage_percent: Option<f64>, |
| 34 | pressure: Option<&'static str>, |
| 35 | } |
| 36 | |
| 37 | pub(super) async fn get_thread_context( |
| 38 | State(state): State<RuntimeApiState>, |
| 39 | Path(thread_id): Path<String>, |
| 40 | ) -> Result<Json<ThreadContextResponse>, ApiError> { |
| 41 | let thread = state |
| 42 | .runtime_threads |
| 43 | .get_thread(&thread_id) |
| 44 | .await |
| 45 | .map_err(map_thread_err)?; |
| 46 | |
| 47 | if let Ok(engine) = state.runtime_threads.get_engine(&thread_id).await |
| 48 | && let Ok(Some(snapshot)) = engine.get_context_budget().await |
| 49 | { |
| 50 | return Ok(Json(ThreadContextResponse { |
| 51 | thread_id, |
| 52 | model: snapshot.model, |
| 53 | provider: Some(snapshot.provider), |
| 54 | model_provider_id: snapshot.model_provider_id, |
| 55 | live: true, |
| 56 | window_tokens: Some(snapshot.window_tokens), |
| 57 | window_source: Some("engine_active_route"), |
| 58 | input_tokens: Some(snapshot.input_tokens), |
| 59 | billed_input_tokens: snapshot.billed_input_tokens, |
| 60 | output_cap_tokens: Some(snapshot.output_cap_tokens), |
| 61 | input_budget_ceiling: Some(snapshot.input_budget_ceiling), |
| 62 | available_input_tokens: Some(snapshot.available_input_tokens), |
| 63 | compaction_trigger_tokens: Some(snapshot.compaction_trigger_tokens), |
| 64 | usage_percent: Some(snapshot.usage_percent), |
| 65 | pressure: Some(snapshot.pressure), |
| 66 | })); |
| 67 | } |
| 68 | |
| 69 | // Engine unavailable or the route cannot bound a window: still answer |
| 70 | // with whatever the thread record and the static route catalog can prove. |
| 71 | let config = state.config.read().clone(); |
| 72 | let route = thread |
| 73 | .model_provider |
| 74 | .as_deref() |
| 75 | .and_then(|provider| { |
| 76 | config |
| 77 | .resolve_persisted_provider_identity( |
| 78 | Some(provider), |
| 79 | thread.model_provider_id.as_deref(), |
| 80 | ) |
| 81 | .ok() |
| 82 | }) |
| 83 | .and_then(|identity| { |
| 84 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 85 | &config, |
| 86 | &identity, |
| 87 | Some(&thread.model), |
| 88 | ) |
| 89 | .ok() |
| 90 | }); |
| 91 | let window_tokens = route |
| 92 | .as_ref() |
| 93 | .map(|route| u64::from(route.context_window.tokens)); |
| 94 | Ok(Json(ThreadContextResponse { |
| 95 | thread_id, |
| 96 | model: thread.model, |
| 97 | provider: thread.model_provider, |
| 98 | model_provider_id: thread.model_provider_id, |
| 99 | live: false, |
| 100 | window_tokens, |
| 101 | window_source: route |
| 102 | .as_ref() |
| 103 | .map(|route| route.context_window.source.label()), |
| 104 | input_tokens: None, |
| 105 | billed_input_tokens: None, |
| 106 | output_cap_tokens: None, |
| 107 | input_budget_ceiling: None, |
| 108 | available_input_tokens: None, |
| 109 | compaction_trigger_tokens: None, |
| 110 | usage_percent: None, |
| 111 | pressure: None, |
| 112 | })) |
| 113 | } |
| 114 | |
| 115 | const STANDING_SCHEMA_VERSION: u32 = 1; |
| 116 | const STANDING_ESTIMATOR: &str = "conservative_max_chars_div3_bytes_div4"; |
| 117 | const STANDING_NOT_MEASURED: [&str; 4] = ["skills", "agents", "mcp_tool_schemas", "memory"]; |
| 118 | pub(super) const STANDING_MAX_ITEMS: usize = 200; |
| 119 | const STANDING_LABEL_MAX_CHARS: usize = 80; |
| 120 | const STANDING_DETAIL_KEYS: [&str; 4] = ["kind", "budget_tokens", "max_bytes", "max_files"]; |
| 121 | |
| 122 | fn snake_case(name: &str) -> String { |
| 123 | let mut out = String::with_capacity(name.len() + 2); |
| 124 | for (index, ch) in name.chars().enumerate() { |
| 125 | if ch.is_ascii_uppercase() { |
| 126 | if index > 0 { |
| 127 | out.push('_'); |
| 128 | } |
| 129 | out.push(ch.to_ascii_lowercase()); |
| 130 | } else { |
| 131 | out.push(ch); |
| 132 | } |
| 133 | } |
| 134 | out |
| 135 | } |
| 136 | |
| 137 | pub(super) fn inert_text(text: &str) -> String { |
| 138 | text.chars() |
| 139 | .map(|ch| { |
| 140 | if ch.is_control() || matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') { |
| 141 | '?' |
| 142 | } else { |
| 143 | ch |
| 144 | } |
| 145 | }) |
| 146 | .collect() |
| 147 | } |
| 148 | |
| 149 | fn slash_joined(path: &std::path::Path) -> String { |
| 150 | path.components() |
| 151 | .map(|part| inert_text(&part.as_os_str().to_string_lossy())) |
| 152 | .collect::<Vec<_>>() |
| 153 | .join("/") |
| 154 | } |
| 155 | |
| 156 | pub(super) fn standing_display_path( |
| 157 | path: &std::path::Path, |
| 158 | global: bool, |
| 159 | workspace_roots: &[std::path::PathBuf], |
| 160 | home_roots: &[std::path::PathBuf], |
| 161 | ) -> String { |
| 162 | let name = path |
| 163 | .file_name() |
| 164 | .map(|name| inert_text(&name.to_string_lossy())) |
| 165 | .unwrap_or_default(); |
| 166 | if global { |
| 167 | return home_roots |
| 168 | .iter() |
| 169 | .filter(|home| home.parent().is_some()) |
| 170 | .find_map(|home| path.strip_prefix(home).ok()) |
| 171 | .map_or(name, |relative| format!("~/{}", slash_joined(relative))); |
| 172 | } |
| 173 | workspace_roots |
| 174 | .iter() |
| 175 | .filter_map(|root| { |
| 176 | let shared = root |
| 177 | .ancestors() |
| 178 | .filter(|ancestor| ancestor.parent().is_some()) |
| 179 | .find(|ancestor| path.starts_with(ancestor))?; |
| 180 | let up = root.strip_prefix(shared).ok()?.components().count(); |
| 181 | Some((up, path.strip_prefix(shared).ok()?)) |
| 182 | }) |
| 183 | .min_by_key(|(up, _)| *up) |
| 184 | .map_or(name, |(up, down)| { |
| 185 | format!("{}{}", "../".repeat(up), slash_joined(down)) |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | fn standing_item( |
| 190 | notice: &serde_json::Value, |
| 191 | workspace_roots: &[std::path::PathBuf], |
| 192 | home_roots: &[std::path::PathBuf], |
| 193 | ) -> serde_json::Value { |
| 194 | let key = |field: &str| { |
| 195 | notice |
| 196 | .get(field) |
| 197 | .and_then(serde_json::Value::as_str) |
| 198 | .map(snake_case) |
| 199 | }; |
| 200 | let global = key("scope").as_deref() == Some("global"); |
| 201 | let path = notice |
| 202 | .get("path") |
| 203 | .and_then(serde_json::Value::as_str) |
| 204 | .map(std::path::Path::new) |
| 205 | .map(|path| standing_display_path(path, global, workspace_roots, home_roots)); |
| 206 | let label = path |
| 207 | .as_deref() |
| 208 | .and_then(|path| path.rsplit('/').next()) |
| 209 | .map(|name| name.chars().take(STANDING_LABEL_MAX_CHARS).collect()) |
| 210 | .unwrap_or_else(|| format!("{} instructions", key("scope").unwrap_or_default())); |
| 211 | let detail = notice |
| 212 | .get("detail") |
| 213 | .and_then(serde_json::Value::as_object) |
| 214 | .map(|detail| { |
| 215 | serde_json::Value::Object( |
| 216 | detail |
| 217 | .iter() |
| 218 | .filter(|(field, _)| STANDING_DETAIL_KEYS.contains(&field.as_str())) |
| 219 | .map(|(field, value)| (field.clone(), value.clone())) |
| 220 | .collect(), |
| 221 | ) |
| 222 | }) |
| 223 | .unwrap_or_default(); |
| 224 | serde_json::json!({ |
| 225 | "label": label, |
| 226 | "path": path, |
| 227 | "scope": key("scope"), |
| 228 | "origin": key("origin"), |
| 229 | "action": key("action"), |
| 230 | "limit": key("limit"), |
| 231 | "tokens_kept": notice.get("tokens_kept"), |
| 232 | "tokens_dropped": notice.get("tokens_dropped"), |
| 233 | "bytes_kept": notice.get("bytes_kept"), |
| 234 | "bytes_dropped": notice.get("bytes_dropped"), |
| 235 | "fallback_selected": notice.get("fallback_selected"), |
| 236 | "detail": detail, |
| 237 | }) |
| 238 | } |
| 239 | |
| 240 | pub(super) fn standing_items( |
| 241 | notices: &[serde_json::Value], |
| 242 | workspace_roots: &[std::path::PathBuf], |
| 243 | home_roots: &[std::path::PathBuf], |
| 244 | ) -> (Vec<serde_json::Value>, usize) { |
| 245 | let items = notices |
| 246 | .iter() |
| 247 | .take(STANDING_MAX_ITEMS) |
| 248 | .map(|notice| standing_item(notice, workspace_roots, home_roots)) |
| 249 | .collect(); |
| 250 | (items, notices.len().saturating_sub(STANDING_MAX_ITEMS)) |
| 251 | } |
| 252 | |
| 253 | fn standing_response( |
| 254 | thread_id: &str, |
| 255 | live: bool, |
| 256 | basis: &str, |
| 257 | extra: serde_json::Value, |
| 258 | ) -> serde_json::Value { |
| 259 | let mut body = serde_json::json!({ |
| 260 | "schema_version": STANDING_SCHEMA_VERSION, |
| 261 | "thread_id": thread_id, |
| 262 | "live": live, |
| 263 | "basis": basis, |
| 264 | "estimator": STANDING_ESTIMATOR, |
| 265 | "estimated": true, |
| 266 | "not_measured": STANDING_NOT_MEASURED, |
| 267 | "items": [], |
| 268 | }); |
| 269 | if let (Some(body), Some(extra)) = (body.as_object_mut(), extra.as_object()) { |
| 270 | body.extend(extra.clone()); |
| 271 | } |
| 272 | body |
| 273 | } |
| 274 | |
| 275 | pub(super) async fn get_thread_standing_context( |
| 276 | State(state): State<RuntimeApiState>, |
| 277 | Path(thread_id): Path<String>, |
| 278 | ) -> Result<Json<serde_json::Value>, ApiError> { |
| 279 | state |
| 280 | .runtime_threads |
| 281 | .get_thread(&thread_id) |
| 282 | .await |
| 283 | .map_err(map_thread_err)?; |
| 284 | |
| 285 | let snapshot = match state.runtime_threads.get_engine(&thread_id).await { |
| 286 | Ok(engine) => engine.get_session_snapshot().await.ok(), |
| 287 | Err(_) => None, |
| 288 | }; |
| 289 | let Some(snapshot) = snapshot else { |
| 290 | return Ok(Json(standing_response( |
| 291 | &thread_id, |
| 292 | false, |
| 293 | "unavailable", |
| 294 | serde_json::Value::Null, |
| 295 | ))); |
| 296 | }; |
| 297 | let Some(receipt) = snapshot.instruction_assembly else { |
| 298 | return Ok(Json(standing_response( |
| 299 | &thread_id, |
| 300 | true, |
| 301 | "no_receipt", |
| 302 | serde_json::Value::Null, |
| 303 | ))); |
| 304 | }; |
| 305 | |
| 306 | let workspace = snapshot.workspace; |
| 307 | let (workspace_roots, home_roots) = tokio::task::spawn_blocking(move || { |
| 308 | let with_canonical = |path: std::path::PathBuf| { |
| 309 | let mut roots = vec![path.clone()]; |
| 310 | if let Ok(canonical) = std::fs::canonicalize(&path) |
| 311 | && canonical != path |
| 312 | { |
| 313 | roots.push(canonical); |
| 314 | } |
| 315 | roots |
| 316 | }; |
| 317 | ( |
| 318 | with_canonical(workspace), |
| 319 | codewhale_paths::user_home() |
| 320 | .map(with_canonical) |
| 321 | .unwrap_or_default(), |
| 322 | ) |
| 323 | }) |
| 324 | .await |
| 325 | .map_err(|_| ApiError::internal("instruction receipt path resolution failed"))?; |
| 326 | |
| 327 | let (items, items_omitted) = standing_items( |
| 328 | receipt |
| 329 | .get("notices") |
| 330 | .and_then(serde_json::Value::as_array) |
| 331 | .map_or(&[][..], Vec::as_slice), |
| 332 | &workspace_roots, |
| 333 | &home_roots, |
| 334 | ); |
| 335 | let delivery = codewhale_engine::runtime_handoff::project_instructions_delivery( |
| 336 | &snapshot.messages, |
| 337 | ) |
| 338 | .map(|delivery| { |
| 339 | serde_json::json!({ |
| 340 | "message_bytes": delivery.message_bytes, |
| 341 | "message_tokens": delivery.message_tokens, |
| 342 | "truncated": delivery.truncated, |
| 343 | }) |
| 344 | }); |
| 345 | Ok(Json(standing_response( |
| 346 | &thread_id, |
| 347 | true, |
| 348 | "installed_receipt", |
| 349 | serde_json::json!({ |
| 350 | "global_tokens": receipt.get("global_tokens"), |
| 351 | "project_tokens": receipt.get("project_tokens"), |
| 352 | "constitution_tokens": receipt.get("constitution_tokens"), |
| 353 | "retained_block_tokens": receipt.get("retained_block_tokens"), |
| 354 | "budgets": receipt.get("budgets"), |
| 355 | "items": items, |
| 356 | "items_omitted": items_omitted, |
| 357 | "delivery": { |
| 358 | "cap_bytes": codewhale_engine::runtime_handoff::PROJECT_INSTRUCTIONS_MAX_BYTES, |
| 359 | "delivered": delivery, |
| 360 | }, |
| 361 | }), |
| 362 | ))) |
| 363 | } |
| 364 |