interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / adapters / aien / src / lib.rs
| 1 | //! INTERPLANE reference adapter for AIEN (ADR 0003). |
| 2 | //! |
| 3 | //! The adapter composes AIEN's existing primitives and mints nothing. It never constructs an |
| 4 | //! `AuthorizedEffect`, a `DoctrineDecision` or a `SafetyDecision`. `authorized` is only ever the |
| 5 | //! translation of an answer AIEN produced: an `Ok` from AIEN's gate for a read, or an |
| 6 | //! `AuthorizedEffect` that `aien_mcp::EffectLane::authorize` minted after AIEN's own |
| 7 | //! `EffectClassAuthority` said Allow. `requires_approval` and `denied` carry AIEN's reason. |
| 8 | use std::cell::RefCell; |
| 9 | use std::collections::{BTreeMap, HashMap}; |
| 10 | use std::fs; |
| 11 | use std::path::{Component, Path, PathBuf}; |
| 12 | use std::rc::Rc; |
| 13 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 14 | use std::sync::Arc; |
| 15 | |
| 16 | use aien_capability::{ |
| 17 | catalog_digest, routing_class, speculation_safe, Digest32, EffectClass, EffectId, JNodeId, |
| 18 | ProviderId, ToolDescriptor, ToolEffects, WorldId, |
| 19 | }; |
| 20 | use aien_mcp::memory::MemoryWire; |
| 21 | use aien_mcp::{ |
| 22 | ApprovalDesk, ApprovalError, ApprovalGrant, AuthorityOutcome, AuthorizedEffect, CallOutcome, |
| 23 | EffectClassAuthority, EffectIntent, EffectLane, EffectReceipt, EffectScope, Error as McpError, |
| 24 | Exposure as AienExposure, SessionManager, SpeculativeLane, SpeculativeToolCall, |
| 25 | TrustLevel as AienTrust, |
| 26 | }; |
| 27 | use interplane_core::*; |
| 28 | use interplane_crossaxis::MappingTable; |
| 29 | use interplane_crossveil::{CallContext, ObservedRecord, Pipeline, Refusal, RuntimeAuthority}; |
| 30 | use serde_json::{json, Map, Value}; |
| 31 | |
| 32 | pub mod compose_ledger; |
| 33 | pub mod fix_the_test; |
| 34 | pub mod provenance_export; |
| 35 | pub mod rsi_m5; |
| 36 | pub use compose_ledger::{ |
| 37 | hmac_sha256, ApprovalBinding, ComposeLedgerAuthority, DeskKey, LedgerClient, ModelTurn, |
| 38 | APPROVAL_BINDING_VERSION, BOUND_REQUIREMENTS, DEFAULT_APPROVER, LEDGER_BOUNDARY, |
| 39 | REQUIREMENTS_TAG_V1, |
| 40 | }; |
| 41 | |
| 42 | /// Runtime id carried in every decision, result and catalog. |
| 43 | pub const RUNTIME_ID: &str = "aien"; |
| 44 | /// Pinned reply for everything the reference adapter does not run. |
| 45 | pub const NOT_EXECUTED: &str = "not executed by the reference adapter"; |
| 46 | /// Pinned reply when the AIEN gate is not linked or the adapter was built unavailable. |
| 47 | pub const UNAVAILABLE: &str = "aien runtime not available"; |
| 48 | |
| 49 | /// `authority.policy_engine` of every effect decision: AIEN's own authority. |
| 50 | pub const ENGINE_EFFECT: &str = "aien-mcp.EffectClassAuthority"; |
| 51 | |
| 52 | const MAX_READ_BYTES: u64 = 1 << 20; |
| 53 | // Pending/replay correlation is retained for the adapter's lifetime, not just a pipeline trace. |
| 54 | const MAX_EFFECT_REQUESTS: usize = 4096; |
| 55 | |
| 56 | /// One capability: AIEN-side name, effects, and the argument schema (all string-typed). |
| 57 | struct Spec { |
| 58 | name: &'static str, |
| 59 | effects: fn() -> ToolEffects, |
| 60 | required: &'static [&'static str], |
| 61 | } |
| 62 | |
| 63 | /// Names come from aegis `ALLOWED_SKILLS` (enforcement.rs:14-24). AIEN enrolls no catalog today |
| 64 | /// (CURRENT_STATE.md: aien-capability has no dependents), so the effect bits below are this |
| 65 | /// adapter's enrollment, using AIEN's own `ToolEffects`. They are inputs to AIEN's classifier, |
| 66 | /// not a classifier of ours. |
| 67 | const SPECS: [Spec; 4] = [ |
| 68 | Spec { |
| 69 | name: "read_file", |
| 70 | effects: || ToolEffects::READ_FILESYSTEM, |
| 71 | required: &["path"], |
| 72 | }, |
| 73 | Spec { |
| 74 | name: "list_dir", |
| 75 | effects: || ToolEffects::READ_FILESYSTEM, |
| 76 | required: &["path"], |
| 77 | }, |
| 78 | Spec { |
| 79 | name: "write_file", |
| 80 | effects: || ToolEffects::WORLD_MUTATION, |
| 81 | required: &["path", "content"], |
| 82 | }, |
| 83 | Spec { |
| 84 | name: "bash_eval", |
| 85 | effects: || ToolEffects::SPAWN_PROCESS | ToolEffects::WORLD_MUTATION, |
| 86 | required: &["command"], |
| 87 | }, |
| 88 | ]; |
| 89 | |
| 90 | fn schema_for(spec: &Spec) -> Map<String, Value> { |
| 91 | let props: Map<String, Value> = spec |
| 92 | .required |
| 93 | .iter() |
| 94 | .map(|k| (k.to_string(), json!({"type": "string"}))) |
| 95 | .collect(); |
| 96 | json!({"type": "object", "properties": props, "required": spec.required}) |
| 97 | .as_object() |
| 98 | .cloned() |
| 99 | .unwrap_or_default() |
| 100 | } |
| 101 | |
| 102 | fn hex(d: &Digest32) -> String { |
| 103 | d.0.iter().map(|b| format!("{b:02x}")).collect() |
| 104 | } |
| 105 | |
| 106 | fn descriptors(overrides: &BTreeMap<String, ToolEffects>) -> Vec<ToolDescriptor> { |
| 107 | SPECS |
| 108 | .iter() |
| 109 | .map(|s| { |
| 110 | let effects = overrides |
| 111 | .get(s.name) |
| 112 | .copied() |
| 113 | .unwrap_or_else(|| (s.effects)()); |
| 114 | let sd = interplane_core::digest(&Value::Object(schema_for(s))); |
| 115 | let raw = sd.trim_start_matches("sha256:"); |
| 116 | let mut bytes = [0u8; 32]; |
| 117 | for (i, b) in bytes.iter_mut().enumerate() { |
| 118 | *b = u8::from_str_radix(&raw[2 * i..2 * i + 2], 16).unwrap_or(0); |
| 119 | } |
| 120 | ToolDescriptor::new(s.name, effects, Digest32(bytes)) |
| 121 | }) |
| 122 | .collect() |
| 123 | } |
| 124 | |
| 125 | /// The real host clock for approval expiry: seconds since the Unix epoch (aien-mcp reads no |
| 126 | /// clock itself; `now` and `expires_at` are in this unit). |
| 127 | pub fn host_clock() -> aien_mcp::Clock { |
| 128 | Arc::new(|| { |
| 129 | std::time::SystemTime::now() |
| 130 | .duration_since(std::time::UNIX_EPOCH) |
| 131 | .map(|d| d.as_secs()) |
| 132 | .unwrap_or(u64::MAX) |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | /// The reference adapter. See the crate README for what is reused and what is reimplemented. |
| 137 | pub struct AienAuthority { |
| 138 | workspace: Option<PathBuf>, |
| 139 | trust_workspace: bool, |
| 140 | available: bool, |
| 141 | descriptors: Vec<ToolDescriptor>, |
| 142 | overrides: BTreeMap<String, ToolEffects>, |
| 143 | lane: SpeculativeLane, |
| 144 | effect_lane: EffectLane, |
| 145 | /// Effects AIEN minted in `decide`, waiting for `execute`. The adapter only holds them. |
| 146 | authorized: HashMap<String, AuthorizedEffect<EffectIntent>>, |
| 147 | /// AIEN's approver handle for the enrolled broker. |
| 148 | desk: Option<ApprovalDesk>, |
| 149 | /// The approval id this adapter minted when `decide` answered `requires_approval`, per request id. |
| 150 | /// A correlation handle only; the authority is the grant AIEN's desk issues. |
| 151 | minted: HashMap<String, String>, |
| 152 | /// Receipts AIEN's ledger returned for a replayed request, handed back by `execute`. |
| 153 | replayed: HashMap<String, EffectReceipt>, |
| 154 | /// Host clock for approval expiry (epoch seconds by default, [`host_clock`]). AIEN's effect lane |
| 155 | /// re-checks expiry with it when an approved effect commits; the ledger route checks it |
| 156 | /// before the daemon handoff. |
| 157 | clock: aien_mcp::Clock, |
| 158 | /// `expires_at` of every grant issued through [`AienAuthority::issue_approval`], by approval id. |
| 159 | expiries: HashMap<Digest32, u64>, |
| 160 | /// The pipeline's exposure at `decide`, per request id, handed to AIEN again when the host |
| 161 | /// presents a grant: the approval answers what the model saw when it asked (0.3 cut E4). |
| 162 | exposures: HashMap<String, Option<AienExposure>>, |
| 163 | provider: ProviderId, |
| 164 | runtime: tokio::runtime::Runtime, |
| 165 | wire_calls: Arc<AtomicUsize>, |
| 166 | pub decide_calls: u32, |
| 167 | pub execute_calls: u32, |
| 168 | } |
| 169 | |
| 170 | impl AienAuthority { |
| 171 | /// Enroll the in-process read provider over `workspace` and return the adapter. |
| 172 | pub fn new(workspace: impl AsRef<Path>) -> Result<Self, String> { |
| 173 | let root = fs::canonicalize(workspace.as_ref()).map_err(|e| format!("workspace: {e}"))?; |
| 174 | let mut a = Self::build(Some(root.clone()), true)?; |
| 175 | a.enroll(root)?; |
| 176 | Ok(a) |
| 177 | } |
| 178 | |
| 179 | /// Fail-closed adapter: `decide()` denies everything with "aien runtime not available". |
| 180 | /// This is also the behaviour when the crate is built without the `aegis-gate` feature. |
| 181 | pub fn unavailable() -> Self { |
| 182 | Self::build(None, false).expect("tokio current-thread runtime") |
| 183 | } |
| 184 | |
| 185 | /// Mark workspace reads as `trusted_runtime` instead of `workspace_untrusted`. |
| 186 | pub fn with_trusted_workspace(mut self, trusted: bool) -> Self { |
| 187 | self.trust_workspace = trusted; |
| 188 | self |
| 189 | } |
| 190 | |
| 191 | /// Number of times the wire (the code that touches the filesystem) was invoked. |
| 192 | pub fn wire_calls(&self) -> usize { |
| 193 | self.wire_calls.load(Ordering::SeqCst) |
| 194 | } |
| 195 | |
| 196 | fn build(workspace: Option<PathBuf>, available: bool) -> Result<Self, String> { |
| 197 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 198 | .build() |
| 199 | .map_err(|e| e.to_string())?; |
| 200 | Ok(Self { |
| 201 | workspace, |
| 202 | trust_workspace: false, |
| 203 | available: available && cfg!(feature = "aegis-gate"), |
| 204 | descriptors: descriptors(&BTreeMap::new()), |
| 205 | overrides: BTreeMap::new(), |
| 206 | lane: SpeculativeLane::new(aien_mcp::McpBroker::new()), |
| 207 | effect_lane: EffectLane::new(aien_mcp::McpBroker::new()).with_clock(host_clock()), |
| 208 | clock: host_clock(), |
| 209 | expiries: HashMap::new(), |
| 210 | authorized: HashMap::new(), |
| 211 | desk: None, |
| 212 | minted: HashMap::new(), |
| 213 | replayed: HashMap::new(), |
| 214 | exposures: HashMap::new(), |
| 215 | provider: ProviderId::new("interplane-reference"), |
| 216 | runtime, |
| 217 | wire_calls: Arc::new(AtomicUsize::new(0)), |
| 218 | decide_calls: 0, |
| 219 | execute_calls: 0, |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | fn enroll(&mut self, root: PathBuf) -> Result<(), String> { |
| 224 | // Pin the workspace object once, rather than resolving its name after approval. |
| 225 | let directory = fs::File::open(&root).map_err(|e| format!("workspace: {e}"))?; |
| 226 | let counter = self.wire_calls.clone(); |
| 227 | let wire = MemoryWire::new(self.descriptors.clone(), move |name, args| { |
| 228 | counter.fetch_add(1, Ordering::SeqCst); |
| 229 | wire_handler(&root, &directory, name, args) |
| 230 | }); |
| 231 | let mgr = SessionManager::new(); |
| 232 | self.runtime |
| 233 | .block_on(mgr.enroll(self.provider.clone(), Arc::new(wire))) |
| 234 | .map_err(|e| e.to_string())?; |
| 235 | self.lane = mgr.speculative_lane(); |
| 236 | self.effect_lane = mgr.effect_lane().with_clock(self.clock.clone()); |
| 237 | self.desk = Some(mgr.approval_desk()); |
| 238 | Ok(()) |
| 239 | } |
| 240 | |
| 241 | /// Re-declare the `ToolEffects` of a stock capability (a fixture or a stricter enrollment) |
| 242 | /// and re-enroll. AIEN's authority then decides from the new bits; the adapter decides nothing. |
| 243 | pub fn with_effects(mut self, name: &str, effects: ToolEffects) -> Result<Self, String> { |
| 244 | if !SPECS.iter().any(|s| s.name == name) { |
| 245 | return Err(format!("unknown capability: {name}")); |
| 246 | } |
| 247 | self.overrides.insert(name.to_string(), effects); |
| 248 | self.descriptors = descriptors(&self.overrides); |
| 249 | if let Some(root) = self.workspace.clone() { |
| 250 | self.enroll(root)?; |
| 251 | } |
| 252 | Ok(self) |
| 253 | } |
| 254 | |
| 255 | fn spec(&self, name: &str) -> Option<(&Spec, &ToolDescriptor)> { |
| 256 | let s = SPECS.iter().find(|s| s.name == name)?; |
| 257 | let d = self.descriptors.iter().find(|d| d.name() == name)?; |
| 258 | Some((s, d)) |
| 259 | } |
| 260 | |
| 261 | /// The mapping table for this adapter: pass-through of every AIEN capability name. |
| 262 | /// `pinned` pins the table to the live catalog digest so a changed catalog is `stale_capability`. |
| 263 | pub fn mapping_table(&self, pinned: bool) -> MappingTable { |
| 264 | let rules: Vec<Value> = SPECS |
| 265 | .iter() |
| 266 | .map(|s| { |
| 267 | json!({"id": format!("passthrough:{}", s.name), "kind": "passthrough", |
| 268 | "from": {"namespace": null, "name": s.name}, "to": s.name}) |
| 269 | }) |
| 270 | .collect(); |
| 271 | let pin = pinned.then(|| self.catalog().catalog_digest); |
| 272 | MappingTable::from_value(json!({"runtime": RUNTIME_ID, "table_version": "1", |
| 273 | "catalog_digest": pin.flatten(), "rules": rules})) |
| 274 | .expect("static table") |
| 275 | } |
| 276 | |
| 277 | fn decision( |
| 278 | &self, |
| 279 | req: &CapabilityRequest, |
| 280 | kind: DecisionKind, |
| 281 | reason: Option<&str>, |
| 282 | engine: &str, |
| 283 | ) -> Decision { |
| 284 | Decision { |
| 285 | kind: DecisionMsgKind, |
| 286 | request_id: req.request_id.clone(), |
| 287 | decision: kind, |
| 288 | capability: Some(req.capability.clone()), |
| 289 | authority: Authority { |
| 290 | runtime: RUNTIME_ID.into(), |
| 291 | policy_engine: engine.into(), |
| 292 | decision_id: None, |
| 293 | extensions: Map::new(), |
| 294 | }, |
| 295 | reason: reason.map(str::to_string), |
| 296 | constraints: vec![], |
| 297 | approval: None, |
| 298 | runtime_state: None, |
| 299 | extensions: Map::new(), |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// Stage the intent for an effect request and build its scope. The idempotency key is the |
| 304 | /// request id, so one logical request is one effect identity (and one ledger entry). |
| 305 | fn stage( |
| 306 | &mut self, |
| 307 | req: &CapabilityRequest, |
| 308 | ) -> Result<(EffectIntent, EffectScope), Box<Decision>> { |
| 309 | let args = Value::Object(req.arguments.clone()); |
| 310 | let staged = self.runtime.block_on(self.lane.stage_effect_intent( |
| 311 | &self.provider, |
| 312 | &req.capability, |
| 313 | args.clone(), |
| 314 | )); |
| 315 | let intent = match staged { |
| 316 | Ok(i) => i, |
| 317 | // Speculation-safe but not read-only (local ephemeral): still goes through AIEN's |
| 318 | // authority. An intent is plain data and carries no authority. |
| 319 | Err(McpError::SpeculationSafe) => EffectIntent { |
| 320 | provider: self.provider.clone(), |
| 321 | tool_name: req.capability.clone(), |
| 322 | arguments: args, |
| 323 | capability_digest: catalog_digest(&self.descriptors), |
| 324 | }, |
| 325 | Err(e) => { |
| 326 | let r = e.to_string(); |
| 327 | return Err(Box::new(self.decision( |
| 328 | req, |
| 329 | DecisionKind::Denied, |
| 330 | Some(&r), |
| 331 | ENGINE_EFFECT, |
| 332 | ))); |
| 333 | } |
| 334 | }; |
| 335 | let scope = EffectScope { |
| 336 | world_id: WorldId(1), |
| 337 | winning_jnode: JNodeId(1), |
| 338 | idempotency_key: EffectId::from_label(req.request_id.as_str()), |
| 339 | }; |
| 340 | Ok((intent, scope)) |
| 341 | } |
| 342 | |
| 343 | /// The approver's handle (AIEN's `ApprovalDesk`), once a workspace is enrolled. Hand it only |
| 344 | /// to the host's approval service; the adapter itself never issues a grant on its own. |
| 345 | pub fn approval_desk(&self) -> Option<&ApprovalDesk> { |
| 346 | self.desk.as_ref() |
| 347 | } |
| 348 | |
| 349 | /// Issue one single-use grant, through AIEN's desk, for exactly the effect `req` names |
| 350 | /// (intent, idempotency key, world, J-node). Valid while `now < expires_at`. |
| 351 | pub fn issue_approval( |
| 352 | &mut self, |
| 353 | req: &CapabilityRequest, |
| 354 | expires_at: u64, |
| 355 | ) -> Result<ApprovalGrant, String> { |
| 356 | let (intent, scope) = self |
| 357 | .stage(req) |
| 358 | .map_err(|d| d.reason.clone().unwrap_or_default())?; |
| 359 | let desk = self.desk.as_ref().ok_or(UNAVAILABLE)?; |
| 360 | let grant = desk.issue(&intent, scope, expires_at); |
| 361 | self.expiries.insert(grant.approval_id(), expires_at); |
| 362 | Ok(grant) |
| 363 | } |
| 364 | |
| 365 | /// Host-only (cut A3): the approval channel. The approver calls this with a grant it got from |
| 366 | /// [`Self::issue_approval`]; the result is the runtime's own continuation decision for the |
| 367 | /// request, to be handed to `Pipeline::continue_approval` (or the [`AienShared::continue_approval`] |
| 368 | /// helper, which does both and cleans up). It is the only place a grant is spent: `decide` |
| 369 | /// never reads one, so nothing the model writes can stand in for a grant. |
| 370 | /// |
| 371 | /// Spend point (sovereign-core #260, two-phase): `EffectLane::authorize_approved` RESERVES the |
| 372 | /// grant when it mints the effect; `EffectLane::execute_effect` COMMITS (spends) it just |
| 373 | /// before the provider call, re-checking expiry with the lane's clock ([`host_clock`] unless |
| 374 | /// [`AienAuthority::set_clock`]). If the pipeline refuses the continuation (stale digest or |
| 375 | /// clock) the minted effect is dropped by `discard_unexecuted`, nothing runs and the grant is |
| 376 | /// RELEASED; a grant presented while it is reserved is refused (`Reserved`). If the provider |
| 377 | /// rejects the call AIEN's ledger entry is removed (the grant stays spent), and if the provider |
| 378 | /// outcome is unknown the ledger keeps `Uncertain`. A second effect never runs silently. `now` is host-supplied |
| 379 | /// epoch time (aien-mcp reads no clock). |
| 380 | pub fn present_approval( |
| 381 | &mut self, |
| 382 | req: &CapabilityRequest, |
| 383 | grant: &ApprovalGrant, |
| 384 | now: u64, |
| 385 | ) -> Decision { |
| 386 | let rid = req.request_id.as_str().to_string(); |
| 387 | let Some(approval_id) = self.minted.get(&rid).cloned() else { |
| 388 | return self.decision( |
| 389 | req, |
| 390 | DecisionKind::Denied, |
| 391 | Some("approval refused: no approval was requested for this request"), |
| 392 | ENGINE_EFFECT, |
| 393 | ); |
| 394 | }; |
| 395 | let refuse = |s: &Self, why: String| { |
| 396 | let mut d = s.decision(req, DecisionKind::Denied, Some(&why), ENGINE_EFFECT); |
| 397 | d.approval = Some(minted_approval(&approval_id, None)); |
| 398 | d |
| 399 | }; |
| 400 | let (intent, scope) = match self.stage(req) { |
| 401 | Ok(x) => x, |
| 402 | Err(d) => return refuse(self, d.reason.clone().unwrap_or_default()), |
| 403 | }; |
| 404 | let class = self |
| 405 | .spec(&req.capability) |
| 406 | .map(|(_, d)| routing_class(d.effects())); |
| 407 | let mut values = vec![format!("effect_class={class:?}")]; |
| 408 | // Absent (no decide seen for this request) stays absent: AIEN reads that as untrusted. |
| 409 | let lane = lane_for( |
| 410 | &self.effect_lane, |
| 411 | self.exposures.get(&rid).cloned().flatten(), |
| 412 | ); |
| 413 | let outcome = |
| 414 | lane.authorize_approved(intent.clone(), scope, &EffectClassAuthority, grant, now); |
| 415 | // A spent grant presented again for the effect it was spent on is a replay of a finished |
| 416 | // request: AIEN's ledger returns the existing receipt and nothing is minted or run. |
| 417 | let outcome = match outcome { |
| 418 | Err(AuthorityOutcome::Approval(ApprovalError::Consumed)) => { |
| 419 | match self.runtime.block_on(lane.authorize_and_execute_approved( |
| 420 | intent, |
| 421 | scope, |
| 422 | &EffectClassAuthority, |
| 423 | grant, |
| 424 | now, |
| 425 | )) { |
| 426 | Ok(receipt) => { |
| 427 | self.replayed.insert(rid, receipt); |
| 428 | values.push("replay=true".into()); |
| 429 | let mut d = |
| 430 | self.decision(req, DecisionKind::Authorized, None, ENGINE_EFFECT); |
| 431 | d.approval = Some(minted_approval(&approval_id, None)); |
| 432 | d.runtime_state = Some(RuntimeExtension { |
| 433 | vocabulary: "aien.effects".into(), |
| 434 | values, |
| 435 | extensions: Map::new(), |
| 436 | }); |
| 437 | return d; |
| 438 | } |
| 439 | Err(other) => Err(other), |
| 440 | } |
| 441 | } |
| 442 | o => o, |
| 443 | }; |
| 444 | match outcome { |
| 445 | Ok(effect) => { |
| 446 | self.authorized.insert(rid, effect); |
| 447 | let mut d = self.decision(req, DecisionKind::Authorized, None, ENGINE_EFFECT); |
| 448 | d.approval = Some(minted_approval(&approval_id, None)); |
| 449 | d.runtime_state = Some(RuntimeExtension { |
| 450 | vocabulary: "aien.effects".into(), |
| 451 | values, |
| 452 | extensions: Map::new(), |
| 453 | }); |
| 454 | d |
| 455 | } |
| 456 | // sovereign-core #260: the grant is reserved by an effect that has neither run nor been |
| 457 | // released (another presentation of the same grant is in flight). Nothing is minted. |
| 458 | Err(AuthorityOutcome::Approval(ApprovalError::Reserved)) => refuse( |
| 459 | self, |
| 460 | "approval refused: Reserved (this grant already holds an effect that has not run or been released)".into(), |
| 461 | ), |
| 462 | Err(AuthorityOutcome::Approval(e)) => refuse(self, format!("approval refused: {e:?}")), |
| 463 | Err(AuthorityOutcome::Denied(r)) | Err(AuthorityOutcome::Contained(r)) => { |
| 464 | refuse(self, r) |
| 465 | } |
| 466 | Err(AuthorityOutcome::Execution(e)) => refuse(self, e.to_string()), |
| 467 | Err(AuthorityOutcome::Pending { reason, .. }) => refuse(self, reason), |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /// Host-only: drop an effect AIEN minted for `request_id` that `execute` did not run (the |
| 472 | /// pipeline refused the continuation). Nothing ran. Since sovereign-core #260 the grant is not |
| 473 | /// spent at mint, only reserved: dropping the effect RELEASES it (AIEN records the reason), and |
| 474 | /// a later mint re-checks expiry, revocation and the binding. Returns whether an unexecuted |
| 475 | /// effect was dropped. |
| 476 | pub fn discard_unexecuted(&mut self, request_id: &str) -> bool { |
| 477 | let effect = self.authorized.remove(request_id); |
| 478 | let had = effect.is_some(); |
| 479 | if let Some(e) = effect { |
| 480 | e.cancel("interplane: the pipeline did not run the effect"); |
| 481 | } |
| 482 | had | self.replayed.remove(request_id).is_some() |
| 483 | } |
| 484 | |
| 485 | /// Host-only (tests, or a host with its own time source): the clock AIEN's effect lane and the |
| 486 | /// ledger route use for approval expiry. Defaults to [`host_clock`]. |
| 487 | pub fn set_clock(&mut self, clock: aien_mcp::Clock) { |
| 488 | self.effect_lane = self.effect_lane.with_clock(clock.clone()); |
| 489 | self.clock = clock; |
| 490 | } |
| 491 | |
| 492 | /// Drop a replayed receipt held for `request_id` (the ledger route never hands one back). |
| 493 | pub(crate) fn discard_replayed(&mut self, request_id: &str) { |
| 494 | self.replayed.remove(request_id); |
| 495 | } |
| 496 | |
| 497 | /// Take the effect AIEN minted for `request_id` out of the adapter (the ledger route holds it, |
| 498 | /// and with it the grant reservation, while the daemon runs the write). |
| 499 | pub(crate) fn take_minted( |
| 500 | &mut self, |
| 501 | request_id: &str, |
| 502 | ) -> Option<AuthorizedEffect<EffectIntent>> { |
| 503 | self.authorized.remove(request_id) |
| 504 | } |
| 505 | |
| 506 | /// Expiry check at the ledger route's commit point, with this adapter's clock: `Ok` while |
| 507 | /// `now < expires_at` of the grant the effect holds; refused when it expired, or when the |
| 508 | /// effect holds no grant this adapter issued (expiry unknown: fail closed). |
| 509 | pub(crate) fn check_expiry( |
| 510 | &self, |
| 511 | effect: &AuthorizedEffect<EffectIntent>, |
| 512 | ) -> Result<(), String> { |
| 513 | let id = effect |
| 514 | .approval_id() |
| 515 | .ok_or("approval refused: the effect holds no approval grant")?; |
| 516 | let exp = *self |
| 517 | .expiries |
| 518 | .get(&id) |
| 519 | .ok_or("approval refused: expiry unknown (grant not issued through this adapter)")?; |
| 520 | let now = (self.clock)(); |
| 521 | if now >= exp { |
| 522 | return Err(format!( |
| 523 | "approval refused: ApprovalExpired (now {now} >= expires_at {exp}) before the write" |
| 524 | )); |
| 525 | } |
| 526 | Ok(()) |
| 527 | } |
| 528 | |
| 529 | /// Whether AIEN minted an effect for `request_id` that has not run yet (the ledger route of |
| 530 | /// [`ComposeLedgerAuthority`] opens only for such an effect). |
| 531 | pub fn holds_minted_effect(&self, request_id: &str) -> bool { |
| 532 | self.authorized.contains_key(request_id) |
| 533 | } |
| 534 | |
| 535 | /// What a successful result is (CROSSVEIL.md rule 7, 0.3 cut E4). A file's text is workspace |
| 536 | /// content; a listing is tool output made of workspace names; a write result is AIEN's receipt |
| 537 | /// plus the adapter's acknowledgement, authored by the runtime. Anything else is tool output of |
| 538 | /// unknown origin and gets the weaker label. `trust_workspace` lifts only the two reads. |
| 539 | fn label(&self, capability: &str) -> (ContentKind, TrustLevel) { |
| 540 | let ws = if self.trust_workspace { |
| 541 | TrustLevel::TrustedRuntime |
| 542 | } else { |
| 543 | TrustLevel::WorkspaceUntrusted |
| 544 | }; |
| 545 | match capability { |
| 546 | "read_file" => (ContentKind::WorkspaceContent, ws), |
| 547 | "list_dir" => (ContentKind::ToolResult, ws), |
| 548 | "write_file" => (ContentKind::ToolResult, TrustLevel::TrustedRuntime), |
| 549 | _ => (ContentKind::ToolResult, TrustLevel::ExternalUntrusted), |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | /// Effect path: stage, then ask AIEN (`EffectLane::authorize` with `EffectClassAuthority`). |
| 554 | /// This never spends a grant: a `requires_approval` verdict stays pending until the host |
| 555 | /// continues it through [`Self::present_approval`]. |
| 556 | /// The adapter translates the answer and never builds the authorized value itself. |
| 557 | fn decide_effect( |
| 558 | &mut self, |
| 559 | req: &CapabilityRequest, |
| 560 | effects: ToolEffects, |
| 561 | exposure: Option<AienExposure>, |
| 562 | ) -> Decision { |
| 563 | let rid = req.request_id.as_str(); |
| 564 | if !self.exposures.contains_key(rid) && self.exposures.len() >= MAX_EFFECT_REQUESTS { |
| 565 | return self.decision( |
| 566 | req, |
| 567 | DecisionKind::Denied, |
| 568 | Some("adapter effect request capacity exhausted"), |
| 569 | ENGINE_EFFECT, |
| 570 | ); |
| 571 | } |
| 572 | if let Some(path) = req.arguments.get("path").and_then(Value::as_str) { |
| 573 | if let Err(why) = self.confine(path) { |
| 574 | return self.decision( |
| 575 | req, |
| 576 | DecisionKind::Denied, |
| 577 | Some(&why), |
| 578 | "adapter.workspace_confinement", |
| 579 | ); |
| 580 | } |
| 581 | } |
| 582 | let (intent, scope) = match self.stage(req) { |
| 583 | Ok(x) => x, |
| 584 | Err(d) => return *d, |
| 585 | }; |
| 586 | let mut values = vec![format!("effect_class={:?}", routing_class(effects))]; |
| 587 | self.exposures |
| 588 | .insert(req.request_id.as_str().to_string(), exposure.clone()); |
| 589 | let outcome = lane_for(&self.effect_lane, exposure).authorize( |
| 590 | intent.clone(), |
| 591 | scope, |
| 592 | &EffectClassAuthority, |
| 593 | ); |
| 594 | match outcome { |
| 595 | Ok(effect) => { |
| 596 | self.authorized |
| 597 | .insert(req.request_id.as_str().to_string(), effect); |
| 598 | let mut d = self.decision(req, DecisionKind::Authorized, None, ENGINE_EFFECT); |
| 599 | d.runtime_state = Some(RuntimeExtension { |
| 600 | vocabulary: "aien.effects".into(), |
| 601 | values, |
| 602 | extensions: Map::new(), |
| 603 | }); |
| 604 | d |
| 605 | } |
| 606 | Err(AuthorityOutcome::Pending { |
| 607 | intent_digest, |
| 608 | reason, |
| 609 | }) => { |
| 610 | values.push("staged=true".into()); |
| 611 | values.push(format!("intent_digest={}", hex(&intent_digest))); |
| 612 | // `decide` never spends a grant. The id is a handle this adapter mints so the host can |
| 613 | // correlate the continuation; it carries no authority (the desk's grant does). |
| 614 | let approval_id = format!( |
| 615 | "aien-approval:{}:{}", |
| 616 | req.request_id.as_str(), |
| 617 | &hex(&intent_digest)[..16] |
| 618 | ); |
| 619 | self.minted |
| 620 | .insert(req.request_id.as_str().to_string(), approval_id.clone()); |
| 621 | let mut d = self.decision( |
| 622 | req, |
| 623 | DecisionKind::RequiresApproval, |
| 624 | Some(&reason), |
| 625 | ENGINE_EFFECT, |
| 626 | ); |
| 627 | d.approval = Some(minted_approval(&approval_id, Some(&hex(&intent_digest)))); |
| 628 | d.runtime_state = Some(RuntimeExtension { |
| 629 | vocabulary: "aien.effect_intent".into(), |
| 630 | values, |
| 631 | extensions: Map::new(), |
| 632 | }); |
| 633 | d |
| 634 | } |
| 635 | Err(AuthorityOutcome::Approval(e)) => { |
| 636 | let r = format!("approval refused: {e:?}"); |
| 637 | self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT) |
| 638 | } |
| 639 | Err(AuthorityOutcome::Denied(r)) | Err(AuthorityOutcome::Contained(r)) => { |
| 640 | self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT) |
| 641 | } |
| 642 | Err(AuthorityOutcome::Execution(e)) => { |
| 643 | let r = e.to_string(); |
| 644 | self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT) |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | fn confine(&self, path: &str) -> Result<(), String> { |
| 650 | let root = self.workspace.as_ref().ok_or(UNAVAILABLE)?; |
| 651 | let p = Path::new(path); |
| 652 | let full = if p.is_absolute() { |
| 653 | p.to_path_buf() |
| 654 | } else { |
| 655 | root.join(p) |
| 656 | }; |
| 657 | let inside = match fs::canonicalize(&full) { |
| 658 | Ok(c) => c.starts_with(root), |
| 659 | Err(_) => { |
| 660 | full.starts_with(root) && !full.components().any(|c| c == Component::ParentDir) |
| 661 | } |
| 662 | }; |
| 663 | if inside { |
| 664 | Ok(()) |
| 665 | } else { |
| 666 | Err(format!("path is outside the workspace: {path}")) |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | /// The pipeline's exposure in AIEN's own vocabulary (0.3 cut E4). The pipeline always supplies one; |
| 672 | /// `None` passes through as `None`, which AIEN treats as untrusted for effects (fail closed). |
| 673 | fn aien_exposure(ctx: &CallContext) -> Option<AienExposure> { |
| 674 | ctx.exposure |
| 675 | .as_ref() |
| 676 | .map(|e| AienExposure::new(e.inputs.clone(), AienTrust::from_wire(e.floor.as_str()))) |
| 677 | } |
| 678 | |
| 679 | /// The effect lane with the host's exposure attached, or the bare lane (no exposure) when absent. |
| 680 | fn lane_for(lane: &EffectLane, exposure: Option<AienExposure>) -> EffectLane { |
| 681 | match exposure { |
| 682 | Some(e) => lane.with_exposure(e), |
| 683 | None => lane.clone(), |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | /// In-process provider body. Reads run behind `SpeculativeLane::invoke_speculative`; `write_file` |
| 688 | /// runs only behind `EffectLane::execute_effect`, i.e. only with an AIEN-minted `AuthorizedEffect`. |
| 689 | fn wire_handler(root: &Path, directory: &fs::File, name: &str, args: &Value) -> CallOutcome { |
| 690 | if name == "write_file" { |
| 691 | return write_handler(root, directory, args); |
| 692 | } |
| 693 | read_handler(root, name, args) |
| 694 | } |
| 695 | |
| 696 | fn write_handler(root: &Path, directory: &fs::File, args: &Value) -> CallOutcome { |
| 697 | let (Some(path), Some(content)) = ( |
| 698 | args.get("path").and_then(Value::as_str), |
| 699 | args.get("content").and_then(Value::as_str), |
| 700 | ) else { |
| 701 | return CallOutcome::Rejected("missing required argument".into()); |
| 702 | }; |
| 703 | match confined_write(root, directory, Path::new(path), content.as_bytes()) { |
| 704 | Ok(()) => CallOutcome::Finished(json!({"path": path, "bytes": content.len()})), |
| 705 | Err(e) => CallOutcome::Rejected(format!("cannot write {path}: {e}")), |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | /// No pathname is opened for writing. Resolve the parent under the enrolled directory, |
| 710 | /// create a new inode exclusively, and replace the name through that same descriptor. |
| 711 | /// Final symlinks are refused; a link planted after the check is replaced, never followed. |
| 712 | #[cfg(target_os = "linux")] |
| 713 | fn confined_write( |
| 714 | root: &Path, |
| 715 | directory: &fs::File, |
| 716 | path: &Path, |
| 717 | content: &[u8], |
| 718 | ) -> std::io::Result<()> { |
| 719 | use rustix::fs::{ |
| 720 | openat, openat2, renameat, statat, unlinkat, AtFlags, FileType, Mode, OFlags, ResolveFlags, |
| 721 | }; |
| 722 | use std::io::{Error, ErrorKind, Write}; |
| 723 | |
| 724 | let path = if path.is_absolute() { |
| 725 | path.strip_prefix(root) |
| 726 | .map_err(|_| Error::new(ErrorKind::PermissionDenied, "outside workspace"))? |
| 727 | } else { |
| 728 | path |
| 729 | }; |
| 730 | if path.components().any(|c| c == Component::ParentDir) { |
| 731 | return Err(Error::new(ErrorKind::PermissionDenied, "outside workspace")); |
| 732 | } |
| 733 | let name = path |
| 734 | .file_name() |
| 735 | .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "missing filename"))?; |
| 736 | let parent = path |
| 737 | .parent() |
| 738 | .filter(|p| !p.as_os_str().is_empty()) |
| 739 | .unwrap_or(Path::new(".")); |
| 740 | let parent = openat2( |
| 741 | directory, |
| 742 | parent, |
| 743 | OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, |
| 744 | Mode::empty(), |
| 745 | ResolveFlags::BENEATH | ResolveFlags::NO_SYMLINKS, |
| 746 | )?; |
| 747 | match statat(&parent, name, AtFlags::SYMLINK_NOFOLLOW) { |
| 748 | Ok(stat) if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile => { |
| 749 | return Err(Error::new( |
| 750 | ErrorKind::PermissionDenied, |
| 751 | "target is not a regular file", |
| 752 | )); |
| 753 | } |
| 754 | Ok(_) | Err(rustix::io::Errno::NOENT) => {} |
| 755 | Err(e) => return Err(e.into()), |
| 756 | } |
| 757 | static NEXT: AtomicUsize = AtomicUsize::new(0); |
| 758 | let temp = format!( |
| 759 | ".interplane-write-{}-{}", |
| 760 | std::process::id(), |
| 761 | NEXT.fetch_add(1, Ordering::Relaxed) |
| 762 | ); |
| 763 | let fd = openat( |
| 764 | &parent, |
| 765 | &temp, |
| 766 | OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC, |
| 767 | Mode::RUSR | Mode::WUSR, |
| 768 | )?; |
| 769 | let result = (|| { |
| 770 | let mut file = fs::File::from(fd); |
| 771 | file.write_all(content)?; |
| 772 | file.sync_all()?; |
| 773 | renameat(&parent, &temp, &parent, name)?; |
| 774 | Ok(()) |
| 775 | })(); |
| 776 | if result.is_err() { |
| 777 | let _ = unlinkat(&parent, &temp, AtFlags::empty()); |
| 778 | } |
| 779 | result |
| 780 | } |
| 781 | |
| 782 | #[cfg(not(target_os = "linux"))] |
| 783 | fn confined_write(_: &Path, _: &fs::File, _: &Path, _: &[u8]) -> std::io::Result<()> { |
| 784 | Err(std::io::Error::new( |
| 785 | std::io::ErrorKind::Unsupported, |
| 786 | "confined writes require Linux openat2", |
| 787 | )) |
| 788 | } |
| 789 | |
| 790 | /// Reimplemented: the read provider body (AIEN ships `MemoryWire` but no filesystem tools |
| 791 | /// in aien-mcp). |
| 792 | fn read_handler(root: &Path, name: &str, args: &Value) -> CallOutcome { |
| 793 | let Some(path) = args.get("path").and_then(Value::as_str) else { |
| 794 | return CallOutcome::Rejected("missing required argument: path".into()); |
| 795 | }; |
| 796 | let p = Path::new(path); |
| 797 | let full = if p.is_absolute() { |
| 798 | p.to_path_buf() |
| 799 | } else { |
| 800 | root.join(p) |
| 801 | }; |
| 802 | let Ok(real) = fs::canonicalize(&full) else { |
| 803 | return CallOutcome::Rejected(format!("cannot read {path}: no such file or directory")); |
| 804 | }; |
| 805 | if !real.starts_with(root) { |
| 806 | return CallOutcome::Rejected(format!("path is outside the workspace: {path}")); |
| 807 | } |
| 808 | match name { |
| 809 | "read_file" => match fs::metadata(&real) { |
| 810 | Ok(m) if m.is_file() && m.len() <= MAX_READ_BYTES => match fs::read_to_string(&real) { |
| 811 | Ok(s) => CallOutcome::Finished(json!({"path": path, "content": s})), |
| 812 | Err(e) => CallOutcome::Rejected(format!("cannot read {path}: {e}")), |
| 813 | }, |
| 814 | Ok(_) => CallOutcome::Rejected(format!("cannot read {path}: not a readable file")), |
| 815 | Err(e) => CallOutcome::Rejected(format!("cannot read {path}: {e}")), |
| 816 | }, |
| 817 | "list_dir" => match fs::read_dir(&real) { |
| 818 | Ok(rd) => { |
| 819 | let mut names: Vec<String> = rd |
| 820 | .flatten() |
| 821 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 822 | .collect(); |
| 823 | names.sort(); |
| 824 | CallOutcome::Finished(json!({"path": path, "entries": names})) |
| 825 | } |
| 826 | Err(e) => CallOutcome::Rejected(format!("cannot list {path}: {e}")), |
| 827 | }, |
| 828 | _ => CallOutcome::Rejected(NOT_EXECUTED.into()), |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | fn type_ok(v: &Value) -> bool { |
| 833 | v.is_string() |
| 834 | } |
| 835 | |
| 836 | impl RuntimeAuthority for AienAuthority { |
| 837 | fn runtime_id(&self) -> &str { |
| 838 | RUNTIME_ID |
| 839 | } |
| 840 | |
| 841 | fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision { |
| 842 | self.decide_calls += 1; |
| 843 | if !self.available { |
| 844 | return self.decision( |
| 845 | req, |
| 846 | DecisionKind::Denied, |
| 847 | Some(UNAVAILABLE), |
| 848 | "adapter.fail_closed", |
| 849 | ); |
| 850 | } |
| 851 | let Some((spec, desc)) = self.spec(&req.capability) else { |
| 852 | let r = format!("unknown capability: {}", req.capability); |
| 853 | return self.decision( |
| 854 | req, |
| 855 | DecisionKind::NotFound, |
| 856 | Some(&r), |
| 857 | "aien-capability.catalog", |
| 858 | ); |
| 859 | }; |
| 860 | for key in spec.required { |
| 861 | match req.arguments.get(*key) { |
| 862 | None => { |
| 863 | let r = format!("missing required argument: {key}"); |
| 864 | return self.decision( |
| 865 | req, |
| 866 | DecisionKind::Invalid, |
| 867 | Some(&r), |
| 868 | "aien-capability.catalog", |
| 869 | ); |
| 870 | } |
| 871 | Some(v) if !type_ok(v) => { |
| 872 | let r = format!("argument {key} must be string"); |
| 873 | return self.decision( |
| 874 | req, |
| 875 | DecisionKind::Invalid, |
| 876 | Some(&r), |
| 877 | "aien-capability.catalog", |
| 878 | ); |
| 879 | } |
| 880 | Some(_) => {} |
| 881 | } |
| 882 | } |
| 883 | // AIEN's live gate, for every known capability. |
| 884 | #[cfg(feature = "aegis-gate")] |
| 885 | if let Err(reason) = |
| 886 | aegis::pre_dispatch_check(&req.capability, &Value::Object(req.arguments.clone())) |
| 887 | { |
| 888 | return self.decision( |
| 889 | req, |
| 890 | DecisionKind::Denied, |
| 891 | Some(&reason), |
| 892 | "aegis.enforcement.pre_dispatch_check", |
| 893 | ); |
| 894 | } |
| 895 | let class = routing_class(desc.effects()); |
| 896 | if !matches!(class, EffectClass::Pure | EffectClass::ReadOnly) { |
| 897 | return self.decide_effect(req, desc.effects(), aien_exposure(ctx)); |
| 898 | } |
| 899 | // Adapter restriction (can only deny): confine reads to the workspace root. |
| 900 | if let Some(path) = req.arguments.get("path").and_then(Value::as_str) { |
| 901 | if let Err(why) = self.confine(path) { |
| 902 | return self.decision( |
| 903 | req, |
| 904 | DecisionKind::Denied, |
| 905 | Some(&why), |
| 906 | "adapter.workspace_confinement", |
| 907 | ); |
| 908 | } |
| 909 | } |
| 910 | let mut d = self.decision( |
| 911 | req, |
| 912 | DecisionKind::Authorized, |
| 913 | None, |
| 914 | "aegis.enforcement.pre_dispatch_check", |
| 915 | ); |
| 916 | d.runtime_state = Some(RuntimeExtension { |
| 917 | vocabulary: "aien.effects".into(), |
| 918 | values: vec![format!("effect_class={:?}", routing_class(desc.effects()))], |
| 919 | extensions: Map::new(), |
| 920 | }); |
| 921 | d |
| 922 | } |
| 923 | |
| 924 | fn execute( |
| 925 | &mut self, |
| 926 | req: &CapabilityRequest, |
| 927 | decision: &Decision, |
| 928 | _ctx: &CallContext, |
| 929 | ) -> ToolResult { |
| 930 | self.execute_calls += 1; |
| 931 | let rid = req.request_id.as_str(); |
| 932 | let fail = |msg: &str| { |
| 933 | ToolResult::failed( |
| 934 | Some(rid), |
| 935 | ResultStatus::Error, |
| 936 | ErrorCode::ExecutionError, |
| 937 | msg, |
| 938 | ) |
| 939 | }; |
| 940 | let readable = self |
| 941 | .spec(&req.capability) |
| 942 | .map(|(_, d)| routing_class(d.effects()) == EffectClass::ReadOnly) |
| 943 | .unwrap_or(false); |
| 944 | let effect = if decision.is_authorized() && !readable { |
| 945 | self.authorized.remove(rid) |
| 946 | } else { |
| 947 | None |
| 948 | }; |
| 949 | let replay = if decision.is_authorized() && !readable { |
| 950 | self.replayed.remove(rid) |
| 951 | } else { |
| 952 | None |
| 953 | }; |
| 954 | let receipt = match (effect, replay) { |
| 955 | (Some(effect), _) => Some( |
| 956 | self.runtime |
| 957 | .block_on(self.effect_lane.execute_effect(effect)), |
| 958 | ), |
| 959 | (None, Some(rc)) => Some(Ok(rc)), |
| 960 | (None, None) => None, |
| 961 | }; |
| 962 | let mut r = if let Some(receipt) = receipt { |
| 963 | match receipt { |
| 964 | Ok(rc) => ToolResult::ok( |
| 965 | rid, |
| 966 | json!({"output": rc.output, "receipt": { |
| 967 | "effect_id": rc.effect_id.0.iter().map(|b| format!("{b:02x}")).collect::<String>(), |
| 968 | "policy_digest": hex(&rc.policy_digest), |
| 969 | "tool_name": rc.tool_name}}), |
| 970 | ), |
| 971 | Err(e) => fail(&match e { |
| 972 | McpError::Rejected(why) => why, |
| 973 | other => other.to_string(), |
| 974 | }), |
| 975 | } |
| 976 | } else if !decision.is_authorized() || !readable { |
| 977 | fail(NOT_EXECUTED) |
| 978 | } else { |
| 979 | let call = SpeculativeToolCall { |
| 980 | provider: self.provider.clone(), |
| 981 | tool_name: req.capability.clone(), |
| 982 | arguments: Value::Object(req.arguments.clone()), |
| 983 | sandboxed: false, |
| 984 | }; |
| 985 | match self.runtime.block_on(self.lane.invoke_speculative(call)) { |
| 986 | Ok(out) => ToolResult::ok(rid, out.output), |
| 987 | Err(e) => fail(&match e { |
| 988 | McpError::Rejected(why) => why, |
| 989 | other => other.to_string(), |
| 990 | }), |
| 991 | } |
| 992 | }; |
| 993 | let ok = r.status == ResultStatus::Ok; |
| 994 | let (kind, trust) = if ok { |
| 995 | let (k, t) = self.label(&req.capability); |
| 996 | (Some(k), Some(t)) |
| 997 | } else { |
| 998 | (None, None) |
| 999 | }; |
| 1000 | r.provenance = Some(ResultProvenance { |
| 1001 | runtime: Some(RUNTIME_ID.into()), |
| 1002 | capability: Some(req.capability.clone()), |
| 1003 | duration_ms: Some(0), |
| 1004 | content_kind: kind, |
| 1005 | trust, |
| 1006 | trusted: None, |
| 1007 | extensions: Map::new(), |
| 1008 | }); |
| 1009 | r |
| 1010 | } |
| 1011 | |
| 1012 | fn catalog(&self) -> Catalog { |
| 1013 | let capabilities = SPECS |
| 1014 | .iter() |
| 1015 | .zip(self.descriptors.iter()) |
| 1016 | .map(|(s, d)| CapabilityDescriptor { |
| 1017 | name: s.name.into(), |
| 1018 | canonical: None, |
| 1019 | description: format!("AIEN capability {}", s.name), |
| 1020 | parameters: schema_for(s), |
| 1021 | domains: vec!["filesystem".into()], |
| 1022 | runtime_effects: Some(RuntimeExtension { |
| 1023 | vocabulary: "aien.tool_effects".into(), |
| 1024 | values: vec![ |
| 1025 | format!("bits={:#x}", d.effects().bits()), |
| 1026 | format!("class={:?}", routing_class(d.effects())), |
| 1027 | format!("speculation_safe={}", speculation_safe(d.effects())), |
| 1028 | ], |
| 1029 | extensions: Map::new(), |
| 1030 | }), |
| 1031 | schema_digest: None, |
| 1032 | extensions: Map::new(), |
| 1033 | }) |
| 1034 | .collect(); |
| 1035 | let aien = catalog_digest(&self.descriptors); |
| 1036 | let mut c = Catalog { |
| 1037 | kind: CatalogKind, |
| 1038 | runtime: RUNTIME_ID.into(), |
| 1039 | catalog_version: "1".into(), |
| 1040 | catalog_digest: Some(format!("sha256:{}", hex(&aien))), |
| 1041 | capabilities, |
| 1042 | extensions: Map::new(), |
| 1043 | }; |
| 1044 | let computed = c.compute_digest(); |
| 1045 | let same = c.catalog_digest.as_deref() == Some(computed.as_str()); |
| 1046 | c.extensions.insert( |
| 1047 | "aien".into(), |
| 1048 | json!({ |
| 1049 | "catalog_digest": format!("sha256:{}", hex(&aien)), |
| 1050 | "interplane_computed_digest": computed, |
| 1051 | "digests_equal": same, |
| 1052 | "formula": "aien_capability::catalog_digest: sha256 over concatenated per-tool digests sorted by name; per-tool digest = sha256(name || effects_bits_le32 || schema_digest)", |
| 1053 | }), |
| 1054 | ); |
| 1055 | c |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | fn minted_approval(approval_id: &str, scope: Option<&str>) -> Approval { |
| 1060 | Approval { |
| 1061 | approval_id: approval_id.to_string(), |
| 1062 | scope: scope.map(str::to_string), |
| 1063 | expires_at: None, |
| 1064 | extensions: Map::new(), |
| 1065 | } |
| 1066 | } |
| 1067 | |
| 1068 | /// A shareable handle to the adapter. The `Pipeline` borrows its runtime for its whole life, but |
| 1069 | /// the host's approver must call the adapter while a request is pending, so the host keeps one |
| 1070 | /// clone here and gives the pipeline another (`Pipeline::new(.., &mut shared.clone(), ..)`). |
| 1071 | /// Single-threaded; each call borrows the adapter only for its own duration. |
| 1072 | #[derive(Clone)] |
| 1073 | pub struct AienShared(Rc<RefCell<AienAuthority>>); |
| 1074 | |
| 1075 | impl AienShared { |
| 1076 | pub fn new(inner: AienAuthority) -> Self { |
| 1077 | Self(Rc::new(RefCell::new(inner))) |
| 1078 | } |
| 1079 | |
| 1080 | /// Host-side access to the adapter (approver calls, counters). |
| 1081 | pub fn with<R>(&self, f: impl FnOnce(&mut AienAuthority) -> R) -> R { |
| 1082 | f(&mut self.0.borrow_mut()) |
| 1083 | } |
| 1084 | |
| 1085 | /// Host-only: continue the pending request `request_id` on `trace` with `grant`. Reads the |
| 1086 | /// request and digest from the pipeline's own pending entry (never from the model), produces |
| 1087 | /// the continuation decision through AIEN, hands it to `Pipeline::continue_approval`, and |
| 1088 | /// drops any effect the pipeline did not run. `now_epoch` is for AIEN's grant expiry, `now` |
| 1089 | /// (`YYYY-MM-DDTHH:MM:SSZ`) for the pipeline's. |
| 1090 | pub fn continue_approval( |
| 1091 | &self, |
| 1092 | pipeline: &mut Pipeline<'_>, |
| 1093 | trace: &str, |
| 1094 | request_id: &str, |
| 1095 | grant: &ApprovalGrant, |
| 1096 | now_epoch: u64, |
| 1097 | now: &str, |
| 1098 | ) -> Result<(ToolResult, ObservedRecord), Refusal> { |
| 1099 | let pa = pipeline |
| 1100 | .pending_approval(trace, request_id) |
| 1101 | .ok_or(Refusal::NoPendingApproval)?; |
| 1102 | let d = self.with(|a| a.present_approval(&pa.capability_request, grant, now_epoch)); |
| 1103 | let out = pipeline.continue_approval(trace, request_id, &d, &pa.request_digest, now); |
| 1104 | self.with(|a| a.discard_unexecuted(request_id)); |
| 1105 | out |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | impl RuntimeAuthority for AienShared { |
| 1110 | fn runtime_id(&self) -> &str { |
| 1111 | RUNTIME_ID |
| 1112 | } |
| 1113 | fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision { |
| 1114 | self.0.borrow_mut().decide(req, ctx) |
| 1115 | } |
| 1116 | fn execute( |
| 1117 | &mut self, |
| 1118 | req: &CapabilityRequest, |
| 1119 | decision: &Decision, |
| 1120 | ctx: &CallContext, |
| 1121 | ) -> ToolResult { |
| 1122 | self.0.borrow_mut().execute(req, decision, ctx) |
| 1123 | } |
| 1124 | fn catalog(&self) -> Catalog { |
| 1125 | self.0.borrow().catalog() |
| 1126 | } |
| 1127 | } |