use serde::{Deserialize, Serialize};
use crate::api::ActionAddress;
pub const PROVIDER: &str = "tilo.invocations";
pub const RESOURCE: &str = "workspace";
pub const CANCEL: &str = "cancel";
pub const RETRY: &str = "retry";
pub const UNDO: &str = "undo";
pub const PAGE: usize = 50;
pub const MOST: usize = 200;
pub const ROOT_CHILD: &str = "invocations";
pub const INVOCATION_TYPE: &str = "invocation";
#[must_use]
pub fn publisher(workspace: &str) -> super::CatalogueProvider {
super::CatalogueProvider {
provider: PROVIDER.to_owned(),
app_id: ROOT_CHILD.to_owned(),
workspace: workspace.to_owned(),
browsable: true,
..super::CatalogueProvider::default()
}
}
#[must_use]
pub fn tree_rows(listed: &[Invocation]) -> Vec<super::CatalogueRow> {
let row = |parent: &str, id: String, of_type: &str, label: String| super::CatalogueRow {
provider: PROVIDER.to_owned(),
app_id: ROOT_CHILD.to_owned(),
parent_resource: parent.to_owned(),
resource: super::CatalogueResource {
id,
kind: of_type.to_owned(),
label,
presentation: None,
},
..super::CatalogueRow::default()
};
let mut root = row(
"",
RESOURCE.to_owned(),
"workspace.invocations",
"Invocations".to_owned(),
);
root.has_children = !listed.is_empty();
std::iter::once(root)
.chain(listed.iter().flat_map(|invocation| {
let id = invocation
.id
.clone()
.or_else(|| invocation.step.clone())
.unwrap_or_default();
let status = serde_json::to_value(invocation.status)
.ok()
.and_then(|status| status.as_str().map(str::to_owned))
.unwrap_or_default();
let mut label = format!("{status} by {}", invocation.by.name);
if let Some(title) = &invocation.title {
label.push_str(": ");
label.push_str(title);
}
let waits = invocation.status == InvocationStatus::Waiting && !id.is_empty();
let own = row(RESOURCE, id.clone(), INVOCATION_TYPE, label);
let resolve = waits.then(|| super::CatalogueRow {
action: Some(resolve_action(&id)),
..own.clone()
});
std::iter::once(own).chain(resolve)
}))
.collect()
}
fn resolve_action(invocation: &str) -> crate::ActionDescriptor {
use crate::{ActionContract, ActionKind, ActionParam, ParamType};
crate::ActionDescriptor {
did: None,
state: crate::ActionState::default(),
semantic_identity: None,
address: ActionAddress::new(invocation, super::asked::RESOLVE),
resource_kind: INVOCATION_TYPE.to_owned(),
resource_label: "Invocation".to_owned(),
action_label: "Answer".to_owned(),
keywords: Vec::new(),
icon: None,
description: Some(
"Answer what this invocation asks you: approve it, approve it and let its asker do \
the same from now on, or decline it."
.to_owned(),
),
locus: crate::ExecutionLocus::ServerPreferred,
kind: crate::OperationKind::Effect,
contract: ActionContract {
kind: ActionKind::Undoable,
..ActionContract::default()
},
input: crate::InputSpec::None,
params: vec![
ActionParam::required(
"resolution",
ParamType::Text,
"`approve`, `approve_and_grant` or `decline`.",
),
ActionParam::optional(
"choice",
ParamType::Integer,
"For a question with choices: the one picked, by its place.",
),
],
view: None,
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct InvocationsQuery {
pub limit: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub invocation: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<InvocationStatus>,
}
impl InvocationsQuery {
#[must_use]
pub fn page(&self) -> usize {
if self.limit == 0 {
PAGE
} else {
self.limit.min(MOST)
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct InvocationBy {
pub name: String,
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationStatus {
Waiting,
Running,
#[default]
Ended,
Failed,
Cancelled,
Undone,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct InvocationChange {
pub app: String,
pub app_id: String,
pub record: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Origin {
pub kind: String,
pub id: String,
}
impl Origin {
#[must_use]
pub fn parse(address: &str, kind: Option<&str>) -> Option<Self> {
let address = address.trim();
if address.is_empty() {
return None;
}
if let Some(stable) = crate::stable_item_address(address) {
let (kind, id) = stable.split_once(':')?;
return Some(Self {
kind: kind.to_owned(),
id: id.to_owned(),
});
}
if let Some((kind, id)) = address.split_once(':')
&& !kind.is_empty()
&& !id.is_empty()
{
return Some(Self {
kind: kind.to_owned(),
id: id.to_owned(),
});
}
let kind = kind.map(str::trim).filter(|kind| !kind.is_empty())?;
Some(Self {
kind: kind.to_owned(),
id: address.to_owned(),
})
}
#[must_use]
pub fn address(&self) -> String {
format!("{}:{}", self.kind, self.id)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Spend {
#[serde(skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
pub input_tokens: u64,
pub output_tokens: u64,
pub cost_micros: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Invocation {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub calls: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<Origin>,
#[serde(skip_serializing_if = "Option::is_none")]
pub retries: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub spend: Option<Spend>,
#[serde(skip_serializing_if = "Option::is_none")]
pub step: Option<String>,
pub by: InvocationBy,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub status: InvocationStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub failure: Option<String>,
pub started_ms: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub ended_ms: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub action: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output: Option<serde_json::Value>,
pub changes: usize,
pub undone: usize,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub records: Vec<InvocationChange>,
pub undoable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub undo_blocked: Option<String>,
pub recorded: bool,
pub remembered: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub person: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub asked: Option<Box<super::asked::Asked>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Invocations {
pub items: Vec<Invocation>,
pub total: usize,
pub waiting: usize,
pub pending: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
#[must_use]
pub fn edited_after(
entries: &[serde_json::Value],
of_step: impl Fn(&serde_json::Value) -> bool,
) -> Option<&serde_json::Value> {
let in_effect = |entry: &serde_json::Value| {
entry.get("undone").and_then(serde_json::Value::as_bool) != Some(true)
};
let is_edit = |entry: &serde_json::Value| entry.get("change_kind").is_none();
let last = entries
.iter()
.rposition(|entry| of_step(entry) && in_effect(entry) && is_edit(entry))?;
let after = entries.get(last.saturating_add(1)..)?;
let later: Vec<&str> = after
.iter()
.filter_map(|entry| entry.get("change").and_then(serde_json::Value::as_str))
.collect();
let moves_only_later = |entry: &serde_json::Value| {
["takes_back", "brings_back"].iter().any(|key| {
entry
.get(*key)
.and_then(serde_json::Value::as_array)
.is_some_and(|moved| {
moved.iter().all(|change| {
change
.as_str()
.is_some_and(|change| later.contains(&change))
})
})
})
};
after.iter().find(|entry| {
in_effect(entry) && is_edit(entry) && !of_step(entry) && !moves_only_later(entry)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_page_is_bounded() {
assert_eq!(InvocationsQuery::default().page(), PAGE);
assert_eq!(
InvocationsQuery {
limit: 3,
..InvocationsQuery::default()
}
.page(),
3
);
assert_eq!(
InvocationsQuery {
limit: 10_000,
..InvocationsQuery::default()
}
.page(),
MOST
);
let answer = serde_json::to_value(Invocation {
status: InvocationStatus::Waiting,
..Invocation::default()
})
.unwrap();
assert_eq!(answer["status"], "waiting");
assert!(answer.get("id").is_none(), "{answer}");
}
#[test]
fn a_listing_asks_for_one_members_runs_and_says_who_ran_each() {
let query = serde_json::to_value(InvocationsQuery {
by: Some("claude".into()),
..InvocationsQuery::default()
})
.unwrap();
assert_eq!(query["by"], "claude");
assert!(
serde_json::to_value(InvocationsQuery::default())
.unwrap()
.get("by")
.is_none()
);
let run = serde_json::to_value(Invocation {
by: InvocationBy {
name: "Claude".into(),
kind: "agent".into(),
id: Some("claude".into()),
},
..Invocation::default()
})
.unwrap();
assert_eq!(
run["by"],
serde_json::json!({"name": "Claude", "kind": "agent", "id": "claude"})
);
let unnamed = serde_json::to_value(InvocationBy::default()).unwrap();
assert!(unnamed.get("id").is_none(), "{unnamed}");
}
#[test]
fn an_undo_of_a_later_step_holds_no_earlier_step_back_and_a_later_edit_does() {
use serde_json::json;
let cover = |entry: &serde_json::Value| entry["step"] == "cover";
let mut entries = vec![
json!({"change": "a1", "step": "cover"}),
json!({"change": "b1", "step": "closing", "undone": true}),
json!({"change": "c1", "step": "u1", "takes_back": ["b1"]}),
json!({"change": "d1", "change_kind": "Housekeeping"}),
];
assert_eq!(edited_after(&entries, cover), None);
entries.push(json!({"change": "e1", "step": "u2", "takes_back": ["z9"]}));
assert_eq!(edited_after(&entries, cover).unwrap()["change"], "e1");
entries.pop();
entries.push(json!({"change": "e1", "step": "bob"}));
assert_eq!(edited_after(&entries, cover).unwrap()["change"], "e1");
}
}