adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Where the engine reads and acts (spec 3.3 §6): the seam between the engine and a
//! kernel, a harness or a plain runner.
//!
//! | Source | Reads | Acts |
//! |---|---|---|
//! | [`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 |
//! | [`ControlSource`](crate::ControlSource) | a kernel's control plane through `ControlClient`: attach, the approvals inbox, processes, health, the ledger | decide, spawn, steer, freeze, unfreeze |
//!
//! A source holds no surface state (spec 3.2 K-I17): every call reads its stores.

use std::time::Duration;

use adk_core::{ApprovalDecision, ApprovalRequest, Event, RunState};
use adk_harness::HarnessMode;
use adk_kernel::QuietHours;
use adk_kernel::proc::LedgerEntry;
use async_trait::async_trait;
use chrono::{DateTime, Utc};

use crate::agents::{
    AgentChoices, AgentDetail, AgentDraft, AgentPreview, AgentPreviewRequest, EndedWork,
};
use crate::error::{Result, SurfaceError};
use crate::model::ScreenPlanView;
use crate::origin::Caller;

/// An agent's state as a source reports it, before projection into an
/// [`AgentRow`](crate::AgentRow) (spec 3.3 §8.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentState {
    /// The agent's name: a kernel target or the runner's root agent.
    pub name: String,
    /// The session its latest work belongs to.
    pub session_id: Option<String>,
    /// The latest run's state.
    pub state: RunState,
    /// The run waits on a decision.
    pub waiting_on_decision: bool,
    /// The run sleeps until this time.
    pub wake_at: Option<DateTime<Utc>>,
    /// The run was suspended, by a stop or by hand.
    pub suspended: bool,
    /// The background sub-agent the latest run belongs to, by the name its parent gave it,
    /// when it is one: the roster says so beside its status.
    pub subagent: Option<String>,
    /// Where its commands run, when it has a shell and the source knows (spec 3.3 §5.7).
    pub shell: Option<crate::model::ShellPlace>,
}

/// A turn of a session that ended in an error, as a source reports it: the thread shows it
/// where the agent's reply would have been ([`Source::turn_failures`]).
///
/// # Example
///
/// ```rust
/// use adk_surface::TurnFailure;
///
/// let failed = TurnFailure {
///     agent: "claims".into(),
///     at: chrono::Utc::now(),
///     error: Some("model.internal: no recorded answer for turn 3".into()),
/// };
/// assert_eq!(failed.agent, "claims");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TurnFailure {
    /// The agent whose turn it was, by its name in the runtime.
    pub agent: String,
    /// When the turn ended.
    pub at: DateTime<Utc>,
    /// The error as the runtime recorded it, such as `model.internal: no recorded answer`.
    pub error: Option<String>,
}

/// Today's spend and the daily limit, in micro-USD (spec 3.3 §8.1 "Daily spending limit").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpendToday {
    /// Spent today (UTC day).
    pub spent: u64,
    /// The daily limit, when one is set.
    pub limit: Option<u64>,
}

/// How a source grants "Always allow" (spec 3.3 §8.2): the label it offers for a request,
/// and the standing rule it creates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlwaysAllowOffer {
    /// The button's words, such as "Always allow for this folder".
    pub label: String,
}

/// A held call that is a step of a previewed screen plan, as a source tells the engine
/// (spec 3.7 Q8): the plan's first step carries the plan's one card, and the steps held with it
/// wait behind that card.
///
/// # Example
///
/// ```rust
/// use adk_surface::{HeldPlan, ScreenPlanView};
///
/// let held = HeldPlan {
///     view: ScreenPlanView { digest: "sha256:ab".into(), window: "app.forms".into(), steps: Vec::new() },
///     text: "0 desktop action(s) in app.forms".into(),
///     step: 0,
///     open: true,
///     fingerprints: Vec::new(),
/// };
/// assert!(held.open);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct HeldPlan {
    /// The plan as its card shows it.
    pub view: ScreenPlanView,
    /// The plan as text: the window, then each step's operation, target and proposed action.
    pub text: String,
    /// Which step the held call is, from 0.
    pub step: usize,
    /// No one decided the plan yet: its first step's card takes one answer for every step.
    pub open: bool,
    /// The fingerprint each step's call is held under, in order.
    pub fingerprints: Vec<String>,
}

/// What became of a message a running turn was offered (spec 3.3 §6 "steer").
///
/// # Example
///
/// ```rust
/// use adk_surface::Steered;
///
/// let taken = Steered::Delivered { event_id: "evt-7".into() };
/// assert_ne!(taken, Steered::Returned);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Steered {
    /// The turn took the message at its agent's next safe point: the session holds it as
    /// this event.
    Delivered {
        /// The id of the session event that carries the message.
        event_id: String,
    },
    /// The turn ended before it took the message, which goes as the session's next message.
    Returned,
}

/// The wait for what became of a message a running turn holds ([`Source::steer`]).
pub type Steering = futures::future::BoxFuture<'static, Result<Steered>>;

/// The seam between the engine and what it shows (spec 3.3 §6).
///
/// Implement it to put the engine over another runtime; the methods with defaults report
/// `surface.unsupported`, and the engine hides what a source cannot do.
#[async_trait]
pub trait Source: Send + Sync {
    /// The application whose sessions the source serves.
    fn app_name(&self) -> &str;

    /// The session's events in store order, or `None` when `user` has no such session.
    ///
    /// The feed numbers events by their position here (spec 3.3 §6), so a source returns
    /// every event, oldest first, exactly as its store keeps them.
    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>>;

    /// Waits until something the surfaces show may have changed, or `max` passes.
    async fn changed(&self, max: Duration) {
        tokio::time::sleep(max).await;
    }

    /// The decision requests `caller` may answer — of the caller's session `session` when
    /// it is set (`InboxQuery::with_session`, spec 3.3 §10 C1) — open ones only when
    /// `open_only`.
    async fn requests(
        &self,
        caller: &Caller,
        session: Option<&str>,
        open_only: bool,
    ) -> Result<Vec<ApprovalRequest>>;

    /// One decision request.
    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>>;

    /// Records `decision` at `expected_version`: `ApprovalService::decide` (spec 3.3 §6,
    /// S-I2). Never retried.
    async fn decide(
        &self,
        id: &str,
        expected_version: u64,
        decision: ApprovalDecision,
    ) -> Result<ApprovalRequest>;

    /// Called once a decision the engine recorded resolved its request, so a call held in a
    /// run that is not parked durably resumes. The default does nothing: an approval service
    /// with a run store wakes a parked run itself.
    async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
        let _ = request;
        Ok(())
    }

    /// [`resolved`](Self::resolved), for the answer `caller` gave: a source that runs the
    /// resumed turn runs it as `caller` when the session is theirs, so the session's mode and
    /// standing rules apply to it (spec 3.3 §6). The default calls `resolved`.
    async fn resolved_by(&self, caller: &Caller, request: &ApprovalRequest) -> Result<()> {
        let _ = caller;
        self.resolved(request).await
    }

    /// What "Always allow" would create for `request`, when this source can create it.
    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
        let _ = request;
        None
    }

    /// Prepares the standing rule "Always allow" offered for `request`, as `caller`, before the
    /// decision is recorded. Returns a commit the engine runs only once the decision approved
    /// the request: never after a lost version, a denial, or an approval a quorum still waits
    /// on.
    async fn prepare_always_allow(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
    ) -> Result<Box<dyn RuleCommit>> {
        let _ = (caller, request);
        Err(SurfaceError::unsupported("always allow"))
    }

    /// The agents of `user`.
    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
        let _ = user;
        Ok(Vec::new())
    }

    /// The agent a message goes to when the person names none, by its name in the runtime: the
    /// one the tray's "Ask Finance" box addresses (spec 3.3 §5.5). `None`, the default, when
    /// the source has no single primary agent.
    fn primary_agent(&self) -> Option<String> {
        None
    }

    /// Whether the source rates `request`'s call high risk whatever the request says, so every
    /// surface asks for what a high-risk call needs (spec 3.3 §7.2): a kernel rates so a tool
    /// its mounted drivers declare `publish_public` or `financial` (spec 3.2 K-I9). `false`, the
    /// default, leaves the request's own risk.
    fn rates_high(&self, request: &ApprovalRequest) -> bool {
        let _ = request;
        false
    }

    /// Whether each image `request` holds as evidence is still kept, in the order of its
    /// evidence (spec 3.7 §8.2). The default cannot tell, and the card shows each image.
    async fn evidence_kept(&self, request: &ApprovalRequest) -> Vec<crate::evidence::EvidenceKept> {
        vec![crate::evidence::EvidenceKept::Unknown; crate::evidence::images(request).len()]
    }

    /// The `index`th image `request` holds as evidence, read from where its locator says and
    /// served only when its bytes hash to its digest; `None` when it is no longer kept. The
    /// engine checks the caller may see the request first (spec 3.7 §7.8: surfaces load
    /// evidence with the viewer's own authorisation).
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source keeps no images, `surface.invalid` when the
    /// stored bytes do not match the digest, or the source's error.
    async fn evidence_image(
        &self,
        request: &ApprovalRequest,
        index: usize,
    ) -> Result<Option<crate::evidence::EvidenceBytes>> {
        let _ = (request, index);
        Err(SurfaceError::unsupported("showing a decision's images"))
    }

    /// Whether [`hold_again`](Self::hold_again) and [`change_image`](Self::change_image) work
    /// here: an edited call with images, or a changed image, is held again for the person
    /// rather than run (spec 3.7 V-I5). `false`, the default.
    fn holds_again(&self) -> bool {
        false
    }

    /// Holds `request`'s call again with `args`, as `caller` asked for it: the request at
    /// `version` is closed with `why`, and the session's agent holds the call with its new
    /// arguments, and the evidence they make, for the person's decision (spec 3.7 V-I5). A
    /// call with images never runs on edited arguments nobody saw the images of.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default; `approval.version_conflict` when the request changed.
    async fn hold_again(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        args: serde_json::Value,
        why: &str,
    ) -> Result<()> {
        let _ = (caller, request, version, args, why);
        Err(SurfaceError::unsupported("holding a call again"))
    }

    /// Makes the image `change` describes from `request`'s evidence — cut smaller, more of it
    /// covered — keeps it beside the original, and holds the call again with it in place of
    /// the original (board choice A8, spec 3.7 V-I5).
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default; `surface.invalid` when the image cannot be changed.
    async fn change_image(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        change: &crate::evidence::ImageChange,
    ) -> Result<crate::evidence::ImageChanged> {
        let _ = (caller, request, version, change);
        Err(SurfaceError::unsupported("changing an image before it leaves"))
    }

    /// The screen plan `request`'s held call is a step of, when the source keeps it (spec 3.7
    /// Q8). `None`, the default: every call is decided on a card of its own.
    async fn screen_plan(&self, request: &ApprovalRequest) -> Option<HeldPlan> {
        let _ = request;
        None
    }

    /// Decides the screen plan whose first step `request` holds, as `caller` answered its card
    /// — every step allowed, or denied with `reason` — and records the decision on `request` at
    /// `version` (spec 3.7 Q8, S-I2): an approval runs each step once, in order, with the plan's
    /// binding, and a step whose target moved is held again for a card of its own.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default; a conflict when the plan or the request changed since
    /// the card was shown.
    async fn decide_screen_plan(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        digest: &str,
        allow: bool,
        reason: Option<String>,
    ) -> Result<ApprovalRequest> {
        let _ = (caller, request, version, digest, allow, reason);
        Err(SurfaceError::unsupported("deciding a screen plan"))
    }

    /// Closes the open card of `plan`, whose first step `request` holds, for `why`: the plan
    /// ends and every step of it still held is cancelled, so none runs (spec 3.7 Q8, V-I17).
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default, or the source's error.
    async fn close_screen_plan(
        &self,
        request: &ApprovalRequest,
        plan: &HeldPlan,
        why: &str,
    ) -> Result<()> {
        let _ = (request, plan, why);
        Err(SurfaceError::unsupported("closing a screen plan"))
    }

    /// When the run that waited on `request` ended while the request is still open, so the
    /// answer is used when the agent picks the thread up again (board choice A12). `None`, the
    /// default, when a run still waits or the source cannot tell.
    async fn run_ended(&self, request: &ApprovalRequest) -> Option<DateTime<Utc>> {
        let _ = request;
        None
    }

    /// Whether [`vision_answers`](Self::vision_answers) and
    /// [`vision_image`](Self::vision_image) work here, so an image card's "Open the source
    /// image" opens the annotated viewer (board choice A9). `false`, the default.
    fn keeps_vision_answers(&self) -> bool {
        false
    }

    /// The answer records the vision tools left in `session` of `user`, as JSON, oldest first
    /// (spec 3.7 §8.2, the annotated viewer). The default keeps none.
    ///
    /// # Errors
    ///
    /// The source's error.
    async fn vision_answers(&self, user: &str, session: &str) -> Result<Vec<serde_json::Value>> {
        let _ = (user, session);
        Ok(Vec::new())
    }

    /// The image `image` of `session` of `user` — a `sha256:` digest, or the name of an image
    /// artifact the session holds — served only when its bytes hash to the digest a digest
    /// names; `None` when the session holds no such image. The engine checks the caller owns
    /// the session first (spec 3.7 §8.3: read routes authorised as the inbox is).
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source keeps no images, `surface.invalid` when the
    /// stored bytes do not match the digest, or the source's error.
    async fn vision_image(
        &self,
        user: &str,
        session: &str,
        image: &str,
    ) -> Result<Option<crate::evidence::EvidenceBytes>> {
        let _ = (user, session, image);
        Err(SurfaceError::unsupported("showing a session's images"))
    }

    /// The eval fixture files a labelled example may be saved to, relative to the fixtures'
    /// root (board choice V13); `None`, the default, when the source saves no examples.
    async fn example_files(&self, user: &str) -> Result<Option<Vec<String>>> {
        let _ = user;
        Ok(None)
    }

    /// Writes the eval set `set` to `file` under the fixtures' root and the image `image`
    /// beside it at `image_path`, relative to the file, when it is not there already
    /// (board choice V13). The run's own answer is untouched.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default; `surface.invalid` when `file` leaves the root; the
    /// source's error.
    async fn save_example(
        &self,
        caller: &Caller,
        file: &str,
        set: serde_json::Value,
        image_path: &str,
        image: &crate::evidence::EvidenceBytes,
    ) -> Result<()> {
        let _ = (caller, file, set, image_path, image);
        Err(SurfaceError::unsupported("saving labelled examples"))
    }

    /// The eval set at `file` under the fixtures' root, when there is one.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` by default; the source's error.
    async fn example_set(&self, user: &str, file: &str) -> Result<Option<serde_json::Value>> {
        let _ = (user, file);
        Err(SurfaceError::unsupported("saving labelled examples"))
    }

    /// Whether `request`'s call moves money by the source's account (spec 3.3 §7.4 rule 4): a
    /// kernel answers for the tools its mounted drivers declare `financial` (spec 3.2 K-I9).
    /// The engine also counts the payment tools; `false`, the default, adds nothing to them.
    fn moves_money(&self, request: &ApprovalRequest) -> bool {
        let _ = request;
        false
    }

    /// Whether a turn of the session is running now.
    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
        let _ = (user, session);
        Ok(false)
    }

    /// The turns of `user`'s session `session` that ended in an error, oldest first: a model
    /// call that failed leaves no event in the session, so the thread shows each where the
    /// reply would have been. The default reports none.
    ///
    /// # Errors
    ///
    /// The source's error.
    async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
        let _ = (user, session);
        Ok(Vec::new())
    }

    /// Whether a call of the session waits on a decision, whoever may answer it: input typed
    /// meanwhile is queued behind it (spec 3.3 §7.4 rule 2), even when the decision was routed
    /// to approvers other than the session's owner. The default says no; the engine still
    /// queues behind the decisions the caller may answer.
    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
        let _ = (user, session);
        Ok(false)
    }

    /// Starts a turn of the session on `text`.
    async fn start_turn(&self, caller: &Caller, session: &str, text: &str) -> Result<()> {
        let _ = (caller, session, text);
        Err(SurfaceError::unsupported("sending a message"))
    }

    /// Starts a turn of the session on `text` and the images the person sent with it
    /// (spec 3.3 §5.1). The default sends a message without images through
    /// [`start_turn`](Self::start_turn) and reports `surface.unsupported` for one with them.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source cannot send images, or the source's error.
    async fn start_turn_images(
        &self,
        caller: &Caller,
        session: &str,
        text: &str,
        images: &[crate::images::MessageImage],
    ) -> Result<()> {
        if images.is_empty() {
            return self.start_turn(caller, session, text).await;
        }
        Err(SurfaceError::unsupported("sending images"))
    }

    /// Stops the session's running turn (spec 3.3 §5.1 "Stop the turn"): the agent stops at
    /// once and waits for the next message; nothing it held for a decision is answered.
    /// Returns whether a turn was running. The default reports `surface.unsupported`.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source cannot stop one turn, or the source's error.
    async fn stop_turn(&self, caller: &Caller, session: &str) -> Result<bool> {
        let _ = (caller, session);
        Err(SurfaceError::unsupported("stopping a turn"))
    }

    /// Offers `text` to the turn of the session that runs now (spec 3.3 §6 "steer"): the
    /// runtime screens it as it screens a turn's own message, and the agent takes it at its
    /// next safe point. Returns the wait for what became of it, or `None` when no turn takes
    /// messages here — none runs, another replica runs it, or the source cannot steer — and
    /// the message goes as the session's next. The default answers `None`.
    ///
    /// # Errors
    ///
    /// The source's error when the message is refused: everything is stopped, or an input
    /// guardrail blocks it.
    async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
        let _ = (caller, session, text);
        Ok(None)
    }

    /// Starts a turn of the session on `text` that carries `call`, a call `caller` asked for
    /// through a form an agent drew (spec 3.3 §7.4 rule 5, wave 4 decision 13). The session's
    /// agent holds the call as itself, inside its own kernel target, under its own policy,
    /// standing rules, acting context and approval store, for the person's decision — or
    /// refuses it — before any model call. The default reports `surface.unsupported`.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source cannot start such a turn, or the source's error.
    async fn request_call(
        &self,
        caller: &Caller,
        session: &str,
        text: &str,
        call: adk_core::RequestedCall,
    ) -> Result<()> {
        let _ = (caller, session, text, call);
        Err(SurfaceError::unsupported("sending a form an agent drew"))
    }

    /// Stops every agent (spec 3.3 §8.2 "Stop all").
    async fn stop_all(&self, caller: &Caller, reason: &str) -> Result<()> {
        let _ = (caller, reason);
        Err(SurfaceError::unsupported("stop all"))
    }

    /// Resumes after a stop (spec 3.3 §8.2 "Resume all").
    async fn resume_all(&self, caller: &Caller) -> Result<()> {
        let _ = caller;
        Err(SurfaceError::unsupported("resume all"))
    }

    /// Whether everything is stopped.
    async fn stopped(&self) -> Result<bool> {
        Ok(false)
    }

    /// The session's mode, when the source runs a harness.
    async fn mode(&self, user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
        let _ = (user, session);
        Ok(None)
    }

    /// Whether [`set_mode`](Self::set_mode) opens a session the caller names that has no
    /// events yet, so a new thread takes a mode before its first message (spec 3.3 §5.2). The
    /// default says no: a session store cannot tell such a session from another person's,
    /// so the engine sets the mode of the caller's own sessions only (S-I8).
    fn opens_sessions(&self) -> bool {
        false
    }

    /// Sets the session's mode.
    async fn set_mode(&self, caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
        let _ = (caller, session, mode);
        Err(SurfaceError::unsupported("changing the mode"))
    }

    /// Today's spend for `user`, and the daily limit.
    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
        let _ = user;
        Ok(None)
    }

    /// Quiet time, when the source knows it.
    fn quiet_hours(&self) -> Option<QuietHours> {
        None
    }

    /// Whether this server serves the control-plane routes of the kernel the source runs on
    /// (`/api/kernel`), so the web home reads them ([`Served::Kernel`](crate::Served::Kernel)).
    /// `false`, the default.
    fn serves_kernel_routes(&self) -> bool {
        false
    }

    /// Whether the source keeps the `/proc` ledger [`ledger`](Self::ledger) reads: without
    /// one, "While you were away" is empty whatever ran (spec 3.3 §5.1).
    fn keeps_ledger(&self) -> bool {
        true
    }

    /// The `/proc` ledger rows since `since`, oldest first.
    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<LedgerEntry>> {
        let _ = since;
        Ok(Vec::new())
    }

    // -----------------------------------------------------------------------
    // Agents a person adds (spec 3.3 §5.7)
    // -----------------------------------------------------------------------

    /// Whether the source keeps agents a person adds: the roster ends with **New agent**.
    fn keeps_agents(&self) -> bool {
        false
    }

    /// The agents `user` added, suggested ones included; none by default.
    async fn agent_definitions(&self, user: &str) -> Result<Vec<AgentDetail>> {
        let _ = user;
        Ok(Vec::new())
    }

    /// One agent `user` added.
    async fn agent(&self, user: &str, id: &str) -> Result<Option<AgentDetail>> {
        let _ = (user, id);
        Ok(None)
    }

    /// What a person may choose for an agent.
    async fn agent_choices(&self) -> Result<AgentChoices> {
        Err(SurfaceError::unsupported("agents of your own"))
    }

    /// What a change would let an agent do, with the digest it applies with.
    async fn preview_agent(
        &self,
        caller: &Caller,
        request: AgentPreviewRequest,
    ) -> Result<AgentPreview> {
        let _ = (caller, request);
        Err(SurfaceError::unsupported("agents of your own"))
    }

    /// Adds the agent `draft` previewed with `digest`; `replaces` names the suggestion **Change
    /// it first** ends.
    async fn add_agent(
        &self,
        caller: &Caller,
        draft: AgentDraft,
        digest: &str,
        replaces: Option<String>,
    ) -> Result<AgentDetail> {
        let _ = (caller, draft, digest, replaces);
        Err(SurfaceError::unsupported("adding an agent"))
    }

    /// Changes `agent` at `version` to `draft`, previewed with `digest`.
    async fn change_agent(
        &self,
        caller: &Caller,
        agent: &str,
        version: u64,
        draft: AgentDraft,
        digest: &str,
    ) -> Result<AgentDetail> {
        let _ = (caller, agent, version, draft, digest);
        Err(SurfaceError::unsupported("changing an agent"))
    }

    /// Pauses `agent`.
    async fn pause_agent(&self, caller: &Caller, agent: &str) -> Result<AgentDetail> {
        let _ = (caller, agent);
        Err(SurfaceError::unsupported("pausing an agent"))
    }

    /// Resumes `agent`, paused by hand.
    async fn resume_agent(&self, caller: &Caller, agent: &str) -> Result<AgentDetail> {
        let _ = (caller, agent);
        Err(SurfaceError::unsupported("resuming an agent"))
    }

    /// Removes `agent` at `version`, previewed with `digest`; returns what ended.
    async fn remove_agent(
        &self,
        caller: &Caller,
        agent: &str,
        version: u64,
        digest: &str,
    ) -> Result<EndedWork> {
        let _ = (caller, agent, version, digest);
        Err(SurfaceError::unsupported("removing an agent"))
    }

    /// Copies the person's standing rule `rule` to `agent`, pinned to it (S-I19); returns its
    /// words.
    async fn copy_rule_to_agent(&self, caller: &Caller, agent: &str, rule: &str) -> Result<String> {
        let _ = (caller, agent, rule);
        Err(SurfaceError::unsupported("copying a rule"))
    }

    /// The threads of `user`'s agent `agent`: each session it ran and when it last changed;
    /// none by default. A removed agent's threads are read through it (spec 3.3 §5.7).
    async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
        let _ = (user, agent);
        Ok(Vec::new())
    }

    /// The agent whose thread `session` is: its stamp, else the target of its latest run.
    async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
        let _ = (user, session);
        Ok(None)
    }

    /// Starts a thread of `session` with `agent` on `text` (spec 3.3 §5.7 "Threads"); the
    /// default starts a turn of the source's own agent.
    async fn start_turn_with(
        &self,
        caller: &Caller,
        agent: &str,
        session: &str,
        text: &str,
    ) -> Result<()> {
        let _ = agent;
        self.start_turn(caller, session, text).await
    }

    /// [`start_turn_with`](Self::start_turn_with) with the images the person sent with the
    /// thread's first message (spec 3.3 §5.1). The default sends a message without images
    /// through `start_turn_with` and reports `surface.unsupported` for one with them.
    ///
    /// # Errors
    ///
    /// `surface.unsupported` when the source cannot send images, or the source's error.
    async fn start_turn_with_images(
        &self,
        caller: &Caller,
        agent: &str,
        session: &str,
        text: &str,
        images: &[crate::images::MessageImage],
    ) -> Result<()> {
        if images.is_empty() {
            return self.start_turn_with(caller, agent, session, text).await;
        }
        Err(SurfaceError::unsupported("sending images"))
    }
}

/// A standing rule prepared for "Always allow", granted only once the decision it belongs to
/// was recorded.
#[async_trait]
pub trait RuleCommit: Send + Sync {
    /// Grants the rule.
    async fn commit(self: Box<Self>) -> Result<()>;
}