323 lines
13 KiB
Rust
323 lines
13 KiB
Rust
//! What a run is started with: the model list and the swarm's cap, the claude
|
|
//! config, the prompts, the session store and the session to resume.
|
|
|
|
use super::{AgentInference, Config, Path, PathBuf, SessionStore};
|
|
|
|
/// Env var carrying the nix-configured `services.hyperhive.agent.availableModels` as a
|
|
/// comma-separated list, forwarded onto this daemon's unit by
|
|
/// `nix/agent-modules/mcp.nix` from the harness unit.
|
|
const AVAILABLE_MODELS_ENV: &str = "HIVE_AVAILABLE_MODELS";
|
|
|
|
/// The models this daemon may spawn a subagent on, from
|
|
/// [`AVAILABLE_MODELS_ENV`]. `None` when the var is absent.
|
|
pub(super) fn available_models() -> Option<String> {
|
|
std::env::var(AVAILABLE_MODELS_ENV).ok()
|
|
}
|
|
|
|
/// The list a named `model` is checked against.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub(super) enum ModelList {
|
|
/// The swarm's `subagent_models` for this agent.
|
|
Swarm(Vec<String>),
|
|
/// [`AVAILABLE_MODELS_ENV`]; `None` when the var is absent.
|
|
Local(Option<String>),
|
|
}
|
|
|
|
/// The swarm's list when it sets one, else `local`. `read` is `None` when
|
|
/// this daemon has no swarm queue to read from; a failed read is logged and
|
|
/// falls back to `local`.
|
|
pub(super) fn model_list(
|
|
read: Option<crate::swarm_models::Read>,
|
|
local: Option<String>,
|
|
) -> ModelList {
|
|
use crate::swarm_models::Read;
|
|
match read {
|
|
Some(Read::Current(AgentInference {
|
|
subagent_models: Some(models),
|
|
..
|
|
})) => ModelList::Swarm(models),
|
|
Some(Read::Failed(error)) => {
|
|
tracing::warn!(
|
|
%error,
|
|
"reading this agent's subagent_models from the swarm failed; checking against \
|
|
{AVAILABLE_MODELS_ENV}"
|
|
);
|
|
ModelList::Local(local)
|
|
}
|
|
Some(Read::Current(_)) | None => ModelList::Local(local),
|
|
}
|
|
}
|
|
|
|
/// The swarm's `max_subagents` for this agent, or `None`, no cap: when it
|
|
/// sets none, when `read` is `None` because this daemon has no swarm queue,
|
|
/// or when the read failed, which is logged as a warning naming the agent and the error.
|
|
pub(super) fn subagent_cap(read: Option<&crate::swarm_models::Read>, agent: &str) -> Option<u32> {
|
|
use crate::swarm_models::Read;
|
|
match read? {
|
|
Read::Current(settings) => settings.max_subagents,
|
|
Read::Failed(error) => {
|
|
tracing::warn!(
|
|
agent,
|
|
%error,
|
|
"reading this agent's subagent settings from the swarm failed; applying no \
|
|
subagent cap"
|
|
);
|
|
None
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Refuse a `model` the operator hasn't made available to this agent.
|
|
///
|
|
/// Default-open on purpose: this is a safety rail, not a security boundary,
|
|
/// so an absent list (or one naming nothing) restricts nothing and an
|
|
/// agent deployed before this gate existed keeps working unchanged. A `None`
|
|
/// model isn't a choice of model either — it lets claude fall back to its own
|
|
/// default — so there is nothing to check.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// A named model absent from `list`; the message names it, every permitted
|
|
/// one and where the list came from, since it is all the caller sees.
|
|
pub(super) fn check_model(model: Option<&str>, list: &ModelList) -> anyhow::Result<()> {
|
|
let Some(model) = model else {
|
|
return Ok(());
|
|
};
|
|
let (allowed, source): (Vec<&str>, &str) = match list {
|
|
ModelList::Swarm(models) => (
|
|
models
|
|
.iter()
|
|
.map(|m| m.trim())
|
|
.filter(|m| !m.is_empty())
|
|
.collect(),
|
|
"the swarm's subagent_models for this agent",
|
|
),
|
|
ModelList::Local(None) => return Ok(()),
|
|
// Split, trim, skip empty tokens.
|
|
ModelList::Local(Some(env)) => (
|
|
env.split(',')
|
|
.map(str::trim)
|
|
.filter(|token| !token.is_empty())
|
|
.collect(),
|
|
AVAILABLE_MODELS_ENV,
|
|
),
|
|
};
|
|
if allowed.is_empty()
|
|
|| allowed
|
|
.iter()
|
|
.any(|entry| entry.eq_ignore_ascii_case(model.trim()))
|
|
{
|
|
return Ok(());
|
|
}
|
|
anyhow::bail!(
|
|
"model `{model}` is not available to this agent — {source} permits: {}",
|
|
allowed.join(", ")
|
|
);
|
|
}
|
|
|
|
/// Extend the ambient `OTEL_RESOURCE_ATTRIBUTES` with a `subagent=<name>`
|
|
/// attribute, so every token/cost/tool-call data point this subagent's own
|
|
/// claude process emits carries it alongside the parent's `agent=<name>`
|
|
/// label. `Config.env` applies after the inherited environment, so this one
|
|
/// entry overriding the ambient value is the intended shape, not a
|
|
/// wholesale replacement.
|
|
pub(super) fn subagent_otel_attrs(name: &str) -> String {
|
|
match std::env::var("OTEL_RESOURCE_ATTRIBUTES") {
|
|
Ok(existing) if !existing.is_empty() => format!("{existing},subagent={name}"),
|
|
_ => format!("subagent={name}"),
|
|
}
|
|
}
|
|
|
|
/// Build the `Config` one subagent turn runs against. `model` maps straight
|
|
/// onto `Config::model` — `--model`, omitted when `None` so claude falls
|
|
/// back to its own default. `effort` does not: an omitted `effort` defaults
|
|
/// to `"medium"` here rather than falling through to claude's own default
|
|
/// (`high` on most models) — a deliberate hive policy for subagent work
|
|
/// specifically, not a reflection of Anthropic's own recommendation, on the
|
|
/// same "cheaper than you" cost-consciousness the `base:claude-subagents`
|
|
/// skill already asks of `model`. `prompt_file`, when given, becomes
|
|
/// `--append-system-prompt-file` — the subagent's task instructions.
|
|
/// `dir`, when given, becomes `Config::cwd` (e.g. a prepared worktree); `None`
|
|
/// is [`crate::paths::default_cwd`].
|
|
/// Always `--dangerously-skip-permissions --strict-mcp-config --tools` — two
|
|
/// gates covering one half each, neither substituting for the other:
|
|
/// `strict_mcp_config` over **MCP** tools (no ambient discovery, so exactly
|
|
/// what [`crate::mcp_config::build`] renders), `--tools` over **built-in**
|
|
/// ones, via [`hive_sh4re::permissions::subagent_builtin_tools_for`] over the
|
|
/// agent's permissions ([`crate::swarm_models::permissions_now`]), which
|
|
/// documents its one `Bash` exception. `--tools` does not filter `mcp__*`,
|
|
/// so the signal tools are unnamed in it (`docs/4-implementation/agent-tools/subagent.md`).
|
|
///
|
|
/// `signal_url` is what makes `goal_reached`/`need_help` callable at all: a
|
|
/// subagent reaches them over the same streamable-http listener its parent
|
|
/// uses, on a route that serves those two tools and nothing else, so being
|
|
/// able to say "I'm done" never carries the ability to spawn a subagent of
|
|
/// its own. It is also *this* session's own URL — minted per run by
|
|
/// [`super::State::mint_signal_url`] and written only into this session's config
|
|
/// file — which is where the signal tools get the identity they no longer
|
|
/// ask the caller for. `None` — which only `status` passes, building a
|
|
/// config purely to resolve the session store — leaves the surface out
|
|
/// entirely.
|
|
pub(super) fn build_config(
|
|
name: &str,
|
|
model: Option<String>,
|
|
effort: Option<String>,
|
|
prompt_file: Option<&str>,
|
|
dir: Option<&str>,
|
|
signal_url: Option<&str>,
|
|
) -> Config {
|
|
let tools = hive_sh4re::permissions::subagent_builtin_tools_for(
|
|
&crate::swarm_models::permissions_now(),
|
|
)
|
|
.join(",");
|
|
// Refuse to spawn on an empty `--tools` rather than reason about what it
|
|
// would do: what an empty value means is disputed and depends on the
|
|
// installed claude release (see `builtin_tools_for`). Nothing here wants
|
|
// "a subagent with no built-ins" anyway, so an empty resolution is a bug
|
|
// either way, and failing on it is safe under every reading.
|
|
assert!(
|
|
!tools.is_empty(),
|
|
"resolved an empty --tools value — a subagent is never spawned on one, \
|
|
since what an empty value grants is release-dependent"
|
|
);
|
|
let mut extra_args = vec![
|
|
"--dangerously-skip-permissions".to_owned(),
|
|
"--tools".to_owned(),
|
|
tools,
|
|
];
|
|
if let Some(path) = prompt_file {
|
|
extra_args.push("--append-system-prompt-file".to_owned());
|
|
extra_args.push(path.to_owned());
|
|
}
|
|
Config {
|
|
model,
|
|
effort: Some(effort.unwrap_or_else(|| "medium".to_owned())),
|
|
cwd: dir.map(PathBuf::from).or_else(crate::paths::default_cwd),
|
|
mcp_config: crate::mcp_config::build(name, signal_url),
|
|
strict_mcp_config: true,
|
|
extra_args,
|
|
env: vec![(
|
|
"OTEL_RESOURCE_ATTRIBUTES".to_owned(),
|
|
subagent_otel_attrs(name),
|
|
)],
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Which file `--append-system-prompt-file` is pointed at, if any, and the
|
|
/// prompt this turn actually opens with, for one spawn.
|
|
///
|
|
/// **The task is always the turn, never a standing system prompt — with or
|
|
/// without a role.** A task baked into the system prompt re-asserts itself
|
|
/// as an instruction on every later turn of the session (`continue`,
|
|
/// `goal`), not just the one the caller wrote it for; the system prompt is
|
|
/// the subagent's standing identity, not a one-shot channel. So the task
|
|
/// instructions (`prompt_file`) are always read and folded ahead of
|
|
/// `trigger` instead, the one channel that has always carried them.
|
|
///
|
|
/// No role: that folded trigger is the whole story — `None` comes back for
|
|
/// the system-prompt file, since there is no role text to put there.
|
|
/// A role: its text, alone, becomes the system-prompt file under
|
|
/// [`crate::paths::harness_dir`] — nothing about the task reaches it.
|
|
/// Per session, like the generated `--mcp-config` beside it, so two
|
|
/// concurrent `start`s never share a system-prompt file.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Unreadable task instructions, or (with a role) a harness dir that
|
|
/// cannot be written. Both refuse the spawn rather than dropping either
|
|
/// half — see `docs/4-implementation/agent-tools/subagent.md`.
|
|
pub(super) fn system_prompt_and_trigger(
|
|
name: &str,
|
|
role: Option<&str>,
|
|
prompt_file: &str,
|
|
trigger: &str,
|
|
) -> anyhow::Result<(Option<PathBuf>, String)> {
|
|
// `harness_dir` panics outside a container (`HYPERHIVE_HARNESS_DIR`
|
|
// unset) — read lazily, only when a role means a system-prompt file
|
|
// actually needs somewhere to land. `compose_prompt` only touches `dir`
|
|
// inside its `Some(role)` branch, so a no-role call never forces this,
|
|
// in tests or otherwise.
|
|
let dir = role.map_or_else(PathBuf::new, |_| crate::paths::harness_dir());
|
|
compose_prompt(&dir, name, role, prompt_file, trigger)
|
|
}
|
|
|
|
/// [`system_prompt_and_trigger`] with the harness dir as an argument rather
|
|
/// than an ambient container-only environment read — the split a test uses
|
|
/// to control where the role-only file lands.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// See [`system_prompt_and_trigger`].
|
|
pub(super) fn compose_prompt(
|
|
dir: &Path,
|
|
name: &str,
|
|
role: Option<&str>,
|
|
prompt_file: &str,
|
|
trigger: &str,
|
|
) -> anyhow::Result<(Option<PathBuf>, String)> {
|
|
let task = std::fs::read_to_string(prompt_file).map_err(|e| {
|
|
anyhow::anyhow!("reading the task instructions at {prompt_file} failed: {e}")
|
|
})?;
|
|
let trigger = format!("{}\n\n{trigger}", task.trim_end());
|
|
let Some(role) = role else {
|
|
return Ok((None, trigger));
|
|
};
|
|
let path = render_role_prompt(dir, name, role)?;
|
|
Ok((Some(path), trigger))
|
|
}
|
|
|
|
/// Write `name`'s system-prompt file — `role`'s text, alone — into `dir`,
|
|
/// returning the file's path. Split from [`compose_prompt`] so the
|
|
/// directory is an argument rather than an ambient container-only
|
|
/// environment read.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// A `dir` that cannot be created or written.
|
|
fn render_role_prompt(dir: &Path, name: &str, role: &str) -> anyhow::Result<PathBuf> {
|
|
std::fs::create_dir_all(dir)
|
|
.map_err(|e| anyhow::anyhow!("creating {} failed: {e}", dir.display()))?;
|
|
let path = dir.join(format!("subagent-system-prompt-{name}.md"));
|
|
std::fs::write(&path, role)
|
|
.map_err(|e| anyhow::anyhow!("writing {} failed: {e}", path.display()))?;
|
|
Ok(path)
|
|
}
|
|
|
|
/// The [`SessionStore`] a subagent's turn actually runs against — same
|
|
/// resolution `hive_claude::Claude` itself uses, so a lookup here can't
|
|
/// disagree with what the driver does a moment later.
|
|
pub(super) fn build_store(config: &Config) -> std::io::Result<SessionStore> {
|
|
Ok(SessionStore::new(
|
|
config.resolved_claude_home()?,
|
|
config.resolved_cwd()?,
|
|
))
|
|
}
|
|
|
|
/// The session id a resume of `name` hands `--resume`: the live session
|
|
/// titled `name` in `config`'s own project dir.
|
|
///
|
|
/// claude resolves a *title* across the project dirs of every git worktree
|
|
/// of the repo, and refuses when more than one matches; `start` archives only
|
|
/// in its own cwd, so a name reused under a sibling worktree's `dir` stays
|
|
/// live there. An id names one file, and a name is never handed over in its
|
|
/// place: a session that is not in this dir is refused, not looked for
|
|
/// elsewhere.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// A store that cannot be resolved, or a project dir with no session titled
|
|
/// `name`; either message names what was searched.
|
|
pub(super) fn resume_target(config: &Config, name: &str) -> anyhow::Result<String> {
|
|
let store = build_store(config)
|
|
.map_err(|e| anyhow::anyhow!("no session titled `{name}` can be looked for: {e}"))?;
|
|
store
|
|
.find_by_title(name)
|
|
.and_then(|path| path.file_stem().map(|id| id.to_string_lossy().into_owned()))
|
|
.ok_or_else(|| {
|
|
anyhow::anyhow!(
|
|
"no session titled `{name}` under {}; pass the `dir` the session was started in",
|
|
store.project_dir().display()
|
|
)
|
|
})
|
|
}
|