Skip to main content

tilo_actions/
outcome.rs

1//! Typed invocation identity, progress, failure, and successful results.
2
3use serde::{Deserialize, Serialize};
4
5/// Resource kind for bytes addressed by their content hash.
6///
7/// Producers return `tilo.content:<hash>` in [`ActionOutput::resources`]; a
8/// content-collecting action may then consume the hash without asking a model
9/// to copy or invent it.
10pub const CONTENT_RESOURCE_KIND: &str = "tilo.content";
11
12/// Build the canonical resource address for content-addressed bytes.
13///
14/// Empty hashes and hashes containing the address separator are refused so a
15/// malformed producer cannot create an ambiguous resource address.
16pub fn content_resource(hash: &str) -> Option<String> {
17    (!hash.is_empty() && !hash.contains(':')).then(|| format!("{CONTENT_RESOURCE_KIND}:{hash}"))
18}
19
20/// Read a content hash from its canonical resource address.
21pub fn content_hash(address: &str) -> Option<&str> {
22    address
23        .strip_prefix(CONTENT_RESOURCE_KIND)?
24        .strip_prefix(':')
25        .filter(|hash| !hash.is_empty() && !hash.contains(':'))
26}
27
28/// The content reference an argument names: a `tilo.content:<reference>`
29/// address, or the bare reference a plan that carried the content gives.
30pub fn named_reference(value: &str) -> Option<&str> {
31    let value = value.trim();
32    let reference = content_hash(value).unwrap_or(value);
33    tilo_content::valid_reference(reference).then_some(reference)
34}
35
36pub use tilo_action_types::InvocationId;
37
38#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
39#[serde(remote = "Self")]
40pub struct ActionOutput {
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub value: Option<serde_json::Value>,
43    /// Canonical resource addresses produced or revealed by the action.
44    #[serde(default, skip_serializing_if = "Vec::is_empty")]
45    pub resources: Vec<String>,
46}
47
48read_through_json_value!(ActionOutput);
49
50impl ActionOutput {
51    /// The characters this action wrote, as its answer names them (`wrote`): the view showing that
52    /// text draws them in the writer's colour, with the writer's caret at their end.
53    #[must_use]
54    pub fn wrote(&self) -> Option<crate::InteractionAnchor> {
55        serde_json::from_value(self.value.as_ref()?.get("wrote")?.clone()).ok()
56    }
57
58    /// `value`, an answer, naming the characters `wrote` the action wrote too. An answer that is
59    /// no object (a summary in words) is kept as it is.
60    #[must_use]
61    pub fn noting_wrote(
62        value: Option<serde_json::Value>,
63        wrote: &crate::InteractionAnchor,
64    ) -> Option<serde_json::Value> {
65        let mut fields = match value {
66            None | Some(serde_json::Value::Null) => serde_json::Map::new(),
67            Some(serde_json::Value::Object(fields)) => fields,
68            other => return other,
69        };
70        fields.insert("wrote".into(), serde_json::to_value(wrote).ok()?);
71        Some(serde_json::Value::Object(fields))
72    }
73}
74
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(remote = "Self")]
77pub struct ActionFailure {
78    pub code: String,
79    pub message: String,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub details: Option<serde_json::Value>,
82    #[serde(default)]
83    pub retryable: bool,
84}
85
86read_through_json_value!(ActionFailure);
87
88impl ActionFailure {
89    /// The failure a run answers with when what it reached needs the person's yes: its caller
90    /// is refused for want of their answer, showing them `facts`
91    /// ([`crate::remote::ActionCallError::ConfirmationRequired`]), and their approve sends the
92    /// call again, which the handler reads ([`crate::remote::InvokeRequest::approval`]).
93    #[must_use]
94    pub fn asks(message: impl Into<String>, facts: &crate::remote::asked::AskedFacts) -> Self {
95        Self {
96            code: crate::remote::CONFIRMATION_REQUIRED_CODE.to_owned(),
97            message: message.into(),
98            details: Some(facts.to_details()),
99            retryable: false,
100        }
101    }
102}
103
104/// Monotonic lifecycle of one invocation. A transport timeout is not a failed
105/// action: callers retain the invocation id and can resume observing it.
106#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
107#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
108pub enum InvocationUpdate {
109    Accepted {
110        invocation: InvocationId,
111    },
112    Progress {
113        invocation: InvocationId,
114        sequence: u64,
115        phase: String,
116        completed: Option<u64>,
117        total: Option<u64>,
118        message: Option<String>,
119    },
120    /// One ordered value from a streaming operation.
121    Item {
122        invocation: InvocationId,
123        sequence: u64,
124        value: serde_json::Value,
125    },
126    Succeeded {
127        invocation: InvocationId,
128        output: ActionOutput,
129    },
130    Failed {
131        invocation: InvocationId,
132        error: ActionFailure,
133    },
134    Cancelled {
135        invocation: InvocationId,
136        message: Option<String>,
137    },
138}
139
140read_through_json_value!(InvocationUpdate);
141
142impl InvocationUpdate {
143    pub fn invocation(&self) -> InvocationId {
144        match self {
145            Self::Accepted { invocation }
146            | Self::Progress { invocation, .. }
147            | Self::Item { invocation, .. }
148            | Self::Succeeded { invocation, .. }
149            | Self::Failed { invocation, .. }
150            | Self::Cancelled { invocation, .. } => *invocation,
151        }
152    }
153
154    pub fn is_terminal(&self) -> bool {
155        matches!(
156            self,
157            Self::Succeeded { .. } | Self::Failed { .. } | Self::Cancelled { .. }
158        )
159    }
160
161    /// Whether it ended in a failure the same call may meet again: whoever
162    /// follows the invocation learns to ask again, and a request under its id
163    /// makes it once more rather than being handed this failure.
164    #[must_use]
165    pub fn asks_again(&self) -> bool {
166        matches!(self, Self::Failed { error, .. } if error.retryable)
167    }
168
169    /// The same update, reported under `id`. A host that tracks a job under
170    /// its own handle uses this to answer in the caller's invocation id.
171    #[must_use]
172    pub fn with_invocation(mut self, id: InvocationId) -> Self {
173        match &mut self {
174            Self::Accepted { invocation }
175            | Self::Progress { invocation, .. }
176            | Self::Item { invocation, .. }
177            | Self::Succeeded { invocation, .. }
178            | Self::Failed { invocation, .. }
179            | Self::Cancelled { invocation, .. } => *invocation = id,
180        }
181        self
182    }
183}
184
185/// Durable, deliberately redacted outcome of a consequential effect.
186///
187/// Receipts are suitable for shared workspace activity. They never retain
188/// invocation arguments, streamed items, returned values/resource addresses,
189/// failure messages, or structured failure details. Those values may contain
190/// credentials or document content and remain available only through the
191/// private invocation lifecycle.
192#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(tag = "status", rename_all = "snake_case")]
194pub enum EffectReceiptStatus {
195    Succeeded,
196    Failed { code: String },
197    Cancelled,
198}
199
200impl EffectReceiptStatus {
201    /// Reduce a terminal lifecycle update to its safe durable representation.
202    /// Non-terminal updates are intentionally not activity records.
203    pub fn from_terminal(update: &InvocationUpdate) -> Option<Self> {
204        match update {
205            InvocationUpdate::Succeeded { .. } => Some(Self::Succeeded),
206            InvocationUpdate::Failed { error, .. } => Some(Self::Failed {
207                code: bounded_identifier(&error.code, "action_failed"),
208            }),
209            InvocationUpdate::Cancelled { .. } => Some(Self::Cancelled),
210            InvocationUpdate::Accepted { .. }
211            | InvocationUpdate::Progress { .. }
212            | InvocationUpdate::Item { .. } => None,
213        }
214    }
215
216    pub const fn label(&self) -> &'static str {
217        match self {
218            Self::Succeeded => "Completed",
219            Self::Failed { .. } => "Failed",
220            Self::Cancelled => "Cancelled",
221        }
222    }
223}
224
225fn bounded_identifier(value: &str, fallback: &str) -> String {
226    let safe = value
227        .chars()
228        .filter(|character| {
229            character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.')
230        })
231        .take(96)
232        .collect::<String>();
233    if safe.is_empty() {
234        fallback.to_string()
235    } else {
236        safe
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    /// Content resource addresses round-trip without guessing and effect receipts redact terminal
245    /// payloads.
246    /// Runs each phase below in order; every phase builds its own fixture.
247    #[test]
248    fn outcomes_address_content_exactly_and_redact_terminal_payloads() {
249        content_resource_addresses_round_trip_without_guessing();
250        effect_receipt_redacts_terminal_payloads();
251        an_invocation_id_is_read_back_as_the_caller_wrote_it();
252    }
253
254    /// A caller that keeps an invocation id of its own (a page's dialog, a script's file) asks
255    /// again under the same one.
256    fn an_invocation_id_is_read_back_as_the_caller_wrote_it() {
257        let invocation = InvocationId::new();
258        let text = invocation.0.to_string();
259        assert_eq!(
260            text.parse::<InvocationId>().expect("its own id reads back"),
261            invocation
262        );
263        assert_eq!(
264            format!(" {text} ")
265                .parse::<InvocationId>()
266                .expect("spaced text reads"),
267            invocation
268        );
269        assert!("not an invocation".parse::<InvocationId>().is_err());
270    }
271
272    fn content_resource_addresses_round_trip_without_guessing() {
273        let address = content_resource("abc123").expect("a content hash has an address");
274        assert_eq!(address, "tilo.content:abc123");
275        assert_eq!(content_hash(&address), Some("abc123"));
276        assert_eq!(content_resource(""), None);
277        assert_eq!(content_resource("two:parts"), None);
278        assert_eq!(content_hash("files.entry:/tmp/a"), None);
279    }
280
281    fn effect_receipt_redacts_terminal_payloads() {
282        let invocation = InvocationId::new();
283        let update = InvocationUpdate::Failed {
284            invocation,
285            error: ActionFailure {
286                code: "smtp.secret\ncode".into(),
287                message: "password=hunter2".into(),
288                details: Some(serde_json::json!({"token": "private"})),
289                retryable: true,
290            },
291        };
292        let receipt = EffectReceiptStatus::from_terminal(&update).expect("terminal receipt");
293        assert_eq!(
294            receipt,
295            EffectReceiptStatus::Failed {
296                code: "smtp.secretcode".into()
297            }
298        );
299        let json = serde_json::to_string(&receipt).expect("encode receipt");
300        assert!(!json.contains("hunter2"));
301        assert!(!json.contains("private"));
302    }
303}