1use std::collections::{BTreeMap, HashMap};
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use adk_core::audit_log::{AuditRecordDraft, AuditRecorder, AuditTrail};
10use adk_core::{
11 ApprovalAction, ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ErrorCategory,
12 Event, RunCheckpointRef, RunState,
13};
14use adk_harness::HarnessMode;
15use adk_kernel::KernelEvent;
16use adk_kernel::control::api::{
17 ApprovalItem, AttachRequest, LedgerParams, SpawnRequest, SteerResponse,
18};
19use adk_kernel::control::{ControlClient, SurfaceRecord};
20use adk_kernel::proc::LedgerEntry;
21use async_trait::async_trait;
22use chrono::{DateTime, Utc};
23use futures::StreamExt;
24use serde_json::json;
25use tokio::sync::watch;
26
27use crate::error::{Result, SurfaceError};
28use crate::inbox::Inbox;
29use crate::origin::Caller;
30use crate::source::{
31 AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday, Steered, Steering, TurnFailure,
32};
33
34const QUIET_REREAD: Duration = Duration::from_secs(15);
37
38const QUIET_IDLE: Duration = Duration::from_secs(300);
42
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
45struct Bus {
46 events: u64,
48 live: bool,
50 running: usize,
52}
53
54#[derive(Clone)]
105pub struct ControlSource {
106 client: ControlClient,
107 app: String,
108 target: String,
109 daily_limit: Option<u64>,
110 changes: Arc<std::sync::OnceLock<watch::Receiver<Bus>>>,
111 inbox: Option<Inbox>,
112 offers: Arc<std::sync::Mutex<Offers>>,
114}
115
116type Offers = BTreeMap<String, (u64, Option<String>)>;
118
119impl fmt::Debug for ControlSource {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.debug_struct("ControlSource")
122 .field("endpoint", &self.client.endpoint())
123 .field("app", &self.app)
124 .field("target", &self.target)
125 .finish_non_exhaustive()
126 }
127}
128
129impl ControlSource {
130 pub fn new(
133 client: ControlClient,
134 app_name: impl Into<String>,
135 target: impl Into<String>,
136 ) -> Self {
137 let inbox =
138 Inbox::for_endpoint(&client.endpoint(), client.bearer_token().map(str::to_owned));
139 Self {
140 client,
141 app: app_name.into(),
142 target: target.into(),
143 daily_limit: None,
144 changes: Arc::new(std::sync::OnceLock::new()),
145 inbox,
146 offers: Arc::default(),
147 }
148 }
149
150 #[must_use]
153 pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
154 self.inbox = self.inbox.map(|inbox| inbox.with_token(token.into()));
155 self
156 }
157
158 #[must_use]
161 pub fn with_daily_limit(mut self, micro_usd: u64) -> Self {
162 self.daily_limit = Some(micro_usd);
163 self
164 }
165
166 pub fn audit_trail(&self) -> AuditTrail {
189 AuditTrail::new(Arc::new(KernelRecorder { client: self.client.clone() }))
190 }
191
192 fn changes(&self) -> watch::Receiver<Bus> {
194 self.changes
195 .get_or_init(|| {
196 let (sender, receiver) = watch::channel(Bus::default());
197 let client = self.client.clone();
198 let app = self.app.clone();
199 tokio::spawn(async move {
200 let mut cursor = None;
201 loop {
202 match client.events(cursor).await {
203 Ok(mut events) => {
204 let mut running: Option<HashMap<String, RunState>> = client
206 .processes(&Default::default())
207 .await
208 .ok()
209 .map(|processes| {
210 processes
211 .into_iter()
212 .filter(|process| {
213 process.run.app_name == app && runs(process.run.state)
214 })
215 .map(|process| (process.meta.pid, process.run.state))
216 .collect()
217 });
218 let count = |running: &Option<HashMap<String, RunState>>| {
219 running.as_ref().map_or(1, HashMap::len)
221 };
222 sender.send_modify(|bus| {
223 bus.events += 1;
224 bus.live = true;
225 bus.running = count(&running);
226 });
227 while let Some(Ok(record)) = events.next().await {
228 cursor = Some(record.cursor);
229 if let (KernelEvent::Process { pid, to, .. }, Some(running)) =
230 (&record.event, running.as_mut())
231 {
232 if runs(*to) {
233 running.insert(pid.clone(), *to);
234 } else {
235 running.remove(pid);
236 }
237 }
238 sender.send_modify(|bus| {
239 bus.events += 1;
240 bus.running = count(&running);
241 });
242 if sender.is_closed() {
243 return;
244 }
245 }
246 }
247 Err(error) => {
248 tracing::debug!(error = %error, "the kernel's event stream is unavailable");
249 }
250 }
251 sender.send_modify(|bus| {
252 bus.events += 1;
253 bus.live = false;
254 });
255 if sender.is_closed() {
256 return;
257 }
258 tokio::time::sleep(Duration::from_secs(2)).await;
259 }
260 });
261 receiver
262 })
263 .clone()
264 }
265
266 async fn processes(&self, user: &str) -> Result<Vec<adk_kernel::Process>> {
267 let mut processes: Vec<_> = self
268 .client
269 .processes(&Default::default())
270 .await?
271 .into_iter()
272 .filter(|process| process.run.user_id == user && process.run.app_name == self.app)
273 .collect();
274 processes.sort_by_key(|process| std::cmp::Reverse(process.run.updated_at));
275 Ok(processes)
276 }
277}
278
279fn runs(state: RunState) -> bool {
281 matches!(state, RunState::Running | RunState::Queued)
282}
283
284fn passing(category: ErrorCategory) -> bool {
287 matches!(
288 category,
289 ErrorCategory::Unavailable
290 | ErrorCategory::Timeout
291 | ErrorCategory::Internal
292 | ErrorCategory::RateLimited
293 | ErrorCategory::ResourceExhausted
294 | ErrorCategory::Cancelled
295 )
296}
297
298const OFFERS: usize = 256;
300
301struct KernelRecorder {
303 client: ControlClient,
304}
305
306#[async_trait]
307impl AuditRecorder for KernelRecorder {
308 fn digest(&self, value: &serde_json::Value) -> String {
309 adk_core::json_digest(value)
310 }
311
312 async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
313 let AuditRecordDraft { kind, action, decision, ext, .. } = draft;
315 let mut record = SurfaceRecord::new(kind, action);
316 if let Some(decision) = decision {
317 record = record.with_decision(decision);
318 }
319 for (key, value) in ext {
320 record = record.with_ext(key, value);
321 }
322 Ok(self.client.record_surface(&record).await?)
323 }
324}
325
326struct KernelRule {
328 client: ControlClient,
329 decision: String,
330}
331
332#[async_trait]
333impl RuleCommit for KernelRule {
334 async fn commit(self: Box<Self>) -> Result<()> {
335 Ok(self.client.grant_always_allow(&self.decision).await?)
336 }
337}
338
339fn request_of(item: ApprovalItem) -> Result<ApprovalRequest> {
341 let policy = serde_json::to_value(ApprovalPolicy::new([]))
342 .map_err(|error| SurfaceError::Invalid(error.to_string()))?;
343 let value = json!({
344 "id": item.id,
345 "scope": item.scope,
346 "fingerprint": "",
347 "toolName": item.tool_name,
348 "argsRedacted": item.args_redacted,
349 "summary": item.summary,
350 "risk": ApprovalRisk::High,
351 "createdAt": item.created_at,
352 "expiresAt": item.expires_at,
353 "allowedActions": item
354 .allowed_actions
355 .into_iter()
356 .filter(|action| *action != ApprovalAction::Edit)
357 .collect::<Vec<_>>(),
358 "policy": policy,
359 "runId": item.run_id,
360 "version": item.version,
361 "state": item.state,
362 });
363 serde_json::from_value(value).map_err(|error| SurfaceError::Invalid(error.to_string()))
364}
365
366#[async_trait]
367impl Source for ControlSource {
368 fn app_name(&self) -> &str {
369 &self.app
370 }
371
372 async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
373 let request = AttachRequest { user_id: Some(user.to_string()), after: None };
374 match self.client.attach(session, &request).await {
375 Ok(attached) => Ok(Some(attached.transcript)),
376 Err(error) => {
377 let error = adk_core::AdkError::from(error);
378 match error.category {
379 ErrorCategory::NotFound => Ok(None),
380 _ => Err(SurfaceError::Source(error)),
381 }
382 }
383 }
384 }
385
386 async fn changed(&self, max: Duration) {
387 let mut changes = self.changes();
388 changes.mark_unchanged();
391 let bus = *changes.borrow();
392 let wait =
393 if bus.live && bus.running == 0 { QUIET_IDLE.max(max) } else { max.max(QUIET_REREAD) };
394 let change = async {
395 if changes.changed().await.is_err() {
396 std::future::pending::<()>().await;
397 }
398 };
399 tokio::select! {
400 () = tokio::time::sleep(wait) => {}
401 () = change => {}
402 }
403 }
404
405 async fn requests(
406 &self,
407 _caller: &Caller,
408 session: Option<&str>,
409 open_only: bool,
410 ) -> Result<Vec<ApprovalRequest>> {
411 if let Some(inbox) = &self.inbox {
412 return inbox.list(&self.app, session, open_only).await;
413 }
414 self.client
415 .approvals()
416 .await?
417 .into_iter()
418 .filter(|item| session.is_none_or(|session| item.scope.session_id == session))
419 .map(request_of)
420 .collect()
421 }
422
423 async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
424 if let Some(inbox) = &self.inbox {
425 return inbox.get(id).await;
426 }
427 Ok(self
428 .client
429 .approvals()
430 .await?
431 .into_iter()
432 .find(|item| item.id == id)
433 .map(request_of)
434 .transpose()?)
435 }
436
437 async fn decide(
438 &self,
439 id: &str,
440 expected_version: u64,
441 decision: ApprovalDecision,
442 ) -> Result<ApprovalRequest> {
443 if let Some(inbox) = &self.inbox {
444 return inbox.decide(id, expected_version, &decision).await;
445 }
446 if decision.kind == ApprovalAction::Edit {
447 return Err(SurfaceError::unsupported("editing a call over the control plane"));
448 }
449 let item = self
450 .client
451 .decide(id, expected_version, decision.kind, decision.reason.as_deref())
452 .await?;
453 let mut request = request_of(item)?;
454 request.decisions.push(decision);
457 Ok(request)
458 }
459
460 async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
461 let known = |offers: &Offers| {
462 offers
463 .get(&request.id)
464 .filter(|(version, _)| *version == request.version)
465 .map(|(_, label)| label.clone())
466 };
467 if let Some(label) = known(&self.offers.lock().unwrap_or_else(|e| e.into_inner())) {
468 return label.map(|label| AlwaysAllowOffer { label });
469 }
470 let label = match self.client.always_allow_offer(&request.id).await {
473 Ok(label) => label,
474 Err(error) if passing(error.category()) => {
475 tracing::debug!(error = %error, decision.id = %request.id, "Always allow could not be looked up");
476 return None;
477 }
478 Err(_) => None,
479 };
480 let mut offers = self.offers.lock().unwrap_or_else(|e| e.into_inner());
481 if offers.len() >= OFFERS {
482 offers.clear();
483 }
484 offers.insert(request.id.clone(), (request.version, label.clone()));
485 label.map(|label| AlwaysAllowOffer { label })
486 }
487
488 async fn prepare_always_allow(
489 &self,
490 _caller: &Caller,
491 request: &ApprovalRequest,
492 ) -> Result<Box<dyn RuleCommit>> {
493 self.client.prepare_always_allow(&request.id).await?;
494 Ok(Box::new(KernelRule { client: self.client.clone(), decision: request.id.clone() }))
495 }
496
497 async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
498 let mut latest: BTreeMap<String, AgentState> = BTreeMap::new();
499 for process in self.processes(user).await? {
500 let run = &process.run;
501 if latest.contains_key(&run.target) {
502 continue;
503 }
504 let waiting_on_decision =
505 matches!(run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }));
506 latest.insert(
507 run.target.clone(),
508 AgentState {
509 shell: None,
511 name: run.target.clone(),
512 session_id: run.session_id.clone(),
513 state: run.state,
514 waiting_on_decision,
515 wake_at: (run.state == RunState::Waiting && !waiting_on_decision)
516 .then_some(run.not_before)
517 .flatten(),
518 suspended: process.meta.suspended_by.is_some(),
519 subagent: (process.meta.kind == adk_kernel::ProcessKind::Subagent).then(|| {
520 process
521 .meta
522 .labels
523 .get(adk_kernel::SUBAGENT_NAME_LABEL)
524 .cloned()
525 .unwrap_or_else(|| "sub-agent".to_string())
526 }),
527 },
528 );
529 }
530 let gone: Vec<String> = self
534 .client
535 .agents()
536 .await
537 .unwrap_or_default()
538 .into_iter()
539 .filter(|view| {
540 matches!(
541 view.agent.state,
542 adk_kernel::agents::AgentRecordState::Removing
543 | adk_kernel::agents::AgentRecordState::Removed
544 )
545 })
546 .map(|view| view.agent.id)
547 .collect();
548 latest.retain(|name, _| !gone.contains(name));
549 Ok(latest.into_values().collect())
550 }
551
552 async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
553 let mut threads: BTreeMap<String, DateTime<Utc>> = BTreeMap::new();
554 for process in self.processes(user).await? {
555 if process.run.target != agent {
556 continue;
557 }
558 if let Some(session) = process.run.session_id.clone() {
559 let at = threads.entry(session).or_insert(process.run.updated_at);
560 *at = (*at).max(process.run.updated_at);
561 }
562 }
563 Ok(threads.into_iter().collect())
564 }
565
566 async fn agent_definitions(&self, user: &str) -> Result<Vec<crate::agents::AgentDetail>> {
569 let views = match self.client.agents().await {
570 Ok(views) => views,
571 Err(error)
573 if matches!(
574 error.category(),
575 adk_core::ErrorCategory::NotFound | adk_core::ErrorCategory::Unsupported
576 ) =>
577 {
578 return Ok(Vec::new());
579 }
580 Err(error) => return Err(error.into()),
581 };
582 let offset = *chrono::Local::now().offset();
583 Ok(views
584 .into_iter()
585 .map(|view| {
586 crate::agents::AgentDetail::of(
587 &view.agent,
588 view.cant_start,
589 user,
590 "ADK-Rust",
591 offset,
592 )
593 })
594 .collect())
595 }
596
597 async fn agent(&self, user: &str, id: &str) -> Result<Option<crate::agents::AgentDetail>> {
598 Ok(self.agent_definitions(user).await?.into_iter().find(|detail| {
600 detail.id == id
601 && !matches!(
602 detail.state,
603 crate::agents::AgentLife::Removed | crate::agents::AgentLife::Refused
604 )
605 }))
606 }
607
608 async fn busy(&self, user: &str, session: &str) -> Result<bool> {
609 Ok(self.processes(user).await?.iter().any(|process| {
610 process.run.session_id.as_deref() == Some(session) && runs(process.run.state)
611 }))
612 }
613
614 async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
615 let mut failures: Vec<TurnFailure> = self
616 .processes(user)
617 .await?
618 .into_iter()
619 .filter(|process| {
620 process.run.session_id.as_deref() == Some(session)
621 && process.run.state == RunState::Failed
622 })
623 .map(|process| TurnFailure {
624 agent: process.run.target,
625 at: process.run.updated_at,
626 error: process.run.error,
627 })
628 .collect();
629 failures.sort_by_key(|failure| failure.at);
630 Ok(failures)
631 }
632
633 async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
634 Ok(self.processes(user).await?.iter().any(|process| {
635 process.run.session_id.as_deref() == Some(session)
636 && process.run.state == RunState::Waiting
637 && matches!(process.run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }))
638 }))
639 }
640
641 async fn start_turn(&self, _caller: &Caller, session: &str, text: &str) -> Result<()> {
642 let request = SpawnRequest::new(self.target.clone(), json!({ "text": text }))
643 .with_session_id(session);
644 self.client.spawn(&request).await?;
645 Ok(())
646 }
647
648 async fn start_turn_images(
650 &self,
651 caller: &Caller,
652 session: &str,
653 text: &str,
654 images: &[crate::images::MessageImage],
655 ) -> Result<()> {
656 if images.is_empty() {
657 return self.start_turn(caller, session, text).await;
658 }
659 let mut content = adk_core::Content::new("user");
660 if !text.trim().is_empty() {
661 content = content.with_text(text);
662 }
663 for image in images {
664 content = content.with_inline_data(image.mime_type.clone(), image.data.clone());
665 }
666 let request = SpawnRequest::new(self.target.clone(), json!({ "content": content }))
667 .with_session_id(session);
668 self.client.spawn(&request).await?;
669 Ok(())
670 }
671
672 async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
673 let (steer_id, pid, lease_epoch) = match self.client.steer(session, text).await? {
674 SteerResponse::Accepted { steer_id, pid, lease_epoch } => (steer_id, pid, lease_epoch),
675 SteerResponse::Returned => return Ok(None),
676 };
677 let source = self.clone();
678 let (user, session) = (caller.user_id().to_string(), session.to_string());
679 Ok(Some(Box::pin(async move {
680 loop {
681 let mut changed = Box::pin(source.changed(QUIET_REREAD));
684 let _ = futures::poll!(changed.as_mut());
685 let held = source.client.processes(&Default::default()).await.map(|processes| {
688 processes.iter().any(|process| {
689 process.meta.pid == pid
690 && process.run.state == RunState::Running
691 && process.run.lease_epoch == lease_epoch
692 })
693 });
694 match (held, source.transcript(&user, &session).await) {
695 (Ok(held), Ok(events)) => {
696 let steered = crate::local::taken(&events.unwrap_or_default(), &steer_id);
697 if steered != Steered::Returned || !held {
698 return Ok(steered);
699 }
700 }
701 (Err(error), _) => {
703 tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's process could not be read");
704 }
705 (_, Err(error)) => {
706 tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's session could not be read");
707 }
708 }
709 changed.await;
710 }
711 })))
712 }
713
714 async fn request_call(
715 &self,
716 caller: &Caller,
717 session: &str,
718 text: &str,
719 call: adk_core::RequestedCall,
720 ) -> Result<()> {
721 let target = self
724 .agent_of_session(caller.user_id(), session)
725 .await?
726 .unwrap_or_else(|| self.target.clone());
727 let request = SpawnRequest::new(target, json!({ "text": text, "requestedCall": call }))
728 .with_session_id(session);
729 self.client.spawn(&request).await?;
730 Ok(())
731 }
732
733 async fn stop_all(&self, _caller: &Caller, reason: &str) -> Result<()> {
734 self.client.freeze(Some(reason)).await?;
735 Ok(())
736 }
737
738 async fn resume_all(&self, _caller: &Caller) -> Result<()> {
739 self.client.unfreeze().await?;
740 Ok(())
741 }
742
743 async fn stopped(&self) -> Result<bool> {
744 Ok(self.client.health().await?.frozen)
745 }
746
747 async fn mode(&self, _user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
748 let Some(session) = session else {
749 return Ok(None);
750 };
751 match self.client.session_mode(session).await {
752 Ok(mode) => Ok(mode.and_then(|mode| mode.parse().ok())),
753 Err(error)
755 if matches!(
756 error.category(),
757 ErrorCategory::Forbidden
758 | ErrorCategory::Unauthorized
759 | ErrorCategory::InvalidInput
760 ) =>
761 {
762 Ok(None)
763 }
764 Err(error) => Err(error.into()),
765 }
766 }
767
768 fn opens_sessions(&self) -> bool {
770 true
771 }
772
773 async fn set_mode(&self, _caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
775 let word = match mode {
776 HarnessMode::ReadOnly => "read-only",
777 other => other.as_str(),
778 };
779 self.client.run_command("mode", word, session).await?;
780 Ok(())
781 }
782
783 async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
784 Ok(self
785 .processes(user)
786 .await?
787 .into_iter()
788 .find(|process| process.run.session_id.as_deref() == Some(session))
789 .map(|process| process.run.target))
790 }
791
792 async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
795 let areas = match self.client.settings().await {
796 Ok(areas) => areas,
797 Err(error) => {
798 tracing::debug!(error = %error, "could not read the areas' settings; spend is not split by area");
799 Vec::new()
800 }
801 };
802 let area = areas
804 .iter()
805 .find(|area| area.primary)
806 .or_else(|| {
807 areas
808 .iter()
809 .find(|area| area.partition.as_str() == adk_kernel::PartitionId::DEFAULT)
810 })
811 .or(match areas.as_slice() {
812 [only] => Some(only),
813 _ => None,
814 });
815 let spent = self
816 .processes(user)
817 .await?
818 .iter()
819 .filter(|process| area.is_none_or(|area| process.meta.partition == area.partition))
820 .map(|process| process.view.spend_today)
821 .sum();
822 let limit = self.daily_limit.or(area.and_then(|area| area.daily_spending_limit));
823 Ok(Some(SpendToday { spent, limit }))
824 }
825
826 async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
827 let mut params = LedgerParams { from: Some(since), ..LedgerParams::default() };
828 let mut entries = Vec::new();
829 loop {
830 let page = self.client.ledger(¶ms).await?;
831 entries.extend(page.entries);
832 match page.next {
833 Some(next) => params.after = Some(next),
834 None => break,
835 }
836 }
837 Ok(entries)
838 }
839}