Skip to main content

universal_exports/moneypenny/
mod.rs

1//! Moneypenny, the operator's assistant, as Universal Exports serves her.
2//!
3//! The model runs on a Station, through the same AgentHandler providers as every Agent: the
4//! roster's assistant Agent (`moneypenny` unless configured otherwise) with its handler,
5//! model, effort and model credentials. Universal Exports keeps the conversations, relays
6//! each message to a Station as an [`ai6::AssistantJob`] and what the harness says back to
7//! the app, and serves her tools on an MCP endpoint of its own. A tool runs as the person
8//! who is chatting, through the same routes and authorization as the app.
9//!
10//! When the roster's `[assistant]` gives people personal repositories, each message names the
11//! person's workspace (their repository, their groups' shared ones, their name for commits). A
12//! change to a shared repository is a proposal unless the group's repository is `write = true`.
13//! Her memory of the person needs none of it: Reports of kind `memory` in the Registry
14//! ([`knowledge`]), with the newest summaries in the context of each new harness.
15//!
16//! A conversation carries no exposure for what she reads: her gate is the person's confirmation, and
17//! exposure is for a Mission's Run. Tool results stay framed in `<ai6-data>`, which tells her
18//! what is data. Only a Report an exposed Run wrote leaves a mark on the conversation,
19//! which what she writes after it carries, so the mark is not washed out by passing through her.
20//!
21//! `show` and `navigate` only add an entry for the app: a view, or an app page offered as a
22//! card the person opens ([`routes`]). Neither reads nor changes anything, so neither is
23//! audited.
24//!
25//! Routes: `GET /v1/user/moneypenny` (the app's WebSocket), `POST /v1/moneypenny/mcp` (the
26//! harness's tools, with a token bound to the person and the conversation),
27//! `GET /v1/station/assistant/next`, `POST /v1/station/assistant/reports` and
28//! `GET /v1/station/assistant/cables` (the Stations).
29
30pub(crate) mod actions;
31pub(crate) mod cables;
32mod checks;
33pub(crate) mod commands;
34mod guide;
35pub(crate) mod images;
36pub(crate) mod knowledge;
37pub(crate) mod links;
38pub(crate) mod log;
39pub(crate) mod mcp;
40pub(crate) mod mcp_tokens;
41mod own_agent;
42pub(crate) mod page_tools;
43pub(crate) mod pages;
44pub(crate) mod routes;
45pub(crate) mod store;
46pub(crate) mod surfaces;
47mod svg;
48pub(crate) mod tools;
49pub(crate) mod views;
50
51pub use pages::PagesConfig;
52pub use views::ViewLimits;
53
54use std::collections::{HashMap, HashSet};
55use std::fmt;
56use std::sync::{Arc, Mutex, OnceLock};
57use std::time::{Duration, Instant};
58
59use ai6::wire::OpaqueJson;
60use ai6::{
61    AssistantChange, AssistantCommand, AssistantCommit, AssistantEvent, AssistantGatewayLimits,
62    AssistantJob, AssistantLimits, AssistantReach, AssistantReport, AssistantSettings,
63    AssistantWorkspace, EVENT_ACCEPTED, EVENT_CABLE_PROPOSAL, EVENT_CABLE_SENT, EVENT_CLOSED,
64    EVENT_COMMANDS, EVENT_COMPLETED, EVENT_FAILED, EVENT_INTERRUPTED, EVENT_LIMIT, EVENT_NOTICE,
65    EVENT_REJECTED, EVENT_TEXT, EVENT_TOOL, Limit, Seconds,
66};
67use axum::Json;
68use axum::extract::ws::{CloseFrame, Message, WebSocketUpgrade};
69use axum::extract::{Path, Query, State};
70use axum::http::{HeaderMap, StatusCode};
71use axum::response::{IntoResponse, Response};
72use futures_util::{SinkExt, StreamExt};
73use serde::{Deserialize, Serialize};
74use sha2::{Digest, Sha256};
75use tokio::sync::{Notify, broadcast};
76use uuid::Uuid;
77
78use crate::{
79    ApiError, Gateway, GatewayError, authorize_resource_action, bearer, resolve_signed_in,
80    unix_timestamp,
81};
82use store::{Bounds, Conversation, Entry, EntryData, Event, Pending, Role, Store, Usage};
83
84/// The request body of a commit proposal.
85#[derive(Serialize)]
86struct CommitBody<'a> {
87    message: &'a str,
88    files: &'a std::collections::BTreeMap<String, Option<String>>,
89}
90
91/// The Missions page route of a Mission a confirmed proposal queued.
92#[derive(Serialize)]
93struct MissionPage<'a> {
94    page: &'static str,
95    operation_id: &'a str,
96    mission_id: &'a str,
97}
98
99/// Whether the person holds `cable.send` and `cable.read`, as the Station is told.
100#[derive(Serialize)]
101pub(crate) struct CableStanding {
102    send: bool,
103    read: bool,
104}
105
106/// The digest a publish proposal's request names.
107#[derive(Deserialize)]
108struct Published {
109    digest: String,
110}
111
112/// Moneypenny's settings: which Agent she is and how much the gateway keeps.
113#[derive(Debug, Clone, PartialEq)]
114pub struct AssistantConfig {
115    agent_id: String,
116    limits: AssistantLimits,
117    gateway: AssistantGatewayLimits,
118    own_agent: ai6::AssistantOwnAgentLimits,
119    cable_body_bytes: Limit,
120    cable_default_ttl: Seconds,
121    route_text_bytes: usize,
122    views: views::ViewLimits,
123}
124
125impl Default for AssistantConfig {
126    fn default() -> Self {
127        let (cable_body_bytes, _, cable_default_ttl) = ai6::CableConfig::default().message_limits();
128        Self {
129            agent_id: "moneypenny".to_owned(),
130            limits: AssistantLimits::default(),
131            gateway: AssistantGatewayLimits::default(),
132            own_agent: ai6::AssistantOwnAgentLimits::default(),
133            cable_body_bytes,
134            cable_default_ttl,
135            route_text_bytes: routes::DEFAULT_TEXT_BYTES,
136            views: views::ViewLimits::default(),
137        }
138    }
139}
140
141impl AssistantConfig {
142    /// Moneypenny is the roster Agent `agent_id`; every other setting at its default.
143    ///
144    /// # Errors
145    ///
146    /// [`GatewayError::InvalidConfiguration`] for an empty identifier, one longer than 256
147    /// bytes or one with control characters.
148    pub fn new(agent_id: impl Into<String>) -> Result<Self, GatewayError> {
149        let agent_id = agent_id.into();
150        if !ai6::directorates::section_00::assistant::valid_identity(&agent_id) {
151            return Err(GatewayError::InvalidConfiguration);
152        }
153        Ok(Self {
154            agent_id,
155            ..Self::default()
156        })
157    }
158
159    /// The roster Agent that is Moneypenny.
160    pub fn agent_id(&self) -> &str {
161        &self.agent_id
162    }
163
164    /// The longest `text` filter an app route may carry, in bytes (default 128, at least 1):
165    /// in her links and cards, and in the page a message was sent from. A longer one refuses
166    /// the view, or drops the page line.
167    #[must_use]
168    pub fn with_route_text_bytes(mut self, bytes: usize) -> Self {
169        self.route_text_bytes = bytes.max(1);
170        self
171    }
172
173    pub(crate) fn route_limits(&self) -> routes::Limits {
174        routes::Limits {
175            text_bytes: self.route_text_bytes,
176        }
177    }
178
179    /// Holds jobs and reports to `limits` (`[assistant.limits]`), as the
180    /// Stations do.
181    ///
182    /// # Errors
183    ///
184    /// [`GatewayError::InvalidConfiguration`] for limits
185    /// [`AssistantLimits::validate`] refuses.
186    pub fn with_limits(mut self, limits: AssistantLimits) -> Result<Self, GatewayError> {
187        limits
188            .validate()
189            .map_err(|_| GatewayError::InvalidConfiguration)?;
190        self.limits = limits;
191        Ok(self)
192    }
193
194    /// Keeps her conversations within `limits` (`[assistant.gateway]`): how many are kept and
195    /// for how long, how much each holds, how many run at once, her tokens, proposals and tools.
196    ///
197    /// # Errors
198    ///
199    /// [`GatewayError::InvalidConfiguration`] for limits
200    /// [`AssistantGatewayLimits::validate`] refuses.
201    pub fn with_gateway_limits(
202        mut self,
203        limits: AssistantGatewayLimits,
204    ) -> Result<Self, GatewayError> {
205        limits
206            .validate()
207            .map_err(|_| GatewayError::InvalidConfiguration)?;
208        self.gateway = limits;
209        Ok(self)
210    }
211
212    /// Links people's own agents by `limits` (`[assistant.own_agent]`): codes, links, connections and
213    /// what an address may hold open. Read when a socket is accepted, so a changed record reaches
214    /// the next connection.
215    ///
216    /// # Errors
217    ///
218    /// [`GatewayError::InvalidConfiguration`] for limits [`ai6::AssistantOwnAgentLimits::validate`]
219    /// refuses.
220    pub fn with_own_agent_limits(
221        mut self,
222        limits: ai6::AssistantOwnAgentLimits,
223    ) -> Result<Self, GatewayError> {
224        limits
225            .validate()
226            .map_err(|_| GatewayError::InvalidConfiguration)?;
227        self.own_agent = limits;
228        Ok(self)
229    }
230
231    /// Refuses a Cable she proposes with a body past `body_bytes`, and tells the person a
232    /// Cable that names no lifetime lasts `default_ttl`: the `cables` record's values
233    /// ([`ai6::CableConfig::message_limits`]), which the relay applies.
234    #[must_use]
235    pub fn with_cable_limits(mut self, body_bytes: Limit, default_ttl: Seconds) -> Self {
236        self.cable_body_bytes = body_bytes;
237        self.cable_default_ttl = default_ttl;
238        self
239    }
240
241    pub(crate) fn bounds(&self) -> Bounds {
242        Bounds {
243            entries: self.gateway.conversation_entries.or_max(),
244            bytes: self.gateway.conversation_bytes.or_max(),
245        }
246    }
247
248    /// The bounds of the views she shows ([`ViewLimits`], each at least 1); the app is sent
249    /// them with each conversation and checks views against the same values.
250    #[must_use]
251    pub fn with_view_limits(mut self, limits: ViewLimits) -> Self {
252        self.views = limits.at_least_one();
253        self
254    }
255}
256
257/// `[assistant.gateway]` of `gateway`'s assistant, the defaults without one.
258pub(crate) fn gateway_limits(gateway: &Gateway) -> AssistantGatewayLimits {
259    gateway
260        .assistant()
261        .as_ref()
262        .map(|assistant| assistant.config().gateway.clone())
263        .unwrap_or_default()
264}
265
266/// What the Station of a page token starts with: a token the person's page gave an agent it speaks
267/// to itself, then the token's ID.
268pub(crate) const PAGE_STATION: &str = "page:";
269
270/// Whether `grant` is a page token.
271fn is_page_grant(grant: &Grant) -> bool {
272    grant.station.starts_with(PAGE_STATION)
273}
274
275/// Whether a token naming `station` is held by a person's own agent, through a relay or a page,
276/// rather than by a harness of a Station.
277pub(crate) fn serves_own_agent(station: &str) -> bool {
278    station.starts_with("link:") || station.starts_with(PAGE_STATION)
279}
280
281/// The token a harness presents: whose conversation it is, and the Station whose harness was
282/// given it. It is withdrawn when the conversation moves to another Station.
283struct Grant {
284    conversation_id: String,
285    person_id: String,
286    station: String,
287    expires_at: f64,
288}
289
290#[derive(Default)]
291struct Desk {
292    store: Store,
293    /// Tokens by their SHA-256.
294    tokens: HashMap<String, Grant>,
295    /// Tool calls in the current minute, by conversation.
296    calls: HashMap<String, (Instant, u32)>,
297    /// Jobs that close or interrupt a harness, by the Station that runs it.
298    controls: Vec<(String, AssistantJob)>,
299    /// The control jobs a Station has not answered yet, by ID, with the Station given each.
300    controlling: HashMap<String, (String, Control)>,
301    /// Confirmed Cables waiting for their Station, by control job ID: the conversation, the
302    /// proposal and when they are given up, Unix seconds.
303    cable_deadlines: HashMap<String, (String, String, f64)>,
304    /// Active own-agent ACP session workers, keyed by conversation ID.
305    own_agents: HashMap<String, own_agent::OwnAgentHandle>,
306    /// Pending own-agent permission prompts `(conversation_id, request_id) -> decision`.
307    pending_permissions: HashMap<(String, String), tokio::sync::oneshot::Sender<Option<bool>>>,
308}
309
310/// What a control job asks of a Station.
311#[derive(Debug, Clone, PartialEq, Eq)]
312enum Control {
313    Close,
314    Interrupt,
315    /// A commit of a shared change, the proposal it carries out when the person confirmed one, and
316    /// what it is, for the note that tells her how it went.
317    Commit {
318        proposal: Option<String>,
319        what: String,
320    },
321    /// Send the Cable held for the proposal with this ID.
322    CableConfirm(String),
323    /// Drop the Cable held for the proposal with this ID.
324    CableDiscard(String),
325}
326
327/// A job that closes or interrupts the harness of `conversation`, or makes `commit`, sending
328/// no message; a Cable decision is the caller's to fill in.
329fn control_job(
330    conversation: &Conversation,
331    agent_id: &str,
332    control: &Control,
333    commit: Option<AssistantCommit>,
334) -> AssistantJob {
335    AssistantJob {
336        job_id: Uuid::new_v4().to_string(),
337        conversation_id: conversation.id.clone(),
338        agent_id: agent_id.to_owned(),
339        message: String::new(),
340        context: Vec::new(),
341        recap: None,
342        // Never accepted anywhere: a control starts no harness.
343        mcp_token: format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()),
344        token_expires_at: now() + 60.0,
345        run_id: conversation.run_id.clone(),
346        route: conversation.route.clone(),
347        close: *control == Control::Close,
348        interrupt: *control == Control::Interrupt,
349        person_id: Some(conversation.person_id.clone()),
350        workspace: None,
351        commit,
352        cables: Vec::new(),
353        cable_confirm: None,
354        cable_discard: None,
355        reach: AssistantReach::default(),
356        skills: Vec::new(),
357        // A control starts no harness, so it carries no reach, skills or groups.
358        groups: None,
359        images: Vec::new(),
360    }
361}
362
363impl Desk {
364    /// Asks the Station running `conversation_id`'s harness to close it, and withdraws the
365    /// conversation's tokens.
366    fn close_harness(&mut self, conversation_id: &str, agent_id: &str) {
367        let Some(conversation) = self.store.conversations.get_mut(conversation_id) else {
368            return;
369        };
370        conversation.live = false;
371        conversation.token = None;
372        let Some(station) = conversation.station.clone() else {
373            return;
374        };
375        let job = control_job(conversation, agent_id, &Control::Close, None);
376        self.tokens
377            .retain(|_, grant| grant.conversation_id != conversation_id);
378        self.controlling
379            .insert(job.job_id.clone(), (station.clone(), Control::Close));
380        self.controls.push((station, job));
381    }
382
383    /// Queues `commit` of `conversation_id` for `station`; its answer is handled as `control`.
384    /// A shared commit's job names `groups`, the person's directory groups, so the Station
385    /// checks the repository is theirs.
386    fn queue_commit(
387        &mut self,
388        conversation_id: &str,
389        agent_id: &str,
390        station: String,
391        (commit, groups): (AssistantCommit, Option<Vec<String>>),
392        control: Control,
393    ) {
394        let Some(conversation) = self.store.conversations.get(conversation_id) else {
395            return;
396        };
397        let mut job = control_job(conversation, agent_id, &control, Some(commit));
398        job.groups = groups;
399        self.controlling
400            .insert(job.job_id.clone(), (station.clone(), control));
401        self.controls.push((station, job));
402    }
403}
404
405/// The settings of Moneypenny's workspaces: the roster's `[assistant]`, the default without a
406/// roster.
407async fn assistant_settings(gateway: &Gateway) -> Result<AssistantSettings, String> {
408    let Some(source) = gateway.roster.clone() else {
409        return Ok(AssistantSettings::default());
410    };
411    tokio::task::spawn_blocking(move || source.load(""))
412        .await
413        .map_err(|error| error.to_string())?
414        .map(|snapshot| snapshot.roster.assistant().clone())
415        .map_err(|error| format!("the roster could not be read: {error}"))
416}
417
418/// Where `person`'s conversations keep their work, `None` when the deployment gives nobody a
419/// personal repository; an `Err` says why this person cannot have one.
420fn workspace_for(
421    settings: &AssistantSettings,
422    person: &ai6::Person,
423    author_chars: Limit,
424) -> Result<Option<AssistantWorkspace>, String> {
425    let Some(personal) = settings.personal_repo_for(&person.id)? else {
426        return Ok(None);
427    };
428    let (author_name, author_email) = author_of(person, author_chars);
429    Ok(Some(AssistantWorkspace {
430        personal,
431        shared: settings
432            .shared_for(&person.groups)
433            .map(|(name, repo)| (name.to_owned(), repo.repo().to_owned()))
434            .collect(),
435        author_name,
436        author_email,
437    }))
438}
439
440/// The name and email `person`'s commits are authored with: the directory's, without control
441/// characters, `<` or `>`, each at most `chars` characters; an email under the reserved
442/// `.invalid` domain when it has none.
443fn author_of(person: &ai6::Person, chars: Limit) -> (String, String) {
444    let printable = |value: &str| -> String {
445        value
446            .chars()
447            .map(|c| {
448                if c.is_control() || matches!(c, '<' | '>') {
449                    ' '
450                } else {
451                    c
452                }
453            })
454            .collect::<String>()
455            .trim()
456            .chars()
457            .take(chars.or_max())
458            .collect()
459    };
460    let shown = crate::principals::shown_name(person);
461    let name = printable(shown.as_deref().unwrap_or(&person.name));
462    let email = person
463        .email
464        .as_deref()
465        .map(printable)
466        .filter(|email| !email.is_empty())
467        .unwrap_or_else(|| {
468            format!(
469                "{}@people.ai6.invalid",
470                ai6::directorates::m::assistant::person_digest(&person.id)
471            )
472        });
473    let name = if name.is_empty() {
474        printable(&person.id)
475    } else {
476        name
477    };
478    (name, email)
479}
480
481/// Settles proposal `id` of `conversation` as done or failed with `result`, and tells her
482/// with the next message.
483fn settle(conversation: &mut Conversation, id: &str, done: bool, result: &str) {
484    let Some(proposal) = conversation
485        .proposals
486        .iter_mut()
487        .find(|proposal| proposal.id == id)
488    else {
489        return;
490    };
491    proposal.status = if done { "done" } else { "failed" };
492    proposal.result = Some(result.to_owned());
493    let shown = proposal.clone();
494    conversation.show_proposal(&shown);
495    conversation.notes.push(format!(
496        "[App: the person confirmed {id}. {}: {result}]",
497        if done { "Done" } else { "It failed" }
498    ));
499}
500
501/// The audit resource of commits to the repositories of the roster's `[assistant]` table.
502const ASSISTANT_AUDIT_RESOURCE: &str = "config:assistant";
503
504/// The commit trailer naming Moneypenny and the conversation.
505fn trailer(conversation_id: &str) -> String {
506    format!("Via: Moneypenny (conversation {conversation_id})")
507}
508
509/// Moneypenny's state in one gateway.
510pub(crate) struct Assistant {
511    /// What a conversation or turn that starts now runs by; one already running keeps the `Arc` it took.
512    config: std::sync::RwLock<Arc<AssistantConfig>>,
513    enabled: std::sync::atomic::AtomicBool,
514    desk: Mutex<Desk>,
515    ready: Notify,
516    /// Told when a Station reports shared bases.
517    based: Notify,
518    /// Where every conversation's entries are kept, once the gateway has a Registry.
519    log: OnceLock<log::Sink>,
520    #[cfg(test)]
521    mcp_origin: std::sync::RwLock<Option<String>>,
522}
523
524impl fmt::Debug for Assistant {
525    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526        f.debug_struct("Assistant")
527            .field("config", &self.config())
528            .finish_non_exhaustive()
529    }
530}
531
532fn digest(token: &str) -> String {
533    Sha256::digest(token.as_bytes())
534        .iter()
535        .map(|byte| format!("{byte:02x}"))
536        .collect()
537}
538
539/// What a confirmed request came to.
540struct Executed {
541    /// What AI6 answered, as data.
542    text: String,
543    /// A new password, which only the app is told.
544    secret: Option<String>,
545    /// The page a queued Mission reopens.
546    receipt: Option<OpaqueJson>,
547    /// Whether the route answered `200` and held the change instead of making it.
548    held: bool,
549}
550
551/// What the audit record `moneypenny.confirmed` names of a proposal: the conversation, the
552/// proposal and its tool, the SHA-256 of the request's canonical body and of the reads it rested
553/// on, the request's path and, as far as the target's bound leaves room, the names of those
554/// reads. The digests come before the path, which is the part a bound cuts.
555fn confirmed_target(conversation_id: &str, proposal: &actions::Proposal) -> String {
556    let body = proposal
557        .draft
558        .call
559        .body
560        .as_ref()
561        .map_or_else(|| "null".to_owned(), ai6::wire::OpaqueJson::canonical);
562    let reads = serde_json::to_string(&proposal.evidence.read).unwrap_or_default();
563    let names: Vec<&str> = proposal
564        .evidence
565        .read
566        .iter()
567        .map(|read| read.tool.as_str())
568        .collect();
569    format!(
570        "{conversation_id} {} {} body=sha256:{} evidence=sha256:{} {} reads={}",
571        proposal.id,
572        proposal.tool,
573        digest(&body),
574        digest(&reads),
575        proposal.draft.call.path,
576        names.join(",")
577    )
578}
579
580fn now() -> f64 {
581    unix_timestamp().unwrap_or(0.0)
582}
583
584impl Assistant {
585    /// The settings a conversation or turn that starts now runs by.
586    pub(crate) fn config(&self) -> Arc<AssistantConfig> {
587        self.config
588            .read()
589            .unwrap_or_else(std::sync::PoisonError::into_inner)
590            .clone()
591    }
592
593    /// Makes the conversations and turns that start from now on run by `config`.
594    pub(crate) fn set_config(&self, config: AssistantConfig) {
595        *self
596            .config
597            .write()
598            .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(config);
599    }
600
601    /// Whether she answers; a turn already running finishes either way.
602    pub(crate) fn enabled(&self) -> bool {
603        self.enabled.load(std::sync::atomic::Ordering::Acquire)
604    }
605
606    pub(crate) fn set_enabled(&self, enabled: bool) {
607        self.enabled
608            .store(enabled, std::sync::atomic::Ordering::Release);
609    }
610
611    pub(crate) fn new(config: AssistantConfig) -> Self {
612        Self {
613            config: std::sync::RwLock::new(Arc::new(config)),
614            enabled: std::sync::atomic::AtomicBool::new(true),
615            desk: Mutex::default(),
616            ready: Notify::new(),
617            based: Notify::new(),
618            log: OnceLock::new(),
619            #[cfg(test)]
620            mcp_origin: std::sync::RwLock::new(None),
621        }
622    }
623
624    pub(crate) fn mcp_origin(&self, gateway: &Gateway) -> String {
625        #[cfg(test)]
626        if let Some(origin) = self
627            .mcp_origin
628            .read()
629            .unwrap_or_else(std::sync::PoisonError::into_inner)
630            .clone()
631        {
632            return origin;
633        }
634        gateway.config.public_origin.clone()
635    }
636
637    #[cfg(test)]
638    pub(crate) fn set_mcp_origin(&self, origin: impl Into<String>) {
639        *self
640            .mcp_origin
641            .write()
642            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(origin.into());
643    }
644
645    /// Snapshot of entries in memory for `id` when owned by `person_id`.
646    pub(crate) fn snapshot_entries(&self, id: &str, person_id: &str) -> Option<Vec<Entry>> {
647        self.desk()
648            .store
649            .conversations
650            .get(id)
651            .filter(|conv| conv.person_id == person_id)
652            .map(|conv| conv.entries.iter().cloned().collect())
653    }
654
655    /// Keeps every conversation's entries in `registry` from now on.
656    pub(crate) fn start_log(&self, registry: Arc<dyn ai6::RegistryBackend>) {
657        self.log
658            .get_or_init(|| log::start(registry, &self.config().gateway));
659    }
660
661    /// Takes conversation `requested` back from the log when this gateway does not hold it and
662    /// it is `person_id`'s: after a restart, the person finds it as they left it.
663    async fn restore(&self, gateway: &Gateway, person_id: &str, bearer: &str, requested: &str) {
664        if self.log.get().is_none() || self.desk().store.conversations.contains_key(requested) {
665            return;
666        }
667        let Some(registry) = gateway.registry.clone() else {
668            return;
669        };
670        let wanted = requested.to_owned();
671        let Ok(Ok(rows)) =
672            tokio::task::spawn_blocking(move || registry.assistant_log(&wanted)).await
673        else {
674            return;
675        };
676        if rows.first().is_none_or(|first| first.person != person_id) {
677            return;
678        }
679        let limits = &self.config().gateway;
680        let Some(mut conversation) = log::rebuild(
681            &rows,
682            bearer,
683            self.config().bounds(),
684            usize::try_from(limits.event_buffer).unwrap_or(usize::MAX),
685        ) else {
686            return;
687        };
688        // What it spent before the restart is in its log: each harness entry carries its turn's
689        // tokens and cost.
690        for turn in rows.iter().filter_map(|row| row.turn.as_ref()) {
691            conversation.spent_tokens = conversation
692                .spent_tokens
693                .saturating_add(turn.tokens.unwrap_or(0));
694            conversation.spent_micro_usd = conversation
695                .spent_micro_usd
696                .saturating_add(turn.cost_micro_usd.unwrap_or(0));
697        }
698        conversation.log = self.log.get().cloned();
699        conversation.log_cap = self.config().own_agent.log_rows_per_minute;
700        conversation.agent = Some(self.config().agent_id.clone());
701        let mut desk = self.desk();
702        if desk.store.conversations.contains_key(requested) {
703            return;
704        }
705        desk.store.make_room(
706            person_id,
707            now(),
708            limits.conversation_age.as_secs_f64(),
709            limits.conversations_per_person.or_max(),
710            limits.conversations.or_max(),
711        );
712        desk.store
713            .conversations
714            .insert(requested.to_owned(), conversation);
715    }
716
717    /// Waits up to `[assistant.gateway] log_flush_timeout` for the conversation log to keep what
718    /// is still queued; at once when no log was started. What is left is logged.
719    pub(crate) async fn flush_log(&self) {
720        let Some(sink) = self.log.get().cloned() else {
721            return;
722        };
723        let timeout = self.config().gateway.log_flush_timeout;
724        let flushed = tokio::task::spawn_blocking(move || sink.flush(timeout)).await;
725        match flushed {
726            Ok(Ok(())) => {}
727            Ok(Err(left)) => eprintln!(
728                "universal-exports: Moneypenny's log was stopped with {left} entries not kept"
729            ),
730            Err(error) => {
731                eprintln!("universal-exports: Moneypenny's log was not flushed: {error}");
732            }
733        }
734    }
735
736    /// Keeps a tool call of conversation `conversation_id`, or its answer, in its log.
737    pub(crate) fn log_tool(
738        &self,
739        conversation_id: &str,
740        tool: &str,
741        event: ai6::AssistantLogEvent,
742    ) {
743        if let Some(conversation) = self.desk().store.conversations.get_mut(conversation_id) {
744            conversation.record(event, tool, true);
745        }
746    }
747
748    fn desk(&self) -> std::sync::MutexGuard<'_, Desk> {
749        // A panic while holding it leaves bounded maps that are still consistent.
750        self.desk
751            .lock()
752            .unwrap_or_else(std::sync::PoisonError::into_inner)
753    }
754
755    /// Opens `requested` when it is the person's, else a new conversation; returns its ID,
756    /// what the app shows and a subscription to what follows.
757    async fn open_with_options(
758        &self,
759        gateway: &Gateway,
760        person: &crate::Person,
761        bearer: &str,
762        requested: Option<&str>,
763        runner: Option<store::Runner>,
764        from: Option<&str>,
765    ) -> Result<(String, Event, broadcast::Receiver<Event>), (&'static str, String)> {
766        let held = requested.and_then(|id| {
767            self.desk()
768                .store
769                .owned(id, &person.id)
770                .map(|conversation| conversation.runner.clone())
771        });
772        let held_link = match &held {
773            Some(held) => own_agent::link_status(gateway, held, &person.id).await,
774            None => None,
775        };
776        if let Some(id) = requested
777            && let Some(existing) = {
778                let mut desk = self.desk();
779                desk.store.owned(id, &person.id).map(|conversation| {
780                    conversation.bearer = bearer.to_owned();
781                    let is_own = matches!(conversation.runner, store::Runner::OwnAgent { .. });
782                    (
783                        conversation.id.clone(),
784                        ready(
785                            conversation,
786                            held_link,
787                            &self.config().views,
788                            &self.config().gateway,
789                        ),
790                        conversation.events.subscribe(),
791                        is_own,
792                    )
793                })
794            }
795        {
796            if existing.3
797                && let Some(ast) = gateway.assistant()
798            {
799                own_agent::warm_attach(gateway.clone(), ast, existing.0.clone());
800            }
801            return Ok((existing.0, existing.1, existing.2));
802        }
803
804        let chosen_runner = runner.unwrap_or_default();
805        if let store::Runner::OwnAgent { link_id } = &chosen_runner {
806            crate::authorize_resource_action(
807                gateway,
808                person.clone(),
809                "config:assistant".to_owned(),
810                "assistant.own_agent",
811            )
812            .await
813            .map_err(|_| ("forbidden", "You may not run your own agent.".to_owned()))?;
814            let registry = gateway
815                .registry
816                .clone()
817                .ok_or(("unavailable", "Registry unavailable.".to_owned()))?;
818            let wanted = link_id.clone();
819            let record = tokio::task::spawn_blocking(move || registry.agent_link(&wanted))
820                .await
821                .map_err(|_| ("unavailable", "Could not read that agent link.".to_owned()))?
822                .map_err(|_| ("unavailable", "Could not read that agent link.".to_owned()))?;
823            let Some(link) = record.filter(|link| link.person_id == person.id) else {
824                return Err(("not_found", "That agent link was not found.".to_owned()));
825            };
826            if !link.may_use_tools() {
827                return Err((
828                    "forbidden",
829                    "Confirm that agent link before starting a conversation with it.".to_owned(),
830                ));
831            }
832        }
833
834        let link = own_agent::link_status(gateway, &chosen_runner, &person.id).await;
835
836        if let Some(source_id) = from {
837            self.restore(gateway, &person.id, bearer, source_id).await;
838        }
839
840        let cfg = self.config();
841        let limits = &cfg.gateway;
842        let marks_kept = gateway
843            .registry
844            .as_ref()
845            .map_or(Limit::UNBOUNDED, |registry| {
846                registry.limits().runs.exposures
847            });
848
849        let mut desk = self.desk();
850        let (seed_recap, seed_marks) = from
851            .and_then(|src_id| desk.store.owned(src_id, &person.id))
852            .map(|src| {
853                (
854                    recap_with_heading(
855                        src,
856                        &cfg,
857                        "Continued from a previous conversation (a recap):",
858                    ),
859                    src.memory_marks.clone(),
860                )
861            })
862            .unwrap_or((None, Vec::new()));
863
864        let now = now();
865        desk.store.make_room(
866            &person.id,
867            now,
868            limits.conversation_age.as_secs_f64(),
869            limits.conversations_per_person.or_max(),
870            limits.conversations.or_max(),
871        );
872        let id = Uuid::new_v4().to_string();
873        let mut conversation = Conversation::new(
874            id.clone(),
875            person.id.clone(),
876            bearer.to_owned(),
877            now,
878            usize::try_from(limits.event_buffer).unwrap_or(usize::MAX),
879        );
880        conversation.log = self.log.get().cloned();
881        conversation.log_cap = cfg.own_agent.log_rows_per_minute;
882        conversation.agent = Some(cfg.agent_id.clone());
883        conversation.runner = chosen_runner;
884        conversation.seed_recap = seed_recap;
885        conversation.note_memory_marks(seed_marks, marks_kept);
886        if matches!(conversation.runner, store::Runner::OwnAgent { .. })
887            || conversation.seed_recap.is_some()
888        {
889            conversation.record_meta();
890        }
891        let is_own = matches!(conversation.runner, store::Runner::OwnAgent { .. });
892        let shown = ready(&conversation, link, &cfg.views, limits);
893        let events = conversation.events.subscribe();
894        desk.store.conversations.insert(id.clone(), conversation);
895        drop(desk);
896        if is_own && let Some(ast) = gateway.assistant() {
897            own_agent::warm_attach(gateway.clone(), ast, id.clone());
898        }
899        Ok((id, shown, events))
900    }
901
902    /// Queues the person's message for a Station, after the page line of `route` (the app page
903    /// they sent it from, in the route's JSON form) when it is a route.
904    async fn message(
905        &self,
906        gateway: &Gateway,
907        conversation_id: &str,
908        person_id: &str,
909        text: &str,
910        route: Option<&OpaqueJson>,
911        images: &[images::AppImage],
912    ) -> Result<(), (&'static str, String)> {
913        // A job carries the message whole or not at all: the smaller bound applies.
914        let most = match (
915            self.config().gateway.message_bytes.get(),
916            self.config().limits.message_bytes.get(),
917        ) {
918            (Some(own), Some(job)) => Limit::at(own.min(job)),
919            (Some(bound), None) | (None, Some(bound)) => Limit::at(bound),
920            (None, None) => Limit::UNBOUNDED,
921        };
922        if text.trim().is_empty() || !most.allows(text.len()) {
923            return Err(("bad_request", format!("A message is 1 to {most} bytes.")));
924        }
925        let bearer = self
926            .desk()
927            .store
928            .owned(conversation_id, person_id)
929            .map(|conversation| conversation.bearer.clone())
930            .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
931        // The tools run with this token: a message after it ended starts nothing.
932        resolve_signed_in(gateway, &bearer).await.map_err(|_| {
933            (
934                "unauthorized",
935                "Sign in again to talk to Moneypenny.".to_owned(),
936            )
937        })?;
938        let spent = self
939            .desk()
940            .store
941            .owned(conversation_id, person_id)
942            .map_or(0, |conversation| conversation.spent_micro_usd);
943        let budget = self.config().limits.conversation_cost_micro_usd;
944        if budget.get().is_some_and(|bound| spent >= bound) {
945            return Err((
946                "budget",
947                format!(
948                    "This conversation has used its budget (${} of ${}). Start a new conversation to continue.",
949                    ai6::directorates::medical::usage::usd_text(spent),
950                    ai6::directorates::medical::usage::usd_text(budget.get().unwrap_or(0)),
951                ),
952            ));
953        }
954        let kept = self.keep_images(gateway, person_id, images)?;
955        let message = match route.and_then(|route| page_line(route, self.config().route_limits())) {
956            Some(line) => format!("{line}\n\n{text}"),
957            None => text.to_owned(),
958        };
959        self.queue(
960            gateway,
961            conversation_id,
962            person_id,
963            &message,
964            Some((text, kept.as_slice())),
965        )
966        .await
967    }
968
969    /// Checks the images of a message against `[assistant.limits]` and keeps them for
970    /// `person_id`; why not, in words for the person.
971    fn keep_images(
972        &self,
973        gateway: &Gateway,
974        person_id: &str,
975        images: &[images::AppImage],
976    ) -> Result<Vec<images::KeptImage>, (&'static str, String)> {
977        if images.is_empty() {
978            return Ok(Vec::new());
979        }
980        let limits = &self.config().limits;
981        if !limits.images.allows(images.len()) {
982            return Err((
983                "bad_request",
984                format!("A message carries at most {} images.", limits.images),
985            ));
986        }
987        let store = gateway
988            .images
989            .clone()
990            .ok_or(("unavailable", "This gateway keeps no images.".to_owned()))?;
991        images
992            .iter()
993            .map(|image| {
994                let bytes = images::check(image, limits.image_bytes)
995                    .map_err(|reason| ("bad_request", format!("Not sent: {reason}.")))?;
996                store
997                    .put(person_id, &image.media_type, &bytes)
998                    .map_err(|_| ("unavailable", "The image could not be kept.".to_owned()))
999            })
1000            .collect()
1001    }
1002
1003    /// Queues `message` for a Station, after any notes for Moneypenny the app left since her
1004    /// last message; `shown` is the person's entry and its images, when the person wrote it.
1005    async fn queue(
1006        &self,
1007        gateway: &Gateway,
1008        conversation_id: &str,
1009        person_id: &str,
1010        message: &str,
1011        shown: Option<(&str, &[images::KeptImage])>,
1012    ) -> Result<(), (&'static str, String)> {
1013        let now = now();
1014        // The workspace is the person's, as their own sign-in names them.
1015        let (bearer, is_own_agent) = self
1016            .desk()
1017            .store
1018            .owned(conversation_id, person_id)
1019            .map(|conversation| {
1020                (
1021                    conversation.bearer.clone(),
1022                    !matches!(conversation.runner, store::Runner::Pool),
1023                )
1024            })
1025            .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
1026        let person = resolve_signed_in(gateway, &bearer).await.map_err(|_| {
1027            (
1028                "unauthorized",
1029                "Sign in again to talk to Moneypenny.".to_owned(),
1030            )
1031        })?;
1032        if is_own_agent {
1033            let ast = gateway
1034                .assistant()
1035                .ok_or(("unavailable", "Moneypenny is not available.".to_owned()))?;
1036            return own_agent::send_prompt(&ast, gateway, conversation_id, &person, message, shown)
1037                .await;
1038        }
1039        let settings = assistant_settings(gateway).await.map_err(|reason| {
1040            (
1041                "unavailable",
1042                format!("Moneypenny cannot keep a workspace for you: {reason}"),
1043            )
1044        })?;
1045        let workspace = workspace_for(&settings, &person, self.config().gateway.author_chars)
1046            .map_err(|reason| {
1047                (
1048                    "unavailable",
1049                    format!("Moneypenny cannot keep a workspace for you: {reason}"),
1050                )
1051            })?;
1052        // Read again for every message, so a narrowed table reaches her next turn: her reach,
1053        // and her skills, the catalog's less what the person's group and person tables leave out.
1054        let reach = settings.reach_for(&person.id, &person.groups);
1055        let skills = settings.skills_for(&person.id, &person.groups);
1056        // A skill the person ran with `/name` is handed to her harness as an instruction to
1057        // run it; the conversation shows what the person typed.
1058        let invoked = if commands::handler_runs_skills(gateway, &self.config().agent_id).await {
1059            commands::invocation(message, &skills)
1060        } else {
1061            None
1062        };
1063        // Read again for every message, so a permission removed reaches her next turn.
1064        let cables = cables::grants(gateway, &person, self.config().limits.cable_grants).await;
1065        let (remembered, marks) = knowledge::starting_reports(gateway, &person).await;
1066        {
1067            let mut desk = self.desk();
1068            let conversation = desk
1069                .store
1070                .owned(conversation_id, person_id)
1071                .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
1072            if conversation.busy {
1073                return Err((
1074                    "busy",
1075                    "Moneypenny is still answering the last message.".to_owned(),
1076                ));
1077            }
1078            // At most `live_per_person` of the person's conversations hold a harness or wait
1079            // for an answer: the least recently used idle harness makes room.
1080            let mut others: Vec<(f64, String, bool)> = desk
1081                .store
1082                .conversations
1083                .values()
1084                .filter(|other| other.person_id == person_id && other.id != conversation_id)
1085                .filter(|other| other.busy || other.live)
1086                .map(|other| (other.updated_at, other.id.clone(), other.busy))
1087                .collect();
1088            let over =
1089                (others.len() + 1).saturating_sub(self.config().gateway.live_per_person.or_max());
1090            if over > 0 {
1091                others.retain(|(_, _, busy)| !busy);
1092                if others.len() < over {
1093                    return Err((
1094                        "busy_elsewhere",
1095                        "Moneypenny is answering in your other conversations; wait for one \
1096                         to finish."
1097                            .to_owned(),
1098                    ));
1099                }
1100                others.sort_by(|a, b| a.0.total_cmp(&b.0));
1101                for (_, other, _) in others.into_iter().take(over) {
1102                    desk.close_harness(&other, &self.config().agent_id);
1103                }
1104            }
1105            let conversation = desk
1106                .store
1107                .owned(conversation_id, person_id)
1108                .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
1109            let marks_kept = gateway
1110                .registry
1111                .as_ref()
1112                .map_or(Limit::UNBOUNDED, |registry| {
1113                    registry.limits().runs.exposures
1114                });
1115            conversation.note_memory_marks(marks, marks_kept);
1116            let mut context = guide::context();
1117            let mut recap = conversation.seed_recap.clone();
1118            if let Some(turn_recap) = self::recap(conversation, &self.config()) {
1119                recap = Some(match recap {
1120                    Some(seed) => format!("{seed}\n\n{turn_recap}"),
1121                    None => turn_recap,
1122                });
1123            }
1124            // What is left of the job's bound takes her memory's summaries; she searches for more.
1125            let used = context.iter().map(String::len).sum::<usize>()
1126                + recap.as_ref().map_or(0, String::len);
1127            let room = match self.config().limits.context_bytes.get() {
1128                Some(bound) => bound
1129                    .saturating_sub(u64::try_from(used).unwrap_or(u64::MAX))
1130                    .min(
1131                        self.config()
1132                            .gateway
1133                            .memory_context_bytes
1134                            .get()
1135                            .unwrap_or(u64::MAX),
1136                    ),
1137                None => self
1138                    .config()
1139                    .gateway
1140                    .memory_context_bytes
1141                    .get()
1142                    .unwrap_or(u64::MAX),
1143            };
1144            context.extend(knowledge::starting_summaries(
1145                &remembered,
1146                Limit::at(room),
1147                self.config().gateway.result_chars,
1148            ));
1149            let mut parts = std::mem::take(&mut conversation.notes);
1150            parts.push(invoked.unwrap_or_else(|| message.to_owned()));
1151            let job = AssistantJob {
1152                job_id: Uuid::new_v4().to_string(),
1153                conversation_id: conversation_id.to_owned(),
1154                agent_id: self.config().agent_id.clone(),
1155                message: cut(
1156                    &parts.join("\n\n"),
1157                    self.config().limits.message_bytes.or_max(),
1158                ),
1159                context,
1160                recap,
1161                // Set when the job is placed: the token is bound to its Station.
1162                mcp_token: String::new(),
1163                token_expires_at: 0.0,
1164                run_id: conversation.run_id.clone(),
1165                route: conversation.route.clone(),
1166                close: false,
1167                interrupt: false,
1168                person_id: Some(person_id.to_owned()),
1169                workspace,
1170                commit: None,
1171                cables,
1172                cable_confirm: None,
1173                cable_discard: None,
1174                reach,
1175                skills,
1176                // The person's directory groups, so the Station applies its per-group narrowing.
1177                groups: Some(person.groups.clone()),
1178                images: shown
1179                    .map(|(_, images)| images)
1180                    .unwrap_or_default()
1181                    .iter()
1182                    .map(|image| ai6::AssistantImage {
1183                        sha256: image.sha256.clone(),
1184                        media_type: image.media_type.clone(),
1185                        bytes: image.bytes,
1186                    })
1187                    .collect(),
1188            };
1189            // A new turn: proposals made from here rest on what she reads from here.
1190            conversation.turn_reads.clear();
1191            if let Some((text, kept)) = shown {
1192                conversation.push(
1193                    Entry {
1194                        role: Role::Person,
1195                        text: text.to_owned(),
1196                        at: now,
1197                        data: (!kept.is_empty()).then(|| images::entry(kept)),
1198                    },
1199                    self.config().bounds(),
1200                );
1201            }
1202            conversation.answered = false;
1203            conversation.set_busy(true);
1204            conversation.pending = Some(Pending {
1205                job,
1206                station: None,
1207                taken_at: None,
1208                queued_at: now,
1209                refused_by: Vec::new(),
1210                reason: None,
1211            });
1212        }
1213        self.ready.notify_waiters();
1214        self.place(gateway, conversation_id).await;
1215        Ok(())
1216    }
1217
1218    /// Lets the link token of `conversation_id` run another `[assistant.own_agent] token_ttl`
1219    /// from now: the person has sent a message.
1220    pub(crate) fn renew_link_token(&self, conversation_id: &str) {
1221        let ttl = self.config().own_agent.token_ttl.0.as_secs_f64();
1222        let mut desk = self.desk();
1223        let Some((token, expires_at)) = desk
1224            .store
1225            .conversations
1226            .get_mut(conversation_id)
1227            .and_then(|conversation| conversation.token.as_mut())
1228            .filter(|(_, station, _)| station.starts_with("link:"))
1229            .map(|(token, _, expires_at)| {
1230                *expires_at = now() + ttl;
1231                (token.clone(), *expires_at)
1232            })
1233        else {
1234            return;
1235        };
1236        if let Some(grant) = desk.tokens.get_mut(&digest(&token)) {
1237            grant.expires_at = expires_at;
1238        }
1239    }
1240
1241    /// Mints an MCP token bound to `conversation_id` and `station`: always a new one, so what an
1242    /// agent held before, through a connection that has since ended, opens nothing.
1243    pub(crate) fn issue_token(
1244        &self,
1245        conversation_id: &str,
1246        station: &str,
1247        config: &AssistantConfig,
1248    ) -> Option<(String, f64)> {
1249        let mut desk = self.desk();
1250        desk.store.conversations.get_mut(conversation_id)?.token = None;
1251        Self::issue_token_in_desk(&mut desk, config, conversation_id, station)
1252    }
1253
1254    fn issue_token_in_desk(
1255        desk: &mut Desk,
1256        config: &AssistantConfig,
1257        conversation_id: &str,
1258        station: &str,
1259    ) -> Option<(String, f64)> {
1260        let now = now();
1261        let conversation = desk.store.conversations.get_mut(conversation_id)?;
1262        let reuse = conversation
1263            .token
1264            .clone()
1265            .filter(|(_, held_by, expires_at)| {
1266                *held_by == station
1267                    && *expires_at > now + config.gateway.token_reuse_margin.0.as_secs_f64()
1268            });
1269        // A person's own agent holds its token for `[assistant.own_agent] token_ttl`, and each
1270        // of the person's messages renews it.
1271        let ttl = if station.starts_with("link:") {
1272            config.own_agent.token_ttl.0
1273        } else {
1274            config.gateway.token_ttl.0
1275        };
1276        let (token, expires_at) = match reuse {
1277            Some((token, _, expires_at)) => (token, expires_at),
1278            None => (
1279                format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()),
1280                now + ttl.as_secs_f64(),
1281            ),
1282        };
1283        conversation.token = Some((token.clone(), station.to_owned(), expires_at));
1284        let person_id = conversation.person_id.clone();
1285        let deadline = config.gateway.answer_deadline.0.as_secs_f64();
1286        let Desk { store, tokens, .. } = desk;
1287        tokens.retain(|key, grant| {
1288            let current = grant.expires_at > now
1289                || store
1290                    .conversations
1291                    .get(&grant.conversation_id)
1292                    .is_some_and(|held| held.outlasts_its_token(key, now, deadline));
1293            // The one link token a conversation holds is the newest.
1294            let kept_station = if station.starts_with("link:") {
1295                grant.station != station
1296            } else {
1297                grant.station == station
1298            };
1299            // A page token is kept: it is not the job path's.
1300            current
1301                && (is_page_grant(grant)
1302                    || grant.conversation_id != conversation_id
1303                    || kept_station)
1304        });
1305        desk.tokens.insert(
1306            digest(&token),
1307            Grant {
1308                conversation_id: conversation_id.to_owned(),
1309                person_id,
1310                station: station.to_owned(),
1311                expires_at,
1312            },
1313        );
1314        Some((token, expires_at))
1315    }
1316
1317    /// Queues the conversation's pending job for the Station that runs its harness, else the
1318    /// Headquarters Station, else any healthy Station that has not refused it.
1319    async fn place(&self, gateway: &Gateway, conversation_id: &str) {
1320        let (preferred, refused) = {
1321            let mut desk = self.desk();
1322            let Some(conversation) = desk.store.conversations.get_mut(conversation_id) else {
1323                return;
1324            };
1325            let Some(pending) = &conversation.pending else {
1326                return;
1327            };
1328            (conversation.station.clone(), pending.refused_by.clone())
1329        };
1330        let healthy = healthy_stations(gateway).await;
1331        let chosen = preferred
1332            .filter(|station| healthy.contains(station))
1333            .into_iter()
1334            .chain(healthy)
1335            .find(|station| !refused.contains(station));
1336        let mut desk = self.desk();
1337        let max_entries = self.config().bounds();
1338        let Some(conversation) = desk.store.conversations.get_mut(conversation_id) else {
1339            return;
1340        };
1341        let Some(pending) = conversation.pending.as_mut() else {
1342            return;
1343        };
1344        match chosen {
1345            Some(station) => {
1346                let Some((token, expires_at)) =
1347                    Self::issue_token_in_desk(&mut desk, &self.config(), conversation_id, &station)
1348                else {
1349                    return;
1350                };
1351                let Some(conversation) = desk.store.conversations.get_mut(conversation_id) else {
1352                    return;
1353                };
1354                let Some(pending) = conversation.pending.as_mut() else {
1355                    return;
1356                };
1357                pending.job.mcp_token = token;
1358                pending.job.token_expires_at = expires_at;
1359                pending.station = Some(station);
1360                pending.taken_at = None;
1361                pending.queued_at = now();
1362                drop(desk);
1363                self.ready.notify_waiters();
1364            }
1365            None => {
1366                let reason = pending
1367                    .reason
1368                    .clone()
1369                    .unwrap_or_else(|| "no Station is checking in".to_owned());
1370                conversation.pending = None;
1371                conversation.push(
1372                    Entry {
1373                        role: Role::Error,
1374                        text: format!("No Station can run Moneypenny now: {reason}."),
1375                        at: now(),
1376                        data: None,
1377                    },
1378                    max_entries,
1379                );
1380                conversation.set_busy(false);
1381            }
1382        }
1383    }
1384
1385    /// Gives up on jobs their Station did not take up in time and offers them elsewhere. Run
1386    /// by every Station poll and by every open conversation socket, so a job is moved on
1387    /// even when no Station polls at all.
1388    async fn sweep(&self, gateway: &Gateway) {
1389        let timeout = self.config().gateway.answer_timeout.0.as_secs_f64();
1390        let now = now();
1391        let mut again = Vec::new();
1392        {
1393            let mut desk = self.desk();
1394            for conversation in desk.store.conversations.values_mut() {
1395                let Some(pending) = conversation.pending.as_mut() else {
1396                    continue;
1397                };
1398                let since = pending.taken_at.unwrap_or(pending.queued_at);
1399                if let Some(late) = pending.station.clone()
1400                    && now - since > timeout
1401                {
1402                    pending.refused_by.push(late);
1403                    pending.reason = Some("the Station did not answer".to_owned());
1404                    pending.station = None;
1405                    again.push(conversation.id.clone());
1406                }
1407            }
1408            // An accepted message whose Station went quiet is given up, so the conversation
1409            // can take another message and be evicted like any idle one.
1410            let deadline = self.config().gateway.answer_deadline.0.as_secs_f64();
1411            let bounds = self.config().bounds();
1412            for conversation in desk.store.conversations.values_mut() {
1413                if conversation.busy
1414                    && conversation.pending.is_none()
1415                    && now - conversation.heard_at > deadline
1416                {
1417                    conversation.live = false;
1418                    conversation.push(
1419                        Entry {
1420                            role: Role::Error,
1421                            text: "No word from Moneypenny's Station for too long; her answer \
1422                                   was given up. Ask again."
1423                                .to_owned(),
1424                            at: now,
1425                            data: None,
1426                        },
1427                        bounds,
1428                    );
1429                    conversation.set_busy(false);
1430                }
1431            }
1432        }
1433        for conversation in again {
1434            self.place(gateway, &conversation).await;
1435        }
1436        self.expire_confirms(gateway).await;
1437        self.discard_unclaimed_drafts(gateway);
1438    }
1439
1440    /// Throws away the drafts of new and replaced pages that no proposal waiting for the person
1441    /// or being confirmed names any more: it was cancelled, expired, dropped for room or went
1442    /// with its conversation.
1443    fn discard_unclaimed_drafts(&self, gateway: &Gateway) {
1444        let Some(store) = gateway.pages.as_ref() else {
1445            return;
1446        };
1447        let ttl = self.config().gateway.proposal_ttl.0.as_secs_f64();
1448        let now = now();
1449        let claimed: HashSet<(String, String)> = self
1450            .desk()
1451            .store
1452            .conversations
1453            .values()
1454            .flat_map(|conversation| conversation.proposals.iter())
1455            .filter(|proposal| {
1456                proposal.tool == page_tools::PUBLISH
1457                    && (proposal.status == "confirming"
1458                        || (proposal.status == "pending" && now - proposal.created_at <= ttl))
1459            })
1460            .filter_map(|proposal| {
1461                let published: Published = proposal.draft.call.body.clone()?.decode().ok()?;
1462                Some((proposal.draft.call.path.clone(), published.digest))
1463            })
1464            .collect();
1465        store.retain_drafts(|id, digest| {
1466            claimed.contains(&(page_tools::replacement_path(id), digest.to_owned()))
1467        });
1468    }
1469
1470    /// The next job for `station`: a close or interrupt first, then the oldest message.
1471    async fn take(&self, gateway: &Gateway, station: &str) -> Option<AssistantJob> {
1472        self.sweep(gateway).await;
1473        let now = now();
1474        let mut desk = self.desk();
1475        if let Some(index) = desk
1476            .controls
1477            .iter()
1478            .position(|(held_by, _)| held_by == station)
1479        {
1480            return Some(desk.controls.remove(index).1);
1481        }
1482        desk.store
1483            .conversations
1484            .values_mut()
1485            .filter_map(|conversation| conversation.pending.as_mut())
1486            .filter(|pending| {
1487                pending.station.as_deref() == Some(station) && pending.taken_at.is_none()
1488            })
1489            .min_by(|a, b| a.queued_at.total_cmp(&b.queued_at))
1490            .map(|pending| {
1491                pending.taken_at = Some(now);
1492                pending.job.clone()
1493            })
1494    }
1495
1496    /// Applies a Station's report; `Err` with the HTTP status it earns.
1497    async fn report(&self, gateway: &Gateway, report: AssistantReport) -> Result<(), StatusCode> {
1498        if !self.config().limits.events.allows(report.events.len())
1499            || !ai6::directorates::section_00::assistant::valid_identity(&report.station_id)
1500        {
1501            return Err(StatusCode::BAD_REQUEST);
1502        }
1503        let max_entries = self.config().bounds();
1504        let mut refused = false;
1505        let mut based = false;
1506        let mut after = cables::After::default();
1507        'locked: {
1508            let mut desk = self.desk();
1509            if let Some(job_id) = &report.job_id
1510                && let Some((given_to, _)) = desk.controlling.get(job_id)
1511            {
1512                // Only the Station the job was given to answers it.
1513                if *given_to != report.station_id {
1514                    return Err(StatusCode::FORBIDDEN);
1515                }
1516                let Some((_, control)) = desk.controlling.remove(job_id) else {
1517                    break 'locked;
1518                };
1519                desk.cable_deadlines.remove(job_id);
1520                // The answer to a close or an interrupt: the harness reports `closed` when it
1521                // is gone and `interrupted` when its turn stops. An interrupt the Station could
1522                // not make is shown, since the answer goes on.
1523                let refused = report
1524                    .events
1525                    .first()
1526                    .filter(|event| event.kind == EVENT_REJECTED);
1527                if control == Control::Interrupt
1528                    && let Some(refused) = refused
1529                    && let Some(conversation) =
1530                        desk.store.conversations.get_mut(&report.conversation_id)
1531                {
1532                    conversation.push(
1533                        Entry {
1534                            role: Role::Error,
1535                            text: format!(
1536                                "Moneypenny could not be stopped: {}",
1537                                or_unknown(refused.text.as_deref().unwrap_or_default())
1538                            ),
1539                            at: now(),
1540                            data: None,
1541                        },
1542                        max_entries,
1543                    );
1544                }
1545                let conversation = desk.store.conversations.get_mut(&report.conversation_id);
1546                match (control, conversation) {
1547                    (Control::Commit { proposal, what }, Some(conversation)) => {
1548                        committed(
1549                            conversation,
1550                            proposal.as_deref(),
1551                            &what,
1552                            &report,
1553                            max_entries,
1554                        );
1555                    }
1556                    (Control::CableConfirm(proposal), Some(conversation)) => {
1557                        let reason = refused.map(|event| event.text.clone().unwrap_or_default());
1558                        cables::answered(conversation, &proposal, reason, &mut after);
1559                    }
1560                    _ => {}
1561                }
1562                break 'locked;
1563            }
1564            let conversation = desk
1565                .store
1566                .conversations
1567                .get_mut(&report.conversation_id)
1568                .ok_or(StatusCode::NOT_FOUND)?;
1569            // A harness cut off by a Stop is heard only for the Cables it sent, so each is
1570            // audited; nothing else it says reaches the conversation.
1571            if report.job_id.is_none()
1572                && conversation.cut_off.as_deref() == Some(report.station_id.as_str())
1573            {
1574                conversation.hear_run(&report);
1575                for event in report
1576                    .events
1577                    .iter()
1578                    .filter(|event| event.kind == EVENT_CABLE_SENT)
1579                {
1580                    cables::apply(
1581                        conversation,
1582                        event,
1583                        &report.station_id,
1584                        max_entries,
1585                        &self.config(),
1586                        &mut after,
1587                    );
1588                }
1589                conversation.reporting = None;
1590                break 'locked;
1591            }
1592            conversation.heard_at = now();
1593            if let Some(job_id) = &report.job_id {
1594                let pending = conversation
1595                    .pending
1596                    .as_mut()
1597                    .filter(|pending| {
1598                        pending.job.job_id == *job_id
1599                            && pending.station.as_deref() == Some(report.station_id.as_str())
1600                    })
1601                    .ok_or(StatusCode::CONFLICT)?;
1602                let answer = report.events.first().ok_or(StatusCode::BAD_REQUEST)?;
1603                match answer.kind.as_str() {
1604                    EVENT_ACCEPTED => {
1605                        conversation.pending = None;
1606                        conversation.live = true;
1607                        if conversation.cut_off.as_deref() == Some(report.station_id.as_str()) {
1608                            conversation.cut_off = None;
1609                        }
1610                        if conversation.station.as_deref() != Some(report.station_id.as_str()) {
1611                            conversation.station = Some(report.station_id.clone());
1612                        }
1613                    }
1614                    EVENT_REJECTED => {
1615                        pending.refused_by.push(report.station_id.clone());
1616                        pending.reason = answer.text.clone();
1617                        pending.station = None;
1618                        refused = true;
1619                    }
1620                    _ => return Err(StatusCode::BAD_REQUEST),
1621                }
1622            } else if conversation.station.as_deref() != Some(report.station_id.as_str()) {
1623                return Err(StatusCode::FORBIDDEN);
1624            }
1625            conversation.hear_run(&report);
1626            if let Some(run_id) = report
1627                .run_id
1628                .filter(|id| ai6::directorates::section_00::assistant::valid_identity(id))
1629            {
1630                conversation.run_id = Some(run_id);
1631                conversation.route = report.route.clone();
1632            }
1633            for event in report
1634                .events
1635                .iter()
1636                .filter(|event| report.job_id.is_none() || event.kind != EVENT_ACCEPTED)
1637            {
1638                if !event.shared.is_empty() {
1639                    conversation
1640                        .keep_shared_bases(&event.shared, self.config().limits.shared_bases);
1641                    based = true;
1642                }
1643                match event.kind.as_str() {
1644                    EVENT_CABLE_PROPOSAL | EVENT_CABLE_SENT => cables::apply(
1645                        conversation,
1646                        event,
1647                        &report.station_id,
1648                        max_entries,
1649                        &self.config(),
1650                        &mut after,
1651                    ),
1652                    EVENT_COMMANDS => conversation.commands = announced(event, &self.config()),
1653                    _ => apply_event(conversation, event, max_entries),
1654                }
1655            }
1656            conversation.reporting = None;
1657            if let Some(conversation) = desk.store.conversations.get(&report.conversation_id) {
1658                let person = conversation.person_id.clone();
1659                desk.store
1660                    .trim_person(&person, self.config().gateway.person_bytes.or_max());
1661            }
1662        }
1663        self.follow_up(gateway, after).await;
1664        if based {
1665            self.based.notify_waiters();
1666        }
1667        if refused {
1668            self.place(gateway, &report.conversation_id).await;
1669        }
1670        Ok(())
1671    }
1672
1673    /// The conversation `token` serves, its person and the person's access token, while the
1674    /// token is accepted.
1675    pub(crate) fn grant(&self, token: &str) -> Option<Granted> {
1676        let mut desk = self.desk();
1677        let now = now();
1678        let key = digest(token);
1679        let grant = desk.tokens.get(&key)?;
1680        let over = grant.expires_at <= now;
1681        let (conversation_id, person_id, station) = (
1682            grant.conversation_id.clone(),
1683            grant.person_id.clone(),
1684            grant.station.clone(),
1685        );
1686        let conversation = desk.store.owned(&conversation_id, &person_id)?;
1687        let deadline = self.config().gateway.answer_deadline.0.as_secs_f64();
1688        if over && !conversation.outlasts_its_token(&key, now, deadline) {
1689            return None;
1690        }
1691        Some(Granted {
1692            conversation_id,
1693            person_id,
1694            station,
1695            bearer: conversation.bearer.clone(),
1696        })
1697    }
1698
1699    /// Runs Moneypenny's write tool `tool`: checks the input and that the person may do it,
1700    /// then records a proposal for the person to confirm. Nothing else happens.
1701    pub(crate) async fn propose(
1702        &self,
1703        gateway: &Gateway,
1704        granted: &Granted,
1705        tool: &actions::WriteTool,
1706        call: &coqui_acp_api::mcp::ToolCall,
1707    ) -> tools::Outcome {
1708        let id = format!("proposal-{}", Uuid::new_v4().simple());
1709        let mut planned = match tool.plan(call, &id) {
1710            Ok(planned) => planned,
1711            Err(outcome) => return outcome,
1712        };
1713        // An edit of her own settings is shown against the settings in force.
1714        let current = if planned.edits_assistant() {
1715            assistant_settings(gateway).await.ok()
1716        } else {
1717            None
1718        };
1719        if let Err(outcome) = planned.compare_settings(current.as_ref()) {
1720            return outcome;
1721        }
1722        let actions::Planned {
1723            mut draft, preview, ..
1724        } = planned;
1725        let Ok(person) = resolve_signed_in(gateway, &granted.bearer).await else {
1726            return tools::Outcome::error("The person's sign-in has ended; nothing was proposed.");
1727        };
1728        // Where a change needs the person's rights may depend on a record, read as the person.
1729        if let Err(outcome) = actions::resolve(gateway, &granted.bearer, &preview, &mut draft).await
1730        {
1731            return outcome;
1732        }
1733        // A change the route lets the person make of their own, such as revoking their own
1734        // key, has no action to check here: the route decides when it is confirmed.
1735        if draft.action != actions::ROUTE_DECIDES
1736            && authorize_resource_action(gateway, person, draft.scope.resource(), draft.action)
1737                .await
1738                .is_err()
1739        {
1740            return tools::Outcome::error(format!(
1741                "Refused: the person may not {} on {}, so nothing was proposed. Tell them so; \
1742                 do not try another way.",
1743                draft.action,
1744                draft.scope.resource()
1745            ));
1746        }
1747        // What confirming would do is read now, as the person, and shown with the proposal.
1748        let guard = match actions::prepare(gateway, &granted.bearer, &preview, &mut draft).await {
1749            Ok(guard) => guard,
1750            Err(outcome) => return outcome,
1751        };
1752        let summary = draft.summary.clone();
1753        let proposal = actions::Proposal {
1754            id: id.clone(),
1755            tool: tool.name,
1756            draft,
1757            status: "pending",
1758            created_at: now(),
1759            run: digest(&granted.bearer),
1760            result: None,
1761            receipt: None,
1762            work: None,
1763            cable: None,
1764            own_cable: None,
1765            evidence: actions::Evidence::default(),
1766            guard,
1767        };
1768        let max_entries = self.config().bounds();
1769        {
1770            let mut desk = self.desk();
1771            let Some(conversation) = desk
1772                .store
1773                .owned(&granted.conversation_id, &granted.person_id)
1774            else {
1775                return tools::Outcome::error("The conversation is gone.");
1776            };
1777            if !record_proposal(conversation, proposal, max_entries, &self.config().gateway) {
1778                return tools::Outcome::error(proposals_full(&self.config().gateway));
1779            }
1780        }
1781        tools::Outcome {
1782            text: format!(
1783                "Proposed as {id}: {summary}. Nothing has changed. The person confirms or \
1784                 cancels it in the app; you will be told which."
1785            ),
1786            is_error: false,
1787        }
1788    }
1789
1790    /// Runs a pending proposal the person confirmed on a socket signed in with `token`, the
1791    /// run it was proposed in, and tells Moneypenny how it went.
1792    async fn confirm(
1793        &self,
1794        gateway: &Gateway,
1795        conversation_id: &str,
1796        person: &ai6::Person,
1797        token: &str,
1798        proposal_id: &str,
1799    ) -> Result<(), (&'static str, String)> {
1800        let draft = {
1801            let mut desk = self.desk();
1802            let conversation = desk
1803                .store
1804                .owned(conversation_id, &person.id)
1805                .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
1806            expire_proposals(conversation, &self.config().gateway);
1807            let proposal = conversation
1808                .proposals
1809                .iter_mut()
1810                .find(|proposal| proposal.id == proposal_id)
1811                .ok_or(("not_found", "There is no such proposal.".to_owned()))?;
1812            if proposal.status != "pending" {
1813                return Err(("conflict", format!("The proposal is {}.", proposal.status)));
1814            }
1815            if proposal.run != digest(token) {
1816                return Err((
1817                    "forbidden",
1818                    "Only the signed-in run it was proposed in can confirm it.".to_owned(),
1819                ));
1820            }
1821            proposal.status = "confirming";
1822            let shown = proposal.clone();
1823            conversation.show_proposal(&shown);
1824            shown
1825        };
1826        if let Some(commit) = draft.work.clone() {
1827            self.confirm_commit(gateway, conversation_id, person, &draft, commit)
1828                .await;
1829            return Ok(());
1830        }
1831        // A held Cable is sent by the Station that holds it, which reports how it went.
1832        if let Some(hold) = draft.cable.clone() {
1833            self.confirm_cable(gateway, conversation_id, person, &draft, hold)
1834                .await;
1835            return Ok(());
1836        }
1837        // A person's own agent's Cable is sent by the gateway's relay, once.
1838        if let Some(cable) = draft.own_cable.clone() {
1839            self.confirm_own_cable(gateway, conversation_id, person, &draft, cable)
1840                .await;
1841            return Ok(());
1842        }
1843        let outcome = self
1844            .execute(gateway, conversation_id, person, token, &draft)
1845            .await;
1846        let (status, result) = match &outcome {
1847            Ok(executed) if executed.held => ("held", executed.text.clone()),
1848            Ok(executed) => ("done", executed.text.clone()),
1849            Err(text) => ("failed", text.clone()),
1850        };
1851        let note = format!(
1852            "[App: the person confirmed {}: {status}. {}]",
1853            draft.id, result
1854        );
1855        let idle = {
1856            let mut desk = self.desk();
1857            let Some(conversation) = desk.store.owned(conversation_id, &person.id) else {
1858                return Ok(());
1859            };
1860            if let Some(proposal) = conversation
1861                .proposals
1862                .iter_mut()
1863                .find(|proposal| proposal.id == proposal_id)
1864            {
1865                proposal.status = status;
1866                proposal.result = Some(result);
1867                if let Ok(executed) = &outcome {
1868                    proposal.receipt = executed.receipt.clone();
1869                }
1870                let shown = proposal.clone();
1871                conversation.show_proposal(&shown);
1872            }
1873            // The app, and only the app, is told the new password, once; it is in no entry.
1874            if let Ok(Executed {
1875                secret: Some(secret),
1876                ..
1877            }) = &outcome
1878            {
1879                let _ = conversation.events.send(Event::Reveal {
1880                    proposal: proposal_id.to_owned(),
1881                    secret: secret.clone(),
1882                });
1883            }
1884            if conversation.busy {
1885                conversation.notes.push(note.clone());
1886                false
1887            } else {
1888                true
1889            }
1890        };
1891        // The result goes back to Moneypenny: now when she is idle, else with the next message.
1892        if idle {
1893            let _ = self
1894                .queue(gateway, conversation_id, &person.id, &note, None)
1895                .await;
1896        }
1897        Ok(())
1898    }
1899
1900    /// Audits a confirmed commit proposal, then asks a Station to make the commit; the
1901    /// Station's answer settles the proposal ([`Self::report`]). One that cannot be audited
1902    /// or sent fails here.
1903    async fn confirm_commit(
1904        &self,
1905        gateway: &Gateway,
1906        conversation_id: &str,
1907        person: &ai6::Person,
1908        proposal: &actions::Proposal,
1909        commit: AssistantCommit,
1910    ) {
1911        let target = confirmed_target(conversation_id, proposal);
1912        let sent = match audit(
1913            gateway,
1914            person,
1915            "moneypenny.confirmed",
1916            String::new(),
1917            Some(ASSISTANT_AUDIT_RESOURCE.to_owned()),
1918            &target,
1919        )
1920        .await
1921        {
1922            Ok(()) => self
1923                .commit_station(gateway, conversation_id)
1924                .await
1925                .ok_or_else(|| "no Station is checking in".to_owned()),
1926            Err(reason) => Err(reason),
1927        };
1928        let mut desk = self.desk();
1929        match sent {
1930            Ok(station) => {
1931                // Checked against the person's groups as they are now.
1932                let groups = Some(person.groups.clone());
1933                desk.queue_commit(
1934                    conversation_id,
1935                    &self.config().agent_id,
1936                    station,
1937                    (commit, groups),
1938                    Control::Commit {
1939                        proposal: Some(proposal.id.clone()),
1940                        what: proposal.draft.summary.clone(),
1941                    },
1942                );
1943                drop(desk);
1944                self.ready.notify_waiters();
1945            }
1946            Err(reason) => {
1947                if let Some(conversation) = desk.store.owned(conversation_id, &person.id) {
1948                    settle(conversation, &proposal.id, false, &reason);
1949                }
1950            }
1951        }
1952    }
1953
1954    /// The Station a commit of `conversation_id` goes to: the one running its harness when
1955    /// it is healthy, else the first healthy one.
1956    async fn commit_station(&self, gateway: &Gateway, conversation_id: &str) -> Option<String> {
1957        let preferred = self
1958            .desk()
1959            .store
1960            .conversations
1961            .get(conversation_id)
1962            .and_then(|conversation| conversation.station.clone());
1963        let healthy = healthy_stations(gateway).await;
1964        preferred
1965            .filter(|station| healthy.contains(station))
1966            .or_else(|| healthy.into_iter().next())
1967    }
1968
1969    /// Records a read tool call of the turn, which a proposal then lists.
1970    pub(crate) fn note_read(
1971        &self,
1972        conversation_id: &str,
1973        tool: &str,
1974        ids: std::collections::BTreeMap<String, String>,
1975    ) {
1976        if let Some(conversation) = self.desk().store.conversations.get_mut(conversation_id) {
1977            conversation.note_read(tool, ids, &self.config().gateway);
1978        }
1979    }
1980
1981    /// Whether `station` runs the conversation: `404` for one this gateway does not hold, `403`
1982    /// for one another Station runs.
1983    fn run_by(&self, station: &str, conversation_id: &str) -> Result<(), ApiError> {
1984        let desk = self.desk();
1985        let conversation = desk
1986            .store
1987            .conversations
1988            .get(conversation_id)
1989            .ok_or_else(ApiError::not_found)?;
1990        if conversation.station.as_deref() != Some(station) {
1991            return Err(ApiError::forbidden());
1992        }
1993        Ok(())
1994    }
1995
1996    /// Runs [`actions::SHARED_CHANGE`]: a change to one file of a shared repository of a
1997    /// group the person is in, proposed, or sent at once (audited `moneypenny.shared.write`)
1998    /// when the deployment lets that group's changes through. The change carries what the
1999    /// file held when she made the call ([`Self::shared_base`]), so its commit is refused when
2000    /// the repository's `main` has changed the file since; a call without one is refused.
2001    pub(crate) async fn propose_shared(
2002        &self,
2003        gateway: &Gateway,
2004        granted: &Granted,
2005        call: &coqui_acp_api::mcp::ToolCall,
2006    ) -> tools::Outcome {
2007        let change =
2008            match actions::shared_change(call, &self.config().limits, &self.config().gateway) {
2009                Ok(change) => change,
2010                Err(outcome) => return outcome,
2011            };
2012        let (group, path, content, message) = (
2013            change.group.as_str(),
2014            change.path.as_str(),
2015            change.content.as_str(),
2016            change.message.as_str(),
2017        );
2018        let Ok(person) = resolve_signed_in(gateway, &granted.bearer).await else {
2019            return tools::Outcome::error("The person's sign-in has ended; nothing was proposed.");
2020        };
2021        let settings = match assistant_settings(gateway).await {
2022            Ok(settings) => settings,
2023            Err(reason) => return tools::Outcome::error(format!("Nothing was proposed: {reason}")),
2024        };
2025        let Some(shared) = settings.shared_named(group, &person.groups) else {
2026            return tools::Outcome::error(format!(
2027                "Refused: the person is not a member of {group:?}, or it shares no repository, \
2028                 so nothing was proposed. Tell them so; do not try another way."
2029            ));
2030        };
2031        let Some(base) = self
2032            .shared_base(&granted.conversation_id, group, path, content)
2033            .await
2034        else {
2035            return tools::Outcome::error(format!(
2036                "Nothing was proposed: the Station running this conversation did not say what \
2037                 {path} held in shared/{group}/ when you called, so a change made to it since \
2038                 could not be caught. Check that shared/{group}/ is in your workspace, then \
2039                 call again."
2040            ));
2041        };
2042        let (author_name, author_email) = author_of(&person, self.config().gateway.author_chars);
2043        let commit = AssistantCommit {
2044            repo: shared.repo().to_owned(),
2045            group: group.to_owned(),
2046            change: AssistantChange::based(
2047                std::collections::BTreeMap::from([(path.to_owned(), Some(content.to_owned()))]),
2048                std::collections::BTreeMap::from([(path.to_owned(), base)]),
2049            ),
2050            message: format!("{message}\n\n{}", trailer(&granted.conversation_id)),
2051            author_name,
2052            author_email,
2053        };
2054        let summary = format!("Write {path} in {group}'s shared repository: {message}");
2055        if shared.write() {
2056            let target = format!("{} {group} {path}", granted.conversation_id);
2057            if let Err(reason) = audit(
2058                gateway,
2059                &person,
2060                "moneypenny.shared.write",
2061                String::new(),
2062                Some(ASSISTANT_AUDIT_RESOURCE.to_owned()),
2063                &target,
2064            )
2065            .await
2066            {
2067                return tools::Outcome::error(format!("Nothing was written: {reason}."));
2068            }
2069            let Some(station) = self.commit_station(gateway, &granted.conversation_id).await else {
2070                return tools::Outcome::error("Nothing was written: no Station is checking in.");
2071            };
2072            let mut desk = self.desk();
2073            desk.queue_commit(
2074                &granted.conversation_id,
2075                &self.config().agent_id,
2076                station,
2077                (commit, Some(person.groups.clone())),
2078                Control::Commit {
2079                    proposal: None,
2080                    what: summary,
2081                },
2082            );
2083            drop(desk);
2084            self.ready.notify_waiters();
2085            return tools::Outcome {
2086                text: format!(
2087                    "Sent to be committed to {group}'s repository at once: the deployment lets \
2088                     {group}'s changes through without a confirmation. You will be told how it \
2089                     went."
2090                ),
2091                is_error: false,
2092            };
2093        }
2094        let proposal = commit_proposal(
2095            actions::SHARED_CHANGE,
2096            digest(&granted.bearer),
2097            format!("{group} shared repository: {path}"),
2098            actions::Scope::Resource(format!("group:{group}")),
2099            "membership",
2100            summary.clone(),
2101            commit,
2102        );
2103        let id = proposal.id.clone();
2104        let bounds = self.config().bounds();
2105        let mut desk = self.desk();
2106        let Some(conversation) = desk
2107            .store
2108            .owned(&granted.conversation_id, &granted.person_id)
2109        else {
2110            return tools::Outcome::error("The conversation is gone.");
2111        };
2112        if !record_proposal(conversation, proposal, bounds, &self.config().gateway) {
2113            return tools::Outcome::error(proposals_full(&self.config().gateway));
2114        }
2115        tools::Outcome {
2116            text: format!(
2117                "Proposed as {id}: {summary}. Nothing has changed. The person confirms or \
2118                 cancels it in the app; you will be told which."
2119            ),
2120            is_error: false,
2121        }
2122    }
2123
2124    /// What the file `path` of `group`'s repository held when the conversation's call that
2125    /// writes `content` to it was made, as its Station reported it ([`ai6::AssistantSharedBase`]):
2126    /// its hex SHA-256, or `None` for no such file. The report and the call reach the gateway
2127    /// separately, so this waits up to `[assistant.gateway] shared_base_wait` for it; `None`
2128    /// when none came.
2129    async fn shared_base(
2130        &self,
2131        conversation_id: &str,
2132        group: &str,
2133        path: &str,
2134        content: &str,
2135    ) -> Option<Option<String>> {
2136        let content = digest(content);
2137        let deadline = tokio::time::Instant::now() + self.config().gateway.shared_base_wait.0;
2138        loop {
2139            let notified = self.based.notified();
2140            tokio::pin!(notified);
2141            notified.as_mut().enable();
2142            let taken = self
2143                .desk()
2144                .store
2145                .conversations
2146                .get_mut(conversation_id)
2147                .and_then(|conversation| conversation.take_shared_base(group, path, &content));
2148            if let Some(taken) = taken {
2149                return Some(taken.base);
2150            }
2151            if tokio::time::timeout_at(deadline, notified).await.is_err() {
2152                return None;
2153            }
2154        }
2155    }
2156
2157    /// Audits, then sends, a confirmed proposal's request as the person; the text is what
2158    /// AI6 answered, wrapped as data, or why it did not run.
2159    async fn execute(
2160        &self,
2161        gateway: &Gateway,
2162        conversation_id: &str,
2163        person: &ai6::Person,
2164        token: &str,
2165        proposal: &actions::Proposal,
2166    ) -> Result<Executed, String> {
2167        // What the person was shown must be what they sign: a request that changed since is
2168        // not acted on, and nothing is audited as confirmed.
2169        if let Some(guard) = &proposal.guard {
2170            actions::recheck(gateway, token, guard).await?;
2171        }
2172        let (operation, resource) = match &proposal.draft.scope {
2173            actions::Scope::Operation(operation) => (operation.clone(), None),
2174            actions::Scope::Resource(resource) => (String::new(), Some(resource.clone())),
2175        };
2176        let target = confirmed_target(conversation_id, proposal);
2177        // Recorded before it runs: a confirmation that cannot be audited is not carried out.
2178        audit(
2179            gateway,
2180            person,
2181            "moneypenny.confirmed",
2182            operation,
2183            resource,
2184            &target,
2185        )
2186        .await?;
2187        match tools::route(gateway, token, &proposal.draft.call).await {
2188            Ok((status, value)) if status.is_success() => {
2189                let mut answer = value.clone().decode::<tools::Fields>().ok();
2190                // A password made for an account goes to the person's app only, never into
2191                // what she reads.
2192                let secret = (proposal.tool == "propose_account_change")
2193                    .then(|| answer.as_mut()?.remove("secret"))
2194                    .flatten()
2195                    .and_then(|secret| tools::text(&secret));
2196                let value = answer.as_ref().map_or(value, |answer| {
2197                    OpaqueJson::capture(answer).expect("members are written as JSON")
2198                });
2199                // A route that answers 200 with `applied: false` held the change: a preview, not a
2200                // change.
2201                let held = answer
2202                    .as_ref()
2203                    .and_then(|answer| answer.get("applied"))
2204                    .and_then(tools::read::<bool>)
2205                    == Some(false);
2206                let shown = format!(
2207                    "AI6 answered {}{}: {}",
2208                    status.as_u16(),
2209                    if held {
2210                        " but applied nothing (held: this was a preview)"
2211                    } else {
2212                        ""
2213                    },
2214                    tools::wrap(proposal.tool, &value, self.config().gateway.result_chars)
2215                );
2216                // The Mission is named by what AI6 answered, never by what she wrote.
2217                let receipt = (proposal.tool == "propose_mission")
2218                    .then(|| {
2219                        let mission = answer.as_ref()?.get("mission_id").and_then(tools::text)?;
2220                        let operation =
2221                            answer.as_ref()?.get("operation_id").and_then(tools::text)?;
2222                        OpaqueJson::capture(MissionPage {
2223                            page: "missions",
2224                            operation_id: &operation,
2225                            mission_id: &mission,
2226                        })
2227                        .ok()
2228                    })
2229                    .flatten();
2230                Ok(Executed {
2231                    text: shown,
2232                    secret,
2233                    receipt,
2234                    held,
2235                })
2236            }
2237            Ok((status, value)) => Err(tools::refusal(
2238                status,
2239                &value,
2240                self.config().gateway.result_chars,
2241            )),
2242            Err(error) => Err(format!("The request failed: {error}")),
2243        }
2244    }
2245
2246    /// Shows a view Moneypenny built, when it is exactly the view schema; otherwise tells her
2247    /// why and shows nothing.
2248    pub(crate) fn show(
2249        &self,
2250        granted: &Granted,
2251        call: &coqui_acp_api::mcp::ToolCall,
2252    ) -> tools::Outcome {
2253        let config = self.config();
2254        let parsed = views::from_call(call, &config.views, config.route_limits());
2255        let view = match parsed {
2256            Ok(view) => view,
2257            Err(reason) => {
2258                // What she sent is echoed in the reason, so it is cut as every result is.
2259                let reason = tools::cut_chars(&reason, self.config().gateway.result_chars);
2260                return tools::Outcome::error(format!(
2261                    "View refused: {reason}. Nothing was shown; fix the view and call show again."
2262                ));
2263            }
2264        };
2265        let id = format!("view-{}", Uuid::new_v4().simple());
2266        let max_entries = self.config().bounds();
2267        let mut desk = self.desk();
2268        let Some(conversation) = desk
2269            .store
2270            .owned(&granted.conversation_id, &granted.person_id)
2271        else {
2272            return tools::Outcome::error("The conversation is gone.");
2273        };
2274        conversation.push(
2275            Entry {
2276                role: Role::View,
2277                text: view.title().unwrap_or_default(),
2278                at: now(),
2279                data: Some(EntryData::View(ai6::wire::assistant_events::ViewEntry {
2280                    id: id.clone(),
2281                    view: match ai6::wire::OpaqueJson::capture(&view) {
2282                        Ok(view) => view,
2283                        Err(error) => {
2284                            return tools::Outcome::error(format!(
2285                                "The view could not be kept: {error}"
2286                            ));
2287                        }
2288                    },
2289                    marks: conversation.memory_marks.clone(),
2290                })),
2291            },
2292            max_entries,
2293        );
2294        desk.store.trim_person(
2295            &granted.person_id,
2296            self.config().gateway.person_bytes.or_max(),
2297        );
2298        tools::Outcome {
2299            text: format!("Shown to the person as {id}."),
2300            is_error: false,
2301        }
2302    }
2303
2304    /// Offers the person an app page when its route and label are valid.
2305    pub(crate) fn navigate(
2306        &self,
2307        granted: &Granted,
2308        call: &coqui_acp_api::mcp::ToolCall,
2309    ) -> tools::Outcome {
2310        let config = self.config();
2311        let (route, label) = match routes::navigation(
2312            call,
2313            config.route_limits(),
2314            config.views.navigate_label_bytes,
2315        ) {
2316            Ok(navigation) => navigation,
2317            Err(reason) => {
2318                return tools::Outcome::error(format!("Navigation refused: {reason}"));
2319            }
2320        };
2321        let id = format!("nav-{}", Uuid::new_v4().simple());
2322        let max_entries = self.config().bounds();
2323        let mut desk = self.desk();
2324        let Some(conversation) = desk
2325            .store
2326            .owned(&granted.conversation_id, &granted.person_id)
2327        else {
2328            return tools::Outcome::error("The conversation is gone.");
2329        };
2330        conversation.push(
2331            Entry {
2332                role: Role::Navigation,
2333                text: label.clone(),
2334                at: now(),
2335                data: Some(EntryData::Navigation(
2336                    ai6::wire::assistant_events::NavigationEntry {
2337                        id: id.clone(),
2338                        route: route.view(),
2339                        label,
2340                        marks: conversation.memory_marks.clone(),
2341                    },
2342                )),
2343            },
2344            max_entries,
2345        );
2346        desk.store.trim_person(
2347            &granted.person_id,
2348            self.config().gateway.person_bytes.or_max(),
2349        );
2350        tools::Outcome {
2351            text: format!("Offered to the person as {id}; the page opens when they choose it."),
2352            is_error: false,
2353        }
2354    }
2355
2356    /// Turns a submitted form into a proposal of its tool, made in this socket's run.
2357    async fn submit(
2358        &self,
2359        gateway: &Gateway,
2360        conversation_id: &str,
2361        person_id: &str,
2362        token: &str,
2363        view_id: &str,
2364        values: &views::DataObject,
2365    ) -> Result<(), (&'static str, String)> {
2366        let view = {
2367            let mut desk = self.desk();
2368            let conversation = desk
2369                .store
2370                .owned(conversation_id, person_id)
2371                .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
2372            conversation
2373                .entries
2374                .iter()
2375                .find_map(|entry| match &entry.data {
2376                    Some(EntryData::View(card)) if card.id == view_id => {
2377                        card.view.clone().decode::<views::View>().ok()
2378                    }
2379                    _ => None,
2380                })
2381                .ok_or(("not_found", "There is no such view.".to_owned()))?
2382        };
2383        let (tool, input) =
2384            views::form_input(&view, values).map_err(|reason| ("bad_request", reason))?;
2385        let input = mcp::call_with(&tool, &input).map_err(|err| ("bad_request", err))?;
2386        let tool = actions::write_tools()
2387            .iter()
2388            .find(|write| write.name == tool)
2389            .ok_or(("bad_request", "The form names no tool.".to_owned()))?;
2390        let granted = Granted {
2391            conversation_id: conversation_id.to_owned(),
2392            person_id: person_id.to_owned(),
2393            station: String::new(),
2394            bearer: token.to_owned(),
2395        };
2396        let outcome = self.propose(gateway, &granted, tool, &input).await;
2397        if outcome.is_error {
2398            return Err(("refused", outcome.text));
2399        }
2400        if let Some(conversation) = self.desk().store.owned(conversation_id, person_id) {
2401            conversation.notes.push(format!(
2402                "[App: the person submitted the form of {view_id}; it is proposed, and you will be told whether they confirm it.]"
2403            ));
2404        }
2405        Ok(())
2406    }
2407    /// Cancels a pending proposal; Moneypenny hears of it with the next message.
2408    fn cancel(
2409        &self,
2410        conversation_id: &str,
2411        person_id: &str,
2412        proposal_id: &str,
2413    ) -> Result<(), (&'static str, String)> {
2414        let mut desk = self.desk();
2415        let conversation = desk
2416            .store
2417            .owned(conversation_id, person_id)
2418            .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
2419        let proposal = conversation
2420            .proposals
2421            .iter_mut()
2422            .find(|proposal| proposal.id == proposal_id && proposal.status == "pending")
2423            .ok_or(("not_found", "There is no such pending proposal.".to_owned()))?;
2424        proposal.status = "cancelled";
2425        let shown = proposal.clone();
2426        conversation
2427            .notes
2428            .push(format!("[App: the person cancelled {proposal_id}.]"));
2429        conversation.show_proposal(&shown);
2430        drop(desk);
2431        // A held Cable is dropped by the Station that holds it.
2432        if let Some(hold) = shown.cable {
2433            self.discard_cable(conversation_id, proposal_id, hold);
2434        }
2435        Ok(())
2436    }
2437
2438    /// Stops the answer the person's conversation waits for: a message no harness has yet is
2439    /// withdrawn, and the Station whose harness is answering is asked to interrupt it, which it
2440    /// reports as `interrupted`. `Ok(false)` when nothing is being answered.
2441    fn interrupt(
2442        &self,
2443        conversation_id: &str,
2444        person_id: &str,
2445    ) -> Result<bool, (&'static str, String)> {
2446        let bounds = self.config().bounds();
2447        let mut desk = self.desk();
2448        let conversation = desk
2449            .store
2450            .owned(conversation_id, person_id)
2451            .ok_or(("not_found", "The conversation is gone.".to_owned()))?;
2452        if !conversation.busy {
2453            return Ok(false);
2454        }
2455        conversation
2456            .notes
2457            .push("[App: the person stopped your last answer.]".to_owned());
2458        if own_agent::interrupt(&mut desk, conversation_id, bounds) {
2459            return Ok(true);
2460        }
2461        let Some(conversation) = desk.store.owned(conversation_id, person_id) else {
2462            return Err(("not_found", "The conversation is gone.".to_owned()));
2463        };
2464        let station = conversation.station.clone();
2465        if let Some(pending) = conversation.pending.take() {
2466            // A Station that already took the withdrawn message has its late `accepted`
2467            // refused, which makes it close the harness it started. Meanwhile that harness is
2468            // cut off: its tool token is withdrawn and its Cable calls are refused.
2469            let taken = pending.taken_at.and(pending.station);
2470            if let Some(taken_by) = &taken {
2471                if station.as_ref() == Some(taken_by) {
2472                    conversation.live = false;
2473                }
2474                conversation.token = None;
2475                conversation.cut_off = Some(taken_by.clone());
2476            }
2477            stopped(conversation, bounds);
2478            if taken.is_some() {
2479                desk.tokens
2480                    .retain(|_, grant| grant.conversation_id != conversation_id);
2481            }
2482            return Ok(true);
2483        }
2484        if station.is_none() {
2485            stopped(conversation, bounds);
2486            return Ok(true);
2487        }
2488        conversation.stopping = true;
2489        let job = control_job(
2490            conversation,
2491            &self.config().agent_id,
2492            &Control::Interrupt,
2493            None,
2494        );
2495        let asked = desk
2496            .controls
2497            .iter()
2498            .any(|(_, queued)| queued.interrupt && queued.conversation_id == conversation_id);
2499        if !asked && let Some(station) = station {
2500            desk.controlling
2501                .insert(job.job_id.clone(), (station.clone(), Control::Interrupt));
2502            desk.controls.push((station, job));
2503            drop(desk);
2504            self.ready.notify_waiters();
2505        }
2506        Ok(true)
2507    }
2508
2509    /// Counts one tool call of the conversation; `false` past the minute's allowance.
2510    pub(crate) fn count_call(&self, conversation_id: &str) -> bool {
2511        let mut desk = self.desk();
2512        let limit = self.config().gateway.tool_calls_per_minute;
2513        // The minute of `tool_calls_per_minute`.
2514        desk.calls
2515            .retain(|_, (started, _)| started.elapsed() < Duration::from_secs(60));
2516        let (_, calls) = desk
2517            .calls
2518            .entry(conversation_id.to_owned())
2519            .or_insert_with(|| (Instant::now(), 0));
2520        *calls += 1;
2521        limit.allows(*calls)
2522    }
2523}
2524
2525/// Records `action` by `person` in the audit log; `Err` says that nothing may run.
2526async fn audit(
2527    gateway: &Gateway,
2528    person: &ai6::Person,
2529    action: &str,
2530    operation: String,
2531    resource: Option<String>,
2532    target: &str,
2533) -> Result<(), String> {
2534    let registry = gateway
2535        .registry
2536        .clone()
2537        .ok_or("this gateway keeps no audit log, so it ran nothing")?;
2538    let record = ai6::AuditRecord {
2539        id: Uuid::new_v4().to_string(),
2540        actor: crate::actor_of(person),
2541        action: action.to_owned(),
2542        operation,
2543        resource,
2544        target: cut(target, gateway_limits(gateway).audit_target_bytes.or_max()),
2545        at: now(),
2546    };
2547    tokio::task::spawn_blocking(move || registry.record_audit(&record))
2548        .await
2549        .map_err(|_| "it could not be audited, so it did not run".to_owned())?
2550        .map_err(|_| "it could not be audited, so it did not run".to_owned())
2551}
2552
2553/// Adds `proposal` to `conversation`, after expired ones are marked and room is made, and
2554/// shows it.
2555fn record_proposal(
2556    conversation: &mut Conversation,
2557    mut proposal: actions::Proposal,
2558    bounds: Bounds,
2559    limits: &AssistantGatewayLimits,
2560) -> bool {
2561    if !room_for_proposal(conversation, limits) {
2562        return false;
2563    }
2564    proposal.evidence = conversation.evidence();
2565    conversation.push(
2566        Entry {
2567            role: Role::Proposal,
2568            text: proposal.draft.summary.clone(),
2569            at: proposal.created_at,
2570            data: Some(EntryData::Proposal(Box::new(proposal.shown()))),
2571        },
2572        bounds,
2573    );
2574    conversation.proposals.push(proposal);
2575    true
2576}
2577
2578/// What she is told when a proposal does not fit.
2579fn proposals_full(limits: &AssistantGatewayLimits) -> String {
2580    format!(
2581        "{} proposals already wait for the person, so nothing was proposed. Ask them to \
2582         confirm or cancel some first.",
2583        limits.proposals
2584    )
2585}
2586
2587/// Drops finished proposals until one more fits; `false` when every one kept still waits for
2588/// the person or is being carried out, which are never dropped.
2589fn room_for_proposal(conversation: &mut Conversation, limits: &AssistantGatewayLimits) -> bool {
2590    expire_proposals(conversation, limits);
2591    while !limits.proposals.allows(conversation.proposals.len() + 1) {
2592        let Some(finished) = conversation
2593            .proposals
2594            .iter()
2595            .position(|proposal| !matches!(proposal.status, "pending" | "confirming"))
2596        else {
2597            return false;
2598        };
2599        conversation.proposals.remove(finished);
2600    }
2601    true
2602}
2603
2604/// A proposal whose confirmation has a Station make `commit`: `request` describes the commit
2605/// for the person (its message, every file's new text), `needs` what it rests on.
2606fn commit_proposal(
2607    tool: &'static str,
2608    run: String,
2609    target: String,
2610    scope: actions::Scope,
2611    needs: &'static str,
2612    summary: String,
2613    commit: AssistantCommit,
2614) -> actions::Proposal {
2615    actions::Proposal {
2616        id: format!("proposal-{}", Uuid::new_v4().simple()),
2617        tool,
2618        draft: actions::Draft {
2619            call: tools::Call {
2620                method: axum::http::Method::from_bytes(b"COMMIT")
2621                    .unwrap_or(axum::http::Method::POST),
2622                path: target,
2623                body: Some(
2624                    ai6::wire::OpaqueJson::capture(CommitBody {
2625                        message: &commit.message,
2626                        files: &commit.change.files,
2627                    })
2628                    .expect("a commit is written as JSON"),
2629                ),
2630            },
2631            scope,
2632            action: needs,
2633            summary,
2634        },
2635        status: "pending",
2636        created_at: now(),
2637        run,
2638        result: None,
2639        receipt: None,
2640        work: Some(commit),
2641        cable: None,
2642        own_cable: None,
2643        evidence: actions::Evidence::default(),
2644        guard: None,
2645    }
2646}
2647
2648/// Who a valid MCP token speaks for.
2649pub(crate) struct Granted {
2650    pub(crate) conversation_id: String,
2651    pub(crate) person_id: String,
2652    pub(crate) station: String,
2653    /// The person's access token, with which the tools run.
2654    pub(crate) bearer: String,
2655}
2656
2657/// Marks proposals older than `[assistant.gateway] proposal_ttl` expired.
2658fn expire_proposals(conversation: &mut Conversation, limits: &AssistantGatewayLimits) {
2659    let now = now();
2660    let ttl = limits.proposal_ttl.0.as_secs_f64();
2661    let mut expired = Vec::new();
2662    for proposal in &mut conversation.proposals {
2663        if proposal.status == "pending" && now - proposal.created_at > ttl {
2664            proposal.status = "expired";
2665            expired.push(proposal.clone());
2666        }
2667    }
2668    for proposal in expired {
2669        conversation.show_proposal(&proposal);
2670    }
2671}
2672
2673/// What the app is shown when it opens a conversation.
2674///
2675/// Only the newest entries that fit `[assistant.gateway] ready_entries` and `ready_bytes` are
2676/// sent; `earlier` counts those left out. `view_limits` are the bounds the app checks views
2677/// against.
2678fn ready(
2679    conversation: &Conversation,
2680    link: Option<store::LinkStatus>,
2681    limits: &views::ViewLimits,
2682    gateway: &AssistantGatewayLimits,
2683) -> Event {
2684    let mut shown = Vec::new();
2685    let mut bytes = 0;
2686    for entry in conversation
2687        .entries
2688        .iter()
2689        .rev()
2690        .take(gateway.ready_entries.or_max())
2691    {
2692        bytes += store::entry_bytes(entry);
2693        if !gateway.ready_bytes.allows(bytes) && !shown.is_empty() {
2694            break;
2695        }
2696        shown.push(entry.clone());
2697    }
2698    shown.reverse();
2699    Event::Ready {
2700        conversation: conversation.id.clone(),
2701        earlier: conversation.entries.len() - shown.len(),
2702        entries: shown,
2703        busy: conversation.busy,
2704        runner: conversation.runner.clone(),
2705        link,
2706        permission_mode: conversation.permission_mode,
2707        agent_options: conversation.agent_options.clone(),
2708        usage: Usage {
2709            tokens: conversation.spent_tokens,
2710            cost_micro_usd: conversation.spent_micro_usd,
2711        },
2712        view_limits: *limits,
2713    }
2714}
2715
2716/// The end of the conversation so far, for a harness that starts without its provider
2717/// Run's own memory of it: at most `[assistant.gateway] recap_bytes`, and under half of
2718/// `[assistant.limits] context_bytes`, the rest being her standing context.
2719fn recap(conversation: &Conversation, config: &AssistantConfig) -> Option<String> {
2720    recap_with_heading(
2721        conversation,
2722        config,
2723        "Earlier in this conversation (a recap; the app restarted your run):",
2724    )
2725}
2726
2727pub(crate) fn recap_with_heading(
2728    conversation: &Conversation,
2729    config: &AssistantConfig,
2730    heading: &str,
2731) -> Option<String> {
2732    let mut lines = Vec::new();
2733    let mut size = 0;
2734    for entry in conversation.entries.iter().rev() {
2735        let who = match entry.role {
2736            Role::Person => "The person",
2737            Role::Moneypenny => "You",
2738            _ => continue,
2739        };
2740        let line = format!("{who}: {}", entry.text);
2741        size += line.len();
2742        if !config.gateway.recap_bytes.allows(size) {
2743            break;
2744        }
2745        lines.push(line);
2746    }
2747    if lines.is_empty() {
2748        return None;
2749    }
2750    lines.reverse();
2751    let recap = format!("{heading}\n\n{}", lines.join("\n\n"));
2752    let half = config
2753        .limits
2754        .context_bytes
2755        .get()
2756        .map_or(u64::MAX, |bytes| bytes / 2);
2757    (u64::try_from(recap.len()).unwrap_or(u64::MAX) < half).then_some(recap)
2758}
2759
2760/// The line that tells Moneypenny which app page the person was on when they sent a message:
2761/// the route in its link form, percent-encoded, or nothing when it is not a route.
2762fn page_line(route: &OpaqueJson, limits: routes::Limits) -> Option<String> {
2763    let route = routes::Route::from_opaque(route, limits).ok()?;
2764    Some(format!("[App page: {}]", route.to_uri()))
2765}
2766
2767fn cut(text: &str, limit: usize) -> String {
2768    let mut end = text.len().min(limit);
2769    while !text.is_char_boundary(end) {
2770        end -= 1;
2771    }
2772    text[..end].to_owned()
2773}
2774
2775/// Records one harness event in the conversation (shared by Station pool reports and own-agent ACP updates).
2776pub(crate) fn apply_event(
2777    conversation: &mut Conversation,
2778    event: &AssistantEvent,
2779    max_entries: Bounds,
2780) {
2781    let at = now();
2782    let text = event.text.clone().unwrap_or_default();
2783    let entry = |role, text: String| Entry {
2784        role,
2785        text,
2786        at,
2787        data: None,
2788    };
2789    match event.kind.as_str() {
2790        EVENT_TEXT if !text.trim().is_empty() => {
2791            // The pieces one answer arrives in are one entry, until a tool or another entry
2792            // comes between them.
2793            if !(conversation.answered && conversation.append_to_last(&text)) {
2794                conversation.push(entry(Role::Moneypenny, text), max_entries);
2795            }
2796            conversation.answered = true;
2797        }
2798        EVENT_TOOL => {
2799            let tools = event.tools.join(", ");
2800            conversation.push(entry(Role::Tools, tools), max_entries);
2801        }
2802        EVENT_COMPLETED => {
2803            if !conversation.answered && !text.trim().is_empty() {
2804                conversation.push(entry(Role::Moneypenny, text), max_entries);
2805            }
2806            conversation.answered = false;
2807            conversation.set_busy(false);
2808        }
2809        EVENT_FAILED | EVENT_LIMIT => {
2810            let what = if event.kind == EVENT_LIMIT {
2811                "Moneypenny's model account is out of quota for now".to_owned()
2812            } else {
2813                format!("Moneypenny stopped: {}", or_unknown(&text))
2814            };
2815            conversation.live = false;
2816            conversation.push(entry(Role::Error, what), max_entries);
2817            conversation.set_busy(false);
2818        }
2819        // What she and the person should know about her workspace.
2820        EVENT_NOTICE if !text.trim().is_empty() => {
2821            conversation.notes.push(format!("[Station: {text}]"));
2822            conversation.push(entry(Role::Notice, text), max_entries);
2823        }
2824        // Only the answer being given can be the one stopped; a later message is not.
2825        EVENT_INTERRUPTED if conversation.busy && conversation.pending.is_none() => {
2826            stopped(conversation, max_entries);
2827        }
2828        EVENT_CLOSED if !conversation.busy || conversation.pending.is_some() => {
2829            // An idle harness closed, or the one a new job replaces.
2830            conversation.live = false;
2831        }
2832        EVENT_CLOSED => {
2833            conversation.live = false;
2834            conversation.push(
2835                entry(
2836                    Role::Error,
2837                    format!(
2838                        "Moneypenny's run closed before she answered: {}",
2839                        or_unknown(&text)
2840                    ),
2841                ),
2842                max_entries,
2843            );
2844            conversation.set_busy(false);
2845        }
2846        _ => {}
2847    }
2848}
2849
2850/// Records a Station's answer to a commit job: an entry for the person, then the proposal it
2851/// carried out settled, or a note telling Moneypenny with her next message.
2852fn committed(
2853    conversation: &mut Conversation,
2854    proposal: Option<&str>,
2855    what: &str,
2856    report: &AssistantReport,
2857    bounds: Bounds,
2858) {
2859    let answer = report.events.first();
2860    let done = answer.is_some_and(|event| event.kind == EVENT_ACCEPTED);
2861    let text = answer
2862        .and_then(|event| event.text.clone())
2863        .unwrap_or_default();
2864    let line = if done {
2865        format!("{what}: {}.", or_unknown(&text))
2866    } else {
2867        format!("{what} failed: {}.", or_unknown(&text))
2868    };
2869    conversation.push(
2870        Entry {
2871            role: if done { Role::Notice } else { Role::Error },
2872            text: line.clone(),
2873            at: now(),
2874            data: None,
2875        },
2876        bounds,
2877    );
2878    match proposal {
2879        Some(id) => settle(conversation, id, done, or_unknown(&text)),
2880        None => conversation.notes.push(format!("[Station: {line}]")),
2881    }
2882}
2883
2884/// Ends the answer the person stopped, and shows that it was stopped.
2885pub(crate) fn stopped(conversation: &mut Conversation, bounds: Bounds) {
2886    conversation.pending = None;
2887    conversation.answered = false;
2888    conversation.push(
2889        Entry {
2890            role: Role::Notice,
2891            text: "You stopped Moneypenny's answer.".to_owned(),
2892            at: now(),
2893            data: None,
2894        },
2895        bounds,
2896    );
2897    conversation.set_busy(false);
2898}
2899
2900pub(crate) fn or_unknown(text: &str) -> &str {
2901    if text.trim().is_empty() {
2902        "no reason given"
2903    } else {
2904        text
2905    }
2906}
2907
2908/// Healthy Stations, the Headquarters Station first, then by ID.
2909async fn healthy_stations(gateway: &Gateway) -> Vec<String> {
2910    let Some(registry) = gateway.registry.clone() else {
2911        return Vec::new();
2912    };
2913    let found = tokio::task::spawn_blocking(move || {
2914        let stations = registry.stations(Duration::MAX).ok()?;
2915        let headquarters = registry.headquarters().ok().flatten();
2916        let dark = registry.limits().stations.gone_dark_after.0.as_secs_f64();
2917        Some((stations, headquarters, dark))
2918    })
2919    .await
2920    .ok()
2921    .flatten();
2922    let Some((stations, headquarters, dark)) = found else {
2923        return Vec::new();
2924    };
2925    let now = now();
2926    let leader = headquarters
2927        .filter(|lease| lease.expires() > now)
2928        .map(|lease| lease.station().to_owned());
2929    let mut healthy: Vec<String> = stations
2930        .iter()
2931        .filter(|station| now - station.seen() <= dark)
2932        .map(|station| station.station().to_owned())
2933        .collect();
2934    healthy.sort_by_key(|station| (Some(station) != leader.as_ref(), station.clone()));
2935    healthy
2936}
2937
2938#[derive(Deserialize)]
2939#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
2940enum FromApp {
2941    Hello {
2942        token: String,
2943        #[serde(default)]
2944        conversation: Option<String>,
2945        #[serde(default)]
2946        runner: Option<store::Runner>,
2947        #[serde(default)]
2948        from: Option<String>,
2949    },
2950    Message {
2951        text: String,
2952        #[serde(default)]
2953        route: Option<OpaqueJson>,
2954        #[serde(default)]
2955        images: Vec<images::AppImage>,
2956    },
2957    New {
2958        #[serde(default)]
2959        runner: Option<store::Runner>,
2960        #[serde(default)]
2961        from: Option<String>,
2962    },
2963    Confirm {
2964        proposal: String,
2965    },
2966    Cancel {
2967        proposal: String,
2968    },
2969    Permission {
2970        request: String,
2971        allow: bool,
2972    },
2973    SetMode {
2974        mode: store::PermissionMode,
2975    },
2976    SetConfigOption {
2977        config_id: String,
2978        value: String,
2979    },
2980    Submit {
2981        view: String,
2982        values: views::DataObject,
2983    },
2984    Interrupt {},
2985}
2986
2987fn frame(event: &Event) -> Message {
2988    Message::Text(
2989        serde_json::to_string(event)
2990            .expect("conversation event serializes")
2991            .into(),
2992    )
2993}
2994
2995fn problem(code: &str, message: &str) -> Event {
2996    Event::Error {
2997        code: code.to_owned(),
2998        message: message.to_owned(),
2999    }
3000}
3001
3002/// `GET /v1/user/moneypenny`: the app's conversation with Moneypenny. The first frame is
3003/// `{"type":"hello","token":ACCESS_TOKEN,"conversation"?:ID}`; the token is the person's
3004/// access token, sent in the socket rather than a header a browser cannot set.
3005pub(crate) async fn socket(State(gateway): State<Gateway>, upgrade: WebSocketUpgrade) -> Response {
3006    if gateway.assistant().is_none() {
3007        return ApiError::unavailable().into_response();
3008    }
3009    upgrade
3010        .max_message_size(socket_limit(&gateway))
3011        .on_upgrade(move |socket| {
3012            converse(
3013                crate::browser_link::AppSocket::websocket(socket),
3014                gateway,
3015                None,
3016            )
3017        })
3018}
3019
3020pub(crate) fn socket_limit(gateway: &Gateway) -> usize {
3021    // A message frame carries its images as base64, four characters for three bytes.
3022    let images = gateway.assistant().as_ref().map_or(0, |assistant| {
3023        let limits = &assistant.config().limits;
3024        limits
3025            .images
3026            .or_max()
3027            .saturating_mul(limits.image_bytes.or_max().div_ceil(3).saturating_mul(4))
3028    });
3029    gateway_limits(gateway)
3030        .socket_message_bytes
3031        .or_max()
3032        .saturating_add(images)
3033}
3034
3035pub(crate) async fn converse(
3036    socket: crate::browser_link::AppSocket,
3037    gateway: Gateway,
3038    binding: Option<&crate::browser_link::Binding>,
3039) {
3040    let Some(assistant) = gateway.assistant() else {
3041        return;
3042    };
3043    let crate::browser_link::AppSocket {
3044        mut sender,
3045        mut receiver,
3046    } = socket;
3047    let hello =
3048        tokio::time::timeout(assistant.config().gateway.hello_timeout.0, receiver.next()).await;
3049    let Ok(Some(Ok(Message::Text(hello)))) = hello else {
3050        let _ = sender.send(close(1008, "say hello first")).await;
3051        return;
3052    };
3053    let Ok(FromApp::Hello {
3054        token,
3055        conversation,
3056        runner,
3057        from,
3058    }) = serde_json::from_str::<FromApp>(&hello)
3059    else {
3060        let _ = sender.send(close(1008, "say hello first")).await;
3061        return;
3062    };
3063    let person = match binding {
3064        Some(binding) => binding.resolve(&gateway, &token).await,
3065        None => resolve_signed_in(&gateway, &token).await,
3066    };
3067    let Ok(person) = person else {
3068        let _ = sender
3069            .send(frame(&problem(
3070                "unauthorized",
3071                "Sign in again to talk to Moneypenny.",
3072            )))
3073            .await;
3074        let _ = sender.send(close(1008, "unauthorized")).await;
3075        return;
3076    };
3077    if let Some(requested) = conversation.as_deref() {
3078        assistant
3079            .restore(&gateway, &person.id, &token, requested)
3080            .await;
3081    }
3082    let (mut conversation_id, shown, mut events) = match assistant
3083        .open_with_options(
3084            &gateway,
3085            &person,
3086            &token,
3087            conversation.as_deref(),
3088            runner,
3089            from.as_deref(),
3090        )
3091        .await
3092    {
3093        Ok(opened) => opened,
3094        Err((code, message)) => {
3095            let _ = sender.send(frame(&problem(code, &message))).await;
3096            let _ = sender.send(close(1008, code)).await;
3097            return;
3098        }
3099    };
3100    if sender.send(frame(&shown)).await.is_err() {
3101        return;
3102    }
3103    let mut sweep = tokio::time::interval(assistant.config().gateway.sweep_every.0);
3104    loop {
3105        tokio::select! {
3106            _ = sweep.tick() => assistant.sweep(&gateway).await,
3107            incoming = receiver.next() => match incoming {
3108                Some(Ok(Message::Text(text))) => {
3109                    match serde_json::from_str::<FromApp>(&text) {
3110                        Ok(FromApp::Message { text, route, images }) => {
3111                            if let Err((code, message)) = assistant
3112                                .message(&gateway, &conversation_id, &person.id, &text, route.as_ref(), &images)
3113                                .await
3114                                && sender.send(frame(&problem(code, &message))).await.is_err()
3115                            {
3116                                break;
3117                            }
3118                        }
3119                        Ok(FromApp::Confirm { proposal }) => {
3120                            if let Err((code, message)) = assistant
3121                                .confirm(&gateway, &conversation_id, &person, &token, &proposal)
3122                                .await
3123                                && sender.send(frame(&problem(code, &message))).await.is_err()
3124                            {
3125                                break;
3126                            }
3127                        }
3128                        Ok(FromApp::Cancel { proposal }) => {
3129                            if let Err((code, message)) =
3130                                assistant.cancel(&conversation_id, &person.id, &proposal)
3131                                && sender.send(frame(&problem(code, &message))).await.is_err()
3132                            {
3133                                break;
3134                            }
3135                        }
3136                        Ok(FromApp::Submit { view, values }) => {
3137                            if let Err((code, message)) = assistant
3138                                .submit(&gateway, &conversation_id, &person.id, &token, &view, &values)
3139                                .await
3140                                && sender.send(frame(&problem(code, &message))).await.is_err()
3141                            {
3142                                break;
3143                            }
3144                        }
3145                        Ok(FromApp::Interrupt {}) => {
3146                            let answer = match assistant.interrupt(&conversation_id, &person.id) {
3147                                Ok(stopping) => Event::Interrupt { stopping },
3148                                Err((code, message)) => problem(code, &message),
3149                            };
3150                            if sender.send(frame(&answer)).await.is_err() {
3151                                break;
3152                            }
3153                        }
3154                        Ok(FromApp::Permission { request, allow }) => {
3155                            if let Err((code, message)) = own_agent::answer_permission(
3156                                &assistant,
3157                                &conversation_id,
3158                                &person.id,
3159                                &request,
3160                                allow,
3161                            ) && sender.send(frame(&problem(code, &message))).await.is_err()
3162                            {
3163                                break;
3164                            }
3165                        }
3166                        Ok(FromApp::SetMode { mode }) => {
3167                            if let Err((code, message)) = own_agent::set_mode(
3168                                &assistant,
3169                                &conversation_id,
3170                                &person.id,
3171                                mode,
3172                            ) && sender.send(frame(&problem(code, &message))).await.is_err()
3173                            {
3174                                break;
3175                            }
3176                        }
3177                        Ok(FromApp::SetConfigOption { config_id, value }) => {
3178                            if let Err((code, message)) = own_agent::set_config_option(
3179                                &assistant,
3180                                &gateway,
3181                                &conversation_id,
3182                                &person.id,
3183                                &config_id,
3184                                &value,
3185                            )
3186                            .await
3187                                && sender.send(frame(&problem(code, &message))).await.is_err()
3188                            {
3189                                break;
3190                            }
3191                        }
3192                        Ok(FromApp::New { runner, from }) => {
3193                            match assistant
3194                                .open_with_options(
3195                                    &gateway,
3196                                    &person,
3197                                    &token,
3198                                    None,
3199                                    runner,
3200                                    from.as_deref(),
3201                                )
3202                                .await
3203                            {
3204                                Ok((id, shown, subscription)) => {
3205                                    conversation_id = id;
3206                                    events = subscription;
3207                                    if sender.send(frame(&shown)).await.is_err() {
3208                                        break;
3209                                    }
3210                                }
3211                                Err((code, message)) => {
3212                                    if sender.send(frame(&problem(code, &message))).await.is_err() {
3213                                        break;
3214                                    }
3215                                }
3216                            }
3217                        }
3218                        Ok(FromApp::Hello { .. }) | Err(_) => {
3219                            if sender
3220                                .send(frame(&problem("bad_request", "That frame is not understood.")))
3221                                .await
3222                                .is_err()
3223                            {
3224                                break;
3225                            }
3226                        }
3227                    }
3228                }
3229                Some(Ok(Message::Ping(payload))) => {
3230                    if sender.send(Message::Pong(payload)).await.is_err() {
3231                        break;
3232                    }
3233                }
3234                Some(Ok(Message::Pong(_))) => {}
3235                Some(Ok(Message::Binary(_))) => {
3236                    let _ = sender.send(close(1003, "text frames only")).await;
3237                    break;
3238                }
3239                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
3240            },
3241            event = events.recv() => match event {
3242                Ok(event) => {
3243                    if sender.send(frame(&event)).await.is_err() {
3244                        break;
3245                    }
3246                }
3247                Err(broadcast::error::RecvError::Lagged(_)) => {
3248                    let _ = sender.send(close(1013, "fell behind; reopen the conversation")).await;
3249                    break;
3250                }
3251                Err(broadcast::error::RecvError::Closed) => break,
3252            },
3253        }
3254    }
3255    drop(events);
3256    own_agent::release_unwatched(&assistant, &conversation_id);
3257}
3258
3259fn close(code: u16, reason: &'static str) -> Message {
3260    Message::Close(Some(CloseFrame {
3261        code,
3262        reason: reason.into(),
3263    }))
3264}
3265
3266#[derive(Deserialize)]
3267pub(crate) struct NextQuery {
3268    station: String,
3269    wait_ms: Option<u64>,
3270}
3271
3272/// `GET /v1/station/assistant/next?station=ID&wait_ms=N`: the next message for the
3273/// Station's assistant desk (`200` and an [`AssistantJob`]), or `204` after `wait_ms`
3274/// (default 1,000, at most `[assistant.gateway] max_wait`).
3275pub(crate) async fn next(
3276    State(gateway): State<Gateway>,
3277    headers: HeaderMap,
3278    Query(query): Query<NextQuery>,
3279) -> Result<Response, ApiError> {
3280    gateway.authenticate_station(bearer(&headers)?)?;
3281    if !ai6::directorates::section_00::assistant::valid_identity(&query.station) {
3282        return Err(ApiError::bad_request());
3283    }
3284    // With Moneypenny off the poll is still held, so an idle Station does not ask in a loop.
3285    let max_wait = gateway
3286        .assistant()
3287        .as_ref()
3288        .map_or(gateway.job_poll_max_wait, |assistant| {
3289            assistant.config().gateway.max_wait.0
3290        });
3291    let wait = Duration::from_millis(query.wait_ms.unwrap_or(1_000)).min(max_wait);
3292    let Some(assistant) = gateway.assistant() else {
3293        tokio::time::sleep(wait).await;
3294        return Ok(StatusCode::NO_CONTENT.into_response());
3295    };
3296    let deadline = tokio::time::Instant::now() + wait;
3297    loop {
3298        let notified = assistant.ready.notified();
3299        tokio::pin!(notified);
3300        notified.as_mut().enable();
3301        if let Some(job) = assistant.take(&gateway, &query.station).await {
3302            return Ok(Json(job).into_response());
3303        }
3304        if tokio::time::timeout_at(deadline, notified).await.is_err() {
3305            return Ok(StatusCode::NO_CONTENT.into_response());
3306        }
3307    }
3308}
3309
3310#[derive(Deserialize)]
3311pub(crate) struct StandingQuery {
3312    station: String,
3313    conversation: String,
3314    /// The Operation whose Cable permissions the Station asks about.
3315    operation: String,
3316}
3317
3318/// `GET /v1/station/assistant/cables?station=ID&conversation=ID&operation=ID`: `"send"` and
3319/// `"read"`, whether the person of a conversation the Station runs holds `cable.send` and
3320/// `cable.read` on the Operation now; `404` for one this gateway does not hold, `403` for one
3321/// another Station runs.
3322pub(crate) async fn cable_standing(
3323    State(gateway): State<Gateway>,
3324    headers: HeaderMap,
3325    Query(query): Query<StandingQuery>,
3326) -> Result<Json<CableStanding>, ApiError> {
3327    gateway.authenticate_station(bearer(&headers)?)?;
3328    let assistant = gateway.assistant().ok_or_else(ApiError::not_found)?;
3329    assistant.run_by(&query.station, &query.conversation)?;
3330    // A harness cut off by a Stop sends and reads no Cable.
3331    let cut_off = assistant
3332        .desk()
3333        .store
3334        .conversations
3335        .get(&query.conversation)
3336        .is_some_and(|conversation| {
3337            conversation.cut_off.as_deref() == Some(query.station.as_str())
3338        });
3339    let (send, read) = if cut_off {
3340        (false, false)
3341    } else {
3342        assistant
3343            .cable_permissions(&gateway, &query.conversation, &query.operation)
3344            .await
3345    };
3346    Ok(Json(CableStanding { send, read }))
3347}
3348
3349#[derive(Deserialize)]
3350pub(crate) struct ImageQuery {
3351    station: String,
3352    conversation: String,
3353}
3354
3355/// An image as a response: its own format, nothing to run, kept nowhere on the way.
3356fn image_response(media_type: &'static str, bytes: Vec<u8>) -> Response {
3357    (
3358        [
3359            (axum::http::header::CONTENT_TYPE, media_type),
3360            (axum::http::header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
3361            (axum::http::header::CACHE_CONTROL, "no-store, private"),
3362            (
3363                axum::http::header::CONTENT_SECURITY_POLICY,
3364                "sandbox; default-src 'none'",
3365            ),
3366        ],
3367        bytes,
3368    )
3369        .into_response()
3370}
3371
3372/// `GET /v1/station/assistant/images/{sha256}?station=&conversation=`: an image the person of a
3373/// conversation the Station runs, or took a job of, sent; `404` for one this gateway does not
3374/// keep for them, `403` for a conversation another Station runs.
3375pub(crate) async fn station_image(
3376    State(gateway): State<Gateway>,
3377    headers: HeaderMap,
3378    Path(sha256): Path<String>,
3379    Query(query): Query<ImageQuery>,
3380) -> Result<Response, ApiError> {
3381    gateway.authenticate_station(bearer(&headers)?)?;
3382    let assistant = gateway.assistant().ok_or_else(ApiError::not_found)?;
3383    // The Station reads a message's images before its harness accepts the message, so the one
3384    // that took the job may read them as well as the one that runs the conversation.
3385    let person = {
3386        let desk = assistant.desk();
3387        let conversation = desk
3388            .store
3389            .conversations
3390            .get(&query.conversation)
3391            .ok_or_else(ApiError::not_found)?;
3392        let taken_by = conversation
3393            .pending
3394            .as_ref()
3395            .and_then(|pending| pending.station.as_deref());
3396        if conversation.station.as_deref() != Some(query.station.as_str())
3397            && taken_by != Some(query.station.as_str())
3398        {
3399            return Err(ApiError::forbidden());
3400        }
3401        conversation.person_id.clone()
3402    };
3403    let store = gateway.images.clone().ok_or_else(ApiError::not_found)?;
3404    let (media_type, bytes) = store
3405        .get(&person, &sha256)
3406        .ok_or_else(ApiError::not_found)?;
3407    Ok(image_response(media_type, bytes))
3408}
3409
3410/// `GET /v1/user/moneypenny/images/{sha256}`: an image the person sent her; `404` for any other.
3411pub(crate) async fn user_image(
3412    State(gateway): State<Gateway>,
3413    headers: HeaderMap,
3414    Path(sha256): Path<String>,
3415) -> Result<Response, ApiError> {
3416    let person = resolve_signed_in(&gateway, bearer(&headers)?).await?;
3417    let store = gateway.images.clone().ok_or_else(ApiError::not_found)?;
3418    let (media_type, bytes) = store
3419        .get(&person.id, &sha256)
3420        .ok_or_else(ApiError::not_found)?;
3421    Ok(image_response(media_type, bytes))
3422}
3423
3424/// The commands an [`EVENT_COMMANDS`] event announces, those with a name a person could type
3425/// after `/`, their descriptions cut to `result_chars`.
3426fn announced(event: &AssistantEvent, config: &AssistantConfig) -> Vec<AssistantCommand> {
3427    event
3428        .commands
3429        .iter()
3430        .filter(|command| {
3431            !command.name.is_empty()
3432                && command
3433                    .name
3434                    .chars()
3435                    .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
3436        })
3437        .map(|command| AssistantCommand {
3438            name: command.name.clone(),
3439            description: cut(&command.description, config.gateway.result_chars.or_max()),
3440            input_hint: command
3441                .input_hint
3442                .as_deref()
3443                .map(|hint| cut(hint, config.gateway.result_chars.or_max())),
3444        })
3445        .collect()
3446}
3447
3448/// `POST /v1/station/assistant/reports`: what a Station's assistant harness did. `204`;
3449/// `404` for a conversation this gateway does not hold, `409` for a job it no longer waits
3450/// for, `403` for a report from a Station that does not run the conversation.
3451pub(crate) async fn reports(
3452    State(gateway): State<Gateway>,
3453    headers: HeaderMap,
3454    axum::Extension(caller): axum::Extension<crate::station_auth::StationCaller>,
3455    Json(report): Json<AssistantReport>,
3456) -> Result<StatusCode, ApiError> {
3457    gateway.authenticate_station(bearer(&headers)?)?;
3458    caller.admits(&report.station_id)?;
3459    let Some(assistant) = gateway.assistant() else {
3460        return Err(ApiError::not_found());
3461    };
3462    match assistant.report(&gateway, report).await {
3463        Ok(()) => Ok(StatusCode::NO_CONTENT),
3464        Err(StatusCode::NOT_FOUND) => Err(ApiError::not_found()),
3465        Err(StatusCode::FORBIDDEN) => Err(ApiError::forbidden()),
3466        Err(StatusCode::CONFLICT) => Err(ApiError::from(GatewayError::Conflict)),
3467        Err(_) => Err(ApiError::bad_request()),
3468    }
3469}
3470
3471#[cfg(test)]
3472mod tests;