use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use adk_core::audit_log::{AuditRecordDraft, AuditRecorder, AuditTrail};
use adk_core::{
ApprovalAction, ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ErrorCategory,
Event, RunCheckpointRef, RunState,
};
use adk_harness::HarnessMode;
use adk_kernel::KernelEvent;
use adk_kernel::control::api::{
ApprovalItem, AttachRequest, LedgerParams, SpawnRequest, SteerResponse,
};
use adk_kernel::control::{ControlClient, SurfaceRecord};
use adk_kernel::proc::LedgerEntry;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::StreamExt;
use serde_json::json;
use tokio::sync::watch;
use crate::error::{Result, SurfaceError};
use crate::inbox::Inbox;
use crate::origin::Caller;
use crate::source::{
AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday, Steered, Steering, TurnFailure,
};
const QUIET_REREAD: Duration = Duration::from_secs(15);
const QUIET_IDLE: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Bus {
events: u64,
live: bool,
running: usize,
}
#[derive(Clone)]
pub struct ControlSource {
client: ControlClient,
app: String,
target: String,
daily_limit: Option<u64>,
changes: Arc<std::sync::OnceLock<watch::Receiver<Bus>>>,
inbox: Option<Inbox>,
offers: Arc<std::sync::Mutex<Offers>>,
}
type Offers = BTreeMap<String, (u64, Option<String>)>;
impl fmt::Debug for ControlSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ControlSource")
.field("endpoint", &self.client.endpoint())
.field("app", &self.app)
.field("target", &self.target)
.finish_non_exhaustive()
}
}
impl ControlSource {
pub fn new(
client: ControlClient,
app_name: impl Into<String>,
target: impl Into<String>,
) -> Self {
let inbox =
Inbox::for_endpoint(&client.endpoint(), client.bearer_token().map(str::to_owned));
Self {
client,
app: app_name.into(),
target: target.into(),
daily_limit: None,
changes: Arc::new(std::sync::OnceLock::new()),
inbox,
offers: Arc::default(),
}
}
#[must_use]
pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
self.inbox = self.inbox.map(|inbox| inbox.with_token(token.into()));
self
}
#[must_use]
pub fn with_daily_limit(mut self, micro_usd: u64) -> Self {
self.daily_limit = Some(micro_usd);
self
}
pub fn audit_trail(&self) -> AuditTrail {
AuditTrail::new(Arc::new(KernelRecorder { client: self.client.clone() }))
}
fn changes(&self) -> watch::Receiver<Bus> {
self.changes
.get_or_init(|| {
let (sender, receiver) = watch::channel(Bus::default());
let client = self.client.clone();
let app = self.app.clone();
tokio::spawn(async move {
let mut cursor = None;
loop {
match client.events(cursor).await {
Ok(mut events) => {
let mut running: Option<HashMap<String, RunState>> = client
.processes(&Default::default())
.await
.ok()
.map(|processes| {
processes
.into_iter()
.filter(|process| {
process.run.app_name == app && runs(process.run.state)
})
.map(|process| (process.meta.pid, process.run.state))
.collect()
});
let count = |running: &Option<HashMap<String, RunState>>| {
running.as_ref().map_or(1, HashMap::len)
};
sender.send_modify(|bus| {
bus.events += 1;
bus.live = true;
bus.running = count(&running);
});
while let Some(Ok(record)) = events.next().await {
cursor = Some(record.cursor);
if let (KernelEvent::Process { pid, to, .. }, Some(running)) =
(&record.event, running.as_mut())
{
if runs(*to) {
running.insert(pid.clone(), *to);
} else {
running.remove(pid);
}
}
sender.send_modify(|bus| {
bus.events += 1;
bus.running = count(&running);
});
if sender.is_closed() {
return;
}
}
}
Err(error) => {
tracing::debug!(error = %error, "the kernel's event stream is unavailable");
}
}
sender.send_modify(|bus| {
bus.events += 1;
bus.live = false;
});
if sender.is_closed() {
return;
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
});
receiver
})
.clone()
}
async fn processes(&self, user: &str) -> Result<Vec<adk_kernel::Process>> {
let mut processes: Vec<_> = self
.client
.processes(&Default::default())
.await?
.into_iter()
.filter(|process| process.run.user_id == user && process.run.app_name == self.app)
.collect();
processes.sort_by_key(|process| std::cmp::Reverse(process.run.updated_at));
Ok(processes)
}
}
fn runs(state: RunState) -> bool {
matches!(state, RunState::Running | RunState::Queued)
}
fn passing(category: ErrorCategory) -> bool {
matches!(
category,
ErrorCategory::Unavailable
| ErrorCategory::Timeout
| ErrorCategory::Internal
| ErrorCategory::RateLimited
| ErrorCategory::ResourceExhausted
| ErrorCategory::Cancelled
)
}
const OFFERS: usize = 256;
struct KernelRecorder {
client: ControlClient,
}
#[async_trait]
impl AuditRecorder for KernelRecorder {
fn digest(&self, value: &serde_json::Value) -> String {
adk_core::json_digest(value)
}
async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
let AuditRecordDraft { kind, action, decision, ext, .. } = draft;
let mut record = SurfaceRecord::new(kind, action);
if let Some(decision) = decision {
record = record.with_decision(decision);
}
for (key, value) in ext {
record = record.with_ext(key, value);
}
Ok(self.client.record_surface(&record).await?)
}
}
struct KernelRule {
client: ControlClient,
decision: String,
}
#[async_trait]
impl RuleCommit for KernelRule {
async fn commit(self: Box<Self>) -> Result<()> {
Ok(self.client.grant_always_allow(&self.decision).await?)
}
}
fn request_of(item: ApprovalItem) -> Result<ApprovalRequest> {
let policy = serde_json::to_value(ApprovalPolicy::new([]))
.map_err(|error| SurfaceError::Invalid(error.to_string()))?;
let value = json!({
"id": item.id,
"scope": item.scope,
"fingerprint": "",
"toolName": item.tool_name,
"argsRedacted": item.args_redacted,
"summary": item.summary,
"risk": ApprovalRisk::High,
"createdAt": item.created_at,
"expiresAt": item.expires_at,
"allowedActions": item
.allowed_actions
.into_iter()
.filter(|action| *action != ApprovalAction::Edit)
.collect::<Vec<_>>(),
"policy": policy,
"runId": item.run_id,
"version": item.version,
"state": item.state,
});
serde_json::from_value(value).map_err(|error| SurfaceError::Invalid(error.to_string()))
}
#[async_trait]
impl Source for ControlSource {
fn app_name(&self) -> &str {
&self.app
}
async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
let request = AttachRequest { user_id: Some(user.to_string()), after: None };
match self.client.attach(session, &request).await {
Ok(attached) => Ok(Some(attached.transcript)),
Err(error) => {
let error = adk_core::AdkError::from(error);
match error.category {
ErrorCategory::NotFound => Ok(None),
_ => Err(SurfaceError::Source(error)),
}
}
}
}
async fn changed(&self, max: Duration) {
let mut changes = self.changes();
changes.mark_unchanged();
let bus = *changes.borrow();
let wait =
if bus.live && bus.running == 0 { QUIET_IDLE.max(max) } else { max.max(QUIET_REREAD) };
let change = async {
if changes.changed().await.is_err() {
std::future::pending::<()>().await;
}
};
tokio::select! {
() = tokio::time::sleep(wait) => {}
() = change => {}
}
}
async fn requests(
&self,
_caller: &Caller,
session: Option<&str>,
open_only: bool,
) -> Result<Vec<ApprovalRequest>> {
if let Some(inbox) = &self.inbox {
return inbox.list(&self.app, session, open_only).await;
}
self.client
.approvals()
.await?
.into_iter()
.filter(|item| session.is_none_or(|session| item.scope.session_id == session))
.map(request_of)
.collect()
}
async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
if let Some(inbox) = &self.inbox {
return inbox.get(id).await;
}
Ok(self
.client
.approvals()
.await?
.into_iter()
.find(|item| item.id == id)
.map(request_of)
.transpose()?)
}
async fn decide(
&self,
id: &str,
expected_version: u64,
decision: ApprovalDecision,
) -> Result<ApprovalRequest> {
if let Some(inbox) = &self.inbox {
return inbox.decide(id, expected_version, &decision).await;
}
if decision.kind == ApprovalAction::Edit {
return Err(SurfaceError::unsupported("editing a call over the control plane"));
}
let item = self
.client
.decide(id, expected_version, decision.kind, decision.reason.as_deref())
.await?;
let mut request = request_of(item)?;
request.decisions.push(decision);
Ok(request)
}
async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
let known = |offers: &Offers| {
offers
.get(&request.id)
.filter(|(version, _)| *version == request.version)
.map(|(_, label)| label.clone())
};
if let Some(label) = known(&self.offers.lock().unwrap_or_else(|e| e.into_inner())) {
return label.map(|label| AlwaysAllowOffer { label });
}
let label = match self.client.always_allow_offer(&request.id).await {
Ok(label) => label,
Err(error) if passing(error.category()) => {
tracing::debug!(error = %error, decision.id = %request.id, "Always allow could not be looked up");
return None;
}
Err(_) => None,
};
let mut offers = self.offers.lock().unwrap_or_else(|e| e.into_inner());
if offers.len() >= OFFERS {
offers.clear();
}
offers.insert(request.id.clone(), (request.version, label.clone()));
label.map(|label| AlwaysAllowOffer { label })
}
async fn prepare_always_allow(
&self,
_caller: &Caller,
request: &ApprovalRequest,
) -> Result<Box<dyn RuleCommit>> {
self.client.prepare_always_allow(&request.id).await?;
Ok(Box::new(KernelRule { client: self.client.clone(), decision: request.id.clone() }))
}
async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
let mut latest: BTreeMap<String, AgentState> = BTreeMap::new();
for process in self.processes(user).await? {
let run = &process.run;
if latest.contains_key(&run.target) {
continue;
}
let waiting_on_decision =
matches!(run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }));
latest.insert(
run.target.clone(),
AgentState {
shell: None,
name: run.target.clone(),
session_id: run.session_id.clone(),
state: run.state,
waiting_on_decision,
wake_at: (run.state == RunState::Waiting && !waiting_on_decision)
.then_some(run.not_before)
.flatten(),
suspended: process.meta.suspended_by.is_some(),
subagent: (process.meta.kind == adk_kernel::ProcessKind::Subagent).then(|| {
process
.meta
.labels
.get(adk_kernel::SUBAGENT_NAME_LABEL)
.cloned()
.unwrap_or_else(|| "sub-agent".to_string())
}),
},
);
}
let gone: Vec<String> = self
.client
.agents()
.await
.unwrap_or_default()
.into_iter()
.filter(|view| {
matches!(
view.agent.state,
adk_kernel::agents::AgentRecordState::Removing
| adk_kernel::agents::AgentRecordState::Removed
)
})
.map(|view| view.agent.id)
.collect();
latest.retain(|name, _| !gone.contains(name));
Ok(latest.into_values().collect())
}
async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
let mut threads: BTreeMap<String, DateTime<Utc>> = BTreeMap::new();
for process in self.processes(user).await? {
if process.run.target != agent {
continue;
}
if let Some(session) = process.run.session_id.clone() {
let at = threads.entry(session).or_insert(process.run.updated_at);
*at = (*at).max(process.run.updated_at);
}
}
Ok(threads.into_iter().collect())
}
async fn agent_definitions(&self, user: &str) -> Result<Vec<crate::agents::AgentDetail>> {
let views = match self.client.agents().await {
Ok(views) => views,
Err(error)
if matches!(
error.category(),
adk_core::ErrorCategory::NotFound | adk_core::ErrorCategory::Unsupported
) =>
{
return Ok(Vec::new());
}
Err(error) => return Err(error.into()),
};
let offset = *chrono::Local::now().offset();
Ok(views
.into_iter()
.map(|view| {
crate::agents::AgentDetail::of(
&view.agent,
view.cant_start,
user,
"ADK-Rust",
offset,
)
})
.collect())
}
async fn agent(&self, user: &str, id: &str) -> Result<Option<crate::agents::AgentDetail>> {
Ok(self.agent_definitions(user).await?.into_iter().find(|detail| {
detail.id == id
&& !matches!(
detail.state,
crate::agents::AgentLife::Removed | crate::agents::AgentLife::Refused
)
}))
}
async fn busy(&self, user: &str, session: &str) -> Result<bool> {
Ok(self.processes(user).await?.iter().any(|process| {
process.run.session_id.as_deref() == Some(session) && runs(process.run.state)
}))
}
async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
let mut failures: Vec<TurnFailure> = self
.processes(user)
.await?
.into_iter()
.filter(|process| {
process.run.session_id.as_deref() == Some(session)
&& process.run.state == RunState::Failed
})
.map(|process| TurnFailure {
agent: process.run.target,
at: process.run.updated_at,
error: process.run.error,
})
.collect();
failures.sort_by_key(|failure| failure.at);
Ok(failures)
}
async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
Ok(self.processes(user).await?.iter().any(|process| {
process.run.session_id.as_deref() == Some(session)
&& process.run.state == RunState::Waiting
&& matches!(process.run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }))
}))
}
async fn start_turn(&self, _caller: &Caller, session: &str, text: &str) -> Result<()> {
let request = SpawnRequest::new(self.target.clone(), json!({ "text": text }))
.with_session_id(session);
self.client.spawn(&request).await?;
Ok(())
}
async fn start_turn_images(
&self,
caller: &Caller,
session: &str,
text: &str,
images: &[crate::images::MessageImage],
) -> Result<()> {
if images.is_empty() {
return self.start_turn(caller, session, text).await;
}
let mut content = adk_core::Content::new("user");
if !text.trim().is_empty() {
content = content.with_text(text);
}
for image in images {
content = content.with_inline_data(image.mime_type.clone(), image.data.clone());
}
let request = SpawnRequest::new(self.target.clone(), json!({ "content": content }))
.with_session_id(session);
self.client.spawn(&request).await?;
Ok(())
}
async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
let (steer_id, pid, lease_epoch) = match self.client.steer(session, text).await? {
SteerResponse::Accepted { steer_id, pid, lease_epoch } => (steer_id, pid, lease_epoch),
SteerResponse::Returned => return Ok(None),
};
let source = self.clone();
let (user, session) = (caller.user_id().to_string(), session.to_string());
Ok(Some(Box::pin(async move {
loop {
let mut changed = Box::pin(source.changed(QUIET_REREAD));
let _ = futures::poll!(changed.as_mut());
let held = source.client.processes(&Default::default()).await.map(|processes| {
processes.iter().any(|process| {
process.meta.pid == pid
&& process.run.state == RunState::Running
&& process.run.lease_epoch == lease_epoch
})
});
match (held, source.transcript(&user, &session).await) {
(Ok(held), Ok(events)) => {
let steered = crate::local::taken(&events.unwrap_or_default(), &steer_id);
if steered != Steered::Returned || !held {
return Ok(steered);
}
}
(Err(error), _) => {
tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's process could not be read");
}
(_, Err(error)) => {
tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's session could not be read");
}
}
changed.await;
}
})))
}
async fn request_call(
&self,
caller: &Caller,
session: &str,
text: &str,
call: adk_core::RequestedCall,
) -> Result<()> {
let target = self
.agent_of_session(caller.user_id(), session)
.await?
.unwrap_or_else(|| self.target.clone());
let request = SpawnRequest::new(target, json!({ "text": text, "requestedCall": call }))
.with_session_id(session);
self.client.spawn(&request).await?;
Ok(())
}
async fn stop_all(&self, _caller: &Caller, reason: &str) -> Result<()> {
self.client.freeze(Some(reason)).await?;
Ok(())
}
async fn resume_all(&self, _caller: &Caller) -> Result<()> {
self.client.unfreeze().await?;
Ok(())
}
async fn stopped(&self) -> Result<bool> {
Ok(self.client.health().await?.frozen)
}
async fn mode(&self, _user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
let Some(session) = session else {
return Ok(None);
};
match self.client.session_mode(session).await {
Ok(mode) => Ok(mode.and_then(|mode| mode.parse().ok())),
Err(error)
if matches!(
error.category(),
ErrorCategory::Forbidden
| ErrorCategory::Unauthorized
| ErrorCategory::InvalidInput
) =>
{
Ok(None)
}
Err(error) => Err(error.into()),
}
}
fn opens_sessions(&self) -> bool {
true
}
async fn set_mode(&self, _caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
let word = match mode {
HarnessMode::ReadOnly => "read-only",
other => other.as_str(),
};
self.client.run_command("mode", word, session).await?;
Ok(())
}
async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
Ok(self
.processes(user)
.await?
.into_iter()
.find(|process| process.run.session_id.as_deref() == Some(session))
.map(|process| process.run.target))
}
async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
let areas = match self.client.settings().await {
Ok(areas) => areas,
Err(error) => {
tracing::debug!(error = %error, "could not read the areas' settings; spend is not split by area");
Vec::new()
}
};
let area = areas
.iter()
.find(|area| area.primary)
.or_else(|| {
areas
.iter()
.find(|area| area.partition.as_str() == adk_kernel::PartitionId::DEFAULT)
})
.or(match areas.as_slice() {
[only] => Some(only),
_ => None,
});
let spent = self
.processes(user)
.await?
.iter()
.filter(|process| area.is_none_or(|area| process.meta.partition == area.partition))
.map(|process| process.view.spend_today)
.sum();
let limit = self.daily_limit.or(area.and_then(|area| area.daily_spending_limit));
Ok(Some(SpendToday { spent, limit }))
}
async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
let mut params = LedgerParams { from: Some(since), ..LedgerParams::default() };
let mut entries = Vec::new();
loop {
let page = self.client.ledger(¶ms).await?;
entries.extend(page.entries);
match page.next {
Some(next) => params.after = Some(next),
None => break,
}
}
Ok(entries)
}
}