Skip to main content

tilo_actions/
published.rs

1//! What an application publishes of its actions: the inert, typed shape one
2//! action has on the wire, and what its invocation must carry.
3//!
4//! One shape holds an action: the application builds it from its typed
5//! [`ActionDescriptor`](crate::ActionDescriptor), the wire carries it as this,
6//! and the broker admits it as this.
7
8use crate::{
9    ActionAddress, ActionContract, ActionDescriptor, ActionParam, Collects, ExecutionLocus,
10    InputSpec, OperationKind, ResourceSemanticIdentity, ResourceViewDescriptor,
11};
12
13/// What one published action's invocation must carry: the transport-side
14/// twin of [`InputSpec`], which says what kind of text it collects.
15#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16pub enum PublishedInput {
17    None,
18    Text {
19        prompt: String,
20        placeholder: String,
21        /// Whether that text names content already in this machine's store
22        /// rather than words somebody says.
23        wants_content: bool,
24    },
25}
26
27impl From<&InputSpec> for PublishedInput {
28    fn from(input: &InputSpec) -> Self {
29        match input {
30            InputSpec::None => Self::None,
31            InputSpec::Text {
32                prompt,
33                placeholder,
34                collects,
35            } => Self::Text {
36                prompt: prompt.clone(),
37                placeholder: placeholder.clone(),
38                wants_content: *collects == Collects::Content,
39            },
40        }
41    }
42}
43
44impl From<&PublishedInput> for InputSpec {
45    fn from(input: &PublishedInput) -> Self {
46        match input {
47            PublishedInput::None => Self::None,
48            PublishedInput::Text {
49                prompt,
50                placeholder,
51                wants_content,
52            } => Self::Text {
53                prompt: prompt.clone(),
54                placeholder: placeholder.clone(),
55                collects: if *wants_content {
56                    Collects::Content
57                } else {
58                    Collects::Words
59                },
60            },
61        }
62    }
63}
64
65/// One inert operation an application publishes, without execution authority.
66#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
67pub struct PublishedAction {
68    pub resource: String,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub semantic_identity: Option<ResourceSemanticIdentity>,
71    pub action: String,
72    pub resource_kind: String,
73    pub resource_label: String,
74    pub action_label: String,
75    /// The other words people use for the action, published with its label.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub keywords: Vec<String>,
78    /// What the action did, said after who did it, published with its label.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub did: Option<String>,
81    /// The action's own picture, by its Lucide name, published with its label.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub icon: Option<String>,
84    pub description: Option<String>,
85    /// What the action's row shows of the state it acts on.
86    #[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
87    pub state: crate::ActionState,
88    pub operation_kind: OperationKind,
89    /// The canonical typed parameter descriptors.
90    pub params: Vec<ActionParam>,
91    /// The complete safety/lifecycle/result contract.
92    pub contract: ActionContract,
93    pub view: Option<ResourceViewDescriptor>,
94    pub input: PublishedInput,
95}
96
97/// One action an app offers while it is closed, as its manifest's `[[offers]]` declare it:
98/// what the app's code publishes on an empty document, written there by `tilolang surface`.
99/// Invoking one launches the app, and the action it then publishes admits the invocation.
100#[derive(Clone, Debug)]
101pub struct Offer<'a> {
102    pub resource: &'a str,
103    pub resource_kind: &'a str,
104    pub action: &'a str,
105    pub label: &'a str,
106    pub description: Option<&'a str>,
107    pub kind: crate::ActionKind,
108    pub operation: OperationKind,
109    /// A person confirms it first.
110    pub confirm: bool,
111    /// The values it asks for before it can run: one line each, or several a small form fills.
112    pub asks: Vec<OfferParam<'a>>,
113    pub keywords: Vec<&'a str>,
114    pub icon: Option<&'a str>,
115}
116
117/// One value an offered action asks for: its name, the type it takes (`text`, `secret`,
118/// `integer`…) and the words a person reads beside the field.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub struct OfferParam<'a> {
121    pub name: &'a str,
122    pub ty: &'a str,
123    pub description: Option<&'a str>,
124}
125
126impl OfferParam<'_> {
127    /// The type the parameter takes, as [`ParamType`](crate::ParamType) spells it: text for a
128    /// value whose words are unknown here.
129    #[must_use]
130    pub fn param_type(&self) -> crate::ParamType {
131        match self.ty {
132            "integer" => crate::ParamType::Integer,
133            "number" => crate::ParamType::Number,
134            "boolean" => crate::ParamType::Boolean,
135            "object" => crate::ParamType::Object,
136            "array" => crate::ParamType::Array,
137            "resource" => crate::ParamType::Resource,
138            "datetime" => crate::ParamType::DateTime,
139            "secret" => crate::ParamType::Secret,
140            _ => crate::ParamType::Text,
141        }
142    }
143}
144
145impl PublishedAction {
146    /// What `offer` of the app called `app_name` publishes, as offered while the app is closed.
147    #[must_use]
148    pub fn offered(offer: &Offer<'_>, app_name: &str) -> Self {
149        use crate::{ActionKind, ConfirmationPolicy, RiskLevel};
150        let (risk, confirmation) = match (offer.confirm, offer.kind) {
151            (true, _) => (RiskLevel::Destructive, ConfirmationPolicy::Confirm),
152            (false, ActionKind::Read) => (RiskLevel::None, ConfirmationPolicy::None),
153            (false, _) => (RiskLevel::Low, ConfirmationPolicy::None),
154        };
155        let params: Vec<ActionParam> = offer
156            .asks
157            .iter()
158            .map(|asked| {
159                let mut param = ActionParam::required_owned(
160                    "",
161                    asked.param_type(),
162                    asked.description.unwrap_or_default().to_owned(),
163                );
164                param.name = asked.name.to_owned().into();
165                param
166            })
167            .collect();
168        Self {
169            resource: offer.resource.to_owned(),
170            semantic_identity: None,
171            action: offer.action.to_owned(),
172            resource_kind: offer.resource_kind.to_owned(),
173            resource_label: app_name.to_owned(),
174            action_label: offer.label.to_owned(),
175            keywords: offer
176                .keywords
177                .iter()
178                .map(|word| (*word).to_owned())
179                .collect(),
180            did: None,
181            icon: offer.icon.map(str::to_owned),
182            description: offer.description.map(str::to_owned),
183            state: crate::ActionState::default(),
184            operation_kind: offer.operation,
185            input: if params.is_empty() {
186                PublishedInput::None
187            } else {
188                PublishedInput::Text {
189                    prompt: offer.label.to_owned(),
190                    placeholder: String::new(),
191                    wants_content: false,
192                }
193            },
194            params,
195            contract: ActionContract {
196                kind: offer.kind,
197                risk,
198                confirmation,
199                ..ActionContract::default()
200            },
201            view: None,
202        }
203    }
204
205    /// Whether this action, read from the app that published it, names a
206    /// semantic identity only of its own kind and in bounds.
207    pub fn check(&self) -> Result<(), String> {
208        if self.semantic_identity.as_ref().is_some_and(|identity| {
209            identity.kind.len() > ResourceSemanticIdentity::MAX_KIND_BYTES
210                || identity.key.len() > ResourceSemanticIdentity::MAX_KEY_BYTES
211                || !identity.is_valid()
212                || identity.kind != self.resource_kind
213        }) {
214            return Err(format!(
215                "action `{}`/`{}`: invalid resource semantic identity",
216                self.resource, self.action
217            ));
218        }
219        Ok(())
220    }
221
222    /// The resource's own id, not the transport alias the window published
223    /// it under ([`ActionDescriptor::domain_resource`]).
224    #[must_use]
225    pub fn domain_resource(&self) -> &str {
226        match &self.semantic_identity {
227            Some(identity) if identity.is_valid() => identity.key.as_str(),
228            _ => self.resource.as_str(),
229        }
230    }
231
232    /// The typed descriptor this action publishes, run at `locus`: the wire
233    /// carries no locus of its own.
234    pub fn descriptor(&self, locus: ExecutionLocus) -> ActionDescriptor {
235        ActionDescriptor {
236            semantic_identity: self.semantic_identity.clone(),
237            address: ActionAddress::new(&self.resource, &self.action),
238            resource_kind: self.resource_kind.clone(),
239            resource_label: self.resource_label.clone(),
240            action_label: self.action_label.clone(),
241            keywords: self.keywords.clone(),
242            did: self.did.clone(),
243            icon: self.icon.clone(),
244            description: self.description.clone(),
245            state: self.state.clone(),
246            locus,
247            kind: self.operation_kind,
248            contract: self.contract.clone(),
249            input: (&self.input).into(),
250            params: self.params.clone(),
251            view: self.view.clone(),
252        }
253    }
254}
255
256impl From<&ActionDescriptor> for PublishedAction {
257    fn from(descriptor: &ActionDescriptor) -> Self {
258        Self {
259            resource: descriptor.address.resource.clone(),
260            semantic_identity: descriptor.semantic_identity.clone(),
261            action: descriptor.address.action.clone(),
262            resource_kind: descriptor.resource_kind.clone(),
263            resource_label: descriptor.resource_label.clone(),
264            action_label: descriptor.action_label.clone(),
265            keywords: descriptor.keywords.clone(),
266            did: descriptor.did.clone(),
267            icon: descriptor.icon.clone(),
268            description: descriptor.description.clone(),
269            state: descriptor.state.clone(),
270            operation_kind: descriptor.kind,
271            params: descriptor.params.clone(),
272            contract: descriptor.contract.clone(),
273            view: descriptor.view.clone(),
274            input: (&descriptor.input).into(),
275        }
276    }
277}
278
279/// The fields of a resource every one of its actions carries.
280#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
281pub struct ResourceFields {
282    pub resource_kind: String,
283    pub resource_label: String,
284    pub semantic_identity: Option<ResourceSemanticIdentity>,
285    /// The workspace holding the resource when it is not the one the publishing window is open
286    /// in ([`crate::ResourceSpec::workspace`]): that workspace admits its actions.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub workspace: Option<String>,
289}
290
291/// Starts a mark in a catalogue entry's text: [`LABEL_MARK`] after it stands
292/// for the resource's label, and a second one for itself.
293const MARK: char = '\u{1}';
294const LABEL_MARK: char = 'L';
295
296/// `text` with every `label` in it that stands as words of its own marked, so
297/// one entry serves every resource whose words differ only by its name
298/// ("Focus Chat", "Focus Notes").
299fn mark_label(text: &str, label: &str) -> String {
300    let escaped = text.replace(MARK, "\u{1}\u{1}");
301    if label.is_empty() || label.contains(MARK) {
302        return escaped;
303    }
304    let mut out = String::with_capacity(escaped.len());
305    let mut from = 0;
306    for (at, _) in escaped.match_indices(label) {
307        let end = at.saturating_add(label.len());
308        let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
309        let before = escaped.get(..at).and_then(|text| text.chars().next_back());
310        let after = escaped.get(end..).and_then(|text| text.chars().next());
311        if word(before) || word(after) {
312            continue;
313        }
314        out.push_str(escaped.get(from..at).unwrap_or_default());
315        out.push(MARK);
316        out.push(LABEL_MARK);
317        from = end;
318    }
319    out.push_str(escaped.get(from..).unwrap_or_default());
320    out
321}
322
323/// [`mark_label`] undone for the resource labelled `label`.
324fn unmark_label(text: &str, label: &str) -> String {
325    if !text.contains(MARK) {
326        return text.to_owned();
327    }
328    let mut out = String::with_capacity(text.len().saturating_add(label.len()));
329    let mut chars = text.chars();
330    while let Some(c) = chars.next() {
331        if c != MARK {
332            out.push(c);
333            continue;
334        }
335        match chars.next() {
336            Some(LABEL_MARK) => out.push_str(label),
337            Some(other) => out.push(other),
338            None => {}
339        }
340    }
341    out
342}
343
344impl PublishedAction {
345    /// The catalogue entry of this action, which every resource of its kind
346    /// shares: everything but its resource's own fields, which a
347    /// [`ResourceFields`] carries, with the resource's label in its words
348    /// marked. Its state stays: keys and toggles are its type's, and a badge
349    /// is shown on the row, so rows with the same badge share the entry.
350    /// [`Self::on_resource`] gives the action back.
351    #[must_use]
352    pub fn shape(&self) -> Self {
353        let mut shape = Self {
354            resource: String::new(),
355            semantic_identity: None,
356            resource_kind: String::new(),
357            resource_label: String::new(),
358            ..self.clone()
359        };
360        shape.map_words(|text| mark_label(text, &self.resource_label));
361        shape
362    }
363
364    /// The action `self`, a [`Self::shape`], is on the resource `resource`
365    /// with `fields`.
366    #[must_use]
367    pub fn on_resource(&self, resource: &str, fields: &ResourceFields) -> Self {
368        let mut action = Self {
369            resource: resource.to_owned(),
370            semantic_identity: fields.semantic_identity.clone(),
371            resource_kind: fields.resource_kind.clone(),
372            resource_label: fields.resource_label.clone(),
373            ..self.clone()
374        };
375        action.map_words(|text| unmark_label(text, &fields.resource_label));
376        action
377    }
378
379    /// Apply `map` to the words it shows: its label, description, input and
380    /// parameter descriptions.
381    fn map_words(&mut self, map: impl Fn(&str) -> String) {
382        self.action_label = map(&self.action_label);
383        if let Some(description) = &mut self.description {
384            *description = map(description);
385        }
386        if let PublishedInput::Text {
387            prompt,
388            placeholder,
389            ..
390        } = &mut self.input
391        {
392            *prompt = map(prompt);
393            *placeholder = map(placeholder);
394        }
395        for param in &mut self.params {
396            param.description = map(&param.description).into();
397        }
398    }
399
400    #[must_use]
401    pub fn resource_fields(&self) -> ResourceFields {
402        ResourceFields {
403            resource_kind: self.resource_kind.clone(),
404            resource_label: self.resource_label.clone(),
405            semantic_identity: self.semantic_identity.clone(),
406            workspace: None,
407        }
408    }
409}