Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/hive-subagent-mcp/src/session.rs

413 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The claude-facing half of this daemon: spawn a subagent turn, keep giving
//! it turns until it says it's done or runs out of them, track it only while
//! it's alive, and push exactly one todo when the whole run stops — saying
//! whether it finished, was killed, or stopped for one of the reasons the
//! continuation loop records.
//!
//! **No task files, no restart recovery.** The daemon's only state is an
//! in-memory `name -> Slot` map (see `State`'s own doc for the rest of the
//! maps, and `Slot`'s for what each state of a claimed name means) — all of
//! it living for exactly as long as the process is. A daemon restart means
//! whatever was running gets killed
//! with it (`tokio`'s own child-process drop semantics), not adopted, and
//! the remembered `dir` is gone too. The durable record of a subagent's
//! existence is `hive_claude::SessionStore` — claude's own on-disk
//! session, found again by name. `continue` is how a caller reattaches to
//! it, whether that's "give it a new turn" or "the daemon restarted and I
//! want to pick this back up" — after a restart, re-supply `dir` once if
//! the session isn't in the agent's work dir (the default when it exists).
//!
//! **A running turn is not necessarily a working turn.** A wedged child
//! satisfies "running" as fully as a busy one, so every line of the child's
//! streams bumps `last_event_at` (`LivenessSink`) and `status` reports its
//! age — the timestamp says the child is alive, never what it said. What it
//! said goes to the swarm as the subagent's terminal (`crate::swarm_term`).
//!
//! **`continue` refuses a name with no session in the `dir` in effect
//! (`resume_target`), and waits for the driver's answer on the rest.** A
//! turn that still misses is the call's own error, naming the directory
//! searched (`classify_end`), within `RESUME_GRACE`. See
//! `docs/4-implementation/agent-tools/subagent.md`.
//! **One `start` can be more than one turn.** With a `goal` set, a turn that
//! ends without a stop signal is followed by another re-prompting the
//! subagent toward it, up to `max_turns` (default five). The loop lives in
//! `spawn_and_track`'s background task, so both tool-call contracts are
//! unchanged and only one todo is pushed, when the *run* stops. No goal
//! means what it always did: one turn, one todo.
//!
//! **A subagent's own stop signals are labels, not gates.** `goal_reached`
//! and `need_help` stop the loop and extend the done message; neither
//! verifies anything. `goal_reached` is self-reported by a subagent that has
//! just been re-prompted with "you have not reached the goal", which is
//! exactly the incentive to claim it — the same failure class as a build
//! report asserting "done, tests pass". Everything here treats it as a claim
//! about the work, never as the work, and says so. See
//! `docs/4-implementation/agent-tools/subagent.md`.
//! **A subagent cannot say who it is.** Neither signal tool takes a session
//! name. Each run is minted an unguessable token at spawn
//! (`State::mint_signal_url`), the URL carrying it is written into that one
//! subagent's own `--mcp-config`, and the route resolves it back to a session
//! before dispatching — so the identity of a signal is a property of the
//! endpoint it arrived on, not a field its sender filled in. An unminted or
//! revoked token is a 404. The `occupancy()` liveness check that used to
//! stand here instead was a guard on an assertion: two siblings running
//! concurrently could each satisfy it for the other's name.
//! **A killed turn is not a finished turn.** A child that died on a signal
//! arrives as a `hive_claude::Error::Exit` carrying its `ExitStatus`, so the
//! "how" is there to be read: `classify_end` takes the signal out of it and
//! `State::finish_turn` remembers it against the name, which is what lets
//! `status`, the end-of-turn todo and `continue`'s own reply all say the
//! session was killed rather than let it read as finished. See
//! `docs/4-implementation/agent-tools/subagent.md`.
//!
//! **No mid-turn compaction.** Building on `hive_claude::Claude::spawn` +
//! `RunningClaude::wait` directly (not `InfiniteSession::run`) is what makes
//! `interrupt` possible at all — `InfiniteSession` has no cancel handle to
//! reach in from the outside, only `RunningClaude::cancel_handle` does. The
//! trade: this daemon doesn't get `InfiniteSession`'s reactive-compact-on-
//! overflow or proactive-checkpoint-compact for free: a turn that overflows
//! the context window surfaces as a plain `Error::PromptTooLong` to the
//! caller instead of self-healing. Subagents are meant to be bounded,
//! single-batch work (see the `base:claude-subagents` skill), not sessions
//! long-lived enough to need in-place compaction — a real follow-up if that
//! assumption stops holding, not shipped here.
//! **A subagent runs on its parent agent's runtime.** `State::runtime` is
//! read once at startup from the same `HIVE_RUNTIME`/`HIVE_ACP_*` variables
//! the harness reads (`hive_runtime::RuntimeSpec`), forwarded onto this unit
//! by `nix/agent-modules/mcp.nix`. On claude, everything above holds as
//! written. On ACP, each run drives one `hive_runtime::AcpRuntime` whose
//! session id is kept in a per-name file under the harness dir
//! (`acp_session_file`): the agent process lives for one run, `interrupt`
//! sends `session/cancel` rather than a signal, a failed turn is `Failed`
//! and never `Killed`, and `model`/`effort` apply only as values the ACP
//! session offers.
//! **Where things are.** This file keeps the types every part shares (`Slot`,
//! `StopReason`, `TurnEnd` and the rest) and re-exports the public calls:
//!
//! | module | holds |
//! | --- | --- |
//! | `state` | `State`: the claims, goals, stop reasons and signal tokens per name |
//! | `config` | the model list and the swarm cap, the claude config, prompts, the session store |
//! | `run` | `start`, `continue_`, the spawns on either runtime and the loop over a run's turns |
//! | `goal` | the goal prompts, `goal_reached`, `need_help` and the report file |
//! | `status` | `status`, `interrupt`, their wording, and the todo a turn's end pushes |
//! | `tests` | the unit tests, split by the same topics |
mod config;
mod goal;
mod run;
mod state;
mod status;
use self::{
config::{
available_models, build_config, build_store, check_model, model_list, resume_target,
subagent_cap, system_prompt_and_trigger,
},
goal::{continuation_prompt, goal_briefing, write_stop_to_report},
run::{acp_session_file, exit_status},
status::{push_turn_end_todo, refused},
};
pub use self::{
goal::{goal_reached, need_help},
run::{StartRequest, continue_, start},
state::State,
status::{interrupt, status},
};
use std::collections::HashMap;
use std::os::unix::process::ExitStatusExt as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use hive_agent_sock::run_cgroup::{self, RunCgroup, RunCgroups};
use hive_claude::{Attach, Claude, Config, SessionStore};
use hive_runtime::{
AcpCommand, AcpRuntime, PermissionAsk, PermissionPolicy, Runtime as _, RuntimeSpec, TurnStop,
};
use hive_types::Permission;
use swarm_wire::agent_inference::AgentInference;
use tokio::sync::oneshot;
use crate::swarm_term::Output;
/// How long a `continue` holds its tool call open waiting to find out
/// whether the resume landed. A cap, not a delay: both real outcomes settle
/// it well inside this, and it is only ever reached by a child that neither
/// speaks nor exits.
///
/// Measured rather than guessed, on this box, running the driver's own
/// invocation (`--print --verbose --output-format stream-json --resume
/// <missing>`) against a session name that matches nothing: 14 runs,
/// 550–1087 ms wall from spawn to exit. A healthy turn's first stream event
/// lands at roughly 500 ms, so the two paths finish within ~100 ms of each
/// other and neither waits on this bound. Five seconds is ~4.6× the slowest
/// miss observed — headroom for a loaded box starting node far slower than
/// any of those runs, while still bounding the one case that reaches it.
const RESUME_GRACE: Duration = Duration::from_secs(5);
/// How many turns a goal-continued session gets before the harness stops it
/// itself. Five is the number the feature was specified with, not one tuned
/// here: enough for a bounded batch to converge, short enough that a
/// subagent which has misunderstood its goal can't re-attempt it forever on
/// someone else's budget. `start`'s `max_turns` overrides it per session,
/// which is where a caller that genuinely needs a longer leash says so.
const DEFAULT_MAX_TURNS: u32 = 5;
/// Why a session's turn continuation stopped — recorded per name, reported
/// by `status`, appended to the end-of-turn todo, and written into the
/// session's report file when it has one.
///
/// Only ends of the *continuation loop* live here. A turn that was killed or
/// that failed outright never reaches the loop's decision at all: those keep
/// the records they already had (`State::killed`, the todo's own killed
/// wording), and giving them a second home here would have handed `status`
/// two rival answers for one fact.
#[derive(Debug, Clone, PartialEq, Eq)]
enum StopReason {
/// The turn ended and there was no goal to continue toward — the
/// single-turn shape every session had before continuation existed.
Done,
/// The subagent called `goal_reached`. **Self-reported.** It records
/// that the subagent claimed the goal, never that the goal was met.
GoalReached(Option<String>),
/// The subagent called `need_help`: it can't proceed, and says why.
NeedHelp(String),
/// `turns` turns ran and the goal was never reported reached.
TurnCap { turns: u32 },
/// An operator called `interrupt`. Unlike the four above, this is
/// recorded from *outside* the run, by `interrupt` itself, before the
/// signal is sent.
///
/// It has to be, and that is the whole of it: `interrupt`'s
/// default is SIGINT, and claude handles SIGINT by writing its terminal
/// `result` event and **exiting 0**. An exit of zero is
/// `TurnEnd::Complete`, so the killed-turn early return in
/// `spawn_and_track` never fires and the loop re-prompts a run the
/// operator had just asked to stop. Recording the reason makes the
/// cancel a fact about the *run* rather than an inference from how its
/// child happened to die.
Cancelled,
}
impl StopReason {
/// The one sentence that says why, shared by the todo extension and the
/// report-file line so a parent reading either sees the same words.
///
/// `GoalReached` carries its "self-reported" caveat in the sentence
/// itself rather than leaving it to whichever surface renders it: the
/// caveat is the load-bearing half of that claim, and a surface that
/// forgot to add it would read as verification.
fn sentence(&self) -> String {
match self {
Self::Done => "its turn ended and there was no goal to continue toward".to_owned(),
Self::GoalReached(msg) => {
let said = msg
.as_deref()
.map_or_else(String::new, |m| format!(": {m}"));
format!(
"the subagent reported its goal reached{said} — self-reported, not verified, \
so read what it actually changed before acting on it"
)
}
Self::NeedHelp(msg) => {
format!("the subagent called `need_help` and can't proceed: {msg}")
}
Self::TurnCap { turns } => format!(
"the harness turn limit was reached ({turns} turns) without the goal ever being \
reported reached, so the work stopped where it had got to"
),
Self::Cancelled => "it was interrupted, which cancels the whole run and not just the \
turn that was in flight — its work stopped wherever it had got to"
.to_owned(),
}
}
}
/// How a subagent's turn ended, as far as the daemon can tell from what
/// [`hive_claude::RunningClaude::wait`] returned.
///
/// The distinction that matters is `Killed` vs everything else: a child that
/// died on a signal was cut off mid-turn by something outside this daemon
/// (the kernel's OOM killer, a `systemctl stop`, an operator's `kill`) or by
/// an `interrupt` call here — either way its work stopped wherever it got
/// to, which is not what `Complete` means.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TurnEnd {
/// The turn ran to completion.
Complete,
/// The child was terminated by `signal` instead of exiting on its own.
Killed { signal: i32 },
/// claude exited on its own but did not complete the turn — a
/// recognized sentinel (rate limit, prompt too long, …) or a plain
/// non-zero exit. Carries the message shown to the caller.
Failed(String),
}
/// What a subagent's turns run on.
enum SubagentRuntime {
/// A `claude` process per turn (`hive_claude::Claude::spawn`).
Claude,
/// The parent agent's ACP agent, spawned from `command`, with each
/// name's session id kept in `sessions` (see [`acp_session_file`]).
Acp {
command: AcpCommand,
sessions: PathBuf,
},
}
/// What `running` holds for a claimed name.
enum Slot {
/// Claimed, with no process confirmed under it: a `start`/`continue`
/// that hasn't spawned yet, or a goal run between turns.
Starting,
/// A turn is in flight, and this is how `interrupt` reaches it.
Running(TurnStop),
/// `interrupt` has signalled a claude turn and its process hasn't exited
/// yet. Nothing escalates past that SIGINT, so a claude that ignores it
/// stays here until it exits; the turn's own `finish_turn` frees the
/// name.
Stopping,
}
/// Which [`Slot`] a claimed name is in, without its cancel handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Occupancy {
Starting,
Running,
Stopping,
}
/// Why [`State::reserve_under`] claimed nothing.
#[derive(Debug, PartialEq, Eq)]
enum Refusal {
/// The name is already tracked.
Taken,
/// `running` names are tracked, and the swarm caps this agent at `cap`.
AtCap { running: usize, cap: u32 },
}
/// What settled a resumed turn's bounded wait — the one thing `continue`
/// blocks on before it answers.
enum ResumeVerdict {
/// The child emitted a stream event that isn't the turn's own terminal
/// `result` — which a resume that matched nothing never gets as far as
/// emitting. The turn is genuinely running; there is nothing left to
/// wait for.
Underway,
/// The turn ended before that happened. A `Failed` end here is the
/// resume miss `continue` exists to report.
Ended(TurnEnd),
}
/// Write half of [`ResumeVerdict`]'s channel, shared between the turn's sink
/// (which reports `Underway`) and its background task (which reports
/// `Ended`). `Option` because a `oneshot::Sender` is consumed by its single
/// send: whichever side gets there first takes it, and the loser finds
/// nothing left to send on — exactly the "first answer wins" the wait wants.
/// The whole thing is `None` on a `start`, which has no resume to miss.
type VerdictTx = Arc<Mutex<Option<oneshot::Sender<ResumeVerdict>>>>;
/// Report `verdict`, if nothing has been reported yet.
///
/// Returns `true` only when this call both won that race *and* found a
/// receiver still listening — i.e. the verdict genuinely reached a
/// `continue` that is about to act on it. The background task reads that
/// answer to decide whether its end-of-turn todo would be a second
/// notification for something the caller has already been told to its face.
fn settle(tx: Option<&VerdictTx>, verdict: ResumeVerdict) -> bool {
let Some(tx) = tx else { return false };
let taken = tx.lock().unwrap_or_else(PoisonError::into_inner).take();
taken.is_some_and(|tx| tx.send(verdict).is_ok())
}
/// Name a signal number for a human: `9` reads as `SIGKILL (signal 9)`. Only
/// the three that end a subagent in practice are named — anything else keeps
/// the number, which is still enough to look up.
fn describe_signal(signal: i32) -> String {
match signal {
libc::SIGKILL => "SIGKILL (signal 9)".to_owned(),
libc::SIGTERM => "SIGTERM (signal 15)".to_owned(),
libc::SIGINT => "SIGINT (signal 2)".to_owned(),
other => format!("signal {other}"),
}
}
/// Read how the turn ended out of what the driver returned. A signalled
/// child surfaces as [`hive_claude::Error::Exit`] whose `ExitStatus` has a
/// `signal()` — the driver's own docs point at exactly this check — so the
/// "how" is preserved by the time it reaches here rather than having to be
/// recovered.
///
/// `searched` is the resume lookup's location, present only for a turn that
/// attached with [`Attach::Resume`] (see `searched_location`). A missed
/// resume arrives as [`hive_claude::Error::SessionNotFound`], whose message
/// names the *value* that matched nothing but not the *directory* it was
/// looked for in — and "the session lives in another directory" is the way
/// this actually fails in practice, so the caller gets told where the daemon
/// looked rather than left to conclude the session is gone.
fn classify_end(outcome: hive_claude::Result<()>, searched: Option<&str>) -> TurnEnd {
let Err(error) = outcome else {
return TurnEnd::Complete;
};
if let hive_claude::Error::Exit { status, .. } = &error
&& let Some(signal) = status.signal()
{
return TurnEnd::Killed { signal };
}
if matches!(error, hive_claude::Error::SessionNotFound)
&& let Some(searched) = searched
{
return TurnEnd::Failed(format!("claude error: {error} {searched}"));
}
TurnEnd::Failed(format!("claude error: {error}"))
}
/// Where a `--resume` against `config` would have looked for the session,
/// phrased to append to claude's own not-found message. Both halves come
/// from the same resolution `build_store` and the driver itself use, so this
/// names the directory that was genuinely searched rather than a guess at
/// it. `None` when either half fails to resolve (no `HOME`, a `cwd` that
/// doesn't exist) — an unresolvable location is worse than none, and the
/// underlying error still reaches the caller unadorned.
fn searched_location(config: &Config) -> Option<String> {
let home = config.resolved_claude_home().ok()?;
let cwd = config.resolved_cwd().ok()?;
Some(format!(
"(searched {} for cwd {}; if it was started elsewhere, pass the `dir` it was started in)",
home.display(),
cwd.display()
))
}
/// `plan_after_turn`'s answer: the loop either stops with a reason to
/// report, or has the next turn's prompt ready to spawn against.
#[derive(Debug, PartialEq, Eq)]
enum Continuation {
Stop(StopReason),
Continue { prompt: String },
}
/// A caller-chosen name, validated the same way `hive-bash-mcp`'s task ids
/// are: a single safe [`hive_types::Ident`] segment, which doubles as
/// claude's own `--name`/`--resume` session title.
fn validate_name(name: &str) -> anyhow::Result<()> {
hive_types::Ident::parse(name)
.map(|_| ())
.map_err(|e| anyhow::anyhow!("invalid subagent name {name:?}: {e}"))
}
/// A subagent run's `oom_score_adj`: under memory pressure the kernel takes a
/// bash task (1000) first, then a subagent run, then the agent's own session
/// (-500, `nix/agent-modules/agent-service.nix`).
const RUN_OOM_SCORE_ADJ: i32 = run_cgroup::SUBAGENT_RUN_OOM_SCORE_ADJ;
#[cfg(test)]
mod tests;