Skip to main content

adk_surface/
engine.rs

1//! The engine (spec 3.3 §6): the feed, the projection and the commands every surface shares.
2
3use std::collections::{HashMap, HashSet, VecDeque};
4use std::fmt;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use adk_core::audit_log::{
10    AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
11};
12use adk_core::{ApprovalDecision, ApprovalRequest, ApprovalState, Clock, SystemClock};
13use chrono::{DateTime, FixedOffset, Local, Utc};
14use futures::future::BoxFuture;
15use futures::stream::{self, BoxStream, StreamExt};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18use serde_json::{Value, json};
19use tokio::sync::{Notify, oneshot};
20use tokio::task::JoinHandle;
21
22use crate::agents::{AgentDetail, AgentLife, GrantedUse};
23use crate::answers::{AnswerLog, AnswerRecord, InMemoryAnswerLog, SURFACE_AUDIT_DECIDE};
24use crate::error::{Result, SurfaceError};
25use crate::hints::{CardHint, CardHints};
26use crate::model::{
27    AgentRef, AgentRow, Briefing, Decided, DecisionCard, FeedEntry, Mode, ModeView, Reversibility,
28    Served, StatusLine,
29};
30use crate::origin::{Caller, Origin, SurfaceKind};
31use crate::project::{self, Place, Projector};
32use crate::rules::{self, Answer, Row};
33use crate::source::{HeldPlan, Source, Steered, Steering};
34use crate::words;
35
36/// The audit action of "Send" and "Queue" (spec 3.3 §11).
37pub const SURFACE_AUDIT_SEND: &str = "surface.send";
38/// The audit action of a message sent to a running turn (spec 3.3 §6 "steer", §11): what
39/// "Steer" was refused or offered, and how a message a turn held ended.
40pub const SURFACE_AUDIT_STEER: &str = "surface.steer";
41
42/// The audit action of **Stop the turn** (spec 3.3 §5.1), recorded before the turn stops.
43pub const SURFACE_AUDIT_STOP_TURN: &str = "surface.stop_turn";
44/// The audit action of "Stop all" (spec 3.3 §11).
45pub const SURFACE_AUDIT_STOP_ALL: &str = "surface.stop_all";
46/// The audit action of "Resume all" (spec 3.3 §11).
47pub const SURFACE_AUDIT_RESUME_ALL: &str = "surface.resume_all";
48/// The audit action of a mode change (spec 3.3 §11).
49pub const SURFACE_AUDIT_SET_MODE: &str = "surface.set_mode";
50/// The audit action of an app's call approved by the home's opt-in consent policy instead of
51/// a person (spec 3.3 §6.1 `genui-apps`).
52pub const SURFACE_AUDIT_APP_CALL_AUTO_APPROVED: &str = "surface.app.call_auto_approved";
53/// The audit action of a drawn form's Send (spec 3.3 §7.4 rule 5, §11).
54pub const SURFACE_AUDIT_DRAWN_SUBMITTED: &str = "surface.drawn.submitted";
55/// The audit action of a person's approval of a form's call, sealed to the drawing they saw
56/// (spec 3.3 §7.4 rule 5).
57pub const SURFACE_AUDIT_DRAWN_SEALED: &str = "surface.drawn.sealed";
58/// The audit action of an answer as it is given, written before it takes effect; its
59/// `surface.decide` record says how it ended (spec 3.3 §11).
60pub const SURFACE_AUDIT_ANSWER: &str = "surface.answer";
61/// The audit action of a person changing an image before it leaves: the old digest, the new
62/// one and the change, written before the call is held again (spec 3.7 §9.3 `vision.edit`).
63pub const SURFACE_AUDIT_IMAGE_CHANGE: &str = "surface.image.change";
64
65/// The audit action of a labelled example saved from the annotated viewer (spec 3.7 §8.2):
66/// the session, the answer, the image's digest, the file, the case and the region kept.
67pub const SURFACE_AUDIT_VISION_EXAMPLE: &str = "surface.vision.example";
68
69/// The code an answer is recorded with when the images it names are not the call's.
70const EVIDENCE_CHANGED: &str = "surface.evidence_changed";
71
72/// What the agent is told of a call a person changed before it ran: it is held again, with
73/// what it would send now, for their answer (spec 3.7 V-I5).
74const HELD_AGAIN_REASON: &str = "The person changed this call before it ran. It is held again \
75    with the change, and the images it would send now, for their answer.";
76
77/// How often the feed reads the session store when the source has nothing faster.
78pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
79
80/// The longest the delivery loop of queued input waits before it looks at the session again,
81/// when nothing wakes it sooner. It waits as long as the session has an open decision or a
82/// running turn, however long that is (spec 3.3 §7.3, S-I4).
83const DRAIN_BACKOFF_MAX: Duration = Duration::from_secs(5);
84
85tokio::task_local! {
86    /// The transcript digest of the spoken answer being recorded: every `surface.decide`
87    /// record written while it is in scope carries it, and none carries the words
88    /// (spec 3.3 §5.6).
89    static SPOKEN_DIGEST: String;
90}
91
92/// Runs `future` with the transcript digest `digest` in scope, when there is one.
93async fn with_digest<F: std::future::Future>(digest: Option<String>, future: F) -> F::Output {
94    match digest {
95        Some(digest) => SPOKEN_DIGEST.scope(digest, future).await,
96        None => future.await,
97    }
98}
99
100/// A command from a surface (spec 3.3 §6). Every command runs as an authenticated
101/// [`Caller`], whose subject, surface and [`Origin`] reach its audit record.
102///
103/// A message sent while a turn of its session runs reaches that turn (§6 "steer"): the
104/// engine offers it through [`Source::steer`], the runtime screens it as it screens a turn's
105/// own message, and the agent takes it at its next safe point. A turn that ends first hands
106/// the message back, and it goes as the session's next message, once.
107///
108/// | Command | A turn of the session runs | Answers |
109/// |---|---|---|
110/// | [`Send`](Self::Send) | Offered to the turn; it waits in the session's queue until the turn takes it or hands it back | At once: [`Queued`](CommandOutcome::Queued) |
111/// | [`Steer`](Self::Steer) | The same | Once the message has a fate: [`Steered`](CommandOutcome::Steered), or [`Queued`](CommandOutcome::Queued) when handed back |
112/// | [`Queue`](Self::Queue) | Never offered: the session's next message | At once: [`Queued`](CommandOutcome::Queued) |
113///
114/// # Example
115///
116/// ```rust
117/// use adk_surface::{Answer, Command};
118///
119/// let command: Command = serde_json::from_value(serde_json::json!({
120///     "type": "decide",
121///     "decisionId": "apr_1",
122///     "version": 1,
123///     "answer": "allowOnce",
124/// }))
125/// .unwrap();
126/// assert!(matches!(command, Command::Decide { answer: Answer::AllowOnce, .. }));
127/// ```
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
129#[serde(tag = "type", rename_all = "camelCase")]
130pub enum Command {
131    /// Answers a decision at the version the surface saw (S-I2).
132    #[serde(rename_all = "camelCase")]
133    Decide {
134        /// The card's `id`.
135        decision_id: String,
136        /// The card's `version`.
137        version: u64,
138        /// The answer.
139        answer: Answer,
140        /// The changed arguments of an `edit`.
141        #[serde(default, skip_serializing_if = "Option::is_none")]
142        edited_args: Option<Value>,
143        /// Why, for a `deny`; reported to the agent.
144        #[serde(default, skip_serializing_if = "Option::is_none")]
145        reason: Option<String>,
146        /// The surface showed the call in full (§7.1).
147        #[serde(default)]
148        expanded: bool,
149        /// The digests of the images the surface showed, in the order of the card's media
150        /// (spec 3.7 §8.2): an answer that lets a call with images run names the images it
151        /// lets leave, and is refused when they are not the call's.
152        #[serde(default, skip_serializing_if = "Vec::is_empty")]
153        evidence: Vec<String>,
154    },
155    /// Tightens the crop of one of a decision's images or covers more of it, then holds the
156    /// call again with the new image in its place (spec 3.7 §8.2, board choice A8): the crop
157    /// only shrinks and covering only grows. The decision at `version` closes; the call with
158    /// the new image waits for the person's answer.
159    #[serde(rename_all = "camelCase")]
160    ChangeImage {
161        /// The card's `id`.
162        decision_id: String,
163        /// The card's `version`.
164        version: u64,
165        /// The digest of the image the person changed, as the card showed it.
166        from: String,
167        /// The change.
168        change: crate::evidence::ImageChange,
169        /// Only make the new image and say its digest and size, holding nothing again: what
170        /// the editor shows before **Use this image** (board choice A8).
171        #[serde(default)]
172        preview: bool,
173    },
174    /// Cancels a spoken "allow once" inside its cancel window (§7.2).
175    #[serde(rename_all = "camelCase")]
176    CancelAnswer {
177        /// The decision.
178        decision_id: String,
179    },
180    /// Sends a message; queued instead while a decision of the session is open (S-I4). A
181    /// running turn of the session is offered it and takes it at its agent's next safe point;
182    /// a turn that ends first leaves it queued as the session's next message.
183    #[serde(rename_all = "camelCase")]
184    Send {
185        /// The session.
186        session_id: String,
187        /// The message.
188        text: String,
189        /// The images the person sent with it (spec 3.3 §5.1): at most
190        /// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
191        /// running turn; it goes as the session's next.
192        #[serde(default, skip_serializing_if = "Vec::is_empty")]
193        images: Vec<crate::model::ImageData>,
194    },
195    /// Sends a message to the running turn of the caller's own session and waits for what
196    /// became of it (§6 "steer"): [`Steered`](CommandOutcome::Steered) when the turn took it,
197    /// [`Queued`](CommandOutcome::Queued) or [`Sent`](CommandOutcome::Sent) when it was handed
198    /// back and goes as the session's next message. A person sends it, never an agent.
199    #[serde(rename_all = "camelCase")]
200    Steer {
201        /// The session.
202        session_id: String,
203        /// The message.
204        text: String,
205    },
206    /// Stops the running turn of the caller's own session (spec 3.3 §5.1): a person only; the
207    /// agent waits for the next message, and nothing held for a decision is answered.
208    #[serde(rename_all = "camelCase")]
209    StopTurn {
210        /// The session.
211        session_id: String,
212    },
213    /// Queues a message as the session's next, after its open decisions (S-I4): never offered
214    /// to a running turn.
215    #[serde(rename_all = "camelCase")]
216    Queue {
217        /// The session.
218        session_id: String,
219        /// The message.
220        text: String,
221        /// The images the person sent with it (spec 3.3 §5.1): at most
222        /// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
223        /// running turn; it goes as the session's next.
224        #[serde(default, skip_serializing_if = "Vec::is_empty")]
225        images: Vec<crate::model::ImageData>,
226    },
227    /// Stops every agent (S-I10).
228    #[serde(rename_all = "camelCase")]
229    StopAll {
230        /// Why.
231        #[serde(default, skip_serializing_if = "Option::is_none")]
232        reason: Option<String>,
233    },
234    /// Resumes after a stop: the web home or a paired local terminal only (S-I10).
235    ResumeAll,
236    /// Changes how much a session's agent acts on its own.
237    #[serde(rename_all = "camelCase")]
238    SetMode {
239        /// The session.
240        session_id: String,
241        /// The mode.
242        mode: Mode,
243    },
244    /// Starts a thread with `agent`: the session's first message goes to it, and its
245    /// harness stamps the session as its own (spec 3.3 §5.7 "Threads").
246    #[serde(rename_all = "camelCase")]
247    NewThread {
248        /// The agent: a roster row's name.
249        agent: String,
250        /// The new session.
251        session_id: String,
252        /// The first message.
253        text: String,
254        /// The images the person sent with it (spec 3.3 §5.1): at most
255        /// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
256        /// running turn; it goes as the session's next.
257        #[serde(default, skip_serializing_if = "Vec::is_empty")]
258        images: Vec<crate::model::ImageData>,
259    },
260    /// Adds an agent by hand, previewed with `digest` (spec 3.3 §5.7).
261    #[serde(rename_all = "camelCase")]
262    AddAgent {
263        /// The definition.
264        draft: Box<crate::agents::AgentDraft>,
265        /// The digest of the preview the person confirmed.
266        digest: String,
267        /// The suggestion **Change it first** replaces, by the agent id it would get.
268        #[serde(default, skip_serializing_if = "Option::is_none")]
269        replaces: Option<String>,
270    },
271    /// Changes an agent at the version seen, previewed with `digest` (spec 3.3 §5.7).
272    #[serde(rename_all = "camelCase")]
273    ChangeAgent {
274        /// The agent.
275        agent: String,
276        /// The version seen.
277        version: u64,
278        /// The definition after the change.
279        draft: Box<crate::agents::AgentDraft>,
280        /// The digest of the preview the person confirmed.
281        digest: String,
282    },
283    /// Pauses an agent (spec 3.3 §5.7).
284    #[serde(rename_all = "camelCase")]
285    PauseAgent {
286        /// The agent.
287        agent: String,
288    },
289    /// Resumes an agent paused by hand: the web home or a paired local terminal (S-I10).
290    #[serde(rename_all = "camelCase")]
291    ResumeAgent {
292        /// The agent.
293        agent: String,
294    },
295    /// Removes an agent at the version seen, previewed with `digest` (spec 3.3 §5.7).
296    #[serde(rename_all = "camelCase")]
297    RemoveAgent {
298        /// The agent.
299        agent: String,
300        /// The version seen.
301        version: u64,
302        /// The digest of the preview that named what ends.
303        digest: String,
304    },
305    /// Copies one of the person's standing rules to an agent, pinned to it (spec 3.3 §5.7
306    /// "Copy one of your rules", S-I19).
307    #[serde(rename_all = "camelCase")]
308    CopyRuleToAgent {
309        /// The agent.
310        agent: String,
311        /// The rule.
312        rule_id: String,
313    },
314    /// Sends a form an agent drew, from the version the person saw (spec 3.3 §7.4 rule 5):
315    /// never runs its tool, but asks for the call, which the drawing agent holds for the
316    /// person's decision. Only a person at a screen sends one (`keyboard`, `pointer`,
317    /// `touch`). Feature `genui`.
318    #[serde(rename_all = "camelCase")]
319    SubmitDrawn {
320        /// The session the form is in.
321        session_id: String,
322        /// The drawn surface.
323        surface_id: String,
324        /// The version the person saw.
325        version: u64,
326        /// The declared action the person used.
327        action_id: String,
328        /// What the person typed or picked, by the field's data path (`/to`).
329        #[serde(default)]
330        values: serde_json::Map<String, Value>,
331    },
332}
333
334/// What a command did (spec 3.3 §6).
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
336#[serde(tag = "type", rename_all = "camelCase")]
337pub enum CommandOutcome {
338    /// This answer was recorded; `card.decided` says how it ended when it did.
339    #[serde(rename_all = "camelCase")]
340    Answered {
341        /// The decision after the answer.
342        card: DecisionCard,
343    },
344    /// Someone answered first: shown, never retried (S-I2).
345    #[serde(rename_all = "camelCase")]
346    AlreadyDecided {
347        /// Who answered, where, how and when.
348        decided: Decided,
349        /// The decision.
350        card: DecisionCard,
351    },
352    /// The decision changed since the version the surface saw and is still open: show it
353    /// again (S-I2).
354    #[serde(rename_all = "camelCase")]
355    Changed {
356        /// The decision now.
357        card: DecisionCard,
358    },
359    /// What a change to an image would make, held nowhere: the editor shows it before **Use
360    /// this image** (board choice A8).
361    #[serde(rename_all = "camelCase")]
362    ImagePreview {
363        /// The image the change would make: its digest and size, and the one it replaces.
364        changed: crate::evidence::ImageChanged,
365    },
366    /// The call was held again with what the person changed — its arguments, or one of its
367    /// images (spec 3.7 V-I5): `card` is the old decision, closed; the call waiting with the
368    /// new image follows in the feed.
369    #[serde(rename_all = "camelCase")]
370    HeldAgain {
371        /// The image change, when an image changed.
372        #[serde(default, skip_serializing_if = "Option::is_none")]
373        changed: Option<crate::evidence::ImageChanged>,
374        /// The old decision.
375        card: DecisionCard,
376    },
377    /// A spoken "allow once" takes effect at `cancel_until` unless cancelled (§7.2).
378    #[serde(rename_all = "camelCase")]
379    Pending {
380        /// The decision.
381        decision_id: String,
382        /// When it takes effect.
383        cancel_until: DateTime<Utc>,
384        /// "Allowing once in 5 seconds".
385        text: String,
386    },
387    /// A spoken answer was cancelled in its window.
388    #[serde(rename_all = "camelCase")]
389    AnswerCancelled {
390        /// The decision.
391        decision_id: String,
392    },
393    /// The message started a turn.
394    #[serde(rename_all = "camelCase")]
395    Sent {
396        /// The session.
397        session_id: String,
398    },
399    /// The session's running turn was stopped, or none was running (spec 3.3 §5.1).
400    #[serde(rename_all = "camelCase")]
401    TurnStopped {
402        /// The session.
403        session_id: String,
404        /// A turn was running and stopped.
405        stopped: bool,
406        /// "Stopped. Your agent waits for your next message."
407        text: String,
408    },
409    /// The session's running turn took the message at its agent's next safe point (§6
410    /// "steer"): the session holds it as event `event_id`, and the turn's next model call
411    /// carries it.
412    #[serde(rename_all = "camelCase")]
413    Steered {
414        /// The session.
415        session_id: String,
416        /// The id of the session event that carries the message.
417        event_id: String,
418    },
419    /// The message waits: until the session's open decisions are answered (S-I4), or until its
420    /// running turn takes it or ends.
421    #[serde(rename_all = "camelCase")]
422    Queued {
423        /// The session.
424        session_id: String,
425        /// Its place in the queue, from 1.
426        position: u32,
427        /// "Sent after this card is answered".
428        text: String,
429    },
430    /// Every agent stopped.
431    #[serde(rename_all = "camelCase")]
432    Stopped {
433        /// "All agents stopped".
434        text: String,
435    },
436    /// Agents run again.
437    Resumed,
438    /// The mode changed.
439    #[serde(rename_all = "camelCase")]
440    ModeSet {
441        /// The mode now.
442        mode: ModeView,
443    },
444    /// The agent was added (spec 3.3 §5.7).
445    #[serde(rename_all = "camelCase")]
446    AgentAdded {
447        /// The agent now.
448        agent: crate::agents::AgentDetail,
449    },
450    /// The agent was changed.
451    #[serde(rename_all = "camelCase")]
452    AgentChanged {
453        /// The agent now.
454        agent: crate::agents::AgentDetail,
455    },
456    /// The agent was paused.
457    #[serde(rename_all = "camelCase")]
458    AgentPaused {
459        /// The agent now.
460        agent: crate::agents::AgentDetail,
461    },
462    /// The agent runs again.
463    #[serde(rename_all = "camelCase")]
464    AgentResumed {
465        /// The agent now.
466        agent: crate::agents::AgentDetail,
467    },
468    /// The agent was removed; its threads stay.
469    #[serde(rename_all = "camelCase")]
470    AgentRemoved {
471        /// What ended.
472        ended: crate::agents::EndedWork,
473    },
474    /// The agent changed since the version the surface showed: show it again (spec 3.3 §5.7).
475    #[serde(rename_all = "camelCase")]
476    AgentOutOfDate {
477        /// The agent now.
478        agent: crate::agents::AgentDetail,
479        /// "Finance was changed in the terminal at 10:01".
480        text: String,
481    },
482    /// A rule was copied to the agent (spec 3.3 S-I19).
483    #[serde(rename_all = "camelCase")]
484    RuleCopied {
485        /// The agent.
486        agent: String,
487        /// The rule's words.
488        label: String,
489    },
490    /// A drawn form was sent: its call is on its way to the drawing agent, which holds it for
491    /// the person's decision (spec 3.3 §7.4 rule 5). The form's state follows from that
492    /// decision, never from this answer.
493    #[serde(rename_all = "camelCase")]
494    FormSent {
495        /// The session.
496        session_id: String,
497        /// The drawn surface.
498        surface_id: String,
499        /// The version sent.
500        version: u64,
501        /// The call asked for.
502        call_id: String,
503    },
504}
505
506/// One frame of a session's feed (spec 3.3 §6): the snapshot, then the live tail.
507#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
508#[serde(tag = "type", rename_all = "camelCase")]
509pub enum FeedFrame {
510    /// One event of the session store; resume after its `seq` (`Last-Event-ID`).
511    #[serde(rename_all = "camelCase")]
512    Entry {
513        /// The entry.
514        entry: FeedEntry,
515    },
516    /// The session's open decisions changed.
517    #[serde(rename_all = "camelCase")]
518    Decisions {
519        /// The open decisions of the session.
520        cards: Vec<DecisionCard>,
521    },
522    /// The store's history of the session was replaced (rewound, or deleted and started
523    /// again): drop what was shown; the entries follow again from the start.
524    #[serde(rename_all = "camelCase")]
525    Reset {
526        /// How many events the store holds now.
527        len: u64,
528    },
529    /// An entry already sent changed: the turn after it ended in an error, which a
530    /// [`TurnFailed`](crate::ThreadItem::TurnFailed) item now says. Show it in place of the
531    /// entry with the same `seq`; resuming still goes after the last `seq` of an `Entry`.
532    #[serde(rename_all = "camelCase")]
533    Changed {
534        /// The entry, as it reads now.
535        entry: FeedEntry,
536    },
537}
538
539type Classify<T> = Arc<dyn Fn(&ApprovalRequest) -> T + Send + Sync>;
540
541/// A session's failed turns as thread items, by the `seq` of the entry each follows.
542type FailedTurns = std::collections::BTreeMap<u64, Vec<crate::model::ThreadItem>>;
543
544/// One read of a session's feed: the frames to send, the cursor after them and the id of the
545/// event at it, the open-decision signature and the failed turns the sent entries carry.
546struct FeedRead {
547    frames: Vec<FeedFrame>,
548    sent: u64,
549    last: Option<String>,
550    cards: Vec<(String, u64)>,
551    failed: FailedTurns,
552}
553
554/// Builds a [`SurfaceEngine`].
555pub struct SurfaceEngineBuilder {
556    source: Arc<dyn Source>,
557    audit: Option<AuditTrail>,
558    answers: Option<Arc<dyn AnswerLog>>,
559    projector: Projector,
560    quiet_set: bool,
561    poll: Duration,
562    clock: Arc<dyn Clock>,
563    voice_window: Duration,
564    stops_need: Option<String>,
565    card_hints: Vec<Arc<dyn CardHints>>,
566    granted: Vec<GrantedUse>,
567    #[cfg(feature = "genui")]
568    seals: Option<crate::genui::ApprovalSeals>,
569    cameras: Option<crate::camera::Cameras>,
570}
571
572impl fmt::Debug for SurfaceEngineBuilder {
573    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574        f.debug_struct("SurfaceEngineBuilder")
575            .field("projector", &self.projector)
576            .finish_non_exhaustive()
577    }
578}
579
580impl SurfaceEngineBuilder {
581    /// Writes a record of every command to `trail` (spec 3.3 §11). Without one, commands are
582    /// not audited.
583    #[must_use]
584    pub fn audit(mut self, trail: AuditTrail) -> Self {
585        self.audit = Some(trail);
586        self
587    }
588
589    /// Keeps how each answer was given in `log` instead of in memory.
590    #[must_use]
591    pub fn answers(mut self, log: Arc<dyn AnswerLog>) -> Self {
592        self.answers = Some(log);
593        self
594    }
595
596    /// Where decisions are also shown, for "Also on your phone and in Telegram".
597    #[must_use]
598    pub fn places(mut self, places: impl IntoIterator<Item = Place>) -> Self {
599        self.projector.places = places.into_iter().collect();
600        self
601    }
602
603    /// Shows times at `offset` east of UTC instead of the host's time zone.
604    #[must_use]
605    pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
606        self.projector.offset = offset;
607        self
608    }
609
610    /// Quiet time, overriding the source's.
611    #[must_use]
612    pub fn quiet_hours(mut self, quiet: adk_kernel::QuietHours) -> Self {
613        self.projector.quiet = Some(quiet);
614        self.quiet_set = true;
615        self
616    }
617
618    /// Shows the agent named `name` as `display_name`.
619    #[must_use]
620    pub fn agent_name(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
621        self.projector.names.insert(name.into(), display_name.into());
622        self
623    }
624
625    /// Writes a decision's heading — what will happen, in plain words — with `heading`
626    /// instead of from the tool and its main argument.
627    #[must_use]
628    pub fn heading(
629        mut self,
630        heading: impl Fn(&ApprovalRequest) -> String + Send + Sync + 'static,
631    ) -> Self {
632        self.projector.heading = Arc::new(heading) as Classify<String>;
633        self
634    }
635
636    /// Tells calls that spend money with `money` instead of by the `payments_*` tool names.
637    #[must_use]
638    pub fn money(
639        mut self,
640        money: impl Fn(&ApprovalRequest) -> bool + Send + Sync + 'static,
641    ) -> Self {
642        self.projector.money = Arc::new(money) as Classify<bool>;
643        self
644    }
645
646    /// Tells whether a call can be taken back with `reversibility`.
647    #[must_use]
648    pub fn reversibility(
649        mut self,
650        reversibility: impl Fn(&ApprovalRequest) -> Reversibility + Send + Sync + 'static,
651    ) -> Self {
652        self.projector.reversibility = Arc::new(reversibility) as Classify<Reversibility>;
653        self
654    }
655
656    /// Adds `hints`, a feature's [`CardHints`], after those added before (spec 3.3 §7.1): for
657    /// each field of a card the first hint that sets it wins, and [`heading`](Self::heading),
658    /// [`money`](Self::money) and [`reversibility`](Self::reversibility) stay the fallback. A
659    /// hint may only make a card stricter or add words; it never adds an answer or changes the
660    /// risk (§7.2).
661    ///
662    /// # Example
663    ///
664    /// ```rust,no_run
665    /// use std::sync::Arc;
666    /// use adk_core::ApprovalRequest;
667    /// use adk_surface::{CardHint, CardHints, LocalSource, SurfaceEngine};
668    ///
669    /// struct Payments;
670    ///
671    /// #[async_trait::async_trait]
672    /// impl CardHints for Payments {
673    ///     async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
674    ///         let mine = request.origin.as_ref()?.source == "mcp:payments";
675    ///         mine.then(|| CardHint::new().spends_money())
676    ///     }
677    /// }
678    ///
679    /// # fn example(source: LocalSource) {
680    /// let engine = SurfaceEngine::builder(Arc::new(source)).card_hints(Arc::new(Payments)).build();
681    /// # let _ = engine;
682    /// # }
683    /// ```
684    #[must_use]
685    pub fn card_hints(mut self, hints: Arc<dyn CardHints>) -> Self {
686        self.card_hints.push(hints);
687        self
688    }
689
690    /// Grants every agent the home runs `granted`, shown on its detail under "On this home it
691    /// can also:" (spec 3.3 §5.7, S-I12, S-I13). A host grants a use when it gives each agent
692    /// it runs the tools for it; a second grant with the same id replaces the first.
693    ///
694    /// # Example
695    ///
696    /// ```rust,no_run
697    /// use std::sync::Arc;
698    /// use adk_surface::{GrantedUse, LocalSource, SurfaceEngine};
699    ///
700    /// # fn example(source: LocalSource) {
701    /// let engine = SurfaceEngine::builder(Arc::new(source))
702    ///     .grant(GrantedUse::new(
703    ///         "genui",
704    ///         "Show forms and tables in your threads — sending asks you first",
705    ///     ))
706    ///     .build();
707    /// assert_eq!(engine.granted().len(), 1);
708    /// # }
709    /// ```
710    #[must_use]
711    pub fn grant(mut self, granted: GrantedUse) -> Self {
712        match self.granted.iter_mut().find(|known| known.id == granted.id) {
713            Some(known) => *known = granted,
714            None => self.granted.push(granted),
715        }
716        self
717    }
718
719    /// Seals each approval of a drawn form's call to the drawing the person saw, with
720    /// `seals` (spec 3.3 §7.4 rule 5); give the same seals to the harness that runs the
721    /// drawing agent (`HarnessAgentBuilder::requested_call_seal`), which checks them right
722    /// before the call runs.
723    #[cfg(feature = "genui")]
724    #[must_use]
725    pub fn approval_seals(mut self, seals: crate::genui::ApprovalSeals) -> Self {
726        self.seals = Some(seals);
727        self
728    }
729
730    /// Shows drawings in the extension catalog `catalog` too (spec 3.3 §6.1 `genui`,
731    /// extension catalogs): register every catalog the agents' render tools draw in
732    /// (`DrawToolset::catalog`). A drawing in a catalog not registered here is refused
733    /// ("this home does not render the catalog …").
734    ///
735    /// # Example
736    ///
737    /// ```rust,no_run
738    /// use std::sync::Arc;
739    /// use adk_surface::genui::DrawToolset;
740    /// use adk_surface::{LocalSource, SurfaceEngine};
741    ///
742    /// # fn example(source: LocalSource, toolset: DrawToolset) {
743    /// let engine = SurfaceEngine::builder(Arc::new(source)).with_catalog(toolset.catalog()).build();
744    /// assert_eq!(engine.catalogs().iter().count(), 2);
745    /// # }
746    /// ```
747    #[cfg(feature = "genui")]
748    #[must_use]
749    pub fn with_catalog(mut self, catalog: &'static crate::genui::Catalog) -> Self {
750        self.projector.catalogs = self.projector.catalogs.clone().with(catalog);
751        self
752    }
753
754    /// How often the feed reads the store when the source signals nothing sooner.
755    #[must_use]
756    pub fn poll_interval(mut self, poll: Duration) -> Self {
757        self.poll = poll;
758        self
759    }
760
761    /// The clock "waiting since" and quiet time are read against.
762    #[must_use]
763    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
764        self.clock = clock;
765        self
766    }
767
768    /// How long a spoken "allow once" can be cancelled (default
769    /// [`VOICE_CANCEL_WINDOW_SECS`](crate::rules::VOICE_CANCEL_WINDOW_SECS)).
770    #[must_use]
771    pub fn voice_cancel_window(mut self, window: Duration) -> Self {
772        self.voice_window = window;
773        self
774    }
775
776    /// Lets only callers in `group` give **Stop all** and **Resume all** (spec 3.3 §11
777    /// S-I10). Both act on every run the source makes, whoever started it, so a server that
778    /// admits more than one person keeps them for its operator; any other caller gets
779    /// `surface.operator_only`. Without it, every caller may.
780    ///
781    /// # Example
782    ///
783    /// ```rust,no_run
784    /// use std::sync::Arc;
785    /// use adk_surface::{LocalSource, SurfaceEngine};
786    ///
787    /// # fn example(source: LocalSource) {
788    /// let engine = SurfaceEngine::builder(Arc::new(source)).stops_need("operator").build();
789    /// # let _ = engine;
790    /// # }
791    /// ```
792    #[must_use]
793    pub fn stops_need(mut self, group: impl Into<String>) -> Self {
794        self.stops_need = Some(group.into());
795        self
796    }
797
798    /// Serves the live camera surface over `cameras` (spec 3.7 §8.2): the routes under
799    /// `/surface/cameras` read and act on them. Without it they answer `surface.unsupported`.
800    ///
801    /// # Example
802    ///
803    /// ```rust,no_run
804    /// use std::sync::Arc;
805    /// use adk_surface::camera::Cameras;
806    /// use adk_surface::{LocalSource, SurfaceEngine};
807    ///
808    /// # fn example(source: LocalSource, cameras: Cameras) {
809    /// let engine = SurfaceEngine::builder(Arc::new(source)).cameras(cameras).build();
810    /// # let _ = engine;
811    /// # }
812    /// ```
813    #[must_use]
814    pub fn cameras(mut self, cameras: crate::camera::Cameras) -> Self {
815        self.cameras = Some(cameras);
816        self
817    }
818
819    /// The engine.
820    pub fn build(mut self) -> SurfaceEngine {
821        if !self.quiet_set {
822            self.projector.quiet = self.source.quiet_hours();
823        }
824        // The source's rating counts beside the request's (spec 3.3 §7.2, spec 3.2 K-I9), so a
825        // call a kernel rates high needs presence or a paired local terminal on every surface.
826        let source = Arc::clone(&self.source);
827        let money = Arc::clone(&self.projector.money);
828        self.projector.money =
829            Arc::new(move |request| money(request) || source.moves_money(request));
830        let source = Arc::clone(&self.source);
831        self.projector.rates_high = Arc::new(move |request| source.rates_high(request));
832        // A drawn form's call never offers Always allow, whatever hints the host adds
833        // (spec 3.3 §7.4 rule 5, wave 4 decision 12).
834        #[cfg(feature = "genui")]
835        let drawn = Arc::new(crate::genui::DrawnHints::new(
836            Arc::clone(&self.source),
837            self.projector.clone(),
838        ));
839        #[cfg(feature = "genui")]
840        self.card_hints.insert(0, Arc::clone(&drawn) as Arc<dyn CardHints>);
841        self.projector.voice_window_secs =
842            u32::try_from(self.voice_window.as_millis().div_ceil(1000)).unwrap_or(u32::MAX);
843        SurfaceEngine {
844            inner: Arc::new(Inner {
845                source: self.source,
846                projector: self.projector,
847                audit: self.audit,
848                answers: self.answers.unwrap_or_else(|| Arc::new(InMemoryAnswerLog::new())),
849                poll: self.poll,
850                clock: self.clock,
851                voice_window: self.voice_window,
852                stops_need: self.stops_need,
853                card_hints: self.card_hints,
854                granted: self.granted,
855                cameras: self.cameras,
856                #[cfg(feature = "genui")]
857                drawn,
858                #[cfg(feature = "genui")]
859                seals: self.seals,
860                queues: Mutex::new(HashMap::new()),
861                next_input: AtomicU64::new(1),
862                draining: Mutex::new(HashSet::new()),
863                wake: Notify::new(),
864                spoken: Mutex::new(HashMap::new()),
865                changed_images: Mutex::new(HashMap::new()),
866                served: Mutex::new(std::collections::BTreeSet::new()),
867            }),
868        }
869    }
870}
871
872/// The engine every surface runs on (spec 3.3 §6): it reads a [`Source`], projects what it
873/// reads into cards, thread items, agent rows, the status line and the briefing, and carries
874/// out commands under the rules of §7.2 and §7.4.
875///
876/// Surfaces hold no state a reconnect cannot rebuild: everything here is read from the
877/// source's stores, except input queued behind an open decision or a running turn, which
878/// waits in this process and is sent, oldest first, once the session is free — whichever
879/// surface answered the decision. A message queued behind a running turn is offered to that
880/// turn (§6 "steer"): it leaves the queue when the turn takes it, and stays in its place when
881/// the turn hands it back, so it reaches the agent exactly once.
882///
883/// # Example
884///
885/// ```rust,no_run
886/// use std::sync::Arc;
887/// use adk_surface::{Caller, LocalSource, Origin, SurfaceEngine, SurfaceKind};
888///
889/// # async fn example(sessions: Arc<dyn adk_session::SessionService>, approvals: Arc<dyn adk_core::ApprovalService>) -> adk_surface::Result<()> {
890/// let source = LocalSource::builder("adk-rust").sessions(sessions).approvals(approvals).build()?;
891/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
892/// let me = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
893/// for card in engine.decisions(&me).await? {
894///     println!("{} · {}", card.heading, card.status_text);
895/// }
896/// # Ok(())
897/// # }
898/// ```
899#[derive(Clone)]
900pub struct SurfaceEngine {
901    inner: Arc<Inner>,
902}
903
904struct Inner {
905    source: Arc<dyn Source>,
906    projector: Projector,
907    audit: Option<AuditTrail>,
908    answers: Arc<dyn AnswerLog>,
909    poll: Duration,
910    clock: Arc<dyn Clock>,
911    voice_window: Duration,
912    /// The group Stop all and Resume all need, when only some callers may give them.
913    stops_need: Option<String>,
914    /// Features' card hints, in the order they were added (spec 3.3 §7.1).
915    card_hints: Vec<Arc<dyn CardHints>>,
916    /// What every agent the home runs may also do (spec 3.3 §5.7).
917    granted: Vec<GrantedUse>,
918    /// The cameras of the live camera surface (spec 3.7 §8.2).
919    cameras: Option<crate::camera::Cameras>,
920    /// The cards of drawn forms this engine sent (spec 3.3 §7.4 rule 5).
921    #[cfg(feature = "genui")]
922    drawn: Arc<crate::genui::DrawnHints>,
923    /// The seals of approvals of drawn forms' calls, when set.
924    #[cfg(feature = "genui")]
925    seals: Option<crate::genui::ApprovalSeals>,
926    /// Input queued behind an open decision or a running turn, per (user, session), oldest
927    /// first.
928    queues: Mutex<HashMap<(String, String), VecDeque<QueuedInput>>>,
929    /// The id of the next queued message.
930    next_input: AtomicU64,
931    /// Sessions with a delivery loop running. Changed only under the `queues` lock, so a
932    /// message queued while a loop ends always finds a loop.
933    draining: Mutex<HashSet<(String, String)>>,
934    /// Wakes the delivery loops to look again: an answer or a message through this engine.
935    wake: Notify,
936    /// Spoken "allow once" answers inside their cancel window, by decision.
937    spoken: Mutex<HashMap<String, Spoken>>,
938    /// Images a person changed through this engine, by the new image's digest: the digest it
939    /// replaced, which the card of the call held again names (spec 3.7 §8.2).
940    changed_images: Mutex<HashMap<String, String>>,
941    /// The parts of the home served beside the engine's routes that routers and the host named
942    /// ([`SurfaceEngine::serve`]).
943    served: Mutex<std::collections::BTreeSet<Served>>,
944}
945
946/// A send's audit fields, with how many images the message carries when it carries any.
947fn with_images(mut fields: Value, images: usize) -> Value {
948    if images > 0 {
949        fields["images"] = json!(images);
950    }
951    fields
952}
953
954/// One message of a session's queue.
955struct QueuedInput {
956    /// Names the message while it waits, whatever joins or leaves the queue.
957    id: u64,
958    text: String,
959    /// The images the person sent with it.
960    images: Vec<crate::images::MessageImage>,
961    /// The session's running turn holds it (spec 3.3 §6 "steer"): it is sent as the next
962    /// message only once the turn hands it back.
963    offered: bool,
964}
965
966/// A spoken "allow once" waiting out its cancel window.
967struct Spoken {
968    /// The task that commits it.
969    handle: JoinHandle<()>,
970    /// Which answer this is: the task commits only while its own entry is here.
971    token: Arc<()>,
972    /// Who said it: only they cancel it.
973    user: String,
974    /// The decision.
975    request: ApprovalRequest,
976    /// The digest of what was said, for the record of its cancel (spec 3.3 §5.6).
977    digest: Option<String>,
978}
979
980impl fmt::Debug for SurfaceEngine {
981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982        f.debug_struct("SurfaceEngine")
983            .field("app_name", &self.inner.source.app_name())
984            .field("projector", &self.inner.projector)
985            .finish_non_exhaustive()
986    }
987}
988
989impl SurfaceEngine {
990    /// A builder over `source`.
991    pub fn builder(source: Arc<dyn Source>) -> SurfaceEngineBuilder {
992        let offset = *Local::now().offset();
993        SurfaceEngineBuilder {
994            source,
995            audit: None,
996            answers: None,
997            projector: Projector::new(offset),
998            quiet_set: false,
999            poll: DEFAULT_POLL_INTERVAL,
1000            clock: Arc::new(SystemClock),
1001            voice_window: Duration::from_secs(u64::from(rules::VOICE_CANCEL_WINDOW_SECS)),
1002            stops_need: None,
1003            card_hints: Vec::new(),
1004            granted: Vec::new(),
1005            #[cfg(feature = "genui")]
1006            seals: None,
1007            cameras: None,
1008        }
1009    }
1010
1011    /// The source.
1012    pub fn source(&self) -> &Arc<dyn Source> {
1013        &self.inner.source
1014    }
1015
1016    fn now(&self) -> DateTime<Utc> {
1017        self.inner.clock.now()
1018    }
1019
1020    /// The cameras of the live camera surface, when the engine serves them (spec 3.7 §8.2).
1021    pub fn camera_hub(&self) -> Option<&crate::camera::Cameras> {
1022        self.inner.cameras.as_ref()
1023    }
1024
1025    /// The engine's clock, for the camera views.
1026    pub(crate) fn clock_now(&self) -> DateTime<Utc> {
1027        self.now()
1028    }
1029
1030    /// How agents are named and times are shown.
1031    pub(crate) fn projector(&self) -> &Projector {
1032        &self.inner.projector
1033    }
1034
1035    /// `Ok` when `session` is one of `caller`'s (S-I8), `surface.not_found` otherwise.
1036    pub(crate) async fn owns_session(&self, caller: &Caller, session: &str) -> Result<()> {
1037        self.transcript(caller, session).await.map(|_| ())
1038    }
1039
1040    /// Sends `text` to `session` as `caller`'s message, queued behind an open decision or a
1041    /// running turn as a typed message is.
1042    pub(crate) async fn send_message(
1043        &self,
1044        caller: &Caller,
1045        session: &str,
1046        text: String,
1047    ) -> Result<CommandOutcome> {
1048        self.send(caller, session.to_string(), text, Vec::new(), false, true).await
1049    }
1050
1051    /// What every agent the home runs may also do, as the host granted it (spec 3.3 §5.7).
1052    ///
1053    /// # Example
1054    ///
1055    /// ```rust,no_run
1056    /// use std::sync::Arc;
1057    /// use adk_surface::{LocalSource, SurfaceEngine};
1058    ///
1059    /// # fn example(source: LocalSource) {
1060    /// let engine = SurfaceEngine::builder(Arc::new(source)).build();
1061    /// assert!(engine.granted().is_empty());
1062    /// # }
1063    /// ```
1064    pub fn granted(&self) -> &[GrantedUse] {
1065        &self.inner.granted
1066    }
1067
1068    /// The catalogs this engine shows drawings in: `forms` and every catalog registered with
1069    /// [`SurfaceEngineBuilder::with_catalog`] (spec 3.3 §6.1 `genui`).
1070    #[cfg(feature = "genui")]
1071    pub fn catalogs(&self) -> &crate::genui::Catalogs {
1072        &self.inner.projector.catalogs
1073    }
1074
1075    /// How long a spoken answer, or a spoken screen action, can be cancelled (spec 3.3 §5.6).
1076    #[cfg(feature = "verb-ui")]
1077    pub(crate) fn voice_cancel_window(&self) -> Duration {
1078        self.inner.voice_window
1079    }
1080
1081    /// `detail` with what the home grants every agent it runs: only an agent that runs, added
1082    /// or paused, is granted anything (spec 3.3 §5.7).
1083    fn with_granted(&self, mut detail: AgentDetail) -> AgentDetail {
1084        detail.granted = match detail.state {
1085            AgentLife::Active | AgentLife::Paused => self.inner.granted.clone(),
1086            AgentLife::Suggested
1087            | AgentLife::Removing
1088            | AgentLife::Removed
1089            | AgentLife::Refused => Vec::new(),
1090        };
1091        detail
1092    }
1093
1094    /// What the features say about `request`'s card, merged in the order they were added
1095    /// (spec 3.3 §7.1).
1096    async fn hint(&self, request: &ApprovalRequest) -> CardHint {
1097        let mut merged = CardHint::new();
1098        for hints in &self.inner.card_hints {
1099            if let Some(hint) = hints.hint(request).await {
1100                merged = merged.then(hint);
1101            }
1102        }
1103        merged
1104    }
1105
1106    // -----------------------------------------------------------------------
1107    // Reads
1108    // -----------------------------------------------------------------------
1109
1110    /// The decisions waiting for `caller`, oldest first, drawn from their inbox entries
1111    /// (spec 3.3 §7.1, S-I1).
1112    ///
1113    /// # Errors
1114    ///
1115    /// Returns the source's error.
1116    pub async fn decisions(&self, caller: &Caller) -> Result<Vec<DecisionCard>> {
1117        self.open_decisions(caller, None).await
1118    }
1119
1120    /// The decisions of one session waiting for `caller`, oldest first (spec 3.3 §10 C1).
1121    ///
1122    /// # Errors
1123    ///
1124    /// Returns the source's error.
1125    pub async fn session_decisions(
1126        &self,
1127        caller: &Caller,
1128        session: &str,
1129    ) -> Result<Vec<DecisionCard>> {
1130        self.open_decisions(caller, Some(session)).await
1131    }
1132
1133    async fn open_decisions(
1134        &self,
1135        caller: &Caller,
1136        session: Option<&str>,
1137    ) -> Result<Vec<DecisionCard>> {
1138        let mut requests: Vec<ApprovalRequest> = self
1139            .inner
1140            .source
1141            .requests(caller, session, true)
1142            .await?
1143            .into_iter()
1144            .filter(|request| {
1145                owns(caller, request)
1146                    && request.state == ApprovalState::Pending
1147                    && session.is_none_or(|session| request.scope.session_id == session)
1148            })
1149            .collect();
1150        requests.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
1151        let held: HashSet<&str> =
1152            requests.iter().map(|request| request.fingerprint.as_str()).collect();
1153        let mut cards = Vec::with_capacity(requests.len());
1154        for request in &requests {
1155            // A later step of an open screen plan waits behind its first step's card: one card
1156            // per plan (spec 3.7 Q8).
1157            if let Some(plan) = self.inner.source.screen_plan(request).await
1158                && plan.step > 0
1159                && plan.open
1160                && plan.fingerprints.first().is_some_and(|first| held.contains(first.as_str()))
1161            {
1162                continue;
1163            }
1164            cards.push(self.card(caller, request).await?);
1165        }
1166        Ok(cards)
1167    }
1168
1169    /// One decision as `caller` sees it: waiting, or decided with who, where and when.
1170    ///
1171    /// # Errors
1172    ///
1173    /// Returns `surface.not_found` when no decision of the caller has `id` (S-I8), or the
1174    /// source's error.
1175    pub async fn decision(&self, caller: &Caller, id: &str) -> Result<DecisionCard> {
1176        let request = self.owned_request(caller, id).await?;
1177        self.card(caller, &request).await
1178    }
1179
1180    async fn owned_request(&self, caller: &Caller, id: &str) -> Result<ApprovalRequest> {
1181        self.inner
1182            .source
1183            .request(id)
1184            .await?
1185            .filter(|request| owns(caller, request))
1186            .ok_or_else(|| SurfaceError::not_found(format!("decision '{id}'")))
1187    }
1188
1189    async fn card(&self, caller: &Caller, request: &ApprovalRequest) -> Result<DecisionCard> {
1190        let always = match request.state {
1191            ApprovalState::Pending => self.always_label(request).await,
1192            _ => None,
1193        };
1194        let answer = match request.state {
1195            ApprovalState::Pending => None,
1196            // Where an answer was given only adds to the card; the card is shown without it.
1197            _ => self.inner.answers.find_for(request).await.unwrap_or_else(|error| {
1198                tracing::warn!(error = %error, decision.id = %request.id, "where a decision was answered could not be read");
1199                None
1200            }),
1201        };
1202        let hint = self.hint(request).await;
1203        let mut card =
1204            self.inner.projector.card(request, caller, always, answer.as_ref(), self.now(), &hint);
1205        // A call held again after a person changed it closed this request with a refusal; it
1206        // reads as the change it was (spec 3.7 V-I5).
1207        if let (Some(decided), Some(record)) = (card.decided.as_mut(), answer.as_ref())
1208            && request.state == ApprovalState::Rejected
1209            && record.answer == Answer::Edit
1210            && record.approval_id == request.id
1211        {
1212            decided.answer = crate::model::DecidedAnswer::Edited;
1213            decided.text = words::held_again_at(&decided.at_text);
1214            if let Some(step) = card.timeline.last_mut() {
1215                step.text = decided.text.clone();
1216            }
1217        }
1218        self.add_media(caller, request, &hint, &mut card).await;
1219        self.add_plan(caller, request, &hint, &mut card).await;
1220        // How far a surface's answer reaches: once, or by the standing rule it made (§5.4).
1221        if let (Some(decided), Some(record)) = (card.decided.as_mut(), answer.as_ref())
1222            && decided.via.is_some()
1223        {
1224            decided.scope_text = match record.answer {
1225                Answer::AllowOnce => Some(words::DONE_ONCE.to_string()),
1226                Answer::AlwaysAllow => self
1227                    .inner
1228                    .source
1229                    .always_allow_offer(request)
1230                    .await
1231                    .map(|offer| lower_first(&offer.label)),
1232                Answer::Edit | Answer::Deny => None,
1233            };
1234        }
1235        // An added agent is drawn with its own name and colour (spec 3.3 §5.7).
1236        if let Some(detail) = self.inner.source.agent(caller.user_id(), &card.agent.name).await? {
1237            card.agent = detail.agent;
1238        }
1239        // "How it got here" for a suggested agent: the suggesting turn, naming what it read.
1240        if card.adds_agent.is_some()
1241            && let Ok(Some(events)) =
1242                self.inner.source.transcript(caller.user_id(), &request.scope.session_id).await
1243        {
1244            let projector = &self.inner.projector;
1245            let steps = crate::agents::suggestion_steps(
1246                &events,
1247                &card.agent.display_name,
1248                request.created_at,
1249                |at| projector.hh_mm(at),
1250            );
1251            let mut timeline: Vec<crate::model::TimelineStep> = steps
1252                .into_iter()
1253                .map(|text| crate::model::TimelineStep { text, current: false })
1254                .collect();
1255            // The suggesting turn's steps take the place of a hint's first step and "Asked at".
1256            let asked = usize::from(hint.first_step.is_some()) + 1;
1257            timeline.extend(card.timeline.into_iter().skip(asked));
1258            card.timeline = timeline;
1259        }
1260        Ok(card)
1261    }
1262
1263    /// The screen plan whose one card `request` carries (spec 3.7 Q8): the plan's first step,
1264    /// while no one decided the plan, or once the request itself was decided.
1265    async fn card_plan(&self, request: &ApprovalRequest) -> Option<HeldPlan> {
1266        self.inner
1267            .source
1268            .screen_plan(request)
1269            .await
1270            .filter(|plan| plan.step == 0 && (plan.open || request.state != ApprovalState::Pending))
1271    }
1272
1273    /// A screen plan's first step carries the plan's one card (spec 3.7 Q8): the plan's
1274    /// heading, its window and every step with its target in place of the call, and only
1275    /// **Allow** and **Deny** — **Allow** where the whole plan can be shown, once it was shown
1276    /// in full. A chat card carries the heading alone (S-I5).
1277    async fn add_plan(
1278        &self,
1279        caller: &Caller,
1280        request: &ApprovalRequest,
1281        hint: &CardHint,
1282        card: &mut DecisionCard,
1283    ) {
1284        let Some(plan) = self.card_plan(request).await else { return };
1285        let steps = plan.view.steps.len();
1286        let (text, truncated) = project::cut_call_text(plan.text.clone());
1287        if rules::row(caller) == Row::Chat {
1288            card.heading = words::screen_plan_chat_heading(steps);
1289            card.call.truncated = truncated;
1290        } else {
1291            card.heading = project::capped(
1292                &words::screen_plan_heading(steps, &plan.view.window),
1293                project::CARD_HEADING_LIMIT,
1294            );
1295            card.call = crate::model::CallView {
1296                tool: request.tool_name.clone(),
1297                args: serde_json::to_value(&plan.view).unwrap_or(Value::Null),
1298                text,
1299                truncated,
1300            };
1301            card.detail = Some(crate::model::CardDetail::new(words::SCREEN_PLAN_DETAIL));
1302            card.plan = Some(plan.view.clone());
1303        }
1304        if request.state == ApprovalState::Pending {
1305            let mut facts = self.inner.projector.facts(request, None, hint);
1306            facts.plan = true;
1307            facts.truncated = truncated;
1308            card.allowed = rules::allowed_answers(caller, &facts);
1309        } else if let Some(decided) = card.decided.as_mut()
1310            && decided.answer == crate::model::DecidedAnswer::Edited
1311        {
1312            // The plan's binding is not a person's edit: the card reads as the yes it was.
1313            decided.answer = crate::model::DecidedAnswer::Yes;
1314            let phrase = decided.via.as_ref().map(crate::origin::Via::phrase);
1315            decided.text = words::said(
1316                (!decided.by_you).then_some(decided.by.as_str()),
1317                words::SaidWhat::Yes,
1318                phrase.as_deref(),
1319                &decided.at_text,
1320            );
1321            if let Some(step) = card.timeline.last_mut() {
1322                step.text = project::capped(&decided.text, project::CARD_LINE_LIMIT);
1323            }
1324        }
1325    }
1326
1327    /// Closes `plan`'s open card, whose first step `request` holds, because everything was
1328    /// stopped (spec 3.7 Q8, V-I17).
1329    async fn close_plan(&self, request: &ApprovalRequest, plan: &HeldPlan) {
1330        if let Err(error) = self
1331            .inner
1332            .source
1333            .close_screen_plan(request, plan, words::STOP_ALL_CLOSED_THE_PLAN)
1334            .await
1335        {
1336            tracing::warn!(error = %error, decision.id = %request.id, "a screen plan's card stayed open after a stop");
1337        }
1338        self.inner.wake.notify_waiters();
1339    }
1340
1341    /// The caller's decisions answered or ended since `since`, newest first, for a surface
1342    /// that opens again after a while, such as the phone (spec 3.3 §5.4).
1343    ///
1344    /// # Errors
1345    ///
1346    /// Returns the source's error.
1347    pub async fn decided_since(
1348        &self,
1349        caller: &Caller,
1350        since: DateTime<Utc>,
1351    ) -> Result<Vec<DecisionCard>> {
1352        let decided_at = |request: &ApprovalRequest| {
1353            request
1354                .decisions
1355                .last()
1356                .map(|decision| decision.decided_at)
1357                .or(request.resolved_at)
1358                .unwrap_or(request.created_at)
1359        };
1360        let mut requests: Vec<ApprovalRequest> = self
1361            .inner
1362            .source
1363            .requests(caller, None, false)
1364            .await?
1365            .into_iter()
1366            .filter(|request| {
1367                owns(caller, request)
1368                    && request.state != ApprovalState::Pending
1369                    && decided_at(request) >= since
1370            })
1371            .collect();
1372        requests.sort_by(|a, b| decided_at(b).cmp(&decided_at(a)).then_with(|| a.id.cmp(&b.id)));
1373        let mut cards = Vec::with_capacity(requests.len());
1374        for request in &requests {
1375            cards.push(self.card(caller, request).await?);
1376        }
1377        Ok(cards)
1378    }
1379
1380    /// The label of "Always allow" for `request`, when the source can create its rule. A
1381    /// request that needs more than one approver never offers it: the rule would let every
1382    /// later call skip the other approvers (spec 3.3 §7.2, §8.2).
1383    /// The images `request` holds, on its card, and what they change about its answers and
1384    /// its timeline (spec 3.7 §8.2): a chat card carries none (S-I5), and a decision whose run
1385    /// ended while it waits says so (board choice A12).
1386    async fn add_media(
1387        &self,
1388        caller: &Caller,
1389        request: &ApprovalRequest,
1390        hint: &CardHint,
1391        card: &mut DecisionCard,
1392    ) {
1393        let waiting = request.state == ApprovalState::Pending;
1394        if waiting && let Some(ended) = self.inner.source.run_ended(request).await {
1395            let at_text = self.inner.projector.hh_mm(ended);
1396            let minutes = (ended - request.created_at).num_minutes().max(0);
1397            card.parked = Some(crate::model::ParkedView {
1398                at: ended,
1399                text: words::stopped_waiting(&card.agent.display_name, &at_text),
1400                at_text: at_text.clone(),
1401            });
1402            let at = card.timeline.len().saturating_sub(1);
1403            let step = crate::model::TimelineStep {
1404                text: words::run_ended(minutes, &at_text),
1405                current: false,
1406            };
1407            card.timeline.insert(at, step);
1408        }
1409        let decided = card.decided.as_ref().map(|decided| decided.answer);
1410        let agent = card.agent.display_name.clone();
1411        let Some(media) = self.media(request, hint, decided, &agent).await else { return };
1412        if waiting {
1413            rules::image_answers(rules::row(caller), self.image_gate(&media), &mut card.allowed);
1414            if let Some(day) =
1415                media.images.iter().find_map(|image| image.purged.as_ref()?.day.clone())
1416            {
1417                let at = card.timeline.len().saturating_sub(1);
1418                let step = crate::model::TimelineStep {
1419                    text: words::image_deleted_step(&day),
1420                    current: false,
1421                };
1422                card.timeline.insert(at, step);
1423            }
1424        }
1425        if rules::row(caller) != Row::Chat {
1426            card.media = Some(media);
1427        }
1428    }
1429
1430    /// The media of `request`'s card, or `None` when it holds no image.
1431    async fn media(
1432        &self,
1433        request: &ApprovalRequest,
1434        hint: &CardHint,
1435        decided: Option<crate::model::DecidedAnswer>,
1436        agent: &str,
1437    ) -> Option<crate::evidence::CardMedia> {
1438        let first = crate::evidence::images(request).first().map(|image| image.digest.clone())?;
1439        let kept = self.inner.source.evidence_kept(request).await;
1440        let replaces = {
1441            let changed =
1442                self.inner.changed_images.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1443            request
1444                .args_redacted
1445                .get("image")
1446                .and_then(Value::as_str)
1447                .and_then(|named| changed.get(named))
1448                .or_else(|| changed.get(&first))
1449                .cloned()
1450        };
1451        // "Open the source image" opens the annotated viewer when the source keeps the
1452        // session's images and the feature named no other place (board choice A9).
1453        let viewer_facts =
1454            hint.media.as_ref().filter(|facts| facts.source_href.is_none()).and_then(|facts| {
1455                let named = request.args_redacted.get("image").and_then(Value::as_str)?;
1456                self.inner.source.keeps_vision_answers().then(|| {
1457                    facts.clone().with_source_href(crate::viewer::viewer_path(
1458                        &request.scope.session_id,
1459                        named,
1460                    ))
1461                })
1462            });
1463        crate::evidence::project(
1464            request,
1465            &crate::evidence::MediaInput {
1466                facts: viewer_facts.as_ref().or(hint.media.as_ref()),
1467                kept: &kept,
1468                decided,
1469                agent: agent.to_string(),
1470                now: self.now(),
1471                offset: self.inner.projector.offset,
1472                can_change: self.inner.source.holds_again(),
1473                replaces,
1474            },
1475        )
1476    }
1477
1478    /// What the rules need to know of a card's images.
1479    fn image_gate(&self, media: &crate::evidence::CardMedia) -> rules::ImageGate {
1480        rules::ImageGate {
1481            sendable: media.sendable(),
1482            holds_again: self.inner.source.holds_again(),
1483        }
1484    }
1485
1486    /// The `index`th image decision `id` holds as evidence, for `caller` (spec 3.7 §8.3): only a
1487    /// decision the caller may see, its bytes checked against the evidence's digest by the
1488    /// source.
1489    ///
1490    /// # Errors
1491    ///
1492    /// `surface.not_found` when the caller has no such decision or image, or the image is no
1493    /// longer kept; the source's error.
1494    pub async fn evidence_image(
1495        &self,
1496        caller: &Caller,
1497        id: &str,
1498        index: usize,
1499    ) -> Result<crate::evidence::EvidenceBytes> {
1500        let request = self.owned_request(caller, id).await?;
1501        let missing = || SurfaceError::not_found(format!("image {index} of decision '{id}'"));
1502        if index >= crate::evidence::images(&request).len() {
1503            return Err(missing());
1504        }
1505        self.inner.source.evidence_image(&request, index).await?.ok_or_else(missing)
1506    }
1507
1508    // -----------------------------------------------------------------------
1509    // The annotated viewer (spec 3.7 §8.2, X12)
1510    // -----------------------------------------------------------------------
1511
1512    /// The answer records of `session` for `caller`, parsed; a record that does not parse is
1513    /// logged and left out.
1514    async fn vision_records(
1515        &self,
1516        caller: &Caller,
1517        session: &str,
1518    ) -> Result<Vec<crate::viewer::Record>> {
1519        // Only the caller's own session (S-I8): the inbox's rule for a thread.
1520        self.transcript(caller, session).await?;
1521        let raw = self.inner.source.vision_answers(caller.user_id(), session).await?;
1522        Ok(raw
1523            .into_iter()
1524            .filter_map(|value| match crate::viewer::Record::parse(value) {
1525                Ok(record) => Some(record),
1526                Err(error) => {
1527                    tracing::warn!(error = %error, session.id = %session, "an answer record is not shown");
1528                    None
1529                }
1530            })
1531            .collect())
1532    }
1533
1534    /// The annotated viewer of image `image` — a `sha256:` digest, or the name of an image
1535    /// the session holds — in `caller`'s `session` (spec 3.7 §8.2, X12): every answer the
1536    /// vision tools gave for it, `answer` shown (the newest otherwise), `compare` beside it.
1537    ///
1538    /// # Errors
1539    ///
1540    /// `surface.not_found` when the caller has no such session or the session no such image;
1541    /// the source's error.
1542    pub async fn viewer(
1543        &self,
1544        caller: &Caller,
1545        session: &str,
1546        image: &str,
1547        answer: Option<&str>,
1548        compare: Option<&str>,
1549    ) -> Result<crate::viewer::ViewerView> {
1550        let records = self.vision_records(caller, session).await?;
1551        let missing = || SurfaceError::not_found(format!("image '{image}' of session '{session}'"));
1552        let digest = if image.starts_with("sha256:") {
1553            image.to_string()
1554        } else if let Some(record) = records.iter().find(|record| {
1555            record.image.name.as_deref() == Some(image)
1556                || record.image.artifact.as_deref() == Some(image)
1557        }) {
1558            record.image.digest.clone()
1559        } else {
1560            let bytes = self
1561                .inner
1562                .source
1563                .vision_image(caller.user_id(), session, image)
1564                .await?
1565                .ok_or_else(missing)?;
1566            crate::evidence::digest_of(&bytes.bytes)
1567        };
1568        let records: Vec<crate::viewer::Record> =
1569            records.into_iter().filter(|record| record.image.digest == digest).collect();
1570        let agent = records.last().map(|record| record.agent.clone()).unwrap_or_default();
1571        let files = self.inner.source.example_files(caller.user_id()).await?;
1572        let input = crate::viewer::ViewerInput {
1573            session,
1574            agent_name: self.inner.projector.agent(&agent).display_name,
1575            offset: self.inner.projector.offset,
1576            can_save: files.is_some(),
1577            files: files.unwrap_or_default(),
1578        };
1579        if let Some(view) = crate::viewer::view(&records, answer, compare, &input) {
1580            return Ok(view);
1581        }
1582        // Nothing has answered for it yet: the picture alone.
1583        let bytes = self.inner.source.vision_image(caller.user_id(), session, &digest).await?;
1584        let bytes = match bytes {
1585            Some(bytes) => bytes,
1586            None => self
1587                .inner
1588                .source
1589                .vision_image(caller.user_id(), session, image)
1590                .await?
1591                .ok_or_else(missing)?,
1592        };
1593        Ok(crate::viewer::unanswered(session, image, &digest, &bytes, &input))
1594    }
1595
1596    /// The bytes of image `image` (a digest or a name) of `caller`'s `session`, checked
1597    /// against its digest (spec 3.7 §8.3).
1598    ///
1599    /// # Errors
1600    ///
1601    /// `surface.not_found` when the caller has no such session or image; the source's error.
1602    pub async fn viewer_image(
1603        &self,
1604        caller: &Caller,
1605        session: &str,
1606        image: &str,
1607    ) -> Result<crate::evidence::EvidenceBytes> {
1608        self.transcript(caller, session).await?;
1609        self.inner.source.vision_image(caller.user_id(), session, image).await?.ok_or_else(|| {
1610            SurfaceError::not_found(format!("image '{image}' of session '{session}'"))
1611        })
1612    }
1613
1614    /// The `RegionSet` of answer `answer` in `caller`'s `session`, as the vision tools
1615    /// published it (board choice V14); with `with`, both answers' sets in an array.
1616    ///
1617    /// # Errors
1618    ///
1619    /// `surface.not_found` when the caller has no such session or answer.
1620    pub async fn viewer_export(
1621        &self,
1622        caller: &Caller,
1623        session: &str,
1624        answer: &str,
1625        with: Option<&str>,
1626    ) -> Result<Value> {
1627        let records = self.vision_records(caller, session).await?;
1628        let set = |id: &str| {
1629            crate::viewer::find(&records, id)
1630                .map(|record| serde_json::to_value(&record.region_set).unwrap_or(Value::Null))
1631                .ok_or_else(|| {
1632                    SurfaceError::not_found(format!("answer '{id}' of session '{session}'"))
1633                })
1634        };
1635        match with {
1636            Some(other) => Ok(Value::Array(vec![set(answer)?, set(other)?])),
1637            None => set(answer),
1638        }
1639    }
1640
1641    /// Saves a labelled example from an answer in `caller`'s `session` (board choices V11–V13):
1642    /// an `adk-eval` case in the eval set `example.file`, its image beside the file. The run's
1643    /// answer is untouched; the example is recorded (`surface.vision.example`).
1644    ///
1645    /// # Errors
1646    ///
1647    /// `surface.not_found` when the caller has no such session or answer; `surface.invalid`
1648    /// when the example does not fit the answer or the file; `surface.unsupported` when the
1649    /// source saves no examples.
1650    pub async fn save_example(
1651        &self,
1652        caller: &Caller,
1653        session: &str,
1654        example: &crate::viewer::LabelledExample,
1655    ) -> Result<crate::viewer::SavedExample> {
1656        crate::viewer::check_file(&example.file).map_err(SurfaceError::Invalid)?;
1657        let records = self.vision_records(caller, session).await?;
1658        let record = crate::viewer::find(&records, &example.answer).ok_or_else(|| {
1659            SurfaceError::not_found(format!("answer '{}' of session '{session}'", example.answer))
1660        })?;
1661        let case = crate::viewer::example_case(record, example).map_err(SurfaceError::Invalid)?;
1662        let image = self
1663            .inner
1664            .source
1665            .vision_image(caller.user_id(), session, &record.image.digest)
1666            .await?
1667            .ok_or_else(|| SurfaceError::not_found(format!("image '{}'", record.image.digest)))?;
1668        let existing = self.inner.source.example_set(caller.user_id(), &example.file).await?;
1669        let set = crate::viewer::with_case(existing, &example.file, case);
1670        let image_path = crate::viewer::fixture_image_path(&record.image.digest, &image.mime_type);
1671        // The example is on record before it is written (spec 3.3 §11).
1672        self.record(
1673            caller,
1674            SURFACE_AUDIT_VISION_EXAMPLE,
1675            json!({
1676                "sessionId": session,
1677                "answer": record.call_id,
1678                "invocationId": record.invocation_id,
1679                "tool": record.tool,
1680                "imageDigest": record.image.digest,
1681                "file": example.file,
1682                "caseName": example.case_name,
1683                "scope": example.scope,
1684                "region": example.region,
1685            }),
1686        )
1687        .await?;
1688        self.inner.source.save_example(caller, &example.file, set, &image_path, &image).await?;
1689        Ok(crate::viewer::SavedExample {
1690            file: example.file.clone(),
1691            case_name: example.case_name.clone(),
1692            image: image_path,
1693            text: format!(
1694                "Saved to {} as {}. The run's answer stays as it was.",
1695                example.file, example.case_name
1696            ),
1697        })
1698    }
1699
1700    async fn always_label(&self, request: &ApprovalRequest) -> Option<String> {
1701        if request.policy.quorum > 1 {
1702            return None;
1703        }
1704        self.inner.source.always_allow_offer(request).await.map(|offer| offer.label)
1705    }
1706
1707    /// The session's thread: every event of its store, numbered by position (spec 3.3 §6).
1708    ///
1709    /// # Errors
1710    ///
1711    /// Returns `surface.not_found` when the caller has no such session (S-I8), or the
1712    /// source's error.
1713    pub async fn thread(&self, caller: &Caller, session: &str) -> Result<Vec<FeedEntry>> {
1714        let events = self.transcript(caller, session).await?;
1715        let links = self.links(caller, session, &events).await?;
1716        let answered = project::answered_calls(&events);
1717        let failed = self.failed_turns(caller, session, &events).await;
1718        Ok(events
1719            .iter()
1720            .enumerate()
1721            .map(|(index, event)| self.entry(index as u64 + 1, event, &links, &answered, &failed))
1722            .collect())
1723    }
1724
1725    /// The entry of the event at `seq`, ending with the turns `failed` says ended in an error
1726    /// after it.
1727    fn entry(
1728        &self,
1729        seq: u64,
1730        event: &adk_core::Event,
1731        links: &HashMap<u64, project::Link>,
1732        answered: &HashSet<String>,
1733        failed: &FailedTurns,
1734    ) -> FeedEntry {
1735        let mut entry = self.inner.projector.entry(seq, event, links, answered);
1736        entry.items.extend(failed.get(&seq).into_iter().flatten().cloned());
1737        entry
1738    }
1739
1740    /// The session's turns that ended in an error, as thread items keyed by the `seq` of the
1741    /// last event before each ended. A turn that failed before the session held any event has
1742    /// no entry to follow and is left out. When the source cannot say, the thread shows
1743    /// without them.
1744    async fn failed_turns(
1745        &self,
1746        caller: &Caller,
1747        session: &str,
1748        events: &[adk_core::Event],
1749    ) -> FailedTurns {
1750        let failures = match self.inner.source.turn_failures(caller.user_id(), session).await {
1751            Ok(failures) => failures,
1752            Err(error) => {
1753                tracing::warn!(session.id = %session, error = %error, "the turns that failed could not be read; the thread shows without them");
1754                return FailedTurns::new();
1755            }
1756        };
1757        let mut failed = FailedTurns::new();
1758        for failure in failures {
1759            let Some(index) = events.iter().rposition(|event| event.timestamp <= failure.at) else {
1760                continue;
1761            };
1762            failed
1763                .entry(index as u64 + 1)
1764                .or_default()
1765                .push(self.inner.projector.turn_failed(&failure));
1766        }
1767        failed
1768    }
1769
1770    async fn transcript(&self, caller: &Caller, session: &str) -> Result<Vec<adk_core::Event>> {
1771        self.inner
1772            .source
1773            .transcript(caller.user_id(), session)
1774            .await?
1775            .ok_or_else(|| SurfaceError::not_found(format!("session '{session}'")))
1776    }
1777
1778    /// The inbox entry of each held call in the session's `events`, by `seq`
1779    /// ([`project::links`]).
1780    async fn links(
1781        &self,
1782        caller: &Caller,
1783        session: &str,
1784        events: &[adk_core::Event],
1785    ) -> Result<HashMap<u64, project::Link>> {
1786        let requests: Vec<ApprovalRequest> = self
1787            .inner
1788            .source
1789            .requests(caller, Some(session), false)
1790            .await?
1791            .into_iter()
1792            .filter(|request| owns(caller, request) && request.scope.session_id == session)
1793            .collect();
1794        Ok(project::links(events, &requests))
1795    }
1796
1797    /// The session's feed (spec 3.3 §6): every event after `after` (none: from the start) as
1798    /// an [`Entry`](FeedFrame::Entry) numbered by its position in the session store, the
1799    /// session's open decisions, then the live tail. Resuming with the last `seq` received
1800    /// never skips or repeats an event.
1801    ///
1802    /// While the stream runs, a history the store replaced — rewound, or deleted and started
1803    /// again — sends [`Reset`](FeedFrame::Reset) and the entries again from the start, whether
1804    /// it got shorter or grew back past what was sent. A client that resumes after `after`
1805    /// is trusted to hold the store's events up to it.
1806    ///
1807    /// A turn that ends in an error leaves no event, so the entry it follows is sent again as
1808    /// [`Changed`](FeedFrame::Changed), ending with a
1809    /// [`TurnFailed`](crate::ThreadItem::TurnFailed) item; a resumed stream sends each entry
1810    /// before `after` that carries one.
1811    ///
1812    /// The stream ends with an error when the session cannot be read.
1813    pub fn feed(
1814        &self,
1815        caller: Caller,
1816        session: String,
1817        after: Option<u64>,
1818    ) -> BoxStream<'static, Result<FeedFrame>> {
1819        struct State {
1820            engine: SurfaceEngine,
1821            caller: Caller,
1822            session: String,
1823            sent: u64,
1824            /// The id of the event at `sent`, once this stream has read it.
1825            last: Option<String>,
1826            cards: Option<Vec<(String, u64)>>,
1827            /// The failed turns the entries sent so far carry; `None` before the first read,
1828            /// so a resumed stream sends again each entry before `after` whose turn failed.
1829            failed: Option<FailedTurns>,
1830            buffer: VecDeque<FeedFrame>,
1831            /// The wait for the next change, begun before the last read so nothing that
1832            /// changes during a read is missed; `None` when a change came during the read.
1833            next: Option<BoxFuture<'static, ()>>,
1834            first: bool,
1835            done: bool,
1836        }
1837        let state = State {
1838            engine: self.clone(),
1839            caller,
1840            session,
1841            sent: after.unwrap_or(0),
1842            last: None,
1843            cards: None,
1844            failed: None,
1845            buffer: VecDeque::new(),
1846            next: None,
1847            first: true,
1848            done: false,
1849        };
1850        stream::unfold(state, |mut state| async move {
1851            loop {
1852                if let Some(frame) = state.buffer.pop_front() {
1853                    return Some((Ok(frame), state));
1854                }
1855                if state.done {
1856                    return None;
1857                }
1858                if !state.first
1859                    && let Some(next) = state.next.take()
1860                {
1861                    next.await;
1862                }
1863                state.first = false;
1864                let source = Arc::clone(&state.engine.inner.source);
1865                let poll = state.engine.inner.poll;
1866                let mut next: BoxFuture<'static, ()> =
1867                    Box::pin(async move { source.changed(poll).await });
1868                state.next = match futures::poll!(next.as_mut()) {
1869                    std::task::Poll::Ready(()) => None,
1870                    std::task::Poll::Pending => Some(next),
1871                };
1872                match state
1873                    .engine
1874                    .refresh(
1875                        &state.caller,
1876                        &state.session,
1877                        state.sent,
1878                        &state.last,
1879                        &state.cards,
1880                        state.failed.as_ref(),
1881                    )
1882                    .await
1883                {
1884                    Ok(read) => {
1885                        state.sent = read.sent;
1886                        state.last = read.last;
1887                        state.cards = Some(read.cards);
1888                        state.failed = Some(read.failed);
1889                        state.buffer.extend(read.frames);
1890                    }
1891                    Err(error) => {
1892                        state.done = true;
1893                        return Some((Err(error), state));
1894                    }
1895                }
1896            }
1897        })
1898        .boxed()
1899    }
1900
1901    /// The frames since `sent`, with the new cursor, the id of the event at it, the
1902    /// open-decision signature and the failed turns the sent entries now carry.
1903    async fn refresh(
1904        &self,
1905        caller: &Caller,
1906        session: &str,
1907        mut sent: u64,
1908        last: &Option<String>,
1909        cards: &Option<Vec<(String, u64)>>,
1910        shown: Option<&FailedTurns>,
1911    ) -> Result<FeedRead> {
1912        let events = self.transcript(caller, session).await?;
1913        let len = events.len() as u64;
1914        let failed = self.failed_turns(caller, session, &events).await;
1915        let mut frames = Vec::new();
1916        let at_cursor = usize::try_from(sent)
1917            .ok()
1918            .and_then(|sent| sent.checked_sub(1))
1919            .and_then(|index| events.get(index))
1920            .map(|event| &event.id);
1921        // Shorter than what was sent, or another event where the last one sent was: the
1922        // store's history was replaced.
1923        let replaced = last.as_ref().is_some_and(|last| at_cursor != Some(last));
1924        if sent > len || replaced {
1925            frames.push(FeedFrame::Reset { len });
1926            sent = 0;
1927        }
1928        // Entries already sent whose failed turns changed since, such as the person's message
1929        // of a turn whose model call has just failed.
1930        let none = FailedTurns::new();
1931        let before = shown.unwrap_or(&none);
1932        let changed: Vec<u64> = failed
1933            .keys()
1934            .chain(before.keys())
1935            .copied()
1936            .filter(|seq| *seq <= sent && failed.get(seq) != before.get(seq))
1937            .collect::<std::collections::BTreeSet<_>>()
1938            .into_iter()
1939            .collect();
1940        if sent < len || !changed.is_empty() {
1941            let links = self.links(caller, session, &events).await?;
1942            let answered = project::answered_calls(&events);
1943            for seq in changed {
1944                if let Some(event) = usize::try_from(seq - 1).ok().and_then(|at| events.get(at)) {
1945                    let entry = self.entry(seq, event, &links, &answered, &failed);
1946                    frames.push(FeedFrame::Changed { entry });
1947                }
1948            }
1949            for (index, event) in
1950                events.iter().enumerate().skip(usize::try_from(sent).unwrap_or(usize::MAX))
1951            {
1952                let entry = self.entry(index as u64 + 1, event, &links, &answered, &failed);
1953                frames.push(FeedFrame::Entry { entry });
1954            }
1955            sent = len;
1956        }
1957        let last = usize::try_from(sent)
1958            .ok()
1959            .and_then(|sent| sent.checked_sub(1))
1960            .and_then(|index| events.get(index))
1961            .map(|event| event.id.clone());
1962        let open = self.session_decisions(caller, session).await?;
1963        let signature: Vec<(String, u64)> =
1964            open.iter().map(|card| (card.id.clone(), card.version)).collect();
1965        if cards.as_ref() != Some(&signature) {
1966            frames.push(FeedFrame::Decisions { cards: open });
1967        }
1968        Ok(FeedRead { frames, sent, last, cards: signature, failed })
1969    }
1970
1971    /// The caller's agents (spec 3.3 §8.1).
1972    ///
1973    /// # Errors
1974    ///
1975    /// Returns the source's error.
1976    pub async fn agents(&self, caller: &Caller) -> Result<Vec<AgentRow>> {
1977        let rows: Vec<AgentRow> = self
1978            .inner
1979            .source
1980            .agents(caller.user_id())
1981            .await?
1982            .iter()
1983            .map(|state| self.inner.projector.agent_row(state))
1984            .collect();
1985        // The person's own agents join the roster from their definitions, so one that has
1986        // never run is listed as Ready (spec 3.3 §5.7 "The roster").
1987        let definitions = self.inner.source.agent_definitions(caller.user_id()).await?;
1988        let can_change =
1989            !matches!(caller.origin, Origin::Agent { .. }) && rules::may_change_agents(caller);
1990        Ok(crate::agents::roster(rows, &definitions, can_change))
1991    }
1992
1993    /// How `caller` answered since `since` (spec 3.3 §5.1 "How you answered"): each answer
1994    /// counted, and on which surfaces.
1995    ///
1996    /// # Errors
1997    ///
1998    /// Returns the answer log's error.
1999    pub async fn answers_since(
2000        &self,
2001        caller: &Caller,
2002        since: DateTime<Utc>,
2003    ) -> Result<crate::answers::AnswerSummary> {
2004        let mine: Vec<AnswerRecord> = self
2005            .inner
2006            .answers
2007            .since(since)
2008            .await?
2009            .into_iter()
2010            .filter(|record| record.by.id == caller.user_id())
2011            .collect();
2012        Ok(crate::answers::AnswerSummary::of(since, &mine))
2013    }
2014
2015    /// The threads `caller` has with `agent`, newest first (spec 3.3 §5.1 "Thread history"):
2016    /// each session and when it last changed.
2017    ///
2018    /// # Errors
2019    ///
2020    /// Returns the source's error.
2021    pub async fn agent_threads(
2022        &self,
2023        caller: &Caller,
2024        agent: &str,
2025    ) -> Result<crate::agents::AgentThreads> {
2026        let offset = self.inner.projector.offset;
2027        let mut threads: Vec<crate::agents::ThreadSummary> = self
2028            .inner
2029            .source
2030            .agent_threads(caller.user_id(), agent)
2031            .await?
2032            .into_iter()
2033            .map(|(session_id, at)| crate::agents::ThreadSummary {
2034                session_id,
2035                at,
2036                when: at.with_timezone(&offset).format("%-d %b %H:%M").to_string(),
2037            })
2038            .collect();
2039        threads.sort_by_key(|thread| std::cmp::Reverse(thread.at));
2040        Ok(crate::agents::AgentThreads { agent: agent.to_string(), threads })
2041    }
2042
2043    /// The agents `caller` removed, each with its threads, which stay readable (spec 3.3
2044    /// §5.7, §13 decision 18): what "Removed agents" at the roster's foot lists.
2045    ///
2046    /// # Errors
2047    ///
2048    /// Returns the source's error.
2049    pub async fn removed_agents(
2050        &self,
2051        caller: &Caller,
2052    ) -> Result<Vec<crate::agents::RemovedAgent>> {
2053        let source = &self.inner.source;
2054        let mut removed = Vec::new();
2055        for detail in source.agent_definitions(caller.user_id()).await? {
2056            if detail.state != crate::agents::AgentLife::Removed {
2057                continue;
2058            }
2059            let threads = source.agent_threads(caller.user_id(), &detail.id).await?;
2060            removed.push(crate::agents::RemovedAgent::of(
2061                &detail,
2062                threads,
2063                self.inner.projector.offset,
2064            ));
2065        }
2066        removed.sort_by(|a, b| {
2067            a.agent.display_name.to_lowercase().cmp(&b.agent.display_name.to_lowercase())
2068        });
2069        Ok(removed)
2070    }
2071
2072    /// Every agent `caller` added, removed ones included, with its version: what the
2073    /// terminal's `--output json` compares, so a change to any field is one line (spec 3.3
2074    /// §5.7).
2075    ///
2076    /// # Errors
2077    ///
2078    /// Returns the source's error.
2079    pub async fn agent_details(&self, caller: &Caller) -> Result<Vec<crate::agents::AgentDetail>> {
2080        let details = self.inner.source.agent_definitions(caller.user_id()).await?;
2081        Ok(details.into_iter().map(|detail| self.with_granted(detail)).collect())
2082    }
2083
2084    /// The agent a message goes to when the person names none (spec 3.3 §5.5): the tray's
2085    /// "Ask Finance". `None` when the source has no single primary agent
2086    /// ([`Source::primary_agent`]).
2087    pub fn primary_agent(&self) -> Option<AgentRef> {
2088        self.inner.source.primary_agent().map(|name| self.inner.projector.agent(&name))
2089    }
2090
2091    /// The status line (spec 3.3 §5.1): the mode word of `session` (or the default), spend
2092    /// against the daily limit, quiet time, and the count of decisions.
2093    ///
2094    /// # Errors
2095    ///
2096    /// Returns the source's error.
2097    pub async fn status(&self, caller: &Caller, session: Option<&str>) -> Result<StatusLine> {
2098        let source = &self.inner.source;
2099        let decisions = self.decisions(caller).await?.len();
2100        let stopped = source.stopped().await?;
2101        Ok(StatusLine {
2102            mode: source.mode(caller.user_id(), session).await?.map(project::mode_view),
2103            spend: source.spend(caller.user_id()).await?.map(project::spend_view),
2104            quiet: self.inner.projector.quiet_view(self.now()),
2105            decisions: u32::try_from(decisions).unwrap_or(u32::MAX),
2106            stopped,
2107            stopped_text: stopped.then(|| words::ALL_AGENTS_STOPPED.to_string()),
2108            host_utc_offset_minutes: Some(
2109                self.now().with_timezone(&Local).offset().local_minus_utc() / 60,
2110            ),
2111            serves: self.serves(),
2112        })
2113    }
2114
2115    /// Names `part` among the parts of the home this server serves beside the engine's
2116    /// routes, so the web home reads its routes ([`StatusLine::serves`]). adk-surface's routers
2117    /// name their own as they are built; a host names a part it mounts from elsewhere, such as
2118    /// the website's desk.
2119    ///
2120    /// # Example
2121    ///
2122    /// ```rust
2123    /// use std::sync::Arc;
2124    /// use adk_session::InMemorySessionService;
2125    /// use adk_surface::{LocalSource, Served, SurfaceEngine};
2126    ///
2127    /// let source = LocalSource::builder("adk-rust")
2128    ///     .sessions(Arc::new(InMemorySessionService::new()))
2129    ///     .build()
2130    ///     .unwrap();
2131    /// let engine = SurfaceEngine::builder(Arc::new(source)).build();
2132    /// engine.serve(Served::Website);
2133    /// assert_eq!(engine.serves(), vec![Served::Website]);
2134    /// ```
2135    pub fn serve(&self, part: Served) {
2136        self.inner.served.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(part);
2137    }
2138
2139    /// The parts of the home this server serves beside the engine's routes, in order: those
2140    /// named with [`serve`](Self::serve), the cameras when the engine has a camera hub, and the
2141    /// kernel's control plane when the source's kernel built its routes.
2142    pub fn serves(&self) -> Vec<Served> {
2143        let mut parts =
2144            self.inner.served.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
2145        if self.inner.cameras.is_some() {
2146            parts.insert(Served::Cameras);
2147        }
2148        if self.inner.source.serves_kernel_routes() {
2149            parts.insert(Served::Kernel);
2150        }
2151        parts.into_iter().collect()
2152    }
2153
2154    /// "While you were away" since `since` (spec 3.3 §5.1, §8.1): spend, waiting decisions,
2155    /// and one line per event on the `/proc` ledger — the events the kernel's
2156    /// `GET /kernel/away` lists (§10 K4) — each agent by the name the roster gives it.
2157    ///
2158    /// # Errors
2159    ///
2160    /// Returns the source's error.
2161    pub async fn briefing(&self, caller: &Caller, since: DateTime<Utc>) -> Result<Briefing> {
2162        let source = &self.inner.source;
2163        let lines = source
2164            .ledger(since)
2165            .await?
2166            .iter()
2167            .filter_map(|entry| self.inner.projector.briefing_line(entry))
2168            .collect();
2169        let waiting = self.decisions(caller).await?.len();
2170        Ok(Briefing {
2171            title: words::WHILE_YOU_WERE_AWAY.to_string(),
2172            since,
2173            since_text: words::briefing_since(&self.inner.projector.hh_mm(since)),
2174            spend: source.spend(caller.user_id()).await?.map(project::spend_view),
2175            waiting: u32::try_from(waiting).unwrap_or(u32::MAX),
2176            lines,
2177            recorded: source.keeps_ledger(),
2178        })
2179    }
2180
2181    // -----------------------------------------------------------------------
2182    // Commands
2183    // -----------------------------------------------------------------------
2184
2185    /// Carries out `command` as `caller` (spec 3.3 §6, §7.2, §7.4, §11).
2186    ///
2187    /// # Errors
2188    ///
2189    /// | Code | When |
2190    /// |---|---|
2191    /// | `surface.not_found` | No decision or session of the caller has that id (S-I8); a `Steer` to a session that is not the caller's |
2192    /// | `surface.answer_not_allowed` | The surface may not give this answer (§7.2) |
2193    /// | `surface.confirm_presence` | A high-risk approval without confirming it is you |
2194    /// | `surface.call_not_expanded` | A truncated call approved before it was expanded |
2195    /// | `surface.not_here` | An agent answering or steering, resuming outside the home, loosening the mode from chat or voice, a `Steer` while everything is stopped |
2196    /// | `surface.operator_only` | Stop all or Resume all from a caller outside the group [`stops_need`](SurfaceEngineBuilder::stops_need) names |
2197    /// | `surface.invalid` | A spoken answer: it goes through `decide_spoken` with its transcript (feature `voice`) |
2198    /// | `surface.unsupported` | The source cannot do it |
2199    /// | the source's code | The source failed |
2200    pub async fn execute(&self, caller: &Caller, command: Command) -> Result<CommandOutcome> {
2201        match command {
2202            // A spoken answer is recorded with its transcript's digest (spec 3.3 §5.6).
2203            Command::Decide { .. } if rules::row(caller) == Row::Voice => {
2204                Err(SurfaceError::Invalid(
2205                    "a spoken answer goes through decide_spoken with its transcript".into(),
2206                ))
2207            }
2208            Command::Decide {
2209                decision_id,
2210                version,
2211                answer,
2212                edited_args,
2213                reason,
2214                expanded,
2215                evidence,
2216            } => {
2217                self.decide(
2218                    caller,
2219                    &decision_id,
2220                    version,
2221                    answer,
2222                    edited_args,
2223                    reason,
2224                    (expanded, evidence),
2225                    None,
2226                )
2227                .await
2228            }
2229            Command::ChangeImage { decision_id, version, from, change, preview } => {
2230                self.change_image(caller, &decision_id, version, &from, change, preview).await
2231            }
2232            Command::CancelAnswer { decision_id } => self.cancel_answer(caller, &decision_id).await,
2233            Command::Send { session_id, text, images } => {
2234                let images = crate::images::decode(&images)?;
2235                self.send(caller, session_id, text, images, false, true).await
2236            }
2237            Command::Steer { session_id, text } => self.steer(caller, session_id, text).await,
2238            Command::StopTurn { session_id } => self.stop_turn(caller, session_id).await,
2239            Command::Queue { session_id, text, images } => {
2240                let images = crate::images::decode(&images)?;
2241                self.send(caller, session_id, text, images, true, false).await
2242            }
2243            Command::StopAll { reason } => {
2244                self.may_stop(caller)?;
2245                self.stop_all(caller, reason).await
2246            }
2247            Command::ResumeAll => {
2248                self.may_stop(caller)?;
2249                self.resume_all(caller).await
2250            }
2251            Command::SetMode { session_id, mode } => self.set_mode(caller, &session_id, mode).await,
2252            Command::NewThread { agent, session_id, text, images } => {
2253                let images = crate::images::decode(&images)?;
2254                self.new_thread(caller, &agent, session_id, text, images).await
2255            }
2256            command @ (Command::AddAgent { .. }
2257            | Command::ChangeAgent { .. }
2258            | Command::PauseAgent { .. }
2259            | Command::ResumeAgent { .. }
2260            | Command::RemoveAgent { .. }
2261            | Command::CopyRuleToAgent { .. }) => self.agent_command(caller, command).await,
2262            Command::SubmitDrawn { session_id, surface_id, version, action_id, values } => {
2263                self.submit_drawn(caller, session_id, surface_id, version, &action_id, &values)
2264                    .await
2265            }
2266        }
2267    }
2268
2269    /// Sends a drawn form (spec 3.3 §7.4 rule 5), checked in order: the session is the
2270    /// caller's (S-I8), the caller is a person at a screen, the surface is at `version`, the
2271    /// action is declared, and the values fit their fields. Then it is recorded and the call
2272    /// is asked for; nothing runs until the person decides.
2273    #[cfg(feature = "genui")]
2274    async fn submit_drawn(
2275        &self,
2276        caller: &Caller,
2277        session: String,
2278        surface: String,
2279        version: u64,
2280        action: &str,
2281        values: &serde_json::Map<String, Value>,
2282    ) -> Result<CommandOutcome> {
2283        let events = self.transcript(caller, &session).await?;
2284        if !matches!(caller.origin, Origin::Keyboard | Origin::Pointer | Origin::Touch) {
2285            return Err(SurfaceError::NotHere(words::SEND_FORMS_FROM_A_SCREEN.to_string()));
2286        }
2287        let sent = crate::genui::submission(
2288            &events,
2289            &self.inner.projector.catalogs,
2290            &surface,
2291            version,
2292            action,
2293            values,
2294        )?;
2295        // A running turn writes the session meanwhile, so the call waits until it ends, as a
2296        // message does: a second run would interleave its events with the turn's (S-I4).
2297        let key = (caller.user_id().to_string(), session.clone());
2298        let queued = self
2299            .inner
2300            .queues
2301            .lock()
2302            .unwrap_or_else(|e| e.into_inner())
2303            .get(&key)
2304            .is_some_and(|queued| !queued.is_empty())
2305            || self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).contains(&key);
2306        if queued || self.inner.source.busy(caller.user_id(), &session).await? {
2307            return Err(SurfaceError::Invalid(words::SEND_FORM_WHEN_FREE.to_string()));
2308        }
2309        let call = adk_core::RequestedCall::new(
2310            sent.tool.clone(),
2311            sent.args.clone(),
2312            caller.subject.clone(),
2313            adk_core::RequestedVia::form(surface.clone(), version, action)
2314                .with_digest(sent.digest.clone()),
2315        );
2316        let call_id = call.function_call_id.clone();
2317        if !self.inner.drawn.begin_send(
2318            caller.user_id(),
2319            &session,
2320            (&surface, version),
2321            &call,
2322            &events,
2323        ) {
2324            return Err(SurfaceError::Invalid(words::FORM_BEING_SENT.to_string()));
2325        }
2326        // Recorded before it is asked for: a send whose record failed is never asked for. The
2327        // record carries digests, never the values: the arguments' digest is the one the
2328        // call's own approval records carry.
2329        let args_digest = self.inner.audit.as_ref().map(|trail| trail.digest(&sent.args));
2330        let asked = async {
2331            self.record(
2332                caller,
2333                SURFACE_AUDIT_DRAWN_SUBMITTED,
2334                json!({
2335                    "sessionId": session,
2336                    "surfaceId": surface,
2337                    "version": version,
2338                    "actionId": action,
2339                    "tool": sent.tool,
2340                    "argsDigest": args_digest,
2341                    "valuesDigest": sent.values_digest,
2342                    "callId": call_id,
2343                    "drawnBy": sent.drawn_by,
2344                    "drawingDigest": sent.digest,
2345                }),
2346            )
2347            .await?;
2348            self.inner.source.request_call(caller, &session, "", call).await
2349        };
2350        if let Err(error) = asked.await {
2351            self.inner.drawn.withdraw(&call_id);
2352            return Err(error);
2353        }
2354        Ok(CommandOutcome::FormSent { session_id: session, surface_id: surface, version, call_id })
2355    }
2356
2357    /// The session's events, when it is the caller's own (S-I8): what an app in it showed.
2358    #[cfg(feature = "genui-apps")]
2359    pub(crate) async fn app_transcript(
2360        &self,
2361        caller: &Caller,
2362        session: &str,
2363    ) -> Result<Vec<adk_core::Event>> {
2364        self.transcript(caller, session).await
2365    }
2366
2367    /// Approves the waiting decision `decision_id` by the home's policy `policy` (spec 3.3
2368    /// §6.1 `genui-apps`, opt-in tiered consent the person set): decided as the person, the
2369    /// rule recorded as `surface.app.call_auto_approved` and on the decision, then resumed like
2370    /// their answer.
2371    #[cfg(feature = "genui-apps")]
2372    pub(crate) async fn approve_by_policy(
2373        &self,
2374        caller: &Caller,
2375        decision_id: &str,
2376        version: u64,
2377        policy: &str,
2378        ext: Value,
2379    ) -> Result<()> {
2380        let mut fields = json!({ "approvalId": decision_id, "policy": policy, "initiator": "app" });
2381        if let (Some(fields), Value::Object(ext)) = (fields.as_object_mut(), ext) {
2382            fields.extend(ext);
2383        }
2384        self.record(caller, SURFACE_AUDIT_APP_CALL_AUTO_APPROVED, fields).await?;
2385        // The person's own standing consent: decided as them, the rule on the record.
2386        let mut decision =
2387            ApprovalDecision::approve(caller.subject.clone()).with_groups(caller.groups.clone());
2388        decision.reason = Some(format!("approved by the home's {policy} consent"));
2389        let updated = self.inner.source.decide(decision_id, version, decision).await?;
2390        if updated.state != ApprovalState::Pending {
2391            if let Err(error) = self.inner.source.resolved_by(caller, &updated).await {
2392                tracing::warn!(error = %error, decision.id = %updated.id, "the approved call could not be resumed");
2393            }
2394            self.spawn_drain(caller.clone(), updated.scope.session_id.clone());
2395        }
2396        Ok(())
2397    }
2398
2399    /// Asks for `call`, a tool call the app from `app` asked for in `session` (spec 3.3 §6.1
2400    /// `genui-apps`): held as the agent whose call showed the app, for the person's decision,
2401    /// whose card says "The app from Weather asked" and never offers **Always allow**.
2402    #[cfg(feature = "genui-apps")]
2403    pub(crate) async fn ask_for_app_call(
2404        &self,
2405        caller: &Caller,
2406        session: &str,
2407        call: adk_core::RequestedCall,
2408        app: &str,
2409    ) -> Result<()> {
2410        self.inner.drawn.app_asked(caller.user_id(), session, &call, app);
2411        self.inner.source.request_call(caller, session, "", call).await
2412    }
2413
2414    #[cfg(not(feature = "genui"))]
2415    async fn submit_drawn(
2416        &self,
2417        caller: &Caller,
2418        session: String,
2419        _surface: String,
2420        _version: u64,
2421        _action: &str,
2422        _values: &serde_json::Map<String, Value>,
2423    ) -> Result<CommandOutcome> {
2424        self.transcript(caller, &session).await?;
2425        Err(SurfaceError::unsupported("sending a form an agent drew"))
2426    }
2427
2428    /// Answers a decision by voice (spec 3.3 §5.6, §7.2): the one way a spoken answer is
2429    /// recorded. `transcript` is what the person said; every `surface.decide` record of the
2430    /// answer carries its SHA-256 as `transcriptDigest`, and none carries the words.
2431    ///
2432    /// The voice row of §7.2 applies: **Allow once** for an everyday call, which waits out
2433    /// the cancel window ([`CommandOutcome::Pending`]; its end arrives on
2434    /// [`SpokenAnswer::settled`](crate::voice::SpokenAnswer::settled)), and **Deny** for any
2435    /// call. The call counts as not expanded, so a call shown truncated is decided on screen.
2436    ///
2437    /// # Errors
2438    ///
2439    /// `surface.invalid` when `caller` is not on the voice surface with origin voice; the
2440    /// codes of [`execute`](Self::execute) otherwise.
2441    ///
2442    /// # Example
2443    ///
2444    /// ```rust,no_run
2445    /// use adk_surface::{Answer, Caller, CommandOutcome, Origin, SurfaceEngine, SurfaceKind};
2446    ///
2447    /// # async fn example(engine: SurfaceEngine, id: &str, version: u64) -> adk_surface::Result<()> {
2448    /// let ana = Caller::human("ana", SurfaceKind::Voice, Origin::Voice);
2449    /// let spoken = engine.decide_spoken(&ana, id, version, Answer::AllowOnce, "allow once").await?;
2450    /// if let CommandOutcome::Pending { text, .. } = &spoken.outcome {
2451    ///     println!("{text}");
2452    /// }
2453    /// # Ok(())
2454    /// # }
2455    /// ```
2456    #[cfg(feature = "voice")]
2457    pub async fn decide_spoken(
2458        &self,
2459        caller: &Caller,
2460        decision_id: &str,
2461        version: u64,
2462        answer: Answer,
2463        transcript: &str,
2464    ) -> Result<crate::voice::SpokenAnswer> {
2465        use sha2::Digest as _;
2466        if caller.origin != Origin::Voice || caller.surface != crate::origin::SurfaceKind::Voice {
2467            return Err(SurfaceError::Invalid(
2468                "decide_spoken records a spoken answer: the caller is on the voice surface and \
2469                 its origin is voice"
2470                    .into(),
2471            ));
2472        }
2473        let digest = format!("{:x}", sha2::Sha256::digest(transcript.as_bytes()));
2474        let (settle, settled) = oneshot::channel();
2475        let outcome = with_digest(
2476            Some(digest),
2477            self.decide(
2478                caller,
2479                decision_id,
2480                version,
2481                answer,
2482                None,
2483                None,
2484                (false, Vec::new()),
2485                Some(settle),
2486            ),
2487        )
2488        .await?;
2489        let settled = matches!(outcome, CommandOutcome::Pending { .. }).then_some(settled);
2490        Ok(crate::voice::SpokenAnswer { outcome, settled })
2491    }
2492
2493    #[allow(clippy::too_many_arguments)]
2494    async fn decide(
2495        &self,
2496        caller: &Caller,
2497        id: &str,
2498        version: u64,
2499        answer: Answer,
2500        edited_args: Option<Value>,
2501        reason: Option<String>,
2502        (expanded, evidence): (bool, Vec<String>),
2503        settle: Option<oneshot::Sender<Result<CommandOutcome>>>,
2504    ) -> Result<CommandOutcome> {
2505        let request = self.owned_request(caller, id).await?;
2506        if let Origin::Agent { agent } = &caller.origin {
2507            let error = SurfaceError::NotHere(format!(
2508                "an agent ({agent}) never answers a decision; it waits for a person (spec 3.3 §7.4)"
2509            ));
2510            self.audit_decide(caller, &request, answer, "refused", Some(&error.code())).await?;
2511            return Err(error);
2512        }
2513        if request.state != ApprovalState::Pending {
2514            return self.already_decided(caller, &request, answer).await;
2515        }
2516        let always = self.always_label(&request).await;
2517        let hint = self.hint(&request).await;
2518        let mut facts = self.inner.projector.facts(&request, always, &hint);
2519        let plan = self.card_plan(&request).await.filter(|plan| plan.open);
2520        if let Some(plan) = &plan {
2521            facts.plan = true;
2522            facts.truncated = project::cut_call_text(plan.text.clone()).1;
2523            facts.always_label = None;
2524        }
2525        let images: Vec<String> =
2526            crate::evidence::images(&request).iter().map(|image| image.digest.clone()).collect();
2527        if !images.is_empty() {
2528            let agent = self.inner.projector.agent(&project::agent_name(&request)).display_name;
2529            let media = self.media(&request, &hint, None, &agent).await;
2530            facts.image = media.as_ref().map(|media| self.image_gate(media));
2531        }
2532        if let Err(violation) = rules::check(caller, &facts, answer, expanded) {
2533            let error = SurfaceError::Rule(violation);
2534            self.audit_decide(caller, &request, answer, "refused", Some(&error.code())).await?;
2535            return Err(error);
2536        }
2537        if let Some(plan) = plan {
2538            // A plan is approved by a person looking at it while agents may act: answered
2539            // after everything was stopped, its card closes (spec 3.7 Q8, V-I17).
2540            if self.inner.source.stopped().await? {
2541                self.close_plan(&request, &plan).await;
2542                let closed = self.inner.source.request(&request.id).await?.unwrap_or(request);
2543                if closed.state == ApprovalState::Pending {
2544                    return Err(SurfaceError::NotHere(
2545                        "everything is stopped: a screen plan is answered once agents may act \
2546                         again"
2547                            .into(),
2548                    ));
2549                }
2550                return self.already_decided(caller, &closed, answer).await;
2551            }
2552            return self
2553                .commit(caller, &request, version, answer, (None, reason), Some(&plan))
2554                .await;
2555        }
2556        if answer == Answer::Edit && edited_args.is_none() {
2557            return Err(SurfaceError::Invalid("an edit needs the changed arguments".into()));
2558        }
2559        // An answer to an MCP server's form is checked against its schema before it is on
2560        // record, so the person hears what to fix instead of the server declining it later.
2561        if answer == Answer::Edit
2562            && let Some(crate::model::ElicitationView::Form { fields, .. }) =
2563                crate::project::elicitation_of(&request)
2564            && let Some(content) = edited_args.as_ref()
2565            && let Err(reason) = crate::project::check_answer(&fields, content)
2566        {
2567            return Err(SurfaceError::Invalid(format!(
2568                "the answer does not fit the form: {reason}"
2569            )));
2570        }
2571        // An answer that lets a call with images run names the images the person saw: the
2572        // decision binds to those digests, and to no other image (spec 3.7 V-I5).
2573        if !images.is_empty()
2574            && matches!(answer, Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit)
2575        {
2576            if evidence.is_empty() {
2577                return Err(SurfaceError::Invalid(
2578                    "an answer that sends images names the digests of the images it saw: send \
2579                     the card's `media.images[].digest` as `evidence`"
2580                        .into(),
2581                ));
2582            }
2583            if evidence != images || request.version != version {
2584                self.audit_decide(caller, &request, answer, "changed", Some(EVIDENCE_CHANGED))
2585                    .await?;
2586                let card = self.card(caller, &request).await?;
2587                return Ok(CommandOutcome::Changed { card });
2588            }
2589        }
2590        // An edited call with images is held again with what it would send now, never run on
2591        // arguments whose images nobody saw (spec 3.7 V-I5).
2592        if !images.is_empty() && answer == Answer::Edit {
2593            let args = edited_args.unwrap_or(Value::Null);
2594            return self.held_again(caller, &request, version, args).await;
2595        }
2596        if rules::row(caller) == Row::Voice && answer == Answer::AllowOnce {
2597            // A spoken answer to a decision that changed since it was read is shown again at
2598            // once, as on every other surface, never promised and then dropped (S-I2).
2599            if request.version != version {
2600                self.audit_decide(
2601                    caller,
2602                    &request,
2603                    answer,
2604                    "changed",
2605                    Some("approval.version_conflict"),
2606                )
2607                .await?;
2608                let card = self.card(caller, &request).await?;
2609                return Ok(CommandOutcome::Changed { card });
2610            }
2611            return self.speak_later(caller, request, version, settle).await;
2612        }
2613        self.commit(caller, &request, version, answer, (edited_args, reason), None).await
2614    }
2615
2616    /// Tightens the crop of one of decision `id`'s images or covers more of it, then holds its
2617    /// call again with the new image (spec 3.7 §8.2, board choice A8, V-I5).
2618    async fn change_image(
2619        &self,
2620        caller: &Caller,
2621        id: &str,
2622        version: u64,
2623        from: &str,
2624        change: crate::evidence::ImageChange,
2625        preview: bool,
2626    ) -> Result<CommandOutcome> {
2627        let request = self.owned_request(caller, id).await?;
2628        if !matches!(caller.origin, Origin::Keyboard | Origin::Pointer | Origin::Touch)
2629            || !matches!(rules::row(caller), Row::Web | Row::Phone | Row::Terminal)
2630        {
2631            return Err(SurfaceError::NotHere(
2632                "an image is changed by a person looking at it, in the home or on the phone".into(),
2633            ));
2634        }
2635        if request.state != ApprovalState::Pending {
2636            return self.already_decided(caller, &request, Answer::Edit).await;
2637        }
2638        let card = self.card(caller, &request).await?;
2639        let media = card.media.as_ref().ok_or_else(|| {
2640            SurfaceError::Invalid(format!("decision '{id}' holds no image to change"))
2641        })?;
2642        let image = media.images.get(change.image as usize).ok_or_else(|| {
2643            SurfaceError::not_found(format!("image {} of decision '{id}'", change.image))
2644        })?;
2645        if request.version != version || image.digest != from {
2646            return Ok(CommandOutcome::Changed { card });
2647        }
2648        if !media.can_change {
2649            return Err(SurfaceError::unsupported("changing this image before it leaves"));
2650        }
2651        change.check(image.width, image.height).map_err(SurfaceError::Invalid)?;
2652        if preview {
2653            return self.preview_change(&request, from, &change).await;
2654        }
2655        // The change is on record before it takes effect (spec 3.3 §11).
2656        self.record(
2657            caller,
2658            SURFACE_AUDIT_IMAGE_CHANGE,
2659            json!({
2660                "approvalId": request.id,
2661                "sessionId": request.scope.session_id,
2662                "tool": request.tool_name,
2663                "version": version,
2664                "fromDigest": from,
2665                "crop": change.crop,
2666                "cover": change.cover,
2667            }),
2668        )
2669        .await?;
2670        let changed = match self.inner.source.change_image(caller, &request, version, &change).await
2671        {
2672            Ok(changed) => changed,
2673            Err(error) => return self.not_held_again(caller, &request, error).await,
2674        };
2675        self.inner
2676            .changed_images
2677            .lock()
2678            .unwrap_or_else(std::sync::PoisonError::into_inner)
2679            .insert(changed.to.clone(), changed.from.clone());
2680        self.record(
2681            caller,
2682            SURFACE_AUDIT_IMAGE_CHANGE,
2683            json!({
2684                "approvalId": request.id,
2685                "fromDigest": changed.from,
2686                "toDigest": changed.to,
2687                "outcome": "held_again",
2688            }),
2689        )
2690        .await?;
2691        self.after_held_again(caller, &request, Some(changed)).await
2692    }
2693
2694    /// The image `change` would make of `request`'s image, made as the source makes it, and
2695    /// held nowhere (board choice A8).
2696    #[cfg(feature = "web")]
2697    async fn preview_change(
2698        &self,
2699        request: &ApprovalRequest,
2700        from: &str,
2701        change: &crate::evidence::ImageChange,
2702    ) -> Result<CommandOutcome> {
2703        let image = self
2704            .inner
2705            .source
2706            .evidence_image(request, change.image as usize)
2707            .await?
2708            .ok_or_else(|| SurfaceError::Invalid("the image is no longer kept".into()))?;
2709        let (bytes, width, height) =
2710            crate::evidence::changed_png(&image.bytes, change).map_err(SurfaceError::Invalid)?;
2711        let changed = crate::evidence::ImageChanged {
2712            from: from.to_string(),
2713            to: crate::evidence::digest_of(&bytes),
2714            width,
2715            height,
2716        };
2717        Ok(CommandOutcome::ImagePreview { changed })
2718    }
2719
2720    #[cfg(not(feature = "web"))]
2721    async fn preview_change(
2722        &self,
2723        _request: &ApprovalRequest,
2724        _from: &str,
2725        _change: &crate::evidence::ImageChange,
2726    ) -> Result<CommandOutcome> {
2727        Err(SurfaceError::unsupported("changing an image before it leaves"))
2728    }
2729
2730    /// Holds `request`'s call again with the edited `args` (spec 3.7 V-I5).
2731    async fn held_again(
2732        &self,
2733        caller: &Caller,
2734        request: &ApprovalRequest,
2735        version: u64,
2736        args: Value,
2737    ) -> Result<CommandOutcome> {
2738        self.record(
2739            caller,
2740            SURFACE_AUDIT_ANSWER,
2741            json!({
2742                "approvalId": request.id,
2743                "sessionId": request.scope.session_id,
2744                "tool": request.tool_name,
2745                "answer": Answer::Edit,
2746                "version": version,
2747                "heldAgain": true,
2748            }),
2749        )
2750        .await?;
2751        if let Err(error) =
2752            self.inner.source.hold_again(caller, request, version, args, HELD_AGAIN_REASON).await
2753        {
2754            return self.not_held_again(caller, request, error).await;
2755        }
2756        self.after_held_again(caller, request, None).await
2757    }
2758
2759    /// What a hold again that failed shows: the decision as it is now when someone answered
2760    /// or changed it first (S-I2), else the error.
2761    async fn not_held_again(
2762        &self,
2763        caller: &Caller,
2764        request: &ApprovalRequest,
2765        error: SurfaceError,
2766    ) -> Result<CommandOutcome> {
2767        let Some(now) = self.inner.source.request(&request.id).await? else {
2768            return Err(error);
2769        };
2770        if now.state != ApprovalState::Pending {
2771            return self.already_decided(caller, &now, Answer::Edit).await;
2772        }
2773        if now.version != request.version {
2774            let card = self.card(caller, &now).await?;
2775            return Ok(CommandOutcome::Changed { card });
2776        }
2777        Err(error)
2778    }
2779
2780    /// Records a hold again as the person's change and shows the closed decision.
2781    async fn after_held_again(
2782        &self,
2783        caller: &Caller,
2784        request: &ApprovalRequest,
2785        changed: Option<crate::evidence::ImageChanged>,
2786    ) -> Result<CommandOutcome> {
2787        let record = AnswerRecord {
2788            approval_id: request.id.clone(),
2789            by: caller.subject.clone(),
2790            via: caller.via(),
2791            answer: Answer::Edit,
2792            at: self.now(),
2793        };
2794        if let Err(error) = self.inner.answers.record(&record).await {
2795            tracing::warn!(error = %error, decision.id = %request.id, "where the change was made could not be kept");
2796        }
2797        self.inner.wake.notify_waiters();
2798        let closed =
2799            self.inner.source.request(&request.id).await?.unwrap_or_else(|| request.clone());
2800        if let Err(error) =
2801            self.audit_decide(caller, &closed, Answer::Edit, "held_again", None).await
2802        {
2803            tracing::warn!(error = %error, decision.id = %closed.id, "the call was held again; its audit record failed");
2804        }
2805        let card = self.card(caller, &closed).await?;
2806        Ok(CommandOutcome::HeldAgain { changed, card })
2807    }
2808
2809    /// Records the answer: `ApprovalService::decide` at `version`, never retried (S-I2); for a
2810    /// screen plan's card, the plan's decision through the source, which records it on the
2811    /// plan's first step (spec 3.7 Q8).
2812    async fn commit(
2813        &self,
2814        caller: &Caller,
2815        request: &ApprovalRequest,
2816        version: u64,
2817        answer: Answer,
2818        (edited_args, reason): (Option<Value>, Option<String>),
2819        plan: Option<&HeldPlan>,
2820    ) -> Result<CommandOutcome> {
2821        let rule = match answer {
2822            Answer::AlwaysAllow => {
2823                Some(self.inner.source.prepare_always_allow(caller, request).await?)
2824            }
2825            _ => None,
2826        };
2827        let subject = caller.subject.clone();
2828        let mut decision = match answer {
2829            Answer::AllowOnce | Answer::AlwaysAllow => ApprovalDecision::approve(subject),
2830            Answer::Edit => ApprovalDecision::edit(subject, edited_args.unwrap_or(Value::Null)),
2831            Answer::Deny => ApprovalDecision::reject(subject, reason.clone().unwrap_or_default()),
2832        }
2833        .with_groups(caller.groups.clone());
2834        if answer == Answer::Deny && reason.as_deref().is_none_or(str::is_empty) {
2835            decision.reason = None;
2836        }
2837        // The answer is on record before it takes effect, and one that cannot be recorded is
2838        // not given (spec 3.3 §11).
2839        let mut given = json!({
2840            "approvalId": request.id,
2841            "sessionId": request.scope.session_id,
2842            "tool": request.tool_name,
2843            "answer": answer,
2844            "version": version,
2845        });
2846        if let Ok(digest) = SPOKEN_DIGEST.try_with(Clone::clone) {
2847            given["transcriptDigest"] = json!(digest);
2848        }
2849        if let Some(plan) = plan {
2850            given["planDigest"] = json!(plan.view.digest);
2851        }
2852        self.record(caller, SURFACE_AUDIT_ANSWER, given).await?;
2853        // A yes to a form's call is sealed to the drawing the person saw before it takes
2854        // effect, so the call that runs is the one they approved (spec 3.3 §7.4 rule 5).
2855        #[cfg(feature = "genui")]
2856        if matches!(answer, Answer::AllowOnce | Answer::Edit)
2857            && let Some(seals) = &self.inner.seals
2858            && let Some(sent) = self.inner.drawn.sent_call(request)
2859        {
2860            let args = decision.edited_args.clone().unwrap_or_else(|| sent.args.clone());
2861            let card_text = format!(
2862                "{} {}",
2863                request.tool_name,
2864                serde_json::to_string(&args).unwrap_or_default()
2865            );
2866            let seal = seals.seal(crate::genui::SealInput {
2867                function_call_id: sent.call_id.clone(),
2868                tool_name: request.tool_name.clone(),
2869                args,
2870                card_text,
2871                drawing_digest: sent.digest.clone(),
2872                surface_id: sent.form.0.clone(),
2873                version: sent.form.1,
2874                approver: caller.user_id().to_string(),
2875            });
2876            self.record(
2877                caller,
2878                SURFACE_AUDIT_DRAWN_SEALED,
2879                json!({
2880                    "approvalId": request.id,
2881                    "callId": sent.call_id,
2882                    "surfaceId": sent.form.0,
2883                    "version": sent.form.1,
2884                    "drawingDigest": sent.digest,
2885                    "seal": seal,
2886                }),
2887            )
2888            .await?;
2889        }
2890        let decided = match plan {
2891            Some(plan) => {
2892                let allow = answer != Answer::Deny;
2893                self.inner
2894                    .source
2895                    .decide_screen_plan(caller, request, version, &plan.view.digest, allow, reason)
2896                    .await
2897            }
2898            None => self.inner.source.decide(&request.id, version, decision).await,
2899        };
2900        match decided {
2901            Ok(updated) => {
2902                // The decision is recorded and cannot be taken back: nothing after this point
2903                // fails the command or keeps the decided call and the queued input waiting.
2904                let resolved = updated.state != ApprovalState::Pending;
2905                // The standing rule only once the request was approved: an approval that a
2906                // quorum still waits on has not won (spec 3.3 §8.2).
2907                if let Some(rule) = rule.filter(|_| updated.state == ApprovalState::Approved)
2908                    && let Err(error) = rule.commit().await
2909                {
2910                    tracing::warn!(error = %error, decision.id = %updated.id, "the call was allowed once; its standing rule could not be created");
2911                }
2912                if resolved {
2913                    let record = AnswerRecord {
2914                        approval_id: updated.id.clone(),
2915                        by: caller.subject.clone(),
2916                        via: caller.via(),
2917                        answer,
2918                        at: self.now(),
2919                    };
2920                    if let Err(error) = self.inner.answers.record(&record).await {
2921                        tracing::warn!(error = %error, decision.id = %updated.id, "where the answer was given could not be kept");
2922                    }
2923                }
2924                if let Err(error) =
2925                    self.audit_decide(caller, &updated, answer, "decided", None).await
2926                {
2927                    tracing::warn!(error = %error, decision.id = %updated.id, "the answer took effect; its audit record failed");
2928                }
2929                if resolved {
2930                    if let Err(error) = self.inner.source.resolved_by(caller, &updated).await {
2931                        tracing::warn!(error = %error, decision.id = %updated.id, "the decided call could not be resumed");
2932                    }
2933                    self.spawn_drain(caller.clone(), updated.scope.session_id.clone());
2934                }
2935                let card = self.card(caller, &updated).await?;
2936                Ok(CommandOutcome::Answered { card })
2937            }
2938            Err(SurfaceError::Source(error))
2939                if matches!(
2940                    error.code,
2941                    "approval.version_conflict" | "approval.already_resolved" | "approval.expired"
2942                ) || (error.category == adk_core::ErrorCategory::Conflict
2943                    && error.code != "approval.already_decided") =>
2944            {
2945                let current = match self.owned_request(caller, &request.id).await {
2946                    Ok(current) => current,
2947                    // The source lists open requests only: answered, but not saying how.
2948                    Err(SurfaceError::NotFound { .. }) => {
2949                        return self.decided_elsewhere(caller, request, answer).await;
2950                    }
2951                    Err(error) => return Err(error),
2952                };
2953                if current.state == ApprovalState::Pending {
2954                    self.audit_decide(caller, &current, answer, "changed", Some(error.code))
2955                        .await?;
2956                    let card = self.card(caller, &current).await?;
2957                    return Ok(CommandOutcome::Changed { card });
2958                }
2959                self.already_decided(caller, &current, answer).await
2960            }
2961            Err(error) => Err(error),
2962        }
2963    }
2964
2965    async fn already_decided(
2966        &self,
2967        caller: &Caller,
2968        request: &ApprovalRequest,
2969        answer: Answer,
2970    ) -> Result<CommandOutcome> {
2971        self.audit_decide(caller, request, answer, "already_decided", None).await?;
2972        let card = self.card(caller, request).await?;
2973        let decided = card.decided.clone().ok_or_else(|| {
2974            SurfaceError::Invalid(format!("decision '{}' is not decided", request.id))
2975        })?;
2976        Ok(CommandOutcome::AlreadyDecided { decided, card })
2977    }
2978
2979    /// A decision the source no longer lists after a conflict: decided, details unknown.
2980    async fn decided_elsewhere(
2981        &self,
2982        caller: &Caller,
2983        request: &ApprovalRequest,
2984        answer: Answer,
2985    ) -> Result<CommandOutcome> {
2986        self.audit_decide(caller, request, answer, "already_decided", None).await?;
2987        let hint = self.hint(request).await;
2988        let mut card = self.inner.projector.card(request, caller, None, None, self.now(), &hint);
2989        // When it was decided is not known either: `at` is when this surface found out, and
2990        // no time is shown.
2991        let decided = Decided {
2992            by: String::new(),
2993            by_you: false,
2994            via: None,
2995            at: self.now(),
2996            at_text: String::new(),
2997            answer: crate::model::DecidedAnswer::Unknown,
2998            text: words::DECIDED.to_string(),
2999            scope_text: None,
3000        };
3001        card.status = crate::model::CardStatus::Decided;
3002        card.status_text = words::DECIDED.to_string();
3003        card.allowed.options.clear();
3004        card.allowed.open_in_home = false;
3005        card.allowed.cancel_window_secs = None;
3006        card.allowed.note = None;
3007        if let Some(step) = card.timeline.last_mut() {
3008            step.text = words::DECIDED.to_string();
3009        }
3010        card.decided = Some(decided.clone());
3011        Ok(CommandOutcome::AlreadyDecided { decided, card })
3012    }
3013
3014    /// A spoken "allow once" waits out its cancel window, then commits (spec 3.3 §5.6, §7.2);
3015    /// how the window ended goes to `settle`.
3016    async fn speak_later(
3017        &self,
3018        caller: &Caller,
3019        request: ApprovalRequest,
3020        version: u64,
3021        settle: Option<oneshot::Sender<Result<CommandOutcome>>>,
3022    ) -> Result<CommandOutcome> {
3023        let window = self.inner.voice_window;
3024        let cancel_until = self.now()
3025            + chrono::Duration::from_std(window).unwrap_or_else(|_| chrono::Duration::seconds(5));
3026        self.audit_decide(caller, &request, Answer::AllowOnce, "pending", None).await?;
3027        let digest = SPOKEN_DIGEST.try_with(Clone::clone).ok();
3028        let engine = self.clone();
3029        let speaker = caller.clone();
3030        let id = request.id.clone();
3031        let task_id = id.clone();
3032        let spoken = request.clone();
3033        let token = Arc::new(());
3034        let mine = Arc::clone(&token);
3035        let (go, entered) = oneshot::channel::<()>();
3036        let handle = tokio::spawn(with_digest(digest.clone(), async move {
3037            // Its entry is in place before the window starts, so a cancel always finds it.
3038            if entered.await.is_err() {
3039                return;
3040            }
3041            tokio::time::sleep(window).await;
3042            // Cancel and Stop all remove the entry before they abort the task: an answer whose
3043            // entry is gone, or was replaced, is withdrawn, whatever the abort's timing.
3044            let withdrawn = {
3045                let mut spoken = engine.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
3046                let current =
3047                    spoken.get(&task_id).is_some_and(|entry| Arc::ptr_eq(&entry.token, &mine));
3048                if current {
3049                    spoken.remove(&task_id);
3050                }
3051                !current
3052            };
3053            if withdrawn {
3054                return;
3055            }
3056            // Everything stopped meanwhile, here or on another surface: nothing runs.
3057            let result = if engine.inner.source.stopped().await.unwrap_or(false) {
3058                if let Err(error) = engine
3059                    .audit_decide(
3060                        &speaker,
3061                        &request,
3062                        Answer::AllowOnce,
3063                        "cancelled",
3064                        Some("surface.stopped"),
3065                    )
3066                    .await
3067                {
3068                    tracing::warn!(error = %error, decision.id = %task_id, "a spoken answer was cancelled; its audit record failed");
3069                }
3070                Err(SurfaceError::NotHere(words::ALL_AGENTS_STOPPED.to_string()))
3071            } else {
3072                engine
3073                    .commit(&speaker, &request, version, Answer::AllowOnce, (None, None), None)
3074                    .await
3075            };
3076            match &result {
3077                Ok(CommandOutcome::Answered { .. }) => {}
3078                Ok(outcome) => {
3079                    tracing::info!(decision.id = %task_id, outcome = ?outcome, "a spoken answer was not recorded: the decision changed in its cancel window");
3080                }
3081                Err(error) => {
3082                    tracing::warn!(error = %error, decision.id = %task_id, "a spoken answer could not be recorded");
3083                }
3084            }
3085            if let Some(settle) = settle {
3086                let _ = settle.send(result);
3087            }
3088        }));
3089        let entry =
3090            Spoken { handle, token, user: caller.user_id().to_string(), request: spoken, digest };
3091        if let Some(previous) =
3092            self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner()).insert(id.clone(), entry)
3093        {
3094            previous.handle.abort();
3095        }
3096        let _ = go.send(());
3097        Ok(CommandOutcome::Pending {
3098            decision_id: id,
3099            cancel_until,
3100            text: words::allowing_in(
3101                u64::try_from(window.as_millis().div_ceil(1000)).unwrap_or(u64::MAX),
3102            ),
3103        })
3104    }
3105
3106    /// Cancels a spoken answer at once, without reading the source, so a cancel never waits
3107    /// on a store; like a stop, it is recorded after, and a failed record does not undo it.
3108    async fn cancel_answer(&self, caller: &Caller, id: &str) -> Result<CommandOutcome> {
3109        let spoken = {
3110            let mut spoken = self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
3111            match spoken.get(id) {
3112                Some(entry) if entry.user == caller.user_id() => spoken.remove(id),
3113                _ => None,
3114            }
3115        };
3116        let Some(spoken) = spoken else {
3117            return Err(SurfaceError::not_found(format!("a spoken answer to '{id}' to cancel")));
3118        };
3119        spoken.handle.abort();
3120        if let Err(error) = with_digest(
3121            spoken.digest,
3122            self.audit_decide(caller, &spoken.request, Answer::AllowOnce, "cancelled", None),
3123        )
3124        .await
3125        {
3126            tracing::warn!(error = %error, decision.id = %id, "the spoken answer was cancelled; its audit record failed");
3127        }
3128        Ok(CommandOutcome::AnswerCancelled { decision_id: id.to_string() })
3129    }
3130
3131    /// **Stop the turn**: a person stops the running turn of their own session; recorded
3132    /// before it takes effect.
3133    async fn stop_turn(&self, caller: &Caller, session: String) -> Result<CommandOutcome> {
3134        if let Origin::Agent { agent } = &caller.origin {
3135            return Err(SurfaceError::NotHere(format!(
3136                "an agent ({agent}) never stops a person's turn; a person does (spec 3.3 §7.4)"
3137            )));
3138        }
3139        if self.inner.source.transcript(caller.user_id(), &session).await?.is_none() {
3140            return Err(SurfaceError::not_found(format!("session '{session}'")));
3141        }
3142        self.audit_command(caller, SURFACE_AUDIT_STOP_TURN, json!({ "sessionId": session }))
3143            .await?;
3144        let stopped = self.inner.source.stop_turn(caller, &session).await?;
3145        Ok(CommandOutcome::TurnStopped {
3146            session_id: session,
3147            stopped,
3148            text: words::TURN_STOPPED.to_string(),
3149        })
3150    }
3151
3152    /// Sends `text` as a message of the session: a turn at once when the session is free,
3153    /// queued otherwise, or always when `queue`. With `offer`, a message that waits behind a
3154    /// running turn is offered to that turn (spec 3.3 §6 "steer").
3155    async fn send(
3156        &self,
3157        caller: &Caller,
3158        session: String,
3159        text: String,
3160        images: Vec<crate::images::MessageImage>,
3161        queue: bool,
3162        offer: bool,
3163    ) -> Result<CommandOutcome> {
3164        if text.trim().is_empty() && images.is_empty() {
3165            return Err(SurfaceError::Invalid("the message is empty".into()));
3166        }
3167        // A running turn takes text at its next safe point; images wait for the next turn.
3168        let offer = offer && images.is_empty();
3169        let pictures = images.len();
3170        let key = (caller.user_id().to_string(), session.clone());
3171        let open = self.session_open(caller, &session).await?;
3172        // Earlier queued input goes first, including a message the delivery loop is starting
3173        // a turn for right now: a new message never overtakes it (S-I4). Input the running
3174        // turn holds is no reason to wait: that turn takes its messages in order.
3175        let (waiting, earlier) = {
3176            let queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3177            let queued = queues.get(&key);
3178            (
3179                queued.is_some_and(|queued| queued.iter().any(|input| !input.offered)),
3180                queued.is_some_and(|queued| !queued.is_empty())
3181                    || self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).contains(&key),
3182            )
3183        };
3184        // A running turn takes the message next, as an open decision does (S-I4).
3185        let busy = !open && !waiting && self.inner.source.busy(caller.user_id(), &session).await?;
3186        if open || earlier || busy || queue {
3187            // Recorded before it is queued: a message whose record failed is never sent.
3188            self.audit_command(
3189                caller,
3190                SURFACE_AUDIT_SEND,
3191                with_images(json!({ "sessionId": session, "queued": true }), pictures),
3192            )
3193            .await?;
3194            let held = match busy && offer && !queue {
3195                true => self.offer(caller, &session, &text).await?,
3196                false => None,
3197            };
3198            let (id, position) = self.enqueue(&key, text.clone(), images, held.is_some());
3199            if let Some(held) = held {
3200                self.settle_offer(caller.clone(), session.clone(), id, held, None);
3201            }
3202            self.spawn_drain(caller.clone(), session.clone());
3203            let text = if open {
3204                words::SENT_AFTER_THIS_CARD_IS_ANSWERED
3205            } else {
3206                words::SENT_WHEN_YOUR_AGENT_IS_FREE
3207            };
3208            return Ok(CommandOutcome::Queued {
3209                session_id: session,
3210                position,
3211                text: text.to_string(),
3212            });
3213        }
3214        self.audit_command(
3215            caller,
3216            SURFACE_AUDIT_SEND,
3217            with_images(json!({ "sessionId": session, "queued": false }), pictures),
3218        )
3219        .await?;
3220        self.inner.source.start_turn_images(caller, &session, &text, &images).await?;
3221        Ok(CommandOutcome::Sent { session_id: session })
3222    }
3223
3224    /// Adds `text` to the end of the session's queue; returns its id and its place, from 1.
3225    fn enqueue(
3226        &self,
3227        key: &(String, String),
3228        text: String,
3229        images: Vec<crate::images::MessageImage>,
3230        offered: bool,
3231    ) -> (u64, u32) {
3232        let id = self.inner.next_input.fetch_add(1, Ordering::Relaxed);
3233        let mut queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3234        let queued = queues.entry(key.clone()).or_default();
3235        queued.push_back(QueuedInput { id, text, images, offered });
3236        (id, u32::try_from(queued.len()).unwrap_or(u32::MAX))
3237    }
3238
3239    /// Offers `text` to the session's running turn (spec 3.3 §6 "steer"). `None` when no turn
3240    /// takes it, or the source cannot be asked just now: the message then waits its turn. A
3241    /// message the runtime refuses is not queued, and the refusal is on record.
3242    async fn offer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
3243        match self.inner.source.steer(caller, session, text).await {
3244            Ok(held) => Ok(held),
3245            Err(error) if transient(&error) => {
3246                tracing::debug!(error = %error, session.id = %session, "a running turn could not be offered a message; it waits as the next message");
3247                Ok(None)
3248            }
3249            Err(error) => {
3250                let fields =
3251                    json!({ "sessionId": session, "outcome": "refused", "code": error.code() });
3252                if let Err(audit) = self.audit_command(caller, SURFACE_AUDIT_STEER, fields).await {
3253                    tracing::warn!(error = %audit, session.id = %session, "a refused message's audit record failed");
3254                }
3255                Err(error)
3256            }
3257        }
3258    }
3259
3260    /// Follows the queued message `id`, which the session's running turn holds, to its end,
3261    /// on a task of the engine's own, so a surface that goes away loses nothing. Taken by
3262    /// the turn, the message leaves the queue; handed back, it stays in its place as the
3263    /// session's next message. `done` hears which.
3264    fn settle_offer(
3265        &self,
3266        caller: Caller,
3267        session: String,
3268        id: u64,
3269        held: Steering,
3270        done: Option<oneshot::Sender<Result<CommandOutcome>>>,
3271    ) {
3272        let engine = self.clone();
3273        tokio::spawn(async move {
3274            let key = (caller.user_id().to_string(), session.clone());
3275            let settled = held.await;
3276            let delivered = match &settled {
3277                Ok(Steered::Delivered { event_id }) => Some(event_id.clone()),
3278                Ok(Steered::Returned) => None,
3279                // What became of it could not be read. A message is never dropped, so it
3280                // goes as the next message.
3281                Err(error) => {
3282                    tracing::warn!(error = %error, session.id = %session, "what became of a message a running turn held could not be read; it goes as the next message");
3283                    None
3284                }
3285            };
3286            let position = {
3287                let mut queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3288                let queued = queues.entry(key).or_default();
3289                let place = queued.iter().position(|input| input.id == id);
3290                match (place, &delivered) {
3291                    (Some(place), Some(_)) => {
3292                        queued.remove(place);
3293                    }
3294                    (Some(place), None) => queued[place].offered = false,
3295                    (None, _) => {}
3296                }
3297                place.map_or(1, |place| u32::try_from(place + 1).unwrap_or(u32::MAX))
3298            };
3299            let fields = match &delivered {
3300                Some(event_id) => {
3301                    json!({ "sessionId": session, "outcome": "delivered", "eventId": event_id })
3302                }
3303                None => json!({ "sessionId": session, "outcome": "returned" }),
3304            };
3305            // The message already has its fate: a record that fails does not change it.
3306            if (delivered.is_some() || done.is_some())
3307                && let Err(error) = engine.audit_command(&caller, SURFACE_AUDIT_STEER, fields).await
3308            {
3309                tracing::warn!(error = %error, session.id = %session, "a steered message's audit record failed");
3310            }
3311            // The delivery loop looks again: a message handed back is the session's next,
3312            // and a queue the turn emptied ends the loop.
3313            engine.inner.wake.notify_waiters();
3314            engine.spawn_drain(caller, session.clone());
3315            if let Some(done) = done {
3316                let outcome = match delivered {
3317                    Some(event_id) => CommandOutcome::Steered { session_id: session, event_id },
3318                    None => CommandOutcome::Queued {
3319                        session_id: session,
3320                        position,
3321                        text: words::SENT_WHEN_YOUR_AGENT_IS_FREE.to_string(),
3322                    },
3323                };
3324                let _ = done.send(Ok(outcome));
3325            }
3326        });
3327    }
3328
3329    /// "Steer" (spec 3.3 §6): sends `text` to the running turn of the caller's own session
3330    /// and waits for what became of it. Refused, and recorded as refused, from an agent, for
3331    /// a session that is not the caller's (S-I8), and while everything is stopped.
3332    async fn steer(
3333        &self,
3334        caller: &Caller,
3335        session: String,
3336        text: String,
3337    ) -> Result<CommandOutcome> {
3338        if text.trim().is_empty() {
3339            return Err(SurfaceError::Invalid("the message is empty".into()));
3340        }
3341        let refusal = if let Origin::Agent { agent } = &caller.origin {
3342            Some(SurfaceError::NotHere(format!(
3343                "an agent ({agent}) never sends a message to a person's running turn; a person \
3344                 does (spec 3.3 §7.4)"
3345            )))
3346        } else if self.inner.source.transcript(caller.user_id(), &session).await?.is_none() {
3347            Some(SurfaceError::not_found(format!("session '{session}'")))
3348        } else if self.inner.source.stopped().await? {
3349            Some(SurfaceError::NotHere(words::ALL_AGENTS_STOPPED.to_string()))
3350        } else {
3351            None
3352        };
3353        if let Some(error) = refusal {
3354            self.audit_command(
3355                caller,
3356                SURFACE_AUDIT_STEER,
3357                json!({ "sessionId": session, "outcome": "refused", "code": error.code() }),
3358            )
3359            .await?;
3360            return Err(error);
3361        }
3362        let key = (caller.user_id().to_string(), session.clone());
3363        // An open decision, or a message that waits, goes first (S-I4): the message is handed
3364        // back at once, as the session's next.
3365        let waiting = self
3366            .inner
3367            .queues
3368            .lock()
3369            .unwrap_or_else(|e| e.into_inner())
3370            .get(&key)
3371            .is_some_and(|queued| queued.iter().any(|input| !input.offered));
3372        if waiting || self.session_open(caller, &session).await? {
3373            return self.send(caller, session, text, Vec::new(), false, false).await;
3374        }
3375        // Recorded before the turn holds it: a message whose record failed is never sent.
3376        self.audit_command(
3377            caller,
3378            SURFACE_AUDIT_STEER,
3379            json!({ "sessionId": session, "outcome": "offered" }),
3380        )
3381        .await?;
3382        let Some(held) = self.offer(caller, &session, &text).await? else {
3383            // No turn takes it here.
3384            return self.send(caller, session, text, Vec::new(), false, false).await;
3385        };
3386        let (id, _) = self.enqueue(&key, text, Vec::new(), true);
3387        let (done, settled) = oneshot::channel();
3388        self.settle_offer(caller.clone(), session, id, held, Some(done));
3389        settled.await.unwrap_or_else(|_| {
3390            Err(SurfaceError::Invalid(
3391                "the engine stopped before the turn said whether it took the message; the \
3392                 session's thread shows it when it did"
3393                    .into(),
3394            ))
3395        })
3396    }
3397
3398    /// Whether the session has a decision open: one the caller may answer, or a call held for
3399    /// someone else (§7.4 rule 2).
3400    async fn session_open(&self, caller: &Caller, session: &str) -> Result<bool> {
3401        let own =
3402            self.inner.source.requests(caller, Some(session), true).await?.iter().any(|request| {
3403                owns(caller, request)
3404                    && request.state == ApprovalState::Pending
3405                    && request.scope.session_id == session
3406            });
3407        Ok(own || self.inner.source.waiting_on_decision(caller.user_id(), session).await?)
3408    }
3409
3410    /// Delivers the session's queued input, oldest first and one turn at a time, once it has
3411    /// no open decision and no running turn (S-I4). The loop waits for as long as that takes,
3412    /// whichever surface answers the decision, and keeps a message whose turn could not start
3413    /// at the front of the queue.
3414    fn spawn_drain(&self, caller: Caller, session: String) {
3415        let key = (caller.user_id().to_string(), session.clone());
3416        {
3417            let queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3418            if queues.get(&key).is_none_or(VecDeque::is_empty) {
3419                return;
3420            }
3421            if !self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone()) {
3422                // The loop already runs: have it look again now.
3423                self.inner.wake.notify_waiters();
3424                return;
3425            }
3426        }
3427        let engine = self.clone();
3428        tokio::spawn(async move {
3429            let poll = engine.inner.poll;
3430            let mut wait = poll;
3431            loop {
3432                let woken = engine.inner.wake.notified();
3433                tokio::pin!(woken);
3434                woken.as_mut().enable();
3435                {
3436                    let queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3437                    if queues.get(&key).is_none_or(VecDeque::is_empty) {
3438                        engine
3439                            .inner
3440                            .draining
3441                            .lock()
3442                            .unwrap_or_else(|e| e.into_inner())
3443                            .remove(&key);
3444                        return;
3445                    }
3446                }
3447                // A message the running turn holds is not sent until the turn hands it back.
3448                let held = engine
3449                    .inner
3450                    .queues
3451                    .lock()
3452                    .unwrap_or_else(|e| e.into_inner())
3453                    .get(&key)
3454                    .and_then(VecDeque::front)
3455                    .is_some_and(|input| input.offered);
3456                let free = match engine.session_open(&caller, &session).await {
3457                    _ if held => Ok(false),
3458                    Ok(true) => Ok(false),
3459                    Ok(false) => {
3460                        engine.inner.source.busy(caller.user_id(), &session).await.map(|busy| !busy)
3461                    }
3462                    Err(error) => Err(error),
3463                };
3464                match free {
3465                    Ok(true) => {}
3466                    Ok(false) => {
3467                        tokio::select! {
3468                            () = engine.inner.source.changed(wait) => {}
3469                            () = &mut woken => {}
3470                        }
3471                        wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
3472                        continue;
3473                    }
3474                    Err(error) => {
3475                        tracing::debug!(error = %error, session.id = %session, "queued input waits: the session could not be read");
3476                        tokio::select! {
3477                            () = tokio::time::sleep(wait) => {}
3478                            () = &mut woken => {}
3479                        }
3480                        wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
3481                        continue;
3482                    }
3483                }
3484                let next = {
3485                    let mut queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3486                    match queues.get_mut(&key) {
3487                        Some(queued) if queued.front().is_some_and(|input| !input.offered) => {
3488                            queued.pop_front()
3489                        }
3490                        _ => None,
3491                    }
3492                };
3493                let Some(input) = next else { continue };
3494                match engine
3495                    .inner
3496                    .source
3497                    .start_turn_images(&caller, &session, &input.text, &input.images)
3498                    .await
3499                {
3500                    Ok(()) => {
3501                        wait = poll;
3502                        // Let the turn begin before looking again.
3503                        tokio::time::sleep(poll).await;
3504                    }
3505                    Err(error) => {
3506                        {
3507                            let mut queues =
3508                                engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3509                            queues.entry(key.clone()).or_default().push_front(input);
3510                            if !transient(&error) {
3511                                // It stays queued and shown; the next message or answer tries
3512                                // again.
3513                                tracing::warn!(error = %error, session.id = %session, "queued input could not be sent; it stays queued");
3514                                engine
3515                                    .inner
3516                                    .draining
3517                                    .lock()
3518                                    .unwrap_or_else(|e| e.into_inner())
3519                                    .remove(&key);
3520                                return;
3521                            }
3522                        }
3523                        tracing::warn!(error = %error, session.id = %session, "queued input could not be sent yet; trying again");
3524                        tokio::select! {
3525                            () = tokio::time::sleep(wait) => {}
3526                            () = &mut woken => {}
3527                        }
3528                        wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
3529                    }
3530                }
3531            }
3532        });
3533    }
3534
3535    /// Takes back the newest input queued for the session, before it is sent; `None` when
3536    /// none waits (spec 3.3 §7.4 rule 2), or when the session's running turn holds the newest
3537    /// (§6 "steer"): the turn may take it at any moment.
3538    pub fn unqueue_last(&self, caller: &Caller, session: &str) -> Option<String> {
3539        let mut queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
3540        let queued = queues.get_mut(&(caller.user_id().to_string(), session.to_string()))?;
3541        match queued.back() {
3542            Some(input) if !input.offered => queued.pop_back().map(|input| input.text),
3543            _ => None,
3544        }
3545    }
3546
3547    /// The input queued for the session, oldest first, as the person reads it: an app's
3548    /// suggestion is its words and label. A message the session's running turn holds is
3549    /// listed until the turn takes it.
3550    pub fn queued(&self, caller: &Caller, session: &str) -> Vec<String> {
3551        self.inner
3552            .queues
3553            .lock()
3554            .unwrap_or_else(|e| e.into_inner())
3555            .get(&(caller.user_id().to_string(), session.to_string()))
3556            .map(|queue| {
3557                queue
3558                    .iter()
3559                    .map(|input| {
3560                        crate::genui::suggested_message(&input.text)
3561                            .unwrap_or_else(|| input.text.clone())
3562                    })
3563                    .collect()
3564            })
3565            .unwrap_or_default()
3566    }
3567
3568    /// Looks at once whether the session's queued input can be sent, after an answer
3569    /// recorded outside [`execute`](Self::execute), such as a take over (spec 3.3 §7.4 rule 2).
3570    /// Queued input is sent without it too, once the session is free.
3571    pub fn deliver_queued(&self, caller: &Caller, session: &str) {
3572        self.spawn_drain(caller.clone(), session.to_string());
3573    }
3574
3575    /// Stop all and Resume all reach every run, so they need the group set with
3576    /// [`SurfaceEngineBuilder::stops_need`] (spec 3.3 §11 S-I10).
3577    fn may_stop(&self, caller: &Caller) -> Result<()> {
3578        match &self.inner.stops_need {
3579            Some(group) if !caller.groups.iter().any(|held| held == group) => {
3580                Err(SurfaceError::OperatorOnly { group: group.clone() })
3581            }
3582            _ => Ok(()),
3583        }
3584    }
3585
3586    async fn stop_all(&self, caller: &Caller, reason: Option<String>) -> Result<CommandOutcome> {
3587        let reason = reason.unwrap_or_else(|| words::STOP_ALL.to_string());
3588        // A spoken "allow once" still in its cancel window is withdrawn first: Stop all is the
3589        // strongest withdrawal (S-I10).
3590        let cancelled: Vec<String> = {
3591            let mut spoken = self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
3592            spoken
3593                .drain()
3594                .map(|(id, entry)| {
3595                    entry.handle.abort();
3596                    id
3597                })
3598                .collect()
3599        };
3600        // Every camera's gate closes before anything else (spec 3.7 V-I17): no frame passes
3601        // the hub from here on, wherever the freeze reaches next.
3602        if let Some(cameras) = &self.inner.cameras
3603            && let Err(error) = cameras.freeze_all().await
3604        {
3605            tracing::warn!(error = %error, "the cameras' gate closed; their source refused the pause");
3606        }
3607        // Stopping never waits on the audit log (spec 3.2 K-I8): record after, warn on failure.
3608        self.inner.source.stop_all(caller, &reason).await?;
3609        // Every open screen plan's card closes: a plan is approved by a person looking at it
3610        // while agents may act, never across a stop (spec 3.7 Q8, V-I17).
3611        let mut closed = Vec::new();
3612        for request in self.inner.source.requests(caller, None, true).await.unwrap_or_default() {
3613            if request.state == ApprovalState::Pending
3614                && let Some(plan) = self.card_plan(&request).await
3615            {
3616                self.close_plan(&request, &plan).await;
3617                closed.push(request.id.clone());
3618            }
3619        }
3620        let mut fields = json!({ "reason": reason });
3621        if !cancelled.is_empty() {
3622            fields["cancelledAnswers"] = json!(cancelled);
3623        }
3624        if !closed.is_empty() {
3625            fields["closedPlans"] = json!(closed);
3626        }
3627        if let Err(error) = self.audit_command(caller, SURFACE_AUDIT_STOP_ALL, fields).await {
3628            tracing::warn!(error = %error, "stop all took effect; its audit record failed");
3629        }
3630        Ok(CommandOutcome::Stopped { text: words::ALL_AGENTS_STOPPED.to_string() })
3631    }
3632
3633    async fn resume_all(&self, caller: &Caller) -> Result<CommandOutcome> {
3634        if !rules::may_resume(caller) {
3635            return Err(SurfaceError::NotHere(
3636                "Resume all happens only in the web home or on a paired local terminal \
3637                 (spec 3.3 S-I10)"
3638                    .into(),
3639            ));
3640        }
3641        self.audit_command(caller, SURFACE_AUDIT_RESUME_ALL, json!({})).await?;
3642        self.inner.source.resume_all(caller).await?;
3643        if let Some(cameras) = &self.inner.cameras {
3644            cameras.thaw_all().await?;
3645        }
3646        Ok(CommandOutcome::Resumed)
3647    }
3648
3649    async fn set_mode(&self, caller: &Caller, session: &str, mode: Mode) -> Result<CommandOutcome> {
3650        let target = project::harness_mode(mode);
3651        let current = self.inner.source.mode(caller.user_id(), Some(session)).await?;
3652        let loosens = current.is_none_or(|current| current.is_stricter_than(target));
3653        if matches!(caller.origin, Origin::Agent { .. })
3654            || (loosens && !rules::may_loosen_mode(caller))
3655        {
3656            return Err(SurfaceError::NotHere(
3657                "letting agents do more on their own is a standing permission: change it in \
3658                 the home app, on your phone or in the terminal"
3659                    .into(),
3660            ));
3661        }
3662        // In an added agent's own thread the mode can only make it ask more (spec 3.3 §5.7).
3663        if let Some(agent) = self.inner.source.agent_of_session(caller.user_id(), session).await?
3664            && let Some(detail) = self.inner.source.agent(caller.user_id(), &agent).await?
3665            && project::harness_mode(detail.mode.mode).is_stricter_than(target)
3666        {
3667            return Err(SurfaceError::NotHere(crate::agents::words::asks_at_most(
3668                &detail.draft.display_name,
3669                &detail.mode.label,
3670            )));
3671        }
3672        // A thread with no message yet takes a mode where the source opens it for the caller,
3673        // as a kernel's `/mode` does; elsewhere only the caller's own session does (S-I8).
3674        if self.inner.source.transcript(caller.user_id(), session).await?.is_none()
3675            && !self.inner.source.opens_sessions()
3676        {
3677            return Err(SurfaceError::not_found(format!("session '{session}'")));
3678        }
3679        self.audit_command(
3680            caller,
3681            SURFACE_AUDIT_SET_MODE,
3682            json!({ "sessionId": session, "mode": target.as_str() }),
3683        )
3684        .await?;
3685        self.inner.source.set_mode(caller, session, target).await?;
3686        Ok(CommandOutcome::ModeSet { mode: project::mode_view(target) })
3687    }
3688
3689    // -----------------------------------------------------------------------
3690    // Agents a person adds (spec 3.3 §5.7)
3691    // -----------------------------------------------------------------------
3692
3693    /// Whether the roster ends with **New agent** for `caller` (spec 3.3 §5.7).
3694    pub fn can_add_agents(&self, caller: &Caller) -> bool {
3695        self.inner.source.keeps_agents()
3696            && !matches!(caller.origin, Origin::Agent { .. })
3697            && rules::may_change_agents(caller)
3698    }
3699
3700    /// One agent `caller` added (spec 3.3 §5.7 "Agent settings").
3701    ///
3702    /// # Errors
3703    ///
3704    /// `surface.not_found` when the caller has no such agent, or the source's error.
3705    pub async fn agent(&self, caller: &Caller, id: &str) -> Result<crate::agents::AgentDetail> {
3706        self.inner
3707            .source
3708            .agent(caller.user_id(), id)
3709            .await?
3710            .map(|detail| self.with_granted(detail))
3711            .ok_or_else(|| SurfaceError::not_found(format!("agent '{id}'")))
3712    }
3713
3714    /// What `caller` may choose for an agent.
3715    ///
3716    /// # Errors
3717    ///
3718    /// `surface.not_here` where agents are not changed, or the source's error.
3719    pub async fn agent_choices(&self, caller: &Caller) -> Result<crate::agents::AgentChoices> {
3720        Self::may_change_agents(caller)?;
3721        self.inner.source.agent_choices().await
3722    }
3723
3724    /// **Here is what Finance can do**: the preview of `request` (spec 3.3 §5.7).
3725    ///
3726    /// # Errors
3727    ///
3728    /// `surface.not_here` where agents are not changed, or the kernel's refusal.
3729    pub async fn preview_agent(
3730        &self,
3731        caller: &Caller,
3732        request: crate::agents::AgentPreviewRequest,
3733    ) -> Result<crate::agents::AgentPreview> {
3734        Self::may_change_agents(caller)?;
3735        self.inner.source.preview_agent(caller, request).await
3736    }
3737
3738    /// Refuses a caller who may not change agents here: an agent, or a surface other than the
3739    /// web home and the terminal (spec 3.3 §5.7, §7.2).
3740    fn may_change_agents(caller: &Caller) -> Result<()> {
3741        if let Origin::Agent { agent } = &caller.origin {
3742            return Err(SurfaceError::NotHere(format!(
3743                "an agent ({agent}) never adds, changes, pauses or removes an agent; a person \
3744                 does (spec 3.3 §5.7)"
3745            )));
3746        }
3747        if !rules::may_change_agents(caller) {
3748            return Err(SurfaceError::NotHere(
3749                "agents are set up and changed in the home app or the terminal (spec 3.3 §7.2)"
3750                    .into(),
3751            ));
3752        }
3753        Ok(())
3754    }
3755
3756    async fn new_thread(
3757        &self,
3758        caller: &Caller,
3759        agent: &str,
3760        session: String,
3761        text: String,
3762        images: Vec<crate::images::MessageImage>,
3763    ) -> Result<CommandOutcome> {
3764        if text.trim().is_empty() && images.is_empty() {
3765            return Err(SurfaceError::Invalid("the message is empty".into()));
3766        }
3767        if let Origin::Agent { agent } = &caller.origin {
3768            return Err(SurfaceError::NotHere(format!(
3769                "an agent ({agent}) never starts a thread for a person (spec 3.3 §7.4)"
3770            )));
3771        }
3772        self.audit_command(
3773            caller,
3774            SURFACE_AUDIT_SEND,
3775            with_images(
3776                json!({ "sessionId": session, "queued": false, "agent": agent }),
3777                images.len(),
3778            ),
3779        )
3780        .await?;
3781        self.inner.source.start_turn_with_images(caller, agent, &session, &text, &images).await?;
3782        Ok(CommandOutcome::Sent { session_id: session })
3783    }
3784
3785    async fn agent_command(&self, caller: &Caller, command: Command) -> Result<CommandOutcome> {
3786        Self::may_change_agents(caller)?;
3787        let source = &self.inner.source;
3788        let agent_of = |command: &Command| match command {
3789            Command::ChangeAgent { agent, .. }
3790            | Command::PauseAgent { agent }
3791            | Command::ResumeAgent { agent }
3792            | Command::RemoveAgent { agent, .. }
3793            | Command::CopyRuleToAgent { agent, .. } => Some(agent.clone()),
3794            _ => None,
3795        };
3796        let agent = agent_of(&command);
3797        let result = match command {
3798            Command::AddAgent { draft, digest, replaces } => source
3799                .add_agent(caller, *draft, &digest, replaces)
3800                .await
3801                .map(|agent| CommandOutcome::AgentAdded { agent: self.with_granted(agent) }),
3802            Command::ChangeAgent { agent, version, draft, digest } => source
3803                .change_agent(caller, &agent, version, *draft, &digest)
3804                .await
3805                .map(|agent| CommandOutcome::AgentChanged { agent: self.with_granted(agent) }),
3806            Command::PauseAgent { agent } => source
3807                .pause_agent(caller, &agent)
3808                .await
3809                .map(|agent| CommandOutcome::AgentPaused { agent: self.with_granted(agent) }),
3810            Command::ResumeAgent { agent } => {
3811                // Resuming is the person at the home or a paired local terminal (S-I10).
3812                if !rules::may_resume_agent(caller) {
3813                    return Err(SurfaceError::NotHere(
3814                        words::ALL_AGENTS_STOPPED_RESUME_IN_HOME.to_string(),
3815                    ));
3816                }
3817                source
3818                    .resume_agent(caller, &agent)
3819                    .await
3820                    .map(|agent| CommandOutcome::AgentResumed { agent: self.with_granted(agent) })
3821            }
3822            Command::RemoveAgent { agent, version, digest } => source
3823                .remove_agent(caller, &agent, version, &digest)
3824                .await
3825                .map(|ended| CommandOutcome::AgentRemoved { ended }),
3826            Command::CopyRuleToAgent { agent, rule_id } => source
3827                .copy_rule_to_agent(caller, &agent, &rule_id)
3828                .await
3829                .map(|label| CommandOutcome::RuleCopied { agent, label }),
3830            _ => return Err(SurfaceError::Invalid("not a command about an agent".into())),
3831        };
3832        match (result, agent) {
3833            // Someone changed it since: shown again with what it is now, never overwritten.
3834            (Err(error), Some(agent)) if crate::agents::local::out_of_date(&error) => {
3835                let detail = self.agent(caller, &agent).await?;
3836                // Where it was changed: "in the terminal", "in the home app", "on your phone".
3837                let place = detail
3838                    .changed_on
3839                    .as_deref()
3840                    .and_then(|surface| serde_json::from_value::<SurfaceKind>(json!(surface)).ok())
3841                    .map_or_else(
3842                        || "elsewhere".to_string(),
3843                        |surface| crate::origin::Via { surface, origin: Origin::Keyboard }.phrase(),
3844                    );
3845                let text = crate::agents::words::changed_in(
3846                    &detail.draft.display_name,
3847                    &place,
3848                    &self.inner.projector.hh_mm(detail.changed_at),
3849                );
3850                Ok(CommandOutcome::AgentOutOfDate { agent: detail, text })
3851            }
3852            (result, _) => result,
3853        }
3854    }
3855
3856    // -----------------------------------------------------------------------
3857    // Audit (spec 3.3 §11)
3858    // -----------------------------------------------------------------------
3859
3860    fn draft(caller: &Caller, kind: AuditRecordKind, action: &str) -> AuditRecordDraft {
3861        let mut draft = AuditRecordDraft::new(kind, action)
3862            .actor(AuditActor::subject(caller.subject.clone()))
3863            .ext("surface", serde_json::to_value(caller.surface).unwrap_or(Value::Null))
3864            .ext("origin", serde_json::to_value(&caller.origin).unwrap_or(Value::Null));
3865        if let Some(device) = &caller.device {
3866            draft = draft.ext("device", json!(device));
3867        }
3868        if caller.presence_confirmed {
3869            draft = draft.ext("presence", json!("confirmed"));
3870        }
3871        draft
3872    }
3873
3874    async fn audit_decide(
3875        &self,
3876        caller: &Caller,
3877        request: &ApprovalRequest,
3878        answer: Answer,
3879        outcome: &str,
3880        code: Option<&str>,
3881    ) -> Result<()> {
3882        let Some(trail) = &self.inner.audit else {
3883            return Ok(());
3884        };
3885        let decision = match (outcome, answer) {
3886            ("decided", Answer::Deny) => Some(AuditDecision::Rejected),
3887            ("decided", _) => Some(AuditDecision::Approved),
3888            _ => None,
3889        };
3890        let mut draft = Self::draft(caller, AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
3891            .ext("approvalId", json!(request.id))
3892            .ext("sessionId", json!(request.scope.session_id))
3893            .ext("tool", json!(request.tool_name))
3894            .ext("answer", serde_json::to_value(answer).unwrap_or(Value::Null))
3895            .ext("outcome", json!(outcome));
3896        if let Some(decision) = decision {
3897            draft = draft.decision(decision);
3898        }
3899        // Whose call it was, so the record can say "You let Finance send one email" (§11).
3900        if let Some(acting) = &request.acting {
3901            draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
3902        }
3903        // What the call acts on, as a feature names it, so a denial names its item as the
3904        // change's own record does: "Finance asked to snooze News digest" (§8, §11).
3905        if let Some(title) = crate::hints::named(&self.inner.card_hints, request).await {
3906            draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
3907        }
3908        if let Some(code) = code {
3909            draft = draft.ext("code", json!(code));
3910        }
3911        if let Ok(digest) = SPOKEN_DIGEST.try_with(Clone::clone) {
3912            draft = draft.ext("transcriptDigest", json!(digest));
3913        }
3914        trail.record(draft).await.map_err(SurfaceError::Source)
3915    }
3916
3917    /// The record of a command `caller` gave (spec 3.3 §11): Stop all and Resume all as
3918    /// governance, a mode change as configuration, every other command through
3919    /// [`record`](Self::record).
3920    pub(crate) async fn audit_command(
3921        &self,
3922        caller: &Caller,
3923        action: &str,
3924        fields: Value,
3925    ) -> Result<()> {
3926        let kind = match action {
3927            SURFACE_AUDIT_STOP_ALL | SURFACE_AUDIT_RESUME_ALL => AuditRecordKind::Governance,
3928            SURFACE_AUDIT_SET_MODE => AuditRecordKind::Configuration,
3929            _ => return self.record(caller, action, fields).await,
3930        };
3931        self.write_record(caller, kind, action, fields).await
3932    }
3933
3934    /// Writes the record `action` of what `caller` did through a surface, with `fields` as its
3935    /// extensions (spec 3.3 §11): stamped with the caller's surface, origin, device and
3936    /// presence as every surface record is, of kind `Other("surface")`, which the kernel's
3937    /// surface-records route accepts. A feature records what a person did with it here, such
3938    /// as `surface.verb`. Without an audit trail nothing is written.
3939    pub(crate) async fn record(&self, caller: &Caller, action: &str, fields: Value) -> Result<()> {
3940        self.write_record(caller, AuditRecordKind::Other("surface".to_string()), action, fields)
3941            .await
3942    }
3943
3944    async fn write_record(
3945        &self,
3946        caller: &Caller,
3947        kind: AuditRecordKind,
3948        action: &str,
3949        fields: Value,
3950    ) -> Result<()> {
3951        let Some(trail) = &self.inner.audit else {
3952            return Ok(());
3953        };
3954        let mut draft = Self::draft(caller, kind, action);
3955        if let Value::Object(fields) = fields {
3956            for (key, value) in fields {
3957                draft = draft.ext(key, value);
3958            }
3959        }
3960        trail.record(draft).await.map_err(SurfaceError::Source)
3961    }
3962}
3963
3964/// Whether a turn that could not start may start later: the source was busy, unavailable or
3965/// over a limit, not refusing the request itself.
3966fn transient(error: &SurfaceError) -> bool {
3967    use adk_core::ErrorCategory;
3968    match error {
3969        SurfaceError::Source(error) => match error.category {
3970            ErrorCategory::RateLimited
3971            | ErrorCategory::Timeout
3972            | ErrorCategory::Unavailable
3973            | ErrorCategory::Cancelled
3974            | ErrorCategory::Internal
3975            | ErrorCategory::ResourceExhausted
3976            | ErrorCategory::Conflict => true,
3977            ErrorCategory::InvalidInput
3978            | ErrorCategory::Unauthorized
3979            | ErrorCategory::Forbidden
3980            | ErrorCategory::NotFound
3981            | ErrorCategory::Unsupported => false,
3982        },
3983        SurfaceError::NotFound { .. }
3984        | SurfaceError::Rule(_)
3985        | SurfaceError::NotHere(_)
3986        | SurfaceError::OperatorOnly { .. }
3987        | SurfaceError::Unsupported { .. }
3988        | SurfaceError::Invalid(_) => false,
3989    }
3990}
3991
3992/// `label` with its first letter in lower case, to follow a "·" in a sentence.
3993fn lower_first(label: &str) -> String {
3994    let mut chars = label.chars();
3995    match chars.next() {
3996        Some(first) => first.to_lowercase().chain(chars).collect(),
3997        None => String::new(),
3998    }
3999}
4000
4001/// The session-owner check every read and command makes (spec 3.3 §11 S-I8).
4002fn owns(caller: &Caller, request: &ApprovalRequest) -> bool {
4003    request.scope.user_id == caller.user_id()
4004}
4005
4006#[cfg(test)]
4007mod tests {
4008    use adk_core::audit_log::InMemoryAuditRecorder;
4009    use adk_core::{InMemoryApprovalStore, StoreApprovalService};
4010    use adk_session::InMemorySessionService;
4011
4012    use super::*;
4013    use crate::LocalSource;
4014
4015    /// A feature's record carries who did it, where and how, as every surface record does,
4016    /// under the kind the kernel's surface-records route accepts (spec 3.3 §11).
4017    #[tokio::test]
4018    async fn a_feature_record_is_stamped_like_every_surface_record() {
4019        let source = LocalSource::builder("adk-rust")
4020            .sessions(Arc::new(InMemorySessionService::new()))
4021            .approvals(Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))))
4022            .build()
4023            .unwrap();
4024        let audit = InMemoryAuditRecorder::new();
4025        let engine = SurfaceEngine::builder(Arc::new(source))
4026            .audit(AuditTrail::new(Arc::new(audit.clone())))
4027            .build();
4028        let caller = Caller::human("ana", SurfaceKind::Phone, Origin::Touch)
4029            .with_device("dev-1")
4030            .with_presence_confirmed();
4031
4032        engine.record(&caller, "surface.verb", json!({ "verb": "snooze" })).await.unwrap();
4033
4034        let expected =
4035            AuditRecordDraft::new(AuditRecordKind::Other("surface".into()), "surface.verb")
4036                .actor(AuditActor::subject(caller.subject.clone()))
4037                .ext("surface", json!("phone"))
4038                .ext("origin", json!({ "kind": "touch" }))
4039                .ext("device", json!("dev-1"))
4040                .ext("presence", json!("confirmed"))
4041                .ext("verb", json!("snooze"));
4042        assert_eq!(audit.records(), vec![expected]);
4043    }
4044}