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-crossveil/src/pipeline.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-crossveil / src / pipeline.rs` 1487 lines ยท 56419 bytes Raw Blame History 1 //! The reference pipeline: admit -> map -> decide -> execute -> render. 2 use std::collections::{HashMap, HashSet, VecDeque}; 3 use std::panic::{catch_unwind, AssertUnwindSafe}; 4 5 use interplane_core::*; 6 use interplane_crossaxis::{coerce_arguments, MappingTable}; 7 use interplane_lenshift::{DialectRegistry, ParseContext, RejectedCall}; 8 use serde::{Deserialize, Serialize}; 9 use serde_json::{json, Map, Value}; 10 11 use crate::{CallContext, RuntimeAuthority}; 12 13 /// Deterministic per-request log entry (no timestamps, no durations). 14 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 15 pub struct ObservedRecord { 16 pub request_id: Option, 17 pub stage: String, 18 pub decision: Option, 19 pub status: String, 20 pub error_code: Option, 21 pub decide_invoked: bool, 22 pub execute_invoked: bool, 23 pub result_digest: String, 24 } 25 26 /// Everything one model turn produced. 27 #[derive(Debug, Clone)] 28 pub struct TurnOutcome { 29 pub turn: u64, 30 pub intents: Vec, 31 pub rejected: Vec, 32 pub records: Vec, 33 pub results: Vec, 34 pub rendered: Vec, 35 pub text: String, 36 /// `tool_request`, `no_tool` or `rejected` (conformance README rule 4). 37 pub outcome: String, 38 /// Set when the whole turn was refused (`unsupported_dialect`). 39 pub error_code: Option, 40 pub partial: bool, 41 } 42 43 /// Why a host continuation or cancel was refused: nothing changed, nothing ran. 44 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 45 pub enum Refusal { 46 /// No pending approval for the call: unknown request, already executed, denied or 47 /// cancelled, a second continuation, or a pipeline created after a restart. 48 NoPendingApproval, 49 /// The trace was closed by the host (`close_trace`). 50 SessionClosed, 51 } 52 53 impl Refusal { 54 /// The reason string pinned in CORE.md (verdict `continuations[].reason`). 55 pub fn as_str(self) -> &'static str { 56 match self { 57 Refusal::NoPendingApproval => "no_pending_approval", 58 Refusal::SessionClosed => "session_closed", 59 } 60 } 61 } 62 63 /// Read-only view of an approval entry, for the host (cut A2). 64 #[derive(Debug, Clone)] 65 pub struct PendingApproval { 66 pub request_id: String, 67 pub approval_id: String, 68 pub expires_at: Option, 69 /// Digest of the `capability_request` exactly as it was sent to `decide`. 70 pub request_digest: String, 71 pub capability_request: CapabilityRequest, 72 pub state: State, 73 } 74 75 /// Digest that binds an approval to its exact `capability_request` (JCS, `sha256:`). 76 pub fn capability_request_digest(cap: &CapabilityRequest) -> String { 77 digest(&serde_json::to_value(cap).unwrap_or(Value::Null)) 78 } 79 80 /// `YYYY-MM-DDTHH:MM:SSZ` (UTC, fixed width) with in-range fields, so string order is time order. 81 fn utc_shape(s: &str) -> bool { 82 let b = s.as_bytes(); 83 if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' { 84 return false; 85 } 86 if b[13] != b':' || b[16] != b':' || b[19] != b'Z' { 87 return false; 88 } 89 let num = |i: usize, n: usize| -> Option { 90 let d = &b[i..i + n]; 91 d.iter() 92 .all(u8::is_ascii_digit) 93 .then(|| d.iter().fold(0, |a, c| a * 10 + u32::from(c - b'0'))) 94 }; 95 matches!( 96 ( 97 num(5, 2), 98 num(8, 2), 99 num(11, 2), 100 num(14, 2), 101 num(17, 2), 102 num(0, 4) 103 ), 104 ( 105 Some(1..=12), 106 Some(1..=31), 107 Some(0..=23), 108 Some(0..=59), 109 Some(0..=59), 110 Some(_) 111 ) 112 ) 113 } 114 115 /// Expired when `now >= expires_at`. A value that is not of the exact shape counts as expired. 116 fn approval_expired(expires_at: &str, now: &str) -> bool { 117 !utc_shape(expires_at) || !utc_shape(now) || now >= expires_at 118 } 119 120 /// A request waiting for the host (REQUIRES_APPROVAL), or what became of it. Memory only. 121 struct PendingEntry { 122 lc: Lifecycle, 123 cap: CapabilityRequest, 124 ctx: CallContext, 125 approval_id: String, 126 expires_at: Option, 127 request_digest: String, 128 catalog_digest: String, 129 } 130 131 /// The pipeline. Holds no decision memory: every request is decided by the runtime. 132 pub struct Pipeline<'a> { 133 pub registry: DialectRegistry, 134 pub table: MappingTable, 135 runtime: &'a mut dyn RuntimeAuthority, 136 pub limits: Limits, 137 pub ledger: RequestLedger, 138 /// RelayLine events, in order. 139 pub events: Vec, 140 /// Prefix of generated message ids: `--`. 141 pub message_prefix: String, 142 pub timestamp: String, 143 seq: HashMap, 144 turn: Option, 145 /// Per trace: every input that has been placed in front of the model, in order (cut P3). 146 inputs: HashMap>, 147 /// Approval entries by `(trace_id, request_id)` (cut A1/A2). Host-only: only the continuation 148 /// and cancel calls below read or change them, and a new pipeline starts empty. 149 pending: HashMap<(String, String), PendingEntry>, 150 /// The trace each entry of `events` belongs to (same length as `events`). 151 event_traces: Vec, 152 /// Traces closed by the host (session state limits): the last `max_closed_traces` in close 153 /// order, exactly (`closed_order` keeps the order). Older ones are retired into `retired`. 154 closed: HashSet, 155 closed_order: VecDeque, 156 retired: Option, 157 } 158 159 /// Fixed-size filter of retired closed-trace ids (CORE.md, "Closing a trace"). Positions: the 160 /// first four big-endian 32-bit words of sha256(trace id as UTF-8), each modulo `bits`. It never 161 /// forgets an added id; it can match an id never added (a false refusal, fail closed). With 162 /// `bits` 0 it matches every id once anything was added. 163 #[derive(Debug, Clone)] 164 struct RetiredFilter { 165 bits: usize, 166 data: Vec, 167 count: u64, 168 } 169 170 impl RetiredFilter { 171 fn new(bits: usize) -> Self { 172 Self { 173 bits, 174 data: vec![0; bits.div_ceil(8)], 175 count: 0, 176 } 177 } 178 179 fn positions(&self, trace: &str) -> [usize; 4] { 180 let hex = digest_bytes(trace.as_bytes()); 181 let hex = &hex["sha256:".len()..]; 182 let mut out = [0usize; 4]; 183 for (i, slot) in out.iter_mut().enumerate() { 184 let word = u32::from_str_radix(&hex[8 * i..8 * i + 8], 16).unwrap_or(0); 185 *slot = (word as usize) % self.bits; 186 } 187 out 188 } 189 190 fn add(&mut self, trace: &str) { 191 self.count += 1; 192 if self.bits > 0 { 193 for pos in self.positions(trace) { 194 self.data[pos >> 3] |= 1 << (pos & 7); 195 } 196 } 197 } 198 199 fn matches(&self, trace: &str) -> bool { 200 if self.bits == 0 { 201 return self.count > 0; 202 } 203 self.positions(trace) 204 .iter() 205 .all(|&pos| self.data[pos >> 3] & (1 << (pos & 7)) != 0) 206 } 207 } 208 209 /// Position in the trust order; `unknown` and anything unrecognized rank as `external_untrusted`. 210 fn trust_rank(t: &TrustLevel) -> u8 { 211 match t { 212 TrustLevel::TrustedRuntime => 3, 213 TrustLevel::UserSupplied => 2, 214 TrustLevel::WorkspaceUntrusted => 1, 215 _ => 0, 216 } 217 } 218 219 fn rank_trust(rank: u8) -> TrustLevel { 220 match rank { 221 3 => TrustLevel::TrustedRuntime, 222 2 => TrustLevel::UserSupplied, 223 1 => TrustLevel::WorkspaceUntrusted, 224 _ => TrustLevel::ExternalUntrusted, 225 } 226 } 227 228 fn rec( 229 request_id: Option<&str>, 230 stage: State, 231 decision: Option<&str>, 232 r: &ToolResult, 233 decide: bool, 234 exec: bool, 235 ) -> ObservedRecord { 236 ObservedRecord { 237 request_id: request_id.map(str::to_string), 238 stage: stage.name().to_string(), 239 decision: decision.map(str::to_string), 240 status: r.status.as_str().to_string(), 241 error_code: r.error.as_ref().map(|e| e.code.as_str().to_string()), 242 decide_invoked: decide, 243 execute_invoked: exec, 244 result_digest: r.result_digest(), 245 } 246 } 247 248 fn valid_rid(v: &Value) -> Option { 249 v.pointer("/payload/request_id") 250 .and_then(Value::as_str) 251 .filter(|s| is_valid_id(s)) 252 .map(str::to_string) 253 } 254 255 /// Name the first field that makes an envelope malformed (for the pinned message). 256 fn malformed_field(v: &Value) -> String { 257 const REQUIRED: [&str; 7] = [ 258 "interplane_version", 259 "message_id", 260 "trace_id", 261 "timestamp", 262 "source", 263 "destination", 264 "payload", 265 ]; 266 for k in REQUIRED { 267 if v.get(k).is_none() { 268 return k.into(); 269 } 270 } 271 for k in ["message_id", "trace_id"] { 272 if !v[k].as_str().is_some_and(is_valid_id) { 273 return k.into(); 274 } 275 } 276 if let Some(p) = v.get("parent_id").filter(|p| !p.is_null()) { 277 if !p.as_str().is_some_and(is_valid_id) { 278 return "parent_id".into(); 279 } 280 } 281 for k in ["source", "destination"] { 282 if serde_json::from_value::(v[k].clone()).is_err() { 283 return k.into(); 284 } 285 } 286 if !v["timestamp"].is_string() { 287 return "timestamp".into(); 288 } 289 let Some(p) = v["payload"].as_object() else { 290 return "payload".into(); 291 }; 292 if !p.get("kind").and_then(Value::as_str).is_some_and(|k| { 293 [ 294 "tool_request", 295 "capability_request", 296 "decision", 297 "result", 298 "event", 299 "catalog", 300 "selection", 301 "probe_report", 302 ] 303 .contains(&k) 304 }) { 305 return "payload.kind".into(); 306 } 307 if p["kind"] == "tool_request" { 308 for k in ["request_id", "tool", "arguments", "provenance"] { 309 if !p.contains_key(k) { 310 return format!("payload.{k}"); 311 } 312 } 313 if !v["payload"]["request_id"].as_str().is_some_and(is_valid_id) { 314 return "payload.request_id".into(); 315 } 316 } 317 "payload".into() 318 } 319 320 impl<'a> Pipeline<'a> { 321 pub fn new( 322 registry: DialectRegistry, 323 table: MappingTable, 324 runtime: &'a mut dyn RuntimeAuthority, 325 limits: Limits, 326 ledger: RequestLedger, 327 ) -> Self { 328 Self { 329 registry, 330 table, 331 runtime, 332 limits, 333 ledger, 334 events: vec![], 335 message_prefix: "m".into(), 336 timestamp: "2026-01-01T00:00:00Z".into(), 337 seq: HashMap::new(), 338 turn: None, 339 inputs: HashMap::new(), 340 pending: HashMap::new(), 341 event_traces: vec![], 342 closed: HashSet::new(), 343 closed_order: VecDeque::new(), 344 retired: None, 345 } 346 } 347 348 // -- session state limits (CORE.md) ---------------------------------------------- 349 /// A trace is held when the pipeline keeps any state for it. 350 fn holds(&self, trace: &str) -> bool { 351 self.ledger.holds(trace) 352 || self.inputs.get(trace).is_some_and(|v| !v.is_empty()) 353 || self.seq.contains_key(trace) 354 || self.pending.keys().any(|(t, _)| t == trace) 355 } 356 357 fn held_count(&self) -> usize { 358 let mut held: HashSet<&str> = self.ledger.traces().map(String::as_str).collect(); 359 held.extend( 360 self.inputs 361 .iter() 362 .filter(|(_, v)| !v.is_empty()) 363 .map(|(t, _)| t.as_str()), 364 ); 365 held.extend(self.seq.keys().map(String::as_str)); 366 held.extend(self.pending.keys().map(|(t, _)| t.as_str())); 367 held.len() 368 } 369 370 /// True for a closed trace: in the window of recent closed ids, or matched by the retirement 371 /// filter (which may also match a trace that was never used: refused, fail closed). A trace 372 /// that holds state is never matched by the filter (a retired id can never hold state again). 373 fn is_closed(&self, trace: &str) -> bool { 374 self.closed.contains(trace) 375 || self 376 .retired 377 .as_ref() 378 .is_some_and(|f| !self.holds(trace) && f.matches(trace)) 379 } 380 381 /// `(closed ids held exactly, bytes of the retirement filter)`: the state closing traces keeps. 382 /// Bounded by `(max_closed_traces, ceil(retired_filter_bits / 8))`. 383 pub fn closed_trace_state(&self) -> (usize, usize) { 384 ( 385 self.closed.len(), 386 self.retired.as_ref().map_or(0, |f| f.data.len()), 387 ) 388 } 389 390 /// False for a closed trace, and for a new trace while `max_traces` are held. 391 fn can_hold(&self, trace: &str) -> bool { 392 if self.is_closed(trace) { 393 return false; 394 } 395 self.holds(trace) || self.held_count() < self.limits.max_traces 396 } 397 398 /// Reserve the worst-case retained output before admitting any runtime work. A 399 /// saturated trace is closed, not allowed to execute with an incomplete exposure ledger. 400 fn reserve_retained(&mut self, trace: &str, inputs: usize, events: usize) -> bool { 401 if self.is_closed(trace) { 402 return false; 403 } 404 if !self.holds(trace) && self.held_count() >= self.limits.max_traces { 405 return true; // downstream max_traces refusal retains no state 406 } 407 let event_count = self 408 .seq 409 .get(trace) 410 .map_or(0, |n| usize::try_from(*n).unwrap_or(usize::MAX)); 411 if self.inputs(trace).len().saturating_add(inputs) > self.limits.max_inputs_per_trace 412 || event_count.saturating_add(events) > self.limits.max_events_per_trace 413 { 414 self.close_trace(trace); 415 return false; 416 } 417 true 418 } 419 420 fn closed_refusal(trace: &str) -> (ErrorCode, String) { 421 (ErrorCode::SessionClosed, format!("session closed: {trace}")) 422 } 423 424 /// `(code, message)` when a further message on the trace is refused. 425 fn message_refusal(&self, trace: &str) -> Option<(ErrorCode, String)> { 426 if self.is_closed(trace) { 427 return Some(Self::closed_refusal(trace)); 428 } 429 let limit = if !self.holds(trace) && self.held_count() >= self.limits.max_traces { 430 "max_traces" 431 } else if self.ledger.message_count(trace) >= self.limits.max_messages_per_trace { 432 "max_messages_per_trace" 433 } else { 434 return None; 435 }; 436 Some(( 437 ErrorCode::SessionLimitExceeded, 438 format!("session limit exceeded: {limit}"), 439 )) 440 } 441 442 /// `(code, message)` when a further request id on the trace is refused. 443 fn request_refusal(&self, trace: &str) -> Option<(ErrorCode, String)> { 444 if self.is_closed(trace) { 445 return Some(Self::closed_refusal(trace)); 446 } 447 if self.ledger.request_count(trace) >= self.limits.max_requests_per_trace { 448 return Some(( 449 ErrorCode::SessionLimitExceeded, 450 "session limit exceeded: max_requests_per_trace".to_string(), 451 )); 452 } 453 None 454 } 455 456 /// Record a request id for a call that is already refused (`run_turn`'s malformed and 457 /// over-the-turn-limit calls), unless that would break a session limit. 458 fn note_refused_request(&mut self, trace: &str, request_id: &str) { 459 if self.request_refusal(trace).is_none() && self.can_hold(trace) { 460 let _ = self.ledger.note_request(trace, request_id); 461 } 462 } 463 464 /// Host-only: drop everything the pipeline keeps for the trace (ledger ids, inputs, approval 465 /// entries, event sequence, events) and refuse any later message, request, input or 466 /// continuation on it with `session_closed`. Closing a trace that holds no state (unknown, 467 /// already closed or retired) is a no-op and records nothing. The id joins the window of the 468 /// last `max_closed_traces` closed ids; the oldest id leaving the window is retired into the 469 /// filter, so it stays refused. Not reachable from model output or an admitted envelope. 470 pub fn close_trace(&mut self, trace: &str) { 471 if self.is_closed(trace) || !self.holds(trace) { 472 return; 473 } 474 self.closed.insert(trace.to_string()); 475 self.closed_order.push_back(trace.to_string()); 476 while self.closed_order.len() > self.limits.max_closed_traces { 477 let Some(oldest) = self.closed_order.pop_front() else { 478 break; 479 }; 480 self.closed.remove(&oldest); 481 let bits = self.limits.retired_filter_bits; 482 self.retired 483 .get_or_insert_with(|| RetiredFilter::new(bits)) 484 .add(&oldest); 485 } 486 self.ledger.forget(trace); 487 self.inputs.remove(trace); 488 self.seq.remove(trace); 489 self.pending.retain(|(t, _), _| t != trace); 490 if self.event_traces.len() == self.events.len() { 491 let mut keep = self.event_traces.iter().map(|t| t != trace); 492 self.events.retain(|_| keep.next().unwrap_or(true)); 493 self.event_traces.retain(|t| t != trace); 494 } 495 } 496 497 /// Host-only: register an input (user request, workspace file, memory hit, skill, ...) placed 498 /// in front of the model on `rec.trace_id`, before the turn that can see it. This is not 499 /// reachable from model output or from an admitted envelope: those paths never call it. 500 /// Refuses a duplicate `input_id` on the trace. 501 pub fn register_input(&mut self, rec: InputRecord) -> Result<(), String> { 502 if self.is_closed(&rec.trace_id) { 503 return Err(format!("session closed: {}", rec.trace_id)); 504 } 505 let held = self.inputs.get(&rec.trace_id).map_or(0, Vec::len); 506 if self 507 .inputs 508 .get(&rec.trace_id) 509 .is_some_and(|l| l.iter().any(|r| r.input_id == rec.input_id)) 510 { 511 return Err(format!("duplicate input_id: {}", rec.input_id)); 512 } 513 if held >= self.limits.max_inputs_per_trace { 514 return Err("session limit exceeded: max_inputs_per_trace".to_string()); 515 } 516 if !self.holds(&rec.trace_id) && self.held_count() >= self.limits.max_traces { 517 return Err("session limit exceeded: max_traces".to_string()); 518 } 519 self.inputs 520 .entry(rec.trace_id.clone()) 521 .or_default() 522 .push(rec); 523 Ok(()) 524 } 525 526 /// The trace's input ledger, in registration order. 527 pub fn inputs(&self, trace: &str) -> &[InputRecord] { 528 self.inputs.get(trace).map(Vec::as_slice).unwrap_or(&[]) 529 } 530 531 /// Exposure computed from the ledger. Fails closed: an empty ledger means the host told us 532 /// nothing about what the model saw, an input with unknown trust ranks as `external_untrusted`, 533 /// and an input derived from an id the ledger does not hold counts as `external_untrusted`. 534 pub fn exposure_for(&self, trace: &str) -> Exposure { 535 let ledger = self.inputs(trace); 536 let mut floor = if ledger.is_empty() { 0 } else { 3 }; 537 for r in ledger { 538 let traced = r 539 .derived_from 540 .iter() 541 .all(|d| ledger.iter().any(|o| &o.input_id == d)); 542 floor = floor.min(if traced { trust_rank(&r.trust) } else { 0 }); 543 } 544 Exposure { 545 inputs: ledger.iter().map(|r| r.input_id.clone()).collect(), 546 floor: rank_trust(floor), 547 extensions: Map::new(), 548 } 549 } 550 551 /// Record a rendered result as an input of the trace (`parent_id` = its request id). The 552 /// trust and kind are the runtime's normalized provenance; absent means `unknown`. 553 fn record_result(&mut self, trace: &str, r: &ToolResult, rendered: &Value) { 554 self.push_result_input(trace, r, digest(rendered)); 555 } 556 557 fn push_result_input(&mut self, trace: &str, r: &ToolResult, content_digest: String) { 558 if !self.can_hold(trace) { 559 return; // closed, or refused as a further trace: no state may grow for it 560 } 561 if self.inputs(trace).len() >= self.limits.max_inputs_per_trace { 562 self.close_trace(trace); 563 return; 564 } 565 let prov = r.provenance.as_ref(); 566 let ledger = self.inputs.entry(trace.to_string()).or_default(); 567 let mut n = ledger 568 .iter() 569 .filter(|o| o.input_id.starts_with("in-auto-")) 570 .count(); 571 while ledger.iter().any(|o| o.input_id == format!("in-auto-{n}")) { 572 n += 1; 573 } 574 ledger.push(InputRecord { 575 input_id: format!("in-auto-{n}"), 576 content_kind: prov 577 .and_then(|p| p.content_kind.clone()) 578 .unwrap_or(ContentKind::Undetermined), 579 trust: prov 580 .and_then(|p| p.trust.clone()) 581 .unwrap_or(TrustLevel::Undetermined), 582 source: Party::new("runtime", self.runtime.runtime_id()), 583 origin: format!("runtime:{}", self.runtime.runtime_id()), 584 content_digest, 585 trace_id: trace.to_string(), 586 parent_id: r.request_id.clone(), 587 derived_from: vec![], 588 extensions: Map::new(), 589 }); 590 } 591 592 fn emit(&mut self, trace: &str, event: EventKind, request_id: Option<&str>) { 593 if !self.can_hold(trace) { 594 return; // closed, or refused as a further trace: nothing is recorded for it 595 } 596 if self 597 .seq 598 .get(trace) 599 .is_some_and(|n| *n >= self.limits.max_events_per_trace as u64) 600 { 601 return; // reservation already refused execution; never retain an overflow event 602 } 603 self.event_traces.push(trace.to_string()); 604 let s = self.seq.entry(trace.to_string()).or_insert(0); 605 let seq = *s; 606 *s += 1; 607 self.events.push(Event { 608 kind: EventMsgKind, 609 event, 610 seq, 611 request_id: request_id.map(str::to_string), 612 turn: self.turn, 613 payload: None, 614 extensions: Map::new(), 615 }); 616 } 617 618 fn emit_outcome(&mut self, trace: &str, r: &ToolResult) { 619 let ev = match r.status { 620 ResultStatus::Ok | ResultStatus::Denied | ResultStatus::RequiresApproval => { 621 EventKind::ToolResult 622 } 623 _ => EventKind::ToolError, 624 }; 625 let rid = r.request_id.clone(); 626 self.emit(trace, ev, rid.as_deref()); 627 } 628 629 /// A refusal before the runtime was reached: provenance is all null. 630 fn reject( 631 &mut self, 632 trace: &str, 633 rid: Option<&str>, 634 code: ErrorCode, 635 msg: &str, 636 ) -> (ToolResult, ObservedRecord) { 637 let r = ToolResult::failed(rid, ResultStatus::Rejected, code, msg); 638 let o = rec(rid, State::Rejected, None, &r, false, false); 639 self.emit_outcome(trace, &r); 640 (r, o) 641 } 642 643 /// Admit a raw JSON envelope: version, replay, duplicate, size, then map/decide/execute. 644 pub fn admit_value(&mut self, v: &Value) -> (ToolResult, ObservedRecord) { 645 let trace = v 646 .get("trace_id") 647 .and_then(Value::as_str) 648 .unwrap_or("unknown") 649 .to_string(); 650 let peek = valid_rid(v); 651 if !self.reserve_retained(&trace, 0, 5) && !self.is_closed(&trace) { 652 return self.reject( 653 &trace, 654 peek.as_deref(), 655 ErrorCode::SessionLimitExceeded, 656 "session limit exceeded: retained state", 657 ); 658 } 659 // Version first, before anything else is read. 660 match v 661 .get("interplane_version") 662 .and_then(Value::as_str) 663 .map(ProtocolVersion::parse) 664 { 665 Some(Ok(ver)) => { 666 if ver.check_major().is_err() { 667 let msg = format!("unsupported protocol major version: {}", ver.major); 668 return self.reject(&trace, None, ErrorCode::UnsupportedVersion, &msg); 669 } 670 } 671 _ => { 672 return self.reject( 673 &trace, 674 peek.as_deref(), 675 ErrorCode::MalformedEnvelope, 676 "malformed envelope: interplane_version", 677 ) 678 } 679 } 680 let env: Envelope = match serde_json::from_value(v.clone()) { 681 Ok(e) => e, 682 Err(_) => { 683 let msg = format!("malformed envelope: {}", malformed_field(v)); 684 return self.reject(&trace, peek.as_deref(), ErrorCode::MalformedEnvelope, &msg); 685 } 686 }; 687 self.admit_checked(&env, Some(v), None) 688 } 689 690 /// Admit a parsed envelope. Order: version, structure, replay, duplicate, size, map, decide, execute. 691 pub fn admit_envelope(&mut self, env: &Envelope) -> (ToolResult, ObservedRecord) { 692 if !self.reserve_retained(&env.trace_id, 0, 5) && !self.is_closed(&env.trace_id) { 693 return self.reject( 694 &env.trace_id, 695 None, 696 ErrorCode::SessionLimitExceeded, 697 "session limit exceeded: retained state", 698 ); 699 } 700 self.admit_checked(env, None, None) 701 } 702 703 fn admit_checked( 704 &mut self, 705 env: &Envelope, 706 raw: Option<&Value>, 707 turn_exposure: Option<&Exposure>, 708 ) -> (ToolResult, ObservedRecord) { 709 let trace = env.trace_id.clone(); 710 let raw_v = match raw { 711 Some(v) => v.clone(), 712 None => serde_json::to_value(env).unwrap_or(Value::Null), 713 }; 714 let peek = valid_rid(&raw_v); 715 match ProtocolVersion::parse(&env.interplane_version) { 716 Ok(v) if v.check_major().is_ok() => {} 717 Ok(v) => { 718 let msg = format!("unsupported protocol major version: {}", v.major); 719 return self.reject(&trace, None, ErrorCode::UnsupportedVersion, &msg); 720 } 721 Err(_) => { 722 return self.reject( 723 &trace, 724 peek.as_deref(), 725 ErrorCode::MalformedEnvelope, 726 "malformed envelope: interplane_version", 727 ) 728 } 729 } 730 if let Err(code) = validate_envelope(env) { 731 let msg = if code == ErrorCode::MalformedToolCall { 732 "arguments is not an object".to_string() 733 } else { 734 format!("malformed envelope: {}", malformed_field(&raw_v)) 735 }; 736 return self.reject(&trace, peek.as_deref(), code, &msg); 737 } 738 if self.ledger.has_message(&trace, &env.message_id) { 739 let msg = format!("replayed message_id: {}", env.message_id); 740 return self.reject(&trace, peek.as_deref(), ErrorCode::ReplayedMessage, &msg); 741 } 742 if let Some((code, msg)) = self.message_refusal(&trace) { 743 return self.reject(&trace, peek.as_deref(), code, &msg); 744 } 745 let _ = self.ledger.note_message(&trace, &env.message_id); 746 let mut req = match env.parse_payload() { 747 Ok(Payload::ToolRequest(t)) => t, 748 _ => { 749 return self.reject( 750 &trace, 751 peek.as_deref(), 752 ErrorCode::MalformedEnvelope, 753 "malformed envelope: payload.kind", 754 ) 755 } 756 }; 757 let rid = req.request_id.clone(); 758 self.emit(&trace, EventKind::ToolRequest, Some(&rid)); 759 if self.ledger.has_request(&trace, &rid) { 760 let msg = format!("duplicate request_id: {rid}"); 761 return self.reject(&trace, Some(&rid), ErrorCode::DuplicateRequestId, &msg); 762 } 763 if let Some((code, msg)) = self.request_refusal(&trace) { 764 return self.reject(&trace, Some(&rid), code, &msg); 765 } 766 let _ = self.ledger.note_request(&trace, &rid); 767 let size = canonicalize(&Value::Object(req.arguments.clone())).len(); 768 if size > self.limits.max_argument_bytes { 769 let msg = format!("arguments exceed {} bytes", self.limits.max_argument_bytes); 770 return self.reject(&trace, Some(&rid), ErrorCode::OversizedArguments, &msg); 771 } 772 // Exposure is the pipeline's own: whatever the model or envelope claimed is overwritten. 773 let exposure = match turn_exposure { 774 Some(e) => e.clone(), 775 None => self.exposure_for(&trace), 776 }; 777 req.provenance.extensions.insert( 778 "exposure".into(), 779 serde_json::to_value(&exposure).unwrap_or_else( 780 |_| json!({"inputs": [], "floor": TrustLevel::ExternalUntrusted.as_str()}), 781 ), 782 ); 783 let ctx = CallContext { 784 trace_id: trace.clone(), 785 message_id: env.message_id.clone(), 786 parent_id: env.parent_id.clone(), 787 model: env.source.clone(), 788 session: None, 789 exposure: Some(exposure), 790 }; 791 self.run_request(&req, &ctx) 792 } 793 794 fn run_request( 795 &mut self, 796 req: &ToolRequest, 797 ctx: &CallContext, 798 ) -> (ToolResult, ObservedRecord) { 799 let trace = ctx.trace_id.clone(); 800 let rid = req.request_id.clone(); 801 let mut lc = Lifecycle::new(&rid); 802 let mut cap = match self.table.map(req) { 803 Ok(c) => c, 804 Err(code) => { 805 let _ = lc.reject(); 806 let name = match &req.tool.namespace { 807 Some(ns) => format!("{ns}.{}", req.tool.name), 808 None => req.tool.name.clone(), 809 }; 810 return self.reject( 811 &trace, 812 Some(&rid), 813 code, 814 &format!("no mapping for tool: {name}"), 815 ); 816 } 817 }; 818 let _ = lc.map(); 819 let catalog = self.runtime.catalog(); 820 if let Some(pinned) = &cap.mapping.catalog_digest { 821 let live = catalog 822 .catalog_digest 823 .clone() 824 .unwrap_or_else(|| catalog.compute_digest()); 825 if *pinned != live { 826 let _ = &lc; 827 return self.reject( 828 &trace, 829 Some(&rid), 830 ErrorCode::StaleCapability, 831 "mapping table catalog digest does not match runtime catalog", 832 ); 833 } 834 } 835 if catalog.is_ambiguous(&cap.capability) { 836 // The definition the model read may not be the one this call routes to (Jan 8975). 837 let _ = lc.reject(); 838 return self.reject( 839 &trace, 840 Some(&rid), 841 ErrorCode::StaleCapability, 842 "capability is advertised more than once with different definitions", 843 ); 844 } 845 if let Some(d) = catalog 846 .capabilities 847 .iter() 848 .find(|c| c.name == cap.capability) 849 { 850 coerce_arguments(&mut cap, d); 851 } 852 self.emit(&trace, EventKind::ToolMapped, Some(&rid)); 853 854 let runtime_name = self.runtime.runtime_id().to_string(); 855 // Provenance for results produced after the runtime was reached but without executing: 856 // no data was produced, so `content_kind` and `trust` stay null (CORE.md). 857 let reached = |cap: &CapabilityRequest| ResultProvenance { 858 runtime: Some(runtime_name.clone()), 859 capability: Some(cap.capability.clone()), 860 content_kind: None, 861 trust: None, 862 ..Default::default() 863 }; 864 865 // decide: fail closed on adapter panic. 866 let decided = catch_unwind(AssertUnwindSafe(|| self.runtime.decide(&cap, ctx))); 867 let decision = match decided { 868 Ok(d) => d, 869 Err(_) => { 870 let mut r = ToolResult::failed( 871 Some(&rid), 872 ResultStatus::Denied, 873 ErrorCode::RuntimeUnavailable, 874 "runtime authority raised an error", 875 ); 876 r.provenance = Some(reached(&cap)); 877 let o = rec(Some(&rid), State::Denied, Some("denied"), &r, true, false); 878 self.emit_outcome(&trace, &r); 879 return (r, o); 880 } 881 }; 882 self.emit(&trace, EventKind::ToolDecision, Some(&rid)); 883 let state = match lc.apply_decision(&decision) { 884 Ok(s) => s, 885 Err(_) => { 886 // Cited a different request: nothing about it can be trusted. Denied. 887 let mut r = ToolResult::failed( 888 Some(&rid), 889 ResultStatus::Denied, 890 ErrorCode::UnknownDecision, 891 "unknown decision value: mismatched request_id", 892 ); 893 r.provenance = Some(reached(&cap)); 894 let o = rec(Some(&rid), State::Denied, Some("denied"), &r, true, false); 895 self.emit_outcome(&trace, &r); 896 return (r, o); 897 } 898 }; 899 let reason = decision.reason.clone(); 900 let non_exec = |status: ResultStatus, code: ErrorCode, msg: &str, embed: bool| { 901 let mut r = ToolResult::failed(Some(&rid), status, code, msg); 902 if embed { 903 r.decision = Some(decision.clone()); 904 } 905 r.provenance = Some(reached(&cap)); 906 r 907 }; 908 let mut pending_entry: Option = None; 909 let (result, dstr) = match state { 910 State::Denied if !decision.decision.is_known() => ( 911 non_exec( 912 ResultStatus::Denied, 913 ErrorCode::UnknownDecision, 914 &format!("unknown decision value: {}", decision.decision.as_str()), 915 false, 916 ), 917 "denied".to_string(), 918 ), 919 State::Denied => ( 920 non_exec( 921 ResultStatus::Denied, 922 ErrorCode::PolicyDenied, 923 reason.as_deref().unwrap_or("denied by runtime policy"), 924 true, 925 ), 926 "denied".into(), 927 ), 928 State::RequiresApproval => { 929 let id = decision 930 .approval 931 .as_ref() 932 .map(|a| a.approval_id.as_str()) 933 .unwrap_or(""); 934 if !id.is_empty() { 935 let live = catalog 936 .catalog_digest 937 .clone() 938 .unwrap_or_else(|| catalog.compute_digest()); 939 pending_entry = Some(PendingEntry { 940 lc: lc.clone(), 941 cap: cap.clone(), 942 ctx: ctx.clone(), 943 approval_id: id.to_string(), 944 expires_at: decision 945 .approval 946 .as_ref() 947 .and_then(|a| a.expires_at.clone()), 948 request_digest: capability_request_digest(&cap), 949 catalog_digest: live, 950 }); 951 } 952 ( 953 non_exec( 954 ResultStatus::RequiresApproval, 955 ErrorCode::ApprovalRequired, 956 &format!("approval required: {id}"), 957 true, 958 ), 959 "requires_approval".into(), 960 ) 961 } 962 State::Rejected if decision.decision == DecisionKind::NotFound => ( 963 non_exec( 964 ResultStatus::NotFound, 965 ErrorCode::CapabilityNotFound, 966 &format!("unknown capability: {}", cap.capability), 967 true, 968 ), 969 "not_found".into(), 970 ), 971 State::Rejected => ( 972 non_exec( 973 ResultStatus::Rejected, 974 ErrorCode::InvalidArguments, 975 reason.as_deref().unwrap_or("invalid arguments"), 976 true, 977 ), 978 "invalid".into(), 979 ), 980 State::Authorized => { 981 return self.execute_authorized(&mut lc, &cap, &decision, ctx, true); 982 } 983 _ => unreachable!("apply_decision from MAPPED only yields the states above"), 984 }; 985 let o = rec(Some(&rid), state, Some(&dstr), &result, true, false); 986 self.emit_outcome(&trace, &result); 987 if let Some(p) = pending_entry { 988 self.pending.insert((trace, rid), p); 989 } 990 (result, o) 991 } 992 993 /// AUTHORIZED -> EXECUTING -> terminal, shared by the first decision and a host continuation. 994 /// `decided` says whether `decide` ran in this call (it does not at a continuation). 995 fn execute_authorized( 996 &mut self, 997 lc: &mut Lifecycle, 998 cap: &CapabilityRequest, 999 decision: &Decision, 1000 ctx: &CallContext, 1001 decided: bool, 1002 ) -> (ToolResult, ObservedRecord) { 1003 let trace = ctx.trace_id.clone(); 1004 let rid = cap.request_id.clone(); 1005 let _ = lc.begin_execution(decision); 1006 self.emit(&trace, EventKind::ToolExecutionStarted, Some(&rid)); 1007 let ran = catch_unwind(AssertUnwindSafe(|| { 1008 self.runtime.execute(cap, decision, ctx) 1009 })); 1010 let mut r = match ran { 1011 // A result for another request is never attached to this one; its data is dropped. 1012 Ok(r) if r.request_id.as_deref() != Some(rid.as_str()) => { 1013 let mut r = ToolResult::failed( 1014 Some(&rid), 1015 ResultStatus::Error, 1016 ErrorCode::ExecutionError, 1017 "runtime returned a result for another request", 1018 ); 1019 r.provenance = Some(ResultProvenance { 1020 runtime: Some(self.runtime.runtime_id().to_string()), 1021 capability: Some(cap.capability.clone()), 1022 // Synthesized by the pipeline: labelled as the schema reads a null label. 1023 content_kind: Some(ContentKind::ToolResult), 1024 trust: Some(TrustLevel::Undetermined), 1025 trusted: TrustLevel::Undetermined.trusted_flag(), 1026 ..Default::default() 1027 }); 1028 r 1029 } 1030 Ok(r) => normalize(r, cap), 1031 Err(_) => { 1032 let mut r = ToolResult::failed( 1033 Some(&rid), 1034 ResultStatus::Error, 1035 ErrorCode::ExecutionError, 1036 "runtime authority raised an error", 1037 ); 1038 r.provenance = Some(ResultProvenance { 1039 runtime: Some(self.runtime.runtime_id().to_string()), 1040 capability: Some(cap.capability.clone()), 1041 // Synthesized by the pipeline: labelled as the schema reads a null label. 1042 content_kind: Some(ContentKind::ToolResult), 1043 trust: Some(TrustLevel::Undetermined), 1044 trusted: TrustLevel::Undetermined.trusted_flag(), 1045 ..Default::default() 1046 }); 1047 r 1048 } 1049 }; 1050 let end = match r.status { 1051 ResultStatus::Ok => State::Succeeded, 1052 ResultStatus::TimedOut => State::TimedOut, 1053 _ => State::Failed, 1054 }; 1055 let _ = lc.finish(end); 1056 r.request_id = Some(rid.clone()); 1057 let o = rec( 1058 Some(&rid), 1059 lc.state(), 1060 Some("authorized"), 1061 &r, 1062 decided, 1063 true, 1064 ); 1065 self.emit_outcome(&trace, &r); 1066 (r, o) 1067 } 1068 1069 /// Host-only (cut A2): read-only view of the approval entry for `(trace_id, request_id)`. 1070 /// Not reachable from model output or an envelope. 1071 pub fn pending_approval(&self, trace: &str, request_id: &str) -> Option { 1072 self.pending 1073 .get(&(trace.to_string(), request_id.to_string())) 1074 .map(|p| PendingApproval { 1075 request_id: request_id.to_string(), 1076 approval_id: p.approval_id.clone(), 1077 expires_at: p.expires_at.clone(), 1078 request_digest: p.request_digest.clone(), 1079 capability_request: p.cap.clone(), 1080 state: p.lc.state(), 1081 }) 1082 } 1083 1084 /// Host-only (cut A2): continue a request that required approval. `decision` is the 1085 /// runtime's own continuation decision, `request_digest` the digest of the 1086 /// `capability_request` the host believes was approved, `now` the host clock 1087 /// (`YYYY-MM-DDTHH:MM:SSZ`). The order of checks is pinned in CORE.md (Approval continuation). 1088 /// A request with no live pending entry is refused and nothing changes. A failed check on a 1089 /// pending entry denies it for good; only `authorized` with everything matching executes, 1090 /// at most once. This never calls `decide` and never touches the request ledger. 1091 pub fn continue_approval( 1092 &mut self, 1093 trace: &str, 1094 request_id: &str, 1095 decision: &Decision, 1096 request_digest: &str, 1097 now: &str, 1098 ) -> Result<(ToolResult, ObservedRecord), Refusal> { 1099 if self.is_closed(trace) { 1100 return Err(Refusal::SessionClosed); 1101 } 1102 if !self.reserve_retained(trace, 1, 3) { 1103 return Err(Refusal::SessionClosed); 1104 } 1105 let key = (trace.to_string(), request_id.to_string()); 1106 let mut p = match self.pending.remove(&key) { 1107 Some(p) if p.lc.state() == State::RequiresApproval => p, 1108 Some(p) => { 1109 self.pending.insert(key, p); 1110 return Err(Refusal::NoPendingApproval); 1111 } 1112 None => return Err(Refusal::NoPendingApproval), 1113 }; 1114 let live = { 1115 let c = self.runtime.catalog(); 1116 c.catalog_digest 1117 .clone() 1118 .unwrap_or_else(|| c.compute_digest()) 1119 }; 1120 let cited = decision.approval.as_ref().map(|a| a.approval_id.as_str()); 1121 let denial: Option<(ErrorCode, String)> = if decision.request_id != request_id { 1122 Some(( 1123 ErrorCode::UnknownDecision, 1124 "unknown decision value: mismatched request_id".into(), 1125 )) 1126 } else if cited != Some(p.approval_id.as_str()) { 1127 Some(( 1128 ErrorCode::PolicyDenied, 1129 "approval refused: approval_id does not match".into(), 1130 )) 1131 } else if request_digest != p.request_digest { 1132 Some(( 1133 ErrorCode::PolicyDenied, 1134 "approval refused: capability_request digest does not match".into(), 1135 )) 1136 } else if p 1137 .expires_at 1138 .as_deref() 1139 .is_some_and(|e| approval_expired(e, now)) 1140 { 1141 Some((ErrorCode::PolicyDenied, "approval expired".into())) 1142 } else if live != p.catalog_digest { 1143 Some(( 1144 ErrorCode::StaleCapability, 1145 "runtime catalog changed since approval was requested".into(), 1146 )) 1147 } else { 1148 match &decision.decision { 1149 DecisionKind::Authorized => None, 1150 DecisionKind::Denied => Some(( 1151 ErrorCode::PolicyDenied, 1152 decision 1153 .reason 1154 .clone() 1155 .unwrap_or_else(|| "denied by runtime policy".into()), 1156 )), 1157 other => Some(( 1158 ErrorCode::UnknownDecision, 1159 format!("unknown decision value: {}", other.as_str()), 1160 )), 1161 } 1162 }; 1163 self.emit(trace, EventKind::ToolDecision, Some(request_id)); 1164 let (r, o) = match denial { 1165 Some((code, msg)) => { 1166 let embed = 1167 code == ErrorCode::PolicyDenied && decision.decision == DecisionKind::Denied; 1168 self.deny_pending(&mut p, trace, code, &msg, embed.then_some(decision)) 1169 } 1170 None => match p.lc.apply_decision(decision) { 1171 Ok(State::Authorized) => { 1172 let (cap, ctx) = (p.cap.clone(), p.ctx.clone()); 1173 self.execute_authorized(&mut p.lc, &cap, decision, &ctx, false) 1174 } 1175 _ => self.deny_pending( 1176 &mut p, 1177 trace, 1178 ErrorCode::UnknownDecision, 1179 "unknown decision value: mismatched request_id", 1180 None, 1181 ), 1182 }, 1183 }; 1184 self.push_result_input(trace, &r, r.result_digest()); 1185 self.pending.insert(key, p); 1186 Ok((r, o)) 1187 } 1188 1189 /// Host-only (cut A2): cancel a pending approval. DENIED is terminal. Anything that is not 1190 /// pending is refused and nothing changes. 1191 pub fn cancel_approval( 1192 &mut self, 1193 trace: &str, 1194 request_id: &str, 1195 ) -> Result<(ToolResult, ObservedRecord), Refusal> { 1196 if self.is_closed(trace) { 1197 return Err(Refusal::SessionClosed); 1198 } 1199 if !self.reserve_retained(trace, 1, 1) { 1200 return Err(Refusal::SessionClosed); 1201 } 1202 let key = (trace.to_string(), request_id.to_string()); 1203 let mut p = match self.pending.remove(&key) { 1204 Some(p) if p.lc.state() == State::RequiresApproval => p, 1205 Some(p) => { 1206 self.pending.insert(key, p); 1207 return Err(Refusal::NoPendingApproval); 1208 } 1209 None => return Err(Refusal::NoPendingApproval), 1210 }; 1211 let (r, o) = self.deny_pending( 1212 &mut p, 1213 trace, 1214 ErrorCode::PolicyDenied, 1215 "approval cancelled by host", 1216 None, 1217 ); 1218 self.push_result_input(trace, &r, r.result_digest()); 1219 self.pending.insert(key, p); 1220 Ok((r, o)) 1221 } 1222 1223 /// REQUIRES_APPROVAL -> DENIED for a pending entry: result, record and event. Execute is not called. 1224 fn deny_pending( 1225 &mut self, 1226 p: &mut PendingEntry, 1227 trace: &str, 1228 code: ErrorCode, 1229 msg: &str, 1230 embed: Option<&Decision>, 1231 ) -> (ToolResult, ObservedRecord) { 1232 let _ = p.lc.cancel(); 1233 let rid = p.cap.request_id.clone(); 1234 let mut r = ToolResult::failed(Some(&rid), ResultStatus::Denied, code, msg); 1235 r.decision = embed.cloned(); 1236 r.provenance = Some(ResultProvenance { 1237 runtime: Some(self.runtime.runtime_id().to_string()), 1238 capability: Some(p.cap.capability.clone()), 1239 content_kind: None, 1240 trust: None, 1241 ..Default::default() 1242 }); 1243 let o = rec(Some(&rid), State::Denied, Some("denied"), &r, false, false); 1244 self.emit_outcome(trace, &r); 1245 (r, o) 1246 } 1247 1248 /// Parse one model turn with a dialect, push every call through the pipeline, render results. 1249 pub fn run_turn( 1250 &mut self, 1251 dialect: &str, 1252 model: &str, 1253 input: &Value, 1254 trace_id: &str, 1255 turn: u64, 1256 ) -> TurnOutcome { 1257 self.turn = Some(turn); 1258 let mut out = TurnOutcome { 1259 turn, 1260 intents: vec![], 1261 rejected: vec![], 1262 records: vec![], 1263 results: vec![], 1264 rendered: vec![], 1265 text: String::new(), 1266 outcome: "rejected".into(), 1267 error_code: None, 1268 partial: false, 1269 }; 1270 let parsed = match self.registry.get(dialect) { 1271 Ok(d) => d.parse( 1272 input, 1273 &ParseContext { 1274 trace_id: trace_id.into(), 1275 turn, 1276 model: model.into(), 1277 }, 1278 ), 1279 Err(code) => { 1280 out.error_code = Some(code); 1281 self.emit(trace_id, EventKind::ToolError, None); 1282 return out; 1283 } 1284 }; 1285 let mut parsed = parsed; 1286 // Five events per call (request, mapping, decision, execution, result), 1287 // plus turn metadata. Include malformed/over-limit calls and every result input. 1288 let calls = parsed.intents.len().saturating_add(parsed.rejected.len()); 1289 let events = calls.saturating_mul(5).saturating_add(4); 1290 if !self.reserve_retained(trace_id, calls, events) { 1291 out.error_code = Some(if self.is_closed(trace_id) { 1292 ErrorCode::SessionClosed 1293 } else { 1294 ErrorCode::SessionLimitExceeded 1295 }); 1296 // Existing closed-trace callers still receive per-call refusals below. 1297 // A saturated new trace holds no state and must not reach the runtime. 1298 if !self.is_closed(trace_id) { 1299 return out; 1300 } 1301 } 1302 if turn > 0 { 1303 self.emit(trace_id, EventKind::Continue, None); 1304 } 1305 let exposure = self.exposure_for(trace_id); 1306 for intent in &mut parsed.intents { 1307 intent.provenance.extensions.insert( 1308 "exposure".into(), 1309 serde_json::to_value(&exposure).unwrap_or(Value::Null), 1310 ); 1311 } 1312 out.text = parsed.text.clone(); 1313 out.partial = parsed.partial; 1314 out.outcome = if !parsed.intents.is_empty() { 1315 "tool_request" 1316 } else if !parsed.rejected.is_empty() { 1317 "rejected" 1318 } else { 1319 "no_tool" 1320 } 1321 .into(); 1322 if parsed.reasoning_digest.is_some() { 1323 self.emit(trace_id, EventKind::ReasoningDelta, None); 1324 } 1325 if !parsed.text.is_empty() { 1326 self.emit(trace_id, EventKind::ModelDelta, None); 1327 } 1328 1329 // Interleave intents and rejected calls in emission order. 1330 enum Item { 1331 Intent(usize), 1332 Rejected(usize), 1333 } 1334 let mut items: Vec<(usize, Item)> = parsed 1335 .intent_indices 1336 .iter() 1337 .enumerate() 1338 .map(|(i, ix)| (*ix, Item::Intent(i))) 1339 .collect(); 1340 items.extend( 1341 parsed 1342 .rejected 1343 .iter() 1344 .enumerate() 1345 .map(|(i, r)| (r.index, Item::Rejected(i))), 1346 ); 1347 items.sort_by_key(|(ix, _)| *ix); 1348 1349 let mut n = 0usize; 1350 for (_, item) in items { 1351 match item { 1352 Item::Rejected(i) => { 1353 let r = &parsed.rejected[i]; 1354 if self.is_closed(trace_id) { 1355 let (code, message) = Self::closed_refusal(trace_id); 1356 let (res, o) = self.reject(trace_id, Some(&r.request_id), code, &message); 1357 out.rendered.push(self.render(dialect, &res, None)); 1358 out.results.push(res); 1359 out.records.push(o); 1360 continue; 1361 } 1362 self.note_refused_request(trace_id, &r.request_id); 1363 let (res, o) = 1364 self.reject(trace_id, Some(&r.request_id), r.code.clone(), &r.message); 1365 out.rendered.push(self.render(dialect, &res, None)); 1366 out.results.push(res); 1367 out.records.push(o); 1368 } 1369 Item::Intent(i) => { 1370 let intent = &parsed.intents[i]; 1371 let (res, o) = if n >= self.limits.max_requests_per_turn { 1372 self.note_refused_request(trace_id, &intent.request_id); 1373 self.reject( 1374 trace_id, 1375 Some(&intent.request_id), 1376 ErrorCode::MalformedToolCall, 1377 "too many tool calls in one turn", 1378 ) 1379 } else { 1380 let env = Envelope::new( 1381 &format!("{}-{}-{}", self.message_prefix, turn, n), 1382 trace_id, 1383 &self.timestamp.clone(), 1384 Party::new("model", model), 1385 Party::new("runtime", self.runtime.runtime_id()), 1386 serde_json::to_value(intent).unwrap_or(Value::Null), 1387 ); 1388 self.admit_checked(&env, None, Some(&exposure)) 1389 }; 1390 n += 1; 1391 out.rendered.push(self.render(dialect, &res, Some(intent))); 1392 out.results.push(res); 1393 out.records.push(o); 1394 } 1395 } 1396 } 1397 // Everything rendered back to the model is visible to its next turn. 1398 for (res, rendered) in out.results.clone().iter().zip(&out.rendered) { 1399 self.record_result(trace_id, res, rendered); 1400 } 1401 if out.intents.is_empty() && parsed.intents.is_empty() && parsed.rejected.is_empty() { 1402 self.emit(trace_id, EventKind::Complete, None); 1403 } 1404 out.intents = parsed.intents; 1405 out.rejected = parsed.rejected; 1406 out 1407 } 1408 1409 fn render(&self, dialect: &str, r: &ToolResult, intent: Option<&ToolRequest>) -> Value { 1410 self.registry 1411 .get(dialect) 1412 .map(|d| d.render_result(r, intent)) 1413 .unwrap_or(Value::Null) 1414 } 1415 } 1416 1417 /// Hold the runtime's execute result to the contract: executed statuses only, request id ours, 1418 /// `content_kind`/`trust` defaulting to `tool_result`/`unknown`, `trusted` derived from `trust`. 1419 fn normalize(mut r: ToolResult, cap: &CapabilityRequest) -> ToolResult { 1420 if !matches!( 1421 r.status, 1422 ResultStatus::Ok | ResultStatus::Error | ResultStatus::TimedOut 1423 ) { 1424 r = ToolResult::failed( 1425 Some(&cap.request_id), 1426 ResultStatus::Error, 1427 ErrorCode::ExecutionError, 1428 "runtime returned a non-execution status from execute", 1429 ); 1430 } 1431 if r.status == ResultStatus::Ok { 1432 r.error = None; 1433 } else { 1434 r.data = Value::Null; 1435 r.decision = None; 1436 let e = r 1437 .error 1438 .get_or_insert_with(|| ErrorObject::new(ErrorCode::ExecutionError, "execution failed")); 1439 e.retryable = matches!( 1440 e.code, 1441 ErrorCode::ExecutionTimeout | ErrorCode::RuntimeUnavailable 1442 ); 1443 } 1444 let p = r.provenance.get_or_insert_with(ResultProvenance::default); 1445 p.runtime.get_or_insert_with(|| cap.runtime.clone()); 1446 p.capability.get_or_insert_with(|| cap.capability.clone()); 1447 p.content_kind = Some(match p.content_kind.take() { 1448 None => ContentKind::ToolResult, 1449 Some(ContentKind::Unknown(_)) => ContentKind::Undetermined, 1450 Some(k) => k, 1451 }); 1452 let trust = match p.trust.take() { 1453 None => TrustLevel::Undetermined, 1454 Some(TrustLevel::Unknown(_)) => TrustLevel::ExternalUntrusted, 1455 Some(t) => t, 1456 }; 1457 p.trusted = trust.trusted_flag(); 1458 p.trust = Some(trust); 1459 r 1460 } 1461 1462 #[cfg(test)] 1463 mod tests { 1464 use super::RetiredFilter; 1465 1466 /// Filter positions at 1009 bits, computed from the CORE.md rule with sha256sum, outside both 1467 /// SDKs (the retired Python SDK tested the same literals). 1468 const RETIRED_FILTER_POSITIONS_1009: [(&str, [usize; 4]); 3] = [ 1469 ("r0", [20, 106, 629, 750]), 1470 ("f6", [278, 703, 321, 847]), 1471 ("trace-\u{e9}", [733, 695, 298, 954]), 1472 ]; 1473 1474 #[test] 1475 fn retirement_filter_positions_match_the_spec_vector() { 1476 let mut f = RetiredFilter::new(1009); 1477 for (t, want) in RETIRED_FILTER_POSITIONS_1009 { 1478 assert_eq!(f.positions(t), want, "{t}"); 1479 } 1480 f.add("r0"); 1481 // Bit p is bit p mod 8, least significant first, of byte p div 8. 1482 let set: Vec = (0..1009) 1483 .filter(|&i| f.data[i >> 3] >> (i & 7) & 1 == 1) 1484 .collect(); 1485 assert_eq!(set, [20, 106, 629, 750]); 1486 } 1487 }