Skip to main content

adk_surface/
local.rs

1//! The in-process source (spec 3.3 §6): a kernel, a harness or a runner in the same process
2//! as the surfaces, with the session store and the approval service they write.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use adk_artifact::{ArtifactService, VersionsRequest};
10use adk_core::audit_log::AuditActor;
11use adk_core::{
12    ApprovalAction, ApprovalDecision, ApprovalRequest, ApprovalResolution, ApprovalService,
13    ApprovalState, Content, DurableRunStore, ErrorCategory, Event, GovernanceControl,
14    ImageEvidence, InboxQuery, NewRun, RequestContext, RequestedCall, RequestedVia,
15    RunCheckpointRef, RunState, SessionId, UserId,
16};
17use adk_harness::{
18    ArgSpec, Harness, HarnessMode, RuleOwner, RulePredicate, RuleSuggestion, StandingDecision,
19    StandingRule, SuggestedScope,
20};
21use adk_kernel::proc::LedgerQuery;
22use adk_kernel::{Kernel, ProcessFilter, ProcessKind, ProcessSpec, QueueClass, QuietHours};
23use adk_runner::Runner;
24use adk_session::{CreateRequest, GetRequest, SessionService};
25use async_trait::async_trait;
26use chrono::{DateTime, Utc};
27use futures::StreamExt;
28
29use crate::error::{Result, SurfaceError};
30use crate::evidence::{EvidenceBytes, EvidenceKept};
31use crate::origin::Caller;
32use crate::source::{
33    AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday, Steered, Steering, TurnFailure,
34};
35use crate::words;
36
37/// How many inbox entries one page reads.
38const INBOX_PAGE: usize = 200;
39
40/// The action a call held again names as how the person asked for it.
41const HELD_AGAIN_ACTION: &str = "held-again";
42
43/// What the agent is told of a call whose image a person changed before it left.
44#[cfg(feature = "web")]
45const IMAGE_CHANGED_REASON: &str = "The person cut the image smaller or covered more of it \
46    before it left. The call is held again with the new image for their answer.";
47
48/// The engine's source for surfaces in the same process as the agents (spec 3.3 §6): the
49/// session store the feed numbers events from, the approval service decisions go through,
50/// and whichever of an in-process [`Kernel`], a [`Harness`] and a [`Runner`] runs the turns.
51///
52/// | Part | Gives the engine |
53/// |---|---|
54/// | [`sessions`](LocalSourceBuilder::sessions) | the feed (required; a harness or runner brings its own) |
55/// | [`approvals`](LocalSourceBuilder::approvals) | decisions: the inbox and `decide` (S-I2) |
56/// | [`kernel`](LocalSourceBuilder::kernel) | agents from the process table, turns as processes, a message for the turn this replica runs (`Kernel::steer`), stop and resume through the kernel's freeze, spend and its daily cap, quiet time, the `/proc` ledger |
57/// | [`harness`](LocalSourceBuilder::harness) | the mode and `set_mode`, "Always allow" as a standing rule, turns, a message for a running turn and resuming decided calls without a kernel |
58/// | [`runner`](LocalSourceBuilder::runner) | turns, a message for a running turn (`Runner::steer`), resuming decided calls, and the runner's kill switch, for apps without a harness |
59///
60/// # Example
61///
62/// ```rust
63/// use std::sync::Arc;
64/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
65/// use adk_session::InMemorySessionService;
66/// use adk_surface::LocalSource;
67///
68/// let source = LocalSource::builder("adk-rust")
69///     .sessions(Arc::new(InMemorySessionService::new()))
70///     .approvals(Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))))
71///     .build()
72///     .unwrap();
73/// # let _ = source;
74/// ```
75#[derive(Clone)]
76pub struct LocalSource {
77    app: String,
78    sessions: Arc<dyn SessionService>,
79    approvals: Option<Arc<dyn ApprovalService>>,
80    kernel: Option<(Kernel, String)>,
81    harness: Option<Arc<Harness>>,
82    runner: Option<Arc<Runner>>,
83    governance: Option<GovernanceControl>,
84    daily_limit: Option<u64>,
85    agents: Option<adk_kernel::agents::AgentsHandle>,
86    artifacts: Option<Arc<dyn ArtifactService>>,
87    runs: Option<Arc<dyn DurableRunStore>>,
88    eval_fixtures: Option<std::path::PathBuf>,
89    /// The rules "Always allow" prepared, granted as their decisions resolve.
90    prepared: Arc<PreparedRules>,
91    /// The turns a harness or runner ran here that ended in an error; a kernel keeps its own.
92    failed: Arc<FailedTurnLog>,
93}
94
95impl fmt::Debug for LocalSource {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.debug_struct("LocalSource")
98            .field("app", &self.app)
99            .field("approvals", &self.approvals.is_some())
100            .field("kernel", &self.kernel.as_ref().map(|(_, target)| target))
101            .field("harness", &self.harness.is_some())
102            .field("runner", &self.runner.is_some())
103            .finish_non_exhaustive()
104    }
105}
106
107/// Builds a [`LocalSource`].
108#[derive(Default)]
109pub struct LocalSourceBuilder {
110    app: String,
111    sessions: Option<Arc<dyn SessionService>>,
112    approvals: Option<Arc<dyn ApprovalService>>,
113    kernel: Option<(Kernel, String)>,
114    harness: Option<Arc<Harness>>,
115    runner: Option<Arc<Runner>>,
116    governance: Option<GovernanceControl>,
117    daily_limit: Option<u64>,
118    agents: Option<adk_kernel::agents::AgentsHandle>,
119    artifacts: Option<Arc<dyn ArtifactService>>,
120    runs: Option<Arc<dyn DurableRunStore>>,
121    eval_fixtures: Option<std::path::PathBuf>,
122}
123
124impl fmt::Debug for LocalSourceBuilder {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.debug_struct("LocalSourceBuilder").field("app", &self.app).finish_non_exhaustive()
127    }
128}
129
130impl LocalSourceBuilder {
131    /// The session store the agents write.
132    #[must_use]
133    pub fn sessions(mut self, sessions: Arc<dyn SessionService>) -> Self {
134        self.sessions = Some(sessions);
135        self
136    }
137
138    /// The approval service held calls are submitted to.
139    #[must_use]
140    pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
141        self.approvals = Some(approvals);
142        self
143    }
144
145    /// An in-process kernel, whose processes of `target` run the turns surfaces send.
146    #[must_use]
147    pub fn kernel(mut self, kernel: Kernel, target: impl Into<String>) -> Self {
148        self.kernel = Some((kernel, target.into()));
149        self
150    }
151
152    /// A harness: its runner's sessions and kill switch unless set, its modes and standing
153    /// rules.
154    #[must_use]
155    pub fn harness(mut self, harness: Arc<Harness>) -> Self {
156        self.harness = Some(harness);
157        self
158    }
159
160    /// A runner for apps without a harness: its sessions and kill switch unless set.
161    #[must_use]
162    pub fn runner(mut self, runner: Arc<Runner>) -> Self {
163        self.runner = Some(runner);
164        self
165    }
166
167    /// The kill switch "Stop all" freezes when there is no kernel.
168    #[must_use]
169    pub fn governance(mut self, governance: GovernanceControl) -> Self {
170        self.governance = Some(governance);
171        self
172    }
173
174    /// The daily spending limit in micro-USD, over the one in force in the kernel's area of
175    /// this source's turns.
176    #[must_use]
177    pub fn daily_limit(mut self, micro_usd: u64) -> Self {
178        self.daily_limit = Some(micro_usd);
179        self
180    }
181
182    /// The agent table of a kernel this source does not run turns on — a kernel built after
183    /// the source, such as the one `adk-rust up` serves the terminal's commands for — so
184    /// "Always allow" on an added agent's card makes a rule for that agent alone (spec 3.3
185    /// S-I19). A [`kernel`](Self::kernel) brings its own.
186    ///
187    /// # Example
188    ///
189    /// ```rust
190    /// use adk_kernel::agents::AgentsHandle;
191    /// use adk_session::InMemorySessionService;
192    ///
193    /// let source = adk_surface::LocalSource::builder("adk-rust")
194    ///     .sessions(std::sync::Arc::new(InMemorySessionService::new()))
195    ///     .agents(AgentsHandle::new())
196    ///     .build()
197    ///     .unwrap();
198    /// # let _ = source;
199    /// ```
200    #[must_use]
201    pub fn agents(mut self, agents: adk_kernel::agents::AgentsHandle) -> Self {
202        self.agents = Some(agents);
203        self
204    }
205
206    /// The artifact service a held call's evidence images live in (spec 3.7 §8.2): cards show
207    /// them, each checked against its digest, and a person may cut one smaller or cover more
208    /// of it before it leaves.
209    ///
210    /// # Example
211    ///
212    /// ```rust
213    /// use std::sync::Arc;
214    /// use adk_artifact::InMemoryArtifactService;
215    /// use adk_session::InMemorySessionService;
216    ///
217    /// let source = adk_surface::LocalSource::builder("desk")
218    ///     .sessions(Arc::new(InMemorySessionService::new()))
219    ///     .artifacts(Arc::new(InMemoryArtifactService::new()))
220    ///     .build()
221    ///     .unwrap();
222    /// # let _ = source;
223    /// ```
224    #[must_use]
225    pub fn artifacts(mut self, artifacts: Arc<dyn ArtifactService>) -> Self {
226        self.artifacts = Some(artifacts);
227        self
228    }
229
230    /// The durable run store whose runs wait on decisions: a decision whose run ended while it
231    /// waits says its answer is used when the agent picks the thread up again (spec 3.7 §8.2,
232    /// board choice A12).
233    #[must_use]
234    pub fn runs(mut self, runs: Arc<dyn DurableRunStore>) -> Self {
235        self.runs = Some(runs);
236        self
237    }
238
239    /// The folder labelled examples are saved under (spec 3.7 §8.2, board choice V13): the
240    /// annotated viewer writes `adk-eval` cases to the `.test.json` files in it, and each
241    /// case's image beside its file, so `cargo adk eval` reads them. Without it, the viewer
242    /// shows answers and exports them but saves no examples.
243    ///
244    /// # Example
245    ///
246    /// ```rust
247    /// use std::sync::Arc;
248    /// use adk_artifact::InMemoryArtifactService;
249    /// use adk_session::InMemorySessionService;
250    ///
251    /// let source = adk_surface::LocalSource::builder("desk")
252    ///     .sessions(Arc::new(InMemorySessionService::new()))
253    ///     .artifacts(Arc::new(InMemoryArtifactService::new()))
254    ///     .eval_fixtures(std::env::temp_dir().join("evals"))
255    ///     .build()
256    ///     .unwrap();
257    /// # let _ = source;
258    /// ```
259    #[must_use]
260    pub fn eval_fixtures(mut self, root: impl Into<std::path::PathBuf>) -> Self {
261        self.eval_fixtures = Some(root.into());
262        self
263    }
264
265    /// The source.
266    ///
267    /// # Errors
268    ///
269    /// Returns `surface.invalid` when no session store was given and no harness or runner
270    /// brings one.
271    pub fn build(self) -> Result<LocalSource> {
272        let runner_sessions = self
273            .harness
274            .as_ref()
275            .map(|harness| harness.runner().session_service().clone())
276            .or_else(|| self.runner.as_ref().map(|runner| runner.session_service().clone()));
277        let sessions = self.sessions.or(runner_sessions).ok_or_else(|| {
278            SurfaceError::Invalid(
279                "a local source needs the session store the agents write: pass sessions(), a \
280                 harness or a runner"
281                    .into(),
282            )
283        })?;
284        let governance = self.governance.or_else(|| {
285            self.harness
286                .as_ref()
287                .map(|harness| harness.runner().governance().clone())
288                .or_else(|| self.runner.as_ref().map(|runner| runner.governance().clone()))
289        });
290        // A rule "Always allow" prepared is granted as its author's yes resolves the decision,
291        // before the call it allowed resumes: on a kernel the decision itself wakes the run
292        // (spec 3.3 §7.2).
293        let prepared = Arc::new(PreparedRules::default());
294        if let Some(harness) = &self.harness {
295            let decided_by = self
296                .approvals
297                .clone()
298                .or_else(|| harness.agent().runtime().approval_service().cloned());
299            if let Some(service) = decided_by {
300                service.add_resolution(prepared.clone());
301            }
302        }
303        Ok(LocalSource {
304            app: self.app,
305            sessions,
306            approvals: self.approvals,
307            kernel: self.kernel,
308            harness: self.harness,
309            runner: self.runner,
310            governance,
311            daily_limit: self.daily_limit,
312            agents: self.agents,
313            artifacts: self.artifacts,
314            runs: self.runs,
315            eval_fixtures: self.eval_fixtures,
316            prepared,
317            failed: Arc::default(),
318        })
319    }
320}
321
322impl LocalSource {
323    /// A builder for the sessions of `app_name`.
324    pub fn builder(app_name: impl Into<String>) -> LocalSourceBuilder {
325        LocalSourceBuilder { app: app_name.into(), ..LocalSourceBuilder::default() }
326    }
327
328    /// The kernel's agent table: the kernel's own, else the handle's while its kernel lives.
329    fn agent_table(&self) -> Option<adk_kernel::agents::Agents> {
330        match &self.kernel {
331            Some((kernel, _)) => Some(kernel.agents().clone()),
332            None => self.agents.as_ref().and_then(adk_kernel::agents::AgentsHandle::get),
333        }
334    }
335
336    /// The bytes of an evidence image, read at its exact version and checked against its
337    /// digest; `None` when it is no longer kept.
338    async fn evidence_bytes(&self, image: &ImageEvidence) -> Result<Option<Vec<u8>>> {
339        let artifacts = self
340            .artifacts
341            .as_ref()
342            .ok_or_else(|| SurfaceError::unsupported("showing a decision's images"))?;
343        crate::evidence::load_image(artifacts.as_ref(), image).await
344    }
345
346    fn approvals(&self) -> Result<&Arc<dyn ApprovalService>> {
347        self.approvals
348            .as_ref()
349            .ok_or_else(|| SurfaceError::unsupported("decisions without an approval service"))
350    }
351
352    fn ids(user: &str, session: &str) -> Result<(UserId, SessionId)> {
353        let user = UserId::new(user).map_err(|error| SurfaceError::Invalid(error.to_string()))?;
354        let session =
355            SessionId::new(session).map_err(|error| SurfaceError::Invalid(error.to_string()))?;
356        Ok((user, session))
357    }
358
359    /// The user's processes on the kernel, newest change first.
360    async fn processes(&self, user: &str) -> Result<Vec<adk_kernel::Process>> {
361        let Some((kernel, _)) = &self.kernel else {
362            return Ok(Vec::new());
363        };
364        let mut processes: Vec<_> = kernel
365            .processes()
366            .ps(ProcessFilter::default())
367            .await?
368            .into_iter()
369            .filter(|process| process.run.user_id == user && process.run.app_name == self.app)
370            .collect();
371        processes.sort_by_key(|process| std::cmp::Reverse(process.run.updated_at));
372        Ok(processes)
373    }
374
375    /// The classes the kernel's mounted drivers declare `tool` of; a name two drivers share
376    /// has both (spec 3.2 K-I9).
377    fn driver_classes(&self, tool: &str) -> Vec<adk_kernel::drivers::EffectClass> {
378        let Some(drivers) = self.kernel.as_ref().and_then(|(kernel, _)| kernel.drivers()) else {
379            return Vec::new();
380        };
381        drivers
382            .mounted()
383            .iter()
384            .filter_map(|id| drivers.record(id))
385            .map(|record| record.manifest.class_of(tool))
386            .collect()
387    }
388
389    async fn ensure_session(&self, user: &str, session: &str) -> Result<()> {
390        if self.transcript(user, session).await?.is_some() {
391            return Ok(());
392        }
393        let created = self
394            .sessions
395            .create(CreateRequest {
396                app_name: self.app.clone(),
397                user_id: user.to_string(),
398                session_id: Some(session.to_string()),
399                state: Default::default(),
400            })
401            .await;
402        match created {
403            Ok(_) => Ok(()),
404            Err(error) if error.category == ErrorCategory::Conflict => Ok(()),
405            Err(error) => Err(SurfaceError::Source(error)),
406        }
407    }
408
409    /// Starts a turn of the session through the harness or the runner and runs it in the
410    /// background; `text` empty resumes the session's decided calls. With `caller`, the turn
411    /// carries the caller's identity, so the harness applies the session's mode and standing
412    /// rules as it does to a request a server admitted (spec 3.3 §6).
413    ///
414    /// Returns once the turn is registered as running, so [`busy`](Source::busy) sees it and
415    /// input queued behind it waits for it (S-I4).
416    async fn run_turn(
417        &self,
418        user: &str,
419        session: &str,
420        text: &str,
421        caller: Option<&Caller>,
422    ) -> Result<()> {
423        let (user_id, session_id) = Self::ids(user, session)?;
424        let text = text.to_string();
425        let context =
426            caller.filter(|caller| caller.user_id() == user).map(|caller| RequestContext {
427                user_id: caller.user_id().to_string(),
428                scopes: caller.groups.clone(),
429                metadata: Default::default(),
430            });
431        let stream = if let Some(harness) = &self.harness {
432            match (text.is_empty(), context) {
433                (true, None) => harness.resume(&user_id, &session_id).await,
434                (true, Some(context)) => harness.resume_as(&user_id, &session_id, context).await,
435                (false, None) => harness.send(&user_id, &session_id, text).await,
436                (false, Some(context)) => {
437                    harness.send_as(&user_id, &session_id, text, context).await
438                }
439            }
440        } else if let Some(runner) = &self.runner {
441            let content = if text.is_empty() {
442                Content::new("user")
443            } else {
444                Content::new("user").with_text(text)
445            };
446            let config = context.map(|context| adk_core::RunConfig {
447                request_context: Some(context),
448                ..runner.run_config().clone()
449            });
450            runner.run_with_config(user_id, session_id.clone(), content, config).await
451        } else {
452            return Err(SurfaceError::unsupported(
453                "sending a message without a kernel, harness or runner",
454            ));
455        };
456        let stream = stream?;
457        let turn = self.turn_of(user, session);
458        tokio::spawn(drain(stream, self.failed.clone(), turn));
459        Ok(())
460    }
461
462    /// Whose turn a stream started here runs: the harness's agent, else the app's runner.
463    fn turn_of(&self, user: &str, session: &str) -> TurnOf {
464        TurnOf {
465            user: user.to_string(),
466            session: session.to_string(),
467            agent: match &self.harness {
468                Some(harness) => harness.agent().info().name.clone(),
469                None => self.app.clone(),
470            },
471        }
472    }
473
474    /// The harness's pending call for `request`, with the standing rule "Always allow" makes
475    /// and the words that say what it covers.
476    async fn always_allow_rule(
477        &self,
478        caller: Option<&Caller>,
479        request: &ApprovalRequest,
480    ) -> Option<(String, StandingRule, adk_core::ToolConfirmationRequest)> {
481        let harness = self.harness.as_ref()?;
482        let runtime = harness.agent().runtime();
483        let pending = runtime.approval_store().pending(&request.scope).await.ok()?;
484        let held = pending.into_iter().find(|entry| entry.fingerprint == request.fingerprint)?;
485        // A call a person asked for through a drawn form is never made a standing rule
486        // (spec 3.3 §7.4 rule 5, wave 4 decision 12).
487        if held
488            .request
489            .function_call_id
490            .as_deref()
491            .is_some_and(adk_core::RequestedCall::is_requested_id)
492        {
493            return None;
494        }
495        // A file write: every file write in its folder (spec 3.3 §8.2). A file change no
496        // folder rule covers — a delete or a move — is asked about every time.
497        let suggestion = match harness.agent().folder_suggestion(&held.request) {
498            Some(folder) => folder,
499            None => StandingRule::suggestions(&held.request).into_iter().find(|suggestion| {
500                !suggestion
501                    .predicates
502                    .iter()
503                    .any(|predicate| matches!(predicate, RulePredicate::PathWithin { .. }))
504            })?,
505        };
506        let label = always_allow_label(&suggestion);
507        let created_by = caller.map_or_else(
508            || adk_core::principal::SubjectRef::human(request.scope.user_id.clone()),
509            |caller| caller.subject.clone(),
510        );
511        let owner = RuleOwner {
512            app_name: request.scope.app_name.clone(),
513            user_id: request.scope.user_id.clone(),
514            subject_kind: adk_core::SubjectKind::Human,
515            session_id: request.scope.session_id.clone(),
516            created_by,
517        };
518        let mut rule = harness
519            .agent()
520            .rule_for_held_call(&held.request, suggestion, StandingDecision::Allow, &owner)
521            .ok()?;
522        // "Always allow" on an added agent's card makes a rule for that agent alone (spec 3.3
523        // S-I19). When the agent table cannot be read, no rule is made: one for every agent
524        // would let the others do what the person allowed this one.
525        if let (Some(table), Some(acting)) = (self.agent_table(), &request.acting) {
526            match table.get(&crate::project::agent_name(request)).await {
527                Ok(Some(_)) => rule.agent = Some(acting.agent.id.as_str().to_string()),
528                Ok(None) => {}
529                Err(error) => {
530                    tracing::warn!(approval.id = %request.id, error = %error, "could not tell whose rule \"Always allow\" makes; none is offered");
531                    return None;
532                }
533            }
534        }
535        Some((label, rule, held.request))
536    }
537}
538
539impl LocalSource {
540    /// The kernel target of `agent`: the source's own for the primary agent, else the added
541    /// agent's id.
542    fn target_of(&self, agent: &str) -> Option<String> {
543        let (_, own) = self.kernel.as_ref()?;
544        Some(if agent == adk_harness::PRIMARY_AGENT_STAMP || agent == own || agent == self.app {
545            own.clone()
546        } else {
547            agent.to_string()
548        })
549    }
550
551    /// The target a message to `session` goes to (spec 3.3 §5.7 "Threads"): the agent its
552    /// stamp names, before the first run the agent of its latest run, else the primary agent.
553    async fn target_for(&self, user: &str, session: &str) -> Result<String> {
554        let own = self.kernel.as_ref().map(|(_, target)| target.clone()).unwrap_or_default();
555        Ok(match self.agent_of_session(user, session).await? {
556            Some(agent) => self.target_of(&agent).unwrap_or(own),
557            None => own,
558        })
559    }
560}
561
562/// The primary agent's name on screen, as the suggesting agent of an added one.
563const PRIMARY_NAME: &str = "ADK-Rust";
564
565/// The host's offset from UTC now: dates on screen are the host's.
566fn local_offset() -> chrono::FixedOffset {
567    *chrono::Local::now().offset()
568}
569
570impl LocalSource {
571    /// Applies `action` with the digest its preview showed, through the kernel's agent table.
572    async fn apply_agent(
573        &self,
574        caller: &Caller,
575        action: adk_kernel::agents::AgentAction,
576        digest: &str,
577    ) -> Result<crate::agents::AgentDetail> {
578        let (kernel, _) =
579            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
580        match crate::agents::local::apply(
581            kernel.agents(),
582            caller,
583            action,
584            digest,
585            PRIMARY_NAME,
586            local_offset(),
587        )
588        .await?
589        {
590            crate::agents::local::Applied::Agent(detail) => Ok(*detail),
591            crate::agents::local::Applied::Removed(_) => {
592                Err(SurfaceError::Invalid("the agent was removed".into()))
593            }
594        }
595    }
596}
597
598/// "Always allow …" for the rule `suggestion` makes, saying all it covers: the command
599/// prefix, the file writes in the folder or the whole workspace, the site, or the tool with
600/// any arguments, in every session or this one, and that commands running project scripts
601/// allow whatever they do (spec 3.3 §8.2, spec 3.1 §7.5).
602fn always_allow_label(suggestion: &RuleSuggestion) -> String {
603    let (label, covers) = match suggestion.predicates.first() {
604        Some(RulePredicate::ShellPrefix { tokens, .. }) => {
605            (words::ALWAYS_ALLOW_FOR_THIS_COMMAND, format!("{} …", tokens.join(" ")))
606        }
607        Some(RulePredicate::WritesWithin { dir }) if dir == "." => (
608            words::ALWAYS_ALLOW_FOR_THIS_FOLDER,
609            "file writes anywhere in the workspace".to_string(),
610        ),
611        Some(RulePredicate::WritesWithin { dir }) => {
612            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, format!("file writes anywhere in {dir}/"))
613        }
614        Some(RulePredicate::PathWithin { dir, .. }) if dir == "." => {
615            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, "anywhere in the workspace".to_string())
616        }
617        Some(RulePredicate::PathWithin { dir, .. }) => {
618            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, format!("anywhere in {dir}/"))
619        }
620        Some(RulePredicate::Arg(ArgSpec::DomainIn { domains, .. })) => {
621            (words::ALWAYS_ALLOW_FOR_THIS_SITE, format!("any page on {}", domains.join(", ")))
622        }
623        Some(RulePredicate::Arg(ArgSpec::Equals { value, .. })) => (
624            words::ALWAYS_ALLOW_FOR_THIS_SITE,
625            format!("{} on {}", suggestion.tool, value.as_str().unwrap_or_default()),
626        ),
627        // Any other condition on the arguments, and none: the tool, with any arguments.
628        Some(RulePredicate::Arg(_)) | None => {
629            (words::ALWAYS_ALLOW_FOR_THIS_PERSON, format!("{} with any arguments", suggestion.tool))
630        }
631    };
632    words::always_allow_covering(
633        label,
634        &covers,
635        suggestion.scope == SuggestedScope::User,
636        suggestion.runs_scripts,
637    )
638}
639
640/// What `events`, a session's, say became of the steering message `steer_id`: delivered as
641/// the event whose marker carries the id, else handed back.
642pub(crate) fn taken(events: &[Event], steer_id: &str) -> Steered {
643    let event = events.iter().find(|event| {
644        event.actions.steering.as_ref().is_some_and(|marker| marker.steer_id == steer_id)
645    });
646    match event {
647        Some(event) => Steered::Delivered { event_id: event.id.clone() },
648        None => Steered::Returned,
649    }
650}
651
652/// Runs a turn's stream to its end, so its events reach the session store; a turn that ends
653/// in an error is recorded in `failed` for the thread to show.
654async fn drain(mut stream: adk_core::EventStream, failed: Arc<FailedTurnLog>, turn: TurnOf) {
655    while let Some(event) = stream.next().await {
656        if let Err(error) = event {
657            tracing::warn!(session.id = %turn.session, error = %error, "a turn a surface started failed");
658            failed.record(turn, error.to_string());
659            break;
660        }
661    }
662}
663
664/// Whose turn a drained stream runs: the user, the session and the agent.
665struct TurnOf {
666    user: String,
667    session: String,
668    agent: String,
669}
670
671/// The most sessions whose failed turns are kept in memory; past it the record starts again.
672const FAILED_SESSIONS: usize = 1_024;
673
674/// The most failed turns kept for one session: its latest.
675const FAILED_PER_SESSION: usize = 16;
676
677/// The turns a harness or runner ran in this process that ended in an error, by user and
678/// session. The session holds no event for a failed model call, so this is what the thread
679/// reads; it lasts as long as the process.
680#[derive(Default)]
681struct FailedTurnLog {
682    by_session: std::sync::Mutex<std::collections::HashMap<(String, String), Vec<TurnFailure>>>,
683}
684
685impl FailedTurnLog {
686    fn record(&self, turn: TurnOf, error: String) {
687        let mut by_session = self.by_session.lock().unwrap_or_else(|e| e.into_inner());
688        let key = (turn.user, turn.session);
689        if by_session.len() >= FAILED_SESSIONS && !by_session.contains_key(&key) {
690            by_session.clear();
691        }
692        let failures = by_session.entry(key).or_default();
693        if failures.len() >= FAILED_PER_SESSION {
694            failures.remove(0);
695        }
696        failures.push(TurnFailure { agent: turn.agent, at: Utc::now(), error: Some(error) });
697    }
698
699    fn of(&self, user: &str, session: &str) -> Vec<TurnFailure> {
700        self.by_session
701            .lock()
702            .unwrap_or_else(|e| e.into_inner())
703            .get(&(user.to_string(), session.to_string()))
704            .cloned()
705            .unwrap_or_default()
706    }
707}
708
709/// A standing rule granted once the decision it was made for approved the call, through the
710/// harness, so `harness.rule.created` is recorded before the rule is stored (spec 3.1 §7.5,
711/// §9.3).
712struct GrantRule {
713    harness: Arc<Harness>,
714    rule: StandingRule,
715    /// The held call the rule was made from.
716    from: adk_core::ToolConfirmationRequest,
717    /// The surface it was made on, such as `web`.
718    surface: String,
719}
720
721impl GrantRule {
722    async fn grant(self) -> Result<()> {
723        self.harness.agent().grant_rule(self.rule, &self.surface, Some(&self.from)).await?;
724        Ok(())
725    }
726}
727
728/// The rules "Always allow" prepared, by the decision each waits for. The approval service
729/// grants one as its author's yes resolves the decision ([`ApprovalResolution`]), before the
730/// outcome reaches the call, so the turn the call resumes already runs under the rule.
731#[derive(Default)]
732struct PreparedRules {
733    by_decision: std::sync::Mutex<std::collections::HashMap<String, Arc<PreparedRule>>>,
734}
735
736impl fmt::Debug for PreparedRules {
737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738        let waiting = self.by_decision.lock().unwrap_or_else(|e| e.into_inner()).len();
739        f.debug_struct("PreparedRules").field("waiting", &waiting).finish()
740    }
741}
742
743/// One prepared rule: who answered, the decision's version then, and the grant, which the
744/// decision's resolution or the engine's commit takes, whichever comes first.
745struct PreparedRule {
746    author: String,
747    version: u64,
748    grant: tokio::sync::Mutex<Option<GrantRule>>,
749}
750
751impl PreparedRules {
752    /// Forgets `rule` as the one prepared for `decision`, unless another replaced it.
753    fn forget(&self, decision: &str, rule: &Arc<PreparedRule>) {
754        let mut by_decision = self.by_decision.lock().unwrap_or_else(|e| e.into_inner());
755        if by_decision.get(decision).is_some_and(|prepared| Arc::ptr_eq(prepared, rule)) {
756            by_decision.remove(decision);
757        }
758    }
759}
760
761#[async_trait]
762impl ApprovalResolution for PreparedRules {
763    async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
764        let prepared =
765            self.by_decision.lock().unwrap_or_else(|e| e.into_inner()).get(&request.id).cloned();
766        let Some(prepared) = prepared else { return };
767        // Only the author's own yes, at the version it was prepared for, grants the rule: an
768        // answer that lost, someone else's yes or a later "Allow once" grants nothing.
769        if request.state != ApprovalState::Approved
770            || decision.kind != ApprovalAction::Approve
771            || decision.approver.id != prepared.author
772            || request.version != prepared.version + 1
773        {
774            return;
775        }
776        self.forget(&request.id, &prepared);
777        let grant = prepared.grant.lock().await.take();
778        if let Some(grant) = grant
779            && let Err(error) = grant.grant().await
780        {
781            tracing::warn!(error = %error, decision.id = %request.id, "the call was allowed once; its standing rule could not be created");
782        }
783    }
784}
785
786/// The engine's hold on a prepared rule: its commit grants the rule unless the decision's
787/// resolution did; dropped uncommitted, the rule is no longer prepared.
788struct PreparedCommit {
789    rules: Arc<PreparedRules>,
790    decision: String,
791    rule: Arc<PreparedRule>,
792}
793
794#[async_trait]
795impl RuleCommit for PreparedCommit {
796    async fn commit(self: Box<Self>) -> Result<()> {
797        let grant = self.rule.grant.lock().await.take();
798        match grant {
799            Some(grant) => grant.grant().await,
800            None => Ok(()),
801        }
802    }
803}
804
805impl Drop for PreparedCommit {
806    fn drop(&mut self) {
807        self.rules.forget(&self.decision, &self.rule);
808    }
809}
810
811#[async_trait]
812impl Source for LocalSource {
813    fn app_name(&self) -> &str {
814        &self.app
815    }
816
817    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
818        let found = self
819            .sessions
820            .get(GetRequest {
821                app_name: self.app.clone(),
822                user_id: user.to_string(),
823                session_id: session.to_string(),
824                num_recent_events: None,
825                after: None,
826            })
827            .await;
828        match found {
829            Ok(session) => Ok(Some(session.events().all())),
830            Err(error) if error.category == ErrorCategory::NotFound => Ok(None),
831            Err(error) if error.category == ErrorCategory::InvalidInput => Ok(None),
832            Err(error) => Err(SurfaceError::Source(error)),
833        }
834    }
835
836    async fn changed(&self, max: Duration) {
837        match &self.kernel {
838            Some((kernel, _)) => {
839                let mut events = kernel.events();
840                tokio::select! {
841                    _ = tokio::time::sleep(max) => {}
842                    _ = events.recv() => {}
843                }
844            }
845            None => tokio::time::sleep(max).await,
846        }
847    }
848
849    async fn requests(
850        &self,
851        caller: &Caller,
852        session: Option<&str>,
853        open_only: bool,
854    ) -> Result<Vec<ApprovalRequest>> {
855        let Some(approvals) = &self.approvals else {
856            return Ok(Vec::new());
857        };
858        let states =
859            if open_only { vec![ApprovalState::Pending] } else { ApprovalState::ALL.to_vec() };
860        let mut query = InboxQuery::for_approver(caller.subject.clone(), caller.groups.clone())
861            .with_states(states)
862            .with_app_name(self.app.clone())
863            .with_limit(INBOX_PAGE);
864        // A session is the caller's: another user's session with the same ID stays out.
865        if let Some(session) = session {
866            query = query.with_user_id(caller.user_id()).with_session_id(session);
867        }
868        let mut requests = Vec::new();
869        loop {
870            let page = approvals.inbox(query.clone()).await?;
871            requests.extend(page.items);
872            match page.next_cursor {
873                Some(cursor) => query = query.with_cursor(Some(cursor)),
874                None => break,
875            }
876        }
877        Ok(requests)
878    }
879
880    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
881        Ok(self.approvals()?.get(id).await?)
882    }
883
884    async fn decide(
885        &self,
886        id: &str,
887        expected_version: u64,
888        decision: ApprovalDecision,
889    ) -> Result<ApprovalRequest> {
890        Ok(self.approvals()?.decide(id, expected_version, decision).await?)
891    }
892
893    async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
894        self.resume_decided(request, None).await
895    }
896
897    async fn evidence_kept(&self, request: &ApprovalRequest) -> Vec<EvidenceKept> {
898        let images = crate::evidence::images(request);
899        let Some(artifacts) = &self.artifacts else {
900            return vec![EvidenceKept::Unknown; images.len()];
901        };
902        let mut kept = Vec::with_capacity(images.len());
903        for image in images {
904            let at = &image.artifact;
905            let versions = artifacts
906                .versions(VersionsRequest {
907                    app_name: at.app_name.clone(),
908                    user_id: at.user_id.clone(),
909                    session_id: at.session_id.clone(),
910                    file_name: at.file_name.clone(),
911                })
912                .await;
913            kept.push(match versions {
914                Ok(found) if found.versions.contains(&at.version) => EvidenceKept::Kept,
915                Ok(_) => EvidenceKept::Deleted,
916                Err(error) if error.is_not_found() => EvidenceKept::Deleted,
917                Err(error) => {
918                    tracing::warn!(error = %error, decision.id = %request.id, "an evidence image's state could not be read");
919                    EvidenceKept::Unknown
920                }
921            });
922        }
923        kept
924    }
925
926    async fn vision_answers(&self, user: &str, session: &str) -> Result<Vec<serde_json::Value>> {
927        let Some(artifacts) = &self.artifacts else { return Ok(Vec::new()) };
928        let names = artifacts
929            .list(adk_artifact::ListRequest {
930                app_name: self.app.clone(),
931                user_id: user.to_string(),
932                session_id: session.to_string(),
933            })
934            .await?
935            .file_names;
936        let mut records = Vec::new();
937        for name in names.iter().filter(|name| {
938            name.starts_with(crate::viewer::VISION_ANSWER_PREFIX) && name.ends_with(".json")
939        }) {
940            let loaded = artifacts
941                .load(adk_artifact::LoadRequest {
942                    app_name: self.app.clone(),
943                    user_id: user.to_string(),
944                    session_id: session.to_string(),
945                    file_name: name.clone(),
946                    version: None,
947                })
948                .await?;
949            let data = match loaded.part {
950                adk_core::Part::InlineData { data, .. } => data,
951                adk_core::Part::Text { text } => text.into_bytes(),
952                _ => continue,
953            };
954            match serde_json::from_slice::<serde_json::Value>(&data) {
955                Ok(record) => records.push(record),
956                Err(error) => {
957                    tracing::warn!(error = %error, artifact.name = %name, "an answer record is not JSON; it is not shown");
958                }
959            }
960        }
961        records.sort_by(|a, b| {
962            let at = |record: &serde_json::Value| {
963                record.get("at").and_then(serde_json::Value::as_str).unwrap_or_default().to_string()
964            };
965            at(a).cmp(&at(b))
966        });
967        Ok(records)
968    }
969
970    fn keeps_vision_answers(&self) -> bool {
971        self.artifacts.is_some()
972    }
973
974    async fn vision_image(
975        &self,
976        user: &str,
977        session: &str,
978        digest: &str,
979    ) -> Result<Option<EvidenceBytes>> {
980        let artifacts = self
981            .artifacts
982            .as_ref()
983            .ok_or_else(|| SurfaceError::unsupported("showing a session's images"))?;
984        let Some(hex) = digest.strip_prefix("sha256:") else {
985            // An image the session holds by name, as a vision tool was called with it.
986            let loaded = artifacts
987                .load(adk_artifact::LoadRequest {
988                    app_name: self.app.clone(),
989                    user_id: user.to_string(),
990                    session_id: session.to_string(),
991                    file_name: digest.to_string(),
992                    version: None,
993                })
994                .await;
995            return match loaded {
996                Ok(loaded) => Ok(match loaded.part {
997                    adk_core::Part::InlineData { mime_type, data, .. }
998                        if mime_type.starts_with("image/") =>
999                    {
1000                        Some(EvidenceBytes { mime_type, bytes: data })
1001                    }
1002                    _ => None,
1003                }),
1004                Err(error) if error.is_not_found() => Ok(None),
1005                Err(error) => Err(error.into()),
1006            };
1007        };
1008        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
1009            return Ok(None);
1010        }
1011        for (extension, mime) in [
1012            ("png", "image/png"),
1013            ("jpeg", "image/jpeg"),
1014            ("webp", "image/webp"),
1015            ("gif", "image/gif"),
1016        ] {
1017            let loaded = artifacts
1018                .load(adk_artifact::LoadRequest {
1019                    app_name: self.app.clone(),
1020                    user_id: user.to_string(),
1021                    session_id: session.to_string(),
1022                    file_name: format!("vision-{hex}.{extension}"),
1023                    version: None,
1024                })
1025                .await;
1026            let part = match loaded {
1027                Ok(loaded) => loaded.part,
1028                Err(error) if error.is_not_found() => continue,
1029                Err(error) => return Err(error.into()),
1030            };
1031            let adk_core::Part::InlineData { data, .. } = part else { continue };
1032            if crate::evidence::digest_of(&data) != digest {
1033                tracing::warn!(image.digest = %digest, "a session image does not match its digest; it is not shown");
1034                return Err(SurfaceError::Invalid(
1035                    "the stored image does not match its digest; it is not shown".into(),
1036                ));
1037            }
1038            return Ok(Some(EvidenceBytes { mime_type: mime.to_string(), bytes: data }));
1039        }
1040        Ok(None)
1041    }
1042
1043    async fn example_files(&self, _user: &str) -> Result<Option<Vec<String>>> {
1044        let Some(root) = &self.eval_fixtures else { return Ok(None) };
1045        let mut files = Vec::new();
1046        let mut pending = vec![root.clone()];
1047        while let Some(dir) = pending.pop() {
1048            let Ok(entries) = std::fs::read_dir(&dir) else { continue };
1049            for entry in entries.flatten() {
1050                let path = entry.path();
1051                if path.is_dir() {
1052                    // Fixture images live beside their files; four levels is plenty.
1053                    if path.strip_prefix(root).map_or(0, |p| p.components().count()) < 4 {
1054                        pending.push(path);
1055                    }
1056                } else if let Ok(relative) = path.strip_prefix(root) {
1057                    let relative = relative.to_string_lossy().replace('\\', "/");
1058                    if relative.ends_with(".test.json") {
1059                        files.push(relative);
1060                    }
1061                }
1062            }
1063        }
1064        files.sort();
1065        Ok(Some(files))
1066    }
1067
1068    async fn example_set(&self, _user: &str, file: &str) -> Result<Option<serde_json::Value>> {
1069        let root = self
1070            .eval_fixtures
1071            .as_ref()
1072            .ok_or_else(|| SurfaceError::unsupported("saving labelled examples"))?;
1073        crate::viewer::check_file(file).map_err(SurfaceError::Invalid)?;
1074        match std::fs::read(root.join(file)) {
1075            Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| {
1076                SurfaceError::Invalid(format!("{file} is not an eval set: {error}"))
1077            }),
1078            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1079            Err(error) => Err(SurfaceError::Invalid(format!("{file} could not be read: {error}"))),
1080        }
1081    }
1082
1083    async fn save_example(
1084        &self,
1085        _caller: &Caller,
1086        file: &str,
1087        set: serde_json::Value,
1088        image_path: &str,
1089        image: &EvidenceBytes,
1090    ) -> Result<()> {
1091        let root = self
1092            .eval_fixtures
1093            .as_ref()
1094            .ok_or_else(|| SurfaceError::unsupported("saving labelled examples"))?;
1095        crate::viewer::check_file(file).map_err(SurfaceError::Invalid)?;
1096        let target = root.join(file);
1097        let folder = target.parent().unwrap_or(root).to_path_buf();
1098        let picture = folder.join(image_path);
1099        let io = |what: &str, error: std::io::Error| {
1100            SurfaceError::Invalid(format!("{what} could not be written: {error}"))
1101        };
1102        if let Some(parent) = picture.parent() {
1103            std::fs::create_dir_all(parent).map_err(|e| io("the fixtures folder", e))?;
1104        }
1105        if !picture.exists() {
1106            std::fs::write(&picture, &image.bytes).map_err(|e| io(image_path, e))?;
1107        }
1108        let text = serde_json::to_vec_pretty(&set)
1109            .map_err(|error| SurfaceError::Invalid(format!("the eval set: {error}")))?;
1110        // Written beside and renamed, so a reader never sees half a file.
1111        let partial = target.with_extension("json.partial");
1112        std::fs::write(&partial, text).map_err(|e| io(file, e))?;
1113        std::fs::rename(&partial, &target).map_err(|e| io(file, e))?;
1114        Ok(())
1115    }
1116
1117    async fn evidence_image(
1118        &self,
1119        request: &ApprovalRequest,
1120        index: usize,
1121    ) -> Result<Option<EvidenceBytes>> {
1122        let image = *crate::evidence::images(request)
1123            .get(index)
1124            .ok_or_else(|| SurfaceError::not_found(format!("image {index} of this decision")))?;
1125        let Some(bytes) = self.evidence_bytes(image).await? else { return Ok(None) };
1126        Ok(Some(EvidenceBytes { mime_type: image.mime_type.clone(), bytes }))
1127    }
1128
1129    fn holds_again(&self) -> bool {
1130        self.approvals.is_some()
1131            && self.artifacts.is_some()
1132            && (self.kernel.is_some() || self.harness.is_some())
1133    }
1134
1135    async fn hold_again(
1136        &self,
1137        caller: &Caller,
1138        request: &ApprovalRequest,
1139        version: u64,
1140        args: serde_json::Value,
1141        why: &str,
1142    ) -> Result<()> {
1143        if !self.holds_again() {
1144            return Err(SurfaceError::unsupported("holding a call again"));
1145        }
1146        // Closed first, at the version the person saw, so the old call can never run as well.
1147        let closed = ApprovalDecision::reject(caller.subject.clone(), why)
1148            .with_groups(caller.groups.clone());
1149        self.approvals()?.decide(&request.id, version, closed).await?;
1150        let call = RequestedCall::new(
1151            request.tool_name.clone(),
1152            args,
1153            caller.subject.clone(),
1154            RequestedVia::form(format!("decision:{}", request.id), version, HELD_AGAIN_ACTION),
1155        );
1156        self.request_call(caller, &request.scope.session_id, "", call).await
1157    }
1158
1159    #[cfg(feature = "web")]
1160    async fn change_image(
1161        &self,
1162        caller: &Caller,
1163        request: &ApprovalRequest,
1164        version: u64,
1165        change: &crate::evidence::ImageChange,
1166    ) -> Result<crate::evidence::ImageChanged> {
1167        let artifacts = self
1168            .artifacts
1169            .as_ref()
1170            .ok_or_else(|| SurfaceError::unsupported("changing an image without its artifacts"))?;
1171        let image =
1172            *crate::evidence::images(request).get(change.image as usize).ok_or_else(|| {
1173                SurfaceError::not_found(format!("image {} of this decision", change.image))
1174            })?;
1175        if image.mime_type != "image/png" {
1176            return Err(SurfaceError::Invalid(format!(
1177                "only a PNG image can be changed here; this one is {}",
1178                image.mime_type
1179            )));
1180        }
1181        let bytes = self
1182            .evidence_bytes(image)
1183            .await?
1184            .ok_or_else(|| SurfaceError::Invalid("the image is no longer kept".into()))?;
1185        let (changed, width, height) =
1186            crate::evidence::changed_png(&bytes, change).map_err(SurfaceError::Invalid)?;
1187        let to = crate::evidence::digest_of(&changed);
1188        // Kept beside the original under the name the vision tools find an image by digest.
1189        let hex = to.trim_start_matches("sha256:");
1190        let at = &image.artifact;
1191        artifacts
1192            .save(adk_artifact::SaveRequest {
1193                app_name: at.app_name.clone(),
1194                user_id: at.user_id.clone(),
1195                session_id: at.session_id.clone(),
1196                file_name: format!("vision-{hex}.png"),
1197                part: adk_core::Part::InlineData {
1198                    mime_type: "image/png".into(),
1199                    data: changed,
1200                    uri: None,
1201                    annotations: None,
1202                },
1203                version: None,
1204            })
1205            .await?;
1206        let mut args = request.args_redacted.clone();
1207        if let Some(map) = args.as_object_mut() {
1208            // The new image is already cut to the crop the call asked for.
1209            map.remove("region");
1210            map.insert("image".into(), serde_json::Value::String(to.clone()));
1211        }
1212        self.hold_again(caller, request, version, args, IMAGE_CHANGED_REASON).await?;
1213        Ok(crate::evidence::ImageChanged { from: image.digest.clone(), to, width, height })
1214    }
1215
1216    #[cfg(feature = "computer-use")]
1217    async fn screen_plan(&self, request: &ApprovalRequest) -> Option<crate::source::HeldPlan> {
1218        let held = self.harness.as_ref()?.held_screen_plan(request)?;
1219        Some(held_plan(&held))
1220    }
1221
1222    #[cfg(feature = "computer-use")]
1223    async fn decide_screen_plan(
1224        &self,
1225        caller: &Caller,
1226        request: &ApprovalRequest,
1227        version: u64,
1228        digest: &str,
1229        allow: bool,
1230        reason: Option<String>,
1231    ) -> Result<ApprovalRequest> {
1232        let harness = self
1233            .harness
1234            .as_ref()
1235            .ok_or_else(|| SurfaceError::unsupported("deciding a screen plan"))?;
1236        let approvals = self.approvals()?;
1237        let answer = if allow {
1238            adk_harness::ScreenPlanAnswer::Approve
1239        } else {
1240            adk_harness::ScreenPlanAnswer::Deny {
1241                message: reason.filter(|reason| !reason.trim().is_empty()),
1242            }
1243        };
1244        let decision = harness
1245            .decide_held_screen_plan(request, digest, answer, &caller.subject)
1246            .await?
1247            .with_groups(caller.groups.clone());
1248        match approvals.decide(&request.id, version, decision).await {
1249            Ok(updated) => Ok(updated),
1250            Err(error) => {
1251                // Another answer reached the call first: the plan waits for a decision again.
1252                harness.revert_held_screen_plan(request, digest).await;
1253                Err(error.into())
1254            }
1255        }
1256    }
1257
1258    #[cfg(feature = "computer-use")]
1259    async fn close_screen_plan(
1260        &self,
1261        request: &ApprovalRequest,
1262        plan: &crate::source::HeldPlan,
1263        why: &str,
1264    ) -> Result<()> {
1265        let harness = self
1266            .harness
1267            .as_ref()
1268            .ok_or_else(|| SurfaceError::unsupported("closing a screen plan"))?;
1269        harness.end_held_screen_plan(request, &plan.view.digest, why).await;
1270        // Every step still held, the card's own call first: a cancel denies the call, so none
1271        // runs on an answer given after the stop.
1272        let approvals = self.approvals()?;
1273        let mut query = InboxQuery::default()
1274            .with_session(&request.scope)
1275            .with_states([ApprovalState::Pending]);
1276        loop {
1277            let page = approvals.inbox(query.clone()).await?;
1278            for item in
1279                page.items.iter().filter(|item| plan.fingerprints.contains(&item.fingerprint))
1280            {
1281                if let Err(error) = approvals.cancel(&item.id, Some(why.to_string())).await {
1282                    tracing::warn!(error = %error, decision.id = %item.id, "a screen plan step's request was not cancelled");
1283                }
1284            }
1285            match page.next_cursor {
1286                Some(cursor) => query = query.with_cursor(Some(cursor)),
1287                None => break,
1288            }
1289        }
1290        Ok(())
1291    }
1292
1293    async fn run_ended(&self, request: &ApprovalRequest) -> Option<DateTime<Utc>> {
1294        let (runs, run_id) = (self.runs.as_ref()?, request.run_id.as_ref()?);
1295        match runs.get(run_id).await {
1296            Ok(Some(run)) if run.state.is_terminal() => Some(run.updated_at),
1297            Ok(_) => None,
1298            Err(error) => {
1299                tracing::warn!(error = %error, decision.id = %request.id, "the run waiting on a decision could not be read");
1300                None
1301            }
1302        }
1303    }
1304
1305    async fn resolved_by(&self, caller: &Caller, request: &ApprovalRequest) -> Result<()> {
1306        // A suggested agent is added as the surface that approved it, so its record names
1307        // where (spec 3.3 §11).
1308        if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
1309            if let Some(table) = self.agent_table() {
1310                table.answered(&request.id, &crate::agents::agent_caller(caller)).await;
1311            }
1312            return Ok(());
1313        }
1314        self.resume_decided(request, Some(caller)).await
1315    }
1316
1317    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
1318        self.always_allow_rule(None, request).await.map(|(label, ..)| AlwaysAllowOffer { label })
1319    }
1320
1321    async fn prepare_always_allow(
1322        &self,
1323        caller: &Caller,
1324        request: &ApprovalRequest,
1325    ) -> Result<Box<dyn RuleCommit>> {
1326        let harness =
1327            self.harness.clone().ok_or_else(|| SurfaceError::unsupported("always allow"))?;
1328        let (_, rule, from) =
1329            self.always_allow_rule(Some(caller), request).await.ok_or_else(|| {
1330                SurfaceError::Invalid("no standing rule applies to this call; allow it once".into())
1331            })?;
1332        let surface = serde_json::to_value(caller.surface)
1333            .ok()
1334            .and_then(|value| value.as_str().map(str::to_string))
1335            .unwrap_or_else(|| "surface".to_string());
1336        let prepared = Arc::new(PreparedRule {
1337            author: caller.user_id().to_string(),
1338            version: request.version,
1339            grant: tokio::sync::Mutex::new(Some(GrantRule { harness, rule, from, surface })),
1340        });
1341        self.prepared
1342            .by_decision
1343            .lock()
1344            .unwrap_or_else(|e| e.into_inner())
1345            .insert(request.id.clone(), prepared.clone());
1346        Ok(Box::new(PreparedCommit {
1347            rules: self.prepared.clone(),
1348            decision: request.id.clone(),
1349            rule: prepared,
1350        }))
1351    }
1352
1353    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
1354        if let Some((kernel, _)) = &self.kernel {
1355            // Where each agent's commands run: the harness's own agent as the harness
1356            // reports it, an agent the person added from its definition (spec 3.3 §5.7).
1357            let views = kernel.agents().list().await?;
1358            let own = self.harness.as_ref().map(|harness| {
1359                (
1360                    harness.agent().info().name.clone(),
1361                    harness.agent().info().shell().map(shell_place),
1362                )
1363            });
1364            let shell_of = |target: &str| -> Option<crate::model::ShellPlace> {
1365                if let Some((name, place)) = &own
1366                    && name == target
1367                {
1368                    return place.clone();
1369                }
1370                views.iter().find(|view| view.agent.id == target).and_then(|view| {
1371                    match view.agent.uses.shell {
1372                        adk_kernel::agents::ShellAccess::None => None,
1373                        adk_kernel::agents::ShellAccess::Sandboxed => {
1374                            Some(crate::model::ShellPlace::Sandbox { enforcer: None })
1375                        }
1376                        adk_kernel::agents::ShellAccess::Host => {
1377                            Some(crate::model::ShellPlace::Host)
1378                        }
1379                    }
1380                })
1381            };
1382            let mut latest: BTreeMap<String, AgentState> = BTreeMap::new();
1383            for process in self.processes(user).await? {
1384                let run = &process.run;
1385                if latest.contains_key(&run.target) {
1386                    continue;
1387                }
1388                let waiting_on_decision =
1389                    matches!(run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }));
1390                latest.insert(
1391                    run.target.clone(),
1392                    AgentState {
1393                        shell: shell_of(&run.target),
1394                        name: run.target.clone(),
1395                        session_id: run.session_id.clone(),
1396                        state: run.state,
1397                        waiting_on_decision,
1398                        wake_at: (run.state == RunState::Waiting && !waiting_on_decision)
1399                            .then_some(run.not_before)
1400                            .flatten(),
1401                        suspended: process.meta.suspended_by.is_some(),
1402                        subagent: (process.meta.kind == adk_kernel::ProcessKind::Subagent).then(
1403                            || {
1404                                process
1405                                    .meta
1406                                    .labels
1407                                    .get(adk_kernel::SUBAGENT_NAME_LABEL)
1408                                    .cloned()
1409                                    .unwrap_or_else(|| "sub-agent".to_string())
1410                            },
1411                        ),
1412                    },
1413                );
1414            }
1415            // A removed agent leaves the roster; its past runs stay in its threads. One
1416            // listing carries every agent's state (spec 3.3 §5.7).
1417            let gone: Vec<String> = views
1418                .into_iter()
1419                .filter(|view| {
1420                    matches!(
1421                        view.agent.state,
1422                        adk_kernel::agents::AgentRecordState::Removing
1423                            | adk_kernel::agents::AgentRecordState::Removed
1424                    )
1425                })
1426                .map(|view| view.agent.id)
1427                .collect();
1428            latest.retain(|name, _| !gone.contains(name));
1429            return Ok(latest.into_values().collect());
1430        }
1431        let (name, shell) = match (&self.harness, &self.runner) {
1432            (Some(harness), _) => (
1433                harness.agent().info().name.clone(),
1434                harness.agent().info().shell().map(shell_place),
1435            ),
1436            (None, Some(_)) => (self.app.clone(), None),
1437            (None, None) => return Ok(Vec::new()),
1438        };
1439        let active = self.active_sessions(user);
1440        let waiting = match &self.approvals {
1441            Some(approvals) => approvals
1442                .inbox(
1443                    InboxQuery::default()
1444                        .with_app_name(self.app.clone())
1445                        .with_user_id(user)
1446                        .with_states(vec![ApprovalState::Pending])
1447                        .with_limit(1),
1448                )
1449                .await?
1450                .items
1451                .into_iter()
1452                .next(),
1453            None => None,
1454        };
1455        let state = if !active.is_empty() {
1456            RunState::Running
1457        } else if waiting.is_some() {
1458            RunState::Waiting
1459        } else {
1460            RunState::Completed
1461        };
1462        Ok(vec![AgentState {
1463            name,
1464            session_id: waiting
1465                .map(|request| request.scope.session_id)
1466                .or_else(|| active.first().cloned()),
1467            state,
1468            waiting_on_decision: state == RunState::Waiting,
1469            wake_at: None,
1470            suspended: false,
1471            subagent: None,
1472            shell,
1473        }])
1474    }
1475
1476    /// The kernel target new messages run on, else the harness's agent (spec 3.3 §5.5).
1477    fn primary_agent(&self) -> Option<String> {
1478        match (&self.kernel, &self.harness) {
1479            (Some((_, target)), _) => Some(target.clone()),
1480            (None, Some(harness)) => Some(harness.agent().info().name.clone()),
1481            (None, None) => None,
1482        }
1483    }
1484
1485    /// A tool the kernel's mounted drivers declare `publish_public` or `financial`, the
1486    /// classes nothing may allow without a person (spec 3.2 K-I9), as the kernel's own decide
1487    /// route and chat rate it.
1488    fn rates_high(&self, request: &ApprovalRequest) -> bool {
1489        self.driver_classes(&request.tool_name)
1490            .into_iter()
1491            .any(adk_kernel::drivers::EffectClass::is_never_auto_allowed)
1492    }
1493
1494    /// A tool the kernel's mounted drivers declare `financial` (spec 3.2 K-I9).
1495    fn moves_money(&self, request: &ApprovalRequest) -> bool {
1496        self.driver_classes(&request.tool_name)
1497            .contains(&adk_kernel::drivers::EffectClass::Financial)
1498    }
1499
1500    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
1501        if self.kernel.is_some() {
1502            return Ok(self.processes(user).await?.iter().any(|process| {
1503                process.run.session_id.as_deref() == Some(session)
1504                    && matches!(process.run.state, RunState::Running | RunState::Queued)
1505            }));
1506        }
1507        Ok(self.active_sessions(user).iter().any(|active| active == session))
1508    }
1509
1510    /// A kernel's failed processes of the session, each with the error its run recorded;
1511    /// without a kernel, the turns this source started that ended in an error.
1512    async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
1513        if self.kernel.is_none() {
1514            return Ok(self.failed.of(user, session));
1515        }
1516        let mut failures: Vec<TurnFailure> = self
1517            .processes(user)
1518            .await?
1519            .into_iter()
1520            .filter(|process| {
1521                process.run.session_id.as_deref() == Some(session)
1522                    && process.run.state == RunState::Failed
1523            })
1524            .map(|process| TurnFailure {
1525                agent: process.run.target,
1526                at: process.run.updated_at,
1527                error: process.run.error,
1528            })
1529            .collect();
1530        failures.sort_by_key(|failure| failure.at);
1531        Ok(failures)
1532    }
1533
1534    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
1535        if self.kernel.is_some() {
1536            return Ok(self.processes(user).await?.iter().any(|process| {
1537                process.run.session_id.as_deref() == Some(session)
1538                    && process.run.state == RunState::Waiting
1539                    && matches!(
1540                        process.run.checkpoint,
1541                        Some(RunCheckpointRef::AwaitingApproval { .. })
1542                    )
1543            }));
1544        }
1545        let Some(approvals) = &self.approvals else {
1546            return Ok(false);
1547        };
1548        // Every open request of the caller's session, whoever may answer it; only whether
1549        // one exists leaves this source.
1550        let page = approvals
1551            .inbox(
1552                InboxQuery::default()
1553                    .with_app_name(self.app.clone())
1554                    .with_user_id(user)
1555                    .with_session_id(session)
1556                    .with_states(vec![ApprovalState::Pending])
1557                    .with_limit(1),
1558            )
1559            .await?;
1560        Ok(!page.items.is_empty())
1561    }
1562
1563    async fn start_turn(&self, caller: &Caller, session: &str, text: &str) -> Result<()> {
1564        let user = caller.user_id();
1565        self.ensure_session(user, session).await?;
1566        if let Some((kernel, _)) = &self.kernel {
1567            // A thread belongs to one agent: its stamp, then its latest run (spec 3.3 §5.7).
1568            let target = self.target_for(user, session).await?;
1569            let run = NewRun::new(
1570                QueueClass::Interactive.as_str(),
1571                self.app.clone(),
1572                user,
1573                target,
1574                serde_json::json!({ "text": text }),
1575            )
1576            .with_session_id(session)
1577            .with_authenticated_user();
1578            kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
1579            return Ok(());
1580        }
1581        self.run_turn(user, session, text, Some(caller)).await
1582    }
1583
1584    /// A message with images: as the run's `content` on a kernel, else straight to the
1585    /// harness or the runner (spec 3.3 §5.1).
1586    async fn start_turn_images(
1587        &self,
1588        caller: &Caller,
1589        session: &str,
1590        text: &str,
1591        images: &[crate::images::MessageImage],
1592    ) -> Result<()> {
1593        if images.is_empty() {
1594            return self.start_turn(caller, session, text).await;
1595        }
1596        let user = caller.user_id();
1597        self.ensure_session(user, session).await?;
1598        let content = message_content(text, images);
1599        if let Some((kernel, _)) = &self.kernel {
1600            let target = self.target_for(user, session).await?;
1601            return self.spawn_content(kernel, user, session, target, content).await;
1602        }
1603        self.run_content(user, session, content, caller).await
1604    }
1605
1606    async fn start_turn_with_images(
1607        &self,
1608        caller: &Caller,
1609        agent: &str,
1610        session: &str,
1611        text: &str,
1612        images: &[crate::images::MessageImage],
1613    ) -> Result<()> {
1614        if images.is_empty() {
1615            return self.start_turn_with(caller, agent, session, text).await;
1616        }
1617        let Some(target) = self.target_of(agent) else {
1618            return self.start_turn_images(caller, session, text, images).await;
1619        };
1620        let (kernel, _) =
1621            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("sending a message"))?;
1622        let user = caller.user_id();
1623        self.ensure_session(user, session).await?;
1624        self.spawn_content(kernel, user, session, target, message_content(text, images)).await
1625    }
1626
1627    /// A kernel kills the session's running and queued runs; a harness or a runner cancels its
1628    /// run in flight. A run waiting on a decision is left to wait.
1629    async fn stop_turn(&self, caller: &Caller, session: &str) -> Result<bool> {
1630        let user = caller.user_id();
1631        if let Some((kernel, _)) = &self.kernel {
1632            let mut stopped = false;
1633            for process in self.processes(user).await? {
1634                let run = &process.run;
1635                if run.session_id.as_deref() == Some(session)
1636                    && matches!(run.state, RunState::Running | RunState::Queued)
1637                {
1638                    kernel.processes().kill(&process.meta.pid, "stopped by the person").await?;
1639                    stopped = true;
1640                }
1641            }
1642            return Ok(stopped);
1643        }
1644        let runner: &Runner = match (&self.harness, &self.runner) {
1645            (Some(harness), _) => harness.runner(),
1646            (None, Some(runner)) => runner,
1647            (None, None) => return Err(SurfaceError::unsupported("stopping a turn")),
1648        };
1649        Ok(runner.interrupt_identity(runner.app_name(), user, session))
1650    }
1651
1652    /// The turn this process runs takes the message: a kernel's claim of the session on this
1653    /// replica, else the harness's or the runner's run in flight.
1654    async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
1655        let user = caller.user_id();
1656        let receipt = if let Some((kernel, _)) = &self.kernel {
1657            kernel.steer(user, session, text).await?.map(|steering| steering.receipt)
1658        } else {
1659            let runner: &Runner = match (&self.harness, &self.runner) {
1660                (Some(harness), _) => harness.runner(),
1661                (None, Some(runner)) => runner,
1662                (None, None) => return Ok(None),
1663            };
1664            // Nothing reaches an agent while everything is stopped.
1665            if let Some(governance) = &self.governance {
1666                governance.check()?;
1667            }
1668            let (user_id, session_id) = Self::ids(user, session)?;
1669            let app = adk_core::AppName::try_from(runner.app_name())
1670                .map_err(|error| SurfaceError::Invalid(error.to_string()))?;
1671            let identity = adk_core::AdkIdentity::new(app, user_id, session_id);
1672            match runner.steer(&identity, Content::new("user").with_text(text)).await {
1673                Ok(receipt) => Some(receipt),
1674                // No run is in flight, or it has not reached its agent yet.
1675                Err(error)
1676                    if error.code == adk_core::STEER_NO_ACTIVE_RUN_CODE
1677                        || error.code == "agent.steer.run_not_ready" =>
1678                {
1679                    None
1680                }
1681                Err(error) => return Err(SurfaceError::Source(error)),
1682            }
1683        };
1684        let Some(receipt) = receipt else { return Ok(None) };
1685        let source = self.clone();
1686        let (user, session) = (user.to_string(), session.to_string());
1687        Ok(Some(Box::pin(async move {
1688            let steer_id = receipt.steer_id().to_string();
1689            match receipt.outcome().await {
1690                Ok(adk_core::SteerOutcome::Delivered { event_id }) => {
1691                    Ok(Steered::Delivered { event_id })
1692                }
1693                Ok(adk_core::SteerOutcome::Returned(_)) => Ok(Steered::Returned),
1694                // The run was dropped before it said: the session holds the message's event
1695                // when the turn took it.
1696                Err(_) => {
1697                    let events = source.transcript(&user, &session).await?.unwrap_or_default();
1698                    Ok(taken(&events, &steer_id))
1699                }
1700            }
1701        })))
1702    }
1703
1704    async fn request_call(
1705        &self,
1706        caller: &Caller,
1707        session: &str,
1708        text: &str,
1709        call: adk_core::RequestedCall,
1710    ) -> Result<()> {
1711        let user = caller.user_id();
1712        self.ensure_session(user, session).await?;
1713        if let Some((kernel, _)) = &self.kernel {
1714            // Held as the drawing agent inside its own target — the target of the session's
1715            // latest run, an area's or an added agent's — parked durably and woken by the
1716            // decision on any surface (spec 3.3 §7.4 rule 5, wave 4 decision 13).
1717            let latest = self
1718                .processes(user)
1719                .await?
1720                .into_iter()
1721                .find(|process| process.run.session_id.as_deref() == Some(session))
1722                .map(|process| process.run.target);
1723            let target = match latest {
1724                Some(target) => target,
1725                None => self.target_for(user, session).await?,
1726            };
1727            let run = NewRun::new(
1728                QueueClass::Interactive.as_str(),
1729                self.app.clone(),
1730                user,
1731                target,
1732                serde_json::json!({ "text": text, "requestedCall": call }),
1733            )
1734            .with_session_id(session)
1735            .with_authenticated_user();
1736            kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
1737            return Ok(());
1738        }
1739        let Some(harness) = &self.harness else {
1740            return Err(SurfaceError::unsupported(
1741                "sending a form an agent drew without a kernel or harness",
1742            ));
1743        };
1744        let (user_id, session_id) = Self::ids(user, session)?;
1745        let context = RequestContext {
1746            user_id: user.to_string(),
1747            scopes: caller.groups.clone(),
1748            metadata: Default::default(),
1749        };
1750        let stream = harness.send_requested(&user_id, &session_id, text, call, context).await?;
1751        let turn = self.turn_of(user, session);
1752        tokio::spawn(drain(stream, self.failed.clone(), turn));
1753        Ok(())
1754    }
1755
1756    async fn stop_all(&self, caller: &Caller, reason: &str) -> Result<()> {
1757        let actor = AuditActor::subject(caller.subject.clone());
1758        if let Some((kernel, _)) = &self.kernel {
1759            kernel.freeze(reason, actor).await?;
1760            return Ok(());
1761        }
1762        let governance =
1763            self.governance.as_ref().ok_or_else(|| SurfaceError::unsupported("stop all"))?;
1764        governance.freeze_recorded(reason, actor).await?;
1765        Ok(())
1766    }
1767
1768    async fn resume_all(&self, caller: &Caller) -> Result<()> {
1769        let actor = AuditActor::subject(caller.subject.clone());
1770        if let Some((kernel, _)) = &self.kernel {
1771            kernel.unfreeze(actor).await?;
1772            return Ok(());
1773        }
1774        let governance =
1775            self.governance.as_ref().ok_or_else(|| SurfaceError::unsupported("resume all"))?;
1776        governance.unfreeze_recorded(actor).await?;
1777        Ok(())
1778    }
1779
1780    async fn stopped(&self) -> Result<bool> {
1781        if let Some((kernel, _)) = &self.kernel {
1782            return Ok(kernel.health().frozen);
1783        }
1784        Ok(self.governance.as_ref().is_some_and(GovernanceControl::is_frozen))
1785    }
1786
1787    async fn mode(&self, user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
1788        let Some(harness) = &self.harness else {
1789            return Ok(None);
1790        };
1791        match session {
1792            Some(session) => {
1793                let (user, session) = Self::ids(user, session)?;
1794                Ok(Some(harness.mode(&user, &session).await?))
1795            }
1796            None => Ok(Some(harness.agent().info().default_mode)),
1797        }
1798    }
1799
1800    async fn set_mode(&self, caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
1801        let harness =
1802            self.harness.as_ref().ok_or_else(|| SurfaceError::unsupported("changing the mode"))?;
1803        let (user, session) = Self::ids(caller.user_id(), session)?;
1804        harness.set_mode(&user, &session, mode).await?;
1805        Ok(())
1806    }
1807
1808    // The area this source's turns run in, the primary agent's: with several areas, its spend
1809    // today against its own limit in force (spec 3.3 §10 K3, §13 Q7).
1810    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
1811        let Some((kernel, target)) = &self.kernel else {
1812            return Ok(self.daily_limit.map(|limit| SpendToday { spent: 0, limit: Some(limit) }));
1813        };
1814        let area = kernel.partition_of_target(target).cloned().unwrap_or_default();
1815        let spent = self
1816            .processes(user)
1817            .await?
1818            .iter()
1819            .filter(|process| process.meta.partition == area)
1820            .map(|process| process.view.spend_today)
1821            .sum();
1822        let limit = match self.daily_limit {
1823            Some(limit) => Some(limit),
1824            None => kernel.area_settings(&area).await?.daily_spending_limit,
1825        };
1826        Ok(Some(SpendToday { spent, limit }))
1827    }
1828
1829    fn quiet_hours(&self) -> Option<QuietHours> {
1830        self.kernel.as_ref().and_then(|(kernel, _)| kernel.config().quiet_hours)
1831    }
1832
1833    fn serves_kernel_routes(&self) -> bool {
1834        self.kernel.as_ref().is_some_and(|(kernel, _)| kernel.serves_routes())
1835    }
1836
1837    fn keeps_ledger(&self) -> bool {
1838        self.kernel.as_ref().is_some_and(|(kernel, _)| kernel.ledger().is_some())
1839    }
1840
1841    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<adk_kernel::proc::LedgerEntry>> {
1842        let Some(ledger) = self.kernel.as_ref().and_then(|(kernel, _)| kernel.ledger()) else {
1843            return Ok(Vec::new());
1844        };
1845        let mut entries = Vec::new();
1846        let mut query = LedgerQuery::default().from(since).limit(500);
1847        loop {
1848            let page = ledger.store().list(&query).await?;
1849            let Some(last) = page.last().map(|entry| entry.seq) else { break };
1850            let full = page.len() >= 500;
1851            entries.extend(page);
1852            if !full {
1853                break;
1854            }
1855            query = query.after(last);
1856        }
1857        Ok(entries)
1858    }
1859
1860    fn keeps_agents(&self) -> bool {
1861        self.kernel.is_some()
1862    }
1863
1864    async fn agent_definitions(&self, user: &str) -> Result<Vec<crate::agents::AgentDetail>> {
1865        let Some((kernel, _)) = &self.kernel else {
1866            return Ok(Vec::new());
1867        };
1868        crate::agents::local::definitions(kernel.agents(), user, PRIMARY_NAME, local_offset()).await
1869    }
1870
1871    async fn agent(&self, user: &str, id: &str) -> Result<Option<crate::agents::AgentDetail>> {
1872        let Some((kernel, _)) = &self.kernel else {
1873            return Ok(None);
1874        };
1875        match crate::agents::local::agent(kernel.agents(), id, user, PRIMARY_NAME, local_offset())
1876            .await
1877        {
1878            Ok(detail) => Ok(Some(detail)),
1879            Err(SurfaceError::NotFound { .. }) => Ok(None),
1880            Err(error) => Err(error),
1881        }
1882    }
1883
1884    async fn agent_choices(&self) -> Result<crate::agents::AgentChoices> {
1885        let (kernel, _) =
1886            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
1887        crate::agents::local::choices(kernel.agents(), kernel.partitions()).await
1888    }
1889
1890    async fn preview_agent(
1891        &self,
1892        caller: &Caller,
1893        request: crate::agents::AgentPreviewRequest,
1894    ) -> Result<crate::agents::AgentPreview> {
1895        let (kernel, _) =
1896            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
1897        crate::agents::local::preview(kernel.agents(), caller, request).await
1898    }
1899
1900    async fn add_agent(
1901        &self,
1902        caller: &Caller,
1903        draft: crate::agents::AgentDraft,
1904        digest: &str,
1905        replaces: Option<String>,
1906    ) -> Result<crate::agents::AgentDetail> {
1907        let action = adk_kernel::agents::AgentAction::Create {
1908            definition: draft.into_definition(),
1909            replaces,
1910        };
1911        self.apply_agent(caller, action, digest).await
1912    }
1913
1914    async fn change_agent(
1915        &self,
1916        caller: &Caller,
1917        agent: &str,
1918        version: u64,
1919        draft: crate::agents::AgentDraft,
1920        digest: &str,
1921    ) -> Result<crate::agents::AgentDetail> {
1922        let action = adk_kernel::agents::AgentAction::Change {
1923            id: agent.to_string(),
1924            expected_version: version,
1925            definition: draft.into_definition(),
1926        };
1927        self.apply_agent(caller, action, digest).await
1928    }
1929
1930    async fn pause_agent(
1931        &self,
1932        caller: &Caller,
1933        agent: &str,
1934    ) -> Result<crate::agents::AgentDetail> {
1935        let action = adk_kernel::agents::AgentAction::Pause { id: agent.to_string() };
1936        let digest = action.digest();
1937        self.apply_agent(caller, action, &digest).await
1938    }
1939
1940    async fn resume_agent(
1941        &self,
1942        caller: &Caller,
1943        agent: &str,
1944    ) -> Result<crate::agents::AgentDetail> {
1945        let action = adk_kernel::agents::AgentAction::Resume { id: agent.to_string() };
1946        let digest = action.digest();
1947        self.apply_agent(caller, action, &digest).await
1948    }
1949
1950    async fn remove_agent(
1951        &self,
1952        caller: &Caller,
1953        agent: &str,
1954        version: u64,
1955        digest: &str,
1956    ) -> Result<crate::agents::EndedWork> {
1957        let (kernel, _) =
1958            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("removing an agent"))?;
1959        let action = adk_kernel::agents::AgentAction::Remove {
1960            id: agent.to_string(),
1961            expected_version: version,
1962        };
1963        match crate::agents::local::apply(
1964            kernel.agents(),
1965            caller,
1966            action,
1967            digest,
1968            PRIMARY_NAME,
1969            local_offset(),
1970        )
1971        .await?
1972        {
1973            crate::agents::local::Applied::Removed(ended) => Ok(ended),
1974            crate::agents::local::Applied::Agent(_) => Ok(crate::agents::EndedWork::default()),
1975        }
1976    }
1977
1978    async fn copy_rule_to_agent(&self, caller: &Caller, agent: &str, rule: &str) -> Result<String> {
1979        let harness =
1980            self.harness.as_ref().ok_or_else(|| SurfaceError::unsupported("copying a rule"))?;
1981        let (kernel, _) =
1982            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("copying a rule"))?;
1983        // Only an agent the person added and still has: never a suggestion, whose id may be
1984        // given again, nor a removed one.
1985        let added =
1986            kernel.agents().get(agent).await?.is_some_and(|view| view.agent.state.is_hosted());
1987        if !added {
1988            return Err(SurfaceError::not_found(format!("agent '{agent}'")));
1989        }
1990        let store = harness.agent().runtime().standing_rules().clone();
1991        let original = store
1992            .list(&self.app, caller.user_id())
1993            .await?
1994            .into_iter()
1995            .find(|candidate| candidate.id == rule)
1996            .ok_or_else(|| SurfaceError::not_found(format!("rule '{rule}'")))?;
1997        let pinned = adk_core::AgentPrincipal::derived(&self.app, agent).id.as_str().to_string();
1998        let copy = adk_harness::copy_rule_to(&original, &pinned, caller.subject.clone())?;
1999        let label = copy.label.clone();
2000        // Through the harness, which records `harness.rule.created` before the rule is
2001        // stored (spec 3.1 I39, spec 3.3 §11).
2002        let surface = serde_json::to_value(caller.surface)
2003            .ok()
2004            .and_then(|value| value.as_str().map(str::to_string))
2005            .unwrap_or_else(|| "surface".to_string());
2006        harness.agent().grant_rule(copy, &surface, None).await?;
2007        Ok(label)
2008    }
2009
2010    async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
2011        let mut threads: BTreeMap<String, DateTime<Utc>> = BTreeMap::new();
2012        for process in self.processes(user).await? {
2013            if process.run.target != agent {
2014                continue;
2015            }
2016            if let Some(session) = process.run.session_id.clone() {
2017                let at = threads.entry(session).or_insert(process.run.updated_at);
2018                *at = (*at).max(process.run.updated_at);
2019            }
2020        }
2021        Ok(threads.into_iter().collect())
2022    }
2023
2024    async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
2025        if self.kernel.is_none() {
2026            return Ok(None);
2027        }
2028        let stamped = self
2029            .sessions
2030            .get(GetRequest {
2031                app_name: self.app.clone(),
2032                user_id: user.to_string(),
2033                session_id: session.to_string(),
2034                num_recent_events: Some(1),
2035                after: None,
2036            })
2037            .await
2038            .ok()
2039            .and_then(|found| found.state().get(adk_harness::AGENT_STATE_KEY))
2040            .and_then(|stamp| stamp.as_str().map(str::to_string));
2041        if stamped.is_some() {
2042            return Ok(stamped);
2043        }
2044        Ok(self
2045            .processes(user)
2046            .await?
2047            .into_iter()
2048            .find(|process| process.run.session_id.as_deref() == Some(session))
2049            .map(|process| process.run.target))
2050    }
2051
2052    async fn start_turn_with(
2053        &self,
2054        caller: &Caller,
2055        agent: &str,
2056        session: &str,
2057        text: &str,
2058    ) -> Result<()> {
2059        let Some(target) = self.target_of(agent) else {
2060            return self.start_turn(caller, session, text).await;
2061        };
2062        let (kernel, _) =
2063            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("sending a message"))?;
2064        let user = caller.user_id();
2065        self.ensure_session(user, session).await?;
2066        let run = NewRun::new(
2067            QueueClass::Interactive.as_str(),
2068            self.app.clone(),
2069            user,
2070            target,
2071            serde_json::json!({ "text": text }),
2072        )
2073        .with_session_id(session)
2074        .with_authenticated_user();
2075        kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
2076        Ok(())
2077    }
2078}
2079
2080impl LocalSource {
2081    /// Spawns an interactive run of `target` that starts from `content`.
2082    async fn spawn_content(
2083        &self,
2084        kernel: &Kernel,
2085        user: &str,
2086        session: &str,
2087        target: String,
2088        content: Content,
2089    ) -> Result<()> {
2090        let input = serde_json::json!({ "content": content });
2091        let run =
2092            NewRun::new(QueueClass::Interactive.as_str(), self.app.clone(), user, target, input)
2093                .with_session_id(session)
2094                .with_authenticated_user();
2095        kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
2096        Ok(())
2097    }
2098
2099    /// [`run_turn`](Self::run_turn) on a whole message, as `caller`.
2100    async fn run_content(
2101        &self,
2102        user: &str,
2103        session: &str,
2104        content: Content,
2105        caller: &Caller,
2106    ) -> Result<()> {
2107        let (user_id, session_id) = Self::ids(user, session)?;
2108        let context = RequestContext {
2109            user_id: caller.user_id().to_string(),
2110            scopes: caller.groups.clone(),
2111            metadata: Default::default(),
2112        };
2113        let stream = if let Some(harness) = &self.harness {
2114            harness.send_content_as(&user_id, &session_id, content, context).await
2115        } else if let Some(runner) = &self.runner {
2116            let config = adk_core::RunConfig {
2117                request_context: Some(context),
2118                ..runner.run_config().clone()
2119            };
2120            runner.run_with_config(user_id, session_id.clone(), content, Some(config)).await
2121        } else {
2122            return Err(SurfaceError::unsupported(
2123                "sending a message without a kernel, harness or runner",
2124            ));
2125        };
2126        let stream = stream?;
2127        let turn = self.turn_of(user, session);
2128        tokio::spawn(drain(stream, self.failed.clone(), turn));
2129        Ok(())
2130    }
2131}
2132
2133/// The plan a held call is a step of, as its card shows it (spec 3.7 Q8).
2134#[cfg(feature = "computer-use")]
2135fn held_plan(held: &adk_harness::HeldScreenPlan) -> crate::source::HeldPlan {
2136    let plan = &held.plan;
2137    let steps = plan
2138        .steps
2139        .iter()
2140        .map(|step| crate::model::ScreenPlanStepView {
2141            operation: step
2142                .action
2143                .get("operation")
2144                .and_then(serde_json::Value::as_str)
2145                .unwrap_or("action")
2146                .to_string(),
2147            target: step.target.as_ref().and_then(|target| target.bounds.as_ref()).map(|bounds| {
2148                let p = bounds.to_points();
2149                format!("({:.0}, {:.0})-({:.0}, {:.0}) pt", p.x, p.y, p.x + p.width, p.y + p.height)
2150            }),
2151            screenshot: step.target.as_ref().and_then(|target| target.screenshot_hash.clone()),
2152            proposed: step.proposed.clone(),
2153        })
2154        .collect();
2155    crate::source::HeldPlan {
2156        view: crate::model::ScreenPlanView {
2157            digest: plan.digest.clone(),
2158            window: plan.window.to_string(),
2159            steps,
2160        },
2161        text: held.render(),
2162        step: held.step,
2163        open: held.state == adk_harness::HeldPlanState::Open,
2164        fingerprints: held.fingerprints.clone(),
2165    }
2166}
2167
2168/// A person's message: its text, then its images.
2169fn message_content(text: &str, images: &[crate::images::MessageImage]) -> Content {
2170    let mut content = Content::new("user");
2171    if !text.trim().is_empty() {
2172        content = content.with_text(text);
2173    }
2174    for image in images {
2175        content = content.with_inline_data(image.mime_type.clone(), image.data.clone());
2176    }
2177    content
2178}
2179
2180/// Where `bash` runs, as the surface shows it (spec 3.3 §5.7).
2181fn shell_place(status: &adk_harness::IsolationStatus) -> crate::model::ShellPlace {
2182    use crate::model::ShellPlace;
2183    match status {
2184        adk_harness::IsolationStatus::Host => ShellPlace::Host,
2185        adk_harness::IsolationStatus::OsSandbox { enforcer } => {
2186            ShellPlace::Sandbox { enforcer: Some(enforcer.clone()) }
2187        }
2188        adk_harness::IsolationStatus::Container { image } => {
2189            ShellPlace::Container { image: image.clone() }
2190        }
2191        adk_harness::IsolationStatus::Remote { provider, off_host } => {
2192            ShellPlace::Remote { provider: provider.clone(), off_host: *off_host }
2193        }
2194        adk_harness::IsolationStatus::Degraded { requested, reason } => {
2195            ShellPlace::Degraded { requested: requested.clone(), reason: reason.clone() }
2196        }
2197        // An isolation a later harness adds is not claimed as a sandbox.
2198        _ => ShellPlace::Host,
2199    }
2200}
2201
2202impl LocalSource {
2203    /// Resumes the session of a decided `request` (spec 3.3 §7.3): a durable run parked on the
2204    /// call is woken by the approval service; a call held in a plain run resumes with an
2205    /// empty turn, as `Harness::resume` does, as the person who answered when it is theirs.
2206    async fn resume_decided(
2207        &self,
2208        request: &ApprovalRequest,
2209        caller: Option<&Caller>,
2210    ) -> Result<()> {
2211        if request.run_id.is_some() && self.kernel.is_some() {
2212            return Ok(());
2213        }
2214        if self.harness.is_none() && self.runner.is_none() {
2215            return Ok(());
2216        }
2217        self.run_turn(&request.scope.user_id, &request.scope.session_id, "", caller).await
2218    }
2219
2220    /// The sessions of `user` in this application with a run in flight, oldest first.
2221    fn active_sessions(&self, user: &str) -> Vec<String> {
2222        let runs = match (&self.harness, &self.runner) {
2223            (Some(harness), _) => harness.runner().active_runs(),
2224            (None, Some(runner)) => runner.active_runs(),
2225            (None, None) => Vec::new(),
2226        };
2227        let mut sessions: Vec<String> = runs
2228            .into_iter()
2229            .filter(|run| run.user_id.as_ref() == user && run.app_name.as_ref() == self.app)
2230            .map(|run| run.session_id.as_ref().to_string())
2231            .collect();
2232        sessions.sort();
2233        sessions.dedup();
2234        sessions
2235    }
2236}