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.

fix(agent): subagents inherit every tool and dispatch by predefined agent (#9245)

Akarshan Biswas3d9529df281e
diff --git a/docs/src/pages/docs/agent/console.mdx b/docs/src/pages/docs/agent/console.mdx
index 4438b12f5..031836853 100644
--- a/docs/src/pages/docs/agent/console.mdx
+++ b/docs/src/pages/docs/agent/console.mdx
@@ -117,12 +117,12 @@ monitor is up), and the input row says what the turn is waiting on, with each it
```
• Waiting for 2 agents · 1 monitor (Esc to stop, type to steer)
- └ kv-review
- └ perf-scan
+ └ review
+ └ explore
└ mon-1 build
```
-A single subagent is named on the row itself (`• Waiting for kv-review`). At most three items are
+A single subagent is named on the row itself (`• Waiting for review`). At most three items are
listed, the last ending in `…` when there are more. The row does not animate, since nothing is being
generated, and it shows no elapsed time: that stays in the header. The footer reads `Esc stop`:
<kbd>Esc</kbd> stops the background work and ends the turn. Anything you type steers the agent.
diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdx
index 74e7930d2..d2f790691 100644
--- a/docs/src/pages/docs/agent/subagents.mdx
+++ b/docs/src/pages/docs/agent/subagents.mdx
@@ -57,7 +57,7 @@ Context share is the one to watch: an agent climbing toward 100% is about to run
| Tool | Purpose |
| --- | --- |
| `dispatch_subagent` | Start one or more subagents and return immediately, listing each one's name, `run_id` and answer file |
-| `message_subagent` | Send a running subagent a correction or extra context, by the name it was dispatched with |
+| `message_subagent` | Send a running subagent a correction or extra context, by its worker name |
| `stop_subagent` | Stop one running subagent by name; its work in progress is discarded |
| `create_subagent` | Save a reusable subagent definition |
| `list_subagents` | List the subagents available here |
@@ -77,7 +77,8 @@ Several messages are delivered together, in order.
- A subagent that already finished is reported as such: dispatch a follow-up instead.
- A message is only text. It cannot widen the subagent's tools, answer a permission prompt, or change
its sandbox or model.
-- If one name was dispatched more than once, the newest still-running subagent is the one addressed.
+- Workers are named after their agent, numbered on repeat (`explore`, `explore-2`), and a name is
+ never handed out twice in a session, so each name addresses one worker.
`stop_subagent` ends one subagent without touching the others. Esc still stops all of them along
with the turn.
@@ -101,8 +102,8 @@ status.
row with the same arguments it turns into `⚠ looping ×4`, since that usually means it is stuck.
In the conversation, a dispatch is one row naming every subagent with each brief under it
-(`• Dispatched kv-review, docs-writer`), and each subagent that ends leaves a row such as
-`• Finished kv-review · 3 tools` with its status under it.
+(`• Dispatched explore, general`), and each subagent that ends leaves a row such as
+`• Finished explore · 3 tools` with its status under it.
## Watching a subagent with `/agents`
@@ -162,28 +163,36 @@ costs you only its final answer.
## Built-in subagents
-Jan ships four subagents, ready to dispatch with no setup:
+Jan ships five subagents, ready to dispatch with no setup:
-| Name | Model | Tools | What it does |
-| --- | --- | --- | --- |
-| `explore` | `smol` | `read`, `ls`, `find`, `grep` | Codebase exploration: finds where things are and reports `path:line` evidence. Read-only by construction: it has no shell and no write tools |
-| `research` | `smol` | `web_search`, `web_fetch`, `read` | Answers a question from current web sources, with citations |
-| `review` | `inherit` | `read`, `shell` | Reviews a change for correctness, risk and missing tests, and reports instead of editing. It keeps the shell for `git` and the project's checks |
-| `debug` | `inherit` | all | Reproduces a failure, finds the root cause, makes the smallest fix and verifies it |
+| Name | Model | What it does |
+| --- | --- | --- |
+| `explore` | `smol` | Codebase exploration: finds where things are and reports `path:line` evidence. Told to only read |
+| `research` | `smol` | Answers a question from current web sources, with citations |
+| `review` | `inherit` | Reviews a change for correctness, risk and missing tests, and reports instead of editing |
+| `debug` | `inherit` | Reproduces a failure, finds the root cause, makes the smallest fix and verifies it |
+| `general` | `inherit` | Any task no other agent fits |
-The main agent picks one by setting `agent` on a dispatch entry; `name` stays the worker's own
-unique label, so one dispatch can run several workers on the same agent:
+Every built-in has the session's full toolset; its role is its prompt and model. `explore` is
+read-only by instruction, not by construction: on the cheap `smol` model under an auto-approving
+policy it could still write or run commands. To hold it to reading, give it a definition of your own
+(see below) with `allowed_tools = ["read", "ls", "find", "grep"]`.
+
+Each dispatch entry names an `agent`, one of the predefined agents, and the task. Workers are named
+after their agent, numbered when one agent runs more than once (`explore`, `explore-2`); the
+dispatch result lists each name, which is what `message_subagent`, `stop_subagent` and the answer
+file `blackboard/<name>.md` use:
```json
{ "subagents": [
- { "name": "explore-api", "agent": "explore", "task": "Where is request auth checked?" },
- { "name": "explore-db", "agent": "explore", "task": "Which tables does the migration touch?" }
+ { "agent": "explore", "task": "Where is request auth checked?" },
+ { "agent": "explore", "task": "Which tables does the migration touch?" }
] }
```
-It sees each agent with its model in the `dispatch_subagent` description, so it can send lookups to
-`explore` and keep your main model for the work that needs it. A worker without `agent` is a one-off,
-whatever it is named: a worker called `research` does not pick up the built-in.
+The main agent sees each agent with its model and purpose in its system prompt, so it can send
+lookups to `explore` and keep your main model for the work that needs it. An `agent` that is not one
+of the predefined agents is refused, with the valid ones listed.
A saved subagent with the same name replaces a built-in one (see below), and the model of any of them
can be changed per project.
@@ -260,21 +269,16 @@ and never edits files.
That writes to the project scope by default, so it applies only in this project. Ask for the user
scope to use it everywhere.
-Once saved, it is dispatched with `agent` set to its name (or, as before, by a worker `name` equal to
-it) and picks up its stored prompt, permissions and model.
-
-## One-off subagents
-
-A subagent doesn't need a saved definition. The agent can invent one for a single task by supplying
-a name and a system prompt together in the same call. Useful for a fan-out where each worker differs
-only slightly.
+Once saved, it is dispatched with `agent` set to its name and picks up its stored prompt,
+permissions and model. Names are at most 64 characters of letters, digits, `-` and `_`.
## Tool permissions
-A subagent's tools are narrowed, never widened:
+A subagent gets the session's full toolset unless something narrows it, and it is never widened:
-- For a **saved** subagent, the allowlist further restricts its own stored allowlist.
-- For a **one-off**, the allowlist is its toolset.
+- A definition's own `allowed_tools` restricts every dispatch of it.
+- A dispatch entry's `allowed_tools` restricts that one worker further. Its values are limited to
+ the tools the session can actually hand a subagent.
Either way it can only ever reach a subset of what the parent could reach, so delegation cannot be
used to escape your project's [tool policy](/docs/agent/permissions#project-policy).
diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rs
index 99b48e97a..c77b935b2 100644
--- a/src-tauri/jan-cli/tests/agent_rpc.rs
+++ b/src-tauri/jan-cli/tests/agent_rpc.rs
@@ -1392,7 +1392,7 @@ fn a_host_only_session_delegates_to_a_child_held_to_its_host_tools() {
let home = scratch.join("home");
let dispatch = tool_call_reply(
"dispatch_subagent",
- serde_json::json!({"subagents":[{"name":"mover","task":"move the arm to bin","allowed_tools":["robot_arm_move"]}]}),
+ serde_json::json!({"subagents":[{"agent":"general","task":"move the arm to bin","allowed_tools":["robot_arm_move"]}]}),
);
let (url, seen) = routed_provider(move |_, body| {
let answered = body["messages"]
@@ -1435,7 +1435,7 @@ fn a_host_only_session_delegates_to_a_child_held_to_its_host_tools() {
let event = &request["params"]["event"];
assert_eq!(event["tool_name"], "robot_arm_move", "{request}");
assert!(
- event["run_id"].as_str().is_some_and(|id| id.starts_with("sub-mover")),
+ event["run_id"].as_str().is_some_and(|id| id.starts_with("sub-general")),
"the call is attributed to the child: {request}"
);
let request_id = event["request_id"].as_str().unwrap().to_owned();
@@ -1474,7 +1474,7 @@ fn a_child_dispatched_without_an_allowlist_inherits_the_host_only_set() {
let home = scratch.join("home");
let dispatch = tool_call_reply(
"dispatch_subagent",
- serde_json::json!({"subagents":[{"name":"mover","task":"say hi"}]}),
+ serde_json::json!({"subagents":[{"agent":"general","task":"say hi"}]}),
);
let (url, seen) = routed_provider(move |_, body| {
let answered = body["messages"]
@@ -1653,7 +1653,7 @@ fn a_child_keeps_the_parents_tool_over_a_host_tool_of_the_same_name() {
.unwrap();
let dispatch = tool_call_reply(
"dispatch_subagent",
- serde_json::json!({"subagents":[{"name":"mover","task":"say hi",
+ serde_json::json!({"subagents":[{"agent":"general","task":"say hi",
"allowed_tools":["plugin__p__echo","robot_arm_move"]}]}),
);
let (url, seen) = routed_provider(move |_, body| {
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
index 688e71280..e8b7f2d08 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/spill.rs
@@ -136,6 +136,16 @@ pub fn reserve_blackboard_result(scratch: &Path, name: &str) -> Option<PathBuf>
}
}
+/// Whether `<scratch>/blackboard/<name>.md` already holds an entry, under the
+/// same stem [`reserve_blackboard_result`] would write to. A dispatch asks this
+/// before reusing a worker name, since reserving that name truncates the file.
+pub fn blackboard_result_exists(scratch: &Path, name: &str) -> bool {
+ scratch
+ .join(BLACKBOARD_DIR)
+ .join(format!("{}.md", sanitize_stem(name)))
+ .exists()
+}
+
/// Read `<scratch>/blackboard/<name>.md` for injection into the next phase,
/// fail-closed against the same redirection the write path guards: the shell
/// shares this scratch and can `rm` a finished answer and `ln -s` a host file in
diff --git a/src-tauri/src/core/agent/builtin_subagents/explore.toml b/src-tauri/src/core/agent/builtin_subagents/explore.toml
index c7fa67a21..49c150bae 100644
--- a/src-tauri/src/core/agent/builtin_subagents/explore.toml
+++ b/src-tauri/src/core/agent/builtin_subagents/explore.toml
@@ -1,11 +1,10 @@
name = "explore"
-description = "Read-only codebase explorer on the cheap smol model: finds where things are and how they connect, and reports file paths and facts. Has no shell and no write tools."
+description = "Codebase explorer on the cheap smol model: finds where things are and how they connect, and reports file paths and facts. Told never to change anything, but holds the full toolset like every agent."
model = "smol"
-allowed_tools = ["read", "ls", "find", "grep"]
system_prompt = """
-You are "explore", a read-only codebase explorer. You are given one question about the code in the current project. Answer it by reading. You have no shell and no tool that can change anything.
+You are "explore", a read-only codebase explorer. You are given one question about the code in the current project. Answer it by reading. Never change anything: no file writes or edits, and only read-only shell commands.
-- Use `grep` to search file contents, `find` to locate files by name, `ls` to list a directory, and `read` to open the files that matter.
+- Search file contents and locate files with read-only shell commands (`rg`/`grep`, `find`, `ls`), and use `read` to open the files that matter.
- 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.
diff --git a/src-tauri/src/core/agent/builtin_subagents/general.toml b/src-tauri/src/core/agent/builtin_subagents/general.toml
new file mode 100644
index 000000000..41fcdfe6d
--- /dev/null
+++ b/src-tauri/src/core/agent/builtin_subagents/general.toml
@@ -0,0 +1,8 @@
+name = "general"
+description = "General-purpose agent on the session's model for any task no other agent fits: does exactly the task it is given with the full toolset and reports back."
+model = "inherit"
+system_prompt = """
+You are "general", a focused subagent handling one task as part of a larger plan. Do exactly the task you are given, using your tools as needed, and do not wait for clarification -- you cannot receive any.
+
+When you finish, end with a concise, self-contained report of what you found or did: it is handed verbatim to the agent that dispatched you and to the agents in the next phase, so include the facts, paths, and decisions they will need.
+"""
diff --git a/src-tauri/src/core/agent/builtin_subagents/research.toml b/src-tauri/src/core/agent/builtin_subagents/research.toml
index acdca92f2..4ab39e4fe 100644
--- a/src-tauri/src/core/agent/builtin_subagents/research.toml
+++ b/src-tauri/src/core/agent/builtin_subagents/research.toml
@@ -1,7 +1,6 @@
name = "research"
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 "research". You are given one question that needs current or external information: library and API documentation, versions, error messages, standards, or anything outside the project.
diff --git a/src-tauri/src/core/agent/builtin_subagents/review.toml b/src-tauri/src/core/agent/builtin_subagents/review.toml
index 77f3e6318..3e4ce8724 100644
--- a/src-tauri/src/core/agent/builtin_subagents/review.toml
+++ b/src-tauri/src/core/agent/builtin_subagents/review.toml
@@ -1,7 +1,6 @@
name = "review"
-description = "Code reviewer on the session's model: reviews a change or a set of files for correctness, risk and missing tests, and reports instead of editing. Has the shell (for git and the project's checks) but no write tools."
+description = "Code reviewer on the session's model: reviews a change or a set of files for correctness, risk and missing tests, and reports instead of editing."
model = "inherit"
-allowed_tools = ["read", "shell"]
system_prompt = """
You are "review", 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.
diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rs
index e195d27b4..952f4ee1b 100644
--- a/src-tauri/src/core/agent/context.rs
+++ b/src-tauri/src/core/agent/context.rs
@@ -241,12 +241,26 @@ const SUBAGENT_GUIDE: &str = "# Subagents\n\nYour own context window is limited.
that could pull in a lot of file content or tool output (broad codebase search, reading files, many \
multi-step research), prefer `dispatch_subagent` over doing it inline: the subagent absorbs that context \
in its own window and returns only the distilled answer. For read-only codebase questions set `agent: \"explore\"` \
-and for web lookups `agent: \"research\"`: both run on a cheaper model. Dispatch independent subagents in parallel when \
+and for web lookups `agent: \"research\"`: both run on a cheaper model; use `agent: \"general\"` when no \
+other agent fits. Dispatch independent subagents in parallel when \
their work doesn't depend on each other; each returns in the background and a note carries its answer when \
it finishes. Once you delegate a task it belongs to that subagent -- do not do the same work yourself; \
spend the wait on other steps, and only `await_subagent` when nothing else is left to do. Do inline work \
yourself for small, targeted tasks where delegating would cost more than it saves.";
+/// The `# Subagents` block: the guide, then the predefined agents the
+/// `dispatch_subagent` `agent` enum accepts, each with its model and purpose.
+/// Read from the registry when the prompt is composed, so it is fixed for the
+/// session like the rest of the prefix; a definition added mid-session shows up
+/// in the next session's prompt (the enum, rebuilt per run, already takes it).
+fn subagent_guide(project_root: &Path) -> String {
+ let registry = crate::core::agent::subagent::SubagentRegistry::load(project_root);
+ match crate::core::agent::subagent::agent_catalog(&registry) {
+ Some(catalog) => format!("{SUBAGENT_GUIDE}\n\nPredefined agents (`agent` field):\n{catalog}"),
+ None => SUBAGENT_GUIDE.to_string(),
+ }
+}
+
/// System-prompt addendum for a `/goal` run with no staged plan: an unattended
/// loop that keeps firing turns until a condition is met needs the phased list
/// up front, both to work through and for the user to read on return. Paired
@@ -438,7 +452,7 @@ fn render(composer: Composer, inputs: &CompositionInputs) -> Option<String> {
Some(runtime_environment_block(inputs.project_root, inputs.scratch))
}
Composer::SessionStart => inputs.session_start.map(SessionStart::block),
- Composer::SubagentGuide => inputs.subagents_enabled.then(|| SUBAGENT_GUIDE.to_string()),
+ Composer::SubagentGuide => inputs.subagents_enabled.then(|| subagent_guide(inputs.project_root)),
Composer::SkillGuide => Some(DEFAULT_SKILL_GUIDE.trim().to_string()),
Composer::WebToolsGuide => Some(WEB_TOOLS_GUIDE.to_string()),
Composer::ProjectContext => load_context_files(inputs.project_root),
@@ -941,6 +955,9 @@ mod tests {
let with = default_prompt(None, &root, None, true).expect("prompt");
assert!(with.contains("belongs to that subagent"));
assert!(with.contains("agent: \"explore\""), "points cheap work at explore");
+ // The names the `agent` enum accepts are spelled out with their purpose.
+ assert!(with.contains("Predefined agents (`agent` field):"), "{with}");
+ assert!(with.contains("- `research` (model: smol): "), "{with}");
assert!(with.contains("do not do the same work yourself"));
assert!(!with.contains("keep working rather than waiting"));
let _ = std::fs::remove_dir_all(&root);
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index ba8cb1d99..6e57e81db 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1081,9 +1081,10 @@ fn format_dispatched_plan(d: &crate::core::agent::subagent::DispatchedPlan) -> S
)
};
format!(
- "{head}\n{where_answers} Steer one by name with message_subagent, or stop it with \
+ "{head}\n{}\n{where_answers} Steer one by name with message_subagent, or stop it with \
stop_subagent. These tasks are the subagents' now -- do not do them yourself; you'll be pinged as \
- each finishes."
+ each finishes.",
+ crate::core::agent::subagent::worker_names_line(&d.names)
)
}
@@ -1556,7 +1557,7 @@ impl CompositeToolInvoker {
async fn handle_subagent_tool(&self, name: &str, args: &serde_json::Value) -> String {
use crate::core::agent::subagent::{
await_subagent, format_subagent_list, parse_await_args, parse_create_args,
- parse_dispatch_plan, spawn_dispatch_plan, subagent_dir_for, SubagentRegistry,
+ spawn_dispatch_plan, subagent_dir_for, SubagentRegistry,
SubagentScope,
};
use tauri_plugin_agent_tools::tools::spill::compose_subagent_result;
@@ -1569,10 +1570,13 @@ impl CompositeToolInvoker {
format_subagent_list(&registry)
}
"dispatch_subagent" => {
- let plan = match parse_dispatch_plan(args) {
+ let plan = match ctx.bg.plan_dispatch(args, self.subagent_scratch()) {
Ok(p) => p,
Err(e) => return format!("ERROR: {e}"),
};
+ // Rejected before any child started (an unknown agent, a tool
+ // the parent denies), the names go back for the retry.
+ let reserved = plan.names.clone();
match spawn_dispatch_plan(
&ctx.bg,
ctx.bg_generation,
@@ -1593,7 +1597,10 @@ impl CompositeToolInvoker {
self.subagent_scratch(),
) {
Ok(d) => format_dispatched_plan(&d),
- Err(e) => format!("ERROR: {e}"),
+ Err(e) => {
+ ctx.bg.release_names(&reserved);
+ format!("ERROR: {e}")
+ }
}
}
"message_subagent" => {
@@ -3047,6 +3054,12 @@ fn advertise_local_tools(
openai_tools.push(tool.schema());
}
}
+ // Last, so the names a child may be given are drawn from the whole array.
+ crate::core::agent::subagent::constrain_tool_names(
+ openai_tools,
+ permissions,
+ allowed_names.is_some(),
+ );
}
/// The last completion of a run stopped by its money ceiling, rewritten into a
@@ -11624,6 +11637,7 @@ mod tests {
},
],
blackboard_dir: Some("blackboard".to_string()),
+ names: vec!["explorer-a".to_string(), "explorer-b".to_string()],
});
assert!(out.contains("sub-explorer-a-1"), "{out}");
assert!(out.contains("sub-explorer-b-2"), "{out}");
@@ -11644,8 +11658,17 @@ mod tests {
run_id: "sub-researcher-1".to_string(),
}],
blackboard_dir: None,
+ names: vec!["researcher".to_string(), "writer".to_string()],
});
assert!(out.contains("sub-researcher-1"), "{out}");
+ // Every worker is named, the later phase's included, in listed order.
+ assert!(
+ out.contains(&crate::core::agent::subagent::worker_names_line(&[
+ "researcher".to_string(),
+ "writer".to_string(),
+ ])),
+ "{out}"
+ );
assert_eq!(out.matches("run_id:").count(), 1, "{out}");
assert!(out.contains("reported as they start"), "{out}");
}
@@ -11775,6 +11798,7 @@ mod tests {
run_id: "sub-w-1".to_string(),
}],
blackboard_dir: None,
+ names: vec!["w".to_string()],
});
assert!(out.contains("stop_subagent"), "{out}");
assert!(out.contains("by name"), "{out}");
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index e0ce1122c..285e75bb9 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -70,6 +70,7 @@ impl SubagentScope {
const BUILTIN_SUBAGENTS: &[&str] = &[
include_str!("builtin_subagents/debug.toml"),
include_str!("builtin_subagents/explore.toml"),
+ include_str!("builtin_subagents/general.toml"),
include_str!("builtin_subagents/research.toml"),
include_str!("builtin_subagents/review.toml"),
];
@@ -173,8 +174,15 @@ pub fn desktop_subagents_dir(jan_data_folder: &Path) -> PathBuf {
workspace::store_dir(&workspace::permanent_store(jan_data_folder), SUBAGENTS)
}
+/// Longest subagent name. Kept well under the blackboard stem's own 80-char
+/// cap so every numbered worker name (`<agent>-<n>`) maps to a distinct
+/// `blackboard/<name>.md`: past the cap they would all truncate to one stem,
+/// and numbering could never find a free name.
+const MAX_AGENT_NAME_LEN: usize = 64;
+
/// A subagent name is used to build a filename, so it must be a single path
-/// component of `[A-Za-z0-9_-]`. Rejects empty, separators, and dots.
+/// component of `[A-Za-z0-9_-]`, at most [`MAX_AGENT_NAME_LEN`] long. Rejects
+/// empty, separators, and dots.
fn validate_name(name: &str) -> Result<(), SubagentError> {
if name.is_empty()
|| !name
@@ -185,6 +193,11 @@ fn validate_name(name: &str) -> Result<(), SubagentError> {
"invalid subagent name '{name}': use only letters, digits, '-' and '_'"
)));
}
+ if name.len() > MAX_AGENT_NAME_LEN {
+ return Err(SubagentError::PermissionDenied(format!(
+ "subagent name '{name}' is too long (max {MAX_AGENT_NAME_LEN} characters)"
+ )));
+ }
Ok(())
}
@@ -248,9 +261,17 @@ impl SubagentRegistry {
self.defs.iter().collect()
}
- /// Each distinct name, sorted: the values `agent` may take.
+ /// Each distinct name, sorted: the values `agent` may take. A hand-written
+ /// definition file whose name a dispatch would refuse (too long, a bad
+ /// character) is left out, so the model is never offered an agent it
+ /// cannot run.
fn dispatchable_names(&self) -> Vec<&str> {
- let mut names: Vec<&str> = self.defs.iter().map(|d| d.name.as_str()).collect();
+ let mut names: Vec<&str> = self
+ .defs
+ .iter()
+ .map(|d| d.name.as_str())
+ .filter(|name| validate_name(name).is_ok())
+ .collect();
names.sort_unstable();
names.dedup();
names
@@ -728,21 +749,19 @@ fn qualify_host_names(
tools
}
-/// One subagent within a phased dispatch. `agent` names the definition to run
-/// (any scope, built-ins included); without it, a `name` matching a saved user,
-/// project or plugin definition uses that one, as before. Either way the
-/// definition's role and tools are used, and `allowed_tools` further narrows
-/// them. Otherwise the subagent runs as a focused general-purpose agent defined
-/// by its `description` (the task) alone. `name` is the worker's own identity
-/// and the blackboard filename its answer is written to
-/// (`blackboard/<name>.md`), so it stays unique even when several workers run
-/// one definition.
+/// One subagent within a phased dispatch. `agent` names the predefined
+/// definition to run (any scope, built-ins included); its role, prompt and
+/// model are used, and `allowed_tools` narrows its tools. `name` is not chosen
+/// by the model: it is the agent's name, numbered for each repeat within one
+/// plan (`explore`, `explore-2`, see [`number_workers`]), and is the worker's
+/// identity -- its run id, its blackboard file (`blackboard/<name>.md`), the
+/// name `message_subagent`/`stop_subagent` address and its transcript rows.
#[derive(Debug, Clone)]
pub struct SubagentRequest {
pub name: String,
pub description: String,
pub allowed_tools: Option<Vec<String>>,
- pub agent: Option<String>,
+ pub agent: String,
}
/// A group of subagents that run concurrently. The next phase starts only once
@@ -760,6 +779,10 @@ pub struct Phase {
#[derive(Debug, Clone)]
pub struct DispatchPlan {
pub phases: Vec<Phase>,
+ /// Every worker's name in the order the call listed them, which the
+ /// phases reorder. The dispatch result reports them in this order so the
+ /// TUI's dispatch row can label each of the call's entries.
+ pub names: Vec<String>,
}
/// The resolved plan for a dispatch: the winning definition plus the effective
@@ -783,74 +806,28 @@ fn resolve_dispatch(
qualify: impl Fn(Vec<String>) -> Vec<String>,
) -> Result<ResolvedDispatch, SubagentError> {
let requested = req.allowed_tools.clone().map(&qualify);
- // A built-in is reached only through `agent`: matching it by the worker's
- // `name` would hand an ad-hoc worker that happens to be called `research`
- // a prompt and allowlist it never asked for. Saved definitions keep the
- // match by name, which is how they have always been dispatched.
- let definition = match req.agent.as_deref() {
- Some(agent) => Some(registry.get(agent).cloned().ok_or_else(|| {
- SubagentError::Upstream(format!(
- "no subagent definition named '{agent}' for agent; available: {}. Omit \
- agent to run a one-off general-purpose subagent.",
- registry.dispatchable_names().join(", ")
- ))
- })?),
- None => registry
- .get(&req.name)
- .filter(|d| d.scope != SubagentScope::Builtin)
- .cloned(),
- };
- match definition {
- Some(mut definition) => {
- // The worker keeps its own identity: its run id, blackboard file
- // and transcript rows name the instance, not the definition.
- definition.name = req.name.clone();
- definition.allowed_tools = definition.allowed_tools.map(&qualify);
- // Registered definition: the call-site allowlist further narrows it.
- let allowed_tools = intersect_allowed_tools(
- definition.allowed_tools.as_deref(),
- requested.as_deref(),
- parent,
- )?;
- Ok(ResolvedDispatch {
- definition,
- allowed_tools,
- })
- }
- None => {
- // No saved definition: a focused general-purpose subagent defined by
- // its task. The call-site allowlist IS its toolset; only the parent's
- // deny-list narrows it further. The list came from the model's own
- // call, so a stale entry is reported as that, not as a definition.
- refuse_renamed_shell(requested.as_deref(), "allowed_tools")?;
- let definition = SubagentDefinition {
- name: req.name.clone(),
- description: req.description.clone(),
- system_prompt: ephemeral_subagent_prompt(&req.name),
- allowed_tools: requested,
- model: None,
- scope: SubagentScope::Project,
- };
- let allowed_tools =
- intersect_allowed_tools(definition.allowed_tools.as_deref(), None, parent)?;
- Ok(ResolvedDispatch {
- definition,
- allowed_tools,
- })
- }
- }
-}
-
-/// The system prompt for a subagent dispatched without a saved definition: a
-/// focused generalist whose closing report becomes the next phase's input.
-fn ephemeral_subagent_prompt(name: &str) -> String {
- format!(
- "You are \"{name}\", a focused subagent handling one task as part of a larger plan. \
- Do exactly the task you are given, using your tools as needed, and do not wait for \
- clarification -- you cannot receive any. When you finish, end with a concise, \
- self-contained report of what you found or did: it is handed verbatim to the agents in \
- the next phase, so include the facts, paths, and decisions they will need."
- )
+ let mut definition = registry.get(&req.agent).cloned().ok_or_else(|| {
+ SubagentError::Upstream(format!(
+ "no subagent named '{}'; agent must be one of: {}. Use `general` for a task \
+ no other agent fits.",
+ req.agent,
+ registry.dispatchable_names().join(", ")
+ ))
+ })?;
+ // The worker keeps its own identity: its run id, blackboard file and
+ // transcript rows name the instance, not the definition.
+ definition.name = req.name.clone();
+ definition.allowed_tools = definition.allowed_tools.map(&qualify);
+ // The call-site allowlist narrows the definition's own.
+ let allowed_tools = intersect_allowed_tools(
+ definition.allowed_tools.as_deref(),
+ requested.as_deref(),
+ parent,
+ )?;
+ Ok(ResolvedDispatch {
+ definition,
+ allowed_tools,
+ })
}
/// Child stream events are folded into the parent's own stream, except the
@@ -1105,6 +1082,11 @@ pub(crate) struct Collected {
/// was never collected so a finished/cancelled parent leaves no orphan runs.
pub(crate) struct BackgroundSubagents {
inner: std::sync::Mutex<std::collections::HashMap<String, BackgroundEntry>>,
+ /// Every worker name a dispatch has handed out in this registry's life.
+ /// A later-phase worker is not in `inner` until its phase starts, so
+ /// without this a second dispatch made meanwhile could be given the same
+ /// name and share its blackboard file and handle.
+ reserved_names: std::sync::Mutex<std::collections::HashSet<String>>,
/// Admission gate: `max_parallel_subagents` permits, one per child that is
/// *running* (as opposed to merely dispatched). A dispatch beyond the cap
/// parks on `acquire_owned` in FIFO order inside its spawned task, so the
@@ -1162,12 +1144,50 @@ impl Default for BackgroundSubagents {
}
impl BackgroundSubagents {
+ /// Parse a dispatch and hold every name it hands out, as one step under
+ /// the reservation lock so two dispatches cannot be given the same name.
+ ///
+ /// A name is taken when this registry ever handed it out -- including to
+ /// a later-phase worker that has not started yet -- or when the scratch
+ /// holds an answer under it: a run that owns its own registry forgets its
+ /// workers when it ends, but their answers stay on the session's
+ /// blackboard, and reusing a name would truncate one in place.
+ pub(crate) fn plan_dispatch(
+ &self,
+ args: &serde_json::Value,
+ scratch: Option<&Path>,
+ ) -> Result<DispatchPlan, SubagentError> {
+ let mut reserved = self.reserved_names.lock().unwrap();
+ let plan = parse_dispatch_plan(args, |name| {
+ reserved.contains(name)
+ || scratch.is_some_and(|s| {
+ tauri_plugin_agent_tools::tools::spill::blackboard_result_exists(s, name)
+ })
+ })?;
+ reserved.extend(
+ plan.phases
+ .iter()
+ .flat_map(|p| p.subagents.iter().map(|s| s.name.clone())),
+ );
+ Ok(plan)
+ }
+
+ /// Hand back the names a dispatch reserved but never started, so a
+ /// corrected retry is named `explore` again rather than `explore-2`.
+ pub(crate) fn release_names(&self, names: &[String]) {
+ let mut reserved = self.reserved_names.lock().unwrap();
+ for name in names {
+ reserved.remove(name);
+ }
+ }
+
/// Create a registry admitting at most `cap` concurrently-running children.
/// Clamped to at least 1: a cap of 0 would make every dispatch queue
/// forever with nothing ever releasing a permit.
pub(crate) fn new(cap: u32) -> Self {
Self {
inner: std::sync::Mutex::new(std::collections::HashMap::new()),
+ reserved_names: std::sync::Mutex::new(std::collections::HashSet::new()),
semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(cap.max(1) as usize)),
queued: std::sync::atomic::AtomicUsize::new(0),
notices: std::sync::Mutex::new(Vec::new()),
@@ -2171,6 +2191,31 @@ pub(crate) struct DispatchedPlan {
/// The blackboard directory in the model's spelling, or `None` when the run
/// is unconfined (no scratch: answers ride the completion pings inline).
pub(crate) blackboard_dir: Option<String>,
+ /// Every worker's name, in the order the call listed them (see
+ /// [`DispatchPlan::names`]).
+ pub(crate) names: Vec<String>,
+}
+
+/// Lead of the dispatch result line naming every worker in the call's order.
+const WORKER_NAMES_LEAD: &str = "Worker names, in the order listed: ";
+
+/// The dispatch result line naming every worker, in the call's order.
+pub(crate) fn worker_names_line(names: &[String]) -> String {
+ format!("{WORKER_NAMES_LEAD}{}.", names.join(", "))
+}
+
+/// The worker names a dispatch result reports (see [`worker_names_line`]), or
+/// `None` for a result that carries none: a failed dispatch, or one saved
+/// before the names were reported. Only the TUI's dispatch row reads it back.
+#[cfg(feature = "cli")]
+pub(crate) fn worker_names_in(result: &str) -> Option<Vec<String>> {
+ let line = result.lines().find_map(|l| l.strip_prefix(WORKER_NAMES_LEAD))?;
+ Some(
+ line.trim_end_matches('.')
+ .split(", ")
+ .map(str::to_string)
+ .collect(),
+ )
}
/// One started child as the dispatch reports it: the name the parent chose and
@@ -2294,6 +2339,7 @@ pub(crate) fn spawn_dispatch_plan(
let phase_count = plan.phases.len();
let total_subagents = plan.phases.iter().map(|p| p.subagents.len()).sum();
+ let names = plan.names.clone();
let blackboard_dir = scratch.map(|s| scratch_display_path(Some(s), &blackboard_dir_path(s)));
let multi = phase_count > 1;
@@ -2368,6 +2414,7 @@ pub(crate) fn spawn_dispatch_plan(
total_subagents,
first_phase: first_children,
blackboard_dir,
+ names,
})
}
@@ -2695,7 +2742,7 @@ pub fn stop_subagent_tool_schema() -> serde_json::Value {
"parameters": {
"type": "object",
"properties": {
- "name": { "type": "string", "description": "The name you gave this subagent in dispatch_subagent. If the name was dispatched more than once, the newest still-running one is stopped." }
+ "name": { "type": "string", "description": "The subagent's name as dispatch_subagent reported it: its agent, numbered on repeat (e.g. `explore`, `explore-2`). If several runs answer to it, the newest still-running one is stopped." }
},
"required": ["name"]
}
@@ -2721,7 +2768,7 @@ pub fn message_subagent_tool_schema() -> serde_json::Value {
"parameters": {
"type": "object",
"properties": {
- "name": { "type": "string", "description": "The name you gave this subagent in dispatch_subagent. If the name was dispatched more than once, the newest still-running one is addressed." },
+ "name": { "type": "string", "description": "The subagent's name as dispatch_subagent reported it: its agent, numbered on repeat (e.g. `explore`, `explore-2`). If several runs answer to it, the newest still-running one is addressed." },
"message": { "type": "string", "description": "What to tell the subagent. Be specific: it sees your message, not this conversation." }
},
"required": ["name", "message"]
@@ -2750,34 +2797,114 @@ pub fn format_subagent_list(registry: &SubagentRegistry) -> String {
lines.join("\n")
}
-/// OpenAI tool schemas for the subagent tools. The dispatch tool's description
-/// lists the currently-resolvable subagent names so the model can pick one
-/// without a separate discovery call.
+/// The agent catalog for the system prompt's `# Subagents` block: each
+/// dispatchable name with the model it runs on and what it is for, one per
+/// line. `None` when nothing is dispatchable. It lives in the cached prompt
+/// prefix rather than the tool description so the schema stays small, and is
+/// read from the same registry the `agent` enum is built from, so the two
+/// never disagree.
+pub fn agent_catalog(registry: &SubagentRegistry) -> Option<String> {
+ let lines: Vec<String> = registry
+ .dispatchable_names()
+ .into_iter()
+ .filter_map(|name| registry.get(name))
+ .map(|d| format!("- `{}` (model: {}): {}", d.name, d.model_label(), d.description))
+ .collect();
+ (!lines.is_empty()).then(|| lines.join("\n"))
+}
+
+/// Tools a child never gets whatever its allowlist says: it cannot dispatch
+/// (nesting is capped at one), and it has no `ask` client, todo list or
+/// monitor set of its own (see [`run_subagent`]).
+fn never_delegated(name: &str) -> bool {
+ is_subagent_tool(name)
+ || matches!(name, "ask" | "todo")
+ || name == tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME
+}
+
+/// Pin every `allowed_tools` array in the subagent schemas to the tools this
+/// run can actually hand a child, as a JSON-schema `enum`.
+///
+/// Left free-form, models filled the optional array with names that match
+/// nothing (`bash`, `search`, `read_file`), which silently narrowed the child
+/// to the forced skill tools. With the names fixed a strict provider cannot
+/// emit a stray one, and every other provider is at least shown the set.
+/// `offered` is the run's final tool array. The shell-free search tools are
+/// added because a child that names them is offered them even though the
+/// parent is not -- but only when nothing would take them away again: a deny
+/// rule drops them, and under a per-run allowlist (`ceiling`) a child gets
+/// only what the parent was offered, which `offered` already says. Applied
+/// after the whole array is built so MCP, plugin and host tools are included,
+/// and derived from per-run inputs alone so the array stays byte-identical
+/// across the run's turns.
+pub fn constrain_tool_names(
+ offered: &mut [serde_json::Value],
+ permissions: &ToolPermissions,
+ ceiling: bool,
+) {
+ let search = tauri_plugin_agent_tools::tools::schema::search_tool_schemas();
+ let search = search
+ .iter()
+ .filter_map(|t| t["function"]["name"].as_str())
+ .filter(|n| !ceiling && !permissions.is_denied(n));
+ let mut names: Vec<String> = offered
+ .iter()
+ .filter_map(|t| t["function"]["name"].as_str())
+ .chain(search)
+ .filter(|n| !never_delegated(n))
+ .map(str::to_string)
+ .collect();
+ names.sort_unstable();
+ names.dedup();
+ for tool in offered.iter_mut() {
+ let name = tool["function"]["name"].as_str().unwrap_or_default();
+ let properties = match name {
+ "dispatch_subagent" => {
+ &mut tool["function"]["parameters"]["properties"]["subagents"]["items"]
+ ["properties"]
+ }
+ "create_subagent" => &mut tool["function"]["parameters"]["properties"],
+ _ => continue,
+ };
+ let Some(properties) = properties.as_object_mut() else {
+ continue;
+ };
+ // Nothing to hand a child (a host-only session that declared no host
+ // tools): an empty `enum` is invalid JSON Schema that some providers
+ // reject, failing every request, so the field is dropped -- a child
+ // then simply inherits the (empty) set.
+ if names.is_empty() {
+ properties.remove("allowed_tools");
+ } else if let Some(items) = properties
+ .get_mut("allowed_tools")
+ .and_then(|field| field.get_mut("items"))
+ {
+ items["enum"] = serde_json::json!(names);
+ }
+ }
+}
+
+/// OpenAI tool schemas for the subagent tools. The dispatch tool's `agent`
+/// field is an `enum` of the dispatchable names; what each one is for is in
+/// the system prompt (see [`agent_catalog`]). The `allowed_tools` names are
+/// pinned later, once the run's whole tool array is known
+/// (see [`constrain_tool_names`]).
pub fn subagent_tool_schemas(
registry: &SubagentRegistry,
max_parallel: u32,
) -> Vec<serde_json::Value> {
use serde_json::json;
- // Each name with the model its winning definition dispatches on, so the
- // agent can send cheap work to a cheap agent without a list call.
- let available: Vec<String> = {
- registry
- .dispatchable_names()
- .into_iter()
- .filter_map(|name| registry.get(name))
- .map(|d| format!("{} ({})", d.name, d.model_label()))
- .collect()
- };
- let bg = format!(" Subagents run in the BACKGROUND, concurrently (up to {max_parallel} at once, from max_parallel_subagents in agent.toml; more are queued FIFO). You keep working and get a note the moment each finishes. Each subagent's final answer is written to blackboard/<name>.md in a shared scratch directory the whole plan can read from and write to. Steer a running child with message_subagent, or stop it with stop_subagent, by the name you gave it here.");
+ // Built-ins are always loaded, so the enum always holds at least `general`.
+ let agent_field = json!({
+ "type": "string",
+ "enum": registry.dispatchable_names(),
+ "description": "The predefined agent to run (see the Subagents section of your instructions for what each is for); use `general` when no other fits. The same agent may appear several times: repeats are named `<agent>-2`, `<agent>-3`, ... in the order listed, and that name is what message_subagent/stop_subagent take and the blackboard/<name>.md file its answer is written to."
+ });
+ let bg = format!(" Subagents run in the BACKGROUND, concurrently (up to {max_parallel} at once, from max_parallel_subagents in agent.toml; more are queued FIFO). You keep working and get a note the moment each finishes. Each subagent's final answer is written to blackboard/<name>.md in a shared scratch directory the whole plan can read from and write to. Steer a running child with message_subagent, or stop it with stop_subagent, by its name (reported when it starts).");
let phases_desc = " List all the subagents in one call. To PIPELINE them, give a subagent a `phase`: subagents sharing a phase run together, lower phases run first, and each later phase is handed the previous phase's results automatically. Omit `phase` for a plain fan-out (one stage, everyone at once); use it to stage work (e.g. phase 0 researches in parallel, phase 1 synthesizes).";
- let dispatch_desc = if available.is_empty() {
- format!("Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} No saved subagents yet; each runs as a focused general-purpose agent defined by its task.")
- } else {
- format!(
- "Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} Set `agent` to run one of these as a subagent, using its role, tools and model (several entries may run the same agent under different names); omit it for a focused general-purpose subagent. Available agents, each with the model it runs on: {}.",
- available.join(", ")
- )
- };
+ let dispatch_desc = format!(
+ "Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} Every subagent gets your full toolset unless its agent's definition or allowed_tools restricts it."
+ );
vec![
json!({
"type": "function",
@@ -2793,8 +2920,7 @@ pub fn subagent_tool_schemas(
"items": {
"type": "object",
"properties": {
- "name": { "type": "string", "description": "Short identity for this subagent, unique across the whole call: letters, digits, '-' and '_' only. It is also the blackboard file its answer is written to (blackboard/<name>.md)." },
- "agent": { "type": "string", "description": "Optional saved or built-in subagent to run as (one of the names listed in this tool's description); its role, tools and model are used. Several entries may share one agent under different names. Omit it for a focused general-purpose subagent defined by its task." },
+ "agent": agent_field,
"task": { "type": "string", "description": "The subagent's sole instruction. Include everything it needs; it does not see this conversation. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them." },
"phase": { "type": "integer", "minimum": 0, "description": "Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out." },
"allowed_tools": {
@@ -2803,7 +2929,7 @@ pub fn subagent_tool_schemas(
"description": "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs shell, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted."
}
},
- "required": ["name", "task"]
+ "required": ["agent", "task"]
}
}
},
@@ -2882,28 +3008,31 @@ fn optional_tool_list(args: &serde_json::Value) -> Option<Vec<String>> {
.filter(|list| !list.is_empty())
}
-/// Longest subagent name accepted in a plan. Kept under the blackboard stem's
-/// own 80-char cap so a validated name maps to `blackboard/<name>.md` verbatim
-/// (no truncation), which is what lets the next phase read it back by name.
-const MAX_SUBAGENT_NAME_LEN: usize = 64;
-
/// Parse a `dispatch_subagent` tool-call argument object into an ordered plan.
///
-/// The wire shape is a flat `subagents` array; each subagent's optional `phase`
-/// (a non-negative integer, default 0) groups it into a stage. Subagents that
-/// share a `phase` run together; lower phases run first. This one shape covers
-/// both a plain fan-out (omit `phase` everywhere -> a single stage) and a
-/// pipeline (raise `phase` for later work). Names are validated (charset +
-/// length) and required unique across the whole plan, since each is a blackboard
-/// filename and a panel identity.
-pub fn parse_dispatch_plan(args: &serde_json::Value) -> Result<DispatchPlan, SubagentError> {
+/// The wire shape is a flat `subagents` array of `{ agent, task, phase? }`.
+/// `agent` (required) is one of the predefined agents; each subagent's optional
+/// `phase` (a non-negative integer, default 0) groups it into a stage.
+/// Subagents that share a `phase` run together; lower phases run first. This
+/// one shape covers both a plain fan-out (omit `phase` everywhere -> a single
+/// stage) and a pipeline (raise `phase` for later work).
+///
+/// Each worker is named by [`number_workers`] in the order listed, skipping a
+/// name `taken` reports still held by an earlier worker of the session. The
+/// name is the worker's blackboard file and the handle
+/// `message_subagent`/`stop_subagent` take, so a repeat must neither overwrite
+/// an earlier worker's answer nor be confused with it.
+pub fn parse_dispatch_plan(
+ args: &serde_json::Value,
+ taken: impl Fn(&str) -> bool,
+) -> Result<DispatchPlan, SubagentError> {
let subs_val = args
.get("subagents")
.and_then(|v| v.as_array())
.ok_or_else(|| {
SubagentError::Upstream(
- "missing required argument 'subagents' (an array of subagents, each with a name \
- and task, plus an optional integer 'phase')"
+ "missing required argument 'subagents' (an array of subagents, each with an \
+ agent and task, plus an optional integer 'phase')"
.to_string(),
)
})?;
@@ -2912,26 +3041,21 @@ pub fn parse_dispatch_plan(args: &serde_json::Value) -> Result<DispatchPlan, Sub
"'subagents' must contain at least one subagent".to_string(),
));
}
- let mut seen = std::collections::HashSet::new();
// BTreeMap so phases come out in ascending `phase` order regardless of the
// order the model listed them, and sparse numbers (0, 5) just collapse to
// adjacent stages.
let mut by_phase: std::collections::BTreeMap<u32, Vec<SubagentRequest>> =
std::collections::BTreeMap::new();
- for sub in subs_val {
- let name = required_str(sub, "name")?;
- validate_name(&name)?;
- if name.len() > MAX_SUBAGENT_NAME_LEN {
- return Err(SubagentError::PermissionDenied(format!(
- "subagent name '{name}' is too long (max {MAX_SUBAGENT_NAME_LEN} characters)"
- )));
- }
- if !seen.insert(name.clone()) {
- return Err(SubagentError::Upstream(format!(
- "duplicate subagent name '{name}': names must be unique across the whole plan \
- (each is a blackboard filename)"
- )));
- }
+ let agents = subs_val
+ .iter()
+ .map(|sub| {
+ let agent = required_str(sub, "agent")?.trim().to_string();
+ validate_name(&agent)?;
+ Ok(agent)
+ })
+ .collect::<Result<Vec<_>, SubagentError>>()?;
+ let names = number_workers(agents.iter().map(String::as_str), taken);
+ for ((sub, agent), name) in subs_val.iter().zip(agents).zip(names.iter().cloned()) {
let description = required_str(sub, "task")?;
let phase = match sub.get("phase") {
None | Some(serde_json::Value::Null) => 0,
@@ -2945,12 +3069,6 @@ pub fn parse_dispatch_plan(args: &serde_json::Value) -> Result<DispatchPlan, Sub
))
})?,
};
- let agent = sub
- .get("agent")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|a| !a.is_empty())
- .map(String::from);
by_phase.entry(phase).or_default().push(SubagentRequest {
name,
description,
@@ -2962,7 +3080,32 @@ pub fn parse_dispatch_plan(args: &serde_json::Value) -> Result<DispatchPlan, Sub
.into_iter()
.map(|(number, subagents)| Phase { number, subagents })
.collect();
- Ok(DispatchPlan { phases })
+ Ok(DispatchPlan { phases, names })
+}
+
+/// Name each worker after its agent, in order: the agent's own name the first
+/// time (`explore`), then numbered (`explore-2`, `explore-3`), skipping any
+/// name `taken` reports in use. The one numbering rule, shared by dispatch and
+/// the TUI's dispatch row.
+pub(crate) fn number_workers<'a>(
+ agents: impl IntoIterator<Item = &'a str>,
+ taken: impl Fn(&str) -> bool,
+) -> Vec<String> {
+ let mut used = std::collections::HashSet::new();
+ agents
+ .into_iter()
+ .map(|agent| {
+ let name = (1..)
+ .map(|n| match n {
+ 1 => agent.to_string(),
+ n => format!("{agent}-{n}"),
+ })
+ .find(|name| !used.contains(name) && !taken(name))
+ .expect("an unbounded sequence has a free name");
+ used.insert(name.clone());
+ name
+ })
+ .collect()
}
/// Parse an `await_subagent` tool-call argument object, returning the run_id.
@@ -3164,7 +3307,7 @@ pub(crate) mod tests {
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, ["debug", "explore", "research", "review"]);
+ assert_eq!(names, ["debug", "explore", "general", "research", "review"]);
for def in &defs {
assert_eq!(def.scope, SubagentScope::Builtin);
assert!(!def.description.is_empty() && !def.system_prompt.is_empty());
@@ -3178,31 +3321,14 @@ pub(crate) mod tests {
);
}
}
- // `explore` is read-only by construction: no shell, no write tools,
- // so a cheap model under an auto-approving parent still cannot write.
- let explore = &defs[1];
- assert_eq!(explore.model.as_deref(), Some(SMOL_ROLE));
- let tools: Vec<&str> = explore
- .allowed_tools
- .as_deref()
- .unwrap()
- .iter()
- .map(String::as_str)
- .collect();
- assert_eq!(tools, ["read", "ls", "find", "grep"]);
- for tool in &tools {
- let cap = tauri_plugin_agent_tools::tools::lookup(tool).unwrap().capability;
- assert_eq!(cap, tauri_plugin_agent_tools::tools::Capability::Read, "{tool}");
+ // Every built-in inherits the dispatching run's full toolset: a role is
+ // its prompt and model, never a narrower tool set the model cannot see.
+ for def in &defs {
+ assert_eq!(def.allowed_tools, None, "{}", def.name);
}
- // `review` keeps the shell for `git diff`, so it must not claim to be
- // read-only; it is told not to edit instead.
- let review = &defs[3];
- assert!(!review.description.contains("read-only"), "{}", review.description);
- // `debug` has to edit and run tests, so it keeps the full toolset
- // (narrowed only by the parent's policy) on the session's model.
- let debug = &defs[0];
- assert_eq!(debug.model.as_deref(), Some(INHERIT_ROLE));
- assert_eq!(debug.allowed_tools, None);
+ assert_eq!(defs[1].model.as_deref(), Some(SMOL_ROLE));
+ assert_eq!(defs[0].model.as_deref(), Some(INHERIT_ROLE));
+ assert_eq!(defs[2].model.as_deref(), Some(INHERIT_ROLE));
assert_eq!(builtin_definitions(), defs, "deterministic");
}
@@ -3573,14 +3699,14 @@ pub(crate) mod tests {
assert!(intersect_allowed_tools(None, Some(&req), &p).is_err());
}
- /// An ad-hoc dispatch has no definition, so the refusal must name the
- /// call's own list -- the one the model wrote and can fix.
+ /// A stale entry in the call's own list is reported against that list --
+ /// the one the model wrote and can fix -- not the definition's.
#[test]
- fn an_ad_hoc_bash_entry_names_the_calls_own_list() {
- let reg = registry_with("other", None);
+ fn a_bash_entry_in_the_call_names_the_calls_own_list() {
+ let reg = registry_with("worker", None);
let Err(SubagentError::PermissionDenied(msg)) = resolve_dispatch_plain(
&reg,
- &req("adhoc", Some(vec!["bash".to_string()])),
+ &req("worker", Some(vec!["bash".to_string()])),
&ToolPermissions::allow_all(),
) else {
panic!("expected a permission error");
@@ -3612,12 +3738,27 @@ pub(crate) mod tests {
}
}
+ /// A `general` worker going by `name`, for tests about scheduling and
+ /// phases rather than which agent runs (all of them `cli`-only).
+ #[cfg(feature = "cli")]
+ fn worker(name: &str) -> SubagentRequest {
+ SubagentRequest {
+ agent: "general".to_string(),
+ ..req(name, None)
+ }
+ }
+
+ /// `parse_dispatch_plan` in a session with no earlier workers.
+ fn parse_dispatch_plan_fresh(args: &serde_json::Value) -> Result<DispatchPlan, SubagentError> {
+ parse_dispatch_plan(args, |_| false)
+ }
+
fn req(name: &str, allowed: Option<Vec<String>>) -> SubagentRequest {
SubagentRequest {
name: name.to_string(),
description: "do the thing".to_string(),
allowed_tools: allowed,
- agent: None,
+ agent: name.to_string(),
}
}
@@ -3823,61 +3964,48 @@ pub(crate) mod tests {
assert_eq!(off["send_reasoning"], serde_json::json!(false));
}
- /// An unknown name is no longer an error: it runs as a focused generalist
- /// whose default prompt names it, with the request's tools as its toolset.
+ /// An `agent` that names nothing is an error listing what it may name, not
+ /// a silent fallback to an unprompted agent on the main model.
#[test]
- fn resolve_unknown_name_runs_ephemeral_generalist() {
- let reg = SubagentRegistry::default();
+ fn resolve_rejects_an_unknown_agent() {
+ let reg = SubagentRegistry::load(&unique_root("unknown_agent"));
let p = ToolPermissions::allow_all();
- let request = SubagentRequest {
- name: "one-off".to_string(),
- description: "task".to_string(),
- allowed_tools: Some(vec!["read".to_string()]),
- agent: None,
- };
- let resolved = resolve_dispatch_plain(&reg, &request, &p).unwrap();
- assert_eq!(resolved.definition.name, "one-off");
- assert!(resolved.definition.system_prompt.contains("one-off"));
- assert_eq!(
- resolved.allowed_tools,
- Some(vec![
- "read".to_string(),
- "skill_list".to_string(),
- "skill_read".to_string(),
- ])
- );
+ let err = resolve_dispatch_plain(&reg, &req("one-off", None), &p)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("one-off") && err.contains("general"), "{err}");
}
#[test]
fn parse_dispatch_plan_groups_flat_subagents_by_phase() {
// Listed out of order and with a gap (0, 2); the parser groups and
// orders them, and the phase number carried is the model's own key.
- let plan = parse_dispatch_plan(&serde_json::json!({
+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({
"subagents": [
- { "name": "synthesize", "task": "write it up", "phase": 2 },
- { "name": "research-api", "task": "study the api" },
- { "name": "research-perf", "task": "study perf", "phase": 0, "allowed_tools": ["read", "grep"] }
+ { "agent": "general", "task": "write it up", "phase": 2 },
+ { "agent": "research", "task": "study the api" },
+ { "agent": "explore", "task": "study perf", "phase": 0, "allowed_tools": ["read", "grep"] }
]
}))
.unwrap();
assert_eq!(plan.phases.len(), 2);
assert_eq!(plan.phases[0].number, 0);
assert_eq!(plan.phases[0].subagents.len(), 2);
- assert_eq!(plan.phases[0].subagents[0].name, "research-api");
+ assert_eq!(plan.phases[0].subagents[0].agent, "research");
assert_eq!(
plan.phases[0].subagents[1].allowed_tools,
Some(vec!["read".to_string(), "grep".to_string()])
);
assert_eq!(plan.phases[1].number, 2);
- assert_eq!(plan.phases[1].subagents[0].name, "synthesize");
+ assert_eq!(plan.phases[1].subagents[0].agent, "general");
}
#[test]
fn parse_dispatch_plan_fans_out_with_no_phase() {
- let plan = parse_dispatch_plan(&serde_json::json!({
+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({
"subagents": [
- { "name": "a", "task": "x" },
- { "name": "b", "task": "y" }
+ { "agent": "explore", "task": "x" },
+ { "agent": "general", "task": "y" }
]
}))
.unwrap();
@@ -3885,34 +4013,48 @@ pub(crate) mod tests {
assert_eq!(plan.phases[0].subagents.len(), 2);
}
+ /// Repeats of one agent are numbered in the order listed, across phases,
+ /// and a name an earlier worker of the session still holds is skipped.
#[test]
- fn parse_dispatch_plan_rejects_duplicate_names() {
- let err = parse_dispatch_plan(&serde_json::json!({
+ fn workers_are_numbered_in_listed_order_skipping_taken_names() {
+ let plan = parse_dispatch_plan(&serde_json::json!({
"subagents": [
- { "name": "a", "task": "x" },
- { "name": "a", "task": "y", "phase": 1 }
+ { "agent": "explore", "task": "a" },
+ { "agent": "general", "task": "b" },
+ { "agent": "explore", "task": "c" },
+ { "agent": "explore", "task": "d", "phase": 1 }
]
- }))
- .unwrap_err();
- assert!(matches!(err, SubagentError::Upstream(m) if m.contains("duplicate")));
+ }), |name| name == "general")
+ .unwrap();
+ let names: Vec<&str> = plan
+ .phases
+ .iter()
+ .flat_map(|p| p.subagents.iter().map(|s| s.name.as_str()))
+ .collect();
+ assert_eq!(names, ["explore", "general-2", "explore-2", "explore-3"]);
}
#[test]
fn parse_dispatch_plan_rejects_empty_missing_and_bad_phase() {
- assert!(parse_dispatch_plan(&serde_json::json!({})).is_err());
- assert!(parse_dispatch_plan(&serde_json::json!({ "subagents": [] })).is_err());
+ assert!(parse_dispatch_plan_fresh(&serde_json::json!({})).is_err());
+ assert!(parse_dispatch_plan_fresh(&serde_json::json!({ "subagents": [] })).is_err());
// missing task
- assert!(parse_dispatch_plan(
- &serde_json::json!({ "subagents": [ { "name": "a" } ] })
+ assert!(parse_dispatch_plan_fresh(
+ &serde_json::json!({ "subagents": [ { "agent": "general" } ] })
+ )
+ .is_err());
+ // missing agent: a free-form name is no longer accepted
+ assert!(parse_dispatch_plan_fresh(
+ &serde_json::json!({ "subagents": [ { "name": "a", "task": "x" } ] })
)
.is_err());
// negative / non-integer phase
- assert!(parse_dispatch_plan(
- &serde_json::json!({ "subagents": [ { "name": "a", "task": "x", "phase": -1 } ] })
+ assert!(parse_dispatch_plan_fresh(
+ &serde_json::json!({ "subagents": [ { "agent": "general", "task": "x", "phase": -1 } ] })
)
.is_err());
- assert!(parse_dispatch_plan(
- &serde_json::json!({ "subagents": [ { "name": "a", "task": "x", "phase": "later" } ] })
+ assert!(parse_dispatch_plan_fresh(
+ &serde_json::json!({ "subagents": [ { "agent": "general", "task": "x", "phase": "later" } ] })
)
.is_err());
}
@@ -4732,14 +4874,15 @@ pub(crate) mod tests {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let plan = DispatchPlan {
+ names: Vec::new(),
phases: vec![
Phase {
number: 0,
- subagents: vec![req("alpha", None), req("beta", None)],
+ subagents: vec![worker("alpha"), worker("beta")],
},
Phase {
number: 1,
- subagents: vec![req("collector", None)],
+ subagents: vec![worker("collector")],
},
],
};
@@ -4808,14 +4951,15 @@ pub(crate) mod tests {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let plan = DispatchPlan {
+ names: Vec::new(),
phases: vec![
Phase {
number: 0,
- subagents: vec![req("alpha", None)],
+ subagents: vec![worker("alpha")],
},
Phase {
number: 1,
- subagents: vec![req("collector", None)],
+ subagents: vec![worker("collector")],
},
],
};
@@ -4877,7 +5021,7 @@ pub(crate) mod tests {
bg.abort_all();
let dispatched =
- spawn_subagent(&scope, &args, req("late", None), &parent_run(), &tx, None, true);
+ spawn_subagent(&scope, &args, worker("late"), &parent_run(), &tx, None, true);
assert!(
matches!(dispatched, Err(SubagentError::Cancelled)),
"a dispatch after teardown must be refused, not started"
@@ -5072,14 +5216,15 @@ pub(crate) mod tests {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let plan = DispatchPlan {
+ names: Vec::new(),
phases: vec![
Phase {
number: 0,
- subagents: vec![req("alpha", None)],
+ subagents: vec![worker("alpha")],
},
Phase {
number: 1,
- subagents: vec![req("collector", None)],
+ subagents: vec![worker("collector")],
},
],
};
@@ -5136,14 +5281,15 @@ pub(crate) mod tests {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let plan = DispatchPlan {
+ names: Vec::new(),
phases: vec![
Phase {
number: 0,
- subagents: vec![req("alpha", None), req("beta", None)],
+ subagents: vec![worker("alpha"), worker("beta")],
},
Phase {
number: 1,
- subagents: vec![req("gamma", None), req("collector", None)],
+ subagents: vec![worker("gamma"), worker("collector")],
},
],
};
@@ -5443,7 +5589,9 @@ pub(crate) mod tests {
]
);
let dispatch = &schemas[0]["function"]["description"].as_str().unwrap();
- assert!(dispatch.contains("reviewer"), "got: {dispatch}");
+ let agent = &schemas[0]["function"]["parameters"]["properties"]["subagents"]["items"]
+ ["properties"]["agent"];
+ assert_eq!(agent["enum"], serde_json::json!(["reviewer"]));
// await_subagent is no longer advertised; the description explains the
// background model (a note carries each child's answer) instead.
assert!(!dispatch.contains("await_subagent"), "no await reference: {dispatch}");
@@ -5473,9 +5621,9 @@ pub(crate) mod tests {
"create_subagent must not let the model choose a model"
);
- let dispatch = schemas[0]["function"]["description"].as_str().unwrap();
- assert!(dispatch.contains("reviewer (smol)"), "{dispatch}");
- assert!(dispatch.contains("writer (inherit)"), "{dispatch}");
+ let catalog = agent_catalog(&reg).unwrap();
+ assert!(catalog.contains("`reviewer` (model: smol)"), "{catalog}");
+ assert!(catalog.contains("`writer` (model: inherit)"), "{catalog}");
}
/// `list_subagents` reports the model a name dispatches on next to its
@@ -5586,44 +5734,29 @@ pub(crate) mod tests {
let _ = std::fs::remove_dir_all(&root);
}
- /// `agent` names the definition a worker runs, separately from the
- /// worker's own `name`, so one plan can fan out several `explore` workers
- /// (names must be unique: each is a blackboard file) and an ad-hoc worker
- /// that happens to be called `research` is not hijacked by the built-in.
+ /// Several workers of one agent each run its definition under their own
+ /// numbered name, which is what their blackboard file and run id carry.
#[test]
- fn agent_names_the_definition_and_name_the_worker() {
+ fn repeated_agents_run_the_definition_under_their_own_names() {
let root = unique_root("agent_field");
let reg = SubagentRegistry::load(&root);
let p = ToolPermissions::allow_all();
- let plan = parse_dispatch_plan(&serde_json::json!({ "subagents": [
- { "name": "explore-api", "agent": "explore", "task": "a" },
- { "name": "explore-db", "agent": "explore", "task": "b" },
- { "name": "research", "task": "look into the build", "allowed_tools": ["shell"] }
+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({ "subagents": [
+ { "agent": "explore", "task": "a" },
+ { "agent": "explore", "task": "b" }
]}))
.expect("two explore workers in one plan");
let subs = &plan.phases[0].subagents;
- assert_eq!(subs[0].agent.as_deref(), Some("explore"));
-
- let api = resolve_dispatch_plain(&reg, &subs[0], &p).unwrap();
- assert_eq!(api.definition.name, "explore-api", "the worker keeps its own name");
- assert_eq!(api.definition.scope, SubagentScope::Builtin);
- assert_eq!(api.definition.model.as_deref(), Some(SMOL_ROLE));
- assert!(api.definition.system_prompt.contains("read-only"));
-
- // No `agent`: a one-off, whatever its name, with its own tools.
- let adhoc = resolve_dispatch_plain(&reg, &subs[2], &p).expect("not hijacked");
- assert_ne!(adhoc.definition.scope, SubagentScope::Builtin);
- assert_eq!(adhoc.definition.model, None);
-
- // An `agent` that names nothing is an error the model can fix, not a
- // silent fallback to a general-purpose agent on the main model.
- let bad = SubagentRequest { agent: Some("nope".into()), ..req("w", None) };
- let err = resolve_dispatch_plain(&reg, &bad, &p).unwrap_err().to_string();
- assert!(err.contains("nope") && err.contains("explore"), "{err}");
+ let second = resolve_dispatch_plain(&reg, &subs[1], &p).unwrap();
+ assert_eq!(second.definition.name, "explore-2", "the worker keeps its own name");
+ assert_eq!(second.definition.scope, SubagentScope::Builtin);
+ assert_eq!(second.definition.model.as_deref(), Some(SMOL_ROLE));
+ assert_eq!(second.allowed_tools, None, "inherits the full toolset");
let _ = std::fs::remove_dir_all(&root);
}
- /// The dispatch schema documents `agent` and lists what it may name.
+ /// The dispatch schema's `agent` is a required enum of the predefined
+ /// agents, and there is no free-form `name` to invent.
#[test]
fn the_dispatch_schema_offers_agent() {
let reg = SubagentRegistry::load(&unique_root("agent_schema"));
@@ -5631,10 +5764,121 @@ pub(crate) mod tests {
let item = &schemas[0]["function"]["parameters"]["properties"]["subagents"]["items"];
let agent = &item["properties"]["agent"];
assert_eq!(agent["type"], "string");
- let required = item["required"].as_array().unwrap();
- assert!(!required.iter().any(|r| r == "agent"));
- let dispatch = schemas[0]["function"]["description"].as_str().unwrap();
- assert!(dispatch.contains("explore (smol)"), "{dispatch}");
+ assert_eq!(item["required"], serde_json::json!(["agent", "task"]));
+ assert!(item["properties"].get("name").is_none());
+ assert_eq!(
+ agent["enum"],
+ serde_json::json!(["debug", "explore", "general", "research", "review"])
+ );
+ }
+
+ /// Every `allowed_tools` array is pinned to the names the run offers, minus
+ /// the tools no child can get, plus the search tools a child may ask for.
+ #[test]
+ fn allowed_tools_are_pinned_to_the_offered_names() {
+ let reg = SubagentRegistry::load(&unique_root("tool_enum"));
+ let mut tools = subagent_tool_schemas(&reg, DEFAULT_MAX_PARALLEL_SUBAGENTS);
+ tools.push(serde_json::json!({ "type": "function", "function": { "name": "shell" } }));
+ tools.push(serde_json::json!({ "type": "function", "function": { "name": "ask" } }));
+ let mut ceiling = tools.clone();
+ let mut denied = tools.clone();
+ constrain_tool_names(&mut tools, &ToolPermissions::allow_all(), false);
+ let expected = serde_json::json!(["find", "grep", "ls", "shell"]);
+ let dispatch = &tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]
+ ["properties"]["allowed_tools"]["items"];
+ assert_eq!(dispatch["enum"], expected);
+ let create = tools
+ .iter()
+ .find(|s| s["function"]["name"] == "create_subagent")
+ .unwrap();
+ let items = &create["function"]["parameters"]["properties"]["allowed_tools"]["items"];
+ assert_eq!(items["enum"], expected);
+
+ // A search tool the child could not be given is not offered either.
+ let enum_of = |tools: &[serde_json::Value]| {
+ tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]["properties"]
+ ["allowed_tools"]["items"]["enum"]
+ .clone()
+ };
+ constrain_tool_names(&mut ceiling, &ToolPermissions::allow_all(), true);
+ assert_eq!(enum_of(&ceiling), serde_json::json!(["shell"]));
+ constrain_tool_names(&mut denied, &perms_denying(&["find"]), false);
+ assert_eq!(enum_of(&denied), serde_json::json!(["grep", "ls", "shell"]));
+
+ // Nothing delegable: no `allowed_tools` at all, never an empty enum.
+ let mut bare = subagent_tool_schemas(&reg, DEFAULT_MAX_PARALLEL_SUBAGENTS);
+ constrain_tool_names(&mut bare, &ToolPermissions::allow_all(), true);
+ let item = &bare[0]["function"]["parameters"]["properties"]["subagents"]["items"];
+ assert!(item["properties"].get("allowed_tools").is_none(), "{item}");
+ let create = bare
+ .iter()
+ .find(|s| s["function"]["name"] == "create_subagent")
+ .unwrap();
+ assert!(create["function"]["parameters"]["properties"].get("allowed_tools").is_none());
+ }
+
+ /// A name is held from the moment a dispatch hands it out -- a later-phase
+ /// worker that has not started included -- and by an answer still on the
+ /// blackboard after the registry that ran it is gone.
+ #[test]
+ fn a_handed_out_or_answered_name_is_not_given_again() {
+ let root = unique_root("bb_taken");
+ let scratch = root.join("scratch");
+ std::fs::create_dir_all(blackboard_dir_path(&scratch)).unwrap();
+ std::fs::write(blackboard_dir_path(&scratch).join("explore.md"), "earlier").unwrap();
+ let bg = BackgroundSubagents::new(1);
+ let names = |plan: DispatchPlan| -> Vec<String> {
+ plan.phases.into_iter().flat_map(|p| p.subagents).map(|s| s.name).collect()
+ };
+ let first = bg
+ .plan_dispatch(
+ &serde_json::json!({ "subagents": [
+ { "agent": "explore", "task": "a" },
+ { "agent": "general", "task": "b", "phase": 1 }
+ ]}),
+ Some(&scratch),
+ )
+ .unwrap();
+ assert_eq!(names(first), ["explore-2", "general"]);
+ // Nothing has been spawned, yet the later-phase `general` is held.
+ let second = bg
+ .plan_dispatch(
+ &serde_json::json!({ "subagents": [
+ { "agent": "general", "task": "c" },
+ { "agent": "explore", "task": "d" }
+ ]}),
+ Some(&scratch),
+ )
+ .unwrap();
+ assert_eq!(names(second.clone()), ["general-2", "explore-3"]);
+ // A dispatch that failed to start gives its names back.
+ bg.release_names(&second.names);
+ let retry = bg
+ .plan_dispatch(
+ &serde_json::json!({ "subagents": [ { "agent": "general", "task": "c" } ] }),
+ Some(&scratch),
+ )
+ .unwrap();
+ assert_eq!(names(retry), ["general-2"]);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A name long enough to share a blackboard stem with its own numbered
+ /// variants is refused up front instead of numbering forever: at dispatch,
+ /// at creation, and in the enum a hand-written file would otherwise reach.
+ #[test]
+ fn an_over_long_agent_name_is_refused() {
+ let long = "a".repeat(MAX_AGENT_NAME_LEN + 1);
+ let err = parse_dispatch_plan_fresh(&serde_json::json!({
+ "subagents": [ { "agent": long, "task": "x" } ]
+ }))
+ .unwrap_err();
+ assert!(err.to_string().contains("too long"), "{err}");
+ let mut reg = registry_with("ok", None);
+ assert!(reg.create(SubagentDefinition { name: long.clone(), ..reg.defs[0].clone() },
+ SubagentScope::User, false).is_err());
+ reg.defs.push(SubagentDefinition { name: long, ..reg.defs[0].clone() });
+ assert_eq!(reg.dispatchable_names(), ["ok"]);
}
#[test]
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 38a9c2859..f6607cb37 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -2112,23 +2112,57 @@ impl AgentRow {
}
}
-/// The dispatch row for a `dispatch_subagent` call: every child it names, each
-/// brief's first line under it (named, when there are several).
-fn dispatch_row(args: &serde_json::Value) -> AgentRow {
- let subagents: Vec<(String, String)> = args
+/// The worker names a `dispatch_subagent` call gives its children. While the
+/// call is in flight only its arguments are known, so they are numbered the
+/// way dispatch numbers them (`explore`, `explore-2`) without the names the
+/// session already holds; `reported`, the names the dispatch result lists,
+/// replaces that guess once it lands. A call saved before workers were named
+/// after their agent carries its own `name`, kept so an old transcript replays
+/// readable.
+fn dispatched_workers<'a>(
+ args: &'a serde_json::Value,
+ reported: Option<&[String]>,
+) -> Vec<(String, &'a serde_json::Value)> {
+ let subs: Vec<(&str, &serde_json::Value)> = args
.get("subagents")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|s| {
- let name = s.get("name").and_then(|v| v.as_str())?;
- let task = s.get("task").and_then(|v| v.as_str()).unwrap_or("");
- let brief = task.lines().map(str::trim).find(|l| !l.is_empty());
- Some((name.to_string(), brief.unwrap_or("").to_string()))
+ let label = s.get("agent").or_else(|| s.get("name"))?.as_str()?;
+ Some((label, s))
})
.collect()
})
.unwrap_or_default();
+ let names = match reported {
+ Some(names) if names.len() == subs.len() => names.to_vec(),
+ _ if subs.iter().all(|(_, s)| s.get("agent").is_none()) => {
+ subs.iter().map(|(name, _)| (*name).to_string()).collect()
+ }
+ _ => crate::core::agent::subagent::number_workers(
+ subs.iter().map(|(agent, _)| *agent),
+ |_| false,
+ ),
+ };
+ names
+ .into_iter()
+ .zip(subs.into_iter().map(|(_, sub)| sub))
+ .collect()
+}
+
+/// The dispatch row for a `dispatch_subagent` call: every child it names, each
+/// brief's first line under it (named, when there are several). `reported` is
+/// the worker names from the dispatch result, once it has landed.
+fn dispatch_row(args: &serde_json::Value, reported: Option<&[String]>) -> AgentRow {
+ let subagents: Vec<(String, String)> = dispatched_workers(args, reported)
+ .into_iter()
+ .map(|(name, s)| {
+ let task = s.get("task").and_then(|v| v.as_str()).unwrap_or("");
+ let brief = task.lines().map(str::trim).find(|l| !l.is_empty());
+ (name, brief.unwrap_or("").to_string())
+ })
+ .collect();
let dim = Style::new().fg(theme::muted());
let several = subagents.len() > 1;
let briefs = subagents
@@ -2393,6 +2427,9 @@ struct Transcript {
/// Standalone (edit/write) call rows still awaiting their result. Several
/// can be open at once: a batch emits every `ToolCall` before any result.
pending_rows: Vec<PendingToolRow>,
+ /// The arguments of each dispatch whose result has not landed, so the row
+ /// can be relabeled with the worker names that result reports.
+ dispatch_args: HashMap<String, serde_json::Value>,
/// Committed reasoning blocks, folded to a summary row and expandable back to
/// their full dimmed lines.
reasoning_blocks: Vec<ReasoningBlock>,
@@ -2594,7 +2631,8 @@ impl Transcript {
self.finalize_tool_group();
self.gap(Kind::Tool);
if name == "dispatch_subagent" {
- self.push_row(RowKind::Agent(Box::new(dispatch_row(args))));
+ self.push_row(RowKind::Agent(Box::new(dispatch_row(args, None))));
+ self.dispatch_args.insert(id.clone(), args.clone());
} else {
self.push_row(RowKind::Tool {
state: ToolState::Running,
@@ -3390,13 +3428,25 @@ impl Transcript {
Some(path) if created => format!("Created {path}"),
_ => row.done,
};
+ let dispatch_args = self.dispatch_args.remove(id);
let call = match &self.rows[row.idx].kind {
// A dispatch keeps its row; the result only confirms what the row
- // already says unless it failed.
+ // already says unless it failed -- and names each worker as the
+ // dispatch actually named it, which only the result knows.
RowKind::Agent(agent) => {
+ let reported = match &result {
+ RowKind::Result { content: Some(text), .. } if !is_error => {
+ crate::core::agent::subagent::worker_names_in(text)
+ }
+ _ => None,
+ };
+ let relabeled = dispatch_args
+ .as_ref()
+ .zip(reported.as_deref())
+ .map(|(args, names)| dispatch_row(args, Some(names)));
let call = RowKind::Agent(Box::new(AgentRow {
state: ToolState::of(is_error),
- ..(**agent).clone()
+ ..relabeled.unwrap_or_else(|| (**agent).clone())
}));
if !is_error {
self.rows[row.idx] = call.into();
@@ -5193,6 +5243,7 @@ impl App {
self.starting.clear();
self.transcript.groups.clear();
self.transcript.pending_rows.clear();
+ self.transcript.dispatch_args.clear();
self.transcript.reasoning_blocks.clear();
self.transcript.expanded_traces.clear();
self.transcript.subagent_blocks.clear();
@@ -10048,22 +10099,12 @@ fn collapse_command(cmd: &str) -> String {
.to_string()
}
-/// The name of the first subagent in a phased `dispatch_subagent` call. The
-/// schema is a flat `subagents: [{ name, task, phase }]`; the transient row
-/// names the first, mirroring the web card (`firstPlannedSubagent`).
/// The dispatch row's subject: the one child's name, or `N subagents: a, b, c`
/// for a fan-out. Every name is listed, since once the live dock has scrolled
/// away this row is the only on-screen account of what was dispatched.
fn dispatched_subagents_label(verb: &str, args: &serde_json::Value) -> String {
- let names: Vec<&str> = args
- .get("subagents")
- .and_then(|v| v.as_array())
- .map(|a| {
- a.iter()
- .filter_map(|s| s.get("name").and_then(|v| v.as_str()))
- .collect()
- })
- .unwrap_or_default();
+ let names: Vec<String> =
+ dispatched_workers(args, None).into_iter().map(|(name, _)| name).collect();
match names.as_slice() {
[] => format!("{verb} subagent"),
[one] => format!("{verb} subagent {one}"),
@@ -24789,12 +24830,12 @@ mod tests {
id: "d1".into(),
name: "dispatch_subagent".into(),
args: json!({ "subagents": [
- { "name": "kv-review", "task": "Review the store.\nThen report." },
- { "name": "docs-writer", "task": "Write the docs." },
+ { "agent": "review", "task": "Review the store.\nThen report." },
+ { "agent": "general", "task": "Write the docs." },
] }),
});
let text = transcript_text(&app);
- assert!(text.contains("• Dispatching kv-review, docs-writer"), "{text}");
+ assert!(text.contains("• Dispatching review, general"), "{text}");
app.apply(StreamEvent::ToolResult {
id: "d1".into(),
content: "dispatched".into(),
@@ -24804,9 +24845,9 @@ mod tests {
let text = transcript_text(&app);
assert!(
text.contains(concat!(
- "• Dispatched kv-review, docs-writer\n",
- " └ kv-review: Review the store.\n",
- " docs-writer: Write the docs."
+ "• Dispatched review, general\n",
+ " └ review: Review the store.\n",
+ " general: Write the docs."
)),
"{text}"
);
@@ -24814,6 +24855,58 @@ mod tests {
assert!(has_dispatch_state(&app, ToolState::Success));
}
+ /// The row names each worker as the dispatch actually named it: an
+ /// earlier `explore` in the session makes this one `explore-2`, which only
+ /// the dispatch result knows.
+ #[test]
+ fn a_dispatch_row_takes_the_worker_names_the_result_reports() {
+ let mut app = test_app();
+ app.apply(StreamEvent::ToolCall {
+ id: "d1".into(),
+ name: "dispatch_subagent".into(),
+ args: json!({ "subagents": [
+ { "agent": "explore", "task": "Find the store." },
+ { "agent": "general", "task": "Write the docs." },
+ ] }),
+ });
+ assert!(transcript_text(&app).contains("• Dispatching explore, general"));
+ app.apply(StreamEvent::ToolResult {
+ id: "d1".into(),
+ content: format!(
+ "Dispatched 2 subagent(s).\n{}",
+ crate::core::agent::subagent::worker_names_line(&[
+ "explore-2".to_string(),
+ "general".to_string(),
+ ])
+ ),
+ is_error: false,
+ diff: None,
+ });
+ let text = transcript_text(&app);
+ assert!(
+ text.contains(concat!(
+ "• Dispatched explore-2, general\n",
+ " └ explore-2: Find the store.\n",
+ " general: Write the docs."
+ )),
+ "{text}"
+ );
+ }
+
+ /// A dispatch saved before workers were named after their agent carries
+ /// its own `name`; replayed, it still shows those names and briefs.
+ #[test]
+ fn a_legacy_named_dispatch_replays_with_its_names() {
+ let dispatch = json!({ "subagents": [
+ { "name": "kv-review", "task": "x" },
+ { "name": "docs-writer", "task": "y" },
+ ] });
+ assert_eq!(
+ tool_finished("dispatch_subagent", &dispatch),
+ "Dispatched 2 subagents kv-review, docs-writer"
+ );
+ }
+
/// A dispatch the run never resolved reads as interrupted, not running.
#[test]
fn an_unresolved_dispatch_row_is_interrupted_by_a_cancel() {
@@ -24821,11 +24914,11 @@ mod tests {
app.apply(StreamEvent::ToolCall {
id: "d1".into(),
name: "dispatch_subagent".into(),
- args: json!({ "subagents": [{ "name": "solo", "task": "go" }] }),
+ args: json!({ "subagents": [{ "agent": "general", "task": "go" }] }),
});
app.transcript.settle(true);
assert!(has_dispatch_state(&app, ToolState::Interrupted));
- assert!(transcript_text(&app).contains("• Dispatching solo\n └ go"));
+ assert!(transcript_text(&app).contains("• Dispatching general\n └ go"));
}
fn has_dispatch_state(app: &App, state: ToolState) -> bool {
@@ -28771,14 +28864,14 @@ mod tests {
#[test]
fn subagent_tool_rows_have_readable_labels() {
- let dispatch = json!({ "subagents": [{ "name": "reviewer", "task": "x" }] });
+ let dispatch = json!({ "subagents": [{ "agent": "review", "task": "x" }] });
assert_eq!(
tool_activity("dispatch_subagent", &dispatch),
- "Dispatching subagent reviewer"
+ "Dispatching subagent review"
);
assert_eq!(
tool_finished("dispatch_subagent", &dispatch),
- "Dispatched subagent reviewer"
+ "Dispatched subagent review"
);
let await_args = json!({ "run_id": "sub-sycl-cuda-gap-explorer-1" });
assert_eq!(
@@ -28800,17 +28893,17 @@ mod tests {
#[test]
fn a_multi_dispatch_row_names_every_subagent() {
let dispatch = json!({ "subagents": [
- { "name": "counter", "task": "x" },
- { "name": "waster", "task": "y" },
- { "name": "reader", "task": "z" },
+ { "agent": "explore", "task": "x" },
+ { "agent": "general", "task": "y" },
+ { "agent": "explore", "task": "z" },
] });
assert_eq!(
tool_activity("dispatch_subagent", &dispatch),
- "Dispatching 3 subagents counter, waster, reader"
+ "Dispatching 3 subagents explore, general, explore-2"
);
assert_eq!(
tool_finished("dispatch_subagent", &dispatch),
- "Dispatched 3 subagents counter, waster, reader"
+ "Dispatched 3 subagents explore, general, explore-2"
);
}
@@ -31750,7 +31843,7 @@ mod tests {
assert_eq!(picker.kind, PickerKind::SubagentModels);
let labels: Vec<_> = picker.items.iter().map(|i| i.value.as_str()).collect();
// The saved explorer and reviewer sit beside the built-in catalog.
- assert_eq!(labels, ["debug", "explore", "explorer", "research", "review", "reviewer"]);
+ assert_eq!(labels, ["debug", "explore", "explorer", "general", "research", "review", "reviewer"]);
let hint = |name: &str| {
let item = picker.items.iter().find(|i| i.value == name).unwrap();
item.hint.clone().unwrap_or_default()