use std::sync::Arc;
use adk_core::principal::SubjectRef;
use async_trait::async_trait;
use axum::Json;
use axum::Router;
use axum::extract::{Path as UrlPath, Query, State};
use axum::routing::{get, post};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::paths;
use super::routes::{Caller, ControlBackend, record};
use super::settings::require_owner;
use crate::error::{KernelError, Result};
use crate::partition::PartitionId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum FactOrigin {
YouSaidThis,
YouConfirmedThis,
Guess,
}
impl FactOrigin {
pub fn label(self) -> &'static str {
match self {
Self::YouSaidThis | Self::YouConfirmedThis => "You said this",
Self::Guess => "A guess",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RememberedFact {
pub id: String,
pub text: String,
pub origin: FactOrigin,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub area: Option<PartitionId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub noticed_by: Option<String>,
pub learned_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tidy_up: Option<String>,
}
impl RememberedFact {
pub fn new(
id: impl Into<String>,
text: impl Into<String>,
origin: FactOrigin,
learned_at: DateTime<Utc>,
) -> Self {
Self {
id: id.into(),
text: text.into(),
origin,
kind: None,
area: None,
noticed_by: None,
learned_at,
tidy_up: None,
}
}
#[must_use]
pub fn with_kind(mut self, kind: impl Into<String>) -> Self {
self.kind = Some(kind.into());
self
}
#[must_use]
pub fn with_area(mut self, area: impl Into<PartitionId>) -> Self {
self.area = Some(area.into());
self
}
#[must_use]
pub fn with_noticed_by(mut self, agent: impl Into<String>) -> Self {
self.noticed_by = Some(agent.into());
self
}
#[must_use]
pub fn with_tidy_up(mut self, tick: impl Into<String>) -> Self {
self.tidy_up = Some(tick.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct TidyUp {
pub id: String,
pub area: PartitionId,
pub at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub finished_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub undone_at: Option<DateTime<Utc>>,
pub merged: usize,
pub superseded: usize,
pub forgotten: usize,
pub distilled: usize,
}
impl TidyUp {
pub fn new(id: impl Into<String>, area: impl Into<PartitionId>, at: DateTime<Utc>) -> Self {
Self {
id: id.into(),
area: area.into(),
at,
finished_at: None,
undone_at: None,
merged: 0,
superseded: 0,
forgotten: 0,
distilled: 0,
}
}
#[must_use]
pub fn with_counts(
mut self,
merged: usize,
superseded: usize,
forgotten: usize,
distilled: usize,
) -> Self {
(self.merged, self.superseded, self.forgotten, self.distilled) =
(merged, superseded, forgotten, distilled);
self
}
#[must_use]
pub fn finished(mut self, at: DateTime<Utc>) -> Self {
self.finished_at = Some(at);
self
}
#[must_use]
pub fn undone(mut self, at: DateTime<Utc>) -> Self {
self.undone_at = Some(at);
self
}
pub fn undoable(&self) -> bool {
self.finished_at.is_some()
&& self.undone_at.is_none()
&& self.merged + self.superseded + self.forgotten + self.distilled > 0
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct TidyUpUndo {
pub id: String,
pub restored: Vec<String>,
pub forgotten: Vec<String>,
pub kept: Vec<String>,
}
impl TidyUpUndo {
pub fn new(
id: impl Into<String>,
restored: Vec<String>,
forgotten: Vec<String>,
kept: Vec<String>,
) -> Self {
Self { id: id.into(), restored, forgotten, kept }
}
}
#[async_trait]
pub trait MemoryBook: Send + Sync {
async fn facts(&self, user: &str, area: Option<&PartitionId>) -> Result<Vec<RememberedFact>>;
async fn confirm(&self, user: &str, id: &str, by: &SubjectRef) -> Result<RememberedFact>;
async fn fix(
&self,
user: &str,
id: &str,
text: &str,
by: &SubjectRef,
) -> Result<RememberedFact>;
async fn forget(&self, user: &str, id: &str, by: &SubjectRef) -> Result<()>;
async fn tidy_ups(&self, user: &str) -> Result<Vec<TidyUp>>;
async fn undo_tidy_up(&self, user: &str, id: &str, by: &SubjectRef) -> Result<TidyUpUndo>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryQuery {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub area: Option<PartitionId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryResponse {
pub facts: Vec<RememberedFact>,
pub tidy_ups: Vec<TidyUp>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FactResponse {
pub fact: RememberedFact,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FixRequest {
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ForgetResponse {
pub forgotten: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UndoRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tidy_up: Option<String>,
}
type Backend = State<Arc<dyn ControlBackend>>;
pub(super) fn routes() -> Router<Arc<dyn ControlBackend>> {
Router::new()
.route(paths::MEMORY, get(list))
.route(paths::FACT_CONFIRM, post(confirm))
.route(paths::FACT_FIX, post(fix))
.route(paths::FACT_FORGET, post(forget))
.route(paths::MEMORY_UNDO, post(undo))
}
fn book_of(backend: &dyn ControlBackend) -> Result<Arc<dyn MemoryBook>> {
backend.kernel().and_then(|kernel| kernel.config().control.memory.clone()).ok_or_else(|| {
KernelError::Config {
reason: "this kernel shows no memory: set ControlPlaneConfig::with_memory, as \
`adk-rust up` does with long-term memory on"
.into(),
}
})
}
async fn list(
State(backend): Backend,
caller: Caller,
Query(query): Query<MemoryQuery>,
) -> Result<Json<MemoryResponse>> {
caller.require_operator("read what the agents remember")?;
let book = book_of(backend.as_ref())?;
let user = &caller.context.user_id;
let facts = book.facts(user, query.area.as_ref()).await?;
let tidy_ups = book.tidy_ups(user).await?;
Ok(Json(MemoryResponse { facts, tidy_ups }))
}
async fn confirm(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<FactResponse>> {
require_owner(&caller, "confirm what the agents remember")?;
let book = book_of(backend.as_ref())?;
record(backend.as_ref(), &caller, "memory.confirm", Some(&id), &[]).await?;
let fact = book.confirm(&caller.context.user_id, &id, &caller.subject()).await?;
Ok(Json(FactResponse { fact }))
}
async fn fix(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
Json(request): Json<FixRequest>,
) -> Result<Json<FactResponse>> {
require_owner(&caller, "fix what the agents remember")?;
let book = book_of(backend.as_ref())?;
record(backend.as_ref(), &caller, "memory.fix", Some(&id), &[]).await?;
let fact = book.fix(&caller.context.user_id, &id, &request.text, &caller.subject()).await?;
Ok(Json(FactResponse { fact }))
}
async fn forget(
State(backend): Backend,
caller: Caller,
UrlPath(id): UrlPath<String>,
) -> Result<Json<ForgetResponse>> {
require_owner(&caller, "make the agents forget")?;
let book = book_of(backend.as_ref())?;
record(backend.as_ref(), &caller, "memory.forget", Some(&id), &[]).await?;
book.forget(&caller.context.user_id, &id, &caller.subject()).await?;
Ok(Json(ForgetResponse { forgotten: id }))
}
async fn undo(
State(backend): Backend,
caller: Caller,
Json(request): Json<UndoRequest>,
) -> Result<Json<TidyUpUndo>> {
require_owner(&caller, "undo a tidy-up of the memory")?;
let book = book_of(backend.as_ref())?;
let user = &caller.context.user_id;
let id = match request.tidy_up {
Some(id) => id,
None => book
.tidy_ups(user)
.await?
.into_iter()
.find(TidyUp::undoable)
.map(|tidy_up| tidy_up.id)
.ok_or_else(|| {
KernelError::Core(adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::NotFound,
crate::error::NOT_FOUND_CODE,
"no overnight tidy-up of the memory is left to undo",
))
})?,
};
record(backend.as_ref(), &caller, "memory.undo", Some(&id), &[]).await?;
Ok(Json(book.undo_tidy_up(user, &id, &caller.subject()).await?))
}