agent_engine/tools/activation.rs
1//! `SessionToolSet` — per-session core + exact activated tools (Task 15,
2//! spec §7.1, §4.2).
3//!
4//! This is bookkeeping only, not yet an execution gate: it records which
5//! configured core tools and which exactly-activated deferred tools belong to
6//! one session, pinned to the catalog generation and schema digests they were
7//! granted against. It never issues model-facing activations, exposes
8//! schemas, initializes implementations, or enforces execution.
9//!
10//! Isolation invariants:
11//! - a new session's set starts with zero activations and inherits nothing
12//! from any other set;
13//! - activation requires an exact [`SessionActivationGrant`] for this
14//! session, tool, current catalog generation, and current schema digest;
15//! - every rejection is typed and leaves the set unchanged (no partial
16//! mutation);
17//! - catalog drift is represented (`is_stale`), never silently absorbed.
18
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use agent_core::BoundedText;
23use thiserror::Error;
24
25use super::catalog::{
26 CapabilityRecord, CapabilitySource, CatalogGeneration, SchemaDigest, SessionActivationGrant,
27 ToolCatalog, ToolEffect, ToolId, TrustProvenance,
28};
29use super::{Tool, ToolRegistry};
30
31pub use agent_core::orchestration::capability::{SessionId, SessionIdError};
32
33/// Runtime-lease placeholder metadata (spec §7.4 territory). Real lease
34/// acquisition/expiry arrives with MCP/extension activation work; until then
35/// every activation records that no runtime has been acquired.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
37#[serde(rename_all = "snake_case")]
38pub enum RuntimeLease {
39 NotAcquired,
40}
41
42/// One exact activation held by a session: the validated grant plus lease
43/// placeholder metadata. The grant carries the pinned catalog generation and
44/// schema digest; the trust provenance of the catalog record is pinned
45/// engine-side at activation time (the grant type in agent-core is
46/// deliberately untouched) so execution can detect a record that was
47/// removed and re-added under a different — even internally coherent —
48/// source/provenance.
49#[derive(Clone, Debug)]
50pub struct ActivatedTool {
51 grant: SessionActivationGrant,
52 provenance: TrustProvenance,
53 lease: RuntimeLease,
54}
55
56impl ActivatedTool {
57 pub fn grant(&self) -> &SessionActivationGrant {
58 &self.grant
59 }
60
61 pub fn schema_digest(&self) -> &SchemaDigest {
62 self.grant.schema_digest()
63 }
64
65 /// The trust provenance of the catalog record at activation time.
66 pub fn provenance(&self) -> &TrustProvenance {
67 &self.provenance
68 }
69
70 pub fn catalog_generation(&self) -> CatalogGeneration {
71 self.grant.catalog_generation()
72 }
73
74 pub fn lease(&self) -> RuntimeLease {
75 self.lease
76 }
77}
78
79/// Typed failure for [`SessionToolSet::revoke_exact`].
80#[derive(Clone, Debug, Error, PartialEq, Eq)]
81pub enum ExactRevocationError {
82 #[error("cannot revoke a configured core tool: {0}")]
83 CoreTool(ToolId),
84 #[error("tool is not activated in this session: {0}")]
85 NotActivated(ToolId),
86}
87
88/// Typed failure for constructing a [`SessionToolSet`].
89#[derive(Clone, Debug, Error, PartialEq, Eq)]
90pub enum SessionToolSetError {
91 #[error("configured core tool is not in the catalog: {0}")]
92 UnknownCoreTool(ToolId),
93}
94
95/// Typed failure for activating a tool in a [`SessionToolSet`]. Every
96/// variant fails closed without mutating the set.
97#[derive(Clone, Debug, Error, PartialEq, Eq)]
98pub enum ActivationError {
99 #[error("activation grant was issued for another session")]
100 SessionMismatch,
101 #[error("activation grant names a tool the catalog does not know: {0}")]
102 UnknownTool(ToolId),
103 #[error(
104 "activation grant generation {} does not match current catalog generation {}",
105 grant.value(),
106 catalog.value()
107 )]
108 StaleGeneration {
109 grant: CatalogGeneration,
110 catalog: CatalogGeneration,
111 },
112 #[error("activation grant schema digest does not match the catalog record for {0}")]
113 DigestMismatch(ToolId),
114 #[error("tool is already activated for this session: {0}")]
115 AlreadyActivated(ToolId),
116 #[error("tool is already in this session's configured core set: {0}")]
117 AlreadyCore(ToolId),
118 #[error(
119 "session tool set snapshot at generation {} is stale against catalog generation {}; rebuild it",
120 set.value(),
121 catalog.value()
122 )]
123 StaleSnapshot {
124 set: CatalogGeneration,
125 catalog: CatalogGeneration,
126 },
127}
128
129/// Per-tool pins captured when a core tool enters a session's set: the
130/// schema digest AND the trust provenance of the catalog record at build
131/// time. Pinning provenance (not just the digest) closes the coherent-
132/// imposter hole: a tool removed and re-added under the SAME `ToolId` with a
133/// schema-identical body but a different, internally consistent
134/// source/provenance must still be denied at execution time.
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct CorePin {
137 schema_digest: SchemaDigest,
138 provenance: TrustProvenance,
139}
140
141impl CorePin {
142 pub fn schema_digest(&self) -> &SchemaDigest {
143 &self.schema_digest
144 }
145
146 pub fn provenance(&self) -> &TrustProvenance {
147 &self.provenance
148 }
149}
150
151/// Why an activation was not carried across a round-top rebuild.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
153#[serde(rename_all = "snake_case")]
154pub enum DropReason {
155 /// The tool is no longer in the catalog.
156 Removed,
157 /// The record's schema digest or trust provenance changed.
158 Drifted,
159}
160
161/// One activation dropped by [`SessionToolSet::rebuilt_for_catalog`].
162#[derive(Clone, Debug, PartialEq, Eq)]
163pub struct DroppedActivation {
164 pub id: ToolId,
165 pub reason: DropReason,
166}
167
168/// Kill-switch for carry-forward: `SYNAPS_TOOLSET_CARRY_FORWARD=0` restores
169/// the zero-inherit rebuild (every catalog mutation wipes activations).
170pub fn carry_forward_enabled() -> bool {
171 std::env::var("SYNAPS_TOOLSET_CARRY_FORWARD").as_deref() != Ok("0")
172}
173
174/// One exact activation as plain, serializable data: what a session hands
175/// to its next runtime across a daemon reload (`SessionReloadRecord`) or a
176/// park. It carries the PINS the activation was granted against — never a
177/// grant: the next runtime has a new tool-session id and re-issues a grant
178/// only after [`SessionToolSet::restore_carried`] re-validated the pins
179/// against its own catalog. Untrusted on the way back in (it round-trips
180/// through a file), which is why every field is re-checked, not believed.
181#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
182pub struct CarriedActivation {
183 /// Canonical `ToolId` (`namespace:name`).
184 pub tool_id: String,
185 /// Lowercase hex schema digest pinned at activation time.
186 pub schema_digest: String,
187 /// Trust provenance pinned at activation time.
188 pub provenance: CarriedProvenance,
189}
190
191/// Serializable mirror of [`TrustProvenance`] for [`CarriedActivation`].
192/// Only ever COMPARED with the current catalog record's provenance; never
193/// converted back into a `TrustProvenance`, so wire data cannot mint one.
194#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
195#[serde(tag = "kind", rename_all = "snake_case")]
196pub enum CarriedProvenance {
197 BuiltinRuntime,
198 ExtensionManifest { extension_id: String },
199 McpConfig { server_id: String },
200 PluginConfig { plugin_id: String },
201 Unverified,
202}
203
204impl From<&TrustProvenance> for CarriedProvenance {
205 fn from(p: &TrustProvenance) -> Self {
206 match p {
207 TrustProvenance::BuiltinRuntime => Self::BuiltinRuntime,
208 TrustProvenance::ExtensionManifest { extension_id } => Self::ExtensionManifest {
209 extension_id: extension_id.clone(),
210 },
211 TrustProvenance::McpConfig { server_id } => Self::McpConfig {
212 server_id: server_id.clone(),
213 },
214 TrustProvenance::PluginConfig { plugin_id } => Self::PluginConfig {
215 plugin_id: plugin_id.clone(),
216 },
217 TrustProvenance::Unverified => Self::Unverified,
218 }
219 }
220}
221
222/// Why a carried activation was not restored.
223#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
224#[serde(rename_all = "snake_case")]
225pub enum RestoreDropReason {
226 /// Not in the current catalog (or not a valid `ToolId`).
227 Removed,
228 /// Schema digest, trust provenance or source trust changed.
229 Drifted,
230 /// `tools.activation_confirm = deny` in the restoring runtime.
231 Denied,
232 /// The target set was not built against the current catalog.
233 StaleSet,
234}
235
236/// Outcome of [`SessionToolSet::restore_carried`]: what was restored and
237/// what was dropped (raw id + reason), for logging and the session notice.
238#[derive(Clone, Debug, Default, PartialEq, Eq)]
239pub struct RestoreReport {
240 pub restored: Vec<ToolId>,
241 pub dropped: Vec<(String, RestoreDropReason)>,
242}
243
244/// The small configured core set plus exact activated deferred tools for one
245/// session, pinned to the catalog generation it was built against. Core
246/// tools are pinned with the schema digest AND trust provenance of their
247/// catalog record at build time, so later drift is detectable per tool, not
248/// just per generation.
249#[derive(Clone, Debug)]
250pub struct SessionToolSet {
251 session: SessionId,
252 catalog_generation: CatalogGeneration,
253 core: BTreeMap<ToolId, CorePin>,
254 activated: BTreeMap<ToolId, ActivatedTool>,
255 /// Session schema-generation counter (spec §7.7): advances by exactly
256 /// one for every successful nonempty activation batch (a single
257 /// activation is a batch of one). Deterministic bookkeeping only; it
258 /// exposes nothing and grants nothing.
259 schema_generation: u64,
260}
261
262impl SessionToolSet {
263 /// Build a fresh set for one session. Every configured core id must
264 /// exist in the catalog (typed failure otherwise) and its schema digest
265 /// AND trust provenance are pinned from the catalog record; the set
266 /// starts with zero activations — nothing is inherited from any other
267 /// session.
268 pub fn new(
269 session: SessionId,
270 core: impl IntoIterator<Item = ToolId>,
271 catalog: &ToolCatalog,
272 ) -> Result<Self, SessionToolSetError> {
273 let mut validated = BTreeMap::new();
274 for id in core {
275 let Some(record) = catalog.get(&id) else {
276 return Err(SessionToolSetError::UnknownCoreTool(id));
277 };
278 validated.insert(
279 id,
280 CorePin {
281 schema_digest: record.schema_digest().clone(),
282 provenance: record.provenance().clone(),
283 },
284 );
285 }
286 Ok(Self {
287 session,
288 catalog_generation: catalog.generation(),
289 core: validated,
290 activated: BTreeMap::new(),
291 schema_generation: 0,
292 })
293 }
294
295 pub fn session(&self) -> &SessionId {
296 &self.session
297 }
298
299 /// Default per-stream-session set (Task 16 behavior preservation): the
300 /// core set is EXACTLY every currently cataloged capability with
301 /// verified provenance — builtins plus already-loaded trusted
302 /// extension/MCP/plugin tools. `Unverified` capabilities are excluded
303 /// (denied-by-default at the gate), and the set carries zero
304 /// activations. Deterministic: ids come straight from the catalog in
305 /// `ToolId` order, so rebuilding after a catalog mutation yields the
306 /// same set for the same catalog state.
307 pub fn default_core_for_catalog(session: SessionId, catalog: &ToolCatalog) -> Self {
308 let core: Vec<ToolId> = catalog
309 .iter()
310 .filter(|record| record.provenance() != &TrustProvenance::Unverified)
311 .map(|record| record.id().clone())
312 .collect();
313 Self::new(session, core, catalog)
314 .expect("core ids are drawn from the catalog itself and must all resolve")
315 }
316
317 /// Deterministic minimal core for Task 18 progressive disclosure. Only
318 /// essential local operations plus discovery/authorization gateways are
319 /// eligible; missing/disabled gateways are skipped rather than invented.
320 /// Specialized subagent lifecycle, extension, MCP, shell-session, and
321 /// dynamically registered tools remain deferred until exact activation.
322 pub fn progressive_core_for_catalog(session: SessionId, catalog: &ToolCatalog) -> Self {
323 const ESSENTIAL_BUILTINS: &[&str] = &[
324 "bash",
325 "read",
326 "write",
327 "edit",
328 "grep",
329 "find",
330 "ls",
331 "search_tools",
332 "activate_tools",
333 "search_skills",
334 "load_skill",
335 ];
336 let core = ESSENTIAL_BUILTINS
337 .iter()
338 .map(|name| ToolId::builtin(name))
339 .filter(|id| catalog.get(id).is_some())
340 .collect::<Vec<_>>();
341 Self::new(session, core, catalog)
342 .expect("progressive core ids are filtered through the catalog")
343 }
344
345 /// Round-top rebuild against a NEWER catalog (`runtime/stream.rs`):
346 /// the core is re-derived exactly as a fresh build would derive it, and
347 /// every prior exact activation whose CURRENT catalog record still
348 /// matches its pinned (schema digest, trust provenance) is re-issued a
349 /// grant at the new generation. Activations whose record is gone or
350 /// drifted are dropped and reported.
351 ///
352 /// This is NOT a gate change: a carried activation is exactly what a
353 /// user re-activation of the same tool would produce against this
354 /// catalog, and `ExecutionGate::authorize` still checks digest and
355 /// provenance against the current record on every call.
356 pub fn rebuilt_for_catalog(
357 &self,
358 catalog: &ToolCatalog,
359 progressive: bool,
360 ) -> (Self, Vec<DroppedActivation>) {
361 let next = if progressive {
362 Self::progressive_core_for_catalog(self.session.clone(), catalog)
363 } else {
364 Self::default_core_for_catalog(self.session.clone(), catalog)
365 };
366 self.carry_activations_into(next, catalog)
367 }
368
369 /// Carry this set's exact activations into `next` — a freshly built core
370 /// for the SAME session against `catalog` — with exactly the checks
371 /// [`Self::rebuilt_for_catalog`] applies (pinned digest + provenance
372 /// unchanged and source trust intact; promoted-to-core ids are not
373 /// carried; drifted/removed ones are dropped and reported). Shared by the
374 /// round-top rebuild and the turn-start reconciliation of a retained
375 /// set, so the two paths can never drift.
376 ///
377 /// A `next` built for a different session inherits nothing: grants never
378 /// cross sessions.
379 pub fn carry_activations_into(
380 &self,
381 mut next: SessionToolSet,
382 catalog: &ToolCatalog,
383 ) -> (Self, Vec<DroppedActivation>) {
384 if next.session != self.session {
385 return (next, Vec::new());
386 }
387 let mut dropped = Vec::new();
388 for old in self.activated.values() {
389 let id = old.grant().tool_id().clone();
390 if let Err(reason) = next.admit_pinned(&id, catalog, |rec| {
391 rec.schema_digest() == old.schema_digest() && rec.provenance() == old.provenance()
392 }) {
393 dropped.push(DroppedActivation { id, reason });
394 }
395 }
396 // Session schema-generation is bookkeeping for "activation batches
397 // applied"; carrying is not a batch: keep the old counter, +1 iff
398 // anything was dropped (the exposed schema changed).
399 next.schema_generation = self.schema_generation + u64::from(!dropped.is_empty());
400 (next, dropped)
401 }
402
403 /// Admit one prior activation of THIS session into this set against
404 /// `catalog` — the single check shared by turn-to-turn carrying
405 /// ([`Self::carry_activations_into`]) and cross-image restore
406 /// ([`Self::restore_carried`]), so the two can never drift:
407 ///
408 /// - uncataloged → `Removed`;
409 /// - already core → `Ok` (still on the wire, nothing to record);
410 /// - `pin_matches(record)` (the pinned schema digest AND trust
411 /// provenance are unchanged) AND the record's source still agrees with
412 /// its provenance (`check_source_trust`, as `activate_many`) → a grant
413 /// at the CURRENT catalog generation is recorded;
414 /// - anything else → `Drifted`, never silently re-granted.
415 ///
416 /// Already-activated ids are left as they are (`Ok`). Does not touch the
417 /// schema-generation counter; callers own that bookkeeping.
418 fn admit_pinned(
419 &mut self,
420 id: &ToolId,
421 catalog: &ToolCatalog,
422 pin_matches: impl FnOnce(&CapabilityRecord) -> bool,
423 ) -> Result<(), DropReason> {
424 let Some(rec) = catalog.get(id) else {
425 return Err(DropReason::Removed);
426 };
427 if self.core.contains_key(id) || self.activated.contains_key(id) {
428 return Ok(());
429 }
430 if !(pin_matches(rec) && check_source_trust(rec).is_ok()) {
431 return Err(DropReason::Drifted);
432 }
433 let grant = SessionActivationGrant::new(
434 self.session.as_str(),
435 id.clone(),
436 catalog.generation(),
437 rec.schema_digest().clone(),
438 )
439 .expect("session id was valid when the set was built");
440 self.activated.insert(
441 id.clone(),
442 ActivatedTool {
443 grant,
444 provenance: rec.provenance().clone(),
445 lease: RuntimeLease::NotAcquired,
446 },
447 );
448 Ok(())
449 }
450
451 /// This session's exact activations as plain data, in `ToolId` order —
452 /// what a daemon reload or a park hands to the session's next runtime
453 /// (see [`CarriedActivation`]). Core tools are not included: the next
454 /// runtime re-derives its core from its own catalog.
455 pub fn carried_activations(&self) -> Vec<CarriedActivation> {
456 self.activated
457 .values()
458 .map(|a| CarriedActivation {
459 tool_id: a.grant().tool_id().as_str().to_string(),
460 schema_digest: a.schema_digest().as_hex().to_string(),
461 provenance: CarriedProvenance::from(a.provenance()),
462 })
463 .collect()
464 }
465
466 /// Restore activations this SAME conversation held in a previous
467 /// runtime (a daemon reload's previous image, or the runtime a park
468 /// dropped) into this set, which must be freshly built against
469 /// `catalog` for the new runtime's tool session.
470 ///
471 /// This continues grants the session already had; it is not a new
472 /// grant. Each entry is re-validated against the CURRENT catalog with
473 /// exactly the pins [`ToolRegistry::session_tools_schema`] and the
474 /// execution gate check — schema digest AND trust provenance — plus
475 /// source trust; an entry that is unparsable, uncataloged, or drifted
476 /// is dropped fail-closed and reported, never re-granted. Restored
477 /// grants are issued for THIS set's session at the current generation,
478 /// so the execution gate authorizes them like any other activation.
479 ///
480 /// Activation policy (`tools.activation_confirm`) is the caller's
481 /// decision (see `runtime::stream::restore_pending_activations`).
482 /// Advances the schema-generation counter by one iff anything was
483 /// restored (one batch), like `activate_many`.
484 pub fn restore_carried(
485 &mut self,
486 carried: &[CarriedActivation],
487 catalog: &ToolCatalog,
488 ) -> RestoreReport {
489 let mut report = RestoreReport::default();
490 if self.catalog_generation != catalog.generation() {
491 // A stale snapshot cannot take grants (as `validate_grant`):
492 // the caller rebuilds against `catalog` first.
493 report.dropped = carried
494 .iter()
495 .map(|c| (c.tool_id.clone(), RestoreDropReason::StaleSet))
496 .collect();
497 return report;
498 }
499 for c in carried {
500 let Ok(id) = ToolId::parse(&c.tool_id) else {
501 report
502 .dropped
503 .push((c.tool_id.clone(), RestoreDropReason::Removed));
504 continue;
505 };
506 let was_new = !self.core.contains_key(&id) && !self.activated.contains_key(&id);
507 match self.admit_pinned(&id, catalog, |rec| {
508 rec.schema_digest().as_hex() == c.schema_digest
509 && CarriedProvenance::from(rec.provenance()) == c.provenance
510 }) {
511 Ok(()) if was_new && self.activated.contains_key(&id) => {
512 report.restored.push(id);
513 }
514 Ok(()) => {}
515 Err(DropReason::Removed) => {
516 report
517 .dropped
518 .push((c.tool_id.clone(), RestoreDropReason::Removed));
519 }
520 Err(DropReason::Drifted) => {
521 report
522 .dropped
523 .push((c.tool_id.clone(), RestoreDropReason::Drifted));
524 }
525 }
526 }
527 if !report.restored.is_empty() {
528 self.schema_generation += 1;
529 }
530 report
531 }
532
533 /// Typed EXACT revocation (Task 19 grant invalidation): remove one
534 /// non-core exact activation from this session's set. The session
535 /// schema generation advances by exactly one IFF an activation was
536 /// removed; core tools and unknown/never-activated ids fail typed with
537 /// zero mutation. Never touches the catalog or sibling activations.
538 pub fn revoke_exact(&mut self, id: &ToolId) -> Result<(), ExactRevocationError> {
539 if self.core.contains_key(id) {
540 return Err(ExactRevocationError::CoreTool(id.clone()));
541 }
542 if self.activated.remove(id).is_none() {
543 return Err(ExactRevocationError::NotActivated(id.clone()));
544 }
545 self.schema_generation += 1;
546 Ok(())
547 }
548
549 /// The catalog generation this set snapshot was built against.
550 pub fn catalog_generation(&self) -> CatalogGeneration {
551 self.catalog_generation
552 }
553
554 /// True when the catalog has mutated since this set was built. A stale
555 /// set must be rebuilt/revalidated, not silently used.
556 pub fn is_stale(&self, catalog: &ToolCatalog) -> bool {
557 self.catalog_generation != catalog.generation()
558 }
559
560 /// Deterministic projection of configured core ids (ToolId order).
561 pub fn core_ids(&self) -> impl Iterator<Item = &ToolId> {
562 self.core.keys()
563 }
564
565 pub fn is_core(&self, id: &ToolId) -> bool {
566 self.core.contains_key(id)
567 }
568
569 /// The schema digest pinned for a configured core tool at build time,
570 /// or `None` when the id is not in this session's core set.
571 pub fn core_schema_digest(&self, id: &ToolId) -> Option<&SchemaDigest> {
572 self.core.get(id).map(CorePin::schema_digest)
573 }
574
575 /// The full (digest, provenance) pin for a configured core tool, or
576 /// `None` when the id is not in this session's core set.
577 pub fn core_pin(&self, id: &ToolId) -> Option<&CorePin> {
578 self.core.get(id)
579 }
580
581 /// Deterministic projection of exact activations (ToolId order).
582 pub fn activated(&self) -> impl Iterator<Item = &ActivatedTool> {
583 self.activated.values()
584 }
585
586 pub fn activation(&self, id: &ToolId) -> Option<&ActivatedTool> {
587 self.activated.get(id)
588 }
589
590 /// Session schema-generation counter (spec §7.7): the number of
591 /// successful nonempty activation batches applied to this set. A
592 /// deterministic bulk `activate_many` advances it by exactly one.
593 pub fn schema_generation(&self) -> u64 {
594 self.schema_generation
595 }
596
597 /// Validate one grant against this set and the current catalog without
598 /// mutating anything. Shared by [`Self::activate`] and
599 /// [`Self::activate_many`] so single and bulk paths can never drift.
600 fn validate_grant(
601 &self,
602 grant: &SessionActivationGrant,
603 catalog: &ToolCatalog,
604 ) -> Result<(), ActivationError> {
605 if grant.session_id() != self.session.as_str() {
606 return Err(ActivationError::SessionMismatch);
607 }
608 let tool_id = grant.tool_id().clone();
609 let record = catalog
610 .get(&tool_id)
611 .ok_or_else(|| ActivationError::UnknownTool(tool_id.clone()))?;
612 if grant.catalog_generation() != catalog.generation() {
613 return Err(ActivationError::StaleGeneration {
614 grant: grant.catalog_generation(),
615 catalog: catalog.generation(),
616 });
617 }
618 if grant.schema_digest() != record.schema_digest() {
619 return Err(ActivationError::DigestMismatch(tool_id));
620 }
621 // A fresh grant cannot rescue a stale set snapshot: the set itself
622 // must be rebuilt against the current catalog first.
623 if self.catalog_generation != catalog.generation() {
624 return Err(ActivationError::StaleSnapshot {
625 set: self.catalog_generation,
626 catalog: catalog.generation(),
627 });
628 }
629 // Exact-tuple re-check through the grant's own covers() so the two
630 // validation paths can never drift apart.
631 debug_assert!(grant.covers(
632 self.session.as_str(),
633 &tool_id,
634 catalog.generation(),
635 record.schema_digest(),
636 ));
637 if self.activated.contains_key(&tool_id) {
638 return Err(ActivationError::AlreadyActivated(tool_id));
639 }
640 // Core tools are always available to the session; re-recording one
641 // as a deferred activation would create two conflicting bookkeeping
642 // entries for the same capability.
643 if self.core.contains_key(&tool_id) {
644 return Err(ActivationError::AlreadyCore(tool_id));
645 }
646 Ok(())
647 }
648
649 /// Record one exact activation. This is set/test/bootstrap plumbing, not
650 /// a model-facing activation flow: the grant must already exist and must
651 /// match this session, a cataloged tool, the CURRENT catalog generation,
652 /// and the CURRENT schema digest exactly. Any drift — foreign session,
653 /// unknown tool, stale generation, changed digest, stale set snapshot,
654 /// duplicate activation, core-set membership — fails typed before any
655 /// mutation, so a failed call leaves the set byte-for-byte unchanged. No
656 /// implementation is constructed, no process started, no schema exposed.
657 /// A successful call is a nonempty batch of one: the session
658 /// schema-generation advances by exactly one.
659 pub fn activate(
660 &mut self,
661 grant: SessionActivationGrant,
662 catalog: &ToolCatalog,
663 ) -> Result<(), ActivationError> {
664 self.validate_grant(&grant, catalog)?;
665 let provenance = catalog
666 .get(grant.tool_id())
667 .expect("validate_grant verified the record exists")
668 .provenance()
669 .clone();
670 self.activated.insert(
671 grant.tool_id().clone(),
672 ActivatedTool {
673 grant,
674 provenance,
675 lease: RuntimeLease::NotAcquired,
676 },
677 );
678 self.schema_generation += 1;
679 Ok(())
680 }
681
682 /// Deterministic atomic bulk activation (spec §7.7): validate EVERY
683 /// requested grant first — duplicates within the batch, unknown ids,
684 /// core-set ids, stale generations, digest mismatches, stale set
685 /// snapshots, and untrusted/inconsistent source provenance all fail
686 /// typed with ZERO partial mutation — then apply in stable `ToolId`
687 /// order and advance the session schema-generation by exactly one. An
688 /// empty batch is a no-op that advances nothing. Returns the number of
689 /// activations applied.
690 pub fn activate_many(
691 &mut self,
692 grants: Vec<SessionActivationGrant>,
693 catalog: &ToolCatalog,
694 ) -> Result<usize, BulkActivationError> {
695 if grants.is_empty() {
696 return Ok(0);
697 }
698 let mut seen: std::collections::BTreeSet<ToolId> = std::collections::BTreeSet::new();
699 for grant in &grants {
700 if !seen.insert(grant.tool_id().clone()) {
701 return Err(BulkActivationError::DuplicateRequest(
702 grant.tool_id().clone(),
703 ));
704 }
705 self.validate_grant(grant, catalog)
706 .map_err(BulkActivationError::Grant)?;
707 // Source trust re-check before ANY grant is applied: an
708 // unverified or provenance-inconsistent capability rejects the
709 // whole batch (validate_grant proved the record exists).
710 let record = catalog
711 .get(grant.tool_id())
712 .expect("validate_grant verified the record exists");
713 check_source_trust(record).map_err(|err| match err {
714 ToolAuthorizationError::SourceProvenanceMismatch(id) => {
715 BulkActivationError::SourceProvenanceMismatch(id)
716 }
717 // check_source_trust only produces UntrustedSource or
718 // SourceProvenanceMismatch; anything else maps to the
719 // conservative untrusted denial for this id.
720 _ => BulkActivationError::UntrustedSource(grant.tool_id().clone()),
721 })?;
722 }
723 // All grants validated: apply in stable ToolId order.
724 let mut ordered = grants;
725 ordered.sort_by(|a, b| a.tool_id().cmp(b.tool_id()));
726 let applied = ordered.len();
727 for grant in ordered {
728 let provenance = catalog
729 .get(grant.tool_id())
730 .expect("validate_grant verified the record exists")
731 .provenance()
732 .clone();
733 self.activated.insert(
734 grant.tool_id().clone(),
735 ActivatedTool {
736 grant,
737 provenance,
738 lease: RuntimeLease::NotAcquired,
739 },
740 );
741 }
742 // Exactly ONE schema-generation advance for the whole batch.
743 self.schema_generation += 1;
744 Ok(applied)
745 }
746}
747
748// ── ExecutionGate (Task 16, spec §7.1 / §4.2) ───────────────────────────────
749
750/// Byte budget for wire/tool names echoed inside typed denials. Denials are
751/// static, bounded, metadata-only strings: hostile oversize wire names must
752/// never be reflected verbatim.
753pub const WIRE_NAME_MAX_BYTES: usize = 128;
754
755fn bounded_wire_name(raw: &str) -> String {
756 BoundedText::new(raw, WIRE_NAME_MAX_BYTES).text
757}
758
759/// Typed resolution of an incoming API/wire tool name to the exact live
760/// runtime tool identity: the wire name as received (bounded), the runtime
761/// name it deterministically maps to (via the registry's sanitized-name
762/// reverse mapping), and the exact catalog [`ToolId`] derived from the live
763/// tool instance itself — never from the alias. Aliases and collision
764/// suffixes therefore cannot select a different identity than the tool they
765/// deterministically resolve to.
766///
767/// This is identity data only; it grants nothing. Authorization happens in
768/// [`ExecutionGate::authorize`], which is the only constructor of
769/// [`AuthorizedToolCall`].
770#[derive(Clone, Debug, PartialEq, Eq)]
771pub struct ResolvedToolCall {
772 wire_name: String,
773 runtime_name: String,
774 tool_id: ToolId,
775}
776
777impl ResolvedToolCall {
778 pub fn new(wire_name: &str, runtime_name: &str, tool_id: ToolId) -> Self {
779 Self {
780 wire_name: bounded_wire_name(wire_name),
781 runtime_name: runtime_name.to_string(),
782 tool_id,
783 }
784 }
785
786 /// The API/wire name as received (bounded for echo safety).
787 pub fn wire_name(&self) -> &str {
788 &self.wire_name
789 }
790
791 /// The exact runtime tool name the wire name resolves to.
792 pub fn runtime_name(&self) -> &str {
793 &self.runtime_name
794 }
795
796 /// The exact catalog identity of the resolved live tool.
797 pub fn tool_id(&self) -> &ToolId {
798 &self.tool_id
799 }
800}
801
802#[derive(Clone, Copy, Debug, PartialEq, Eq)]
803pub enum ActivationBasis {
804 Core,
805 Exact {
806 catalog_generation: CatalogGeneration,
807 },
808}
809
810/// A fully authorized tool call: exact resolved identity plus the acquired
811/// implementation. The implementation field is private and the ONLY
812/// constructor is [`ExecutionGate::authorize`], which acquires it strictly
813/// after every check passes — the safe path cannot reach an implementation
814/// without passing the gate.
815pub struct AuthorizedToolCall {
816 resolved: ResolvedToolCall,
817 implementation: Arc<dyn Tool>,
818 activation_basis: ActivationBasis,
819}
820
821impl AuthorizedToolCall {
822 pub fn resolved(&self) -> &ResolvedToolCall {
823 &self.resolved
824 }
825
826 pub fn wire_name(&self) -> &str {
827 self.resolved.wire_name()
828 }
829
830 pub fn runtime_name(&self) -> &str {
831 self.resolved.runtime_name()
832 }
833
834 pub fn tool_id(&self) -> &ToolId {
835 self.resolved.tool_id()
836 }
837
838 pub fn activation_basis(&self) -> ActivationBasis {
839 self.activation_basis
840 }
841
842 /// The authorized implementation handle.
843 pub fn implementation(&self) -> Arc<dyn Tool> {
844 Arc::clone(&self.implementation)
845 }
846}
847
848impl std::fmt::Debug for AuthorizedToolCall {
849 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
850 f.debug_struct("AuthorizedToolCall")
851 .field("resolved", &self.resolved)
852 .finish_non_exhaustive()
853 }
854}
855
856/// Typed execution-gate denial. Every variant is static, bounded, and
857/// metadata-only: no tool input, no schema bytes, no provider body content —
858/// only bounded identities and generation counters.
859#[derive(Clone, Debug, Error, PartialEq, Eq)]
860pub enum ToolAuthorizationError {
861 /// The wire name resolves to no live registered tool. Message shape kept
862 /// compatible with the legacy tool-loop denial; the echoed name is
863 /// bounded at resolution time.
864 #[error("Unknown tool: {wire_name}")]
865 UnknownTool { wire_name: String },
866 /// The live tool exists but the catalog holds no record for its
867 /// identity — the registry/catalog invariant is broken; fail closed.
868 #[error("Tool call denied: capability is not cataloged: {0}")]
869 NotCataloged(ToolId),
870 /// Known capability, but neither core for this session nor covered by an
871 /// exact activation grant (the forged deferred-call case).
872 #[error("Tool call denied: tool is not activated for this session: {0}")]
873 NotActivated(ToolId),
874 /// The capability's current schema digest differs from the digest the
875 /// session pinned at core-build/activation time — a changed tool is
876 /// never silently blessed.
877 #[error("Tool call denied: schema digest changed since authorization was pinned: {0}")]
878 SchemaDigestMismatch(ToolId),
879 /// Unverified/unknown provenance is denied by default, even if the
880 /// capability was (mis)configured as core, until an explicit later
881 /// policy exists.
882 #[error("Tool call denied: source provenance is unverified: {0}")]
883 UntrustedSource(ToolId),
884 /// Source/trust provenance failure: either the catalog record's source
885 /// and trust provenance disagree (an internally inconsistent record must
886 /// never authorize), or the record's CURRENT provenance differs from the
887 /// provenance the session pinned at core-build/activation time (a tool
888 /// removed and re-added under a different — even internally coherent —
889 /// provenance must never authorize).
890 #[error("Tool call denied: source/trust provenance is inconsistent or drifted from the session's pin: {0}")]
891 SourceProvenanceMismatch(ToolId),
892}
893
894/// The spec §7.1 execution gate: a pure, reusable authorization component
895/// evaluated immediately before tool implementation lookup/execution.
896///
897/// Order of checks (each fails typed, closed, without acquiring anything):
898/// 1. resolve wire name → exact live `ToolId` (deterministic reverse
899/// mapping; aliases cannot pick a different identity);
900/// 2. the identity must be cataloged;
901/// 3. the identity must be core (pinned digest intact) or hold an exact
902/// session activation grant covering (session, tool, digest) — see
903/// [`grant_covers_execution`]: catalog generation drift alone does NOT
904/// deny at execution time; only a real change to the called tool's
905/// record (digest, presence, provenance) does;
906/// 4. the record's CURRENT trust provenance must equal the provenance the
907/// session PINNED at core-build/activation time — this closes the
908/// coherent-imposter hole (same `ToolId`, schema-identical body,
909/// different but internally consistent source/provenance);
910/// 5. source trust is re-evaluated conservatively — see the honesty note
911/// on [`check_source_trust`]: this re-checks typed source/provenance
912/// consistency and denies Unknown/Unverified, but does NOT yet consult
913/// live manifest permission/revocation state (Task 20 integrates the
914/// permission/revocation policy);
915/// 6. side-effect/confirmation policy (interim: `Unclassified` is allowed
916/// only for verified-provenance capabilities — Task 24 adds real effect
917/// classes);
918/// 7. only then is the implementation acquired.
919///
920/// TOCTOU: callers must resolve, authorize, and acquire against ONE
921/// consistent registry borrow/lock guard — [`ExecutionGate::authorize_wire_call`]
922/// does exactly that for a `&ToolRegistry` held under the caller's read lock.
923pub struct ExecutionGate;
924
925impl ExecutionGate {
926 /// Resolve an incoming API/wire name against one registry snapshot.
927 pub fn resolve(
928 registry: &ToolRegistry,
929 wire_name: &str,
930 ) -> Result<ResolvedToolCall, ToolAuthorizationError> {
931 registry
932 .resolve_wire_call(wire_name)
933 .ok_or_else(|| ToolAuthorizationError::UnknownTool {
934 wire_name: bounded_wire_name(wire_name),
935 })
936 }
937
938 /// Authorize a resolved identity against one catalog snapshot and one
939 /// session tool set. On success — and only then — the implementation is
940 /// acquired from the catalog record's factory and returned inside the
941 /// typed [`AuthorizedToolCall`]. Failure acquires nothing and leaves the
942 /// session set untouched (the gate never mutates it).
943 ///
944 /// SECURITY INVARIANT (per-tool digest + provenance validation): no
945 /// tool executes unless its CURRENT catalog record — presence of the
946 /// exact `ToolId`, schema digest, and source/trust provenance — exactly
947 /// matches what the session pinned at core-build/activation time.
948 /// Catalog generation inequality ALONE is no longer a denial reason at
949 /// execution time: an unrelated background mutation (e.g. a plugin
950 /// load mid-round) must not kill in-flight calls to schema-identical
951 /// tools. Any REAL drift of the called tool's record — changed digest,
952 /// removal, changed provenance (even to an internally coherent one) —
953 /// still denies typed and closed.
954 ///
955 /// ACCEPTED RESIDUAL RISK: [`SchemaDigest`] hashes the schema JSON
956 /// only, not the implementation factory. A record replaced in place
957 /// with an identical schema AND identical pinned provenance but a
958 /// different implementation passes this gate; the exposure is bounded
959 /// by the deterministic round-top rebuild (runtime/stream.rs), which
960 /// re-pins the set against the current catalog between provider rounds.
961 pub fn authorize(
962 catalog: &ToolCatalog,
963 session: &SessionToolSet,
964 resolved: ResolvedToolCall,
965 ) -> Result<AuthorizedToolCall, ToolAuthorizationError> {
966 let tool_id = resolved.tool_id().clone();
967 let record = catalog
968 .get(&tool_id)
969 .ok_or_else(|| ToolAuthorizationError::NotCataloged(tool_id.clone()))?;
970
971 // Generation drift is observed (for logging) but NOT a wholesale
972 // denial: the per-tool checks below are unconditional and judge the
973 // called tool's CURRENT record against the session's pins. The
974 // round-top rebuild (runtime/stream.rs) still uses `is_stale` to
975 // refresh the set deterministically between rounds.
976 let generation_drift = session.is_stale(catalog);
977
978 // Core status or exact activation grant, with pinned-digest
979 // verification either way — unconditional, drift or not. The pinned
980 // trust provenance is carried out of each branch for the
981 // unconditional pinned-provenance check below.
982 let activation_basis;
983 let pinned_provenance: &TrustProvenance;
984 if let Some(pin) = session.core_pin(&tool_id) {
985 if pin.schema_digest() != record.schema_digest() {
986 if generation_drift {
987 tracing::warn!(
988 tool = %tool_id,
989 set_generation = session.catalog_generation().value(),
990 catalog_generation = catalog.generation().value(),
991 "tool denied under catalog generation drift: pinned core schema digest \
992 no longer matches the current catalog record"
993 );
994 }
995 return Err(ToolAuthorizationError::SchemaDigestMismatch(tool_id));
996 }
997 pinned_provenance = pin.provenance();
998 activation_basis = ActivationBasis::Core;
999 } else if let Some(activated) = session.activation(&tool_id) {
1000 if activated.schema_digest() != record.schema_digest() {
1001 if generation_drift {
1002 tracing::warn!(
1003 tool = %tool_id,
1004 set_generation = session.catalog_generation().value(),
1005 catalog_generation = catalog.generation().value(),
1006 "tool denied under catalog generation drift: activation grant schema \
1007 digest no longer matches the current catalog record"
1008 );
1009 }
1010 return Err(ToolAuthorizationError::SchemaDigestMismatch(tool_id));
1011 }
1012 // Execution-time grant re-check on the (session, tool, digest)
1013 // tuple — deliberately WITHOUT the generation term (see
1014 // `grant_covers_execution`). Grant ISSUANCE and activation stay
1015 // generation-strict (`validate_grant`, `covers()`).
1016 if !grant_covers_execution(
1017 activated.grant(),
1018 session.session().as_str(),
1019 &tool_id,
1020 record.schema_digest(),
1021 ) {
1022 return Err(ToolAuthorizationError::NotActivated(tool_id));
1023 }
1024 pinned_provenance = activated.provenance();
1025 activation_basis = ActivationBasis::Exact {
1026 catalog_generation: activated.catalog_generation(),
1027 };
1028 } else {
1029 return Err(ToolAuthorizationError::NotActivated(tool_id));
1030 }
1031
1032 // Unconditional pinned-provenance equality (BLOCKER fix): the
1033 // record's CURRENT trust provenance must equal the provenance the
1034 // session pinned at core-build/activation time. This — not the
1035 // self-consistency check below — is what catches the coherent
1036 // imposter: a tool removed and re-added under the same `ToolId`
1037 // with a schema-identical body but a different, internally
1038 // consistent source/provenance pair.
1039 if pinned_provenance != record.provenance() {
1040 if generation_drift {
1041 tracing::warn!(
1042 tool = %tool_id,
1043 set_generation = session.catalog_generation().value(),
1044 catalog_generation = catalog.generation().value(),
1045 "tool denied under catalog generation drift: current record provenance \
1046 no longer matches the provenance the session pinned"
1047 );
1048 }
1049 return Err(ToolAuthorizationError::SourceProvenanceMismatch(tool_id));
1050 }
1051
1052 // Conservative source trust re-check immediately before
1053 // acquisition: typed source/provenance SELF-consistency plus the
1054 // deny-by-default for Unknown/Unverified (see check_source_trust) —
1055 // live manifest permission/revocation state is not consulted here
1056 // yet (Task 20). This complements (does not replace) the
1057 // pinned-provenance equality above.
1058 check_source_trust(record)?;
1059
1060 if generation_drift {
1061 tracing::warn!(
1062 tool = %tool_id,
1063 set_generation = session.catalog_generation().value(),
1064 catalog_generation = catalog.generation().value(),
1065 "tool call survived catalog generation drift: current record digest, presence \
1066 and provenance exactly match the session's pins"
1067 );
1068 }
1069
1070 // Effect classes (Task 24) are execution-SCHEDULING policy, not
1071 // authorization policy: every class may execute once authorized —
1072 // the stream scheduler decides concurrency/ordering from the
1073 // recorded class. The exhaustive match keeps this decision loud if
1074 // a future class needs gate-level treatment.
1075 match record.effect() {
1076 ToolEffect::ReadOnly | ToolEffect::IdempotentWrite | ToolEffect::NonIdempotent => {}
1077 }
1078
1079 // Acquisition happens strictly after authorization succeeds.
1080 let implementation = record.implementation();
1081 Ok(AuthorizedToolCall {
1082 resolved,
1083 implementation,
1084 activation_basis,
1085 })
1086 }
1087
1088 /// Resolve + authorize + acquire against ONE registry borrow (one
1089 /// consistent snapshot under the caller's read lock — no TOCTOU between
1090 /// resolution and implementation acquisition).
1091 pub fn authorize_wire_call(
1092 registry: &ToolRegistry,
1093 session: &SessionToolSet,
1094 wire_name: &str,
1095 ) -> Result<AuthorizedToolCall, ToolAuthorizationError> {
1096 let resolved = Self::resolve(registry, wire_name)?;
1097 Self::authorize(registry.catalog(), session, resolved)
1098 }
1099}
1100
1101/// Execution-time grant coverage: (session, tool, digest) equality WITHOUT
1102/// the generation term of [`SessionActivationGrant::covers`]. Rationale: at
1103/// execution time the tool's identity and schema are already re-validated
1104/// against the CURRENT catalog record, so requiring the pinned generation to
1105/// equal the live one only makes unrelated catalog mutations (background
1106/// plugin loads) kill in-flight calls to schema-identical tools. `covers()`
1107/// itself (agent-core) stays exact-tuple and is still what grant ISSUANCE
1108/// and activation validation (`validate_grant`) enforce — this relaxation
1109/// applies ONLY to re-validation of an already-established authorization.
1110fn grant_covers_execution(
1111 grant: &SessionActivationGrant,
1112 session_id: &str,
1113 tool_id: &ToolId,
1114 schema_digest: &SchemaDigest,
1115) -> bool {
1116 grant.session_id() == session_id
1117 && grant.tool_id() == tool_id
1118 && grant.schema_digest() == schema_digest
1119}
1120
1121/// Conservative per-source trust policy — CONSISTENCY check, not a live
1122/// permission lookup: `BuiltinRuntime` provenance is valid only for
1123/// builtin-sourced records; extension/MCP/plugin provenance must match the
1124/// catalog source identity exactly; `Unverified` (and any unknown source)
1125/// is denied by default even if configured core.
1126///
1127/// Honesty note (Task 16): this validates the typed provenance recorded at
1128/// catalog time against the record's source identity. It does NOT consult
1129/// live manifest permission state or revocation — a capability whose
1130/// extension permissions were revoked after cataloging still passes this
1131/// check until the catalog entry is removed/rebuilt. Live
1132/// permission/revocation integration is Task 20.
1133/// Whether `activate_tools` could ever grant this record: the same source
1134/// trust check activation applies (verified provenance that matches its
1135/// declared source). Used to decide which dormant tools are advertised as
1136/// deferred definitions; it never authorizes anything by itself.
1137pub(crate) fn is_activatable_record(record: &CapabilityRecord) -> bool {
1138 check_source_trust(record).is_ok()
1139}
1140
1141fn check_source_trust(record: &CapabilityRecord) -> Result<(), ToolAuthorizationError> {
1142 let deny_untrusted = || ToolAuthorizationError::UntrustedSource(record.id().clone());
1143 let deny_mismatch = || ToolAuthorizationError::SourceProvenanceMismatch(record.id().clone());
1144 match (record.provenance(), record.source()) {
1145 (TrustProvenance::Unverified, _) => Err(deny_untrusted()),
1146 (_, CapabilitySource::Unknown { .. }) => Err(deny_untrusted()),
1147 (TrustProvenance::BuiltinRuntime, CapabilitySource::Builtin) => Ok(()),
1148 (
1149 TrustProvenance::ExtensionManifest { extension_id },
1150 CapabilitySource::Extension {
1151 extension_id: source_extension_id,
1152 ..
1153 },
1154 ) if extension_id == source_extension_id => Ok(()),
1155 (
1156 TrustProvenance::McpConfig { server_id },
1157 CapabilitySource::Mcp {
1158 server_id: source_server_id,
1159 ..
1160 },
1161 ) if server_id == source_server_id => Ok(()),
1162 (
1163 TrustProvenance::PluginConfig { plugin_id },
1164 CapabilitySource::Plugin {
1165 plugin_id: source_plugin_id,
1166 ..
1167 },
1168 ) if plugin_id == source_plugin_id => Ok(()),
1169 _ => Err(deny_mismatch()),
1170 }
1171}
1172
1173// ── Task 17: host grant issuance, typed confirmation authority, and the
1174// retained shared session set (spec §7.2, §7.3, §7.7) ─────────────────────
1175
1176/// One retained per-stream-session handle: `activate_tools` mutates the SAME
1177/// set the `ExecutionGate` and the next provider round consume. Interior
1178/// critical sections are short and never held across `.await`.
1179pub type SharedSessionToolSet = Arc<std::sync::RwLock<SessionToolSet>>;
1180
1181/// The per-runtime slot that RETAINS a session's [`SharedSessionToolSet`]
1182/// across stream turns. Exact activations are session-scoped (the
1183/// `activate_tools` contract says so), so the set that holds them must outlive
1184/// a single provider turn: every turn of the same runtime tool session
1185/// reconciles and reuses the retained set instead of minting a fresh,
1186/// zero-activation one. Shared by `Runtime` clones exactly like
1187/// `host_tool_session`; empty until the first progressive turn.
1188pub type RetainedSessionToolSet = Arc<std::sync::Mutex<Option<SharedSessionToolSet>>>;
1189
1190/// Activations a runtime was handed from the same conversation's previous
1191/// runtime (daemon reload, unpark) and has not applied yet. Consumed by the
1192/// first progressive turn start (or projected read-only by a keep-warm
1193/// ping before it), against THAT moment's catalog — as late as possible, so
1194/// tools registered after the runtime was built are seen. Shared by
1195/// `Runtime` clones exactly like [`RetainedSessionToolSet`].
1196pub type PendingToolRestore = Arc<std::sync::Mutex<Option<Vec<CarriedActivation>>>>;
1197
1198/// Typed failure for deterministic bulk activation ([`SessionToolSet::activate_many`]).
1199/// Every variant fails the WHOLE batch with zero partial mutation.
1200#[derive(Clone, Debug, Error, PartialEq, Eq)]
1201pub enum BulkActivationError {
1202 #[error("duplicate tool id in one activation batch: {0}")]
1203 DuplicateRequest(ToolId),
1204 #[error("activation batch rejected: {0}")]
1205 Grant(#[from] ActivationError),
1206 #[error("activation batch rejected: source provenance is unverified: {0}")]
1207 UntrustedSource(ToolId),
1208 #[error("activation batch rejected: catalog source and trust provenance disagree: {0}")]
1209 SourceProvenanceMismatch(ToolId),
1210}
1211
1212/// Host-supplied activation authority for MODEL-INITIATED activation.
1213///
1214/// `ModelConfirmed` may be populated ONLY by host policy (explicit server
1215/// auto-approve or an interactive confirmation mechanism) — never from
1216/// model-authored JSON arguments. Explicit user-requested activation goes
1217/// through [`activate_exact_for_user`], a host Rust API that involves no
1218/// authority value at all (PR #63 ergonomics: a user asking for an exact
1219/// known tool needs no redundant prompt).
1220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1221pub enum ActivationAuthority {
1222 /// No confirmation authority: model-initiated activation is denied
1223 /// before any grant issuance or set/schema mutation.
1224 Unauthorized,
1225 /// Host confirmation policy satisfied for this session/turn.
1226 ModelConfirmed,
1227}
1228
1229/// Typed failure for host grant issuance. Issuance validates the exact
1230/// known `ToolId`, the current catalog generation/digest (pinned into the
1231/// grant), and source trust — before any grant exists.
1232#[derive(Clone, Debug, Error, PartialEq, Eq)]
1233pub enum GrantIssuanceError {
1234 #[error("cannot issue activation grant: tool is not in the catalog: {0}")]
1235 UnknownTool(ToolId),
1236 #[error("cannot issue activation grant: source provenance is unverified: {0}")]
1237 UntrustedSource(ToolId),
1238 #[error("cannot issue activation grant: catalog source and trust provenance disagree: {0}")]
1239 SourceProvenanceMismatch(ToolId),
1240 #[error("cannot issue activation grant: {0}")]
1241 Grant(#[from] agent_core::orchestration::capability::ActivationGrantError),
1242}
1243
1244/// Issue one exact session-scoped activation grant against the CURRENT
1245/// catalog state. Validates: the id is a known exact cataloged capability
1246/// and its source trust/provenance is consistent and verified. The grant
1247/// pins the current catalog generation and schema digest. Pure: no factory
1248/// invocation, no process start, no network, no set mutation.
1249pub fn issue_exact_grant(
1250 catalog: &ToolCatalog,
1251 session: &SessionId,
1252 tool_id: &ToolId,
1253) -> Result<SessionActivationGrant, GrantIssuanceError> {
1254 let record = catalog
1255 .get(tool_id)
1256 .ok_or_else(|| GrantIssuanceError::UnknownTool(tool_id.clone()))?;
1257 check_source_trust(record).map_err(|err| match err {
1258 ToolAuthorizationError::SourceProvenanceMismatch(id) => {
1259 GrantIssuanceError::SourceProvenanceMismatch(id)
1260 }
1261 _ => GrantIssuanceError::UntrustedSource(tool_id.clone()),
1262 })?;
1263 Ok(SessionActivationGrant::new(
1264 session.as_str(),
1265 tool_id.clone(),
1266 catalog.generation(),
1267 record.schema_digest().clone(),
1268 )?)
1269}
1270
1271/// Typed failure for the host activation entry points.
1272#[derive(Clone, Debug, Error, PartialEq, Eq)]
1273pub enum HostActivationError {
1274 /// Model-initiated activation without host confirmation authority.
1275 /// Denied BEFORE grant issuance and before any set/schema mutation.
1276 #[error(
1277 "tool activation requires host confirmation authority; \
1278 model-initiated activation was not confirmed"
1279 )]
1280 ConfirmationRequired,
1281 #[error(transparent)]
1282 Issuance(#[from] GrantIssuanceError),
1283 #[error(transparent)]
1284 Bulk(#[from] BulkActivationError),
1285}
1286
1287/// Explicit USER-REQUESTED exact activation (spec §7.3 / PR #63 ergonomics):
1288/// the host may authorize one exact known local identity without a
1289/// redundant confirmation prompt. This is a host Rust API — it is never
1290/// reachable from model-authored JSON and takes no confirmation boolean.
1291/// Grants are session-scoped and never persisted.
1292pub fn activate_exact_for_user(
1293 set: &mut SessionToolSet,
1294 catalog: &ToolCatalog,
1295 tool_id: &ToolId,
1296) -> Result<(), HostActivationError> {
1297 let grant = issue_exact_grant(catalog, set.session(), tool_id)?;
1298 set.activate_many(vec![grant], catalog)?;
1299 Ok(())
1300}
1301
1302/// MODEL-INITIATED exact activation: requires host-supplied
1303/// [`ActivationAuthority::ModelConfirmed`]. Without it, the request is
1304/// denied before any grant issuance, set mutation, or schema-generation
1305/// advance. All requested ids are validated and issued first; the batch
1306/// applies atomically in stable `ToolId` order with exactly one session
1307/// schema-generation advance. Grants are session-scoped, never persisted.
1308pub fn activate_model_initiated(
1309 authority: ActivationAuthority,
1310 set: &mut SessionToolSet,
1311 catalog: &ToolCatalog,
1312 tool_ids: &[ToolId],
1313) -> Result<usize, HostActivationError> {
1314 match authority {
1315 ActivationAuthority::ModelConfirmed => {}
1316 ActivationAuthority::Unauthorized => {
1317 return Err(HostActivationError::ConfirmationRequired);
1318 }
1319 }
1320 let session = set.session().clone();
1321 let mut grants = Vec::with_capacity(tool_ids.len());
1322 for tool_id in tool_ids {
1323 grants.push(issue_exact_grant(catalog, &session, tool_id)?);
1324 }
1325 Ok(set.activate_many(grants, catalog)?)
1326}
1327
1328/// Resolve the session tool set for the extension-provider route (Task 17,
1329/// closing the Task 16 policy divergence): when the runtime threads its
1330/// RETAINED per-stream set, the route consumes THAT set's current state —
1331/// including exact activations — at its pinned generation. The route must
1332/// never silently mint a fresh default-core set for the same round. Only
1333/// callers with no retained handle at all (internal/sync helpers) fall back
1334/// to a fresh default-core set with zero activations under a locally minted
1335/// session.
1336///
1337/// Generation drift is deliberately SURVIVED here (per-tool digest
1338/// validation fix): the retained set is served as-is even when the catalog
1339/// generation moved past its snapshot, because every actual execution still
1340/// passes through [`ExecutionGate::authorize`], which unconditionally
1341/// re-validates each called tool's current record (presence, digest,
1342/// provenance) against the session's pins. Denying the whole retained set
1343/// wholesale would let an unrelated background catalog mutation kill an
1344/// entire in-flight round of schema-identical tools. Infallible: neither
1345/// path can be denied anymore, so the return type is the plain set.
1346pub fn route_session_set(
1347 retained: Option<&SharedSessionToolSet>,
1348 catalog: &ToolCatalog,
1349 fallback_session: impl FnOnce() -> SessionId,
1350) -> SessionToolSet {
1351 match retained {
1352 Some(shared) => {
1353 let guard = shared
1354 .read()
1355 .unwrap_or_else(std::sync::PoisonError::into_inner);
1356 if guard.is_stale(catalog) {
1357 tracing::warn!(
1358 set_generation = guard.catalog_generation().value(),
1359 catalog_generation = catalog.generation().value(),
1360 "serving retained session tool set across catalog generation drift; \
1361 per-call ExecutionGate::authorize still protects execution"
1362 );
1363 }
1364 guard.clone()
1365 }
1366 None => SessionToolSet::default_core_for_catalog(fallback_session(), catalog),
1367 }
1368}