Skip to main content

adk_harness/
kernel.rs

1//! The glue between the harness and the Agent Kernel (spec 3.2 §10 HK1, HK3; feature
2//! `kernel`).
3//!
4//! `adk-kernel` hosts any `Arc<Runner>` and reads no harness type (spec 3.2 §6 D-1); this
5//! module gives it the harness:
6//!
7//! | Item | Spec |
8//! |---|---|
9//! | [`Harness::kernel`]: a `KernelBuilder` with the harness runner as the app's and the `harness.goal` targets | §10 HK1 |
10//! | `PartitionMode` → [`HarnessMode`], one to one | §10 HK1, §7.8 |
11//! | Goal progress, the loop guard's verdict and each session's usage for the kernel's process view | §7.3, §7.10, §10 HK3 |
12//! | Parking a goal that stopped making progress, `Waiting` and suspended manually, with `harness.goal.stalled` | §7.3, §10 HK3 |
13//! | Decisions on the harness's approval service waking the kernel's approval sleepers | §7.4 |
14//! | `propose_followup`, class `Todo`: an agent's follow-up as a `Proposed` agenda item | §7.5 |
15//! | The standing rules the kernel's daily review checks for renewal | §9.1 |
16//! | [`driver_tool_kind`]: `EffectClass` → [`ToolKind::External`], the manifest's class over any `readOnlyHint` | §7.7, §10 HK1 |
17//! | [`DriverClasses`], [`HarnessAgentBuilder::kernel_drivers`]: a partition's drivers with their classes and the kernel's driver policy | §7.7, §7.8 |
18//! | [`HarnessRulePins`]: standing rules carried to re-approved driver declarations | §7.7, K-I14 |
19//! | The harness's activity in the kernel's content-free ledger: each run's `intent`, each tool call with its effect class and duration, and its audit records — `harness.spend`, the loop guard, approvals, denials and the rest — through `LedgerAuditTap`; a partition's harness writes its rows in its partition | §7.10, §7.8 |
20
21use std::sync::{Arc, OnceLock, RwLock};
22
23use adk_core::audit_log::AuditTrail;
24use adk_core::{
25    AdkError, ApprovalCall, ApprovalDecision, ApprovalDelegation, ApprovalEventKind,
26    ApprovalNotification, ApprovalNotifier, ApprovalRequest, ApprovalService, ApprovalState,
27    ApprovalStore, ApprovalTick, ErrorCategory, ErrorComponent, InboxPage, InboxQuery, Result,
28    RunCheckpointRef, RunRecord, SubjectRef, Tool, ToolApproval, ToolConfirmationDecision,
29    ToolContext, ToolEffect,
30};
31use adk_kernel::proc::{Activity, LateLedgerSink, LedgerAuditTap, LedgerSink};
32use adk_kernel::{
33    AgendaHandle, AgendaItem, AgendaOrigin, ApprovalWakeSource, GoalProgress, KernelBuilder,
34    KernelConfig, PartitionId, PartitionMode, PlanRef, ProcessHandle, ProgressSource,
35    ProposalOutcome, RuleAge, StandingRuleSource, Wake,
36};
37use async_trait::async_trait;
38use chrono::{DateTime, Utc};
39use serde_json::{Value, json};
40
41use crate::approvals::{OriginPin, StandingRuleStore};
42use crate::builder::HarnessAgentBuilder;
43use crate::goal::{GoalBook, GoalParker, GoalStore};
44use crate::harness::Harness;
45use crate::mode::{HarnessMode, ModeRecord, ModeSource, ModeStore};
46use crate::policy::{OriginClasses, ToolKind, has_harness_layer};
47use crate::tools::PlanStep;
48
49impl From<PartitionMode> for HarnessMode {
50    /// A partition's mode is the harness mode of the same name (spec 3.2 §10 HK1); a mode a
51    /// later kernel adds maps to the strictest, `ReadOnly`.
52    fn from(mode: PartitionMode) -> Self {
53        match mode {
54            PartitionMode::ReadOnly => HarnessMode::ReadOnly,
55            PartitionMode::Plan => HarnessMode::Plan,
56            PartitionMode::Ask => HarnessMode::Ask,
57            PartitionMode::Auto => HarnessMode::Auto,
58            _ => HarnessMode::ReadOnly,
59        }
60    }
61}
62
63/// The harness class of a driver tool of `class` (spec 3.2 §7.7, §10 HK1).
64///
65/// The manifest the user approved is the source of truth, so a server's own `readOnlyHint`
66/// never grants anything (3.1 I12): `read` is a trusted read-only external tool, and every
67/// other class a trusted external tool with effects, which the mode table asks about in
68/// Ask and Auto and refuses in ReadOnly and Plan. `publish_public` and `financial` map the
69/// same way; the kernel's driver policy, which [`HarnessAgentBuilder::kernel_drivers`]
70/// composes with the harness's, asks before every call of them, so no mode, standing rule
71/// or earlier approval allows one (K-I9).
72///
73/// # Example
74///
75/// ```rust
76/// use adk_core::ToolEffect;
77/// use adk_harness::{ToolKind, driver_tool_kind};
78/// use adk_kernel::drivers::EffectClass;
79///
80/// assert_eq!(
81///     driver_tool_kind(EffectClass::Read),
82///     ToolKind::External { effect: ToolEffect::ReadOnly, trusted_origin: true }
83/// );
84/// assert_eq!(
85///     driver_tool_kind(EffectClass::SendExternal),
86///     ToolKind::External { effect: ToolEffect::NonIdempotent, trusted_origin: true }
87/// );
88/// ```
89pub fn driver_tool_kind(class: adk_kernel::drivers::EffectClass) -> ToolKind {
90    ToolKind::External { effect: class.tool_effect(), trusted_origin: true }
91}
92
93/// Classes the kernel's driver tools by their approved manifests (spec 3.2 §7.7).
94///
95/// # Example
96///
97/// ```rust
98/// use std::sync::Arc;
99/// use adk_harness::{DriverClasses, OriginClasses};
100/// use adk_kernel::drivers::DriverSupervisor;
101/// use adk_kernel::stores::InMemoryDriverStore;
102///
103/// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
104/// let classes = DriverClasses::new(drivers);
105/// assert_eq!(classes.class_of("driver:email", "send_draft"), None); // not mounted
106/// assert_eq!(classes.class_of("mcp:email", "send_draft"), None); // not a driver
107/// ```
108#[derive(Debug, Clone)]
109pub struct DriverClasses {
110    drivers: adk_kernel::drivers::DriverSupervisor,
111}
112
113impl DriverClasses {
114    /// The classes of `drivers`' mounted manifests.
115    pub fn new(drivers: adk_kernel::drivers::DriverSupervisor) -> Self {
116        Self { drivers }
117    }
118}
119
120impl OriginClasses for DriverClasses {
121    fn class_of(&self, source: &str, tool: &str) -> Option<ToolKind> {
122        self.drivers.class_of(source, tool).map(driver_tool_kind)
123    }
124}
125
126impl HarnessAgentBuilder {
127    /// Mounts the kernel's drivers for `partition` (spec 3.2 §7.7, §7.8): the tools of the
128    /// drivers whose manifest lists `partition` and whose id is in `drivers` — the
129    /// partition's own driver list — classed by their manifests, with the kernel's driver
130    /// policy composed with the harness's, the stricter decision winning (K-I6).
131    ///
132    /// # Example
133    ///
134    /// ```rust,ignore
135    /// let agent = HarnessAgent::builder("work")
136    ///     .model(model)
137    ///     .workspace(workspace)
138    ///     .kernel_drivers(&drivers, &partition.id, &partition.drivers)
139    ///     .build()?;
140    /// ```
141    pub fn kernel_drivers(
142        self,
143        drivers: &adk_kernel::drivers::DriverSupervisor,
144        partition: &adk_kernel::PartitionId,
145        ids: &[String],
146    ) -> Self {
147        self.toolset(drivers.toolset_for(partition, ids))
148            .tool_classes(Arc::new(DriverClasses::new(drivers.clone())))
149            .add_operator_policy(drivers.policy())
150    }
151}
152
153/// Moves a person's standing rules onto a driver tool's re-approved declaration
154/// (spec 3.2 §7.7, K-I14): each of the subject's rules in the app pinned exactly to the old
155/// declaration of the tool is granted again, pinned to the new one.
156///
157/// # Example
158///
159/// ```rust,ignore
160/// let drivers = DriverSupervisor::builder(store).rule_pins(harness.driver_rule_pins()).build();
161/// ```
162#[derive(Debug, Clone)]
163pub struct HarnessRulePins {
164    app_name: String,
165    rules: Arc<dyn StandingRuleStore>,
166}
167
168impl HarnessRulePins {
169    /// Re-pins the rules of `app_name` in `rules`.
170    pub fn new(app_name: impl Into<String>, rules: Arc<dyn StandingRuleStore>) -> Self {
171        Self { app_name: app_name.into(), rules }
172    }
173}
174
175#[async_trait]
176impl adk_kernel::drivers::StandingRulePins for HarnessRulePins {
177    async fn repin(
178        &self,
179        subject: &str,
180        source: &str,
181        tool: &str,
182        from: &str,
183        to: &str,
184    ) -> Result<usize> {
185        let mut moved = 0;
186        for mut rule in self.rules.list(&self.app_name, subject).await? {
187            let pinned = matches!(
188                &rule.origin,
189                OriginPin::Exact { source: pinned, declaration_digest } if pinned == source && declaration_digest == from
190            );
191            if !pinned || rule.tool != tool {
192                continue;
193            }
194            rule.origin =
195                OriginPin::Exact { source: source.to_string(), declaration_digest: to.to_string() };
196            self.rules.grant(rule).await?;
197            moved += 1;
198        }
199        Ok(moved)
200    }
201}
202
203impl Harness {
204    /// Carries this harness's standing rules to re-approved driver declarations; pass it
205    /// to `DriverSupervisorBuilder::rule_pins` (spec 3.2 §7.7).
206    pub fn driver_rule_pins(&self) -> Arc<dyn adk_kernel::drivers::StandingRulePins> {
207        Arc::new(HarnessRulePins::new(
208            self.app_name(),
209            self.agent().runtime().standing_rules().clone(),
210        ))
211    }
212}
213
214impl Harness {
215    /// A kernel builder that hosts this harness (spec 3.2 §10 HK1): the harness runner as
216    /// the app's target (`adk-rust` in the CLI) and as `harness.goal`, with the harness's
217    /// session service, approval service, governance control, audit trail and spend ledger,
218    /// its run store when it has one, and a progress source for goal progress, the loop
219    /// guard's verdict, each session's usage and the parking of a stalled goal.
220    ///
221    /// The caller adds the process store, the `KernelConfig` and the control plane. The
222    /// governance control is set with `KernelBuilder::governance`, so a later `config(..)`
223    /// keeps it. Decisions made through the harness's approval service wake the kernel's
224    /// `Wake::Approval` sleepers; a caller that also decides through the service it passed
225    /// to the harness builder hands that service out as
226    /// `harness.agent().runtime().approval_service()` instead. Goals land on the kernel's
227    /// `background` queue when the harness was given
228    /// `with_goal_queue(adk_kernel::QueueClass::BACKGROUND)`.
229    ///
230    /// A partition's harness registers its runner as its partition's targets,
231    /// `<app>@<partition>` and `harness.goal@<partition>`, bound to the partition, with the
232    /// partition table its policy reads ([`host_partition`](Self::host_partition)); add the
233    /// other partitions' harnesses with `host_partition` (spec 3.2 §7.8).
234    ///
235    /// # Example
236    ///
237    /// ```rust,ignore
238    /// let kernel = harness
239    ///     .with_goal_queue(adk_kernel::QueueClass::BACKGROUND)
240    ///     .kernel()
241    ///     .process_store(Arc::new(adk_kernel::InMemoryProcessStore::new()))
242    ///     .build()?;
243    /// kernel.start().await?;
244    /// ```
245    pub fn kernel(&self) -> KernelBuilder {
246        let runtime = self.agent().runtime();
247        let (target, runner) = self.goal_target();
248        let progress = self.kernel_progress();
249        let source = runtime.kernel_approvals.bind();
250        let builder = adk_kernel::Kernel::builder()
251            .config(KernelConfig::default().with_app_name(self.app_name()));
252        // A partition's harness runs as its partition's targets and answers for its
253        // partition's processes (spec 3.2 §7.8).
254        let builder = match self.agent().partition() {
255            Some(_) => self.host_partition_with(builder, progress.clone()),
256            None => builder.agent(self.app_name(), runner.clone()).agent(target, runner.clone()),
257        };
258        let mut builder = builder
259            .session_service(self.sessions().clone())
260            .governance(runner.governance().clone())
261            .progress_source(progress)
262            .wake_source(source)
263            .agenda_handle(runtime.kernel_agenda.clone())
264            .standing_rules(Arc::new(HarnessRules(runtime.standing_rules.clone())));
265        if let Some(service) = runtime.approval_service() {
266            builder = builder.approval_service(service.clone());
267        }
268        if let Some(trail) = runner.run_config().audit.clone().or_else(|| runtime.audit.clone()) {
269            builder = builder.audit(trail);
270        }
271        if let Some(ledger) = runtime.spend_ledger.clone() {
272            builder = builder.spend_ledger(ledger);
273        }
274        if let Some(runs) = self.run_store() {
275            builder = builder.run_store(runs.clone());
276        }
277        builder
278    }
279}
280
281/// The session a durable run continues, as the worker names it.
282fn session_of(run: &RunRecord) -> String {
283    match (&run.checkpoint, &run.session_id) {
284        (
285            Some(
286                RunCheckpointRef::Session { session_id, .. }
287                | RunCheckpointRef::AwaitingApproval { session_id, .. },
288            ),
289            _,
290        ) => session_id.clone(),
291        (_, Some(session_id)) => session_id.clone(),
292        _ => format!("run-{}", run.run_id),
293    }
294}
295
296impl Harness {
297    /// What this harness tells a kernel about the processes it runs, the parker of its
298    /// stalled goals.
299    pub(crate) fn kernel_progress(&self) -> Arc<HarnessProgress> {
300        let runtime = self.agent().runtime();
301        let progress = Arc::new(HarnessProgress {
302            goals: runtime.goal_store().clone(),
303            book: runtime.goals.until.book().clone(),
304            #[cfg(feature = "observe")]
305            trails: runtime.run_trails.clone(),
306            processes: RwLock::new(None),
307            ledger: runtime.kernel_ledger.clone(),
308            partition: self.agent().partition().map(|partition| partition.id.clone()),
309        });
310        runtime.goals.until.book().set_parker(progress.clone());
311        progress
312    }
313}
314
315/// What the harness tells the kernel about the processes it runs (spec 3.2 §7.3, §10 HK3).
316pub(crate) struct HarnessProgress {
317    goals: Arc<dyn GoalStore>,
318    book: Arc<GoalBook>,
319    #[cfg(feature = "observe")]
320    trails: Arc<crate::observe::RunTrails>,
321    processes: RwLock<Option<ProcessHandle>>,
322    /// Where the harness writes its activity; bound to the kernel's ledger at start.
323    ledger: LateLedgerSink,
324    /// The partition of a partition's harness, whose ledger rows carry it (spec 3.2 §7.8).
325    partition: Option<PartitionId>,
326}
327
328/// The kernel's ledger as a partition's harness writes to it: every row in the partition
329/// (spec 3.2 §7.8, §7.10). The harness serves only its partition's sessions, so the
330/// partition is the session's.
331struct PartitionRows {
332    ledger: Arc<dyn LedgerSink>,
333    partition: PartitionId,
334}
335
336#[async_trait]
337impl LedgerSink for PartitionRows {
338    async fn record(&self, activity: Activity) -> adk_kernel::Result<()> {
339        self.ledger.record(activity.with_partition(self.partition.clone())).await
340    }
341}
342
343#[async_trait]
344impl ProgressSource for HarnessProgress {
345    async fn goal_progress(&self, run: &RunRecord) -> adk_kernel::Result<Option<GoalProgress>> {
346        let session = session_of(run);
347        let Some(record) = self.goals.get(&run.app_name, &run.user_id, &session).await? else {
348            return Ok(None);
349        };
350        let mut progress = GoalProgress::new(record.state.iteration, record.state.max_iterations);
351        let track = self.book.track(&record.run_id);
352        if let Some(track) = &track {
353            let elapsed = Utc::now() - track.started_at;
354            progress = progress.with_duration(elapsed.to_std().unwrap_or_default());
355        }
356        if let Some(exit) = record.state.last_check {
357            let tail = track.and_then(|track| track.last_tail).unwrap_or_default();
358            progress = progress.with_last_check(exit, tail);
359        }
360        Ok(Some(progress))
361    }
362
363    #[cfg(feature = "observe")]
364    async fn loop_guard(&self, run: &RunRecord) -> adk_kernel::Result<Option<String>> {
365        Ok(self.trails.verdict(&run.app_name, &run.user_id, &session_of(run)))
366    }
367
368    #[cfg(feature = "observe")]
369    async fn usage(&self, run: &RunRecord) -> adk_kernel::Result<Option<adk_kernel::RunUsage>> {
370        Ok(self.trails.session_usage(&run.app_name, &run.user_id, &session_of(run)))
371    }
372
373    fn attach(&self, processes: ProcessHandle) {
374        *self.processes.write().unwrap_or_else(|e| e.into_inner()) = Some(processes);
375    }
376
377    fn attach_ledger(&self, ledger: Arc<dyn LedgerSink>) {
378        let ledger = match &self.partition {
379            Some(partition) => Arc::new(PartitionRows { ledger, partition: partition.clone() })
380                as Arc<dyn LedgerSink>,
381            None => ledger,
382        };
383        if !self.ledger.bind(ledger) {
384            tracing::debug!("the harness already writes to a kernel's ledger; keeping it");
385        }
386    }
387}
388
389/// `trail` with every record also written to the kernel's ledger once bound (spec 3.2
390/// §7.10): the record first, then its content-free row.
391pub(crate) fn tap_audit(trail: AuditTrail, ledger: &LateLedgerSink) -> AuditTrail {
392    let tap = LedgerAuditTap::new(trail.recorder().clone(), Arc::new(ledger.clone()));
393    AuditTrail::new(Arc::new(tap)).with_failure_mode(trail.failure_mode())
394}
395
396#[async_trait]
397impl GoalParker for HarnessProgress {
398    async fn park(&self, run_id: &str) -> Result<bool> {
399        let processes = self.processes.read().unwrap_or_else(|e| e.into_inner()).clone();
400        match processes {
401            Some(processes) => processes.suspend(run_id).await.map_err(Into::into),
402            None => Ok(false),
403        }
404    }
405}
406
407/// The rows one harness run writes to the kernel's ledger (spec 3.2 §7.10): its `intent`
408/// when it starts, and each tool call when its response arrives, with the tool's effect
409/// class, the time it took and, as the subject the ledger hashes, the call's fingerprint.
410#[cfg(feature = "observe")]
411pub(crate) struct ToolEvents {
412    sink: LateLedgerSink,
413    effects: Arc<std::collections::HashMap<String, String>>,
414    agent: String,
415    trace: Option<String>,
416    started: std::collections::HashMap<String, (String, String, DateTime<Utc>)>,
417}
418
419#[cfg(feature = "observe")]
420impl ToolEvents {
421    /// The rows of a run of `agent` in `invocation`, or `None` until a kernel's ledger is
422    /// bound.
423    pub(crate) fn new(
424        sink: &LateLedgerSink,
425        effects: &Arc<std::collections::HashMap<String, String>>,
426        agent: &str,
427        invocation: &str,
428    ) -> Option<Self> {
429        sink.is_bound().then(|| Self {
430            sink: sink.clone(),
431            effects: Arc::clone(effects),
432            agent: adk_kernel::proc::label(agent, 128),
433            trace: ((1..=64).contains(&invocation.len())
434                && invocation.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
435            .then(|| invocation.to_string()),
436            started: std::collections::HashMap::new(),
437        })
438    }
439
440    async fn record(&self, activity: adk_kernel::proc::Activity) {
441        let activity = match &self.trace {
442            Some(trace) => activity.with_trace_id(trace.clone()),
443            None => activity,
444        };
445        if let Err(error) = self.sink.record(activity).await {
446            tracing::warn!(error = %error, "could not write a harness ledger row");
447        }
448    }
449
450    /// The run started.
451    pub(crate) async fn intent(&self) {
452        self.record(adk_kernel::proc::Activity::new(
453            adk_kernel::proc::LedgerKind::Intent,
454            self.agent.clone(),
455        ))
456        .await;
457    }
458
459    /// Notes the calls `event` makes and writes a row for each response it carries.
460    pub(crate) async fn observe(&mut self, event: &adk_core::Event) {
461        if event.llm_response.partial {
462            return;
463        }
464        let Some(content) = &event.llm_response.content else { return };
465        for part in &content.parts {
466            match part {
467                adk_core::Part::FunctionCall { name, args, id, .. } => {
468                    if self.started.len() > 1024 {
469                        self.started.clear();
470                    }
471                    let key = id.clone().unwrap_or_else(|| name.clone());
472                    let fingerprint = adk_core::tool_call_fingerprint(name, args);
473                    self.started.insert(key, (name.clone(), fingerprint, event.timestamp));
474                }
475                adk_core::Part::FunctionResponse { function_response, id, .. } => {
476                    let key = id.clone().unwrap_or_else(|| function_response.name.clone());
477                    let Some((name, fingerprint, at)) = self.started.remove(&key) else {
478                        continue;
479                    };
480                    let mut activity = adk_kernel::proc::Activity::new(
481                        adk_kernel::proc::LedgerKind::ToolCall,
482                        self.agent.clone(),
483                    )
484                    .with_duration((event.timestamp - at).to_std().unwrap_or_default())
485                    .with_subject(fingerprint);
486                    if let Some(effect) = self.effects.get(&name) {
487                        activity = activity.with_effect(effect.clone());
488                    }
489                    self.record(activity).await;
490                }
491                _ => {}
492            }
493        }
494    }
495}
496
497/// The notifier the harness's approval service reports outcomes to under a kernel: a no-op
498/// until [`Harness::kernel`] binds the kernel's `ApprovalWakeSource` (spec 3.2 §7.4).
499#[derive(Default)]
500pub(crate) struct LateApprovalNotifier {
501    source: OnceLock<Arc<ApprovalWakeSource>>,
502    bound: OnceLock<Arc<dyn ApprovalNotifier>>,
503}
504
505impl std::fmt::Debug for LateApprovalNotifier {
506    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
507        f.debug_struct("LateApprovalNotifier").field("bound", &self.bound.get().is_some()).finish()
508    }
509}
510
511impl LateApprovalNotifier {
512    /// The kernel's approval wake source, created and bound on first use; every kernel built
513    /// from the harness shares it.
514    fn bind(&self) -> Arc<ApprovalWakeSource> {
515        let source = self.source.get_or_init(|| Arc::new(ApprovalWakeSource::new())).clone();
516        let _ = self.bound.set(source.clone());
517        source
518    }
519
520    /// Binds `notifier`, for tests that stand in for the kernel.
521    #[cfg(test)]
522    fn bind_to(&self, notifier: Arc<dyn ApprovalNotifier>) {
523        let _ = self.bound.set(notifier);
524    }
525
526    /// Reports a request `Harness::decide` withdrew: resolved by the person's `decision` once
527    /// it is recorded, or cancelled when none was (spec 3.3 §7.3).
528    pub(crate) async fn decided_in_the_harness(
529        &self,
530        request: &ApprovalRequest,
531        decision: Option<&ToolApproval>,
532    ) {
533        let mut reported = request.clone();
534        if let Some(decision) = decision {
535            reported.state = match decision.decision {
536                ToolConfirmationDecision::Approve => ApprovalState::Approved,
537                ToolConfirmationDecision::Deny => ApprovalState::Rejected,
538            };
539        }
540        self.notify(&reported, None).await;
541    }
542
543    async fn notify(&self, request: &ApprovalRequest, decision: Option<ApprovalDecision>) {
544        let Some(notifier) = self.bound.get() else { return };
545        let kind = match request.state {
546            ApprovalState::Approved | ApprovalState::Rejected | ApprovalState::Responded => {
547                ApprovalEventKind::Resolved
548            }
549            ApprovalState::Expired => ApprovalEventKind::Expired,
550            ApprovalState::Cancelled => ApprovalEventKind::Cancelled,
551            ApprovalState::Pending => return,
552        };
553        let notification = ApprovalNotification {
554            id: format!("{}:{}", request.id, request.version),
555            kind,
556            request: request.clone(),
557            decision,
558            escalation_step: None,
559            at: Utc::now(),
560        };
561        if let Err(error) = notifier.notify(&notification).await {
562            tracing::warn!(approval.id = %request.id, error = %error, "could not tell the kernel about an approval outcome");
563        }
564    }
565}
566
567/// The harness's approval service under a kernel: forwards every call and reports each
568/// request that reached its outcome through it to the late-bound notifier.
569#[derive(Debug)]
570pub(crate) struct NotifyingApprovals {
571    inner: Arc<dyn ApprovalService>,
572    late: Arc<LateApprovalNotifier>,
573}
574
575impl NotifyingApprovals {
576    pub(crate) fn wrap(
577        inner: Arc<dyn ApprovalService>,
578        late: &Arc<LateApprovalNotifier>,
579    ) -> Arc<dyn ApprovalService> {
580        Arc::new(Self { inner, late: Arc::clone(late) })
581    }
582}
583
584#[async_trait]
585impl ApprovalService for NotifyingApprovals {
586    async fn submit(&self, request: ApprovalRequest) -> Result<ApprovalRequest> {
587        self.inner.submit(request).await
588    }
589
590    async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>> {
591        self.inner.submit_call(call).await
592    }
593
594    async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>> {
595        self.inner.get(id).await
596    }
597
598    async fn inbox(&self, query: InboxQuery) -> Result<InboxPage> {
599        self.inner.inbox(query).await
600    }
601
602    async fn decide(
603        &self,
604        id: &str,
605        expected_version: u64,
606        decision: ApprovalDecision,
607    ) -> Result<ApprovalRequest> {
608        let request = self.inner.decide(id, expected_version, decision.clone()).await?;
609        self.late.notify(&request, Some(decision)).await;
610        Ok(request)
611    }
612
613    async fn delegate(&self, delegation: ApprovalDelegation) -> Result<ApprovalDelegation> {
614        self.inner.delegate(delegation).await
615    }
616
617    async fn revoke_delegation(&self, id: &str) -> Result<bool> {
618        self.inner.revoke_delegation(id).await
619    }
620
621    async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>> {
622        self.inner.delegations_to(to).await
623    }
624
625    async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
626        let request = self.inner.cancel(id, reason).await?;
627        self.late.notify(&request, None).await;
628        Ok(request)
629    }
630
631    async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
632        // `Harness::decide` reports its withdrawal once the person's decision is recorded, so
633        // no sleeper wakes before the decision exists (spec 3.3 §7.3).
634        let reported_later = reason.as_deref() == Some(crate::harness::DECIDED_IN_THE_HARNESS);
635        let request = self.inner.withdraw(id, reason).await?;
636        if !reported_later {
637            self.late.notify(&request, None).await;
638        }
639        Ok(request)
640    }
641
642    async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick> {
643        let tick = self.inner.tick(now).await?;
644        for id in &tick.expired {
645            if let Ok(Some(request)) = self.inner.get(id).await {
646                self.late.notify(&request, None).await;
647            }
648        }
649        Ok(tick)
650    }
651
652    fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
653        self.inner.approval_store()
654    }
655
656    fn route_unrouted(&self, router: Arc<dyn adk_core::ApprovalRouter>) -> bool {
657        self.inner.route_unrouted(router)
658    }
659
660    fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
661        self.inner.add_notifier(notifier)
662    }
663
664    fn add_resolution(&self, hook: Arc<dyn adk_core::ApprovalResolution>) -> bool {
665        self.inner.add_resolution(hook)
666    }
667
668    async fn record_review(
669        &self,
670        call: ApprovalCall,
671        decision: ApprovalDecision,
672    ) -> Result<Option<ApprovalRequest>> {
673        // Decided and applied in the run: there is nothing for a sleeper to wake on.
674        self.inner.record_review(call, decision).await
675    }
676}
677
678/// The harness's standing rules as the kernel's daily review reads them (spec 3.2 §9.1):
679/// ids, owners, grant times and expiries, nothing else.
680struct HarnessRules(Arc<dyn StandingRuleStore>);
681
682#[async_trait]
683impl StandingRuleSource for HarnessRules {
684    async fn rules(&self, app: &str, user: &str) -> adk_kernel::Result<Vec<RuleAge>> {
685        let rules = self.0.list(app, user).await?;
686        Ok(rules
687            .into_iter()
688            .map(|rule| {
689                let age = RuleAge::new(rule.id, user, rule.created_at);
690                match rule.expires_at {
691                    Some(at) => age.with_expiry(at),
692                    None => age,
693                }
694            })
695            .collect())
696    }
697}
698
699/// The name of the tool an agent proposes follow-up work with (spec 3.2 §7.5).
700pub(crate) const PROPOSE_FOLLOWUP: &str = "propose_followup";
701
702/// The most characters of a follow-up's title.
703const TITLE_MAX_CHARS: usize = 200;
704/// The most characters of a follow-up's rationale.
705const RATIONALE_MAX_CHARS: usize = 2_000;
706
707/// The kernel's mode for a session in `mode`; the one-to-one inverse of
708/// `From<PartitionMode> for HarnessMode`.
709fn partition_mode(mode: HarnessMode) -> PartitionMode {
710    match mode {
711        HarnessMode::ReadOnly => PartitionMode::ReadOnly,
712        HarnessMode::Plan => PartitionMode::Plan,
713        HarnessMode::Ask => PartitionMode::Ask,
714        HarnessMode::Auto => PartitionMode::Auto,
715    }
716}
717
718fn invalid(message: impl Into<String>) -> AdkError {
719    AdkError::new(
720        ErrorComponent::Tool,
721        ErrorCategory::InvalidInput,
722        "harness.followup.invalid",
723        message,
724    )
725}
726
727/// `propose_followup { title, rationale, when?, steps? }` (spec 3.2 §7.5): proposes work
728/// for later as an agenda item in state `Proposed`, its only effect. Registered as class
729/// `Todo`, so it is allowed in every mode; running the item is governed by the kernel's
730/// agenda — held in ReadOnly and Plan, put to the inbox in Ask, scheduled in Auto — and by
731/// its quiet hours and daily budget.
732///
733/// The follow-up runs in a session of its own whose mode is recorded as this session's at
734/// the time of the proposal, so its process never runs above the proposing run's mode
735/// (K-I7). A partition's harness proposes into its partition (spec 3.2 §7.8). Without a
736/// kernel hosting the harness the tool answers that none runs.
737pub(crate) struct ProposeFollowupTool {
738    agenda: AgendaHandle,
739    modes: (Arc<dyn ModeStore>, HarnessMode),
740    partition: Option<adk_kernel::PartitionId>,
741}
742
743impl ProposeFollowupTool {
744    pub(crate) fn new(
745        agenda: AgendaHandle,
746        mode_store: Arc<dyn ModeStore>,
747        default_mode: HarnessMode,
748        partition: Option<adk_kernel::PartitionId>,
749    ) -> Self {
750        Self { agenda, modes: (mode_store, default_mode), partition }
751    }
752
753    async fn mode(&self, ctx: &dyn ToolContext) -> HarnessMode {
754        let (store, default_mode) = &self.modes;
755        match store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await {
756            Ok(Some(record)) => record.mode_for_invocation(ctx.invocation_id()),
757            Ok(None) => *default_mode,
758            Err(error) => {
759                tracing::warn!(error = %error, "mode store unavailable; the follow-up is proposed read-only");
760                HarnessMode::ReadOnly
761            }
762        }
763    }
764}
765
766#[async_trait]
767impl Tool for ProposeFollowupTool {
768    fn name(&self) -> &str {
769        PROPOSE_FOLLOWUP
770    }
771
772    fn description(&self) -> &str {
773        "Propose follow-up work to do later, outside this conversation: a title, why it is \
774         worth doing, optionally when to do it and the steps. The proposal goes on the \
775         agenda; it runs only once approved (by the user, or by an Auto-mode policy), outside \
776         quiet hours and within the daily budget. Proposing does nothing else."
777    }
778
779    fn parameters_schema(&self) -> Option<Value> {
780        Some(json!({
781            "type": "object",
782            "properties": {
783                "title": { "type": "string", "description": "What to do, in a short line." },
784                "rationale": { "type": "string", "description": "Why it is worth doing, and what triggers it." },
785                "when": {
786                    "type": "object",
787                    "description": "When to run it; omit to run once approved. One of: {\"at\": \"<RFC 3339 time>\"}, {\"cron\": {\"expr\": \"<cron>\", \"missed\": \"skip\"}}, {\"fileChange\": {\"root\": \"<dir>\", \"glob\": \"<pattern>\", \"debounceMs\": 500}}, {\"runFinished\": {\"pid\": \"<process id>\"}}."
788                },
789                "steps": {
790                    "type": "array",
791                    "description": "The plan, when there is one.",
792                    "items": {
793                        "type": "object",
794                        "properties": {
795                            "id": { "type": "string" },
796                            "title": { "type": "string" },
797                            "instruction": { "type": "string" },
798                            "depends_on": { "type": "array", "items": { "type": "string" } }
799                        },
800                        "required": ["id", "title", "instruction"]
801                    }
802                }
803            },
804            "required": ["title", "rationale"]
805        }))
806    }
807
808    fn effect(&self) -> ToolEffect {
809        // A resumed run never proposes the same follow-up twice.
810        ToolEffect::NonIdempotent
811    }
812
813    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
814        let config = ctx
815            .run_config()
816            .ok_or_else(|| AdkError::tool("propose_followup runs only inside a harness run"))?;
817        if !config.tool_policy.as_deref().is_some_and(has_harness_layer) {
818            return Err(AdkError::tool(
819                "propose_followup refuses to run without the harness policy in the run config",
820            ));
821        }
822        let text = |field: &str, max: usize| -> Result<String> {
823            let value = args
824                .get(field)
825                .and_then(Value::as_str)
826                .map(str::trim)
827                .filter(|value| !value.is_empty())
828                .ok_or_else(|| invalid(format!("propose_followup needs a non-empty '{field}'")))?;
829            if value.chars().count() > max {
830                return Err(invalid(format!("'{field}' is longer than {max} characters")));
831            }
832            Ok(value.to_string())
833        };
834        let title = text("title", TITLE_MAX_CHARS)?;
835        let rationale = text("rationale", RATIONALE_MAX_CHARS)?;
836        let when: Option<Wake> = match args.get("when") {
837            None | Some(Value::Null) => None,
838            Some(value) => Some(serde_json::from_value(value.clone()).map_err(|error| {
839                invalid(format!("'when' is not a wake this kernel knows: {error}"))
840            })?),
841        };
842        let steps: Option<Vec<PlanStep>> = match args.get("steps") {
843            None | Some(Value::Null) => None,
844            Some(value) => Some(
845                serde_json::from_value(value.clone())
846                    .map_err(|error| invalid(format!("'steps' are not plan steps: {error}")))?,
847            ),
848        };
849        let Some(agenda) = self.agenda.get() else {
850            return Ok(json!({
851                "error": "no agent kernel hosts this harness, so nothing can be proposed for later; \
852                          the user can start one with `adk-rust up`"
853            }));
854        };
855        let mode = self.mode(ctx.as_ref()).await;
856        let pid = config
857            .durable_run_id
858            .clone()
859            .unwrap_or_else(|| format!("invocation:{}", ctx.invocation_id()));
860        let mut item = AgendaItem::new(
861            uuid::Uuid::new_v4().to_string(),
862            SubjectRef::human(ctx.user_id()),
863            title,
864            rationale,
865            AgendaOrigin::Agent { pid, confidence: 1.0 },
866            Utc::now(),
867        );
868        if let Some(partition) = &self.partition {
869            item = item.with_partition(partition.clone());
870        }
871        if let Some(when) = when {
872            item = item.with_when(when);
873        }
874        if let Some(steps) = steps.filter(|steps| !steps.is_empty()) {
875            let steps: Vec<Value> =
876                steps.iter().filter_map(|step| serde_json::to_value(step).ok()).collect();
877            let digest =
878                crate::fsutil::hex_digest(Value::from(steps.clone()).to_string().as_bytes());
879            item = item.with_plan(PlanRef::new(format!("sha256:{digest}"), steps));
880        }
881        // The follow-up's session starts in this session's mode, before any process can
882        // read it, so the follow-up never runs above the proposing run's mode (K-I7).
883        let (store, _) = &self.modes;
884        store
885            .set(
886                ctx.app_name(),
887                ctx.user_id(),
888                &adk_kernel::agenda::item_session(&item.id),
889                ModeRecord::new(mode, ModeSource::SystemTighten),
890            )
891            .await?;
892        let outcome = agenda.propose(item, partition_mode(mode)).await.map_err(AdkError::from)?;
893        Ok(match outcome {
894            ProposalOutcome::Held { item } => json!({
895                "proposed": item.id,
896                "state": "proposed",
897                "note": format!("held on the agenda for the user: this session is in {mode} mode"),
898            }),
899            ProposalOutcome::AwaitingApproval { item, request_id } => json!({
900                "proposed": item.id,
901                "state": "proposed",
902                "awaitingApproval": request_id,
903            }),
904            ProposalOutcome::Scheduled { item, pid } => json!({
905                "proposed": item.id,
906                "state": "scheduled",
907                "pid": pid,
908            }),
909            ProposalOutcome::Rejected { reason } => json!({
910                "error": format!("the follow-up was not proposed: {reason}"),
911            }),
912            other => json!({ "outcome": other }),
913        })
914    }
915}
916
917#[cfg(test)]
918mod tests {
919    use std::sync::Mutex;
920
921    use adk_core::{
922        ApprovalPolicy, ApprovalScope, ApproverSelector, InMemoryApprovalStore,
923        StoreApprovalService, ToolConfirmationRequest,
924    };
925
926    use super::*;
927
928    #[test]
929    fn partition_modes_map_to_the_harness_mode_of_the_same_name() {
930        let pairs = [
931            (PartitionMode::ReadOnly, HarnessMode::ReadOnly),
932            (PartitionMode::Plan, HarnessMode::Plan),
933            (PartitionMode::Ask, HarnessMode::Ask),
934            (PartitionMode::Auto, HarnessMode::Auto),
935        ];
936        for (partition, harness) in pairs {
937            assert_eq!(HarnessMode::from(partition), harness);
938            assert_eq!(partition.as_str(), harness.to_string());
939        }
940    }
941
942    #[derive(Debug, Default)]
943    struct Seen(Mutex<Vec<ApprovalEventKind>>);
944
945    #[async_trait]
946    impl ApprovalNotifier for Seen {
947        async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
948            self.0.lock().unwrap().push(notification.kind);
949            Ok(())
950        }
951    }
952
953    #[derive(Debug, Default)]
954    struct States(Mutex<Vec<(ApprovalEventKind, ApprovalState)>>);
955
956    #[async_trait]
957    impl ApprovalNotifier for States {
958        async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
959            self.0.lock().unwrap().push((notification.kind, notification.request.state));
960            Ok(())
961        }
962    }
963
964    /// Wave 2 review finding 21 (spec 3.3 §7.3): the request `Harness::decide` withdraws wakes
965    /// no kernel sleeper until the person's decision is recorded, and is then reported with
966    /// that decision; a withdrawal for a call decided another way is reported at once.
967    #[tokio::test]
968    async fn a_request_withdrawn_by_the_harness_is_reported_with_the_persons_decision() {
969        let late = Arc::new(LateApprovalNotifier::default());
970        let states = Arc::new(States::default());
971        late.bind_to(states.clone());
972        let store = Arc::new(InMemoryApprovalStore::new());
973        let service =
974            NotifyingApprovals::wrap(Arc::new(StoreApprovalService::new(store.clone())), &late);
975        let scope = ApprovalScope::new("app", "alice", "s1");
976        let call = ToolConfirmationRequest::new("transfer", serde_json::json!({ "amount": 10 }));
977        store.record_pending(&scope, &call).await.unwrap();
978        let policy = ApprovalPolicy::new([ApproverSelector::human("bob")]);
979        let first = service
980            .submit(ApprovalRequest::new("req-1", scope.clone(), &call, policy.clone()))
981            .await
982            .unwrap();
983
984        let reason = Some(crate::harness::DECIDED_IN_THE_HARNESS.to_string());
985        let withdrawn = service.withdraw(&first.id, reason).await.unwrap();
986        assert!(states.0.lock().unwrap().is_empty(), "the withdrawal alone wakes nothing");
987        late.decided_in_the_harness(&withdrawn, Some(&ToolApproval::approve())).await;
988        assert_eq!(
989            *states.0.lock().unwrap(),
990            [(ApprovalEventKind::Resolved, ApprovalState::Approved)]
991        );
992
993        let second =
994            service.submit(ApprovalRequest::new("req-2", scope, &call, policy)).await.unwrap();
995        let note = Some("the call was decided another way (handler)".to_string());
996        service.withdraw(&second.id, note).await.unwrap();
997        assert_eq!(
998            states.0.lock().unwrap().last(),
999            Some(&(ApprovalEventKind::Cancelled, ApprovalState::Cancelled))
1000        );
1001    }
1002
1003    #[tokio::test]
1004    async fn an_outcome_through_the_harness_service_reaches_the_bound_notifier() {
1005        let late = Arc::new(LateApprovalNotifier::default());
1006        let store = Arc::new(InMemoryApprovalStore::new());
1007        let service =
1008            NotifyingApprovals::wrap(Arc::new(StoreApprovalService::new(store.clone())), &late);
1009        let scope = ApprovalScope::new("app", "alice", "s1");
1010        let call = ToolConfirmationRequest {
1011            tool_name: "transfer".into(),
1012            function_call_id: Some("call-1".into()),
1013            args: serde_json::json!({ "amount": 10 }),
1014            acting: None,
1015            origin: None,
1016            evidence: Vec::new(),
1017        };
1018        store.record_pending(&scope, &call).await.unwrap();
1019        let policy = ApprovalPolicy::new([ApproverSelector::human("bob")]);
1020        let first = service
1021            .submit(ApprovalRequest::new("req-1", scope.clone(), &call, policy.clone()))
1022            .await
1023            .unwrap();
1024        // Unbound: an outcome reaches no one, and nothing fails.
1025        service.cancel(&first.id, None).await.unwrap();
1026
1027        let seen = Arc::new(Seen::default());
1028        late.bind_to(seen.clone());
1029        let second =
1030            service.submit(ApprovalRequest::new("req-2", scope, &call, policy)).await.unwrap();
1031        service
1032            .decide(&second.id, second.version, ApprovalDecision::approve(SubjectRef::human("bob")))
1033            .await
1034            .unwrap();
1035        assert_eq!(*seen.0.lock().unwrap(), [ApprovalEventKind::Resolved]);
1036    }
1037}