rpi-cli 0.35.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
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
//! Authenticated, bounded Unix control endpoint. Capabilities are implementation
//! promises, not an enumeration of the eventual protocol. Native prompt
//! admission/receipts are supported. Administrative execution only accepts
//! complete profile, guarded Close/CancelSubmitted and Stop intents through the
//! daemon's fixed native authority and durable coordinator; legacy ops stay off.

use super::{
    area_rpc::SessionRoutes,
    client::{encode_frame, read_frame, write_frame},
    daemon::DaemonAdministration,
    protocol::*,
    service::HostService,
    CatalogError,
};
use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
use tokio::{
    net::{UnixListener, UnixStream},
    task::{JoinHandle, JoinSet},
    time::Instant,
};
use tokio_util::sync::CancellationToken;

type SessionRoutesByAgent = BTreeMap<super::AgentId, Option<Arc<tokio::sync::Mutex<()>>>>;

#[derive(Clone, Default)]
struct ControlAuthority {
    administration: Option<DaemonAdministration>,
    mini: Option<super::mini_control::MiniControl>,
    session_rpc: Arc<SessionRoutesByAgent>,
    idle_timeout: Option<Duration>,
}

#[derive(Clone)]
pub struct ControlConfig {
    pub socket_path: PathBuf,
    pub host_id: HostId,
    pub token: AuthToken,
    pub max_connections: usize,
    pub handshake_timeout: Duration,
    /// Total idle/read + dispatch + write budget per query, not per byte.
    pub request_timeout: Duration,
}
impl ControlConfig {
    pub fn validate(&self) -> Result<(), ServerError> {
        if !self.socket_path.is_absolute()
            || !(1..=64).contains(&self.max_connections)
            || [self.handshake_timeout, self.request_timeout]
                .iter()
                .any(|duration| duration.is_zero() || *duration > Duration::from_secs(300))
        {
            return Err(ServerError::InvalidConfiguration);
        }
        Ok(())
    }
}

/// Fixed diagnostics never contain wire input, tokens, paths or OS errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ServerError {
    #[error("invalid shared Host control configuration")]
    InvalidConfiguration,
    #[error("shared Host endpoint must be absent, with a private owned parent")]
    UnsafeEndpoint,
    #[error("shared Host endpoint could not be bound")]
    Bind,
    #[error("shared Host control listener stopped unexpectedly")]
    ListenerStopped,
    #[error("shared Host control task stopped unexpectedly")]
    TaskStopped,
}

/// Remove only the socket inode this listener created. Never remove a newer
/// listener, replacement file or stale socket belonging to somebody else.
pub(super) struct SocketLease {
    path: PathBuf,
    dev: u64,
    ino: u64,
    unlink_on_drop: bool,
}
impl SocketLease {
    #[cfg(target_os = "macos")]
    pub(super) fn identity(&self) -> (u64, u64) {
        (self.dev, self.ino)
    }

    #[cfg(target_os = "macos")]
    pub(super) fn inherited(path: PathBuf, (dev, ino): (u64, u64)) -> Self {
        Self {
            path,
            dev,
            ino,
            unlink_on_drop: false,
        }
    }

    pub(super) fn remove(&self) {
        use std::os::unix::fs::{FileTypeExt, MetadataExt};
        if let Ok(metadata) = std::fs::symlink_metadata(&self.path) {
            if metadata.file_type().is_socket()
                && metadata.dev() == self.dev
                && metadata.ino() == self.ino
            {
                let _ = std::fs::remove_file(&self.path);
            }
        }
    }
}
impl Drop for SocketLease {
    fn drop(&mut self) {
        if self.unlink_on_drop {
            self.remove();
        }
    }
}
pub(super) fn bind_endpoint(
    path: PathBuf,
) -> Result<(std::os::unix::net::UnixListener, SocketLease), ServerError> {
    use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
    let parent = path.parent().ok_or(ServerError::InvalidConfiguration)?;
    let metadata = std::fs::symlink_metadata(parent).map_err(|_| ServerError::UnsafeEndpoint)?;
    if !metadata.is_dir()
        || metadata.uid() != nix::unistd::Uid::effective().as_raw()
        || metadata.mode() & 0o077 != 0
    {
        return Err(ServerError::UnsafeEndpoint);
    }
    match std::fs::symlink_metadata(&path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        _ => return Err(ServerError::UnsafeEndpoint),
    }
    let listener = std::os::unix::net::UnixListener::bind(&path).map_err(|_| ServerError::Bind)?;
    let metadata = std::fs::symlink_metadata(&path).map_err(|_| ServerError::Bind)?;
    let lease = SocketLease {
        path: path.clone(),
        dev: metadata.dev(),
        ino: metadata.ino(),
        unlink_on_drop: true,
    };
    if !metadata.file_type().is_socket()
        || metadata.nlink() != 1
        || metadata.uid() != nix::unistd::Uid::effective().as_raw()
    {
        return Err(ServerError::UnsafeEndpoint);
    }
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
        .map_err(|_| ServerError::Bind)?;
    listener
        .set_nonblocking(true)
        .map_err(|_| ServerError::Bind)?;
    Ok((listener, lease))
}

/// Explicit stop waits for all connection tasks and inode cleanup. Drop merely
/// requests that cleanup; it never closes Agents or shuts down the catalog.
pub struct ControlServer {
    welcome: Welcome,
    stop: CancellationToken,
    task: Option<JoinHandle<Result<ControlExit, ServerError>>>,
    terminal: Option<Result<ControlExit, ServerError>>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ControlExit {
    Stopped,
    AdministrativeStop,
    Idle,
}
impl ControlServer {
    pub async fn bind(config: ControlConfig, service: HostService) -> Result<Self, ServerError> {
        Self::bind_with_administration(config, service, None).await
    }
    pub(crate) async fn bind_with_administration(
        config: ControlConfig,
        service: HostService,
        administration: Option<DaemonAdministration>,
    ) -> Result<Self, ServerError> {
        Self::bind_with_controls(
            config,
            service,
            administration,
            None,
            None,
            SessionRoutes::default(),
            None,
        )
        .await
    }
    pub(super) async fn bind_with_controls(
        config: ControlConfig,
        service: HostService,
        administration: Option<DaemonAdministration>,
        mini: Option<super::mini_control::MiniControl>,
        inherited: Option<std::os::unix::net::UnixListener>,
        routes: SessionRoutes,
        idle_timeout: Option<Duration>,
    ) -> Result<Self, ServerError> {
        config.validate()?;
        if routes.restore_on_attach && administration.is_none() {
            return Err(ServerError::InvalidConfiguration);
        }
        for &id in &routes.agents {
            let record = service
                .catalog()
                .get(id)
                .await
                .map_err(|_| ServerError::InvalidConfiguration)?;
            if record.spec.mode != super::AgentMode::Persistent {
                return Err(ServerError::InvalidConfiguration);
            }
            // Set up an already-live emitter so a control-submitted run can
            // have observers even if no Session peer was present at admission.
            // A short idle deadline may win during startup. In that case the
            // allowlisted route stays available for a later explicit Restore.
            match service.ordinary_client(id) {
                Ok(client) => match client.area_session(false).await {
                    Ok(_) | Err(super::ordinary::BackendError::Closed) => (),
                    Err(_) => return Err(ServerError::InvalidConfiguration),
                },
                Err(
                    super::service::ServiceError::Busy | super::service::ServiceError::NotLoaded,
                ) => (),
                Err(_) => return Err(ServerError::InvalidConfiguration),
            }
        }
        let authority = ControlAuthority {
            administration,
            mini,
            session_rpc: Arc::new(
                routes
                    .agents
                    .into_iter()
                    .map(|id| {
                        (
                            id,
                            routes
                                .restore_on_attach
                                .then(|| Arc::new(tokio::sync::Mutex::new(()))),
                        )
                    })
                    .collect(),
            ),
            idle_timeout,
        };
        let (listener, lease) = match inherited {
            Some(listener) => (listener, None),
            None => {
                let path = config.socket_path.clone();
                // An abandoned spawn_blocking result still drops its socket lease.
                let (listener, lease) = tokio::task::spawn_blocking(move || bind_endpoint(path))
                    .await
                    .map_err(|_| ServerError::TaskStopped)??;
                (listener, Some(lease))
            }
        };
        let listener = UnixListener::from_std(listener).map_err(|_| ServerError::Bind)?;
        let mut welcome = Welcome {
            protocol: PROTOCOL.into(),
            version: Version::default(),
            host_id: config.host_id,
            epoch: String::from(service.catalog().epoch())
                .try_into()
                .map_err(|_| ServerError::InvalidConfiguration)?,
            capabilities: vec![
                Capability::Status,
                Capability::List,
                Capability::Inspect,
                Capability::Receipts,
                Capability::Results,
                Capability::Submit,
            ],
            limits: Limits {
                max_in_flight: 1,
                ..Limits::default()
            },
        };
        if authority.mini.is_some() {
            welcome.capabilities.push(Capability::Mini);
        }
        if authority.administration.is_some() {
            welcome.capabilities.extend([
                Capability::Profiles,
                Capability::AdministrativeReceipts,
                Capability::AdministrativeCreate,
                Capability::AdministrativeRestore,
                Capability::AdministrativeClose,
                Capability::AdministrativeCancel,
                Capability::AdministrativeStop,
            ]);
        }
        let stop = CancellationToken::new();
        let task = tokio::spawn(serve(
            listener,
            lease,
            config,
            service,
            authority,
            welcome.clone(),
            stop.clone(),
        ));
        Ok(Self {
            welcome,
            stop,
            task: Some(task),
            terminal: None,
        })
    }
    pub fn welcome(&self) -> &Welcome {
        &self.welcome
    }
    pub fn stopped_by_administration(&self) -> bool {
        matches!(self.terminal, Some(Ok(ControlExit::AdministrativeStop)))
    }
    pub(super) fn stopped_for_idleness(&self) -> bool {
        matches!(self.terminal, Some(Ok(ControlExit::Idle)))
    }
    /// Cancellation-safe: abandoning this wait does not discard the task handle.
    pub async fn wait(&mut self) -> Result<(), ServerError> {
        if let Some(result) = self.terminal {
            return result.map(|_| ());
        }
        let result = match self.task.as_mut() {
            Some(task) => task.await.unwrap_or(Err(ServerError::TaskStopped)),
            None => Ok(ControlExit::Stopped),
        };
        self.task.take();
        self.terminal = Some(result);
        result.map(|_| ())
    }
    pub async fn stop(&mut self) -> Result<(), ServerError> {
        self.stop.cancel();
        self.wait().await
    }
}
impl Drop for ControlServer {
    fn drop(&mut self) {
        self.stop.cancel();
    }
}

async fn serve(
    listener: UnixListener,
    lease: Option<SocketLease>,
    config: ControlConfig,
    service: HostService,
    authority: ControlAuthority,
    welcome: Welcome,
    stop: CancellationToken,
) -> Result<ControlExit, ServerError> {
    let native_stop = authority
        .administration
        .as_ref()
        .map(DaemonAdministration::stop_completed)
        .unwrap_or_default();
    let mut connections = JoinSet::new();
    let mut idle = authority.idle_timeout.zip(service.empty_since());
    let mut disconnected_at = Instant::now();
    let result = loop {
        let deadline = idle.as_mut().and_then(|(timeout, empty_since)| {
            empty_since
                .borrow_and_update()
                .map(|since| since.max(disconnected_at) + *timeout)
        });
        let idle_expired = async {
            if let Some(deadline) = deadline {
                tokio::time::sleep_until(deadline).await;
            } else {
                std::future::pending::<()>().await;
            }
        };
        tokio::select! {
            biased;
            _ = native_stop.cancelled() => break Ok(ControlExit::AdministrativeStop),
            _ = stop.cancelled() => break Ok(ControlExit::Stopped),
            Some(_) = connections.join_next(), if !connections.is_empty() => {
                if connections.is_empty() {
                    disconnected_at = Instant::now();
                }
            }
            _ = async { if let Some((_, empty_since)) = idle.as_mut() { let _ = empty_since.changed().await; } }, if idle.is_some() => {},
            accepted = listener.accept() => {
                let (stream, _) = match accepted { Ok(pair) => pair, Err(_) => break Err(ServerError::ListenerStopped) };
                // No task, frame allocation, or auth work for excess connections.
                if connections.len() >= config.max_connections { drop(stream); continue; }
                connections.spawn(connection(stream, config.clone(), service.clone(), authority.clone(), welcome.clone(), native_stop.clone()));
            }
            _ = idle_expired, if connections.is_empty() => {
                let (timeout, _) = idle.as_ref().expect("idle deadline requires a timeout");
                match service.shutdown_if_idle(*timeout).await {
                    Ok(true) => break Ok(ControlExit::Idle),
                    Ok(false) => disconnected_at = Instant::now(),
                    Err(error) => {
                        use std::io::Write;
                        let _ = writeln!(std::io::stderr().lock(), "Host idle shutdown failed: {error}");
                        idle = None;
                    }
                }
            }
        }
    };
    // A completed native Stop closes admission, not the response waiters.
    // Idle readers/handshakes observe native_stop; already-dispatched exchanges
    // may flush within their ORIGINAL total deadline. No new grace per byte,
    // waiter or connection, and no dependency on a peer reading the reply.
    if result != Ok(ControlExit::AdministrativeStop) {
        // External stop/listener failure may abort waits, never owned jobs.
        connections.abort_all();
    }
    while connections.join_next().await.is_some() {}
    // Keep the listener FD alive through the inode check/unlink, so its inode
    // cannot be recycled for a replacement listener before our cleanup check.
    drop(lease);
    drop(listener);
    result
}

async fn connection(
    mut stream: UnixStream,
    config: ControlConfig,
    service: HostService,
    authority: ControlAuthority,
    welcome: Welcome,
    native_stop: CancellationToken,
) {
    if stream.peer_cred().map(|peer| peer.uid()).ok()
        != Some(nix::unistd::Uid::effective().as_raw())
    {
        return;
    }
    #[derive(serde::Deserialize)]
    #[serde(untagged)]
    enum Handshake {
        Control(Hello),
        Session(super::area_rpc::SessionHello),
    }
    let handshake = async {
        let (hello, session) = match read_frame(&mut stream, MAX_FRAME_BYTES).await? {
            Handshake::Control(hello) => (hello, None),
            Handshake::Session(request) => (request.session_rpc, Some(request.agent_id)),
        };
        if !config.token.matches(&hello.token)
            || hello.host_id != config.host_id
            || hello.protocol != PROTOCOL
            || hello.version.major != MAJOR
        {
            return Err(super::client::Failure::IncompatiblePeer);
        }
        if session.is_none() {
            write_frame(&mut stream, &encode_frame(&welcome, MAX_FRAME_BYTES)?).await?;
        }
        Ok(session)
    };
    let handshake_result = tokio::select! {
        biased;
        _ = native_stop.cancelled() => return,
        result = tokio::time::timeout(config.handshake_timeout, handshake) => result,
    };
    match handshake_result {
        Ok(Ok(Some(agent))) => {
            if let Some(gate) = authority.session_rpc.get(&agent) {
                let restore = gate.clone().zip(authority.administration.clone());
                let session = tokio::select! {
                    biased;
                    _ = native_stop.cancelled() => return,
                    result = tokio::time::timeout(config.handshake_timeout,
                        super::area_rpc::Session::open(&service, agent, config.host_id, restore)) => result,
                };
                if let Ok(Ok(session)) = session {
                    session.serve(stream, native_stop).await;
                }
            }
            return;
        }
        Ok(Ok(None)) => (),
        _ => return,
    }
    loop {
        let exchange = async {
            let request: Request = tokio::select! {
                biased;
                _ = native_stop.cancelled() => return Err(super::client::Failure::Connection),
                result = read_frame(&mut stream, welcome.limits.max_frame_bytes) => result?,
            };
            // Once dispatch starts it retains its bounded reply opportunity,
            // including when the owned Stop completes before observe wakes.
            let reply = if request.epoch != welcome.epoch {
                Reply::Error {
                    code: ErrorCode::StaleEpoch,
                }
            } else if !request.command.valid(welcome.limits) {
                Reply::Error {
                    code: ErrorCode::InvalidRequest,
                }
            } else if !welcome.supports(request.command.capability()) {
                Reply::Error {
                    code: ErrorCode::Unsupported,
                }
            } else {
                dispatch(&service, &authority, config.host_id, request.command).await
            };
            let response = Response {
                call_id: request.call_id,
                epoch: welcome.epoch,
                reply,
            };
            let bytes = encode_frame(&response, welcome.limits.max_frame_bytes)?;
            write_frame(&mut stream, &bytes).await
        };
        if !matches!(
            tokio::time::timeout(config.request_timeout, exchange).await,
            Ok(Ok(()))
        ) {
            return;
        }
    }
}
fn catalog_code(error: &CatalogError) -> ErrorCode {
    match error {
        CatalogError::UnknownAgent => ErrorCode::NotFound,
        CatalogError::WorkerStopped => ErrorCode::Busy,
        _ => ErrorCode::Internal,
    }
}
fn catalog_error(error: CatalogError) -> Reply {
    Reply::Error {
        code: catalog_code(&error),
    }
}
fn service_error(error: super::service::ServiceError) -> Reply {
    use super::ordinary::BackendError;
    use super::service::ServiceError;
    Reply::Error {
        code: match error {
            ServiceError::Stopping
            | ServiceError::Busy
            | ServiceError::Backend(BackendError::Busy) => ErrorCode::Busy,
            ServiceError::NotLoaded => ErrorCode::NotFound,
            ServiceError::Backend(BackendError::AdmissionUncertain) => {
                ErrorCode::PersistenceUncertain
            }
            ServiceError::AlreadyOwned => ErrorCode::Conflict,
            ServiceError::Backend(_) | ServiceError::TaskStopped => ErrorCode::Internal,
            ServiceError::Catalog(error) => catalog_code(&error),
            ServiceError::ShutdownIncomplete { .. } => ErrorCode::Internal,
        },
    }
}
fn backend_code(error: &super::ordinary::BackendError) -> ErrorCode {
    use super::ordinary::BackendError;
    match error {
        BackendError::AdmissionUncertain | BackendError::Unsaved => ErrorCode::PersistenceUncertain,
        BackendError::Admission(_) | BackendError::InputTooLarge => ErrorCode::InvalidRequest,
        BackendError::Busy => ErrorCode::Busy,
        BackendError::Closed => ErrorCode::NotFound,
        _ => ErrorCode::Internal,
    }
}
async fn dispatch(
    service: &HostService,
    authority: &ControlAuthority,
    host_id: HostId,
    command: Command,
) -> Reply {
    if matches!(
        command,
        Command::MiniExecute { .. } | Command::MiniReceipt { .. } | Command::MiniResult { .. }
    ) {
        return match &authority.mini {
            Some(mini) => mini.dispatch(command).await,
            None => Reply::Error {
                code: ErrorCode::Unsupported,
            },
        };
    }
    if matches!(
        command,
        Command::Profiles { .. }
            | Command::AdministrativeReceipt { .. }
            | Command::AdministrativeCreate { .. }
            | Command::AdministrativeRestore { .. }
            | Command::AdministrativeClose { .. }
            | Command::AdministrativeCancel { .. }
            | Command::AdministrativeStop { .. }
    ) {
        return administrative::dispatch(authority.administration.as_ref(), command).await;
    }
    let result = match command {
        Command::Status {} => service.catalog().status().await.map(|status| serde_json::json!({
            "epoch": status.epoch, "registered": status.registered, "resident": status.resident,
            "executing": status.executing, "busy": status.busy, "mini": status.mini,
            "max_agents": status.max_agents, "owners": service.owner_count(), "stopping": service.is_stopping(),
        })),
        Command::Inspect { agent_id } => {
            let Ok(id) = String::from(agent_id).try_into() else { return Reply::Error { code: ErrorCode::InvalidRequest }; };
            service.catalog().get(id).await.and_then(|record| serde_json::to_value(record).map_err(CatalogError::from))
        }
        Command::Result { agent_id, request_id, run_id, offset, max_bytes } => {
            return submission_result::query(service, host_id, agent_id, request_id, run_id, offset, max_bytes).await;
        }
        Command::Receipt {
            agent_id,
            request_id,
        } => {
            let Ok(id) = String::from(agent_id).try_into() else {
                return Reply::Error {
                    code: ErrorCode::InvalidRequest,
                };
            };
            // A receipt query is a read of one loaded Agent's native journal.
            // It never loads, replays or resumes anything.
            return match service.admission(id, &String::from(request_id)).await {
                Ok(Some(status)) => match serde_json::to_value(serde_json::json!({
                    "found": true,
                    "agent_id": agent_id,
                    "request_id": request_id,
                    "receipt": status.receipt,
                    "execution": status.execution,
                })) {
                    Ok(data) => Reply::Data { data },
                    Err(_) => Reply::Error {
                        code: ErrorCode::Internal,
                    },
                },
                Ok(None) => Reply::Data {
                    data: serde_json::json!({
                        "found": false,
                        "agent_id": agent_id,
                        "request_id": request_id,
                    }),
                },
                Err(error) => service_error(error),
            };
        }
        Command::Submit {
            agent_id,
            request_id,
            prompt,
        } => {
            let Ok(id) = String::from(agent_id).try_into() else {
                return Reply::Error {
                    code: ErrorCode::InvalidRequest,
                };
            };
            let client = match service.ordinary_client(id) {
                Ok(client) => client,
                Err(error) => return service_error(error),
            };
            // Stable message identity: the wire submit is plain text, so a
            // retry of the same request id must serialize identically. Ordering
            // comes from entry sequences, not a wall-clock message stamp.
            let messages = vec![rpi_ai::UserMessage::new(prompt, 0).into()];
            let ticket = match client
                .submit_admitted(
                    String::from(host_id),
                    String::from(request_id),
                    messages,
                )
                .await
            {
                Ok(ticket) => ticket,
                Err(error) => {
                    return Reply::Error {
                        code: backend_code(&error),
                    }
                }
            };
            // Only the durable admission is awaited here. Execution continues in
            // the supervised backend after this reply, so the reply is not a run
            // result and not an exactly-once tool side-effect proof.
            return match ticket.wait_admitted().await {
                Ok(receipt) => Reply::Data {
                    data: serde_json::json!({
                        "durable": true,
                        "agent_id": agent_id,
                        "request_id": request_id,
                        "receipt": receipt,
                    }),
                },
                Err(error) => Reply::Error {
                    code: backend_code(&error),
                },
            };
        }
        Command::List { after, limit } => {
            let after = match after.map(|id| String::from(id).try_into()).transpose() { Ok(value) => value, Err(_) => return Reply::Error { code: ErrorCode::InvalidRequest } };
            service.catalog().list(after, limit).await.map(|page| {
                // A list is a bounded summary, never 128 full launch records.
                let agents: Vec<_> = page.agents.into_iter().map(|record| serde_json::json!({
                    "id": record.spec.id, "name": record.spec.name, "parent_id": record.spec.parent_id,
                    "mode": record.spec.mode, "state": record.state, "revision": record.revision,
                })).collect();
                serde_json::json!({"agents": agents, "next_cursor": page.next_cursor})
            })
        }
        _ => return Reply::Error { code: ErrorCode::Unsupported },
    };
    match result {
        Ok(data) => Reply::Data { data },
        Err(error) => catalog_error(error),
    }
}

#[path = "submission_result.rs"]
mod submission_result;

#[path = "server_administration.rs"]
mod administrative;

#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;