Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): user-scope skills in ~/.jan/skills (janhq/jan-internal#394)

thinhlpg673d1cc9ac38
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index 2670a1786..370ae72d6 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -19,13 +19,16 @@ your-project/
|-- project.json # which directory this store belongs to
|-- agent.toml # model, budget, tool policy
|-- threads/ # saved sessions
-|-- skills/ # reusable procedures
+|-- skills/ # reusable procedures (project scope)
|-- MEMORY.md # generated index of memory/
|-- memory/ # durable facts
|-- plugins/ # installed plugins
`-- subagents/ # reusable subagent definitions
```
+User-wide skills live beside the projects in `~/.jan/skills/`, and a same-named project skill
+shadows them. See [Skills](/docs/agent/skills#where-they-live).
+
The store name (the `<slug>` in these docs) is the project directory's name plus a short hash of
its full path. A linked git
worktree maps to its main checkout, so both share one store.
diff --git a/docs/src/pages/docs/agent/skills.mdx b/docs/src/pages/docs/agent/skills.mdx
index a1805c5f6..987a8f7e7 100644
--- a/docs/src/pages/docs/agent/skills.mdx
+++ b/docs/src/pages/docs/agent/skills.mdx
@@ -16,19 +16,36 @@ task calls for it, so a large library of skills doesn't crowd the context window
## Where they live
+Skills come from three places. On a name collision the earlier one wins:
+
```
-~/.jan/projects/<slug>/skills/
-├── release/
-│ └── SKILL.md # folder form, can bundle scripts alongside
-└── add-migration.md # flat form
+1. ~/.jan/projects/<slug>/skills/ project: this project only
+ ├── release/
+ │ └── SKILL.md # folder form, can bundle scripts alongside
+ └── add-migration.md # flat form
+2. ~/.jan/projects/<slug>/plugins/<P>/ plugin skills, always named <P>:<name>
+3. ~/.jan/skills/ user: every project on this machine
+4. jan built-in onboarding skill
```
+Put a skill in `~/.jan/skills/` to use it from every project. A project skill with the same name
+**shadows** the user one in that project. Plugin skills never collide, because they're always
+qualified as `<plugin>:<name>`. A project or user skill named `jan` replaces the built-in one.
+
+Run `/skills` in the console to see every skill with its scope. A skill hidden by a
+higher-precedence one is marked `shadowed by project`.
+
+Skill folders can be symlinks in either scope, for example
+`~/.jan/skills/review -> ~/my-skills/review`. Jan follows them. If the same folder is reached twice,
+it's listed once. Dangling links and symlink loops are skipped.
+
The folder form is what new and imported skills are written as, and it lets a skill ship helper
scripts or templates next to its instructions. The format matches the wider SKILL.md ecosystem, so
skills written elsewhere generally work here.
The model sees skills rebuilt from disk on every run. To refresh the `/` popup after adding, editing,
-or deleting one mid-session, run `/reload skills`; it reports what was added, removed, or changed.
+or deleting one mid-session, including a user skill, run `/reload skills`. It reports what was
+added, removed, or changed.
## Writing one
@@ -58,6 +75,9 @@ You can write the file yourself, or ask the agent to:
Write a skill for how we cut releases, based on what you see in CHANGELOG.md and the CI config
```
+`skill_write` writes to the project by default. Ask for a user skill ("save this as a user skill")
+and the agent passes `scope: "user"`, which writes to `~/.jan/skills/<name>/SKILL.md`.
+
## Who can invoke a skill
A skill has two invocation sides, and frontmatter closes either one:
@@ -80,23 +100,31 @@ from a git repo or picked from a marketplace, invocable under `<plugin>:<skill>`
| --- | --- |
| `skill_list` | No |
| `skill_read` | No |
-| `skill_write` | Yes |
+| `skill_write` (`scope`: `project` default, or `user`) | No, unless denied in `[tools]` |
+
+`skill_list` and `skill_read` cover every scope above, including plugin skills
+(`skill_read` accepts `<plugin>:<name>`, or the plain name when it's unique).
## Controlling which are active
```toml
[skills]
enabled = [] # empty means all skills are enabled
-inject = "always" # always | relevance
```
-`enabled` is a whitelist. `inject` decides how they reach the model: `always` puts every skill's
-name and purpose in the system prompt, `relevance` selects per task.
+`enabled` is a whitelist across every scope. It matches a plain name, a qualified
+`<plugin>:<name>`, or a plugin name, which enables all of that plugin's skills. Every enabled skill's
+name and purpose goes into the system prompt, and the body loads on demand.
+
+<Callout type="info">
+Older scaffolds had an `inject = "always" | "relevance"` key. It was never read and is now
+ignored, with a one-time warning in the log. You can delete it.
+</Callout>
<Callout type="info">
-Skills are shared with [Jan Desktop's Cowork surface](/docs/desktop/cowork), which ships in
-the `nightly` channel only - the same project files, through the same directory. A skill written
-in one shows up in the other.
+[Jan Desktop's Cowork surface](/docs/desktop/cowork) (`nightly` channel only) keeps its own skill
+store under `<data folder>/agent-workspace/skills`. It layers the attached folder's project skills on
+top of that store. It doesn't read `~/.jan/skills` yet.
</Callout>
## Skills, JAN.md, and memory
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 888e51206..0f241d05d 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -17,7 +17,7 @@ join the same list, ranked by how closely they match the start of the name. The
characters match strictly as a prefix, so a barely-started buffer stays tight instead of surfacing
every name that merely contains those letters.
-Installed project skills ([Skills](/docs/agent/skills)) join the same popup: typing `/deploy` matches a skill named `deploy` (magenta row, alongside the cyan commands), <kbd>Tab</kbd> completes it, and <kbd>Enter</kbd> tells the agent to follow the skill. Disabled skills (via `[skills].enabled`) are not offered, and neither are `user-invocable: false` skills - those stay agent-invoked only.
+Installed skills from every scope ([Skills](/docs/agent/skills): project, plugin, and user `~/.jan/skills`) join the same popup: typing `/deploy` matches a skill named `deploy` (magenta row, alongside the cyan commands), <kbd>Tab</kbd> completes it, and <kbd>Enter</kbd> tells the agent to follow the skill. Disabled skills (via `[skills].enabled`) are not offered, and neither are `user-invocable: false` skills - those stay agent-invoked only.
Skills accept arguments, and there are two ways to invoke one:
@@ -66,6 +66,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper |
| `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it |
| `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |
+| `/skills` | List every skill Jan can see from this project, with its scope (`project`, `plugin`, `user`, `built-in`), invocation flags, and whether it is disabled. A skill hidden by a same-named higher-precedence one is marked `shadowed by <scope>` |
| `/reload [config\|plugin\|skills\|system-prompt]` | Re-read on-disk state into the running session without a restart (bare: all). `config` re-applies the project's `agent.toml` limits - `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `[budget].max_tokens` - to the next run and lists what changed; the model, `[tools]`, `[provider]` and `[budget].max_usd` still need a restart. `plugin`/`skills` re-scan and rebuild the catalog, reporting added/removed/changed entries. `system-prompt` re-reads `JAN.md`, which applies on the next run |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md b/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md
index f3171e472..f90aa9c8a 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md
@@ -22,6 +22,7 @@ Everything else is per-user state under `~/.jan/`, created on first use.
|-- config.toml # CLI provider configuration and credentials
|-- MEMORY.md # generated index: user notes + projects with memory
|-- memory/ # user-wide notes (`user:<name>`), every project
+|-- skills/ # user-wide skills, every project (project skills shadow them)
`-- projects/
`-- <name>-<hash>/ # one per project directory (git worktrees share it)
|-- project.json # which directory this store belongs to
@@ -37,7 +38,10 @@ Everything else is per-user state under `~/.jan/`, created on first use.
```
`agent.toml` has `[agent]`, `[provider]`, `[budget]`, `[tools]`, and `[skills]` sections.
-A simple skill can be `skills/<name>.md`. Run `jan cli agent status --project .` to scaffold
+A simple skill can be `skills/<name>.md`. Skill precedence is project > user (`~/.jan/skills`) >
+built-in `jan`. Plugin skills are always named `<plugin>:<name>`. `/skills` lists each skill's scope
+and marks shadowed ones, and `skill_write` with `scope: "user"` writes a user skill. Symlinked
+skill folders are followed. Run `jan cli agent status --project .` to scaffold
the store. A project that still has a `.jan/` folder from an older Jan is moved into
`~/.jan/projects/` automatically the next time Jan starts in it.
`memory_cross_project = false` in `config.toml` hides other projects' memory from the agent.
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index ddbd2e5a8..5e57cc5ae 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -471,13 +471,20 @@ fn render_write_diff(prior: Option<&str>, content: &str) -> String {
/// `skill_list` tool: catalog of `name — description` lines for ENABLED skills
/// only (disabled skills must stay invisible to the model). Empty if none.
fn skill_list(ctx: &ToolContext<'_>) -> String {
- skills::catalog_layered(&ctx.skill_roots(), ctx.enabled_skills)
- .iter()
- .map(|m| {
- if m.description.is_empty() {
- m.name.clone()
+ let entries: Vec<(String, String)> = match &ctx.skill_source {
+ Some(source) => source.catalog(),
+ None => skills::catalog_layered(&ctx.skill_roots(), ctx.enabled_skills)
+ .into_iter()
+ .map(|m| (m.name, m.description))
+ .collect(),
+ };
+ entries
+ .into_iter()
+ .map(|(name, description)| {
+ if description.is_empty() {
+ name
} else {
- format!("{} — {}", m.name, m.description)
+ format!("{name} — {description}")
}
})
.collect::<Vec<_>>()
@@ -491,6 +498,9 @@ fn skill_read(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
let Some(name) = arg_str(args, "name") else {
return "ERROR: missing required argument 'name'".to_string();
};
+ if let Some(source) = &ctx.skill_source {
+ return source.read(name).unwrap_or_else(|e| e);
+ }
if !skills::is_enabled(ctx.enabled_skills, name) {
return format!("ERROR: skill '{name}' not found");
}
@@ -506,6 +516,8 @@ fn skill_read(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
}
/// `skill_write` tool: create/update a skill (new ones as `<name>/SKILL.md`).
+/// `scope` picks the store: `project` (the default, `store_root`) or `user`
+/// (`skill_user_root`, i.e. `~/.jan/skills`, visible from every project).
/// The `[skills].enabled` whitelist is honored for writes too: a disabled skill
/// is treated as read-only so the model cannot silently overwrite (or resurrect)
/// a skill the user has turned off or locked out of the catalog.
@@ -519,8 +531,18 @@ fn skill_write(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
if !skills::is_enabled(ctx.enabled_skills, name) {
return format!("ERROR: skill '{name}' is disabled and read-only");
}
- match skills::write(ctx.store_root, name, content) {
- Ok(()) => format!("Wrote skill '{name}'"),
+ let (store, label) = match arg_str(args, "scope").unwrap_or("project") {
+ "project" => (ctx.store_root, "skill"),
+ "user" => match ctx.skill_user_root {
+ Some(root) => (root, "user skill"),
+ None => return "ERROR: scope 'user' is not available here".to_string(),
+ },
+ other => {
+ return format!("ERROR: invalid scope '{other}' (expected \"project\" or \"user\")")
+ }
+ };
+ match skills::write(store, name, content) {
+ Ok(()) => format!("Wrote {label} '{name}'"),
Err(e) => e,
}
}
@@ -3576,6 +3598,87 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[tokio::test]
+ async fn skill_write_scope_picks_the_project_or_user_store() {
+ let root = unique_root();
+ let store = crate::workspace::project_store(&root);
+ let home = root.join("home-jan");
+ let ctx = ToolContext::new(&root, &store, &[]).with_skill_user_root(Some(&home));
+ let write = |args: serde_json::Value| {
+ let ctx = ctx.clone();
+ async move { super::execute_builtin(lookup("skill_write").unwrap(), &args, &ctx).await.0 }
+ };
+
+ // No scope: the project store, as before.
+ let out = write(json!({"name": "a", "content": "x"})).await;
+ assert_eq!(out, "Wrote skill 'a'");
+ assert!(store.join("skills/a/SKILL.md").is_file());
+ assert!(!home.join("skills/a").exists());
+
+ // scope: "project" is the same thing, spelled out.
+ write(json!({"name": "b", "content": "x", "scope": "project"})).await;
+ assert!(store.join("skills/b/SKILL.md").is_file());
+
+ // scope: "user" writes to `<jan home>/skills`.
+ let out = write(json!({"name": "c", "content": "x", "scope": "user"})).await;
+ assert_eq!(out, "Wrote user skill 'c'");
+ assert!(home.join("skills/c/SKILL.md").is_file());
+ assert!(!store.join("skills/c").exists());
+
+ // An unknown scope is refused, not silently defaulted.
+ let out = write(json!({"name": "d", "content": "x", "scope": "global"})).await;
+ assert!(out.starts_with("ERROR: invalid scope"), "{out}");
+
+ // A surface with no user root refuses the user scope.
+ let bare = ToolContext::new(&root, &store, &[]);
+ let out = super::execute_builtin(
+ lookup("skill_write").unwrap(),
+ &json!({"name": "e", "content": "x", "scope": "user"}),
+ &bare,
+ )
+ .await
+ .0;
+ assert!(out.starts_with("ERROR: scope 'user'"), "{out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_skill_source_overrides_list_and_read() {
+ struct Fixed;
+ impl crate::tools::SkillProvider for Fixed {
+ fn catalog(&self) -> Vec<(String, String)> {
+ vec![("p:one".into(), "first".into()), ("two".into(), String::new())]
+ }
+ fn read(&self, name: &str) -> Result<String, String> {
+ (name == "p:one")
+ .then(|| "body one".to_string())
+ .ok_or_else(|| format!("ERROR: skill '{name}' not found"))
+ }
+ }
+ let root = unique_root();
+ let store = crate::workspace::project_store(&root);
+ let ctx =
+ ToolContext::new(&root, &store, &[]).with_skill_source(std::sync::Arc::new(Fixed));
+ let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx)
+ .await
+ .0;
+ assert_eq!(list, "p:one — first\ntwo");
+ let read = super::execute_builtin(
+ lookup("skill_read").unwrap(),
+ &json!({"name": "p:one"}),
+ &ctx,
+ )
+ .await
+ .0;
+ assert_eq!(read, "body one");
+ let missing =
+ super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "x"}), &ctx)
+ .await
+ .0;
+ assert!(missing.starts_with("ERROR"), "{missing}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn built_in_jan_skill_is_available_without_project_skills() {
let root = unique_root();
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index dec1aa56b..2720cc805 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -84,6 +84,16 @@ pub struct ToolContext<'a> {
/// every surface with no folder attached. Skill *writes* and all memory ops
/// still target `store_root`; only skill reads consult this overlay.
pub skill_project_root: Option<&'a Path>,
+ /// A richer skill resolver supplied by the host (the CLI's layering of
+ /// project, plugin, user and built-in skills). When set, `skill_list`/`skill_read` go
+ /// through it instead of the plain layered store scan, so every surface the
+ /// host builds sees the same catalog its system prompt advertises. `None`
+ /// keeps the store-only behaviour (the desktop).
+ pub skill_source: Option<SkillSource>,
+ /// The user-wide skill store root (`~/.jan`; skills land in its `skills/`),
+ /// the target of `skill_write` with `scope: "user"`. `None` on surfaces
+ /// with no user scope, where that scope is refused.
+ pub skill_user_root: Option<&'a Path>,
/// `~/.jan`, reached by the `memory_*` tools as the `user:` scope and as
/// the parent of other projects' stores. `None` (the desktop) confines
/// memory to `store_root`.
@@ -200,6 +210,8 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("project_root", &self.project_root)
.field("store_root", &self.store_root)
.field("skill_project_root", &self.skill_project_root)
+ .field("skill_source", &self.skill_source.is_some())
+ .field("skill_user_root", &self.skill_user_root)
.field("memory_home", &self.memory_home)
.field("cross_project", &self.cross_project)
.field("enabled_skills", &self.enabled_skills)
@@ -226,6 +238,19 @@ impl std::fmt::Debug for ToolContext<'_> {
}
}
+/// A host-side skill resolver for the model's `skill_list`/`skill_read`.
+/// Implementations apply their own enabled whitelist and invocation-side
+/// filtering: `catalog` returns only model-invocable, enabled skills as
+/// `(name, description)` pairs in a stable order, and `read` returns the body
+/// (frontmatter stripped) of one such skill or an `ERROR: ...` string.
+pub trait SkillProvider: Send + Sync {
+ fn catalog(&self) -> Vec<(String, String)>;
+ fn read(&self, name: &str) -> Result<String, String>;
+}
+
+/// Shared handle to a [`SkillProvider`]; cheap to clone into every context.
+pub type SkillSource = std::sync::Arc<dyn SkillProvider>;
+
/// A tool's live-output channel: called with each chunk as it arrives, in order.
/// Chunks are raw fragments, not lines -- a caller that wants lines buffers them.
pub type OutputSink = std::sync::Arc<dyn Fn(String) + Send + Sync>;
@@ -338,6 +363,8 @@ impl<'a> ToolContext<'a> {
project_root,
store_root,
skill_project_root: None,
+ skill_source: None,
+ skill_user_root: None,
memory_home: None,
cross_project: false,
enabled_skills,
@@ -416,6 +443,20 @@ impl<'a> ToolContext<'a> {
self
}
+ /// Resolve `skill_list`/`skill_read` through `source`. See
+ /// [`Self::skill_source`].
+ pub fn with_skill_source(mut self, source: SkillSource) -> Self {
+ self.skill_source = Some(source);
+ self
+ }
+
+ /// Enable `skill_write`'s `scope: "user"`, writing under `root/skills`.
+ /// See [`Self::skill_user_root`].
+ pub fn with_skill_user_root(mut self, root: Option<&'a Path>) -> Self {
+ self.skill_user_root = root;
+ self
+ }
+
/// Give the `memory_*` tools the user scope and, when `cross_project`, the
/// other projects under `home`. See [`crate::memory::Scopes`].
pub fn with_memory_home(mut self, home: &'a Path, cross_project: bool) -> Self {
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs
index ef9d78e41..57198095e 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs
@@ -150,7 +150,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {
"type": "function",
"function": {
"name": "skill_list",
- "description": "List the project skills (reusable procedures) with a one-line description of each. No arguments.",
+ "description": "List the available skills (reusable procedures) with a one-line description of each. No arguments.",
"parameters": { "type": "object", "properties": {}, "required": [] }
}
}),
@@ -172,12 +172,13 @@ pub fn builtin_tool_schemas() -> Vec<Value> {
"type": "function",
"function": {
"name": "skill_write",
- "description": "Create or update a project skill (a reusable procedure for this project). Keep it concise.",
+ "description": "Create or update a skill (a reusable procedure). Keep it concise.",
"parameters": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "Skill name (without the .md extension); becomes the skill title." },
- "content": { "type": "string", "description": "Full Markdown content of the skill." }
+ "content": { "type": "string", "description": "Full Markdown content of the skill." },
+ "scope": { "type": "string", "enum": ["project", "user"], "description": "Where to store it: `project` (default) for this project only, `user` for every project." }
},
"required": ["name", "content"]
}
@@ -323,6 +324,26 @@ mod tests {
assert_eq!(names, expected);
}
+ /// `skill_write` gains an optional `scope` (janhq/jan-internal#394):
+ /// additive, so `required` is unchanged and a caller that omits it keeps
+ /// writing to the project. The schema must also serialize to the same
+ /// bytes every time, since the tool array sits in the cached prefix.
+ #[test]
+ fn skill_write_scope_is_optional_and_the_schema_is_deterministic() {
+ let schemas = builtin_tool_schemas();
+ let write = schemas
+ .iter()
+ .find(|s| s["function"]["name"] == "skill_write")
+ .expect("skill_write advertised");
+ let params = &write["function"]["parameters"];
+ assert_eq!(params["required"], json!(["name", "content"]));
+ assert_eq!(params["properties"]["scope"]["type"], "string");
+ assert_eq!(params["properties"]["scope"]["enum"], json!(["project", "user"]));
+ let once = serde_json::to_string(&builtin_tool_schemas()).unwrap();
+ let twice = serde_json::to_string(&builtin_tool_schemas()).unwrap();
+ assert_eq!(once, twice);
+ }
+
/// The search schemas name the arguments the handlers actually read; a
/// rename on either side would otherwise silently produce a tool whose
/// required argument never arrives.
diff --git a/src-tauri/src/core/agent/default_skill.md b/src-tauri/src/core/agent/default_skill.md
index 22f5b35bd..009fd2114 100644
--- a/src-tauri/src/core/agent/default_skill.md
+++ b/src-tauri/src/core/agent/default_skill.md
@@ -21,9 +21,12 @@ but NOT its full instructions. When a skill's purpose matches the task, call
- `skill_read` (name) - load a skill's full instructions. Do this before
applying a skill; the catalog only shows its purpose. The same
`disable-model-invocation: true` rule applies: such skills read as not found.
-- `skill_write` (name, content) - create a new skill or update an existing one
- (same name overwrites). Use a short, descriptive name; keep the skill concise.
- Start the skill with a one-line description so the catalog can summarize it.
+- `skill_write` (name, content, scope?) - create a new skill or update an
+ existing one (same name overwrites). Use a short, descriptive name; keep the
+ skill concise. Start the skill with a one-line description so the catalog can
+ summarize it. Skills go to this project by default; pass `scope: "user"` only
+ for a procedure that is useful in every project (a same-named project skill
+ shadows a user one).
Create or update a skill when you discover a procedure worth reusing on later
runs. Refine an existing skill instead of duplicating it.
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 86b4a9509..0a82b3752 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -928,6 +928,16 @@ impl CompositeToolInvoker {
Some(home) => ctx.with_memory_home(home, self.cross_project),
None => ctx,
};
+ // The model's skill tools resolve through the same layering as the
+ // system-prompt catalog (project, plugin, user, built-in), and
+ // `skill_write` `scope:"user"` lands in `~/.jan/skills` (the same
+ // `~/.jan` as the user memory scope).
+ let ctx = ctx
+ .with_skill_source(crate::core::agent::skills::CoreSkillSource::shared(
+ &self.project_root,
+ &self.enabled_skills,
+ ))
+ .with_skill_user_root(self.memory_home.as_deref());
ctx.with_network(self.allow_network)
.with_home_readonly(self.allow_home_read)
.with_sandbox(self.sandbox)
@@ -2168,6 +2178,10 @@ impl ToolInvoker for CompositeToolInvoker {
None => ctx,
};
let ctx = ctx
+ .with_skill_source(crate::core::agent::skills::CoreSkillSource::shared(
+ &root, &enabled,
+ ))
+ .with_skill_user_root(memory_home.as_deref())
.with_network(allow_network)
.with_home_readonly(allow_home_read)
.with_sandbox(sandbox)
@@ -7890,6 +7904,47 @@ mod tests {
}
}
+ /// janhq/jan-internal#394: the CLI's `skill_list`/`skill_read` resolve
+ /// through the same layering as the prompt catalog, so a plugin skill the
+ /// prompt advertises is readable (it used to read only `<store>/skills`),
+ /// on both the concurrent read path and the serial one.
+ #[tokio::test]
+ async fn the_cli_skill_tools_read_plugin_skills() {
+ let root = std::env::temp_dir().join(format!(
+ "jan_loop_plugin_skill_{}_{}",
+ std::process::id(),
+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let dir = crate::core::agent::skills::plugins_dir(&root).join("rel/skills/prepare");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("SKILL.md"), "---\ndescription: prep\n---\nplugin body\n")
+ .unwrap();
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let invoker = build_prompting_invoker(root.clone(), tx, PermissionRegistry::default());
+ let call = |id: &str, name: &str, args: &str| {
+ json!({"id": id, "type": "function", "function": {"name": name, "arguments": args}})
+ };
+ let out = invoker
+ .invoke(&[
+ call("l", "skill_list", "{}"),
+ call("r", "skill_read", r#"{"name":"rel:prepare"}"#),
+ ])
+ .await
+ .unwrap();
+ assert!(out[0].content.contains("rel:prepare — prep"), "{}", out[0].content);
+ assert_eq!(out[1].content, "plugin body");
+ // Through the non-concurrent context too (the one writes use).
+ let (text, _) = tauri_plugin_agent_tools::tools::handlers::execute_builtin(
+ tauri_plugin_agent_tools::tools::lookup("skill_read").unwrap(),
+ &json!({"name": "prepare"}),
+ &invoker.tool_context(),
+ )
+ .await;
+ assert_eq!(text, "plugin body");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
/// The acceptance requirement that a hook denial is indistinguishable from
/// a gate denial in the transcript: same `ERROR: tool '<name>' denied`
/// prefix, carried back as an ordinary tool result rather than a run error.
diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rs
index 4c9eaec8b..5ee807bc8 100644
--- a/src-tauri/src/core/agent/prefix_stability.rs
+++ b/src-tauri/src/core/agent/prefix_stability.rs
@@ -192,6 +192,18 @@ impl Project {
"---\nname: example\ndescription: An example skill\n---\n\nSkill body.\n",
)
.unwrap();
+ // A user-scope skill (`~/.jan/skills`, janhq/jan-internal#394): the
+ // catalog layers it in, and it must be as byte-stable as a project one.
+ // The test home is shared by the whole process, so the skill lives as
+ // long as any fixture does and no longer.
+ LIVE_FIXTURES.fetch_add(1, Ordering::SeqCst);
+ let user = crate::core::agent::skills::user_skills_dir().unwrap();
+ std::fs::create_dir_all(user.join("user-example")).unwrap();
+ std::fs::write(
+ user.join("user-example/SKILL.md"),
+ "---\nname: user-example\ndescription: A user-wide example skill\n---\n\nUser body.\n",
+ )
+ .unwrap();
std::fs::write(
store.join("memory/note.md"),
"A durable fact about the fixture project.\n\nLonger detail.\n",
@@ -205,8 +217,17 @@ impl Project {
}
}
+/// Live [`Project`] fixtures, so the shared user-scope skill is removed when
+/// the last one drops.
+static LIVE_FIXTURES: AtomicU32 = AtomicU32::new(0);
+
impl Drop for Project {
fn drop(&mut self) {
+ if LIVE_FIXTURES.fetch_sub(1, Ordering::SeqCst) == 1 {
+ if let Some(user) = crate::core::agent::skills::user_skills_dir() {
+ let _ = std::fs::remove_dir_all(user.join("user-example"));
+ }
+ }
let _ = std::fs::remove_dir_all(&self.root);
}
}
@@ -379,6 +400,7 @@ fn the_fixture_reaches_every_prefix_composer() {
"<project_context>",
"# Available Skills",
"## Skill: example",
+ "## Skill: user-example",
"# Available Memories",
"- `note` - A durable fact about the fixture project.",
] {
diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rs
index 167855b25..792ab858d 100644
--- a/src-tauri/src/core/agent/skills.rs
+++ b/src-tauri/src/core/agent/skills.rs
@@ -26,6 +26,45 @@ pub(crate) fn skills_dir(root: &Path) -> PathBuf {
crate::core::agent::project::store_root(root).join("skills")
}
+/// The user-wide skill store root: `~/.jan` (skills live in its `skills/`,
+/// beside the user memory scope `~/.jan/memory`). Resolved through
+/// [`crate::core::agent::project::jan_home`], so test builds point at a
+/// per-process temp home. `None` when there is no usable home directory.
+pub(crate) fn user_store_root() -> Option<PathBuf> {
+ crate::core::agent::project::jan_home()
+}
+
+/// `~/.jan/skills`, the user scope: skills visible from every project.
+pub(crate) fn user_skills_dir() -> Option<PathBuf> {
+ user_store_root().map(|home| tauri_plugin_agent_tools::skills::skills_dir(&home))
+}
+
+/// Where a skill came from. Resolution order (earlier shadows later on the
+/// same plain name): project, then user, then the built-in `jan` skill.
+/// Plugin skills are always qualified `<plugin>:<name>`, so they never collide
+/// with a plain name.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SkillScope {
+ Project,
+ Plugin,
+ User,
+ Builtin,
+}
+
+#[cfg(any(feature = "cli", test))]
+#[cfg_attr(not(feature = "cli"), allow(dead_code))]
+impl SkillScope {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ SkillScope::Project => "project",
+ SkillScope::Plugin => "plugin",
+ SkillScope::User => "user",
+ SkillScope::Builtin => "built-in",
+ }
+ }
+}
+
/// One skill on disk, located by its identity name (folder name or flat stem).
#[derive(Debug, Clone)]
pub(crate) struct SkillEntry {
@@ -36,6 +75,20 @@ pub(crate) struct SkillEntry {
pub is_folder: bool,
/// The plugin this skill ships in (`Some`), or `None` for a project skill.
pub plugin: Option<String>,
+ /// True for a skill from the user scope (`~/.jan/skills`).
+ pub user: bool,
+}
+
+impl SkillEntry {
+ pub(crate) fn scope(&self) -> SkillScope {
+ if self.plugin.is_some() {
+ SkillScope::Plugin
+ } else if self.user {
+ SkillScope::User
+ } else {
+ SkillScope::Project
+ }
+ }
}
/// Summary for the management UI / prompt catalog.
@@ -51,6 +104,8 @@ pub struct SkillMeta {
pub user_invocable: bool,
/// Offered to the model (system-prompt catalog, `skill_list`/`skill_read`).
pub model_invocable: bool,
+ /// Which layer the skill resolved from.
+ pub scope: SkillScope,
}
/// Frontmatter fields we recognize; everything else is ignored.
@@ -174,8 +229,14 @@ pub(crate) fn scan_skill_dir(dir: &Path) -> Vec<SkillEntry> {
};
for entry in rd.flatten() {
let path = entry.path();
- let Ok(ft) = entry.file_type() else { continue };
- if ft.is_dir() {
+ // `metadata` follows symlinks (unlike `DirEntry::file_type`), so a
+ // symlinked skill folder or file is listed like a real one. Dangling
+ // links and symlink loops fail here (ELOOP) and are skipped; nothing
+ // below recurses, so a loop can never be walked.
+ let Ok(meta) = std::fs::metadata(&path) else {
+ continue;
+ };
+ if meta.is_dir() {
let skill_md = path.join("SKILL.md");
if skill_md.is_file() {
if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
@@ -184,16 +245,18 @@ pub(crate) fn scan_skill_dir(dir: &Path) -> Vec<SkillEntry> {
file: skill_md,
is_folder: true,
plugin: None,
+ user: false,
});
}
}
- } else if path.extension().and_then(|x| x.to_str()) == Some("md") {
+ } else if meta.is_file() && path.extension().and_then(|x| x.to_str()) == Some("md") {
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
consider(SkillEntry {
name: stem.to_string(),
file: path,
is_folder: false,
plugin: None,
+ user: false,
});
}
}
@@ -208,6 +271,33 @@ pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {
scan_skill_dir(&skills_dir(root))
}
+/// All user-scope skills (`~/.jan/skills`), sorted by name.
+pub(crate) fn discover_user() -> Vec<SkillEntry> {
+ let Some(dir) = user_skills_dir() else {
+ return Vec::new();
+ };
+ scan_skill_dir(&dir)
+ .into_iter()
+ .map(|e| SkillEntry { user: true, ..e })
+ .collect()
+}
+
+/// A skill file's identity on disk for deduplication: its canonical path, so
+/// the same folder reached through two symlinks (or a project `skills/` that
+/// is itself a link to `~/.jan/skills`) counts once.
+fn canonical(file: &Path) -> PathBuf {
+ std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf())
+}
+
+/// A skill that lost to a higher-precedence one of the same name.
+#[derive(Debug, Clone)]
+#[cfg_attr(not(any(feature = "cli", test)), allow(dead_code))]
+pub(crate) struct Shadowed {
+ pub entry: SkillEntry,
+ /// The scope of the skill that wins.
+ pub by: SkillScope,
+}
+
/// The plugins directory `<store_root>/plugins`.
pub(crate) fn plugins_dir(root: &Path) -> PathBuf {
crate::core::agent::project::store_root(root).join("plugins")
@@ -296,6 +386,7 @@ pub(crate) fn discover_plugins(root: &Path) -> Vec<SkillEntry> {
file: root_md,
is_folder: false,
plugin: Some(plugin.to_string()),
+ user: false,
});
}
out.extend(tagged);
@@ -304,12 +395,96 @@ pub(crate) fn discover_plugins(root: &Path) -> Vec<SkillEntry> {
out
}
-/// Project skills followed by plugin skills (qualified). Project skills shadow
-/// plugin skills of the same plain name.
+/// Every active skill in precedence order: project skills, plugin skills
+/// (qualified `<plugin>:<name>`), then user skills not shadowed by a project
+/// skill of the same name. The same file reached twice (symlinks) is kept
+/// once, at its highest-precedence location.
pub(crate) fn discover_all(root: &Path) -> Vec<SkillEntry> {
- let mut out = discover(root);
- out.extend(discover_plugins(root));
- out
+ discover_layers(root).0
+}
+
+/// [`discover_all`] plus the entries it dropped because a higher layer owns
+/// the name. A duplicate of the same canonical file is not reported as
+/// shadowed: it is one skill seen twice, not two skills competing.
+pub(crate) fn discover_layers(root: &Path) -> (Vec<SkillEntry>, Vec<Shadowed>) {
+ let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
+ let mut out: Vec<SkillEntry> = Vec::new();
+ for e in discover(root).into_iter().chain(discover_plugins(root)) {
+ if seen.insert(canonical(&e.file)) {
+ out.push(e);
+ }
+ }
+ let mut shadowed = Vec::new();
+ for e in discover_user() {
+ if !seen.insert(canonical(&e.file)) {
+ continue;
+ }
+ if out.iter().any(|o| o.plugin.is_none() && o.name == e.name) {
+ shadowed.push(Shadowed {
+ entry: e,
+ by: SkillScope::Project,
+ });
+ continue;
+ }
+ out.push(e);
+ }
+ (out, shadowed)
+}
+
+/// One row of the `/skills` listing: every discovered skill, its scope, and
+/// which scope shadows it, if any. Sorted by name, winners before losers.
+#[cfg(any(feature = "cli", test))]
+#[cfg_attr(not(feature = "cli"), allow(dead_code))]
+pub(crate) struct SkillReportRow {
+ pub name: String,
+ pub scope: SkillScope,
+ pub description: String,
+ pub shadowed_by: Option<SkillScope>,
+ pub user_invocable: bool,
+ pub model_invocable: bool,
+ pub enabled: bool,
+}
+
+/// The `/skills` listing: active skills (both invocation sides), the built-in
+/// `jan` skill, and every shadowed entry, marked. `enabled` is the
+/// `[skills].enabled` whitelist, reported rather than filtered.
+#[cfg(any(feature = "cli", test))]
+pub(crate) fn report(root: &Path, enabled: &[String]) -> Vec<SkillReportRow> {
+ let (active, shadowed) = discover_layers(root);
+ let row = |e: &SkillEntry, shadowed_by: Option<SkillScope>| {
+ let parsed = parse(&std::fs::read_to_string(&e.file).unwrap_or_default());
+ SkillReportRow {
+ name: qualified_name(e),
+ scope: e.scope(),
+ description: describe(&parsed),
+ shadowed_by,
+ user_invocable: parsed.user_invocable,
+ model_invocable: parsed.model_invocable,
+ enabled: is_enabled(enabled, e),
+ }
+ };
+ let mut rows: Vec<SkillReportRow> = active.iter().map(|e| row(e, None)).collect();
+ rows.extend(shadowed.iter().map(|s| row(&s.entry, Some(s.by))));
+ let builtin = default_jan_skill_meta();
+ let jan_owner = active
+ .iter()
+ .find(|e| e.plugin.is_none() && e.name == DEFAULT_JAN_SKILL_NAME)
+ .map(SkillEntry::scope);
+ rows.push(SkillReportRow {
+ name: builtin.name,
+ scope: SkillScope::Builtin,
+ description: builtin.description,
+ shadowed_by: jan_owner,
+ user_invocable: true,
+ model_invocable: true,
+ enabled: enabled.is_empty() || enabled.iter().any(|n| n == DEFAULT_JAN_SKILL_NAME),
+ });
+ rows.sort_by(|a, b| {
+ a.name
+ .cmp(&b.name)
+ .then(a.shadowed_by.is_some().cmp(&b.shadowed_by.is_some()))
+ });
+ rows
}
/// The user-facing identity of a skill entry: `name` for project skills,
@@ -321,30 +496,40 @@ pub(crate) fn qualified_name(entry: &SkillEntry) -> String {
}
}
-/// Locate a project skill by name, preferring the folder form. Plugin skills
-/// are not resolved here — `resolve_readable` handles those.
+/// Locate a plain (unqualified) skill by name: the project store first, then
+/// the user scope, each preferring the folder form. Plugin skills are not
+/// resolved here — `resolve_readable` handles those.
fn resolve(root: &Path, name: &str) -> Result<SkillEntry, String> {
let stem = safe_stem(name)?;
- let dir = skills_dir(root);
- let folder = dir.join(&stem).join("SKILL.md");
+ if let Some(entry) = resolve_in_dir(&skills_dir(root), &stem, false) {
+ return Ok(entry);
+ }
+ if let Some(entry) = user_skills_dir().and_then(|dir| resolve_in_dir(&dir, &stem, true)) {
+ return Ok(entry);
+ }
+ Err(format!("ERROR: skill '{name}' not found"))
+}
+
+/// Locate `stem` in one plain skills directory, folder form first.
+fn resolve_in_dir(dir: &Path, stem: &str, user: bool) -> Option<SkillEntry> {
+ let folder = dir.join(stem).join("SKILL.md");
if folder.is_file() {
- return Ok(SkillEntry {
- name: stem,
+ return Some(SkillEntry {
+ name: stem.to_string(),
file: folder,
is_folder: true,
plugin: None,
+ user,
});
}
let flat = dir.join(format!("{stem}.md"));
- if flat.is_file() {
- return Ok(SkillEntry {
- name: stem,
- file: flat,
- is_folder: false,
- plugin: None,
- });
- }
- Err(format!("ERROR: skill '{name}' not found"))
+ flat.is_file().then(|| SkillEntry {
+ name: stem.to_string(),
+ file: flat,
+ is_folder: false,
+ plugin: None,
+ user,
+ })
}
/// Locate a skill inside an installed plugin: `plugins/<plugin>/skills/<plain>`
@@ -363,6 +548,7 @@ fn resolve_in_plugin(root: &Path, plugin: &str, plain: &str) -> Option<SkillEntr
file: folder,
is_folder: true,
plugin: Some(plugin.to_string()),
+ user: false,
});
}
let flat = base.join("skills").join(format!("{plain}.md"));
@@ -372,6 +558,7 @@ fn resolve_in_plugin(root: &Path, plugin: &str, plain: &str) -> Option<SkillEntr
file: flat,
is_folder: false,
plugin: Some(plugin.to_string()),
+ user: false,
});
}
if plain == plugin {
@@ -382,14 +569,15 @@ fn resolve_in_plugin(root: &Path, plugin: &str, plain: &str) -> Option<SkillEntr
file: root_md,
is_folder: false,
plugin: Some(plugin.to_string()),
+ user: false,
});
}
}
None
}
-/// Locate any readable skill: project skill first (project shadows plugins),
-/// then the explicit `<plugin>:<plain>` form, then a plain name that is unique
+/// Locate any readable skill: a plain project or user skill first (project
+/// shadows user), then the explicit `<plugin>:<plain>` form, then a plain name that is unique
/// across installed plugins. Used by `read_raw` so `skill_read` and invocation
/// dispatch reach plugin skills with the same names the catalogs advertise.
pub(crate) fn resolve_readable(root: &Path, name: &str) -> Result<SkillEntry, String> {
@@ -441,6 +629,7 @@ fn meta_for(entry: &SkillEntry, parsed: &ParsedSkill) -> SkillMeta {
plugin: entry.plugin.clone(),
user_invocable: parsed.user_invocable,
model_invocable: parsed.model_invocable,
+ scope: entry.scope(),
}
}
/// Whether a name refers to the built-in Jan skill (aliased `jan`), which is
@@ -462,6 +651,7 @@ fn default_jan_skill_meta() -> SkillMeta {
plugin: None,
user_invocable: true,
model_invocable: true,
+ scope: SkillScope::Builtin,
}
}
@@ -538,7 +728,7 @@ pub(crate) fn user_catalog(root: &Path, enabled: &[String]) -> Vec<SkillMeta> {
side_catalog(root, enabled, |p| p.user_invocable)
}
-/// Every discovered skill (project + plugin), both invocation sides, ignoring
+/// Every discovered skill (project + plugin + user), both invocation sides, ignoring
/// the enabled whitelist — the full disk truth. This is what `/reload skills`
/// diffs against the previous scan, so an edit or install shows up as an
/// added/removed/changed entry regardless of who may invoke it.
@@ -682,9 +872,60 @@ pub(crate) fn build_invocation_message(
Ok((msg, meta.description))
}
-/// Find a skill in a user-side catalog by the name a human typed: exact
-/// match first (project names and the explicit `<plugin>:<skill>` form), then
-/// a plain name that is unique across plugin skills.
+/// The body the model's `skill_read` gets for `name`: resolved against the
+/// model-side catalog (enabled whitelist, `disable-model-invocation`), so it
+/// reads exactly the skills the system prompt advertises, plugin and user
+/// skills included. Frontmatter is stripped.
+pub(crate) fn read_for_model(root: &Path, enabled: &[String], name: &str) -> Result<String, String> {
+ let not_found = || format!("ERROR: skill '{name}' not found");
+ let catalog = catalog(root, enabled);
+ let meta = find_user_skill(&catalog, name).ok_or_else(not_found)?;
+ match resolve_readable(root, &meta.name) {
+ Ok(entry) => {
+ let raw = std::fs::read_to_string(&entry.file).map_err(|e| format!("ERROR: {e}"))?;
+ Ok(parse(&raw).body)
+ }
+ Err(_) if meta.scope == SkillScope::Builtin => Ok(parse(DEFAULT_JAN_SKILL).body),
+ Err(_) => Err(not_found()),
+ }
+}
+
+/// The CLI's skill resolver for the model tools (`skill_list`/`skill_read`):
+/// the same project + plugin + user + built-in layering as the system-prompt
+/// catalog, so a skill the prompt advertises is always readable.
+pub(crate) struct CoreSkillSource {
+ pub root: PathBuf,
+ pub enabled: Vec<String>,
+}
+
+impl CoreSkillSource {
+ pub(crate) fn shared(
+ root: &Path,
+ enabled: &[String],
+ ) -> tauri_plugin_agent_tools::tools::SkillSource {
+ std::sync::Arc::new(Self {
+ root: root.to_path_buf(),
+ enabled: enabled.to_vec(),
+ })
+ }
+}
+
+impl tauri_plugin_agent_tools::tools::SkillProvider for CoreSkillSource {
+ fn catalog(&self) -> Vec<(String, String)> {
+ catalog(&self.root, &self.enabled)
+ .into_iter()
+ .map(|m| (m.name, m.description))
+ .collect()
+ }
+
+ fn read(&self, name: &str) -> Result<String, String> {
+ read_for_model(&self.root, &self.enabled, name)
+ }
+}
+
+/// Find a skill in a catalog by the name a human (or the model) typed: exact
+/// match first (project/user names and the explicit `<plugin>:<skill>`
+/// form), then a plain name that is unique across plugin skills.
fn find_user_skill(user_skills: &[SkillMeta], name: &str) -> Option<SkillMeta> {
if let Some(meta) = user_skills.iter().find(|m| m.name == name).cloned() {
return Some(meta);
@@ -1221,4 +1462,206 @@ mod tests {
assert!(build_invocation_message(&root, "nope", "").is_err());
let _ = std::fs::remove_dir_all(&root);
}
+
+ /// Skills written into the (per-process, test-only) user scope
+ /// `~/.jan/skills`, removed on drop so no other test sees them.
+ struct UserSkills(Vec<std::path::PathBuf>);
+
+ impl UserSkills {
+ fn new() -> Self {
+ Self(Vec::new())
+ }
+
+ fn folder(&mut self, name: &str, body: &str) -> std::path::PathBuf {
+ let dir = user_skills_dir().unwrap().join(name);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("SKILL.md"), body).unwrap();
+ self.0.push(dir.clone());
+ dir
+ }
+
+ fn flat(&mut self, name: &str, body: &str) {
+ let dir = user_skills_dir().unwrap();
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join(format!("{name}.md"));
+ std::fs::write(&file, body).unwrap();
+ self.0.push(file);
+ }
+
+ /// Track a path created by the test itself (a symlink, say).
+ fn track(&mut self, path: std::path::PathBuf) {
+ self.0.push(path);
+ }
+ }
+
+ impl Drop for UserSkills {
+ fn drop(&mut self) {
+ for path in &self.0 {
+ if std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()) {
+ let _ = std::fs::remove_dir_all(path);
+ } else {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn user_scope_skills_reach_catalogs_and_reads_from_any_project() {
+ let mut user = UserSkills::new();
+ user.folder("u394-review", "---\ndescription: Review a diff\n---\nreview body\n");
+ user.flat("u394-notes", "---\ndescription: Take notes\n---\nnotes body\n");
+ for tag in ["ua", "ub"] {
+ let root = temp_root(tag);
+ let model = catalog(&root, &[]);
+ let m = model.iter().find(|m| m.name == "u394-review").expect("user skill listed");
+ assert_eq!(m.scope, SkillScope::User);
+ assert_eq!(m.description, "Review a diff");
+ assert!(model.iter().any(|m| m.name == "u394-notes"), "flat user skill");
+ assert!(user_catalog(&root, &[]).iter().any(|m| m.name == "u394-review"));
+ assert_eq!(read_for_model(&root, &[], "u394-review").unwrap(), "review body");
+ assert_eq!(read_for_model(&root, &[], "u394-notes").unwrap(), "notes body");
+ let (msg, _) = build_invocation_message(&root, "u394-review", "").unwrap();
+ assert!(msg.contains("review body"), "{msg}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+ }
+
+ #[test]
+ fn project_skill_shadows_a_same_named_user_skill_and_report_marks_it() {
+ let mut user = UserSkills::new();
+ user.folder("u394-deploy", "---\ndescription: user deploy\n---\nuser body\n");
+ let root = temp_root("shadow");
+ project_skill(&root, "u394-deploy", "---\ndescription: project deploy\n---\nproject body\n");
+
+ let model = catalog(&root, &[]);
+ let hits: Vec<_> = model.iter().filter(|m| m.name == "u394-deploy").collect();
+ assert_eq!(hits.len(), 1, "one entry per name");
+ assert_eq!(hits[0].scope, SkillScope::Project);
+ assert_eq!(hits[0].description, "project deploy");
+ assert_eq!(read_for_model(&root, &[], "u394-deploy").unwrap(), "project body");
+
+ let rows = report(&root, &[]);
+ let rows: Vec<_> = rows.iter().filter(|r| r.name == "u394-deploy").collect();
+ assert_eq!(rows.len(), 2, "winner and shadowed entry both reported");
+ assert_eq!((rows[0].scope, rows[0].shadowed_by), (SkillScope::Project, None));
+ assert_eq!(
+ (rows[1].scope, rows[1].shadowed_by),
+ (SkillScope::User, Some(SkillScope::Project))
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn plugin_skills_stay_qualified_beside_a_same_named_user_skill() {
+ let mut user = UserSkills::new();
+ user.folder("u394-prepare", "---\ndescription: user prep\n---\nuser prep body\n");
+ let root = temp_root("plugq");
+ plugin_skill(&root, "rel", "u394-prepare", "---\ndescription: plugin prep\n---\nplugin prep body\n");
+
+ let model = catalog(&root, &[]);
+ let plain = model.iter().find(|m| m.name == "u394-prepare").unwrap();
+ assert_eq!(plain.scope, SkillScope::User);
+ let qualified = model.iter().find(|m| m.name == "rel:u394-prepare").unwrap();
+ assert_eq!(qualified.scope, SkillScope::Plugin);
+ // The plain name is the user skill; the qualified name is the plugin's.
+ assert_eq!(read_for_model(&root, &[], "u394-prepare").unwrap(), "user prep body");
+ assert_eq!(read_for_model(&root, &[], "rel:u394-prepare").unwrap(), "plugin prep body");
+ // Nothing is shadowed: the names differ.
+ assert!(report(&root, &[]).iter().all(|r| r.shadowed_by.is_none() || r.name == "jan"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn built_in_jan_is_shadowed_by_a_user_skill_named_jan() {
+ let mut user = UserSkills::new();
+ user.folder("jan", "---\ndescription: my jan\n---\nmine\n");
+ let root = temp_root("janu");
+ let model = catalog(&root, &[]);
+ let jan: Vec<_> = model.iter().filter(|m| m.name == "jan").collect();
+ assert_eq!(jan.len(), 1);
+ assert_eq!(jan[0].scope, SkillScope::User);
+ assert_eq!(read_for_model(&root, &[], "jan").unwrap(), "mine");
+ let builtin = report(&root, &[])
+ .into_iter()
+ .find(|r| r.scope == SkillScope::Builtin)
+ .unwrap();
+ assert_eq!(builtin.shadowed_by, Some(SkillScope::User));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn model_reads_plugin_skills_and_honours_filters() {
+ let root = temp_root("plugread");
+ plugin_skill(&root, "rel", "prepare", "---\ndescription: prep\n---\nprep body\n");
+ plugin_skill(
+ &root,
+ "rel",
+ "secret",
+ "---\ndescription: s\ndisable-model-invocation: true\n---\nno\n",
+ );
+ // Qualified and unique-plain names both read.
+ assert_eq!(read_for_model(&root, &[], "rel:prepare").unwrap(), "prep body");
+ assert_eq!(read_for_model(&root, &[], "prepare").unwrap(), "prep body");
+ // A user-only skill never reaches the model.
+ assert!(read_for_model(&root, &[], "rel:secret").is_err());
+ // The whitelist applies: a plugin not enabled is unreadable.
+ assert!(read_for_model(&root, &["other".into()], "rel:prepare").is_err());
+ assert!(read_for_model(&root, &["rel".into()], "rel:prepare").is_ok());
+ // The built-in jan skill still reads.
+ assert!(!read_for_model(&root, &[], "jan").unwrap().is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlinked_skill_folders_are_listed_in_both_scopes_and_deduped() {
+ use std::os::unix::fs::symlink;
+ let library = temp_root("library");
+ for name in ["u394-linked-proj", "u394-linked-user"] {
+ let dir = library.join(name);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("SKILL.md"), format!("---\ndescription: {name}\n---\nbody\n"))
+ .unwrap();
+ }
+ let root = temp_root("symlink");
+ let proj_dir = skills_dir(&root);
+ std::fs::create_dir_all(&proj_dir).unwrap();
+ symlink(library.join("u394-linked-proj"), proj_dir.join("u394-linked-proj")).unwrap();
+ // A symlink loop and a dangling link must be skipped, not hang or panic.
+ symlink(proj_dir.join("loop-b"), proj_dir.join("loop-a")).unwrap();
+ symlink(proj_dir.join("loop-a"), proj_dir.join("loop-b")).unwrap();
+ symlink(library.join("missing"), proj_dir.join("dangling")).unwrap();
+ // A self-referencing folder link (`dir/self -> dir`) is one level only.
+ symlink(&proj_dir, proj_dir.join("self")).unwrap();
+
+ let mut user = UserSkills::new();
+ let user_dir = user_skills_dir().unwrap();
+ std::fs::create_dir_all(&user_dir).unwrap();
+ let link = user_dir.join("u394-linked-user");
+ symlink(library.join("u394-linked-user"), &link).unwrap();
+ user.track(link);
+ // The same library folder linked into both scopes counts once.
+ let dup = user_dir.join("u394-linked-proj");
+ symlink(library.join("u394-linked-proj"), &dup).unwrap();
+ user.track(dup);
+
+ let model = catalog(&root, &[]);
+ let names: Vec<_> = model.iter().map(|m| (m.name.as_str(), m.scope)).collect();
+ assert!(names.contains(&("u394-linked-proj", SkillScope::Project)), "{names:?}");
+ assert!(names.contains(&("u394-linked-user", SkillScope::User)), "{names:?}");
+ assert_eq!(
+ names.iter().filter(|(n, _)| *n == "u394-linked-proj").count(),
+ 1,
+ "{names:?}"
+ );
+ assert!(!names.iter().any(|(n, _)| n.starts_with("loop") || *n == "dangling"));
+ // The duplicate is not reported as shadowing: it is the same file.
+ assert!(report(&root, &[])
+ .iter()
+ .all(|r| r.name != "u394-linked-proj" || r.shadowed_by.is_none()));
+ assert_eq!(read_for_model(&root, &[], "u394-linked-user").unwrap(), "body");
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&library);
+ }
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 6bde589e2..300d0b592 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -12193,6 +12193,12 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
description: "Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace",
alias_of: None,
},
+ SlashCommand {
+ name: "/skills",
+ hint: "",
+ description: "List skills with their scope (project, plugin, user, built-in) and shadowing",
+ alias_of: None,
+ },
SlashCommand {
name: "/reload",
hint: "[config|plugin|skills|system-prompt]",
@@ -12436,6 +12442,7 @@ async fn run_command(
"shells" | "jobs" => open_background_shells_picker(app),
"plugin" => plugin_command(app, arg).await,
"reload" => reload_command(app, arg),
+ "skills" => skills_command(app),
"login" => login_command(app, arg),
"logout" => logout_command(app, arg),
"update" => update_command(app),
@@ -14505,14 +14512,60 @@ fn reload_skill_entries(skills: &[crate::core::agent::skills::SkillMeta]) -> Vec
key: name.clone(),
label: name,
state: format!(
- "{} [user:{} model:{}]",
- m.description, m.user_invocable, m.model_invocable
+ "{} [{} user:{} model:{}]",
+ m.description,
+ m.scope.label(),
+ m.user_invocable,
+ m.model_invocable
),
}
})
.collect()
}
+/// `/skills`: every skill Jan can see from this project, with its scope and
+/// invocation sides, and each one hidden by a same-named higher-precedence
+/// skill marked with what shadows it. Precedence: project > user > built-in;
+/// plugin skills are qualified `<plugin>:<name>` and never collide.
+fn skills_command(app: &mut App) {
+ let enabled = crate::core::agent::project::enabled_skills(&app.project_root);
+ let rows = crate::core::agent::skills::report(&app.project_root, &enabled);
+ let user_dir = crate::core::agent::skills::user_skills_dir()
+ .map(|d| d.display().to_string())
+ .unwrap_or_else(|| "(no home directory)".to_string());
+ let active = rows.iter().filter(|r| r.shadowed_by.is_none()).count();
+ app.note(&format!(
+ "◈ skills · {active} active · precedence project > user > built-in · user scope {user_dir}"
+ ));
+ for row in &rows {
+ let mut flags = Vec::new();
+ if !row.user_invocable {
+ flags.push("model-only".to_string());
+ }
+ if !row.model_invocable {
+ flags.push("user-only".to_string());
+ }
+ if !row.enabled {
+ flags.push("disabled".to_string());
+ }
+ if let Some(by) = row.shadowed_by {
+ flags.push(format!("shadowed by {}", by.label()));
+ }
+ let flags = if flags.is_empty() {
+ String::new()
+ } else {
+ format!(" ({})", flags.join(", "))
+ };
+ app.system_detail_text(&format!(
+ "{:<9} {}{} · {}",
+ row.scope.label(),
+ row.name,
+ flags,
+ row.description
+ ));
+ }
+}
+
/// Display lines for what a reload changed, one list per kind of change.
#[derive(Default)]
struct ReloadDiff {
@@ -14586,7 +14639,7 @@ fn reload_catalog(app: &mut App, plugins: bool, skills: bool) {
}
if skills {
let after = reload_skill_entries(&app.slash_catalog.all_skills);
- app.note("◈ reload · skills · re-scanned project and plugin skills");
+ app.note("◈ reload · skills · re-scanned project, plugin, and user skills");
report_reload_diff(app, diff_reload_entries(&skills_before, &after));
}
}
@@ -37223,6 +37276,50 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// janhq/jan-internal#394: `/skills` lists every scope, and a user skill
+ /// hidden by a same-named project skill is shown as shadowed; the popup
+ /// catalog offers user skills and `/reload skills` picks up new ones.
+ #[tokio::test]
+ async fn skills_command_lists_scopes_and_marks_shadowing() {
+ let (mut app, root) = skill_test_app("tui394-deploy", "Project deploy.");
+ let user = crate::core::agent::skills::user_skills_dir().unwrap();
+ for (name, desc) in [("tui394-deploy", "User deploy."), ("tui394-review", "User review.")] {
+ std::fs::create_dir_all(user.join(name)).unwrap();
+ std::fs::write(
+ user.join(name).join("SKILL.md"),
+ format!("---\ndescription: {desc}\n---\n\nBody.\n"),
+ )
+ .unwrap();
+ }
+ run_command(&mut app, "skills", &no_mcp()).await;
+ let out = transcript_text(&app);
+ assert!(out.contains("precedence project > user > built-in"), "{out}");
+ assert!(out.contains("project tui394-deploy · Project deploy."), "{out}");
+ assert!(
+ out.contains("user tui394-deploy (shadowed by project) · User deploy."),
+ "{out}"
+ );
+ assert!(out.contains("user tui394-review · User review."), "{out}");
+ assert!(out.contains("built-in jan"), "{out}");
+
+ // The popup offers the user skill once `/reload skills` rescans.
+ run_command(&mut app, "reload skills", &no_mcp()).await;
+ assert!(transcript_text(&app).contains("+ tui394-review"));
+ assert!(app.slash_catalog.skills.iter().any(|m| m.name == "tui394-review"));
+ app.input = "/skill:tui394-r".into();
+ assert!(
+ app.slash_matches()
+ .iter()
+ .any(|m| m.name() == "/skill:tui394-review"),
+ "popup offers the user skill"
+ );
+
+ for name in ["tui394-deploy", "tui394-review"] {
+ let _ = std::fs::remove_dir_all(user.join(name));
+ }
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn reload_system_prompt_reads_jan_md() {
let (mut app, root) = skill_test_app("deploy", "How to deploy.");
diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rs
index f3d9082c5..d4bcc339d 100644
--- a/src-tauri/src/core/mcp/server/mod.rs
+++ b/src-tauri/src/core/mcp/server/mod.rs
@@ -93,6 +93,9 @@ pub struct ServeOptions {
pub store_root: PathBuf,
/// The `[skills].enabled` whitelist; empty means every skill.
pub enabled_skills: Vec<String>,
+ /// `~/.jan`, whose `skills/` is the user scope `skill_write` `scope:"user"`
+ /// writes to. `None` refuses that scope.
+ pub user_store_root: Option<PathBuf>,
/// Let the sandboxed shell reach the network.
pub allow_network: bool,
/// Run `bash` under OS confinement. Left on unless the operator turns it off.
@@ -112,6 +115,7 @@ impl ServeOptions {
project_root,
store_root,
enabled_skills: Vec::new(),
+ user_store_root: crate::core::agent::skills::user_store_root(),
allow_network: false,
sandbox: true,
scratch_root: None,
@@ -197,7 +201,12 @@ impl JanToolServer {
.with_network(self.opts.allow_network)
.with_sandbox(self.opts.sandbox)
.with_hidden_root(self.hidden_root.as_deref())
- .with_confined_writes(true);
+ .with_confined_writes(true)
+ .with_skill_source(crate::core::agent::skills::CoreSkillSource::shared(
+ &self.opts.project_root,
+ &self.opts.enabled_skills,
+ ))
+ .with_skill_user_root(self.opts.user_store_root.as_deref());
if let Some(scratch) = self.opts.scratch_root.as_deref() {
ctx = ctx.with_scratch_root(scratch);
}
diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rs
index 68d936695..f6771f3d7 100644
--- a/src-tauri/src/core/mcp/server/tests.rs
+++ b/src-tauri/src/core/mcp/server/tests.rs
@@ -454,3 +454,49 @@ async fn bash_exit_status_decides_is_error() {
client.cancel().await.ok();
server_task.abort();
}
+
+/// janhq/jan-internal#394: a served client reaches the same skills the agent
+/// does: user-scope skills from `~/.jan/skills` and plugin skills, by the
+/// names `skill_list` advertises, and `skill_write` `scope:"user"` lands in
+/// the user store.
+#[tokio::test]
+async fn served_skill_tools_reach_user_and_plugin_skills() {
+ let root = std::env::temp_dir().join(format!(
+ "jan_mcp_skills_{}_{}",
+ std::process::id(),
+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let plugin = crate::core::agent::skills::plugins_dir(&root).join("rel/skills/prep394");
+ std::fs::create_dir_all(&plugin).unwrap();
+ std::fs::write(plugin.join("SKILL.md"), "---\ndescription: prep\n---\nplugin body\n").unwrap();
+ let user_dir = crate::core::agent::skills::user_skills_dir().unwrap();
+ let user_skill = user_dir.join("mcp394-user");
+ std::fs::create_dir_all(&user_skill).unwrap();
+ std::fs::write(user_skill.join("SKILL.md"), "---\ndescription: mine\n---\nuser body\n").unwrap();
+
+ let server = JanToolServer::new(options(&root));
+ let (list, _) = server.dispatch("skill_list", &serde_json::json!({})).await;
+ assert!(list.contains("mcp394-user — mine"), "{list}");
+ assert!(list.contains("rel:prep394 — prep"), "{list}");
+ let (body, _) = server
+ .dispatch("skill_read", &serde_json::json!({"name": "mcp394-user"}))
+ .await;
+ assert_eq!(body, "user body");
+ let (body, _) = server
+ .dispatch("skill_read", &serde_json::json!({"name": "rel:prep394"}))
+ .await;
+ assert_eq!(body, "plugin body");
+ let (out, _) = server
+ .dispatch(
+ "skill_write",
+ &serde_json::json!({"name": "mcp394-written", "content": "x", "scope": "user"}),
+ )
+ .await;
+ assert_eq!(out, "Wrote user skill 'mcp394-written'");
+ assert!(user_dir.join("mcp394-written/SKILL.md").is_file());
+
+ let _ = std::fs::remove_dir_all(&user_skill);
+ let _ = std::fs::remove_dir_all(user_dir.join("mcp394-written"));
+ let _ = std::fs::remove_dir_all(&root);
+}