interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-mcp / src / broker.rs

892 lines · 32596 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::collections::HashMap;
17use std::sync::{Arc, Mutex};
18use std::time::{Duration, SystemTime};
19
20use aien_capability::{
21 catalog_digest, speculation_safe, Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor,
22 ToolEffects, WorldId,
23};
24use aien_trace::{
25 now_unix_ms, BoundedId, BoundedNote, CorrelationIds, EffectCertainty, EventKind, EventStatus,
26 EvidenceRefs, NullSink, TraceEvent, TraceId, TraceSink,
27};
28use serde_json::Value;
29
30use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord, GrantState, Reservation};
31use crate::authority::{
32 intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority,
33 EffectScope, Exposure,
34};
35use crate::effect::{mint, mint_reserved};
36use crate::{
37 AuthorizedEffect, CallOutcome, CapabilitySnapshot, EffectIntent, EffectReceipt, Error, McpWire,
38 ToolResult,
39};
40
41const SNAPSHOT_TTL: Duration = Duration::from_secs(60);
42
43/// Live MCP connection. Private to this crate: callers receive snapshots and receipts.
44struct McpSession {
45 epoch: u64,
46 wire: Arc<dyn McpWire>,
47 tools: Vec<ToolDescriptor>,
48 catalog_digest: Digest32,
49}
50
51enum LedgerEntry {
52 InFlight,
53 Completed(EffectReceipt),
54 Uncertain,
55}
56
57/// Which effect owns a ledger key: the intent digest (provider, tool, arguments, catalog), the
58/// world and the winning J-node. The same four things an approval binds, so a key cannot be
59/// replayed as a receipt for a different effect.
60#[derive(Clone, Copy, PartialEq, Eq)]
61struct EffectIdentity {
62 intent: Digest32,
63 world_id: WorldId,
64 winning_jnode: JNodeId,
65}
66
67struct LedgerRow {
68 identity: EffectIdentity,
69 entry: LedgerEntry,
70}
71
72pub(crate) struct Inner {
73 sessions: HashMap<String, McpSession>,
74 ledger: HashMap<EffectId, LedgerRow>,
75 pub(crate) approvals: HashMap<Digest32, ApprovalRecord>,
76 pub(crate) next_approval: u64,
77 pub(crate) next_reservation: u64,
78}
79
80/// Owns admitted MCP sessions and the idempotency ledger.
81#[derive(Clone)]
82pub struct McpBroker {
83 inner: Arc<Mutex<Inner>>,
84}
85
86impl McpBroker {
87 pub fn new() -> Self {
88 Self {
89 inner: Arc::new(Mutex::new(Inner {
90 sessions: HashMap::new(),
91 ledger: HashMap::new(),
92 approvals: HashMap::new(),
93 next_approval: 0,
94 next_reservation: 0,
95 })),
96 }
97 }
98
99 /// Enroll a provider. Speculative branches cannot do this.
100 pub async fn admit(&self, provider: ProviderId, wire: Arc<dyn McpWire>) -> Result<(), Error> {
101 let tools = wire.list_tools().await?;
102 let session = McpSession {
103 epoch: 1,
104 catalog_digest: catalog_digest(&tools),
105 tools,
106 wire,
107 };
108 let mut inner = self.lock();
109 inner
110 .sessions
111 .insert(provider.as_str().to_string(), session);
112 Ok(())
113 }
114
115 /// Replace the cached catalog after the provider's schema changes.
116 pub async fn replace_catalog(
117 &self,
118 provider: &ProviderId,
119 tools: Vec<ToolDescriptor>,
120 ) -> Result<(), Error> {
121 let mut inner = self.lock();
122 let session = inner
123 .sessions
124 .get_mut(provider.as_str())
125 .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
126 let digest = catalog_digest(&tools);
127 if digest != session.catalog_digest {
128 session.epoch = session.epoch.saturating_add(1);
129 session.catalog_digest = digest;
130 session.tools = tools;
131 }
132 Ok(())
133 }
134
135 pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
136 self.inner
137 .lock()
138 .unwrap_or_else(|poisoned| poisoned.into_inner())
139 }
140}
141
142impl Default for McpBroker {
143 fn default() -> Self {
144 Self::new()
145 }
146}
147
148/// Lane J-Space is allowed to hold.
149#[derive(Clone)]
150pub struct SpeculativeLane {
151 broker: McpBroker,
152}
153
154impl SpeculativeLane {
155 pub fn new(broker: McpBroker) -> Self {
156 Self { broker }
157 }
158
159 /// Refresh an already admitted provider and return the snapshot.
160 ///
161 /// This does not dial. A provider missing from the session map is
162 /// `NotAdmitted`. Opening a transport is enrollment on [`crate::SessionManager`].
163 pub async fn discovery_snapshot(
164 &self,
165 provider: &ProviderId,
166 ) -> Result<CapabilitySnapshot, Error> {
167 let wire = {
168 let inner = self.broker.lock();
169 let session = inner
170 .sessions
171 .get(provider.as_str())
172 .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
173 session.wire.clone()
174 };
175 let tools = wire.list_tools().await?;
176 let mut inner = self.broker.lock();
177 let session = inner
178 .sessions
179 .get_mut(provider.as_str())
180 .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
181 let digest = catalog_digest(&tools);
182 if digest != session.catalog_digest {
183 session.epoch = session.epoch.saturating_add(1);
184 session.catalog_digest = digest;
185 }
186 session.tools = tools;
187 let generated_at = SystemTime::now();
188 Ok(CapabilitySnapshot {
189 provider: provider.clone(),
190 session_epoch: session.epoch,
191 catalog_digest: session.catalog_digest,
192 tools: session.tools.clone().into(),
193 generated_at,
194 expires_at: generated_at + SNAPSHOT_TTL,
195 })
196 }
197
198 pub async fn invoke_speculative(&self, call: SpeculativeToolCall) -> Result<ToolResult, Error> {
199 let wire = {
200 let inner = self.broker.lock();
201 let session = inner
202 .sessions
203 .get(call.provider.as_str())
204 .ok_or_else(|| Error::NotAdmitted(call.provider.clone()))?;
205 let tool = find_tool(session, &call.tool_name).ok_or_else(|| Error::UnknownTool {
206 provider: call.provider.clone(),
207 tool: call.tool_name.clone(),
208 })?;
209 if !speculation_safe(tool.effects()) {
210 return Err(Error::EffectRequiresCommit);
211 }
212 if tool
213 .effects()
214 .intersects(ToolEffects::SPAWN_PROCESS | ToolEffects::LOCAL_EPHEMERAL)
215 && !call.sandboxed
216 {
217 return Err(Error::SandboxRequired);
218 }
219 session.wire.clone()
220 };
221 match wire.call_tool(&call.tool_name, &call.arguments).await? {
222 CallOutcome::Finished(output) => Ok(ToolResult { output }),
223 CallOutcome::Rejected(reason) => Err(Error::Rejected(reason)),
224 CallOutcome::Uncertain => Err(Error::ReconciliationRequired),
225 }
226 }
227
228 pub async fn stage_effect_intent(
229 &self,
230 provider: &ProviderId,
231 tool_name: &str,
232 arguments: Value,
233 ) -> Result<EffectIntent, Error> {
234 let inner = self.broker.lock();
235 let session = inner
236 .sessions
237 .get(provider.as_str())
238 .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
239 let tool = find_tool(session, tool_name).ok_or_else(|| Error::UnknownTool {
240 provider: provider.clone(),
241 tool: tool_name.to_string(),
242 })?;
243 if speculation_safe(tool.effects()) {
244 return Err(Error::SpeculationSafe);
245 }
246 Ok(EffectIntent {
247 provider: provider.clone(),
248 tool_name: tool_name.to_string(),
249 arguments,
250 capability_digest: session.catalog_digest,
251 })
252 }
253}
254
255/// Request J-Space may make on the speculative lane.
256pub struct SpeculativeToolCall {
257 pub provider: ProviderId,
258 pub tool_name: String,
259 pub arguments: Value,
260 pub sandboxed: bool,
261}
262
263/// Lane the Effect Broker holds. `execute_effect` accepts only an authorized effect.
264#[derive(Clone)]
265pub struct EffectLane {
266 broker: McpBroker,
267 exposure: Option<Exposure>,
268 clock: Option<Clock>,
269 trace: LaneTrace,
270}
271
272/// Correlation tap of one lane. Observational: it never changes a verdict.
273#[derive(Clone)]
274struct LaneTrace {
275 sink: Arc<dyn TraceSink>,
276 trace_id: TraceId,
277 parent: Option<u64>,
278}
279
280impl LaneTrace {
281 fn off() -> Self {
282 Self {
283 sink: Arc::new(NullSink),
284 trace_id: TraceId([0; 16]),
285 parent: None,
286 }
287 }
288
289 fn enabled(&self) -> bool {
290 self.sink.enabled()
291 }
292
293 fn emit(
294 &self,
295 kind: EventKind,
296 status: EventStatus,
297 certainty: Option<EffectCertainty>,
298 ids: CorrelationIds,
299 refs: EvidenceRefs,
300 note: Option<&str>,
301 ) {
302 self.sink.emit(TraceEvent {
303 trace_id: self.trace_id,
304 event_id: self.sink.next_event_id(),
305 parent_event_id: self.parent,
306 at_unix_ms: now_unix_ms(),
307 kind,
308 status,
309 effect_certainty: certainty,
310 ids,
311 refs,
312 note: note.map(BoundedNote::new),
313 });
314 }
315}
316
317const STALE_INTENT: &str = "intent was staged against a stale catalog";
318const NOT_ADMITTED: &str = "provider is not admitted";
319/// The lane has no way to enforce a restriction list, so a non-empty one is refused rather than
320/// minted as if it were a plain `Allow`.
321const UNENFORCED_RESTRICTIONS: &str =
322 "restricted allow refused: the lane cannot enforce restrictions";
323
324fn hex(bytes: &[u8]) -> String {
325 const H: &[u8; 16] = b"0123456789abcdef";
326 let mut s = String::with_capacity(bytes.len() * 2);
327 for b in bytes {
328 s.push(H[(b >> 4) as usize] as char);
329 s.push(H[(b & 15) as usize] as char);
330 }
331 s
332}
333
334fn put_str(out: &mut Vec<u8>, s: &str) {
335 out.extend_from_slice(&(s.len() as u64).to_le_bytes());
336 out.extend_from_slice(s.as_bytes());
337}
338
339// Canonical, length-prefixed encoding of a JSON value: object keys sorted, so the
340// result does not depend on serde_json's map order feature.
341fn put_value(out: &mut Vec<u8>, v: &Value) {
342 match v {
343 Value::Null => out.push(0),
344 Value::Bool(b) => out.extend_from_slice(&[1, *b as u8]),
345 Value::Number(n) => {
346 out.push(2);
347 put_str(out, &n.to_string());
348 }
349 Value::String(s) => {
350 out.push(3);
351 put_str(out, s);
352 }
353 Value::Array(a) => {
354 out.push(4);
355 out.extend_from_slice(&(a.len() as u64).to_le_bytes());
356 for x in a {
357 put_value(out, x);
358 }
359 }
360 Value::Object(m) => {
361 out.push(5);
362 out.extend_from_slice(&(m.len() as u64).to_le_bytes());
363 let mut keys: Vec<&String> = m.keys().collect();
364 keys.sort();
365 for k in keys {
366 put_str(out, k);
367 put_value(out, &m[k]);
368 }
369 }
370 }
371}
372
373/// SHA-256 over a canonical encoding of every receipt field: a domain tag, then fixed-width
374/// ids and digests, then length-prefixed strings, then the output value with sorted object
375/// keys. A trace carries this digest, never the output itself. The independent receipt
376/// verifier, not this digest, governs whether a receipt is believed.
377pub fn receipt_digest(r: &EffectReceipt) -> [u8; 32] {
378 let mut b = Vec::new();
379 b.extend_from_slice(b"aien-mcp.effect-receipt.v1\0");
380 b.extend_from_slice(&r.effect_id.0);
381 b.extend_from_slice(&r.world_id.0.to_le_bytes());
382 b.extend_from_slice(&r.winning_jnode.0.to_le_bytes());
383 b.extend_from_slice(&r.policy_digest.0);
384 put_str(&mut b, r.provider.as_str());
385 put_str(&mut b, &r.tool_name);
386 b.extend_from_slice(&r.capability_digest.0);
387 put_value(&mut b, &r.output);
388 Digest32::of(&b).0
389}
390
391/// Host-supplied time source, in the same unit as `now` and `expires_at`.
392pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
393
394impl EffectLane {
395 pub fn new(broker: McpBroker) -> Self {
396 Self {
397 broker,
398 exposure: None,
399 clock: None,
400 trace: LaneTrace::off(),
401 }
402 }
403
404 /// A lane whose `execute_effect` re-checks approval expiry at commit using `clock`. The crate
405 /// reads no wall clock itself. A lane without a clock refuses to run any effect that holds an
406 /// approval reservation (`Error::ApprovalClockMissing`) and releases the grant. Effects
407 /// without a reservation do not need a clock.
408 pub fn with_clock(&self, clock: Clock) -> Self {
409 Self {
410 clock: Some(clock),
411 ..self.clone()
412 }
413 }
414
415 /// A lane that tells authorities what the model was exposed to. Host/runtime call only:
416 /// an intent cannot carry exposure. A lane built with [`Self::new`] has no exposure, which
417 /// [`crate::EffectClassAuthority`] treats as `external_untrusted` for effect classes (fail closed).
418 pub fn with_exposure(&self, exposure: Exposure) -> Self {
419 Self {
420 broker: self.broker.clone(),
421 exposure: Some(exposure),
422 clock: self.clock.clone(),
423 trace: self.trace.clone(),
424 }
425 }
426
427 /// Attach a correlation trace (observational only). Every `authority_decided` and
428 /// `effect_executed` event of this lane becomes a child of `parent_event` in `trace_id`. Events
429 /// carry digests and ids, never arguments or outputs. The default is a `NullSink`.
430 pub fn with_trace(
431 self,
432 sink: Arc<dyn TraceSink>,
433 trace_id: TraceId,
434 parent_event: Option<u64>,
435 ) -> Self {
436 Self {
437 trace: LaneTrace {
438 sink,
439 trace_id,
440 parent: parent_event,
441 },
442 ..self
443 }
444 }
445
446 /// Ask `authority` whether `intent` may run, and mint an `AuthorizedEffect` only on
447 /// `Allow` or an `AllowRestricted` with no restrictions. This is the only production path to
448 /// an `AuthorizedEffect`. A non-empty restriction list is denied: nothing here can enforce it.
449 ///
450 /// The lane, not the caller, reads the live descriptor for the authority. A stale intent
451 /// (digest differs from the live catalog) is denied before the authority is asked.
452 /// `RequireApproval` returns `Pending` with the intent digest; no approval is consumed here
453 /// (see [`Self::authorize_approved`]). `Deny` and `Contain` return errors.
454 pub fn authorize(
455 &self,
456 intent: EffectIntent,
457 scope: EffectScope,
458 authority: &dyn EffectAuthority,
459 ) -> Result<AuthorizedEffect<EffectIntent>, AuthorityOutcome> {
460 self.authorize_inner(intent, scope, authority, None)
461 }
462
463 /// Like [`Self::authorize`], but a `RequireApproval` verdict is satisfied by spending `grant`.
464 ///
465 /// The grant must have been issued by an [`crate::ApprovalDesk`] for exactly this intent and
466 /// scope, must be unspent, unrevoked and unexpired (`now < expires_at`). A refused grant is not spent
467 /// unless it was already spent. `Deny` and `Contain` stay refused whatever the grant says,
468 /// and an `Allow` verdict never touches the grant.
469 pub fn authorize_approved(
470 &self,
471 intent: EffectIntent,
472 scope: EffectScope,
473 authority: &dyn EffectAuthority,
474 grant: &ApprovalGrant,
475 now: u64,
476 ) -> Result<AuthorizedEffect<EffectIntent>, AuthorityOutcome> {
477 self.authorize_inner(intent, scope, authority, Some((grant, now)))
478 }
479
480 fn authorize_inner(
481 &self,
482 intent: EffectIntent,
483 scope: EffectScope,
484 authority: &dyn EffectAuthority,
485 approval: Option<(&ApprovalGrant, u64)>,
486 ) -> Result<AuthorizedEffect<EffectIntent>, AuthorityOutcome> {
487 if !self.trace.enabled() {
488 return self.authorize_core(intent, scope, authority, approval);
489 }
490 let digest = intent_digest(&intent);
491 let mut ids = self.effect_ids(&intent.provider, &intent.tool_name, scope.world_id);
492 let presented = approval.map(|(g, _)| hex(&g.id().0));
493 let result = self.authorize_core(intent, scope, authority, approval);
494 let (status, note): (EventStatus, Option<&str>) = match &result {
495 Ok(_) => (EventStatus::Ok, None),
496 Err(AuthorityOutcome::Pending { .. }) => (EventStatus::ApprovalPending, None),
497 Err(AuthorityOutcome::Denied(r)) if r == STALE_INTENT => {
498 (EventStatus::Rejected, Some("stale_intent"))
499 }
500 Err(AuthorityOutcome::Denied(r)) if r == NOT_ADMITTED => {
501 (EventStatus::Rejected, Some("provider_not_admitted"))
502 }
503 Err(AuthorityOutcome::Denied(_)) => (EventStatus::Rejected, None),
504 Err(AuthorityOutcome::Contained(_)) => (EventStatus::Rejected, Some("contained")),
505 Err(AuthorityOutcome::Approval(e)) => (EventStatus::Rejected, Some(approval_name(e))),
506 Err(AuthorityOutcome::Execution(_)) => (EventStatus::Failed, None),
507 };
508 let grant = match &result {
509 Ok(e) => e.approval_id().map(|d| hex(&d.0)),
510 Err(_) => presented,
511 };
512 if let Some(grant) = grant {
513 ids.grant_id = Some(BoundedId::new(&grant));
514 }
515 let refs = EvidenceRefs {
516 intent_digest: aien_trace::Digest::new(&hex(&digest.0)).ok(),
517 ..Default::default()
518 };
519 self.trace
520 .emit(EventKind::AuthorityDecided, status, None, ids, refs, note);
521 result
522 }
523
524 fn effect_ids(&self, provider: &ProviderId, tool: &str, world: WorldId) -> CorrelationIds {
525 let mut name = String::with_capacity(provider.as_str().len() + 1 + tool.len());
526 name.push_str(provider.as_str());
527 name.push(':');
528 name.push_str(tool);
529 CorrelationIds {
530 world_id: Some(world.0),
531 tool_request_id: Some(BoundedId::new(&name)),
532 ..Default::default()
533 }
534 }
535
536 fn authorize_core(
537 &self,
538 intent: EffectIntent,
539 scope: EffectScope,
540 authority: &dyn EffectAuthority,
541 approval: Option<(&ApprovalGrant, u64)>,
542 ) -> Result<AuthorizedEffect<EffectIntent>, AuthorityOutcome> {
543 let (descriptor, live) = {
544 let inner = self.broker.lock();
545 let session = inner
546 .sessions
547 .get(intent.provider.as_str())
548 .ok_or_else(|| AuthorityOutcome::Denied(NOT_ADMITTED.into()))?;
549 (
550 find_tool(session, &intent.tool_name).cloned(),
551 session.catalog_digest,
552 )
553 };
554 if intent.capability_digest != live {
555 return Err(AuthorityOutcome::Denied(STALE_INTENT.into()));
556 }
557 let ctx = AuthorityContext::new(scope, descriptor, live, self.exposure.clone());
558 let decision = authority.authorize(&intent, &ctx);
559 let policy_digest = {
560 let mut bytes = format!("{decision:?}|{}|", intent.tool_name).into_bytes();
561 bytes.extend_from_slice(&live.0);
562 Digest32::of(&bytes)
563 };
564 match decision {
565 AuthorityDecision::AllowRestricted(ref restrictions) if !restrictions.is_empty() => {
566 Err(AuthorityOutcome::Denied(UNENFORCED_RESTRICTIONS.into()))
567 }
568 AuthorityDecision::Allow | AuthorityDecision::AllowRestricted(_) => Ok(mint(
569 intent,
570 scope.world_id,
571 scope.winning_jnode,
572 policy_digest,
573 live,
574 scope.idempotency_key,
575 )),
576 AuthorityDecision::RequireApproval(reason) => {
577 let Some((grant, now)) = approval else {
578 return Err(AuthorityOutcome::Pending {
579 intent_digest: intent_digest(&intent),
580 reason,
581 });
582 };
583 let reservation = self
584 .reserve(grant, &intent, &scope, now)
585 .map_err(AuthorityOutcome::Approval)?;
586 Ok(mint_reserved(
587 intent,
588 scope.world_id,
589 scope.winning_jnode,
590 policy_digest,
591 live,
592 scope.idempotency_key,
593 reservation,
594 ))
595 }
596 AuthorityDecision::Deny(reason) => Err(AuthorityOutcome::Denied(reason)),
597 AuthorityDecision::Contain(reason) => Err(AuthorityOutcome::Contained(reason)),
598 }
599 }
600
601 /// `authorize`, then `execute_effect`. Nothing reaches the provider unless authorized.
602 pub async fn authorize_and_execute(
603 &self,
604 intent: EffectIntent,
605 scope: EffectScope,
606 authority: &dyn EffectAuthority,
607 ) -> Result<EffectReceipt, AuthorityOutcome> {
608 let effect = self.authorize(intent, scope, authority)?;
609 self.execute_effect(effect)
610 .await
611 .map_err(AuthorityOutcome::Execution)
612 }
613
614 /// `authorize_approved`, then `execute_effect`.
615 ///
616 /// If `grant` is already spent for this same effect (same intent, key, world, J-node), the
617 /// request is a replay: the ledger's existing outcome is returned and nothing is minted.
618 /// Any other use of a spent grant is refused with `ApprovalError::Consumed`.
619 pub async fn authorize_and_execute_approved(
620 &self,
621 intent: EffectIntent,
622 scope: EffectScope,
623 authority: &dyn EffectAuthority,
624 grant: &ApprovalGrant,
625 now: u64,
626 ) -> Result<EffectReceipt, AuthorityOutcome> {
627 if let Some(existing) = self.replay_of(grant, &intent, &scope) {
628 if self.trace.enabled() {
629 let mut ids = self.effect_ids(&intent.provider, &intent.tool_name, scope.world_id);
630 ids.grant_id = Some(BoundedId::new(&hex(&grant.id().0)));
631 self.trace_execution(&existing, true, ids, Some(intent_digest(&intent)));
632 }
633 return existing.map_err(AuthorityOutcome::Execution);
634 }
635 let effect = self.authorize_approved(intent, scope, authority, grant, now)?;
636 self.execute_effect(effect)
637 .await
638 .map_err(AuthorityOutcome::Execution)
639 }
640
641 /// Ledger outcome for a spent grant presented again for the effect it was spent on.
642 fn replay_of(
643 &self,
644 grant: &ApprovalGrant,
645 intent: &EffectIntent,
646 scope: &EffectScope,
647 ) -> Option<Result<EffectReceipt, Error>> {
648 let inner = self.broker.lock();
649 let record = inner.approvals.get(&grant.id())?;
650 if record.state != GrantState::Spent || !record.binds(intent, scope) {
651 return None;
652 }
653 let row = inner.ledger.get(&scope.idempotency_key)?;
654 if row.identity != identity(intent, scope.world_id, scope.winning_jnode) {
655 return Some(Err(Error::IdempotencyConflict));
656 }
657 match &row.entry {
658 LedgerEntry::Completed(receipt) => Some(Ok(receipt.clone())),
659 LedgerEntry::Uncertain => Some(Err(Error::ReconciliationRequired)),
660 LedgerEntry::InFlight => Some(Err(Error::EffectInFlight)),
661 }
662 }
663
664 /// Check and reserve `grant` atomically under the broker lock. The returned reservation is
665 /// committed by `execute_effect` and released if the effect is dropped or cancelled.
666 fn reserve(
667 &self,
668 grant: &ApprovalGrant,
669 intent: &EffectIntent,
670 scope: &EffectScope,
671 now: u64,
672 ) -> Result<Reservation, ApprovalError> {
673 let mut inner = self.broker.lock();
674 let record = inner
675 .approvals
676 .get_mut(&grant.id())
677 .ok_or(ApprovalError::Unknown)?;
678 if !record.binds(intent, scope) {
679 return Err(ApprovalError::Mismatch);
680 }
681 match record.state {
682 GrantState::Spent => return Err(ApprovalError::Consumed),
683 GrantState::Reserved(_) => return Err(ApprovalError::Reserved),
684 GrantState::Available => {}
685 }
686 if record.revoked {
687 return Err(ApprovalError::Revoked);
688 }
689 if now >= record.expires_at {
690 return Err(ApprovalError::Expired);
691 }
692 let token = {
693 inner.next_reservation = inner.next_reservation.saturating_add(1);
694 inner.next_reservation
695 };
696 let record = inner
697 .approvals
698 .get_mut(&grant.id())
699 .ok_or(ApprovalError::Unknown)?;
700 record.state = GrantState::Reserved(token);
701 record.release_reason = None;
702 Ok(Reservation::new(self.broker.clone(), grant.id(), token))
703 }
704
705 pub async fn execute_effect(
706 &self,
707 effect: AuthorizedEffect<EffectIntent>,
708 ) -> Result<EffectReceipt, Error> {
709 if !self.trace.enabled() {
710 return self.execute_core(effect, &mut false).await;
711 }
712 let mut ids = self.effect_ids(
713 &effect.intent().provider,
714 &effect.intent().tool_name,
715 effect.world_id(),
716 );
717 ids.grant_id = effect.approval_id().map(|d| BoundedId::new(&hex(&d.0)));
718 let digest = intent_digest(effect.intent());
719 let mut replay = false;
720 let result = self.execute_core(effect, &mut replay).await;
721 self.trace_execution(&result, replay, ids, Some(digest));
722 result
723 }
724
725 fn trace_execution(
726 &self,
727 result: &Result<EffectReceipt, Error>,
728 replay: bool,
729 ids: CorrelationIds,
730 intent: Option<Digest32>,
731 ) {
732 let mut refs = EvidenceRefs {
733 intent_digest: intent.and_then(|d| aien_trace::Digest::new(&hex(&d.0)).ok()),
734 ..Default::default()
735 };
736 let (status, certainty, note) = match result {
737 Ok(receipt) => {
738 refs.effect_receipt_digest =
739 aien_trace::Digest::new(&hex(&receipt_digest(receipt))).ok();
740 let note = replay.then_some("ledger_replay");
741 (EventStatus::Ok, Some(EffectCertainty::EffectOccurred), note)
742 }
743 Err(Error::Rejected(_)) => {
744 (EventStatus::Rejected, Some(EffectCertainty::NoEffect), None)
745 }
746 Err(Error::ReconciliationRequired) => (
747 EventStatus::Uncertain,
748 Some(EffectCertainty::Uncertain),
749 None,
750 ),
751 Err(Error::EffectInFlight) => (EventStatus::Rejected, None, Some("in_flight")),
752 Err(_) => (
753 EventStatus::Rejected,
754 Some(EffectCertainty::NoEffect),
755 Some("refused"),
756 ),
757 };
758 self.trace.emit(
759 EventKind::EffectExecuted,
760 status,
761 certainty,
762 ids,
763 refs,
764 note,
765 );
766 }
767
768 async fn execute_core(
769 &self,
770 effect: AuthorizedEffect<EffectIntent>,
771 replay: &mut bool,
772 ) -> Result<EffectReceipt, Error> {
773 let key = effect.idempotency_key();
774 let provider = effect.intent().provider.clone();
775 let tool_name = effect.intent().tool_name.clone();
776 let arguments = effect.intent().arguments.clone();
777 let staged_catalog = effect.intent().capability_digest;
778 let who = identity(effect.intent(), effect.world_id(), effect.winning_jnode());
779 let wire = {
780 let mut inner = self.broker.lock();
781 if let Some(existing) = inner.ledger.get(&key) {
782 // A key names one effect. A request for another effect under the same key did not
783 // run and must not be answered with the first effect's receipt.
784 if existing.identity != who {
785 return Err(Error::IdempotencyConflict);
786 }
787 return match &existing.entry {
788 LedgerEntry::Completed(receipt) => {
789 *replay = true;
790 Ok(receipt.clone())
791 }
792 LedgerEntry::Uncertain => Err(Error::ReconciliationRequired),
793 LedgerEntry::InFlight => Err(Error::EffectInFlight),
794 };
795 }
796 let wire = {
797 let session = inner
798 .sessions
799 .get(provider.as_str())
800 .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
801 if session.catalog_digest != effect.capability_digest()
802 || staged_catalog != effect.capability_digest()
803 {
804 return Err(Error::StaleCapability);
805 }
806 if find_tool(session, &tool_name).is_none() {
807 return Err(Error::UnknownTool {
808 provider: provider.clone(),
809 tool: tool_name.clone(),
810 });
811 }
812 session.wire.clone()
813 };
814 // Point of no return: the provider is about to be called. Until here a refusal drops
815 // the effect and releases its grant; from here the grant is spent.
816 if let Some(reservation) = effect.reservation() {
817 let now = self.clock.as_ref().map(|c| c());
818 reservation.commit_locked(&mut inner, now)?;
819 }
820 inner.ledger.insert(
821 key,
822 LedgerRow {
823 identity: who,
824 entry: LedgerEntry::InFlight,
825 },
826 );
827 wire
828 };
829
830 let outcome = wire.call_tool(&tool_name, &arguments).await;
831 let mut inner = self.broker.lock();
832 match outcome {
833 Ok(CallOutcome::Finished(output)) => {
834 let receipt = EffectReceipt {
835 effect_id: key,
836 world_id: effect.world_id(),
837 winning_jnode: effect.winning_jnode(),
838 policy_digest: effect.policy_digest(),
839 provider,
840 tool_name,
841 capability_digest: effect.capability_digest(),
842 output,
843 };
844 inner.ledger.insert(
845 key,
846 LedgerRow {
847 identity: who,
848 entry: LedgerEntry::Completed(receipt.clone()),
849 },
850 );
851 Ok(receipt)
852 }
853 Ok(CallOutcome::Uncertain) | Err(_) => {
854 inner.ledger.insert(
855 key,
856 LedgerRow {
857 identity: who,
858 entry: LedgerEntry::Uncertain,
859 },
860 );
861 Err(Error::ReconciliationRequired)
862 }
863 Ok(CallOutcome::Rejected(reason)) => {
864 inner.ledger.remove(&key);
865 Err(Error::Rejected(reason))
866 }
867 }
868 }
869}
870
871fn identity(intent: &EffectIntent, world_id: WorldId, winning_jnode: JNodeId) -> EffectIdentity {
872 EffectIdentity {
873 intent: intent_digest(intent),
874 world_id,
875 winning_jnode,
876 }
877}
878
879fn find_tool<'a>(session: &'a McpSession, name: &str) -> Option<&'a ToolDescriptor> {
880 session.tools.iter().find(|tool| tool.name() == name)
881}
882
883fn approval_name(e: &ApprovalError) -> &'static str {
884 match e {
885 ApprovalError::Unknown => "approval_unknown",
886 ApprovalError::Mismatch => "approval_mismatch",
887 ApprovalError::Consumed => "approval_consumed",
888 ApprovalError::Reserved => "approval_reserved",
889 ApprovalError::Expired => "approval_expired",
890 ApprovalError::Revoked => "approval_revoked",
891 }
892}