Skip to main content

adk_surface/
control.rs

1//! The control-plane source (spec 3.3 §6): a kernel in another process or on another
2//! machine, through `adk_kernel::control::ControlClient`.
3
4use std::collections::{BTreeMap, HashMap};
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use adk_core::audit_log::{AuditRecordDraft, AuditRecorder, AuditTrail};
10use adk_core::{
11    ApprovalAction, ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ErrorCategory,
12    Event, RunCheckpointRef, RunState,
13};
14use adk_harness::HarnessMode;
15use adk_kernel::KernelEvent;
16use adk_kernel::control::api::{
17    ApprovalItem, AttachRequest, LedgerParams, SpawnRequest, SteerResponse,
18};
19use adk_kernel::control::{ControlClient, SurfaceRecord};
20use adk_kernel::proc::LedgerEntry;
21use async_trait::async_trait;
22use chrono::{DateTime, Utc};
23use futures::StreamExt;
24use serde_json::json;
25use tokio::sync::watch;
26
27use crate::error::{Result, SurfaceError};
28use crate::inbox::Inbox;
29use crate::origin::Caller;
30use crate::source::{
31    AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday, Steered, Steering, TurnFailure,
32};
33
34/// How long the feed waits for a bus event before it reads the session again anyway, while a
35/// process runs (its turn writes the session between bus events) or the bus is unreachable.
36const QUIET_REREAD: Duration = Duration::from_secs(15);
37
38/// How long the feed waits for a bus event while no process runs and the bus is connected:
39/// nothing then changes a session without a bus event, and every session read is an attach
40/// the kernel records (spec 3.2 §9.3), so an idle surface reads only this often.
41const QUIET_IDLE: Duration = Duration::from_secs(300);
42
43/// What the one subscription to the kernel's bus knows, shared by every feed.
44#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
45struct Bus {
46    /// Moves on every bus event, and when the stream connects or drops.
47    events: u64,
48    /// The stream is connected.
49    live: bool,
50    /// Processes running or queued, as the bus last reported them.
51    running: usize,
52}
53
54/// The engine's source over a kernel's control plane (spec 3.3 §6, spec 3.2 §7.11): a
55/// terminal or a home attached to a kernel elsewhere, over its socket, named pipe or HTTP.
56///
57/// Sessions, processes, the ledger and the kill switch go through `ControlClient`, so the
58/// caller is whoever the client authenticates as (the OS user on the socket, a bearer token
59/// over HTTP), and the kernel records each session read as `kernel.control`. The feed re-reads
60/// a session when the kernel's event bus reports a change; with no event, every 15 seconds
61/// while a process runs or the bus is unreachable, and every 5 minutes otherwise.
62///
63/// Decisions come from the approvals inbox beside the kernel routes, read in full —
64/// `GET /api/approvals?session=`, `GET /api/approvals/{id}`, `POST /api/approvals/{id}/decide`
65/// — over the same socket or HTTP endpoint, so cards carry their risk, agent and earlier
66/// decisions, "Edit" sends its arguments, and a decision answered elsewhere says who
67/// answered. The inbox gets the client's bearer token
68/// ([`ControlClient::bearer_token`]); [`with_bearer_token`](Self::with_bearer_token) replaces
69/// it for the inbox alone. Every inbox call gives up after 30 seconds, as the client's calls
70/// do. Over a named pipe (Windows) the source keeps to `ControlClient`'s
71/// pending items, which carry none of these: every decision counts as high risk, "Edit" is
72/// not offered, and a decision answered elsewhere is no longer found.
73///
74/// "Always allow" is offered where the kernel's command host makes a standing rule of the
75/// call (`GET /api/kernel/rules/always-allow/{id}`, spec 3.3 §5.2): the rule is prepared
76/// while the decision waits and granted once the yes is recorded, as in process. A paired
77/// device's token reaches none of those routes, so a remote terminal offers Allow once, Edit
78/// and Deny.
79///
80/// A message for a running turn goes through `POST /api/kernel/sessions/{id}/steer`, which
81/// the replica that answers takes only for a turn it runs itself; a turn another replica runs
82/// hands the message back, and it goes as the session's next message. What became of a
83/// message the kernel accepted is read from the kernel's stores: delivered once the session
84/// holds its event, handed back once its process leaves the claim that held it.
85///
86/// The session's mode is read from the kernel (`GET /api/kernel/sessions/{id}/mode`) and set
87/// by the REPL's `/mode`, which the kernel runs over its harness (spec 3.3 §5.2), so the
88/// Permissions keys and `/mode` work on a thread that has no message yet. The engine's
89/// records reach the kernel's signed log through [`audit_trail`](Self::audit_trail).
90///
91/// # Example
92///
93/// ```rust,no_run
94/// use adk_kernel::control::ControlClient;
95/// use adk_surface::ControlSource;
96///
97/// # async fn example(home: &std::path::Path) -> adk_surface::Result<()> {
98/// let client = ControlClient::connect_local(home).await?.expect("a kernel is running");
99/// let source = ControlSource::new(client, "adk-rust", "adk-rust");
100/// # let _ = source;
101/// # Ok(())
102/// # }
103/// ```
104#[derive(Clone)]
105pub struct ControlSource {
106    client: ControlClient,
107    app: String,
108    target: String,
109    daily_limit: Option<u64>,
110    changes: Arc<std::sync::OnceLock<watch::Receiver<Bus>>>,
111    inbox: Option<Inbox>,
112    /// "Always allow" as the kernel offers it: the engine asks every time it draws a card.
113    offers: Arc<std::sync::Mutex<Offers>>,
114}
115
116/// "Always allow" as a kernel offers it, by decision: the version asked at, and the words.
117type Offers = BTreeMap<String, (u64, Option<String>)>;
118
119impl fmt::Debug for ControlSource {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.debug_struct("ControlSource")
122            .field("endpoint", &self.client.endpoint())
123            .field("app", &self.app)
124            .field("target", &self.target)
125            .finish_non_exhaustive()
126    }
127}
128
129impl ControlSource {
130    /// A source over `client` for the sessions of `app_name`, starting turns as processes of
131    /// `target`.
132    pub fn new(
133        client: ControlClient,
134        app_name: impl Into<String>,
135        target: impl Into<String>,
136    ) -> Self {
137        let inbox =
138            Inbox::for_endpoint(&client.endpoint(), client.bearer_token().map(str::to_owned));
139        Self {
140            client,
141            app: app_name.into(),
142            target: target.into(),
143            daily_limit: None,
144            changes: Arc::new(std::sync::OnceLock::new()),
145            inbox,
146            offers: Arc::default(),
147        }
148    }
149
150    /// Sends `token` as a bearer token to the approvals inbox instead of the client's own
151    /// token, which [`new`](Self::new) already passes on.
152    #[must_use]
153    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
154        self.inbox = self.inbox.map(|inbox| inbox.with_token(token.into()));
155        self
156    }
157
158    /// A daily spending limit in micro-USD in place of the one the kernel reports for the
159    /// primary agent's area (`GET /kernel/settings`, spec 3.3 §10 K3).
160    #[must_use]
161    pub fn with_daily_limit(mut self, micro_usd: u64) -> Self {
162        self.daily_limit = Some(micro_usd);
163        self
164    }
165
166    /// The kernel's signed log, for the engine over this source: each record the engine
167    /// writes — every answer with the surface and how it was given, Stop all, Resume all, a
168    /// mode change, a message sent — goes to `POST /api/kernel/surface/records`, and the kernel
169    /// writes it with the caller as its actor (spec 3.3 §11). Only the person reaches that
170    /// route: give it to the engine of a caller the kernel admits as the operator, never a
171    /// paired device's, whose answers the kernel records itself.
172    ///
173    /// # Example
174    ///
175    /// ```rust,no_run
176    /// use std::sync::Arc;
177    /// use adk_kernel::control::ControlClient;
178    /// use adk_surface::{ControlSource, SurfaceEngine};
179    ///
180    /// # async fn example(home: &std::path::Path) -> adk_surface::Result<()> {
181    /// let client = ControlClient::connect_local(home).await?.expect("a kernel is running");
182    /// let source = ControlSource::new(client, "adk-rust", "adk-rust");
183    /// let engine = SurfaceEngine::builder(Arc::new(source.clone())).audit(source.audit_trail()).build();
184    /// # let _ = engine;
185    /// # Ok(())
186    /// # }
187    /// ```
188    pub fn audit_trail(&self) -> AuditTrail {
189        AuditTrail::new(Arc::new(KernelRecorder { client: self.client.clone() }))
190    }
191
192    /// What the kernel's bus reports, from one subscription shared by every feed.
193    fn changes(&self) -> watch::Receiver<Bus> {
194        self.changes
195            .get_or_init(|| {
196                let (sender, receiver) = watch::channel(Bus::default());
197                let client = self.client.clone();
198                let app = self.app.clone();
199                tokio::spawn(async move {
200                    let mut cursor = None;
201                    loop {
202                        match client.events(cursor).await {
203                            Ok(mut events) => {
204                                // The processes running now; the bus keeps the count from here.
205                                let mut running: Option<HashMap<String, RunState>> = client
206                                    .processes(&Default::default())
207                                    .await
208                                    .ok()
209                                    .map(|processes| {
210                                        processes
211                                            .into_iter()
212                                            .filter(|process| {
213                                                process.run.app_name == app && runs(process.run.state)
214                                            })
215                                            .map(|process| (process.meta.pid, process.run.state))
216                                            .collect()
217                                    });
218                                let count = |running: &Option<HashMap<String, RunState>>| {
219                                    // Unknown counts as running: the feed keeps re-reading.
220                                    running.as_ref().map_or(1, HashMap::len)
221                                };
222                                sender.send_modify(|bus| {
223                                    bus.events += 1;
224                                    bus.live = true;
225                                    bus.running = count(&running);
226                                });
227                                while let Some(Ok(record)) = events.next().await {
228                                    cursor = Some(record.cursor);
229                                    if let (KernelEvent::Process { pid, to, .. }, Some(running)) =
230                                        (&record.event, running.as_mut())
231                                    {
232                                        if runs(*to) {
233                                            running.insert(pid.clone(), *to);
234                                        } else {
235                                            running.remove(pid);
236                                        }
237                                    }
238                                    sender.send_modify(|bus| {
239                                        bus.events += 1;
240                                        bus.running = count(&running);
241                                    });
242                                    if sender.is_closed() {
243                                        return;
244                                    }
245                                }
246                            }
247                            Err(error) => {
248                                tracing::debug!(error = %error, "the kernel's event stream is unavailable");
249                            }
250                        }
251                        sender.send_modify(|bus| {
252                            bus.events += 1;
253                            bus.live = false;
254                        });
255                        if sender.is_closed() {
256                            return;
257                        }
258                        tokio::time::sleep(Duration::from_secs(2)).await;
259                    }
260                });
261                receiver
262            })
263            .clone()
264    }
265
266    async fn processes(&self, user: &str) -> Result<Vec<adk_kernel::Process>> {
267        let mut processes: Vec<_> = self
268            .client
269            .processes(&Default::default())
270            .await?
271            .into_iter()
272            .filter(|process| process.run.user_id == user && process.run.app_name == self.app)
273            .collect();
274        processes.sort_by_key(|process| std::cmp::Reverse(process.run.updated_at));
275        Ok(processes)
276    }
277}
278
279/// Whether a process in `state` is running or about to.
280fn runs(state: RunState) -> bool {
281    matches!(state, RunState::Running | RunState::Queued)
282}
283
284/// Whether an error of `category` may pass: the kernel was out of reach, busy or failed, not
285/// refusing.
286fn passing(category: ErrorCategory) -> bool {
287    matches!(
288        category,
289        ErrorCategory::Unavailable
290            | ErrorCategory::Timeout
291            | ErrorCategory::Internal
292            | ErrorCategory::RateLimited
293            | ErrorCategory::ResourceExhausted
294            | ErrorCategory::Cancelled
295    )
296}
297
298/// How many decisions' "Always allow" offers a source keeps.
299const OFFERS: usize = 256;
300
301/// The engine's records, written on the kernel's signed log over its control plane.
302struct KernelRecorder {
303    client: ControlClient,
304}
305
306#[async_trait]
307impl AuditRecorder for KernelRecorder {
308    fn digest(&self, value: &serde_json::Value) -> String {
309        adk_core::json_digest(value)
310    }
311
312    async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
313        // The kernel names the actor itself, as the caller it admitted.
314        let AuditRecordDraft { kind, action, decision, ext, .. } = draft;
315        let mut record = SurfaceRecord::new(kind, action);
316        if let Some(decision) = decision {
317            record = record.with_decision(decision);
318        }
319        for (key, value) in ext {
320            record = record.with_ext(key, value);
321        }
322        Ok(self.client.record_surface(&record).await?)
323    }
324}
325
326/// The standing rule the kernel prepared for a decision, granted once its yes is recorded.
327struct KernelRule {
328    client: ControlClient,
329    decision: String,
330}
331
332#[async_trait]
333impl RuleCommit for KernelRule {
334    async fn commit(self: Box<Self>) -> Result<()> {
335        Ok(self.client.grant_always_allow(&self.decision).await?)
336    }
337}
338
339/// An inbox item, over a named pipe, as a request: risk high, as the item does not say.
340fn request_of(item: ApprovalItem) -> Result<ApprovalRequest> {
341    let policy = serde_json::to_value(ApprovalPolicy::new([]))
342        .map_err(|error| SurfaceError::Invalid(error.to_string()))?;
343    let value = json!({
344        "id": item.id,
345        "scope": item.scope,
346        "fingerprint": "",
347        "toolName": item.tool_name,
348        "argsRedacted": item.args_redacted,
349        "summary": item.summary,
350        "risk": ApprovalRisk::High,
351        "createdAt": item.created_at,
352        "expiresAt": item.expires_at,
353        "allowedActions": item
354            .allowed_actions
355            .into_iter()
356            .filter(|action| *action != ApprovalAction::Edit)
357            .collect::<Vec<_>>(),
358        "policy": policy,
359        "runId": item.run_id,
360        "version": item.version,
361        "state": item.state,
362    });
363    serde_json::from_value(value).map_err(|error| SurfaceError::Invalid(error.to_string()))
364}
365
366#[async_trait]
367impl Source for ControlSource {
368    fn app_name(&self) -> &str {
369        &self.app
370    }
371
372    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
373        let request = AttachRequest { user_id: Some(user.to_string()), after: None };
374        match self.client.attach(session, &request).await {
375            Ok(attached) => Ok(Some(attached.transcript)),
376            Err(error) => {
377                let error = adk_core::AdkError::from(error);
378                match error.category {
379                    ErrorCategory::NotFound => Ok(None),
380                    _ => Err(SurfaceError::Source(error)),
381                }
382            }
383        }
384    }
385
386    async fn changed(&self, max: Duration) {
387        let mut changes = self.changes();
388        // Only what happens from now on: a clone starts at the version the shared receiver
389        // saw first, which every event since has moved past.
390        changes.mark_unchanged();
391        let bus = *changes.borrow();
392        let wait =
393            if bus.live && bus.running == 0 { QUIET_IDLE.max(max) } else { max.max(QUIET_REREAD) };
394        let change = async {
395            if changes.changed().await.is_err() {
396                std::future::pending::<()>().await;
397            }
398        };
399        tokio::select! {
400            () = tokio::time::sleep(wait) => {}
401            () = change => {}
402        }
403    }
404
405    async fn requests(
406        &self,
407        _caller: &Caller,
408        session: Option<&str>,
409        open_only: bool,
410    ) -> Result<Vec<ApprovalRequest>> {
411        if let Some(inbox) = &self.inbox {
412            return inbox.list(&self.app, session, open_only).await;
413        }
414        self.client
415            .approvals()
416            .await?
417            .into_iter()
418            .filter(|item| session.is_none_or(|session| item.scope.session_id == session))
419            .map(request_of)
420            .collect()
421    }
422
423    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
424        if let Some(inbox) = &self.inbox {
425            return inbox.get(id).await;
426        }
427        Ok(self
428            .client
429            .approvals()
430            .await?
431            .into_iter()
432            .find(|item| item.id == id)
433            .map(request_of)
434            .transpose()?)
435    }
436
437    async fn decide(
438        &self,
439        id: &str,
440        expected_version: u64,
441        decision: ApprovalDecision,
442    ) -> Result<ApprovalRequest> {
443        if let Some(inbox) = &self.inbox {
444            return inbox.decide(id, expected_version, &decision).await;
445        }
446        if decision.kind == ApprovalAction::Edit {
447            return Err(SurfaceError::unsupported("editing a call over the control plane"));
448        }
449        let item = self
450            .client
451            .decide(id, expected_version, decision.kind, decision.reason.as_deref())
452            .await?;
453        let mut request = request_of(item)?;
454        // The control plane answers with the request but not its decisions: record this one,
455        // so the card says who answered.
456        request.decisions.push(decision);
457        Ok(request)
458    }
459
460    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
461        let known = |offers: &Offers| {
462            offers
463                .get(&request.id)
464                .filter(|(version, _)| *version == request.version)
465                .map(|(_, label)| label.clone())
466        };
467        if let Some(label) = known(&self.offers.lock().unwrap_or_else(|e| e.into_inner())) {
468            return label.map(|label| AlwaysAllowOffer { label });
469        }
470        // A kernel without the route, or a device's token, offers none, for good; a kernel
471        // out of reach for a moment is asked again on the next draw.
472        let label = match self.client.always_allow_offer(&request.id).await {
473            Ok(label) => label,
474            Err(error) if passing(error.category()) => {
475                tracing::debug!(error = %error, decision.id = %request.id, "Always allow could not be looked up");
476                return None;
477            }
478            Err(_) => None,
479        };
480        let mut offers = self.offers.lock().unwrap_or_else(|e| e.into_inner());
481        if offers.len() >= OFFERS {
482            offers.clear();
483        }
484        offers.insert(request.id.clone(), (request.version, label.clone()));
485        label.map(|label| AlwaysAllowOffer { label })
486    }
487
488    async fn prepare_always_allow(
489        &self,
490        _caller: &Caller,
491        request: &ApprovalRequest,
492    ) -> Result<Box<dyn RuleCommit>> {
493        self.client.prepare_always_allow(&request.id).await?;
494        Ok(Box::new(KernelRule { client: self.client.clone(), decision: request.id.clone() }))
495    }
496
497    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
498        let mut latest: BTreeMap<String, AgentState> = BTreeMap::new();
499        for process in self.processes(user).await? {
500            let run = &process.run;
501            if latest.contains_key(&run.target) {
502                continue;
503            }
504            let waiting_on_decision =
505                matches!(run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }));
506            latest.insert(
507                run.target.clone(),
508                AgentState {
509                    // The control plane does not say where an agent's commands run.
510                    shell: None,
511                    name: run.target.clone(),
512                    session_id: run.session_id.clone(),
513                    state: run.state,
514                    waiting_on_decision,
515                    wake_at: (run.state == RunState::Waiting && !waiting_on_decision)
516                        .then_some(run.not_before)
517                        .flatten(),
518                    suspended: process.meta.suspended_by.is_some(),
519                    subagent: (process.meta.kind == adk_kernel::ProcessKind::Subagent).then(|| {
520                        process
521                            .meta
522                            .labels
523                            .get(adk_kernel::SUBAGENT_NAME_LABEL)
524                            .cloned()
525                            .unwrap_or_else(|| "sub-agent".to_string())
526                    }),
527                },
528            );
529        }
530        // A removed agent leaves the roster. One listing carries every agent's state, removed
531        // ones included, so no agent is looked up on its own (spec 3.3 §5.7); a kernel that
532        // keeps no agents lists none.
533        let gone: Vec<String> = self
534            .client
535            .agents()
536            .await
537            .unwrap_or_default()
538            .into_iter()
539            .filter(|view| {
540                matches!(
541                    view.agent.state,
542                    adk_kernel::agents::AgentRecordState::Removing
543                        | adk_kernel::agents::AgentRecordState::Removed
544                )
545            })
546            .map(|view| view.agent.id)
547            .collect();
548        latest.retain(|name, _| !gone.contains(name));
549        Ok(latest.into_values().collect())
550    }
551
552    async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
553        let mut threads: BTreeMap<String, DateTime<Utc>> = BTreeMap::new();
554        for process in self.processes(user).await? {
555            if process.run.target != agent {
556                continue;
557            }
558            if let Some(session) = process.run.session_id.clone() {
559                let at = threads.entry(session).or_insert(process.run.updated_at);
560                *at = (*at).max(process.run.updated_at);
561            }
562        }
563        Ok(threads.into_iter().collect())
564    }
565
566    // The terminal changes agents through `/agent` on the kernel; this source reads them for
567    // the roster (spec 3.3 §5.7, §10 L1).
568    async fn agent_definitions(&self, user: &str) -> Result<Vec<crate::agents::AgentDetail>> {
569        let views = match self.client.agents().await {
570            Ok(views) => views,
571            // A kernel without agents of a person's own lists none.
572            Err(error)
573                if matches!(
574                    error.category(),
575                    adk_core::ErrorCategory::NotFound | adk_core::ErrorCategory::Unsupported
576                ) =>
577            {
578                return Ok(Vec::new());
579            }
580            Err(error) => return Err(error.into()),
581        };
582        let offset = *chrono::Local::now().offset();
583        Ok(views
584            .into_iter()
585            .map(|view| {
586                crate::agents::AgentDetail::of(
587                    &view.agent,
588                    view.cant_start,
589                    user,
590                    "ADK-Rust",
591                    offset,
592                )
593            })
594            .collect())
595    }
596
597    async fn agent(&self, user: &str, id: &str) -> Result<Option<crate::agents::AgentDetail>> {
598        // A removed agent has no settings; its threads are read through "Removed agents".
599        Ok(self.agent_definitions(user).await?.into_iter().find(|detail| {
600            detail.id == id
601                && !matches!(
602                    detail.state,
603                    crate::agents::AgentLife::Removed | crate::agents::AgentLife::Refused
604                )
605        }))
606    }
607
608    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
609        Ok(self.processes(user).await?.iter().any(|process| {
610            process.run.session_id.as_deref() == Some(session) && runs(process.run.state)
611        }))
612    }
613
614    async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
615        let mut failures: Vec<TurnFailure> = self
616            .processes(user)
617            .await?
618            .into_iter()
619            .filter(|process| {
620                process.run.session_id.as_deref() == Some(session)
621                    && process.run.state == RunState::Failed
622            })
623            .map(|process| TurnFailure {
624                agent: process.run.target,
625                at: process.run.updated_at,
626                error: process.run.error,
627            })
628            .collect();
629        failures.sort_by_key(|failure| failure.at);
630        Ok(failures)
631    }
632
633    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
634        Ok(self.processes(user).await?.iter().any(|process| {
635            process.run.session_id.as_deref() == Some(session)
636                && process.run.state == RunState::Waiting
637                && matches!(process.run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }))
638        }))
639    }
640
641    async fn start_turn(&self, _caller: &Caller, session: &str, text: &str) -> Result<()> {
642        let request = SpawnRequest::new(self.target.clone(), json!({ "text": text }))
643            .with_session_id(session);
644        self.client.spawn(&request).await?;
645        Ok(())
646    }
647
648    /// A message with images goes as the run's `content` (spec 3.3 §5.1).
649    async fn start_turn_images(
650        &self,
651        caller: &Caller,
652        session: &str,
653        text: &str,
654        images: &[crate::images::MessageImage],
655    ) -> Result<()> {
656        if images.is_empty() {
657            return self.start_turn(caller, session, text).await;
658        }
659        let mut content = adk_core::Content::new("user");
660        if !text.trim().is_empty() {
661            content = content.with_text(text);
662        }
663        for image in images {
664            content = content.with_inline_data(image.mime_type.clone(), image.data.clone());
665        }
666        let request = SpawnRequest::new(self.target.clone(), json!({ "content": content }))
667            .with_session_id(session);
668        self.client.spawn(&request).await?;
669        Ok(())
670    }
671
672    async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
673        let (steer_id, pid, lease_epoch) = match self.client.steer(session, text).await? {
674            SteerResponse::Accepted { steer_id, pid, lease_epoch } => (steer_id, pid, lease_epoch),
675            SteerResponse::Returned => return Ok(None),
676        };
677        let source = self.clone();
678        let (user, session) = (caller.user_id().to_string(), session.to_string());
679        Ok(Some(Box::pin(async move {
680            loop {
681                // The wait for the next change begins before the reads, so a change during
682                // them is not missed.
683                let mut changed = Box::pin(source.changed(QUIET_REREAD));
684                let _ = futures::poll!(changed.as_mut());
685                // The process first, the session after: an event the turn saved before it
686                // ended is read once the turn is seen to have ended.
687                let held = source.client.processes(&Default::default()).await.map(|processes| {
688                    processes.iter().any(|process| {
689                        process.meta.pid == pid
690                            && process.run.state == RunState::Running
691                            && process.run.lease_epoch == lease_epoch
692                    })
693                });
694                match (held, source.transcript(&user, &session).await) {
695                    (Ok(held), Ok(events)) => {
696                        let steered = crate::local::taken(&events.unwrap_or_default(), &steer_id);
697                        if steered != Steered::Returned || !held {
698                            return Ok(steered);
699                        }
700                    }
701                    // The kernel is out of reach: its stores say once it answers again.
702                    (Err(error), _) => {
703                        tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's process could not be read");
704                    }
705                    (_, Err(error)) => {
706                        tracing::debug!(error = %error, steer.id = %steer_id, "a steered message's session could not be read");
707                    }
708                }
709                changed.await;
710            }
711        })))
712    }
713
714    async fn request_call(
715        &self,
716        caller: &Caller,
717        session: &str,
718        text: &str,
719        call: adk_core::RequestedCall,
720    ) -> Result<()> {
721        // The thread's agent holds the call in its own target (spec 3.3 §7.4 rule 5): the
722        // target of the session's latest run, else this terminal's.
723        let target = self
724            .agent_of_session(caller.user_id(), session)
725            .await?
726            .unwrap_or_else(|| self.target.clone());
727        let request = SpawnRequest::new(target, json!({ "text": text, "requestedCall": call }))
728            .with_session_id(session);
729        self.client.spawn(&request).await?;
730        Ok(())
731    }
732
733    async fn stop_all(&self, _caller: &Caller, reason: &str) -> Result<()> {
734        self.client.freeze(Some(reason)).await?;
735        Ok(())
736    }
737
738    async fn resume_all(&self, _caller: &Caller) -> Result<()> {
739        self.client.unfreeze().await?;
740        Ok(())
741    }
742
743    async fn stopped(&self) -> Result<bool> {
744        Ok(self.client.health().await?.frozen)
745    }
746
747    async fn mode(&self, _user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
748        let Some(session) = session else {
749            return Ok(None);
750        };
751        match self.client.session_mode(session).await {
752            Ok(mode) => Ok(mode.and_then(|mode| mode.parse().ok())),
753            // A paired device's token, or a kernel that offers no commands, reads no mode.
754            Err(error)
755                if matches!(
756                    error.category(),
757                    ErrorCategory::Forbidden
758                        | ErrorCategory::Unauthorized
759                        | ErrorCategory::InvalidInput
760                ) =>
761            {
762                Ok(None)
763            }
764            Err(error) => Err(error.into()),
765        }
766    }
767
768    // The kernel's `/mode` opens a new thread of the person it serves.
769    fn opens_sessions(&self) -> bool {
770        true
771    }
772
773    // The REPL's `/mode`, which the kernel runs over its harness, sets it (spec 3.3 §5.2).
774    async fn set_mode(&self, _caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
775        let word = match mode {
776            HarnessMode::ReadOnly => "read-only",
777            other => other.as_str(),
778        };
779        self.client.run_command("mode", word, session).await?;
780        Ok(())
781    }
782
783    async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
784        Ok(self
785            .processes(user)
786            .await?
787            .into_iter()
788            .find(|process| process.run.session_id.as_deref() == Some(session))
789            .map(|process| process.run.target))
790    }
791
792    // The primary agent's area, where this source's turns run: with several areas, its spend
793    // today against its own limit, never the default area's (spec 3.3 §10 K3, §13 Q7).
794    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
795        let areas = match self.client.settings().await {
796            Ok(areas) => areas,
797            Err(error) => {
798                tracing::debug!(error = %error, "could not read the areas' settings; spend is not split by area");
799                Vec::new()
800            }
801        };
802        // A kernel that marks no area: the default area, or the only one.
803        let area = areas
804            .iter()
805            .find(|area| area.primary)
806            .or_else(|| {
807                areas
808                    .iter()
809                    .find(|area| area.partition.as_str() == adk_kernel::PartitionId::DEFAULT)
810            })
811            .or(match areas.as_slice() {
812                [only] => Some(only),
813                _ => None,
814            });
815        let spent = self
816            .processes(user)
817            .await?
818            .iter()
819            .filter(|process| area.is_none_or(|area| process.meta.partition == area.partition))
820            .map(|process| process.view.spend_today)
821            .sum();
822        let limit = self.daily_limit.or(area.and_then(|area| area.daily_spending_limit));
823        Ok(Some(SpendToday { spent, limit }))
824    }
825
826    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
827        let mut params = LedgerParams { from: Some(since), ..LedgerParams::default() };
828        let mut entries = Vec::new();
829        loop {
830            let page = self.client.ledger(&params).await?;
831            entries.extend(page.entries);
832            match page.next {
833                Some(next) => params.after = Some(next),
834                None => break,
835            }
836        }
837        Ok(entries)
838    }
839}