1use 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 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
63pub fn driver_tool_kind(class: adk_kernel::drivers::EffectClass) -> ToolKind {
90 ToolKind::External { effect: class.tool_effect(), trusted_origin: true }
91}
92
93#[derive(Debug, Clone)]
109pub struct DriverClasses {
110 drivers: adk_kernel::drivers::DriverSupervisor,
111}
112
113impl DriverClasses {
114 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 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#[derive(Debug, Clone)]
163pub struct HarnessRulePins {
164 app_name: String,
165 rules: Arc<dyn StandingRuleStore>,
166}
167
168impl HarnessRulePins {
169 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 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 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 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
281fn 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 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
315pub(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 ledger: LateLedgerSink,
324 partition: Option<PartitionId>,
326}
327
328struct 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
389pub(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#[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 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 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 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#[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 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 #[cfg(test)]
522 fn bind_to(&self, notifier: Arc<dyn ApprovalNotifier>) {
523 let _ = self.bound.set(notifier);
524 }
525
526 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(¬ification).await {
562 tracing::warn!(approval.id = %request.id, error = %error, "could not tell the kernel about an approval outcome");
563 }
564 }
565}
566
567#[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 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 self.inner.record_review(call, decision).await
675 }
676}
677
678struct 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
699pub(crate) const PROPOSE_FOLLOWUP: &str = "propose_followup";
701
702const TITLE_MAX_CHARS: usize = 200;
704const RATIONALE_MAX_CHARS: usize = 2_000;
706
707fn 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
727pub(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 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 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 #[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 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}