adk_kernel/control/commands.rs
1//! The harness REPL's slash commands and "Always allow" over the control plane (spec 3.3
2//! §5.2, §7.2, §8.2).
3//!
4//! The kernel runs no command itself and names no harness type: a [`CommandHost`] is what the
5//! harness gives the kernel, as a [`MemoryBook`](super::MemoryBook) is, so a terminal attached
6//! to the kernel offers the same commands as the REPL, run by the same code over the kernel's
7//! harness, and answers "Always allow" with the standing rule the harness makes in process.
8//! `adk-rust up` builds one over its harness.
9//!
10//! | Route (under `/api`) | Caller | Does |
11//! |---|---|---|
12//! | `GET /kernel/commands` | the person, no device | The commands the host offers, in `/help` order ([`CommandsResponse`]) |
13//! | `POST /kernel/commands/run` | the person, no device | Runs one in the caller's session ([`RunCommandRequest`] → [`RunCommandResponse`]); one that changes something is refused while everything is stopped |
14//! | `GET /kernel/rules/always-allow/{id}` | the person, no device | What "Always allow" creates for the caller's waiting decision `id` ([`AlwaysAllowResponse`]); `404` when no standing rule applies |
15//! | `POST /kernel/rules/always-allow/{id}/prepare` | the person, no device | Prepares that rule, before the decision is answered |
16//! | `POST /kernel/rules/always-allow/{id}/grant` | the person, no device | Grants the prepared rule, once the caller's own yes was recorded |
17//! | `GET /kernel/sessions/{session}/mode` | the person, no device | The mode of the caller's session ([`SessionModeResponse`]), read without a record; `404` when the host keeps no modes |
18//! | `POST /kernel/surface/records` | the person, no device | Writes one record of a surface engine attached to the kernel ([`SurfaceRecord`]) on the kernel's signed log |
19//!
20//! "Always allow" takes two steps because the rule is made from the held call, which the
21//! answer clears, and is granted only once the answer was recorded: an answer that loses to
22//! one given elsewhere grants nothing, as in process. The routes never make a standing rule
23//! of a high-risk call, and grant one only when the decision's last answer is the caller's
24//! own "Allow once": an edit, or someone else's yes, grants nothing (spec 3.3 §7.2).
25//!
26//! While everything is stopped, a command that lets the agents do more is refused with
27//! `409 kernel.frozen`; one that only makes them do less — the host says which
28//! ([`CommandHost::tightens`]) — still runs, so a rule can be revoked or a fact forgotten
29//! before Resume all (S-I10).
30//!
31//! A surface engine in another process, such as a terminal attached to the kernel, writes
32//! its records — every answer with the surface and how it was given, Stop all, Resume all,
33//! a mode change, a message sent — through `POST /kernel/surface/records`, so they reach the
34//! same signed log as the home's (spec 3.3 §11). The kernel names the caller as the record's
35//! actor and the transport it came over, whatever the record says; only `surface.*` actions
36//! are written, and an answer's record only for the caller's own decision.
37//!
38//! A paired device's token is refused with `403`: commands and standing rules change what
39//! the agents may do, which only the person at the kernel's socket, pipe or loopback, or
40//! signed in to the home, may (S-I7). Each run is recorded as `kernel.control` with action
41//! `commands.run`, the command's name as its target and the session, arguments, whether it
42//! changes something and how the caller reached the kernel ([`CommandReach`]) as its details;
43//! a granted rule as `rules.always_allow`, the decision as its target. Both are recorded
44//! before they act. The host gets each run as a [`CommandCall`]: the caller, their session,
45//! the command and how the caller reached the kernel, so a command can decide what it allows
46//! by it.
47
48use std::collections::BTreeMap;
49use std::sync::Arc;
50
51use adk_core::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
52use adk_core::principal::SubjectRef;
53use adk_core::{
54 AdkError, ApprovalAction, ApprovalRequest, ApprovalRisk, ApprovalState, ErrorCategory,
55 ErrorComponent,
56};
57use async_trait::async_trait;
58use axum::Json;
59use axum::Router;
60use axum::extract::{Extension, Path as UrlPath, State};
61use axum::http::Method;
62use axum::routing::{get, post};
63use serde::{Deserialize, Serialize};
64use serde_json::json;
65
66use super::client::encode;
67use super::routes::{Caller, ControlBackend, record};
68use super::server::PeerProcess;
69use super::settings::require_owner;
70use super::{ControlTransport, paths};
71use crate::error::{
72 CONFIG_CODE, FROZEN_CODE, INVALID_STATE_CODE, KernelError, NOT_FOUND_CODE, Result,
73};
74
75/// How much of a command's arguments its record keeps.
76const RECORDED_ARGS: usize = 200;
77
78/// A slash command the kernel's host offers (spec 3.3 §5.2).
79///
80/// # Example
81///
82/// ```rust
83/// use adk_kernel::control::CommandInfo;
84///
85/// let todos = CommandInfo::new("todos", "Show the session's todo list");
86/// assert_eq!(serde_json::to_value(&todos).unwrap()["name"], "todos");
87/// ```
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90#[non_exhaustive]
91pub struct CommandInfo {
92 /// The name typed after the slash: `todos` for `/todos`.
93 pub name: String,
94 /// One line on what it does.
95 pub description: String,
96}
97
98impl CommandInfo {
99 /// The command `name`, described as `description`.
100 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
101 Self { name: name.into(), description: description.into() }
102 }
103}
104
105/// How the caller of a command reached the kernel (spec 3.3 §5.2): the transport, the paired
106/// device whose token admitted it, and the calling process where the transport says. A
107/// command reads it to decide what it allows; the run's record names it.
108///
109/// # Example
110///
111/// ```rust
112/// use adk_kernel::control::{CommandReach, ControlTransport};
113///
114/// let local = CommandReach::new(ControlTransport::Socket).with_peer_pid(4242);
115/// assert!(local.is_local() && local.device.is_none());
116/// let phone = CommandReach::new(ControlTransport::Http).with_device("dev_1");
117/// assert!(!phone.is_local());
118/// assert_eq!(serde_json::to_value(&local).unwrap()["peerPid"], 4242);
119/// ```
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase")]
122#[non_exhaustive]
123pub struct CommandReach {
124 /// The kernel's socket, its named pipe, or HTTP.
125 pub transport: ControlTransport,
126 /// The paired device whose token admitted the call; `None` for the person at the kernel
127 /// or signed in to the home.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub device: Option<String>,
130 /// The process that called, when the transport says: the socket's peer.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub peer_pid: Option<u32>,
133}
134
135impl CommandReach {
136 /// A call that came over `transport`, from no device and no known process.
137 pub fn new(transport: ControlTransport) -> Self {
138 Self { transport, device: None, peer_pid: None }
139 }
140
141 /// Sets the paired device whose token admitted the call.
142 #[must_use]
143 pub fn with_device(mut self, device: impl Into<String>) -> Self {
144 self.device = Some(device.into());
145 self
146 }
147
148 /// Sets the process that called.
149 #[must_use]
150 pub fn with_peer_pid(mut self, pid: u32) -> Self {
151 self.peer_pid = Some(pid);
152 self
153 }
154
155 /// Whether the caller is at the kernel's own machine as the OS user that runs it: the
156 /// socket or the named pipe, which admit no one else.
157 pub fn is_local(&self) -> bool {
158 matches!(self.transport, ControlTransport::Socket | ControlTransport::Pipe)
159 }
160}
161
162/// One run of a command, as the host gets it (spec 3.3 §5.2).
163///
164/// # Example
165///
166/// ```rust
167/// use adk_kernel::control::{CommandCall, CommandReach, ControlTransport};
168///
169/// let call = CommandCall::new("ana", "s1", "todos", "", CommandReach::new(ControlTransport::Socket));
170/// assert_eq!((call.user.as_str(), call.name.as_str()), ("ana", "todos"));
171/// ```
172#[derive(Debug, Clone, PartialEq, Eq)]
173#[non_exhaustive]
174pub struct CommandCall {
175 /// The caller; the host runs the command for this person only.
176 pub user: String,
177 /// The caller's session it runs in: the thread the terminal shows.
178 pub session: String,
179 /// The command's name, without the slash.
180 pub name: String,
181 /// The text after its name, trimmed.
182 pub args: String,
183 /// How the caller reached the kernel.
184 pub reach: CommandReach,
185}
186
187impl CommandCall {
188 /// `/name args` run by `user` in `session`, reached as `reach`.
189 pub fn new(
190 user: impl Into<String>,
191 session: impl Into<String>,
192 name: impl Into<String>,
193 args: impl Into<String>,
194 reach: CommandReach,
195 ) -> Self {
196 Self {
197 user: user.into(),
198 session: session.into(),
199 name: name.into(),
200 args: args.into(),
201 reach,
202 }
203 }
204}
205
206/// `GET /kernel/commands` answer (spec 3.3 §5.2).
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209pub struct CommandsResponse {
210 /// The commands, in `/help` order.
211 pub commands: Vec<CommandInfo>,
212}
213
214/// `POST /kernel/commands/run` body (spec 3.3 §5.2).
215#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
216#[serde(rename_all = "camelCase")]
217pub struct RunCommandRequest {
218 /// The command's name, without the slash.
219 pub name: String,
220 /// The text after its name.
221 #[serde(default)]
222 pub args: String,
223 /// The caller's session the command runs in: the thread the terminal shows.
224 pub session_id: String,
225}
226
227/// `POST /kernel/commands/run` answer (spec 3.3 §5.2).
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(rename_all = "camelCase")]
230pub struct RunCommandResponse {
231 /// What the command returned, as the REPL prints it. Escape it before display (S-I9).
232 pub text: String,
233}
234
235/// The answer of the "Always allow" routes: the words of the rule (spec 3.3 §8.2).
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "camelCase")]
238pub struct AlwaysAllowResponse {
239 /// The answer's words, such as "Always allow for this folder".
240 pub label: String,
241}
242
243/// `GET /kernel/sessions/{session}/mode` answer: the mode of the caller's session, so a
244/// terminal attached to the kernel shows the mode in force and knows whether a change
245/// loosens it (spec 3.3 §5.2, §8.1).
246///
247/// # Example
248///
249/// ```rust
250/// use adk_kernel::control::SessionModeResponse;
251///
252/// let answer: SessionModeResponse = serde_json::from_value(serde_json::json!({ "mode": "ask" })).unwrap();
253/// assert_eq!(answer.mode, "ask");
254/// ```
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256#[serde(rename_all = "camelCase")]
257pub struct SessionModeResponse {
258 /// The mode, as the harness names it: `read_only`, `plan`, `ask` or `auto`.
259 pub mode: String,
260}
261
262/// `POST /kernel/surface/records` body: one record of a surface engine attached to the
263/// kernel — an answer with the surface and how it was given, Stop all, Resume all, a mode
264/// change, a message sent — for the kernel's signed log (spec 3.3 §11).
265///
266/// The kernel writes it with the caller as its actor and the transport it came over as
267/// `transport`; whatever the record says of either is dropped.
268///
269/// # Example
270///
271/// ```rust
272/// use adk_core::audit_log::AuditRecordKind;
273/// use adk_kernel::control::SurfaceRecord;
274///
275/// let record = SurfaceRecord::new(AuditRecordKind::Governance, "surface.stop_all")
276/// .with_ext("surface", serde_json::json!("terminal"))
277/// .with_ext("origin", serde_json::json!({ "kind": "keyboard" }));
278/// assert_eq!(serde_json::to_value(&record).unwrap()["kind"], "governance");
279/// ```
280#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase")]
282#[non_exhaustive]
283pub struct SurfaceRecord {
284 /// What the record is about.
285 pub kind: AuditRecordKind,
286 /// The action: `surface.decide`, `surface.stop_all`, …
287 pub action: String,
288 /// The decision an answer's record carries.
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub decision: Option<AuditDecision>,
291 /// Its fields: the surface, how it was given, the decision's id, the outcome.
292 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
293 pub ext: BTreeMap<String, serde_json::Value>,
294}
295
296impl SurfaceRecord {
297 /// A record of `action`, of `kind`, with no fields yet.
298 pub fn new(kind: AuditRecordKind, action: impl Into<String>) -> Self {
299 Self { kind, action: action.into(), decision: None, ext: BTreeMap::new() }
300 }
301
302 /// Sets the decision.
303 #[must_use]
304 pub fn with_decision(mut self, decision: AuditDecision) -> Self {
305 self.decision = Some(decision);
306 self
307 }
308
309 /// Adds the field `key`.
310 #[must_use]
311 pub fn with_ext(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
312 self.ext.insert(key.into(), value);
313 self
314 }
315}
316
317/// The prefix of the actions a surface engine writes (spec 3.3 §11).
318const SURFACE_ACTIONS: &str = "surface.";
319
320/// The fields of a surface's record the kernel sets itself: who the caller is and how it came.
321const KERNEL_FIELDS: &[&str] = &["transport", "device", "deviceName", "presence"];
322
323/// What the harness gives the kernel so a surface attached to it runs the REPL's commands
324/// and answers "Always allow" (spec 3.3 §5.2, §7.2). A run's [`CommandCall`] names the
325/// caller; the host runs a command in that person's session only.
326///
327/// # Example
328///
329/// ```rust
330/// use adk_kernel::control::{CommandCall, CommandHost, CommandInfo};
331///
332/// struct Uptime;
333///
334/// #[async_trait::async_trait]
335/// impl CommandHost for Uptime {
336/// fn commands(&self) -> Vec<CommandInfo> {
337/// vec![CommandInfo::new("uptime", "How long the kernel has run")]
338/// }
339///
340/// fn changes(&self, _: &str, _: &str) -> bool {
341/// false
342/// }
343///
344/// async fn run(&self, call: &CommandCall) -> adk_kernel::Result<String> {
345/// let place = if call.reach.is_local() { "here" } else { "over HTTP" };
346/// Ok(format!("Up 3 hours; you called {place}"))
347/// }
348/// }
349/// ```
350#[async_trait]
351pub trait CommandHost: Send + Sync {
352 /// The commands, in `/help` order.
353 fn commands(&self) -> Vec<CommandInfo>;
354
355 /// Whether `/name args` changes something — a rule, the memory, the mode — rather than
356 /// reads: while everything is stopped, it is refused unless it
357 /// [`tightens`](Self::tightens).
358 fn changes(&self, name: &str, args: &str) -> bool;
359
360 /// Whether `call`, which changes something, only makes the agents do less — revokes a
361 /// rule, forgets a fact, turns the sandbox on, sets a stricter mode — so it runs while
362 /// everything is stopped, and a person can clean up before Resume all (spec 3.3 §5.2,
363 /// S-I10). By default nothing does, and every change is refused until Resume all.
364 ///
365 /// # Errors
366 ///
367 /// The host's error, such as a store it reads the session's mode from.
368 async fn tightens(&self, call: &CommandCall) -> Result<bool> {
369 let _ = call;
370 Ok(false)
371 }
372
373 /// The mode of `user`'s session `session`, as the harness names it (`read_only`,
374 /// `plan`, `ask`, `auto`); `None` when the host keeps no modes, and by default.
375 ///
376 /// # Errors
377 ///
378 /// The host's error.
379 async fn session_mode(&self, user: &str, session: &str) -> Result<Option<String>> {
380 let _ = (user, session);
381 Ok(None)
382 }
383
384 /// Runs `call`: `/name args` for its user in their session; returns what to show.
385 ///
386 /// # Errors
387 ///
388 /// A `NotFound` error for a command it does not offer, or the command's error.
389 async fn run(&self, call: &CommandCall) -> Result<String>;
390
391 /// The words of "Always allow" for the waiting decision `request`, when the harness can
392 /// make a standing rule of its call; `None` otherwise, and by default.
393 ///
394 /// # Errors
395 ///
396 /// The host's error.
397 async fn always_allow_offer(&self, request: &ApprovalRequest) -> Result<Option<String>> {
398 let _ = request;
399 Ok(None)
400 }
401
402 /// Makes the standing rule "Always allow" creates for the waiting decision `request`, as
403 /// `by`, and keeps it until [`grant_always_allow`](Self::grant_always_allow); returns its
404 /// words.
405 ///
406 /// # Errors
407 ///
408 /// An `InvalidInput` error when no standing rule applies to the call; by default, a
409 /// `Config` error.
410 async fn prepare_always_allow(
411 &self,
412 request: &ApprovalRequest,
413 by: &SubjectRef,
414 ) -> Result<String> {
415 let _ = (request, by);
416 Err(no_rules())
417 }
418
419 /// Grants the rule prepared for `request`, which was allowed.
420 ///
421 /// # Errors
422 ///
423 /// A `NotFound` error when no rule was prepared for it; by default, a `Config` error.
424 async fn grant_always_allow(&self, request: &ApprovalRequest) -> Result<()> {
425 let _ = request;
426 Err(no_rules())
427 }
428}
429
430fn no_rules() -> KernelError {
431 KernelError::Core(AdkError::new(
432 ErrorComponent::Server,
433 ErrorCategory::InvalidInput,
434 CONFIG_CODE,
435 "this kernel makes no standing rules from a decision: allow it once",
436 ))
437}
438
439type Backend = State<Arc<dyn ControlBackend>>;
440
441/// The routes, relative to `/api`, over the backend in their state.
442pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
443 Router::new()
444 .route(paths::COMMANDS, get(list))
445 .route(paths::COMMAND_RUN, post(run))
446 .route(paths::ALWAYS_ALLOW, get(offer))
447 .route(paths::ALWAYS_ALLOW_PREPARE, post(prepare))
448 .route(paths::ALWAYS_ALLOW_GRANT, post(grant))
449 .route(paths::SESSION_MODE, get(session_mode))
450 .route(paths::SURFACE_RECORDS, post(surface_record))
451}
452
453/// The command host of `backend`, or a `Config` error naming why there is none.
454fn host_of(backend: &dyn ControlBackend) -> Result<Arc<dyn CommandHost>> {
455 backend.kernel().and_then(|kernel| kernel.config().control.commands.clone()).ok_or_else(|| {
456 KernelError::Config {
457 reason: "this kernel offers no commands: set ControlPlaneConfig::with_commands, as \
458 `adk-rust up` does"
459 .into(),
460 }
461 })
462}
463
464async fn list(State(backend): Backend, caller: Caller) -> Result<Json<CommandsResponse>> {
465 require_owner(&caller, "use the REPL's commands")?;
466 Ok(Json(CommandsResponse { commands: host_of(backend.as_ref())?.commands() }))
467}
468
469async fn run(
470 State(backend): Backend,
471 caller: Caller,
472 peer: Option<Extension<PeerProcess>>,
473 Json(request): Json<RunCommandRequest>,
474) -> Result<Json<RunCommandResponse>> {
475 require_owner(&caller, "run the REPL's commands")?;
476 let host = host_of(backend.as_ref())?;
477 let RunCommandRequest { name, args, session_id } = request;
478 let args = args.trim().to_string();
479 if !host.commands().iter().any(|command| command.name == name) {
480 return Err(KernelError::Core(AdkError::new(
481 ErrorComponent::Server,
482 ErrorCategory::NotFound,
483 NOT_FOUND_CODE,
484 format!("no command /{name} on this kernel; /help lists them"),
485 )));
486 }
487 let changes = host.changes(&name, &args);
488 let mut reach = CommandReach::new(caller.transport);
489 if let Some(device) = caller.context.metadata.get(crate::pairing::DEVICE_ID_METADATA) {
490 reach = reach.with_device(device.clone());
491 }
492 if let Some(Extension(PeerProcess(pid))) = peer {
493 reach = reach.with_peer_pid(pid);
494 }
495 let recorded: String = args.chars().take(RECORDED_ARGS).collect();
496 let call = CommandCall::new(caller.context.user_id.clone(), &session_id, &name, args, reach);
497 // Stopped, the agents may still be made to do less: cleaning up never waits (S-I10).
498 let governance = backend.governance();
499 if changes && governance.is_frozen() && !host.tightens(&call).await? {
500 let reason = governance.reason().unwrap_or_default();
501 return Err(KernelError::Core(AdkError::new(
502 ErrorComponent::Server,
503 ErrorCategory::Conflict,
504 FROZEN_CODE,
505 format!(
506 "everything is stopped ({reason}), so /{name} cannot let the agents do more \
507 until you resume all; what makes them do less still runs"
508 ),
509 )));
510 }
511 let extra = [
512 ("session", json!(session_id)),
513 ("args", json!(recorded)),
514 ("changes", json!(changes)),
515 ("reach", json!(call.reach)),
516 ];
517 record(backend.as_ref(), &caller, "commands.run", Some(&name), &extra).await?;
518 let text = host.run(&call).await?;
519 Ok(Json(RunCommandResponse { text }))
520}
521
522/// The caller's decision `id`, from the kernel's approvals inbox (S-I8).
523async fn owned_request(
524 backend: &dyn ControlBackend,
525 caller: &Caller,
526 id: &str,
527) -> Result<ApprovalRequest> {
528 let approvals = backend.approvals().ok_or_else(|| KernelError::Config {
529 reason: "this kernel has no approvals inbox; start it with an approval service".into(),
530 })?;
531 approvals
532 .get(id)
533 .await?
534 .filter(|request| request.scope.user_id == caller.context.user_id)
535 .ok_or_else(|| {
536 KernelError::Core(AdkError::new(
537 ErrorComponent::Server,
538 ErrorCategory::NotFound,
539 NOT_FOUND_CODE,
540 format!("no decision {id} of yours"),
541 ))
542 })
543}
544
545/// The caller's waiting decision `id`.
546async fn waiting(
547 backend: &dyn ControlBackend,
548 caller: &Caller,
549 id: &str,
550) -> Result<ApprovalRequest> {
551 let request = owned_request(backend, caller, id).await?;
552 if request.state != ApprovalState::Pending {
553 return Err(KernelError::Core(AdkError::new(
554 ErrorComponent::Server,
555 ErrorCategory::Conflict,
556 INVALID_STATE_CODE,
557 format!("decision {id} is no longer waiting"),
558 )));
559 }
560 Ok(request)
561}
562
563/// Whether `request` is high risk, as it says or as the kernel rates its tool: "Always allow"
564/// is never offered for it, on any surface (spec 3.3 §7.2).
565fn high_risk(backend: &dyn ControlBackend, request: &ApprovalRequest) -> bool {
566 request.risk >= ApprovalRisk::High || super::pairing::rated_high(backend.kernel(), request)
567}
568
569/// The answer of a call no standing rule may be made of.
570fn no_rule_applies() -> KernelError {
571 KernelError::Core(AdkError::new(
572 ErrorComponent::Server,
573 ErrorCategory::NotFound,
574 NOT_FOUND_CODE,
575 "no standing rule applies to this call; allow it once",
576 ))
577}
578
579async fn offer(
580 State(backend): Backend,
581 caller: Caller,
582 UrlPath(id): UrlPath<String>,
583) -> Result<Json<AlwaysAllowResponse>> {
584 require_owner(&caller, "see what Always allow creates")?;
585 let host = host_of(backend.as_ref())?;
586 let request = waiting(backend.as_ref(), &caller, &id).await?;
587 if high_risk(backend.as_ref(), &request) {
588 return Err(no_rule_applies());
589 }
590 match host.always_allow_offer(&request).await? {
591 Some(label) => Ok(Json(AlwaysAllowResponse { label })),
592 None => Err(no_rule_applies()),
593 }
594}
595
596async fn prepare(
597 State(backend): Backend,
598 caller: Caller,
599 UrlPath(id): UrlPath<String>,
600) -> Result<Json<AlwaysAllowResponse>> {
601 require_owner(&caller, "create a standing rule")?;
602 let host = host_of(backend.as_ref())?;
603 let request = waiting(backend.as_ref(), &caller, &id).await?;
604 if high_risk(backend.as_ref(), &request) {
605 return Err(crate::pairing::forbidden(format!(
606 "decision {id} is high risk: no standing rule is ever made of it; allow it once"
607 )));
608 }
609 let label = host.prepare_always_allow(&request, &caller.subject()).await?;
610 Ok(Json(AlwaysAllowResponse { label }))
611}
612
613async fn grant(
614 State(backend): Backend,
615 caller: Caller,
616 UrlPath(id): UrlPath<String>,
617) -> Result<Json<serde_json::Value>> {
618 require_owner(&caller, "create a standing rule")?;
619 let host = host_of(backend.as_ref())?;
620 let request = owned_request(backend.as_ref(), &caller, &id).await?;
621 // The rule follows the caller's own yes, recorded first: an answer that lost, an edit, or
622 // someone else's yes grants nothing.
623 let own_yes = request.decisions.last().is_some_and(|decision| {
624 decision.kind == ApprovalAction::Approve && decision.approver.id == caller.context.user_id
625 });
626 if request.state != ApprovalState::Approved || !own_yes || high_risk(backend.as_ref(), &request)
627 {
628 return Err(KernelError::Core(AdkError::new(
629 ErrorComponent::Server,
630 ErrorCategory::Conflict,
631 INVALID_STATE_CODE,
632 format!("decision {id} was not allowed by your yes, so no rule is made from it"),
633 )));
634 }
635 record(backend.as_ref(), &caller, "rules.always_allow", Some(&id), &[]).await?;
636 host.grant_always_allow(&request).await?;
637 Ok(Json(json!({ "granted": id })))
638}
639
640async fn session_mode(
641 State(backend): Backend,
642 caller: Caller,
643 UrlPath(session): UrlPath<String>,
644) -> Result<Json<SessionModeResponse>> {
645 require_owner(&caller, "read a session's mode")?;
646 let host = host_of(backend.as_ref())?;
647 match host.session_mode(&caller.context.user_id, &session).await? {
648 Some(mode) => Ok(Json(SessionModeResponse { mode })),
649 None => Err(KernelError::Core(AdkError::new(
650 ErrorComponent::Server,
651 ErrorCategory::NotFound,
652 NOT_FOUND_CODE,
653 "this kernel keeps no mode for its sessions",
654 ))),
655 }
656}
657
658async fn surface_record(
659 State(backend): Backend,
660 caller: Caller,
661 Json(record): Json<SurfaceRecord>,
662) -> Result<Json<serde_json::Value>> {
663 require_owner(&caller, "write a surface's records")?;
664 let SurfaceRecord { kind, action, decision, ext } = record;
665 let kinds = [
666 AuditRecordKind::Approval,
667 AuditRecordKind::Governance,
668 AuditRecordKind::Configuration,
669 AuditRecordKind::Other("surface".into()),
670 ];
671 if !action.starts_with(SURFACE_ACTIONS) || !kinds.contains(&kind) {
672 return Err(KernelError::Core(AdkError::new(
673 ErrorComponent::Server,
674 ErrorCategory::InvalidInput,
675 CONFIG_CODE,
676 format!("only a surface's records (`surface.…`) are written here, not `{action}`"),
677 )));
678 }
679 // An answer is on record for the caller's own decision only (S-I8).
680 if let Some(id) = ext.get("approvalId") {
681 let id = id.as_str().unwrap_or_default();
682 owned_request(backend.as_ref(), &caller, id).await?;
683 }
684 let Some(trail) = backend.audit_trail() else {
685 return Ok(Json(json!({ "recorded": false })));
686 };
687 let mut draft =
688 AuditRecordDraft::new(kind, action).actor(AuditActor::subject(caller.subject()));
689 if let Some(decision) = decision {
690 draft = draft.decision(decision);
691 }
692 for (key, value) in ext {
693 if !KERNEL_FIELDS.contains(&key.as_str()) {
694 draft = draft.ext(key, value);
695 }
696 }
697 draft = draft.ext("transport", json!(caller.transport));
698 trail.record(draft).await?;
699 Ok(Json(json!({ "recorded": true })))
700}
701
702impl super::ControlClient {
703 /// `GET /kernel/commands`: the REPL's commands the kernel offers, in `/help` order (spec
704 /// 3.3 §5.2).
705 ///
706 /// # Errors
707 ///
708 /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
709 /// the kernel answered: `403` for a device token, `400` when the kernel offers none.
710 pub async fn commands(&self) -> Result<Vec<CommandInfo>> {
711 let answer: CommandsResponse =
712 self.call(Method::GET, paths::COMMANDS.to_string(), None::<&()>).await?;
713 Ok(answer.commands)
714 }
715
716 /// `POST /kernel/commands/run`: runs `/name args` in the caller's session `session`, by
717 /// the REPL's code on the kernel's harness; returns what it printed (spec 3.3 §5.2).
718 ///
719 /// # Errors
720 ///
721 /// As [`commands`](Self::commands), and `404` for a command the kernel does not offer,
722 /// `409` for one that changes something while everything is stopped, or the command's
723 /// error.
724 pub async fn run_command(&self, name: &str, args: &str, session: &str) -> Result<String> {
725 let body = RunCommandRequest {
726 name: name.to_string(),
727 args: args.to_string(),
728 session_id: session.to_string(),
729 };
730 let answer: RunCommandResponse =
731 self.call(Method::POST, paths::COMMAND_RUN.to_string(), Some(&body)).await?;
732 Ok(answer.text)
733 }
734
735 /// `GET /kernel/rules/always-allow/{id}`: the words of "Always allow" for the caller's
736 /// waiting decision `id`, or `None` when no standing rule applies (spec 3.3 §8.2).
737 ///
738 /// # Errors
739 ///
740 /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
741 /// the kernel answered: `403` for a device token, `409` for a decision no longer waiting.
742 pub async fn always_allow_offer(&self, id: &str) -> Result<Option<String>> {
743 let path = paths::ALWAYS_ALLOW.replace("{id}", &encode(id));
744 match self.call::<AlwaysAllowResponse>(Method::GET, path, None::<&()>).await {
745 Ok(answer) => Ok(Some(answer.label)),
746 Err(error) if error.category() == ErrorCategory::NotFound => Ok(None),
747 Err(error) => Err(error),
748 }
749 }
750
751 /// `POST /kernel/rules/always-allow/{id}/prepare`: makes the standing rule "Always
752 /// allow" creates for the waiting decision `id`, before it is answered; returns its
753 /// words (spec 3.3 §8.2).
754 ///
755 /// # Errors
756 ///
757 /// As [`always_allow_offer`](Self::always_allow_offer), and `400` when no rule applies.
758 pub async fn prepare_always_allow(&self, id: &str) -> Result<String> {
759 let path = paths::ALWAYS_ALLOW_PREPARE.replace("{id}", &encode(id));
760 let answer: AlwaysAllowResponse = self.call(Method::POST, path, Some(&())).await?;
761 Ok(answer.label)
762 }
763
764 /// `POST /kernel/rules/always-allow/{id}/grant`: grants the rule prepared for the
765 /// decision `id` once it was allowed (spec 3.3 §8.2).
766 ///
767 /// # Errors
768 ///
769 /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
770 /// the kernel answered: `403` for a device token, `409` for a decision not allowed,
771 /// `404` when no rule was prepared for it.
772 pub async fn grant_always_allow(&self, id: &str) -> Result<()> {
773 let path = paths::ALWAYS_ALLOW_GRANT.replace("{id}", &encode(id));
774 let _: serde_json::Value = self.call(Method::POST, path, Some(&())).await?;
775 Ok(())
776 }
777
778 /// `GET /kernel/sessions/{session}/mode`: the mode of the caller's session `session`, as
779 /// the harness names it, or `None` when the kernel keeps no modes (spec 3.3 §5.2).
780 ///
781 /// # Errors
782 ///
783 /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
784 /// the kernel answered: `403` for a device token, `400` when the kernel offers no
785 /// commands.
786 pub async fn session_mode(&self, session: &str) -> Result<Option<String>> {
787 let path = paths::SESSION_MODE.replace("{session}", &encode(session));
788 match self.call::<SessionModeResponse>(Method::GET, path, None::<&()>).await {
789 Ok(answer) => Ok(Some(answer.mode)),
790 Err(error) if error.category() == ErrorCategory::NotFound => Ok(None),
791 Err(error) => Err(error),
792 }
793 }
794
795 /// `POST /kernel/surface/records`: writes `record`, one record of a surface engine in this
796 /// process, on the kernel's signed log, with the caller as its actor (spec 3.3 §11).
797 ///
798 /// # Errors
799 ///
800 /// Returns [`KernelError::ControlPlane`] when the kernel cannot be reached, or the error
801 /// the kernel answered: `403` for a device token, `400` for an action that is not a
802 /// surface's, `404` for an answer to a decision that is not the caller's, or the log's
803 /// error.
804 pub async fn record_surface(&self, record: &SurfaceRecord) -> Result<()> {
805 let path = paths::SURFACE_RECORDS.to_string();
806 let _: serde_json::Value = self.call(Method::POST, path, Some(record)).await?;
807 Ok(())
808 }
809}