Compare commits

...
7 changed files with 300 additions and 61 deletions

View file

@ -296,7 +296,7 @@ nix/
forge-theme/theme-catppuccin-vibec0re.css Catppuccin Mocha forge theme
docs/
conventions.md naming, identity=socket, async forms, commit style
conventions.md naming, identity=socket, tool groups, async forms, commit style
gotchas.md NixOS / nspawn quirks and lessons learned
web-ui.md index → web-ui/shape.md (shared skeleton, SSE,
terminal, listener bind, relative paths, atomic

View file

@ -274,6 +274,47 @@ status_text, status_set_at, hive_name, swarm_name }`:
`services.hyperhive.hiveName` / `services.hyperhive.swarmName`).
Both `None` when the options aren't configured.
## Tool groups
The MCP tool surface an agent receives is derived from a set of named
`ToolGroup` values (`hive_sh4re::ToolGroup`), not from a hardcoded
binary flavor.
| Group | Tools |
|---|---|
| `messaging` | `send`, `recv`, `ask`, `answer` |
| `meta` | `set_status`, `get_agent_meta` |
| `inbox` | `get_loose_ends`, `cancel_loose_end`, `remind`, `request_next_turn` |
| `lifecycle` | `kill`, `start`, `restart`, `update` *(privileged)* |
| `approvals` | `request_init_config`, `request_apply_commit`, `request_update_meta_inputs` *(privileged)* |
| `scheduling` | `request_schedule_prompt`, `fire_schedule_now`, `cancel_schedule`, `edit_schedule`, `list_schedules` *(privileged)* |
| `diagnostics` | `get_logs` *(privileged)* |
**Config storage** — per-agent tool groups live in
`/var/lib/hyperhive/meta/tool-groups.json` (hive-c0re-owned, committed to the
meta repo alongside `topology.json`). Format: `{ "alice": ["messaging", "meta",
"inbox", "lifecycle"], "bob": ["messaging", "meta", "inbox"] }`. An absent entry
means "use role default". Tool permissions are intentionally NOT configurable
from `agent.nix` — that file goes through the manager's approval flow, so
letting it declare its own groups would let the manager grant itself any tool by
submitting a config commit, bypassing the operator gate.
**Setting groups** — the operator sets groups via the dashboard or
`hive-c0re::tool_groups::set_groups(name, groups)`. After a change
`meta::sync_agents` commits the updated file; the next agent rebuild picks up
the new `HIVE_TOOL_GROUPS` env var. Agents with no entry get no var.
**Runtime resolution** — at session start the harness reads `HIVE_TOOL_GROUPS`
(a comma-separated list of snake_case group names injected by the meta renderer
from `tool-groups.json`). Unrecognised tokens are logged and skipped. Falls back
to `ToolGroup::AGENT_DEFAULT` (`messaging`, `meta`, `inbox`) or
`ToolGroup::MANAGER_DEFAULT` (all groups) when the var is absent or empty.
**Updating the surface** — when a new `#[tool]` fn is added to `AgentServer`
or `ManagerServer` in `hive-ag3nt/src/mcp.rs`, add its name to the matching
`ToolGroup::tools()` slice in `hive-sh4re/src/lib.rs`. That's the single
source of truth; `allowed_mcp_tools` reads it at session start.
## Async forms
Dashboard + per-agent mutating forms carry `data-async`; a delegated

View file

@ -468,10 +468,9 @@ impl AgentServer {
}
// IMPORTANT: when adding a new `#[tool]` fn to this impl, also add
// its name to `allowed_mcp_tools(Flavor::Agent)` below. Claude
// Code's permission gate refuses uninlisted MCP tools in
// non-interactive `--print` mode with "permissions not granted yet"
// — keep the two lists in lockstep.
// its name to the matching `ToolGroup::tools()` slice in hive-sh4re.
// Claude Code's permission gate refuses uninlisted MCP tools in
// non-interactive `--print` mode with "permissions not granted yet".
#[tool_router]
impl AgentServer {
#[tool(
@ -1062,10 +1061,9 @@ impl ManagerServer {
}
// IMPORTANT: when adding a new `#[tool]` fn to this impl, also add
// its name to `allowed_mcp_tools(Flavor::Manager)` below. Claude
// Code's permission gate refuses uninlisted MCP tools in
// non-interactive `--print` mode with "permissions not granted yet"
// — keep the two lists in lockstep.
// its name to the matching `ToolGroup::tools()` slice in hive-sh4re.
// Claude Code's permission gate refuses uninlisted MCP tools in
// non-interactive `--print` mode with "permissions not granted yet".
#[tool_router]
impl ManagerServer {
#[tool(
@ -1731,56 +1729,70 @@ pub enum Flavor {
Manager,
}
/// MCP tools claude is allowed to call without prompting. Mirrors the
/// hyperhive surface so a new tool added in the corresponding `#[tool_router]`
/// impl needs to be listed here too.
#[must_use]
pub fn allowed_mcp_tools(flavor: Flavor) -> Vec<String> {
let names: &[&str] = match flavor {
Flavor::Agent => &[
"send",
"recv",
"ask",
"answer",
"remind",
"get_loose_ends",
"set_status",
"get_agent_meta",
"cancel_loose_end",
],
Flavor::Manager => &[
"send",
"recv",
"request_init_config",
"kill",
"start",
"restart",
"update",
"request_apply_commit",
// The remaining manager tools below were added incrementally
// and have historically been missed in the allow-list when
// their `#[tool]` impls landed. Claude Code's permission gate
// refuses uninlisted tools in non-interactive `--print` mode
// with a "permissions not granted yet" error — keep this
// block in lockstep with the `#[tool]` fns in `ManagerServer`.
"request_update_meta_inputs",
"request_schedule_prompt",
"fire_schedule_now",
"cancel_schedule",
"edit_schedule",
"list_schedules",
"ask",
"answer",
"get_logs",
"get_loose_ends",
"remind",
"set_status",
"get_agent_meta",
"cancel_loose_end",
],
/// Env var written by the meta renderer with a comma-separated list of
/// `hive_sh4re::ToolGroup` snake_case names (e.g. `"messaging,inbox,meta"`).
/// When present, the harness expands the groups into per-tool allow entries
/// instead of using the hardcoded flavor default. See `docs/conventions.md::Tool groups`.
const TOOL_GROUPS_ENV: &str = "HIVE_TOOL_GROUPS";
/// Resolve the active tool groups for a harness session.
///
/// Reads `HIVE_TOOL_GROUPS` from the environment first. Each comma-separated
/// token is matched (case-insensitive) against the `ToolGroup` serde names
/// (`messaging`, `meta`, `inbox`, `lifecycle`, `approvals`, `scheduling`,
/// `diagnostics`). Unrecognised tokens are logged and skipped. Falls back to
/// the flavor default when the env var is absent or empty.
fn effective_tool_groups(flavor: Flavor) -> Vec<hive_sh4re::ToolGroup> {
let raw = match std::env::var(TOOL_GROUPS_ENV) {
Ok(v) if !v.trim().is_empty() => v,
_ => {
// No env var — use the flavor default unchanged.
let defaults = match flavor {
Flavor::Agent => hive_sh4re::ToolGroup::AGENT_DEFAULT,
Flavor::Manager => hive_sh4re::ToolGroup::MANAGER_DEFAULT,
};
return defaults.to_vec();
}
};
let mut out: Vec<String> = names
let mut groups = Vec::new();
for token in raw.split(',') {
let t = token.trim().to_ascii_lowercase();
// Parse via serde_json (the canonical deserialization path).
match serde_json::from_value::<hive_sh4re::ToolGroup>(
serde_json::Value::String(t.clone()),
) {
Ok(g) => groups.push(g),
Err(_) => tracing::warn!(
token = %t,
"{TOOL_GROUPS_ENV}: unknown tool group, skipping"
),
}
}
if groups.is_empty() {
tracing::warn!(
"{TOOL_GROUPS_ENV} set but contained no recognised groups; \
falling back to flavor default"
);
return match flavor {
Flavor::Agent => hive_sh4re::ToolGroup::AGENT_DEFAULT.to_vec(),
Flavor::Manager => hive_sh4re::ToolGroup::MANAGER_DEFAULT.to_vec(),
};
}
groups
}
/// MCP tools claude is allowed to call without prompting, derived from
/// the supplied tool groups. Adding a new `#[tool]` fn to a server impl
/// requires updating the matching `ToolGroup::tools()` slice in hive-sh4re
/// (single source of truth). See `docs/conventions.md::Tool groups`.
#[must_use]
pub fn allowed_mcp_tools(groups: &[hive_sh4re::ToolGroup]) -> Vec<String> {
// Collect all tool names, deduplicating while preserving order.
let mut seen = std::collections::HashSet::new();
let mut out: Vec<String> = groups
.iter()
.flat_map(|g| g.tools())
.filter(|t| seen.insert(*t))
.map(|t| format!("mcp__{SERVER_NAME}__{t}"))
.collect();
// Extra MCP servers declared via `hyperhive.extraMcpServers` in
@ -1822,7 +1834,8 @@ pub fn allowed_tools_arg(flavor: Flavor) -> String {
}
})
.collect();
all.extend(allowed_mcp_tools(flavor));
let groups = effective_tool_groups(flavor);
all.extend(allowed_mcp_tools(&groups));
all.join(",")
}

View file

@ -45,4 +45,5 @@ pub mod scheduled_prompts;
pub mod scheduled_prompts_worker;
pub mod server;
pub mod stats_vacuum;
pub mod tool_groups;
pub mod topology;

View file

@ -141,6 +141,13 @@ pub async fn sync_agents(
if crate::topology::topology_path().exists() {
git(&dir, &["add", "topology.json"]).await?;
}
// Stage tool-groups.json when it exists. Created on first
// `set_groups` call (operator-driven); absent = all agents on
// their role defaults, no file needed. git add is a no-op when
// the file is unchanged.
if crate::tool_groups::tool_groups_path().exists() {
git(&dir, &["add", "tool-groups.json"]).await?;
}
nix(&dir, &["flake", "lock"]).await?;
if std::path::Path::new(&dir).join("flake.lock").exists() {
git(&dir, &["add", "flake.lock"]).await?;
@ -436,7 +443,7 @@ where
let pronouns_escaped = operator_pronouns.replace('\\', "\\\\").replace('"', "\\\"");
let _ = writeln!(
out,
" dashboardPort = {dashboard_port};\n operatorPronouns = \"{pronouns_escaped}\";\n mkAgent = {{ name, isManager, port, parent ? null }}:"
" dashboardPort = {dashboard_port};\n operatorPronouns = \"{pronouns_escaped}\";\n mkAgent = {{ name, isManager, port, parent ? null, toolGroups ? null }}:"
);
out.push_str(
r#" let
@ -446,6 +453,7 @@ where
input = inputs."agent-${name}";
service = if isManager then "hive-m1nd" else "hive-ag3nt";
parentEnv = if parent == null then {} else { HIVE_PARENT = parent; };
toolGroupsEnv = if toolGroups == null then {} else { HIVE_TOOL_GROUPS = toolGroups; };
in
base.extendModules {
modules = [
@ -477,7 +485,7 @@ where
HIVE_LABEL = name;
HYPERHIVE_STATE_DIR = "/agents/${name}/state";
};
systemd.services.${service}.environment = parentEnv // {
systemd.services.${service}.environment = parentEnv // toolGroupsEnv // {
HIVE_PORT = toString port;
HIVE_LABEL = name;
HIVE_DASHBOARD_PORT = toString dashboardPort;
@ -527,19 +535,32 @@ where
// (every container at root). `meta::sync_agents` seeds the file
// on first run with manager as root + everyone else under manager.
let topology = crate::topology::read();
let tool_groups_map = crate::tool_groups::read();
for spec in agents {
let parent_attr = topology
.get(&spec.name)
.and_then(|p| p.as_ref())
.map_or_else(|| "null".to_owned(), |p| format!("\"{p}\""));
// Emit `toolGroups = "group1,group2"` when the operator has
// explicitly configured groups for this agent. Absent entry = null
// = harness falls back to its role default (no env var emitted,
// no rebuild cascade for agents whose groups haven't changed).
let groups = tool_groups_map.get(&spec.name).cloned().unwrap_or_default();
let tool_groups_attr = if groups.is_empty() {
"null".to_owned()
} else {
let joined = groups.join(",");
format!("\"{joined}\"")
};
let _ = writeln!(
out,
" {} = mkAgent {{ name = \"{}\"; isManager = {}; port = {}; parent = {}; }};",
" {} = mkAgent {{ name = \"{}\"; isManager = {}; port = {}; parent = {}; toolGroups = {}; }};",
spec.name,
spec.name,
if spec.is_manager { "true" } else { "false" },
spec.port,
parent_attr,
tool_groups_attr,
);
}
out.push_str(" };\n };\n}\n");

View file

@ -0,0 +1,88 @@
//! Per-agent tool-group configuration. Stored at
//! `/var/lib/hyperhive/meta/tool-groups.json` alongside `topology.json`
//! and the meta `flake.nix`.
//!
//! Format: a JSON object mapping agent name to an array of
//! `hive_sh4re::ToolGroup` snake_case strings:
//!
//! ```json
//! {
//! "alice": ["messaging", "meta", "inbox", "lifecycle"],
//! "bob": ["messaging", "meta", "inbox"]
//! }
//! ```
//!
//! An absent entry (or an absent file) means "use the harness role
//! default" — agents get `messaging + meta + inbox`, the manager gets
//! all groups. `render_flake` in `meta.rs` reads this file and
//! injects `HIVE_TOOL_GROUPS` into each agent's systemd service env;
//! agents with no entry get no env var and the harness falls back.
//!
//! Write path: `set_groups` is called from the dashboard action handler
//! that the operator uses to grant/revoke tool groups per agent.
//! The manager may also request group changes via an approval; hive-c0re
//! applies the change on approval, commits the file, and cascades a rebuild.
use std::collections::BTreeMap;
use std::path::PathBuf;
const TOOL_GROUPS_FILE: &str = "tool-groups.json";
#[must_use]
pub fn tool_groups_path() -> PathBuf {
crate::meta::meta_dir().join(TOOL_GROUPS_FILE)
}
/// Read the per-agent tool-group map. Returns an empty map when the
/// file is absent or unparsable — callers treat a missing entry as
/// "use role default".
#[must_use]
pub fn read() -> BTreeMap<String, Vec<String>> {
let path = tool_groups_path();
let Ok(raw) = std::fs::read_to_string(&path) else {
return BTreeMap::new();
};
serde_json::from_str(&raw).unwrap_or_default()
}
/// Look up the configured tool groups for one agent. Returns an empty
/// vec when the agent has no entry — callers should treat this as
/// "use the harness role default."
#[must_use]
pub fn groups_for(name: &str) -> Vec<String> {
read().get(name).cloned().unwrap_or_default()
}
/// Persist the full tool-groups map. Sorted JSON output keeps diffs
/// minimal. Best-effort — returns `io::Error` so callers decide
/// whether to abort or log.
pub fn write(map: &BTreeMap<String, Vec<String>>) -> std::io::Result<()> {
let path = tool_groups_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(map)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
}
/// Set the tool groups for one agent and persist the map. An empty
/// `groups` vec removes the entry (agent reverts to role default).
pub fn set_groups(name: &str, groups: &[String]) -> std::io::Result<()> {
let mut current = read();
if groups.is_empty() {
current.remove(name);
} else {
current.insert(name.to_owned(), groups.to_vec());
}
write(&current)
}
/// Drop the entry for an agent that is being destroyed. Idempotent.
pub fn remove_agent(name: &str) -> std::io::Result<()> {
let mut current = read();
if current.remove(name).is_some() {
write(&current)?;
}
Ok(())
}

View file

@ -711,6 +711,81 @@ pub struct SchedulePromptPayload {
pub description: Option<String>,
}
/// Named group of MCP tools an agent may be granted. The harness reads
/// `HIVE_TOOL_GROUPS` from the environment (a comma-separated list of
/// snake_case group names written by the meta renderer from per-agent
/// config) and expands it to the matching tool names for `--allowedTools`.
/// When the env var is absent the harness falls back to the flavor default
/// (`AGENT_DEFAULT` or `MANAGER_DEFAULT`). See `docs/conventions.md::Tool groups`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolGroup {
/// `send`, `recv`, `ask`, `answer`
Messaging,
/// `set_status`, `get_agent_meta`
Meta,
/// `get_loose_ends`, `cancel_loose_end`, `remind`, `request_next_turn`
Inbox,
/// `kill`, `start`, `restart`, `update` - *(privileged)*
Lifecycle,
/// `request_init_config`, `request_apply_commit`,
/// `request_update_meta_inputs` - *(privileged)*
Approvals,
/// `request_schedule_prompt`, `fire_schedule_now`, `cancel_schedule`,
/// `edit_schedule`, `list_schedules` - *(privileged)*
Scheduling,
/// `get_logs` - *(privileged)*
Diagnostics,
}
impl ToolGroup {
/// The MCP tool names (without the `mcp__hyperhive__` prefix) in this group.
#[must_use]
pub fn tools(self) -> &'static [&'static str] {
match self {
Self::Messaging => &["send", "recv", "ask", "answer"],
Self::Meta => &["set_status", "get_agent_meta"],
Self::Inbox => &[
"get_loose_ends",
"cancel_loose_end",
"remind",
"request_next_turn",
],
Self::Lifecycle => &["kill", "start", "restart", "update"],
Self::Approvals => &[
"request_init_config",
"request_apply_commit",
"request_update_meta_inputs",
],
Self::Scheduling => &[
"request_schedule_prompt",
"fire_schedule_now",
"cancel_schedule",
"edit_schedule",
"list_schedules",
],
Self::Diagnostics => &["get_logs"],
}
}
/// Default tool groups for a plain agent harness — equivalent to the
/// old `Flavor::Agent` allow-list. Used when `HIVE_TOOL_GROUPS` is unset.
pub const AGENT_DEFAULT: &'static [Self] =
&[Self::Messaging, Self::Meta, Self::Inbox];
/// Default tool groups for the manager harness — equivalent to the
/// old `Flavor::Manager` allow-list. Used when `HIVE_TOOL_GROUPS` is unset.
pub const MANAGER_DEFAULT: &'static [Self] = &[
Self::Messaging,
Self::Meta,
Self::Inbox,
Self::Lifecycle,
Self::Approvals,
Self::Scheduling,
Self::Diagnostics,
];
}
/// Schedule row shape on the wire — mirror of
/// `scheduled_prompts::Schedule` but in the public crate so the
/// dashboard and agent surfaces can deserialize without depending