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/interplane-mv/blob/main/rust/crates/interplane-crossaxis/src/lib.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. 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 `interplane-mv / rust / crates / interplane-crossaxis / src / lib.rs` 1025 lines ยท 37487 bytes Raw Blame History 1 //! CrossAxis: explicit capability mapping and the deterministic domain selector. 2 //! It never answers "may the model run it?". 3 use interplane_core::{ 4 canonicalize, CapabilityDescriptor, CapabilityRequest, CapabilityRequestKind, Catalog, 5 ErrorCode, ExcludedEntry, ExpansionBounds, ExpansionEntry, FullSelected, MappingInfo, Measure, 6 RefusedEntry, SelectedEntry, Selection, SelectionKind, SelectorInfo, TokenMeasure, ToolRef, 7 ToolRequest, 8 }; 9 use serde::{Deserialize, Serialize}; 10 use serde_json::{Map, Number, Value}; 11 use thiserror::Error; 12 13 /// Rule kind. 14 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 15 #[serde(rename_all = "snake_case")] 16 pub enum RuleKind { 17 Alias, 18 Passthrough, 19 } 20 21 /// Canonical coordinates a rule matches. 22 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 23 pub struct RuleFrom { 24 #[serde(default)] 25 pub namespace: Option, 26 pub name: String, 27 } 28 29 /// An explicit argument rename. 30 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 31 pub struct Rename { 32 pub from: String, 33 pub to: String, 34 } 35 36 /// One mapping rule. 37 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 38 pub struct Rule { 39 pub id: String, 40 pub kind: RuleKind, 41 pub from: RuleFrom, 42 pub to: String, 43 #[serde(default)] 44 pub renames: Vec, 45 } 46 47 /// A versioned mapping table (data, not code). 48 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 49 pub struct MappingTable { 50 pub runtime: String, 51 #[serde(deserialize_with = "string_or_number")] 52 pub table_version: String, 53 /// Digest of the runtime catalog this table was built against (optional). 54 #[serde(default, skip_serializing_if = "Option::is_none")] 55 pub catalog_digest: Option, 56 pub rules: Vec, 57 } 58 59 fn string_or_number<'de, D: serde::Deserializer<'de>>(d: D) -> Result { 60 match Value::deserialize(d)? { 61 Value::String(s) => Ok(s), 62 Value::Number(n) => Ok(n.to_string()), 63 _ => Err(serde::de::Error::custom( 64 "table_version must be a string or number", 65 )), 66 } 67 } 68 69 /// Table loading failure. 70 #[derive(Debug, Error)] 71 pub enum MappingError { 72 #[error("invalid mapping table: {0}")] 73 Invalid(#[from] serde_json::Error), 74 #[error("passthrough rule {0} must have a null namespace and `to` equal to `from.name`")] 75 BadPassthrough(String), 76 } 77 78 impl MappingTable { 79 pub fn from_json_str(s: &str) -> Result { 80 Self::from_value(serde_json::from_str(s)?) 81 } 82 pub fn from_value(v: Value) -> Result { 83 let t: MappingTable = serde_json::from_value(v)?; 84 for r in &t.rules { 85 if r.kind == RuleKind::Passthrough 86 && (r.from.namespace.is_some() || r.from.name != r.to) 87 { 88 return Err(MappingError::BadPassthrough(r.id.clone())); 89 } 90 } 91 Ok(t) 92 } 93 94 /// Exact lookup, first matching rule wins. No match -> `unknown_capability`. 95 pub fn map(&self, req: &ToolRequest) -> Result { 96 let rule = self 97 .rules 98 .iter() 99 .find(|r| r.from.namespace == req.tool.namespace && r.from.name == req.tool.name) 100 .ok_or(ErrorCode::UnknownCapability)?; 101 let mut arguments = req.arguments.clone(); 102 for rn in &rule.renames { 103 if let Some(v) = arguments.remove(&rn.from) { 104 arguments.insert(rn.to.clone(), v); 105 } 106 } 107 Ok(CapabilityRequest { 108 kind: CapabilityRequestKind, 109 request_id: req.request_id.clone(), 110 runtime: self.runtime.clone(), 111 capability: rule.to.clone(), 112 arguments, 113 tool: ToolRef { 114 namespace: req.tool.namespace.clone(), 115 name: req.tool.name.clone(), 116 }, 117 mapping: MappingInfo { 118 table_version: self.table_version.clone(), 119 rule_id: rule.id.clone(), 120 passthrough: rule.kind == RuleKind::Passthrough, 121 catalog_digest: self.catalog_digest.clone(), 122 coerced: None, 123 extensions: Map::new(), 124 }, 125 runtime_effects: None, 126 extensions: Map::new(), 127 }) 128 } 129 } 130 131 fn schema_types(schema: &Value) -> Vec<&str> { 132 match schema.get("type") { 133 Some(Value::String(s)) => vec![s.as_str()], 134 Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), 135 _ => vec![], 136 } 137 } 138 139 /// Coerce string arguments to the integer/number/boolean the capability schema declares, when the 140 /// string parses. Records the coerced keys in `mapping.coerced` (sorted). Returns the keys. 141 pub fn coerce_arguments(req: &mut CapabilityRequest, cap: &CapabilityDescriptor) -> Vec { 142 let mut done = vec![]; 143 let Some(props) = cap.parameters.get("properties").and_then(Value::as_object) else { 144 return done; 145 }; 146 for (k, v) in req.arguments.iter_mut() { 147 let (Some(schema), Value::String(s)) = (props.get(k), &*v) else { 148 continue; 149 }; 150 let types = schema_types(schema); 151 if types.contains(&"string") { 152 continue; 153 } 154 let new = if types.contains(&"integer") && s.parse::().is_ok() { 155 Some(Value::from(s.parse::().unwrap_or_default())) 156 } else if types.contains(&"number") { 157 match (s.parse::(), s.parse::()) { 158 (Ok(i), _) => Some(Value::from(i)), 159 (_, Ok(f)) => Number::from_f64(f).map(Value::Number), 160 _ => None, 161 } 162 } else if types.contains(&"boolean") && (s == "true" || s == "false") { 163 Some(Value::Bool(s == "true")) 164 } else { 165 None 166 }; 167 if let Some(n) = new { 168 *v = n; 169 done.push(k.clone()); 170 } 171 } 172 done.sort(); 173 if !done.is_empty() { 174 req.mapping.coerced = Some(done.clone()); 175 } 176 done 177 } 178 179 /// `domain_match` v1. Returns the receipt (without `measure`) and the selected descriptors. 180 pub fn select( 181 catalog: &Catalog, 182 requested_domains: &[String], 183 max_capabilities: Option, 184 always_include: &[String], 185 ) -> (Selection, Vec) { 186 let exclude = |name: &str, reason: &str| ExcludedEntry { 187 name: name.into(), 188 reason: reason.into(), 189 extensions: Map::new(), 190 }; 191 // 1. Pinned capabilities, in catalog order, never truncated. 192 let mut selected: Vec<(&CapabilityDescriptor, String)> = catalog 193 .capabilities 194 .iter() 195 .filter(|c| always_include.contains(&c.name)) 196 .map(|c| (c, "always_include".to_string())) 197 .collect(); 198 let pinned = selected.len(); 199 // 2. Domain matches sorted by name. 200 let mut domain: Vec<(&CapabilityDescriptor, String)> = vec![]; 201 let mut excluded: Vec = vec![]; 202 let mut rest: Vec<&CapabilityDescriptor> = catalog 203 .capabilities 204 .iter() 205 .filter(|c| !always_include.contains(&c.name)) 206 .collect(); 207 rest.sort_by(|a, b| a.name.cmp(&b.name)); 208 for c in rest { 209 if c.domains.is_empty() { 210 excluded.push(exclude(&c.name, "no_domains")); 211 } else if let Some(d) = c.domains.iter().find(|d| requested_domains.contains(d)) { 212 domain.push((c, format!("domain:{d}"))); 213 } else { 214 excluded.push(exclude(&c.name, "domain_mismatch")); 215 } 216 } 217 if let Some(max) = max_capabilities { 218 let keep = max.saturating_sub(pinned).min(domain.len()); 219 for (c, _) in domain.drain(keep..) { 220 excluded.push(exclude(&c.name, "max_capabilities")); 221 } 222 } 223 selected.extend(domain); 224 excluded.sort_by(|a, b| a.name.cmp(&b.name)); 225 let descriptors = selected.iter().map(|(c, _)| (*c).clone()).collect(); 226 let sel = Selection { 227 kind: SelectionKind, 228 runtime: catalog.runtime.clone(), 229 catalog_digest: catalog 230 .catalog_digest 231 .clone() 232 .unwrap_or_else(|| catalog.compute_digest()), 233 selector: SelectorInfo { 234 name: "domain_match".into(), 235 version: "1".into(), 236 max_capabilities: max_capabilities.map(|m| m as u64), 237 expansion: None, 238 extensions: Map::new(), 239 }, 240 requested_domains: requested_domains.to_vec(), 241 always_include: always_include.to_vec(), 242 selected: selected 243 .iter() 244 .map(|(c, rule)| SelectedEntry { 245 name: c.name.clone(), 246 rule_id: rule.clone(), 247 domains: c.domains.clone(), 248 extensions: Map::new(), 249 }) 250 .collect(), 251 excluded, 252 measure: None, 253 expansions: vec![], 254 parent_digest: None, 255 selection_digest: None, 256 extensions: Map::new(), 257 }; 258 (sel, descriptors) 259 } 260 261 /// Render descriptors as OpenAI-style `tools` entries (the default measuring renderer; the same 262 /// shape as the Python `openai_tools_renderer`). 263 pub fn openai_tools_renderer(caps: &[CapabilityDescriptor]) -> Value { 264 Value::Array( 265 caps.iter() 266 .map(|c| { 267 serde_json::json!({"type": "function", "function": { 268 "name": c.name, "description": c.description, "parameters": c.parameters}}) 269 }) 270 .collect(), 271 ) 272 } 273 274 /// Bytes of `v` as sent on the wire: canonical JSON (RFC 8785), UTF-8. 275 fn wire_bytes(v: &Value) -> u64 { 276 canonicalize(v).len() as u64 277 } 278 279 /// The unit values of `measure.tokens.unit`. 280 pub const TOKEN_UNITS: [&str; 4] = [ 281 "bytes", 282 "tokens_model_reported", 283 "tokens_endpoint_tokenizer", 284 "tokens_estimated", 285 ]; 286 /// `source` recorded by [`EstimatedTokens`]. 287 pub const ESTIMATOR_SOURCE: &str = "estimator v1 ceil(utf8_bytes/4)"; 288 289 /// Counts one prompt. A live counter (model-reported `usage.prompt_tokens`, an endpoint 290 /// `/tokenize`) lives in the bench runner and implements this trait; Core stays offline. 291 /// `messages` is the JSON array of messages as sent, `tools` the rendered `tools` array (`None` 292 /// means no tools in the request). 293 pub trait TokenCounter { 294 /// One of [`TOKEN_UNITS`]. 295 fn unit(&self) -> &str; 296 /// Free text recorded in the receipt. 297 fn source(&self) -> &str; 298 fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64; 299 } 300 301 /// Unit `bytes`: canonical-JSON bytes of `messages` plus, when present, of `tools`. 302 pub struct BytesOnly; 303 impl TokenCounter for BytesOnly { 304 fn unit(&self) -> &str { 305 "bytes" 306 } 307 fn source(&self) -> &str { 308 "canonical json bytes of messages and tools" 309 } 310 fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64 { 311 wire_bytes(messages) + tools.map_or(0, wire_bytes) 312 } 313 } 314 315 /// Unit `tokens_estimated`. Estimator v1: `ceil(utf8_len(jcs(value)) / 4)` per value; a prompt is 316 /// the estimate for `messages` plus, when present, the estimate for `tools`. 317 pub struct EstimatedTokens; 318 impl TokenCounter for EstimatedTokens { 319 fn unit(&self) -> &str { 320 "tokens_estimated" 321 } 322 fn source(&self) -> &str { 323 ESTIMATOR_SOURCE 324 } 325 fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64 { 326 let est = |v: &Value| wire_bytes(v).div_ceil(4); 327 est(messages) + tools.map_or(0, est) 328 } 329 } 330 331 /// Fill `selection.measure`: render the full catalog and the selection with the same renderer and 332 /// count the canonical-JSON bytes of each rendering (the bytes of `tools` as sent). 333 pub fn measure( 334 selection: &mut Selection, 335 catalog: &Catalog, 336 selected: &[CapabilityDescriptor], 337 render: F, 338 ) where 339 F: Fn(&[CapabilityDescriptor]) -> Value, 340 { 341 measure_tokens(selection, catalog, selected, render, None); 342 } 343 344 /// Totals the bench measured in the same unit as the counter, passed through into the receipt. 345 #[derive(Debug, Clone, Copy, Default)] 346 pub struct BenchTotals { 347 pub all_rounds_prompt: Option, 348 pub completion: Option, 349 } 350 351 /// [`measure`] plus `measure.tokens` when a counter and the base `messages` (system + user, as 352 /// sent) are given: `first_turn_prompt = count(messages, tools)`, `base_context = count(messages, 353 /// None)`, `tool_schema = first_turn_prompt - base_context`. 354 pub fn measure_tokens( 355 selection: &mut Selection, 356 catalog: &Catalog, 357 selected: &[CapabilityDescriptor], 358 render: F, 359 counted: Option<(&dyn TokenCounter, &Value, BenchTotals)>, 360 ) where 361 F: Fn(&[CapabilityDescriptor]) -> Value, 362 { 363 let (full_r, sel_r) = (render(&catalog.capabilities), render(selected)); 364 let (f_bytes, s_bytes) = (wire_bytes(&full_r), wire_bytes(&sel_r)); 365 let tokens = counted.map(|(counter, messages, totals)| { 366 let base = counter.count_prompt(messages, None); 367 let first = FullSelected { 368 full: counter.count_prompt(messages, Some(&full_r)), 369 selected: counter.count_prompt(messages, Some(&sel_r)), 370 }; 371 TokenMeasure { 372 unit: counter.unit().to_string(), 373 source: counter.source().to_string(), 374 base_context: base, 375 tool_schema: FullSelected { 376 full: first.full.saturating_sub(base), 377 selected: first.selected.saturating_sub(base), 378 }, 379 first_turn_prompt: first, 380 all_rounds_prompt: totals.all_rounds_prompt, 381 completion: totals.completion, 382 } 383 }); 384 selection.measure = Some(Measure { 385 full_count: Some(catalog.capabilities.len() as u64), 386 selected_count: Some(selected.len() as u64), 387 full_rendered_bytes: Some(f_bytes), 388 selected_rendered_bytes: Some(s_bytes), 389 full_tokens: None, 390 selected_tokens: None, 391 tokenizer: None, 392 rendered_bytes: Some(FullSelected { 393 full: f_bytes, 394 selected: s_bytes, 395 }), 396 tokens, 397 extensions: Map::new(), 398 }); 399 } 400 401 pub const DEFAULT_MAX_EXPANSIONS: u64 = 2; 402 pub const DEFAULT_MAX_ADDED_PER_EXPANSION: u64 = 8; 403 pub const DEFAULT_DISCOVER_LIMIT: usize = 8; 404 405 /// Evidence for [`expand`]. 406 #[derive(Debug, Clone, PartialEq)] 407 pub enum Evidence { 408 /// The model called a capability that exists in the catalog but is not in the selection. 409 RequestedExcluded { 410 name: String, 411 include_domain_siblings: bool, 412 }, 413 /// Names returned by [`discover`] for `query`. 414 DiscoveryHit { 415 query: Option, 416 names: Vec, 417 }, 418 } 419 420 impl Evidence { 421 /// Parse the evidence JSON object (the form hashed into `evidence_digest`). 422 pub fn from_value(v: &Value) -> Result { 423 let bad = |m: &str| ExpansionError(m.to_string()); 424 match v.get("kind").and_then(Value::as_str) { 425 Some("requested_excluded") => Ok(Evidence::RequestedExcluded { 426 name: v 427 .get("name") 428 .and_then(Value::as_str) 429 .filter(|n| !n.is_empty()) 430 .ok_or_else(|| bad("requested_excluded needs a name"))? 431 .to_string(), 432 include_domain_siblings: v.get("include_domain_siblings") 433 == Some(&Value::Bool(true)), 434 }), 435 Some("discovery_hit") => { 436 let names = v 437 .get("names") 438 .and_then(Value::as_array) 439 .and_then(|a| { 440 a.iter() 441 .map(|n| n.as_str().map(str::to_string)) 442 .collect::>>() 443 }) 444 .ok_or_else(|| bad("discovery_hit needs names: [string]"))?; 445 Ok(Evidence::DiscoveryHit { 446 query: v.get("query").and_then(Value::as_str).map(str::to_string), 447 names, 448 }) 449 } 450 other => Err(ExpansionError(format!("unknown evidence kind: {other:?}"))), 451 } 452 } 453 } 454 455 /// The evidence or selection is unusable (refusals are recorded in the receipt, not returned). 456 #[derive(Debug, Clone, PartialEq, Eq, Error)] 457 #[error("{0}")] 458 pub struct ExpansionError(pub String); 459 460 /// Digest of the selection with `selection_digest` and `measure` removed. 461 pub fn selection_digest(sel: &Selection) -> String { 462 let mut v = serde_json::to_value(sel).unwrap_or(Value::Null); 463 if let Some(o) = v.as_object_mut() { 464 o.remove("selection_digest"); 465 o.remove("measure"); 466 } 467 interplane_core::digest(&v) 468 } 469 470 /// Names of EXCLUDED capabilities whose name or description contains `query` (ASCII 471 /// case-insensitive substring), sorted by name, at most `limit`. `runtime_disabled` exclusions are 472 /// never offered; an empty query gives `[]`. Pure. 473 pub fn discover( 474 catalog: &Catalog, 475 selection: &Selection, 476 query: &str, 477 limit: usize, 478 ) -> Vec { 479 let q = query.to_ascii_lowercase(); 480 if q.is_empty() { 481 return vec![]; 482 } 483 let mut hits: Vec = catalog 484 .capabilities 485 .iter() 486 .filter(|c| { 487 selection 488 .excluded 489 .iter() 490 .any(|e| e.name == c.name && e.reason != "runtime_disabled") 491 }) 492 .filter(|c| { 493 c.name.to_ascii_lowercase().contains(&q) 494 || c.description.to_ascii_lowercase().contains(&q) 495 }) 496 .map(|c| c.name.clone()) 497 .collect(); 498 hits.sort(); 499 hits.truncate(limit); 500 hits 501 } 502 503 /// Bounded evidence-based expansion; returns a new selection (the input is untouched). Bounds 504 /// recorded in `selector.expansion` win over `max_expansions` / `max_added_per_expansion`, which 505 /// win over the defaults (2 and 8); the effective bounds are recorded. `evidence_json` is the 506 /// evidence object whose digest goes into the receipt. Refusal reasons and order: spec/CROSSAXIS.md. 507 pub fn expand( 508 selection: &Selection, 509 catalog: &Catalog, 510 evidence_json: &Value, 511 max_expansions: Option, 512 max_added_per_expansion: Option, 513 ) -> Result { 514 let evidence = Evidence::from_value(evidence_json)?; 515 let cat_digest = catalog 516 .catalog_digest 517 .clone() 518 .unwrap_or_else(|| catalog.compute_digest()); 519 if selection.catalog_digest != cat_digest { 520 return Err(ExpansionError( 521 "selection was made against a different catalog".into(), 522 )); 523 } 524 let find = |n: &str| catalog.capabilities.iter().find(|c| c.name == n); 525 let (kind, candidates): (&str, Vec) = match &evidence { 526 Evidence::RequestedExcluded { 527 name, 528 include_domain_siblings, 529 } => { 530 let mut c = vec![name.clone()]; 531 if *include_domain_siblings { 532 if let Some(cap) = find(name) { 533 let mut sib: Vec = catalog 534 .capabilities 535 .iter() 536 .filter(|o| { 537 o.name != *name && o.domains.iter().any(|d| cap.domains.contains(d)) 538 }) 539 .map(|o| o.name.clone()) 540 .collect(); 541 sib.sort(); 542 c.extend(sib); 543 } 544 } 545 ("requested_excluded", c) 546 } 547 Evidence::DiscoveryHit { names, .. } => ("discovery_hit", names.clone()), 548 }; 549 550 let mut out = selection.clone(); 551 let parent = selection_digest(selection); 552 let rec = out.selector.expansion.clone(); 553 let max_exp = rec 554 .as_ref() 555 .map(|b| b.max_expansions) 556 .or(max_expansions) 557 .unwrap_or(DEFAULT_MAX_EXPANSIONS); 558 let max_add = rec 559 .as_ref() 560 .map(|b| b.max_added_per_expansion) 561 .or(max_added_per_expansion) 562 .unwrap_or(DEFAULT_MAX_ADDED_PER_EXPANSION); 563 out.selector.expansion = Some(ExpansionBounds { 564 max_expansions: max_exp, 565 max_added_per_expansion: max_add, 566 }); 567 568 let used = out 569 .expansions 570 .iter() 571 .filter(|e| !e.added.is_empty()) 572 .count() as u64; 573 let round = out.expansions.len() as u64 + 1; 574 let cap_limit = out.selector.max_capabilities; 575 let mut added: Vec = vec![]; 576 let mut refused: Vec = vec![]; 577 let mut seen: Vec<&String> = vec![]; 578 for name in &candidates { 579 if seen.contains(&name) { 580 continue; 581 } 582 seen.push(name); 583 let reason = if find(name).is_none() { 584 Some("not_in_catalog") 585 } else if out.selected.iter().any(|e| &e.name == name) { 586 Some("already_selected") 587 } else if out 588 .excluded 589 .iter() 590 .any(|e| &e.name == name && e.reason == "runtime_disabled") 591 { 592 Some("runtime_disabled") 593 } else if used >= max_exp { 594 Some("max_expansions") 595 } else if added.len() as u64 >= max_add { 596 Some("max_added_per_expansion") 597 } else if cap_limit.is_some_and(|m| (out.selected.len() + added.len()) as u64 >= m) { 598 Some("max_capabilities") 599 } else { 600 None 601 }; 602 match reason { 603 None => added.push(name.clone()), 604 Some(r) => refused.push(RefusedEntry { 605 name: name.clone(), 606 reason: r.into(), 607 }), 608 } 609 } 610 for name in &added { 611 if let Some(c) = find(name) { 612 out.selected.push(SelectedEntry { 613 name: c.name.clone(), 614 rule_id: format!("expansion:{round}"), 615 domains: c.domains.clone(), 616 extensions: Map::new(), 617 }); 618 } 619 } 620 out.excluded.retain(|e| !added.contains(&e.name)); 621 out.expansions.push(ExpansionEntry { 622 round, 623 reason: kind.into(), 624 evidence_digest: interplane_core::digest(evidence_json), 625 added, 626 refused, 627 }); 628 out.measure = None; 629 out.parent_digest = Some(parent); 630 out.selection_digest = None; 631 out.selection_digest = Some(selection_digest(&out)); 632 Ok(out) 633 } 634 635 #[cfg(test)] 636 mod tests { 637 use super::*; 638 use serde_json::json; 639 640 fn table() -> MappingTable { 641 MappingTable::from_value(json!({"runtime": "r", "table_version": "3", "rules": [ 642 {"id": "alias:filesystem.read", "kind": "alias", "from": {"namespace": "filesystem", "name": "read"}, "to": "read_file", 643 "renames": [{"from": "file", "to": "path"}]}, 644 {"id": "passthrough:read_file", "kind": "passthrough", "from": {"namespace": null, "name": "read_file"}, "to": "read_file"} 645 ]})) 646 .unwrap() 647 } 648 fn req(ns: Option<&str>, name: &str, args: Value) -> ToolRequest { 649 serde_json::from_value( 650 json!({"kind":"tool_request","request_id":"r1","tool":{"namespace":ns,"name":name}, 651 "arguments":args,"provenance":{"dialect":"openai","parser_version":"1.0.0"}}), 652 ) 653 .unwrap() 654 } 655 fn cap(name: &str, domains: &[&str], params: Value) -> CapabilityDescriptor { 656 serde_json::from_value( 657 json!({"name":name,"description":"d","parameters":params,"domains":domains}), 658 ) 659 .unwrap() 660 } 661 fn catalog() -> Catalog { 662 Catalog { 663 kind: interplane_core::CatalogKind, 664 runtime: "r".into(), 665 catalog_version: "1".into(), 666 catalog_digest: None, 667 capabilities: vec![ 668 cap("write", &["filesystem"], json!({})), 669 cap("send", &["email"], json!({})), 670 cap("read", &["filesystem", "code"], json!({})), 671 cap("bare", &[], json!({})), 672 ], 673 extensions: Map::new(), 674 } 675 } 676 677 #[test] 678 fn alias_passthrough_and_rename() { 679 let m = table() 680 .map(&req(Some("filesystem"), "read", json!({"file": "/a"}))) 681 .unwrap(); 682 assert_eq!( 683 ( 684 m.capability.as_str(), 685 m.mapping.rule_id.as_str(), 686 m.mapping.passthrough 687 ), 688 ("read_file", "alias:filesystem.read", false) 689 ); 690 assert_eq!(m.arguments["path"], json!("/a")); 691 let p = table().map(&req(None, "read_file", json!({}))).unwrap(); 692 assert!(p.mapping.passthrough); 693 assert_eq!(p.mapping.table_version, "3"); 694 } 695 #[test] 696 fn unknown_is_exact_not_fuzzy() { 697 assert_eq!( 698 table().map(&req(None, "read", json!({}))).unwrap_err(), 699 ErrorCode::UnknownCapability 700 ); 701 assert_eq!( 702 table() 703 .map(&req(Some("filesystem"), "READ", json!({}))) 704 .unwrap_err(), 705 ErrorCode::UnknownCapability 706 ); 707 } 708 #[test] 709 fn table_loading_negative_and_numeric_version() { 710 assert!(MappingTable::from_json_str("{}").is_err()); 711 assert!(MappingTable::from_json_str("not json").is_err()); 712 let t = 713 MappingTable::from_json_str(r#"{"runtime":"r","table_version":1,"rules":[]}"#).unwrap(); 714 assert_eq!(t.table_version, "1"); 715 let bad = json!({"runtime":"r","table_version":"1","rules":[{"id":"x","kind":"passthrough","from":{"name":"a"},"to":"b"}]}); 716 assert!(matches!( 717 MappingTable::from_value(bad), 718 Err(MappingError::BadPassthrough(_)) 719 )); 720 } 721 #[test] 722 fn coercion_records_keys() { 723 let c = cap( 724 "f", 725 &[], 726 json!({"type":"object","properties":{"n":{"type":"integer"},"x":{"type":"number"},"b":{"type":"boolean"},"s":{"type":"string"},"bad":{"type":"integer"}}}), 727 ); 728 let mut m = table() 729 .map(&req( 730 None, 731 "read_file", 732 json!({"n":"5","x":"2.5","b":"true","s":"7","bad":"abc","other":"1"}), 733 )) 734 .unwrap(); 735 let keys = coerce_arguments(&mut m, &c); 736 assert_eq!(keys, vec!["b", "n", "x"]); 737 assert_eq!(m.arguments["n"], json!(5)); 738 assert_eq!(m.arguments["x"], json!(2.5)); 739 assert_eq!(m.arguments["b"], json!(true)); 740 assert_eq!(m.arguments["s"], json!("7")); 741 assert_eq!(m.arguments["bad"], json!("abc")); 742 assert_eq!( 743 m.mapping.coerced, 744 Some(vec!["b".into(), "n".into(), "x".into()]) 745 ); 746 } 747 #[test] 748 fn select_domain_match_sorted_deterministic() { 749 let (s, caps) = select(&catalog(), &["filesystem".to_string()], None, &[]); 750 assert_eq!( 751 caps.iter().map(|c| c.name.as_str()).collect::>(), 752 ["read", "write"] 753 ); 754 assert_eq!(s.selector.name, "domain_match"); 755 let reasons: Vec<(&str, &str)> = s 756 .excluded 757 .iter() 758 .map(|e| (e.name.as_str(), e.reason.as_str())) 759 .collect(); 760 assert_eq!( 761 reasons, 762 [("bare", "no_domains"), ("send", "domain_mismatch")] 763 ); 764 let (s2, _) = select(&catalog(), &["filesystem".to_string()], None, &[]); 765 assert_eq!(s, s2); 766 } 767 #[test] 768 fn select_max_and_always_include() { 769 let (s, caps) = select( 770 &catalog(), 771 &["filesystem".to_string()], 772 Some(2), 773 &["send".to_string()], 774 ); 775 assert_eq!( 776 caps.iter().map(|c| c.name.as_str()).collect::>(), 777 ["send", "read"], 778 "pinned first, never truncated" 779 ); 780 assert!(s 781 .excluded 782 .iter() 783 .any(|e| e.name == "write" && e.reason == "max_capabilities")); 784 assert_eq!(s.selected[0].rule_id, "always_include"); 785 assert_eq!(s.selected[1].rule_id, "domain:filesystem"); 786 let (_, caps) = select(&catalog(), &[], None, &["bare".to_string()]); 787 assert_eq!(caps.len(), 1); 788 } 789 #[test] 790 fn measure_counts_bytes() { 791 let cat = catalog(); 792 let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); 793 measure(&mut s, &cat, &caps, |c| { 794 Value::Array(c.iter().map(|x| json!({"name": x.name})).collect()) 795 }); 796 let m = s.measure.unwrap(); 797 assert_eq!((m.full_count, m.selected_count), (Some(4), Some(1))); 798 assert!(m.selected_rendered_bytes < m.full_rendered_bytes); 799 assert_eq!( 800 m.selected_rendered_bytes, 801 Some(r#"[{"name":"send"}]"#.len() as u64) 802 ); 803 } 804 805 // ---- measurement 806 fn msgs() -> Value { 807 json!([{"role":"system","content":"s"},{"role":"user","content":"find the readme"}]) 808 } 809 #[test] 810 fn measure_bytes_are_wire_bytes_and_tokens_are_absent_without_a_counter() { 811 let cat = catalog(); 812 let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); 813 measure(&mut s, &cat, &caps, openai_tools_renderer); 814 let m = s.measure.clone().unwrap(); 815 assert_eq!( 816 m.rendered_bytes.unwrap().full, 817 canonicalize(&openai_tools_renderer(&cat.capabilities)).len() as u64 818 ); 819 assert_eq!(m.full_rendered_bytes, Some(m.rendered_bytes.unwrap().full)); 820 assert!(m.tokens.is_none()); 821 let v = serde_json::to_value(&s).unwrap(); 822 assert!(v["measure"].get("tokens").is_none() && v["measure"].get("full_tokens").is_none()); 823 assert!(v.get("always_include").is_none()); 824 assert_eq!( 825 v["selector"], 826 json!({"name": "domain_match", "version": "1"}) 827 ); 828 } 829 #[test] 830 fn estimated_tokens_exact_and_differential() { 831 let cat = catalog(); 832 let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); 833 let m = msgs(); 834 measure_tokens( 835 &mut s, 836 &cat, 837 &caps, 838 openai_tools_renderer, 839 Some((&EstimatedTokens, &m, BenchTotals::default())), 840 ); 841 let t = s.measure.unwrap().tokens.unwrap(); 842 let est = |v: &Value| (canonicalize(v).len() as u64).div_ceil(4); 843 assert_eq!( 844 (t.unit.as_str(), t.source.as_str()), 845 ("tokens_estimated", ESTIMATOR_SOURCE) 846 ); 847 assert_eq!(t.base_context, est(&m)); 848 let (full_t, sel_t) = ( 849 est(&openai_tools_renderer(&cat.capabilities)), 850 est(&openai_tools_renderer(&caps)), 851 ); 852 assert_eq!( 853 (t.tool_schema.full, t.tool_schema.selected), 854 (full_t, sel_t) 855 ); 856 assert_eq!(t.first_turn_prompt.full, t.base_context + full_t); 857 assert!(TOKEN_UNITS.contains(&"bytes") && t.all_rounds_prompt.is_none()); 858 // the Python implementation computes the same numbers from the same inputs 859 assert_eq!(EstimatedTokens.count_prompt(&json!([]), None), 1); 860 assert_eq!(BytesOnly.count_prompt(&json!([]), Some(&json!({}))), 4); 861 } 862 863 // ---- expansion 864 fn email_sel(max: Option) -> (Catalog, Selection) { 865 let cat = catalog(); 866 let (s, _) = select(&cat, &["email".to_string()], max, &[]); 867 (cat, s) 868 } 869 fn big() -> Catalog { 870 let mut c = catalog(); 871 c.capabilities.push(cap("list", &["filesystem"], json!({}))); 872 c.capabilities 873 .push(cap("trash", &["filesystem"], json!({}))); 874 c 875 } 876 fn rx(name: &str) -> Value { 877 json!({"kind": "requested_excluded", "name": name}) 878 } 879 #[test] 880 fn expand_adds_records_and_chains_digests() { 881 let (cat, sel) = email_sel(None); 882 let before = sel.clone(); 883 let out = expand(&sel, &cat, &rx("write"), None, None).unwrap(); 884 assert_eq!(sel, before, "input untouched"); 885 let names: Vec<_> = out.selected.iter().map(|e| e.name.as_str()).collect(); 886 assert_eq!(names, ["send", "write"]); 887 assert_eq!(out.selected[1].rule_id, "expansion:1"); 888 assert!(!out.excluded.iter().any(|e| e.name == "write")); 889 let e = &out.expansions[0]; 890 assert_eq!( 891 (e.round, e.reason.as_str(), e.added.clone()), 892 (1, "requested_excluded", vec!["write".to_string()]) 893 ); 894 assert_eq!(e.evidence_digest, interplane_core::digest(&rx("write"))); 895 assert_eq!(out.parent_digest, Some(selection_digest(&sel))); 896 assert_eq!(out.selection_digest, Some(selection_digest(&out))); 897 assert_eq!( 898 out.selector.expansion, 899 Some(ExpansionBounds { 900 max_expansions: 2, 901 max_added_per_expansion: 8 902 }) 903 ); 904 let again = expand(&sel, &cat, &rx("write"), None, None).unwrap(); 905 assert_eq!( 906 canonicalize(&serde_json::to_value(&again).unwrap()), 907 canonicalize(&serde_json::to_value(&out).unwrap()) 908 ); 909 let out2 = expand(&out, &cat, &rx("read"), None, None).unwrap(); 910 assert_eq!(out2.parent_digest, out.selection_digest); 911 assert_eq!( 912 out2.expansions.iter().map(|e| e.round).collect::>(), 913 [1, 2] 914 ); 915 } 916 #[test] 917 fn expand_drops_measure_and_rejects_a_foreign_catalog_and_bad_evidence() { 918 let cat = catalog(); 919 let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); 920 measure(&mut s, &cat, &caps, openai_tools_renderer); 921 assert!(expand(&s, &cat, &rx("read"), None, None) 922 .unwrap() 923 .measure 924 .is_none()); 925 let mut other = catalog(); 926 other.capabilities.pop(); 927 other.catalog_digest = None; 928 assert!(expand(&s, &other, &rx("read"), None, None).is_err()); 929 for bad in [ 930 json!({}), 931 json!({"kind": "x"}), 932 json!({"kind": "requested_excluded"}), 933 json!({"kind": "discovery_hit"}), 934 ] { 935 assert!(expand(&s, &cat, &bad, None, None).is_err()); 936 } 937 } 938 #[test] 939 fn expand_refusal_reasons_and_order() { 940 let cat = catalog(); 941 let (_, sel) = email_sel(Some(2)); 942 let ev = json!({"kind": "discovery_hit", "names": ["nope", "send", "read", "write"]}); 943 let last = expand(&sel, &cat, &ev, None, None) 944 .unwrap() 945 .expansions 946 .pop() 947 .unwrap(); 948 assert_eq!(last.added, ["read"]); 949 let r: Vec<_> = last 950 .refused 951 .iter() 952 .map(|r| (r.name.as_str(), r.reason.as_str())) 953 .collect(); 954 assert_eq!( 955 r, 956 [ 957 ("nope", "not_in_catalog"), 958 ("send", "already_selected"), 959 ("write", "max_capabilities") 960 ] 961 ); 962 // max_added_per_expansion 963 let cat = big(); 964 let (s2, _) = select(&cat, &["email".to_string()], None, &[]); 965 let ev = json!({"kind": "discovery_hit", "names": ["read", "list", "trash"]}); 966 let last = expand(&s2, &cat, &ev, None, Some(2)) 967 .unwrap() 968 .expansions 969 .pop() 970 .unwrap(); 971 assert_eq!(last.added, ["read", "list"]); 972 assert_eq!(last.refused[0].reason, "max_added_per_expansion"); 973 // max_expansions: refused rounds are recorded, count in numbering, and add nothing 974 let mut s = s2; 975 for n in ["read", "list"] { 976 s = expand(&s, &cat, &rx(n), None, None).unwrap(); 977 } 978 let s3 = expand(&s, &cat, &rx("trash"), Some(99), None).unwrap(); 979 let last = s3.expansions.last().unwrap(); 980 assert_eq!((last.round, last.added.len()), (3, 0)); 981 assert_eq!(last.refused[0].reason, "max_expansions"); 982 assert!( 983 !s3.selected.iter().any(|e| e.name == "trash"), 984 "recorded bounds win over arguments" 985 ); 986 } 987 #[test] 988 fn expand_siblings_runtime_disabled_and_discover() { 989 let (cat, sel) = email_sel(None); 990 let ev = 991 json!({"kind": "requested_excluded", "name": "write", "include_domain_siblings": true}); 992 let last = expand(&sel, &cat, &ev, None, None) 993 .unwrap() 994 .expansions 995 .pop() 996 .unwrap(); 997 assert_eq!(last.added, ["write", "read"]); 998 let mut dis = sel.clone(); 999 dis.excluded 1000 .iter_mut() 1001 .find(|e| e.name == "read") 1002 .unwrap() 1003 .reason = "runtime_disabled".into(); 1004 assert!(!discover(&cat, &dis, "d", 8).contains(&"read".to_string())); 1005 let last = expand(&dis, &cat, &rx("read"), None, None) 1006 .unwrap() 1007 .expansions 1008 .pop() 1009 .unwrap(); 1010 assert_eq!(last.refused[0].reason, "runtime_disabled"); 1011 // discover: ASCII case-insensitive over name and description, sorted, capped, excluded only 1012 let cat = big(); 1013 let (s, _) = select(&cat, &["email".to_string()], None, &[]); 1014 assert_eq!( 1015 discover(&cat, &s, "R", 8), 1016 ["bare", "read", "trash", "write"] 1017 ); 1018 assert_eq!( 1019 discover(&cat, &s, "D", 8), 1020 ["bare", "list", "read", "trash", "write"] 1021 ); 1022 assert_eq!(discover(&cat, &s, "d", 2), ["bare", "list"]); 1023 assert!(discover(&cat, &s, "send", 8).is_empty() && discover(&cat, &s, "", 8).is_empty()); 1024 } 1025 }