Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified Download src/catalog.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 29.8 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/catalog.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/src/catalog.rs
-
curl -L -o catalog.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/catalog.rs
29.8 kB
| //! Open action catalog, typed argument contracts, and safe Lisp rendering. | |
| //! | |
| //! Basis: Dynamic set of `ActionSpec` descriptors unifying the 48 audited core | |
| //! operations with open `lispm-kit` and Emacs interactive commands. | |
| //! Tightness: Arbitrary S-expressions are unrepresentable; `function` must be a | |
| //! public Emacs symbol outside the dangerous-evaluator denylist, and `ArgContract` | |
| //! admits only fixed typed constants or one domain-validated literal string. | |
| use std::collections::{BTreeMap, BTreeSet}; | |
| use std::fs; | |
| use std::path::Path; | |
| use serde::{Deserialize, Serialize}; | |
| use serde_json::{Map, Value}; | |
| use thiserror::Error; | |
| use unicode_normalization::UnicodeNormalization; | |
| use crate::actions::{ | |
| ActionKind, InputError, ParsedClause, is_folder_basename, is_python_web_url, parse_command, | |
| quote_lisp_string, validate_argument, | |
| }; | |
| use crate::tokenizer::tokenize; | |
| /// Primitives that evaluate code, spawn shells, or destroy host state are never routable. | |
| const DENIED_FUNCTIONS: &[&str] = &[ | |
| "eval", | |
| "eval-expression", | |
| "eval-buffer", | |
| "eval-region", | |
| "eval-defun", | |
| "eval-last-sexp", | |
| "funcall", | |
| "apply", | |
| "load", | |
| "load-file", | |
| "load-library", | |
| "shell-command", | |
| "async-shell-command", | |
| "shell-command-on-region", | |
| "call-process", | |
| "call-process-region", | |
| "start-process", | |
| "start-file-process", | |
| "make-process", | |
| "delete-file", | |
| "delete-directory", | |
| "rename-file", | |
| "copy-file", | |
| "kill-emacs", | |
| "save-buffers-kill-emacs", | |
| "save-buffers-kill-terminal", | |
| ]; | |
| /// Validation failures when constructing or merging an `ActionCatalog`. | |
| pub enum CatalogError { | |
| /// Schema version or structural invariant failed. | |
| Invalid(&'static str), | |
| /// Two entries share the same action identifier with conflicting definitions. | |
| DuplicateId(String), | |
| /// A function name is private, malformed, or on the security denylist. | |
| DisallowedFunction(String), | |
| /// An action description has no English tokens for the action encoder. | |
| EmptyDescription(String), | |
| /// Filesystem read failed. | |
| Io( std::io::Error), | |
| /// JSON decoding failed. | |
| Json( serde_json::Error), | |
| } | |
| /// Typed validation domain for a single-string action parameter. | |
| pub enum StringDomain { | |
| /// Any non-empty Unicode string without NUL characters. | |
| Any, | |
| /// Single trimmed Finder child folder basename without path separators. | |
| FolderBasename, | |
| /// Explicit absolute `http://` or `https://` URL. | |
| HttpUrl, | |
| } | |
| impl StringDomain { | |
| /// Validate `value` against both universal string invariants and this domain. | |
| pub fn validate(self, value: &str) -> Result<(), InputError> { | |
| validate_argument(value)?; | |
| match self { | |
| Self::Any => Ok(()), | |
| Self::FolderBasename if is_folder_basename(value) => Ok(()), | |
| Self::FolderBasename => Err(InputError::InvalidFolderName), | |
| Self::HttpUrl if is_python_web_url(value) => Ok(()), | |
| Self::HttpUrl => Err(InputError::InvalidBrowserUrl), | |
| } | |
| } | |
| } | |
| /// Compile-time or catalog-declared constant argument passed to a `Fixed` command. | |
| pub enum FixedArg { | |
| /// Signed integer constant (such as `1` or `-1` for `other-window`). | |
| Int(i64), | |
| /// String constant (such as `"about:blank"` for `lispm-browser-new-tab`). | |
| Text(String), | |
| } | |
| /// Parameter and rendering contract of an `ActionSpec`. | |
| pub enum ArgContract { | |
| /// Zero user-supplied dynamic arguments; optional typed constants. | |
| Fixed { | |
| /// Constant arguments appended after `function`. | |
| args: Vec<FixedArg>, | |
| }, | |
| /// Exactly one user-supplied quoted string argument. | |
| String { | |
| /// JSON proposal field name (e.g., `"path"`, `"name"`, `"text"`, `"url"`, `"arg"`). | |
| field: String, | |
| /// Domain check enforced before admitting a proposal. | |
| domain: StringDomain, | |
| }, | |
| } | |
| impl ArgContract { | |
| /// Whether this action requires one dynamic quoted string argument. | |
| pub const fn takes_string(&self) -> bool { | |
| matches!(self, Self::String { .. }) | |
| } | |
| } | |
| /// Metadata and execution contract for one open-vocabulary Emacs or LispM action. | |
| pub struct ActionSpec { | |
| /// Stable unique action identifier (used in JSON proposals and supervision). | |
| pub id: String, | |
| /// Public Emacs Lisp function symbol invoked at execution time. | |
| pub function: String, | |
| /// Typed argument contract. | |
| pub contract: ArgContract, | |
| /// Human-readable label and help text encoded by the right tower. | |
| pub description: String, | |
| /// Optional major-mode name scoping when this command is active (`None` = global). | |
| pub mode: Option<String>, | |
| } | |
| /// Check public Emacs Lisp identifier syntax (`^[a-z][a-z0-9-]*$`, no `--` private separator). | |
| pub fn valid_public_symbol(name: &str) -> bool { | |
| let mut bytes = name.bytes(); | |
| let Some(first) = bytes.next() else { | |
| return false; | |
| }; | |
| first.is_ascii_lowercase() | |
| && name.len() <= 128 | |
| && !name.contains("--") | |
| && !name.ends_with('-') | |
| && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') | |
| && !DENIED_FUNCTIONS.contains(&name) | |
| } | |
| /// Expand digits inside mixed alphanumeric identifier tokens outside JSON quotes. | |
| /// | |
| /// Standalone numeric counts (such as `"3"` or `"450"`) contain no ASCII letters | |
| /// and remain untouched so `parse_command` rejects unsupported numeric quantifiers. | |
| pub fn parse_open_command(command: &str) -> Result<Vec<ParsedClause>, InputError> { | |
| let mut rewritten = String::with_capacity(command.len() + 8); | |
| let mut chars = command.chars().peekable(); | |
| let mut in_quotes = false; | |
| let mut escaped = false; | |
| while let Some(&ch) = chars.peek() { | |
| if in_quotes { | |
| chars.next(); | |
| rewritten.push(ch); | |
| if escaped { | |
| escaped = false; | |
| } else if ch == '\\' { | |
| escaped = true; | |
| } else if ch == '"' { | |
| in_quotes = false; | |
| } | |
| continue; | |
| } | |
| if ch == '"' { | |
| chars.next(); | |
| in_quotes = true; | |
| rewritten.push(ch); | |
| continue; | |
| } | |
| if ch.is_ascii_alphanumeric() { | |
| let mut token = String::new(); | |
| while let Some(&c) = chars.peek() { | |
| if c.is_ascii_alphanumeric() { | |
| token.push(c); | |
| chars.next(); | |
| } else { | |
| break; | |
| } | |
| } | |
| let has_alpha = token.bytes().any(|b| b.is_ascii_alphabetic()); | |
| let has_digit = token.bytes().any(|b| b.is_ascii_digit()); | |
| if has_alpha && has_digit { | |
| let expanded = expand_identifier_digits(&token); | |
| rewritten.push_str(expanded.trim()); | |
| } else { | |
| rewritten.push_str(&token); | |
| } | |
| continue; | |
| } | |
| chars.next(); | |
| rewritten.push(ch); | |
| } | |
| parse_command(&rewritten) | |
| } | |
| /// Expand digits in identifiers (such as `1password`) into English words for the tokenizer. | |
| fn expand_identifier_digits(text: &str) -> String { | |
| let mut out = String::with_capacity(text.len() + 8); | |
| for ch in text.chars() { | |
| match ch { | |
| '0' => out.push_str(" zero "), | |
| '1' => out.push_str(" one "), | |
| '2' => out.push_str(" two "), | |
| '3' => out.push_str(" three "), | |
| '4' => out.push_str(" four "), | |
| '5' => out.push_str(" five "), | |
| '6' => out.push_str(" six "), | |
| '7' => out.push_str(" seven "), | |
| '8' => out.push_str(" eight "), | |
| '9' => out.push_str(" nine "), | |
| '-' | '_' | '/' | '.' | ':' => out.push(' '), | |
| c => out.push(c), | |
| } | |
| } | |
| out | |
| } | |
| impl ActionSpec { | |
| /// Validate symbol safety, field names, constant strings, and encodable text. | |
| pub fn validate(&self) -> Result<(), CatalogError> { | |
| if !valid_public_symbol(&self.id) { | |
| return Err(CatalogError::DisallowedFunction(self.id.clone())); | |
| } | |
| if !valid_public_symbol(&self.function) { | |
| return Err(CatalogError::DisallowedFunction(self.function.clone())); | |
| } | |
| if let Some(mode) = &self.mode | |
| && !valid_public_symbol(mode) | |
| { | |
| return Err(CatalogError::DisallowedFunction(mode.clone())); | |
| } | |
| match &self.contract { | |
| ArgContract::Fixed { args } => { | |
| if args.len() > 2 { | |
| return Err(CatalogError::Invalid("at most two fixed constants allowed")); | |
| } | |
| for arg in args { | |
| if let FixedArg::Text(text) = arg | |
| && validate_argument(text).is_err() | |
| { | |
| return Err(CatalogError::Invalid("invalid fixed string constant")); | |
| } | |
| } | |
| } | |
| ArgContract::String { field, .. } => { | |
| if field == "action" || !valid_public_symbol(field) { | |
| return Err(CatalogError::Invalid("invalid string parameter field name")); | |
| } | |
| } | |
| } | |
| if self.encoder_words().is_empty() { | |
| return Err(CatalogError::EmptyDescription(self.id.clone())); | |
| } | |
| Ok(()) | |
| } | |
| /// Build canonical token sequence for the Action Tower (max 48 words). | |
| pub fn encoder_words(&self) -> Vec<String> { | |
| let stripped_id = self.id.strip_prefix("lispm-").unwrap_or(&self.id); | |
| let combined = format!( | |
| "{} {}", | |
| expand_identifier_digits(stripped_id), | |
| expand_identifier_digits(&self.description) | |
| ); | |
| let folded: String = combined.nfkc().flat_map(char::to_lowercase).collect(); | |
| let mut words = tokenize(&folded).unwrap_or_default(); | |
| // Deduplicate adjacent identical tokens while preserving phrase order. | |
| words.dedup(); | |
| if self.contract.takes_string() { | |
| words.truncate(47); | |
| words.push(String::from("NAME")); | |
| } else { | |
| words.truncate(48); | |
| } | |
| words | |
| } | |
| /// Canonical space-joined encoder phrase fed to `tokenizer::encode`. | |
| pub fn encoder_phrase(&self) -> String { | |
| self.encoder_words().join(" ") | |
| } | |
| /// Check whether this action is active given the originating buffer's active mode names. | |
| pub fn is_active_in_modes(&self, active_modes: Option<&[String]>) -> bool { | |
| match (&self.mode, active_modes) { | |
| (None, _) => true, | |
| (Some(_), None) => true, | |
| (Some(required), Some(modes)) => modes.iter().any(|m| m == required), | |
| } | |
| } | |
| } | |
| /// Validated open-vocabulary action catalog preserving deterministic index order. | |
| pub struct ActionCatalog { | |
| /// Schema version, currently one. | |
| pub format_version: u32, | |
| /// Ordered action specifications; the first 48 in default catalogs are the core set. | |
| pub actions: Vec<ActionSpec>, | |
| } | |
| impl Default for ActionCatalog { | |
| fn default() -> Self { | |
| Self::builtin() | |
| } | |
| } | |
| impl ActionCatalog { | |
| /// Construct and validate an `ActionCatalog` from ordered `actions`. | |
| pub fn new(actions: Vec<ActionSpec>) -> Result<Self, CatalogError> { | |
| let catalog = Self { | |
| format_version: 1, | |
| actions, | |
| }; | |
| catalog.validate()?; | |
| Ok(catalog) | |
| } | |
| /// Load an `ActionCatalog` from JSON bytes. | |
| pub fn from_bytes(bytes: &[u8]) -> Result<Self, CatalogError> { | |
| let catalog: Self = serde_json::from_slice(bytes)?; | |
| catalog.validate()?; | |
| Ok(catalog) | |
| } | |
| /// Load `<path>` if present, otherwise return `Self::builtin()`. | |
| pub fn load_or_builtin(path: &Path) -> Result<Self, CatalogError> { | |
| match fs::read(path) { | |
| Ok(bytes) => Self::from_bytes(&bytes), | |
| Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::builtin()), | |
| Err(err) => Err(err.into()), | |
| } | |
| } | |
| /// Return ordered action IDs followed by `"reject"`. | |
| pub fn labels_with_reject(&self) -> Vec<String> { | |
| let mut labels: Vec<String> = self.actions.iter().map(|spec| spec.id.clone()).collect(); | |
| labels.push(String::from("reject")); | |
| labels | |
| } | |
| /// Validate uniqueness, schema version, and every individual `ActionSpec`. | |
| pub fn validate(&self) -> Result<(), CatalogError> { | |
| if self.format_version != 1 { | |
| return Err(CatalogError::Invalid("unsupported catalog format_version")); | |
| } | |
| if self.actions.is_empty() { | |
| return Err(CatalogError::Invalid("action catalog cannot be empty")); | |
| } | |
| let mut seen = BTreeSet::new(); | |
| for spec in &self.actions { | |
| spec.validate()?; | |
| if !seen.insert(spec.id.clone()) { | |
| return Err(CatalogError::DuplicateId(spec.id.clone())); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| /// Look up an `ActionSpec` by its stable `id`. | |
| pub fn get(&self, id: &str) -> Option<&ActionSpec> { | |
| self.actions.iter().find(|spec| spec.id == id) | |
| } | |
| /// Merge `incoming` open actions into `self`, preserving builtin core definitions. | |
| pub fn merge(&self, incoming: &Self) -> Result<Self, CatalogError> { | |
| self.validate()?; | |
| incoming.validate()?; | |
| let builtin_ids: BTreeSet<String> = Self::builtin() | |
| .actions | |
| .into_iter() | |
| .map(|spec| spec.id) | |
| .collect(); | |
| let mut by_id: BTreeMap<String, ActionSpec> = BTreeMap::new(); | |
| let mut order: Vec<String> = Vec::new(); | |
| for spec in &self.actions { | |
| order.push(spec.id.clone()); | |
| by_id.insert(spec.id.clone(), spec.clone()); | |
| } | |
| for spec in &incoming.actions { | |
| if builtin_ids.contains(&spec.id) { | |
| // Core 48 contracts are immutable so benchmarks and safety domains never weaken. | |
| continue; | |
| } | |
| if !by_id.contains_key(&spec.id) { | |
| order.push(spec.id.clone()); | |
| } | |
| by_id.insert(spec.id.clone(), spec.clone()); | |
| } | |
| let merged = order | |
| .into_iter() | |
| .filter_map(|id| by_id.remove(&id)) | |
| .collect(); | |
| Self::new(merged) | |
| } | |
| /// Authoritative 48 core Emacs and LispM actions with rich right-tower descriptions. | |
| pub fn builtin() -> Self { | |
| let fixed = |id: &str, function: &str, args: Vec<FixedArg>, desc: &str| ActionSpec { | |
| id: id.to_owned(), | |
| function: function.to_owned(), | |
| contract: ArgContract::Fixed { args }, | |
| description: desc.to_owned(), | |
| mode: None, | |
| }; | |
| let string = | |
| |id: &str, function: &str, field: &str, domain: StringDomain, desc: &str| ActionSpec { | |
| id: id.to_owned(), | |
| function: function.to_owned(), | |
| contract: ArgContract::String { | |
| field: field.to_owned(), | |
| domain, | |
| }, | |
| description: desc.to_owned(), | |
| mode: None, | |
| }; | |
| let specs = vec![ | |
| fixed("split-window-right", "split-window-right", vec![], "Split window right side by side vertically into two columns"), | |
| fixed("split-window-below", "split-window-below", vec![], "Split window below horizontally stacked top and bottom"), | |
| fixed("other-window", "other-window", vec![FixedArg::Int(1)], "Select next other window pane forward"), | |
| fixed("delete-other-windows", "delete-other-windows", vec![], "Keep only current window maximize single pane close others"), | |
| fixed("balance-windows", "balance-windows", vec![], "Balance equalize all editing window sizes"), | |
| fixed("beginning-of-buffer", "beginning-of-buffer", vec![], "Go move jump to beginning top start of buffer"), | |
| fixed("end-of-buffer", "end-of-buffer", vec![], "Go move jump to end bottom finish of buffer"), | |
| string("switch-to-buffer", "switch-to-buffer", "name", StringDomain::Any, "Switch display show buffer named by string"), | |
| fixed("previous-window", "other-window", vec![FixedArg::Int(-1)], "Select previous preceding window pane backward"), | |
| fixed("delete-window", "delete-window", vec![], "Close delete dismiss current selected window pane"), | |
| fixed("save-buffer", "save-buffer", vec![], "Save write persist current buffer changes to file"), | |
| fixed("undo-only", "undo-only", vec![FixedArg::Int(1)], "Undo revert last editing change"), | |
| fixed("undo-redo", "undo-redo", vec![FixedArg::Int(1)], "Redo restore last undone editing change"), | |
| fixed("beginning-of-line", "beginning-of-line", vec![], "Move point cursor to beginning start of current line"), | |
| fixed("end-of-line", "end-of-line", vec![], "Move point cursor to end of current line"), | |
| fixed("forward-word", "forward-word", vec![FixedArg::Int(1)], "Move step forward ahead by one word"), | |
| fixed("backward-word", "backward-word", vec![FixedArg::Int(1)], "Move step backward back by one word"), | |
| fixed("scroll-up-command", "scroll-up-command", vec![], "Scroll down advance view next page screen"), | |
| fixed("scroll-down-command", "scroll-down-command", vec![], "Scroll up view previous preceding page screen"), | |
| fixed("mark-whole-buffer", "mark-whole-buffer", vec![], "Select mark highlight entire whole buffer text"), | |
| fixed("yank", "yank", vec![], "Paste yank insert latest killed copied text from kill ring"), | |
| fixed("kill-line", "kill-line", vec![], "Kill cut remove rest of current line from cursor to end"), | |
| string("find-file", "find-file", "path", StringDomain::Any, "Open visit read file path in buffer"), | |
| string("search-forward", "search-forward", "text", StringDomain::Any, "Search find forward ahead for literal text string"), | |
| fixed("lispm-finder-home", "lispm-finder-home", vec![], "Open show Finder file manager at home folder directory"), | |
| string("lispm-finder-open-directory", "lispm-finder-open-directory", "path", StringDomain::Any, "Open show directory folder path in Finder"), | |
| fixed("lispm-finder-back", "lispm-finder-back", vec![], "Go navigate back previous directory in Finder history"), | |
| fixed("lispm-finder-forward", "lispm-finder-forward", vec![], "Go navigate forward in Finder folder history"), | |
| fixed("lispm-finder-up", "lispm-finder-up", vec![], "Go up to parent enclosing directory folder in Finder"), | |
| fixed("lispm-finder-refresh", "lispm-finder-refresh", vec![], "Refresh reload rescan current directory in Finder"), | |
| string("lispm-finder-new-folder", "lispm-finder-new-folder", "name", StringDomain::FolderBasename, "Create make new child folder directory named in Finder"), | |
| fixed("lispm-browser", "lispm-browser", vec![], "Open launch show LispM web Browser application"), | |
| string("lispm-browser-open-url", "lispm-browser-open-url", "url", StringDomain::HttpUrl, "Open navigate visit web URL address in Browser"), | |
| fixed("lispm-browser-back", "lispm-browser-back", vec![], "Go navigate back previous web page in Browser history"), | |
| fixed("lispm-browser-forward", "lispm-browser-forward", vec![], "Go navigate forward next web page in Browser history"), | |
| fixed("lispm-browser-reload", "lispm-browser-reload", vec![], "Reload refresh current visible web page in Browser"), | |
| fixed("lispm-browser-new-tab", "lispm-browser-new-tab", vec![FixedArg::Text(String::from("about:blank"))], "Open create new blank empty tab in Browser"), | |
| fixed("lispm-browser-next-tab", "lispm-browser-next-tab", vec![], "Select switch to next following Browser tab"), | |
| fixed("lispm-browser-previous-tab", "lispm-browser-previous-tab", vec![], "Select switch to previous preceding Browser tab"), | |
| fixed("lispm-browser-close-shown-tab", "lispm-browser-close-shown-tab", vec![], "Close dismiss current visible shown Browser tab"), | |
| fixed("lispm-stickies", "lispm-stickies", vec![], "Open show Stickies sticky notes application"), | |
| string("lispm-stickies-new-note", "lispm-stickies-new-note", "text", StringDomain::Any, "Create make new sticky note containing text in Stickies"), | |
| fixed("lispm-stickies-next-note", "lispm-stickies-next-note", vec![], "Select show next following sticky note in Stickies"), | |
| fixed("lispm-stickies-previous-note", "lispm-stickies-previous-note", vec![], "Select show previous preceding sticky note in Stickies"), | |
| fixed("lispm-rotom", "lispm-rotom", vec![], "Open show Rotom model daemon and accounts panel"), | |
| fixed("lispm-comfyui", "lispm-comfyui", vec![], "Open show ComfyUI workflow editor application"), | |
| fixed("lispm-office", "lispm-office", vec![], "Open show LispM Office agent workspace overview"), | |
| fixed("lispm-mail", "lispm-mail", vec![], "Open show LispM Mail email client mailboxes"), | |
| ]; | |
| debug_assert_eq!(specs.len(), ActionKind::ALL.len()); | |
| Self { | |
| format_version: 1, | |
| actions: specs, | |
| } | |
| } | |
| } | |
| /// One validated open-catalog operation ready for Lisp or JSON rendering. | |
| pub struct OpenAction { | |
| /// Action identifier from the catalog. | |
| id: String, | |
| /// Validated public Emacs Lisp function symbol. | |
| function: String, | |
| /// Validated fixed constants or single dynamic literal. | |
| call: OpenCall, | |
| } | |
| enum OpenCall { | |
| Fixed(Vec<FixedArg>), | |
| String { field: String, value: String }, | |
| } | |
| impl OpenAction { | |
| /// Validate `argument` against `spec` and construct an immutable `OpenAction`. | |
| pub fn new(spec: &ActionSpec, argument: Option<String>) -> Result<Self, InputError> { | |
| let call = match (&spec.contract, argument) { | |
| (ArgContract::Fixed { args }, None) => OpenCall::Fixed(args.clone()), | |
| (ArgContract::Fixed { .. }, Some(_)) => return Err(InputError::UnexpectedArgument), | |
| (ArgContract::String { .. }, None) => return Err(InputError::ArgumentRequired), | |
| (ArgContract::String { field, domain }, Some(value)) => { | |
| domain.validate(&value)?; | |
| OpenCall::String { | |
| field: field.clone(), | |
| value, | |
| } | |
| } | |
| }; | |
| Ok(Self { | |
| id: spec.id.clone(), | |
| function: spec.function.clone(), | |
| call, | |
| }) | |
| } | |
| /// Stable action identifier. | |
| pub fn id(&self) -> &str { | |
| &self.id | |
| } | |
| /// Render deterministic Emacs Lisp call without arbitrary code interpolation. | |
| pub fn to_lisp(&self) -> String { | |
| match &self.call { | |
| OpenCall::Fixed(args) if args.is_empty() => format!("({})", self.function), | |
| OpenCall::Fixed(args) => { | |
| let rendered = args | |
| .iter() | |
| .map(|arg| match arg { | |
| FixedArg::Int(n) => n.to_string(), | |
| FixedArg::Text(s) => quote_lisp_string(s), | |
| }) | |
| .collect::<Vec<_>>() | |
| .join(" "); | |
| format!("({} {rendered})", self.function) | |
| } | |
| OpenCall::String { value, .. } => { | |
| format!("({} {})", self.function, quote_lisp_string(value)) | |
| } | |
| } | |
| } | |
| /// Render the canonical JSON action object (`{"action": id, ...}`). | |
| pub fn to_json(&self) -> Value { | |
| let mut object = Map::new(); | |
| object.insert("action".to_owned(), Value::String(self.id.clone())); | |
| if let OpenCall::String { field, value } = &self.call { | |
| object.insert(field.clone(), Value::String(value.clone())); | |
| } | |
| Value::Object(object) | |
| } | |
| } | |
| /// Validated one-or-two-action open program with distinct action IDs. | |
| pub struct OpenProgram { | |
| actions: Vec<OpenAction>, | |
| } | |
| impl OpenProgram { | |
| /// Enforce 1..=2 actions and forbid repeating the same action ID. | |
| pub fn new(actions: Vec<OpenAction>) -> Result<Self, InputError> { | |
| match actions.as_slice() { | |
| [_] => {} | |
| [first, second] if first.id != second.id => {} | |
| [_, _] => return Err(InputError::RepeatedOperation), | |
| _ => return Err(InputError::InvalidProgramLength), | |
| } | |
| Ok(Self { actions }) | |
| } | |
| /// Borrow ordered actions. | |
| pub fn actions(&self) -> &[OpenAction] { | |
| &self.actions | |
| } | |
| /// Render deterministic Emacs Lisp expression (wrapping 2 calls in `progn`). | |
| pub fn to_lisp(&self) -> String { | |
| let calls = self | |
| .actions | |
| .iter() | |
| .map(OpenAction::to_lisp) | |
| .collect::<Vec<_>>() | |
| .join(" "); | |
| if self.actions.len() == 1 { | |
| calls | |
| } else { | |
| format!("(progn {calls})") | |
| } | |
| } | |
| /// Render canonical `{"actions": [...]}` JSON proposal. | |
| pub fn to_json(&self) -> Value { | |
| let mut object = Map::new(); | |
| object.insert( | |
| "actions".to_owned(), | |
| Value::Array(self.actions.iter().map(OpenAction::to_json).collect()), | |
| ); | |
| Value::Object(object) | |
| } | |
| } | |
| mod tests { | |
| use super::*; | |
| use crate::actions::{Action, ActionKind, Program}; | |
| fn builtin_catalog_is_bijective_with_legacy_48_actions_in_lisp_and_json() { | |
| let catalog = ActionCatalog::builtin(); | |
| assert!(catalog.validate().is_ok()); | |
| assert_eq!(catalog.actions.len(), 48); | |
| for (spec, kind) in catalog.actions.iter().zip(ActionKind::ALL) { | |
| assert_eq!(spec.id, kind.label()); | |
| let sample = match &spec.contract { | |
| ArgContract::Fixed { .. } => None, | |
| ArgContract::String { | |
| domain: StringDomain::HttpUrl, | |
| .. | |
| } => Some(String::from("https://example.org/docs")), | |
| _ => Some(String::from("notes.el")), | |
| }; | |
| let legacy = Program::new(vec![Action::new(kind, sample.clone()).unwrap()]).unwrap(); | |
| let open = OpenProgram::new(vec![OpenAction::new(spec, sample).unwrap()]).unwrap(); | |
| assert_eq!(open.to_lisp(), legacy.to_lisp()); | |
| assert_eq!(open.to_json(), legacy.to_json()); | |
| } | |
| } | |
| fn dangerous_and_private_symbols_are_rejected_at_catalog_boundary() { | |
| for bad in [ | |
| "eval", | |
| "shell-command", | |
| "async-shell-command", | |
| "delete-file", | |
| "kill-emacs", | |
| "lispm-finder--private", | |
| "UpperCase", | |
| "bad space", | |
| ] { | |
| let spec = ActionSpec { | |
| id: bad.to_owned(), | |
| function: bad.to_owned(), | |
| contract: ArgContract::Fixed { args: vec![] }, | |
| description: String::from("Perform operation"), | |
| mode: None, | |
| }; | |
| assert!(spec.validate().is_err(), "{bad} must be rejected"); | |
| } | |
| } | |
| fn digit_bearing_open_actions_produce_clean_encoder_tokens() { | |
| let spec = ActionSpec { | |
| id: String::from("lispm-1password-copy-code"), | |
| function: String::from("lispm-1password-copy-code"), | |
| contract: ArgContract::Fixed { args: vec![] }, | |
| description: String::from("Copy One-Time Code in 1Password"), | |
| mode: Some(String::from("lispm-1password-mode")), | |
| }; | |
| spec.validate().unwrap(); | |
| let phrase = spec.encoder_phrase(); | |
| assert!(phrase.contains("one")); | |
| assert!(phrase.contains("password")); | |
| assert!(phrase.contains("copy")); | |
| assert!(phrase.contains("code")); | |
| } | |
| fn parse_open_command_expands_identifier_digits_but_rejects_numeric_counts() { | |
| let clauses = | |
| parse_open_command("open the 1password vault \"https://127.0.0.1:8080/1password\"") | |
| .unwrap(); | |
| assert_eq!(clauses.len(), 1); | |
| assert_eq!(clauses[0].text, "open the one password vault NAME"); | |
| assert_eq!( | |
| clauses[0].name.as_deref(), | |
| Some("https://127.0.0.1:8080/1password") | |
| ); | |
| assert!(parse_open_command("move forward 3 words").is_err()); | |
| assert!(parse_open_command("bake bread at 450 degrees").is_err()); | |
| } | |
| } | |