Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Move portable skill primitives to tinyskills

Steven Enamakel73feacd6656f
diff --git a/.gitmodules b/.gitmodules
index 98a3f0aa8f..3c8b009bd2 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -51,3 +51,6 @@
path = vendor/tinyconnectors
url = https://github.com/tinyhumansai/tinyconnectors
branch = main
+[submodule "vendor/tinyskills"]
+ path = vendor/tinyskills
+ url = https://github.com/tinyhumansai/tinyskills
diff --git a/Cargo.lock b/Cargo.lock
index c45cd84a5a..a94df6f07c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4187,6 +4187,7 @@ dependencies = [
"tinymemory-conformance",
"tinymemory-sources",
"tinyruntime-bus",
+ "tinyskills",
"tinytools",
"tinyvoice-bus",
"tinywallet",
@@ -6807,6 +6808,18 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "tinyskills"
+version = "0.2.1"
+dependencies = [
+ "serde",
+ "serde_json",
+ "serde_yaml",
+ "sha2 0.10.9",
+ "thiserror 2.0.20",
+ "tracing",
+]
+
[[package]]
name = "tinystr"
version = "0.7.6"
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 9207cfed88..c93d7d9ece 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -594,6 +594,8 @@ tinychannels = { version = "0.1", features = ["relay-websocket"], optional = tru
# --features flows` would carry `ureq` and the archive stack for a host that
# never loads a module. The kernel-floor ratchet catches exactly that, and did.
tinybus = { path = "../../vendor/tinybus/crates/tinybus", default-features = false, features = ["macros", "uds"] }
+# Portable skill metadata, parsing, discovery, and filesystem hardening.
+tinyskills = { path = "../../vendor/tinyskills/crates/tinyskills" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_repr = "0.1"
diff --git a/crates/openhuman-core/src/skills/bundled/mod.rs b/crates/openhuman-core/src/skills/bundled/mod.rs
index 7d381b9c1c..4558058772 100644
--- a/crates/openhuman-core/src/skills/bundled/mod.rs
+++ b/crates/openhuman-core/src/skills/bundled/mod.rs
@@ -1,325 +1,46 @@
-//! Skills that ship **inside the binary**.
-//!
-//! A bundled skill is an ordinary SKILL.md bundle — frontmatter, a body, and
-//! `references/` files — whose bytes are `include_str!`'d at compile time from
-//! a directory in this repository. At boot it is written into the workspace
-//! under [`builtin_root`] and from then on it is discovered, described, read
-//! and run by exactly the same code paths as a skill the user installed. There
-//! is no second reader, no virtual filesystem, and no `location: None` case for
-//! downstream code to handle.
-//!
-//! # Why materialise instead of serving from memory
-//!
-//! Every consumer downstream of discovery resolves a real path:
-//! `read_workflow_resource` canonicalises against the bundle root and refuses
-//! symlinks, `run_skill` hands the worker a directory, and the UI shows the
-//! user where the bundle lives. Serving embedded bytes instead would mean an
-//! `Option<PathBuf>` branch in each of those, and the security properties of
-//! the resource reader — traversal and symlink rejection — would have to be
-//! restated for the in-memory case rather than inherited. Writing the files out
-//! once per version is cheaper than that, and it also makes a bundled skill
-//! something the user can read on disk.
-//!
-//! # What this is NOT
-//!
-//! It is not an extension point. The table below is a `const` compiled into the
-//! binary, exactly like [`crate::modules::registry`], and for the
-//! same reason: a table that config or RPC could add entries to would let a
-//! remote party place instructions in front of the model. A skill the user
-//! wants comes from `skill_registry_install`, which has its own review path.
-//!
-//! # Precedence
-//!
-//! Builtin is the **lowest** scope ([`WorkflowScope::Builtin`]). A user or
-//! project skill with the same name shadows it, so shipping a bundle can never
-//! take a name away from someone who already used it.
+//! OpenHuman's compiled-in skill table and product-specific install root.
use std::path::{Path, PathBuf};
-use sha2::{Digest, Sha256};
+pub use tinyskills::{BundledFile, BundledSkill, InstallReport};
-/// One file inside a bundled skill, relative to the bundle directory.
-#[derive(Debug, Clone, Copy)]
-pub struct BundledFile {
- /// Slash-separated path relative to the bundle root (`WORKFLOW.md`,
- /// `references/expressions.md`). Validated by
- /// [`BundledSkill::validate`] — see the test module.
- pub path: &'static str,
- pub contents: &'static str,
-}
-
-/// A skill compiled into the binary.
-#[derive(Debug, Clone, Copy)]
-pub struct BundledSkill {
- /// The on-disk directory name, and the id the model names in `run_skill` /
- /// `describe_workflow`.
- pub dir_name: &'static str,
- pub files: &'static [BundledFile],
-}
-
-impl BundledSkill {
- /// A digest over the bundle's full contents, used to decide whether the
- /// materialised copy on disk is current.
- ///
- /// Both the path and the contents of every file are hashed, each
- /// length-prefixed, so that renaming a file or moving a byte between two
- /// files changes the digest. Without the length prefix the concatenation
- /// `("ab", "c")` and `("a", "bc")` would hash identically.
- pub fn digest(&self) -> String {
- let mut hasher = Sha256::new();
- for file in self.files {
- hasher.update((file.path.len() as u64).to_le_bytes());
- hasher.update(file.path.as_bytes());
- hasher.update((file.contents.len() as u64).to_le_bytes());
- hasher.update(file.contents.as_bytes());
- }
- format!("{:x}", hasher.finalize())
- }
-
- /// Reject a bundle this host will not write out.
- ///
- /// These are compile-time constants from this repository, so none of this
- /// can fire in a shipped build — which is exactly why it is checked by a
- /// test rather than trusted. The cost of being wrong is writing outside the
- /// workspace, and "our own constants are fine" is the assumption that makes
- /// that mistake survivable for one refactor too long.
- pub fn validate(&self) -> Result<(), String> {
- if self.dir_name.is_empty()
- || self.dir_name.starts_with('.')
- || self.dir_name.contains('/')
- || self.dir_name.contains('\\')
- {
- return Err(format!(
- "invalid bundled skill dir_name `{}`",
- self.dir_name
- ));
- }
- if self.files.is_empty() {
- return Err(format!("bundled skill `{}` has no files", self.dir_name));
- }
- let has_manifest = self.files.iter().any(|f| {
- f.path == super::ops_types::WORKFLOW_MD || f.path == super::ops_types::SKILL_MD
- });
- if !has_manifest {
- return Err(format!(
- "bundled skill `{}` has no WORKFLOW.md or SKILL.md; discovery would skip it",
- self.dir_name
- ));
- }
- for file in self.files {
- validate_relative_path(self.dir_name, file.path)?;
- }
- Ok(())
- }
-}
-
-fn validate_relative_path(dir_name: &str, path: &str) -> Result<(), String> {
- if path.is_empty() {
- return Err(format!("bundled skill `{dir_name}` has an empty file path"));
- }
- if path.starts_with('/') || path.starts_with('\\') || path.contains(':') {
- return Err(format!(
- "bundled skill `{dir_name}` file `{path}` is not workspace-relative"
- ));
- }
- for component in path.split('/') {
- if component.is_empty() || component == "." || component == ".." {
- return Err(format!(
- "bundled skill `{dir_name}` file `{path}` has a traversal component"
- ));
- }
- if component.starts_with('.') {
- return Err(format!(
- "bundled skill `{dir_name}` file `{path}` has a dotfile component; \
- discovery skips those"
- ));
- }
- }
- Ok(())
-}
-
-/// The compiled-in table.
-///
-/// Gated per entry, not as a whole: `flow-authoring` teaches the flows node
-/// vocabulary, and in a build without the `flows` feature there is nothing for
-/// it to author. Shipping it anyway would put a manual for absent tools in
-/// front of the model — the same failure the `Off` tool mode exists to avoid.
+/// Skills compiled into this product build.
pub const BUNDLED: &[BundledSkill] = &[
#[cfg(feature = "flows")]
crate::flows::skills::FLOW_AUTHORING,
];
-/// Where materialised bundles live.
-///
-/// Its own root rather than a subdirectory of `.openhuman/skills/`, because the
-/// contents are ours to overwrite: [`install`] deletes and rewrites a bundle
-/// whose digest moved, and doing that inside a directory the user also writes
-/// to would eventually delete something of theirs.
+/// Product-owned root for materialized builtin skills.
pub fn builtin_root(workspace_dir: &Path) -> PathBuf {
workspace_dir.join(".openhuman").join("builtin-skills")
}
-/// Name of the digest sidecar written beside each materialised bundle.
-///
-/// A dotfile so `scan_root` skips it (it skips `.`-prefixed entries) and it is
-/// never mistaken for a skill resource.
-const DIGEST_FILE: &str = ".digest";
-
-/// What [`install`] did, for the boot log.
-#[derive(Debug, Default, PartialEq, Eq)]
-pub struct InstallReport {
- pub written: Vec<String>,
- pub unchanged: Vec<String>,
- pub failed: Vec<(String, String)>,
-}
-
-/// Materialise every bundled skill into `workspace_dir`, skipping those whose
-/// on-disk digest already matches.
-///
-/// Never returns `Err`: a workspace that cannot take a builtin skill should
-/// boot without it rather than not boot. Failures land in
-/// [`InstallReport::failed`] and are logged.
+/// Materialize all compiled-in skills and log the outcome.
pub fn install(workspace_dir: &Path) -> InstallReport {
let root = builtin_root(workspace_dir);
- let mut report = InstallReport::default();
-
- for skill in BUNDLED {
- let name = skill.dir_name.to_string();
- match install_one(&root, skill) {
- Ok(true) => {
- tracing::info!(skill = %name, "[skills][bundled] wrote builtin skill");
- report.written.push(name);
- }
- Ok(false) => {
- tracing::debug!(skill = %name, "[skills][bundled] builtin skill already current");
- report.unchanged.push(name);
- }
- Err(err) => {
- tracing::warn!(
- skill = %name,
- error = %err,
- "[skills][bundled] failed to install builtin skill; it will be absent this run"
- );
- report.failed.push((name, err));
- }
- }
+ let report = tinyskills::bundle::install(&root, BUNDLED);
+ for skill in &report.written {
+ tracing::info!(skill, "[skills][bundled] wrote builtin skill");
+ }
+ for skill in &report.unchanged {
+ tracing::debug!(skill, "[skills][bundled] builtin skill already current");
+ }
+ for (skill, error) in &report.failed {
+ tracing::warn!(
+ skill,
+ error,
+ "[skills][bundled] failed to install builtin skill"
+ );
}
-
- tracing::debug!(
- root = %root.display(),
- written = report.written.len(),
- unchanged = report.unchanged.len(),
- failed = report.failed.len(),
- "[skills][bundled] install:exit"
- );
report
}
-/// Boot entry point: install every bundled skill and discard the report.
-///
-/// Separate from [`install`] only so it can have the same signature as the
-/// skills-off stub, which cannot name [`InstallReport`] (that type lives inside
-/// the gate). The one caller logs nothing extra — [`install`] already logs per
-/// skill — so nothing is lost by dropping the report here.
+/// Boot entry point used by runtime composition.
pub fn install_bundled_skills(workspace_dir: &Path) {
let _ = install(workspace_dir);
}
-/// Whether `dir` contains exactly the bytes compiled for `skill`.
-///
-/// Discovery must not trust the sidecar alone: a user who can modify the
-/// materialised directory must not be able to turn arbitrary instructions into
-/// a `Builtin` workflow. Check every compiled file and reject extra entries,
-/// symlinks, and non-regular files.
+/// Verify a materialized builtin still exactly matches its compiled bytes.
pub fn is_current_materialization(dir: &Path, skill: &BundledSkill) -> bool {
- let Ok(dir_meta) = std::fs::symlink_metadata(dir) else {
- return false;
- };
- if skill.validate().is_err() || !dir_meta.is_dir() || dir_meta.file_type().is_symlink() {
- return false;
- }
- let expected: std::collections::HashSet<&str> = skill.files.iter().map(|f| f.path).collect();
- for file in skill.files {
- let path = dir.join(file.path);
- let Ok(meta) = std::fs::symlink_metadata(&path) else {
- return false;
- };
- if !meta.is_file() || meta.file_type().is_symlink() {
- return false;
- }
- let Ok(contents) = std::fs::read(&path) else {
- return false;
- };
- if contents != file.contents.as_bytes() {
- return false;
- }
- }
- let mut stack = vec![dir.to_path_buf()];
- while let Some(current) = stack.pop() {
- let Ok(entries) = std::fs::read_dir(&current) else {
- return false;
- };
- for entry in entries.flatten() {
- let Ok(meta) = std::fs::symlink_metadata(entry.path()) else {
- return false;
- };
- let entry_path = entry.path();
- let Ok(relative) = entry_path.strip_prefix(dir) else {
- return false;
- };
- let relative = relative.to_string_lossy().replace('\\', "/");
- if meta.file_type().is_symlink() || (!meta.is_dir() && !meta.is_file()) {
- return false;
- }
- if meta.is_dir() {
- stack.push(entry.path());
- } else if relative != DIGEST_FILE && !expected.contains(relative.as_str()) {
- return false;
- }
- }
- }
- true
-}
-
-/// Returns `Ok(true)` when the bundle was (re)written, `Ok(false)` when the
-/// on-disk copy was already current.
-fn install_one(root: &Path, skill: &BundledSkill) -> Result<bool, String> {
- skill.validate()?;
-
- let dir = root.join(skill.dir_name);
- let digest = skill.digest();
- let digest_path = dir.join(DIGEST_FILE);
-
- if std::fs::read_to_string(&digest_path).is_ok_and(|found| found.trim() == digest) {
- return Ok(false);
- }
-
- // Remove rather than overwrite: a previous version may have shipped a file
- // this one does not, and leaving it behind would let a stale reference doc
- // keep answering `read_workflow_resource` calls forever.
- if dir.exists() {
- std::fs::remove_dir_all(&dir)
- .map_err(|e| format!("failed to clear {}: {e}", dir.display()))?;
- }
-
- for file in skill.files {
- let target = dir.join(file.path);
- if let Some(parent) = target.parent() {
- std::fs::create_dir_all(parent)
- .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
- }
- std::fs::write(&target, file.contents)
- .map_err(|e| format!("failed to write {}: {e}", target.display()))?;
- }
-
- // Written last, so an interrupted install leaves no digest and the next
- // boot rewrites the bundle rather than trusting a half-written one.
- std::fs::write(&digest_path, &digest)
- .map_err(|e| format!("failed to write {}: {e}", digest_path.display()))?;
-
- Ok(true)
+ tinyskills::bundle::is_current_materialization(dir, *skill)
}
-
-#[cfg(test)]
-#[path = "mod_tests.rs"]
-mod mod_tests;
diff --git a/crates/openhuman-core/src/skills/mod.rs b/crates/openhuman-core/src/skills/mod.rs
index 57095a31c4..e3b020a1af 100644
--- a/crates/openhuman-core/src/skills/mod.rs
+++ b/crates/openhuman-core/src/skills/mod.rs
@@ -58,8 +58,6 @@ pub mod ops_create;
#[cfg(feature = "skills")]
pub mod ops_discover;
#[cfg(feature = "skills")]
-mod ops_discover_resource;
-#[cfg(feature = "skills")]
pub mod ops_install;
#[cfg(feature = "skills")]
pub mod ops_parse;
diff --git a/crates/openhuman-core/src/skills/ops_discover/collision.rs b/crates/openhuman-core/src/skills/ops_discover/collision.rs
index 30b0bac948..6eece955e2 100644
--- a/crates/openhuman-core/src/skills/ops_discover/collision.rs
+++ b/crates/openhuman-core/src/skills/ops_discover/collision.rs
@@ -1,92 +1,7 @@
-//! Cross-scope name-collision resolution for discovered workflows: which
-//! scope wins on a same-name (or same-`dir_name`) hit, and the warning left
-//! on the survivor / shadowed entries.
+//! Compatibility helper for scope precedence tests.
-use std::collections::HashMap;
+use crate::skills::ops_types::WorkflowScope;
-use crate::skills::ops_types::{Workflow, WorkflowScope};
-
-pub(super) fn absorb(by_name: &mut HashMap<String, Workflow>, incoming: Vec<Workflow>) {
- for mut skill in incoming {
- let key = skill.name.clone();
- // A workflow's runnable identity is `dir_name`, while `name` is only
- // display metadata. Collapse on either so a profile-local `foo/` also
- // shadows a global `foo/` whose frontmatter happens to use a different
- // display name. Otherwise registry lookup by slug could nondeterministically
- // select the global copy.
- let collision_keys: Vec<String> = by_name
- .iter()
- .filter(|(existing_name, existing)| {
- existing_name.as_str() == key || existing.dir_name == skill.dir_name
- })
- .map(|(existing_name, _)| existing_name.clone())
- .collect();
-
- if let Some((_, highest_name, highest_scope)) = collision_keys
- .iter()
- .filter_map(|collision_key| by_name.get(collision_key))
- .map(|existing| {
- (
- precedence(existing.scope),
- existing.name.clone(),
- existing.scope,
- )
- })
- .max_by_key(|(rank, _, _)| *rank)
- {
- if precedence(skill.scope) < precedence(highest_scope) {
- if let Some(kept) = by_name.get_mut(&highest_name) {
- kept.warnings.push(format!(
- "workflow id '{}' or name '{}' also declared in {:?} scope at {} (ignored)",
- skill.dir_name,
- skill.name,
- skill.scope,
- skill
- .location
- .as_deref()
- .map(|p| p.display().to_string())
- .unwrap_or_else(|| "<unknown>".to_string())
- ));
- }
- continue;
- }
- }
-
- for collision_key in collision_keys {
- if let Some(loser) = by_name.remove(&collision_key) {
- skill.warnings.push(format!(
- "shadowed {:?}-scope skill '{}' (workflow id '{}') at {}",
- loser.scope,
- loser.name,
- loser.dir_name,
- loser
- .location
- .as_deref()
- .map(|p| p.display().to_string())
- .unwrap_or_else(|| "<unknown>".to_string())
- ));
- }
- }
- by_name.insert(key, skill);
- }
-}
-
-pub(super) fn precedence(scope: WorkflowScope) -> u8 {
- match scope {
- // Builtin sits below everything, including Legacy: a bundle that ships
- // with the binary must never shadow something the user installed or
- // wrote. Adding a builtin skill is then a change that cannot take a
- // name away from an existing workspace.
- WorkflowScope::Builtin => 0,
- WorkflowScope::Legacy => 1,
- WorkflowScope::User => 2,
- WorkflowScope::Project => 3,
- // Profile-local skills win against every global scope for their owner.
- WorkflowScope::Profile => 4,
- // Flows are never discovered by this scanner, so they never take part
- // in a name collision resolved here. Ranked above everything so that
- // if one ever reaches this function the answer is deterministic rather
- // than accidental.
- WorkflowScope::Flow => 5,
- }
+pub(super) const fn precedence(scope: WorkflowScope) -> u8 {
+ scope.precedence()
}
diff --git a/crates/openhuman-core/src/skills/ops_discover/resource.rs b/crates/openhuman-core/src/skills/ops_discover/resource.rs
index 2e5efb941a..e09c1b70d1 100644
--- a/crates/openhuman-core/src/skills/ops_discover/resource.rs
+++ b/crates/openhuman-core/src/skills/ops_discover/resource.rs
@@ -1,38 +1,13 @@
-//! Reading a bundled skill resource file, hardened against traversal and
-//! symlink escape, plus the skill-id resolution it relies on.
+//! OpenHuman discovery context around `tinyskills` resource reads.
+use std::collections::HashSet;
use std::path::Path;
-use crate::skills::ops_discover_resource::resolve_workflow_for_resource;
-use crate::skills::ops_types::{WorkflowScope, MAX_WORKFLOW_RESOURCE_BYTES};
+use crate::skills::ops_types::WorkflowScope;
use super::api::load_workflow_metadata_for_profile;
use super::scan::scan_root;
-/// Read a bundled skill resource as UTF-8 text, hardened against directory
-/// traversal, symlink escape, and oversized payloads.
-///
-/// `skill_id` identifies the skill by its discovered `name` or its on-disk
-/// `dir_name` slug — the same identifiers surfaced in the UI summary. The
-/// skill is resolved by running the standard
-/// discovery pipeline (`dirs::home_dir()` + `workspace_dir`, honoring the
-/// `.openhuman/trust` marker) and locating the matching entry; this keeps the
-/// read scoped to legitimately installed skills and reuses all the symlink /
-/// traversal hardening already baked into discovery.
-///
-/// `relative_path` is resolved relative to the skill's on-disk directory
-/// (the parent of its `SKILL.md` / `skill.json`). All of the following are
-/// rejected with an error:
-///
-/// * paths that canonicalize outside the skill root (traversal),
-/// * paths whose final component or any intermediate component is a symlink
-/// (link-follow escape),
-/// * non-file targets (directories, sockets, fifos),
-/// * files larger than [`MAX_WORKFLOW_RESOURCE_BYTES`],
-/// * non-UTF-8 byte contents (binary files must be surfaced some other way —
-/// no lossy replacement).
-///
-/// On success returns the file's contents as an owned `String`.
pub fn read_workflow_resource(
workspace_dir: &Path,
skill_id: &str,
@@ -41,157 +16,29 @@ pub fn read_workflow_resource(
read_workflow_resource_with_profile(workspace_dir, skill_id, relative_path, None)
}
-/// The dir_name/name set of skills discovered under a profile-local skills root.
-///
-/// Used by the `describe_workflow` / `read_workflow_resource` / `run_workflow`
-/// tools to treat a profile's private skills as implicitly allowed for their
-/// owner (they bypass the `allowed_skills` allowlist, mirroring `list_workflows`).
-/// Empty when no profile root is active, so the profile-less session and other
-/// profiles are unaffected.
-pub fn profile_local_skill_ids(
- profile_skills_root: Option<&Path>,
-) -> std::collections::HashSet<String> {
+pub fn profile_local_skill_ids(profile_skills_root: Option<&Path>) -> HashSet<String> {
let Some(root) = profile_skills_root else {
- return std::collections::HashSet::new();
+ return HashSet::new();
};
scan_root(root, WorkflowScope::Profile)
.into_iter()
- .flat_map(|w| {
- let mut ids = vec![w.name];
- if !w.dir_name.is_empty() {
- ids.push(w.dir_name);
- }
- ids
- })
+ .flat_map(|workflow| [workflow.name, workflow.dir_name])
+ .filter(|id| !id.is_empty())
.collect()
}
-/// Like [`read_workflow_resource`], but resolves the skill against the active
-/// profile's private skills root too (`<workspace>/personalities/<id>/skills/`)
-/// when `profile_skills_root` is supplied. `None` is byte-identical to
-/// [`read_workflow_resource`].
pub fn read_workflow_resource_with_profile(
workspace_dir: &Path,
skill_id: &str,
relative_path: &Path,
profile_skills_root: Option<&Path>,
) -> Result<String, String> {
- tracing::debug!(
- skill_id = %skill_id,
- relative_path = %relative_path.display(),
- workspace = %workspace_dir.display(),
- has_profile_root = profile_skills_root.is_some(),
- "[skills] read_workflow_resource: entry"
- );
-
if skill_id.trim().is_empty() {
return Err("skill_id must not be empty".to_string());
}
-
- let relative_str = relative_path.to_string_lossy();
- if relative_str.trim().is_empty() {
- return Err("relative_path must not be empty".to_string());
- }
- if relative_path.is_absolute() {
- return Err("relative_path must be relative, not absolute".to_string());
- }
- // Reject any component that is `..`, is empty, starts with `.`, or is the
- // root. `..` is the obvious traversal vector; the others are defense in
- // depth against unusual path inputs (e.g. `./`, `//foo`, Windows `C:`).
- for component in relative_path.components() {
- use std::path::Component;
- match component {
- Component::Normal(_) => {}
- Component::ParentDir => {
- return Err("relative_path must not contain '..' components".to_string());
- }
- Component::CurDir | Component::RootDir | Component::Prefix(_) => {
- return Err("relative_path must be a plain relative path".to_string());
- }
- }
- }
-
- // Resolve the skill by running the standard discovery pipeline. We reuse
- // `load_workflow_metadata_for_profile` (which honors both user and workspace
- // roots plus the trust marker, and the active profile's private root when
- // supplied) so the resource read is scoped to the exact same set of skills
- // the owner would already have seen listed.
- let skill = resolve_workflow_for_resource(
+ let skill = tinyskills::resolve_skill(
load_workflow_metadata_for_profile(workspace_dir, profile_skills_root),
skill_id,
)?;
- let skill_root = skill
- .location
- .as_deref()
- .and_then(|p| p.parent())
- .ok_or_else(|| format!("skill '{skill_id}' has no on-disk location"))?
- .to_path_buf();
-
- // Canonicalize the root first. The root must itself be a real directory
- // on disk (not a symlink). Reject early if this fails.
- let canonical_root = std::fs::canonicalize(&skill_root).map_err(|e| {
- format!(
- "failed to canonicalize skill root {}: {e}",
- skill_root.display()
- )
- })?;
-
- let requested = canonical_root.join(relative_path);
-
- // Pre-check the immediate target with `symlink_metadata` so we catch
- // symlinked leaves before `canonicalize` silently follows them.
- let leaf_meta = std::fs::symlink_metadata(&requested)
- .map_err(|e| format!("failed to stat resource {}: {e}", requested.display()))?;
- if leaf_meta.file_type().is_symlink() {
- return Err("resource path is a symlink".to_string());
- }
- if !leaf_meta.is_file() {
- return Err("resource path is not a regular file".to_string());
- }
-
- // Size gate — check via metadata before reading so we never allocate the
- // buffer for an oversized file.
- let size = leaf_meta.len();
- if size > MAX_WORKFLOW_RESOURCE_BYTES {
- return Err(format!(
- "resource file is {size} bytes, exceeds limit of {MAX_WORKFLOW_RESOURCE_BYTES}"
- ));
- }
-
- // Canonicalize the full path and verify it stays within the skill root.
- // This catches any symlink reachable via an intermediate path component
- // that was created after our initial checks (race-ish, but the
- // `is_symlink` check above makes the obvious attack infeasible).
- let canonical_requested = std::fs::canonicalize(&requested).map_err(|e| {
- format!(
- "failed to canonicalize resource {}: {e}",
- requested.display()
- )
- })?;
- if !canonical_requested.starts_with(&canonical_root) {
- return Err(format!(
- "resource path escapes skill root: {}",
- canonical_requested.display()
- ));
- }
-
- // Read the bytes and enforce strict UTF-8 (no lossy replacement — we
- // would rather refuse a binary file than silently mangle it).
- let bytes = std::fs::read(&canonical_requested).map_err(|e| {
- format!(
- "failed to read resource {}: {e}",
- canonical_requested.display()
- )
- })?;
- let content = std::str::from_utf8(&bytes)
- .map_err(|e| format!("resource is not valid UTF-8 text: {e}"))?
- .to_string();
-
- tracing::debug!(
- skill_id = %skill_id,
- bytes = bytes.len(),
- "[skills] read_workflow_resource: success"
- );
-
- Ok(content)
+ tinyskills::read_resource(&skill, relative_path)
}
diff --git a/crates/openhuman-core/src/skills/ops_discover/scan.rs b/crates/openhuman-core/src/skills/ops_discover/scan.rs
index 9c57c5d737..0761e7af84 100644
--- a/crates/openhuman-core/src/skills/ops_discover/scan.rs
+++ b/crates/openhuman-core/src/skills/ops_discover/scan.rs
@@ -2,30 +2,9 @@
//! into `Workflow` entries, and the shared multi-root scan engine that both
//! the full discovery surface and the automations-only view share.
-use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use crate::skills::ops_parse::{load_from_legacy_manifest, load_from_workflow_md};
-use crate::skills::ops_types::{Workflow, WorkflowScope, SKILL_JSON, SKILL_MD, WORKFLOW_MD};
-
-use super::collision::absorb;
-
-const EXCLUDED_SKILL_DIRS: &[&str] = &[
- ".git",
- ".github",
- ".hub",
- ".archive",
- ".venv",
- "venv",
- "node_modules",
- "site-packages",
- "__pycache__",
- ".tox",
- ".nox",
- ".pytest_cache",
- ".mypy_cache",
- ".ruff_cache",
-];
+use crate::skills::ops_types::{Workflow, WorkflowScope};
/// Which on-disk root category a bundle was discovered under.
///
@@ -67,7 +46,7 @@ pub(super) fn discover_filtered(
);
// Scan order matters for collision resolution: the last scope to register
// a name wins, so we scan user first, then project, then legacy.
- let mut by_name: HashMap<String, Workflow> = HashMap::new();
+ let mut discovered = Vec::new();
// Builtin skills (`<workspace>/.openhuman/builtin-skills/`) are a skill
// root scanned FIRST and at the lowest precedence, so every other scope
@@ -83,10 +62,7 @@ pub(super) fn discover_filtered(
scope = ?WorkflowScope::Builtin,
"[workflows] discover:branch:builtin"
);
- absorb(
- &mut by_name,
- scan_bundled_root(&root, WorkflowScope::Builtin),
- );
+ discovered.extend(scan_bundled_root(&root, WorkflowScope::Builtin));
}
}
@@ -99,7 +75,7 @@ pub(super) fn discover_filtered(
scope = ?WorkflowScope::User,
"[workflows] discover:branch:user"
);
- absorb(&mut by_name, scan_root(&root, WorkflowScope::User));
+ discovered.extend(scan_root(&root, WorkflowScope::User));
}
}
}
@@ -114,7 +90,7 @@ pub(super) fn discover_filtered(
scope = ?WorkflowScope::Project,
"[workflows] discover:branch:project"
);
- absorb(&mut by_name, scan_root(&root, WorkflowScope::Project));
+ discovered.extend(scan_root(&root, WorkflowScope::Project));
}
}
}
@@ -129,7 +105,7 @@ pub(super) fn discover_filtered(
scope = ?WorkflowScope::Legacy,
"[workflows] discover:branch:legacy"
);
- absorb(&mut by_name, scan_root(&legacy_root, WorkflowScope::Legacy));
+ discovered.extend(scan_root(&legacy_root, WorkflowScope::Legacy));
}
}
@@ -147,21 +123,17 @@ pub(super) fn discover_filtered(
scope = ?WorkflowScope::Profile,
"[profiles] discover:branch:profile-local skills"
);
- let before = by_name.len();
- absorb(
- &mut by_name,
- scan_root(profile_root, WorkflowScope::Profile),
- );
+ let before = discovered.len();
+ discovered.extend(scan_root(profile_root, WorkflowScope::Profile));
tracing::debug!(
names_before = before,
- names_after = by_name.len(),
+ names_after = discovered.len(),
"[profiles] profile-local skills absorbed (profile scope wins same-name collisions)"
);
}
}
- let mut out: Vec<Workflow> = by_name.into_values().collect();
- out.sort_by(|a, b| a.name.cmp(&b.name));
+ let out = tinyskills::resolve_collisions(discovered);
tracing::debug!(discovered_count = out.len(), "[workflows] discover:exit");
out
}
@@ -171,7 +143,8 @@ fn scan_bundled_root(root: &Path, scope: WorkflowScope) -> Vec<Workflow> {
for bundled in crate::skills::bundled::BUNDLED {
let dir = root.join(bundled.dir_name);
if crate::skills::bundled::is_current_materialization(&dir, bundled) {
- if let Some(workflow) = load_skill_dir(&dir, bundled.dir_name, scope) {
+ if let Some(mut workflow) = tinyskills::load_skill_dir(&dir, scope) {
+ normalize_source_format(&mut workflow);
out.push(workflow);
}
}
@@ -206,84 +179,15 @@ fn project_roots(workspace: &Path) -> Vec<(PathBuf, RootKind)> {
}
pub(super) fn scan_root(root: &Path, scope: WorkflowScope) -> Vec<Workflow> {
- let mut out = Vec::new();
- scan_root_inner(root, scope, &mut out);
- out.sort_by(|a, b| a.dir_name.cmp(&b.dir_name));
- out
-}
-
-fn scan_root_inner(root: &Path, scope: WorkflowScope, out: &mut Vec<Workflow>) {
- let entries = match std::fs::read_dir(root) {
- Ok(entries) => entries,
- Err(_) => return,
- };
-
- // `read_dir` order is unspecified. When two sibling directories declare
- // the same logical `frontmatter.name` (which can differ from the folder
- // name), cross-scope/same-scope deduplication downstream would otherwise
- // pick a non-deterministic winner across runs. Sort by on-disk directory
- // name for a stable, reproducible order.
- let mut entries: Vec<_> = entries.flatten().collect();
- entries.sort_by_key(|entry| entry.file_name());
-
- for entry in entries {
- // Use `file_type()` rather than `path.is_dir()` so a symlinked
- // child cannot be loaded as a skill. `is_dir()` dereferences
- // symlinks, which would re-open out-of-tree loading even though
- // `walk_files` already rejects symlinks deeper in the resource
- // walker. Skip both symlinks and non-directory entries here; if
- // the `file_type()` call itself fails (rare — transient I/O),
- // treat it as "not safe to traverse" and skip.
- let Ok(file_type) = entry.file_type() else {
- continue;
- };
- if file_type.is_symlink() || !file_type.is_dir() {
- continue;
- }
- let path = entry.path();
- let dir_name = entry.file_name().to_string_lossy().to_string();
- if dir_name.starts_with('.') || EXCLUDED_SKILL_DIRS.contains(&dir_name.as_str()) {
- continue;
- }
- if let Some(skill) = load_skill_dir(&path, &dir_name, scope) {
- out.push(skill);
- continue;
- }
- scan_root_inner(&path, scope, out);
+ let mut workflows = tinyskills::scan_root(root, scope);
+ for workflow in &mut workflows {
+ normalize_source_format(workflow);
}
+ workflows
}
-fn load_skill_dir(dir: &Path, dir_name: &str, scope: WorkflowScope) -> Option<Workflow> {
- // WORKFLOW.md is the current filename; SKILL.md is read for back-compat
- // with workflows authored before the rename.
- let workflow_md = dir.join(WORKFLOW_MD);
- let legacy_md = dir.join(SKILL_MD);
- let legacy_manifest = dir.join(SKILL_JSON);
-
- // `exists()` follows symlinks, so a manifest could point at an arbitrary
- // file outside the bundle and discovery would ingest its contents into the
- // catalog/prompt flow. Since the legacy `skills/` roots are scanned without
- // a trust marker, require a real (non-symlink) regular file before loading.
- let is_safe_manifest = |path: &Path| {
- matches!(
- std::fs::symlink_metadata(path),
- Ok(meta) if meta.is_file() && !meta.file_type().is_symlink()
- )
- };
-
- if is_safe_manifest(&workflow_md) {
- return Some(load_from_workflow_md(&workflow_md, dir, dir_name, scope));
- }
- if is_safe_manifest(&legacy_md) {
- return Some(load_from_workflow_md(&legacy_md, dir, dir_name, scope));
- }
- if is_safe_manifest(&legacy_manifest) {
- return Some(load_from_legacy_manifest(
- &legacy_manifest,
- dir,
- dir_name,
- scope,
- ));
+fn normalize_source_format(workflow: &mut Workflow) {
+ if workflow.source_format == "agentskills" {
+ workflow.source_format = "openhuman".to_string();
}
- None
}
diff --git a/crates/openhuman-core/src/skills/ops_discover_resource.rs b/crates/openhuman-core/src/skills/ops_discover_resource.rs
deleted file mode 100644
index 1517c7aa04..0000000000
--- a/crates/openhuman-core/src/skills/ops_discover_resource.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-//! Resolution helpers for reading resources from discovered skills.
-
-use crate::skills::ops_types::Workflow;
-
-pub(super) fn resolve_workflow_for_resource(
- workflows: Vec<Workflow>,
- skill_id: &str,
-) -> Result<Workflow, String> {
- let mut dir_match: Option<Workflow> = None;
- let mut name_match: Option<Workflow> = None;
-
- for workflow in workflows {
- if workflow.dir_name == skill_id {
- if dir_match.is_some() {
- return Err(format!(
- "skill id '{skill_id}' is ambiguous across multiple skill directories"
- ));
- }
- dir_match = Some(workflow);
- continue;
- }
- if workflow.name == skill_id {
- if name_match.is_some() {
- return Err(format!(
- "skill name '{skill_id}' is ambiguous; use the directory id"
- ));
- }
- name_match = Some(workflow);
- }
- }
- match (dir_match, name_match) {
- (Some(dir_skill), Some(name_skill)) if dir_skill.location == name_skill.location => {
- Ok(dir_skill)
- }
- (Some(_), Some(_)) => Err(format!(
- "skill id '{skill_id}' matches both a directory id and a different skill name"
- )),
- (Some(skill), None) | (None, Some(skill)) => Ok(skill),
- (None, None) => Err(format!("skill '{skill_id}' not found")),
- }
-}
diff --git a/crates/openhuman-core/src/skills/ops_parse.rs b/crates/openhuman-core/src/skills/ops_parse.rs
index bcff408ab0..bb98dd992a 100644
--- a/crates/openhuman-core/src/skills/ops_parse.rs
+++ b/crates/openhuman-core/src/skills/ops_parse.rs
@@ -1,323 +1,37 @@
-//! SKILL.md parsing, resource inventory, and skill-resource reading.
+//! Compatibility facade over the portable `tinyskills` document parser.
-use std::path::{Path, PathBuf};
+use std::path::Path;
-use super::ops_types::{
- detect_source_format, extract_author, extract_related_skills, extract_tags, extract_version,
-};
-use super::ops_types::{
- LegacyWorkflowManifest, Workflow, WorkflowFrontmatter, WorkflowScope, MAX_DESCRIPTION_LEN,
- MAX_NAME_LEN, RESOURCE_DIRS,
-};
+use super::ops_types::{Workflow, WorkflowFrontmatter, WorkflowScope};
+
+pub use tinyskills::inventory_resources;
-/// Split a `SKILL.md` file into parsed frontmatter and the remaining body.
-///
-/// Accepts frontmatter delimited by leading `---` lines. Returns `None` when
-/// the file cannot be read or the frontmatter block is unterminated.
-///
-/// The third element of the tuple carries parse-level diagnostics — for now
-/// just the YAML deserialisation error when frontmatter exists but is
-/// malformed. Callers merge these into the skill's user-visible warnings so
-/// the catalog surfaces the real cause instead of a generic "could not parse"
-/// placeholder.
pub fn parse_workflow_md(path: &Path) -> Option<(WorkflowFrontmatter, String, Vec<String>)> {
- let content = std::fs::read_to_string(path).ok()?;
- parse_workflow_md_str(&content)
+ tinyskills::parse_skill(path)
}
-/// Content-only variant of [`parse_workflow_md`] used when the SKILL.md has been
-/// fetched over HTTPS (see [`install_workflow_from_url`]) and has not yet landed
-/// on disk. Returns `None` when the frontmatter block is opened with `---` but
-/// never terminated — the same failure mode the file-based parser rejects.
pub fn parse_workflow_md_str(content: &str) -> Option<(WorkflowFrontmatter, String, Vec<String>)> {
- let mut lines = content.lines();
- let first = lines.next()?;
- if first.trim() != "---" {
- // No frontmatter — treat whole file as body.
- return Some((
- WorkflowFrontmatter::default(),
- content.to_string(),
- Vec::new(),
- ));
- }
-
- let mut yaml = String::new();
- let mut terminated = false;
- let mut body = String::new();
- for line in lines {
- if line.trim() == "---" {
- terminated = true;
- continue;
- }
- if !terminated {
- yaml.push_str(line);
- yaml.push('\n');
- } else {
- body.push_str(line);
- body.push('\n');
- }
- }
-
- if !terminated {
- return None;
- }
-
- let mut parse_warnings = Vec::new();
- let frontmatter = match serde_yaml::from_str::<WorkflowFrontmatter>(&yaml) {
- Ok(fm) => fm,
- Err(err) => {
- log::warn!("[skills] failed to parse frontmatter: {err}");
- parse_warnings.push(format!("frontmatter parse error: {err}"));
- WorkflowFrontmatter::default()
- }
- };
-
- Some((frontmatter, body, parse_warnings))
-}
-
-/// Shallow-scan a skill directory for bundled resources.
-///
-/// Returns every file (relative to `dir`) under any of the conventional
-/// resource subdirectories (`scripts/`, `references/`, `assets/`). Deeper
-/// nesting is walked recursively.
-pub fn inventory_resources(dir: &Path) -> Vec<PathBuf> {
- let mut out = Vec::new();
- for sub in RESOURCE_DIRS {
- let root = dir.join(sub);
- // `root.is_dir()` follows symlinks, so a `scripts -> /some/other/tree`
- // symlink would still pass and `walk_files` would inventory the
- // external tree. Use `symlink_metadata` for a non-dereferencing check
- // and reject symlinked roots outright; `walk_files` already guards
- // deeper symlinks inside the tree.
- let meta = match std::fs::symlink_metadata(&root) {
- Ok(m) => m,
- Err(_) => continue,
- };
- if meta.file_type().is_symlink() || !meta.is_dir() {
- continue;
- }
- walk_files(&root, dir, &mut out);
- }
- out.sort();
- out
-}
-
-pub(crate) fn walk_files(current: &Path, base: &Path, out: &mut Vec<PathBuf>) {
- let entries = match std::fs::read_dir(current) {
- Ok(e) => e,
- Err(_) => return,
- };
- for entry in entries.flatten() {
- // Use `file_type()` — not `is_dir()` / `is_file()` — so we can detect and
- // skip symlinks before traversing. `is_dir()`/`is_file()` follow symlinks
- // and would cause unbounded recursion on a cycle (e.g. `resources/self ->
- // resources/`) or silent leakage outside the skill directory when a
- // symlink points at `/`, `/etc`, or another skill's tree.
- let Ok(file_type) = entry.file_type() else {
- continue;
- };
- if file_type.is_symlink() {
- continue;
- }
- let path = entry.path();
- if file_type.is_dir() {
- walk_files(&path, base, out);
- } else if file_type.is_file() {
- if let Ok(rel) = path.strip_prefix(base) {
- out.push(rel.to_path_buf());
- }
- }
- }
-}
-
-pub(crate) fn first_body_line(body: &str) -> Option<String> {
- for line in body.lines() {
- let trimmed = line.trim();
- if trimmed.is_empty() || trimmed.starts_with('#') {
- continue;
- }
- return Some(trimmed.to_string());
- }
- None
+ tinyskills::parse_skill_str(content)
}
-/// Load a skill from a `SKILL.md` file.
pub(crate) fn load_from_workflow_md(
skill_md: &Path,
dir: &Path,
dir_name: &str,
scope: WorkflowScope,
) -> Workflow {
- let mut warnings = Vec::new();
- let (frontmatter, body) = match parse_workflow_md(skill_md) {
- Some((fm, body, parse_warnings)) => {
- warnings.extend(parse_warnings);
- (fm, body)
- }
- None => {
- warnings.push(format!(
- "could not parse {} — exposing directory as placeholder",
- skill_md.display()
- ));
- (WorkflowFrontmatter::default(), String::new())
- }
- };
-
- let name = if frontmatter.name.trim().is_empty() {
- warnings.push("frontmatter missing 'name'; using directory name".to_string());
- dir_name.to_string()
- } else {
- if frontmatter.name != dir_name {
- warnings.push(format!(
- "frontmatter name '{}' does not match directory '{}'",
- frontmatter.name, dir_name
- ));
- }
- if frontmatter.name.len() > MAX_NAME_LEN {
- warnings.push(format!(
- "frontmatter name is {} chars (max recommended: {})",
- frontmatter.name.len(),
- MAX_NAME_LEN
- ));
- }
- frontmatter.name.clone()
- };
-
- let description = if frontmatter.description.trim().is_empty() {
- warnings
- .push("frontmatter missing 'description'; falling back to first body line".to_string());
- first_body_line(&body).unwrap_or_else(|| "No description provided".to_string())
- } else {
- if frontmatter.description.len() > MAX_DESCRIPTION_LEN {
- warnings.push(format!(
- "description is {} chars (max recommended: {})",
- frontmatter.description.len(),
- MAX_DESCRIPTION_LEN
- ));
- }
- frontmatter.description.clone()
- };
-
- let version = extract_version(&frontmatter, &mut warnings);
- let author = extract_author(&frontmatter, &mut warnings);
- let tags = extract_tags(&frontmatter, &mut warnings);
- let platforms = frontmatter.platforms.clone();
- let related_skills = extract_related_skills(&frontmatter);
- let source_format = detect_source_format(&frontmatter);
- let tools = frontmatter.allowed_tools.clone();
-
- Workflow {
- name,
- dir_name: dir_name.to_string(),
- description,
- version,
- author,
- tags,
- platforms,
- related_skills,
- source_format,
- tools,
- prompts: Vec::new(),
- location: Some(skill_md.to_path_buf()),
- frontmatter,
- resources: inventory_resources(dir),
- scope,
- legacy: false,
- warnings,
+ let mut workflow = tinyskills::document::load_document(skill_md, dir, dir_name, scope);
+ if workflow.source_format == "agentskills" {
+ workflow.source_format = "openhuman".to_string();
}
+ workflow
}
-/// Load a skill from a legacy `skill.json` manifest.
pub(crate) fn load_from_legacy_manifest(
manifest_path: &Path,
dir: &Path,
dir_name: &str,
scope: WorkflowScope,
) -> Workflow {
- let mut warnings = vec![format!(
- "skill uses legacy skill.json; migrate to SKILL.md frontmatter"
- )];
- let parsed = std::fs::read_to_string(manifest_path)
- .ok()
- .and_then(|content| serde_json::from_str::<LegacyWorkflowManifest>(&content).ok());
-
- let manifest = parsed.unwrap_or_else(|| {
- warnings.push(format!(
- "could not parse {} as JSON; using directory name",
- manifest_path.display()
- ));
- LegacyWorkflowManifest {
- name: dir_name.to_string(),
- description: String::new(),
- version: String::new(),
- author: None,
- tags: Vec::new(),
- tools: Vec::new(),
- prompts: Vec::new(),
- }
- });
-
- let name = if manifest.name.trim().is_empty() {
- dir_name.to_string()
- } else {
- manifest.name
- };
-
- // `load_from_legacy_manifest` is only called when SKILL.md is absent
- // (see load_skill_dir), so there is no SKILL.md to fall back to here.
- let description = if manifest.description.is_empty() {
- "No description provided".to_string()
- } else {
- manifest.description
- };
-
- let location = Some(manifest_path.to_path_buf());
-
- Workflow {
- name,
- dir_name: dir_name.to_string(),
- description,
- version: manifest.version,
- author: manifest.author,
- tags: manifest.tags,
- platforms: Vec::new(),
- related_skills: Vec::new(),
- source_format: "legacy".to_string(),
- tools: manifest.tools,
- prompts: manifest.prompts,
- location,
- frontmatter: WorkflowFrontmatter::default(),
- resources: inventory_resources(dir),
- scope,
- legacy: true,
- warnings,
- }
-}
-
-impl Workflow {
- /// Re-read the SKILL.md body (everything after the YAML frontmatter
- /// block) from disk. Returns `None` for legacy `skill.json` skills,
- /// for skills whose `location` points nowhere, or when the file
- /// cannot be parsed as a SKILL.md document.
- pub fn read_body(&self) -> Option<String> {
- if self.legacy {
- log::debug!(
- "[workflows:inject] read_body skipped for legacy skill.json skill name={}",
- self.name
- );
- return None;
- }
- let path = self.location.as_ref()?;
- match parse_workflow_md(path) {
- Some((_, body, _)) => Some(body),
- None => {
- log::warn!(
- "[workflows:inject] read_body failed to parse {} for skill {}",
- path.display(),
- self.name
- );
- None
- }
- }
- }
+ tinyskills::document::load_legacy(manifest_path, dir, dir_name, scope)
}
diff --git a/crates/openhuman-core/src/skills/ops_types.rs b/crates/openhuman-core/src/skills/ops_types.rs
index 9ac1e150c7..54c1e3b0c7 100644
--- a/crates/openhuman-core/src/skills/ops_types.rs
+++ b/crates/openhuman-core/src/skills/ops_types.rs
@@ -1,331 +1,15 @@
-//! Core types, constants, and frontmatter helpers for the skills subsystem.
+//! OpenHuman-compatible names for the portable `tinyskills` model.
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use std::path::PathBuf;
+pub use tinyskills::model::{
+ MAX_DESCRIPTION_LEN, MAX_NAME_LEN, RESOURCE_DIRS, SKILL_JSON, SKILL_MD, SKILL_TOML,
+ WORKFLOW_MD, WORKFLOW_TOML,
+};
+pub use tinyskills::{
+ Skill as Workflow, SkillFrontmatter as WorkflowFrontmatter, SkillScope as WorkflowScope,
+};
pub(crate) const TRUST_MARKER: &str = "trust";
-/// Primary workflow definition filename written by create/update.
-pub(crate) const WORKFLOW_MD: &str = "WORKFLOW.md";
-/// Primary sidecar manifest filename (inputs / when_to_use / [github]).
-pub(crate) const WORKFLOW_TOML: &str = "workflow.toml";
-/// Legacy definition filename still read for back-compat with workflows
-/// authored before the skills→workflows rename.
-pub(crate) const SKILL_MD: &str = "SKILL.md";
-/// Legacy sidecar manifest filename, read for back-compat.
-pub(crate) const SKILL_TOML: &str = "skill.toml";
-pub(crate) const SKILL_JSON: &str = "skill.json";
-pub(crate) const MAX_NAME_LEN: usize = 64;
-pub(crate) const MAX_DESCRIPTION_LEN: usize = 1024;
-pub(crate) const RESOURCE_DIRS: &[&str] = &[
- "scripts",
- "references",
- "assets",
- // Hermes-style skills commonly ship extra markdown/code under these
- // directories. Treat them as browsable resources, not executable runtime
- // entrypoints.
- "templates",
- "examples",
- "prompts",
-];
-
-/// Upper bound on resource payload size (in bytes) returned by
-/// [`read_workflow_resource`]. 128 KB is large enough for a typical SKILL-bundled
-/// script or reference doc but small enough to keep the JSON-RPC payload and
-/// UI memory footprint bounded even when a skill author bundles something
-/// unusually chonky (e.g. a minified binary fixture). Requests for files
-/// larger than this limit are rejected outright — callers must stream or
-/// download the file via another mechanism.
-pub const MAX_WORKFLOW_RESOURCE_BYTES: u64 = 128 * 1024;
-
-/// Where the skill was discovered. Determines precedence on name collision.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-#[derive(Default)]
-pub enum WorkflowScope {
- /// A skill compiled into the binary and materialised under
- /// `<workspace>/.openhuman/builtin-skills/` at boot. LOWEST precedence:
- /// a user or project skill of the same name shadows it, so shipping a
- /// bundle can never take a name away from someone already using it.
- /// See `skills::bundled`.
- Builtin,
- /// Workflow shipped with the user's global config (`~/.openhuman/skills/...`).
- #[default]
- User,
- /// Workflow shipped with the current workspace (`<ws>/.openhuman/skills/...`).
- /// Requires the trust marker to be loaded.
- Project,
- /// Workflow discovered under the legacy `<workspace>/skills/` layout.
- Legacy,
- /// Workflow private to the active agent profile, discovered under
- /// `<workspace>/personalities/<id>/skills/` and surfaced ONLY for turns
- /// running under that profile. Highest collision precedence — a
- /// profile-local skill shadows a same-named global one for its owner. See
- /// `ops_discover::discover_workflows_with_profile`.
- Profile,
- /// A saved **Flows automation** (a tinyflows graph), surfaced in the same
- /// catalogue as SKILL.md bundles.
- ///
- /// **Not discovered from disk.** Every other scope is a directory the
- /// skill scanner walked; this one is a row in `flows.db`, mapped into a
- /// catalogue entry by `flows::catalogue`. It is a listing, not a bundle:
- /// there is no `SKILL.md`, so `describe_workflow` and
- /// `read_workflow_resource` have nothing to read and say so by name rather
- /// than failing generically.
- ///
- /// It exists because a user asking "what can this thing already do for me"
- /// does not distinguish the two, and neither should the catalogue. Before
- /// this, the prompt carried ~200 bytes of caveat teaching the model that
- /// the list it was reading deliberately omitted half the answer, and that
- /// calling the obvious tool on the missing half "will error".
- Flow,
-}
-
-/// Parsed frontmatter of a `SKILL.md` file.
-///
-/// Matches the agentskills.io SKILL.md spec: `name` and `description` are
-/// required; `license`, `compatibility`, `metadata`, and `allowed-tools` are
-/// optional. Spec additions land in [`Self::extra`] via `#[serde(flatten)]`.
-///
-/// Version, author, tags, and other non-required fields belong under
-/// [`Self::metadata`]. Writers that still put them at the top level are
-/// accepted with a migration warning.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct WorkflowFrontmatter {
- #[serde(default)]
- pub name: String,
- #[serde(default)]
- pub description: String,
- #[serde(default)]
- pub license: Option<String>,
- #[serde(default)]
- pub compatibility: Option<String>,
- /// Platform compatibility hint used by Hermes-style skills. Absence means
- /// all platforms.
- #[serde(default)]
- pub platforms: Vec<String>,
- /// Spec-compliant metadata map. Version, author, tags, and other
- /// non-required fields live here.
- #[serde(default)]
- pub metadata: HashMap<String, serde_yaml::Value>,
- /// Tools the skill author asserts their instructions rely on
- /// (non-binding hint; the host decides what to expose).
- #[serde(
- default,
- rename = "allowed-tools",
- alias = "allowed_tools",
- alias = "tools",
- deserialize_with = "de_string_or_seq"
- )]
- pub allowed_tools: Vec<String>,
- /// Domain events that should activate this skill.
- ///
- /// Each entry is a trigger pattern of the form `"domain"` or
- /// `"domain/event_slug"` (e.g. `"composio"`,
- /// `"composio/trigger_received"`, `"cron"`, `"channel/inbound_message"`).
- /// A bare domain (no slash) matches any event in that domain.
- /// The host builds a [`TriggeredWorkflowIndex`] at startup and registers a
- /// subscriber that logs matching skills; the actual agent-session launch
- /// is handled by the integration layer (see `skills::bus`).
- #[serde(default)]
- pub triggers: Vec<String>,
- /// Forward-compat hatch for spec additions. Non-spec top-level keys
- /// (including legacy `version`, `author`, `tags`) land here and trigger
- /// a migration warning when read.
- #[serde(flatten)]
- pub extra: HashMap<String, serde_yaml::Value>,
-}
-
-/// Deserialize `allowed-tools` from either a YAML sequence (`[Bash, Read]`) or a
-/// single scalar string in Claude Code's convention (`allowed-tools: Bash,
-/// Read, Grep`). A bare scalar is split on commas and trimmed. Without this,
-/// skills authored for the `claude` CLI — which writes a comma-joined string —
-/// fail frontmatter parsing, and their declared tools (Bash, etc.) get dropped,
-/// surfacing as "tool not available" at run time.
-fn de_string_or_seq<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
-where
- D: serde::Deserializer<'de>,
-{
- #[derive(Deserialize)]
- #[serde(untagged)]
- enum StringOrSeq {
- Seq(Vec<String>),
- Str(String),
- }
- Ok(match StringOrSeq::deserialize(deserializer)? {
- StringOrSeq::Seq(v) => v,
- StringOrSeq::Str(s) => s
- .split(',')
- .map(|t| t.trim().to_string())
- .filter(|t| !t.is_empty())
- .collect(),
- })
-}
-
-pub(crate) fn metadata_string(fm: &WorkflowFrontmatter, key: &str) -> Option<String> {
- fm.metadata
- .get(key)
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
-}
-
-pub(crate) fn metadata_string_seq(value: &serde_yaml::Value) -> Vec<String> {
- value
- .as_sequence()
- .map(|seq| {
- seq.iter()
- .filter_map(|t| t.as_str().map(|s| s.to_string()))
- .collect()
- })
- .unwrap_or_default()
-}
-
-pub(crate) fn extract_version(fm: &WorkflowFrontmatter, warnings: &mut Vec<String>) -> String {
- if let Some(v) = metadata_string(fm, "version") {
- return v;
- }
- if let Some(v) = fm.extra.get("version").and_then(|v| v.as_str()) {
- warnings
- .push("top-level 'version' is deprecated; move under 'metadata.version'".to_string());
- return v.to_string();
- }
- String::new()
-}
-
-pub(crate) fn extract_author(
- fm: &WorkflowFrontmatter,
- warnings: &mut Vec<String>,
-) -> Option<String> {
- if let Some(v) = metadata_string(fm, "author") {
- return Some(v);
- }
- if let Some(v) = fm.extra.get("author").and_then(|v| v.as_str()) {
- warnings.push("top-level 'author' is deprecated; move under 'metadata.author'".to_string());
- return Some(v.to_string());
- }
- None
-}
-
-pub(crate) fn extract_tags(fm: &WorkflowFrontmatter, warnings: &mut Vec<String>) -> Vec<String> {
- let mut tags = Vec::new();
- if let Some(v) = fm.metadata.get("tags") {
- tags.extend(metadata_string_seq(v));
- }
- if let Some(hermes_tags) = fm
- .metadata
- .get("hermes")
- .and_then(|v| v.as_mapping())
- .and_then(|m| m.get(serde_yaml::Value::String("tags".to_string())))
- {
- tags.extend(metadata_string_seq(hermes_tags));
- }
- if let Some(v) = fm.extra.get("tags") {
- warnings.push("top-level 'tags' is deprecated; move under 'metadata.tags'".to_string());
- tags.extend(metadata_string_seq(v));
- }
- tags.sort();
- tags.dedup();
- tags
-}
-
-pub(crate) fn extract_related_skills(fm: &WorkflowFrontmatter) -> Vec<String> {
- let mut related = fm
- .metadata
- .get("related_skills")
- .map(metadata_string_seq)
- .unwrap_or_default();
- if let Some(hermes_related) = fm
- .metadata
- .get("hermes")
- .and_then(|v| v.as_mapping())
- .and_then(|m| m.get(serde_yaml::Value::String("related_skills".to_string())))
- {
- related.extend(metadata_string_seq(hermes_related));
- }
- related.sort();
- related.dedup();
- related
-}
-
-pub(crate) fn detect_source_format(fm: &WorkflowFrontmatter) -> String {
- if fm.metadata.contains_key("hermes") || !fm.platforms.is_empty() {
- "hermes".to_string()
- } else {
- "openhuman".to_string()
- }
-}
-
-/// A discovered skill.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct Workflow {
- /// Display name (from frontmatter, falls back to directory name).
- pub name: String,
- /// On-disk slug — the directory name under `~/.openhuman/skills/` (user
- /// scope) or the workspace skills directory (project scope). This is the
- /// identifier the uninstall RPC resolves against; it may differ from
- /// [`Workflow::name`] when frontmatter declares a mismatched display name.
- #[serde(default)]
- pub dir_name: String,
- /// Short description used in the catalog summary.
- pub description: String,
- /// Version string, if declared.
- pub version: String,
- /// Author string, if declared.
- pub author: Option<String>,
- /// Tags declared in frontmatter.
- pub tags: Vec<String>,
- /// Compatible platform hints from SKILL.md frontmatter.
- #[serde(default)]
- pub platforms: Vec<String>,
- /// Related skill names declared by the ecosystem/catalog.
- #[serde(default)]
- pub related_skills: Vec<String>,
- /// Normalized ecosystem format hint (`openhuman`, `hermes`, or `legacy`).
- #[serde(default)]
- pub source_format: String,
- /// Tool hint declared in frontmatter (`allowed-tools`).
- #[serde(default)]
- pub tools: Vec<String>,
- /// Prompt files declared in legacy `skill.json`. Unused for SKILL.md skills.
- #[serde(default)]
- pub prompts: Vec<String>,
- /// Path to the `SKILL.md` (or `skill.json`) file.
- pub location: Option<PathBuf>,
- /// Full parsed frontmatter when sourced from `SKILL.md`.
- #[serde(default)]
- pub frontmatter: WorkflowFrontmatter,
- /// Bundled resource files (relative to the skill directory).
- #[serde(default)]
- pub resources: Vec<PathBuf>,
- /// Where the skill came from.
- #[serde(default)]
- pub scope: WorkflowScope,
- /// True when loaded from the legacy `skill.json` / `<ws>/skills/` layout.
- #[serde(default)]
- pub legacy: bool,
- /// Non-fatal parse warnings, surfaced in the catalog for user debugging.
- #[serde(default)]
- pub warnings: Vec<String>,
-}
-
-/// Internal structure for parsing legacy `skill.json` manifests.
-#[derive(Debug, Deserialize)]
-pub(crate) struct LegacyWorkflowManifest {
- #[serde(default)]
- pub name: String,
- #[serde(default)]
- pub description: String,
- #[serde(default)]
- pub version: String,
- #[serde(default)]
- pub author: Option<String>,
- #[serde(default)]
- pub tags: Vec<String>,
- #[serde(default)]
- pub tools: Vec<String>,
- #[serde(default)]
- pub prompts: Vec<String>,
-}
+pub const MAX_WORKFLOW_RESOURCE_BYTES: u64 = tinyskills::model::MAX_RESOURCE_BYTES;
#[cfg(test)]
#[path = "ops_types_tests.rs"]
diff --git a/vendor/tinyskills b/vendor/tinyskills
new file mode 160000
index 0000000000..d6dc40f3c8
--- /dev/null
+++ b/vendor/tinyskills
@@ -0,0 +1 @@
+Subproject commit d6dc40f3c84726f0396836620ed6c6baedaa0628