Skip to main content

adk_kernel/control/
client.rs

1//! The control-plane client the CLI and other surfaces use (spec 3.2 §7.11, §8.1).
2
3use std::collections::VecDeque;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use adk_core::{AdkError, ApprovalAction, ErrorCategory, ErrorComponent};
8use futures::stream::{self, BoxStream, StreamExt};
9use hyper::body::Bytes;
10use hyper::{Method, StatusCode};
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13use serde_json::Value;
14
15use super::api::{
16    AgendaItemResponse, AgendaQuery, AgendaResponse, ApprovalItem, AttachRequest, AttachResponse,
17    FreezeRequest, FreezeResponse, KillRequest, NiceRequest, ProcessResponse, ProcessesQuery,
18    ProcessesResponse, RejectRequest, RunNowRequest, ScheduleRequest, SpawnRequest, SteerRequest,
19    SteerResponse,
20};
21use super::{ControlPlaneConfig, paths};
22use crate::agenda::AgendaItem;
23use crate::bus::EventRecord;
24use crate::error::{self, KernelError, Result};
25use crate::kernel::KernelHealth;
26use crate::process::Process;
27use crate::sched::QueueClass;
28use crate::wake::WakeSet;
29
30/// The approvals inbox, beside the kernel routes under `/api`.
31const APPROVALS: &str = "/approvals";
32
33/// How long a call other than [`events`](ControlClient::events) waits for the kernel.
34const CALL_TIMEOUT: Duration = Duration::from_secs(30);
35
36/// A client of a running kernel's control plane (spec 3.2 §7.11), over its Unix socket, its
37/// named pipe on Windows (§10 W2) or HTTP. Surfaces hold no state (K-I17): every call reads
38/// the kernel.
39///
40/// # Example
41///
42/// ```rust,no_run
43/// use adk_kernel::control::ControlClient;
44///
45/// # async fn example(home: &std::path::Path) -> adk_kernel::Result<()> {
46/// let client = match ControlClient::connect_local(home).await? {
47///     Some(client) => client,
48///     None => ControlClient::http("https://kernel.example.com").with_bearer_token("token"),
49/// };
50/// for process in client.processes(&Default::default()).await? {
51///     println!("{} {:?}", process.meta.pid, process.run.state);
52/// }
53/// # Ok(())
54/// # }
55/// ```
56#[derive(Debug, Clone)]
57pub struct ControlClient {
58    transport: Transport,
59    token: Option<String>,
60}
61
62#[derive(Debug, Clone)]
63enum Transport {
64    Socket(PathBuf),
65    #[cfg(windows)]
66    Pipe(String),
67    Http {
68        base: String,
69        client: reqwest::Client,
70    },
71}
72
73/// A response's status and body.
74struct Answer {
75    status: StatusCode,
76    body: BoxStream<'static, Result<Bytes>>,
77}
78
79impl Answer {
80    async fn bytes(self) -> Result<Vec<u8>> {
81        let mut body = self.body;
82        let mut bytes = Vec::new();
83        while let Some(chunk) = body.next().await {
84            bytes.extend_from_slice(&chunk?);
85        }
86        Ok(bytes)
87    }
88}
89
90impl ControlClient {
91    /// A client of the kernel listening on the Unix socket at `path`.
92    pub fn socket(path: impl Into<PathBuf>) -> Self {
93        Self { transport: Transport::Socket(path.into()), token: None }
94    }
95
96    /// A client of the kernel listening on the named pipe `name` (Windows; spec 3.2 §10 W2),
97    /// as [`ControlPlaneConfig::pipe_name`] names it. The client talks to the pipe only when
98    /// its owner is the user running the client.
99    #[cfg(windows)]
100    pub fn pipe(name: impl Into<String>) -> Self {
101        Self { transport: Transport::Pipe(name.into()), token: None }
102    }
103
104    /// A client of the kernel serving HTTP at `base_url`, the routes under its `/api`.
105    pub fn http(base_url: impl Into<String>) -> Self {
106        let base = base_url.into().trim_end_matches('/').to_string();
107        Self { transport: Transport::Http { base, client: reqwest::Client::new() }, token: None }
108    }
109
110    /// Sends `token` as a bearer token.
111    #[must_use]
112    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
113        self.token = Some(token.into());
114        self
115    }
116
117    /// The bearer token the client sends, so a caller of other routes on the same control
118    /// plane (the approvals inbox, spec 3.3 §6) sends the same one.
119    ///
120    /// # Example
121    ///
122    /// ```rust
123    /// use adk_kernel::control::ControlClient;
124    ///
125    /// let client = ControlClient::http("https://kernel.example.com").with_bearer_token("token");
126    /// assert_eq!(client.bearer_token(), Some("token"));
127    /// assert_eq!(ControlClient::socket("/run/kernel.sock").bearer_token(), None);
128    /// ```
129    pub fn bearer_token(&self) -> Option<&str> {
130        self.token.as_deref()
131    }
132
133    /// Where the client connects: `unix:<path>`, `pipe:<name>` or the base URL.
134    pub fn endpoint(&self) -> String {
135        match &self.transport {
136            Transport::Socket(path) => format!("unix:{}", path.display()),
137            #[cfg(windows)]
138            Transport::Pipe(name) => format!("pipe:{name}"),
139            Transport::Http { base, .. } => base.clone(),
140        }
141    }
142
143    /// A client of the kernel running at `home`, or `None` when none answers on its socket,
144    /// or on Windows its named pipe (spec 3.2 §10 W2).
145    ///
146    /// A socket left by a kernel that did not stop cleanly counts as none; a pipe goes away
147    /// with its kernel.
148    ///
149    /// # Errors
150    ///
151    /// Returns [`KernelError::ControlPlane`] when the socket or pipe exists but this user may
152    /// not use it: another account owns it, or its permissions refuse this user; or when the
153    /// directory of its own that a socket too long for the home sits in is a symlink, another
154    /// user's, or open to other users (spec 3.3 G18).
155    pub async fn connect_local(home: &Path) -> Result<Option<Self>> {
156        #[cfg(windows)]
157        {
158            let Some(name) = ControlPlaneConfig::default().pipe_name(home) else {
159                return Ok(None);
160            };
161            match super::pipe::answers(&name).await {
162                Ok(true) => Ok(Some(Self::pipe(name))),
163                Ok(false) => Ok(None),
164                Err(error) => Err(KernelError::ControlPlane {
165                    reason: format!(
166                        "the kernel pipe {name} exists but cannot be used: {error}; it admits \
167                         only the OS user that runs the kernel"
168                    ),
169                }),
170            }
171        }
172        #[cfg(not(windows))]
173        {
174            let Some(path) = ControlPlaneConfig::default().socket_path(home) else {
175                return Ok(None);
176            };
177            connect_local_socket(path, &home.join(ControlPlaneConfig::DEFAULT_SOCKET)).await
178        }
179    }
180
181    /// `GET /kernel/health`.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
186    /// error the kernel answered.
187    pub async fn health(&self) -> Result<KernelHealth> {
188        self.call(Method::GET, paths::HEALTH.to_string(), None::<&()>).await
189    }
190
191    /// `GET /kernel/inventory`: what the kernel runs, and a warning for each thing it would
192    /// silently not do (`Kernel::inventory`); for the `operator` scope.
193    ///
194    /// # Errors
195    ///
196    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
197    /// kernel's error for a caller without the `operator` scope.
198    pub async fn inventory(&self) -> Result<crate::inventory::KernelInventory> {
199        self.call(Method::GET, paths::INVENTORY.to_string(), None::<&()>).await
200    }
201
202    /// `GET /kernel/partitions`: the partition table (spec 3.2 §7.8).
203    ///
204    /// # Errors
205    ///
206    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
207    /// error the kernel answered.
208    pub async fn partitions(&self) -> Result<Vec<crate::partition::Partition>> {
209        let answer: super::api::PartitionsResponse =
210            self.call(Method::GET, paths::PARTITIONS.to_string(), None::<&()>).await?;
211        Ok(answer.partitions)
212    }
213
214    /// `GET /kernel/agents`: the agents a person added, but tombstones and refused
215    /// suggestions (spec 3.3 §10 K7).
216    ///
217    /// # Errors
218    ///
219    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
220    /// error the kernel answered.
221    pub async fn agents(&self) -> Result<Vec<crate::agents::AgentView>> {
222        let answer: super::api::AgentsResponse =
223            self.call(Method::GET, paths::AGENTS.to_string(), None::<&()>).await?;
224        Ok(answer.agents)
225    }
226
227    /// `GET /kernel/agents/{id}`: one agent a person added, tombstones included (spec 3.3
228    /// §10 K7).
229    ///
230    /// # Errors
231    ///
232    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
233    /// error the kernel answered: `kernel.agent.not_found` for an unknown id.
234    pub async fn agent(&self, id: &str) -> Result<crate::agents::AgentView> {
235        let path = paths::AGENT.replace("{id}", &encode(id));
236        self.call(Method::GET, path, None::<&()>).await
237    }
238
239    /// `POST /kernel/partitions`: creates or replaces `partition` (spec 3.2 §7.8).
240    ///
241    /// # Errors
242    ///
243    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
244    /// error the kernel answered.
245    pub async fn put_partition(
246        &self,
247        partition: &crate::partition::Partition,
248    ) -> Result<crate::partition::Partition> {
249        let answer: super::api::PartitionResponse =
250            self.call(Method::POST, paths::PARTITIONS.to_string(), Some(partition)).await?;
251        Ok(answer.partition)
252    }
253
254    /// `POST /kernel/partitions/{id}/mode`: sets partition `id`'s mode (spec 3.2 §8.1).
255    ///
256    /// # Errors
257    ///
258    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
259    /// error the kernel answered.
260    pub async fn set_partition_mode(
261        &self,
262        id: &str,
263        mode: crate::partition::PartitionMode,
264    ) -> Result<crate::partition::Partition> {
265        let path = paths::PARTITION_MODE.replace("{id}", &encode(id));
266        let body = super::api::PartitionModeRequest { mode };
267        let answer: super::api::PartitionResponse =
268            self.call(Method::POST, path, Some(&body)).await?;
269        Ok(answer.partition)
270    }
271
272    /// `GET /kernel/settings`: every area's quiet time, daily spending limit and mode in
273    /// force (spec 3.3 §10 K3).
274    ///
275    /// # Errors
276    ///
277    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
278    /// error the kernel answered: `403` without the `operator` scope or a device's `read`.
279    pub async fn settings(&self) -> Result<Vec<super::api::AreaView>> {
280        let answer: super::api::SettingsResponse =
281            self.call(Method::GET, paths::SETTINGS.to_string(), None::<&()>).await?;
282        Ok(answer.areas)
283    }
284
285    /// `GET /kernel/settings/{partition}`: one area's settings in force (spec 3.3 §10 K3).
286    ///
287    /// # Errors
288    ///
289    /// As [`settings`](Self::settings), and `404` for an unknown area.
290    pub async fn area_settings(&self, partition: &str) -> Result<super::api::AreaView> {
291        let path = paths::AREA_SETTINGS.replace("{partition}", &encode(partition));
292        let answer: super::api::AreaResponse = self.call(Method::GET, path, None::<&()>).await?;
293        Ok(answer.area)
294    }
295
296    /// `POST /kernel/settings/{partition}/quiet-time`: sets the area's quiet time, or turns
297    /// it off with `None` (spec 3.3 §10 K3).
298    ///
299    /// # Errors
300    ///
301    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
302    /// error the kernel answered: `403` for a device token or without the `operator` scope,
303    /// `404` for an unknown area.
304    pub async fn set_quiet_time(
305        &self,
306        partition: &str,
307        window: Option<crate::sched::QuietHours>,
308    ) -> Result<super::api::AreaView> {
309        let path = paths::QUIET_TIME.replace("{partition}", &encode(partition));
310        let body = super::api::QuietTimeRequest { window };
311        let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
312        Ok(answer.area)
313    }
314
315    /// `POST /kernel/settings/{partition}/spending-limit`: sets the area's daily spending
316    /// limit in micro-USD, or removes it with `None` (spec 3.3 §10 K3).
317    ///
318    /// # Errors
319    ///
320    /// As [`set_quiet_time`](Self::set_quiet_time).
321    pub async fn set_spending_limit(
322        &self,
323        partition: &str,
324        micro_usd: Option<u64>,
325    ) -> Result<super::api::AreaView> {
326        let path = paths::SPENDING_LIMIT.replace("{partition}", &encode(partition));
327        let body = super::api::SpendingLimitRequest { micro_usd };
328        let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
329        Ok(answer.area)
330    }
331
332    /// `POST /kernel/settings/{partition}/mode`: sets how much the area's agents act alone
333    /// (spec 3.3 §10 K3).
334    ///
335    /// # Errors
336    ///
337    /// As [`set_quiet_time`](Self::set_quiet_time).
338    pub async fn set_area_mode(
339        &self,
340        partition: &str,
341        mode: crate::partition::PartitionMode,
342    ) -> Result<super::api::AreaView> {
343        let path = paths::AREA_MODE.replace("{partition}", &encode(partition));
344        let body = super::api::PartitionModeRequest { mode };
345        let answer: super::api::AreaResponse = self.call(Method::POST, path, Some(&body)).await?;
346        Ok(answer.area)
347    }
348
349    /// `GET /kernel/away`: "While you were away" after the viewer's cursor (spec 3.3 §10
350    /// K4). A paired device reads as itself; `query.viewer` names any other surface.
351    ///
352    /// # Errors
353    ///
354    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
355    /// error the kernel answered.
356    #[cfg(feature = "proc")]
357    pub async fn away(&self, query: &super::api::AwayQuery) -> Result<super::api::AwayResponse> {
358        let mut pairs = Vec::new();
359        if let Some(viewer) = &query.viewer {
360            pairs.push(format!("viewer={}", encode(viewer)));
361        }
362        if let Some(after) = query.after {
363            pairs.push(format!("after={after}"));
364        }
365        if let Some(limit) = query.limit {
366            pairs.push(format!("limit={limit}"));
367        }
368        let path = match pairs.is_empty() {
369            true => paths::AWAY.to_string(),
370            false => format!("{}?{}", paths::AWAY, pairs.join("&")),
371        };
372        self.call(Method::GET, path, None::<&()>).await
373    }
374
375    /// `POST /kernel/away/seen`: marks "While you were away" seen through row `through`, a
376    /// page's `through` (spec 3.3 §10 K4); returns the cursor, which never moves back.
377    ///
378    /// # Errors
379    ///
380    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
381    /// error the kernel answered: `400` for a row the ledger does not hold yet.
382    #[cfg(feature = "proc")]
383    pub async fn mark_away_seen(
384        &self,
385        viewer: Option<&str>,
386        through: u64,
387    ) -> Result<super::AwayCursor> {
388        let body = super::api::SeenRequest { viewer: viewer.map(str::to_string), through };
389        let answer: super::api::SeenResponse =
390            self.call(Method::POST, paths::AWAY_SEEN.to_string(), Some(&body)).await?;
391        Ok(answer.cursor)
392    }
393
394    /// `GET /kernel/away/lines/{seq}`: one line of "While you were away" with its ledger
395    /// row, the line's record (spec 3.3 §10 K4).
396    ///
397    /// # Errors
398    ///
399    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
400    /// error the kernel answered: `404` for a row the ledger does not hold.
401    #[cfg(feature = "proc")]
402    pub async fn away_line(&self, seq: u64) -> Result<super::api::AwayLineResponse> {
403        let path = paths::AWAY_LINE.replace("{seq}", &seq.to_string());
404        self.call(Method::GET, path, None::<&()>).await
405    }
406
407    /// `GET /kernel/memory`: what the agents remember about the caller, with provenance, and
408    /// the overnight tidy-ups (spec 3.3 §10 K5).
409    ///
410    /// # Errors
411    ///
412    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
413    /// error the kernel answered: `400` when the kernel shows no memory.
414    pub async fn memory(&self, area: Option<&str>) -> Result<super::api::MemoryResponse> {
415        let path = match area {
416            Some(area) => format!("{}?area={}", paths::MEMORY, encode(area)),
417            None => paths::MEMORY.to_string(),
418        };
419        self.call(Method::GET, path, None::<&()>).await
420    }
421
422    /// `POST /kernel/memory/facts/{id}/confirm`: "That's right" (spec 3.3 §8.2, §10 K5).
423    ///
424    /// # Errors
425    ///
426    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
427    /// error the kernel answered: `403` for a device token, `404` for a fact that is not
428    /// the caller's.
429    pub async fn confirm_fact(&self, id: &str) -> Result<super::RememberedFact> {
430        let path = paths::FACT_CONFIRM.replace("{id}", &encode(id));
431        let answer: super::api::FactResponse = self.call(Method::POST, path, Some(&())).await?;
432        Ok(answer.fact)
433    }
434
435    /// `POST /kernel/memory/facts/{id}/fix`: "Fix it" with the person's `text` (spec 3.3
436    /// §8.2, §10 K5).
437    ///
438    /// # Errors
439    ///
440    /// As [`confirm_fact`](Self::confirm_fact), and `400` for a text the harness refuses.
441    pub async fn fix_fact(&self, id: &str, text: &str) -> Result<super::RememberedFact> {
442        let path = paths::FACT_FIX.replace("{id}", &encode(id));
443        let body = super::api::FixRequest { text: text.to_string() };
444        let answer: super::api::FactResponse = self.call(Method::POST, path, Some(&body)).await?;
445        Ok(answer.fact)
446    }
447
448    /// `POST /kernel/memory/facts/{id}/forget`: "Forget it" (spec 3.3 §8.2, §10 K5).
449    ///
450    /// # Errors
451    ///
452    /// As [`confirm_fact`](Self::confirm_fact).
453    pub async fn forget_fact(&self, id: &str) -> Result<()> {
454        let path = paths::FACT_FORGET.replace("{id}", &encode(id));
455        let _: super::api::ForgetResponse = self.call(Method::POST, path, Some(&())).await?;
456        Ok(())
457    }
458
459    /// `POST /kernel/memory/undo`: "Undo" the tidy-up `id`, or the latest one that can be
460    /// undone (spec 3.3 §8.2, §10 K5).
461    ///
462    /// # Errors
463    ///
464    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
465    /// error the kernel answered: `403` for a device token, `404` when nothing is left to
466    /// undo, `409` for a tidy-up unfinished or undone.
467    pub async fn undo_tidy_up(&self, id: Option<&str>) -> Result<super::TidyUpUndo> {
468        let body = super::api::UndoRequest { tidy_up: id.map(str::to_string) };
469        self.call(Method::POST, paths::MEMORY_UNDO.to_string(), Some(&body)).await
470    }
471
472    /// `GET /kernel/record`: the latest `limit` actions on record, newest first (spec 3.3
473    /// §10 K5).
474    ///
475    /// # Errors
476    ///
477    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
478    /// error the kernel answered: `400` when the kernel shows no record.
479    pub async fn record(&self, limit: Option<usize>) -> Result<Vec<super::RecordLine>> {
480        let path = match limit {
481            Some(limit) => format!("{}?limit={limit}", paths::RECORD),
482            None => paths::RECORD.to_string(),
483        };
484        let answer: super::api::RecordResponse = self.call(Method::GET, path, None::<&()>).await?;
485        Ok(answer.lines)
486    }
487
488    /// `GET /kernel/record/check`: whether every action is on record and nothing was
489    /// changed or deleted, as `adk-rust audit verify` answers (spec 3.3 §10 K5).
490    ///
491    /// # Errors
492    ///
493    /// As [`record`](Self::record).
494    pub async fn check_record(&self) -> Result<super::RecordCheck> {
495        self.call(Method::GET, paths::RECORD_CHECK.to_string(), None::<&()>).await
496    }
497
498    /// `GET /kernel/processes`.
499    ///
500    /// # Errors
501    ///
502    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
503    /// error the kernel answered.
504    pub async fn processes(&self, query: &ProcessesQuery) -> Result<Vec<Process>> {
505        let mut pairs = Vec::new();
506        if let Some(partition) = &query.partition {
507            pairs.push(format!("partition={}", encode(partition.as_str())));
508        }
509        if let Some(state) = query.state {
510            let state = serde_json::to_value(state)?;
511            pairs.push(format!("state={}", encode(state.as_str().unwrap_or_default())));
512        }
513        if let Some(limit) = query.limit {
514            pairs.push(format!("limit={limit}"));
515        }
516        let path = match pairs.is_empty() {
517            true => paths::PROCESSES.to_string(),
518            false => format!("{}?{}", paths::PROCESSES, pairs.join("&")),
519        };
520        let answer: ProcessesResponse = self.call(Method::GET, path, None::<&()>).await?;
521        Ok(answer.processes)
522    }
523
524    /// `POST /kernel/processes`: starts a process of a registered target as the caller.
525    ///
526    /// # Errors
527    ///
528    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
529    /// error the kernel answered: `404` for an unknown target, `403` without the `operator`
530    /// scope.
531    pub async fn spawn(&self, request: &SpawnRequest) -> Result<Process> {
532        let answer: ProcessResponse =
533            self.call(Method::POST, paths::PROCESSES.to_string(), Some(request)).await?;
534        Ok(answer.process)
535    }
536
537    /// `GET /approvals`: the held calls the caller may decide, pending first page.
538    ///
539    /// # Errors
540    ///
541    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
542    /// error the kernel answered: `404` when it serves no approvals inbox.
543    pub async fn approvals(&self) -> Result<Vec<ApprovalItem>> {
544        #[derive(serde::Deserialize)]
545        struct Page {
546            items: Vec<ApprovalItem>,
547        }
548        let page: Page =
549            self.call(Method::GET, format!("{APPROVALS}?limit=200"), None::<&()>).await?;
550        Ok(page.items)
551    }
552
553    /// `POST /approvals/{id}/decide`: decides a held call, at the `version` the caller read.
554    ///
555    /// # Errors
556    ///
557    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
558    /// error the kernel answered: `409` for a stale version, `403` for a caller who may not
559    /// decide it.
560    pub async fn decide(
561        &self,
562        id: &str,
563        version: u64,
564        action: ApprovalAction,
565        reason: Option<&str>,
566    ) -> Result<ApprovalItem> {
567        let body = serde_json::json!({
568            "expectedVersion": version,
569            "action": action,
570            "reason": reason,
571        });
572        let path = format!("{APPROVALS}/{}/decide", encode(id));
573        self.call(Method::POST, path, Some(&body)).await
574    }
575
576    /// `POST /kernel/processes/{pid}/kill`.
577    ///
578    /// # Errors
579    ///
580    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
581    /// error the kernel answered.
582    pub async fn kill(&self, pid: &str, reason: Option<&str>) -> Result<Process> {
583        let body = KillRequest { reason: reason.map(str::to_string) };
584        self.process_action(paths::KILL, pid, &body).await
585    }
586
587    /// `POST /kernel/processes/{pid}/nice`.
588    ///
589    /// # Errors
590    ///
591    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
592    /// error the kernel answered.
593    pub async fn nice(&self, pid: &str, queue: QueueClass) -> Result<Process> {
594        self.process_action(paths::NICE, pid, &NiceRequest { queue }).await
595    }
596
597    /// `POST /kernel/processes/{pid}/suspend`.
598    ///
599    /// # Errors
600    ///
601    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
602    /// error the kernel answered.
603    pub async fn suspend(&self, pid: &str) -> Result<Process> {
604        self.process_action(paths::SUSPEND, pid, &()).await
605    }
606
607    /// `POST /kernel/processes/{pid}/resume`.
608    ///
609    /// # Errors
610    ///
611    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
612    /// error the kernel answered.
613    pub async fn resume(&self, pid: &str) -> Result<Process> {
614        self.process_action(paths::RESUME, pid, &()).await
615    }
616
617    /// `POST /kernel/processes/{pid}/run-now`: runs a cron sleeper now, outside its schedule
618    /// ([`Kernel::run_now`](crate::Kernel::run_now)); a retry with the same `request_id`
619    /// queues nothing new.
620    ///
621    /// # Errors
622    ///
623    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
624    /// error the kernel answered, such as `kernel.frozen`.
625    pub async fn run_now(
626        &self,
627        pid: &str,
628        request_id: Option<&str>,
629    ) -> Result<crate::kernel::RunNow> {
630        let path = paths::RUN_NOW.replace("{pid}", &encode(pid));
631        self.call(Method::POST, path, Some(&run_now_request(request_id))).await
632    }
633
634    /// `POST /kernel/triggers/{name}/run-now`: runs a standing cron trigger now, outside its
635    /// schedule ([`Kernel::run_now`](crate::Kernel::run_now)).
636    ///
637    /// # Errors
638    ///
639    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
640    /// error the kernel answered.
641    pub async fn run_trigger_now(
642        &self,
643        name: &str,
644        request_id: Option<&str>,
645    ) -> Result<crate::kernel::RunNow> {
646        let path = paths::TRIGGER_RUN_NOW.replace("{name}", &encode(name));
647        self.call(Method::POST, path, Some(&run_now_request(request_id))).await
648    }
649
650    /// `GET /kernel/drivers`: the mounted drivers (spec 3.2 §7.7).
651    ///
652    /// # Errors
653    ///
654    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
655    /// error the kernel answered.
656    #[cfg(feature = "drivers")]
657    pub async fn drivers(&self) -> Result<Vec<crate::drivers::DriverView>> {
658        let answer: super::api::DriversResponse =
659            self.call(Method::GET, paths::DRIVERS.to_string(), None::<&()>).await?;
660        Ok(answer.drivers)
661    }
662
663    /// `POST /kernel/drivers/{id}/mount`: what mounting `manifest` (its TOML) approves,
664    /// and with `confirm` the mount itself.
665    ///
666    /// # Errors
667    ///
668    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
669    /// error the kernel answered.
670    #[cfg(feature = "drivers")]
671    pub async fn mount_driver(
672        &self,
673        id: &str,
674        manifest: &str,
675        confirm: bool,
676    ) -> Result<super::api::MountDriverResponse> {
677        let mut body = super::api::MountDriverRequest::new(manifest);
678        body.confirm = confirm;
679        let path = paths::DRIVER_MOUNT.replace("{id}", &encode(id));
680        self.call(Method::POST, path, Some(&body)).await
681    }
682
683    /// `POST /kernel/drivers/{id}/unmount`; `false` when no such driver was mounted.
684    ///
685    /// # Errors
686    ///
687    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
688    /// error the kernel answered.
689    #[cfg(feature = "drivers")]
690    pub async fn unmount_driver(&self, id: &str) -> Result<bool> {
691        let path = paths::DRIVER_UNMOUNT.replace("{id}", &encode(id));
692        let answer: super::api::UnmountDriverResponse =
693            self.call(Method::POST, path, Some(&())).await?;
694        Ok(answer.unmounted)
695    }
696
697    /// `POST /kernel/drivers/{id}/restart`.
698    ///
699    /// # Errors
700    ///
701    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
702    /// error the kernel answered.
703    #[cfg(feature = "drivers")]
704    pub async fn restart_driver(&self, id: &str) -> Result<crate::drivers::DriverView> {
705        let path = paths::DRIVER_RESTART.replace("{id}", &encode(id));
706        let answer: super::api::DriverResponse = self.call(Method::POST, path, Some(&())).await?;
707        Ok(answer.driver)
708    }
709
710    /// `POST /kernel/drivers/{id}/reapprove`.
711    ///
712    /// # Errors
713    ///
714    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
715    /// error the kernel answered.
716    #[cfg(feature = "drivers")]
717    pub async fn reapprove_driver(&self, id: &str) -> Result<crate::drivers::DriverView> {
718        let path = paths::DRIVER_REAPPROVE.replace("{id}", &encode(id));
719        let answer: super::api::DriverResponse = self.call(Method::POST, path, Some(&())).await?;
720        Ok(answer.driver)
721    }
722
723    /// `POST /kernel/freeze`.
724    ///
725    /// # Errors
726    ///
727    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
728    /// error the kernel answered.
729    pub async fn freeze(&self, reason: Option<&str>) -> Result<FreezeResponse> {
730        let body = FreezeRequest { reason: reason.map(str::to_string) };
731        self.call(Method::POST, paths::FREEZE.to_string(), Some(&body)).await
732    }
733
734    /// `POST /kernel/unfreeze`.
735    ///
736    /// # Errors
737    ///
738    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
739    /// error the kernel answered.
740    pub async fn unfreeze(&self) -> Result<FreezeResponse> {
741        self.call(Method::POST, paths::UNFREEZE.to_string(), Some(&())).await
742    }
743
744    /// `GET /kernel/proc/ledger` as JSON: one page of the activity ledger (spec 3.2 §7.10).
745    /// Page on with `params.after` set to the answer's `next`.
746    ///
747    /// # Errors
748    ///
749    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
750    /// error the kernel answered: `403` without the `operator` scope.
751    #[cfg(feature = "proc")]
752    pub async fn ledger(
753        &self,
754        params: &super::api::LedgerParams,
755    ) -> Result<super::api::LedgerResponse> {
756        let mut pairs = Vec::new();
757        let mut pair = |key: &str, value: Option<String>| {
758            if let Some(value) = value {
759                pairs.push(format!("{key}={}", encode(&value)));
760            }
761        };
762        pair("partition", params.partition.as_ref().map(|p| p.as_str().to_string()));
763        pair("kind", params.kind.clone());
764        pair("agent", params.agent.clone());
765        pair("from", params.from.map(|from| from.to_rfc3339()));
766        pair("to", params.to.map(|to| to.to_rfc3339()));
767        pair("after", params.after.map(|after| after.to_string()));
768        pair("limit", params.limit.map(|limit| limit.to_string()));
769        let path = match pairs.is_empty() {
770            true => paths::PROC_LEDGER.to_string(),
771            false => format!("{}?{}", paths::PROC_LEDGER, pairs.join("&")),
772        };
773        self.call(Method::GET, path, None::<&()>).await
774    }
775
776    /// `GET /kernel/proc/baselines`: each partition's last baseline pass (spec 3.2 §7.10).
777    ///
778    /// # Errors
779    ///
780    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
781    /// error the kernel answered.
782    #[cfg(feature = "proc")]
783    pub async fn baselines(&self) -> Result<Vec<crate::proc::PassState>> {
784        let answer: super::api::BaselinesResponse =
785            self.call(Method::GET, paths::PROC_BASELINES.to_string(), None::<&()>).await?;
786        Ok(answer.partitions)
787    }
788
789    /// `GET /kernel/proc/observations`: the observations the kernel offered, newest first
790    /// (spec 3.2 §7.10).
791    ///
792    /// # Errors
793    ///
794    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
795    /// error the kernel answered.
796    #[cfg(feature = "proc")]
797    pub async fn observations(
798        &self,
799        params: &super::api::ObservationsParams,
800    ) -> Result<Vec<crate::proc::Observation>> {
801        let mut pairs = Vec::new();
802        if let Some(partition) = &params.partition {
803            pairs.push(format!("partition={}", encode(partition.as_str())));
804        }
805        if let Some(since) = params.since {
806            pairs.push(format!("since={since}"));
807        }
808        if let Some(limit) = params.limit {
809            pairs.push(format!("limit={limit}"));
810        }
811        let path = match pairs.is_empty() {
812            true => paths::PROC_OBSERVATIONS.to_string(),
813            false => format!("{}?{}", paths::PROC_OBSERVATIONS, pairs.join("&")),
814        };
815        let answer: super::api::ObservationsResponse =
816            self.call(Method::GET, path, None::<&()>).await?;
817        Ok(answer.observations)
818    }
819
820    /// `GET /kernel/events`: the event bus from just after `after`, then live.
821    ///
822    /// # Errors
823    ///
824    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached; a broken
825    /// stream ends with the error as its last item.
826    pub async fn events(
827        &self,
828        after: Option<u64>,
829    ) -> Result<BoxStream<'static, Result<EventRecord>>> {
830        let path = match after {
831            Some(cursor) => format!("{}?after={cursor}", paths::EVENTS),
832            None => paths::EVENTS.to_string(),
833        };
834        let answer = self.send(Method::GET, &path, None, None).await?;
835        if !answer.status.is_success() {
836            let status = answer.status;
837            return Err(answer_error(status, &answer.bytes().await?));
838        }
839        Ok(server_sent_records(answer.body))
840    }
841
842    /// `POST /kernel/attach/{session}`.
843    ///
844    /// # Errors
845    ///
846    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
847    /// error the kernel answered.
848    pub async fn attach(
849        &self,
850        session_id: &str,
851        request: &AttachRequest,
852    ) -> Result<AttachResponse> {
853        let path = paths::ATTACH.replace("{session}", &encode(session_id));
854        self.call(Method::POST, path, Some(request)).await
855    }
856
857    /// `POST /kernel/sessions/{session}/steer`: sends `text` to the running turn of the
858    /// caller's session `session_id` (spec 3.3 §6 "steer").
859    ///
860    /// [`SteerResponse::Accepted`] means the turn holds the message, not that it took it: the
861    /// message is delivered once [`attach`](Self::attach) shows an event whose steering marker
862    /// carries the answer's steer id, and handed back once the process leaves the answer's
863    /// claim without one. On [`SteerResponse::Returned`], [`spawn`](Self::spawn) it as the
864    /// session's next message.
865    ///
866    /// # Errors
867    ///
868    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
869    /// the kernel answered: `403` without the `operator` scope or for a device token, `503`
870    /// while everything is stopped, `400` for a blank message, or an input guardrail's
871    /// refusal.
872    ///
873    /// # Example
874    ///
875    /// ```rust,no_run
876    /// use adk_kernel::control::ControlClient;
877    /// use adk_kernel::control::api::{SpawnRequest, SteerResponse};
878    ///
879    /// # async fn example(client: ControlClient) -> adk_kernel::Result<()> {
880    /// let text = "use the staging database";
881    /// if client.steer("s-1", text).await? == SteerResponse::Returned {
882    ///     let next = SpawnRequest::new("adk-rust", serde_json::json!({ "text": text }));
883    ///     client.spawn(&next.with_session_id("s-1")).await?;
884    /// }
885    /// # Ok(())
886    /// # }
887    /// ```
888    pub async fn steer(&self, session_id: &str, text: &str) -> Result<SteerResponse> {
889        let path = paths::SESSION_STEER.replace("{session}", &encode(session_id));
890        self.call(Method::POST, path, Some(&SteerRequest::new(text))).await
891    }
892
893    /// `GET /kernel/agenda` (spec 3.2 §7.5, §8.1 `adk-rust agenda list`).
894    ///
895    /// # Errors
896    ///
897    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
898    /// error the kernel answered.
899    pub async fn agenda(&self, query: &AgendaQuery) -> Result<Vec<AgendaItem>> {
900        let mut pairs = Vec::new();
901        if let Some(partition) = &query.partition {
902            pairs.push(format!("partition={}", encode(partition.as_str())));
903        }
904        if let Some(state) = query.state {
905            pairs.push(format!("state={}", encode(state.as_str())));
906        }
907        if let Some(limit) = query.limit {
908            pairs.push(format!("limit={limit}"));
909        }
910        if query.newest_first {
911            pairs.push("newestFirst=true".to_string());
912        }
913        if let Some(after) = &query.after {
914            pairs.push(format!("after={}", encode(after)));
915        }
916        let path = match pairs.is_empty() {
917            true => paths::AGENDA.to_string(),
918            false => format!("{}?{}", paths::AGENDA, pairs.join("&")),
919        };
920        let answer: AgendaResponse = self.call(Method::GET, path, None::<&()>).await?;
921        Ok(answer.items)
922    }
923
924    /// `POST /kernel/agenda/{id}/approve`: approves the item as the caller, then schedules it.
925    ///
926    /// # Errors
927    ///
928    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
929    /// error the kernel answered: `404` for an unknown item, `409` for one not proposed.
930    pub async fn approve_item(&self, id: &str) -> Result<AgendaItem> {
931        self.agenda_action(paths::AGENDA_APPROVE, id, &()).await
932    }
933
934    /// `POST /kernel/agenda/{id}/reject`.
935    ///
936    /// # Errors
937    ///
938    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
939    /// error the kernel answered.
940    pub async fn reject_item(&self, id: &str, reason: Option<&str>) -> Result<AgendaItem> {
941        let body = RejectRequest { reason: reason.map(str::to_string) };
942        self.agenda_action(paths::AGENDA_REJECT, id, &body).await
943    }
944
945    /// `POST /kernel/agenda/{id}/schedule`: puts the approved item's process to sleep on
946    /// `wake`.
947    ///
948    /// # Errors
949    ///
950    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
951    /// error the kernel answered.
952    pub async fn schedule_item(&self, id: &str, wake: WakeSet) -> Result<AgendaItem> {
953        self.agenda_action(paths::AGENDA_SCHEDULE, id, &ScheduleRequest { wake }).await
954    }
955
956    /// `POST /kernel/pairing`: issues a pairing code for a device acting for the caller
957    /// (spec 3.3 §10 K2, `adk-rust pair`).
958    ///
959    /// # Errors
960    ///
961    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
962    /// error the kernel answered: `403` without the `operator` scope, `400` when the kernel
963    /// pairs no devices.
964    pub async fn issue_pairing_code(
965        &self,
966        request: &super::api::IssueRequest,
967    ) -> Result<crate::pairing::IssuedCode> {
968        self.call(Method::POST, paths::PAIRING.to_string(), Some(request)).await
969    }
970
971    /// `POST /kernel/pairing/claim`: pairs this client's device with `code` and returns its
972    /// token, once (spec 3.3 §10 K2). The call needs no token and sends none, so a client
973    /// whose old token was revoked or expired re-pairs; send the one it returns with
974    /// [`with_bearer_token`](Self::with_bearer_token) from then on.
975    ///
976    /// # Errors
977    ///
978    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
979    /// error the kernel answered: `401` for a wrong, used or expired code.
980    pub async fn claim_pairing(
981        &self,
982        code: &str,
983        name: Option<&str>,
984    ) -> Result<crate::pairing::ClaimedDevice> {
985        let body =
986            super::api::ClaimRequest { code: code.to_string(), name: name.map(str::to_string) };
987        let anonymous = Self { transport: self.transport.clone(), token: None };
988        anonymous.call(Method::POST, paths::PAIRING_CLAIM.to_string(), Some(&body)).await
989    }
990
991    /// `GET /kernel/devices`: every paired device (spec 3.3 §10 K2, `adk-rust pair list`).
992    ///
993    /// # Errors
994    ///
995    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
996    /// error the kernel answered.
997    pub async fn devices(&self) -> Result<Vec<crate::pairing::DeviceView>> {
998        let answer: super::api::DevicesResponse =
999            self.call(Method::GET, paths::DEVICES.to_string(), None::<&()>).await?;
1000        Ok(answer.devices)
1001    }
1002
1003    /// `POST /kernel/devices/{id}/revoke`: removes a device; its token stops working at once
1004    /// (spec 3.3 §10 K2, `adk-rust pair revoke`).
1005    ///
1006    /// # Errors
1007    ///
1008    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
1009    /// error the kernel answered: `404` for an unknown device.
1010    pub async fn revoke_device(&self, id: &str) -> Result<crate::pairing::DeviceView> {
1011        let path = paths::DEVICE_REVOKE.replace("{id}", &encode(id));
1012        let answer: super::api::DeviceResponse = self.call(Method::POST, path, Some(&())).await?;
1013        Ok(answer.device)
1014    }
1015
1016    /// `GET /kernel/channels`: the paired chat accounts and the ones waiting for their code
1017    /// to be accepted (spec 3.3 §10 K1).
1018    ///
1019    /// # Errors
1020    ///
1021    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
1022    /// error the kernel answered; a kernel without chat channels answers none.
1023    pub async fn channel_accounts(&self) -> Result<super::api::ChannelAccountsResponse> {
1024        self.call(Method::GET, paths::CHANNELS.to_string(), None::<&()>).await
1025    }
1026
1027    /// `POST /kernel/channels/pair`: accepts the code a chat account was sent, so its
1028    /// messages reach the caller's agents (spec 3.3 §10 K1).
1029    ///
1030    /// # Errors
1031    ///
1032    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
1033    /// error the kernel answered: `401` for a wrong or expired code, `400` when the kernel
1034    /// has no chat channels.
1035    pub async fn accept_channel(&self, code: &str) -> Result<super::api::ChannelAccountView> {
1036        let body = super::api::AcceptChannelRequest { code: code.to_string() };
1037        let answer: super::api::ChannelAccountResponse =
1038            self.call(Method::POST, paths::CHANNEL_PAIR.to_string(), Some(&body)).await?;
1039        Ok(answer.account)
1040    }
1041
1042    /// `POST /kernel/channels/{id}/revoke`: removes a chat account (spec 3.3 §10 K1).
1043    ///
1044    /// # Errors
1045    ///
1046    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
1047    /// error the kernel answered: `404` for an unknown account.
1048    pub async fn revoke_channel_account(&self, id: &str) -> Result<super::api::ChannelAccountView> {
1049        let path = paths::CHANNEL_REVOKE.replace("{id}", &encode(id));
1050        let answer: super::api::ChannelAccountResponse =
1051            self.call(Method::POST, path, Some(&())).await?;
1052        Ok(answer.account)
1053    }
1054
1055    /// `POST /kernel/channels/waiting/{id}/dismiss`: dismisses a chat account waiting to be
1056    /// paired; its code stops working (spec 3.3 §10 K1).
1057    ///
1058    /// # Errors
1059    ///
1060    /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the
1061    /// error the kernel answered: `404` for an account that is not waiting.
1062    pub async fn dismiss_channel_request(
1063        &self,
1064        id: &str,
1065    ) -> Result<super::api::ChannelPairingView> {
1066        let path = paths::CHANNEL_DISMISS.replace("{id}", &encode(id));
1067        let answer: super::api::ChannelPairingResponse =
1068            self.call(Method::POST, path, Some(&())).await?;
1069        Ok(answer.waiting)
1070    }
1071
1072    async fn agenda_action(
1073        &self,
1074        route: &str,
1075        id: &str,
1076        body: &impl Serialize,
1077    ) -> Result<AgendaItem> {
1078        let path = route.replace("{id}", &encode(id));
1079        let answer: AgendaItemResponse = self.call(Method::POST, path, Some(body)).await?;
1080        Ok(answer.item)
1081    }
1082
1083    async fn process_action(
1084        &self,
1085        route: &str,
1086        pid: &str,
1087        body: &impl Serialize,
1088    ) -> Result<Process> {
1089        let path = route.replace("{pid}", &encode(pid));
1090        let answer: ProcessResponse = self.call(Method::POST, path, Some(body)).await?;
1091        Ok(answer.process)
1092    }
1093
1094    /// Sends a JSON call and decodes the JSON answer, or the error the kernel answered.
1095    pub(super) async fn call<T: DeserializeOwned>(
1096        &self,
1097        method: Method,
1098        path: String,
1099        body: Option<&impl Serialize>,
1100    ) -> Result<T> {
1101        let body = body.map(serde_json::to_vec).transpose()?;
1102        let answer = self.send(method, &path, body, Some(CALL_TIMEOUT)).await?;
1103        let status = answer.status;
1104        let bytes = answer.bytes().await?;
1105        if !status.is_success() {
1106            return Err(answer_error(status, &bytes));
1107        }
1108        serde_json::from_slice(&bytes).map_err(|error| KernelError::ControlPlane {
1109            reason: format!(
1110                "the kernel at {} answered {path} with a body this client cannot read ({error}); \
1111                 are the CLI and the kernel the same version?",
1112                self.endpoint()
1113            ),
1114        })
1115    }
1116
1117    async fn send(
1118        &self,
1119        method: Method,
1120        path: &str,
1121        body: Option<Vec<u8>>,
1122        timeout: Option<Duration>,
1123    ) -> Result<Answer> {
1124        let path = format!("{}{path}", paths::API_PREFIX);
1125        let unreachable = |error: &dyn std::fmt::Display| KernelError::ControlPlane {
1126            reason: format!(
1127                "could not reach the kernel at {}: {error}; start it with `adk-rust up`",
1128                self.endpoint()
1129            ),
1130        };
1131        match &self.transport {
1132            Transport::Http { base, client } => {
1133                let mut request = client.request(method, format!("{base}{path}"));
1134                if let Some(token) = &self.token {
1135                    request = request.bearer_auth(token);
1136                }
1137                if let Some(body) = body {
1138                    request = request.header("content-type", "application/json").body(body);
1139                }
1140                if let Some(timeout) = timeout {
1141                    request = request.timeout(timeout);
1142                }
1143                let response = request.send().await.map_err(|error| unreachable(&error))?;
1144                let status = StatusCode::from_u16(response.status().as_u16())
1145                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1146                let body = response
1147                    .bytes_stream()
1148                    .map(|chunk| {
1149                        chunk.map_err(|error| KernelError::ControlPlane {
1150                            reason: format!("the kernel's answer broke off: {error}"),
1151                        })
1152                    })
1153                    .boxed();
1154                Ok(Answer { status, body })
1155            }
1156            local => {
1157                let send = local_request(local, method, &path, self.token.as_deref(), body);
1158                let answer = match timeout {
1159                    Some(timeout) => tokio::time::timeout(timeout, send)
1160                        .await
1161                        .map_err(|_| unreachable(&"the kernel did not answer in time"))?,
1162                    None => send.await,
1163                };
1164                answer.map_err(|error| unreachable(&error))
1165            }
1166        }
1167    }
1168}
1169
1170#[cfg(unix)]
1171async fn connect_local_socket(path: PathBuf, configured: &Path) -> Result<Option<ControlClient>> {
1172    // A socket standing in for one too long for the home sits in a directory of its own,
1173    // checked first, so no socket another user placed is reached (spec 3.3 G18).
1174    if path != configured
1175        && let Some(dir) = path.parent()
1176        && !super::socket::check_dir(dir)?
1177    {
1178        return Ok(None);
1179    }
1180    match tokio::fs::symlink_metadata(&path).await {
1181        Ok(_) => {}
1182        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1183        Err(error) => {
1184            return Err(KernelError::ControlPlane {
1185                reason: format!("could not read the kernel socket {}: {error}", path.display()),
1186            });
1187        }
1188    }
1189    match tokio::net::UnixStream::connect(&path).await {
1190        Ok(_) => Ok(Some(ControlClient::socket(path))),
1191        Err(error)
1192            if matches!(
1193                error.kind(),
1194                std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
1195            ) =>
1196        {
1197            Ok(None)
1198        }
1199        Err(error) => Err(KernelError::ControlPlane {
1200            reason: format!(
1201                "the kernel socket {} exists but cannot be opened: {error}; it admits only the \
1202                 OS user that runs the kernel",
1203                path.display()
1204            ),
1205        }),
1206    }
1207}
1208
1209#[cfg(all(not(unix), not(windows)))]
1210async fn connect_local_socket(_path: PathBuf, _configured: &Path) -> Result<Option<ControlClient>> {
1211    Ok(None)
1212}
1213
1214/// One HTTP/1.1 exchange over the socket at `socket`.
1215#[cfg(unix)]
1216async fn socket_exchange(
1217    socket: &Path,
1218    request: hyper::Request<http_body_util::Full<Bytes>>,
1219) -> std::result::Result<hyper::Response<hyper::body::Incoming>, String> {
1220    let stream =
1221        tokio::net::UnixStream::connect(socket).await.map_err(|error| error.to_string())?;
1222    let (mut sender, connection) =
1223        hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
1224            .await
1225            .map_err(|error| error.to_string())?;
1226    tokio::spawn(async move {
1227        if let Err(error) = connection.await {
1228            tracing::debug!(error = %error, "kernel socket connection closed");
1229        }
1230    });
1231    sender.send_request(request).await.map_err(|error| error.to_string())
1232}
1233
1234/// One HTTP/1.1 exchange over the local transport `local`: the socket, or the pipe.
1235async fn local_request(
1236    local: &Transport,
1237    method: Method,
1238    path: &str,
1239    token: Option<&str>,
1240    body: Option<Vec<u8>>,
1241) -> std::result::Result<Answer, String> {
1242    use http_body_util::{BodyStream, Full};
1243
1244    let mut request =
1245        hyper::Request::builder().method(method).uri(path).header(hyper::header::HOST, "localhost");
1246    if let Some(token) = token {
1247        request = request.header(hyper::header::AUTHORIZATION, format!("Bearer {token}"));
1248    }
1249    if body.is_some() {
1250        request = request.header(hyper::header::CONTENT_TYPE, "application/json");
1251    }
1252    let request = request
1253        .body(Full::new(Bytes::from(body.unwrap_or_default())))
1254        .map_err(|error| error.to_string())?;
1255    let response = match local {
1256        #[cfg(unix)]
1257        Transport::Socket(socket) => socket_exchange(socket, request).await?,
1258        #[cfg(not(unix))]
1259        Transport::Socket(socket) => {
1260            let _ = request;
1261            return Err(format!(
1262                "the local control socket {} needs a Unix platform; on Windows the kernel \
1263                 serves a named pipe, which ControlClient::connect_local finds",
1264                socket.display()
1265            ));
1266        }
1267        #[cfg(windows)]
1268        Transport::Pipe(name) => super::pipe::request(name, request).await?,
1269        Transport::Http { base, .. } => {
1270            return Err(format!("{base} is reached over HTTP, not over a local transport"));
1271        }
1272    };
1273    let status = response.status();
1274    let body = BodyStream::new(response.into_body())
1275        .filter_map(|frame| async move {
1276            match frame {
1277                Ok(frame) => frame.into_data().ok().map(Ok),
1278                Err(error) => Some(Err(KernelError::ControlPlane {
1279                    reason: format!("the kernel's answer broke off: {error}"),
1280                })),
1281            }
1282        })
1283        .boxed();
1284    Ok(Answer { status, body })
1285}
1286
1287/// The error a kernel's non-success answer carries: its problem document, the server's
1288/// `{"error": "..."}` refusal, or the status alone.
1289fn answer_error(status: StatusCode, body: &[u8]) -> KernelError {
1290    let value: Option<Value> = serde_json::from_slice(body).ok();
1291    let error = value.as_ref().and_then(|value| value.get("error"));
1292    if let Some(problem) = error.and_then(Value::as_object) {
1293        let message = problem.get("message").and_then(Value::as_str).unwrap_or("").to_string();
1294        let code = problem.get("code").and_then(Value::as_str).unwrap_or("");
1295        let category = problem
1296            .get("category")
1297            .and_then(|category| serde_json::from_value(category.clone()).ok())
1298            .unwrap_or_else(|| category_of(status));
1299        return KernelError::Core(AdkError::new(
1300            ErrorComponent::Server,
1301            category,
1302            known_code(code),
1303            message,
1304        ));
1305    }
1306    let message = match error.and_then(Value::as_str) {
1307        Some(message) => message.to_string(),
1308        None => String::from_utf8_lossy(body).trim().chars().take(300).collect(),
1309    };
1310    match status {
1311        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => KernelError::Unauthorized {
1312            reason: format!(
1313                "{message}; pass the kernel's bearer token (--token or ADK_SERVE_TOKEN), or run \
1314                 the command as the user that runs the kernel"
1315            ),
1316        },
1317        _ => {
1318            KernelError::ControlPlane { reason: format!("the kernel answered {status}: {message}") }
1319        }
1320    }
1321}
1322
1323/// The category a status stands for, when an answer names none.
1324fn category_of(status: StatusCode) -> ErrorCategory {
1325    match status.as_u16() {
1326        400 => ErrorCategory::InvalidInput,
1327        401 => ErrorCategory::Unauthorized,
1328        403 => ErrorCategory::Forbidden,
1329        404 => ErrorCategory::NotFound,
1330        409 => ErrorCategory::Conflict,
1331        429 => ErrorCategory::RateLimited,
1332        501 => ErrorCategory::Unsupported,
1333        503 => ErrorCategory::Unavailable,
1334        _ => ErrorCategory::Internal,
1335    }
1336}
1337
1338/// The kernel code `code` names, or the control-plane code for one this client does not know.
1339fn known_code(code: &str) -> &'static str {
1340    error::CODES.iter().copied().find(|known| *known == code).unwrap_or(error::CONTROL_PLANE_CODE)
1341}
1342
1343/// Percent-encodes `text` for a path segment or a query value.
1344/// The body of a run now with `request_id`, when one is given.
1345fn run_now_request(request_id: Option<&str>) -> RunNowRequest {
1346    match request_id {
1347        Some(id) => RunNowRequest::default().with_request_id(id),
1348        None => RunNowRequest::default(),
1349    }
1350}
1351
1352pub(super) fn encode(text: &str) -> String {
1353    let mut encoded = String::with_capacity(text.len());
1354    for byte in text.bytes() {
1355        match byte {
1356            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
1357                encoded.push(byte as char);
1358            }
1359            _ => encoded.push_str(&format!("%{byte:02X}")),
1360        }
1361    }
1362    encoded
1363}
1364
1365/// The event records of a server-sent event stream: the `data` of each event, keep-alive
1366/// comments skipped.
1367fn server_sent_records(
1368    body: BoxStream<'static, Result<Bytes>>,
1369) -> BoxStream<'static, Result<EventRecord>> {
1370    struct Reader {
1371        body: BoxStream<'static, Result<Bytes>>,
1372        buffer: Vec<u8>,
1373        ready: VecDeque<Result<EventRecord>>,
1374        done: bool,
1375    }
1376    let reader = Reader { body, buffer: Vec::new(), ready: VecDeque::new(), done: false };
1377    stream::unfold(reader, |mut reader| async move {
1378        loop {
1379            if let Some(record) = reader.ready.pop_front() {
1380                return Some((record, reader));
1381            }
1382            if reader.done {
1383                return None;
1384            }
1385            match reader.body.next().await {
1386                Some(Ok(chunk)) => {
1387                    reader.buffer.extend_from_slice(&chunk);
1388                    while let Some(end) = event_end(&reader.buffer) {
1389                        let block: Vec<u8> = reader.buffer.drain(..end.0).collect();
1390                        reader.buffer.drain(..end.1);
1391                        if let Some(record) = parse_event(&block) {
1392                            reader.ready.push_back(record);
1393                        }
1394                    }
1395                }
1396                Some(Err(error)) => {
1397                    reader.done = true;
1398                    reader.ready.push_back(Err(error));
1399                }
1400                None => reader.done = true,
1401            }
1402        }
1403    })
1404    .boxed()
1405}
1406
1407/// Where the first event in `buffer` ends: its length and the separator's.
1408fn event_end(buffer: &[u8]) -> Option<(usize, usize)> {
1409    let lf = buffer.windows(2).position(|window| window == b"\n\n").map(|at| (at, 2));
1410    let crlf = buffer.windows(4).position(|window| window == b"\r\n\r\n").map(|at| (at, 4));
1411    match (lf, crlf) {
1412        (Some(lf), Some(crlf)) => Some(if lf.0 <= crlf.0 { lf } else { crlf }),
1413        (found, None) | (None, found) => found,
1414    }
1415}
1416
1417/// The record in one event's lines, or `None` for an event with no data.
1418fn parse_event(block: &[u8]) -> Option<Result<EventRecord>> {
1419    let text = String::from_utf8_lossy(block);
1420    let data: Vec<&str> = text
1421        .lines()
1422        .filter_map(|line| line.strip_prefix("data:"))
1423        .map(|data| data.strip_prefix(' ').unwrap_or(data))
1424        .collect();
1425    if data.is_empty() {
1426        return None;
1427    }
1428    Some(serde_json::from_str(&data.join("\n")).map_err(KernelError::from))
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433    use super::*;
1434
1435    #[test]
1436    fn segments_are_percent_encoded() {
1437        assert_eq!(encode("run-1_a.b~c"), "run-1_a.b~c");
1438        assert_eq!(encode("a/b c?d"), "a%2Fb%20c%3Fd");
1439    }
1440
1441    #[tokio::test]
1442    async fn server_sent_events_split_on_blank_lines_across_chunks() {
1443        let record = |cursor: u64| {
1444            serde_json::to_string(&EventRecord {
1445                cursor,
1446                at: chrono::Utc::now(),
1447                event: crate::KernelEvent::Governance { frozen: true, reason: None },
1448            })
1449            .unwrap()
1450        };
1451        let text = format!(
1452            ": keep-alive\n\nid: 1\nevent: governance\ndata: {}\n\nid: 2\r\ndata: {}\r\n\r\n",
1453            record(1),
1454            record(2)
1455        );
1456        let (head, tail) = text.split_at(40);
1457        let chunks = vec![Ok(Bytes::from(head.to_string())), Ok(Bytes::from(tail.to_string()))];
1458        let records: Vec<_> = server_sent_records(stream::iter(chunks).boxed())
1459            .map(|record| record.unwrap().cursor)
1460            .collect()
1461            .await;
1462        assert_eq!(records, vec![1, 2]);
1463    }
1464
1465    #[test]
1466    fn answers_map_to_kernel_errors() {
1467        let problem = AdkError::from(KernelError::NotFound { pid: "run-9".into() });
1468        let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1469        let error = AdkError::from(answer_error(StatusCode::NOT_FOUND, &body));
1470        assert_eq!((error.code, error.category), (error::NOT_FOUND_CODE, ErrorCategory::NotFound));
1471        assert!(error.message.contains("run-9"));
1472
1473        let refused =
1474            answer_error(StatusCode::UNAUTHORIZED, br#"{"error":"missing authorization"}"#);
1475        assert!(matches!(refused, KernelError::Unauthorized { .. }), "{refused}");
1476
1477        let other = answer_error(StatusCode::BAD_GATEWAY, b"upstream down");
1478        assert!(other.to_string().contains("upstream down"), "{other}");
1479    }
1480
1481    #[test]
1482    fn every_kernel_code_reaches_the_client() {
1483        let refusals = [
1484            KernelError::AgendaNotFound { item: "agenda-1".into() },
1485            KernelError::AgendaState {
1486                item: "agenda-1".into(),
1487                state: crate::agenda::AgendaStateKind::Rejected,
1488                action: "approved",
1489            },
1490            KernelError::Quota { partition: "work".into(), reason: "max running 2".into() },
1491        ];
1492        for refusal in refusals {
1493            let problem = AdkError::from(refusal);
1494            let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1495            let status = StatusCode::from_u16(problem.http_status_code()).unwrap();
1496            let error = AdkError::from(answer_error(status, &body));
1497            assert_eq!((error.code, error.category), (problem.code, problem.category));
1498        }
1499        for code in error::CODES {
1500            let problem =
1501                AdkError::new(ErrorComponent::Server, ErrorCategory::Conflict, code, "refused");
1502            let body = serde_json::to_vec(&problem.to_problem_json()).unwrap();
1503            assert_eq!(AdkError::from(answer_error(StatusCode::CONFLICT, &body)).code, *code);
1504        }
1505        // A code from a crate the kernel composes, which this client does not list.
1506        let foreign = AdkError::new(
1507            ErrorComponent::Server,
1508            ErrorCategory::Conflict,
1509            "session.not_found",
1510            "refused",
1511        );
1512        let body = serde_json::to_vec(&foreign.to_problem_json()).unwrap();
1513        let error = AdkError::from(answer_error(StatusCode::CONFLICT, &body));
1514        assert_eq!((error.code, error.message.as_str()), (error::CONTROL_PLANE_CODE, "refused"));
1515    }
1516}