Skip to main content

tilo_actions/
resource.rs

1//! The nested **Resource** tree an app publishes, and the **`ActionSpec`**s
2//! each resource exports.
3//!
4//! A [`ResourceSpec`] is something the app currently has *open/presented*
5//! (a playing video, an open book); resources **nest** — a video owns
6//! its comments, a book its annotations. Each exports [`ActionSpec`]s:
7//! the operations Ctrl+K offers for it.
8//!
9//! The split that matters: [`ResourceSpec`]/[`ActionSpec`] is
10//! **presentation** — local, per-frame, with human labels and (for a
11//! prompted action) a closure. The [`EncodedAction`] an `ActionSpec`
12//! yields is the **action** — serializable, replayable. Presentation
13//! never crosses a boundary; only the action does.
14//!
15//! # The typed projection
16//!
17//! A spec also carries a **serializable projection of itself**: a typed
18//! [`params`](ActionSpec::params) list and a builder that turns bound
19//! [`ActionArgs`] into that same [`EncodedAction`]. That is what lets a caller
20//! with no window enumerate the surface (see `crate::wire`) and invoke it by
21//! name — the presentation stays local, but a faithful *description* of it can
22//! now cross.
23//!
24//! The projection is derived from the same closure the palette uses:
25//! [`immediate`](ActionSpec::immediate) projects to zero parameters returning
26//! its pre-encoded action, and
27//! [`prompted_param`](ActionSpec::prompted_param) projects to one required
28//! [`Text`](ParamType::Text) parameter, named for what it is, that calls the
29//! app's closure. An affordance, its palette row, and an external invocation
30//! therefore run through one function and produce the same action.
31//!
32//! [`typed`](ActionSpec::typed) constructs an action whose argument has a
33//! domain type (a number in `0..=1`, a fixed set of filter names) instead of
34//! relying on a lenient prose parser.
35
36use std::sync::Arc;
37
38use serde::{Deserialize, Serialize};
39
40use crate::action::{Action, ActionError, EncodedAction, ExecutionLocus, OperationKind};
41use crate::api::ActionAddress;
42use crate::contract::{
43    ActionContract, ActionKind, ActionNeed, Availability, ConfirmationPolicy, ExecutionMode,
44    ResultSpec, RiskLevel,
45};
46use crate::params::{ActionArgs, ActionParam, ArgError, ArgValue, ParamType};
47
48/// Builds an action's encoded form from arguments already bound against its
49/// declared [`params`](ActionSpec::params).
50///
51/// Infallible by design: every check a caller can fail — presence, type,
52/// choice — happens in [`ActionArgs::bind`] *before* this runs, so a builder
53/// that holds an `ActionArgs` is looking at values it declared and can use them
54/// directly. The [`Target`] is that of the spec being invoked, for a type
55/// shared by many; an action whose builder holds what it acts on ignores it.
56pub type ArgsBuilder = Arc<dyn Fn(&Target, &ActionArgs) -> EncodedAction + Send + Sync>;
57
58/// Failure to construct or emit a control binding.
59#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
60pub enum ActionBindingError {
61    #[error("action `{action}` is not exported by resource `{resource}`")]
62    ActionNotExported { resource: String, action: String },
63    #[error(transparent)]
64    InvalidArguments(#[from] ArgError),
65    /// The control's value does not make arguments of the action at all.
66    #[error("{0}")]
67    Unbindable(String),
68}
69
70type Arguments<I> =
71    Arc<dyn Fn(I) -> Result<serde_json::Map<String, serde_json::Value>, String> + Send + Sync>;
72
73/// What a control binds to: one published resource and the actions it exports. A row an app
74/// publishes ([`ResourceSpec`] here, the framework's live row above it) is one, so a control
75/// binds to the row it shows without the app building the published tree itself.
76pub trait Exports {
77    /// The resource as it is published: its identity, kind, sharing and exported actions.
78    fn exported(&self) -> &ResourceSpec;
79}
80
81impl Exports for ResourceSpec {
82    fn exported(&self) -> &ResourceSpec {
83        self
84    }
85}
86
87/// A resource kept behind a pointer exports what the resource does, as a reference to it did when
88/// the binding took a `&ResourceSpec`.
89impl<T: Exports + ?Sized> Exports for &T {
90    fn exported(&self) -> &ResourceSpec {
91        (**self).exported()
92    }
93}
94
95impl<T: Exports + ?Sized> Exports for Box<T> {
96    fn exported(&self) -> &ResourceSpec {
97        (**self).exported()
98    }
99}
100
101impl<T: Exports + ?Sized> Exports for std::rc::Rc<T> {
102    fn exported(&self) -> &ResourceSpec {
103        (**self).exported()
104    }
105}
106
107impl<T: Exports + ?Sized> Exports for Arc<T> {
108    fn exported(&self) -> &ResourceSpec {
109        (**self).exported()
110    }
111}
112
113impl<T: Exports> Exports for std::sync::LazyLock<T> {
114    fn exported(&self) -> &ResourceSpec {
115        std::sync::LazyLock::force(self).exported()
116    }
117}
118
119/// Type-safe adapter from a control's input value to an exported action.
120///
121/// Construction requires the row that really exports the action ([`Exports`])
122/// and its [`ActionSpec`], rather than parallel string constants. Construction and emission validate the
123/// arguments against the parameters of a clone of that spec and never run its
124/// encoder, which may plan the whole action: a binding is made for each control
125/// a frame reads. The host re-resolves, validates and encodes at dispatch time
126/// because this object is convenience, not authority.
127#[derive(Clone)]
128pub struct ActionBinding<I> {
129    address: ActionAddress,
130    /// The kind of record the action acts on, as the resource publishes it: what
131    /// the control's identity names instead of the one resource, which the
132    /// window's business is ([`Self::identity`]).
133    kind: String,
134    /// The app the resource is published by, when everyone in the workspace reads it rather than
135    /// only its person ([`ResourceSpec::personal`]): what [`Self::shared_resource`] names.
136    shared_by: Option<String>,
137    spec: ActionSpec,
138    arguments: Arguments<I>,
139}
140
141impl<I> ActionBinding<I> {
142    /// Bind a typed control value to arguments for an action actually exported
143    /// by `resource`.
144    ///
145    /// # Errors
146    ///
147    /// Returns [`ActionBindingError::ActionNotExported`] if `spec` is absent
148    /// from `resource`.
149    pub fn new(
150        resource: &(impl Exports + ?Sized),
151        spec: &ActionSpec,
152        arguments: impl Fn(I) -> serde_json::Map<String, serde_json::Value> + Send + Sync + 'static,
153    ) -> Result<Self, ActionBindingError> {
154        Self::fallible(resource, spec, move |input| Ok(arguments(input)))
155    }
156
157    /// [`Self::new`] for an input that may not make arguments: a value that
158    /// does not serialize, a form that does not fit the parameters. Such an
159    /// input is refused when the control emits it, never sent empty.
160    ///
161    /// # Errors
162    ///
163    /// Returns [`ActionBindingError::ActionNotExported`] if `spec` is absent
164    /// from `resource`.
165    pub fn fallible(
166        resource: &(impl Exports + ?Sized),
167        spec: &ActionSpec,
168        arguments: impl Fn(I) -> Result<serde_json::Map<String, serde_json::Value>, String>
169        + Send
170        + Sync
171        + 'static,
172    ) -> Result<Self, ActionBindingError> {
173        let resource = resource.exported();
174        let exported = resource
175            .actions
176            .iter()
177            .find(|candidate| candidate.id == spec.id)
178            .ok_or_else(|| ActionBindingError::ActionNotExported {
179                resource: resource.id.0.clone(),
180                action: spec.id.clone(),
181            })?;
182        Ok(Self {
183            address: ActionAddress::new(resource.id.0.clone(), spec.id.clone()),
184            kind: resource.kind.clone(),
185            shared_by: (!resource.personal).then(|| resource.app_id.clone().unwrap_or_default()),
186            // Always retain the spec from the resource, even if a caller
187            // passed an independently-created spec with the same id.
188            spec: exported.clone(),
189            arguments: Arc::new(arguments),
190        })
191    }
192
193    /// Produce a host-routable intent after strict parameter validation.
194    ///
195    /// # Errors
196    ///
197    /// Returns [`ActionBindingError::InvalidArguments`] if the mapped input
198    /// violates the exported action's parameter contract.
199    pub fn invoke(&self, input: I) -> Result<ControlInvocation, ActionBindingError> {
200        let arguments = (self.arguments)(input).map_err(ActionBindingError::Unbindable)?;
201        self.spec.validate_json(&arguments)?;
202        Ok(ControlInvocation {
203            address: self.address.clone(),
204            arguments,
205        })
206    }
207
208    pub fn address(&self) -> &ActionAddress {
209        &self.address
210    }
211
212    /// The record a control bound here writes into for everyone in the workspace to read, as the
213    /// app publishing it, the resource and its kind: a change to a shared document (a message
214    /// sent into a conversation), never an effect, a view change or the person's own record.
215    #[must_use]
216    pub fn shared_resource(&self) -> Option<(&str, &str, &str)> {
217        let app = self.shared_by.as_deref()?;
218        (self.spec.kind == OperationKind::Document).then_some((
219            app,
220            self.address.resource.as_str(),
221            self.kind.as_str(),
222        ))
223    }
224
225    /// What a control bound to it does, as a window publishes it: the address
226    /// the API runs it by ([`ResourceSpec::address_of`]) — so the row's Complete
227    /// names that row, and what a person presses and what a caller names at
228    /// the API are one thing.
229    #[must_use]
230    pub fn identity(&self) -> ActionAddress {
231        self.address.clone()
232    }
233
234    /// The same binding for a control whose value `J` maps to this one's
235    /// input: a field that reports each edit for a binding that takes the text.
236    #[must_use]
237    pub fn map_input<J>(self, map: impl Fn(J) -> I + Send + Sync + 'static) -> ActionBinding<J>
238    where
239        I: 'static,
240    {
241        let arguments = self.arguments;
242        ActionBinding {
243            address: self.address,
244            kind: self.kind,
245            shared_by: self.shared_by,
246            spec: self.spec,
247            arguments: Arc::new(move |input| arguments(map(input))),
248        }
249    }
250}
251
252impl ActionBinding<()> {
253    /// Bind a nullary control to the action `spec` its declaration publishes
254    /// on `resource`, which no row carries: an effect the resource offers.
255    /// # Errors
256    /// [`ActionBindingError::InvalidArguments`] when `spec` requires an argument.
257    pub fn declared(
258        resource: impl Into<String>,
259        spec: ActionSpec,
260    ) -> Result<Self, ActionBindingError> {
261        let binding = Self {
262            address: ActionAddress::new(resource, spec.id.clone()),
263            kind: String::new(),
264            shared_by: None,
265            spec,
266            arguments: std::sync::Arc::new(|()| Ok(serde_json::Map::new())),
267        };
268        binding.spec.validate_json(&serde_json::Map::new())?;
269        Ok(binding)
270    }
271
272    /// Bind a nullary control to a nullary exported action.
273    pub fn unit(
274        resource: &(impl Exports + ?Sized),
275        spec: &ActionSpec,
276    ) -> Result<Self, ActionBindingError> {
277        let binding = Self::new(resource, spec, |()| serde_json::Map::new())?;
278        // Refuse a required-argument action at construction, not first click.
279        binding.spec.validate_json(&serde_json::Map::new())?;
280        Ok(binding)
281    }
282
283    /// Look up the real exported spec by stable id, then create a nullary
284    /// binding. Useful when the resource is assembled inline or generated.
285    pub fn unit_for(
286        resource: &(impl Exports + ?Sized),
287        action_id: &str,
288    ) -> Result<Self, ActionBindingError> {
289        let spec = resource
290            .exported()
291            .actions
292            .iter()
293            .find(|spec| spec.id == action_id)
294            .ok_or_else(|| ActionBindingError::ActionNotExported {
295                resource: resource.exported().id.0.clone(),
296                action: action_id.to_string(),
297            })?;
298        Self::unit(resource, spec)
299    }
300
301    /// Bind a control to a fixed, strictly validated JSON argument object.
302    pub fn static_json(
303        resource: &(impl Exports + ?Sized),
304        spec: &ActionSpec,
305        arguments: serde_json::Map<String, serde_json::Value>,
306    ) -> Result<Self, ActionBindingError> {
307        let binding = Self::new(resource, spec, move |()| arguments.clone())?;
308        binding
309            .spec
310            .validate_json(&(binding.arguments)(()).map_err(ActionBindingError::Unbindable)?)?;
311        Ok(binding)
312    }
313
314    /// Look up the real exported spec by id, then bind fixed JSON arguments.
315    pub fn static_json_for(
316        resource: &(impl Exports + ?Sized),
317        action_id: &str,
318        arguments: serde_json::Map<String, serde_json::Value>,
319    ) -> Result<Self, ActionBindingError> {
320        let spec = resource
321            .exported()
322            .actions
323            .iter()
324            .find(|spec| spec.id == action_id)
325            .ok_or_else(|| ActionBindingError::ActionNotExported {
326                resource: resource.exported().id.0.clone(),
327                action: action_id.to_string(),
328            })?;
329        Self::static_json(resource, spec, arguments)
330    }
331}
332
333/// The generic parameter name of an argument that is a bare value: an
334/// accessibility set-value, a content hash ([`ActionSpec::prompted_content`]),
335/// a wire `InvokeArgument::Text` before a descriptor says where it goes.
336/// An app's own prompted action names its parameter
337/// ([`ActionSpec::prompted_param`]) and callers ask [`ActionSpec::prompt_param`].
338pub const PROMPTED_PARAM: &str = "value";
339
340/// The text of an argument object that holds exactly one string, whatever it
341/// is called: what a continuation or an accessibility set-value reads of a
342/// prompted action's arguments without knowing the action's own name for it.
343/// The contract of a spec nothing has declared a kind for: its operation's
344/// without the kind, which only the declaration names
345/// ([`ActionSpec::of_kind`]).
346fn unnamed_kind(contract: ActionContract) -> ActionContract {
347    ActionContract {
348        kind: ActionKind::Outside,
349        ..contract
350    }
351}
352
353pub fn sole_text_argument(arguments: &serde_json::Map<String, serde_json::Value>) -> Option<&str> {
354    let mut values = arguments.values();
355    match (values.next(), values.next()) {
356        (Some(serde_json::Value::String(text)), None) => Some(text),
357        _ => None,
358    }
359}
360
361/// Inert envelope produced when the legacy one-field palette cannot satisfy a
362/// typed contract. Hosts recognize it as a refusal; it is never registered or
363/// dispatched as an application operation.
364pub const INVALID_ARGUMENTS_TYPE: &str = "tilo.invalid_arguments";
365
366/// The operation type of the verbs an accessibility surface publishes for a
367/// control: focusing it, pressing it, toggling it or setting its value. They
368/// stand in for the person's own pointer and keyboard, which only the person
369/// at the device invokes, so they need what reading needs; what the control
370/// then does is decided as the control's own action declares it.
371pub const SEMANTIC_OPERATION_TYPE: &str = "tilo.ui.semantic-action";
372
373pub use tilo_action_types::ResourceId;
374
375/// What an action's row shows of the state the action acts on, beside its
376/// label: data, never drawing code. Every surface that lists the action (the
377/// palette, a menu, an agent's listing) reads the same.
378#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(default, deny_unknown_fields)]
380pub struct ActionState {
381    /// A short live status ("On", "Current").
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub badge: Option<String>,
384    /// The action flips the state its badge shows, so choosing it keeps the
385    /// list it was chosen from open on the new state.
386    #[serde(skip_serializing_if = "std::ops::Not::not")]
387    pub toggles: bool,
388    /// The keys that do the same, spelled as the keyboard layout in use
389    /// reads them.
390    #[serde(skip_serializing_if = "Option::is_none")]
391    pub shortcut: Option<String>,
392}
393
394impl ActionState {
395    pub const MAX_BADGE_BYTES: usize = ResourcePresentation::MAX_BADGE_BYTES;
396
397    /// Nothing to show.
398    #[must_use]
399    pub fn is_empty(&self) -> bool {
400        self == &Self::default()
401    }
402
403    /// A row showing `badge`.
404    #[must_use]
405    pub fn badge(badge: impl Into<String>) -> Self {
406        Self {
407            badge: Some(badge.into()),
408            ..Self::default()
409        }
410    }
411}
412
413/// Bounded, declarative search presentation for a resource.
414///
415/// This is data, never app-provided drawing code: the shell chooses the
416/// typography, colours, icons, and layout.
417#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
418#[serde(default, deny_unknown_fields)]
419pub struct ResourcePresentation {
420    pub detail: Option<String>,
421    pub badge: Option<String>,
422    /// Bounded plain-text content for a shell/toolkit-owned preview. Apps
423    /// provide data only; they never control preview pixels or interaction.
424    pub preview: Option<String>,
425}
426
427impl ResourcePresentation {
428    pub const MAX_DETAIL_BYTES: usize = 160;
429    pub const MAX_BADGE_BYTES: usize = 32;
430    pub const MAX_PREVIEW_BYTES: usize = 512;
431
432    #[must_use]
433    pub fn is_valid(&self) -> bool {
434        self.detail
435            .as_ref()
436            .is_none_or(|value| value.len() <= Self::MAX_DETAIL_BYTES && !value.contains('\n'))
437            && self
438                .badge
439                .as_ref()
440                .is_none_or(|value| value.len() <= Self::MAX_BADGE_BYTES && !value.contains('\n'))
441            && self.preview.as_ref().is_none_or(|value| {
442                value.len() <= Self::MAX_PREVIEW_BYTES
443                    && !value
444                        .chars()
445                        .any(|character| matches!(character, '\r' | '\0'))
446            })
447    }
448}
449
450/// How a live resource-view provider accepts a compositor-owned mount.
451///
452/// The named parameters belong to the referenced action's typed contract.
453/// Keeping them explicit avoids inferring view support from conventional
454/// parameter names.
455#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(deny_unknown_fields)]
457pub struct ResourceViewMountSpec {
458    pub action: String,
459    pub capability_param: String,
460    pub view_param: String,
461}
462
463impl ResourceViewMountSpec {
464    pub fn new(
465        action: impl Into<String>,
466        capability_param: impl Into<String>,
467        view_param: impl Into<String>,
468    ) -> Self {
469        Self {
470            action: action.into(),
471            capability_param: capability_param.into(),
472            view_param: view_param.into(),
473        }
474    }
475}
476
477/// Explicit range-navigation binding. Offsets retain the reference's Chars or
478/// Bytes unit; the app validates them against its current text before moving.
479#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
480#[serde(deny_unknown_fields)]
481pub struct ResourceViewRangeSpec {
482    pub action: String,
483    pub start_param: String,
484    pub end_param: String,
485    pub unit_param: String,
486}
487
488impl ResourceViewRangeSpec {
489    pub fn new(action: impl Into<String>) -> Self {
490        Self {
491            action: action.into(),
492            start_param: "start".into(),
493            end_param: "end".into(),
494            unit_param: "unit".into(),
495        }
496    }
497}
498
499/// An explicit presentation of a resource, separate from the actions used to
500/// open or mount it.
501///
502/// `id` is the stable view identity. `open_action` and the optional mount
503/// action are execution bindings and may change without turning every local
504/// [`OperationKind::View`] action into an advertised resource view.
505#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(deny_unknown_fields)]
507pub struct ResourceViewSpec {
508    pub id: String,
509    pub label: String,
510    pub description: Option<String>,
511    pub open_action: String,
512    pub primary: bool,
513    pub mount: Option<ResourceViewMountSpec>,
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub range: Option<ResourceViewRangeSpec>,
516    /// The view opens on the whole desktop, not in its app alone full tab:
517    /// what it shows comes from the desktop's session (a workspace's
518    /// history, say), which a page showing one app does not run. A link to
519    /// it opens the desktop at this view.
520    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
521    pub desktop: bool,
522    /// What a place of the resource shows when it stands as content on its own (a place on the
523    /// canvas, an answer's view) rather than as its app's window: the view the words naming the
524    /// resource, not its app, place it through. At most one view of a resource is so.
525    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
526    pub place: bool,
527}
528
529impl ResourceViewSpec {
530    pub fn new(
531        id: impl Into<String>,
532        label: impl Into<String>,
533        open_action: impl Into<String>,
534    ) -> Self {
535        Self {
536            id: id.into(),
537            label: label.into(),
538            description: None,
539            open_action: open_action.into(),
540            primary: false,
541            mount: None,
542            range: None,
543            desktop: false,
544            place: false,
545        }
546    }
547
548    /// Open it on the whole desktop ([`Self::desktop`]).
549    #[must_use]
550    pub fn on_desktop(mut self) -> Self {
551        self.desktop = true;
552        self
553    }
554
555    #[must_use]
556    pub fn with_description(mut self, description: impl Into<String>) -> Self {
557        self.description = Some(description.into());
558        self
559    }
560
561    #[must_use]
562    pub fn with_primary(mut self, primary: bool) -> Self {
563        self.primary = primary;
564        self
565    }
566
567    /// Make it what a place of the resource shows on its own ([`Self::place`]).
568    #[must_use]
569    pub fn with_place(mut self, place: bool) -> Self {
570        self.place = place;
571        self
572    }
573
574    #[must_use]
575    pub fn with_mount(mut self, mount: ResourceViewMountSpec) -> Self {
576        self.mount = Some(mount);
577        self
578    }
579
580    #[must_use]
581    pub fn with_range(mut self, range: ResourceViewRangeSpec) -> Self {
582        self.range = Some(range);
583        self
584    }
585
586    /// Validate this declaration against the actions exported by `resource`.
587    ///
588    /// Cross-view invariants such as unique open actions and a single primary
589    /// view are checked by [`crate::validate_surface_contracts`].
590    pub fn validate(&self, resource: &ResourceSpec) -> Vec<String> {
591        let mut errors = Vec::new();
592        if self.id.is_empty() || self.id.contains(KEY_SEP) {
593            errors.push("view id is empty or contains the separator".into());
594        }
595        if self.label.trim().is_empty() {
596            errors.push("view label must be non-empty".into());
597        }
598        validate_view_action(resource, &self.open_action, "open", &mut errors);
599        if let Some(mount) = &self.mount {
600            validate_view_action(resource, &mount.action, "mount", &mut errors);
601            if mount.capability_param == mount.view_param {
602                errors.push("mount capability and view parameters must be distinct".into());
603            }
604            if let Some(action) = resource
605                .actions
606                .iter()
607                .find(|action| action.id == mount.action)
608            {
609                for (role, name) in [
610                    ("capability", &mount.capability_param),
611                    ("view", &mount.view_param),
612                ] {
613                    if name.trim().is_empty() {
614                        errors.push(format!("mount {role} parameter must be non-empty"));
615                    } else if !action.params().iter().any(|parameter| {
616                        parameter.name.as_ref() == name
617                            && parameter.ty == ParamType::Text
618                            && !parameter.required
619                    }) {
620                        errors.push(format!(
621                            "mount {role} parameter `{name}` must name an optional text parameter"
622                        ));
623                    }
624                }
625            }
626        }
627        if let Some(range) = &self.range {
628            let names = [&range.start_param, &range.end_param, &range.unit_param];
629            if names.iter().any(|name| name.trim().is_empty())
630                || names[0] == names[1]
631                || names[0] == names[2]
632                || names[1] == names[2]
633            {
634                errors.push("range parameter names must be non-empty and distinct".into());
635            }
636            if let Some(action) = resource.actions.iter().find(|a| a.id == range.action) {
637                if action.kind != OperationKind::View
638                    || action.contract.confirmation != ConfirmationPolicy::None
639                {
640                    errors.push("range action must be a view without confirmation".into());
641                }
642                for (name, ty) in [
643                    (&range.start_param, ParamType::Integer),
644                    (&range.end_param, ParamType::Integer),
645                    (&range.unit_param, ParamType::Text),
646                ] {
647                    if !action
648                        .params()
649                        .iter()
650                        .any(|p| p.name.as_ref() == name && p.ty == ty)
651                    {
652                        errors.push(format!(
653                            "range parameter `{name}` has the wrong type or is missing"
654                        ));
655                    }
656                }
657                if action
658                    .params()
659                    .iter()
660                    .any(|p| p.required && !names.iter().any(|n| p.name.as_ref() == *n))
661                {
662                    errors.push("range action requires unrelated input".into());
663                }
664            } else {
665                errors.push("range action is not exported".into());
666            }
667        }
668        errors
669    }
670}
671
672fn validate_view_action(
673    resource: &ResourceSpec,
674    action_id: &str,
675    role: &str,
676    errors: &mut Vec<String>,
677) {
678    let Some(action) = resource
679        .actions
680        .iter()
681        .find(|action| action.id == action_id)
682    else {
683        errors.push(format!("{role} action `{action_id}` is not exported"));
684        return;
685    };
686    if action.kind != OperationKind::View {
687        errors.push(format!(
688            "{role} action `{action_id}` must be a view operation"
689        ));
690    }
691    if action.contract.confirmation != ConfirmationPolicy::None {
692        errors.push(format!(
693            "{role} action `{action_id}` must not require confirmation"
694        ));
695    }
696    if action.params().iter().any(|parameter| parameter.required) {
697        errors.push(format!(
698            "{role} action `{action_id}` must not require caller parameters"
699        ));
700    }
701}
702
703/// Descriptive source-domain identity, independent of the live dispatch alias.
704/// This metadata grants no permission or authority.
705#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
706pub struct ResourceSemanticIdentity {
707    pub kind: String,
708    pub key: String,
709}
710
711impl ResourceSemanticIdentity {
712    pub const MAX_KIND_BYTES: usize = 128;
713    pub const MAX_KEY_BYTES: usize = 4096;
714
715    #[must_use]
716    pub fn new(kind: impl Into<String>, key: impl Into<String>) -> Option<Self> {
717        let identity = Self {
718            kind: kind.into(),
719            key: key.into(),
720        };
721        identity.is_valid().then_some(identity)
722    }
723
724    #[must_use]
725    pub fn is_valid(&self) -> bool {
726        !self.kind.is_empty()
727            && self.kind.len() <= Self::MAX_KIND_BYTES
728            && self
729                .kind
730                .bytes()
731                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
732            && !self.key.is_empty()
733            && self.key.len() <= Self::MAX_KEY_BYTES
734            && !self.key.chars().any(char::is_control)
735    }
736}
737
738pub use crate::noun::{Noun, ResourceType, action_label, app_label, in_words, plural, singular};
739
740/// Whether `kind` names a control the window already draws, or an
741/// operation of the host it runs on: nodes published so a caller can
742/// address them, never something a person looks for in a list.
743#[must_use]
744pub fn kind_mirrors_a_control(kind: &str) -> bool {
745    kind == "tilo.control"
746        || kind == "tl.host"
747        || ["tilo.control.", "tilo.ui.", "tilo.host."]
748            .iter()
749            .any(|prefix| kind.starts_with(prefix))
750}
751
752/// Whether `kind` names a control the window draws: its press, drag, focus
753/// or value stands in for the pointer and keyboard of the person at the
754/// device. Only that person invokes an action on it; anyone else, an agent
755/// above all, is refused it and never offered it. What a control does that
756/// others need, the app offers as an action of its own.
757#[must_use]
758pub fn kind_is_a_drawn_control(kind: &str) -> bool {
759    kind == "tilo.control"
760        || ["tilo.control.", "tilo.ui."]
761            .iter()
762            .any(|prefix| kind.starts_with(prefix))
763}
764
765/// Whether a resource of `kind` titled `label` is something a person looks
766/// for: titled, and the app's own rather than a mirror of one of its
767/// controls or an operation of the host it runs on. Those are published to
768/// be addressed, never listed.
769#[must_use]
770pub fn listed_for_people(kind: &str, label: &str) -> bool {
771    !label.trim().is_empty() && !kind_mirrors_a_control(kind)
772}
773
774/// What kind of thing an action's one text argument names. Words are
775/// what the asker says outright; a content hash addresses bytes already
776/// in this machine's blob store (nobody types one, it names something
777/// an earlier operation produced). Declared on the spec rather than
778/// inferred, so a caller with no screen can tell "give me a new name"
779/// from "give me the image to place".
780#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
781pub enum Collects {
782    /// Free text, in the words of whoever is asking.
783    #[default]
784    Words,
785    /// The content hash of bytes already in this machine's blob store.
786    Content,
787}
788
789/// How the palette collects an [`ActionSpec`]'s input when it is chosen.
790///
791/// A view of the action's type: the encoding itself comes from the spec
792/// ([`ActionSpec::encode_immediate`], [`ActionSpec::build_deferred`],
793/// [`ActionSpec::build_text`]), which binds the type to the spec's target.
794#[derive(Clone, Copy, Debug, PartialEq, Eq)]
795pub enum ActionInput<'a> {
796    /// Fires at once, with no argument. Holds the encoding made when the
797    /// action was declared, the same for every invocation; `None` for one
798    /// encoded per invocation from its target
799    /// ([`ActionSpec::encode_immediate`]), which a caller holding the
800    /// resource tree resolves by address when it fires, as a deferred one.
801    Immediate(Option<&'a Arc<EncodedAction>>),
802    /// A no-argument operation built only at final admitted owner execution.
803    /// Enumeration and confirmation retain declared intent, not minted bytes.
804    Deferred { type_id: &'a str },
805    /// Collects one free-text argument first, then builds its encoded action.
806    Prompted {
807        prompt: &'a str,
808        placeholder: &'a str,
809        /// What that argument names. See [`Collects`].
810        collects: Collects,
811    },
812}
813
814/// What an action type keeps of how the palette collects its input.
815#[derive(Clone)]
816enum InputMode {
817    /// Fires at once. `Some` holds the encoding made when the action was
818    /// declared (an action with no target, so one encoding for every
819    /// invocation); `None` builds it from the target per invocation.
820    Immediate(Option<Arc<EncodedAction>>),
821    Deferred {
822        type_id: String,
823    },
824    Prompted {
825        prompt: String,
826        placeholder: String,
827        collects: Collects,
828    },
829}
830
831/// What one [`ActionSpec`] acts on: the item its shared [`ActionType`] is
832/// bound to (a note's path, a file's id). An action type's builders receive
833/// it, so the type is held once for every item that offers it. An action
834/// declared with its state captured in its builder has none.
835#[derive(Clone, Default)]
836pub struct Target(Option<Arc<dyn std::any::Any + Send + Sync>>);
837
838impl Target {
839    /// No target: the action's builder holds what it acts on.
840    #[must_use]
841    pub const fn none() -> Self {
842        Self(None)
843    }
844
845    /// `value` as a target. Clone the target to bind several actions of one
846    /// item to the same allocation.
847    #[must_use]
848    pub fn new<T: std::any::Any + Send + Sync>(value: T) -> Self {
849        Self(Some(Arc::new(value)))
850    }
851
852    /// The target, when it is a `T`.
853    #[must_use]
854    pub fn get<T: std::any::Any>(&self) -> Option<&T> {
855        self.0.as_deref()?.downcast_ref()
856    }
857
858    /// Whether `self` and `other` are one target: the same allocation, as
859    /// the specs of one item bound from one target are. Two targets made
860    /// apart are different even when their values are equal, so a resource
861    /// bound anew is told from one kept.
862    #[must_use]
863    pub fn same(&self, other: &Self) -> bool {
864        match (&self.0, &other.0) {
865            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
866            (None, None) => true,
867            _ => false,
868        }
869    }
870}
871
872/// Builds a prompted action's encoded form for one target from its text.
873type TargetTextBuilder = Arc<dyn Fn(&Target, &str) -> EncodedAction + Send + Sync>;
874
875/// Collision-free, provider-defined identity for one continuation target or
876/// handler. Tuple components remain separate; callers never join or hash them.
877#[derive(Clone, Debug, PartialEq, Eq)]
878pub struct ContinuationKey {
879    namespace: String,
880    parts: Vec<Vec<u8>>,
881}
882
883impl ContinuationKey {
884    pub fn new(
885        namespace: impl Into<String>,
886        parts: impl IntoIterator<Item = impl Into<Vec<u8>>>,
887    ) -> Self {
888        Self {
889            namespace: namespace.into(),
890            parts: parts.into_iter().map(Into::into).collect(),
891        }
892    }
893}
894
895pub enum ContinuationArguments<'a> {
896    Immediate,
897    Text(&'a str),
898    Json(&'a serde_json::Map<String, serde_json::Value>),
899}
900
901pub enum ContinuationQuery<'a> {
902    Exact(ContinuationArguments<'a>),
903    Draft,
904}
905
906#[derive(Clone, Debug, PartialEq, Eq)]
907pub enum ContinuationEvidence {
908    Exact {
909        target: ContinuationKey,
910        handler: ContinuationKey,
911    },
912    Draft {
913        resolution_domain: ContinuationKey,
914        handler: ContinuationKey,
915    },
916}
917
918impl ContinuationEvidence {
919    /// Stream unambiguous comparison data without allocating a serialized copy.
920    /// The format is private to comparison consumers, not a wire protocol.
921    pub fn write_canonical_identity(&self, sink: &mut impl std::io::Write) -> std::io::Result<()> {
922        fn length(sink: &mut impl std::io::Write, value: usize) -> std::io::Result<()> {
923            let value = u64::try_from(value).map_err(|_| {
924                std::io::Error::new(std::io::ErrorKind::InvalidInput, "identity length overflow")
925            })?;
926            sink.write_all(&value.to_le_bytes())
927        }
928        fn bytes(sink: &mut impl std::io::Write, value: &[u8]) -> std::io::Result<()> {
929            length(sink, value.len())?;
930            sink.write_all(value)
931        }
932        fn key(sink: &mut impl std::io::Write, value: &ContinuationKey) -> std::io::Result<()> {
933            bytes(sink, value.namespace.as_bytes())?;
934            length(sink, value.parts.len())?;
935            for part in &value.parts {
936                bytes(sink, part)?;
937            }
938            Ok(())
939        }
940        sink.write_all(b"tilo.continuation-identity\0v1")?;
941        match self {
942            Self::Exact { target, handler } => {
943                sink.write_all(&[0])?;
944                key(sink, target)?;
945                key(sink, handler)
946            }
947            Self::Draft {
948                resolution_domain,
949                handler,
950            } => {
951                sink.write_all(&[1])?;
952                key(sink, resolution_domain)?;
953                key(sink, handler)
954            }
955        }
956    }
957}
958
959type ContinuationResolver =
960    Arc<dyn for<'a> Fn(ContinuationQuery<'a>) -> Option<ContinuationEvidence> + Send + Sync>;
961
962#[derive(Clone)]
963enum InvocationBuilder {
964    Fixed(Arc<EncodedAction>),
965    Dynamic {
966        build: ArgsBuilder,
967        deferred_type: Option<String>,
968    },
969    /// A prompted action's builder of its one text, which the typed input mode
970    /// reads from the action's [`prompt parameter`](ActionSpec::prompt_param).
971    Text(TargetTextBuilder),
972}
973
974/// The facet naming the nested resource an action was addressed through,
975/// when history names the enclosing resource whose action it is
976/// ([`ActionSpec::history_context`]).
977pub const NESTED_RESOURCE_FACET: &str = "part";
978
979/// What an action is, whichever resource offers it: its id, label, contract,
980/// parameters and builders. Held once per (resource type, action) and shared
981/// by every [`ActionSpec`] that binds it to a [`Target`].
982///
983/// Read through the spec (`spec.label`, `spec.contract`); change one spec's
984/// with [`ActionSpec::type_mut`], which copies a shared type first.
985#[derive(Clone)]
986pub struct ActionType {
987    /// Stable id within the resource (e.g. `"like"`, `"reply"`).
988    pub id: String,
989    /// The id a change this action makes says it by, where that is not `id`: an app that offers
990    /// its actions under a name (a tilolang app's `new_note`) records the declaration's id
991    /// (`qymo5lg2`) in its changes, and history reads this action's label for them. Empty where
992    /// the two are the same, as for a native verb.
993    pub declared: String,
994    pub label: String,
995    /// The other words people use for this action, in plain language
996    /// ("mkdir" and "make directory" for New folder): search finds the
997    /// action by them as it does by its label. Declared with the label, so
998    /// every surface that lists the action knows them; never a list kept
999    /// inside a search provider.
1000    pub keywords: Vec<String>,
1001    /// What the action did, in the app's own words, said after who did it
1002    /// ("showed this on the canvas", "added a subtask"): the past-tense form a
1003    /// record of what was done reads, declared beside the label rather than
1004    /// made from it. `None` where the app declares none; a record then names
1005    /// the action by its label.
1006    pub did: Option<String>,
1007    /// The action's own picture beside its label, by its Lucide name.
1008    pub icon: Option<String>,
1009    pub description: Option<String>,
1010    /// What the action's row shows of the state it acts on: its badge,
1011    /// whether it flips that state in place, its shortcut. Published with
1012    /// the action and published anew whenever that state changes.
1013    pub state: ActionState,
1014    /// Declared execution locus (mirrors the concrete action's
1015    /// [`Action::locus`]), so the palette can show/route it before the
1016    /// action is built.
1017    pub locus: ExecutionLocus,
1018    /// Whether this mutates the shared document, performs an external effect,
1019    /// or changes only the invoking application's local view.
1020    pub kind: OperationKind,
1021    /// The single protocol type routed for an effect/view operation. Keeping
1022    /// this beside the descriptor lets the host prove that publication and
1023    /// the widget's handler registry agree, including prompted operations
1024    /// whose encoded value does not exist until arguments are bound.
1025    pub operation_type: Option<String>,
1026    /// Machine-readable safety, availability, lifecycle, and result contract.
1027    pub contract: ActionContract,
1028    /// How the palette collects the input. See [`ActionSpec::input`].
1029    input: InputMode,
1030    /// The typed argument surface an external caller invokes against. Private
1031    /// because it must stay in step with `build` — the two are always set
1032    /// together by a constructor, never independently.
1033    pub(crate) params: Vec<ActionParam>,
1034    /// Builds the encoded action from arguments bound against `params`. The
1035    /// palette's input mode uses the same closure, which is what makes the palette
1036    /// path and the external path provably one function.
1037    build: InvocationBuilder,
1038    /// Classifies one invocation's bound arguments when the action's risk
1039    /// depends on them. See [`ActionSpec::with_risk`].
1040    risk_of: Option<RiskClassifier>,
1041    /// Decides from one invocation's bound arguments whether Undo takes it
1042    /// back, when that depends on them. See [`ActionSpec::with_undo_of`].
1043    undo_of: Option<UndoClassifier>,
1044    /// Classifies what one invocation's bound arguments are, for the grants
1045    /// deciding it. See [`ActionSpec::with_need_of`].
1046    need_of: Option<NeedClassifier>,
1047    continuation_resolver: Option<ContinuationResolver>,
1048    /// Whether the action carries any of its resource's other actions (a
1049    /// generic edit, a group) rather than being a verb of its own. See
1050    /// [`ActionSpec::carrying`].
1051    carrier: bool,
1052    /// The kind and label of the enclosing resource whose action this one
1053    /// applies as, for a nested resource's action. See
1054    /// [`ActionSpec::applied_as`].
1055    applied_as: Option<(String, String)>,
1056    /// The provider that publishes and runs the action, when it is not the
1057    /// resource's publisher, and the resource it publishes it on there when
1058    /// another than the one it is offered on here: a view binds its
1059    /// controls to another provider's action ([`ActionSpec::run_by`]).
1060    provider: Option<Arc<RunBy>>,
1061}
1062
1063/// Where another provider runs an action a view offers
1064/// ([`ActionSpec::run_by`]).
1065#[derive(Clone, Debug, PartialEq)]
1066pub struct RunBy {
1067    /// The provider that publishes and runs it.
1068    pub provider: String,
1069    /// The resource it publishes it on, when another than the one it is
1070    /// offered on here (a row's operation on a record the provider keeps).
1071    pub resource: Option<String>,
1072    /// The action it publishes and the arguments this one fixes of it,
1073    /// when it is offered here as another (a bound edit of its field edit).
1074    pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
1075}
1076
1077impl ActionType {
1078    /// This type bound to `target`: the action one item offers.
1079    #[must_use]
1080    pub fn bind(self: &Arc<Self>, target: Target) -> ActionSpec {
1081        ActionSpec {
1082            ty: Arc::clone(self),
1083            target,
1084            bound: None,
1085        }
1086    }
1087
1088    fn encode(&self, target: &Target, args: &ActionArgs) -> EncodedAction {
1089        match &self.build {
1090            InvocationBuilder::Fixed(encoded) => encoded.as_ref().clone(),
1091            InvocationBuilder::Dynamic { build, .. } => build(target, args),
1092            InvocationBuilder::Text(build) => {
1093                let text = primary_param(&self.params)
1094                    .and_then(|param| args.text(&param.name))
1095                    .unwrap_or("");
1096                build(target, text)
1097            }
1098        }
1099    }
1100}
1101
1102/// One action a resource exports to the palette: an [`ActionType`] bound to
1103/// the [`Target`] it acts on. Small: the type is shared, so a resource of
1104/// ten thousand items holds each of its types once.
1105///
1106/// It reads as its type (`spec.id`, `spec.contract`).
1107#[derive(Clone)]
1108pub struct ActionSpec {
1109    ty: Arc<ActionType>,
1110    target: Target,
1111    /// The arguments this action fixes, when it is a declaration offered on
1112    /// the item it acts on, and so not among `params`: the item's, as its
1113    /// target is, so the type stays shared. See [`ActionSpec::with_bound`].
1114    bound: Option<Arc<[(String, serde_json::Value)]>>,
1115}
1116
1117impl std::ops::Deref for ActionSpec {
1118    type Target = ActionType;
1119
1120    fn deref(&self) -> &ActionType {
1121        &self.ty
1122    }
1123}
1124
1125/// Classifies the risk of one invocation from its bound arguments.
1126/// The [`Target`] is that of the spec being invoked.
1127pub type RiskClassifier = Arc<dyn Fn(&Target, &ActionArgs) -> RiskLevel + Send + Sync>;
1128
1129/// Decides from one invocation's bound arguments whether Undo takes it back.
1130pub type UndoClassifier = Arc<dyn Fn(&ActionArgs) -> bool + Send + Sync>;
1131
1132/// Classifies what one invocation is from its bound arguments.
1133/// The [`Target`] is that of the spec being invoked.
1134pub type NeedClassifier = Arc<dyn Fn(&Target, &ActionArgs) -> ActionNeed + Send + Sync>;
1135
1136struct TypedActionSeed {
1137    id: String,
1138    label: String,
1139    placeholder: String,
1140    locus: ExecutionLocus,
1141    kind: OperationKind,
1142    operation_type: Option<String>,
1143    params: Vec<ActionParam>,
1144}
1145
1146/// What a constructor declares of a new action type before its input mode and
1147/// builder.
1148struct Declared {
1149    id: String,
1150    label: String,
1151    locus: ExecutionLocus,
1152    kind: OperationKind,
1153    operation_type: Option<String>,
1154    params: Vec<ActionParam>,
1155}
1156
1157impl Declared {
1158    fn new(id: String, label: String, locus: ExecutionLocus, kind: OperationKind) -> Self {
1159        Self {
1160            id,
1161            label,
1162            locus,
1163            kind,
1164            operation_type: None,
1165            params: Vec::new(),
1166        }
1167    }
1168}
1169
1170impl ActionSpec {
1171    fn of(ty: ActionType) -> Self {
1172        Self {
1173            ty: Arc::new(ty),
1174            target: Target::none(),
1175            bound: None,
1176        }
1177    }
1178
1179    /// The type this spec binds: what every resource offering the action
1180    /// shares. Bind it to other targets with [`ActionType::bind`].
1181    #[must_use]
1182    pub fn action_type(&self) -> &Arc<ActionType> {
1183        &self.ty
1184    }
1185
1186    /// What this spec acts on.
1187    #[must_use]
1188    pub fn target(&self) -> &Target {
1189        &self.target
1190    }
1191
1192    /// This spec's type, to change: copied first when other specs share it,
1193    /// so a change to one item's action never reaches another's.
1194    pub fn type_mut(&mut self) -> &mut ActionType {
1195        Arc::make_mut(&mut self.ty)
1196    }
1197
1198    /// How the palette collects this action's input.
1199    #[must_use]
1200    pub fn input(&self) -> ActionInput<'_> {
1201        match &self.input {
1202            InputMode::Immediate(encoded) => ActionInput::Immediate(encoded.as_ref()),
1203            InputMode::Deferred { type_id } => ActionInput::Deferred { type_id },
1204            InputMode::Prompted {
1205                prompt,
1206                placeholder,
1207                collects,
1208            } => ActionInput::Prompted {
1209                prompt,
1210                placeholder,
1211                collects: *collects,
1212            },
1213        }
1214    }
1215
1216    /// The action an [`Immediate`](ActionInput::Immediate) spec fires, or
1217    /// `None` for one that takes input or is deferred. An action declared
1218    /// with what it acts on in its builder was encoded once, when declared;
1219    /// one bound to a target is encoded for it now.
1220    #[must_use]
1221    pub fn encode_immediate(&self) -> Option<Arc<EncodedAction>> {
1222        match &self.input {
1223            InputMode::Immediate(Some(encoded)) => Some(Arc::clone(encoded)),
1224            InputMode::Immediate(None) => {
1225                Some(Arc::new(self.ty.encode(&self.target, &ActionArgs::none())))
1226            }
1227            InputMode::Deferred { .. } | InputMode::Prompted { .. } => None,
1228        }
1229    }
1230
1231    /// The encoding an [`Immediate`](ActionInput::Immediate) spec already holds, when it was
1232    /// encoded once and shared by every resource offering it; `None` for one built from its
1233    /// target when it is invoked. Reads, never builds: validating a surface of ten thousand
1234    /// items runs no action.
1235    #[must_use]
1236    pub fn published_encoding(&self) -> Option<&Arc<EncodedAction>> {
1237        match &self.input {
1238            InputMode::Immediate(encoded) => encoded.as_ref(),
1239            InputMode::Deferred { .. } | InputMode::Prompted { .. } => None,
1240        }
1241    }
1242
1243    /// Run a [`Deferred`](ActionInput::Deferred) spec's builder, unchecked:
1244    /// `None` for any other. Callers check the result's type against the
1245    /// declared one, as the API does.
1246    #[must_use]
1247    pub fn build_deferred(&self) -> Option<EncodedAction> {
1248        match &self.input {
1249            InputMode::Deferred { .. } => Some(self.ty.encode(&self.target, &ActionArgs::none())),
1250            InputMode::Immediate(_) | InputMode::Prompted { .. } => None,
1251        }
1252    }
1253
1254    /// This action as `provider` publishes and runs it: a view shows another
1255    /// provider's resource and binds its controls to that provider's
1256    /// actions. The view's publisher never runs nor publishes it; its host
1257    /// invokes it at `provider`, which admits and runs it as any caller's.
1258    #[must_use]
1259    pub fn run_by(self, provider: impl Into<String>) -> Self {
1260        self.run_as(RunBy {
1261            provider: provider.into(),
1262            resource: None,
1263            invokes: None,
1264        })
1265    }
1266
1267    /// [`Self::run_by`] as `run` says where the provider publishes it.
1268    #[must_use]
1269    pub fn run_as(mut self, run: RunBy) -> Self {
1270        self.type_mut().provider = Some(Arc::new(run));
1271        self
1272    }
1273
1274    /// Where another provider than the resource's publisher runs this
1275    /// action ([`Self::run_by`]).
1276    #[must_use]
1277    pub fn run_by_provider(&self) -> Option<&RunBy> {
1278        self.provider.as_deref()
1279    }
1280
1281    /// The provider that runs this action, when it is another than the
1282    /// resource's publisher ([`Self::run_by`]).
1283    #[must_use]
1284    pub fn provider(&self) -> Option<&str> {
1285        self.provider.as_deref().map(|run| run.provider.as_str())
1286    }
1287
1288    /// Mark this action as applied as the enclosing resource of kind `kind`
1289    /// (labelled `label`): a nested resource (a note's rich-text body)
1290    /// publishes its document actions re-encoded as the record's field
1291    /// edit, so the record's surface, permissions and history decide them.
1292    #[must_use]
1293    pub fn applied_as(mut self, kind: impl Into<String>, label: impl Into<String>) -> Self {
1294        if self.kind == OperationKind::Document {
1295            self.type_mut().applied_as = Some((kind.into(), label.into()));
1296        }
1297        self
1298    }
1299
1300    /// The history entry of invoking this action on the resource `id`, of
1301    /// kind `kind` and labelled `label`. It names that resource, of the kind
1302    /// whose action the value is: for a nested resource's action, the
1303    /// enclosing resource's kind and label, with the nested resource kept as
1304    /// a [`NESTED_RESOURCE_FACET`] facet. Naming the nested kind made the
1305    /// change claim a kind its app's surface does not describe, so every
1306    /// receiver held it and the signer refused it.
1307    #[must_use]
1308    pub fn history_context(&self, id: &str, kind: &str, label: &str) -> crate::ActionContext {
1309        match &self.applied_as {
1310            Some((owner_kind, owner_label)) => {
1311                let mut context = crate::ActionContext::for_resource(id, owner_kind, owner_label);
1312                context
1313                    .facets
1314                    .push(crate::ActionFacet::new(NESTED_RESOURCE_FACET, label));
1315                context
1316            }
1317            None => crate::ActionContext::for_resource(id, kind, label),
1318        }
1319    }
1320
1321    /// Borrow the actual fixed encoding used by the typed invocation builder.
1322    /// `None` means the builder is opaque, even if its palette input is Immediate.
1323    /// This is comparison data, never permission to invoke an action.
1324    pub fn fixed_invocation_encoding(&self) -> Option<&EncodedAction> {
1325        match &self.build {
1326            InvocationBuilder::Fixed(encoded) => Some(encoded),
1327            InvocationBuilder::Dynamic { .. } | InvocationBuilder::Text(_) => None,
1328        }
1329    }
1330
1331    /// Whether a provider installed continuation evidence. An installed provider
1332    /// returning unknown is distinct from having no provider.
1333    pub fn has_continuation_identity(&self) -> bool {
1334        self.continuation_resolver.is_some()
1335    }
1336
1337    /// Declared type of an explicit deferred invocation. This is inert metadata,
1338    /// never an encoding or authorization to execute the retained builder.
1339    pub fn deferred_invocation_type(&self) -> Option<&str> {
1340        match &self.build {
1341            InvocationBuilder::Dynamic { deferred_type, .. } => deferred_type.as_deref(),
1342            InvocationBuilder::Fixed(_) | InvocationBuilder::Text(_) => None,
1343        }
1344    }
1345
1346    pub(crate) fn validate_deferred_shape(&self) -> Result<(), ArgError> {
1347        match (&self.input, self.deferred_invocation_type()) {
1348            (InputMode::Deferred { type_id }, Some(expected))
1349                if !type_id.is_empty()
1350                    && type_id == expected
1351                    && self.params.is_empty()
1352                    && match self.kind {
1353                        OperationKind::Document => self.operation_type.is_none(),
1354                        OperationKind::Effect | OperationKind::View => {
1355                            self.operation_type.as_deref() == Some(expected)
1356                        }
1357                    } =>
1358            {
1359                Ok(())
1360            }
1361            (InputMode::Deferred { .. }, _) | (_, Some(_)) => Err(ArgError::Constraint {
1362                name: "deferred".into(),
1363                reason: "deferred input and retained declaration disagree".into(),
1364            }),
1365            (_, None) => Ok(()),
1366        }
1367    }
1368
1369    fn validate_built(&self, encoded: EncodedAction) -> Result<EncodedAction, ArgError> {
1370        // A refusal carries the builder's reason to the caller, as a typed
1371        // action's does.
1372        if let Some(expected) = self.deferred_invocation_type()
1373            && encoded.type_id != expected
1374            && encoded.type_id != INVALID_ARGUMENTS_TYPE
1375        {
1376            return Err(ArgError::Constraint {
1377                name: "deferred".into(),
1378                reason: format!(
1379                    "builder returned `{}` but declared `{expected}`",
1380                    encoded.type_id
1381                ),
1382            });
1383        }
1384        Ok(encoded)
1385    }
1386
1387    /// Strict argument validation without invoking an encoder.
1388    pub fn validate_json(
1389        &self,
1390        supplied: &serde_json::Map<String, serde_json::Value>,
1391    ) -> Result<(), ArgError> {
1392        self.validate_deferred_shape()?;
1393        ActionArgs::bind_json(&self.params, self.without_bound(supplied)?.as_ref()).map(|_| ())
1394    }
1395
1396    /// The arguments this action fixes ([`Self::with_bound`]), by name.
1397    #[must_use]
1398    pub fn bound(&self) -> &[(String, serde_json::Value)] {
1399        self.bound.as_deref().unwrap_or_default()
1400    }
1401
1402    /// This action fixing `values`: a declaration offered on the item it
1403    /// acts on ("rename *this* album"), its item parameter bound and left
1404    /// out of [`Self::params`]. A caller that passes a bound argument anyway
1405    /// is heard as leaving it out when it names the bound value (an item's
1406    /// id also in a longer form of the item's address, `sheets/<id>`), and
1407    /// refused, naming the bound value, when it names another: the action
1408    /// acts on its item only.
1409    #[must_use]
1410    pub fn with_bound(mut self, values: Vec<(String, serde_json::Value)>) -> Self {
1411        self.bound = (!values.is_empty()).then(|| values.into());
1412        self
1413    }
1414
1415    /// The bound argument `name`, stated in what this action publishes: an
1416    /// optional parameter whose only accepted value is the one this action
1417    /// is bound to, described as `description`. A row of a person's own
1418    /// window invokes it without naming anything — it is bound here — while
1419    /// a caller reading the published action learns which item this one is
1420    /// bound to, and answers that one among several a page or a list
1421    /// publishes side by side. Calling it again for another name states that
1422    /// one beside the first, so a row can state every value it is bound to.
1423    ///
1424    /// Nothing an invocation carries changes: the value invocations run is
1425    /// still the bound one ([`Self::with_bound`]), and naming it is how a
1426    /// caller says which of several bound rows it means.
1427    #[must_use]
1428    pub fn stating_bound(mut self, name: &str, description: &str) -> Self {
1429        let Some((_, value)) = self.bound().iter().find(|(bound, _)| bound == name) else {
1430            return self;
1431        };
1432        let value = match value {
1433            serde_json::Value::String(text) => text.clone(),
1434            other => other.to_string(),
1435        };
1436        let ty = Arc::make_mut(&mut self.ty);
1437        let stated = crate::ActionParam {
1438            name: name.to_owned().into(),
1439            ty: crate::ParamType::Text,
1440            required: false,
1441            entry: false,
1442            description: description.to_owned().into(),
1443            choices: vec![value.into()],
1444            schema: None,
1445            nullable: false,
1446        };
1447        match ty.params.iter_mut().find(|param| param.name == name) {
1448            Some(param) => *param = stated,
1449            None => ty.params.push(stated),
1450        }
1451        self
1452    }
1453
1454    /// `supplied` without the bound arguments it repeats
1455    /// ([`Self::with_bound`]).
1456    fn without_bound<'a>(
1457        &self,
1458        supplied: &'a serde_json::Map<String, serde_json::Value>,
1459    ) -> Result<std::borrow::Cow<'a, serde_json::Map<String, serde_json::Value>>, ArgError> {
1460        let repeated: Vec<&(String, serde_json::Value)> = self
1461            .bound()
1462            .iter()
1463            .filter(|(name, _)| supplied.contains_key(name))
1464            .collect();
1465        if repeated.is_empty() {
1466            return Ok(std::borrow::Cow::Borrowed(supplied));
1467        }
1468        let mut kept = supplied.clone();
1469        for (name, value) in repeated {
1470            let given = kept.remove(name).unwrap_or_default();
1471            check_bound(name, value, &given)?;
1472        }
1473        Ok(std::borrow::Cow::Owned(kept))
1474    }
1475
1476    /// `supplied` pairs without the bound arguments they repeat.
1477    fn pairs_without_bound(
1478        &self,
1479        supplied: impl IntoIterator<Item = (String, ArgValue)>,
1480    ) -> Result<Vec<(String, ArgValue)>, ArgError> {
1481        let mut kept = Vec::new();
1482        for (name, given) in supplied {
1483            match self.bound().iter().find(|(bound, _)| *bound == name) {
1484                Some((_, value)) => check_bound(&name, value, &given.to_json())?,
1485                None => kept.push((name, given)),
1486            }
1487        }
1488        Ok(kept)
1489    }
1490
1491    /// The spec of a newly declared type, bound to no target.
1492    fn declared(
1493        seed: Declared,
1494        contract: ActionContract,
1495        input: InputMode,
1496        build: InvocationBuilder,
1497    ) -> Self {
1498        Self::of(ActionType {
1499            id: seed.id,
1500            declared: String::new(),
1501            label: seed.label,
1502            keywords: Vec::new(),
1503            did: None,
1504            icon: None,
1505            description: None,
1506            state: ActionState::default(),
1507            locus: seed.locus,
1508            kind: seed.kind,
1509            operation_type: seed.operation_type,
1510            contract,
1511            input,
1512            params: seed.params,
1513            build,
1514            risk_of: None,
1515            undo_of: None,
1516            need_of: None,
1517            continuation_resolver: None,
1518            carrier: false,
1519            applied_as: None,
1520            provider: None,
1521        })
1522    }
1523
1524    /// A document operation whose no-argument builder runs only at execution.
1525    /// Both invocation input modes share this one closure; construction never runs it.
1526    pub fn deferred(
1527        id: impl Into<String>,
1528        label: impl Into<String>,
1529        locus: ExecutionLocus,
1530        type_id: impl Into<String>,
1531        build: impl Fn() -> EncodedAction + Send + Sync + 'static,
1532    ) -> Self {
1533        Self::deferred_on(id, label, locus, type_id, move |_| build())
1534    }
1535
1536    /// [`deferred`](Self::deferred) for a type shared by many targets: the
1537    /// builder is given the target of the spec being invoked.
1538    pub fn deferred_on(
1539        id: impl Into<String>,
1540        label: impl Into<String>,
1541        locus: ExecutionLocus,
1542        type_id: impl Into<String>,
1543        build: impl Fn(&Target) -> EncodedAction + Send + Sync + 'static,
1544    ) -> Self {
1545        Self::deferred_with_kind(
1546            Declared::new(id.into(), label.into(), locus, OperationKind::Document),
1547            type_id.into(),
1548            build,
1549        )
1550    }
1551
1552    /// An effect/view operation with deferred no-argument encoding.
1553    pub fn deferred_operation(
1554        id: impl Into<String>,
1555        label: impl Into<String>,
1556        kind: OperationKind,
1557        type_id: impl Into<String>,
1558        build: impl Fn() -> EncodedAction + Send + Sync + 'static,
1559    ) -> Self {
1560        Self::deferred_with_kind(
1561            Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind),
1562            type_id.into(),
1563            move |_| build(),
1564        )
1565    }
1566
1567    fn deferred_with_kind(
1568        mut seed: Declared,
1569        type_id: String,
1570        build: impl Fn(&Target) -> EncodedAction + Send + Sync + 'static,
1571    ) -> Self {
1572        seed.operation_type = (seed.kind != OperationKind::Document).then(|| type_id.clone());
1573        let contract = ActionContract::for_operation(seed.kind);
1574        Self::declared(
1575            seed,
1576            contract,
1577            InputMode::Deferred {
1578                type_id: type_id.clone(),
1579            },
1580            InvocationBuilder::Dynamic {
1581                build: Arc::new(move |target, _| build(target)),
1582                deferred_type: Some(type_id),
1583            },
1584        )
1585    }
1586
1587    /// An action that fires immediately with `encoded`, declared as `seed`
1588    /// under `contract`.
1589    fn fixed(seed: Declared, contract: ActionContract, encoded: EncodedAction) -> Self {
1590        let encoded = Arc::new(encoded);
1591        Self::declared(
1592            seed,
1593            contract,
1594            InputMode::Immediate(Some(Arc::clone(&encoded))),
1595            InvocationBuilder::Fixed(encoded),
1596        )
1597    }
1598
1599    /// An action that fires immediately. `type_id` must match the app's
1600    /// registry registration for `A`.
1601    ///
1602    /// Projects to zero parameters: invoking it externally with an empty
1603    /// argument set yields exactly the pre-encoded action the palette fires.
1604    ///
1605    /// # Errors
1606    ///
1607    /// Returns [`ActionError`] when `action` cannot be encoded.
1608    pub fn immediate<A>(
1609        id: impl Into<String>,
1610        label: impl Into<String>,
1611        type_id: impl Into<String>,
1612        action: &A,
1613    ) -> Result<Self, ActionError>
1614    where
1615        A: Action + serde::Serialize,
1616    {
1617        let locus = action.locus();
1618        let encoded = EncodedAction::encode(type_id, action)?;
1619        Ok(Self::fixed(
1620            Declared::new(id.into(), label.into(), locus, OperationKind::Document),
1621            unnamed_kind(ActionContract::default()),
1622            encoded,
1623        ))
1624    }
1625
1626    /// An action that fires immediately, from an [`EncodedAction`] the caller
1627    /// already holds.
1628    ///
1629    /// [`immediate`](Self::immediate) is the usual API — it takes a typed
1630    /// action and reads its [`locus`](Action::locus) — but a caller that has
1631    /// only the encoded form (a stored action, a fixture, one that arrived over
1632    /// a wire) has no typed value to hand it. Projects to zero parameters, the
1633    /// same as `immediate`.
1634    pub fn immediate_encoded(
1635        id: impl Into<String>,
1636        label: impl Into<String>,
1637        locus: ExecutionLocus,
1638        encoded: EncodedAction,
1639    ) -> Self {
1640        Self::fixed(
1641            Declared::new(id.into(), label.into(), locus, OperationKind::Document),
1642            unnamed_kind(ActionContract::default()),
1643            encoded,
1644        )
1645    }
1646
1647    /// An action that first collects a free-text argument, then builds its
1648    /// encoded action from it, the argument being the parameter `param`:
1649    /// `ActionParam::required("title", ParamType::Text, "The note's new
1650    /// title")`. The name and description are what an agent reads, and the
1651    /// description is also the palette's prompt.
1652    ///
1653    /// The projection and the palette share the *same* `build` closure, so an
1654    /// external invocation and the on-screen affordance produce the
1655    /// byte-identical [`EncodedAction`]. Callers that hold the typed text
1656    /// find where it goes with [`Self::prompt_param`], never by name. Name the
1657    /// parameter for what it is (`title`, `name`, `comment`): an agent reads
1658    /// it, and the generic [`PROMPTED_PARAM`] tells it nothing.
1659    pub fn prompted_param(
1660        id: impl Into<String>,
1661        label: impl Into<String>,
1662        param: ActionParam,
1663        placeholder: impl Into<String>,
1664        locus: ExecutionLocus,
1665        build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
1666    ) -> Self {
1667        Self::prompted_param_on(id, label, param, placeholder, locus, move |_, text| {
1668            build(text)
1669        })
1670    }
1671
1672    /// [`prompted_param`](Self::prompted_param) for a type shared by many
1673    /// targets: the builder is given the target of the spec being invoked.
1674    pub fn prompted_param_on(
1675        id: impl Into<String>,
1676        label: impl Into<String>,
1677        param: ActionParam,
1678        placeholder: impl Into<String>,
1679        locus: ExecutionLocus,
1680        build: impl Fn(&Target, &str) -> EncodedAction + Send + Sync + 'static,
1681    ) -> Self {
1682        let mut seed = Declared::new(id.into(), label.into(), locus, OperationKind::Document);
1683        let prompt = param.description.to_string();
1684        seed.params = vec![param];
1685        Self::declared(
1686            seed,
1687            unnamed_kind(ActionContract::default()),
1688            InputMode::Prompted {
1689                prompt,
1690                placeholder: placeholder.into(),
1691                collects: Collects::Words,
1692            },
1693            InvocationBuilder::Text(Arc::new(build)),
1694        )
1695    }
1696
1697    /// The name of the parameter the typed text of a prompted action goes
1698    /// into, or `None` for an action that collects no text. The one place a
1699    /// caller holding the text of a prompt (the palette, a broker request, a
1700    /// continuation) learns where it belongs.
1701    pub fn prompt_param(&self) -> Option<&str> {
1702        match self.input {
1703            InputMode::Prompted { .. } => {
1704                primary_param(self.params()).map(|param| param.name.as_ref())
1705            }
1706            _ => None,
1707        }
1708    }
1709
1710    /// The parameter one line of typed text fills, when the action is a
1711    /// capture: it declares one ([`ActionParam::entry`]).
1712    #[must_use]
1713    pub fn entry_param(&self) -> Option<&str> {
1714        self.params()
1715            .iter()
1716            .find(|param| param.entry)
1717            .map(|param| param.name.as_ref())
1718    }
1719
1720    /// `text` as this action's typed arguments, when it is a prompted action.
1721    pub fn prompt_arguments(
1722        &self,
1723        text: &str,
1724    ) -> Option<serde_json::Map<String, serde_json::Value>> {
1725        let name = self.prompt_param()?;
1726        let mut arguments = serde_json::Map::new();
1727        arguments.insert(name.to_owned(), serde_json::Value::String(text.to_owned()));
1728        Some(arguments)
1729    }
1730
1731    /// An immediate effect or view operation owned by the application.
1732    ///
1733    /// # Errors
1734    ///
1735    /// Returns [`ActionError::Encode`] if `payload` fails to serialize.
1736    pub fn operation<T>(
1737        id: impl Into<String>,
1738        label: impl Into<String>,
1739        kind: OperationKind,
1740        type_id: impl Into<String>,
1741        payload: &T,
1742    ) -> Result<Self, ActionError>
1743    where
1744        T: serde::Serialize,
1745    {
1746        debug_assert_ne!(kind, OperationKind::Document);
1747        let type_id = type_id.into();
1748        let encoded = EncodedAction::encode_operation(type_id.clone(), payload)?;
1749        let mut seed = Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind);
1750        seed.operation_type = Some(type_id);
1751        Ok(Self::fixed(
1752            seed,
1753            ActionContract::for_operation(kind),
1754            encoded,
1755        ))
1756    }
1757
1758    /// A prompted effect or view operation owned by the application.
1759    pub fn prompted_operation(
1760        id: impl Into<String>,
1761        label: impl Into<String>,
1762        prompt: impl Into<String>,
1763        placeholder: impl Into<String>,
1764        kind: OperationKind,
1765        type_id: impl Into<String>,
1766        build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
1767    ) -> Self {
1768        debug_assert_ne!(kind, OperationKind::Document);
1769        let prompt = prompt.into();
1770        let type_id = type_id.into();
1771        let expected = type_id.clone();
1772        let mut seed = Declared::new(id.into(), label.into(), ExecutionLocus::ClientLocal, kind);
1773        seed.operation_type = Some(type_id);
1774        seed.params = vec![ActionParam::required_owned(
1775            PROMPTED_PARAM,
1776            ParamType::Text,
1777            prompt.clone(),
1778        )];
1779        Self::declared(
1780            seed,
1781            ActionContract::for_operation(kind),
1782            InputMode::Prompted {
1783                prompt,
1784                placeholder: placeholder.into(),
1785                collects: Collects::Words,
1786            },
1787            InvocationBuilder::Text(Arc::new(move |_, value| {
1788                enforce_operation_type(build(value), &expected)
1789            })),
1790        )
1791    }
1792
1793    /// An action with a real typed argument surface. Framework-internal: the
1794    /// declaration macros and the tilolang publisher build specs, never an app.
1795    ///
1796    /// This is the constructor for an argument that has a *type* — a number in
1797    /// `0..=1`, a rate, one of a fixed set of filter names — rather than prose
1798    /// a lenient parser guesses at. [`ActionArgs::bind`] enforces the
1799    /// declaration, so a caller that sends `"hlaf"` for a choice parameter gets
1800    /// a named refusal instead of a silent default.
1801    ///
1802    /// The palette can still offer it. Its [`input`](Self::input) is derived
1803    /// from `params`:
1804    ///
1805    /// * no parameters → [`Immediate`](ActionInput::Immediate) of the action
1806    ///   `build` returns for an empty argument set;
1807    /// * otherwise → [`Prompted`](ActionInput::Prompted) collecting the
1808    ///   *primary* parameter (the first required one, else the first), parsed
1809    ///   into its declared type.
1810    ///
1811    /// A palette entry is one text field, so for a multi-parameter action it
1812    /// can only carry the primary argument and the rest are left unbound —
1813    /// which is why `build` sees `ActionArgs` and decides what an absent
1814    /// optional means. Text the palette cannot parse into the primary
1815    /// parameter's type is likewise left unbound rather than coerced; only the
1816    /// keyboard path can be that lossy, and the external path stays strict.
1817    #[doc(hidden)]
1818    pub fn typed(
1819        id: impl Into<String>,
1820        label: impl Into<String>,
1821        placeholder: impl Into<String>,
1822        locus: ExecutionLocus,
1823        params: Vec<ActionParam>,
1824        build: impl Fn(&ActionArgs) -> EncodedAction + Send + Sync + 'static,
1825    ) -> Self {
1826        Self::typed_with_kind(
1827            TypedActionSeed {
1828                id: id.into(),
1829                label: label.into(),
1830                placeholder: placeholder.into(),
1831                locus,
1832                kind: OperationKind::Document,
1833                operation_type: None,
1834                params,
1835            },
1836            Arc::new(move |_, args| build(args)),
1837            true,
1838        )
1839    }
1840
1841    /// [`typed`](Self::typed) for a type shared by many targets: the builder
1842    /// is given the target of the spec being invoked. A nullary one is
1843    /// encoded per invocation, as its target says what it does.
1844    #[doc(hidden)]
1845    pub fn typed_on(
1846        id: impl Into<String>,
1847        label: impl Into<String>,
1848        placeholder: impl Into<String>,
1849        locus: ExecutionLocus,
1850        params: Vec<ActionParam>,
1851        build: impl Fn(&Target, &ActionArgs) -> EncodedAction + Send + Sync + 'static,
1852    ) -> Self {
1853        Self::typed_with_kind(
1854            TypedActionSeed {
1855                id: id.into(),
1856                label: label.into(),
1857                placeholder: placeholder.into(),
1858                locus,
1859                kind: OperationKind::Document,
1860                operation_type: None,
1861                params,
1862            },
1863            Arc::new(build),
1864            false,
1865        )
1866    }
1867
1868    /// A typed effect or view operation. This is the non-document counterpart
1869    /// to [`typed`](Self::typed), with the same strict multi-parameter binding.
1870    #[doc(hidden)]
1871    pub fn typed_operation(
1872        id: impl Into<String>,
1873        label: impl Into<String>,
1874        placeholder: impl Into<String>,
1875        kind: OperationKind,
1876        type_id: impl Into<String>,
1877        params: Vec<ActionParam>,
1878        build: impl Fn(&ActionArgs) -> EncodedAction + Send + Sync + 'static,
1879    ) -> Self {
1880        debug_assert_ne!(kind, OperationKind::Document);
1881        Self::typed_with_kind(
1882            TypedActionSeed {
1883                id: id.into(),
1884                label: label.into(),
1885                placeholder: placeholder.into(),
1886                locus: ExecutionLocus::ClientLocal,
1887                kind,
1888                operation_type: Some(type_id.into()),
1889                params,
1890            },
1891            Arc::new(move |_, args| build(args)),
1892            true,
1893        )
1894    }
1895
1896    /// [`typed_operation`](Self::typed_operation) for a type shared by many
1897    /// targets, as [`typed_on`](Self::typed_on) is for [`typed`](Self::typed).
1898    ///
1899    /// The builder is boxed where it is made, so the toolkit compiles this
1900    /// once rather than every app once per vocabulary.
1901    #[doc(hidden)]
1902    pub fn typed_operation_on(
1903        id: impl Into<String>,
1904        label: impl Into<String>,
1905        placeholder: impl Into<String>,
1906        kind: OperationKind,
1907        type_id: impl Into<String>,
1908        params: Vec<ActionParam>,
1909        build: ArgsBuilder,
1910    ) -> Self {
1911        debug_assert_ne!(kind, OperationKind::Document);
1912        Self::typed_with_kind(
1913            TypedActionSeed {
1914                id: id.into(),
1915                label: label.into(),
1916                placeholder: placeholder.into(),
1917                locus: ExecutionLocus::ClientLocal,
1918                kind,
1919                operation_type: Some(type_id.into()),
1920                params,
1921            },
1922            build,
1923            false,
1924        )
1925    }
1926
1927    /// `eager`: encode a nullary action once, now, as an action that holds
1928    /// what it acts on in its builder always has.
1929    fn typed_with_kind(seed: TypedActionSeed, build: ArgsBuilder, eager: bool) -> Self {
1930        let build: ArgsBuilder = if let Some(expected) = seed.operation_type.clone() {
1931            Arc::new(move |target, args| enforce_operation_type(build(target, args), &expected))
1932        } else {
1933            build
1934        };
1935        let input = match primary_param(&seed.params) {
1936            None => InputMode::Immediate(
1937                eager.then(|| Arc::new(build(&Target::none(), &ActionArgs::none()))),
1938            ),
1939            Some(primary) => InputMode::Prompted {
1940                prompt: primary.description.to_string(),
1941                placeholder: seed.placeholder,
1942                collects: Collects::Words,
1943            },
1944        };
1945        let contract = unnamed_kind(ActionContract::for_operation(seed.kind));
1946        Self::declared(
1947            Declared {
1948                id: seed.id,
1949                label: seed.label,
1950                locus: seed.locus,
1951                kind: seed.kind,
1952                operation_type: seed.operation_type,
1953                params: seed.params,
1954            },
1955            contract,
1956            input,
1957            InvocationBuilder::Dynamic {
1958                build,
1959                deferred_type: None,
1960            },
1961        )
1962    }
1963
1964    /// Fire `encoded` at once when a person chooses the action (the palette,
1965    /// a menu, the shortcut), asking nothing; a caller that passes arguments
1966    /// still binds them against its parameters. For a typed action whose
1967    /// arguments all have a meaning when left out (open search, unnarrowed).
1968    #[must_use]
1969    pub fn with_immediate(mut self, encoded: EncodedAction) -> Self {
1970        self.type_mut().input = InputMode::Immediate(Some(Arc::new(encoded)));
1971        self
1972    }
1973
1974    /// Fire at once when a person chooses the action, asking nothing, encoded per invocation
1975    /// from its target: [`with_immediate`](Self::with_immediate) for a type shared by many
1976    /// targets. For a typed action whose parameters are all optional, each with a meaning when
1977    /// left out; a caller that passes arguments still binds them against its parameters. An
1978    /// action with a required parameter keeps asking for it.
1979    #[must_use]
1980    pub fn with_immediate_per_target(mut self) -> Self {
1981        if self.params().iter().all(|param| !param.required) {
1982            self.type_mut().input = InputMode::Immediate(None);
1983        }
1984        self
1985    }
1986
1987    /// Opt one action into inert, provider-defined continuation evidence.
1988    #[must_use]
1989    pub fn with_continuation_identity(
1990        mut self,
1991        resolver: impl for<'a> Fn(ContinuationQuery<'a>) -> Option<ContinuationEvidence>
1992        + Send
1993        + Sync
1994        + 'static,
1995    ) -> Self {
1996        self.type_mut().continuation_resolver = Some(Arc::new(resolver));
1997        self
1998    }
1999
2000    /// Resolve comparison-only evidence for the exact input or draft domain.
2001    /// A mismatched response variant is rejected as unsupported.
2002    pub fn continuation_identity(
2003        &self,
2004        query: ContinuationQuery<'_>,
2005    ) -> Option<ContinuationEvidence> {
2006        let exact = matches!(query, ContinuationQuery::Exact(_));
2007        let evidence = self.continuation_resolver.as_ref()?(query)?;
2008        match (exact, &evidence) {
2009            (true, ContinuationEvidence::Exact { .. })
2010            | (false, ContinuationEvidence::Draft { .. }) => Some(evidence),
2011            _ => None,
2012        }
2013    }
2014
2015    /// An action whose one argument is the content hash of bytes this
2016    /// machine already holds, rather than typed words — a separate
2017    /// constructor (not a parameter on [`Self::prompted_param`]) so every
2018    /// existing action keeps saying exactly what it said.
2019    pub fn prompted_content(
2020        id: impl Into<String>,
2021        label: impl Into<String>,
2022        prompt: impl Into<String>,
2023        placeholder: impl Into<String>,
2024        locus: ExecutionLocus,
2025        build: impl Fn(&str) -> EncodedAction + Send + Sync + 'static,
2026    ) -> Self {
2027        Self::prompted_content_on(id, label, prompt, placeholder, locus, move |_, hash| {
2028            build(hash)
2029        })
2030    }
2031
2032    /// [`prompted_content`](Self::prompted_content) for a type shared by many
2033    /// targets: the builder is given the target of the spec being invoked.
2034    pub fn prompted_content_on(
2035        id: impl Into<String>,
2036        label: impl Into<String>,
2037        prompt: impl Into<String>,
2038        placeholder: impl Into<String>,
2039        locus: ExecutionLocus,
2040        build: impl Fn(&Target, &str) -> EncodedAction + Send + Sync + 'static,
2041    ) -> Self {
2042        let mut spec = Self::prompted_param_on(
2043            id,
2044            label,
2045            ActionParam::required_owned(PROMPTED_PARAM, ParamType::Text, prompt.into()),
2046            placeholder,
2047            locus,
2048            build,
2049        );
2050        if let InputMode::Prompted { collects, .. } = &mut spec.type_mut().input {
2051            *collects = Collects::Content;
2052        }
2053        spec
2054    }
2055
2056    /// Declare the other words people use for this action
2057    /// ([`Self::keywords`]): plain words, one phrase each, no repetition of
2058    /// the label.
2059    #[must_use]
2060    pub fn with_keywords<S: Into<String>>(mut self, keywords: impl IntoIterator<Item = S>) -> Self {
2061        self.type_mut().keywords = keywords.into_iter().map(Into::into).collect();
2062        self
2063    }
2064
2065    /// Declare what the action did, said after who did it ([`Self::did`]):
2066    /// "showed this on the canvas", "added a subtask".
2067    #[must_use]
2068    pub fn with_did(mut self, did: impl Into<String>) -> Self {
2069        let did = did.into();
2070        self.type_mut().did = Some(did).filter(|did| !did.trim().is_empty());
2071        self
2072    }
2073
2074    /// Give the action its own picture ([`Self::icon`]), by its Lucide name.
2075    #[must_use]
2076    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
2077        self.type_mut().icon = Some(icon.into());
2078        self
2079    }
2080
2081    #[must_use]
2082    pub fn with_description(mut self, description: impl Into<String>) -> Self {
2083        self.type_mut().description = Some(description.into());
2084        self
2085    }
2086
2087    /// Show `state` on the action's row ([`ActionState`]): publish the
2088    /// action anew when it changes.
2089    #[must_use]
2090    pub fn with_state(mut self, state: ActionState) -> Self {
2091        self.type_mut().state = state;
2092        self
2093    }
2094
2095    #[must_use]
2096    pub fn with_contract(mut self, contract: ActionContract) -> Self {
2097        self.type_mut().contract = contract;
2098        self
2099    }
2100
2101    #[must_use]
2102    pub fn unavailable(mut self, code: impl Into<String>, reason: impl Into<String>) -> Self {
2103        self.type_mut().contract.availability = Availability::Unavailable {
2104            code: code.into(),
2105            reason: reason.into(),
2106        };
2107        self
2108    }
2109
2110    /// A deletion: its kind is
2111    /// [`deletion_kind`](ActionContract::deletion_kind), and the tags the spec
2112    /// already carries settle its confirmation — asked with a click unless a
2113    /// compensated undo says Undo takes it back.
2114    #[must_use]
2115    pub fn destructive(mut self) -> Self {
2116        let contract = &mut self.type_mut().contract;
2117        contract.risk = RiskLevel::Destructive;
2118        contract.kind = contract.deletion_kind();
2119        contract.settle_confirmation();
2120        self
2121    }
2122
2123    /// List this action for `audience` only ([`Audience`](crate::Audience)).
2124    /// Recorded in the contract's tags, so the audience crosses every
2125    /// boundary the inert contract does. Call after
2126    /// [`with_contract`](Self::with_contract), which replaces the tags.
2127    #[must_use]
2128    pub fn for_audience(mut self, audience: crate::Audience) -> Self {
2129        self.type_mut().contract.set_audience(audience);
2130        self
2131    }
2132
2133    /// Declare this read-only action as the one that answers, with no
2134    /// arguments, the first page of the app's open document. Recorded as
2135    /// [`DOCUMENT_READ_TAG`](crate::DOCUMENT_READ_TAG), so a caller that just
2136    /// opened a file finds it in the directory. Call after
2137    /// [`with_contract`](Self::with_contract), which replaces the tags.
2138    #[must_use]
2139    pub fn reads_document(mut self) -> Self {
2140        push_tag(
2141            &mut self.type_mut().contract,
2142            crate::contract::DOCUMENT_READ_TAG,
2143        );
2144        self
2145    }
2146
2147    /// Declare this view as a read of what its record holds that takes
2148    /// arguments (a version, a review of one): recorded as
2149    /// [`RESOURCE_READ_TAG`](crate::RESOURCE_READ_TAG), it moves nothing, anyone
2150    /// who may read the record may run it, and it discloses the record to
2151    /// them. Call after [`with_contract`](Self::with_contract), which replaces
2152    /// the tags.
2153    #[must_use]
2154    pub fn reads_resource(mut self) -> Self {
2155        push_tag(
2156            &mut self.type_mut().contract,
2157            crate::contract::RESOURCE_READ_TAG,
2158        );
2159        self
2160    }
2161
2162    /// Declare this action as the one that opens the file its `path`
2163    /// parameter names in this app instance, of any type when `extensions`
2164    /// is empty, else of those (lowercase, no dot). Recorded as
2165    /// [`OPENS_PATH_TAG`](crate::OPENS_PATH_TAG), so a caller that launches
2166    /// the app with a file opens it here, and never through an action
2167    /// that only happens to take a `path`. Call after
2168    /// [`with_contract`](Self::with_contract), which replaces the tags.
2169    #[must_use]
2170    pub fn opens_path(mut self, extensions: &[&str]) -> Self {
2171        push_tag(
2172            &mut self.type_mut().contract,
2173            crate::contract::OPENS_PATH_TAG,
2174        );
2175        for extension in extensions {
2176            push_tag(
2177                &mut self.type_mut().contract,
2178                &format!(
2179                    "{}{}",
2180                    crate::contract::OPENS_PATH_EXTENSION_PREFIX,
2181                    extension.to_ascii_lowercase()
2182                ),
2183            );
2184        }
2185        self
2186    }
2187
2188    /// Who this action is listed for. See [`for_audience`](Self::for_audience).
2189    pub fn audience(&self) -> crate::Audience {
2190        self.contract.audience()
2191    }
2192
2193    /// Whether people's listings (the palette, menus) offer it.
2194    pub fn reaches_people(&self) -> bool {
2195        self.contract.reaches_people()
2196    }
2197
2198    /// Whether agents' listings offer it.
2199    pub fn reaches_agents(&self) -> bool {
2200        self.contract.reaches_agents()
2201    }
2202
2203    /// Whether a row a person picks can supply what it asks for: nothing, or
2204    /// the one line its prompt collects (a name, a number, a date). One that
2205    /// needs several arguments, or a list, an object or another resource's
2206    /// address, is taken by callers that name them (agents, scripts, the
2207    /// controls bound to where the person is), never from a row.
2208    pub fn takes_a_row_answer(&self) -> bool {
2209        let mut required = self.params.iter().filter(|param| param.required);
2210        match (required.next(), required.next()) {
2211            (None, _) => true,
2212            (Some(param), None) => {
2213                matches!(self.input(), ActionInput::Prompted { .. })
2214                    && matches!(
2215                        param.ty,
2216                        ParamType::Text
2217                            | ParamType::Integer
2218                            | ParamType::Number
2219                            | ParamType::DateTime
2220                            | ParamType::Secret
2221                    )
2222            }
2223            (Some(_), Some(_)) => false,
2224        }
2225    }
2226
2227    /// Declare that this action carries the resource's other actions (a
2228    /// generic typed edit, a group of edits): history records the actions
2229    /// it carried, never this one. The contract advertises
2230    /// [`CARRIER_TAG`](crate::CARRIER_TAG), so whoever decides for it or words
2231    /// it for a person reads what it carries. Call after
2232    /// [`with_contract`](Self::with_contract), which replaces the tags.
2233    #[must_use]
2234    pub fn carrying(mut self) -> Self {
2235        self.type_mut().carrier = true;
2236        push_tag(&mut self.type_mut().contract, crate::contract::CARRIER_TAG);
2237        self
2238    }
2239
2240    /// Whether this action carries the resource's other actions. See
2241    /// [`Self::carrying`].
2242    pub fn carries_actions(&self) -> bool {
2243        self.carrier
2244    }
2245
2246    /// Classify each invocation's risk from its bound arguments, for an action
2247    /// whose consequence depends on them (a generic edit whose value may
2248    /// delete). Whenever the classified risk
2249    /// [requires confirmation](RiskLevel::requires_confirmation), the host
2250    /// asks for exactly the confirmation a declared
2251    /// [`destructive`](Self::destructive) action gets; otherwise the action
2252    /// runs directly. The contract advertises
2253    /// [`ARGUMENT_RISK_TAG`](crate::ARGUMENT_RISK_TAG) so callers that cannot
2254    /// classify know to expect it.
2255    #[must_use]
2256    pub fn with_risk(
2257        self,
2258        classify: impl Fn(&ActionArgs) -> RiskLevel + Send + Sync + 'static,
2259    ) -> Self {
2260        self.with_risk_on(move |_, args| classify(args))
2261    }
2262
2263    /// [`with_risk`](Self::with_risk) for a type shared by many targets: the
2264    /// classifier is given the target of the spec being invoked.
2265    #[must_use]
2266    pub fn with_risk_on(
2267        mut self,
2268        classify: impl Fn(&Target, &ActionArgs) -> RiskLevel + Send + Sync + 'static,
2269    ) -> Self {
2270        push_tag(
2271            &mut self.type_mut().contract,
2272            crate::contract::ARGUMENT_RISK_TAG,
2273        );
2274        self.type_mut().risk_of = Some(Arc::new(classify));
2275        self
2276    }
2277
2278    /// Classify what each invocation is from its bound arguments, for an
2279    /// action whose consequence depends on them (a generic edit: a reply
2280    /// writes only the comments, a deletion changes the document). The
2281    /// declared [`ActionContract::kind`] and [`ActionContract::field`] stay
2282    /// the least any invocation is, which is what a host offers the action
2283    /// under; every check that admits an invocation asks
2284    /// [`need_for`](Self::need_for) too.
2285    #[must_use]
2286    pub fn with_need_of(
2287        mut self,
2288        classify: impl Fn(&ActionArgs) -> ActionNeed + Send + Sync + 'static,
2289    ) -> Self {
2290        self.type_mut().need_of = Some(Arc::new(move |_, args| classify(args)));
2291        self
2292    }
2293
2294    /// What one invocation with these bound arguments is: the classifier's
2295    /// verdict, else the declared contract's.
2296    pub fn need_for_args(&self, args: &ActionArgs) -> ActionNeed {
2297        let mut need = self.need_of.as_ref().map_or_else(
2298            || self.contract.need(),
2299            |classify| self.contract.scoped(classify(&self.target, args)),
2300        );
2301        need.privileged |= self.risk_for(args) == RiskLevel::Privileged;
2302        need
2303    }
2304
2305    /// What one invocation is, by the value it carries: `json`, or the
2306    /// palette's and legacy text API's `argument` (typed JSON behind
2307    /// [`ARGUMENTS_JSON_PREFIX`](crate::ARGUMENTS_JSON_PREFIX), one line of
2308    /// text for the primary parameter, or nothing). Arguments that do not
2309    /// bind build no action, so they are what the declaration says.
2310    #[must_use]
2311    pub fn need_for(
2312        &self,
2313        json: Option<&serde_json::Map<String, serde_json::Value>>,
2314        argument: Option<&str>,
2315    ) -> ActionNeed {
2316        // An invocation whose risk depends on its arguments may be
2317        // privileged ([`Self::need_for_args`]) even with no classifier.
2318        if self.need_of.is_none() && self.risk_of.is_none() {
2319            return self.contract.need();
2320        }
2321        if let Some(json) = json {
2322            return self
2323                .without_bound(json)
2324                .and_then(|json| ActionArgs::bind_json(&self.params, &json))
2325                .map_or_else(|_| self.contract.need(), |args| self.need_for_args(&args));
2326        }
2327        if let Some(json) =
2328            argument.and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
2329        {
2330            return serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(json)
2331                .map_or_else(
2332                    |_| self.contract.need(),
2333                    |arguments| self.need_for(Some(&arguments), None),
2334                );
2335        }
2336        let supplied = argument.map_or_else(Vec::new, |text| primary_argument(&self.params, text));
2337        ActionArgs::bind(&self.params, supplied)
2338            .map_or_else(|_| self.contract.need(), |args| self.need_for_args(&args))
2339    }
2340
2341    /// Decide per invocation whether Undo takes it back, for an action that
2342    /// carries others (a group: Undo takes it back only when it takes back
2343    /// every member). Without it, the contract's
2344    /// [`can_be_undone`](ActionContract::can_be_undone) decides.
2345    #[must_use]
2346    pub fn with_undo_of(
2347        mut self,
2348        classify: impl Fn(&ActionArgs) -> bool + Send + Sync + 'static,
2349    ) -> Self {
2350        self.type_mut().undo_of = Some(Arc::new(classify));
2351        self
2352    }
2353
2354    /// Whether Undo takes back one invocation with these bound arguments.
2355    pub fn undoable_for(&self, args: &ActionArgs) -> bool {
2356        self.undo_of
2357            .as_ref()
2358            .map_or_else(|| self.contract.can_be_undone(), |classify| classify(args))
2359    }
2360
2361    /// The risk of one invocation: the classifier's verdict for these
2362    /// arguments, or the declared [`ActionContract::risk`].
2363    pub fn risk_for(&self, args: &ActionArgs) -> RiskLevel {
2364        self.risk_of
2365            .as_ref()
2366            .map_or(self.contract.risk, |classify| classify(&self.target, args))
2367    }
2368
2369    /// The confirmation one invocation with these bound arguments needs: the
2370    /// declared policy when there is one, else
2371    /// [`Confirm`](ConfirmationPolicy::Confirm) when
2372    /// [`risk_for`](Self::risk_for) requires confirmation. Every check that
2373    /// admits an invocation asks this, never the declared policy alone.
2374    pub fn confirmation_for_args(&self, args: &ActionArgs) -> ConfirmationPolicy {
2375        if self.contract.confirmation != ConfirmationPolicy::None || self.risk_of.is_none() {
2376            return self.contract.confirmation.clone();
2377        }
2378        if self
2379            .risk_for(args)
2380            .requires_confirmation_when(self.undoable_for(args))
2381        {
2382            ConfirmationPolicy::Confirm
2383        } else {
2384            ConfirmationPolicy::None
2385        }
2386    }
2387
2388    /// [`confirmation_for_args`](Self::confirmation_for_args) for arguments
2389    /// that arrived as JSON. Arguments that do not bind cannot build an
2390    /// action at all, so they get the declared policy.
2391    pub fn confirmation_for_json(
2392        &self,
2393        supplied: &serde_json::Map<String, serde_json::Value>,
2394    ) -> ConfirmationPolicy {
2395        if self.risk_of.is_none() {
2396            return self.contract.confirmation.clone();
2397        }
2398        self.without_bound(supplied)
2399            .and_then(|supplied| ActionArgs::bind_json(&self.params, &supplied))
2400            .map_or_else(
2401                |_| self.contract.confirmation.clone(),
2402                |args| self.confirmation_for_args(&args),
2403            )
2404    }
2405
2406    /// [`confirmation_for_args`](Self::confirmation_for_args) for the palette
2407    /// and legacy text API: typed JSON behind
2408    /// [`ARGUMENTS_JSON_PREFIX`](crate::ARGUMENTS_JSON_PREFIX), one line of
2409    /// text for the primary parameter, or nothing.
2410    pub fn confirmation_for_argument(&self, argument: Option<&str>) -> ConfirmationPolicy {
2411        if self.risk_of.is_none() {
2412            return self.contract.confirmation.clone();
2413        }
2414        if let Some(json) =
2415            argument.and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
2416        {
2417            return serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(json)
2418                .map_or_else(
2419                    |_| self.contract.confirmation.clone(),
2420                    |arguments| self.confirmation_for_json(&arguments),
2421                );
2422        }
2423        let supplied = argument.map_or_else(Vec::new, |text| primary_argument(&self.params, text));
2424        ActionArgs::bind(&self.params, supplied).map_or_else(
2425            |_| self.contract.confirmation.clone(),
2426            |args| self.confirmation_for_args(&args),
2427        )
2428    }
2429
2430    #[must_use]
2431    pub fn privileged(mut self) -> Self {
2432        self.type_mut().contract.risk = RiskLevel::Privileged;
2433        self.type_mut().contract.confirmation = ConfirmationPolicy::Confirm;
2434        self
2435    }
2436
2437    /// Set what the action is able to do, as the declaration sees it. See
2438    /// [`ActionContract::kind`].
2439    #[must_use]
2440    pub fn of_kind(mut self, kind: ActionKind) -> Self {
2441        self.type_mut().contract.kind = kind;
2442        self
2443    }
2444
2445    /// Set the field the action writes, and its kind unless the declaration
2446    /// named one ([`of_kind`](Self::of_kind)), which a need does not overrule.
2447    #[must_use]
2448    pub fn with_need(mut self, need: ActionNeed) -> Self {
2449        self.type_mut().contract.kind = need.kind;
2450        self.type_mut().contract.field = need.field;
2451        self
2452    }
2453
2454    /// Place the action below the one field it writes. See
2455    /// [`ActionContract::field`].
2456    #[must_use]
2457    pub fn below_field(mut self, field: impl Into<String>) -> Self {
2458        self.type_mut().contract.field = Some(field.into());
2459        self
2460    }
2461
2462    #[must_use]
2463    pub fn execution(mut self, execution: ExecutionMode) -> Self {
2464        self.type_mut().contract.execution = execution;
2465        self
2466    }
2467
2468    #[must_use]
2469    pub fn returns(mut self, result: ResultSpec) -> Self {
2470        self.type_mut().contract.result = result;
2471        self
2472    }
2473
2474    /// This document action as another resource carries it: every action it
2475    /// builds passes through `wrap`, which re-encodes it as the action of the
2476    /// resource that contains this one (a rich-text edit becomes the note's
2477    /// edit of its body, registered under `wrapped_type`). Parameters,
2478    /// kind, field, risk and confirmation stay this action's. A builder's
2479    /// refusal passes through unchanged. An effect or view operation is
2480    /// returned as it is: it writes nothing to wrap.
2481    #[must_use]
2482    pub fn rewrapped(
2483        mut self,
2484        wrapped_type: &str,
2485        wrap: impl Fn(EncodedAction) -> EncodedAction + Send + Sync + 'static,
2486    ) -> Self {
2487        if self.kind != OperationKind::Document {
2488            return self;
2489        }
2490        let wrap: Arc<dyn Fn(EncodedAction) -> EncodedAction + Send + Sync> =
2491            Arc::new(move |encoded: EncodedAction| {
2492                if encoded.type_id == INVALID_ARGUMENTS_TYPE {
2493                    encoded
2494                } else {
2495                    wrap(encoded)
2496                }
2497            });
2498        let ty = self.type_mut();
2499        ty.build = match ty.build.clone() {
2500            InvocationBuilder::Fixed(encoded) => {
2501                InvocationBuilder::Fixed(Arc::new(wrap(encoded.as_ref().clone())))
2502            }
2503            InvocationBuilder::Dynamic {
2504                build,
2505                deferred_type,
2506            } => {
2507                let wrap = Arc::clone(&wrap);
2508                InvocationBuilder::Dynamic {
2509                    build: Arc::new(move |target, args| wrap(build(target, args))),
2510                    deferred_type: deferred_type.map(|_| wrapped_type.to_owned()),
2511                }
2512            }
2513            InvocationBuilder::Text(build) => {
2514                let wrap = Arc::clone(&wrap);
2515                InvocationBuilder::Text(Arc::new(move |target, text| wrap(build(target, text))))
2516            }
2517        };
2518        match &mut ty.input {
2519            InputMode::Immediate(Some(encoded)) => {
2520                *encoded = Arc::new(wrap(encoded.as_ref().clone()));
2521            }
2522            InputMode::Deferred { type_id } => wrapped_type.clone_into(type_id),
2523            InputMode::Immediate(None) | InputMode::Prompted { .. } => {}
2524        }
2525        self
2526    }
2527
2528    /// This document action, carried out on another document than the one
2529    /// its resource's host holds (the person's own record, a settings
2530    /// section): published as an effect operation of `operation_type` whose
2531    /// value is `wrap` of the encoded action, which the host answering
2532    /// `operation_type` applies to that document. Parameters, kind,
2533    /// permission, risk and confirmation stay this action's, and it is
2534    /// tagged [`crate::ROUTED_CHANGE_TAG`]: a change of a document still. An
2535    /// effect or view operation is returned as it is.
2536    #[must_use]
2537    pub fn routed(
2538        self,
2539        operation_type: &str,
2540        wrap: impl Fn(EncodedAction) -> EncodedAction + Send + Sync + 'static,
2541    ) -> Self {
2542        if self.kind != OperationKind::Document {
2543            return self;
2544        }
2545        let mut spec = self.rewrapped(operation_type, wrap);
2546        let ty = spec.type_mut();
2547        ty.kind = OperationKind::Effect;
2548        ty.operation_type = Some(operation_type.to_owned());
2549        push_tag(&mut ty.contract, crate::ROUTED_CHANGE_TAG);
2550        spec
2551    }
2552
2553    /// What an invocation of this action must carry. Empty for the nullary
2554    /// majority.
2555    ///
2556    /// Part of the descriptor rather than something a caller discovers by
2557    /// trying: enumeration is all a caller that cannot see the screen has to
2558    /// work from, so an action whose parameters were not advertised would be
2559    /// un-invokable except by guesswork.
2560    pub fn params(&self) -> &[ActionParam] {
2561        &self.params
2562    }
2563
2564    /// Narrow the parameter `name` this action declares for the entity it is
2565    /// offered on: the values it takes there now, what it means there, the
2566    /// bounds its state sets. A parameter the action does not declare is left
2567    /// alone, so narrowing a spec an entity does not have the argument for is
2568    /// no change rather than a panic.
2569    pub fn narrow_param(&mut self, name: &str, narrow: impl FnOnce(&mut ActionParam)) {
2570        if let Some(param) = Arc::make_mut(&mut self.ty)
2571            .params
2572            .iter_mut()
2573            .find(|param| param.name == name)
2574        {
2575            narrow(param);
2576        }
2577    }
2578
2579    /// Bind `supplied` against [`params`](Self::params) and build the action.
2580    ///
2581    /// Strict: a missing, unknown, wrong-typed or out-of-choice argument is
2582    /// refused here, and the caller never receives an [`EncodedAction`] to
2583    /// dispatch — so a bad call cannot become a partial mutation, because
2584    /// nothing was ever handed to the executor.
2585    pub fn build_args(
2586        &self,
2587        supplied: impl IntoIterator<Item = (String, ArgValue)>,
2588    ) -> Result<EncodedAction, ArgError> {
2589        self.validate_deferred_shape()?;
2590        let bound = ActionArgs::bind(&self.params, self.pairs_without_bound(supplied)?)?;
2591        self.validate_built(self.ty.encode(&self.target, &bound))
2592    }
2593
2594    /// [`build_args`](Self::build_args) for arguments that arrived as JSON.
2595    pub fn build_json(
2596        &self,
2597        supplied: &serde_json::Map<String, serde_json::Value>,
2598    ) -> Result<EncodedAction, ArgError> {
2599        self.validate_deferred_shape()?;
2600        let bound = ActionArgs::bind_json(&self.params, self.without_bound(supplied)?.as_ref())?;
2601        self.validate_built(self.ty.encode(&self.target, &bound))
2602    }
2603
2604    /// The palette input mode's encoding for one typed text argument, exactly as a
2605    /// prompted affordance builds it. `None` when this action collects no text.
2606    pub fn build_text(&self, text: &str) -> Option<EncodedAction> {
2607        if !matches!(self.input, InputMode::Prompted { .. }) {
2608            return None;
2609        }
2610        Some(match &self.build {
2611            InvocationBuilder::Text(build) => build(&self.target, text),
2612            InvocationBuilder::Fixed(_) | InvocationBuilder::Dynamic { .. } => {
2613                match ActionArgs::bind(&self.params, primary_argument(&self.params, text)) {
2614                    Ok(bound) => self.ty.encode(&self.target, &bound),
2615                    Err(error) => EncodedAction {
2616                        type_id: INVALID_ARGUMENTS_TYPE.into(),
2617                        payload: error.to_string().into_bytes(),
2618                    },
2619                }
2620            }
2621        })
2622    }
2623}
2624
2625/// Whether `given`, passed for `name`, which an action binds to `value`
2626/// ([`ActionSpec::with_bound`]), names that value: as it is, or, for an
2627/// item's id, as the end of a longer form of its address (`sheets/<id>`,
2628/// `sheets.workbook/sheets/<id>`, `sheet:<id>`).
2629fn check_bound(
2630    name: &str,
2631    value: &serde_json::Value,
2632    given: &serde_json::Value,
2633) -> Result<(), ArgError> {
2634    let same = given == value
2635        || match (value, given) {
2636            (serde_json::Value::String(id), serde_json::Value::String(given)) => {
2637                given.trim() == id
2638                    || given
2639                        .rsplit(['/', ':'])
2640                        .next()
2641                        .is_some_and(|last| last == id && !id.is_empty())
2642            }
2643            _ => false,
2644        };
2645    if same {
2646        return Ok(());
2647    }
2648    let shown = match value {
2649        serde_json::Value::String(id) => id.clone(),
2650        other => other.to_string(),
2651    };
2652    Err(ArgError::Constraint {
2653        name: name.to_owned(),
2654        reason: format!(
2655            "is `{shown}` here: this action acts on that item only. Leave `{name}` out, or \
2656             invoke the action on the item you mean"
2657        ),
2658    })
2659}
2660
2661fn enforce_operation_type(encoded: EncodedAction, expected: &str) -> EncodedAction {
2662    // A refusal carries the builder's own reason to the caller; the API reads
2663    // it out of the payload. Only an encoding of another operation, which the
2664    // spec cannot invoke, is a defect worth naming here.
2665    if encoded.type_id == expected || encoded.type_id == INVALID_ARGUMENTS_TYPE {
2666        encoded
2667    } else {
2668        EncodedAction {
2669            type_id: INVALID_ARGUMENTS_TYPE.into(),
2670            payload: format!(
2671                "operation builder returned `{}` but declared `{expected}`",
2672                encoded.type_id
2673            )
2674            .into_bytes(),
2675        }
2676    }
2677}
2678
2679fn push_tag(contract: &mut ActionContract, tag: &str) {
2680    if !contract.tags.iter().any(|existing| existing == tag) {
2681        contract.tags.push(tag.to_owned());
2682    }
2683}
2684
2685/// Bind one line of text to the primary parameter (the first required one,
2686/// else the first), as the palette collects it.
2687fn primary_argument(params: &[ActionParam], text: &str) -> Vec<(String, ArgValue)> {
2688    primary_param(params).map_or_else(Vec::new, |primary| {
2689        parse_argument(&primary.name, primary.ty, text)
2690    })
2691}
2692
2693/// Parse the one line the palette can collect into a parameter's declared
2694/// type. Unparseable text binds nothing rather than coercing to a wrong value;
2695/// the builder decides what absence means, exactly as it does for an
2696/// unsupplied optional.
2697fn parse_argument(name: &str, ty: ParamType, text: &str) -> Vec<(String, ArgValue)> {
2698    let parsed = match ty {
2699        ParamType::Text => Some(ArgValue::Text(text.to_string())),
2700        ParamType::Integer => text.trim().parse::<i128>().ok().map(ArgValue::Integer),
2701        ParamType::Number => text.trim().parse::<f64>().ok().map(ArgValue::Number),
2702        ParamType::Boolean => match text.trim() {
2703            "true" | "yes" | "on" => Some(ArgValue::Boolean(true)),
2704            "false" | "no" | "off" => Some(ArgValue::Boolean(false)),
2705            _ => None,
2706        },
2707        ParamType::Object => {
2708            serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(text)
2709                .ok()
2710                .map(ArgValue::Object)
2711        }
2712        ParamType::Array => serde_json::from_str::<Vec<serde_json::Value>>(text)
2713            .ok()
2714            .map(ArgValue::Array),
2715        ParamType::Resource => Some(ArgValue::Resource(text.to_string())),
2716        ParamType::DateTime => Some(ArgValue::DateTime(text.to_string())),
2717        ParamType::Secret => Some(ArgValue::Secret(text.to_string())),
2718    };
2719    parsed
2720        .map(|v| vec![(name.to_owned(), v)])
2721        .unwrap_or_default()
2722}
2723
2724/// The parameter one line of palette text binds to: the one that takes an
2725/// entry, else the first required one, else the first.
2726fn primary_param(params: &[ActionParam]) -> Option<&ActionParam> {
2727    params
2728        .iter()
2729        .find(|p| p.entry)
2730        .or_else(|| params.iter().find(|p| p.required))
2731        .or_else(|| params.first())
2732}
2733
2734pub use tilo_action_types::KEY_SEP;
2735
2736/// One (resource, action) pair produced by [`flatten`], addressable by a
2737/// composite [`key`](FlatAction::key) the palette uses as its row id.
2738pub struct FlatAction<'a> {
2739    /// `"<resource_id>\u{1f}<action_id>"` — the palette row id.
2740    pub key: String,
2741    pub resource_id: ResourceId,
2742    pub resource_kind: String,
2743    pub resource_label: String,
2744    pub resource_presentation: Option<ResourcePresentation>,
2745    pub action: &'a ActionSpec,
2746    /// How deep the resource sits in its forest: 0 for a root (the app or
2747    /// the open document itself), more for an item inside it.
2748    pub depth: usize,
2749}
2750
2751impl FlatAction<'_> {
2752    /// Whether a person searching what can be done (the palette, a window's
2753    /// search) is offered this action: one they can take now
2754    /// ([`ActionContract::a_person_can_take_now`]) on a resource listed for
2755    /// people ([`listed_for_people`]), and not the opening of a search hit,
2756    /// which the hit's own row stands for ([`OPENS_HIT_TAG`]).
2757    #[must_use]
2758    pub fn offered_to_a_person(&self) -> bool {
2759        self.action.contract.a_person_can_take_now()
2760            && listed_for_people(&self.resource_kind, &self.resource_label)
2761            && !self
2762                .action
2763                .contract
2764                .tags
2765                .iter()
2766                .any(|tag| tag == crate::OPENS_HIT_TAG)
2767    }
2768
2769    /// Whether it is listed as a row of its own: [`Self::offered_to_a_person`]
2770    /// and asking no more than a row can collect
2771    /// ([`ActionSpec::takes_a_row_answer`]). What a row cannot collect (a
2772    /// record, a person, several arguments) is picked where it lives.
2773    #[must_use]
2774    pub fn lists_a_row(&self) -> bool {
2775        self.offered_to_a_person() && self.action.takes_a_row_answer()
2776    }
2777
2778    /// The row a person reads for this action ([`listed_row`]).
2779    #[must_use]
2780    pub fn row(&self) -> ListedRow {
2781        listed_row(
2782            &self.action.label,
2783            (self.depth > 0).then_some(self.resource_label.as_str()),
2784        )
2785    }
2786}
2787
2788#[path = "resource/listed_row.rs"]
2789mod listed_row;
2790pub use listed_row::{ListedRow, listed_row, listed_row_problems};
2791
2792mod reading_row;
2793pub use reading_row::ReadingRow;
2794
2795/// Depth-first flatten of a resource forest into every exported action,
2796/// parents before children — what the palette lists.
2797pub fn flatten(resources: &[ResourceSpec]) -> Vec<FlatAction<'_>> {
2798    let mut out = Vec::new();
2799    for r in resources {
2800        flatten_into(r, 0, &mut out);
2801    }
2802    out
2803}
2804
2805fn flatten_into<'a>(resource: &'a ResourceSpec, depth: usize, out: &mut Vec<FlatAction<'a>>) {
2806    for action in &resource.actions {
2807        out.push(FlatAction {
2808            key: format!("{}{}{}", resource.id.0, KEY_SEP, action.id),
2809            resource_id: resource.id.clone(),
2810            resource_kind: resource.kind.clone(),
2811            resource_label: resource.label.clone(),
2812            resource_presentation: resource.presentation.clone(),
2813            action,
2814            depth,
2815        });
2816    }
2817    for child in &resource.children {
2818        flatten_into(child, depth.saturating_add(1), out);
2819    }
2820}
2821
2822#[path = "resource/control.rs"]
2823mod control;
2824pub use control::ControlInvocation;
2825
2826#[path = "resource/spec.rs"]
2827mod spec;
2828pub use spec::ResourceSpec;
2829
2830#[path = "resource/choices.rs"]
2831mod choices;
2832
2833#[path = "resource/carried.rs"]
2834mod carried;
2835
2836#[cfg(test)]
2837#[path = "resource/tests.rs"]
2838mod tests;
2839
2840#[cfg(test)]
2841#[path = "resource/history_tests.rs"]
2842mod history_tests;
2843
2844#[cfg(test)]
2845#[path = "resource/effective_invocation_tests.rs"]
2846mod effective_invocation_tests;
2847
2848#[cfg(test)]
2849#[path = "resource/deferred_tests.rs"]
2850mod deferred_tests;