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

432 lines
20 KiB
Rust

//! What a caller asks about a run: `status`, `interrupt`, their wording, and the
//! todo a turn's end pushes.
use super::{
Duration, Occupancy, PoisonError, Refusal, Slot, State, StopReason, SubagentRuntime, TurnEnd,
acp_session_file, build_config, build_store, describe_signal, validate_name,
};
/// Report whether `name` is currently running — a zero-cost check that
/// never launches a process, unlike `continue`. Distinguishes running,
/// starting (reserved, not yet a confirmed spawn — see `State`'s doc),
/// killed (its last turn died on a signal), each of the four ways a goal
/// run stops, idle (a session exists, its last turn finished, nothing is in
/// flight), and no such session at all.
///
/// A *running* answer also carries how long since that turn last produced
/// output, which is the part of this answer a caller can act on: "running"
/// describes a wedged child and a busy one identically, and the age
/// separates them (see `State`'s `last_event` doc).
///
/// A goal-continued session carries `turn N of M` alongside that, in every
/// state. With the age, it is what lets a caller tell *working* from
/// *wedged* from *out of turns* off one answer, without reaching for `ps`
/// or reading any file.
///
/// # Errors
///
/// An invalid name, or no session — running, killed, stopped or on disk —
/// under `name`.
pub fn status(state: &State, name: &str, dir: Option<&str>) -> anyhow::Result<String> {
validate_name(name)?;
// Read-only: an explicit `dir` here is a one-off "check this other
// directory's session" per this fn's own doc, not a new remembered
// default — `peek_dir` resolves the same way but never writes.
let dir = state.peek_dir(name, dir);
let facts = StatusFacts {
occupancy: state.occupancy(name),
killed: state.killed_by(name),
last_event_age: state.last_event_age(name),
turns: state.turns(name),
stop: state.stop_reason(name),
..StatusFacts::new(name)
};
// Nothing on disk to look for while something is tracked in memory —
// those states answer on their own, and the store read is the only
// expensive part of this call. A recorded stop reason counts: it is
// proof this daemon ran the session, which is what the lookup asks.
let session_exists =
if facts.occupancy.is_none() && facts.killed.is_none() && facts.stop.is_none() {
if let SubagentRuntime::Acp { sessions, .. } = &state.runtime {
acp_session_file(sessions, name).exists()
} else {
// No signal surface in this config: it exists only to resolve
// the session store, and rendering a subagent's MCP config for
// a read-only status check would be writing a file for nobody.
let config = build_config(name, None, None, None, dir.as_deref(), None);
build_store(&config)?.find_by_title(name).is_some()
}
} else {
false
};
describe_status(&StatusFacts {
session_exists,
..facts
})
}
/// The liveness clause appended to a *running* answer, and the whole point
/// of recording the timestamp: an age in seconds a caller can read a verdict
/// off directly, rather than one it has to go and measure itself with `ps`
/// and CPU-time deltas.
///
/// Deliberately just the number now — the full "seconds means working,
/// minutes means wedged, resets each turn" explanation used to repeat here
/// on every single call. It already lives in the `status` tool description
/// and in `docs/4-implementation/agent-tools/subagent.md`'s "Telling working from wedged"
/// section, so restating it in a line meant to be skimmed, possibly several
/// times a minute, was pure repetition.
///
/// Empty when there's no age to report — a turn that ended between `status`
/// reading `running` and reading the clock. Saying nothing is right there:
/// the alternative is an age that describes a turn which has already
/// finished, which reads as a stall that never happened.
fn describe_liveness(age: Option<Duration>) -> String {
match age {
None => String::new(),
Some(age) => format!(" Last event {}s ago.", age.as_secs()),
}
}
/// The progress sentence a goal-continued session carries in every state:
/// which turn of its budget it is on. Empty for a session with no goal,
/// which has no budget to be partway through.
///
/// On a *running* answer this is the turn in flight; on a stopped one it is
/// the turn it stopped on — the same number either way, since the counter
/// only advances when the loop decides to spend another turn.
fn describe_turns(turns: Option<(u32, u32)>) -> String {
match turns {
None => String::new(),
Some((turn, max_turns)) => format!(" Turn {turn} of {max_turns}."),
}
}
/// Everything `status` gathers, as one value — seven separate parameters
/// read as noise at both the call site and the test sites, and every one of
/// them is a fact about the same session.
pub(super) struct StatusFacts<'a> {
pub(super) name: &'a str,
pub(super) occupancy: Option<Occupancy>,
pub(super) killed: Option<i32>,
pub(super) session_exists: bool,
pub(super) last_event_age: Option<Duration>,
pub(super) turns: Option<(u32, u32)>,
pub(super) stop: Option<StopReason>,
}
impl<'a> StatusFacts<'a> {
/// The nothing-known baseline for `name`: no process, no records, no
/// session. Both the real gathering in `status` and the tests build on
/// it, so neither has to spell out the fields it isn't exercising.
pub(super) fn new(name: &'a str) -> Self {
Self {
name,
occupancy: None,
killed: None,
session_exists: false,
last_event_age: None,
turns: None,
stop: None,
}
}
}
/// Render `status`'s answer from the facts it gathers. Split out from the
/// gathering so the killed-versus-idle distinction — and the liveness age,
/// the turn counter and each stop reason — are exercisable without a real
/// spawn, a real signal, a real stream of events and a real on-disk claude
/// session.
///
/// A recorded kill outranks both the stop reason and the on-disk session:
/// the session file exists either way and a stop reason may be left over
/// from the signal a subagent raised just before something killed it, so
/// neither can tell a killed turn from a finished one. The kill can.
///
/// Every answer is self-contained — it names the one state the caller got
/// and what to do next — because the tool description deliberately doesn't
/// enumerate the state space (the operator's ruling on this surface:
/// describe the tool, explain the state when returning it). Keep the split:
/// a terser answer here has nowhere left to be explained from.
pub(super) fn describe_status(facts: &StatusFacts<'_>) -> anyhow::Result<String> {
let name = facts.name;
let turns = describe_turns(facts.turns);
match facts.occupancy {
Some(Occupancy::Running) => {
return Ok(format!(
"subagent `{name}` is running — its turn is still in flight, so there's nothing \
to do but let it work: the daemon pushes a todo when the run ends, or \
`interrupt` it if you want it stopped early.{turns}{}{}",
describe_liveness(facts.last_event_age),
describe_pending_signal(facts.stop.as_ref()),
));
}
Some(Occupancy::Starting) => {
return Ok(format!(
"subagent `{name}` is starting — the name is claimed but no process is confirmed \
under it yet, either because a `start`/`continue` hasn't spawned one or because \
a goal run is between turns. Normally over in well under a second: check again \
shortly rather than starting anything else under this name.{turns}"
));
}
Some(Occupancy::Stopping) => {
return Ok(format!(
"subagent `{name}` is stopping — `interrupt` sent it SIGINT and its process \
hasn't exited yet. The name stays claimed until it does, so `start` and \
`continue` are refused meanwhile. Nothing escalates past that SIGINT: one that \
never exits needs killing by hand.{turns}{}",
describe_liveness(facts.last_event_age),
));
}
None => {}
}
if let Some(signal) = facts.killed {
return Ok(format!(
"subagent `{name}` was killed — its last turn died on {}, so its work stopped \
wherever it had got to rather than finishing. `continue` still resumes it, but \
whatever it was told to do is unfinished: check what it actually left behind before \
trusting it.{turns}",
describe_signal(signal)
));
}
if let Some(stop) = &facts.stop {
return Ok(describe_stopped(name, stop, &turns));
}
if facts.session_exists {
Ok(format!(
"subagent `{name}` is idle — its session exists, its last turn ended on its own \
rather than being cut off, and nothing is in flight: that turn's own todo says how \
it went, and `continue` gives it another.{turns}"
))
} else {
anyhow::bail!(
"no subagent named `{name}` exists — nothing is running under that name and there's \
no session on disk to resume, so `start` is what creates one (check the name if you \
expected something here)."
)
}
}
/// The note a *running* answer carries when the subagent has already raised
/// a stop signal for the turn still in flight. Without it a parent polling
/// `status` would read plain "running" for the whole stretch between the
/// subagent saying it is blocked and its turn actually ending — the one
/// stretch where "it's working, leave it alone" is the wrong conclusion.
fn describe_pending_signal(stop: Option<&StopReason>) -> String {
match stop {
None | Some(StopReason::Done | StopReason::TurnCap { .. }) => String::new(),
Some(stop) => format!(
" It has already signalled how this run ends — {} — so this is its last turn.",
stop.sentence()
),
}
}
/// The answer for a session whose run has stopped, one per [`StopReason`].
/// Each names the state, why the continuation stopped, and what `continue`
/// would do about it — and the `GoalReached` one is deliberately the least
/// reassuring of them, because it is the one a caller is most likely to
/// read as "finished successfully" when it means "said so".
fn describe_stopped(name: &str, stop: &StopReason, turns: &str) -> String {
match stop {
StopReason::Done => format!(
"subagent `{name}` is idle — its session exists, its last turn ended on its own \
rather than being cut off, and nothing is in flight: that turn's own todo says how \
it went, and `continue` gives it another.{turns}"
),
StopReason::GoalReached(msg) => format!(
"subagent `{name}` stopped: it reported its goal reached{}. Nothing is in flight and \
no further goal turn will start.{turns} That report is the subagent's own claim, not \
a verification of anything — read the diff and whatever gate the work was supposed \
to pass before you treat the goal as met, exactly as you would a build report saying \
the tests passed.",
msg.as_deref()
.map_or_else(String::new, |m| format!(": {m}"))
),
StopReason::NeedHelp(msg) => format!(
"subagent `{name}` is BLOCKED and needs help: {msg}. It called `need_help`, which \
stopped its goal continuation, and nothing is in flight — it stays blocked until you \
answer it. `continue` is how you answer: give it what it asked for as the next \
turn's prompt."
),
StopReason::TurnCap { turns: spent } => format!(
"subagent `{name}` ran out of turns — the harness limit of {spent} was reached and it \
never reported its goal reached, so the work stopped wherever it had got to rather \
than finishing.{turns} Check what it actually left behind; `continue` gives it a \
fresh allowance if carrying on is worth it."
),
StopReason::Cancelled => format!(
"subagent `{name}` was CANCELLED — someone called `interrupt` on it, which stopped \
the run and not merely the turn that was in flight, so nothing further will start \
on its own.{turns} Its work stopped wherever it had got to: check what it left \
behind before acting on it. `continue` restarts it, with a fresh turn allowance."
),
}
}
/// Stop `name`'s running turn: SIGINT to claude's process group (see
/// `hive_claude::Cancel::cancel`), or `session/cancel` on ACP. Nothing
/// escalates to SIGKILL: each command claude's Bash tool starts leads its
/// own session, and only claude shutting down on SIGINT stops it.
///
/// Returns without waiting. A claude turn's name stays claimed as
/// `Slot::Stopping` until the turn's own `finish_turn` clears it, so no
/// second claude starts on the session while the first is winding down.
///
/// It stops the goal run, not just the turn, by **recording
/// `StopReason::Cancelled`**: claude answers SIGINT by emitting its
/// terminal `result` event and exiting 0, which is `TurnEnd::Complete`, so
/// only the recorded reason, which `plan_after_turn` checks before the
/// goal, keeps the loop from re-prompting. It is written while the
/// `running` lock is held, so a turn that ends on its own in between still
/// finds it.
///
/// # Errors
///
/// An invalid name, nothing tracked under `name`, nothing to signal right
/// now (a spawn or ACP turn not yet live, or a goal run between turns; the
/// reservation is put back, so a concurrent `start`/`continue` is still
/// refused), or a claude already signalled and not yet exited.
pub fn interrupt(state: &State, name: &str) -> anyhow::Result<String> {
validate_name(name)?;
let mut running = state.running.lock().unwrap_or_else(PoisonError::into_inner);
let mut claimed = "";
match running.remove(name) {
None => anyhow::bail!("no subagent named `{name}` is currently running"),
Some(Slot::Starting) => {
running.insert(name.to_owned(), Slot::Starting);
tracing::info!(name, "interrupt refused: no process is tracked yet");
return Err(still_starting(name));
}
Some(Slot::Stopping) => {
running.insert(name.to_owned(), Slot::Stopping);
anyhow::bail!(
"subagent `{name}` was already interrupted and its process hasn't exited yet — \
`status` says when it has"
);
}
// `stop()` is `false` when no turn is in flight (an ACP agent not
// prompted yet, or a turn just ended), and then nothing was stopped.
// The stop goes in before the signal and comes out under the same
// `stops` lock, so `plan_after_turn` never reads a cancel that
// didn't happen.
Some(Slot::Running(stop)) => {
let mut stops = state.stops.lock().unwrap_or_else(PoisonError::into_inner);
let prior = stops.insert(name.to_owned(), StopReason::Cancelled);
if !stop.stop() {
match prior {
Some(prior) => stops.insert(name.to_owned(), prior),
None => stops.remove(name),
};
drop(stops);
running.insert(name.to_owned(), Slot::Running(stop));
return Err(still_starting(name));
}
drop(stops);
if matches!(state.runtime, SubagentRuntime::Claude) {
running.insert(name.to_owned(), Slot::Stopping);
claimed = " The name stays claimed until claude has exited; `status` says \
`stopping` until then.";
}
}
}
Ok(format!(
"interrupt sent to subagent `{name}` — the run is cancelled, not just the turn that was \
in flight, so no further goal turn will start. `continue` is what restarts it, with a \
fresh turn allowance.{claimed}"
))
}
/// `start`'s and `continue`'s refusal for a name `reserve_under` would not
/// claim.
pub(super) fn refused(state: &State, name: &str, refusal: &Refusal, hint: &str) -> anyhow::Error {
match refusal {
Refusal::Taken => name_taken(state, name, hint),
Refusal::AtCap { cap: 0, .. } => anyhow::anyhow!(
"subagents are disabled for this agent: the cap is 0 (set in swarm-ui → this \
agent → inference)"
),
Refusal::AtCap { running, cap } => anyhow::anyhow!(
"{running} {} running, cap is {cap} (set in swarm-ui → this agent → \
inference) — wait for one to finish, or `interrupt` one",
if *running == 1 {
"subagent"
} else {
"subagents"
}
),
}
}
/// `start`'s and `continue`'s refusal for a name `reserve_under` found claimed:
/// `hint` says what to do about a live session, and an interrupted one that
/// hasn't exited yet gets its own answer.
fn name_taken(state: &State, name: &str, hint: &str) -> anyhow::Error {
if state.occupancy(name) == Some(Occupancy::Stopping) {
anyhow::anyhow!(
"subagent `{name}` is stopping — it was interrupted and its process hasn't exited \
yet; the name is free once it has (`status` says when)"
)
} else {
anyhow::anyhow!("subagent `{name}` is already running — {hint}")
}
}
/// `interrupt`'s refusal for a name that is claimed but has nothing to
/// signal yet.
fn still_starting(name: &str) -> anyhow::Error {
anyhow::anyhow!(
"subagent `{name}` is still starting — not yet confirmed running, try again shortly"
)
}
/// Push `name`'s one-shot end-of-turn todo. Best-effort: a connect/write
/// failure is logged and swallowed, matching every other in-agent-socket
/// producer in this codebase — there's no retry queue to fall back to, and
/// the caller has already moved on by the time this fires.
pub(super) async fn push_turn_end_todo(
socket: &std::path::Path,
name: &str,
end: &TurnEnd,
stop: Option<&StopReason>,
) {
let req = hive_agent_sock::Request::UpsertTodo {
subsystem: "subagent".to_owned(),
key: Some(name.to_owned()),
summary: turn_end_summary(name, end, stop),
source: None,
reopen_if_acked: false,
};
if let Err(e) = hive_sock_client::notify(socket, &req, hive_sock_client::Retry::None).await {
tracing::warn!(name, error = ?e, "subagent: end-of-turn todo push failed");
}
}
/// The todo text for a run that has ended. A killed turn deliberately does
/// not use the "finished" wording the other two share: this todo is the only
/// thing the owning agent is shown without asking, so it has to read as the
/// interruption it is rather than as one more completed subagent.
///
/// A `stop` **extends** that message, it never replaces it. Both halves are
/// load-bearing and neither substitutes for the other: the turn's own end is
/// what the daemon observed, the stop reason is why the run went no further
/// — and for `GoalReached` that second half is a claim, which would read as
/// a verdict if it were allowed to stand where the observed end belongs.
/// `StopReason::Done` adds nothing, since "there was no goal" is exactly
/// what the unextended message already describes.
pub(super) fn turn_end_summary(name: &str, end: &TurnEnd, stop: Option<&StopReason>) -> String {
let base = match end {
TurnEnd::Complete => format!("subagent `{name}` finished: turn complete"),
TurnEnd::Failed(e) => format!("subagent `{name}` finished: {e}"),
TurnEnd::Killed { signal } => format!(
"subagent `{name}` was KILLED mid-turn ({}) — it did not finish, and its work stopped \
wherever it had got to. Check what it left behind before you act on it; `continue` \
resumes the session if you want it carried on.",
describe_signal(*signal)
),
};
match stop {
None | Some(StopReason::Done) => base,
Some(stop) => format!("{base} — and the run stopped there: {}", stop.sentence()),
}
}