Skip to main content

rpi_cli/host/
server.rs

1//! Authenticated, bounded Unix control endpoint. Capabilities are implementation
2//! promises, not an enumeration of the eventual protocol. Native prompt
3//! admission/receipts are supported. Administrative execution only accepts
4//! complete profile, guarded Close/CancelSubmitted and Stop intents through the
5//! daemon's fixed native authority and durable coordinator; legacy ops stay off.
6
7use super::{
8    area_rpc::SessionRoutes,
9    client::{encode_frame, read_frame, write_frame},
10    daemon::DaemonAdministration,
11    protocol::*,
12    service::HostService,
13    CatalogError,
14};
15use std::{collections::BTreeMap, path::PathBuf, sync::Arc, time::Duration};
16use tokio::{
17    net::{UnixListener, UnixStream},
18    task::{JoinHandle, JoinSet},
19    time::Instant,
20};
21use tokio_util::sync::CancellationToken;
22
23type SessionRoutesByAgent = BTreeMap<super::AgentId, Option<Arc<tokio::sync::Mutex<()>>>>;
24
25#[derive(Clone, Default)]
26struct ControlAuthority {
27    administration: Option<DaemonAdministration>,
28    mini: Option<super::mini_control::MiniControl>,
29    session_rpc: Arc<SessionRoutesByAgent>,
30    idle_timeout: Option<Duration>,
31}
32
33#[derive(Clone)]
34pub struct ControlConfig {
35    pub socket_path: PathBuf,
36    pub host_id: HostId,
37    pub token: AuthToken,
38    pub max_connections: usize,
39    pub handshake_timeout: Duration,
40    /// Total idle/read + dispatch + write budget per query, not per byte.
41    pub request_timeout: Duration,
42}
43impl ControlConfig {
44    pub fn validate(&self) -> Result<(), ServerError> {
45        if !self.socket_path.is_absolute()
46            || !(1..=64).contains(&self.max_connections)
47            || [self.handshake_timeout, self.request_timeout]
48                .iter()
49                .any(|duration| duration.is_zero() || *duration > Duration::from_secs(300))
50        {
51            return Err(ServerError::InvalidConfiguration);
52        }
53        Ok(())
54    }
55}
56
57/// Fixed diagnostics never contain wire input, tokens, paths or OS errors.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
59pub enum ServerError {
60    #[error("invalid shared Host control configuration")]
61    InvalidConfiguration,
62    #[error("shared Host endpoint must be absent, with a private owned parent")]
63    UnsafeEndpoint,
64    #[error("shared Host endpoint could not be bound")]
65    Bind,
66    #[error("shared Host control listener stopped unexpectedly")]
67    ListenerStopped,
68    #[error("shared Host control task stopped unexpectedly")]
69    TaskStopped,
70}
71
72/// Remove only the socket inode this listener created. Never remove a newer
73/// listener, replacement file or stale socket belonging to somebody else.
74pub(super) struct SocketLease {
75    path: PathBuf,
76    dev: u64,
77    ino: u64,
78    unlink_on_drop: bool,
79}
80impl SocketLease {
81    #[cfg(target_os = "macos")]
82    pub(super) fn identity(&self) -> (u64, u64) {
83        (self.dev, self.ino)
84    }
85
86    #[cfg(target_os = "macos")]
87    pub(super) fn inherited(path: PathBuf, (dev, ino): (u64, u64)) -> Self {
88        Self {
89            path,
90            dev,
91            ino,
92            unlink_on_drop: false,
93        }
94    }
95
96    pub(super) fn remove(&self) {
97        use std::os::unix::fs::{FileTypeExt, MetadataExt};
98        if let Ok(metadata) = std::fs::symlink_metadata(&self.path) {
99            if metadata.file_type().is_socket()
100                && metadata.dev() == self.dev
101                && metadata.ino() == self.ino
102            {
103                let _ = std::fs::remove_file(&self.path);
104            }
105        }
106    }
107}
108impl Drop for SocketLease {
109    fn drop(&mut self) {
110        if self.unlink_on_drop {
111            self.remove();
112        }
113    }
114}
115pub(super) fn bind_endpoint(
116    path: PathBuf,
117) -> Result<(std::os::unix::net::UnixListener, SocketLease), ServerError> {
118    use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
119    let parent = path.parent().ok_or(ServerError::InvalidConfiguration)?;
120    let metadata = std::fs::symlink_metadata(parent).map_err(|_| ServerError::UnsafeEndpoint)?;
121    if !metadata.is_dir()
122        || metadata.uid() != nix::unistd::Uid::effective().as_raw()
123        || metadata.mode() & 0o077 != 0
124    {
125        return Err(ServerError::UnsafeEndpoint);
126    }
127    match std::fs::symlink_metadata(&path) {
128        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
129        _ => return Err(ServerError::UnsafeEndpoint),
130    }
131    let listener = std::os::unix::net::UnixListener::bind(&path).map_err(|_| ServerError::Bind)?;
132    let metadata = std::fs::symlink_metadata(&path).map_err(|_| ServerError::Bind)?;
133    let lease = SocketLease {
134        path: path.clone(),
135        dev: metadata.dev(),
136        ino: metadata.ino(),
137        unlink_on_drop: true,
138    };
139    if !metadata.file_type().is_socket()
140        || metadata.nlink() != 1
141        || metadata.uid() != nix::unistd::Uid::effective().as_raw()
142    {
143        return Err(ServerError::UnsafeEndpoint);
144    }
145    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
146        .map_err(|_| ServerError::Bind)?;
147    listener
148        .set_nonblocking(true)
149        .map_err(|_| ServerError::Bind)?;
150    Ok((listener, lease))
151}
152
153/// Explicit stop waits for all connection tasks and inode cleanup. Drop merely
154/// requests that cleanup; it never closes Agents or shuts down the catalog.
155pub struct ControlServer {
156    welcome: Welcome,
157    stop: CancellationToken,
158    task: Option<JoinHandle<Result<ControlExit, ServerError>>>,
159    terminal: Option<Result<ControlExit, ServerError>>,
160}
161
162#[derive(Clone, Copy, PartialEq, Eq)]
163enum ControlExit {
164    Stopped,
165    AdministrativeStop,
166    Idle,
167}
168impl ControlServer {
169    pub async fn bind(config: ControlConfig, service: HostService) -> Result<Self, ServerError> {
170        Self::bind_with_administration(config, service, None).await
171    }
172    pub(crate) async fn bind_with_administration(
173        config: ControlConfig,
174        service: HostService,
175        administration: Option<DaemonAdministration>,
176    ) -> Result<Self, ServerError> {
177        Self::bind_with_controls(
178            config,
179            service,
180            administration,
181            None,
182            None,
183            SessionRoutes::default(),
184            None,
185        )
186        .await
187    }
188    pub(super) async fn bind_with_controls(
189        config: ControlConfig,
190        service: HostService,
191        administration: Option<DaemonAdministration>,
192        mini: Option<super::mini_control::MiniControl>,
193        inherited: Option<std::os::unix::net::UnixListener>,
194        routes: SessionRoutes,
195        idle_timeout: Option<Duration>,
196    ) -> Result<Self, ServerError> {
197        config.validate()?;
198        if routes.restore_on_attach && administration.is_none() {
199            return Err(ServerError::InvalidConfiguration);
200        }
201        for &id in &routes.agents {
202            let record = service
203                .catalog()
204                .get(id)
205                .await
206                .map_err(|_| ServerError::InvalidConfiguration)?;
207            if record.spec.mode != super::AgentMode::Persistent {
208                return Err(ServerError::InvalidConfiguration);
209            }
210            // Set up an already-live emitter so a control-submitted run can
211            // have observers even if no Session peer was present at admission.
212            // A short idle deadline may win during startup. In that case the
213            // allowlisted route stays available for a later explicit Restore.
214            match service.ordinary_client(id) {
215                Ok(client) => match client.area_session(false).await {
216                    Ok(_) | Err(super::ordinary::BackendError::Closed) => (),
217                    Err(_) => return Err(ServerError::InvalidConfiguration),
218                },
219                Err(
220                    super::service::ServiceError::Busy | super::service::ServiceError::NotLoaded,
221                ) => (),
222                Err(_) => return Err(ServerError::InvalidConfiguration),
223            }
224        }
225        let authority = ControlAuthority {
226            administration,
227            mini,
228            session_rpc: Arc::new(
229                routes
230                    .agents
231                    .into_iter()
232                    .map(|id| {
233                        (
234                            id,
235                            routes
236                                .restore_on_attach
237                                .then(|| Arc::new(tokio::sync::Mutex::new(()))),
238                        )
239                    })
240                    .collect(),
241            ),
242            idle_timeout,
243        };
244        let (listener, lease) = match inherited {
245            Some(listener) => (listener, None),
246            None => {
247                let path = config.socket_path.clone();
248                // An abandoned spawn_blocking result still drops its socket lease.
249                let (listener, lease) = tokio::task::spawn_blocking(move || bind_endpoint(path))
250                    .await
251                    .map_err(|_| ServerError::TaskStopped)??;
252                (listener, Some(lease))
253            }
254        };
255        let listener = UnixListener::from_std(listener).map_err(|_| ServerError::Bind)?;
256        let mut welcome = Welcome {
257            protocol: PROTOCOL.into(),
258            version: Version::default(),
259            host_id: config.host_id,
260            epoch: String::from(service.catalog().epoch())
261                .try_into()
262                .map_err(|_| ServerError::InvalidConfiguration)?,
263            capabilities: vec![
264                Capability::Status,
265                Capability::List,
266                Capability::Inspect,
267                Capability::Receipts,
268                Capability::Results,
269                Capability::Submit,
270            ],
271            limits: Limits {
272                max_in_flight: 1,
273                ..Limits::default()
274            },
275        };
276        if authority.mini.is_some() {
277            welcome.capabilities.push(Capability::Mini);
278        }
279        if authority.administration.is_some() {
280            welcome.capabilities.extend([
281                Capability::Profiles,
282                Capability::AdministrativeReceipts,
283                Capability::AdministrativeCreate,
284                Capability::AdministrativeRestore,
285                Capability::AdministrativeClose,
286                Capability::AdministrativeCancel,
287                Capability::AdministrativeStop,
288            ]);
289        }
290        let stop = CancellationToken::new();
291        let task = tokio::spawn(serve(
292            listener,
293            lease,
294            config,
295            service,
296            authority,
297            welcome.clone(),
298            stop.clone(),
299        ));
300        Ok(Self {
301            welcome,
302            stop,
303            task: Some(task),
304            terminal: None,
305        })
306    }
307    pub fn welcome(&self) -> &Welcome {
308        &self.welcome
309    }
310    pub fn stopped_by_administration(&self) -> bool {
311        matches!(self.terminal, Some(Ok(ControlExit::AdministrativeStop)))
312    }
313    pub(super) fn stopped_for_idleness(&self) -> bool {
314        matches!(self.terminal, Some(Ok(ControlExit::Idle)))
315    }
316    /// Cancellation-safe: abandoning this wait does not discard the task handle.
317    pub async fn wait(&mut self) -> Result<(), ServerError> {
318        if let Some(result) = self.terminal {
319            return result.map(|_| ());
320        }
321        let result = match self.task.as_mut() {
322            Some(task) => task.await.unwrap_or(Err(ServerError::TaskStopped)),
323            None => Ok(ControlExit::Stopped),
324        };
325        self.task.take();
326        self.terminal = Some(result);
327        result.map(|_| ())
328    }
329    pub async fn stop(&mut self) -> Result<(), ServerError> {
330        self.stop.cancel();
331        self.wait().await
332    }
333}
334impl Drop for ControlServer {
335    fn drop(&mut self) {
336        self.stop.cancel();
337    }
338}
339
340async fn serve(
341    listener: UnixListener,
342    lease: Option<SocketLease>,
343    config: ControlConfig,
344    service: HostService,
345    authority: ControlAuthority,
346    welcome: Welcome,
347    stop: CancellationToken,
348) -> Result<ControlExit, ServerError> {
349    let native_stop = authority
350        .administration
351        .as_ref()
352        .map(DaemonAdministration::stop_completed)
353        .unwrap_or_default();
354    let mut connections = JoinSet::new();
355    let mut idle = authority.idle_timeout.zip(service.empty_since());
356    let mut disconnected_at = Instant::now();
357    let result = loop {
358        let deadline = idle.as_mut().and_then(|(timeout, empty_since)| {
359            empty_since
360                .borrow_and_update()
361                .map(|since| since.max(disconnected_at) + *timeout)
362        });
363        let idle_expired = async {
364            if let Some(deadline) = deadline {
365                tokio::time::sleep_until(deadline).await;
366            } else {
367                std::future::pending::<()>().await;
368            }
369        };
370        tokio::select! {
371            biased;
372            _ = native_stop.cancelled() => break Ok(ControlExit::AdministrativeStop),
373            _ = stop.cancelled() => break Ok(ControlExit::Stopped),
374            Some(_) = connections.join_next(), if !connections.is_empty() => {
375                if connections.is_empty() {
376                    disconnected_at = Instant::now();
377                }
378            }
379            _ = async { if let Some((_, empty_since)) = idle.as_mut() { let _ = empty_since.changed().await; } }, if idle.is_some() => {},
380            accepted = listener.accept() => {
381                let (stream, _) = match accepted { Ok(pair) => pair, Err(_) => break Err(ServerError::ListenerStopped) };
382                // No task, frame allocation, or auth work for excess connections.
383                if connections.len() >= config.max_connections { drop(stream); continue; }
384                connections.spawn(connection(stream, config.clone(), service.clone(), authority.clone(), welcome.clone(), native_stop.clone()));
385            }
386            _ = idle_expired, if connections.is_empty() => {
387                let (timeout, _) = idle.as_ref().expect("idle deadline requires a timeout");
388                match service.shutdown_if_idle(*timeout).await {
389                    Ok(true) => break Ok(ControlExit::Idle),
390                    Ok(false) => disconnected_at = Instant::now(),
391                    Err(error) => {
392                        use std::io::Write;
393                        let _ = writeln!(std::io::stderr().lock(), "Host idle shutdown failed: {error}");
394                        idle = None;
395                    }
396                }
397            }
398        }
399    };
400    // A completed native Stop closes admission, not the response waiters.
401    // Idle readers/handshakes observe native_stop; already-dispatched exchanges
402    // may flush within their ORIGINAL total deadline. No new grace per byte,
403    // waiter or connection, and no dependency on a peer reading the reply.
404    if result != Ok(ControlExit::AdministrativeStop) {
405        // External stop/listener failure may abort waits, never owned jobs.
406        connections.abort_all();
407    }
408    while connections.join_next().await.is_some() {}
409    // Keep the listener FD alive through the inode check/unlink, so its inode
410    // cannot be recycled for a replacement listener before our cleanup check.
411    drop(lease);
412    drop(listener);
413    result
414}
415
416async fn connection(
417    mut stream: UnixStream,
418    config: ControlConfig,
419    service: HostService,
420    authority: ControlAuthority,
421    welcome: Welcome,
422    native_stop: CancellationToken,
423) {
424    if stream.peer_cred().map(|peer| peer.uid()).ok()
425        != Some(nix::unistd::Uid::effective().as_raw())
426    {
427        return;
428    }
429    #[derive(serde::Deserialize)]
430    #[serde(untagged)]
431    enum Handshake {
432        Control(Hello),
433        Session(super::area_rpc::SessionHello),
434    }
435    let handshake = async {
436        let (hello, session) = match read_frame(&mut stream, MAX_FRAME_BYTES).await? {
437            Handshake::Control(hello) => (hello, None),
438            Handshake::Session(request) => (request.session_rpc, Some(request.agent_id)),
439        };
440        if !config.token.matches(&hello.token)
441            || hello.host_id != config.host_id
442            || hello.protocol != PROTOCOL
443            || hello.version.major != MAJOR
444        {
445            return Err(super::client::Failure::IncompatiblePeer);
446        }
447        if session.is_none() {
448            write_frame(&mut stream, &encode_frame(&welcome, MAX_FRAME_BYTES)?).await?;
449        }
450        Ok(session)
451    };
452    let handshake_result = tokio::select! {
453        biased;
454        _ = native_stop.cancelled() => return,
455        result = tokio::time::timeout(config.handshake_timeout, handshake) => result,
456    };
457    match handshake_result {
458        Ok(Ok(Some(agent))) => {
459            if let Some(gate) = authority.session_rpc.get(&agent) {
460                let restore = gate.clone().zip(authority.administration.clone());
461                let session = tokio::select! {
462                    biased;
463                    _ = native_stop.cancelled() => return,
464                    result = tokio::time::timeout(config.handshake_timeout,
465                        super::area_rpc::Session::open(&service, agent, config.host_id, restore)) => result,
466                };
467                if let Ok(Ok(session)) = session {
468                    session.serve(stream, native_stop).await;
469                }
470            }
471            return;
472        }
473        Ok(Ok(None)) => (),
474        _ => return,
475    }
476    loop {
477        let exchange = async {
478            let request: Request = tokio::select! {
479                biased;
480                _ = native_stop.cancelled() => return Err(super::client::Failure::Connection),
481                result = read_frame(&mut stream, welcome.limits.max_frame_bytes) => result?,
482            };
483            // Once dispatch starts it retains its bounded reply opportunity,
484            // including when the owned Stop completes before observe wakes.
485            let reply = if request.epoch != welcome.epoch {
486                Reply::Error {
487                    code: ErrorCode::StaleEpoch,
488                }
489            } else if !request.command.valid(welcome.limits) {
490                Reply::Error {
491                    code: ErrorCode::InvalidRequest,
492                }
493            } else if !welcome.supports(request.command.capability()) {
494                Reply::Error {
495                    code: ErrorCode::Unsupported,
496                }
497            } else {
498                dispatch(&service, &authority, config.host_id, request.command).await
499            };
500            let response = Response {
501                call_id: request.call_id,
502                epoch: welcome.epoch,
503                reply,
504            };
505            let bytes = encode_frame(&response, welcome.limits.max_frame_bytes)?;
506            write_frame(&mut stream, &bytes).await
507        };
508        if !matches!(
509            tokio::time::timeout(config.request_timeout, exchange).await,
510            Ok(Ok(()))
511        ) {
512            return;
513        }
514    }
515}
516fn catalog_code(error: &CatalogError) -> ErrorCode {
517    match error {
518        CatalogError::UnknownAgent => ErrorCode::NotFound,
519        CatalogError::WorkerStopped => ErrorCode::Busy,
520        _ => ErrorCode::Internal,
521    }
522}
523fn catalog_error(error: CatalogError) -> Reply {
524    Reply::Error {
525        code: catalog_code(&error),
526    }
527}
528fn service_error(error: super::service::ServiceError) -> Reply {
529    use super::ordinary::BackendError;
530    use super::service::ServiceError;
531    Reply::Error {
532        code: match error {
533            ServiceError::Stopping
534            | ServiceError::Busy
535            | ServiceError::Backend(BackendError::Busy) => ErrorCode::Busy,
536            ServiceError::NotLoaded => ErrorCode::NotFound,
537            ServiceError::Backend(BackendError::AdmissionUncertain) => {
538                ErrorCode::PersistenceUncertain
539            }
540            ServiceError::AlreadyOwned => ErrorCode::Conflict,
541            ServiceError::Backend(_) | ServiceError::TaskStopped => ErrorCode::Internal,
542            ServiceError::Catalog(error) => catalog_code(&error),
543            ServiceError::ShutdownIncomplete { .. } => ErrorCode::Internal,
544        },
545    }
546}
547fn backend_code(error: &super::ordinary::BackendError) -> ErrorCode {
548    use super::ordinary::BackendError;
549    match error {
550        BackendError::AdmissionUncertain | BackendError::Unsaved => ErrorCode::PersistenceUncertain,
551        BackendError::Admission(_) | BackendError::InputTooLarge => ErrorCode::InvalidRequest,
552        BackendError::Busy => ErrorCode::Busy,
553        BackendError::Closed => ErrorCode::NotFound,
554        _ => ErrorCode::Internal,
555    }
556}
557async fn dispatch(
558    service: &HostService,
559    authority: &ControlAuthority,
560    host_id: HostId,
561    command: Command,
562) -> Reply {
563    if matches!(
564        command,
565        Command::MiniExecute { .. } | Command::MiniReceipt { .. } | Command::MiniResult { .. }
566    ) {
567        return match &authority.mini {
568            Some(mini) => mini.dispatch(command).await,
569            None => Reply::Error {
570                code: ErrorCode::Unsupported,
571            },
572        };
573    }
574    if matches!(
575        command,
576        Command::Profiles { .. }
577            | Command::AdministrativeReceipt { .. }
578            | Command::AdministrativeCreate { .. }
579            | Command::AdministrativeRestore { .. }
580            | Command::AdministrativeClose { .. }
581            | Command::AdministrativeCancel { .. }
582            | Command::AdministrativeStop { .. }
583    ) {
584        return administrative::dispatch(authority.administration.as_ref(), command).await;
585    }
586    let result = match command {
587        Command::Status {} => service.catalog().status().await.map(|status| serde_json::json!({
588            "epoch": status.epoch, "registered": status.registered, "resident": status.resident,
589            "executing": status.executing, "busy": status.busy, "mini": status.mini,
590            "max_agents": status.max_agents, "owners": service.owner_count(), "stopping": service.is_stopping(),
591        })),
592        Command::Inspect { agent_id } => {
593            let Ok(id) = String::from(agent_id).try_into() else { return Reply::Error { code: ErrorCode::InvalidRequest }; };
594            service.catalog().get(id).await.and_then(|record| serde_json::to_value(record).map_err(CatalogError::from))
595        }
596        Command::Result { agent_id, request_id, run_id, offset, max_bytes } => {
597            return submission_result::query(service, host_id, agent_id, request_id, run_id, offset, max_bytes).await;
598        }
599        Command::Receipt {
600            agent_id,
601            request_id,
602        } => {
603            let Ok(id) = String::from(agent_id).try_into() else {
604                return Reply::Error {
605                    code: ErrorCode::InvalidRequest,
606                };
607            };
608            // A receipt query is a read of one loaded Agent's native journal.
609            // It never loads, replays or resumes anything.
610            return match service.admission(id, &String::from(request_id)).await {
611                Ok(Some(status)) => match serde_json::to_value(serde_json::json!({
612                    "found": true,
613                    "agent_id": agent_id,
614                    "request_id": request_id,
615                    "receipt": status.receipt,
616                    "execution": status.execution,
617                })) {
618                    Ok(data) => Reply::Data { data },
619                    Err(_) => Reply::Error {
620                        code: ErrorCode::Internal,
621                    },
622                },
623                Ok(None) => Reply::Data {
624                    data: serde_json::json!({
625                        "found": false,
626                        "agent_id": agent_id,
627                        "request_id": request_id,
628                    }),
629                },
630                Err(error) => service_error(error),
631            };
632        }
633        Command::Submit {
634            agent_id,
635            request_id,
636            prompt,
637        } => {
638            let Ok(id) = String::from(agent_id).try_into() else {
639                return Reply::Error {
640                    code: ErrorCode::InvalidRequest,
641                };
642            };
643            let client = match service.ordinary_client(id) {
644                Ok(client) => client,
645                Err(error) => return service_error(error),
646            };
647            // Stable message identity: the wire submit is plain text, so a
648            // retry of the same request id must serialize identically. Ordering
649            // comes from entry sequences, not a wall-clock message stamp.
650            let messages = vec![rpi_ai::UserMessage::new(prompt, 0).into()];
651            let ticket = match client
652                .submit_admitted(
653                    String::from(host_id),
654                    String::from(request_id),
655                    messages,
656                )
657                .await
658            {
659                Ok(ticket) => ticket,
660                Err(error) => {
661                    return Reply::Error {
662                        code: backend_code(&error),
663                    }
664                }
665            };
666            // Only the durable admission is awaited here. Execution continues in
667            // the supervised backend after this reply, so the reply is not a run
668            // result and not an exactly-once tool side-effect proof.
669            return match ticket.wait_admitted().await {
670                Ok(receipt) => Reply::Data {
671                    data: serde_json::json!({
672                        "durable": true,
673                        "agent_id": agent_id,
674                        "request_id": request_id,
675                        "receipt": receipt,
676                    }),
677                },
678                Err(error) => Reply::Error {
679                    code: backend_code(&error),
680                },
681            };
682        }
683        Command::List { after, limit } => {
684            let after = match after.map(|id| String::from(id).try_into()).transpose() { Ok(value) => value, Err(_) => return Reply::Error { code: ErrorCode::InvalidRequest } };
685            service.catalog().list(after, limit).await.map(|page| {
686                // A list is a bounded summary, never 128 full launch records.
687                let agents: Vec<_> = page.agents.into_iter().map(|record| serde_json::json!({
688                    "id": record.spec.id, "name": record.spec.name, "parent_id": record.spec.parent_id,
689                    "mode": record.spec.mode, "state": record.state, "revision": record.revision,
690                })).collect();
691                serde_json::json!({"agents": agents, "next_cursor": page.next_cursor})
692            })
693        }
694        _ => return Reply::Error { code: ErrorCode::Unsupported },
695    };
696    match result {
697        Ok(data) => Reply::Data { data },
698        Err(error) => catalog_error(error),
699    }
700}
701
702#[path = "submission_result.rs"]
703mod submission_result;
704
705#[path = "server_administration.rs"]
706mod administrative;
707
708#[cfg(test)]
709#[path = "server_tests.rs"]
710mod tests;