tilo-actions 0.5.2

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! What an application publishes of its actions: the inert, typed shape one
//! action has on the wire, and what its invocation must carry.
//!
//! One shape holds an action: the application builds it from its typed
//! [`ActionDescriptor`](crate::ActionDescriptor), the wire carries it as this,
//! and the broker admits it as this.

use crate::{
    ActionAddress, ActionContract, ActionDescriptor, ActionParam, Collects, ExecutionLocus,
    InputSpec, OperationKind, ResourceSemanticIdentity, ResourceViewDescriptor,
};

/// What one published action's invocation must carry: the transport-side
/// twin of [`InputSpec`], which says what kind of text it collects.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PublishedInput {
    None,
    Text {
        prompt: String,
        placeholder: String,
        /// Whether that text names content already in this machine's store
        /// rather than words somebody says.
        wants_content: bool,
    },
}

impl From<&InputSpec> for PublishedInput {
    fn from(input: &InputSpec) -> Self {
        match input {
            InputSpec::None => Self::None,
            InputSpec::Text {
                prompt,
                placeholder,
                collects,
            } => Self::Text {
                prompt: prompt.clone(),
                placeholder: placeholder.clone(),
                wants_content: *collects == Collects::Content,
            },
        }
    }
}

impl From<&PublishedInput> for InputSpec {
    fn from(input: &PublishedInput) -> Self {
        match input {
            PublishedInput::None => Self::None,
            PublishedInput::Text {
                prompt,
                placeholder,
                wants_content,
            } => Self::Text {
                prompt: prompt.clone(),
                placeholder: placeholder.clone(),
                collects: if *wants_content {
                    Collects::Content
                } else {
                    Collects::Words
                },
            },
        }
    }
}

/// One inert operation an application publishes, without execution authority.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PublishedAction {
    pub resource: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantic_identity: Option<ResourceSemanticIdentity>,
    pub action: String,
    pub resource_kind: String,
    pub resource_label: String,
    pub action_label: String,
    /// The other words people use for the action, published with its label.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keywords: Vec<String>,
    /// What the action did, said after who did it, published with its label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub did: Option<String>,
    /// The action's own picture, by its Lucide name, published with its label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    pub description: Option<String>,
    /// What the action's row shows of the state it acts on.
    #[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
    pub state: crate::ActionState,
    pub operation_kind: OperationKind,
    /// The canonical typed parameter descriptors.
    pub params: Vec<ActionParam>,
    /// The complete safety/lifecycle/result contract.
    pub contract: ActionContract,
    pub view: Option<ResourceViewDescriptor>,
    pub input: PublishedInput,
}

/// One action an app offers while it is closed, as its manifest's `[[offers]]` declare it:
/// what the app's code publishes on an empty document, written there by `tilolang surface`.
/// Invoking one launches the app, and the action it then publishes admits the invocation.
#[derive(Clone, Debug)]
pub struct Offer<'a> {
    pub resource: &'a str,
    pub resource_kind: &'a str,
    pub action: &'a str,
    pub label: &'a str,
    pub description: Option<&'a str>,
    pub kind: crate::ActionKind,
    pub operation: OperationKind,
    /// A person confirms it first.
    pub confirm: bool,
    /// The values it asks for before it can run: one line each, or several a small form fills.
    pub asks: Vec<OfferParam<'a>>,
    pub keywords: Vec<&'a str>,
    pub icon: Option<&'a str>,
}

/// One value an offered action asks for: its name, the type it takes (`text`, `secret`,
/// `integer`…) and the words a person reads beside the field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OfferParam<'a> {
    pub name: &'a str,
    pub ty: &'a str,
    pub description: Option<&'a str>,
}

impl OfferParam<'_> {
    /// The type the parameter takes, as [`ParamType`](crate::ParamType) spells it: text for a
    /// value whose words are unknown here.
    #[must_use]
    pub fn param_type(&self) -> crate::ParamType {
        match self.ty {
            "integer" => crate::ParamType::Integer,
            "number" => crate::ParamType::Number,
            "boolean" => crate::ParamType::Boolean,
            "object" => crate::ParamType::Object,
            "array" => crate::ParamType::Array,
            "resource" => crate::ParamType::Resource,
            "datetime" => crate::ParamType::DateTime,
            "secret" => crate::ParamType::Secret,
            _ => crate::ParamType::Text,
        }
    }
}

impl PublishedAction {
    /// What `offer` of the app called `app_name` publishes, as offered while the app is closed.
    #[must_use]
    pub fn offered(offer: &Offer<'_>, app_name: &str) -> Self {
        use crate::{ActionKind, ConfirmationPolicy, RiskLevel};
        let (risk, confirmation) = match (offer.confirm, offer.kind) {
            (true, _) => (RiskLevel::Destructive, ConfirmationPolicy::Confirm),
            (false, ActionKind::Read) => (RiskLevel::None, ConfirmationPolicy::None),
            (false, _) => (RiskLevel::Low, ConfirmationPolicy::None),
        };
        let params: Vec<ActionParam> = offer
            .asks
            .iter()
            .map(|asked| {
                let mut param = ActionParam::required_owned(
                    "",
                    asked.param_type(),
                    asked.description.unwrap_or_default().to_owned(),
                );
                param.name = asked.name.to_owned().into();
                param
            })
            .collect();
        Self {
            resource: offer.resource.to_owned(),
            semantic_identity: None,
            action: offer.action.to_owned(),
            resource_kind: offer.resource_kind.to_owned(),
            resource_label: app_name.to_owned(),
            action_label: offer.label.to_owned(),
            keywords: offer
                .keywords
                .iter()
                .map(|word| (*word).to_owned())
                .collect(),
            did: None,
            icon: offer.icon.map(str::to_owned),
            description: offer.description.map(str::to_owned),
            state: crate::ActionState::default(),
            operation_kind: offer.operation,
            input: if params.is_empty() {
                PublishedInput::None
            } else {
                PublishedInput::Text {
                    prompt: offer.label.to_owned(),
                    placeholder: String::new(),
                    wants_content: false,
                }
            },
            params,
            contract: ActionContract {
                kind: offer.kind,
                risk,
                confirmation,
                ..ActionContract::default()
            },
            view: None,
        }
    }

    /// Whether this action, read from the app that published it, names a
    /// semantic identity only of its own kind and in bounds.
    pub fn check(&self) -> Result<(), String> {
        if self.semantic_identity.as_ref().is_some_and(|identity| {
            identity.kind.len() > ResourceSemanticIdentity::MAX_KIND_BYTES
                || identity.key.len() > ResourceSemanticIdentity::MAX_KEY_BYTES
                || !identity.is_valid()
                || identity.kind != self.resource_kind
        }) {
            return Err(format!(
                "action `{}`/`{}`: invalid resource semantic identity",
                self.resource, self.action
            ));
        }
        Ok(())
    }

    /// The resource's own id, not the transport alias the window published
    /// it under ([`ActionDescriptor::domain_resource`]).
    #[must_use]
    pub fn domain_resource(&self) -> &str {
        match &self.semantic_identity {
            Some(identity) if identity.is_valid() => identity.key.as_str(),
            _ => self.resource.as_str(),
        }
    }

    /// The typed descriptor this action publishes, run at `locus`: the wire
    /// carries no locus of its own.
    pub fn descriptor(&self, locus: ExecutionLocus) -> ActionDescriptor {
        ActionDescriptor {
            semantic_identity: self.semantic_identity.clone(),
            address: ActionAddress::new(&self.resource, &self.action),
            resource_kind: self.resource_kind.clone(),
            resource_label: self.resource_label.clone(),
            action_label: self.action_label.clone(),
            keywords: self.keywords.clone(),
            did: self.did.clone(),
            icon: self.icon.clone(),
            description: self.description.clone(),
            state: self.state.clone(),
            locus,
            kind: self.operation_kind,
            contract: self.contract.clone(),
            input: (&self.input).into(),
            params: self.params.clone(),
            view: self.view.clone(),
        }
    }
}

impl From<&ActionDescriptor> for PublishedAction {
    fn from(descriptor: &ActionDescriptor) -> Self {
        Self {
            resource: descriptor.address.resource.clone(),
            semantic_identity: descriptor.semantic_identity.clone(),
            action: descriptor.address.action.clone(),
            resource_kind: descriptor.resource_kind.clone(),
            resource_label: descriptor.resource_label.clone(),
            action_label: descriptor.action_label.clone(),
            keywords: descriptor.keywords.clone(),
            did: descriptor.did.clone(),
            icon: descriptor.icon.clone(),
            description: descriptor.description.clone(),
            state: descriptor.state.clone(),
            operation_kind: descriptor.kind,
            params: descriptor.params.clone(),
            contract: descriptor.contract.clone(),
            view: descriptor.view.clone(),
            input: (&descriptor.input).into(),
        }
    }
}

/// The fields of a resource every one of its actions carries.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ResourceFields {
    pub resource_kind: String,
    pub resource_label: String,
    pub semantic_identity: Option<ResourceSemanticIdentity>,
    /// The workspace holding the resource when it is not the one the publishing window is open
    /// in ([`crate::ResourceSpec::workspace`]): that workspace admits its actions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
}

/// Starts a mark in a catalogue entry's text: [`LABEL_MARK`] after it stands
/// for the resource's label, and a second one for itself.
const MARK: char = '\u{1}';
const LABEL_MARK: char = 'L';

/// `text` with every `label` in it that stands as words of its own marked, so
/// one entry serves every resource whose words differ only by its name
/// ("Focus Chat", "Focus Notes").
fn mark_label(text: &str, label: &str) -> String {
    let escaped = text.replace(MARK, "\u{1}\u{1}");
    if label.is_empty() || label.contains(MARK) {
        return escaped;
    }
    let mut out = String::with_capacity(escaped.len());
    let mut from = 0;
    for (at, _) in escaped.match_indices(label) {
        let end = at.saturating_add(label.len());
        let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
        let before = escaped.get(..at).and_then(|text| text.chars().next_back());
        let after = escaped.get(end..).and_then(|text| text.chars().next());
        if word(before) || word(after) {
            continue;
        }
        out.push_str(escaped.get(from..at).unwrap_or_default());
        out.push(MARK);
        out.push(LABEL_MARK);
        from = end;
    }
    out.push_str(escaped.get(from..).unwrap_or_default());
    out
}

/// [`mark_label`] undone for the resource labelled `label`.
fn unmark_label(text: &str, label: &str) -> String {
    if !text.contains(MARK) {
        return text.to_owned();
    }
    let mut out = String::with_capacity(text.len().saturating_add(label.len()));
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        if c != MARK {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some(LABEL_MARK) => out.push_str(label),
            Some(other) => out.push(other),
            None => {}
        }
    }
    out
}

impl PublishedAction {
    /// The catalogue entry of this action, which every resource of its kind
    /// shares: everything but its resource's own fields, which a
    /// [`ResourceFields`] carries, with the resource's label in its words
    /// marked. Its state stays: keys and toggles are its type's, and a badge
    /// is shown on the row, so rows with the same badge share the entry.
    /// [`Self::on_resource`] gives the action back.
    #[must_use]
    pub fn shape(&self) -> Self {
        let mut shape = Self {
            resource: String::new(),
            semantic_identity: None,
            resource_kind: String::new(),
            resource_label: String::new(),
            ..self.clone()
        };
        shape.map_words(|text| mark_label(text, &self.resource_label));
        shape
    }

    /// The action `self`, a [`Self::shape`], is on the resource `resource`
    /// with `fields`.
    #[must_use]
    pub fn on_resource(&self, resource: &str, fields: &ResourceFields) -> Self {
        let mut action = Self {
            resource: resource.to_owned(),
            semantic_identity: fields.semantic_identity.clone(),
            resource_kind: fields.resource_kind.clone(),
            resource_label: fields.resource_label.clone(),
            ..self.clone()
        };
        action.map_words(|text| unmark_label(text, &fields.resource_label));
        action
    }

    /// Apply `map` to the words it shows: its label, description, input and
    /// parameter descriptions.
    fn map_words(&mut self, map: impl Fn(&str) -> String) {
        self.action_label = map(&self.action_label);
        if let Some(description) = &mut self.description {
            *description = map(description);
        }
        if let PublishedInput::Text {
            prompt,
            placeholder,
            ..
        } = &mut self.input
        {
            *prompt = map(prompt);
            *placeholder = map(placeholder);
        }
        for param in &mut self.params {
            param.description = map(&param.description).into();
        }
    }

    #[must_use]
    pub fn resource_fields(&self) -> ResourceFields {
        ResourceFields {
            resource_kind: self.resource_kind.clone(),
            resource_label: self.resource_label.clone(),
            semantic_identity: self.semantic_identity.clone(),
            workspace: None,
        }
    }
}