1use 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
48pub type ArgsBuilder = Arc<dyn Fn(&Target, &ActionArgs) -> EncodedAction + Send + Sync>;
57
58#[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 #[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
73pub trait Exports {
77 fn exported(&self) -> &ResourceSpec;
79}
80
81impl Exports for ResourceSpec {
82 fn exported(&self) -> &ResourceSpec {
83 self
84 }
85}
86
87impl<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#[derive(Clone)]
128pub struct ActionBinding<I> {
129 address: ActionAddress,
130 kind: String,
134 shared_by: Option<String>,
137 spec: ActionSpec,
138 arguments: Arguments<I>,
139}
140
141impl<I> ActionBinding<I> {
142 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 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 spec: exported.clone(),
189 arguments: Arc::new(arguments),
190 })
191 }
192
193 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 #[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 #[must_use]
230 pub fn identity(&self) -> ActionAddress {
231 self.address.clone()
232 }
233
234 #[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 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 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 binding.spec.validate_json(&serde_json::Map::new())?;
280 Ok(binding)
281 }
282
283 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 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 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
333pub const PROMPTED_PARAM: &str = "value";
339
340fn 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
361pub const INVALID_ARGUMENTS_TYPE: &str = "tilo.invalid_arguments";
365
366pub const SEMANTIC_OPERATION_TYPE: &str = "tilo.ui.semantic-action";
372
373pub use tilo_action_types::ResourceId;
374
375#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(default, deny_unknown_fields)]
380pub struct ActionState {
381 #[serde(skip_serializing_if = "Option::is_none")]
383 pub badge: Option<String>,
384 #[serde(skip_serializing_if = "std::ops::Not::not")]
387 pub toggles: bool,
388 #[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 #[must_use]
399 pub fn is_empty(&self) -> bool {
400 self == &Self::default()
401 }
402
403 #[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#[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 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#[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#[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#[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 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
521 pub desktop: bool,
522 #[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 #[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 #[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 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#[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#[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#[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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
781pub enum Collects {
782 #[default]
784 Words,
785 Content,
787}
788
789#[derive(Clone, Copy, Debug, PartialEq, Eq)]
795pub enum ActionInput<'a> {
796 Immediate(Option<&'a Arc<EncodedAction>>),
802 Deferred { type_id: &'a str },
805 Prompted {
807 prompt: &'a str,
808 placeholder: &'a str,
809 collects: Collects,
811 },
812}
813
814#[derive(Clone)]
816enum InputMode {
817 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#[derive(Clone, Default)]
836pub struct Target(Option<Arc<dyn std::any::Any + Send + Sync>>);
837
838impl Target {
839 #[must_use]
841 pub const fn none() -> Self {
842 Self(None)
843 }
844
845 #[must_use]
848 pub fn new<T: std::any::Any + Send + Sync>(value: T) -> Self {
849 Self(Some(Arc::new(value)))
850 }
851
852 #[must_use]
854 pub fn get<T: std::any::Any>(&self) -> Option<&T> {
855 self.0.as_deref()?.downcast_ref()
856 }
857
858 #[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
872type TargetTextBuilder = Arc<dyn Fn(&Target, &str) -> EncodedAction + Send + Sync>;
874
875#[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 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 Text(TargetTextBuilder),
972}
973
974pub const NESTED_RESOURCE_FACET: &str = "part";
978
979#[derive(Clone)]
986pub struct ActionType {
987 pub id: String,
989 pub declared: String,
994 pub label: String,
995 pub keywords: Vec<String>,
1001 pub did: Option<String>,
1007 pub icon: Option<String>,
1009 pub description: Option<String>,
1010 pub state: ActionState,
1014 pub locus: ExecutionLocus,
1018 pub kind: OperationKind,
1021 pub operation_type: Option<String>,
1026 pub contract: ActionContract,
1028 input: InputMode,
1030 pub(crate) params: Vec<ActionParam>,
1034 build: InvocationBuilder,
1038 risk_of: Option<RiskClassifier>,
1041 undo_of: Option<UndoClassifier>,
1044 need_of: Option<NeedClassifier>,
1047 continuation_resolver: Option<ContinuationResolver>,
1048 carrier: bool,
1052 applied_as: Option<(String, String)>,
1056 provider: Option<Arc<RunBy>>,
1061}
1062
1063#[derive(Clone, Debug, PartialEq)]
1066pub struct RunBy {
1067 pub provider: String,
1069 pub resource: Option<String>,
1072 pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
1075}
1076
1077impl ActionType {
1078 #[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(¶m.name))
1095 .unwrap_or("");
1096 build(target, text)
1097 }
1098 }
1099 }
1100}
1101
1102#[derive(Clone)]
1108pub struct ActionSpec {
1109 ty: Arc<ActionType>,
1110 target: Target,
1111 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
1125pub type RiskClassifier = Arc<dyn Fn(&Target, &ActionArgs) -> RiskLevel + Send + Sync>;
1128
1129pub type UndoClassifier = Arc<dyn Fn(&ActionArgs) -> bool + Send + Sync>;
1131
1132pub 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
1146struct 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 #[must_use]
1182 pub fn action_type(&self) -> &Arc<ActionType> {
1183 &self.ty
1184 }
1185
1186 #[must_use]
1188 pub fn target(&self) -> &Target {
1189 &self.target
1190 }
1191
1192 pub fn type_mut(&mut self) -> &mut ActionType {
1195 Arc::make_mut(&mut self.ty)
1196 }
1197
1198 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
1277 pub fn run_by_provider(&self) -> Option<&RunBy> {
1278 self.provider.as_deref()
1279 }
1280
1281 #[must_use]
1284 pub fn provider(&self) -> Option<&str> {
1285 self.provider.as_deref().map(|run| run.provider.as_str())
1286 }
1287
1288 #[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 #[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 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 pub fn has_continuation_identity(&self) -> bool {
1334 self.continuation_resolver.is_some()
1335 }
1336
1337 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 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 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 #[must_use]
1398 pub fn bound(&self) -> &[(String, serde_json::Value)] {
1399 self.bound.as_deref().unwrap_or_default()
1400 }
1401
1402 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 pub fn audience(&self) -> crate::Audience {
2190 self.contract.audience()
2191 }
2192
2193 pub fn reaches_people(&self) -> bool {
2195 self.contract.reaches_people()
2196 }
2197
2198 pub fn reaches_agents(&self) -> bool {
2200 self.contract.reaches_agents()
2201 }
2202
2203 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 #[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 pub fn carries_actions(&self) -> bool {
2243 self.carrier
2244 }
2245
2246 #[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 #[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 #[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 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 #[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 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 #[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 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 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 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 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 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 #[must_use]
2440 pub fn of_kind(mut self, kind: ActionKind) -> Self {
2441 self.type_mut().contract.kind = kind;
2442 self
2443 }
2444
2445 #[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 #[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 #[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 #[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 pub fn params(&self) -> &[ActionParam] {
2561 &self.params
2562 }
2563
2564 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 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 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 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
2625fn 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 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
2685fn 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
2693fn 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
2724fn 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
2736pub struct FlatAction<'a> {
2739 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 pub depth: usize,
2749}
2750
2751impl FlatAction<'_> {
2752 #[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 #[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 #[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
2795pub 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;