Skip to main content

adk_surface/
project.rs

1//! Projection: inbox entries, session events, process states and ledger rows become cards,
2//! thread items, agent rows, status and briefing lines, once, in Rust (spec 3.3 §6, §7.1, §8).
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::fmt;
6use std::sync::Arc;
7
8use adk_core::{
9    ApprovalAction, ApprovalRequest, ApprovalState, Event, Part, RunState, ToolConfirmationRequest,
10};
11use adk_harness::HarnessMode;
12use adk_harness::take_over::TAKE_OVER_TOOL;
13use adk_kernel::control::api::{AwayKind, AwayLine};
14use adk_kernel::proc::{KERNEL_AGENT, LedgerEntry};
15use adk_kernel::{AGENDA_TOOL_NAME, AgendaItem, AgendaOrigin, QuietHours, Wake};
16use chrono::{DateTime, FixedOffset, TimeZone, Utc};
17use serde_json::Value;
18
19use crate::answers::AnswerRecord;
20use crate::hints::CardHint;
21use crate::model::{
22    AgentRef, AgentRow, AgentStatus, Avatar, BriefingLine, CallView, CardStatus, CommandRun,
23    Decided, DecidedAnswer, DecisionCard, ElicitationView, ElicitedField, ElicitedKind,
24    ElicitedOption, FeedEntry, Mode, ModeView, OutputLine, Pill, QuietView, Reversibility, RunStop,
25    ShellView, Speaker, SpendView, ThreadItem, TimelineStep,
26};
27use crate::origin::{Caller, SurfaceKind};
28use crate::rules::{self, Answer, DecisionFacts};
29use crate::source::{AgentState, SpendToday, TurnFailure};
30use crate::words::{self, SaidWhat};
31
32/// How long a call's text may be before it is shown truncated (spec 3.3 §7.1).
33pub const CALL_TEXT_LIMIT: usize = 2_000;
34
35/// The most lines of a run's output a thread shows: its last ones (spec 3.3 §5.1).
36pub const RUN_LINES: usize = 40;
37
38/// The most characters of one output line a thread shows.
39const RUN_LINE_CHARS: usize = 400;
40
41/// The most characters of a failed turn's reason a thread shows.
42const REASON_CHARS: usize = 500;
43
44/// The longest agent name a decision card shows, in characters.
45pub const CARD_NAME_LIMIT: usize = 64;
46/// The longest heading a decision card shows, in characters.
47pub const CARD_HEADING_LIMIT: usize = 160;
48/// The longest summary, step, detail or "also shown" line a decision card shows.
49pub const CARD_LINE_LIMIT: usize = 280;
50
51/// The most fields of an MCP elicitation form a card draws; a longer form is refused there.
52const ELICITED_FIELDS_LIMIT: usize = 24;
53/// The most options of an elicitation field a card draws.
54const ELICITED_OPTIONS_LIMIT: usize = 50;
55
56/// The server of a decision a harness parked for an MCP elicitation
57/// (`mcp:{server}/elicitation`).
58pub(crate) fn elicitation_server(tool: &str) -> Option<&str> {
59    tool.strip_prefix("mcp:")?.strip_suffix("/elicitation")
60}
61
62/// What an MCP server asks in `request`, for the home to draw in its own controls: a form
63/// when every field is one the home draws (text, email, web address, date, number, yes or no,
64/// a choice), the page of a URL elicitation, `None` otherwise (the card then offers Deny).
65pub(crate) fn elicitation_of(request: &ApprovalRequest) -> Option<ElicitationView> {
66    let server = capped(elicitation_server(&request.tool_name)?, CARD_NAME_LIMIT);
67    let shown = &request.args_redacted;
68    let message = capped(shown.get("message").and_then(Value::as_str)?, CARD_LINE_LIMIT);
69    if let Some(url) = shown.get("url").and_then(Value::as_str) {
70        let (host, warning) = address_parts(url)?;
71        return Some(ElicitationView::Url {
72            server,
73            message,
74            url: url.to_string(),
75            host,
76            warning: warning.map(str::to_string),
77        });
78    }
79    let schema = shown.get("schema")?;
80    let properties = schema.get("properties")?.as_object()?;
81    if properties.len() > ELICITED_FIELDS_LIMIT {
82        return None;
83    }
84    let required: Vec<&str> = schema
85        .get("required")
86        .and_then(Value::as_array)
87        .map(|names| names.iter().filter_map(Value::as_str).collect())
88        .unwrap_or_default();
89    let fields = properties
90        .iter()
91        .map(|(name, property)| elicited_field(name, property, required.contains(&name.as_str())))
92        .collect::<Option<Vec<_>>>()?;
93    Some(ElicitationView::Form { server, message, fields })
94}
95
96/// One field of an elicitation schema, or `None` for a kind the home does not draw.
97fn elicited_field(name: &str, property: &Value, required: bool) -> Option<ElicitedField> {
98    let text = |key: &str| property.get(key).and_then(Value::as_str);
99    let mut options = Vec::new();
100    if let Some(values) = property.get("enum").and_then(Value::as_array) {
101        let names = property.get("enumNames").and_then(Value::as_array);
102        for (index, value) in values.iter().enumerate() {
103            let value = value.as_str()?;
104            let label = names.and_then(|names| names.get(index)).and_then(Value::as_str);
105            options.push((value, label.unwrap_or(value)));
106        }
107    } else if let Some(choices) =
108        property.get("oneOf").or_else(|| property.get("anyOf")).and_then(Value::as_array)
109    {
110        for choice in choices {
111            let value = choice.get("const").and_then(Value::as_str)?;
112            let label = choice.get("title").and_then(Value::as_str).unwrap_or(value);
113            options.push((value, label));
114        }
115    }
116    if options.len() > ELICITED_OPTIONS_LIMIT {
117        return None;
118    }
119    let kind = if options.is_empty() {
120        match text("type")? {
121            "string" => match text("format") {
122                Some("email") => ElicitedKind::Email,
123                Some("uri") => ElicitedKind::Url,
124                Some("date") => ElicitedKind::Date,
125                Some("date-time") => ElicitedKind::DateTime,
126                _ => ElicitedKind::Text,
127            },
128            "number" => ElicitedKind::Number,
129            "integer" => ElicitedKind::Integer,
130            "boolean" => ElicitedKind::Boolean,
131            _ => return None,
132        }
133    } else {
134        ElicitedKind::Choice
135    };
136    let default = property.get("default").filter(|value| !value.is_object() && !value.is_array());
137    Some(ElicitedField {
138        name: name.to_string(),
139        label: capped(text("title").unwrap_or(name), CARD_NAME_LIMIT),
140        description: text("description").map(|description| capped(description, CARD_LINE_LIMIT)),
141        kind,
142        required,
143        default: default.cloned(),
144        options: options
145            .into_iter()
146            .map(|(value, label)| ElicitedOption {
147                value: value.to_string(),
148                label: capped(label, CARD_NAME_LIMIT),
149            })
150            .collect(),
151        minimum: property.get("minimum").and_then(Value::as_f64),
152        maximum: property.get("maximum").and_then(Value::as_f64),
153        min_length: property.get("minLength").and_then(Value::as_u64),
154        max_length: property.get("maxLength").and_then(Value::as_u64),
155    })
156}
157
158/// Checks the person's answer to an elicitation form against the fields the card drew: an
159/// object of those fields only, every required one present, each of its kind, a choice one of
160/// its options, numbers and lengths within bounds. The harness checks it again against the
161/// server's schema before the server sees it.
162pub(crate) fn check_answer(fields: &[ElicitedField], content: &Value) -> Result<(), String> {
163    let answer = content.as_object().ok_or("the answer is an object of the form's fields")?;
164    if let Some(unknown) = answer.keys().find(|key| !fields.iter().any(|f| &f.name == *key)) {
165        return Err(format!("{unknown} is not a field of the form"));
166    }
167    for field in fields {
168        let Some(value) = answer.get(&field.name) else {
169            if field.required {
170                return Err(format!("{} is required", field.label));
171            }
172            continue;
173        };
174        let fits = match field.kind {
175            ElicitedKind::Number => value.is_number(),
176            ElicitedKind::Integer => value.is_i64() || value.is_u64(),
177            ElicitedKind::Boolean => value.is_boolean(),
178            ElicitedKind::Choice => value
179                .as_str()
180                .is_some_and(|picked| field.options.iter().any(|option| option.value == picked)),
181            _ => value.is_string(),
182        };
183        if !fits {
184            return Err(format!("{} does not take {value}", field.label));
185        }
186        if let Some(number) = value.as_f64()
187            && (field.minimum.is_some_and(|min| number < min)
188                || field.maximum.is_some_and(|max| number > max))
189        {
190            return Err(format!("{} is out of its range", field.label));
191        }
192        if let Some(text) = value.as_str() {
193            let length = text.chars().count() as u64;
194            if field.min_length.is_some_and(|min| length < min)
195                || field.max_length.is_some_and(|max| length > max)
196            {
197                return Err(format!("{} is too short or too long", field.label));
198            }
199        }
200    }
201    Ok(())
202}
203
204/// The host of `url`, lowercased, and why to look twice at it: look-alike characters
205/// (punycode or non-ASCII), a name hidden before an `@`, or no encryption.
206fn address_parts(url: &str) -> Option<(String, Option<&'static str>)> {
207    let (scheme, rest) = url.split_once("://")?;
208    let authority = rest.split(['/', '?', '#']).next()?;
209    let (userinfo, host_port) = match authority.rsplit_once('@') {
210        Some((userinfo, host_port)) => (Some(userinfo), host_port),
211        None => (None, authority),
212    };
213    let host = match host_port.strip_prefix('[') {
214        Some(bracketed) => bracketed.split(']').next()?,
215        None => host_port.split(':').next()?,
216    }
217    .to_lowercase();
218    if host.is_empty() {
219        return None;
220    }
221    let warning = if !host.is_ascii() || host.split('.').any(|label| label.starts_with("xn--")) {
222        Some(words::LOOK_ALIKE_ADDRESS)
223    } else if userinfo.is_some() {
224        Some(words::HIDDEN_HOST_ADDRESS)
225    } else if scheme.eq_ignore_ascii_case("http") {
226        Some(words::UNENCRYPTED_ADDRESS)
227    } else {
228        None
229    };
230    Some((host, warning))
231}
232
233/// `text` cut to `limit` characters, with an ellipsis when cut.
234pub(crate) fn capped(text: &str, limit: usize) -> String {
235    if text.chars().count() <= limit {
236        return text.to_string();
237    }
238    let mut cut: String = text.chars().take(limit.saturating_sub(1)).collect();
239    cut.push('…');
240    cut
241}
242
243/// Somewhere a decision is also shown, for "Also on your phone and in Telegram"
244/// (spec 3.3 §7.1).
245///
246/// # Example
247///
248/// ```rust
249/// use adk_surface::Place;
250///
251/// assert_eq!(Place::chat("Telegram").phrase, "in Telegram");
252/// assert_eq!(Place::phone().phrase, "on your phone");
253/// ```
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct Place {
256    /// The surface.
257    pub surface: SurfaceKind,
258    /// The place in words: "on your phone", "in Telegram".
259    pub phrase: String,
260}
261
262impl Place {
263    /// The web home.
264    pub fn web() -> Self {
265        Self { surface: SurfaceKind::Web, phrase: words::IN_THE_HOME_APP.to_string() }
266    }
267
268    /// The phone.
269    pub fn phone() -> Self {
270        Self { surface: SurfaceKind::Phone, phrase: words::ON_YOUR_PHONE.to_string() }
271    }
272
273    /// The terminal.
274    pub fn terminal() -> Self {
275        Self { surface: SurfaceKind::Terminal, phrase: words::IN_THE_TERMINAL.to_string() }
276    }
277
278    /// The desktop tray.
279    pub fn tray() -> Self {
280        Self { surface: SurfaceKind::Tray, phrase: words::FROM_THE_TRAY.to_string() }
281    }
282
283    /// A chat channel.
284    pub fn chat(channel: &str) -> Self {
285        Self { surface: SurfaceKind::Chat, phrase: words::in_channel(channel) }
286    }
287}
288
289type Classify<T> = Arc<dyn Fn(&ApprovalRequest) -> T + Send + Sync>;
290
291/// What the engine needs to project: the person's time zone, quiet time, where decisions are
292/// shown, and how calls are read.
293#[derive(Clone)]
294pub(crate) struct Projector {
295    pub(crate) offset: FixedOffset,
296    pub(crate) quiet: Option<QuietHours>,
297    pub(crate) places: Vec<Place>,
298    pub(crate) names: BTreeMap<String, String>,
299    pub(crate) heading: Classify<String>,
300    pub(crate) money: Classify<bool>,
301    /// Whether the source rates a call high risk whatever the request says (spec 3.2 K-I9).
302    pub(crate) rates_high: Classify<bool>,
303    pub(crate) reversibility: Classify<Reversibility>,
304    /// The engine's cancel window for a spoken "allow once", in whole seconds, which a voice
305    /// card advertises.
306    pub(crate) voice_window_secs: u32,
307    /// The catalogs drawings are shown in: `forms` and every registered extension catalog
308    /// (spec 3.3 §6.1 `genui`).
309    #[cfg(feature = "genui")]
310    pub(crate) catalogs: crate::genui::Catalogs,
311}
312
313impl fmt::Debug for Projector {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        f.debug_struct("Projector")
316            .field("offset", &self.offset)
317            .field("quiet", &self.quiet)
318            .field("places", &self.places)
319            .finish_non_exhaustive()
320    }
321}
322
323impl Projector {
324    pub(crate) fn new(offset: FixedOffset) -> Self {
325        Self {
326            offset,
327            quiet: None,
328            places: Vec::new(),
329            names: BTreeMap::new(),
330            heading: Arc::new(heading),
331            money: Arc::new(spends_money),
332            rates_high: Arc::new(|_| false),
333            reversibility: Arc::new(reversibility),
334            voice_window_secs: rules::VOICE_CANCEL_WINDOW_SECS,
335            #[cfg(feature = "genui")]
336            catalogs: crate::genui::Catalogs::forms(),
337        }
338    }
339
340    /// `at` as local `HH:MM`.
341    pub(crate) fn hh_mm(&self, at: DateTime<Utc>) -> String {
342        at.with_timezone(&self.offset).format("%H:%M").to_string()
343    }
344
345    pub(crate) fn agent(&self, name: &str) -> AgentRef {
346        let display_name = self.names.get(name).cloned().unwrap_or_else(|| humanize(name));
347        AgentRef { name: name.to_string(), avatar: avatar(&display_name), display_name }
348    }
349
350    /// The agent a suggestion would add, as its card shows it (spec 3.3 §5.7): `None` for
351    /// every other request.
352    pub(crate) fn adds_agent(
353        &self,
354        request: &ApprovalRequest,
355    ) -> Option<crate::agents::AgentCardView> {
356        if request.tool_name != adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
357            return None;
358        }
359        let suggester = self.agent(&agent_name(request)).display_name;
360        let area = request.args_redacted.get("area").and_then(Value::as_str).unwrap_or_default();
361        crate::agents::AgentCardView::of_request(
362            request,
363            &suggester,
364            &crate::agents::area_name(area),
365        )
366    }
367
368    /// The facts the §7.2 rules read. A feature's `hint` may only make them stricter: mark
369    /// money or take **Always allow** away, never add an answer or change the risk
370    /// (spec 3.3 §7.1, §7.2).
371    pub(crate) fn facts(
372        &self,
373        request: &ApprovalRequest,
374        always_label: Option<String>,
375        hint: &CardHint,
376    ) -> DecisionFacts {
377        // A suggested agent is added or not, never always or edited (spec 3.3 §7.2); long
378        // instructions are expanded before it is added, as a long call is (S-I13).
379        if let Some(agent) = self.adds_agent(request) {
380            let assessed = adk_kernel::agents::AgentRecord::new(
381                String::new(),
382                agent.draft.clone().into_definition(),
383                adk_kernel::agents::AgentRecordState::Proposed,
384                adk_kernel::agents::AgentOrigin::ByHand,
385                adk_core::principal::SubjectRef::human(&request.scope.user_id),
386                request.created_at,
387            );
388            return DecisionFacts {
389                risk: request.risk.into(),
390                money: adk_harness::assess_agent(&assessed).money || hint.marks_money(),
391                truncated: agent.instructions_truncated,
392                allows: request
393                    .allowed_actions
394                    .iter()
395                    .copied()
396                    .filter(|action| {
397                        matches!(action, ApprovalAction::Approve | ApprovalAction::Reject)
398                    })
399                    .collect(),
400                always_label: None,
401                adds_agent: true,
402                image: None,
403                plan: false,
404            };
405        }
406        // Edit replaces the call's arguments with what the surface sends back, so it is
407        // offered only where the card shows those arguments (spec 3.3 §7.2): never over a
408        // redacted view or an elicitation's form, which would be submitted as written. A take
409        // over is answered with the secret the person types, or refused (§8.2, §10 H2).
410        let own_args = shows_own_arguments(request);
411        let take_over = request.tool_name == TAKE_OVER_TOOL;
412        let answers_a_form = matches!(elicitation_of(request), Some(ElicitationView::Form { .. }));
413        let risk = if (self.rates_high)(request) {
414            request.risk.max(adk_core::ApprovalRisk::High)
415        } else {
416            request.risk
417        };
418        DecisionFacts {
419            risk: risk.into(),
420            money: (self.money)(request) || hint.marks_money(),
421            truncated: call_view(request).truncated,
422            allows: request
423                .allowed_actions
424                .iter()
425                .copied()
426                .filter(|action| match action {
427                    ApprovalAction::Reject => true,
428                    // An elicitation form is answered with the person's own values, drawn
429                    // in the home's fields and checked against the server's schema.
430                    ApprovalAction::Edit => (own_args || answers_a_form) && !take_over,
431                    ApprovalAction::Approve | ApprovalAction::Respond => !take_over,
432                })
433                .collect(),
434            always_label: always_label.filter(|_| !take_over && !hint.removes_always()),
435            adds_agent: false,
436            image: None,
437            plan: false,
438        }
439    }
440
441    pub(crate) fn decided(
442        &self,
443        request: &ApprovalRequest,
444        caller: &Caller,
445        answer: Option<&AnswerRecord>,
446    ) -> Option<Decided> {
447        if request.state == ApprovalState::Pending {
448            return None;
449        }
450        let last = request.decisions.last();
451        let answer_kind = match request.state {
452            ApprovalState::Approved => match last.map(|decision| decision.kind) {
453                Some(ApprovalAction::Edit) => DecidedAnswer::Edited,
454                _ => DecidedAnswer::Yes,
455            },
456            ApprovalState::Rejected => DecidedAnswer::No,
457            ApprovalState::Responded => DecidedAnswer::Replied,
458            ApprovalState::Pending | ApprovalState::Expired | ApprovalState::Cancelled => {
459                DecidedAnswer::Ended
460            }
461        };
462        let at = last
463            .map(|decision| decision.decided_at)
464            .or(request.resolved_at)
465            .unwrap_or(request.created_at);
466        let at_text = self.hh_mm(at);
467        let approver = last.filter(|_| answer_kind != DecidedAnswer::Ended);
468        let by_you = approver.is_some_and(|decision| decision.approver.id == caller.user_id());
469        let by = match approver {
470            Some(_) if by_you => "You".to_string(),
471            Some(decision) => decision.approver.id.clone(),
472            None => String::new(),
473        };
474        let via = answer
475            .filter(|record| {
476                record.approval_id == request.id
477                    && approver.is_some_and(|decision| decision.approver == record.by)
478            })
479            .map(|record| record.via.clone());
480        let said = match answer_kind {
481            DecidedAnswer::Yes => Some(SaidWhat::Yes),
482            DecidedAnswer::No => Some(SaidWhat::No),
483            DecidedAnswer::Edited => Some(SaidWhat::Edited),
484            DecidedAnswer::Replied => Some(SaidWhat::Replied),
485            DecidedAnswer::Ended | DecidedAnswer::Unknown => None,
486        };
487        let text = match said {
488            Some(what) => {
489                let phrase = via.as_ref().map(crate::origin::Via::phrase);
490                words::said((!by_you).then_some(by.as_str()), what, phrase.as_deref(), &at_text)
491            }
492            None => words::ENDED_WITHOUT_AN_ANSWER.to_string(),
493        };
494        Some(Decided { by, by_you, via, at, at_text, answer: answer_kind, text, scope_text: None })
495    }
496
497    /// The card of `request` as `caller` sees it (spec 3.3 §7.1), with a feature's `hint`
498    /// ahead of the engine's own headings and reversibility.
499    pub(crate) fn card(
500        &self,
501        request: &ApprovalRequest,
502        caller: &Caller,
503        always_label: Option<String>,
504        answer: Option<&AnswerRecord>,
505        now: DateTime<Utc>,
506        hint: &CardHint,
507    ) -> DecisionCard {
508        let facts = self.facts(request, always_label, hint);
509        let chat = rules::row(caller) == rules::Row::Chat;
510        // A chat card leaves the machine through someone else's servers: it carries the
511        // agent, the risk and a short summary, never the call's arguments (S-I5).
512        let (heading, summary, call) = if chat {
513            let full = call_view(request);
514            let call = CallView {
515                tool: full.tool.clone(),
516                args: Value::Null,
517                text: full.tool,
518                truncated: full.truncated,
519            };
520            let heading = hint.chat_heading.clone().unwrap_or_else(|| chat_heading(request));
521            (heading, None, call)
522        } else {
523            // What an MCP server asks reads as its question ("MCP server billing asks: …"),
524            // the summary the harness wrote, not as the tool name it was parked under.
525            let asked = elicitation_server(&request.tool_name)
526                .map(|_| request.summary.trim())
527                .filter(|summary| !summary.is_empty())
528                .map(str::to_string);
529            let heading = hint.heading.clone().or(asked).unwrap_or_else(|| (self.heading)(request));
530            (heading, self.kernel_summary(request, now), call_view(request))
531        };
532        let decided = self.decided(request, caller, answer);
533        let mut allowed = rules::allowed_answers(caller, &facts);
534        // The window the engine waits, not the default, so a voice renderer counts down the
535        // time the answer can really still be cancelled.
536        if allowed.cancel_window_secs.is_some() {
537            allowed.cancel_window_secs = Some(self.voice_window_secs);
538        }
539        // A suggestion is done or left for now, a question confirmed or forgotten (§8.1).
540        if let Some((yes, no)) = kernel_answer_words(request) {
541            for option in &mut allowed.options {
542                match option.answer {
543                    Answer::AllowOnce if !option.needs_presence => option.label = yes.to_string(),
544                    Answer::Deny => option.label = no.to_string(),
545                    Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => {}
546                }
547            }
548        }
549        // What an MCP server asks is drawn in the home's own fields; Edit sends the answer.
550        let elicitation = if chat { None } else { elicitation_of(request) };
551        if matches!(elicitation, Some(ElicitationView::Form { .. })) {
552            for option in &mut allowed.options {
553                if option.answer == Answer::Edit {
554                    option.label = words::ANSWER.to_string();
555                }
556            }
557        }
558        if decided.is_some() {
559            allowed.options.clear();
560            allowed.open_in_home = false;
561            allowed.cancel_window_secs = None;
562            allowed.note = None;
563        }
564        let since = self.hh_mm(request.created_at);
565        let mut timeline: Vec<String> = hint.first_step.iter().cloned().collect();
566        timeline.push(words::asked_at(&since));
567        let until = decided.as_ref().map_or(now, |decided| decided.at);
568        if self.waited_through_quiet(request.created_at, until) {
569            timeline.push(words::WAITED_THROUGH_QUIET_TIME.to_string());
570        }
571        timeline.push(match &decided {
572            Some(decided) => decided.text.clone(),
573            None => words::WAITING_FOR_YOU.to_string(),
574        });
575        let last = timeline.len() - 1;
576        let timeline = timeline
577            .into_iter()
578            .enumerate()
579            .map(|(index, text)| TimelineStep { text, current: index == last })
580            .collect();
581        let adds_agent = self.adds_agent(request);
582        let reversibility = match adds_agent {
583            Some(_) => Reversibility::CanBeRemoved,
584            None => hint.reversibility.unwrap_or_else(|| (self.reversibility)(request)),
585        };
586        let also: Vec<String> = self
587            .places
588            .iter()
589            .filter(|place| place.surface != caller.surface)
590            .map(|place| place.phrase.clone())
591            .collect();
592        let (status, status_text) = match decided {
593            Some(_) => (CardStatus::Decided, words::DECIDED),
594            None => (CardStatus::Waiting, words::WAITING_FOR_YOU),
595        };
596        let mut card = DecisionCard {
597            id: request.id.clone(),
598            version: request.version,
599            session_id: request.scope.session_id.clone(),
600            agent: self.agent(&agent_name(request)),
601            waiting_since: request.created_at,
602            since_text: words::since(&since),
603            status,
604            status_text: status_text.to_string(),
605            heading,
606            summary,
607            call,
608            timeline,
609            allowed,
610            risk: facts.risk,
611            risk_text: facts.risk.words().to_string(),
612            reversibility,
613            reversibility_text: match reversibility {
614                Reversibility::CantBeUnsent => words::CANT_BE_UNSENT,
615                Reversibility::CantBeUndone => words::CANT_BE_UNDONE,
616                Reversibility::CanBeRemoved => crate::agents::words::YOU_CAN_REMOVE_IT_LATER,
617                Reversibility::CanBeChangedBack => words::YOU_CAN_CHANGE_IT_BACK,
618            }
619            .to_string(),
620            money: facts.money,
621            also_shown: words::also_shown(&also),
622            decided,
623            adds_agent,
624            // Like the summary, never on a chat card (S-I5).
625            detail: hint.detail.clone().filter(|_| !chat),
626            elicitation,
627            media: None,
628            parked: None,
629            plan: None,
630        };
631        // Every line of the card fits: nothing a name or a hint carries can push the call and
632        // its answers out of sight, or pass a long text off as the home's own words.
633        card.agent.display_name = capped(&card.agent.display_name, CARD_NAME_LIMIT);
634        card.heading = capped(&card.heading, CARD_HEADING_LIMIT);
635        card.summary = card.summary.map(|summary| capped(&summary, CARD_LINE_LIMIT));
636        for step in &mut card.timeline {
637            step.text = capped(&step.text, CARD_LINE_LIMIT);
638        }
639        card.also_shown = card.also_shown.map(|also| capped(&also, CARD_LINE_LIMIT));
640        if let Some(detail) = &mut card.detail {
641            detail.text = capped(&detail.text, CARD_LINE_LIMIT);
642        }
643        card
644    }
645
646    /// What a decision the kernel itself asks means for the person, beyond its heading: who
647    /// suggests an agenda item and when it runs once allowed, what a driver mount starts
648    /// (spec 3.3 §7.1, §8.1). `None` for every other call, whose heading says it all.
649    pub(crate) fn kernel_summary(
650        &self,
651        request: &ApprovalRequest,
652        now: DateTime<Utc>,
653    ) -> Option<String> {
654        let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
655        if request.tool_name == AGENDA_TOOL_NAME {
656            let Some(item) = agenda_item(request) else {
657                return Some(words::AGENTS_SUGGEST.to_string());
658            };
659            if item.origin.is_question() {
660                return Some(words::NOTICED_SOMETHING.to_string());
661            }
662            let who = match &item.origin {
663                AgendaOrigin::User => words::YOU_SUGGESTED_THIS.to_string(),
664                AgendaOrigin::Agent { .. } => {
665                    words::suggested_by(Some(&self.agent(&agent_name(request)).display_name))
666                }
667                // Consolidation, and any origin a later kernel adds: the kernel's own work.
668                _ => words::suggested_by(None),
669            };
670            let when = match &item.when {
671                Some(wake) => self.wake_words(wake, now),
672                None => words::RIGHT_AWAY.to_string(),
673            };
674            let mut text = format!("{who} {}", words::once_you_say_yes(&when));
675            if let Some(steps) = item.plan.as_ref().map(|plan| plan.steps.len()).filter(|n| *n > 0)
676            {
677                text.push(' ');
678                text.push_str(&words::plan_of(steps));
679            }
680            if let Some(cap) = item.budget.as_ref().and_then(|budget| budget.max_cost_micro_usd) {
681                text.push(' ');
682                text.push_str(&words::may_spend(cap));
683            }
684            return Some(text);
685        }
686        if operation != DRIVER_MOUNT_OPERATION {
687            return None;
688        }
689        request.args_redacted.get("commandLine").and_then(Value::as_str).map(words::driver_starts)
690    }
691
692    /// When a wake fires, in words, after "it runs": "every 5 minutes", "at 07:30".
693    fn wake_words(&self, wake: &Wake, now: DateTime<Utc>) -> String {
694        match wake {
695            Wake::At(at) if *at <= now => words::RIGHT_AWAY.to_string(),
696            Wake::At(at) => {
697                let local = at.with_timezone(&self.offset);
698                let today = now.with_timezone(&self.offset).date_naive();
699                let time = local.format("%H:%M");
700                if local.date_naive() == today {
701                    format!("at {time}")
702                } else if today.succ_opt() == Some(local.date_naive()) {
703                    format!("tomorrow at {time}")
704                } else {
705                    format!("on {} at {time}", local.format("%a %-d %b"))
706                }
707            }
708            Wake::Cron { expr, .. } => self.cron_words(expr, now),
709            Wake::FileChange { root, glob, .. } => {
710                format!("when a file matching {glob} changes in {}", root.display())
711            }
712            Wake::Webhook { hook } => format!("when {hook} calls in"),
713            Wake::Queue { source } => format!("when a message arrives from {source}"),
714            Wake::Approval { .. } => "once a decision it waits on is answered".to_string(),
715            Wake::RunFinished { .. } => "after another of your agents' tasks finishes".to_string(),
716            Wake::BudgetReplenished { .. } => "once the day's budget allows it".to_string(),
717            Wake::Manual => "when you start it".to_string(),
718            // A wake a later kernel adds.
719            _ => "later".to_string(),
720        }
721    }
722
723    /// A cron schedule (UTC, five fields, or six or seven from the second) in words, in the
724    /// person's time zone: "every 5 minutes", "every weekday at 07:00"; any other schedule
725    /// as it is written.
726    fn cron_words(&self, expr: &str, now: DateTime<Utc>) -> String {
727        let written = || format!("on the schedule {expr}");
728        let all: Vec<&str> = expr.split_whitespace().collect();
729        let fields = match all.len() {
730            5 => &all[..],
731            6 | 7 if all[0] == "0" && all.get(6).is_none_or(|year| *year == "*") => &all[1..6],
732            _ => return written(),
733        };
734        let &[minute, hour, day, month, weekday] = fields else {
735            return written();
736        };
737        let every = |field: &str| match field {
738            "*" => Some(1),
739            _ => field.strip_prefix("*/").and_then(|step| step.parse::<u32>().ok()),
740        };
741        let number = |field: &str| field.parse::<u32>().ok();
742        if day != "*" || month != "*" {
743            return written();
744        }
745        match (every(minute), number(minute), every(hour), number(hour)) {
746            (Some(1), _, Some(1), _) if weekday == "*" => "every minute".to_string(),
747            (Some(step), _, Some(1), _) if weekday == "*" => format!("every {step} minutes"),
748            (_, Some(_), Some(1), _) if weekday == "*" => "every hour".to_string(),
749            (_, Some(_), Some(step), _) if weekday == "*" => format!("every {step} hours"),
750            (_, Some(minute), _, Some(hour)) => {
751                let Some(at) = now.date_naive().and_hms_opt(hour, minute, 0) else {
752                    return written();
753                };
754                let at = Utc.from_utc_datetime(&at);
755                let local = at.with_timezone(&self.offset);
756                let time = local.format("%H:%M");
757                let days = match weekday.to_ascii_uppercase().as_str() {
758                    "*" => "every day".to_string(),
759                    // Another day where the person lives: the days would read wrong.
760                    _ if local.date_naive() != at.date_naive() => return written(),
761                    // Six and seven fields number the days as the `cron` crate does (1 is
762                    // Sunday); only five follow Unix cron (`adk_core::schedule`).
763                    other if all.len() != 5 && other.bytes().any(|b| b.is_ascii_digit()) => {
764                        return written();
765                    }
766                    "1-5" | "MON-FRI" => "every weekday".to_string(),
767                    other => match WEEKDAYS.iter().find(|(number, name, _)| {
768                        *number == other || name.eq_ignore_ascii_case(other)
769                    }) {
770                        Some((_, _, day)) => format!("every {day}"),
771                        None => return written(),
772                    },
773                };
774                format!("{days} at {time}")
775            }
776            _ => written(),
777        }
778    }
779
780    /// Whether `[from, until]` overlaps quiet time.
781    pub(crate) fn waited_through_quiet(&self, from: DateTime<Utc>, until: DateTime<Utc>) -> bool {
782        let Some(quiet) = self.quiet else {
783            return false;
784        };
785        if quiet.contains(from) || quiet.contains(until) {
786            return true;
787        }
788        let offset = self.quiet_offset(&quiet);
789        let first = from.with_timezone(&offset).date_naive();
790        let last = until.with_timezone(&offset).date_naive();
791        let mut day = first;
792        while day <= last {
793            if let Some(start) = offset.from_local_datetime(&day.and_time(quiet.start)).earliest()
794                && start > from
795                && start <= until
796            {
797                return true;
798            }
799            day = match day.succ_opt() {
800                Some(next) => next,
801                None => break,
802            };
803        }
804        false
805    }
806
807    fn quiet_offset(&self, quiet: &QuietHours) -> FixedOffset {
808        quiet
809            .utc_offset_minutes
810            .and_then(|minutes| FixedOffset::east_opt(minutes * 60))
811            .unwrap_or(self.offset)
812    }
813
814    pub(crate) fn quiet_view(&self, now: DateTime<Utc>) -> Option<QuietView> {
815        let quiet = self.quiet?;
816        if quiet.start == quiet.end {
817            return None;
818        }
819        let start = quiet.start.format("%H:%M").to_string();
820        let end = quiet.end.format("%H:%M").to_string();
821        let active = quiet.contains(now);
822        let text = if active { words::quiet_until(&end) } else { words::quiet_from(&start) };
823        Some(QuietView { active, start, end, text })
824    }
825
826    /// The event at `seq`, its held call linked to the decision [`links`] gives that `seq`;
827    /// `answered` holds the calls the session's later events answer ([`answered_calls`]).
828    pub(crate) fn entry(
829        &self,
830        seq: u64,
831        event: &Event,
832        links: &HashMap<u64, Link>,
833        answered: &HashSet<String>,
834    ) -> FeedEntry {
835        FeedEntry {
836            seq,
837            at: event.timestamp,
838            at_text: self.hh_mm(event.timestamp),
839            items: self.items(event, links.get(&seq), answered),
840        }
841    }
842
843    /// The thread item of a turn that ended in an error: who could not answer and why. The
844    /// runtime records an error as `component.category: message`; the message is the reason
845    /// and the rest its code.
846    pub(crate) fn turn_failed(&self, failure: &TurnFailure) -> ThreadItem {
847        let error = failure.error.as_deref().map(str::trim).filter(|error| !error.is_empty());
848        let (code, reason) = match error.map(|error| (error, error.split_once(": "))) {
849            Some((_, Some((code, message))))
850                if code.split('.').count() == 2
851                    && code.chars().all(|c| c.is_ascii_lowercase() || c == '_' || c == '.') =>
852            {
853                (Some(code.to_string()), Some(message.trim()))
854            }
855            Some((error, _)) => (None, Some(error)),
856            None => (None, None),
857        };
858        let reason = reason.map(|reason| match reason.char_indices().nth(REASON_CHARS) {
859            Some((cut, _)) => format!("{}…", &reason[..cut]),
860            None => reason.to_string(),
861        });
862        ThreadItem::TurnFailed {
863            text: words::couldnt_answer(&self.agent(&failure.agent).display_name),
864            reason,
865            code,
866        }
867    }
868
869    fn items(
870        &self,
871        event: &Event,
872        link: Option<&Link>,
873        answered: &HashSet<String>,
874    ) -> Vec<ThreadItem> {
875        let mut items = Vec::new();
876        let from_person = event.author == "user";
877        // A call a person asked for through a drawn form (spec 3.3 §7.4 rule 5).
878        let requested = crate::genui::requested_via(event);
879        if let Some(content) = &event.llm_response.content {
880            let mut text = String::new();
881            // The images a person sent with the message (spec 3.3 §5.1).
882            let mut images = Vec::new();
883            for part in &content.parts {
884                match part {
885                    Part::Text { text: chunk } if !event.llm_response.partial => {
886                        text.push_str(chunk);
887                    }
888                    Part::InlineData { mime_type, data, .. } if from_person => {
889                        images.extend(crate::images::shown(mime_type, data));
890                    }
891                    // The person's own call: its DrawnSent item shows it, not the agent's work.
892                    Part::FunctionCall { id, .. }
893                        if requested.is_some() && crate::genui::is_requested(id.as_ref()) => {}
894                    // Replies an agent suggests: shown under its message, never as its work.
895                    Part::FunctionCall { name, args, id, .. }
896                        if name == crate::suggest::SUGGEST_REPLIES_TOOL =>
897                    {
898                        if let Ok(replies) = crate::suggest::replies_of(args) {
899                            items.push(ThreadItem::Suggestions { replies, call_id: id.clone() });
900                        }
901                    }
902                    Part::FunctionCall { name, args, id, .. } => {
903                        items.push(ThreadItem::Activity {
904                            tool: name.clone(),
905                            text: describe_call(name, args),
906                            call_id: id.clone(),
907                        });
908                    }
909                    // A held call's placeholder answer: its Decision item shows it.
910                    Part::FunctionResponse { function_response, .. }
911                        if adk_core::is_confirmation_pending(&function_response.response) => {}
912                    // The suggestions' own answer says nothing to the person.
913                    Part::FunctionResponse { function_response, .. }
914                        if function_response.name == crate::suggest::SUGGEST_REPLIES_TOOL => {}
915                    // A call a person asked for that the agent's rules refused before holding it.
916                    Part::FunctionResponse { function_response, id: Some(id), .. }
917                        if requested.is_some() && crate::genui::is_requested(Some(id)) =>
918                    {
919                        if let Some(via) = &requested {
920                            items.push(crate::genui::sent(
921                                via,
922                                &function_response.name,
923                                id,
924                                event,
925                                &self.hh_mm(event.timestamp),
926                                Some(&self.agent(&event.author).display_name),
927                                None,
928                            ));
929                        }
930                    }
931                    Part::FunctionResponse { function_response, id, .. } => {
932                        // A drawing, or a refused one, when the event proves a render tool
933                        // made it (spec 3.3 §7.4 rule 5).
934                        #[cfg(feature = "genui")]
935                        {
936                            if let Some(item) = crate::genui::project(
937                                self,
938                                event,
939                                &function_response.name,
940                                &function_response.response,
941                                id.as_ref(),
942                            ) {
943                                items.push(item);
944                                continue;
945                            }
946                        }
947                        let ok = !response_failed(&function_response.response);
948                        let text = if !ok
949                            && crate::genui::is_requested(id.as_ref())
950                            && crate::genui::refused_on_resume(
951                                &function_response.name,
952                                &function_response.response,
953                            ) {
954                            words::cant_use_any_more(
955                                &self.agent(&event.author).display_name,
956                                &function_response.name,
957                            )
958                        } else if ok {
959                            words::DONE.to_string()
960                        } else {
961                            words::FAILED.to_string()
962                        };
963                        // A perception call's answer opens in the annotated viewer.
964                        let image = (ok
965                            && crate::viewer::answers_about_image(&function_response.name))
966                        .then(|| function_response.response.get("image").and_then(Value::as_str))
967                        .flatten()
968                        .filter(|digest| digest.starts_with("sha256:"))
969                        .map(str::to_string);
970                        // A command or code that ran: what it wrote, and how it exited.
971                        match command_run(&function_response.name, &function_response.response) {
972                            Some(run) => {
973                                let ok = ok
974                                    && run.exit_code.is_none_or(|code| code == 0)
975                                    && run.stopped.is_none();
976                                let text = if ok { words::DONE } else { words::FAILED };
977                                items.push(ThreadItem::Run {
978                                    tool: function_response.name.clone(),
979                                    call_id: id.clone(),
980                                    ok,
981                                    text: text.to_string(),
982                                    run,
983                                });
984                            }
985                            None => items.push(ThreadItem::Result {
986                                tool: function_response.name.clone(),
987                                call_id: id.clone(),
988                                ok,
989                                text,
990                                image,
991                            }),
992                        }
993                    }
994                    _ => {}
995                }
996            }
997            let text = text.trim();
998            // The event that holds a call carries the runtime's own notice, not the agent's
999            // words: its Decision item says it plainly (§8). A requested call's line is for
1000            // the model; its DrawnSent item says it to the person.
1001            if (!text.is_empty() || !images.is_empty())
1002                && event.actions.tool_confirmation.is_none()
1003                && requested.is_none()
1004            {
1005                let message = if from_person {
1006                    ThreadItem::Message {
1007                        from: Speaker::You,
1008                        author: "You".to_string(),
1009                        // An app's suggestion the person sent reads as its words and label.
1010                        text: crate::genui::suggested_message(text)
1011                            .unwrap_or_else(|| text.to_string()),
1012                        images,
1013                    }
1014                } else {
1015                    ThreadItem::Message {
1016                        from: Speaker::Agent,
1017                        author: self.agent(&event.author).display_name,
1018                        text: text.to_string(),
1019                        images: Vec::new(),
1020                    }
1021                };
1022                items.insert(0, message);
1023            }
1024        }
1025        if let Some(held) = &event.actions.tool_confirmation {
1026            // "Waiting for you" only while the caller's own decision is open (§8.1); a call
1027            // routed to other approvers, or to no one, waits for an answer; one answered since
1028            // is decided.
1029            let ran = held.function_call_id.as_ref().is_some_and(|id| answered.contains(id));
1030            let text = match link {
1031                Some(link) if link.pending && !ran => words::WAITING_FOR_YOU,
1032                Some(_) => words::DECIDED,
1033                None if ran => words::DECIDED,
1034                None => words::WAITING_FOR_AN_ANSWER,
1035            };
1036            if let (Some(via), Some(call_id)) = (&requested, &held.function_call_id) {
1037                items.push(crate::genui::sent(
1038                    via,
1039                    &held.tool_name,
1040                    call_id,
1041                    event,
1042                    &self.hh_mm(event.timestamp),
1043                    None,
1044                    link.map(|link| link.id.clone()),
1045                ));
1046            }
1047            items.push(ThreadItem::Decision {
1048                decision_id: link.map(|link| link.id.clone()),
1049                tool: held.tool_name.clone(),
1050                text: text.to_string(),
1051            });
1052        }
1053        items
1054    }
1055
1056    pub(crate) fn agent_row(&self, state: &AgentState) -> AgentRow {
1057        let (status, status_text) = match state.state {
1058            RunState::Running | RunState::Queued => {
1059                (AgentStatus::Working, words::WORKING.to_string())
1060            }
1061            RunState::Waiting if state.waiting_on_decision && !state.suspended => {
1062                (AgentStatus::WaitingForYou, words::WAITING_FOR_YOU.to_string())
1063            }
1064            RunState::Waiting => match state.wake_at.filter(|_| !state.suspended) {
1065                Some(at) => (AgentStatus::Asleep, words::asleep_until(&self.hh_mm(at))),
1066                None => (AgentStatus::Asleep, words::ASLEEP.to_string()),
1067            },
1068            RunState::Completed | RunState::Cancelled => {
1069                (AgentStatus::Done, words::DONE.to_string())
1070            }
1071            RunState::Failed => (AgentStatus::Failed, words::FAILED.to_string()),
1072            // A state a later runtime adds shows as idle, never as working or done.
1073            _ => (AgentStatus::Asleep, words::ASLEEP.to_string()),
1074        };
1075        // A background sub-agent's row says whose work it is (its name, from its parent).
1076        let status_text = match &state.subagent {
1077            Some(name) => format!("{status_text} · sub-agent {name}"),
1078            None => status_text,
1079        };
1080        AgentRow {
1081            agent: self.agent(&state.name),
1082            status,
1083            status_text,
1084            wake_at: state.wake_at.filter(|_| status == AgentStatus::Asleep && !state.suspended),
1085            session_id: state.session_id.clone(),
1086            area: None,
1087            mode: None,
1088            added: false,
1089            can_change: false,
1090            shell: state
1091                .shell
1092                .clone()
1093                .map(|place| ShellView { text: words::commands_run(&place), place }),
1094        }
1095    }
1096
1097    /// The line of "While you were away" a ledger row makes, or `None` for a row that is no
1098    /// event of its own (spec 3.3 §5.1, §10 K4): the line the kernel's `GET /kernel/away`
1099    /// lists for it ([`AwayLine`]), so every surface shows the same lines and the kernel's
1100    /// own housekeeping (wakes, its processes' state changes) is never one.
1101    pub(crate) fn briefing_line(&self, entry: &LedgerEntry) -> Option<BriefingLine> {
1102        let line = AwayLine::of(entry)?;
1103        // A decision says which answer it was, whether its row is the harness's or the kernel's.
1104        let denied = line.effect.as_deref() == Some("deny");
1105        let at = entry.utc();
1106        let agent = self.ledger_agent(&entry.agent);
1107        let who = agent.clone().unwrap_or_else(|| words::YOUR_AGENTS.to_string());
1108        // The `/proc` ledger writes the state a process entered as the row's effect (spec 3.2
1109        // §7.10); the loop guard's row carries none.
1110        let failed = entry.effect.as_deref() == Some("failed");
1111        // Mid-sentence, as the object of the decision.
1112        let whom = agent.as_deref().unwrap_or("your agents");
1113        let (pill, text) = match line.kind {
1114            AwayKind::Done => (Some(Pill::Done), words::briefing_sentence("turn", &who)),
1115            AwayKind::Failed if failed => (Some(Pill::Failed), format!("{who} failed.")),
1116            AwayKind::Failed => (Some(Pill::Failed), words::briefing_sentence("loop_guard", &who)),
1117            AwayKind::Stopped => (None, format!("{who} was stopped.")),
1118            AwayKind::Suggestion => match &agent {
1119                Some(agent) => {
1120                    (Some(Pill::Suggestion), words::briefing_sentence("proposal", agent))
1121                }
1122                None => (Some(Pill::Suggestion), words::AGENTS_SUGGEST.to_string()),
1123            },
1124            AwayKind::Question => (Some(Pill::Question), words::NOTICED_SOMETHING.to_string()),
1125            AwayKind::Decided if denied => {
1126                (Some(Pill::YouDecided), words::briefing_sentence("rejection", whom))
1127            }
1128            AwayKind::Decided => {
1129                (Some(Pill::YouDecided), words::briefing_sentence("approval", whom))
1130            }
1131            AwayKind::StoppedAll => (None, format!("{}.", words::ALL_AGENTS_STOPPED)),
1132            AwayKind::ResumedAll => (None, words::ALL_AGENTS_RESUMED.to_string()),
1133            // A kind a later kernel adds says what kind of thing happened, never more.
1134            _ => (None, words::briefing_sentence("", &who)),
1135        };
1136        Some(BriefingLine {
1137            seq: entry.seq,
1138            at,
1139            at_text: self.hh_mm(at),
1140            agent: who,
1141            pill,
1142            pill_text: pill.map(|pill| pill_words(pill).to_string()),
1143            text,
1144        })
1145    }
1146
1147    /// The display name of the agent a ledger row names: its acting identity
1148    /// (`urn:adk:agent:{app}/{agent}`) or its target, as the roster names it; `None` for the
1149    /// kernel's own work, which no agent did.
1150    fn ledger_agent(&self, label: &str) -> Option<String> {
1151        if label == KERNEL_AGENT || label.is_empty() {
1152            return None;
1153        }
1154        let name = label.rsplit(['/', ':']).next().filter(|name| !name.is_empty()).unwrap_or(label);
1155        Some(self.agent(name).display_name)
1156    }
1157}
1158
1159fn pill_words(pill: Pill) -> &'static str {
1160    match pill {
1161        Pill::Done => words::DONE,
1162        Pill::Failed => words::FAILED,
1163        Pill::WaitingForYou => words::WAITING_FOR_YOU,
1164        Pill::YouDecided => words::YOU_DECIDED,
1165        Pill::Suggestion => words::SUGGESTION,
1166        Pill::Question => words::QUESTION,
1167    }
1168}
1169
1170/// The mode with its §8.1 words.
1171pub(crate) fn mode_view(mode: HarnessMode) -> ModeView {
1172    let (mode, label) = match mode {
1173        HarnessMode::ReadOnly => (Mode::JustLook, words::JUST_LOOK),
1174        HarnessMode::Plan => (Mode::Suggest, words::SUGGEST),
1175        HarnessMode::Auto => (Mode::GoAhead, words::GO_AHEAD),
1176        // Ask, and any mode a later harness adds, reads as the default.
1177        _ => (Mode::AskFirst, words::ASK_FIRST),
1178    };
1179    ModeView { mode, label: label.to_string(), status: words::mode_status(label) }
1180}
1181
1182/// The harness mode a §8.1 mode word sets.
1183pub(crate) fn harness_mode(mode: Mode) -> HarnessMode {
1184    match mode {
1185        Mode::JustLook => HarnessMode::ReadOnly,
1186        Mode::Suggest => HarnessMode::Plan,
1187        Mode::AskFirst => HarnessMode::Ask,
1188        Mode::GoAhead => HarnessMode::Auto,
1189    }
1190}
1191
1192pub(crate) fn spend_view(spend: SpendToday) -> SpendView {
1193    let text = match spend.limit {
1194        Some(limit) => words::spent_of(spend.spent, limit),
1195        None => words::spent_today(spend.spent),
1196    };
1197    SpendView { spent_micro_usd: spend.spent, limit_micro_usd: spend.limit, text }
1198}
1199
1200/// The agent a request is from: the acting agent's name, else the application.
1201pub(crate) fn agent_name(request: &ApprovalRequest) -> String {
1202    request
1203        .acting
1204        .as_ref()
1205        .map(|acting| {
1206            let id = acting.agent.id.as_str();
1207            id.rsplit(['/', ':']).next().unwrap_or(id).to_string()
1208        })
1209        .filter(|name| !name.is_empty())
1210        .unwrap_or_else(|| request.scope.app_name.clone())
1211}
1212
1213/// The decision a held call links to in a thread.
1214#[derive(Debug, Clone, PartialEq, Eq)]
1215pub(crate) struct Link {
1216    /// The request's id.
1217    pub(crate) id: String,
1218    /// The request is still open.
1219    pub(crate) pending: bool,
1220}
1221
1222/// How far apart a request's creation and the event that held its call may be and still be
1223/// one moment: the inbox writes the request just before or after the session writes the event.
1224const HOLD_SLACK_MS: i64 = 1_000;
1225
1226/// Calls held closer together than this were held in one model turn and link in event order.
1227const ONE_TURN_MS: i64 = 500;
1228
1229/// The calls `events` answer: every function response that is not a held call's placeholder,
1230/// by call ID.
1231pub(crate) fn answered_calls(events: &[Event]) -> HashSet<String> {
1232    events
1233        .iter()
1234        .filter_map(|event| event.llm_response.content.as_ref())
1235        .flat_map(|content| &content.parts)
1236        .filter_map(|part| match part {
1237            Part::FunctionResponse { function_response, id, .. }
1238                if !adk_core::is_confirmation_pending(&function_response.response) =>
1239            {
1240                id.clone()
1241            }
1242            _ => None,
1243        })
1244        .collect()
1245}
1246
1247/// The decision of each held call in a session's `events`, by the event's `seq` (its position
1248/// from 1), out of the session's `requests` (spec 3.3 §7.1).
1249///
1250/// A request with a fingerprint decides the calls held with that fingerprint. A request
1251/// served without one, as a kernel's approvals inbox serves them, decides a call of the same
1252/// tool by the same acting agent. Calls link in two passes over the session: first each call
1253/// to the request showing its exact arguments, then each call still unlinked to the earliest
1254/// request still free, since a route may show approvers redacted arguments — unless a later
1255/// call, held in another turn by the time that request was written, is the one it belongs to.
1256/// No request decides two calls, so a call whose own request is missing (unrouted, or not the
1257/// caller's to decide) links to none rather than to another call's, whether that call's
1258/// arguments are shown or redacted. A call held again keeps its request unless that request
1259/// was resolved before the call was held again.
1260pub(crate) fn links(events: &[Event], requests: &[ApprovalRequest]) -> HashMap<u64, Link> {
1261    let mut order: Vec<&ApprovalRequest> = requests.iter().collect();
1262    order.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
1263    let holds: Vec<(u64, &ToolConfirmationRequest, chrono::DateTime<Utc>, String)> = events
1264        .iter()
1265        .enumerate()
1266        .filter_map(|(index, event)| {
1267            let held = event.actions.tool_confirmation.as_ref()?;
1268            Some((index as u64 + 1, held, event.timestamp, held.fingerprint()))
1269        })
1270        .collect();
1271    let decides = |request: &ApprovalRequest,
1272                   held: &ToolConfirmationRequest,
1273                   fingerprint: &str,
1274                   exact: bool| {
1275        match request.fingerprint.is_empty() {
1276            false => exact && request.fingerprint == fingerprint,
1277            true => {
1278                let agent = held.acting.as_deref().map(|acting| &acting.agent.id);
1279                request.tool_name == held.tool_name
1280                    && match (agent, &request.acting) {
1281                        (Some(agent), Some(acting)) => *agent == acting.agent.id,
1282                        _ => true,
1283                    }
1284                    && (!exact || request.args_redacted == held.args)
1285            }
1286        }
1287    };
1288    let mut taken = vec![false; order.len()];
1289    let mut linked: HashMap<u64, usize> = HashMap::new();
1290    for exact in [true, false] {
1291        let mut held_by: HashMap<&str, usize> = HashMap::new();
1292        for (hold, (seq, held, at, fingerprint)) in holds.iter().enumerate() {
1293            if let Some(&position) = linked.get(seq) {
1294                held_by.insert(fingerprint, position);
1295                continue;
1296            }
1297            // Whether `request` belongs to a later call of another turn: one still unlinked,
1298            // not a call held again under its open request, held by the time the request was
1299            // written.
1300            let later_owner = |request: &ApprovalRequest| {
1301                holds[hold + 1..].iter().enumerate().any(|(offset, (other, call, when, print))| {
1302                    let inherits = holds[..hold + 1 + offset].iter().any(|(earlier, _, _, p)| {
1303                        p == print
1304                            && linked.get(earlier).is_some_and(|&position| {
1305                                order[position].resolved_at.is_none_or(|at| at > *when)
1306                            })
1307                    });
1308                    !linked.contains_key(other)
1309                        && print != fingerprint
1310                        && !inherits
1311                        && *when > *at + chrono::Duration::milliseconds(ONE_TURN_MS)
1312                        && *when
1313                            <= request.created_at + chrono::Duration::milliseconds(HOLD_SLACK_MS)
1314                        && decides(request, call, print, false)
1315                })
1316            };
1317            let kept = held_by.get(fingerprint.as_str()).copied();
1318            let next = match kept {
1319                // Held again while its request was still open, as the event's time shows,
1320                // not the request's state now.
1321                Some(position)
1322                    if order[position].resolved_at.is_none_or(|resolved| resolved > *at) =>
1323                {
1324                    Some(position)
1325                }
1326                _ => (0..order.len())
1327                    .find(|&position| {
1328                        !taken[position]
1329                            && decides(order[position], held, fingerprint, exact)
1330                            && (exact || !later_owner(order[position]))
1331                    })
1332                    .or(kept),
1333            };
1334            if let Some(position) = next {
1335                taken[position] = true;
1336                held_by.insert(fingerprint, position);
1337                linked.insert(*seq, position);
1338            }
1339        }
1340    }
1341    linked
1342        .into_iter()
1343        .map(|(seq, position)| {
1344            let request = order[position];
1345            (seq, Link { id: request.id.clone(), pending: request.state == ApprovalState::Pending })
1346        })
1347        .collect()
1348}
1349
1350/// `full`, cut short past [`CALL_TEXT_LIMIT`] characters, and whether it was.
1351pub(crate) fn cut_call_text(full: String) -> (String, bool) {
1352    if full.chars().count() <= CALL_TEXT_LIMIT {
1353        return (full, false);
1354    }
1355    let mut cut: String = full.chars().take(CALL_TEXT_LIMIT).collect();
1356    cut.push('…');
1357    (cut, true)
1358}
1359
1360/// The exact call, cut short past [`CALL_TEXT_LIMIT`] characters.
1361pub(crate) fn call_view(request: &ApprovalRequest) -> CallView {
1362    let (text, truncated) = cut_call_text(call_text(&request.tool_name, &request.args_redacted));
1363    CallView {
1364        tool: request.tool_name.clone(),
1365        args: request.args_redacted.clone(),
1366        text,
1367        truncated,
1368    }
1369}
1370
1371/// The arguments the inbox shows are the call's own (`ApprovalRequest::shows_call_args`). A
1372/// source that serves no fingerprints, the approvals API, removes Edit itself where they are
1373/// not (`inbox::request_of`).
1374fn shows_own_arguments(request: &ApprovalRequest) -> bool {
1375    request.fingerprint.is_empty() || request.shows_call_args()
1376}
1377
1378/// `tool(key: value, …)`, each value as JSON, keys in sorted order.
1379fn call_text(tool: &str, args: &Value) -> String {
1380    match args {
1381        Value::Object(map) => {
1382            // Sorted, so the text is the same whether serde_json keeps insertion order
1383            // (`preserve_order`, which a workspace build turns on) or not.
1384            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
1385            entries.sort_by(|a, b| a.0.cmp(b.0));
1386            let fields: Vec<String> =
1387                entries.into_iter().map(|(key, value)| format!("{key}: {value}")).collect();
1388            format!("{tool}({})", fields.join(", "))
1389        }
1390        Value::Null => format!("{tool}()"),
1391        other => format!("{tool}({other})"),
1392    }
1393}
1394
1395/// What will happen, in plain words, from the call: "Write file note.txt",
1396/// "Send email to [client email]" (spec 3.3 §7.1, §8 "Name the outcome"). A decision the
1397/// kernel itself asks is named by what it is about, never by the kernel's tool or its JSON:
1398/// an agenda item by its title.
1399pub(crate) fn heading(request: &ApprovalRequest) -> String {
1400    // A take over says what to type, in the words of the tool that asks (spec 3.3 §8.2).
1401    if request.tool_name == TAKE_OVER_TOOL && !request.summary.trim().is_empty() {
1402        return request.summary.clone();
1403    }
1404    if let Some(operation) = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX) {
1405        // The kernel's heading of a suggested agent, never the model's (spec 3.3 S-I13).
1406        if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
1407            let name = request
1408                .args_redacted
1409                .get("displayName")
1410                .and_then(Value::as_str)
1411                .unwrap_or_default();
1412            return crate::agents::words::add_an_agent_called(name);
1413        }
1414        if request.tool_name == AGENDA_TOOL_NAME {
1415            return match agenda_item(request) {
1416                Some(item) if !item.title.trim().is_empty() => sentence(&item.title),
1417                Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
1418                Some(_) | None => words::SUGGESTION.to_string(),
1419            };
1420        }
1421        if operation == DRIVER_MOUNT_OPERATION
1422            && let Some(id) = request.args_redacted.get("id").and_then(Value::as_str)
1423        {
1424            return words::start_driver(id);
1425        }
1426        return humanize(operation);
1427    }
1428    describe_call(&request.tool_name, &request.args_redacted)
1429}
1430
1431/// What a chat card says will happen: the tool in plain words, "Write file", "Send email" —
1432/// never its arguments, since a chat card leaves the machine (spec 3.3 §7.1, S-I5). The
1433/// kernel's own decisions say what kind they are: "Suggestion", "Question".
1434pub(crate) fn chat_heading(request: &ApprovalRequest) -> String {
1435    if request.tool_name == AGENDA_TOOL_NAME {
1436        return match agenda_item(request) {
1437            Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
1438            Some(_) | None => words::SUGGESTION.to_string(),
1439        };
1440    }
1441    humanize(request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX).unwrap_or(&request.tool_name))
1442}
1443
1444/// What a decision the kernel itself asks is about, as the person knows it — the agent a
1445/// suggestion adds, the agenda item's title, the driver a mount starts — for the record of an
1446/// answer to it, which never names the kernel's tool (spec 3.3 §8, §11).
1447pub(crate) fn kernel_name(request: &ApprovalRequest) -> Option<String> {
1448    let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
1449    let name = if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
1450        request.args_redacted.get("displayName").and_then(Value::as_str).map(str::to_string)
1451    } else if request.tool_name == AGENDA_TOOL_NAME {
1452        agenda_item(request).map(|item| item.title)
1453    } else if operation == DRIVER_MOUNT_OPERATION {
1454        request.args_redacted.get("id").and_then(Value::as_str).map(str::to_string)
1455    } else {
1456        None
1457    };
1458    name.map(|name| name.trim().to_string()).filter(|name| !name.is_empty())
1459}
1460
1461/// The prefix of the inbox tools of decisions the kernel itself asks, not an agent's call:
1462/// `kernel:agenda`, `kernel:driver.mount`.
1463const KERNEL_TOOL_PREFIX: &str = "kernel:";
1464
1465/// The operation of a driver mount a hosted definition asks for
1466/// (`adk_kernel::managed::DRIVER_MOUNT_TOOL_NAME`, behind the kernel's `managed` feature).
1467const DRIVER_MOUNT_OPERATION: &str = "driver.mount";
1468
1469/// Cron weekdays: their number, their name, and their name in words.
1470const WEEKDAYS: [(&str, &str, &str); 8] = [
1471    ("0", "SUN", "Sunday"),
1472    ("1", "MON", "Monday"),
1473    ("2", "TUE", "Tuesday"),
1474    ("3", "WED", "Wednesday"),
1475    ("4", "THU", "Thursday"),
1476    ("5", "FRI", "Friday"),
1477    ("6", "SAT", "Saturday"),
1478    ("7", "SUN", "Sunday"),
1479];
1480
1481/// The agenda item an agenda proposal carries (`adk_kernel::AGENDA_TOOL_NAME`): the item is
1482/// its arguments.
1483fn agenda_item(request: &ApprovalRequest) -> Option<AgendaItem> {
1484    (request.tool_name == AGENDA_TOOL_NAME)
1485        .then(|| serde_json::from_value(request.args_redacted.clone()).ok())
1486        .flatten()
1487}
1488
1489/// The words of "allow once" and "deny" on a decision the kernel asks: a suggestion is done
1490/// or left for now, a question is right or forgotten (spec 3.3 §8.1, §8.2).
1491fn kernel_answer_words(request: &ApprovalRequest) -> Option<(&'static str, &'static str)> {
1492    if request.tool_name != AGENDA_TOOL_NAME {
1493        return None;
1494    }
1495    match agenda_item(request) {
1496        Some(item) if item.origin.is_question() => Some((words::THATS_RIGHT, words::FORGET_IT)),
1497        Some(_) | None => Some((words::DO_IT, words::NOT_NOW)),
1498    }
1499}
1500
1501/// `text` on one line, starting with a capital: a title in sentence case (spec 3.3 §8).
1502fn sentence(text: &str) -> String {
1503    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
1504    let mut chars = line.chars();
1505    match chars.next() {
1506        Some(first) => first.to_uppercase().chain(chars).collect(),
1507        None => line,
1508    }
1509}
1510
1511/// The argument a heading names, short enough for one line.
1512fn primary_argument(args: &Value) -> Option<(&'static str, String)> {
1513    const KEYS: [&str; 9] =
1514        ["to", "path", "file", "url", "command", "recipient", "name", "query", "title"];
1515    let map = args.as_object()?;
1516    KEYS.iter().find_map(|key| {
1517        let value = map.get(*key)?.as_str()?.trim();
1518        if value.is_empty() {
1519            return None;
1520        }
1521        let mut short: String = value.chars().take(60).collect();
1522        if value.chars().count() > 60 {
1523            short.push('…');
1524        }
1525        Some((*key, short))
1526    })
1527}
1528
1529/// Whether a call spends money: the payment tools `adk-payments` publishes, all named
1530/// `payments_*` (spec 3.1 §7.16), or a request whose route marks it.
1531pub(crate) fn spends_money(request: &ApprovalRequest) -> bool {
1532    request.tool_name.starts_with("payments_")
1533}
1534
1535/// Whether a call can be taken back, from its name: messages can't be unsent; everything
1536/// else is shown as not undoable, since a surface cannot know better (spec 3.3 §7.1).
1537pub(crate) fn reversibility(request: &ApprovalRequest) -> Reversibility {
1538    let name = request.tool_name.to_lowercase();
1539    let sends = ["send", "email", "mail", "message", "sms", "post", "reply", "notify", "publish"];
1540    if sends.iter().any(|word| name.contains(word)) {
1541        Reversibility::CantBeUnsent
1542    } else {
1543        Reversibility::CantBeUndone
1544    }
1545}
1546
1547/// A short line for a tool call in a thread: "Read file timesheet-october.csv".
1548fn describe_call(tool: &str, args: &Value) -> String {
1549    let mut text = humanize(tool);
1550    if let Some((key, value)) = primary_argument(args) {
1551        text.push(' ');
1552        if key == "to" {
1553            text.push_str("to ");
1554        }
1555        text.push_str(&value);
1556    }
1557    text
1558}
1559
1560fn response_failed(response: &Value) -> bool {
1561    response.get("error").is_some()
1562        || response
1563            .get("status")
1564            .and_then(Value::as_str)
1565            .is_some_and(|status| matches!(status, "error" | "failed" | "denied" | "not_run"))
1566}
1567
1568/// `send_email` → "Send email"; `chiefOfStaff` → "Chief of staff".
1569pub(crate) fn humanize(name: &str) -> String {
1570    let mut words: Vec<String> = Vec::new();
1571    let mut current = String::new();
1572    let mut previous_lower = false;
1573    for c in name.chars() {
1574        if matches!(c, '_' | '-' | ' ' | '.' | ':' | '/') {
1575            if !current.is_empty() {
1576                words.push(std::mem::take(&mut current));
1577            }
1578            previous_lower = false;
1579            continue;
1580        }
1581        if c.is_uppercase() && previous_lower && !current.is_empty() {
1582            words.push(std::mem::take(&mut current));
1583        }
1584        previous_lower = c.is_lowercase() || c.is_ascii_digit();
1585        current.extend(c.to_lowercase());
1586    }
1587    if !current.is_empty() {
1588        words.push(current);
1589    }
1590    let mut text = words.join(" ");
1591    if let Some(first) = text.get(..1) {
1592        let upper = first.to_uppercase();
1593        text.replace_range(..1, &upper);
1594    }
1595    if text.is_empty() { name.to_string() } else { text }
1596}
1597
1598/// A monogram in the agent's own colour (spec 3.3 §9).
1599fn avatar(display_name: &str) -> Avatar {
1600    const COLORS: [&str; 8] =
1601        ["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];
1602    let monogram: String = display_name
1603        .chars()
1604        .find(|c| c.is_alphanumeric())
1605        .map(|c| c.to_uppercase().collect())
1606        .unwrap_or_default();
1607    let hash = display_name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1608        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1609    });
1610    let index = usize::try_from(hash % COLORS.len() as u64).unwrap_or(0);
1611    Avatar { monogram, color: COLORS[index].to_string() }
1612}
1613
1614/// The run a tool's result describes, for a shell's `bash` (`command`, `exit_code`, `stdout`,
1615/// `stderr`, `truncated`) and the sandbox's `sandbox_exec` (`status`, `stdout`, `stderr`,
1616/// `exit_code`, `duration_ms`); `None` for any other result (spec 3.3 §5.1). The call's own
1617/// command comes from the result where the tool repeats it.
1618fn command_run(tool: &str, response: &serde_json::Value) -> Option<CommandRun> {
1619    let object = response.as_object()?;
1620    let has_output = object.contains_key("stdout") || object.contains_key("stderr");
1621    let shell = object.contains_key("command") && object.contains_key("exit_code");
1622    let sandbox = tool == "sandbox_exec" && (has_output || object.contains_key("status"));
1623    if !(sandbox || shell && has_output) {
1624        return None;
1625    }
1626    let string = |key: &str| object.get(key).and_then(serde_json::Value::as_str).unwrap_or("");
1627    let stopped = match string("status") {
1628        "timeout" => Some(RunStop::Timeout),
1629        "memory_exceeded" => Some(RunStop::MemoryExceeded),
1630        "policy_violation" => Some(RunStop::PolicyViolation),
1631        "error" => Some(RunStop::Error),
1632        _ => None,
1633    };
1634    let line = |text: &str, stderr: bool| OutputLine {
1635        text: if text.chars().count() > RUN_LINE_CHARS {
1636            format!("{}…", text.chars().take(RUN_LINE_CHARS).collect::<String>())
1637        } else {
1638            text.to_string()
1639        },
1640        stderr,
1641    };
1642    let mut all: Vec<OutputLine> = string("stdout").lines().map(|text| line(text, false)).collect();
1643    all.extend(string("stderr").lines().map(|text| line(text, true)));
1644    let lines = u32::try_from(all.len()).unwrap_or(u32::MAX);
1645    let output = all.split_off(all.len().saturating_sub(RUN_LINES));
1646    let command = Some(string("command")).filter(|command| !command.is_empty());
1647    Some(CommandRun {
1648        command: command.map(|command| command.chars().take(CALL_TEXT_LIMIT).collect()),
1649        language: object.get("language").and_then(serde_json::Value::as_str).map(str::to_string),
1650        exit_code: object
1651            .get("exit_code")
1652            .and_then(serde_json::Value::as_i64)
1653            .and_then(|code| i32::try_from(code).ok()),
1654        duration_ms: object.get("duration_ms").and_then(serde_json::Value::as_u64),
1655        output,
1656        lines,
1657        truncated: object.get("truncated").and_then(serde_json::Value::as_bool).unwrap_or(false),
1658        stopped,
1659    })
1660}
1661
1662#[cfg(test)]
1663mod tests {
1664    use super::*;
1665
1666    #[test]
1667    fn a_long_line_is_cut_with_an_ellipsis_and_a_short_one_kept() {
1668        assert_eq!(capped("Finance", CARD_NAME_LIMIT), "Finance");
1669        let long = "x".repeat(CARD_NAME_LIMIT + 50);
1670        let cut = capped(&long, CARD_NAME_LIMIT);
1671        assert_eq!(cut.chars().count(), CARD_NAME_LIMIT);
1672        assert!(cut.ends_with('…'));
1673    }
1674    use adk_core::{ApprovalPolicy, ApprovalScope, ToolConfirmationRequest};
1675    use chrono::{Duration, NaiveTime};
1676    use serde_json::json;
1677
1678    fn time(hh: u32, mm: u32) -> NaiveTime {
1679        NaiveTime::from_hms_opt(hh, mm, 0).unwrap()
1680    }
1681
1682    fn minutes(minutes: i64) -> Duration {
1683        Duration::minutes(minutes)
1684    }
1685
1686    fn request(tool: &str, args: Value) -> ApprovalRequest {
1687        let call = ToolConfirmationRequest {
1688            tool_name: tool.into(),
1689            function_call_id: Some("c1".into()),
1690            args,
1691            origin: None,
1692            acting: None,
1693            evidence: Vec::new(),
1694        };
1695        ApprovalRequest::new(
1696            "apr_1",
1697            ApprovalScope::new("app", "ana", "s1"),
1698            &call,
1699            ApprovalPolicy::new([]),
1700        )
1701    }
1702
1703    #[test]
1704    fn headings_name_the_outcome() {
1705        assert_eq!(
1706            heading(&request("send_email", json!({ "to": "[client email]" }))),
1707            "Send email to [client email]"
1708        );
1709        assert_eq!(
1710            heading(&request("write_file", json!({ "path": "note.txt", "content": "x" }))),
1711            "Write file note.txt"
1712        );
1713        assert_eq!(humanize("chiefOfStaff"), "Chief of staff");
1714    }
1715
1716    /// A proposal of the kernel's agenda, as `Agenda::submit` puts it to the inbox.
1717    fn agenda(item: &AgendaItem) -> ApprovalRequest {
1718        let args = serde_json::to_value(item).unwrap();
1719        let request = request(AGENDA_TOOL_NAME, args.clone())
1720            .with_redacted_args(args)
1721            .with_summary(format!("Agenda follow-up: {}", item.title));
1722        if item.origin.is_question() {
1723            request.with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject])
1724        } else {
1725            request.with_allowed_actions([
1726                ApprovalAction::Approve,
1727                ApprovalAction::Edit,
1728                ApprovalAction::Reject,
1729            ])
1730        }
1731    }
1732
1733    fn item(title: &str, origin: AgendaOrigin) -> AgendaItem {
1734        AgendaItem::new(
1735            "item-1",
1736            adk_core::principal::SubjectRef::human("ana"),
1737            title,
1738            "worth doing",
1739            origin,
1740            Utc.with_ymd_and_hms(2026, 10, 25, 7, 3, 0).unwrap(),
1741        )
1742    }
1743
1744    /// The owner's 07:03 demo: a decision the kernel asks reads in plain words — who suggests
1745    /// it, what it does, when it runs — and never as the kernel's tool or its JSON (spec 3.3
1746    /// §7.1, §8).
1747    #[test]
1748    fn kernel_decisions_read_in_plain_words() {
1749        let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
1750        projector.names.insert("app".into(), "Finance".into());
1751        let now = Utc.with_ymd_and_hms(2026, 10, 25, 4, 3, 0).unwrap();
1752        let agent = AgendaOrigin::Agent { pid: "run-7".into(), confidence: 1.0 };
1753        let cron =
1754            |expr: &str| Wake::Cron { expr: expr.into(), missed: adk_core::MissedFirePolicy::Skip };
1755        let cases = [
1756            (
1757                item("check the news every 5 minutes", agent.clone())
1758                    .with_when(cron("*/5 * * * *")),
1759                "Check the news every 5 minutes",
1760                "Finance suggests this. Once you say yes, it runs every 5 minutes.",
1761            ),
1762            // 04:00 UTC is 07:00 for a person at UTC+3.
1763            (
1764                item("Read the overnight mail", agent.clone()).with_when(cron("0 0 4 * * MON-FRI")),
1765                "Read the overnight mail",
1766                "Finance suggests this. Once you say yes, it runs every weekday at 07:00.",
1767            ),
1768            // Five fields number the days as Unix cron does, so 1-5 is Monday to Friday and
1769            // 0 is Sunday; six number them as the `cron` crate does, where 1-5 starts on
1770            // Sunday, so its numbers are not read.
1771            (
1772                item("Send the standup", agent.clone()).with_when(cron("0 6 * * 1-5")),
1773                "Send the standup",
1774                "Finance suggests this. Once you say yes, it runs every weekday at 09:00.",
1775            ),
1776            (
1777                item("Plan the week", agent.clone()).with_when(cron("0 6 * * 0")),
1778                "Plan the week",
1779                "Finance suggests this. Once you say yes, it runs every Sunday at 09:00.",
1780            ),
1781            (
1782                item("Sum the week", agent.clone()).with_when(cron("0 0 6 * * 1-5")),
1783                "Sum the week",
1784                "Finance suggests this. Once you say yes, it runs on the schedule 0 0 6 * * 1-5.",
1785            ),
1786            (
1787                item("Book the dentist", agent.clone())
1788                    .with_when(Wake::At(Utc.with_ymd_and_hms(2026, 10, 26, 6, 30, 0).unwrap())),
1789                "Book the dentist",
1790                "Finance suggests this. Once you say yes, it runs tomorrow at 09:30.",
1791            ),
1792            (
1793                item("Tidy the notes", AgendaOrigin::Consolidation),
1794                "Tidy the notes",
1795                "Your agents suggest this. Once you say yes, it runs right away.",
1796            ),
1797            (
1798                item(
1799                    "You prefer morning meetings",
1800                    AgendaOrigin::Observation { id: "obs-1".into() },
1801                ),
1802                "You prefer morning meetings",
1803                "Your agents noticed something. Is that right?",
1804            ),
1805            (
1806                item("Archive", agent).with_when(cron("15 3 1 * *")),
1807                "Archive",
1808                "Finance suggests this. Once you say yes, it runs on the schedule 15 3 1 * *.",
1809            ),
1810        ];
1811        let me = Caller::human("ana", SurfaceKind::Web, crate::origin::Origin::Pointer);
1812        for (item, heading, summary) in cases {
1813            let card = projector.card(&agenda(&item), &me, None, None, now, &CardHint::new());
1814            assert_eq!((card.heading.as_str(), card.summary.as_deref()), (heading, Some(summary)));
1815            for text in [card.heading.as_str(), summary] {
1816                assert!(!text.contains("kernel") && !text.contains('{'), "{text}");
1817            }
1818            let labels: Vec<&str> = card.allowed.options.iter().map(|o| o.label.as_str()).collect();
1819            let expected: &[&str] = if item.origin.is_question() {
1820                &["That's right", "Forget it"]
1821            } else {
1822                &["Do it", "Edit", "Not now"]
1823            };
1824            assert_eq!(labels, expected, "{heading}");
1825        }
1826
1827        // A driver mount names what it starts; any other kernel decision its operation.
1828        let mount = request(
1829            "kernel:driver.mount",
1830            json!({ "id": "email", "commandLine": "mcp-email --inbox", "partitions": ["default"] }),
1831        );
1832        assert_eq!(heading(&mount), "Start email for your agents");
1833        assert_eq!(
1834            projector.kernel_summary(&mount, now).as_deref(),
1835            Some("It runs mcp-email --inbox on the computer your agents run on.")
1836        );
1837        let other = request("kernel:quota.raise", json!({ "partition": "default" }));
1838        assert_eq!(
1839            (heading(&other), projector.kernel_summary(&other, now)),
1840            ("Quota raise".to_string(), None)
1841        );
1842        // An agenda request whose item cannot be read still names no internals.
1843        let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
1844        assert_eq!(heading(&unreadable), "Suggestion");
1845        assert_eq!(chat_heading(&unreadable), "Suggestion");
1846    }
1847
1848    /// The record of an answer names a kernel decision by what it is about, never by the
1849    /// kernel's tool (spec 3.3 §8, §11).
1850    #[test]
1851    fn a_kernel_decision_is_named_by_what_it_is_about() {
1852        let added = request(
1853            adk_kernel::agents::AGENT_CREATE_TOOL_NAME,
1854            json!({ "name": "finance", "displayName": "Finance" }),
1855        );
1856        let mount = request("kernel:driver.mount", json!({ "id": "email" }));
1857        let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
1858        let other = request("kernel:quota.raise", json!({ "partition": "default" }));
1859        let call = request("write_file", json!({ "path": "notes.md" }));
1860        assert_eq!(
1861            [&added, &mount, &unreadable, &other, &call].map(kernel_name),
1862            [Some("Finance".to_string()), Some("email".to_string()), None, None, None]
1863        );
1864    }
1865
1866    #[test]
1867    fn long_calls_are_truncated_and_flagged() {
1868        let long = request("write_file", json!({ "content": "x".repeat(5_000) }));
1869        let view = call_view(&long);
1870        assert!(view.truncated);
1871        assert!(view.text.chars().count() <= CALL_TEXT_LIMIT + 1);
1872        assert!(!call_view(&request("write_file", json!({ "path": "a" }))).truncated);
1873    }
1874
1875    #[test]
1876    fn quiet_time_in_the_timeline() {
1877        let mut projector = Projector::new(FixedOffset::east_opt(0).unwrap());
1878        projector.quiet = Some(QuietHours::new(time(22, 0), time(7, 0)).with_utc_offset_minutes(0));
1879        let asked = Utc.with_ymd_and_hms(2026, 10, 23, 18, 0, 0).unwrap();
1880        assert!(!projector.waited_through_quiet(asked, asked + minutes(60)));
1881        assert!(projector.waited_through_quiet(asked, asked + minutes(13 * 60 + 30)));
1882        let view = projector.quiet_view(asked).unwrap();
1883        assert_eq!(view.text, "Quiet from 22:00");
1884        assert_eq!(
1885            projector.quiet_view(asked + minutes(6 * 60)).unwrap().text,
1886            "Quiet until 07:00"
1887        );
1888    }
1889
1890    #[test]
1891    fn a_failed_turn_says_who_could_not_answer_and_why() {
1892        let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
1893        let failed = |error: Option<&str>| {
1894            projector.turn_failed(&TurnFailure {
1895                agent: "claims_desk".into(),
1896                at: Utc::now(),
1897                error: error.map(str::to_string),
1898            })
1899        };
1900        let item = |reason: Option<&str>, code: Option<&str>| ThreadItem::TurnFailed {
1901            text: "Claims desk couldn't answer".into(),
1902            reason: reason.map(str::to_string),
1903            code: code.map(str::to_string),
1904        };
1905        assert_eq!(
1906            failed(Some("model.internal: no recorded answer for turn 3")),
1907            item(Some("no recorded answer for turn 3"), Some("model.internal"))
1908        );
1909        // Text that does not start with a code is the reason whole.
1910        assert_eq!(
1911            failed(Some("Upstream said: try later")),
1912            item(Some("Upstream said: try later"), None)
1913        );
1914        assert_eq!(failed(Some("  ")), item(None, None));
1915        assert_eq!(failed(None), item(None, None));
1916        let long = format!("model.unavailable: {}", "x".repeat(REASON_CHARS + 20));
1917        let ThreadItem::TurnFailed { reason: Some(reason), .. } = failed(Some(&long)) else {
1918            panic!("a reason");
1919        };
1920        assert_eq!(reason.chars().count(), REASON_CHARS + 1);
1921        assert!(reason.ends_with('…'));
1922    }
1923
1924    #[test]
1925    fn agent_rows_say_what_each_agent_is_doing() {
1926        let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
1927        let state = |state, waiting_on_decision, wake_at, suspended| AgentState {
1928            name: "chief_of_staff".into(),
1929            session_id: None,
1930            state,
1931            waiting_on_decision,
1932            wake_at,
1933            suspended,
1934            subagent: None,
1935            shell: None,
1936        };
1937        let seven = Some(Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap());
1938        let words = |row: AgentRow| (row.agent.display_name, row.status_text);
1939        assert_eq!(
1940            words(projector.agent_row(&state(RunState::Running, false, None, false))),
1941            ("Chief of staff".into(), "Working".into())
1942        );
1943        assert_eq!(
1944            projector.agent_row(&state(RunState::Waiting, true, None, false)).status_text,
1945            "Waiting for you"
1946        );
1947        assert_eq!(
1948            projector.agent_row(&state(RunState::Waiting, false, seven, false)).status_text,
1949            "Asleep until 07:00"
1950        );
1951        assert_eq!(
1952            projector.agent_row(&state(RunState::Waiting, false, seven, true)).status_text,
1953            "Asleep"
1954        );
1955        assert_eq!(
1956            projector.agent_row(&state(RunState::Completed, false, None, false)).status_text,
1957            "Done"
1958        );
1959        assert_eq!(
1960            projector.agent_row(&state(RunState::Failed, false, None, false)).status_text,
1961            "Failed"
1962        );
1963        let mut alpha = state(RunState::Waiting, true, None, false);
1964        alpha.subagent = Some("alpha".into());
1965        assert_eq!(
1966            projector.agent_row(&alpha).status_text,
1967            "Waiting for you · sub-agent alpha",
1968            "a background sub-agent's row names it"
1969        );
1970    }
1971
1972    #[test]
1973    fn briefing_lines_come_from_ledger_rows() {
1974        let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
1975        projector.names.insert("adk-rust".into(), "ADK-Rust".into());
1976        let row = |kind: &str, agent: &str, effect: Option<&str>| -> LedgerEntry {
1977            serde_json::from_value(json!({
1978                "seq": 7,
1979                "ts": "2026-10-23T23:05:00+03:00",
1980                "partition": "default",
1981                "agent": agent,
1982                "kind": kind,
1983                "effect": effect,
1984            }))
1985            .unwrap()
1986        };
1987        let line = projector.briefing_line(&row("proposal", "kernel", Some("proposed"))).unwrap();
1988        assert_eq!(
1989            (line.at_text.as_str(), line.pill_text.as_deref(), line.seq),
1990            ("23:05", Some("Suggestion"), 7)
1991        );
1992        assert_eq!(line.text, "Your agents suggest something. Nothing happens until you say so.");
1993        let agent = "urn:adk:agent:adk-rust/adk-rust";
1994        let decided = projector.briefing_line(&row("decided", agent, Some("approve"))).unwrap();
1995        assert_eq!(
1996            (decided.pill_text.as_deref(), decided.text.as_str()),
1997            (Some("You decided"), "You allowed ADK-Rust to go ahead.")
1998        );
1999        // The person's answer recorded by the harness is the decision's row.
2000        let said_no = projector.briefing_line(&row("rejection", agent, None)).unwrap();
2001        assert_eq!(said_no.text, "You said no to ADK-Rust.");
2002        let question = projector.briefing_line(&row("observation", "kernel", None)).unwrap();
2003        assert_eq!(question.text, "Your agents noticed something. Is that right?");
2004        // The kernel's housekeeping and an agent's steps that are no event of their own make no
2005        // line.
2006        for (kind, agent, effect) in [
2007            ("wake", "kernel", Some("woke")),
2008            ("process", "kernel", Some("completed")),
2009            ("process", agent, Some("running")),
2010            ("spend", agent, None),
2011            ("intent", agent, None),
2012            ("tool_call", agent, None),
2013            ("proposal", "kernel", Some("running")),
2014        ] {
2015            assert_eq!(
2016                projector.briefing_line(&row(kind, agent, effect)),
2017                None,
2018                "{kind} {effect:?}"
2019            );
2020        }
2021    }
2022}