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): ship a built-in subagent catalog

Akarshan Biswasfb7ac6247e89
diff --git a/src-tauri/src/core/agent/builtin_subagents/explorer.toml b/src-tauri/src/core/agent/builtin_subagents/explorer.toml
new file mode 100644
index 000000000..c87b46328
--- /dev/null
+++ b/src-tauri/src/core/agent/builtin_subagents/explorer.toml
@@ -0,0 +1,13 @@
+name = "explorer"
+description = "Read-only codebase explorer on the cheap smol model: finds where things are and how they connect, and reports file paths and facts."
+model = "smol"
+allowed_tools = ["read", "shell"]
+system_prompt = """
+You are "explorer", a read-only codebase explorer. You are given one question about the code in the current project. Answer it by reading, never by changing anything.
+
+- Use the shell for listing and searching (`ls`, `rg`/`grep`, `find`, `git log`, `git grep`) and `read` to open the files that matter. Never run a command that writes, installs, builds, deletes or touches the network.
+- Search wide first, then read narrowly: open only the parts of files that bear on the question.
+- Do not guess. When the code does not settle something, say so and name what you checked.
+
+Finish with a concise, self-contained report for the agent that dispatched you: the answer first, then the evidence as `path:line` references with a one-line note each. Quote code only when the exact text matters.
+"""
diff --git a/src-tauri/src/core/agent/builtin_subagents/researcher.toml b/src-tauri/src/core/agent/builtin_subagents/researcher.toml
new file mode 100644
index 000000000..aac31df37
--- /dev/null
+++ b/src-tauri/src/core/agent/builtin_subagents/researcher.toml
@@ -0,0 +1,13 @@
+name = "researcher"
+description = "Web researcher on the smol model: answers a question from current sources and returns a cited summary."
+model = "smol"
+allowed_tools = ["web_search", "web_fetch", "read"]
+system_prompt = """
+You are "researcher". You are given one question that needs current or external information: library and API documentation, versions, error messages, standards, or anything outside the project.
+
+- Search with specific, descriptive queries, then read the most relevant pages in full with `web_fetch`. Do not rely on search snippets for anything that matters.
+- Prefer primary sources (official documentation, the project's repository, specifications) over blog posts and forums, and note each source's date when it matters.
+- When sources disagree or are thin, say so instead of picking one silently.
+
+Finish with a concise, self-contained report for the agent that dispatched you: the answer first, then the supporting points, each with the URL it came from.
+"""
diff --git a/src-tauri/src/core/agent/builtin_subagents/reviewer.toml b/src-tauri/src/core/agent/builtin_subagents/reviewer.toml
new file mode 100644
index 000000000..29972b255
--- /dev/null
+++ b/src-tauri/src/core/agent/builtin_subagents/reviewer.toml
@@ -0,0 +1,14 @@
+name = "reviewer"
+description = "Read-only code reviewer on the session's model: reviews a change or a set of files for correctness, risk and missing tests, and never edits."
+model = "inherit"
+allowed_tools = ["read", "shell"]
+system_prompt = """
+You are "reviewer", a careful code reviewer. You are given a change to review (a diff, a commit range, a branch or a list of files). You never edit files; you report.
+
+- Get the change yourself with read-only commands (`git diff`, `git show`, `git log`) and read the surrounding code that the change depends on or affects.
+- Look for real problems first: wrong behaviour, unhandled errors and edge cases, concurrency and resource issues, security, broken contracts with callers, and tests that are missing or do not test what they claim.
+- Check each suspicion against the code before reporting it. Leave out style preferences unless they hide a bug.
+- You may run the project's existing read-only checks (tests, linters) when that settles a question, but never a command that writes outside the build output or touches the network.
+
+Finish with a self-contained report: a one-line verdict, then each finding with its severity (blocking, should fix, nit), its `path:line`, what is wrong and a suggested fix. Say plainly if you found nothing.
+"""
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 374bae234..848793e6d 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1528,13 +1528,7 @@ impl CompositeToolInvoker {
Ok(d) => d,
Err(e) => return format!("ERROR: {e}"),
};
- let scope_label = match scope {
- SubagentScope::User => "user",
- SubagentScope::Project => "project",
- // Unreachable: create_subagent rejects the plugin scope
- // before this point.
- SubagentScope::Plugin => "plugin",
- };
+ let scope_label = scope.label();
let mut registry = SubagentRegistry::load(&self.project_root);
match registry.create_in(&dir, def.clone(), scope, overwrite) {
Ok(shadows) => {
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 29faac8b2..12934de4b 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -31,6 +31,68 @@ pub enum SubagentScope {
/// Claude Code convention). Read-only: managed via plugin install/remove,
/// never via `create_subagent`.
Plugin,
+ /// A subagent shipped inside Jan itself (`builtin_subagents/*.toml`).
+ /// Read-only and the lowest precedence: any saved definition of the same
+ /// name replaces it, and `[subagents.<name>]` in agent.toml retargets its
+ /// model.
+ Builtin,
+}
+
+impl SubagentScope {
+ /// The scope's name in listings (`name [scope]: ...`).
+ pub fn label(self) -> &'static str {
+ match self {
+ SubagentScope::User => "user",
+ SubagentScope::Project => "project",
+ SubagentScope::Plugin => "plugin",
+ SubagentScope::Builtin => "builtin",
+ }
+ }
+
+ /// Whether definitions in this scope are managed outside `create_subagent`.
+ fn read_only_reason(self) -> Option<&'static str> {
+ match self {
+ SubagentScope::User | SubagentScope::Project => None,
+ SubagentScope::Plugin => Some(
+ "plugin scope is read-only: plugin agents are managed via plugin install/remove",
+ ),
+ SubagentScope::Builtin => Some(
+ "builtin scope is read-only: a project or user subagent of the same name \
+ replaces a builtin one",
+ ),
+ }
+ }
+}
+
+/// The subagents shipped with Jan, in the order they load. Sorted by name and
+/// embedded at compile time, so the dispatch description that lists them is
+/// byte-identical across runs (it sits in the cached prompt prefix).
+const BUILTIN_SUBAGENTS: &[&str] = &[
+ include_str!("builtin_subagents/explorer.toml"),
+ include_str!("builtin_subagents/researcher.toml"),
+ include_str!("builtin_subagents/reviewer.toml"),
+];
+
+/// Parse [`BUILTIN_SUBAGENTS`]. A file that fails to parse is a build defect a
+/// test pins, so it is skipped with a warning rather than failing every run.
+fn builtin_definitions() -> Vec<SubagentDefinition> {
+ BUILTIN_SUBAGENTS
+ .iter()
+ .filter_map(|raw| match toml::from_str::<SubagentFile>(raw) {
+ Ok(file) => Some(SubagentDefinition {
+ name: file.name,
+ description: file.description,
+ system_prompt: file.system_prompt,
+ allowed_tools: file.allowed_tools,
+ model: file.model,
+ scope: SubagentScope::Builtin,
+ }),
+ Err(e) => {
+ log::warn!("subagent: skipping a builtin definition: {e}");
+ None
+ }
+ })
+ .collect()
}
/// A dispatchable subagent definition, resolved from a `<name>.toml` file plus
@@ -139,7 +201,7 @@ impl SubagentRegistry {
/// `/settings` screen shows that next to the override, so a user can see
/// what clearing the override falls back to.
pub fn load_definitions(project_root: &Path) -> Self {
- let mut defs = Vec::new();
+ let mut defs = builtin_definitions();
load_plugin_agents(project_root, &mut defs);
if let Some(dir) = user_subagents_dir() {
load_dir(&dir, SubagentScope::User, &mut defs);
@@ -194,10 +256,10 @@ impl SubagentRegistry {
"project scope requires create_in; use create_in".to_string(),
))
}
- SubagentScope::Plugin => return Err(SubagentError::Upstream(
- "plugin scope is read-only: plugin agents are managed via plugin install/remove"
- .to_string(),
- )),
+ SubagentScope::Plugin | SubagentScope::Builtin => {
+ let reason = scope.read_only_reason().unwrap_or_default();
+ return Err(SubagentError::Upstream(reason.to_string()));
+ }
};
self.create_in(&dir, def, scope, overwrite)
}
@@ -213,11 +275,8 @@ impl SubagentRegistry {
overwrite: bool,
) -> Result<bool, SubagentError> {
validate_name(&def.name)?;
- if scope == SubagentScope::Plugin {
- return Err(SubagentError::Upstream(
- "plugin scope is read-only: plugin agents are managed via plugin install/remove"
- .to_string(),
- ));
+ if let Some(reason) = scope.read_only_reason() {
+ return Err(SubagentError::Upstream(reason.to_string()));
}
let collides = self
.defs
@@ -2608,12 +2667,7 @@ pub fn format_subagent_list(registry: &SubagentRegistry) -> String {
}
let mut lines = Vec::with_capacity(defs.len());
for d in defs {
- let scope = match d.scope {
- SubagentScope::User => "user",
- SubagentScope::Project => "project",
- SubagentScope::Plugin => "plugin",
- };
- lines.push(format!("{} [{}]: {}", d.name, scope, d.description));
+ lines.push(format!("{} [{}]: {}", d.name, d.scope.label(), d.description));
}
lines.join("\n")
}
@@ -2880,9 +2934,8 @@ pub fn subagent_dir_for(
SubagentScope::User => user_subagents_dir().ok_or_else(|| {
SubagentError::Upstream("cannot resolve home directory for user scope".to_string())
}),
- SubagentScope::Plugin => Err(SubagentError::Upstream(
- "plugin scope is read-only: plugin agents are managed via plugin install/remove"
- .to_string(),
+ SubagentScope::Plugin | SubagentScope::Builtin => Err(SubagentError::Upstream(
+ scope.read_only_reason().unwrap_or_default().to_string(),
)),
}
}
@@ -3004,15 +3057,87 @@ pub(crate) mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// With nothing saved anywhere, only the shipped catalog loads.
#[test]
- fn empty_directories_yield_empty_registry() {
+ fn empty_directories_yield_only_the_builtin_catalog() {
let root = unique_root("empty");
let reg = SubagentRegistry::load(&root);
- assert!(reg.list().is_empty());
+ assert!(reg.list().iter().all(|d| d.scope == SubagentScope::Builtin));
assert!(reg.get("nope").is_none());
let _ = std::fs::remove_dir_all(&root);
}
+ /// The shipped catalog parses, in a fixed order: the dispatch tool's
+ /// description names it, and that description sits in the cached prompt
+ /// prefix, so the bytes must not move between runs.
+ #[test]
+ fn the_builtin_catalog_parses_in_a_stable_order() {
+ let defs = builtin_definitions();
+ let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
+ assert_eq!(names, ["explorer", "researcher", "reviewer"]);
+ for def in &defs {
+ assert_eq!(def.scope, SubagentScope::Builtin);
+ assert!(!def.description.is_empty() && !def.system_prompt.is_empty());
+ assert!(validate_name(&def.name).is_ok());
+ // Every tool named is one a child can actually be offered.
+ for tool in def.allowed_tools.as_deref().unwrap_or_default() {
+ assert!(
+ tauri_plugin_agent_tools::tools::lookup(tool).is_some(),
+ "{}: unknown tool {tool}",
+ def.name
+ );
+ }
+ }
+ let explorer = &defs[0];
+ assert_eq!(explorer.model.as_deref(), Some(SMOL_ROLE));
+ assert_eq!(
+ explorer.allowed_tools.as_deref(),
+ Some(&["read".to_string(), "shell".to_string()][..])
+ );
+ assert_eq!(builtin_definitions(), defs, "deterministic");
+ }
+
+ /// Built-ins are the lowest precedence: a plugin, user or project agent of
+ /// the same name replaces one, and the agent.toml override still applies.
+ #[test]
+ fn saved_definitions_shadow_builtins_and_overrides_apply_to_them() {
+ let root = unique_root("builtin_shadow");
+ write_def(&project_subagents_dir(&root), "reviewer", "model = \"mine\"\n");
+ let toml = crate::core::agent::project::agent_toml_path(&root);
+ std::fs::write(&toml, "[subagents.explorer]\nmodel = \"inherit\"\n").unwrap();
+
+ let reg = SubagentRegistry::load(&root);
+ let reviewer = reg.get("reviewer").unwrap();
+ assert_eq!(reviewer.scope, SubagentScope::Project);
+ assert_eq!(reviewer.model.as_deref(), Some("mine"));
+ let explorer = reg.get("explorer").unwrap();
+ assert_eq!(explorer.scope, SubagentScope::Builtin);
+ assert_eq!(explorer.model.as_deref(), Some(INHERIT_ROLE));
+ let listed = format_subagent_list(&reg);
+ assert!(listed.contains("explorer [builtin]"), "{listed}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The built-in scope is read-only, like the plugin scope: it ships with
+ /// Jan, so there is no file to write. A same-name project definition is
+ /// how a user replaces one.
+ #[test]
+ fn the_builtin_scope_is_not_a_create_target() {
+ let root = unique_root("builtin_ro");
+ let mut reg = SubagentRegistry::load(&root);
+ let def = builtin_definitions().remove(0);
+ assert!(reg
+ .create_in(&root, def.clone(), SubagentScope::Builtin, true)
+ .is_err());
+ assert!(reg.create(def, SubagentScope::Builtin, true).is_err());
+ assert!(subagent_dir_for(&root, SubagentScope::Builtin).is_err());
+ assert!(parse_create_args(&serde_json::json!({
+ "name": "x", "description": "d", "system_prompt": "sp", "scope": "builtin"
+ }))
+ .is_err());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn parses_definition_fields() {
let root = unique_root("parse");
@@ -3083,7 +3208,8 @@ pub(crate) mod tests {
write_def(&dir, "good", "");
let reg = SubagentRegistry::load(&root);
assert!(reg.get("good").is_some());
- assert_eq!(reg.list().len(), 1);
+ let saved = reg.list().into_iter().filter(|d| d.scope == SubagentScope::Project);
+ assert_eq!(saved.count(), 1);
let _ = std::fs::remove_dir_all(&root);
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 9ff1b771a..375f6900b 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -31289,9 +31289,11 @@ mod tests {
let picker = app.picker.as_ref().expect("subagents screen open");
assert_eq!(picker.kind, PickerKind::SubagentModels);
let labels: Vec<_> = picker.items.iter().map(|i| i.value.as_str()).collect();
- assert_eq!(labels, ["explorer", "reviewer"]);
+ // The saved explorer and reviewer shadow the built-ins of the same
+ // name; the built-in researcher is listed beside them.
+ assert_eq!(labels, ["explorer", "researcher", "reviewer"]);
assert_eq!(picker.items[0].hint.as_deref(), Some("big"));
- assert_eq!(picker.items[1].hint.as_deref(), Some("inherit"));
+ assert_eq!(picker.items[2].hint.as_deref(), Some("inherit"));
// Enter on explorer: the model picker, aimed at it, offering roles.
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;