Skip to main content

adk_kernel/control/
mod.rs

1//! The control plane (spec 3.2 §7.11).
2//!
3//! One API, three transports: a Unix domain socket at the kernel home (macOS, Linux) or a
4//! named pipe named after it (Windows, §10 W2), each of which trusts the OS user, and HTTP on
5//! loopback or, with authentication, on the network. Surfaces hold no state (K-I17); every
6//! control action carries an authenticated subject and is audited as `kernel.control`
7//! (K-I16).
8//!
9//! [`router`] is the API. `adk-rust up` merges it into `ServerBuilder` with
10//! `add_api_routes`, so the server's auth middleware and `RequestContextExtractor` apply and
11//! the routes are served under `/api`; [`ControlPlane`] serves the same router, under the
12//! same `/api` prefix, on the socket and on [`ControlPlaneConfig::http`] when set.
13//!
14//! | Route ([`paths`], under `/api`) | Purpose |
15//! |---|---|
16//! | `GET /kernel/health` | [`KernelHealth`](crate::KernelHealth) |
17//! | `GET /kernel/processes` | the process table, each process with its [`ProcessView`](crate::ProcessView) ([`api::ProcessesQuery`]) |
18//! | `POST /kernel/processes` | start a process of a registered target as the caller ([`api::SpawnRequest`]): a turn a surface sends, or a sleeper with a wake set |
19//! | `POST /kernel/processes/{pid}/{kill,nice,suspend,resume}` | [`ProcessTable`](crate::ProcessTable) actions |
20//! | `POST /kernel/processes/{pid}/run-now`, `POST /kernel/triggers/{name}/run-now` | run a cron sleeper or a standing cron trigger now, outside its schedule ([`api::RunNowRequest`], [`Kernel::run_now`]); refused while frozen |
21//! | `GET /kernel/events` | the event bus as server-sent events, from a cursor ([`api::EventsQuery`]) |
22//! | `POST /kernel/attach/{session}` | a surface attaches to a session: transcript cursor, pending holds, process |
23//! | `POST /kernel/sessions/{session}/steer` | send a message to the running turn of the caller's session ([`api::SteerRequest`], [`Kernel::steer`]): accepted by the turn this replica runs, or handed back to send as the next message |
24//! | `POST /kernel/freeze`, `POST /kernel/unfreeze` | [`Kernel::freeze`] and [`Kernel::unfreeze`]; `unfreeze` only on the socket or pipe, a paired local terminal ([`RESUME_NOT_HERE_CODE`] over HTTP, spec 3.3 S-I10) |
25//! | `GET /kernel/agenda` | the agenda ([`api::AgendaQuery`]) |
26//! | `POST /kernel/agenda/{id}/{approve,reject,schedule}` | [`Agenda`](crate::Agenda) actions as the caller ([`api::RejectRequest`], [`api::ScheduleRequest`]) |
27//! | `GET /kernel/drivers`, `POST /kernel/drivers/{id}/{mount,unmount,restart,reapprove}` (feature `drivers`) | the mounted drivers; a mount shown, then approved with `confirm` (`api::MountDriverRequest`, spec 3.2 §7.7) |
28//! | `GET /kernel/proc/ledger` (feature `proc`) | the content-free ledger, paged by `seq`, as JSON or as the JSONL `cargo adk eval --ledger` reads |
29//! | `GET /kernel/proc/baselines`, `GET /kernel/proc/observations` (feature `proc`) | each partition's last baseline pass, and the observations it offered |
30//! | `POST /kernel/pairing`, `POST /kernel/pairing/claim`, `GET /kernel/devices`, `POST /kernel/devices/{id}/revoke` | device pairing (spec 3.3 §10 K2), when [`ControlPlaneConfig::with_pairing`] sets it; see [`pairing`](crate::pairing) |
31//! | `POST /kernel/channels/pair`, `GET /kernel/channels`, `POST /kernel/channels/{id}/revoke` (feature `channels`) | chat accounts' pairings (spec 3.3 §10 K1) |
32//! | `GET /kernel/partitions` | the partition table ([`api::PartitionsResponse`], spec 3.2 §7.8) |
33//! | `POST /kernel/partitions`, `POST /kernel/partitions/{id}/mode` | create or replace a partition; set its mode ([`api::PartitionModeRequest`]) |
34//! | `GET /kernel/settings[/{partition}]`, `POST /kernel/settings/{partition}/{quiet-time,spending-limit,mode}` | quiet time, the daily spending limit and the mode while the kernel runs (spec 3.3 §10 K3); see [the routes the surfaces need](self#the-routes-the-surfaces-need) |
35//! | `GET /kernel/away`, `POST /kernel/away/seen`, `GET /kernel/away/lines/{seq}` (feature `proc`) | "While you were away" over the `/proc` ledger with a cursor per device (spec 3.3 §10 K4) |
36//! | `GET /kernel/memory`, `POST /kernel/memory/facts/{id}/{confirm,fix,forget}`, `POST /kernel/memory/undo` | what the agents remember, with provenance, and its corrections (spec 3.3 §10 K5) |
37//! | `GET /kernel/record`, `GET /kernel/record/check` | the latest actions on record, and the check that the record is complete (spec 3.3 §10 K5) |
38//! | `GET /kernel/commands`, `POST /kernel/commands/run`, `GET /kernel/rules/always-allow/{id}`, `POST /kernel/rules/always-allow/{id}/{prepare,grant}`, `GET /kernel/sessions/{session}/mode` | the REPL's slash commands, "Always allow" and a session's mode, when [`ControlPlaneConfig::with_commands`] sets a host (spec 3.3 §5.2); see [`CommandHost`] |
39//! | `POST /kernel/surface/records` | the records of a surface engine attached to the kernel, on its signed log (spec 3.3 §11); see [`SurfaceRecord`] |
40//!
41//! The approvals inbox, `/api/runs`, `/api/cron`, `/api/admin/freeze` and `/hooks/{name}`
42//! are the existing server routes, unchanged; `POST /api/admin/freeze` delegates to
43//! [`Kernel::freeze`] through the kernel's `FreezeDelegate` (§10 S4). The socket serves the
44//! approvals inbox beside the kernel routes when the kernel has an approval service, so a
45//! held call is decided over the socket as over HTTP; [`decide_guard`] answers each decision
46//! under spec 3.3 §7.2 for the surface the transport is.
47//!
48//! # Authentication and audit
49//!
50//! Every route needs an authenticated caller: the `Option<RequestContext>` the server's auth
51//! middleware puts in the request extensions must be `Some`, or the route answers `401`.
52//!
53//! | Transport | Caller |
54//! |---|---|
55//! | Socket | The OS user, with the `operator` scope, when the peer's uid is the socket owner's; any other peer is refused |
56//! | Named pipe (Windows) | The OS user, with the `operator` scope, when the token the client opened the pipe with is the kernel's user; the pipe's DACL admits that user alone, and any other client is refused |
57//! | HTTP merged into `ServerBuilder` | Whatever the server's `RequestContextExtractor` admits: `LoopbackOperatorExtractor`, `BearerTokenExtractor` or an SSO extractor |
58//! | [`ControlPlaneConfig::http`] with an extractor | The extractor's subject |
59//! | [`ControlPlaneConfig::http`] on loopback without one | Loopback peers as the OS user with the `operator` scope |
60//! | [`ControlPlaneConfig::http`] beyond loopback without one | Refused at start (K-I18) |
61//!
62//! The routes that change the kernel — `spawn`, `steer`, `kill`, `nice`, `suspend`, `resume`,
63//! `freeze`, `unfreeze`, the agenda's `approve`, `reject` and `schedule`, the driver actions
64//! and the partition writes — and the `/proc` routes, which describe the user's activity,
65//! need the `operator` scope (`403` otherwise), which the socket, the pipe and a loopback
66//! bind grant. `attach` reads only the caller's own sessions. A ledger read is recorded as
67//! `kernel.control` with action `proc.ledger`: the ledger leaves the host only through it, and
68//! "While you were away" (spec 3.3 §10 K4) serves only the rows of its lines.
69//!
70//! A paired device's token (spec 3.3 §10 K2, S-I7) admits it over HTTP as the person who
71//! paired it, only to the routes its scopes open (`read`, `decide`, `stop`; never
72//! `unfreeze`), whatever HTTP admits otherwise: on a loopback HTTP bind a request carrying a
73//! device token is the device, not the operator. The socket and the named pipe admit only
74//! the kernel's own OS user, as the operator, and read no `Authorization` header, so a
75//! device token there changes nothing. Pairing never widens the bind.
76//!
77//! Every action that changes the kernel or reads a session writes a `kernel.control` record
78//! with `subject`, `transport`, `action` and `target` to the kernel's audit trail before it
79//! acts (K-I16; `spawn` records the new `pid` once it exists and cancels the process when
80//! the record fails), and is refused when the record cannot be written under
81//! `AuditFailureMode::Block`, except `freeze`, which takes effect regardless. Reads of the
82//! process table, the partition table, the health and the event stream are authenticated
83//! and not recorded.
84//!
85//! # The routes the surfaces need
86//!
87//! Spec 3.3 §10 K3–K5 adds the routes behind the home's Today and "Agent Memory and Rules"
88//! screens. Reading them needs the `operator` scope, which a paired device with `read`
89//! has; changing a setting or a memory needs the `operator` scope and no device token: the
90//! person at the kernel's socket, pipe or loopback, or signed in to the home. A chat
91//! channel reaches no kernel route.
92//!
93//! | Route | Read | Change | Recorded as `kernel.control` |
94//! |---|---|---|---|
95//! | Settings (K3) | `operator` or device `read` | the person, no device | `settings.quiet_time`, `settings.spending_limit`, `settings.mode`, with `from` and `to` |
96//! | While you were away (K4) | `operator` or device `read` | its own cursor: `operator` or device `read` | no |
97//! | Memory (K5) | `operator` or device `read` | the person, no device | `memory.confirm`, `memory.fix`, `memory.forget`, `memory.undo` |
98//! | Record (K5) | `operator` or device `read` | — | no |
99//!
100//! The settings and cursors live in the [`ControlStore`] of
101//! [`ControlPlaneConfig::control_store`]; the memory and the record are what a
102//! [`MemoryBook`] and a [`RecordBook`] give the kernel, which `adk-rust up` builds over the
103//! harness's facts and the kernel's signed audit log.
104
105use std::collections::BTreeMap;
106use std::fmt;
107use std::net::SocketAddr;
108use std::path::{Path, PathBuf};
109use std::sync::Arc;
110
111use adk_core::AdkError;
112use adk_server::auth_bridge::RequestContextExtractor;
113use axum::Json;
114use axum::Router;
115use axum::http::StatusCode;
116use axum::response::{IntoResponse, Response};
117use serde::{Deserialize, Serialize};
118
119use crate::error::{KernelError, Result};
120use crate::kernel::Kernel;
121
122mod agents;
123pub mod api;
124#[cfg(feature = "proc")]
125mod away;
126mod client;
127mod commands;
128mod decide;
129mod memory;
130mod pairing;
131#[cfg(windows)]
132mod pipe;
133mod record;
134mod routes;
135mod server;
136pub(crate) mod settings;
137#[cfg(unix)]
138mod socket;
139mod store;
140#[cfg(test)]
141mod tests;
142
143pub use crate::error::{DECIDE_NOT_HERE_CODE, RESUME_NOT_HERE_CODE};
144pub use client::ControlClient;
145pub use commands::{
146    AlwaysAllowResponse, CommandCall, CommandHost, CommandInfo, CommandReach, CommandsResponse,
147    RunCommandRequest, RunCommandResponse, SessionModeResponse, SurfaceRecord,
148};
149pub use memory::{FactOrigin, MemoryBook, RememberedFact, TidyUp, TidyUpUndo};
150#[cfg(feature = "channels")]
151pub(crate) use pairing::rated_high;
152pub use record::{RecordBook, RecordCheck, RecordLine};
153pub use server::ControlPlane;
154pub(crate) use store::LastRead;
155#[cfg(feature = "postgres")]
156pub use store::PostgresControlStore;
157#[cfg(feature = "redis")]
158pub use store::RedisControlStore;
159#[cfg(feature = "sqlite")]
160pub use store::SqliteControlStore;
161pub use store::{AreaSettings, AreaStart, AwayCursor, Change, ControlStore, InMemoryControlStore};
162
163/// The control plane's route paths, relative to the `/api` prefix they are served under
164/// (spec 3.2 §7.11).
165pub mod paths {
166    /// The prefix every route is served under, on the socket and through
167    /// `ServerBuilder::add_api_routes`.
168    pub const API_PREFIX: &str = "/api";
169    /// `GET`: the kernel's health.
170    pub const HEALTH: &str = "/kernel/health";
171    /// `GET`: what the kernel runs and would silently not do (`Kernel::inventory`), for the
172    /// `operator` scope.
173    pub const INVENTORY: &str = "/kernel/inventory";
174    /// `GET`: the process table; `POST`: start a process.
175    pub const PROCESSES: &str = "/kernel/processes";
176    /// `POST`: kill a process.
177    pub const KILL: &str = "/kernel/processes/{pid}/kill";
178    /// `POST`: move a process to another queue.
179    pub const NICE: &str = "/kernel/processes/{pid}/nice";
180    /// `POST`: suspend a process.
181    pub const SUSPEND: &str = "/kernel/processes/{pid}/suspend";
182    /// `POST`: resume a process.
183    pub const RESUME: &str = "/kernel/processes/{pid}/resume";
184    /// `POST`: run a cron sleeper now.
185    pub const RUN_NOW: &str = "/kernel/processes/{pid}/run-now";
186    /// `POST`: run a standing cron trigger now.
187    pub const TRIGGER_RUN_NOW: &str = "/kernel/triggers/{name}/run-now";
188    /// `GET`: the event bus as server-sent events.
189    pub const EVENTS: &str = "/kernel/events";
190    /// `POST`: attach to a session.
191    pub const ATTACH: &str = "/kernel/attach/{session}";
192    /// `POST`: freeze execution.
193    pub const FREEZE: &str = "/kernel/freeze";
194    /// `POST`: lift the freeze.
195    pub const UNFREEZE: &str = "/kernel/unfreeze";
196    /// `GET`: the agenda (spec 3.2 §7.5).
197    pub const AGENDA: &str = "/kernel/agenda";
198    /// `POST`: approve an agenda item.
199    pub const AGENDA_APPROVE: &str = "/kernel/agenda/{id}/approve";
200    /// `POST`: reject an agenda item.
201    pub const AGENDA_REJECT: &str = "/kernel/agenda/{id}/reject";
202    /// `POST`: schedule an agenda item on a wake set.
203    pub const AGENDA_SCHEDULE: &str = "/kernel/agenda/{id}/schedule";
204    /// `GET`: the mounted drivers (spec 3.2 §7.7).
205    pub const DRIVERS: &str = "/kernel/drivers";
206    /// `POST`: show, or with `confirm`, approve and mount a driver's manifest.
207    pub const DRIVER_MOUNT: &str = "/kernel/drivers/{id}/mount";
208    /// `POST`: unmount a driver.
209    pub const DRIVER_UNMOUNT: &str = "/kernel/drivers/{id}/unmount";
210    /// `POST`: restart a driver.
211    pub const DRIVER_RESTART: &str = "/kernel/drivers/{id}/restart";
212    /// `POST`: re-approve a driver's changed declarations.
213    pub const DRIVER_REAPPROVE: &str = "/kernel/drivers/{id}/reapprove";
214    /// `GET`: the activity ledger (spec 3.2 §7.10).
215    pub const PROC_LEDGER: &str = "/kernel/proc/ledger";
216    /// `GET`: each partition's baselines (spec 3.2 §7.10).
217    pub const PROC_BASELINES: &str = "/kernel/proc/baselines";
218    /// `GET`: the observations (spec 3.2 §7.10).
219    pub const PROC_OBSERVATIONS: &str = "/kernel/proc/observations";
220    /// `POST`: issue a device pairing code (spec 3.3 §10 K2).
221    pub const PAIRING: &str = "/kernel/pairing";
222    /// `POST`: claim a pairing code; the one route that needs no caller (spec 3.3 §10 K2).
223    pub const PAIRING_CLAIM: &str = "/kernel/pairing/claim";
224    /// `GET`: the paired devices (spec 3.3 §10 K2).
225    pub const DEVICES: &str = "/kernel/devices";
226    /// `POST`: remove a paired device (spec 3.3 §10 K2).
227    pub const DEVICE_REVOKE: &str = "/kernel/devices/{id}/revoke";
228    /// `GET`: the paired chat accounts (spec 3.3 §10 K1).
229    pub const CHANNELS: &str = "/kernel/channels";
230    /// `POST`: accept the code a chat account was sent (spec 3.3 §10 K1).
231    pub const CHANNEL_PAIR: &str = "/kernel/channels/pair";
232    /// `POST`: remove a paired chat account (spec 3.3 §10 K1).
233    pub const CHANNEL_REVOKE: &str = "/kernel/channels/{id}/revoke";
234    /// `POST`: dismiss a chat account waiting to be paired (spec 3.3 §10 K1).
235    pub const CHANNEL_DISMISS: &str = "/kernel/channels/waiting/{id}/dismiss";
236    /// `GET`: the agents a person added (spec 3.3 §10 K7); no route changes one.
237    pub const AGENTS: &str = "/kernel/agents";
238    /// `GET`: one agent a person added (spec 3.3 §10 K7).
239    pub const AGENT: &str = "/kernel/agents/{id}";
240    /// `GET`: the partition table; `POST`: create or replace a partition (spec 3.2 §7.8).
241    pub const PARTITIONS: &str = "/kernel/partitions";
242    /// `POST`: set a partition's mode (spec 3.2 §7.8, §8.1 `partitions set-mode`).
243    pub const PARTITION_MODE: &str = "/kernel/partitions/{id}/mode";
244    /// `GET`: every area's settings in force (spec 3.3 §10 K3).
245    pub const SETTINGS: &str = "/kernel/settings";
246    /// `GET`: one area's settings in force (spec 3.3 §10 K3).
247    pub const AREA_SETTINGS: &str = "/kernel/settings/{partition}";
248    /// `POST`: set or turn off an area's quiet time (spec 3.3 §10 K3).
249    pub const QUIET_TIME: &str = "/kernel/settings/{partition}/quiet-time";
250    /// `POST`: set or remove an area's daily spending limit (spec 3.3 §10 K3).
251    pub const SPENDING_LIMIT: &str = "/kernel/settings/{partition}/spending-limit";
252    /// `POST`: set how much an area's agents act alone (spec 3.3 §10 K3).
253    pub const AREA_MODE: &str = "/kernel/settings/{partition}/mode";
254    /// `GET`: "While you were away" from the viewer's cursor (spec 3.3 §10 K4).
255    pub const AWAY: &str = "/kernel/away";
256    /// `POST`: mark "While you were away" seen through a ledger row (spec 3.3 §10 K4).
257    pub const AWAY_SEEN: &str = "/kernel/away/seen";
258    /// `GET`: one line of "While you were away" with its ledger row (spec 3.3 §10 K4).
259    pub const AWAY_LINE: &str = "/kernel/away/lines/{seq}";
260    /// `GET`: what the agents remember, with provenance (spec 3.3 §10 K5).
261    pub const MEMORY: &str = "/kernel/memory";
262    /// `POST`: confirm a remembered fact: "That's right" (spec 3.3 §10 K5).
263    pub const FACT_CONFIRM: &str = "/kernel/memory/facts/{id}/confirm";
264    /// `POST`: correct a remembered fact: "Fix it" (spec 3.3 §10 K5).
265    pub const FACT_FIX: &str = "/kernel/memory/facts/{id}/fix";
266    /// `POST`: forget a remembered fact: "Forget it" (spec 3.3 §10 K5).
267    pub const FACT_FORGET: &str = "/kernel/memory/facts/{id}/forget";
268    /// `POST`: undo an overnight tidy-up of the memory (spec 3.3 §10 K5).
269    pub const MEMORY_UNDO: &str = "/kernel/memory/undo";
270    /// `GET`: the latest actions on record (spec 3.3 §10 K5).
271    pub const RECORD: &str = "/kernel/record";
272    /// `GET`: check that every action is on record and nothing was changed or deleted (spec
273    /// 3.3 §10 K5).
274    pub const RECORD_CHECK: &str = "/kernel/record/check";
275    /// `GET`: the REPL's slash commands the kernel offers (spec 3.3 §5.2).
276    pub const COMMANDS: &str = "/kernel/commands";
277    /// `POST`: run one of them in the caller's session (spec 3.3 §5.2).
278    pub const COMMAND_RUN: &str = "/kernel/commands/run";
279    /// `GET`: what "Always allow" creates for a waiting decision (spec 3.3 §8.2).
280    pub const ALWAYS_ALLOW: &str = "/kernel/rules/always-allow/{id}";
281    /// `POST`: make that standing rule, before the decision is answered (spec 3.3 §8.2).
282    pub const ALWAYS_ALLOW_PREPARE: &str = "/kernel/rules/always-allow/{id}/prepare";
283    /// `POST`: grant it, once the decision was allowed (spec 3.3 §8.2).
284    pub const ALWAYS_ALLOW_GRANT: &str = "/kernel/rules/always-allow/{id}/grant";
285    /// `GET`: the mode of the caller's session (spec 3.3 §5.2).
286    pub const SESSION_MODE: &str = "/kernel/sessions/{session}/mode";
287    /// `POST`: write a surface engine's record on the kernel's signed log (spec 3.3 §11).
288    pub const SURFACE_RECORDS: &str = "/kernel/surface/records";
289    /// `POST`: send a message to the running turn of the caller's session (spec 3.3 §6).
290    pub const SESSION_STEER: &str = "/kernel/sessions/{session}/steer";
291}
292
293/// Where the control plane listens and how it authenticates HTTP callers (spec 3.2 §7.11).
294///
295/// The socket trusts the OS user. HTTP authenticates with the extractor the caller passes:
296/// adk-cli passes `LoopbackOperatorExtractor` on loopback and `BearerTokenExtractor`
297/// otherwise, with the `operator` scope the approvals inbox routes to; SSO extractors from
298/// `adk-auth` serve teams. A non-loopback bind without an extractor is refused (K-I18).
299///
300/// # Example
301///
302/// ```rust
303/// use std::path::Path;
304/// use adk_kernel::control::ControlPlaneConfig;
305///
306/// let config = ControlPlaneConfig::default();
307/// assert_eq!(config.socket_path(Path::new("/home/a/.config/adk-rust")).unwrap(), Path::new("/home/a/.config/adk-rust/kernel.sock"));
308/// assert!(config.validate().is_ok());
309///
310/// let exposed = ControlPlaneConfig::default().with_http("0.0.0.0:8080".parse().unwrap());
311/// assert!(exposed.validate().is_err());
312/// ```
313#[derive(Clone)]
314#[non_exhaustive]
315pub struct ControlPlaneConfig {
316    /// The Unix socket, relative to the kernel home unless absolute; `None` serves no
317    /// socket. Defaults to [`DEFAULT_SOCKET`](Self::DEFAULT_SOCKET).
318    pub socket: Option<PathBuf>,
319    /// An HTTP bind the kernel serves itself; `None` when the routes are merged into a
320    /// `ServerBuilder` instead. Defaults to `None`.
321    pub http: Option<SocketAddr>,
322    /// Authenticates HTTP callers; required on a non-loopback bind (K-I18).
323    pub extractor: Option<Arc<dyn RequestContextExtractor>>,
324    /// Pairs devices and admits their tokens (spec 3.3 §10 K2); `None` pairs none.
325    pub pairing: Option<crate::pairing::Pairing>,
326    /// Keeps the settings a person changes while the kernel runs and each device's place in
327    /// "While you were away" (spec 3.3 §10 K3, K4). Defaults to an
328    /// [`InMemoryControlStore`], so a restart brings back the start settings; `adk-rust up`
329    /// keeps them beside its other stores.
330    pub control_store: Arc<dyn ControlStore>,
331    /// What the agents remember, for the memory routes (spec 3.3 §10 K5); `None` serves
332    /// none.
333    pub memory: Option<Arc<dyn MemoryBook>>,
334    /// The record of actions and its check, for the record routes (spec 3.3 §10 K5); `None`
335    /// serves none.
336    pub record: Option<Arc<dyn RecordBook>>,
337    /// The REPL's slash commands and "Always allow", for the command routes (spec 3.3 §5.2);
338    /// `None` serves none.
339    pub commands: Option<Arc<dyn CommandHost>>,
340    /// The mode each area's agents started in, which the settings routes report until the
341    /// person changes it (spec 3.3 §10 K3). A partition's record gives its own.
342    pub start_modes: BTreeMap<crate::partition::PartitionId, crate::partition::PartitionMode>,
343    /// The modes the settings routes refuse to set, each with why, such as Auto on a kernel
344    /// served beyond loopback without a sandbox (spec 3.3 §10 K3); a change to one made
345    /// before is not applied.
346    pub refused_modes: Vec<(crate::partition::PartitionMode, String)>,
347    /// The in-memory store `Default` made, to tell it from one the caller set.
348    default_control_store: Arc<dyn ControlStore>,
349}
350
351impl ControlPlaneConfig {
352    /// The socket's file name under the kernel home.
353    pub const DEFAULT_SOCKET: &'static str = "kernel.sock";
354
355    /// Serves the socket at `path`, relative to the kernel home unless absolute.
356    #[must_use]
357    pub fn with_socket(mut self, path: impl Into<PathBuf>) -> Self {
358        self.socket = Some(path.into());
359        self
360    }
361
362    /// Serves no socket.
363    #[must_use]
364    pub fn without_socket(mut self) -> Self {
365        self.socket = None;
366        self
367    }
368
369    /// Serves HTTP on `addr`.
370    #[must_use]
371    pub fn with_http(mut self, addr: SocketAddr) -> Self {
372        self.http = Some(addr);
373        self
374    }
375
376    /// Authenticates HTTP callers with `extractor`.
377    #[must_use]
378    pub fn with_extractor(mut self, extractor: Arc<dyn RequestContextExtractor>) -> Self {
379        self.extractor = Some(extractor);
380        self
381    }
382
383    /// Pairs devices with `pairing` and admits their tokens, each to the routes its scopes
384    /// open (spec 3.3 §10 K2). It changes no bind: a non-loopback bind still needs an
385    /// extractor (S-I7, K-I18).
386    #[must_use]
387    pub fn with_pairing(mut self, pairing: crate::pairing::Pairing) -> Self {
388        self.pairing = Some(pairing);
389        self
390    }
391
392    /// Keeps changed settings and away cursors in `store` (spec 3.3 §10 K3, K4).
393    #[must_use]
394    pub fn with_control_store(mut self, store: Arc<dyn ControlStore>) -> Self {
395        self.control_store = store;
396        self
397    }
398
399    /// Serves the memory routes over `book` (spec 3.3 §10 K5).
400    #[must_use]
401    pub fn with_memory(mut self, book: Arc<dyn MemoryBook>) -> Self {
402        self.memory = Some(book);
403        self
404    }
405
406    /// Serves the record routes over `book` (spec 3.3 §10 K5).
407    #[must_use]
408    pub fn with_record(mut self, book: Arc<dyn RecordBook>) -> Self {
409        self.record = Some(book);
410        self
411    }
412
413    /// Serves the REPL's slash commands and "Always allow" over `host` (spec 3.3 §5.2), so a
414    /// terminal attached to the kernel has the commands the REPL has.
415    #[must_use]
416    pub fn with_commands(mut self, host: Arc<dyn CommandHost>) -> Self {
417        self.commands = Some(host);
418        self
419    }
420
421    /// Reports `mode` as the mode `partition`'s agents started in (spec 3.3 §10 K3).
422    #[must_use]
423    pub fn with_start_mode(
424        mut self,
425        partition: impl Into<crate::partition::PartitionId>,
426        mode: crate::partition::PartitionMode,
427    ) -> Self {
428        self.start_modes.insert(partition.into(), mode);
429        self
430    }
431
432    /// Refuses to set `mode` through the settings routes, saying `reason` (spec 3.3 §10 K3):
433    /// the start checks of `adk-rust up` hold for a mode changed while it runs.
434    ///
435    /// # Example
436    ///
437    /// ```rust
438    /// use adk_kernel::PartitionMode;
439    /// use adk_kernel::control::ControlPlaneConfig;
440    ///
441    /// let config = ControlPlaneConfig::default()
442    ///     .with_refused_mode(PartitionMode::Auto, "Go ahead needs --sandbox beyond loopback");
443    /// assert_eq!(config.refused_modes.len(), 1);
444    /// ```
445    #[must_use]
446    pub fn with_refused_mode(
447        mut self,
448        mode: crate::partition::PartitionMode,
449        reason: impl Into<String>,
450    ) -> Self {
451        self.refused_modes.push((mode, reason.into()));
452        self
453    }
454
455    /// Whether the control store is still the in-memory one `Default` made, so a restart
456    /// brings back the start settings.
457    pub fn has_default_control_store(&self) -> bool {
458        std::ptr::addr_eq(
459            Arc::as_ptr(&self.control_store),
460            Arc::as_ptr(&self.default_control_store),
461        )
462    }
463
464    /// Why the settings routes refuse to set `mode`, or `None`.
465    pub fn refused_mode(&self, mode: crate::partition::PartitionMode) -> Option<&str> {
466        self.refused_modes
467            .iter()
468            .find(|(refused, _)| *refused == mode)
469            .map(|(_, reason)| reason.as_str())
470    }
471
472    /// The socket's path for the kernel at `home`, or `None` when no socket is served.
473    ///
474    /// It is the socket under `home` when that path fits a Unix socket address (103 bytes on
475    /// macOS, 107 on Linux). When it does not, the kernel and its clients use
476    /// `adk-rust-<tag>/<socket name>` under the user's own temp directory instead, the tag
477    /// derived from the resolved home, so each derives the same path from the same home
478    /// (spec 3.3 G18). Windows serves a named pipe and keeps the path under the home.
479    ///
480    /// # Example
481    ///
482    /// ```rust
483    /// use std::path::Path;
484    /// use adk_kernel::control::ControlPlaneConfig;
485    ///
486    /// let config = ControlPlaneConfig::default();
487    /// let short = config.socket_path(Path::new("/home/a/.config/adk-rust")).unwrap();
488    /// assert_eq!(short, Path::new("/home/a/.config/adk-rust/kernel.sock"));
489    /// # #[cfg(unix)]
490    /// # {
491    /// let long = Path::new("/srv").join("a-kernel-home-with-a-long-name/".repeat(4));
492    /// let socket = config.socket_path(&long).unwrap();
493    /// assert!(!socket.starts_with(&long) && socket.ends_with("kernel.sock"));
494    /// # }
495    /// ```
496    pub fn socket_path(&self, home: &Path) -> Option<PathBuf> {
497        let path = home.join(self.socket.as_ref()?);
498        #[cfg(unix)]
499        let path = socket::place(path);
500        Some(path)
501    }
502
503    /// The named pipe Windows serves in place of the socket (spec 3.2 §10 W2), or `None`
504    /// when no socket is served: `\\.\pipe\adk-rust-kernel-<tag>`, where the tag is
505    /// derived from the absolute socket path, so each kernel home has its own pipe. Pipe
506    /// names are not files, so the name is computed the same way on every platform.
507    ///
508    /// # Example
509    ///
510    /// ```rust
511    /// use std::path::Path;
512    /// use adk_kernel::control::ControlPlaneConfig;
513    ///
514    /// let config = ControlPlaneConfig::default();
515    /// let pipe = config.pipe_name(Path::new("/home/a/.config/adk-rust")).unwrap();
516    /// assert!(pipe.starts_with(r"\\.\pipe\adk-rust-kernel-"));
517    /// assert_ne!(Some(pipe), config.pipe_name(Path::new("/srv/kernel")));
518    /// assert_eq!(config.without_socket().pipe_name(Path::new("/srv/kernel")), None);
519    /// ```
520    pub fn pipe_name(&self, home: &Path) -> Option<String> {
521        let socket = home.join(self.socket.as_ref()?);
522        Some(format!(r"\\.\pipe\adk-rust-kernel-{}", crate::path_tag(&socket)))
523    }
524
525    /// Refuses a non-loopback HTTP bind without an extractor (K-I18).
526    ///
527    /// # Errors
528    ///
529    /// Returns [`KernelError::Config`] naming the bind.
530    pub fn validate(&self) -> Result<()> {
531        match self.http {
532            Some(addr) if !addr.ip().is_loopback() && self.extractor.is_none() => {
533                Err(KernelError::Config {
534                    reason: format!(
535                        "serving the control plane on {addr} needs authentication: pass a \
536                         bearer token or SSO extractor, or bind 127.0.0.1"
537                    ),
538                })
539            }
540            _ => Ok(()),
541        }
542    }
543}
544
545impl Default for ControlPlaneConfig {
546    fn default() -> Self {
547        let control_store: Arc<dyn ControlStore> = Arc::new(InMemoryControlStore::new());
548        Self {
549            socket: Some(PathBuf::from(Self::DEFAULT_SOCKET)),
550            http: None,
551            extractor: None,
552            pairing: None,
553            default_control_store: Arc::clone(&control_store),
554            control_store,
555            memory: None,
556            record: None,
557            commands: None,
558            start_modes: BTreeMap::new(),
559            refused_modes: Vec::new(),
560        }
561    }
562}
563
564impl fmt::Debug for ControlPlaneConfig {
565    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566        f.debug_struct("ControlPlaneConfig")
567            .field("socket", &self.socket)
568            .field("http", &self.http)
569            .field("extractor", &self.extractor.is_some())
570            .field("pairing", &self.pairing)
571            .field("memory", &self.memory.is_some())
572            .field("record", &self.record.is_some())
573            .field("commands", &self.commands.is_some())
574            .field("start_modes", &self.start_modes)
575            .field("refused_modes", &self.refused_modes)
576            .finish()
577    }
578}
579
580/// The transport a control action arrived on, as the `kernel.control` audit record names it
581/// (spec 3.2 §9.3).
582///
583/// # Example
584///
585/// ```rust
586/// use adk_kernel::control::ControlTransport;
587///
588/// assert_eq!(serde_json::to_value(ControlTransport::Socket).unwrap(), "socket");
589/// ```
590#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
591#[serde(rename_all = "camelCase")]
592#[non_exhaustive]
593pub enum ControlTransport {
594    /// The Unix socket.
595    Socket,
596    /// HTTP.
597    Http,
598    /// The named pipe on Windows (spec 3.2 §10 W2).
599    Pipe,
600}
601
602/// The control plane's routes over `kernel` (spec 3.2 §7.11), relative to the `/api`
603/// prefix: merge them with `ServerBuilder::add_api_routes`, whose auth middleware puts the
604/// caller's `RequestContext` in the request extensions. Building them sets
605/// [`Kernel::serves_routes`], which tells a web home served beside them to read them.
606///
607/// # Example
608///
609/// ```rust,no_run
610/// # fn example(kernel: adk_kernel::Kernel, builder: adk_server::ServerBuilder) {
611/// let builder = builder.add_api_routes(adk_kernel::control::router(kernel));
612/// # let _ = builder;
613/// # }
614/// ```
615pub fn router(kernel: Kernel) -> Router {
616    kernel.mark_routes_served();
617    routes::routes(Arc::new(kernel))
618}
619
620/// The claim route of `kernel`'s device pairing (spec 3.3 §10 K2) at
621/// `/api/kernel/pairing/claim`, which needs no caller since the code is the credential:
622/// merge it with `ServerBuilder::add_root_routes`, outside the auth middleware and inside
623/// the host and origin checks. Empty when the kernel pairs no devices.
624///
625/// A server that serves the kernel's routes to devices needs all three pieces: the routes
626/// behind a [`DeviceTokenExtractor`](crate::pairing::DeviceTokenExtractor), this claim
627/// route, and [`guard_devices`] around the built app, which checks a device's decision for
628/// its risk and records it; the extractor refuses a device's decision the guard did not
629/// admit.
630///
631/// # Example
632///
633/// ```rust,no_run
634/// use std::sync::Arc;
635/// use adk_kernel::pairing::DeviceTokenExtractor;
636///
637/// # fn example(kernel: adk_kernel::Kernel, config: adk_server::ServerConfig, bearer: Arc<dyn adk_server::auth_bridge::RequestContextExtractor>) {
638/// let pairing = kernel.config().control.pairing.clone().expect("the kernel pairs devices");
639/// let extractor = DeviceTokenExtractor::new(pairing).with_fallback(bearer);
640/// let app = adk_server::ServerBuilder::new(config.with_request_context(Arc::new(extractor)))
641///     .add_api_routes(adk_kernel::control::router(kernel.clone()))
642///     .add_root_routes(adk_kernel::control::claim_router(kernel.clone()))
643///     .build();
644/// let app = adk_kernel::control::guard_devices(&kernel, app);
645/// # let _ = app;
646/// # }
647/// ```
648pub fn claim_router(kernel: Kernel) -> Router {
649    let backend: Arc<dyn routes::ControlBackend> = Arc::new(kernel);
650    match backend.pairing() {
651        Some(_) => pairing::claim_routes(backend),
652        None => Router::new(),
653    }
654}
655
656/// `app` with every request that carries a device token checked against `kernel`'s pairing
657/// first (spec 3.3 §10 K2, S-I7): `401` for an unknown, expired or revoked token, `403` for
658/// a route its scopes do not open, a decision it answers on `POST /approvals/{id}/decide`
659/// limited to low and medium risk and recorded. The server's own routes are those of
660/// [`Pairing::with_device_routes`](crate::pairing::Pairing::with_device_routes); a decision
661/// on one of them is admitted for the server's engine, which applies what each surface may
662/// decide. Layer it on the whole app that serves the kernel's routes, so no route outside
663/// them admits a device either; requests without a device token pass untouched.
664///
665/// # Example
666///
667/// ```rust,no_run
668/// # fn example(kernel: adk_kernel::Kernel, app: axum::Router) {
669/// let app = adk_kernel::control::guard_devices(&kernel, app);
670/// # let _ = app;
671/// # }
672/// ```
673pub fn guard_devices(kernel: &Kernel, app: Router) -> Router {
674    pairing::guard(Arc::new(kernel.clone()), app)
675}
676
677/// `kernel`'s check of every decision on `POST /api/approvals/{id}/decide` (spec 3.3 §7.2,
678/// §11 S-I11, S-I13): the answer is checked under §7.2 for the surface the server
679/// established — the kernel's socket or pipe as a paired local terminal, a paired device by
680/// its kind, an operator credential over HTTP as `api` — and refused with
681/// [`DECIDE_NOT_HERE_CODE`] where that surface may not give it; never by a surface a client
682/// declares. An admitted decision is recorded before it reaches the inbox, and a suggested
683/// agent it answers is added or ended at once as that surface. The kernel's own control plane
684/// installs it; a server that serves the kernel's inbox installs it with
685/// `ApprovalEndpoints::with_decide_guard`.
686///
687/// # Example
688///
689/// ```rust,no_run
690/// use adk_server::approvals::ApprovalEndpoints;
691///
692/// # fn example(kernel: adk_kernel::Kernel, service: std::sync::Arc<dyn adk_core::ApprovalService>, builder: adk_server::ServerBuilder) {
693/// let endpoints =
694///     ApprovalEndpoints::new(service).with_decide_guard(adk_kernel::control::decide_guard(&kernel));
695/// let builder = builder.with_approval_endpoints(endpoints);
696/// # let _ = builder;
697/// # }
698/// ```
699pub fn decide_guard(kernel: &Kernel) -> Arc<dyn adk_server::approvals::DecideGuard> {
700    Arc::new(decide::KernelDecideGuard::new(Arc::new(kernel.clone())))
701}
702
703impl IntoResponse for KernelError {
704    fn into_response(self) -> Response {
705        let error = AdkError::from(self);
706        let status = StatusCode::from_u16(error.http_status_code())
707            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
708        (status, Json(error.to_problem_json())).into_response()
709    }
710}