Skip to main content

adk_surface/
source.rs

1//! Where the engine reads and acts (spec 3.3 §6): the seam between the engine and a
2//! kernel, a harness or a plain runner.
3//!
4//! | Source | Reads | Acts |
5//! |---|---|---|
6//! | [`LocalSource`](crate::LocalSource) | the session store, the approval service, an in-process kernel's process table and `/proc` ledger, a harness's mode | decide, start a turn (kernel process, harness or runner), steer a running turn, freeze and unfreeze, set the mode, standing rules |
7//! | [`ControlSource`](crate::ControlSource) | a kernel's control plane through `ControlClient`: attach, the approvals inbox, processes, health, the ledger | decide, spawn, steer, freeze, unfreeze |
8//!
9//! A source holds no surface state (spec 3.2 K-I17): every call reads its stores.
10
11use std::time::Duration;
12
13use adk_core::{ApprovalDecision, ApprovalRequest, Event, RunState};
14use adk_harness::HarnessMode;
15use adk_kernel::QuietHours;
16use adk_kernel::proc::LedgerEntry;
17use async_trait::async_trait;
18use chrono::{DateTime, Utc};
19
20use crate::agents::{
21    AgentChoices, AgentDetail, AgentDraft, AgentPreview, AgentPreviewRequest, EndedWork,
22};
23use crate::error::{Result, SurfaceError};
24use crate::model::ScreenPlanView;
25use crate::origin::Caller;
26
27/// An agent's state as a source reports it, before projection into an
28/// [`AgentRow`](crate::AgentRow) (spec 3.3 §8.1).
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct AgentState {
31    /// The agent's name: a kernel target or the runner's root agent.
32    pub name: String,
33    /// The session its latest work belongs to.
34    pub session_id: Option<String>,
35    /// The latest run's state.
36    pub state: RunState,
37    /// The run waits on a decision.
38    pub waiting_on_decision: bool,
39    /// The run sleeps until this time.
40    pub wake_at: Option<DateTime<Utc>>,
41    /// The run was suspended, by a stop or by hand.
42    pub suspended: bool,
43    /// The background sub-agent the latest run belongs to, by the name its parent gave it,
44    /// when it is one: the roster says so beside its status.
45    pub subagent: Option<String>,
46    /// Where its commands run, when it has a shell and the source knows (spec 3.3 §5.7).
47    pub shell: Option<crate::model::ShellPlace>,
48}
49
50/// A turn of a session that ended in an error, as a source reports it: the thread shows it
51/// where the agent's reply would have been ([`Source::turn_failures`]).
52///
53/// # Example
54///
55/// ```rust
56/// use adk_surface::TurnFailure;
57///
58/// let failed = TurnFailure {
59///     agent: "claims".into(),
60///     at: chrono::Utc::now(),
61///     error: Some("model.internal: no recorded answer for turn 3".into()),
62/// };
63/// assert_eq!(failed.agent, "claims");
64/// ```
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct TurnFailure {
67    /// The agent whose turn it was, by its name in the runtime.
68    pub agent: String,
69    /// When the turn ended.
70    pub at: DateTime<Utc>,
71    /// The error as the runtime recorded it, such as `model.internal: no recorded answer`.
72    pub error: Option<String>,
73}
74
75/// Today's spend and the daily limit, in micro-USD (spec 3.3 §8.1 "Daily spending limit").
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct SpendToday {
78    /// Spent today (UTC day).
79    pub spent: u64,
80    /// The daily limit, when one is set.
81    pub limit: Option<u64>,
82}
83
84/// How a source grants "Always allow" (spec 3.3 §8.2): the label it offers for a request,
85/// and the standing rule it creates.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct AlwaysAllowOffer {
88    /// The button's words, such as "Always allow for this folder".
89    pub label: String,
90}
91
92/// A held call that is a step of a previewed screen plan, as a source tells the engine
93/// (spec 3.7 Q8): the plan's first step carries the plan's one card, and the steps held with it
94/// wait behind that card.
95///
96/// # Example
97///
98/// ```rust
99/// use adk_surface::{HeldPlan, ScreenPlanView};
100///
101/// let held = HeldPlan {
102///     view: ScreenPlanView { digest: "sha256:ab".into(), window: "app.forms".into(), steps: Vec::new() },
103///     text: "0 desktop action(s) in app.forms".into(),
104///     step: 0,
105///     open: true,
106///     fingerprints: Vec::new(),
107/// };
108/// assert!(held.open);
109/// ```
110#[derive(Debug, Clone, PartialEq)]
111pub struct HeldPlan {
112    /// The plan as its card shows it.
113    pub view: ScreenPlanView,
114    /// The plan as text: the window, then each step's operation, target and proposed action.
115    pub text: String,
116    /// Which step the held call is, from 0.
117    pub step: usize,
118    /// No one decided the plan yet: its first step's card takes one answer for every step.
119    pub open: bool,
120    /// The fingerprint each step's call is held under, in order.
121    pub fingerprints: Vec<String>,
122}
123
124/// What became of a message a running turn was offered (spec 3.3 §6 "steer").
125///
126/// # Example
127///
128/// ```rust
129/// use adk_surface::Steered;
130///
131/// let taken = Steered::Delivered { event_id: "evt-7".into() };
132/// assert_ne!(taken, Steered::Returned);
133/// ```
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Steered {
136    /// The turn took the message at its agent's next safe point: the session holds it as
137    /// this event.
138    Delivered {
139        /// The id of the session event that carries the message.
140        event_id: String,
141    },
142    /// The turn ended before it took the message, which goes as the session's next message.
143    Returned,
144}
145
146/// The wait for what became of a message a running turn holds ([`Source::steer`]).
147pub type Steering = futures::future::BoxFuture<'static, Result<Steered>>;
148
149/// The seam between the engine and what it shows (spec 3.3 §6).
150///
151/// Implement it to put the engine over another runtime; the methods with defaults report
152/// `surface.unsupported`, and the engine hides what a source cannot do.
153#[async_trait]
154pub trait Source: Send + Sync {
155    /// The application whose sessions the source serves.
156    fn app_name(&self) -> &str;
157
158    /// The session's events in store order, or `None` when `user` has no such session.
159    ///
160    /// The feed numbers events by their position here (spec 3.3 §6), so a source returns
161    /// every event, oldest first, exactly as its store keeps them.
162    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>>;
163
164    /// Waits until something the surfaces show may have changed, or `max` passes.
165    async fn changed(&self, max: Duration) {
166        tokio::time::sleep(max).await;
167    }
168
169    /// The decision requests `caller` may answer — of the caller's session `session` when
170    /// it is set (`InboxQuery::with_session`, spec 3.3 §10 C1) — open ones only when
171    /// `open_only`.
172    async fn requests(
173        &self,
174        caller: &Caller,
175        session: Option<&str>,
176        open_only: bool,
177    ) -> Result<Vec<ApprovalRequest>>;
178
179    /// One decision request.
180    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>>;
181
182    /// Records `decision` at `expected_version`: `ApprovalService::decide` (spec 3.3 §6,
183    /// S-I2). Never retried.
184    async fn decide(
185        &self,
186        id: &str,
187        expected_version: u64,
188        decision: ApprovalDecision,
189    ) -> Result<ApprovalRequest>;
190
191    /// Called once a decision the engine recorded resolved its request, so a call held in a
192    /// run that is not parked durably resumes. The default does nothing: an approval service
193    /// with a run store wakes a parked run itself.
194    async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
195        let _ = request;
196        Ok(())
197    }
198
199    /// [`resolved`](Self::resolved), for the answer `caller` gave: a source that runs the
200    /// resumed turn runs it as `caller` when the session is theirs, so the session's mode and
201    /// standing rules apply to it (spec 3.3 §6). The default calls `resolved`.
202    async fn resolved_by(&self, caller: &Caller, request: &ApprovalRequest) -> Result<()> {
203        let _ = caller;
204        self.resolved(request).await
205    }
206
207    /// What "Always allow" would create for `request`, when this source can create it.
208    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
209        let _ = request;
210        None
211    }
212
213    /// Prepares the standing rule "Always allow" offered for `request`, as `caller`, before the
214    /// decision is recorded. Returns a commit the engine runs only once the decision approved
215    /// the request: never after a lost version, a denial, or an approval a quorum still waits
216    /// on.
217    async fn prepare_always_allow(
218        &self,
219        caller: &Caller,
220        request: &ApprovalRequest,
221    ) -> Result<Box<dyn RuleCommit>> {
222        let _ = (caller, request);
223        Err(SurfaceError::unsupported("always allow"))
224    }
225
226    /// The agents of `user`.
227    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
228        let _ = user;
229        Ok(Vec::new())
230    }
231
232    /// The agent a message goes to when the person names none, by its name in the runtime: the
233    /// one the tray's "Ask Finance" box addresses (spec 3.3 §5.5). `None`, the default, when
234    /// the source has no single primary agent.
235    fn primary_agent(&self) -> Option<String> {
236        None
237    }
238
239    /// Whether the source rates `request`'s call high risk whatever the request says, so every
240    /// surface asks for what a high-risk call needs (spec 3.3 §7.2): a kernel rates so a tool
241    /// its mounted drivers declare `publish_public` or `financial` (spec 3.2 K-I9). `false`, the
242    /// default, leaves the request's own risk.
243    fn rates_high(&self, request: &ApprovalRequest) -> bool {
244        let _ = request;
245        false
246    }
247
248    /// Whether each image `request` holds as evidence is still kept, in the order of its
249    /// evidence (spec 3.7 §8.2). The default cannot tell, and the card shows each image.
250    async fn evidence_kept(&self, request: &ApprovalRequest) -> Vec<crate::evidence::EvidenceKept> {
251        vec![crate::evidence::EvidenceKept::Unknown; crate::evidence::images(request).len()]
252    }
253
254    /// The `index`th image `request` holds as evidence, read from where its locator says and
255    /// served only when its bytes hash to its digest; `None` when it is no longer kept. The
256    /// engine checks the caller may see the request first (spec 3.7 §7.8: surfaces load
257    /// evidence with the viewer's own authorisation).
258    ///
259    /// # Errors
260    ///
261    /// `surface.unsupported` when the source keeps no images, `surface.invalid` when the
262    /// stored bytes do not match the digest, or the source's error.
263    async fn evidence_image(
264        &self,
265        request: &ApprovalRequest,
266        index: usize,
267    ) -> Result<Option<crate::evidence::EvidenceBytes>> {
268        let _ = (request, index);
269        Err(SurfaceError::unsupported("showing a decision's images"))
270    }
271
272    /// Whether [`hold_again`](Self::hold_again) and [`change_image`](Self::change_image) work
273    /// here: an edited call with images, or a changed image, is held again for the person
274    /// rather than run (spec 3.7 V-I5). `false`, the default.
275    fn holds_again(&self) -> bool {
276        false
277    }
278
279    /// Holds `request`'s call again with `args`, as `caller` asked for it: the request at
280    /// `version` is closed with `why`, and the session's agent holds the call with its new
281    /// arguments, and the evidence they make, for the person's decision (spec 3.7 V-I5). A
282    /// call with images never runs on edited arguments nobody saw the images of.
283    ///
284    /// # Errors
285    ///
286    /// `surface.unsupported` by default; `approval.version_conflict` when the request changed.
287    async fn hold_again(
288        &self,
289        caller: &Caller,
290        request: &ApprovalRequest,
291        version: u64,
292        args: serde_json::Value,
293        why: &str,
294    ) -> Result<()> {
295        let _ = (caller, request, version, args, why);
296        Err(SurfaceError::unsupported("holding a call again"))
297    }
298
299    /// Makes the image `change` describes from `request`'s evidence — cut smaller, more of it
300    /// covered — keeps it beside the original, and holds the call again with it in place of
301    /// the original (board choice A8, spec 3.7 V-I5).
302    ///
303    /// # Errors
304    ///
305    /// `surface.unsupported` by default; `surface.invalid` when the image cannot be changed.
306    async fn change_image(
307        &self,
308        caller: &Caller,
309        request: &ApprovalRequest,
310        version: u64,
311        change: &crate::evidence::ImageChange,
312    ) -> Result<crate::evidence::ImageChanged> {
313        let _ = (caller, request, version, change);
314        Err(SurfaceError::unsupported("changing an image before it leaves"))
315    }
316
317    /// The screen plan `request`'s held call is a step of, when the source keeps it (spec 3.7
318    /// Q8). `None`, the default: every call is decided on a card of its own.
319    async fn screen_plan(&self, request: &ApprovalRequest) -> Option<HeldPlan> {
320        let _ = request;
321        None
322    }
323
324    /// Decides the screen plan whose first step `request` holds, as `caller` answered its card
325    /// — every step allowed, or denied with `reason` — and records the decision on `request` at
326    /// `version` (spec 3.7 Q8, S-I2): an approval runs each step once, in order, with the plan's
327    /// binding, and a step whose target moved is held again for a card of its own.
328    ///
329    /// # Errors
330    ///
331    /// `surface.unsupported` by default; a conflict when the plan or the request changed since
332    /// the card was shown.
333    async fn decide_screen_plan(
334        &self,
335        caller: &Caller,
336        request: &ApprovalRequest,
337        version: u64,
338        digest: &str,
339        allow: bool,
340        reason: Option<String>,
341    ) -> Result<ApprovalRequest> {
342        let _ = (caller, request, version, digest, allow, reason);
343        Err(SurfaceError::unsupported("deciding a screen plan"))
344    }
345
346    /// Closes the open card of `plan`, whose first step `request` holds, for `why`: the plan
347    /// ends and every step of it still held is cancelled, so none runs (spec 3.7 Q8, V-I17).
348    ///
349    /// # Errors
350    ///
351    /// `surface.unsupported` by default, or the source's error.
352    async fn close_screen_plan(
353        &self,
354        request: &ApprovalRequest,
355        plan: &HeldPlan,
356        why: &str,
357    ) -> Result<()> {
358        let _ = (request, plan, why);
359        Err(SurfaceError::unsupported("closing a screen plan"))
360    }
361
362    /// When the run that waited on `request` ended while the request is still open, so the
363    /// answer is used when the agent picks the thread up again (board choice A12). `None`, the
364    /// default, when a run still waits or the source cannot tell.
365    async fn run_ended(&self, request: &ApprovalRequest) -> Option<DateTime<Utc>> {
366        let _ = request;
367        None
368    }
369
370    /// Whether [`vision_answers`](Self::vision_answers) and
371    /// [`vision_image`](Self::vision_image) work here, so an image card's "Open the source
372    /// image" opens the annotated viewer (board choice A9). `false`, the default.
373    fn keeps_vision_answers(&self) -> bool {
374        false
375    }
376
377    /// The answer records the vision tools left in `session` of `user`, as JSON, oldest first
378    /// (spec 3.7 §8.2, the annotated viewer). The default keeps none.
379    ///
380    /// # Errors
381    ///
382    /// The source's error.
383    async fn vision_answers(&self, user: &str, session: &str) -> Result<Vec<serde_json::Value>> {
384        let _ = (user, session);
385        Ok(Vec::new())
386    }
387
388    /// The image `image` of `session` of `user` — a `sha256:` digest, or the name of an image
389    /// artifact the session holds — served only when its bytes hash to the digest a digest
390    /// names; `None` when the session holds no such image. The engine checks the caller owns
391    /// the session first (spec 3.7 §8.3: read routes authorised as the inbox is).
392    ///
393    /// # Errors
394    ///
395    /// `surface.unsupported` when the source keeps no images, `surface.invalid` when the
396    /// stored bytes do not match the digest, or the source's error.
397    async fn vision_image(
398        &self,
399        user: &str,
400        session: &str,
401        image: &str,
402    ) -> Result<Option<crate::evidence::EvidenceBytes>> {
403        let _ = (user, session, image);
404        Err(SurfaceError::unsupported("showing a session's images"))
405    }
406
407    /// The eval fixture files a labelled example may be saved to, relative to the fixtures'
408    /// root (board choice V13); `None`, the default, when the source saves no examples.
409    async fn example_files(&self, user: &str) -> Result<Option<Vec<String>>> {
410        let _ = user;
411        Ok(None)
412    }
413
414    /// Writes the eval set `set` to `file` under the fixtures' root and the image `image`
415    /// beside it at `image_path`, relative to the file, when it is not there already
416    /// (board choice V13). The run's own answer is untouched.
417    ///
418    /// # Errors
419    ///
420    /// `surface.unsupported` by default; `surface.invalid` when `file` leaves the root; the
421    /// source's error.
422    async fn save_example(
423        &self,
424        caller: &Caller,
425        file: &str,
426        set: serde_json::Value,
427        image_path: &str,
428        image: &crate::evidence::EvidenceBytes,
429    ) -> Result<()> {
430        let _ = (caller, file, set, image_path, image);
431        Err(SurfaceError::unsupported("saving labelled examples"))
432    }
433
434    /// The eval set at `file` under the fixtures' root, when there is one.
435    ///
436    /// # Errors
437    ///
438    /// `surface.unsupported` by default; the source's error.
439    async fn example_set(&self, user: &str, file: &str) -> Result<Option<serde_json::Value>> {
440        let _ = (user, file);
441        Err(SurfaceError::unsupported("saving labelled examples"))
442    }
443
444    /// Whether `request`'s call moves money by the source's account (spec 3.3 §7.4 rule 4): a
445    /// kernel answers for the tools its mounted drivers declare `financial` (spec 3.2 K-I9).
446    /// The engine also counts the payment tools; `false`, the default, adds nothing to them.
447    fn moves_money(&self, request: &ApprovalRequest) -> bool {
448        let _ = request;
449        false
450    }
451
452    /// Whether a turn of the session is running now.
453    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
454        let _ = (user, session);
455        Ok(false)
456    }
457
458    /// The turns of `user`'s session `session` that ended in an error, oldest first: a model
459    /// call that failed leaves no event in the session, so the thread shows each where the
460    /// reply would have been. The default reports none.
461    ///
462    /// # Errors
463    ///
464    /// The source's error.
465    async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
466        let _ = (user, session);
467        Ok(Vec::new())
468    }
469
470    /// Whether a call of the session waits on a decision, whoever may answer it: input typed
471    /// meanwhile is queued behind it (spec 3.3 §7.4 rule 2), even when the decision was routed
472    /// to approvers other than the session's owner. The default says no; the engine still
473    /// queues behind the decisions the caller may answer.
474    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
475        let _ = (user, session);
476        Ok(false)
477    }
478
479    /// Starts a turn of the session on `text`.
480    async fn start_turn(&self, caller: &Caller, session: &str, text: &str) -> Result<()> {
481        let _ = (caller, session, text);
482        Err(SurfaceError::unsupported("sending a message"))
483    }
484
485    /// Starts a turn of the session on `text` and the images the person sent with it
486    /// (spec 3.3 §5.1). The default sends a message without images through
487    /// [`start_turn`](Self::start_turn) and reports `surface.unsupported` for one with them.
488    ///
489    /// # Errors
490    ///
491    /// `surface.unsupported` when the source cannot send images, or the source's error.
492    async fn start_turn_images(
493        &self,
494        caller: &Caller,
495        session: &str,
496        text: &str,
497        images: &[crate::images::MessageImage],
498    ) -> Result<()> {
499        if images.is_empty() {
500            return self.start_turn(caller, session, text).await;
501        }
502        Err(SurfaceError::unsupported("sending images"))
503    }
504
505    /// Stops the session's running turn (spec 3.3 §5.1 "Stop the turn"): the agent stops at
506    /// once and waits for the next message; nothing it held for a decision is answered.
507    /// Returns whether a turn was running. The default reports `surface.unsupported`.
508    ///
509    /// # Errors
510    ///
511    /// `surface.unsupported` when the source cannot stop one turn, or the source's error.
512    async fn stop_turn(&self, caller: &Caller, session: &str) -> Result<bool> {
513        let _ = (caller, session);
514        Err(SurfaceError::unsupported("stopping a turn"))
515    }
516
517    /// Offers `text` to the turn of the session that runs now (spec 3.3 §6 "steer"): the
518    /// runtime screens it as it screens a turn's own message, and the agent takes it at its
519    /// next safe point. Returns the wait for what became of it, or `None` when no turn takes
520    /// messages here — none runs, another replica runs it, or the source cannot steer — and
521    /// the message goes as the session's next. The default answers `None`.
522    ///
523    /// # Errors
524    ///
525    /// The source's error when the message is refused: everything is stopped, or an input
526    /// guardrail blocks it.
527    async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
528        let _ = (caller, session, text);
529        Ok(None)
530    }
531
532    /// Starts a turn of the session on `text` that carries `call`, a call `caller` asked for
533    /// through a form an agent drew (spec 3.3 §7.4 rule 5, wave 4 decision 13). The session's
534    /// agent holds the call as itself, inside its own kernel target, under its own policy,
535    /// standing rules, acting context and approval store, for the person's decision — or
536    /// refuses it — before any model call. The default reports `surface.unsupported`.
537    ///
538    /// # Errors
539    ///
540    /// `surface.unsupported` when the source cannot start such a turn, or the source's error.
541    async fn request_call(
542        &self,
543        caller: &Caller,
544        session: &str,
545        text: &str,
546        call: adk_core::RequestedCall,
547    ) -> Result<()> {
548        let _ = (caller, session, text, call);
549        Err(SurfaceError::unsupported("sending a form an agent drew"))
550    }
551
552    /// Stops every agent (spec 3.3 §8.2 "Stop all").
553    async fn stop_all(&self, caller: &Caller, reason: &str) -> Result<()> {
554        let _ = (caller, reason);
555        Err(SurfaceError::unsupported("stop all"))
556    }
557
558    /// Resumes after a stop (spec 3.3 §8.2 "Resume all").
559    async fn resume_all(&self, caller: &Caller) -> Result<()> {
560        let _ = caller;
561        Err(SurfaceError::unsupported("resume all"))
562    }
563
564    /// Whether everything is stopped.
565    async fn stopped(&self) -> Result<bool> {
566        Ok(false)
567    }
568
569    /// The session's mode, when the source runs a harness.
570    async fn mode(&self, user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
571        let _ = (user, session);
572        Ok(None)
573    }
574
575    /// Whether [`set_mode`](Self::set_mode) opens a session the caller names that has no
576    /// events yet, so a new thread takes a mode before its first message (spec 3.3 §5.2). The
577    /// default says no: a session store cannot tell such a session from another person's,
578    /// so the engine sets the mode of the caller's own sessions only (S-I8).
579    fn opens_sessions(&self) -> bool {
580        false
581    }
582
583    /// Sets the session's mode.
584    async fn set_mode(&self, caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
585        let _ = (caller, session, mode);
586        Err(SurfaceError::unsupported("changing the mode"))
587    }
588
589    /// Today's spend for `user`, and the daily limit.
590    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
591        let _ = user;
592        Ok(None)
593    }
594
595    /// Quiet time, when the source knows it.
596    fn quiet_hours(&self) -> Option<QuietHours> {
597        None
598    }
599
600    /// Whether this server serves the control-plane routes of the kernel the source runs on
601    /// (`/api/kernel`), so the web home reads them ([`Served::Kernel`](crate::Served::Kernel)).
602    /// `false`, the default.
603    fn serves_kernel_routes(&self) -> bool {
604        false
605    }
606
607    /// Whether the source keeps the `/proc` ledger [`ledger`](Self::ledger) reads: without
608    /// one, "While you were away" is empty whatever ran (spec 3.3 §5.1).
609    fn keeps_ledger(&self) -> bool {
610        true
611    }
612
613    /// The `/proc` ledger rows since `since`, oldest first.
614    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
615        let _ = since;
616        Ok(Vec::new())
617    }
618
619    // -----------------------------------------------------------------------
620    // Agents a person adds (spec 3.3 §5.7)
621    // -----------------------------------------------------------------------
622
623    /// Whether the source keeps agents a person adds: the roster ends with **New agent**.
624    fn keeps_agents(&self) -> bool {
625        false
626    }
627
628    /// The agents `user` added, suggested ones included; none by default.
629    async fn agent_definitions(&self, user: &str) -> Result<Vec<AgentDetail>> {
630        let _ = user;
631        Ok(Vec::new())
632    }
633
634    /// One agent `user` added.
635    async fn agent(&self, user: &str, id: &str) -> Result<Option<AgentDetail>> {
636        let _ = (user, id);
637        Ok(None)
638    }
639
640    /// What a person may choose for an agent.
641    async fn agent_choices(&self) -> Result<AgentChoices> {
642        Err(SurfaceError::unsupported("agents of your own"))
643    }
644
645    /// What a change would let an agent do, with the digest it applies with.
646    async fn preview_agent(
647        &self,
648        caller: &Caller,
649        request: AgentPreviewRequest,
650    ) -> Result<AgentPreview> {
651        let _ = (caller, request);
652        Err(SurfaceError::unsupported("agents of your own"))
653    }
654
655    /// Adds the agent `draft` previewed with `digest`; `replaces` names the suggestion **Change
656    /// it first** ends.
657    async fn add_agent(
658        &self,
659        caller: &Caller,
660        draft: AgentDraft,
661        digest: &str,
662        replaces: Option<String>,
663    ) -> Result<AgentDetail> {
664        let _ = (caller, draft, digest, replaces);
665        Err(SurfaceError::unsupported("adding an agent"))
666    }
667
668    /// Changes `agent` at `version` to `draft`, previewed with `digest`.
669    async fn change_agent(
670        &self,
671        caller: &Caller,
672        agent: &str,
673        version: u64,
674        draft: AgentDraft,
675        digest: &str,
676    ) -> Result<AgentDetail> {
677        let _ = (caller, agent, version, draft, digest);
678        Err(SurfaceError::unsupported("changing an agent"))
679    }
680
681    /// Pauses `agent`.
682    async fn pause_agent(&self, caller: &Caller, agent: &str) -> Result<AgentDetail> {
683        let _ = (caller, agent);
684        Err(SurfaceError::unsupported("pausing an agent"))
685    }
686
687    /// Resumes `agent`, paused by hand.
688    async fn resume_agent(&self, caller: &Caller, agent: &str) -> Result<AgentDetail> {
689        let _ = (caller, agent);
690        Err(SurfaceError::unsupported("resuming an agent"))
691    }
692
693    /// Removes `agent` at `version`, previewed with `digest`; returns what ended.
694    async fn remove_agent(
695        &self,
696        caller: &Caller,
697        agent: &str,
698        version: u64,
699        digest: &str,
700    ) -> Result<EndedWork> {
701        let _ = (caller, agent, version, digest);
702        Err(SurfaceError::unsupported("removing an agent"))
703    }
704
705    /// Copies the person's standing rule `rule` to `agent`, pinned to it (S-I19); returns its
706    /// words.
707    async fn copy_rule_to_agent(&self, caller: &Caller, agent: &str, rule: &str) -> Result<String> {
708        let _ = (caller, agent, rule);
709        Err(SurfaceError::unsupported("copying a rule"))
710    }
711
712    /// The threads of `user`'s agent `agent`: each session it ran and when it last changed;
713    /// none by default. A removed agent's threads are read through it (spec 3.3 §5.7).
714    async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
715        let _ = (user, agent);
716        Ok(Vec::new())
717    }
718
719    /// The agent whose thread `session` is: its stamp, else the target of its latest run.
720    async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
721        let _ = (user, session);
722        Ok(None)
723    }
724
725    /// Starts a thread of `session` with `agent` on `text` (spec 3.3 §5.7 "Threads"); the
726    /// default starts a turn of the source's own agent.
727    async fn start_turn_with(
728        &self,
729        caller: &Caller,
730        agent: &str,
731        session: &str,
732        text: &str,
733    ) -> Result<()> {
734        let _ = agent;
735        self.start_turn(caller, session, text).await
736    }
737
738    /// [`start_turn_with`](Self::start_turn_with) with the images the person sent with the
739    /// thread's first message (spec 3.3 §5.1). The default sends a message without images
740    /// through `start_turn_with` and reports `surface.unsupported` for one with them.
741    ///
742    /// # Errors
743    ///
744    /// `surface.unsupported` when the source cannot send images, or the source's error.
745    async fn start_turn_with_images(
746        &self,
747        caller: &Caller,
748        agent: &str,
749        session: &str,
750        text: &str,
751        images: &[crate::images::MessageImage],
752    ) -> Result<()> {
753        if images.is_empty() {
754            return self.start_turn_with(caller, agent, session, text).await;
755        }
756        Err(SurfaceError::unsupported("sending images"))
757    }
758}
759
760/// A standing rule prepared for "Always allow", granted only once the decision it belongs to
761/// was recorded.
762#[async_trait]
763pub trait RuleCommit: Send + Sync {
764    /// Grants the rule.
765    async fn commit(self: Box<Self>) -> Result<()>;
766}