Skip to main content

adk_kernel/control/
api.rs

1//! Wire types of the control plane (spec 3.2 §7.11). Every payload is `camelCase`.
2
3use std::collections::BTreeMap;
4
5use adk_core::{
6    ApprovalAction, ApprovalScope, ApprovalState, Event, RunState, ToolConfirmationRequest,
7};
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12pub use super::pairing::{
13    AcceptChannelRequest, ChannelAccountResponse, ChannelAccountState, ChannelAccountView,
14    ChannelAccountsResponse, ChannelPairingResponse, ChannelPairingView, ClaimRequest,
15    DeviceResponse, DevicesResponse, IssueRequest,
16};
17// The routes the surfaces need (spec 3.3 §10 K3–K5).
18pub use super::agents::AgentsResponse;
19#[cfg(feature = "proc")]
20pub use super::away::{
21    AwayCounts, AwayKind, AwayLine, AwayLineResponse, AwayQuery, AwayResponse, DEFAULT_VIEWER,
22    MAX_PAGE_ROWS, QuietTimeReport, SeenRequest, SeenResponse,
23};
24pub use super::memory::{
25    FactResponse, FixRequest, ForgetResponse, MemoryQuery, MemoryResponse, UndoRequest,
26};
27pub use super::record::{RecordQuery, RecordResponse};
28pub use super::settings::{
29    AreaResponse, AreaView, QuietTimeRequest, SettingsResponse, SpendingLimitRequest,
30};
31
32use crate::agenda::{AgendaFilter, AgendaItem, AgendaStateKind};
33use crate::partition::PartitionId;
34use crate::process::{Process, ProcessKind};
35use crate::sched::QueueClass;
36use crate::stores::ProcessFilter;
37use crate::wake::WakeSet;
38
39/// `GET /kernel/processes` query: `adk-rust ps [--partition P] [--state S]` (spec 3.2 §8.1).
40///
41/// # Example
42///
43/// ```rust
44/// use adk_core::RunState;
45/// use adk_kernel::control::api::ProcessesQuery;
46///
47/// let query = ProcessesQuery { state: Some(RunState::Waiting), ..ProcessesQuery::default() };
48/// assert_eq!(query.to_filter().states, vec![RunState::Waiting]);
49/// ```
50#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52pub struct ProcessesQuery {
53    /// Only processes in this partition.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub partition: Option<PartitionId>,
56    /// Only processes in this state.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub state: Option<RunState>,
59    /// At most this many processes.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub limit: Option<usize>,
62}
63
64impl ProcessesQuery {
65    /// The [`ProcessFilter`] the query selects.
66    pub fn to_filter(&self) -> ProcessFilter {
67        let mut filter = ProcessFilter::default();
68        if let Some(partition) = &self.partition {
69            filter = filter.partition(partition.clone());
70        }
71        if let Some(state) = self.state {
72            filter = filter.states([state]);
73        }
74        if let Some(limit) = self.limit {
75            filter = filter.limit(limit);
76        }
77        filter
78    }
79}
80
81/// `GET /kernel/processes` answer.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct ProcessesResponse {
85    /// The processes, each with its live view.
86    pub processes: Vec<Process>,
87}
88
89/// The answer of a process action: the process after it.
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[serde(rename_all = "camelCase")]
92pub struct ProcessResponse {
93    /// The process.
94    pub process: Process,
95}
96
97/// `POST /kernel/processes/{pid}/kill` body.
98#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct KillRequest {
101    /// Why, recorded on the run and in the audit record.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub reason: Option<String>,
104}
105
106/// `POST /kernel/processes/{pid}/nice` body.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase")]
109pub struct NiceRequest {
110    /// The queue class to move the process to.
111    pub queue: QueueClass,
112}
113
114/// `POST /kernel/freeze` body.
115#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase")]
117pub struct FreezeRequest {
118    /// The freeze reason.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub reason: Option<String>,
121}
122
123/// `POST /kernel/freeze` and `POST /kernel/unfreeze` answer.
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase")]
126pub struct FreezeResponse {
127    /// Whether execution is frozen after the call.
128    pub frozen: bool,
129    /// The freeze reason.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub reason: Option<String>,
132    /// Running processes the freeze parked, on this replica.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub parked_runs: Option<usize>,
135    /// Why the freeze's `kernel.control` record could not be written; the freeze took effect
136    /// regardless, since the kill switch never waits on the audit log.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub audit_error: Option<String>,
139}
140
141/// `GET /kernel/events` query. The `Last-Event-ID` header, when present, takes precedence.
142#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase")]
144pub struct EventsQuery {
145    /// Replay events after this cursor before the live ones.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub after: Option<u64>,
148}
149
150/// `POST /kernel/attach/{session}` body.
151#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub struct AttachRequest {
154    /// The session's user; defaults to the caller.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub user_id: Option<String>,
157    /// Only transcript events after this time: the cursor of an earlier attach.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub after: Option<DateTime<Utc>>,
160}
161
162/// `POST /kernel/attach/{session}` answer: transcript cursor, pending holds, process
163/// (spec 3.2 §7.11).
164#[derive(Debug, Clone, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct AttachResponse {
167    /// The session.
168    pub session_id: String,
169    /// The transcript since the request's cursor.
170    pub transcript: Vec<Event>,
171    /// The cursor to attach from next time: the last transcript event's time.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub cursor: Option<DateTime<Utc>>,
174    /// Calls the session holds for approval.
175    #[serde(default)]
176    pub pending: Vec<ToolConfirmationRequest>,
177    /// The process running the session, when one does.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub process: Option<Process>,
180}
181
182/// `POST /kernel/processes` body: a process to start (spec 3.2 §7.3, §7.11), run as the
183/// authenticated caller.
184///
185/// The run's user is always the caller; a body naming one, or any other unknown field, is
186/// refused with `422`. A wake set starts the process asleep (`adk-rust wake`).
187///
188/// # Example
189///
190/// ```rust
191/// use adk_kernel::control::api::SpawnRequest;
192///
193/// let request = SpawnRequest::new("adk-rust", serde_json::json!({ "text": "run the tests" }))
194///     .with_session_id("s-1");
195/// let json = serde_json::to_value(&request).unwrap();
196/// assert_eq!(json["sessionId"], "s-1");
197/// assert!(serde_json::from_value::<SpawnRequest>(serde_json::json!({
198///     "target": "adk-rust",
199///     "userId": "someone-else",
200/// }))
201/// .is_err());
202/// ```
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase", deny_unknown_fields)]
205pub struct SpawnRequest {
206    /// A target registered on the kernel, such as `adk-rust` or `harness.goal`.
207    pub target: String,
208    /// The run's input: a string, `{"text": ...}` or `{"content": ...}` for an agent.
209    #[serde(default)]
210    pub input: Value,
211    /// The session an agent run continues; defaults to a new one.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub session_id: Option<String>,
214    /// The queue class; defaults to interactive.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub queue: Option<QueueClass>,
217    /// What kind of work it is; defaults to interactive.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub kind: Option<ProcessKind>,
220    /// The process that caused it.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub parent: Option<String>,
223    /// Starts the process asleep on this wake set.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub wake: Option<WakeSet>,
226    /// Free-form labels.
227    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
228    pub labels: BTreeMap<String, String>,
229}
230
231impl SpawnRequest {
232    /// A process of `target` with `input`, interactive, in a new session.
233    pub fn new(target: impl Into<String>, input: Value) -> Self {
234        Self {
235            target: target.into(),
236            input,
237            session_id: None,
238            queue: None,
239            kind: None,
240            parent: None,
241            wake: None,
242            labels: BTreeMap::new(),
243        }
244    }
245
246    /// Continues `session_id`.
247    #[must_use]
248    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
249        self.session_id = Some(session_id.into());
250        self
251    }
252
253    /// Runs on `queue`.
254    #[must_use]
255    pub fn with_queue(mut self, queue: QueueClass) -> Self {
256        self.queue = Some(queue);
257        self
258    }
259
260    /// Records the process as `kind`.
261    #[must_use]
262    pub fn with_kind(mut self, kind: ProcessKind) -> Self {
263        self.kind = Some(kind);
264        self
265    }
266
267    /// Starts the process asleep on `wake`.
268    #[must_use]
269    pub fn with_wake(mut self, wake: WakeSet) -> Self {
270        self.wake = Some(wake);
271        self
272    }
273}
274
275/// `POST /kernel/processes/{pid}/run-now` and `POST /kernel/triggers/{name}/run-now` body:
276/// an optional request id, so a retried request queues one run now
277/// ([`Kernel::run_now`](crate::Kernel::run_now)).
278///
279/// # Example
280///
281/// ```rust
282/// use adk_kernel::control::api::RunNowRequest;
283///
284/// let request = RunNowRequest::default().with_request_id("r-1");
285/// assert_eq!(serde_json::to_value(&request).unwrap()["requestId"], "r-1");
286/// ```
287#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase", deny_unknown_fields)]
289#[non_exhaustive]
290pub struct RunNowRequest {
291    /// The request's id; generated when absent.
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub request_id: Option<String>,
294}
295
296impl RunNowRequest {
297    /// Sets the request id a retry repeats.
298    #[must_use]
299    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
300        self.request_id = Some(request_id.into());
301        self
302    }
303}
304
305/// `POST /kernel/sessions/{session}/steer` body: a message for the running turn of the
306/// caller's session (spec 3.3 §6 "steer"). The message is always the caller's own; any other
307/// field is refused with `422`.
308///
309/// # Example
310///
311/// ```rust
312/// use adk_kernel::control::api::SteerRequest;
313///
314/// let request = SteerRequest::new("use the staging database");
315/// assert_eq!(serde_json::to_value(&request).unwrap()["text"], "use the staging database");
316/// ```
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase", deny_unknown_fields)]
319pub struct SteerRequest {
320    /// The message.
321    pub text: String,
322}
323
324impl SteerRequest {
325    /// A request to send `text`.
326    pub fn new(text: impl Into<String>) -> Self {
327        Self { text: text.into() }
328    }
329}
330
331/// `POST /kernel/sessions/{session}/steer` answer (spec 3.3 §6 "steer").
332///
333/// The kernel answers once the running turn holds the message, not once the turn takes it.
334/// An accepted message is delivered when the session holds an event whose steering marker
335/// carries `steerId`, and handed back when the claim `leaseEpoch` of process `pid` ends
336/// without one.
337///
338/// # Example
339///
340/// ```rust
341/// use adk_kernel::control::api::SteerResponse;
342///
343/// let answer: SteerResponse = serde_json::from_value(serde_json::json!({
344///     "outcome": "accepted",
345///     "steerId": "steer-1",
346///     "pid": "run-7",
347///     "leaseEpoch": 2,
348/// }))
349/// .unwrap();
350/// assert!(matches!(answer, SteerResponse::Accepted { lease_epoch: 2, .. }));
351/// assert_eq!(serde_json::to_value(SteerResponse::Returned).unwrap()["outcome"], "returned");
352/// ```
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(tag = "outcome", rename_all = "camelCase")]
355pub enum SteerResponse {
356    /// The running turn holds the message for its agent's next safe point.
357    #[serde(rename_all = "camelCase")]
358    Accepted {
359        /// The id the message's session event carries once the turn takes it.
360        steer_id: String,
361        /// The process that holds the message.
362        pid: String,
363        /// The lease epoch of the claim that holds it.
364        lease_epoch: u64,
365    },
366    /// No turn of the session takes messages on this replica: send it as the session's next
367    /// message.
368    Returned,
369}
370
371/// A held call waiting in the approvals inbox, as `GET /api/approvals` shows it to an
372/// approver: without the call's fingerprint, which holds its unredacted arguments.
373#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
374#[serde(rename_all = "camelCase")]
375pub struct ApprovalItem {
376    /// The request id `decide` takes.
377    pub id: String,
378    /// The session the call was held in.
379    pub scope: ApprovalScope,
380    /// The tool called.
381    pub tool_name: String,
382    /// The arguments, redacted.
383    pub args_redacted: Value,
384    /// A one-line description.
385    #[serde(default)]
386    pub summary: String,
387    /// The version `decide` must name.
388    pub version: u64,
389    /// Where the request is.
390    pub state: ApprovalState,
391    /// What an approver may do.
392    #[serde(default)]
393    pub allowed_actions: Vec<ApprovalAction>,
394    /// The durable run parked on the call, when one is.
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub run_id: Option<String>,
397    /// When the call was held.
398    pub created_at: DateTime<Utc>,
399    /// When the request expires.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub expires_at: Option<DateTime<Utc>>,
402}
403
404/// `GET /kernel/agenda` query: `adk-rust agenda list` (spec 3.2 §7.11, §8.1).
405///
406/// # Example
407///
408/// ```rust
409/// use adk_kernel::AgendaStateKind;
410/// use adk_kernel::control::api::AgendaQuery;
411///
412/// let query = AgendaQuery { state: Some(AgendaStateKind::Proposed), ..AgendaQuery::default() };
413/// assert_eq!(query.to_filter().states, vec![AgendaStateKind::Proposed]);
414///
415/// // The newest twenty, then the twenty before them (spec 3.3 §5.1).
416/// let newest = AgendaQuery { newest_first: true, limit: Some(20), ..AgendaQuery::default() };
417/// let next = AgendaQuery { after: Some("item-41".into()), ..newest.clone() };
418/// assert_eq!(serde_json::to_value(&next).unwrap()["newestFirst"], true);
419/// ```
420#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
421#[serde(rename_all = "camelCase")]
422pub struct AgendaQuery {
423    /// Only items of this partition.
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub partition: Option<PartitionId>,
426    /// Only items in this state.
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub state: Option<AgendaStateKind>,
429    /// At most this many items.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub limit: Option<usize>,
432    /// Newest first instead of oldest first, so a surface reads the newest items without
433    /// paging through every older one (spec 3.3 §5.1).
434    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
435    pub newest_first: bool,
436    /// Only the items after this one in the order asked: the last item of the page before.
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub after: Option<String>,
439}
440
441impl AgendaQuery {
442    /// The [`AgendaFilter`] the query selects.
443    pub fn to_filter(&self) -> AgendaFilter {
444        let mut filter = AgendaFilter::default();
445        if let Some(partition) = &self.partition {
446            filter = filter.partition(partition.clone());
447        }
448        if let Some(state) = self.state {
449            filter = filter.states([state]);
450        }
451        if let Some(limit) = self.limit {
452            filter = filter.limit(limit);
453        }
454        filter
455    }
456}
457
458/// `GET /kernel/agenda` answer.
459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461pub struct AgendaResponse {
462    /// The items, oldest first, or newest first when asked.
463    pub items: Vec<AgendaItem>,
464}
465
466/// The answer of an agenda action: the item after it.
467#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
468#[serde(rename_all = "camelCase")]
469pub struct AgendaItemResponse {
470    /// The item.
471    pub item: AgendaItem,
472}
473
474/// `POST /kernel/agenda/{id}/reject` body.
475#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(rename_all = "camelCase")]
477pub struct RejectRequest {
478    /// Why, recorded on the event and in the audit record.
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub reason: Option<String>,
481}
482
483/// `POST /kernel/agenda/{id}/schedule` body: `adk-rust agenda schedule ID --at|--cron`.
484///
485/// # Example
486///
487/// ```rust
488/// use adk_kernel::{Wake, WakeSet};
489/// use adk_kernel::control::api::ScheduleRequest;
490///
491/// let request = ScheduleRequest { wake: WakeSet::any_of([Wake::At(chrono::Utc::now())]) };
492/// assert!(serde_json::to_value(&request).unwrap()["wake"]["anyOf"].is_array());
493/// ```
494#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
495#[serde(rename_all = "camelCase")]
496pub struct ScheduleRequest {
497    /// The wake set the item's process sleeps on.
498    pub wake: WakeSet,
499}
500
501/// `GET /kernel/drivers` answer (spec 3.2 §7.7, §7.11).
502#[cfg(feature = "drivers")]
503#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
504#[serde(rename_all = "camelCase")]
505pub struct DriversResponse {
506    /// The mounted drivers, ordered by id.
507    pub drivers: Vec<crate::drivers::DriverView>,
508}
509
510/// `POST /kernel/drivers/{id}/mount` body (spec 3.2 §7.7).
511///
512/// Without `confirm` the kernel answers what the mount would approve and mounts nothing;
513/// with it, the caller approves that and the driver is mounted.
514///
515/// # Example
516///
517/// ```rust
518/// use adk_kernel::control::api::MountDriverRequest;
519///
520/// let request = MountDriverRequest::new("id = \"fs\"\ncommand = \"mcp-fs\"\n").confirmed();
521/// assert!(request.confirm);
522/// ```
523#[cfg(feature = "drivers")]
524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
525#[serde(rename_all = "camelCase", deny_unknown_fields)]
526pub struct MountDriverRequest {
527    /// The manifest, as its TOML file holds it.
528    pub manifest: String,
529    /// Whether the caller approves the mount.
530    #[serde(default)]
531    pub confirm: bool,
532}
533
534#[cfg(feature = "drivers")]
535impl MountDriverRequest {
536    /// A request to see what mounting `manifest` approves.
537    pub fn new(manifest: impl Into<String>) -> Self {
538        Self { manifest: manifest.into(), confirm: false }
539    }
540
541    /// The same request, approving the mount.
542    #[must_use]
543    pub fn confirmed(mut self) -> Self {
544        self.confirm = true;
545        self
546    }
547}
548
549/// `POST /kernel/drivers/{id}/mount` answer.
550#[cfg(feature = "drivers")]
551#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
552#[serde(rename_all = "camelCase")]
553pub struct MountDriverResponse {
554    /// What the mount approves: the command line, the partitions, the effect classes.
555    pub proposal: crate::drivers::DriverProposal,
556    /// The mounted driver, when the request confirmed.
557    #[serde(default, skip_serializing_if = "Option::is_none")]
558    pub mounted: Option<crate::drivers::DriverView>,
559}
560
561/// `POST /kernel/drivers/{id}/{restart,reapprove}` answer.
562#[cfg(feature = "drivers")]
563#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
564#[serde(rename_all = "camelCase")]
565pub struct DriverResponse {
566    /// The driver after the action.
567    pub driver: crate::drivers::DriverView,
568}
569
570/// `POST /kernel/drivers/{id}/unmount` answer.
571#[cfg(feature = "drivers")]
572#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
573#[serde(rename_all = "camelCase")]
574pub struct UnmountDriverResponse {
575    /// Whether a driver of that id was mounted.
576    pub unmounted: bool,
577}
578
579/// How `GET /kernel/proc/ledger` answers (spec 3.2 §7.10, §7.11).
580///
581/// # Example
582///
583/// ```rust
584/// use adk_kernel::control::api::LedgerFormat;
585///
586/// assert_eq!(serde_json::to_value(LedgerFormat::Jsonl).unwrap(), "jsonl");
587/// ```
588#[cfg(feature = "proc")]
589#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(rename_all = "camelCase")]
591pub enum LedgerFormat {
592    /// A [`LedgerResponse`] page.
593    #[default]
594    Json,
595    /// One row per line, the JSONL `cargo adk eval --ledger` reads
596    /// (`application/x-ndjson`); the next page's cursor is the `x-ledger-next` header.
597    Jsonl,
598}
599
600/// `GET /kernel/proc/ledger` query: `adk-rust proc ledger` (spec 3.2 §7.10, §7.11, §8.1).
601///
602/// `limit` defaults to [`LedgerParams::DEFAULT_LIMIT`] and is capped at
603/// [`LedgerParams::MAX_LIMIT`]; page on with `after` set to the last row's `seq`.
604///
605/// # Example
606///
607/// ```rust
608/// use adk_kernel::control::api::LedgerParams;
609///
610/// let params = LedgerParams { kind: Some("tool_call,intent".into()), after: Some(40), ..LedgerParams::default() };
611/// let query = params.to_query();
612/// assert_eq!(query.kinds, ["tool_call", "intent"]);
613/// assert_eq!(query.limit, Some(LedgerParams::DEFAULT_LIMIT));
614/// ```
615#[cfg(feature = "proc")]
616#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(rename_all = "camelCase")]
618pub struct LedgerParams {
619    /// Only rows of this partition.
620    #[serde(default, skip_serializing_if = "Option::is_none")]
621    pub partition: Option<PartitionId>,
622    /// Only rows of these kinds, comma-separated.
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub kind: Option<String>,
625    /// Only rows of this agent.
626    #[serde(default, skip_serializing_if = "Option::is_none")]
627    pub agent: Option<String>,
628    /// Only rows at or after this instant.
629    #[serde(default, skip_serializing_if = "Option::is_none")]
630    pub from: Option<DateTime<Utc>>,
631    /// Only rows before this instant.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub to: Option<DateTime<Utc>>,
634    /// Only rows after this sequence number.
635    #[serde(default, skip_serializing_if = "Option::is_none")]
636    pub after: Option<u64>,
637    /// At most this many rows.
638    #[serde(default, skip_serializing_if = "Option::is_none")]
639    pub limit: Option<usize>,
640    /// JSON page or JSONL.
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub format: Option<LedgerFormat>,
643}
644
645#[cfg(feature = "proc")]
646impl LedgerParams {
647    /// Rows a page holds when the query names no limit.
648    pub const DEFAULT_LIMIT: usize = 500;
649    /// Most rows one page holds.
650    pub const MAX_LIMIT: usize = 5_000;
651
652    /// The store query the parameters select.
653    pub fn to_query(&self) -> crate::proc::LedgerQuery {
654        let mut query = crate::proc::LedgerQuery::default()
655            .limit(self.limit.unwrap_or(Self::DEFAULT_LIMIT).clamp(1, Self::MAX_LIMIT));
656        if let Some(partition) = &self.partition {
657            query = query.partition(partition.clone());
658        }
659        for kind in self.kind.iter().flat_map(|kinds| kinds.split(',')) {
660            let kind = kind.trim();
661            if !kind.is_empty() {
662                query = query.kind(kind);
663            }
664        }
665        if let Some(agent) = &self.agent {
666            query = query.agent(agent.clone());
667        }
668        if let Some(from) = self.from {
669            query = query.from(from);
670        }
671        if let Some(to) = self.to {
672            query = query.to(to);
673        }
674        if let Some(after) = self.after {
675            query = query.after(after);
676        }
677        query
678    }
679}
680
681/// `GET /kernel/proc/ledger` answer.
682#[cfg(feature = "proc")]
683#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
684#[serde(rename_all = "camelCase")]
685pub struct LedgerResponse {
686    /// The rows, in sequence order.
687    pub entries: Vec<crate::proc::LedgerEntry>,
688    /// The cursor of the next page, when this one is full.
689    #[serde(default, skip_serializing_if = "Option::is_none")]
690    pub next: Option<u64>,
691}
692
693/// `GET /kernel/proc/baselines` answer: each partition's last pass (spec 3.2 §7.10).
694#[cfg(feature = "proc")]
695#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
696#[serde(rename_all = "camelCase")]
697pub struct BaselinesResponse {
698    /// One state per partition the pass has tested, by partition; its `baselines` holds
699    /// every dimension's baseline and deviation test on `lastDay`.
700    pub partitions: Vec<crate::proc::PassState>,
701}
702
703/// `GET /kernel/proc/observations` query (spec 3.2 §7.10, §7.11).
704///
705/// # Example
706///
707/// ```rust
708/// use adk_kernel::control::api::ObservationsParams;
709///
710/// let params = ObservationsParams { limit: Some(3), ..ObservationsParams::default() };
711/// assert_eq!(params.to_query().limit, Some(3));
712/// ```
713#[cfg(feature = "proc")]
714#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
715#[serde(rename_all = "camelCase")]
716pub struct ObservationsParams {
717    /// Only observations of this partition.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub partition: Option<PartitionId>,
720    /// Only observations of this day or later.
721    #[serde(default, skip_serializing_if = "Option::is_none")]
722    pub since: Option<chrono::NaiveDate>,
723    /// At most this many.
724    #[serde(default, skip_serializing_if = "Option::is_none")]
725    pub limit: Option<usize>,
726}
727
728#[cfg(feature = "proc")]
729impl ObservationsParams {
730    /// The store query the parameters select.
731    pub fn to_query(&self) -> crate::proc::ObservationQuery {
732        let mut query = crate::proc::ObservationQuery::default();
733        if let Some(partition) = &self.partition {
734            query = query.partition(partition.clone());
735        }
736        if let Some(since) = self.since {
737            query = query.since(since);
738        }
739        if let Some(limit) = self.limit {
740            query = query.limit(limit);
741        }
742        query
743    }
744}
745
746/// `GET /kernel/proc/observations` answer.
747#[cfg(feature = "proc")]
748#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
749#[serde(rename_all = "camelCase")]
750pub struct ObservationsResponse {
751    /// The observations, newest day first.
752    pub observations: Vec<crate::proc::Observation>,
753}
754
755/// `GET /kernel/partitions` answer (spec 3.2 §7.8, §7.11).
756#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
757#[serde(rename_all = "camelCase")]
758pub struct PartitionsResponse {
759    /// Every partition, ordered by id.
760    pub partitions: Vec<crate::partition::Partition>,
761}
762
763/// `POST /kernel/partitions` and `POST /kernel/partitions/{id}/mode` answer: the partition
764/// after the change (spec 3.2 §7.8).
765#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
766#[serde(rename_all = "camelCase")]
767pub struct PartitionResponse {
768    /// The partition.
769    pub partition: crate::partition::Partition,
770}
771
772/// `POST /kernel/partitions/{id}/mode` body (spec 3.2 §8.1 `partitions set-mode`).
773#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
774#[serde(rename_all = "camelCase")]
775pub struct PartitionModeRequest {
776    /// The partition's new mode.
777    pub mode: crate::partition::PartitionMode,
778}