use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::sync::Arc;
use adk_core::{
ApprovalAction, ApprovalRequest, ApprovalState, Event, Part, RunState, ToolConfirmationRequest,
};
use adk_harness::HarnessMode;
use adk_harness::take_over::TAKE_OVER_TOOL;
use adk_kernel::control::api::{AwayKind, AwayLine};
use adk_kernel::proc::{KERNEL_AGENT, LedgerEntry};
use adk_kernel::{AGENDA_TOOL_NAME, AgendaItem, AgendaOrigin, QuietHours, Wake};
use chrono::{DateTime, FixedOffset, TimeZone, Utc};
use serde_json::Value;
use crate::answers::AnswerRecord;
use crate::hints::CardHint;
use crate::model::{
AgentRef, AgentRow, AgentStatus, Avatar, BriefingLine, CallView, CardStatus, CommandRun,
Decided, DecidedAnswer, DecisionCard, ElicitationView, ElicitedField, ElicitedKind,
ElicitedOption, FeedEntry, Mode, ModeView, OutputLine, Pill, QuietView, Reversibility, RunStop,
ShellView, Speaker, SpendView, ThreadItem, TimelineStep,
};
use crate::origin::{Caller, SurfaceKind};
use crate::rules::{self, Answer, DecisionFacts};
use crate::source::{AgentState, SpendToday, TurnFailure};
use crate::words::{self, SaidWhat};
pub const CALL_TEXT_LIMIT: usize = 2_000;
pub const RUN_LINES: usize = 40;
const RUN_LINE_CHARS: usize = 400;
const REASON_CHARS: usize = 500;
pub const CARD_NAME_LIMIT: usize = 64;
pub const CARD_HEADING_LIMIT: usize = 160;
pub const CARD_LINE_LIMIT: usize = 280;
const ELICITED_FIELDS_LIMIT: usize = 24;
const ELICITED_OPTIONS_LIMIT: usize = 50;
pub(crate) fn elicitation_server(tool: &str) -> Option<&str> {
tool.strip_prefix("mcp:")?.strip_suffix("/elicitation")
}
pub(crate) fn elicitation_of(request: &ApprovalRequest) -> Option<ElicitationView> {
let server = capped(elicitation_server(&request.tool_name)?, CARD_NAME_LIMIT);
let shown = &request.args_redacted;
let message = capped(shown.get("message").and_then(Value::as_str)?, CARD_LINE_LIMIT);
if let Some(url) = shown.get("url").and_then(Value::as_str) {
let (host, warning) = address_parts(url)?;
return Some(ElicitationView::Url {
server,
message,
url: url.to_string(),
host,
warning: warning.map(str::to_string),
});
}
let schema = shown.get("schema")?;
let properties = schema.get("properties")?.as_object()?;
if properties.len() > ELICITED_FIELDS_LIMIT {
return None;
}
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let fields = properties
.iter()
.map(|(name, property)| elicited_field(name, property, required.contains(&name.as_str())))
.collect::<Option<Vec<_>>>()?;
Some(ElicitationView::Form { server, message, fields })
}
fn elicited_field(name: &str, property: &Value, required: bool) -> Option<ElicitedField> {
let text = |key: &str| property.get(key).and_then(Value::as_str);
let mut options = Vec::new();
if let Some(values) = property.get("enum").and_then(Value::as_array) {
let names = property.get("enumNames").and_then(Value::as_array);
for (index, value) in values.iter().enumerate() {
let value = value.as_str()?;
let label = names.and_then(|names| names.get(index)).and_then(Value::as_str);
options.push((value, label.unwrap_or(value)));
}
} else if let Some(choices) =
property.get("oneOf").or_else(|| property.get("anyOf")).and_then(Value::as_array)
{
for choice in choices {
let value = choice.get("const").and_then(Value::as_str)?;
let label = choice.get("title").and_then(Value::as_str).unwrap_or(value);
options.push((value, label));
}
}
if options.len() > ELICITED_OPTIONS_LIMIT {
return None;
}
let kind = if options.is_empty() {
match text("type")? {
"string" => match text("format") {
Some("email") => ElicitedKind::Email,
Some("uri") => ElicitedKind::Url,
Some("date") => ElicitedKind::Date,
Some("date-time") => ElicitedKind::DateTime,
_ => ElicitedKind::Text,
},
"number" => ElicitedKind::Number,
"integer" => ElicitedKind::Integer,
"boolean" => ElicitedKind::Boolean,
_ => return None,
}
} else {
ElicitedKind::Choice
};
let default = property.get("default").filter(|value| !value.is_object() && !value.is_array());
Some(ElicitedField {
name: name.to_string(),
label: capped(text("title").unwrap_or(name), CARD_NAME_LIMIT),
description: text("description").map(|description| capped(description, CARD_LINE_LIMIT)),
kind,
required,
default: default.cloned(),
options: options
.into_iter()
.map(|(value, label)| ElicitedOption {
value: value.to_string(),
label: capped(label, CARD_NAME_LIMIT),
})
.collect(),
minimum: property.get("minimum").and_then(Value::as_f64),
maximum: property.get("maximum").and_then(Value::as_f64),
min_length: property.get("minLength").and_then(Value::as_u64),
max_length: property.get("maxLength").and_then(Value::as_u64),
})
}
pub(crate) fn check_answer(fields: &[ElicitedField], content: &Value) -> Result<(), String> {
let answer = content.as_object().ok_or("the answer is an object of the form's fields")?;
if let Some(unknown) = answer.keys().find(|key| !fields.iter().any(|f| &f.name == *key)) {
return Err(format!("{unknown} is not a field of the form"));
}
for field in fields {
let Some(value) = answer.get(&field.name) else {
if field.required {
return Err(format!("{} is required", field.label));
}
continue;
};
let fits = match field.kind {
ElicitedKind::Number => value.is_number(),
ElicitedKind::Integer => value.is_i64() || value.is_u64(),
ElicitedKind::Boolean => value.is_boolean(),
ElicitedKind::Choice => value
.as_str()
.is_some_and(|picked| field.options.iter().any(|option| option.value == picked)),
_ => value.is_string(),
};
if !fits {
return Err(format!("{} does not take {value}", field.label));
}
if let Some(number) = value.as_f64()
&& (field.minimum.is_some_and(|min| number < min)
|| field.maximum.is_some_and(|max| number > max))
{
return Err(format!("{} is out of its range", field.label));
}
if let Some(text) = value.as_str() {
let length = text.chars().count() as u64;
if field.min_length.is_some_and(|min| length < min)
|| field.max_length.is_some_and(|max| length > max)
{
return Err(format!("{} is too short or too long", field.label));
}
}
}
Ok(())
}
fn address_parts(url: &str) -> Option<(String, Option<&'static str>)> {
let (scheme, rest) = url.split_once("://")?;
let authority = rest.split(['/', '?', '#']).next()?;
let (userinfo, host_port) = match authority.rsplit_once('@') {
Some((userinfo, host_port)) => (Some(userinfo), host_port),
None => (None, authority),
};
let host = match host_port.strip_prefix('[') {
Some(bracketed) => bracketed.split(']').next()?,
None => host_port.split(':').next()?,
}
.to_lowercase();
if host.is_empty() {
return None;
}
let warning = if !host.is_ascii() || host.split('.').any(|label| label.starts_with("xn--")) {
Some(words::LOOK_ALIKE_ADDRESS)
} else if userinfo.is_some() {
Some(words::HIDDEN_HOST_ADDRESS)
} else if scheme.eq_ignore_ascii_case("http") {
Some(words::UNENCRYPTED_ADDRESS)
} else {
None
};
Some((host, warning))
}
pub(crate) fn capped(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
return text.to_string();
}
let mut cut: String = text.chars().take(limit.saturating_sub(1)).collect();
cut.push('โฆ');
cut
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Place {
pub surface: SurfaceKind,
pub phrase: String,
}
impl Place {
pub fn web() -> Self {
Self { surface: SurfaceKind::Web, phrase: words::IN_THE_HOME_APP.to_string() }
}
pub fn phone() -> Self {
Self { surface: SurfaceKind::Phone, phrase: words::ON_YOUR_PHONE.to_string() }
}
pub fn terminal() -> Self {
Self { surface: SurfaceKind::Terminal, phrase: words::IN_THE_TERMINAL.to_string() }
}
pub fn tray() -> Self {
Self { surface: SurfaceKind::Tray, phrase: words::FROM_THE_TRAY.to_string() }
}
pub fn chat(channel: &str) -> Self {
Self { surface: SurfaceKind::Chat, phrase: words::in_channel(channel) }
}
}
type Classify<T> = Arc<dyn Fn(&ApprovalRequest) -> T + Send + Sync>;
#[derive(Clone)]
pub(crate) struct Projector {
pub(crate) offset: FixedOffset,
pub(crate) quiet: Option<QuietHours>,
pub(crate) places: Vec<Place>,
pub(crate) names: BTreeMap<String, String>,
pub(crate) heading: Classify<String>,
pub(crate) money: Classify<bool>,
pub(crate) rates_high: Classify<bool>,
pub(crate) reversibility: Classify<Reversibility>,
pub(crate) voice_window_secs: u32,
#[cfg(feature = "genui")]
pub(crate) catalogs: crate::genui::Catalogs,
}
impl fmt::Debug for Projector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Projector")
.field("offset", &self.offset)
.field("quiet", &self.quiet)
.field("places", &self.places)
.finish_non_exhaustive()
}
}
impl Projector {
pub(crate) fn new(offset: FixedOffset) -> Self {
Self {
offset,
quiet: None,
places: Vec::new(),
names: BTreeMap::new(),
heading: Arc::new(heading),
money: Arc::new(spends_money),
rates_high: Arc::new(|_| false),
reversibility: Arc::new(reversibility),
voice_window_secs: rules::VOICE_CANCEL_WINDOW_SECS,
#[cfg(feature = "genui")]
catalogs: crate::genui::Catalogs::forms(),
}
}
pub(crate) fn hh_mm(&self, at: DateTime<Utc>) -> String {
at.with_timezone(&self.offset).format("%H:%M").to_string()
}
pub(crate) fn agent(&self, name: &str) -> AgentRef {
let display_name = self.names.get(name).cloned().unwrap_or_else(|| humanize(name));
AgentRef { name: name.to_string(), avatar: avatar(&display_name), display_name }
}
pub(crate) fn adds_agent(
&self,
request: &ApprovalRequest,
) -> Option<crate::agents::AgentCardView> {
if request.tool_name != adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
return None;
}
let suggester = self.agent(&agent_name(request)).display_name;
let area = request.args_redacted.get("area").and_then(Value::as_str).unwrap_or_default();
crate::agents::AgentCardView::of_request(
request,
&suggester,
&crate::agents::area_name(area),
)
}
pub(crate) fn facts(
&self,
request: &ApprovalRequest,
always_label: Option<String>,
hint: &CardHint,
) -> DecisionFacts {
if let Some(agent) = self.adds_agent(request) {
let assessed = adk_kernel::agents::AgentRecord::new(
String::new(),
agent.draft.clone().into_definition(),
adk_kernel::agents::AgentRecordState::Proposed,
adk_kernel::agents::AgentOrigin::ByHand,
adk_core::principal::SubjectRef::human(&request.scope.user_id),
request.created_at,
);
return DecisionFacts {
risk: request.risk.into(),
money: adk_harness::assess_agent(&assessed).money || hint.marks_money(),
truncated: agent.instructions_truncated,
allows: request
.allowed_actions
.iter()
.copied()
.filter(|action| {
matches!(action, ApprovalAction::Approve | ApprovalAction::Reject)
})
.collect(),
always_label: None,
adds_agent: true,
image: None,
plan: false,
};
}
let own_args = shows_own_arguments(request);
let take_over = request.tool_name == TAKE_OVER_TOOL;
let answers_a_form = matches!(elicitation_of(request), Some(ElicitationView::Form { .. }));
let risk = if (self.rates_high)(request) {
request.risk.max(adk_core::ApprovalRisk::High)
} else {
request.risk
};
DecisionFacts {
risk: risk.into(),
money: (self.money)(request) || hint.marks_money(),
truncated: call_view(request).truncated,
allows: request
.allowed_actions
.iter()
.copied()
.filter(|action| match action {
ApprovalAction::Reject => true,
ApprovalAction::Edit => (own_args || answers_a_form) && !take_over,
ApprovalAction::Approve | ApprovalAction::Respond => !take_over,
})
.collect(),
always_label: always_label.filter(|_| !take_over && !hint.removes_always()),
adds_agent: false,
image: None,
plan: false,
}
}
pub(crate) fn decided(
&self,
request: &ApprovalRequest,
caller: &Caller,
answer: Option<&AnswerRecord>,
) -> Option<Decided> {
if request.state == ApprovalState::Pending {
return None;
}
let last = request.decisions.last();
let answer_kind = match request.state {
ApprovalState::Approved => match last.map(|decision| decision.kind) {
Some(ApprovalAction::Edit) => DecidedAnswer::Edited,
_ => DecidedAnswer::Yes,
},
ApprovalState::Rejected => DecidedAnswer::No,
ApprovalState::Responded => DecidedAnswer::Replied,
ApprovalState::Pending | ApprovalState::Expired | ApprovalState::Cancelled => {
DecidedAnswer::Ended
}
};
let at = last
.map(|decision| decision.decided_at)
.or(request.resolved_at)
.unwrap_or(request.created_at);
let at_text = self.hh_mm(at);
let approver = last.filter(|_| answer_kind != DecidedAnswer::Ended);
let by_you = approver.is_some_and(|decision| decision.approver.id == caller.user_id());
let by = match approver {
Some(_) if by_you => "You".to_string(),
Some(decision) => decision.approver.id.clone(),
None => String::new(),
};
let via = answer
.filter(|record| {
record.approval_id == request.id
&& approver.is_some_and(|decision| decision.approver == record.by)
})
.map(|record| record.via.clone());
let said = match answer_kind {
DecidedAnswer::Yes => Some(SaidWhat::Yes),
DecidedAnswer::No => Some(SaidWhat::No),
DecidedAnswer::Edited => Some(SaidWhat::Edited),
DecidedAnswer::Replied => Some(SaidWhat::Replied),
DecidedAnswer::Ended | DecidedAnswer::Unknown => None,
};
let text = match said {
Some(what) => {
let phrase = via.as_ref().map(crate::origin::Via::phrase);
words::said((!by_you).then_some(by.as_str()), what, phrase.as_deref(), &at_text)
}
None => words::ENDED_WITHOUT_AN_ANSWER.to_string(),
};
Some(Decided { by, by_you, via, at, at_text, answer: answer_kind, text, scope_text: None })
}
pub(crate) fn card(
&self,
request: &ApprovalRequest,
caller: &Caller,
always_label: Option<String>,
answer: Option<&AnswerRecord>,
now: DateTime<Utc>,
hint: &CardHint,
) -> DecisionCard {
let facts = self.facts(request, always_label, hint);
let chat = rules::row(caller) == rules::Row::Chat;
let (heading, summary, call) = if chat {
let full = call_view(request);
let call = CallView {
tool: full.tool.clone(),
args: Value::Null,
text: full.tool,
truncated: full.truncated,
};
let heading = hint.chat_heading.clone().unwrap_or_else(|| chat_heading(request));
(heading, None, call)
} else {
let asked = elicitation_server(&request.tool_name)
.map(|_| request.summary.trim())
.filter(|summary| !summary.is_empty())
.map(str::to_string);
let heading = hint.heading.clone().or(asked).unwrap_or_else(|| (self.heading)(request));
(heading, self.kernel_summary(request, now), call_view(request))
};
let decided = self.decided(request, caller, answer);
let mut allowed = rules::allowed_answers(caller, &facts);
if allowed.cancel_window_secs.is_some() {
allowed.cancel_window_secs = Some(self.voice_window_secs);
}
if let Some((yes, no)) = kernel_answer_words(request) {
for option in &mut allowed.options {
match option.answer {
Answer::AllowOnce if !option.needs_presence => option.label = yes.to_string(),
Answer::Deny => option.label = no.to_string(),
Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => {}
}
}
}
let elicitation = if chat { None } else { elicitation_of(request) };
if matches!(elicitation, Some(ElicitationView::Form { .. })) {
for option in &mut allowed.options {
if option.answer == Answer::Edit {
option.label = words::ANSWER.to_string();
}
}
}
if decided.is_some() {
allowed.options.clear();
allowed.open_in_home = false;
allowed.cancel_window_secs = None;
allowed.note = None;
}
let since = self.hh_mm(request.created_at);
let mut timeline: Vec<String> = hint.first_step.iter().cloned().collect();
timeline.push(words::asked_at(&since));
let until = decided.as_ref().map_or(now, |decided| decided.at);
if self.waited_through_quiet(request.created_at, until) {
timeline.push(words::WAITED_THROUGH_QUIET_TIME.to_string());
}
timeline.push(match &decided {
Some(decided) => decided.text.clone(),
None => words::WAITING_FOR_YOU.to_string(),
});
let last = timeline.len() - 1;
let timeline = timeline
.into_iter()
.enumerate()
.map(|(index, text)| TimelineStep { text, current: index == last })
.collect();
let adds_agent = self.adds_agent(request);
let reversibility = match adds_agent {
Some(_) => Reversibility::CanBeRemoved,
None => hint.reversibility.unwrap_or_else(|| (self.reversibility)(request)),
};
let also: Vec<String> = self
.places
.iter()
.filter(|place| place.surface != caller.surface)
.map(|place| place.phrase.clone())
.collect();
let (status, status_text) = match decided {
Some(_) => (CardStatus::Decided, words::DECIDED),
None => (CardStatus::Waiting, words::WAITING_FOR_YOU),
};
let mut card = DecisionCard {
id: request.id.clone(),
version: request.version,
session_id: request.scope.session_id.clone(),
agent: self.agent(&agent_name(request)),
waiting_since: request.created_at,
since_text: words::since(&since),
status,
status_text: status_text.to_string(),
heading,
summary,
call,
timeline,
allowed,
risk: facts.risk,
risk_text: facts.risk.words().to_string(),
reversibility,
reversibility_text: match reversibility {
Reversibility::CantBeUnsent => words::CANT_BE_UNSENT,
Reversibility::CantBeUndone => words::CANT_BE_UNDONE,
Reversibility::CanBeRemoved => crate::agents::words::YOU_CAN_REMOVE_IT_LATER,
Reversibility::CanBeChangedBack => words::YOU_CAN_CHANGE_IT_BACK,
}
.to_string(),
money: facts.money,
also_shown: words::also_shown(&also),
decided,
adds_agent,
detail: hint.detail.clone().filter(|_| !chat),
elicitation,
media: None,
parked: None,
plan: None,
};
card.agent.display_name = capped(&card.agent.display_name, CARD_NAME_LIMIT);
card.heading = capped(&card.heading, CARD_HEADING_LIMIT);
card.summary = card.summary.map(|summary| capped(&summary, CARD_LINE_LIMIT));
for step in &mut card.timeline {
step.text = capped(&step.text, CARD_LINE_LIMIT);
}
card.also_shown = card.also_shown.map(|also| capped(&also, CARD_LINE_LIMIT));
if let Some(detail) = &mut card.detail {
detail.text = capped(&detail.text, CARD_LINE_LIMIT);
}
card
}
pub(crate) fn kernel_summary(
&self,
request: &ApprovalRequest,
now: DateTime<Utc>,
) -> Option<String> {
let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
if request.tool_name == AGENDA_TOOL_NAME {
let Some(item) = agenda_item(request) else {
return Some(words::AGENTS_SUGGEST.to_string());
};
if item.origin.is_question() {
return Some(words::NOTICED_SOMETHING.to_string());
}
let who = match &item.origin {
AgendaOrigin::User => words::YOU_SUGGESTED_THIS.to_string(),
AgendaOrigin::Agent { .. } => {
words::suggested_by(Some(&self.agent(&agent_name(request)).display_name))
}
_ => words::suggested_by(None),
};
let when = match &item.when {
Some(wake) => self.wake_words(wake, now),
None => words::RIGHT_AWAY.to_string(),
};
let mut text = format!("{who} {}", words::once_you_say_yes(&when));
if let Some(steps) = item.plan.as_ref().map(|plan| plan.steps.len()).filter(|n| *n > 0)
{
text.push(' ');
text.push_str(&words::plan_of(steps));
}
if let Some(cap) = item.budget.as_ref().and_then(|budget| budget.max_cost_micro_usd) {
text.push(' ');
text.push_str(&words::may_spend(cap));
}
return Some(text);
}
if operation != DRIVER_MOUNT_OPERATION {
return None;
}
request.args_redacted.get("commandLine").and_then(Value::as_str).map(words::driver_starts)
}
fn wake_words(&self, wake: &Wake, now: DateTime<Utc>) -> String {
match wake {
Wake::At(at) if *at <= now => words::RIGHT_AWAY.to_string(),
Wake::At(at) => {
let local = at.with_timezone(&self.offset);
let today = now.with_timezone(&self.offset).date_naive();
let time = local.format("%H:%M");
if local.date_naive() == today {
format!("at {time}")
} else if today.succ_opt() == Some(local.date_naive()) {
format!("tomorrow at {time}")
} else {
format!("on {} at {time}", local.format("%a %-d %b"))
}
}
Wake::Cron { expr, .. } => self.cron_words(expr, now),
Wake::FileChange { root, glob, .. } => {
format!("when a file matching {glob} changes in {}", root.display())
}
Wake::Webhook { hook } => format!("when {hook} calls in"),
Wake::Queue { source } => format!("when a message arrives from {source}"),
Wake::Approval { .. } => "once a decision it waits on is answered".to_string(),
Wake::RunFinished { .. } => "after another of your agents' tasks finishes".to_string(),
Wake::BudgetReplenished { .. } => "once the day's budget allows it".to_string(),
Wake::Manual => "when you start it".to_string(),
_ => "later".to_string(),
}
}
fn cron_words(&self, expr: &str, now: DateTime<Utc>) -> String {
let written = || format!("on the schedule {expr}");
let all: Vec<&str> = expr.split_whitespace().collect();
let fields = match all.len() {
5 => &all[..],
6 | 7 if all[0] == "0" && all.get(6).is_none_or(|year| *year == "*") => &all[1..6],
_ => return written(),
};
let &[minute, hour, day, month, weekday] = fields else {
return written();
};
let every = |field: &str| match field {
"*" => Some(1),
_ => field.strip_prefix("*/").and_then(|step| step.parse::<u32>().ok()),
};
let number = |field: &str| field.parse::<u32>().ok();
if day != "*" || month != "*" {
return written();
}
match (every(minute), number(minute), every(hour), number(hour)) {
(Some(1), _, Some(1), _) if weekday == "*" => "every minute".to_string(),
(Some(step), _, Some(1), _) if weekday == "*" => format!("every {step} minutes"),
(_, Some(_), Some(1), _) if weekday == "*" => "every hour".to_string(),
(_, Some(_), Some(step), _) if weekday == "*" => format!("every {step} hours"),
(_, Some(minute), _, Some(hour)) => {
let Some(at) = now.date_naive().and_hms_opt(hour, minute, 0) else {
return written();
};
let at = Utc.from_utc_datetime(&at);
let local = at.with_timezone(&self.offset);
let time = local.format("%H:%M");
let days = match weekday.to_ascii_uppercase().as_str() {
"*" => "every day".to_string(),
_ if local.date_naive() != at.date_naive() => return written(),
other if all.len() != 5 && other.bytes().any(|b| b.is_ascii_digit()) => {
return written();
}
"1-5" | "MON-FRI" => "every weekday".to_string(),
other => match WEEKDAYS.iter().find(|(number, name, _)| {
*number == other || name.eq_ignore_ascii_case(other)
}) {
Some((_, _, day)) => format!("every {day}"),
None => return written(),
},
};
format!("{days} at {time}")
}
_ => written(),
}
}
pub(crate) fn waited_through_quiet(&self, from: DateTime<Utc>, until: DateTime<Utc>) -> bool {
let Some(quiet) = self.quiet else {
return false;
};
if quiet.contains(from) || quiet.contains(until) {
return true;
}
let offset = self.quiet_offset(&quiet);
let first = from.with_timezone(&offset).date_naive();
let last = until.with_timezone(&offset).date_naive();
let mut day = first;
while day <= last {
if let Some(start) = offset.from_local_datetime(&day.and_time(quiet.start)).earliest()
&& start > from
&& start <= until
{
return true;
}
day = match day.succ_opt() {
Some(next) => next,
None => break,
};
}
false
}
fn quiet_offset(&self, quiet: &QuietHours) -> FixedOffset {
quiet
.utc_offset_minutes
.and_then(|minutes| FixedOffset::east_opt(minutes * 60))
.unwrap_or(self.offset)
}
pub(crate) fn quiet_view(&self, now: DateTime<Utc>) -> Option<QuietView> {
let quiet = self.quiet?;
if quiet.start == quiet.end {
return None;
}
let start = quiet.start.format("%H:%M").to_string();
let end = quiet.end.format("%H:%M").to_string();
let active = quiet.contains(now);
let text = if active { words::quiet_until(&end) } else { words::quiet_from(&start) };
Some(QuietView { active, start, end, text })
}
pub(crate) fn entry(
&self,
seq: u64,
event: &Event,
links: &HashMap<u64, Link>,
answered: &HashSet<String>,
) -> FeedEntry {
FeedEntry {
seq,
at: event.timestamp,
at_text: self.hh_mm(event.timestamp),
items: self.items(event, links.get(&seq), answered),
}
}
pub(crate) fn turn_failed(&self, failure: &TurnFailure) -> ThreadItem {
let error = failure.error.as_deref().map(str::trim).filter(|error| !error.is_empty());
let (code, reason) = match error.map(|error| (error, error.split_once(": "))) {
Some((_, Some((code, message))))
if code.split('.').count() == 2
&& code.chars().all(|c| c.is_ascii_lowercase() || c == '_' || c == '.') =>
{
(Some(code.to_string()), Some(message.trim()))
}
Some((error, _)) => (None, Some(error)),
None => (None, None),
};
let reason = reason.map(|reason| match reason.char_indices().nth(REASON_CHARS) {
Some((cut, _)) => format!("{}โฆ", &reason[..cut]),
None => reason.to_string(),
});
ThreadItem::TurnFailed {
text: words::couldnt_answer(&self.agent(&failure.agent).display_name),
reason,
code,
}
}
fn items(
&self,
event: &Event,
link: Option<&Link>,
answered: &HashSet<String>,
) -> Vec<ThreadItem> {
let mut items = Vec::new();
let from_person = event.author == "user";
let requested = crate::genui::requested_via(event);
if let Some(content) = &event.llm_response.content {
let mut text = String::new();
let mut images = Vec::new();
for part in &content.parts {
match part {
Part::Text { text: chunk } if !event.llm_response.partial => {
text.push_str(chunk);
}
Part::InlineData { mime_type, data, .. } if from_person => {
images.extend(crate::images::shown(mime_type, data));
}
Part::FunctionCall { id, .. }
if requested.is_some() && crate::genui::is_requested(id.as_ref()) => {}
Part::FunctionCall { name, args, id, .. }
if name == crate::suggest::SUGGEST_REPLIES_TOOL =>
{
if let Ok(replies) = crate::suggest::replies_of(args) {
items.push(ThreadItem::Suggestions { replies, call_id: id.clone() });
}
}
Part::FunctionCall { name, args, id, .. } => {
items.push(ThreadItem::Activity {
tool: name.clone(),
text: describe_call(name, args),
call_id: id.clone(),
});
}
Part::FunctionResponse { function_response, .. }
if adk_core::is_confirmation_pending(&function_response.response) => {}
Part::FunctionResponse { function_response, .. }
if function_response.name == crate::suggest::SUGGEST_REPLIES_TOOL => {}
Part::FunctionResponse { function_response, id: Some(id), .. }
if requested.is_some() && crate::genui::is_requested(Some(id)) =>
{
if let Some(via) = &requested {
items.push(crate::genui::sent(
via,
&function_response.name,
id,
event,
&self.hh_mm(event.timestamp),
Some(&self.agent(&event.author).display_name),
None,
));
}
}
Part::FunctionResponse { function_response, id, .. } => {
#[cfg(feature = "genui")]
{
if let Some(item) = crate::genui::project(
self,
event,
&function_response.name,
&function_response.response,
id.as_ref(),
) {
items.push(item);
continue;
}
}
let ok = !response_failed(&function_response.response);
let text = if !ok
&& crate::genui::is_requested(id.as_ref())
&& crate::genui::refused_on_resume(
&function_response.name,
&function_response.response,
) {
words::cant_use_any_more(
&self.agent(&event.author).display_name,
&function_response.name,
)
} else if ok {
words::DONE.to_string()
} else {
words::FAILED.to_string()
};
let image = (ok
&& crate::viewer::answers_about_image(&function_response.name))
.then(|| function_response.response.get("image").and_then(Value::as_str))
.flatten()
.filter(|digest| digest.starts_with("sha256:"))
.map(str::to_string);
match command_run(&function_response.name, &function_response.response) {
Some(run) => {
let ok = ok
&& run.exit_code.is_none_or(|code| code == 0)
&& run.stopped.is_none();
let text = if ok { words::DONE } else { words::FAILED };
items.push(ThreadItem::Run {
tool: function_response.name.clone(),
call_id: id.clone(),
ok,
text: text.to_string(),
run,
});
}
None => items.push(ThreadItem::Result {
tool: function_response.name.clone(),
call_id: id.clone(),
ok,
text,
image,
}),
}
}
_ => {}
}
}
let text = text.trim();
if (!text.is_empty() || !images.is_empty())
&& event.actions.tool_confirmation.is_none()
&& requested.is_none()
{
let message = if from_person {
ThreadItem::Message {
from: Speaker::You,
author: "You".to_string(),
text: crate::genui::suggested_message(text)
.unwrap_or_else(|| text.to_string()),
images,
}
} else {
ThreadItem::Message {
from: Speaker::Agent,
author: self.agent(&event.author).display_name,
text: text.to_string(),
images: Vec::new(),
}
};
items.insert(0, message);
}
}
if let Some(held) = &event.actions.tool_confirmation {
let ran = held.function_call_id.as_ref().is_some_and(|id| answered.contains(id));
let text = match link {
Some(link) if link.pending && !ran => words::WAITING_FOR_YOU,
Some(_) => words::DECIDED,
None if ran => words::DECIDED,
None => words::WAITING_FOR_AN_ANSWER,
};
if let (Some(via), Some(call_id)) = (&requested, &held.function_call_id) {
items.push(crate::genui::sent(
via,
&held.tool_name,
call_id,
event,
&self.hh_mm(event.timestamp),
None,
link.map(|link| link.id.clone()),
));
}
items.push(ThreadItem::Decision {
decision_id: link.map(|link| link.id.clone()),
tool: held.tool_name.clone(),
text: text.to_string(),
});
}
items
}
pub(crate) fn agent_row(&self, state: &AgentState) -> AgentRow {
let (status, status_text) = match state.state {
RunState::Running | RunState::Queued => {
(AgentStatus::Working, words::WORKING.to_string())
}
RunState::Waiting if state.waiting_on_decision && !state.suspended => {
(AgentStatus::WaitingForYou, words::WAITING_FOR_YOU.to_string())
}
RunState::Waiting => match state.wake_at.filter(|_| !state.suspended) {
Some(at) => (AgentStatus::Asleep, words::asleep_until(&self.hh_mm(at))),
None => (AgentStatus::Asleep, words::ASLEEP.to_string()),
},
RunState::Completed | RunState::Cancelled => {
(AgentStatus::Done, words::DONE.to_string())
}
RunState::Failed => (AgentStatus::Failed, words::FAILED.to_string()),
_ => (AgentStatus::Asleep, words::ASLEEP.to_string()),
};
let status_text = match &state.subagent {
Some(name) => format!("{status_text} ยท sub-agent {name}"),
None => status_text,
};
AgentRow {
agent: self.agent(&state.name),
status,
status_text,
wake_at: state.wake_at.filter(|_| status == AgentStatus::Asleep && !state.suspended),
session_id: state.session_id.clone(),
area: None,
mode: None,
added: false,
can_change: false,
shell: state
.shell
.clone()
.map(|place| ShellView { text: words::commands_run(&place), place }),
}
}
pub(crate) fn briefing_line(&self, entry: &LedgerEntry) -> Option<BriefingLine> {
let line = AwayLine::of(entry)?;
let denied = line.effect.as_deref() == Some("deny");
let at = entry.utc();
let agent = self.ledger_agent(&entry.agent);
let who = agent.clone().unwrap_or_else(|| words::YOUR_AGENTS.to_string());
let failed = entry.effect.as_deref() == Some("failed");
let whom = agent.as_deref().unwrap_or("your agents");
let (pill, text) = match line.kind {
AwayKind::Done => (Some(Pill::Done), words::briefing_sentence("turn", &who)),
AwayKind::Failed if failed => (Some(Pill::Failed), format!("{who} failed.")),
AwayKind::Failed => (Some(Pill::Failed), words::briefing_sentence("loop_guard", &who)),
AwayKind::Stopped => (None, format!("{who} was stopped.")),
AwayKind::Suggestion => match &agent {
Some(agent) => {
(Some(Pill::Suggestion), words::briefing_sentence("proposal", agent))
}
None => (Some(Pill::Suggestion), words::AGENTS_SUGGEST.to_string()),
},
AwayKind::Question => (Some(Pill::Question), words::NOTICED_SOMETHING.to_string()),
AwayKind::Decided if denied => {
(Some(Pill::YouDecided), words::briefing_sentence("rejection", whom))
}
AwayKind::Decided => {
(Some(Pill::YouDecided), words::briefing_sentence("approval", whom))
}
AwayKind::StoppedAll => (None, format!("{}.", words::ALL_AGENTS_STOPPED)),
AwayKind::ResumedAll => (None, words::ALL_AGENTS_RESUMED.to_string()),
_ => (None, words::briefing_sentence("", &who)),
};
Some(BriefingLine {
seq: entry.seq,
at,
at_text: self.hh_mm(at),
agent: who,
pill,
pill_text: pill.map(|pill| pill_words(pill).to_string()),
text,
})
}
fn ledger_agent(&self, label: &str) -> Option<String> {
if label == KERNEL_AGENT || label.is_empty() {
return None;
}
let name = label.rsplit(['/', ':']).next().filter(|name| !name.is_empty()).unwrap_or(label);
Some(self.agent(name).display_name)
}
}
fn pill_words(pill: Pill) -> &'static str {
match pill {
Pill::Done => words::DONE,
Pill::Failed => words::FAILED,
Pill::WaitingForYou => words::WAITING_FOR_YOU,
Pill::YouDecided => words::YOU_DECIDED,
Pill::Suggestion => words::SUGGESTION,
Pill::Question => words::QUESTION,
}
}
pub(crate) fn mode_view(mode: HarnessMode) -> ModeView {
let (mode, label) = match mode {
HarnessMode::ReadOnly => (Mode::JustLook, words::JUST_LOOK),
HarnessMode::Plan => (Mode::Suggest, words::SUGGEST),
HarnessMode::Auto => (Mode::GoAhead, words::GO_AHEAD),
_ => (Mode::AskFirst, words::ASK_FIRST),
};
ModeView { mode, label: label.to_string(), status: words::mode_status(label) }
}
pub(crate) fn harness_mode(mode: Mode) -> HarnessMode {
match mode {
Mode::JustLook => HarnessMode::ReadOnly,
Mode::Suggest => HarnessMode::Plan,
Mode::AskFirst => HarnessMode::Ask,
Mode::GoAhead => HarnessMode::Auto,
}
}
pub(crate) fn spend_view(spend: SpendToday) -> SpendView {
let text = match spend.limit {
Some(limit) => words::spent_of(spend.spent, limit),
None => words::spent_today(spend.spent),
};
SpendView { spent_micro_usd: spend.spent, limit_micro_usd: spend.limit, text }
}
pub(crate) fn agent_name(request: &ApprovalRequest) -> String {
request
.acting
.as_ref()
.map(|acting| {
let id = acting.agent.id.as_str();
id.rsplit(['/', ':']).next().unwrap_or(id).to_string()
})
.filter(|name| !name.is_empty())
.unwrap_or_else(|| request.scope.app_name.clone())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Link {
pub(crate) id: String,
pub(crate) pending: bool,
}
const HOLD_SLACK_MS: i64 = 1_000;
const ONE_TURN_MS: i64 = 500;
pub(crate) fn answered_calls(events: &[Event]) -> HashSet<String> {
events
.iter()
.filter_map(|event| event.llm_response.content.as_ref())
.flat_map(|content| &content.parts)
.filter_map(|part| match part {
Part::FunctionResponse { function_response, id, .. }
if !adk_core::is_confirmation_pending(&function_response.response) =>
{
id.clone()
}
_ => None,
})
.collect()
}
pub(crate) fn links(events: &[Event], requests: &[ApprovalRequest]) -> HashMap<u64, Link> {
let mut order: Vec<&ApprovalRequest> = requests.iter().collect();
order.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
let holds: Vec<(u64, &ToolConfirmationRequest, chrono::DateTime<Utc>, String)> = events
.iter()
.enumerate()
.filter_map(|(index, event)| {
let held = event.actions.tool_confirmation.as_ref()?;
Some((index as u64 + 1, held, event.timestamp, held.fingerprint()))
})
.collect();
let decides = |request: &ApprovalRequest,
held: &ToolConfirmationRequest,
fingerprint: &str,
exact: bool| {
match request.fingerprint.is_empty() {
false => exact && request.fingerprint == fingerprint,
true => {
let agent = held.acting.as_deref().map(|acting| &acting.agent.id);
request.tool_name == held.tool_name
&& match (agent, &request.acting) {
(Some(agent), Some(acting)) => *agent == acting.agent.id,
_ => true,
}
&& (!exact || request.args_redacted == held.args)
}
}
};
let mut taken = vec![false; order.len()];
let mut linked: HashMap<u64, usize> = HashMap::new();
for exact in [true, false] {
let mut held_by: HashMap<&str, usize> = HashMap::new();
for (hold, (seq, held, at, fingerprint)) in holds.iter().enumerate() {
if let Some(&position) = linked.get(seq) {
held_by.insert(fingerprint, position);
continue;
}
let later_owner = |request: &ApprovalRequest| {
holds[hold + 1..].iter().enumerate().any(|(offset, (other, call, when, print))| {
let inherits = holds[..hold + 1 + offset].iter().any(|(earlier, _, _, p)| {
p == print
&& linked.get(earlier).is_some_and(|&position| {
order[position].resolved_at.is_none_or(|at| at > *when)
})
});
!linked.contains_key(other)
&& print != fingerprint
&& !inherits
&& *when > *at + chrono::Duration::milliseconds(ONE_TURN_MS)
&& *when
<= request.created_at + chrono::Duration::milliseconds(HOLD_SLACK_MS)
&& decides(request, call, print, false)
})
};
let kept = held_by.get(fingerprint.as_str()).copied();
let next = match kept {
Some(position)
if order[position].resolved_at.is_none_or(|resolved| resolved > *at) =>
{
Some(position)
}
_ => (0..order.len())
.find(|&position| {
!taken[position]
&& decides(order[position], held, fingerprint, exact)
&& (exact || !later_owner(order[position]))
})
.or(kept),
};
if let Some(position) = next {
taken[position] = true;
held_by.insert(fingerprint, position);
linked.insert(*seq, position);
}
}
}
linked
.into_iter()
.map(|(seq, position)| {
let request = order[position];
(seq, Link { id: request.id.clone(), pending: request.state == ApprovalState::Pending })
})
.collect()
}
pub(crate) fn cut_call_text(full: String) -> (String, bool) {
if full.chars().count() <= CALL_TEXT_LIMIT {
return (full, false);
}
let mut cut: String = full.chars().take(CALL_TEXT_LIMIT).collect();
cut.push('โฆ');
(cut, true)
}
pub(crate) fn call_view(request: &ApprovalRequest) -> CallView {
let (text, truncated) = cut_call_text(call_text(&request.tool_name, &request.args_redacted));
CallView {
tool: request.tool_name.clone(),
args: request.args_redacted.clone(),
text,
truncated,
}
}
fn shows_own_arguments(request: &ApprovalRequest) -> bool {
request.fingerprint.is_empty() || request.shows_call_args()
}
fn call_text(tool: &str, args: &Value) -> String {
match args {
Value::Object(map) => {
let mut entries: Vec<(&String, &Value)> = map.iter().collect();
entries.sort_by(|a, b| a.0.cmp(b.0));
let fields: Vec<String> =
entries.into_iter().map(|(key, value)| format!("{key}: {value}")).collect();
format!("{tool}({})", fields.join(", "))
}
Value::Null => format!("{tool}()"),
other => format!("{tool}({other})"),
}
}
pub(crate) fn heading(request: &ApprovalRequest) -> String {
if request.tool_name == TAKE_OVER_TOOL && !request.summary.trim().is_empty() {
return request.summary.clone();
}
if let Some(operation) = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX) {
if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
let name = request
.args_redacted
.get("displayName")
.and_then(Value::as_str)
.unwrap_or_default();
return crate::agents::words::add_an_agent_called(name);
}
if request.tool_name == AGENDA_TOOL_NAME {
return match agenda_item(request) {
Some(item) if !item.title.trim().is_empty() => sentence(&item.title),
Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
Some(_) | None => words::SUGGESTION.to_string(),
};
}
if operation == DRIVER_MOUNT_OPERATION
&& let Some(id) = request.args_redacted.get("id").and_then(Value::as_str)
{
return words::start_driver(id);
}
return humanize(operation);
}
describe_call(&request.tool_name, &request.args_redacted)
}
pub(crate) fn chat_heading(request: &ApprovalRequest) -> String {
if request.tool_name == AGENDA_TOOL_NAME {
return match agenda_item(request) {
Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
Some(_) | None => words::SUGGESTION.to_string(),
};
}
humanize(request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX).unwrap_or(&request.tool_name))
}
pub(crate) fn kernel_name(request: &ApprovalRequest) -> Option<String> {
let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
let name = if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
request.args_redacted.get("displayName").and_then(Value::as_str).map(str::to_string)
} else if request.tool_name == AGENDA_TOOL_NAME {
agenda_item(request).map(|item| item.title)
} else if operation == DRIVER_MOUNT_OPERATION {
request.args_redacted.get("id").and_then(Value::as_str).map(str::to_string)
} else {
None
};
name.map(|name| name.trim().to_string()).filter(|name| !name.is_empty())
}
const KERNEL_TOOL_PREFIX: &str = "kernel:";
const DRIVER_MOUNT_OPERATION: &str = "driver.mount";
const WEEKDAYS: [(&str, &str, &str); 8] = [
("0", "SUN", "Sunday"),
("1", "MON", "Monday"),
("2", "TUE", "Tuesday"),
("3", "WED", "Wednesday"),
("4", "THU", "Thursday"),
("5", "FRI", "Friday"),
("6", "SAT", "Saturday"),
("7", "SUN", "Sunday"),
];
fn agenda_item(request: &ApprovalRequest) -> Option<AgendaItem> {
(request.tool_name == AGENDA_TOOL_NAME)
.then(|| serde_json::from_value(request.args_redacted.clone()).ok())
.flatten()
}
fn kernel_answer_words(request: &ApprovalRequest) -> Option<(&'static str, &'static str)> {
if request.tool_name != AGENDA_TOOL_NAME {
return None;
}
match agenda_item(request) {
Some(item) if item.origin.is_question() => Some((words::THATS_RIGHT, words::FORGET_IT)),
Some(_) | None => Some((words::DO_IT, words::NOT_NOW)),
}
}
fn sentence(text: &str) -> String {
let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
let mut chars = line.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => line,
}
}
fn primary_argument(args: &Value) -> Option<(&'static str, String)> {
const KEYS: [&str; 9] =
["to", "path", "file", "url", "command", "recipient", "name", "query", "title"];
let map = args.as_object()?;
KEYS.iter().find_map(|key| {
let value = map.get(*key)?.as_str()?.trim();
if value.is_empty() {
return None;
}
let mut short: String = value.chars().take(60).collect();
if value.chars().count() > 60 {
short.push('โฆ');
}
Some((*key, short))
})
}
pub(crate) fn spends_money(request: &ApprovalRequest) -> bool {
request.tool_name.starts_with("payments_")
}
pub(crate) fn reversibility(request: &ApprovalRequest) -> Reversibility {
let name = request.tool_name.to_lowercase();
let sends = ["send", "email", "mail", "message", "sms", "post", "reply", "notify", "publish"];
if sends.iter().any(|word| name.contains(word)) {
Reversibility::CantBeUnsent
} else {
Reversibility::CantBeUndone
}
}
fn describe_call(tool: &str, args: &Value) -> String {
let mut text = humanize(tool);
if let Some((key, value)) = primary_argument(args) {
text.push(' ');
if key == "to" {
text.push_str("to ");
}
text.push_str(&value);
}
text
}
fn response_failed(response: &Value) -> bool {
response.get("error").is_some()
|| response
.get("status")
.and_then(Value::as_str)
.is_some_and(|status| matches!(status, "error" | "failed" | "denied" | "not_run"))
}
pub(crate) fn humanize(name: &str) -> String {
let mut words: Vec<String> = Vec::new();
let mut current = String::new();
let mut previous_lower = false;
for c in name.chars() {
if matches!(c, '_' | '-' | ' ' | '.' | ':' | '/') {
if !current.is_empty() {
words.push(std::mem::take(&mut current));
}
previous_lower = false;
continue;
}
if c.is_uppercase() && previous_lower && !current.is_empty() {
words.push(std::mem::take(&mut current));
}
previous_lower = c.is_lowercase() || c.is_ascii_digit();
current.extend(c.to_lowercase());
}
if !current.is_empty() {
words.push(current);
}
let mut text = words.join(" ");
if let Some(first) = text.get(..1) {
let upper = first.to_uppercase();
text.replace_range(..1, &upper);
}
if text.is_empty() { name.to_string() } else { text }
}
fn avatar(display_name: &str) -> Avatar {
const COLORS: [&str; 8] =
["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];
let monogram: String = display_name
.chars()
.find(|c| c.is_alphanumeric())
.map(|c| c.to_uppercase().collect())
.unwrap_or_default();
let hash = display_name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
});
let index = usize::try_from(hash % COLORS.len() as u64).unwrap_or(0);
Avatar { monogram, color: COLORS[index].to_string() }
}
fn command_run(tool: &str, response: &serde_json::Value) -> Option<CommandRun> {
let object = response.as_object()?;
let has_output = object.contains_key("stdout") || object.contains_key("stderr");
let shell = object.contains_key("command") && object.contains_key("exit_code");
let sandbox = tool == "sandbox_exec" && (has_output || object.contains_key("status"));
if !(sandbox || shell && has_output) {
return None;
}
let string = |key: &str| object.get(key).and_then(serde_json::Value::as_str).unwrap_or("");
let stopped = match string("status") {
"timeout" => Some(RunStop::Timeout),
"memory_exceeded" => Some(RunStop::MemoryExceeded),
"policy_violation" => Some(RunStop::PolicyViolation),
"error" => Some(RunStop::Error),
_ => None,
};
let line = |text: &str, stderr: bool| OutputLine {
text: if text.chars().count() > RUN_LINE_CHARS {
format!("{}โฆ", text.chars().take(RUN_LINE_CHARS).collect::<String>())
} else {
text.to_string()
},
stderr,
};
let mut all: Vec<OutputLine> = string("stdout").lines().map(|text| line(text, false)).collect();
all.extend(string("stderr").lines().map(|text| line(text, true)));
let lines = u32::try_from(all.len()).unwrap_or(u32::MAX);
let output = all.split_off(all.len().saturating_sub(RUN_LINES));
let command = Some(string("command")).filter(|command| !command.is_empty());
Some(CommandRun {
command: command.map(|command| command.chars().take(CALL_TEXT_LIMIT).collect()),
language: object.get("language").and_then(serde_json::Value::as_str).map(str::to_string),
exit_code: object
.get("exit_code")
.and_then(serde_json::Value::as_i64)
.and_then(|code| i32::try_from(code).ok()),
duration_ms: object.get("duration_ms").and_then(serde_json::Value::as_u64),
output,
lines,
truncated: object.get("truncated").and_then(serde_json::Value::as_bool).unwrap_or(false),
stopped,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_long_line_is_cut_with_an_ellipsis_and_a_short_one_kept() {
assert_eq!(capped("Finance", CARD_NAME_LIMIT), "Finance");
let long = "x".repeat(CARD_NAME_LIMIT + 50);
let cut = capped(&long, CARD_NAME_LIMIT);
assert_eq!(cut.chars().count(), CARD_NAME_LIMIT);
assert!(cut.ends_with('โฆ'));
}
use adk_core::{ApprovalPolicy, ApprovalScope, ToolConfirmationRequest};
use chrono::{Duration, NaiveTime};
use serde_json::json;
fn time(hh: u32, mm: u32) -> NaiveTime {
NaiveTime::from_hms_opt(hh, mm, 0).unwrap()
}
fn minutes(minutes: i64) -> Duration {
Duration::minutes(minutes)
}
fn request(tool: &str, args: Value) -> ApprovalRequest {
let call = ToolConfirmationRequest {
tool_name: tool.into(),
function_call_id: Some("c1".into()),
args,
origin: None,
acting: None,
evidence: Vec::new(),
};
ApprovalRequest::new(
"apr_1",
ApprovalScope::new("app", "ana", "s1"),
&call,
ApprovalPolicy::new([]),
)
}
#[test]
fn headings_name_the_outcome() {
assert_eq!(
heading(&request("send_email", json!({ "to": "[client email]" }))),
"Send email to [client email]"
);
assert_eq!(
heading(&request("write_file", json!({ "path": "note.txt", "content": "x" }))),
"Write file note.txt"
);
assert_eq!(humanize("chiefOfStaff"), "Chief of staff");
}
fn agenda(item: &AgendaItem) -> ApprovalRequest {
let args = serde_json::to_value(item).unwrap();
let request = request(AGENDA_TOOL_NAME, args.clone())
.with_redacted_args(args)
.with_summary(format!("Agenda follow-up: {}", item.title));
if item.origin.is_question() {
request.with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject])
} else {
request.with_allowed_actions([
ApprovalAction::Approve,
ApprovalAction::Edit,
ApprovalAction::Reject,
])
}
}
fn item(title: &str, origin: AgendaOrigin) -> AgendaItem {
AgendaItem::new(
"item-1",
adk_core::principal::SubjectRef::human("ana"),
title,
"worth doing",
origin,
Utc.with_ymd_and_hms(2026, 10, 25, 7, 3, 0).unwrap(),
)
}
#[test]
fn kernel_decisions_read_in_plain_words() {
let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
projector.names.insert("app".into(), "Finance".into());
let now = Utc.with_ymd_and_hms(2026, 10, 25, 4, 3, 0).unwrap();
let agent = AgendaOrigin::Agent { pid: "run-7".into(), confidence: 1.0 };
let cron =
|expr: &str| Wake::Cron { expr: expr.into(), missed: adk_core::MissedFirePolicy::Skip };
let cases = [
(
item("check the news every 5 minutes", agent.clone())
.with_when(cron("*/5 * * * *")),
"Check the news every 5 minutes",
"Finance suggests this. Once you say yes, it runs every 5 minutes.",
),
(
item("Read the overnight mail", agent.clone()).with_when(cron("0 0 4 * * MON-FRI")),
"Read the overnight mail",
"Finance suggests this. Once you say yes, it runs every weekday at 07:00.",
),
(
item("Send the standup", agent.clone()).with_when(cron("0 6 * * 1-5")),
"Send the standup",
"Finance suggests this. Once you say yes, it runs every weekday at 09:00.",
),
(
item("Plan the week", agent.clone()).with_when(cron("0 6 * * 0")),
"Plan the week",
"Finance suggests this. Once you say yes, it runs every Sunday at 09:00.",
),
(
item("Sum the week", agent.clone()).with_when(cron("0 0 6 * * 1-5")),
"Sum the week",
"Finance suggests this. Once you say yes, it runs on the schedule 0 0 6 * * 1-5.",
),
(
item("Book the dentist", agent.clone())
.with_when(Wake::At(Utc.with_ymd_and_hms(2026, 10, 26, 6, 30, 0).unwrap())),
"Book the dentist",
"Finance suggests this. Once you say yes, it runs tomorrow at 09:30.",
),
(
item("Tidy the notes", AgendaOrigin::Consolidation),
"Tidy the notes",
"Your agents suggest this. Once you say yes, it runs right away.",
),
(
item(
"You prefer morning meetings",
AgendaOrigin::Observation { id: "obs-1".into() },
),
"You prefer morning meetings",
"Your agents noticed something. Is that right?",
),
(
item("Archive", agent).with_when(cron("15 3 1 * *")),
"Archive",
"Finance suggests this. Once you say yes, it runs on the schedule 15 3 1 * *.",
),
];
let me = Caller::human("ana", SurfaceKind::Web, crate::origin::Origin::Pointer);
for (item, heading, summary) in cases {
let card = projector.card(&agenda(&item), &me, None, None, now, &CardHint::new());
assert_eq!((card.heading.as_str(), card.summary.as_deref()), (heading, Some(summary)));
for text in [card.heading.as_str(), summary] {
assert!(!text.contains("kernel") && !text.contains('{'), "{text}");
}
let labels: Vec<&str> = card.allowed.options.iter().map(|o| o.label.as_str()).collect();
let expected: &[&str] = if item.origin.is_question() {
&["That's right", "Forget it"]
} else {
&["Do it", "Edit", "Not now"]
};
assert_eq!(labels, expected, "{heading}");
}
let mount = request(
"kernel:driver.mount",
json!({ "id": "email", "commandLine": "mcp-email --inbox", "partitions": ["default"] }),
);
assert_eq!(heading(&mount), "Start email for your agents");
assert_eq!(
projector.kernel_summary(&mount, now).as_deref(),
Some("It runs mcp-email --inbox on the computer your agents run on.")
);
let other = request("kernel:quota.raise", json!({ "partition": "default" }));
assert_eq!(
(heading(&other), projector.kernel_summary(&other, now)),
("Quota raise".to_string(), None)
);
let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
assert_eq!(heading(&unreadable), "Suggestion");
assert_eq!(chat_heading(&unreadable), "Suggestion");
}
#[test]
fn a_kernel_decision_is_named_by_what_it_is_about() {
let added = request(
adk_kernel::agents::AGENT_CREATE_TOOL_NAME,
json!({ "name": "finance", "displayName": "Finance" }),
);
let mount = request("kernel:driver.mount", json!({ "id": "email" }));
let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
let other = request("kernel:quota.raise", json!({ "partition": "default" }));
let call = request("write_file", json!({ "path": "notes.md" }));
assert_eq!(
[&added, &mount, &unreadable, &other, &call].map(kernel_name),
[Some("Finance".to_string()), Some("email".to_string()), None, None, None]
);
}
#[test]
fn long_calls_are_truncated_and_flagged() {
let long = request("write_file", json!({ "content": "x".repeat(5_000) }));
let view = call_view(&long);
assert!(view.truncated);
assert!(view.text.chars().count() <= CALL_TEXT_LIMIT + 1);
assert!(!call_view(&request("write_file", json!({ "path": "a" }))).truncated);
}
#[test]
fn quiet_time_in_the_timeline() {
let mut projector = Projector::new(FixedOffset::east_opt(0).unwrap());
projector.quiet = Some(QuietHours::new(time(22, 0), time(7, 0)).with_utc_offset_minutes(0));
let asked = Utc.with_ymd_and_hms(2026, 10, 23, 18, 0, 0).unwrap();
assert!(!projector.waited_through_quiet(asked, asked + minutes(60)));
assert!(projector.waited_through_quiet(asked, asked + minutes(13 * 60 + 30)));
let view = projector.quiet_view(asked).unwrap();
assert_eq!(view.text, "Quiet from 22:00");
assert_eq!(
projector.quiet_view(asked + minutes(6 * 60)).unwrap().text,
"Quiet until 07:00"
);
}
#[test]
fn a_failed_turn_says_who_could_not_answer_and_why() {
let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
let failed = |error: Option<&str>| {
projector.turn_failed(&TurnFailure {
agent: "claims_desk".into(),
at: Utc::now(),
error: error.map(str::to_string),
})
};
let item = |reason: Option<&str>, code: Option<&str>| ThreadItem::TurnFailed {
text: "Claims desk couldn't answer".into(),
reason: reason.map(str::to_string),
code: code.map(str::to_string),
};
assert_eq!(
failed(Some("model.internal: no recorded answer for turn 3")),
item(Some("no recorded answer for turn 3"), Some("model.internal"))
);
assert_eq!(
failed(Some("Upstream said: try later")),
item(Some("Upstream said: try later"), None)
);
assert_eq!(failed(Some(" ")), item(None, None));
assert_eq!(failed(None), item(None, None));
let long = format!("model.unavailable: {}", "x".repeat(REASON_CHARS + 20));
let ThreadItem::TurnFailed { reason: Some(reason), .. } = failed(Some(&long)) else {
panic!("a reason");
};
assert_eq!(reason.chars().count(), REASON_CHARS + 1);
assert!(reason.ends_with('โฆ'));
}
#[test]
fn agent_rows_say_what_each_agent_is_doing() {
let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
let state = |state, waiting_on_decision, wake_at, suspended| AgentState {
name: "chief_of_staff".into(),
session_id: None,
state,
waiting_on_decision,
wake_at,
suspended,
subagent: None,
shell: None,
};
let seven = Some(Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap());
let words = |row: AgentRow| (row.agent.display_name, row.status_text);
assert_eq!(
words(projector.agent_row(&state(RunState::Running, false, None, false))),
("Chief of staff".into(), "Working".into())
);
assert_eq!(
projector.agent_row(&state(RunState::Waiting, true, None, false)).status_text,
"Waiting for you"
);
assert_eq!(
projector.agent_row(&state(RunState::Waiting, false, seven, false)).status_text,
"Asleep until 07:00"
);
assert_eq!(
projector.agent_row(&state(RunState::Waiting, false, seven, true)).status_text,
"Asleep"
);
assert_eq!(
projector.agent_row(&state(RunState::Completed, false, None, false)).status_text,
"Done"
);
assert_eq!(
projector.agent_row(&state(RunState::Failed, false, None, false)).status_text,
"Failed"
);
let mut alpha = state(RunState::Waiting, true, None, false);
alpha.subagent = Some("alpha".into());
assert_eq!(
projector.agent_row(&alpha).status_text,
"Waiting for you ยท sub-agent alpha",
"a background sub-agent's row names it"
);
}
#[test]
fn briefing_lines_come_from_ledger_rows() {
let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
projector.names.insert("adk-rust".into(), "ADK-Rust".into());
let row = |kind: &str, agent: &str, effect: Option<&str>| -> LedgerEntry {
serde_json::from_value(json!({
"seq": 7,
"ts": "2026-10-23T23:05:00+03:00",
"partition": "default",
"agent": agent,
"kind": kind,
"effect": effect,
}))
.unwrap()
};
let line = projector.briefing_line(&row("proposal", "kernel", Some("proposed"))).unwrap();
assert_eq!(
(line.at_text.as_str(), line.pill_text.as_deref(), line.seq),
("23:05", Some("Suggestion"), 7)
);
assert_eq!(line.text, "Your agents suggest something. Nothing happens until you say so.");
let agent = "urn:adk:agent:adk-rust/adk-rust";
let decided = projector.briefing_line(&row("decided", agent, Some("approve"))).unwrap();
assert_eq!(
(decided.pill_text.as_deref(), decided.text.as_str()),
(Some("You decided"), "You allowed ADK-Rust to go ahead.")
);
let said_no = projector.briefing_line(&row("rejection", agent, None)).unwrap();
assert_eq!(said_no.text, "You said no to ADK-Rust.");
let question = projector.briefing_line(&row("observation", "kernel", None)).unwrap();
assert_eq!(question.text, "Your agents noticed something. Is that right?");
for (kind, agent, effect) in [
("wake", "kernel", Some("woke")),
("process", "kernel", Some("completed")),
("process", agent, Some("running")),
("spend", agent, None),
("intent", agent, None),
("tool_call", agent, None),
("proposal", "kernel", Some("running")),
] {
assert_eq!(
projector.briefing_line(&row(kind, agent, effect)),
None,
"{kind} {effect:?}"
);
}
}
}