adk_kernel/partition/crossing.rs
1//! Crossings (spec 3.2 §7.8, §13 Q3): a request from one partition that reaches another
2//! partition's memory, drivers or sessions.
3//!
4//! | Caller | Decision |
5//! |---|---|
6//! | Not the coordinator | `Deny`, recorded as a crossing |
7//! | The coordinator, into or out of a partition with `cross_partition: deny`, or into a partition its own blocks | `Deny`, recorded |
8//! | The coordinator, a read approved earlier in the same run | `Allow`, recorded as a run grant |
9//! | The coordinator, otherwise | `RequireApproval`, non-waivable: no standing rule and no `expires_at` rule answers it, and the harness strips run-wide approvals of it |
10//!
11//! The unit of approval is the [crossing fingerprint](Crossing::fingerprint):
12//! `ToolConfirmationRequest::fingerprint()` — the acting agent, the tool's origin, the tool
13//! name and the canonical arguments — extended with the target partition and the resource
14//! class. An approved read lets the coordinator's identical reads through for the rest of
15//! that run and nothing beyond it; writes, and `Financial` and `PublishPublic` driver calls,
16//! stay one-shot.
17
18use std::collections::BTreeMap;
19use std::fmt;
20use std::sync::{Arc, RwLock};
21
22use adk_core::{
23 AdkError, ErrorCategory, ErrorComponent, PolicyCall, PolicyDecision, Tool,
24 ToolConfirmationRequest, ToolContext, ToolEffect, ToolOrigin, ToolPolicy, ToolPolicyRequest,
25};
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31use super::{PartitionId, Partitions};
32
33/// The argument naming the target partition of a crossing tool whose
34/// [`CrossingRoute`] is [`Argument`](CrossingRoute::Argument).
35pub const CROSSING_PARTITION_ARG: &str = "partition";
36
37/// What a crossing reaches (spec 3.2 §7.8): the resource class of its fingerprint.
38///
39/// # Example
40///
41/// ```rust
42/// use adk_kernel::CrossingResource;
43///
44/// assert_eq!(CrossingResource::Driver.as_str(), "driver");
45/// assert_eq!(serde_json::to_value(CrossingResource::Memory).unwrap(), "memory");
46/// ```
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49#[non_exhaustive]
50pub enum CrossingResource {
51 /// Another partition's long-term facts or project-scoped memory.
52 Memory,
53 /// A driver mounted for another partition.
54 Driver,
55 /// Another partition's sessions.
56 Session,
57}
58
59impl CrossingResource {
60 /// The class's name: `memory`, `driver` or `session`.
61 pub fn as_str(self) -> &'static str {
62 match self {
63 Self::Memory => "memory",
64 Self::Driver => "driver",
65 Self::Session => "session",
66 }
67 }
68}
69
70impl fmt::Display for CrossingResource {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(self.as_str())
73 }
74}
75
76/// Whether a crossing only reads (spec 3.2 §7.8, §13 Q3).
77///
78/// An approved [`Read`](Self::Read) holds for the coordinator's identical reads for the
79/// rest of the run; everything else is [`Write`](Self::Write) and one-shot — a write, and a
80/// driver call of effect class `Financial` or `PublishPublic` (K-I9).
81///
82/// # Example
83///
84/// ```rust
85/// use adk_kernel::CrossingAccess;
86///
87/// assert_eq!(serde_json::to_value(CrossingAccess::Write).unwrap(), "write");
88/// ```
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase")]
91#[non_exhaustive]
92pub enum CrossingAccess {
93 /// Reads only; approved for the rest of the run.
94 Read,
95 /// Writes or acts; approved one call at a time.
96 Write,
97}
98
99impl CrossingAccess {
100 /// The access's name: `read` or `write`.
101 pub fn as_str(self) -> &'static str {
102 match self {
103 Self::Read => "read",
104 Self::Write => "write",
105 }
106 }
107}
108
109/// One request reaching from one partition into another (spec 3.2 §7.8).
110///
111/// # Example
112///
113/// ```rust
114/// use adk_kernel::{Crossing, CrossingAccess, CrossingResource};
115///
116/// let crossing = Crossing::new("home", "work", CrossingResource::Driver, "calendar", CrossingAccess::Read);
117/// assert_eq!(crossing.label(), "work › calendar");
118/// let [allow, deny, block] = crossing.answers();
119/// assert_eq!(allow, "allow this read of work › calendar for this run");
120/// assert_eq!(deny, "deny");
121/// assert_eq!(block, "deny and block crossings to work from this partition");
122/// ```
123#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125#[non_exhaustive]
126pub struct Crossing {
127 /// The partition of the agent making the request.
128 pub from: PartitionId,
129 /// The partition the request reaches.
130 pub to: PartitionId,
131 /// What it reaches.
132 pub resource: CrossingResource,
133 /// The resource's name in the prompt: a driver id, `memory`, a session.
134 pub name: String,
135 /// Whether it only reads.
136 pub access: CrossingAccess,
137}
138
139impl Crossing {
140 /// A crossing from `from` into `to`'s `resource` named `name`.
141 pub fn new(
142 from: impl Into<PartitionId>,
143 to: impl Into<PartitionId>,
144 resource: CrossingResource,
145 name: impl Into<String>,
146 access: CrossingAccess,
147 ) -> Self {
148 Self { from: from.into(), to: to.into(), resource, name: name.into(), access }
149 }
150
151 /// `<to> › <name>`, as the prompt names the crossing.
152 pub fn label(&self) -> String {
153 format!("{} › {}", self.to, self.name)
154 }
155
156 /// The crossing fingerprint of `request` (spec 3.2 §7.8, §13 Q3): its
157 /// [`fingerprint`](ToolConfirmationRequest::fingerprint) — the acting agent, the tool's
158 /// origin, the tool name and the canonical arguments — extended with the target
159 /// partition and the resource class, separated by U+001F.
160 ///
161 /// # Example
162 ///
163 /// ```rust
164 /// use adk_core::ToolConfirmationRequest;
165 /// use adk_kernel::{Crossing, CrossingAccess, CrossingResource};
166 /// use serde_json::json;
167 ///
168 /// let request = ToolConfirmationRequest::new("search", json!({ "q": "dentist" }));
169 /// let crossing = |to: &str, resource| Crossing::new("home", to, resource, "memory", CrossingAccess::Read);
170 /// let work = crossing("work", CrossingResource::Memory).fingerprint(&request);
171 /// assert!(work.starts_with(&request.fingerprint()));
172 /// assert_ne!(work, crossing("team", CrossingResource::Memory).fingerprint(&request));
173 /// assert_ne!(work, crossing("work", CrossingResource::Session).fingerprint(&request));
174 /// ```
175 pub fn fingerprint(&self, request: &ToolConfirmationRequest) -> String {
176 let mut out = request.fingerprint();
177 for part in [self.to.as_str(), self.resource.as_str()] {
178 out.push('\u{1f}');
179 // A control character would forge a separator.
180 out.extend(part.chars().map(|c| if c.is_control() { '\u{fffd}' } else { c }));
181 }
182 out
183 }
184
185 /// The prompt's three answers (spec 3.2 §7.8): allow — for the rest of the run when the
186 /// crossing reads, once otherwise — deny, and deny and block crossings to the target
187 /// from this partition.
188 pub fn answers(&self) -> [String; 3] {
189 let allow = match self.access {
190 CrossingAccess::Read => format!("allow this read of {} for this run", self.label()),
191 CrossingAccess::Write => format!("allow this change to {} once", self.label()),
192 };
193 [
194 allow,
195 "deny".to_string(),
196 format!("deny and block crossings to {} from this partition", self.to),
197 ]
198 }
199
200 /// The reason a crossing that needs approval is held with: it names the crossing and
201 /// the answers.
202 pub fn approval_reason(&self) -> String {
203 let [allow, deny, block] = self.answers();
204 format!(
205 "partition crossing from `{}` into {}: needs a person's approval, which no standing \
206 rule can give ({allow} / {deny} / {block})",
207 self.from,
208 self.label()
209 )
210 }
211}
212
213/// The stored form of a crossing fingerprint: `sha256:` and its hex digest, so the ledger
214/// holds no argument text.
215pub(crate) fn digest(fingerprint: &str) -> String {
216 use sha2::{Digest, Sha256};
217 use std::fmt::Write as _;
218
219 let mut out = String::with_capacity(7 + 64);
220 out.push_str("sha256:");
221 for byte in Sha256::digest(fingerprint.as_bytes()) {
222 let _ = write!(out, "{byte:02x}");
223 }
224 out
225}
226
227/// What happened to a crossing (spec 3.2 §9.3 `kernel.partition.crossing`).
228///
229/// # Example
230///
231/// ```rust
232/// use adk_kernel::CrossingOutcome;
233///
234/// assert_eq!(serde_json::to_value(CrossingOutcome::RunGrant).unwrap(), "runGrant");
235/// ```
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
237#[serde(rename_all = "camelCase")]
238#[non_exhaustive]
239pub enum CrossingOutcome {
240 /// Refused at the policy.
241 Denied,
242 /// Held for a person's approval.
243 Held,
244 /// Ran after a person approved it; for a read, the approval the rest of the run reuses.
245 Approved,
246 /// Let through by a read approved earlier in the same run.
247 RunGrant,
248}
249
250impl CrossingOutcome {
251 /// The outcome's name: `denied`, `held`, `approved` or `runGrant`.
252 pub fn as_str(self) -> &'static str {
253 match self {
254 Self::Denied => "denied",
255 Self::Held => "held",
256 Self::Approved => "approved",
257 Self::RunGrant => "runGrant",
258 }
259 }
260}
261
262/// One entry of the crossing ledger (spec 3.2 §7.8, §9.3): who crossed where, when, in
263/// which run, and what happened. It holds a digest of the crossing fingerprint, never the
264/// call's arguments.
265///
266/// # Example
267///
268/// ```rust
269/// use adk_kernel::{CrossingOutcome, CrossingRecord};
270///
271/// let record: CrossingRecord = serde_json::from_value(serde_json::json!({
272/// "id": "c-1", "at": "2026-10-23T09:00:00Z", "run": "run-1", "agent": "urn:adk:agent:app/harness",
273/// "from": "home", "to": "work", "resource": "driver", "name": "calendar", "access": "read",
274/// "tool": "work__list_events", "fingerprint": "sha256:00", "outcome": "held"
275/// })).unwrap();
276/// assert_eq!(record.outcome, CrossingOutcome::Held);
277/// ```
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct CrossingRecord {
282 /// The record's id.
283 pub id: String,
284 /// When it happened.
285 pub at: DateTime<Utc>,
286 /// The run: its durable run id, or the invocation id outside a durable run.
287 pub run: String,
288 /// The acting agent's id.
289 pub agent: String,
290 /// The partition of the agent.
291 pub from: PartitionId,
292 /// The partition reached.
293 pub to: PartitionId,
294 /// What was reached.
295 pub resource: CrossingResource,
296 /// The resource's name.
297 pub name: String,
298 /// Whether it only read.
299 pub access: CrossingAccess,
300 /// The tool called.
301 pub tool: String,
302 /// `sha256:` digest of the crossing fingerprint.
303 pub fingerprint: String,
304 /// What happened.
305 pub outcome: CrossingOutcome,
306 /// Why, for a refusal.
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub reason: Option<String>,
309}
310
311/// Which crossing records [`PartitionStore::crossings`](super::PartitionStore::crossings)
312/// returns. An empty field matches everything.
313///
314/// # Example
315///
316/// ```rust
317/// use adk_kernel::{CrossingFilter, CrossingOutcome};
318///
319/// let filter = CrossingFilter::default().from("home").outcomes([CrossingOutcome::Approved]).limit(10);
320/// assert_eq!(filter.limit, Some(10));
321/// ```
322#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
323#[serde(rename_all = "camelCase")]
324#[non_exhaustive]
325pub struct CrossingFilter {
326 /// Only crossings out of this partition.
327 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub from: Option<PartitionId>,
329 /// Only crossings into this partition.
330 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub to: Option<PartitionId>,
332 /// Only crossings of this run.
333 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub run: Option<String>,
335 /// Only crossings with this fingerprint digest.
336 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub fingerprint: Option<String>,
338 /// Only crossings with one of these outcomes.
339 #[serde(default, skip_serializing_if = "Vec::is_empty")]
340 pub outcomes: Vec<CrossingOutcome>,
341 /// Only crossings at or after this time.
342 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub since: Option<DateTime<Utc>>,
344 /// At most this many records.
345 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub limit: Option<usize>,
347}
348
349impl CrossingFilter {
350 /// Only crossings out of `from`.
351 #[must_use]
352 pub fn from(mut self, from: impl Into<PartitionId>) -> Self {
353 self.from = Some(from.into());
354 self
355 }
356
357 /// Only crossings into `to`.
358 #[must_use]
359 pub fn to(mut self, to: impl Into<PartitionId>) -> Self {
360 self.to = Some(to.into());
361 self
362 }
363
364 /// Only crossings of `run`.
365 #[must_use]
366 pub fn run(mut self, run: impl Into<String>) -> Self {
367 self.run = Some(run.into());
368 self
369 }
370
371 /// Only crossings whose fingerprint digest is `digest`.
372 #[must_use]
373 pub fn fingerprint(mut self, digest: impl Into<String>) -> Self {
374 self.fingerprint = Some(digest.into());
375 self
376 }
377
378 /// Only crossings with one of `outcomes`.
379 #[must_use]
380 pub fn outcomes(mut self, outcomes: impl IntoIterator<Item = CrossingOutcome>) -> Self {
381 self.outcomes = outcomes.into_iter().collect();
382 self
383 }
384
385 /// Only crossings at or after `since`.
386 #[must_use]
387 pub fn since(mut self, since: DateTime<Utc>) -> Self {
388 self.since = Some(since);
389 self
390 }
391
392 /// At most `limit` records.
393 #[must_use]
394 pub fn limit(mut self, limit: usize) -> Self {
395 self.limit = Some(limit);
396 self
397 }
398
399 /// Whether `record` passes every field but `limit`.
400 pub fn matches(&self, record: &CrossingRecord) -> bool {
401 self.from.as_ref().is_none_or(|from| *from == record.from)
402 && self.to.as_ref().is_none_or(|to| *to == record.to)
403 && self.run.as_ref().is_none_or(|run| *run == record.run)
404 && self.fingerprint.as_ref().is_none_or(|digest| *digest == record.fingerprint)
405 && (self.outcomes.is_empty() || self.outcomes.contains(&record.outcome))
406 && self.since.is_none_or(|since| record.at >= since)
407 }
408}
409
410/// How a crossing tool's call names what it reaches (spec 3.2 §7.8).
411///
412/// # Example
413///
414/// ```rust
415/// use adk_kernel::{CrossingAccess, CrossingResource, CrossingRoute};
416/// use serde_json::json;
417///
418/// let route = CrossingRoute::argument(CrossingResource::Memory, CrossingAccess::Read, "memory");
419/// let crossing = route.crossing(&"home".into(), &json!({ "partition": "work", "query": "x" })).unwrap();
420/// assert_eq!(crossing.label(), "work › memory");
421/// assert!(route.crossing(&"home".into(), &json!({ "query": "x" })).is_err());
422/// ```
423#[derive(Debug, Clone, PartialEq, Eq)]
424#[non_exhaustive]
425pub enum CrossingRoute {
426 /// The call's [`partition`](CROSSING_PARTITION_ARG) argument names the target.
427 Argument {
428 /// What the tool reaches.
429 resource: CrossingResource,
430 /// Whether it only reads.
431 access: CrossingAccess,
432 /// The resource's name in the prompt.
433 name: String,
434 },
435 /// The tool reaches one partition: a driver tool of another partition offered to the
436 /// coordinator ([`CrossingTool`]).
437 Fixed {
438 /// The partition it reaches.
439 to: PartitionId,
440 /// What the tool reaches.
441 resource: CrossingResource,
442 /// Whether it only reads.
443 access: CrossingAccess,
444 /// The resource's name in the prompt.
445 name: String,
446 },
447}
448
449impl CrossingRoute {
450 /// A route whose call names the target in its `partition` argument.
451 pub fn argument(
452 resource: CrossingResource,
453 access: CrossingAccess,
454 name: impl Into<String>,
455 ) -> Self {
456 Self::Argument { resource, access, name: name.into() }
457 }
458
459 /// A route into `to`.
460 pub fn fixed(
461 to: impl Into<PartitionId>,
462 resource: CrossingResource,
463 access: CrossingAccess,
464 name: impl Into<String>,
465 ) -> Self {
466 Self::Fixed { to: to.into(), resource, access, name: name.into() }
467 }
468
469 /// The crossing a call from `from` with `args` makes.
470 ///
471 /// # Errors
472 ///
473 /// The reason, when an [`Argument`](Self::Argument) route's call names no partition.
474 pub fn crossing(&self, from: &PartitionId, args: &Value) -> Result<Crossing, String> {
475 match self {
476 Self::Argument { resource, access, name } => {
477 let to = args
478 .get(CROSSING_PARTITION_ARG)
479 .and_then(Value::as_str)
480 .map(str::trim)
481 .filter(|to| !to.is_empty())
482 .ok_or_else(|| {
483 format!("the call names no `{CROSSING_PARTITION_ARG}` to reach")
484 })?;
485 Ok(Crossing::new(from.clone(), to, *resource, name.clone(), *access))
486 }
487 Self::Fixed { to, resource, access, name } => {
488 Ok(Crossing::new(from.clone(), to.clone(), *resource, name.clone(), *access))
489 }
490 }
491 }
492}
493
494/// The run an approved read holds for (spec 3.2 §13 Q3): a durable run, across the
495/// invocations that resume it, or one invocation outside a durable run.
496///
497/// A durable run's approved reads are kept in the [`PartitionStore`](super::PartitionStore)
498/// and released when the kernel's worker finishes the run; an invocation's are kept in
499/// memory and released when its root agent ends. Neither outlives its run, and run and
500/// invocation ids are never reused.
501///
502/// # Example
503///
504/// ```rust
505/// use adk_kernel::CrossingRun;
506///
507/// assert_eq!(CrossingRun::of(Some("run-1"), "inv-1"), CrossingRun::Durable("run-1".into()));
508/// assert_eq!(CrossingRun::of(None, "inv-1").as_str(), "inv-1");
509/// ```
510#[derive(Debug, Clone, PartialEq, Eq, Hash)]
511#[non_exhaustive]
512pub enum CrossingRun {
513 /// A [`DurableRunStore`](adk_core::DurableRunStore) run.
514 Durable(String),
515 /// An invocation outside a durable run.
516 Invocation(String),
517}
518
519impl CrossingRun {
520 /// The durable run `durable_run_id` when there is one, else the invocation.
521 pub fn of(durable_run_id: Option<&str>, invocation_id: &str) -> Self {
522 match durable_run_id {
523 Some(run) => Self::Durable(run.to_string()),
524 None => Self::Invocation(invocation_id.to_string()),
525 }
526 }
527
528 /// The run's id, as the crossing ledger records it.
529 pub fn as_str(&self) -> &str {
530 match self {
531 Self::Durable(id) | Self::Invocation(id) => id,
532 }
533 }
534}
535
536/// The policy of one partition's harness (spec 3.2 §7.8, K-I15): a `ToolPolicy` that
537/// decides the calls of its crossing tools and lets every other call through, so it composes
538/// with the harness policy through `StrictestPolicy` and never loosens it (K-I6).
539///
540/// | Call | Decision |
541/// |---|---|
542/// | Not a crossing tool, or a crossing into the agent's own partition | `Allow` |
543/// | A crossing by any agent but the coordinator | `Deny` |
544/// | A crossing the partition table refuses ([`Partitions::admit`]) | `Deny` |
545/// | The coordinator's read whose crossing fingerprint was approved earlier in the run | `Allow` |
546/// | Any other crossing by the coordinator | `RequireApproval`, naming the crossing and its three answers |
547///
548/// Every decision about a crossing is recorded in the ledger and as `kernel.partition.crossing`.
549/// The run is the call's durable run (`PolicyCall::durable_run_id`), else its invocation.
550///
551/// # Example
552///
553/// ```rust
554/// use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest};
555/// use adk_kernel::{CrossingAccess, CrossingResource, CrossingRoute, Partitions};
556/// use serde_json::json;
557///
558/// # #[tokio::main(flavor = "current_thread")]
559/// # async fn main() {
560/// let policy = Partitions::in_memory()
561/// .policy("work")
562/// .with_crossing_tool("partition_memory_search", CrossingRoute::argument(CrossingResource::Memory, CrossingAccess::Read, "memory"));
563/// let mut request = ToolPolicyRequest::new("partition_memory_search", json!({ "partition": "home", "query": "dentist" }));
564/// request.agent_name = "harness".into();
565/// // Not the coordinator: denied.
566/// assert!(matches!(policy.evaluate(&request).await, PolicyDecision::Deny { .. }));
567/// // Any other tool is the harness's to decide.
568/// assert_eq!(policy.evaluate(&ToolPolicyRequest::new("read_file", json!({}))).await, PolicyDecision::Allow);
569/// # }
570/// ```
571#[derive(Clone)]
572pub struct PartitionPolicy {
573 partitions: Partitions,
574 home: PartitionId,
575 coordinator: Option<String>,
576 routes: Arc<RwLock<BTreeMap<String, CrossingRoute>>>,
577}
578
579impl fmt::Debug for PartitionPolicy {
580 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581 f.debug_struct("PartitionPolicy")
582 .field("home", &self.home)
583 .field("coordinator", &self.coordinator)
584 .field("routes", &self.routes.read().unwrap_or_else(|e| e.into_inner()).len())
585 .finish()
586 }
587}
588
589impl PartitionPolicy {
590 pub(super) fn new(partitions: Partitions, home: PartitionId) -> Self {
591 Self { partitions, home, coordinator: None, routes: Arc::default() }
592 }
593
594 /// Makes the agent named `agent_name` — the root agent of this partition's harness —
595 /// the coordinator, the one agent that may cross, under approval.
596 #[must_use]
597 pub fn with_coordinator(mut self, agent_name: impl Into<String>) -> Self {
598 self.coordinator = Some(agent_name.into());
599 self
600 }
601
602 /// Decides calls to the tool `name` as crossings along `route`.
603 #[must_use]
604 pub fn with_crossing_tool(self, name: impl Into<String>, route: CrossingRoute) -> Self {
605 self.register(name, route);
606 self
607 }
608
609 /// Decides calls to the tool `name` as crossings along `route`, in this policy and every
610 /// clone of it.
611 pub fn register(&self, name: impl Into<String>, route: CrossingRoute) {
612 self.routes.write().unwrap_or_else(|e| e.into_inner()).insert(name.into(), route);
613 }
614
615 /// The partition of the harness the policy governs.
616 pub fn home(&self) -> &PartitionId {
617 &self.home
618 }
619
620 /// The coordinator's agent name, when this partition's harness is the coordinator.
621 pub fn coordinator(&self) -> Option<&str> {
622 self.coordinator.as_deref()
623 }
624
625 /// The partition table.
626 pub fn partitions(&self) -> &Partitions {
627 &self.partitions
628 }
629
630 /// The route of the crossing tool `name`, or `None` when the tool is no crossing tool.
631 pub fn route(&self, name: &str) -> Option<CrossingRoute> {
632 self.routes.read().unwrap_or_else(|e| e.into_inner()).get(name).cloned()
633 }
634
635 fn is_coordinator(&self, agent_name: &str) -> bool {
636 self.coordinator.as_deref() == Some(agent_name)
637 }
638
639 /// Runs `body`, the reach of a crossing tool into another partition, after checking
640 /// the crossing the call makes ([`Partitions::admit`]), and records it afterwards: a
641 /// crossing tool's `execute` (spec 3.2 §7.8, K-I15).
642 ///
643 /// The governed path authorized the call before `execute`: the policy held a crossing
644 /// for approval unless the run had approved the same read. This check refuses any call
645 /// the partition table refuses, so even a harness built without the policy never
646 /// crosses for an agent other than the coordinator.
647 ///
648 /// # Errors
649 ///
650 /// A `Forbidden` tool error when the crossing is refused, or `body`'s error.
651 pub async fn run_crossing<F, Fut>(
652 &self,
653 ctx: &dyn ToolContext,
654 tool: &dyn Tool,
655 args: &Value,
656 body: F,
657 ) -> adk_core::Result<Value>
658 where
659 F: FnOnce() -> Fut,
660 Fut: std::future::Future<Output = adk_core::Result<Value>>,
661 {
662 let route = self.route(tool.name()).ok_or_else(|| {
663 AdkError::tool(format!(
664 "{} is not registered as a crossing tool of partition `{}`",
665 tool.name(),
666 self.home
667 ))
668 })?;
669 let crossing = route.crossing(&self.home, args).map_err(refused)?;
670 if crossing.to == self.home {
671 return body().await;
672 }
673 self.partitions
674 .admit(&crossing, self.is_coordinator(ctx.agent_name()))
675 .await
676 .map_err(refused)?;
677 let acting = ctx.acting_context();
678 let request = ToolConfirmationRequest::new(tool.name(), args.clone())
679 .with_acting_context(acting.clone())
680 .with_origin(ToolOrigin::of(tool));
681 let fingerprint = crossing.fingerprint(&request);
682 let durable = ctx.run_config().and_then(|config| config.durable_run_id.clone());
683 let run = CrossingRun::of(durable.as_deref(), ctx.invocation_id());
684 let value = body().await?;
685 if let Err(error) = self
686 .partitions
687 .executed(&crossing, &fingerprint, &run, acting.agent.id.as_str(), tool.name())
688 .await
689 {
690 tracing::warn!(error = %error, crossing = %crossing.label(), "a crossing ran but could not be recorded");
691 }
692 Ok(value)
693 }
694}
695
696fn refused(reason: String) -> AdkError {
697 AdkError::new(
698 ErrorComponent::Tool,
699 ErrorCategory::Forbidden,
700 crate::error::CROSSING_DENIED_CODE,
701 reason,
702 )
703}
704
705#[async_trait]
706impl ToolPolicy for PartitionPolicy {
707 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
708 self.evaluate_call(request, &PolicyCall::new()).await
709 }
710
711 async fn evaluate_call(
712 &self,
713 request: &ToolPolicyRequest,
714 call: &PolicyCall<'_>,
715 ) -> PolicyDecision {
716 let Some(route) = self.route(&request.tool_name) else {
717 return PolicyDecision::Allow;
718 };
719 let crossing = match route.crossing(&self.home, &request.args) {
720 Ok(crossing) => crossing,
721 Err(reason) => return PolicyDecision::deny(reason),
722 };
723 if crossing.to == self.home {
724 return PolicyDecision::Allow;
725 }
726 let mut confirmation =
727 ToolConfirmationRequest::new(&request.tool_name, request.args.clone());
728 if let Some(acting) = &request.acting {
729 confirmation = confirmation.with_acting_context(acting.clone());
730 }
731 if let Some(origin) = call.origin {
732 confirmation = confirmation.with_origin(origin.clone());
733 }
734 let fingerprint = crossing.fingerprint(&confirmation);
735 let run = CrossingRun::of(call.durable_run_id, &request.invocation_id);
736 let agent = request
737 .acting
738 .as_ref()
739 .map(|acting| acting.agent.id.as_str().to_string())
740 .unwrap_or_else(|| request.agent_name.clone());
741 let recorded = super::CrossingCall {
742 crossing: &crossing,
743 fingerprint: &fingerprint,
744 run: run.as_str(),
745 agent: &agent,
746 tool: &request.tool_name,
747 };
748 let decided = |outcome, reason: Option<String>| {
749 self.partitions.decided(&recorded, call.function_call_id, outcome, reason)
750 };
751 if let Err(reason) =
752 self.partitions.admit(&crossing, self.is_coordinator(&request.agent_name)).await
753 {
754 tracing::info!(crossing = %crossing.label(), agent.name = %request.agent_name, reason = %reason, "partition crossing denied");
755 decided(CrossingOutcome::Denied, Some(reason.clone())).await;
756 return PolicyDecision::deny(format!("partition crossing denied: {reason}"));
757 }
758 if crossing.access == CrossingAccess::Read
759 && self.partitions.granted(&run, &fingerprint).await
760 {
761 decided(CrossingOutcome::RunGrant, None).await;
762 return PolicyDecision::Allow;
763 }
764 decided(CrossingOutcome::Held, None).await;
765 PolicyDecision::require_approval(crossing.approval_reason())
766 }
767
768 fn policy_ref(&self) -> Option<String> {
769 Some(format!("adk-kernel.partition:{}", self.home))
770 }
771}
772
773/// The most characters of a tool name providers accept.
774const TOOL_NAME_MAX: usize = 64;
775
776/// A tool of another partition offered to the coordinator (spec 3.2 §7.8): a driver's tool,
777/// or a tool reading another partition's sessions, named `<to>__<tool>` and governed as a
778/// crossing by the coordinator's [`PartitionPolicy`], with which it registers itself.
779///
780/// Its declaration, annotations, origin and effect are the wrapped tool's, under its own
781/// name; its description names the crossing. The access is the caller's to state from the
782/// tool's effect class — [`Read`](CrossingAccess::Read) only for a driver tool of class
783/// `Read`, never for `Financial` or `PublishPublic` — never from the tool's own hints (spec
784/// 3.1 I12, K-I9); a `Read` the tool does not also declare `ToolEffect::ReadOnly` for is
785/// taken as `Write`, so only a read both sides agree on is reused for the rest of a run.
786///
787/// # Example
788///
789/// ```rust,ignore
790/// let policy = partitions.policy("home").with_coordinator("harness");
791/// let tool = CrossingTool::new(list_events, &policy, "work", CrossingResource::Driver, CrossingAccess::Read, "calendar");
792/// assert_eq!(tool.name(), "work__list_events");
793/// ```
794pub struct CrossingTool {
795 inner: Arc<dyn Tool>,
796 name: String,
797 description: String,
798 policy: PartitionPolicy,
799}
800
801impl fmt::Debug for CrossingTool {
802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803 f.debug_struct("CrossingTool").field("name", &self.name).finish_non_exhaustive()
804 }
805}
806
807impl CrossingTool {
808 /// `inner`, a tool reaching partition `to`'s `resource` named `name`, offered to the
809 /// coordinator of `policy`'s partition; registers the crossing with `policy`.
810 pub fn new(
811 inner: Arc<dyn Tool>,
812 policy: &PartitionPolicy,
813 to: impl Into<PartitionId>,
814 resource: CrossingResource,
815 access: CrossingAccess,
816 name: impl Into<String>,
817 ) -> Self {
818 let to = to.into();
819 // A read is reused for the rest of a run only when the tool also declares itself
820 // read-only; a hint never widens what the caller stated (spec 3.1 I12, K-I9).
821 let access = match (access, inner.effect()) {
822 (CrossingAccess::Read, ToolEffect::ReadOnly) => CrossingAccess::Read,
823 _ => CrossingAccess::Write,
824 };
825 let route = CrossingRoute::fixed(to.clone(), resource, access, name);
826 let label = match &route {
827 CrossingRoute::Fixed { name, .. } => format!("{to} › {name}"),
828 CrossingRoute::Argument { .. } => to.to_string(),
829 };
830 let tool_name: String = format!("{to}__{}", inner.name())
831 .chars()
832 .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '-') { c } else { '_' })
833 .take(TOOL_NAME_MAX)
834 .collect();
835 let description = format!(
836 "[Reaches partition `{to}` ({label}): every call needs the user's approval.] {}",
837 inner.description()
838 );
839 policy.register(tool_name.clone(), route);
840 Self { inner, name: tool_name, description, policy: policy.clone() }
841 }
842
843 /// The wrapped tool.
844 pub fn inner(&self) -> &Arc<dyn Tool> {
845 &self.inner
846 }
847}
848
849#[async_trait]
850impl Tool for CrossingTool {
851 fn name(&self) -> &str {
852 &self.name
853 }
854
855 fn description(&self) -> &str {
856 &self.description
857 }
858
859 fn declaration(&self) -> Value {
860 let mut declaration = self.inner.declaration();
861 if let Value::Object(fields) = &mut declaration {
862 fields.insert("name".into(), Value::String(self.name.clone()));
863 fields.insert("description".into(), Value::String(self.description.clone()));
864 }
865 declaration
866 }
867
868 fn parameters_schema(&self) -> Option<Value> {
869 self.inner.parameters_schema()
870 }
871
872 fn response_schema(&self) -> Option<Value> {
873 self.inner.response_schema()
874 }
875
876 fn is_long_running(&self) -> bool {
877 self.inner.is_long_running()
878 }
879
880 fn annotations(&self) -> Option<&Value> {
881 self.inner.annotations()
882 }
883
884 fn origin(&self) -> &str {
885 self.inner.origin()
886 }
887
888 fn required_scopes(&self) -> &[&str] {
889 self.inner.required_scopes()
890 }
891
892 fn is_read_only(&self) -> bool {
893 self.inner.is_read_only()
894 }
895
896 fn effect(&self) -> ToolEffect {
897 self.inner.effect()
898 }
899
900 fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
901 self.inner.egress(args)
902 }
903
904 fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
905 self.inner.approval_evidence(args)
906 }
907
908 fn batch_group(&self) -> Option<adk_core::BatchGroup> {
909 self.inner.batch_group()
910 }
911
912 fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
913 self.inner.timeout_override()
914 }
915
916 fn is_concurrency_safe(&self) -> bool {
917 self.inner.is_concurrency_safe()
918 }
919
920 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
921 let inner = Arc::clone(&self.inner);
922 let call_ctx = Arc::clone(&ctx);
923 let call_args = args.clone();
924 self.policy
925 .run_crossing(ctx.as_ref(), self, &args, move || async move {
926 inner.execute(call_ctx, call_args).await
927 })
928 .await
929 }
930}
931
932/// A crossing that keeps happening (spec 3.2 §7.8): what the maintenance process reports, with
933/// partition membership as the remedy, never a waiver.
934///
935/// # Example
936///
937/// ```rust
938/// use adk_kernel::{CrossingResource, RecurringCrossing};
939///
940/// let recurring = RecurringCrossing::new("home", "work", CrossingResource::Driver, "calendar", 14);
941/// assert!(recurring.remedy().contains("move calendar into home, or merge home and work"));
942/// ```
943#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
944#[serde(rename_all = "camelCase")]
945#[non_exhaustive]
946pub struct RecurringCrossing {
947 /// The partition the requests came from.
948 pub from: PartitionId,
949 /// The partition they reached.
950 pub to: PartitionId,
951 /// What they reached.
952 pub resource: CrossingResource,
953 /// The resource's name.
954 pub name: String,
955 /// How many crossings in the window: each request held, denied, or let through by its
956 /// run's approval.
957 pub count: usize,
958}
959
960impl RecurringCrossing {
961 /// `count` crossings from `from` into `to`'s `resource` named `name`.
962 pub fn new(
963 from: impl Into<PartitionId>,
964 to: impl Into<PartitionId>,
965 resource: CrossingResource,
966 name: impl Into<String>,
967 count: usize,
968 ) -> Self {
969 Self { from: from.into(), to: to.into(), resource, name: name.into(), count }
970 }
971
972 /// The report line: how often, and that the remedy is partition membership.
973 pub fn remedy(&self) -> String {
974 format!(
975 "partition {} crossed into {} › {} {} times; if it needs it this often, move {} into \
976 {}, or merge {} and {} (`adk-rust partitions`); a crossing is never waived",
977 self.from, self.to, self.name, self.count, self.name, self.from, self.from, self.to
978 )
979 }
980}