Skip to content

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

refactor(skills): delegate manifest handling to tinyskills

Steven Enamakel1e6c8056ffdd
diff --git a/crates/openhuman-core/src/skills/ops_create.rs b/crates/openhuman-core/src/skills/ops_create.rs
index c0667d0a45..34e5b40517 100644
--- a/crates/openhuman-core/src/skills/ops_create.rs
+++ b/crates/openhuman-core/src/skills/ops_create.rs
@@ -1,11 +1,11 @@
//! Workflow creation: scaffolding new SKILL.md-based skills on disk.
-use serde::{Deserialize, Serialize};
-use std::path::{Path, PathBuf};
+use serde::{Deserialize};
+use std::path::Path;
use tinyskills::{
- scaffold_bundle, slugify, validate_description, validate_display_name, BundleSpec,
- ScaffoldOptions,
+ render_manifest_toml, scaffold_bundle, slugify, validate_description, validate_display_name,
+ validate_manifest_inputs, BundleSpec, ScaffoldOptions,
};
use super::ops_discover::{discover_workflows_inner, is_workspace_trusted};
@@ -15,39 +15,9 @@ use {
};
/// One declared `[[inputs]]` entry as supplied at create time by the
-/// Create-a-Workflow form.
-///
-/// Wire shape (kebab-case-free, mirrors what
-/// `crate::skills::registry::WorkflowInput` expects when the
-/// emitted `skill.toml` is parsed back at run time):
-///
-/// ```json
-/// { "name": "repo", "description": "owner/name", "required": true, "type": "string" }
-/// ```
-///
-/// `description` and `type` are optional; when omitted the on-disk
-/// `[[inputs]]` entry leaves them absent (the registry's
-/// `WorkflowInput` defaults already cover this — `description = ""`,
-/// `kind = None`). `required` defaults to `true` because that is the
-/// only sensible default for a user who bothered to add a row.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct WorkflowCreateInputDef {
- pub name: String,
- #[serde(default)]
- pub description: Option<String>,
- #[serde(default = "default_required")]
- pub required: bool,
- /// Type hint — accepted values are `"string"` (default), `"integer"`,
- /// and `"boolean"`. The registry parser stores this verbatim in
- /// `WorkflowInput.kind`; it is the Skills Runner that uses it to pick
- /// the right form control (text / number / checkbox).
- #[serde(default, rename = "type")]
- pub type_: Option<String>,
-}
-
-fn default_required() -> bool {
- true
-}
+/// Create-a-Workflow form. The wire shape, validation and `skill.toml`
+/// rendering are owned by `tinyskills::manifest`.
+pub type WorkflowCreateInputDef = tinyskills::ManifestInput;
/// Input for [`create_workflow`]. Mirrors the `skills.create` JSON-RPC payload.
#[derive(Debug, Clone, Deserialize, Default)]
@@ -129,32 +99,6 @@ pub fn create_workflow(
create_workflow_inner(home.as_deref(), workspace_dir, params)
}
-/// Pre-rename compat roots (`<root>/skills`) an edit may still find a
-/// workflow under; mirrors `ops_discover::user_roots` / `project_roots`
-/// minus the primary `workflows/` root. Builtin/legacy/flow scopes have no
-/// writable legacy location.
-fn legacy_workflow_roots(
- home_dir: Option<&Path>,
- workspace_dir: &Path,
- scope: WorkflowScope,
-) -> Vec<PathBuf> {
- match scope {
- WorkflowScope::User => home_dir
- .map(|home| {
- vec![
- home.join(".openhuman").join("skills"),
- home.join(".agents").join("skills"),
- ]
- })
- .unwrap_or_default(),
- WorkflowScope::Project => vec![
- workspace_dir.join(".openhuman").join("skills"),
- workspace_dir.join(".agents").join("skills"),
- ],
- _ => Vec::new(),
- }
-}
-
pub(crate) fn create_workflow_inner(
home_dir: Option<&Path>,
workspace_dir: &Path,
@@ -167,7 +111,7 @@ pub(crate) fn create_workflow_inner(
"[skills] create_workflow: entry"
);
- validate_inputs(&mut params.inputs)?;
+ validate_manifest_inputs(&mut params.inputs).map_err(|e| e.to_string())?;
let display_name = validate_display_name(&params.name).map_err(|e| e.to_string())?;
let description = validate_description(&params.description).map_err(|e| e.to_string())?;
@@ -223,7 +167,7 @@ pub(crate) fn create_workflow_inner(
};
let options = ScaffoldOptions {
overwrite: params.overwrite,
- legacy_roots: legacy_workflow_roots(home_dir, workspace_dir, params.scope),
+ legacy_roots: tinyskills::legacy_scaffold_roots(home_dir, workspace_dir, params.scope),
..Default::default()
};
let scaffolded = scaffold_bundle(&scope_root, &spec, &options).map_err(|e| e.to_string())?;
@@ -246,7 +190,7 @@ pub(crate) fn create_workflow_inner(
// Distinct trigger when provided, else reuse the description so the
// field is never empty (matches the prior behaviour).
let workflow_toml =
- render_workflow_toml(&slug, when_to_use.unwrap_or(description), &params.inputs);
+ render_manifest_toml(&slug, when_to_use.unwrap_or(description), &params.inputs);
std::fs::write(&workflow_toml_path, workflow_toml)
.map_err(|e| format!("failed to write {}: {e}", workflow_toml_path.display()))?;
} else if params.overwrite {
@@ -285,82 +229,3 @@ pub(crate) fn create_workflow_inner(
Ok(created)
}
-
-/// Validate the declared `[[inputs]]` before any on-disk write.
-///
-/// For each entry this trims the `name` in place, rejects empty /
-/// whitespace-only names, and enforces case-insensitive uniqueness across
-/// all input names so the emitted `skill.toml` never carries a blank or
-/// duplicate `[[inputs]]` key. Names are trimmed in place so every later
-/// consumer (e.g. [`render_workflow_toml`]) sees the validated value.
-fn validate_inputs(inputs: &mut [WorkflowCreateInputDef]) -> Result<(), String> {
- let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
- for input in inputs.iter_mut() {
- let trimmed = input.name.trim();
- if trimmed.is_empty() {
- return Err("input name must not be empty".to_string());
- }
- if !seen.insert(trimmed.to_ascii_lowercase()) {
- return Err(format!("duplicate input name '{trimmed}'"));
- }
- let trimmed = trimmed.to_string();
- input.name = trimmed;
- }
- Ok(())
-}
-
-/// Render the sibling `skill.toml` next to a freshly scaffolded SKILL.md
-/// when the user declared `[[inputs]]` at create time. Emits the
-/// minimal set the registry parser needs to discover and render the
-/// inputs at run time: `id`, `when_to_use`, plus one `[[inputs]]` entry
-/// per declared input. Field shape mirrors the existing bundled skills
-/// (e.g. `crates/openhuman-core/src/skills/defaults/github-issue-crusher/skill.toml`)
-/// so `discover_workflows_inner` parses the new file identically.
-pub(crate) fn render_workflow_toml(
- slug: &str,
- when_to_use: &str,
- inputs: &[WorkflowCreateInputDef],
-) -> String {
- let mut out = String::new();
- out.push_str(&format!("id = {}\n", toml_string_literal(slug)));
- out.push_str(&format!(
- "when_to_use = {}\n",
- toml_string_literal(when_to_use)
- ));
- for input in inputs {
- out.push_str("\n[[inputs]]\n");
- out.push_str(&format!("name = {}\n", toml_string_literal(&input.name)));
- if let Some(d) = input.description.as_deref().filter(|s| !s.is_empty()) {
- out.push_str(&format!("description = {}\n", toml_string_literal(d)));
- }
- out.push_str(&format!("required = {}\n", input.required));
- if let Some(t) = input.type_.as_deref().filter(|s| !s.is_empty()) {
- out.push_str(&format!("type = {}\n", toml_string_literal(t)));
- }
- }
- out
-}
-
-/// Emit a TOML basic-string literal: wraps in `"..."` and escapes the
-/// minimum set TOML requires inside basic strings (`\`, `"`, control
-/// chars). Multi-line strings are not used; new-lines inside a value
-/// are escaped to `\n` so the literal stays single-line and round-trips
-/// through the TOML parser unchanged.
-fn toml_string_literal(s: &str) -> String {
- let mut escaped = String::with_capacity(s.len() + 2);
- for ch in s.chars() {
- match ch {
- '\\' => escaped.push_str("\\\\"),
- '"' => escaped.push_str("\\\""),
- '\n' => escaped.push_str("\\n"),
- '\r' => escaped.push_str("\\r"),
- '\t' => escaped.push_str("\\t"),
- c => escaped.push(c),
- }
- }
- format!("\"{escaped}\"")
-}
-
-#[cfg(test)]
-#[path = "ops_create_render_skill_toml_tests_tests.rs"]
-mod render_skill_toml_tests;
diff --git a/crates/openhuman-core/src/skills/ops_create_render_skill_toml_tests_tests.rs b/crates/openhuman-core/src/skills/ops_create_render_skill_toml_tests_tests.rs
deleted file mode 100644
index 70c77632d1..0000000000
--- a/crates/openhuman-core/src/skills/ops_create_render_skill_toml_tests_tests.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-use super::*;
-
-#[test]
-fn no_inputs_returns_header_only() {
- let out = render_workflow_toml("my-skill", "Does the thing.", &[]);
- assert!(out.contains("id = \"my-skill\""));
- assert!(out.contains("when_to_use = \"Does the thing.\""));
- assert!(!out.contains("[[inputs]]"));
-}
-
-#[test]
-fn one_input_with_all_fields_roundtrips() {
- let inputs = vec![WorkflowCreateInputDef {
- name: "repo".into(),
- description: Some("owner/name".into()),
- required: true,
- type_: Some("string".into()),
- }];
- let out = render_workflow_toml("my-skill", "Does the thing.", &inputs);
- // Parse it back through the actual TOML parser to prove the
- // output is well-formed — the registry uses `toml::from_str` so
- // any round-trip failure here would surface at skill discovery.
- let parsed: toml::Value = toml::from_str(&out).expect("emitted skill.toml must parse");
- let inputs_arr = parsed["inputs"].as_array().expect("[[inputs]] is an array");
- assert_eq!(inputs_arr.len(), 1);
- let entry = &inputs_arr[0];
- assert_eq!(entry["name"].as_str(), Some("repo"));
- assert_eq!(entry["description"].as_str(), Some("owner/name"));
- assert_eq!(entry["required"].as_bool(), Some(true));
- assert_eq!(entry["type"].as_str(), Some("string"));
-}
-
-#[test]
-fn optional_fields_omitted_when_empty() {
- let inputs = vec![WorkflowCreateInputDef {
- name: "n".into(),
- description: None,
- required: false,
- type_: None,
- }];
- let out = render_workflow_toml("my-skill", "x", &inputs);
- let parsed: toml::Value = toml::from_str(&out).expect("parse");
- let entry = &parsed["inputs"].as_array().unwrap()[0];
- assert_eq!(entry["name"].as_str(), Some("n"));
- assert_eq!(entry["required"].as_bool(), Some(false));
- assert!(entry.get("description").is_none());
- assert!(entry.get("type").is_none());
-}
-
-#[test]
-fn escapes_dangerous_chars_in_strings() {
- let inputs = vec![WorkflowCreateInputDef {
- name: "n".into(),
- description: Some("has \"quotes\" and \\ backslash\nand newline".into()),
- required: true,
- type_: None,
- }];
- let out = render_workflow_toml("my-skill", "x", &inputs);
- // Must still parse cleanly — the escape logic is what we're
- // exercising here; the round-trip assertion below is the contract.
- let parsed: toml::Value = toml::from_str(&out).expect("escaped strings must parse");
- let entry = &parsed["inputs"].as_array().unwrap()[0];
- assert_eq!(
- entry["description"].as_str(),
- Some("has \"quotes\" and \\ backslash\nand newline")
- );
-}
-
-/// The trigger half of mid-session refresh: creating a workflow must
-/// publish `DomainEvent::WorkflowsChanged` so live sessions re-scan. This
-/// guards the `publish_global` emission line (the `refresh_workflows` test
-/// writes to disk directly and bypasses create/install, so without this a
-/// dropped emission would stay green while silently killing the feature).
-#[tokio::test]
-async fn create_workflow_inner_emits_workflows_changed() {
- use crate::core::events::DomainEvent;
- use tinybus::TryRecvError;
-
- crate::core::bus::init().await.expect("bus init");
- let mut rx = crate::core::bus::BUS
- .get()
- .expect("event bus should be initialized")
- .receiver();
-
- let home = tempfile::TempDir::new().expect("temp home");
- let ws = tempfile::TempDir::new().expect("temp workspace");
- let params = CreateWorkflowParams {
- name: "zz-emit-test".into(),
- description: "emit test skill".into(),
- scope: WorkflowScope::User,
- ..Default::default()
- };
- create_workflow_inner(Some(home.path()), ws.path(), params)
- .expect("create_workflow_inner should succeed");
-
- let mut saw = false;
- loop {
- match rx.try_recv() {
- // The event bus is a process-wide singleton, so other tests
- // running in parallel publish their own WorkflowsChanged events
- // (e.g. "install"/"uninstall" from ops_install). Match only our
- // own "create" reason and skip the rest rather than asserting on
- // whichever event happens to arrive first.
- Ok(DomainEvent::WorkflowsChanged { reason }) if reason == "create" => {
- saw = true;
- break;
- }
- Ok(_) => continue,
- Err(TryRecvError::Lagged(_)) => continue,
- Err(TryRecvError::Empty) | Err(TryRecvError::Closed) => break,
- }
- }
- assert!(
- saw,
- "create_workflow_inner must publish DomainEvent::WorkflowsChanged"
- );
-}