Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-cli/src/context7.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-cli / src / context7.rs` 537 lines ยท 17828 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use reqwest::Client; 17 use serde_json::{json, Value}; 18 19 const SEARCH_URL: &str = "https://context7.com/api/v2/libs/search"; 20 const CONTEXT_URL: &str = "https://context7.com/api/v2/context"; 21 const MAX_LIBRARIES: usize = 5; 22 const MAX_SNIPPETS: usize = 4; 23 const MAX_CODE_CHARS: usize = 1200; 24 const MAX_INFO_CHARS: usize = 800; 25 26 pub fn context7_dispatch_tool(args: &Value) -> Value { 27 match tokio::runtime::Handle::try_current() { 28 Ok(handle) => tokio::task::block_in_place(|| handle.block_on(context7_dispatch(args))), 29 Err(_) => json!({"status": "error", "error": "Context7 requires a running async runtime"}), 30 } 31 } 32 33 pub async fn context7_dispatch(args: &Value) -> Value { 34 let action = args 35 .get("action") 36 .and_then(Value::as_str) 37 .unwrap_or("resolve") 38 .trim() 39 .to_ascii_lowercase(); 40 match action.as_str() { 41 "resolve" | "resolve-library-id" | "search" => resolve_library(args).await, 42 "query" | "query-docs" | "docs" => query_docs(args).await, 43 other => json!({ 44 "status": "error", 45 "error": format!("Unknown context7 action '{other}'. Use resolve or query.") 46 }), 47 } 48 } 49 50 async fn resolve_library(args: &Value) -> Value { 51 let library = args 52 .get("library") 53 .or_else(|| args.get("libraryName")) 54 .or_else(|| args.get("name")) 55 .and_then(Value::as_str) 56 .unwrap_or("") 57 .trim(); 58 if library.is_empty() { 59 return json!({"status": "error", "error": "context7 resolve requires library"}); 60 } 61 let query = args 62 .get("query") 63 .and_then(Value::as_str) 64 .unwrap_or(library) 65 .trim(); 66 let query = if query.is_empty() { library } else { query }; 67 match get_json(SEARCH_URL, &[("libraryName", library), ("query", query)]).await { 68 Ok(body) => compact_libraries(&body, library, query), 69 Err(error) => json!({"status": "error", "error": error}), 70 } 71 } 72 73 async fn query_docs(args: &Value) -> Value { 74 let library_id = args 75 .get("library_id") 76 .or_else(|| args.get("libraryId")) 77 .and_then(Value::as_str) 78 .unwrap_or("") 79 .trim(); 80 if !valid_library_id(library_id) { 81 return json!({ 82 "status": "error", 83 "error": "context7 query requires library_id like /org/project. Resolve the library first." 84 }); 85 } 86 let query = args 87 .get("query") 88 .and_then(Value::as_str) 89 .unwrap_or("") 90 .trim(); 91 if query.is_empty() { 92 return json!({"status": "error", "error": "context7 query requires one specific query"}); 93 } 94 match get_json( 95 CONTEXT_URL, 96 &[ 97 ("libraryId", library_id), 98 ("query", query), 99 ("type", "json"), 100 ], 101 ) 102 .await 103 { 104 Ok(body) => compact_context(&body, library_id, query), 105 Err(error) => json!({"status": "error", "error": error}), 106 } 107 } 108 109 async fn get_json(url: &str, params: &[(&str, &str)]) -> Result { 110 let key = crate::vault::get_secret("CONTEXT7_API_KEY") 111 .map_err(|_| "CONTEXT7_API_KEY is unavailable from atlas-vault".to_string())?; 112 let client = Client::new(); 113 let response = client 114 .get(url) 115 .bearer_auth(key) 116 .header("Accept", "application/json") 117 .query(params) 118 .send() 119 .await 120 .map_err(|error| format!("Context7 connection failed: {error}"))?; 121 let status = response.status(); 122 if status.as_u16() == 301 { 123 let body = response.json::().await.unwrap_or(Value::Null); 124 let redirect = body 125 .get("redirectUrl") 126 .and_then(Value::as_str) 127 .unwrap_or(""); 128 return Err(format!( 129 "Context7 moved this library. Use library_id {redirect}" 130 )); 131 } 132 if !status.is_success() { 133 let body = response.text().await.unwrap_or_default(); 134 return Err(format!("Context7 returned {status}: {}", scrub(&body))); 135 } 136 response 137 .json::() 138 .await 139 .map_err(|error| format!("Context7 returned invalid JSON: {error}")) 140 } 141 142 fn valid_library_id(id: &str) -> bool { 143 let mut parts = id.split('/'); 144 if parts.next() != Some("") { 145 return false; 146 } 147 let Some(source) = parts.next() else { 148 return false; 149 }; 150 let Some(name) = parts.next() else { 151 return false; 152 }; 153 if source.is_empty() || source.contains('@') || name.is_empty() { 154 return false; 155 } 156 match parts.next() { 157 None => true, 158 Some(version) if !version.is_empty() && !version.contains('@') && !name.contains('@') => { 159 parts.next().is_none() 160 } 161 Some(_) => false, 162 } 163 } 164 165 fn compact_libraries(body: &Value, library: &str, query: &str) -> Value { 166 let results = body 167 .get("results") 168 .and_then(Value::as_array) 169 .cloned() 170 .unwrap_or_default(); 171 let libraries: Vec = results 172 .into_iter() 173 .take(MAX_LIBRARIES) 174 .map(|item| { 175 json!({ 176 "id": item.get("id").cloned().unwrap_or(Value::Null), 177 "title": item.get("title").cloned().unwrap_or(Value::Null), 178 "description": clip(item.get("description").and_then(Value::as_str).unwrap_or(""), 240), 179 "trust_score": item.get("trustScore").or_else(|| item.get("benchmarkScore")).cloned().unwrap_or(Value::Null), 180 "snippets": item.get("totalSnippets").or_else(|| item.get("snippets")).cloned().unwrap_or(Value::Null) 181 }) 182 }) 183 .collect(); 184 json!({ 185 "status": "ok", 186 "mode": "resolve", 187 "library": library, 188 "query": query, 189 "libraries": libraries, 190 "next": "Call context7 query with one library_id and one specific question." 191 }) 192 } 193 194 fn compact_context(body: &Value, library_id: &str, query: &str) -> Value { 195 let code: Vec = body 196 .get("codeSnippets") 197 .and_then(Value::as_array) 198 .into_iter() 199 .flatten() 200 .take(MAX_SNIPPETS) 201 .map(|snippet| { 202 let code = snippet 203 .get("codeList") 204 .and_then(Value::as_array) 205 .and_then(|list| list.first()) 206 .and_then(|item| item.get("code")) 207 .and_then(Value::as_str) 208 .unwrap_or(""); 209 json!({ 210 "title": snippet.get("codeTitle").cloned().unwrap_or(Value::Null), 211 "page": snippet.get("pageTitle").cloned().unwrap_or(Value::Null), 212 "language": snippet.get("codeLanguage").cloned().unwrap_or(Value::Null), 213 "code": clip(code, MAX_CODE_CHARS) 214 }) 215 }) 216 .collect(); 217 let info: Vec = body 218 .get("infoSnippets") 219 .and_then(Value::as_array) 220 .into_iter() 221 .flatten() 222 .take(MAX_SNIPPETS) 223 .map(|snippet| { 224 json!({ 225 "breadcrumb": snippet.get("breadcrumb").cloned().unwrap_or(Value::Null), 226 "content": clip(snippet.get("content").and_then(Value::as_str).unwrap_or(""), MAX_INFO_CHARS) 227 }) 228 }) 229 .collect(); 230 json!({ 231 "status": "ok", 232 "mode": "query", 233 "library_id": library_id, 234 "query": query, 235 "code": code, 236 "info": info 237 }) 238 } 239 240 fn clip(text: &str, limit: usize) -> String { 241 let mut chars = text.chars(); 242 let clipped: String = chars.by_ref().take(limit).collect(); 243 if chars.next().is_some() { 244 format!("{clipped} ...") 245 } else { 246 clipped 247 } 248 } 249 250 struct SyncTarget { 251 slug: &'static str, 252 library: &'static str, 253 query: &'static str, 254 prefer: &'static [&'static str], 255 } 256 257 fn sync_catalog() -> &'static [SyncTarget] { 258 &[ 259 SyncTarget { 260 slug: "rust", 261 library: "rust", 262 query: "ownership, borrowing, lifetimes, and Result error handling", 263 prefer: &["doc.rust-lang", "rust-lang"], 264 }, 265 SyncTarget { 266 slug: "tokio", 267 library: "tokio", 268 query: "spawn tasks on a multi-thread runtime and use select", 269 prefer: &["tokio-rs/tokio"], 270 }, 271 SyncTarget { 272 slug: "axum", 273 library: "axum", 274 query: "Router, JSON extractors, and WebSocket routes", 275 prefer: &["tokio-rs/axum"], 276 }, 277 SyncTarget { 278 slug: "serde", 279 library: "serde", 280 query: "derive Serialize and rename_all for structs", 281 prefer: &["serde-rs/serde"], 282 }, 283 ] 284 } 285 286 fn pick_library_id(libraries: &[Value], prefer: &[&str]) -> Option { 287 let ids: Vec<&str> = libraries 288 .iter() 289 .filter_map(|item| item.get("id").and_then(Value::as_str)) 290 .filter(|id| valid_library_id(id)) 291 .collect(); 292 for hint in prefer { 293 if let Some(id) = ids.iter().copied().find(|id| id.contains(hint)) { 294 return Some(id.to_string()); 295 } 296 } 297 ids.first().map(|id| (*id).to_string()) 298 } 299 300 fn render_reference(library: &str, library_id: &str, query: &str, docs: &Value) -> String { 301 let mut out = format!("Context7 reference for {library} ({library_id}).\nQuestion: {query}\n"); 302 if let Some(info) = docs.get("info").and_then(Value::as_array) { 303 for note in info { 304 let breadcrumb = note.get("breadcrumb").and_then(Value::as_str).unwrap_or(""); 305 let content = note.get("content").and_then(Value::as_str).unwrap_or(""); 306 if !content.is_empty() { 307 out.push_str(&format!("\n{breadcrumb}\n{content}\n")); 308 } 309 } 310 } 311 if let Some(code) = docs.get("code").and_then(Value::as_array) { 312 for snippet in code { 313 let title = snippet 314 .get("title") 315 .and_then(Value::as_str) 316 .unwrap_or("code"); 317 let body = snippet.get("code").and_then(Value::as_str).unwrap_or(""); 318 if !body.is_empty() { 319 out.push_str(&format!("\n{title}\n{body}\n")); 320 } 321 } 322 } 323 clip(&out, 6000) 324 } 325 326 pub async fn sync_to_cortex() -> i32 { 327 let mut failures = 0usize; 328 let mut written = Vec::new(); 329 for target in sync_catalog() { 330 match sync_one(target).await { 331 Ok(library_id) => { 332 println!("context7:{:<8} {}", target.slug, library_id); 333 written.push(target.slug); 334 } 335 Err(error) => { 336 failures += 1; 337 println!("context7:{:<8} error: {error}", target.slug); 338 } 339 } 340 } 341 let stamp = chrono::Utc::now().to_rfc3339(); 342 let manifest = format!( 343 "Context7 sync at {stamp}. Updated: {}. Failures: {failures}.", 344 written.join(", ") 345 ); 346 match crate::cortex::write_to_cortex( 347 "context7:sync", 348 &manifest, 349 "reference", 350 json!({ 351 "source": "context7", 352 "fetched_at": stamp, 353 "updated": written, 354 "failures": failures 355 }), 356 ) 357 .await 358 { 359 Ok(_) => println!("context7:sync recorded"), 360 Err(error) => { 361 failures += 1; 362 println!("context7:sync error: {error}"); 363 } 364 } 365 if failures == 0 { 366 0 367 } else { 368 1 369 } 370 } 371 372 async fn sync_one(target: &SyncTarget) -> Result { 373 let resolved = resolve_library(&json!({ 374 "library": target.library, 375 "query": target.query 376 })) 377 .await; 378 if resolved.get("status").and_then(Value::as_str) != Some("ok") { 379 return Err(resolved 380 .get("error") 381 .and_then(Value::as_str) 382 .unwrap_or("resolve failed") 383 .to_string()); 384 } 385 let libraries = resolved 386 .get("libraries") 387 .and_then(Value::as_array) 388 .cloned() 389 .unwrap_or_default(); 390 let library_id = pick_library_id(&libraries, target.prefer) 391 .ok_or_else(|| format!("no Context7 id for {}", target.library))?; 392 let docs = query_docs(&json!({ 393 "library_id": library_id, 394 "query": target.query 395 })) 396 .await; 397 if docs.get("status").and_then(Value::as_str) != Some("ok") { 398 return Err(docs 399 .get("error") 400 .and_then(Value::as_str) 401 .unwrap_or("query failed") 402 .to_string()); 403 } 404 let content = render_reference(target.library, &library_id, target.query, &docs); 405 let name = format!("context7:{}", target.slug); 406 crate::cortex::write_to_cortex( 407 &name, 408 &content, 409 "reference", 410 json!({ 411 "source": "context7", 412 "library": target.library, 413 "library_id": library_id, 414 "query": target.query, 415 "fetched_at": chrono::Utc::now().to_rfc3339() 416 }), 417 ) 418 .await?; 419 Ok(library_id) 420 } 421 422 fn scrub(body: &str) -> String { 423 let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null); 424 let message = parsed 425 .get("message") 426 .and_then(Value::as_str) 427 .or_else(|| parsed.get("error").and_then(Value::as_str)) 428 .unwrap_or(body); 429 if message.contains("ctx7sk") || message.contains("Bearer ") { 430 "Context7 rejected the request".to_string() 431 } else { 432 clip(message, 300) 433 } 434 } 435 436 #[cfg(test)] 437 mod tests { 438 use super::*; 439 440 #[test] 441 fn library_ids_match_context7_shape() { 442 assert!(valid_library_id("/tokio-rs/tokio")); 443 assert!(valid_library_id("/vercel/next.js")); 444 assert!(valid_library_id("/vercel/next.js/14.2.5")); 445 assert!(valid_library_id("/vercel/next.js@14.2.5")); 446 assert!(!valid_library_id("/a/b/c/d")); 447 assert!(!valid_library_id("react")); 448 assert!(!valid_library_id("/onlyone")); 449 assert!(!valid_library_id("/a/b/c/d")); 450 } 451 452 #[test] 453 fn resolve_payload_keeps_five_ids_and_drops_the_rest() { 454 let body = json!({ 455 "results": [ 456 {"id": "/tokio-rs/tokio", "title": "Tokio", "description": "x".repeat(400), "trustScore": 90, "totalSnippets": 12}, 457 {"id": "/a/two", "title": "Two"}, 458 {"id": "/a/three", "title": "Three"}, 459 {"id": "/a/four", "title": "Four"}, 460 {"id": "/a/five", "title": "Five"}, 461 {"id": "/a/six", "title": "Six"} 462 ] 463 }); 464 let compact = compact_libraries(&body, "tokio", "spawn a task"); 465 assert_eq!(compact["libraries"].as_array().unwrap().len(), 5); 466 assert_eq!(compact["libraries"][0]["id"], "/tokio-rs/tokio"); 467 assert!(compact["libraries"][0]["description"] 468 .as_str() 469 .unwrap() 470 .ends_with(" ...")); 471 assert!( 472 compact["libraries"][0] 473 .get("description") 474 .unwrap() 475 .as_str() 476 .unwrap() 477 .len() 478 < 400 479 ); 480 } 481 482 #[test] 483 fn query_payload_clips_code_and_keeps_the_library_id() { 484 let body = json!({ 485 "codeSnippets": [{ 486 "codeTitle": "Spawn", 487 "codeLanguage": "bash", 488 "pageTitle": "Tokio", 489 "codeList": [{"code": "m".repeat(2000)}] 490 }], 491 "infoSnippets": [{"breadcrumb": "Spawn", "content": "Call tokio::spawn."}] 492 }); 493 let compact = compact_context(&body, "/tokio-rs/tokio", "spawn flags"); 494 assert_eq!(compact["library_id"], "/tokio-rs/tokio"); 495 assert!(compact["code"][0]["code"] 496 .as_str() 497 .unwrap() 498 .ends_with(" ...")); 499 assert_eq!(compact["info"][0]["content"], "Call tokio::spawn."); 500 } 501 502 #[test] 503 fn sync_catalog_covers_the_stack_in_use() { 504 let slugs: Vec<&str> = sync_catalog().iter().map(|target| target.slug).collect(); 505 assert_eq!(slugs, vec!["rust", "tokio", "axum", "serde"]); 506 } 507 508 #[test] 509 fn preferred_library_id_beats_the_first_hit() { 510 let libraries = vec![ 511 json!({"id": "/other/rust-book"}), 512 json!({"id": "/websites/doc_rust-lang_org"}), 513 ]; 514 assert_eq!( 515 pick_library_id(&libraries, &["doc.rust-lang", "rust-lang"]).as_deref(), 516 Some("/websites/doc_rust-lang_org") 517 ); 518 } 519 520 #[test] 521 fn rendered_reference_names_the_library_and_clips() { 522 let docs = json!({ 523 "info": [{"breadcrumb": "Borrowing", "content": "A borrow lasts for a scope."}], 524 "code": [{"title": "Example", "code": "x".repeat(7000)}] 525 }); 526 let text = render_reference("rust", "/websites/doc_rust-lang_org", "borrowing", &docs); 527 assert!(text.contains("doc_rust-lang_org")); 528 assert!(text.contains("A borrow lasts")); 529 assert!(text.chars().count() <= 6004); 530 } 531 532 #[test] 533 fn error_text_does_not_keep_a_key() { 534 let scrubbed = scrub(r#"{"message":"bad key ctx7sk-secret-value"}"#); 535 assert_eq!(scrubbed, "Context7 rejected the request"); 536 } 537 }