rpi-cli 0.31.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Supervised ordinary JSONL backend. No CLI resource loader, global cwd/env
//! mutation, second Agent loop, IPC, or durable input-ACK protocol lives here.

mod supervisor;
#[cfg(unix)]
pub(super) use supervisor::AreaPeer;
pub(super) use supervisor::ReclaimClock;
#[cfg(all(test, unix))]
mod tests;

use super::{AgentRecord, AgentSpec, CatalogError, CatalogGuard, HostCatalog, RunId};
use rpi_agent::AgentMessage;
use rpi_harness::{
    agent_harness::{
        ActiveOperationSnapshot, CompactionResult, HarnessWriteFailure, HostAdmissionReceipt,
        HostAdmissionStatus, QueueResult, RunResult, UnsavedMessage,
    },
    session::{jsonl::JsonlSessionFacts, types::HistoryIdentity, Session},
    types::AgentHarnessOptions,
};
use rpi_tools::OsExecutionEnv;
use std::{
    future::Future,
    io,
    sync::{Arc, Weak},
};
use tokio::sync::watch;

pub type BackendResult<T> = Result<T, BackendError>;

/// Display is deliberately fixed; source errors and reports may contain private
/// transcript/provider details and must not be serialized with Debug by IPC.
#[derive(Clone, Debug, thiserror::Error)]
pub enum BackendError {
    #[error("ordinary backend catalog operation failed")]
    Catalog(#[source] Arc<CatalogError>),
    /// Definite pre-effect rejection by the guarded control entry points. This
    /// is distinct from a catalog failure after cancellation/cleanup has begun.
    #[error("ordinary backend administrative guard was rejected; no action accepted")]
    GuardRejected(#[source] Arc<CatalogError>),
    #[error("ordinary backend Harness operation failed")]
    Harness(#[source] Arc<rpi_harness::result::HarnessError>),
    #[error("ordinary backend Session operation failed")]
    Session(#[source] Arc<rpi_harness::error::SessionError>),
    #[error("ordinary backend filesystem operation failed")]
    Io(#[source] Arc<io::Error>),
    #[error("ordinary backend binding rejected: {0}")]
    Binding(&'static str),
    /// A resource declaration may already be visible. This is not a pure
    /// validation rejection; reconcile saved facts before any retry.
    #[error("ordinary backend resource persistence failed or is uncertain")]
    ResourcePersistence,
    /// A DLL may still own workers/code/context and the real writer. Fixed
    /// diagnostic; the Arc is lifecycle custody, not serializable error data.
    #[error("ordinary backend extension cleanup is not proven; ownership retained")]
    ExtensionUnsettled(Arc<super::NativeExtensionCustody>),
    #[error("ordinary backend is busy; no operation was accepted")]
    Busy,
    #[error("ordinary backend is closing or closed")]
    Closed,
    #[error("ordinary backend requires reconciliation")]
    Faulted,
    #[error("ordinary backend input exceeds its byte budget")]
    InputTooLarge,
    #[error("ordinary backend operation was cancelled before Harness admission")]
    CancelledBeforeAdmission,
    #[error("ordinary backend request admission was rejected: {0}")]
    Admission(&'static str),
    #[error("ordinary backend request admission outcome is uncertain; reconcile before retrying")]
    AdmissionUncertain,
    #[error("ordinary backend task panicked or stopped; inspect durable state")]
    TaskStopped,
    #[error("ordinary backend persistence failed or is uncertain; cannot unload safely")]
    Unsaved,
}

macro_rules! source_error {
    ($source:ty, $variant:ident) => {
        impl From<$source> for BackendError {
            fn from(error: $source) -> Self {
                Self::$variant(Arc::new(error))
            }
        }
    };
}
source_error!(CatalogError, Catalog);
source_error!(rpi_harness::result::HarnessError, Harness);
source_error!(rpi_harness::error::SessionError, Session);
source_error!(io::Error, Io);

/// Mandatory trusted assembly/preflight callback. Inspect the exact saved facts,
/// resolve resources/permissions/credentials per Agent, and reject unsupported
/// bindings before the prepared restore claims a writer or repairs a journal.
/// It must not call CLI `build_prepared` or mutate process globals. The supplied
/// options' Session is replaced by this backend's exact committed JSONL Session.
pub type OrdinaryBinder = Box<
    dyn FnOnce(
            &AgentSpec,
            Arc<OsExecutionEnv>,
            &JsonlSessionFacts,
        ) -> BackendResult<AgentHarnessOptions>
        + Send
        + 'static,
>;

/// Deferred, owned resource assembly. Constructing this future is part of pure
/// readonly validation; it must not start workers or perform registration until
/// polled by an actual restore. No writer/repair has occurred when it runs.
pub type OrdinaryAssembly = std::pin::Pin<
    Box<dyn std::future::Future<Output = BackendResult<AgentHarnessOptions>> + Send + 'static>,
>;

/// Pure validation of exact saved facts, returning an unpolled assembly plan.
/// It must reject metadata/resource/permission mismatches without loading code
/// or starting work. Actual restore repeats validation with fresh facts. This
/// trusted Rust interface is not a model/IPC capability or an exactly-once API.
pub type OrdinaryDeferredBinder = Box<
    dyn FnOnce(
            &AgentSpec,
            Arc<OsExecutionEnv>,
            &JsonlSessionFacts,
        ) -> BackendResult<OrdinaryAssembly>
        + Send
        + 'static,
>;

enum BindingResolver {
    Immediate(OrdinaryBinder),
    Deferred(OrdinaryDeferredBinder),
}

/// Explicit environment plus a trusted assembly callback. The environment is
/// shared by Session storage, builtin tools and skill execution for this Agent;
/// do not reuse it across Agents (its process cleanup ownership is per Agent).
pub struct OrdinaryBinding {
    environment: Option<Arc<OsExecutionEnv>>,
    binder: BindingResolver,
    // Closed native resource variants only; executable assembly additionally
    // requires the explicit owned DLL custody below, never a generic callback.
    pub(super) instruction_resources: Option<Arc<super::NativeBindingResources>>,
    pub(super) extensions: Option<Arc<super::NativeExtensionCustody>>,
    // Fault injection is test-only; production Session storage always uses the
    // explicitly bound OS environment, never a caller-supplied weak backend.
    #[cfg(test)]
    filesystem: Option<Arc<dyn rpi_tools::FileSystem>>,
}
impl OrdinaryBinding {
    pub fn new(environment: Arc<OsExecutionEnv>, binder: OrdinaryBinder) -> BackendResult<Self> {
        if !environment.has_explicit_environment() {
            return Err(BackendError::Binding(
                "explicit execution environment required",
            ));
        }
        Ok(Self {
            environment: Some(environment),
            binder: BindingResolver::Immediate(binder),
            instruction_resources: None,
            extensions: None,
            #[cfg(test)]
            filesystem: None,
        })
    }
    /// Split pure readonly validation from asynchronous owned assembly. Only
    /// restore polls the returned plan; preflight drops it without polling.
    /// Assembly must retain all callback/library ownership through failure and
    /// cleanup; the backend validates its complete options before commit_strict.
    pub fn new_deferred(
        environment: Arc<OsExecutionEnv>,
        validator: OrdinaryDeferredBinder,
    ) -> BackendResult<Self> {
        if !environment.has_explicit_environment() {
            return Err(BackendError::Binding(
                "explicit execution environment required",
            ));
        }
        Ok(Self {
            environment: Some(environment),
            binder: BindingResolver::Deferred(validator),
            instruction_resources: None,
            extensions: None,
            #[cfg(test)]
            filesystem: None,
        })
    }
    /// Attach the concrete DLL batch loaded by this binding's owned assembly.
    /// Its workers/callbacks/physical cleanup become part of the backend's
    /// writer and residency barrier, including failed startup. This trusted
    /// Rust API does not expose DLLs through profile/model/IPC input.
    pub fn with_extensions(mut self, custody: Arc<super::NativeExtensionCustody>) -> Self {
        self.extensions = Some(custody);
        self
    }

    /// Readonly native preflight before registration/Starting. Consumes this
    /// one-load environment; actual restore must use a fresh binding and repeat
    /// validation, not rely on facts surviving external filesystem changes.
    #[cfg(unix)]
    pub(crate) async fn preflight_session(self, spec: &super::AgentSpec) -> BackendResult<()> {
        supervisor::preflight(spec, self).await
    }
    #[cfg(unix)]
    pub(crate) fn execution_environment(&self) -> BackendResult<Arc<OsExecutionEnv>> {
        self.environment.clone().ok_or(BackendError::Binding(
            "explicit execution environment required",
        ))
    }
    pub(crate) fn legacy(binder: OrdinaryBinder) -> Self {
        Self {
            environment: None,
            binder: BindingResolver::Immediate(binder),
            instruction_resources: None,
            extensions: None,
            #[cfg(test)]
            filesystem: None,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct OrdinaryLimits {
    pub max_input_bytes: usize,
}
impl Default for OrdinaryLimits {
    fn default() -> Self {
        Self {
            max_input_bytes: 8 * 1024 * 1024,
        }
    }
}

#[derive(Debug)]
pub enum OrdinaryOperation {
    Prompt(Vec<AgentMessage>),
    ResumePending,
    ResumeDeferred(String),
    Compact(Option<String>),
}

#[derive(Clone, Debug)]
pub enum OrdinaryOutput {
    Run(Box<RunResult>),
    NoPendingResume,
    Compaction(Box<CompactionResult>),
    /// The exact request id was already durably admitted; this call did not
    /// execute it again. Query the admission status for execution facts.
    AlreadyAdmitted,
}

#[derive(Clone, Copy, Debug)]
pub enum Delivery {
    Steer,
    FollowUp,
    NextRun,
}

#[derive(Clone, Debug)]
pub struct BackendReport {
    pub outcome: BackendResult<OrdinaryOutput>,
    pub write_failures: Vec<HarnessWriteFailure>,
    pub unsaved_messages: usize,
    /// A fallible Session path may return directly without a warning/recovery
    /// copy. Never treat zero warnings as proof that the operation was saved.
    pub persistence_uncertain: bool,
    /// Execution may have settled even when publishing Idle failed. Preserve
    /// both facts rather than replacing the actual run outcome with fake success.
    pub catalog_error: Option<BackendError>,
}

#[derive(Clone, Debug)]
pub struct BackendSnapshot {
    pub record: AgentRecord,
    pub ticket: Option<RunId>,
    /// Volatile input association for the active task or explicitly parked
    /// deferred operation. Not a durable receipt; absent after owner restore.
    pub submitted_request_id: Option<String>,
    /// Volatile signal for this supervised ticket, never proof of settlement.
    pub cancel_requested: bool,
    pub active: Option<ActiveOperationSnapshot>,
    pub pending_resume: bool,
    /// Parked external provider work is busy even without an executing task.
    pub deferred: Option<String>,
    pub retiring: bool,
    pub closed: bool,
    pub fault: Option<BackendError>,
    pub last_report: Option<Arc<BackendReport>>,
}

type Completion = Option<BackendResult<Arc<BackendReport>>>;

/// In-memory operation ticket scoped to this Host lifetime. NOT a durable input
/// receipt or the Harness operation ID; the latter is in `OrdinaryOutput::Run`.
/// Dropping this observer never drops/cancels the supervised operation.
#[derive(Clone)]
pub struct RunTicket {
    pub id: RunId,
    completion: watch::Receiver<Completion>,
}
impl RunTicket {
    pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
        wait_completion(self.completion.clone()).await
    }
}

/// Native admission outcome, published independently of execution settlement.
/// `Pending` is observable only while the supervisor task is running.
#[derive(Clone, Debug)]
pub enum AdmissionState {
    Pending,
    Admitted(Arc<HostAdmissionReceipt>),
    Rejected(BackendError),
}

/// Ticket for a request whose input is admitted before execution. The two
/// waits are deliberately separate: `wait_admitted` returns as soon as the
/// native journal and its sync barrier cover the exact input, while `wait`
/// observes the supervised execution report.
#[derive(Clone, Debug)]
pub struct AdmittedRunTicket {
    pub id: RunId,
    admission: watch::Receiver<AdmissionState>,
    completion: watch::Receiver<Completion>,
}
impl AdmittedRunTicket {
    /// Wait for the durable input receipt. This never implies execution.
    pub async fn wait_admitted(&self) -> BackendResult<Arc<HostAdmissionReceipt>> {
        let mut receiver = self.admission.clone();
        loop {
            match receiver.borrow().clone() {
                AdmissionState::Pending => {}
                AdmissionState::Admitted(receipt) => return Ok(receipt),
                AdmissionState::Rejected(error) => return Err(error),
            }
            receiver
                .changed()
                .await
                .map_err(|_| BackendError::TaskStopped)?;
        }
    }

    pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
        wait_completion(self.completion.clone()).await
    }
}

/// Fixed mapping from native admission errors to Host-safe diagnostics. Never
/// forward raw journal text, digests or messages to the client.
pub(super) fn admission_error(error: rpi_harness::durable::DurableError) -> BackendError {
    use rpi_harness::durable::DurableError as Native;
    match error {
        Native::Closed => BackendError::Closed,
        Native::Recovering => BackendError::Faulted,
        Native::LimitExceeded => BackendError::InputTooLarge,
        Native::InvalidRequest(_) => BackendError::Admission("invalid admission request"),
        Native::Conflict => BackendError::Admission("request identity conflicts with the journal"),
        Native::CommitUncertain(_) | Native::ReadFailure(_) => BackendError::AdmissionUncertain,
        _ => BackendError::Faulted,
    }
}

async fn wait_completion(
    mut receiver: watch::Receiver<Completion>,
) -> BackendResult<Arc<BackendReport>> {
    loop {
        if let Some(result) = receiver.borrow().clone() {
            return result;
        }
        receiver
            .changed()
            .await
            .map_err(|_| BackendError::TaskStopped)?;
    }
}

/// Host-owned lifetime, separate from weak client views. Explicitly close and
/// inspect errors before removing this owner from a future service registry.
/// Drop only starts best-effort cooperative cleanup; no forced task abort occurs.
#[must_use = "retain the Host owner independently of transient clients"]
pub struct OrdinaryAgent {
    inner: Arc<supervisor::Backend>,
}

impl OrdinaryAgent {
    pub async fn restore(
        catalog: HostCatalog,
        id: super::AgentId,
        guard: CatalogGuard,
        binder: OrdinaryBinder,
    ) -> BackendResult<Self> {
        Self::restore_with_limits(catalog, id, guard, OrdinaryLimits::default(), binder).await
    }

    pub async fn restore_with_limits(
        catalog: HostCatalog,
        id: super::AgentId,
        guard: CatalogGuard,
        limits: OrdinaryLimits,
        binder: OrdinaryBinder,
    ) -> BackendResult<Self> {
        Self::restore_bound(catalog, id, guard, limits, OrdinaryBinding::legacy(binder)).await
    }

    pub async fn restore_bound(
        catalog: HostCatalog,
        id: super::AgentId,
        guard: CatalogGuard,
        limits: OrdinaryLimits,
        binding: OrdinaryBinding,
    ) -> BackendResult<Self> {
        Self::restore_bound_with_intent(catalog, id, guard, limits, binding, false).await
    }

    pub(super) async fn restore_bound_with_intent(
        catalog: HostCatalog,
        id: super::AgentId,
        guard: CatalogGuard,
        limits: OrdinaryLimits,
        binding: OrdinaryBinding,
        attach: bool,
    ) -> BackendResult<Self> {
        if limits.max_input_bytes == 0 {
            return Err(BackendError::Binding("input byte budget must be nonzero"));
        }
        // This task owns startup even if its awaiting caller disappears. An
        // unclaimed successful owner is dropped and cooperatively cleaned up.
        owned(async move { supervisor::restore(catalog, id, guard, limits, binding, attach).await })
            .await
    }

    pub fn client(&self) -> OrdinaryClient {
        OrdinaryClient {
            inner: Arc::downgrade(&self.inner),
        }
    }

    pub(super) fn shutdown_grace(&self) -> Option<std::time::Duration> {
        self.inner.shutdown_grace
    }

    pub(super) fn reclaim_clock(&self) -> Option<watch::Receiver<ReclaimClock>> {
        self.inner.reclaim.as_ref().map(watch::Sender::subscribe)
    }

    pub(super) async fn unload_idle(&self) -> BackendResult<()> {
        self.inner.unload_idle().await
    }

    pub async fn close(&self) -> BackendResult<()> {
        self.inner.retire();
        let inner = self.inner.clone();
        owned(async move { inner.close().await }).await
    }

    /// Administrative close, unlike unconditional owner shutdown. Rejection of
    /// an epoch/revision guard cannot retire or cancel the current operation.
    /// Once accepted, settlement remains owned if its waiting caller disappears.
    /// This is not a durable request-id receipt or an IPC authorization grant.
    pub async fn close_guarded(&self, guard: CatalogGuard) -> BackendResult<()> {
        let inner = self.inner.clone();
        owned(async move { inner.close_guarded(guard).await }).await
    }
}
impl Drop for OrdinaryAgent {
    fn drop(&mut self) {
        if self.inner.is_closed() {
            return;
        }
        self.inner.retire();
        let inner = self.inner.clone();
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            runtime.spawn(async move {
                if let Err(error) = inner.close().await {
                    if !matches!(error, BackendError::Busy) {
                        tracing::warn!("ordinary backend owner dropped before clean shutdown; reconciliation required");
                    }
                }
            });
        } else {
            tracing::warn!("ordinary backend dropped outside its runtime; reconciliation required");
        }
    }
}

#[derive(Clone)]
pub struct OrdinaryClient {
    inner: Weak<supervisor::Backend>,
}
impl OrdinaryClient {
    fn upgrade(&self) -> BackendResult<Arc<supervisor::Backend>> {
        self.inner.upgrade().ok_or(BackendError::Closed)
    }

    pub async fn submit(&self, operation: OrdinaryOperation) -> BackendResult<RunTicket> {
        let inner = self.upgrade()?;
        inner.validate_operation(&operation)?;
        let guard = inner
            .control
            .clone()
            .try_lock_owned()
            .map_err(|_| BackendError::Busy)?;
        owned(async move { inner.submit(guard, operation).await }).await
    }

    /// Admit the exact prompt under `request_id` before executing it. Only
    /// `wait_admitted` returning a receipt is a durable input claim.
    pub async fn submit_admitted(
        &self,
        host_id: String,
        request_id: String,
        messages: Vec<AgentMessage>,
    ) -> BackendResult<AdmittedRunTicket> {
        let inner = self.upgrade()?;
        inner.validate_messages(&messages)?;
        let guard = inner
            .control
            .clone()
            .try_lock_owned()
            .map_err(|_| BackendError::Busy)?;
        owned(async move {
            inner
                .submit_admitted(guard, host_id, request_id, messages)
                .await
        })
        .await
    }

    /// Read the native admission/reconciliation status for one request.
    pub async fn admission(&self, request_id: &str) -> BackendResult<Option<HostAdmissionStatus>> {
        let inner = self.upgrade()?;
        inner.admission(request_id).await
    }

    /// Read an already-linked native result and prove a physical barrier after
    /// its records/references were read. This does not execute or resume a run.
    pub async fn get_result(
        &self,
        run_id: &str,
        history: HistoryIdentity,
    ) -> BackendResult<Option<(RunResult, HistoryIdentity)>> {
        self.upgrade()?.get_result(run_id, history).await
    }

    /// Bounded listing of native admissions for reconciliation.
    pub async fn admissions(&self) -> BackendResult<Vec<HostAdmissionStatus>> {
        let inner = self.upgrade()?;
        inner.admissions().await
    }

    pub async fn deliver(
        &self,
        message: AgentMessage,
        delivery: Delivery,
    ) -> BackendResult<QueueResult> {
        let inner = self.upgrade()?;
        inner.validate_message(&message)?;
        let guard = inner
            .control
            .clone()
            .try_lock_owned()
            .map_err(|_| BackendError::Busy)?;
        owned(async move { inner.deliver(guard, message, delivery).await }).await
    }

    /// Cooperative signal for this exact ticket, not proof of settlement. A late
    /// cancellation can never target a subsequent operation on the same Agent.
    pub async fn cancel(&self, ticket: RunId) -> BackendResult<bool> {
        self.upgrade()?.cancel(ticket)
    }

    /// Validate the owner-observed epoch/revision and exact volatile ticket in
    /// the same control critical section as cancellation. A successful signal
    /// is not settlement or a durable request receipt; no subsequent ticket is
    /// affected by a late cancellation of the addressed one.
    pub async fn cancel_guarded(&self, guard: CatalogGuard, ticket: RunId) -> BackendResult<bool> {
        self.upgrade()?.cancel_guarded(guard, ticket)
    }

    /// Signal only the active supervised task associated with this exact input
    /// identity. Duplicates cannot retarget it. A parked deferred operation or
    /// restored historical receipt returns false; no operation is resumed.
    pub async fn cancel_submitted_guarded(
        &self,
        guard: CatalogGuard,
        request_id: &str,
    ) -> BackendResult<bool> {
        self.upgrade()?.cancel_submitted_guarded(guard, request_id)
    }

    #[cfg(unix)]
    pub(in crate::host) async fn area_session(
        &self,
        attach: bool,
    ) -> BackendResult<(super::area_rpc::Events, Option<AreaPeer>)> {
        self.upgrade()?.area_session(attach).await
    }

    #[cfg(unix)]
    pub(in crate::host) async fn area_command(
        &self,
        kind: &str,
        msg: &serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        self.upgrade()
            .map_err(|error| error.to_string())?
            .area_command(kind, msg)
            .await
    }

    /// Cheap volatile observation; does not scan transcripts or prove settlement.
    pub async fn snapshot(&self) -> BackendResult<BackendSnapshot> {
        self.upgrade()?.snapshot()
    }

    /// Explicit recovery/export surface. The caller owns the returned payload;
    /// a future IPC adapter must apply its own response/output byte budgets.
    pub fn unsaved_messages(&self) -> BackendResult<Vec<UnsavedMessage>> {
        Ok(self.upgrade()?.unsaved_messages())
    }
}

async fn owned<T: Send + 'static>(
    future: impl Future<Output = BackendResult<T>> + Send + 'static,
) -> BackendResult<T> {
    tokio::spawn(future)
        .await
        .map_err(|_| BackendError::TaskStopped)?
}