use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use super::secret_arguments::{SecretAnswers, SecretParameters, secret_arguments, without_secrets};
use super::workspace_invocations::{CANCEL, Origin, PROVIDER, RETRY, Spend, UNDO};
use super::{
ActionCallError, ActionProvider, Caller, CatalogueQuery, InvocationReceipt, InvocationState,
InvokeArgument, InvokeRequest, MAX_CATALOGUE_PAGE, Pending, ReceiptStatus, RemoteActionTarget,
ResourceWake, pending,
};
use crate::InvocationId;
pub type OriginWrites<'a> = dyn Fn(&Caller, &Origin) -> bool + 'a;
const KEPT: usize = 4096;
pub const NOT_KEPT: &str = "what it was asked with is not kept with its record: ask for it again";
pub const NO_HISTORY: &str = "the record it changed offers no history to take back";
fn given(mut state: InvocationState) -> InvocationState {
if let crate::InvocationUpdate::Succeeded { output, .. } = &mut state.update {
*output = crate::ActionOutput {
value: Some(serde_json::json!({ "given": true })),
resources: Vec::new(),
};
}
state
}
pub type Route = (Arc<dyn ActionProvider + Send + Sync>, Caller);
#[derive(Clone)]
pub struct Recorded {
pub caller: Caller,
pub asked: Caller,
pub request: InvokeRequest,
pub sealed: Vec<String>,
pub workspace: Option<String>,
pub started_ms: u64,
pub ended_ms: Option<u64>,
pub state: Option<InvocationState>,
pub changes: u64,
pub waiting: bool,
pub origin: Option<Origin>,
pub retries: Option<InvocationId>,
pub spend: Option<Spend>,
pub undone: bool,
pub secret: bool,
route: Route,
}
#[derive(Default)]
pub struct Invocations {
kept: Mutex<Kept>,
secrets: std::sync::OnceLock<SecretParameters>,
answers: std::sync::OnceLock<SecretAnswers>,
}
#[derive(Default)]
struct Kept {
by_id: HashMap<InvocationId, Recorded>,
order: VecDeque<InvocationId>,
watching: Vec<(String, ResourceWake)>,
}
impl Invocations {
fn kept(&self) -> std::sync::MutexGuard<'_, Kept> {
self.kept.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn keep_no_secrets(&self, secrets: SecretParameters) {
let _ = self.secrets.set(secrets);
}
pub fn keep_secret_answers(&self, answers: SecretAnswers) {
let _ = self.answers.set(answers);
}
fn journaled(&self, request: &InvokeRequest) -> (InvokeRequest, Vec<String>) {
let names = self.secrets.get().map_or_else(Vec::new, |secrets| {
secret_arguments(request, secrets(&request.target))
});
let (mut kept, taken) = without_secrets(request, &names);
let mut sealed: Vec<String> = taken.keys().cloned().collect();
if super::person_vault::calls_by_address(request, super::person_vault::ADD)
&& let Some(secrets) = self.secrets.get()
&& let InvokeArgument::Json(arguments) = &mut kept.argument
&& let Some(serde_json::Value::Object(inner)) = arguments.get_mut("arguments")
{
let add = super::person_vault::target(super::person_vault::ADD);
let names = secrets(&add).unwrap_or_else(|| inner.keys().cloned().collect());
for name in names {
if inner.remove(&name).is_some() {
sealed.push(format!("arguments.{name}"));
}
}
}
(kept, sealed)
}
pub fn record(
&self,
caller: &Caller,
asked: &Caller,
request: &InvokeRequest,
workspace: Option<&str>,
route: Route,
) {
self.recorded(caller, asked, request, workspace, route, None);
}
fn recorded(
&self,
caller: &Caller,
asked: &Caller,
request: &InvokeRequest,
workspace: Option<&str>,
route: Route,
retries: Option<InvocationId>,
) {
let id = request.invocation;
let secret = self.answers_a_secret(request);
let (mut journaled, sealed) = self.journaled(request);
if secret {
journaled.argument = InvokeArgument::None;
}
let recorded = Recorded {
caller: caller.clone(),
asked: asked.clone(),
request: journaled,
sealed,
workspace: workspace.map(str::to_owned),
started_ms: tilo_clock::unix_now_ms(),
ended_ms: None,
state: None,
changes: 0,
waiting: false,
origin: origin_of(caller, request),
retries,
spend: None,
undone: false,
secret,
route,
};
let mut kept = self.kept();
if let Some(known) = kept.by_id.get_mut(&id) {
known.route = recorded.route;
return;
}
kept.by_id.insert(id, recorded);
kept.order.push_back(id);
while kept.order.len() > KEPT {
if let Some(oldest) = kept.order.pop_front() {
kept.by_id.remove(&oldest);
}
}
let woken: Vec<ResourceWake> = match workspace {
Some(workspace) => {
let (woken, still) = std::mem::take(&mut kept.watching)
.into_iter()
.partition(|(watched, _)| watched == workspace);
kept.watching = still;
woken.into_iter().map(|(_, wake)| wake).collect()
}
None => Vec::new(),
};
drop(kept);
for wake in woken {
wake.wake();
}
}
fn answers_a_secret(&self, request: &InvokeRequest) -> bool {
self.answers.get().map_or_else(
|| super::person_vault::answers_secret(request),
|answers| answers(request),
)
}
pub fn watch(&self, workspace: &str, wake: &ResourceWake) {
let going: Vec<(InvocationId, Route)> = {
let mut kept = self.kept();
kept.watching.retain(|(_, waiting)| waiting.waiting());
kept.watching.push((workspace.to_owned(), wake.clone()));
kept.by_id
.iter()
.filter(|(_, recorded)| {
recorded.workspace.as_deref() == Some(workspace) && recorded.ended_ms.is_none()
})
.map(|(id, recorded)| (*id, recorded.route.clone()))
.collect()
};
for (id, (provider, runs_as)) in going {
if let Some(changed) = provider.next_change(&runs_as, &id) {
let wake = wake.clone();
changed.then(move |_| wake.wake());
}
}
}
#[must_use]
pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<Recorded> {
self.kept()
.by_id
.get(id)
.filter(|recorded| caller.continues(&recorded.caller))
.cloned()
}
#[must_use]
pub fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
self.get(caller, id)?;
self.refreshed(id)?.state
}
#[must_use]
pub fn listed(&self, workspace: &str) -> Vec<Recorded> {
let ids: Vec<InvocationId> = {
let kept = self.kept();
kept.order
.iter()
.filter(|id| {
kept.by_id
.get(id)
.is_some_and(|recorded| recorded.workspace.as_deref() == Some(workspace))
})
.copied()
.collect()
};
ids.iter().filter_map(|id| self.refreshed(id)).collect()
}
pub fn note_spend(&self, id: &InvocationId, spend: Spend) {
if let Some(recorded) = self.kept().by_id.get_mut(id) {
recorded.spend = Some(spend);
}
}
pub fn drop_secret_answers(&self) {
let answers = self.answers.get();
let mut kept = self.kept();
for recorded in kept.by_id.values_mut() {
let secret = recorded.secret
|| answers.is_some_and(|answers| answers(&recorded.request))
|| super::person_vault::answers_secret(&recorded.request);
if secret {
recorded.secret = true;
recorded.request.argument = InvokeArgument::None;
recorded.state = recorded.state.take().map(given);
}
}
}
pub fn keep_secret(&self, id: &InvocationId) {
if let Some(recorded) = self.kept().by_id.get_mut(id) {
recorded.secret = true;
recorded.request.argument = InvokeArgument::None;
recorded.state = recorded.state.take().map(given);
}
}
pub fn note_waiting(&self, id: &InvocationId) {
if let Some(recorded) = self.kept().by_id.get_mut(id) {
recorded.waiting = true;
}
}
fn refreshed(&self, id: &InvocationId) -> Option<Recorded> {
let (provider, runs_as) = self.kept().by_id.get(id)?.route.clone();
let state = provider.observe(&runs_as, id);
let ended = state
.as_ref()
.is_some_and(|state| state.update.is_terminal());
let mut kept = self.kept();
let recorded = kept.by_id.get_mut(id)?;
if recorded.state.as_ref() != state.as_ref() {
recorded.changes = recorded.changes.saturating_add(1);
}
if ended && recorded.ended_ms.is_none() {
recorded.ended_ms = Some(tilo_clock::unix_now_ms());
}
recorded.state = if recorded.secret {
state.map(given)
} else {
state
};
let recorded = recorded.clone();
drop(kept);
Some(recorded)
}
#[must_use]
pub fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
let (provider, runs_as) = self.get(caller, id)?.route;
provider.next_change(&runs_as, id)
}
#[must_use]
pub fn answer(
self: &Arc<Self>,
caller: &Caller,
request: &InvokeRequest,
may_write_origin: &OriginWrites<'_>,
) -> Option<Pending<Result<InvocationReceipt, ActionCallError>>> {
let target = &request.target;
let action = target.address.action.as_str();
if target.provider != PROVIDER || ![CANCEL, RETRY, UNDO].contains(&action) {
return None;
}
let Some(id) = uuid::Uuid::parse_str(&target.address.resource)
.ok()
.map(InvocationId)
else {
return Some(Pending::ready(Err(ActionCallError::UnknownInvocation)));
};
let Some(recorded) = self.find(&id) else {
return Some(Pending::ready(Err(ActionCallError::UnknownInvocation)));
};
if !Self::may_manage(caller, &recorded, may_write_origin) {
let verb = match action {
RETRY => "run it again",
UNDO => "take it back",
_ => "stop it",
};
return Some(Pending::ready(Err(refused(verb, recorded.origin.as_ref()))));
}
if action == RETRY {
return Some(Self::retry(self, &recorded, request.invocation));
}
if action == UNDO {
let asked = request.invocation;
let taken = Self::take_back_recorded(self, &recorded);
let (complete, answer) = pending();
taken.then(move |done| {
complete.complete(match done {
Some(Ok(())) => Ok(InvocationReceipt {
invocation: asked,
status: ReceiptStatus::Completed {
output: crate::ActionOutput::default(),
},
}),
Some(Err(error)) => Err(error),
None => Err(ActionCallError::Unavailable {
reason: "the record did not answer".into(),
}),
});
});
return Some(answer);
}
let (provider, runs_as) = recorded.route;
let invocation = request.invocation;
Some(provider.cancel(&runs_as, &id).map(move |stopped| {
stopped.map(|()| InvocationReceipt {
invocation,
status: ReceiptStatus::Completed {
output: crate::ActionOutput::default(),
},
})
}))
}
fn take_back_recorded(
records: &Arc<Self>,
recorded: &Recorded,
) -> Pending<Result<(), ActionCallError>> {
if recorded.undone {
return Pending::ready(Err(already_taken_back()));
}
let id = recorded.request.invocation;
let at = recorded.request.target.provider.clone();
let run = id.0.to_string();
let (complete, answer) = pending();
let records = Arc::clone(records);
take_back_run(&recorded.route, &at, None, &run, None).then(move |done| {
let result = match done {
None => Err(ActionCallError::Unavailable {
reason: "the record did not answer".into(),
}),
Some(Err(error)) => Err(error),
Some(Ok(())) => {
records.mark_undone(&id);
Ok(())
}
};
complete.complete(result);
});
answer
}
fn mark_undone(&self, id: &InvocationId) {
if let Some(recorded) = self.kept().by_id.get_mut(id) {
recorded.undone = true;
}
}
fn retry(
records: &Arc<Self>,
recorded: &Recorded,
asked: InvocationId,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
if recorded.request.signed.is_some() {
return Pending::ready(Err(ActionCallError::Refused {
reason: "it was asked for from another device: run it again from there".to_owned(),
}));
}
if !recorded.sealed.is_empty() {
return Pending::ready(Err(ActionCallError::Refused {
reason: NOT_KEPT.to_owned(),
}));
}
let original = recorded.request.invocation;
let mut request = recorded.request.clone();
request.invocation = InvocationId::new();
let fresh = request.invocation;
records.recorded(
&recorded.caller,
&recorded.asked,
&request,
recorded.workspace.as_deref(),
recorded.route.clone(),
Some(original),
);
let (provider, runs_as) = recorded.route.clone();
let waiting = Arc::clone(records);
provider.invoke(&runs_as, request).map(move |result| {
if result
.as_ref()
.err()
.is_some_and(ActionCallError::awaits_person)
{
waiting.note_waiting(&fresh);
}
result.map(|_| InvocationReceipt {
invocation: asked,
status: ReceiptStatus::Completed {
output: crate::ActionOutput {
value: Some(serde_json::json!({
"invocation": fresh.0.to_string(),
"address": format!("{PROVIDER}/{}", fresh.0),
"retries": original.0.to_string(),
})),
..crate::ActionOutput::default()
},
},
})
})
}
fn find(&self, id: &InvocationId) -> Option<Recorded> {
self.kept().by_id.get(id).cloned()
}
fn may_manage(
caller: &Caller,
recorded: &Recorded,
may_write_origin: &OriginWrites<'_>,
) -> bool {
caller.continues(&recorded.caller)
|| agent_person_is(caller, &recorded.caller)
|| recorded
.origin
.as_ref()
.is_some_and(|origin| may_write_origin(caller, origin))
}
#[must_use]
pub fn stop_agent(
&self,
caller: &Caller,
workspace: &str,
agent: &tilo_action_policy::MemberId,
may_write_origin: &OriginWrites<'_>,
) -> Vec<Pending<Result<(), ActionCallError>>> {
let ids: Vec<InvocationId> = {
let kept = self.kept();
kept.order
.iter()
.filter_map(|id| {
let recorded = kept.by_id.get(id)?;
if recorded.workspace.as_deref() != Some(workspace)
|| recorded.ended_ms.is_some()
|| recorded.caller.acting().member_id() != Some(agent)
{
return None;
}
Some(*id)
})
.collect()
};
ids.into_iter()
.filter_map(|id| self.cancel(caller, &id, may_write_origin))
.collect()
}
#[must_use]
pub fn cancel(
&self,
caller: &Caller,
id: &InvocationId,
may_write_origin: &OriginWrites<'_>,
) -> Option<Pending<Result<(), ActionCallError>>> {
let recorded = self.find(id)?;
if !Self::may_manage(caller, &recorded, may_write_origin) {
return Some(Pending::ready(Err(refused(
"stop it",
recorded.origin.as_ref(),
))));
}
let (provider, runs_as) = recorded.route;
Some(provider.cancel(&runs_as, id))
}
}
pub fn take_back_run(
route: &Route,
at: &str,
root: Option<&str>,
run: &str,
step: Option<&str>,
) -> Pending<Result<(), ActionCallError>> {
let (provider, runs_as) = route.clone();
let query = CatalogueQuery {
provider: Some(at.to_owned()),
needle: UNDO.to_owned(),
max_results: MAX_CATALOGUE_PAGE,
..CatalogueQuery::default()
};
let run = run.to_owned();
let step = step.map(str::to_owned);
let root = root.map(str::to_owned);
let (complete, answer) = pending();
provider.query(&runs_as, query).then(move |page| {
let found = match page {
None => Err(ActionCallError::Unavailable {
reason: "the record did not answer".into(),
}),
Some(Err(error)) => Err(error),
Some(Ok(page)) => {
undo_action(&page.rows, root.as_deref()).ok_or_else(|| ActionCallError::Refused {
reason: NO_HISTORY.to_owned(),
})
}
};
let (token, address) = match found {
Ok(found) => found,
Err(error) => {
complete.complete(Err(error));
return;
}
};
let mut arguments = serde_json::Map::new();
arguments.insert("invocation".to_owned(), serde_json::Value::String(run));
if let Some(step) = step {
arguments.insert("step".to_owned(), serde_json::Value::String(step));
}
let request = InvokeRequest {
invocation: InvocationId::new(),
target: RemoteActionTarget {
provider: token,
address,
},
argument: InvokeArgument::Json(arguments),
context: None,
confirmation: None,
revision: None,
on_behalf_of: None,
wait_ms: None,
appearance: None,
signed: None,
};
provider.invoke(&runs_as, request).then(move |answered| {
complete.complete(match answered {
None => Err(ActionCallError::Unavailable {
reason: "the record did not answer".into(),
}),
Some(Ok(receipt)) => taken(receipt.status),
Some(Err(error)) => Err(error),
});
});
});
answer
}
fn undo_action(
rows: &[super::CatalogueRow],
root: Option<&str>,
) -> Option<(String, crate::ActionAddress)> {
let mut fallback = None;
for row in rows {
let Some(action) = &row.action else {
continue;
};
if action.address.action != UNDO {
continue;
}
if root.is_some_and(|root| !action.address.resource.starts_with(root)) {
continue;
}
if action.params.iter().any(|param| param.name == "invocation") {
return Some((row.provider.clone(), action.address.clone()));
}
fallback.get_or_insert_with(|| (row.provider.clone(), action.address.clone()));
}
fallback
}
fn taken(status: ReceiptStatus) -> Result<(), ActionCallError> {
match status {
ReceiptStatus::Completed { .. } => Ok(()),
ReceiptStatus::Failed { error } => Err(ActionCallError::Refused {
reason: error.message,
}),
ReceiptStatus::Rejected { error } => Err(error),
ReceiptStatus::Cancelled { .. } => Err(ActionCallError::Refused {
reason: "taking it back was stopped".into(),
}),
ReceiptStatus::Accepted => Err(ActionCallError::Unavailable {
reason: "taking it back is still running".into(),
}),
}
}
fn already_taken_back() -> ActionCallError {
ActionCallError::Refused {
reason: "what this invocation changed is already taken back".into(),
}
}
fn origin_of(caller: &Caller, request: &InvokeRequest) -> Option<Origin> {
if let InvokeArgument::Json(arguments) = &request.argument
&& let Some(from) = arguments
.get(crate::params::FROM_ARGUMENT)
.and_then(crate::params::MadeFrom::from_json)
&& let Some(origin) = Origin::parse(&from.resource, Some(&from.kind))
{
return Some(origin);
}
caller
.turn()
.and_then(|turn| Origin::parse(&turn.conversation, None))
}
fn agent_person_is(caller: &Caller, owner: &Caller) -> bool {
let Some(person) = owner.acting_for_person() else {
return false;
};
let acting = caller.acting();
acting.person_id() == Some(person)
&& !acting.is_agent()
&& !acting.is_bot()
&& acting.app().is_none()
}
fn refused(verb: &str, origin: Option<&Origin>) -> ActionCallError {
let may = match origin {
Some(origin) => format!(
"the caller who made this invocation, the person its agent works for, or someone \
who may write {} may",
origin.address()
),
None => {
"the caller who made this invocation, or the person its agent works for, may".to_owned()
}
};
ActionCallError::Refused {
reason: format!("only {may} {verb}"),
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
use crate::remote::{
CataloguePage, CatalogueQuery, InvokeArgument, PendingPoll, RemoteActionTarget,
};
use crate::{ActionOutput, InvocationUpdate};
#[derive(Default)]
struct Runs {
stopped: AtomicBool,
written: Mutex<Vec<(String, String)>>,
}
impl Runs {
fn writes(&self, id: &InvocationId) -> Vec<String> {
self.written
.lock()
.unwrap()
.iter()
.filter(|(of, _)| of == &id.0.to_string())
.map(|(_, what)| what.clone())
.collect()
}
}
impl ActionProvider for Runs {
fn query(
&self,
_: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
let mut page = CataloguePage::default();
if query.provider.as_deref() == Some("terminal") {
page.rows.push(super::super::CatalogueRow::for_action(
"terminal",
"terminal",
crate::ActionDescriptor {
address: crate::ActionAddress::new("tl:terminal:", UNDO),
semantic_identity: None,
resource_kind: "terminal".into(),
resource_label: "Terminal".into(),
action_label: "Undo".into(),
keywords: Vec::new(),
did: None,
icon: None,
description: None,
state: crate::ActionState::default(),
locus: crate::ExecutionLocus::ClientLocal,
kind: crate::OperationKind::Effect,
contract: crate::ActionContract::default(),
input: crate::InputSpec::None,
params: vec![crate::ActionParam::optional(
"invocation",
crate::ParamType::Text,
"The invocation whose changes are taken back.",
)],
view: None,
},
));
}
Pending::ready(Ok(page))
}
fn invoke(
&self,
_: &Caller,
request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
if request.target.address.action != UNDO {
return Pending::ready(Err(ActionCallError::UnknownAction));
}
let InvokeArgument::Json(arguments) = &request.argument else {
return Pending::ready(Err(ActionCallError::InvalidRequest {
reason: "the undo names no invocation".into(),
}));
};
let named = arguments
.get("invocation")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
self.written.lock().unwrap().retain(|(of, _)| of != named);
Pending::ready(Ok(InvocationReceipt {
invocation: request.invocation,
status: ReceiptStatus::Completed {
output: ActionOutput::default(),
},
}))
}
fn observe(&self, _: &Caller, id: &InvocationId) -> Option<InvocationState> {
let update = if self.stopped.load(Ordering::SeqCst) {
InvocationUpdate::Succeeded {
invocation: *id,
output: ActionOutput::default(),
}
} else {
InvocationUpdate::Accepted { invocation: *id }
};
Some(InvocationState::new(*id, update))
}
fn cancel(&self, _: &Caller, _: &InvocationId) -> Pending<Result<(), ActionCallError>> {
self.stopped.store(true, Ordering::SeqCst);
Pending::ready(Ok(()))
}
}
fn request() -> InvokeRequest {
InvokeRequest {
invocation: InvocationId::new(),
target: RemoteActionTarget {
provider: "terminal".into(),
address: crate::ActionAddress::new("terminal", "run"),
},
argument: InvokeArgument::Text("make".into()),
context: None,
confirmation: None,
revision: None,
on_behalf_of: None,
wait_ms: None,
appearance: None,
signed: None,
}
}
fn record_action(id: &InvocationId, action: &str) -> InvokeRequest {
let mut request = request();
request.invocation = InvocationId::new();
request.target = RemoteActionTarget {
provider: PROVIDER.into(),
address: crate::ActionAddress::new(id.0.to_string(), action),
};
request.argument = InvokeArgument::None;
request
}
fn made(runs: &Runs, id: &InvocationId, first: &str, second: &str) {
let mut written = runs.written.lock().unwrap();
written.push((id.0.to_string(), first.to_owned()));
written.push((id.0.to_string(), second.to_owned()));
}
fn answered(
invocations: &Arc<Invocations>,
caller: &Caller,
request: &InvokeRequest,
never: &OriginWrites<'_>,
) -> Result<InvocationReceipt, ActionCallError> {
invocations
.answer(caller, request, never)
.expect("the record answers its own action")
.poll_ready()
.ready()
}
trait Ready<T> {
fn ready(self) -> T;
}
impl<T: std::fmt::Debug> Ready<T> for PendingPoll<T> {
fn ready(self) -> T {
match self {
PendingPoll::Ready(value) => value,
other => panic!("the answer was ready, not {other:?}"),
}
}
}
#[test]
fn a_call_is_recorded_without_what_its_action_declares_secret() {
let invocations = Arc::new(Invocations::default());
let params = [
crate::ActionParam::required("kind", crate::ParamType::Text, "kind"),
crate::ActionParam::required("title", crate::ParamType::Text, "title"),
crate::ActionParam::required("secret", crate::ParamType::Secret, "secret"),
crate::ActionParam::optional("notes", crate::ParamType::Secret, "notes"),
crate::ActionParam::optional("fields", crate::ParamType::Secret, "fields"),
];
let target = super::super::person_vault::target(super::super::person_vault::ADD);
let described = target.clone();
invocations.keep_no_secrets(Arc::new(move |asked: &RemoteActionTarget| {
if asked.provider == crate::remote::ACTIONS_PROVIDER {
return Some(Vec::new());
}
(*asked == described)
.then(|| super::super::secret_arguments::secret_parameters(¶ms))
}));
let asked = Caller::local_person("ada").in_new_execution();
let mut request = request();
request.target = target;
let serde_json::Value::Object(arguments) = serde_json::json!({
"kind": "login",
"belongsTo": ["https://bank.example"],
"title": "Bank",
"secret": "made-up-password-0451",
"notes": "made-up-recovery-words",
"fields": [{"label": "PIN", "value": "made-up-pin-7351"}],
}) else {
unreachable!("an object");
};
let mut called = request.clone();
called.invocation = InvocationId::new();
called.target = RemoteActionTarget {
provider: crate::remote::ACTIONS_PROVIDER.to_owned(),
address: crate::ActionAddress::new("actions", "call"),
};
let mut by_address = serde_json::Map::new();
by_address.insert("address".into(), "tilo.vault/vault#add".into());
by_address.insert("arguments".into(), arguments.clone().into());
called.argument = InvokeArgument::Json(by_address);
request.argument = InvokeArgument::Json(arguments);
let runs = Arc::new(Runs::default());
invocations.record(&asked, &asked, &request, Some("w1"), (runs, asked.clone()));
let runs = Arc::new(Runs::default());
invocations.record(&asked, &asked, &called, Some("w1"), (runs, asked.clone()));
let kept = invocations.get(&asked, &request.invocation).unwrap();
let kept_call = invocations.get(&asked, &called.invocation).unwrap();
let written = serde_json::to_string(&kept.request).unwrap()
+ &serde_json::to_string(&kept_call.request).unwrap()
+ &invocations
.listed("w1")
.iter()
.map(|listed| serde_json::to_string(&listed.request).unwrap())
.collect::<String>();
for secret in [
"made-up-password-0451",
"made-up-recovery-words",
"made-up-pin-7351",
] {
assert!(!written.contains(secret), "{written}");
}
assert!(written.contains("https://bank.example"), "{written}");
assert!(written.contains("Bank"), "{written}");
}
#[test]
fn a_call_of_an_undescribed_action_is_recorded_without_its_arguments() {
let invocations = Arc::new(Invocations::default());
invocations.keep_no_secrets(Arc::new(|_: &RemoteActionTarget| None));
let asked = Caller::local_person("ada").in_new_execution();
let mut request = request();
request.argument = InvokeArgument::Text("made-up-passphrase-3317".into());
let id = request.invocation;
let runs = Arc::new(Runs::default());
invocations.record(&asked, &asked, &request, Some("w1"), (runs, asked.clone()));
let kept = invocations.get(&asked, &id).unwrap();
assert_eq!(kept.request.argument, InvokeArgument::None);
assert_eq!(kept.sealed, [super::super::secret_arguments::TEXT_ARGUMENT]);
let listed = invocations
.listed("w1")
.iter()
.map(|listed| serde_json::to_string(&listed.request).unwrap())
.collect::<String>();
assert!(!listed.contains("made-up-passphrase-3317"), "{listed}");
let never = |_: &Caller, _: &Origin| false;
match answered(&invocations, &asked, &record_action(&id, RETRY), &never) {
Err(ActionCallError::Refused { reason }) => assert_eq!(reason, NOT_KEPT),
other => panic!("run again without what it was asked with: {other:?}"),
}
}
#[test]
fn a_vault_reveal_is_recorded_as_answering_a_secret() {
use super::super::{person_accounts, person_vault};
let invocations = Arc::new(Invocations::default());
let asked = Caller::local_person("ada").in_new_execution();
let mut reveal = request();
reveal.target = person_vault::target(person_vault::REVEAL);
let mut credential = request();
credential.target = person_accounts::target(person_accounts::CLOUD_CREDENTIAL);
let serde_json::Value::Object(signing_in) = serde_json::json!({
"account": "files-1",
}) else {
unreachable!("an object");
};
credential.argument = InvokeArgument::Json(signing_in);
let mut called = request();
called.target = RemoteActionTarget {
provider: "tilo.actions".to_owned(),
address: crate::ActionAddress::new("actions", "call"),
};
let serde_json::Value::Object(arguments) = serde_json::json!({
"address": "tilo.workspace/workspace.permissions:w1/vault#reveal",
"arguments": {"item": "vault.item:00"},
}) else {
unreachable!("an object");
};
called.argument = InvokeArgument::Json(arguments);
let mut called_credential = called.clone();
called_credential.invocation = InvocationId::new();
let serde_json::Value::Object(signing_in_call) = serde_json::json!({
"address": "tilo.accounts/accounts#cloud-credential",
"arguments": {"account": "files-1"},
}) else {
unreachable!("an object");
};
called_credential.argument = InvokeArgument::Json(signing_in_call);
let mut listed = called.clone();
listed.invocation = InvocationId::new();
let serde_json::Value::Object(listing) = serde_json::json!({
"address": "tilo.workspace/workspace.permissions:w1/vault#list",
}) else {
unreachable!("an object");
};
listed.argument = InvokeArgument::Json(listing);
for (request, secret) in [
(&reveal, true),
(&credential, true),
(&called, true),
(&called_credential, true),
(&listed, false),
] {
assert_eq!(person_vault::answers_secret(request), secret);
let runs = Arc::new(Runs::default());
invocations.record(&asked, &asked, request, Some("w1"), (runs, asked.clone()));
let kept = invocations.get(&asked, &request.invocation).unwrap();
assert_eq!(kept.secret, secret, "{:?}", request.target);
if secret {
assert_eq!(
kept.request.argument,
InvokeArgument::None,
"{:?} keeps none of what it was asked with",
request.target
);
}
}
}
#[test]
fn an_invocation_takes_back_the_writes_its_run_made() {
let invocations = Arc::new(Invocations::default());
let never = |_: &Caller, _: &Origin| false;
let asked = Caller::local_person("ada").in_new_execution();
let request = request();
let id = request.invocation;
let runs = Arc::new(Runs::default());
invocations.record(
&asked,
&asked,
&request,
Some("w1"),
(runs.clone(), asked.clone()),
);
made(&runs, &id, "Shipping notes.", " Sent.");
assert_eq!(runs.writes(&id).len(), 2, "the run made two writes");
let undone = answered(&invocations, &asked, &record_action(&id, UNDO), &never)
.expect("its caller takes it back");
assert!(matches!(undone.status, ReceiptStatus::Completed { .. }));
assert!(
runs.writes(&id).is_empty(),
"both writes the run made are taken back"
);
assert!(
invocations.get(&asked, &id).unwrap().undone,
"the record says what it changed was taken back"
);
}
#[test]
fn someone_who_may_not_manage_the_run_is_refused_in_words() {
let invocations = Arc::new(Invocations::default());
let never = |_: &Caller, _: &Origin| false;
let asked = Caller::local_person("ada").in_new_execution();
let request = request();
let id = request.invocation;
let runs = Arc::new(Runs::default());
invocations.record(
&asked,
&asked,
&request,
Some("w1"),
(runs.clone(), asked.clone()),
);
made(&runs, &id, "Shipping notes.", " Sent.");
let stranger = Caller::local_person("bob").in_new_execution();
let refused = answered(&invocations, &stranger, &record_action(&id, UNDO), &never)
.expect_err("a stranger is refused");
let ActionCallError::Refused { reason } = &refused else {
panic!("a stranger is refused in words, not {refused:?}");
};
assert!(
reason.starts_with("only the caller who made this invocation"),
"{reason}"
);
assert!(
reason.ends_with("take it back"),
"the refusal names what they may not do: {reason}"
);
assert_eq!(runs.writes(&id).len(), 2, "nothing was taken back");
}
#[test]
fn taking_an_invocation_back_twice_is_refused_in_words() {
let invocations = Arc::new(Invocations::default());
let never = |_: &Caller, _: &Origin| false;
let asked = Caller::local_person("ada").in_new_execution();
let request = request();
let id = request.invocation;
let runs = Arc::new(Runs::default());
invocations.record(
&asked,
&asked,
&request,
Some("w1"),
(runs.clone(), asked.clone()),
);
made(&runs, &id, "Shipping notes.", " Sent.");
answered(&invocations, &asked, &record_action(&id, UNDO), &never)
.expect("the first takes it back");
let refused = answered(&invocations, &asked, &record_action(&id, UNDO), &never)
.expect_err("the second is refused");
let ActionCallError::Refused { reason } = &refused else {
panic!("a second undo is a refusal in words, not {refused:?}");
};
assert_eq!(
reason, "what this invocation changed is already taken back",
"a person reads what stands"
);
}
#[test]
fn an_invocations_person_takes_back_a_run_of_its_agents() {
let invocations = Arc::new(Invocations::default());
let never = |_: &Caller, _: &Origin| false;
let agent = Caller::local_agent("scout", "ada");
let request = request();
let id = request.invocation;
let runs = Arc::new(Runs::default());
invocations.record(
&agent,
&agent,
&request,
Some("w1"),
(runs.clone(), agent.clone()),
);
made(&runs, &id, "Shipping notes.", " Sent.");
let person = Caller::local_person("ada").in_new_execution();
answered(&invocations, &person, &record_action(&id, UNDO), &never)
.expect("the person the agent works for takes it back");
assert!(
runs.writes(&id).is_empty(),
"both of the agent's writes went"
);
}
#[test]
fn an_invocation_is_followed_and_stopped_where_it_was_handed_on_to() {
let invocations = Arc::new(Invocations::default());
let never = |_: &Caller, _: &Origin| false;
let asked = Caller::local_person("ada").in_new_execution();
let request = request();
let id = request.invocation;
let here: Arc<Runs> = Arc::default();
invocations.record(&asked, &asked, &request, Some("w1"), (here, asked.clone()));
let there: Arc<Runs> = Arc::default();
let runs_as = Caller::local_agent("host", "ada");
invocations.record(
&asked,
&asked,
&request,
Some("w1"),
(Arc::clone(&there) as _, runs_as),
);
let running = invocations
.observe(&asked, &id)
.expect("its caller follows it");
assert!(!running.update.is_terminal());
for stranger in [
Caller::local_person("bob"),
asked.clone().in_new_execution(),
] {
assert!(invocations.observe(&stranger, &id).is_none());
assert!(matches!(
invocations
.cancel(&stranger, &id, &never)
.expect("the device knows it")
.poll_ready(),
PendingPoll::Ready(Err(ActionCallError::Refused { .. }))
));
}
let stopped = invocations
.cancel(&asked, &id, &never)
.expect("its caller stops it");
let mut stopped = std::pin::pin!(stopped);
let answered = std::future::Future::poll(
stopped.as_mut(),
&mut std::task::Context::from_waker(std::task::Waker::noop()),
);
assert_eq!(answered, std::task::Poll::Ready(Some(Ok(()))));
assert!(
there.stopped.load(Ordering::SeqCst),
"stopped where it runs"
);
let ended = invocations.observe(&asked, &id).unwrap();
assert!(ended.update.is_terminal());
let recorded = invocations.get(&asked, &id).unwrap();
assert_eq!(recorded.workspace.as_deref(), Some("w1"));
assert_eq!(recorded.caller, asked, "who asked stays who asked");
assert!(recorded.ended_ms.is_some());
assert_eq!(recorded.changes, 2);
let mut get = request.clone();
get.invocation = InvocationId::new();
get.target = RemoteActionTarget {
provider: PROVIDER.into(),
address: crate::ActionAddress::new(id.0.to_string(), "get"),
};
assert!(
invocations.answer(&asked, &request, &never).is_none(),
"not one of its actions"
);
assert!(
invocations.answer(&asked, &get, &never).is_none(),
"a record is no action's to read"
);
invocations.note_spend(
&id,
Spend {
provider: Some("Models".into()),
model: Some("judge-small".into()),
input_tokens: 3,
output_tokens: 2,
cost_micros: 4321,
},
);
let spent = invocations.get(&asked, &id).unwrap().spend.unwrap();
assert_eq!(spent.cost_micros, 4321);
}
}