Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(command-center): move projection and control logic into tinyagents_session

Steven Enamakel7cfba8af9576
diff --git a/Cargo.lock b/Cargo.lock
index 2e4c357d28..f49132f398 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6483,6 +6483,7 @@ dependencies = [
"serde_json",
"sha2 0.11.0",
"tempfile",
+ "thiserror 2.0.20",
"tinyagents-harness",
"tinytools-agent 0.5.0",
"tokio",
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/control.rs b/crates/openhuman-core/src/agent/orchestration/command_center/control.rs
deleted file mode 100644
index 73883d09e4..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/command_center/control.rs
+++ /dev/null
@@ -1,273 +0,0 @@
-//! Command-center control verbs (issue #3373).
-//!
-//! The read-only projection in [`super::ops`] shows what background agent work
-//! is in flight; these verbs let a reviewer *act* on a single row. Each verb is
-//! a durable transition on the run ledger (`tinyagents_session::run_ledger`):
-//!
-//! - **stop** — cancel a non-terminal run (→ `cancelled`).
-//! - **retry** — re-queue a finished-with-error run (`failed` / `cancelled` /
-//! `interrupted` → `pending`), clearing the stale error + completion time.
-//! - **continue** — answer an `awaiting_user` run so it can resume (→ `running`).
-//! - **follow_up** — record a follow-up instruction against any run, leaving its
-//! status unchanged (mirrors recording a parent→child message).
-//!
-//! These mirror the in-memory [`AgentOrchestrationSession`] control plane
-//! (`close_agent` / `resume_agent` / `follow_up` / `message_agent`) but operate
-//! on the *durable* ledger, so they survive restart and apply to any tracked
-//! run rather than only the children of a live session. They persist the new
-//! status (via [`transition_agent_run_status`], which can clear `error` /
-//! `completed_at` — the upsert path cannot) and append a `run_event` recording
-//! the action for the run's timeline.
-//!
-//! The allowed-transition matrix lives in the pure [`plan_transition`], which is
-//! unit-tested without a database, mirroring [`super::ops::build_view`].
-//!
-//! [`AgentOrchestrationSession`]: crate::agent::orchestration::ops::AgentOrchestrationSession
-//! [`transition_agent_run_status`]: tinyagents_session::run_ledger::transition_agent_run_status
-
-use chrono::{DateTime, Utc};
-use serde_json::json;
-use thiserror::Error;
-
-use crate::config::Config;
-use tinyagents_session::run_ledger::{
- append_run_event, get_agent_run, transition_agent_run_status, AgentRunStatus, RunEventAppend,
-};
-
-use super::ops::project_row;
-use super::types::AgentWorkRow;
-
-/// A control action a reviewer can take on a command-center row.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum ControlVerb {
- /// Cancel an in-flight run.
- Stop,
- /// Re-queue a run that finished with an error.
- Retry,
- /// Answer an `awaiting_user` run so it can resume.
- Continue,
- /// Record a follow-up instruction against a run.
- FollowUp,
-}
-
-impl ControlVerb {
- /// Parse the wire `action` string. Returns `None` for an unknown verb.
- pub fn parse(raw: &str) -> Option<Self> {
- match raw.trim() {
- "stop" => Some(Self::Stop),
- "retry" => Some(Self::Retry),
- "continue" => Some(Self::Continue),
- "follow_up" => Some(Self::FollowUp),
- _ => None,
- }
- }
-
- /// Stable wire string for this verb.
- pub fn as_str(self) -> &'static str {
- match self {
- Self::Stop => "stop",
- Self::Retry => "retry",
- Self::Continue => "continue",
- Self::FollowUp => "follow_up",
- }
- }
-
- /// Whether this verb requires a non-empty user `message`.
- ///
- /// `continue` carries the answer that unblocks an `awaiting_user` run, and
- /// `follow_up` carries the new instruction — both are meaningless empty.
- pub fn requires_message(self) -> bool {
- matches!(self, Self::Continue | Self::FollowUp)
- }
-}
-
-/// Why a control verb could not be applied.
-#[derive(Debug, Error)]
-pub enum ControlError {
- /// No run matched the supplied id.
- #[error("agent run '{0}' not found")]
- RunNotFound(String),
- /// The verb is not legal from the run's current status.
- #[error("'{verb}' is not allowed while run is '{status}'")]
- InvalidTransition {
- verb: &'static str,
- status: &'static str,
- },
- /// The verb requires a message and none was supplied.
- #[error("'{0}' requires a non-empty message")]
- MessageRequired(&'static str),
- /// A durable run-ledger read/write failed.
- #[error(transparent)]
- Storage(#[from] anyhow::Error),
-}
-
-/// Lets `?` carry a run-ledger failure straight into [`ControlError`].
-///
-/// The ledger lives in `tinyagents` and speaks `TinyAgentsError`, while this
-/// module's callers speak `anyhow`. Without this the `#[from] anyhow::Error`
-/// variant does not apply, because `TinyAgentsError` is a distinct type — so
-/// every ledger call in this file would need its own `map_err`.
-impl From<tinyagents_harness::TinyAgentsError> for ControlError {
- fn from(err: tinyagents_harness::TinyAgentsError) -> Self {
- Self::Storage(err.into())
- }
-}
-
-/// The durable status a verb moves a run to, plus the event type to record.
-///
-/// `error` / `completed_at` handling is verb-specific and applied in
-/// [`apply_control`]; only the status move + event name are decided here so the
-/// transition legality stays purely testable.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct ControlPlan {
- target_status: AgentRunStatus,
- event_type: &'static str,
-}
-
-/// Decide whether `verb` is legal from `current` and, if so, where it lands.
-///
-/// Pure: no I/O. The matrix is exhaustive on the verb so a new verb fails to
-/// compile until its transition rule is decided.
-fn plan_transition(
- current: AgentRunStatus,
- verb: ControlVerb,
-) -> Result<ControlPlan, ControlError> {
- let invalid = || ControlError::InvalidTransition {
- verb: verb.as_str(),
- status: current.as_str(),
- };
- match verb {
- // Stop only makes sense while the run is still live.
- ControlVerb::Stop => {
- if current.is_terminal() {
- Err(invalid())
- } else {
- Ok(ControlPlan {
- target_status: AgentRunStatus::Cancelled,
- event_type: "control_stopped",
- })
- }
- }
- // Retry re-queues a run that finished with an error (failed) or was
- // stopped (cancelled / interrupted). A successfully completed run has
- // nothing to retry; a live run is not yet retryable.
- ControlVerb::Retry => match current {
- AgentRunStatus::Failed | AgentRunStatus::Cancelled | AgentRunStatus::Interrupted => {
- Ok(ControlPlan {
- target_status: AgentRunStatus::Pending,
- event_type: "control_retry",
- })
- }
- _ => Err(invalid()),
- },
- // Continue answers a run that is explicitly blocked on the user.
- ControlVerb::Continue => {
- if current == AgentRunStatus::AwaitingUser {
- Ok(ControlPlan {
- target_status: AgentRunStatus::Running,
- event_type: "control_continued",
- })
- } else {
- Err(invalid())
- }
- }
- // Follow-up just records a new instruction; the run keeps its status
- // (you can follow up on a completed run as easily as a running one).
- ControlVerb::FollowUp => Ok(ControlPlan {
- target_status: current,
- event_type: "control_follow_up",
- }),
- }
-}
-
-/// Apply a control verb to one background agent run.
-///
-/// Validates the message requirement, loads the run, checks the transition is
-/// legal for its current status, persists the new status (clearing or setting
-/// `error` / `completed_at` per verb), and appends a `run_event` capturing the
-/// action. Returns the freshly re-projected [`AgentWorkRow`].
-///
-/// Errors: [`ControlError::MessageRequired`] when a message-bearing verb has no
-/// message, [`ControlError::RunNotFound`] for an unknown run id,
-/// [`ControlError::InvalidTransition`] for an illegal move, or
-/// [`ControlError::Storage`] for a ledger failure.
-pub fn apply_control(
- config: &Config,
- run_id: &str,
- verb: ControlVerb,
- message: Option<&str>,
- reason: Option<&str>,
-) -> Result<AgentWorkRow, ControlError> {
- let message = message.map(str::trim).filter(|s| !s.is_empty());
- let reason = reason.map(str::trim).filter(|s| !s.is_empty());
- log::debug!(
- target: "command_center",
- "[command_center] apply_control.entry run_id={run_id} verb={} has_message={} has_reason={}",
- verb.as_str(),
- message.is_some(),
- reason.is_some()
- );
-
- if verb.requires_message() && message.is_none() {
- log::debug!(
- target: "command_center",
- "[command_center] apply_control.message_required run_id={run_id} verb={}",
- verb.as_str()
- );
- return Err(ControlError::MessageRequired(verb.as_str()));
- }
-
- let run = get_agent_run(&config.workspace_dir, run_id)?
- .ok_or_else(|| ControlError::RunNotFound(run_id.to_string()))?;
- let from_status = run.status;
- let plan = plan_transition(from_status, verb)?;
-
- // Verb-specific error / completion handling. The transition op writes both
- // columns verbatim, so `None` clears them.
- let (next_error, next_completed_at): (Option<String>, Option<DateTime<Utc>>) = match verb {
- // Stopping records the optional reason and stamps completion now.
- ControlVerb::Stop => (reason.map(str::to_string), Some(Utc::now())),
- // Re-queuing drops the stale failure reason and completion time.
- ControlVerb::Retry | ControlVerb::Continue => (None, None),
- // Follow-up leaves the run as-is.
- ControlVerb::FollowUp => (run.error.clone(), run.completed_at),
- };
-
- let updated = transition_agent_run_status(
- &config.workspace_dir,
- run_id,
- plan.target_status,
- next_error.as_deref(),
- next_completed_at,
- )?
- .ok_or_else(|| ControlError::RunNotFound(run_id.to_string()))?;
-
- // Record the action on the run's durable timeline.
- append_run_event(
- &config.workspace_dir,
- RunEventAppend {
- run_id: run_id.to_string(),
- event_type: plan.event_type.to_string(),
- payload: json!({
- "verb": verb.as_str(),
- "fromStatus": from_status.as_str(),
- "toStatus": plan.target_status.as_str(),
- "message": message,
- "reason": reason,
- }),
- },
- )?;
-
- log::debug!(
- target: "command_center",
- "[command_center] apply_control.done run_id={run_id} verb={} from={} to={}",
- verb.as_str(),
- from_status.as_str(),
- plan.target_status.as_str()
- );
- Ok(project_row(updated))
-}
-
-#[cfg(test)]
-#[path = "control_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/control_tests.rs b/crates/openhuman-core/src/agent/orchestration/command_center/control_tests.rs
deleted file mode 100644
index e7f686fcc8..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/command_center/control_tests.rs
+++ /dev/null
@@ -1,278 +0,0 @@
-use super::*;
-use serde_json::json;
-use tempfile::TempDir;
-use tinyagents_session::run_ledger::{
- list_recent_run_events, upsert_agent_run, AgentRunKind, AgentRunUpsert, RunEventListRequest,
-};
-
-fn test_config(dir: &TempDir) -> Config {
- let mut config = Config::default();
- config.workspace_dir = dir.path().to_path_buf();
- config.action_dir = dir.path().join("actions");
- config
-}
-
-fn seed_run(config: &Config, id: &str, status: AgentRunStatus) {
- upsert_agent_run(
- &config.workspace_dir,
- AgentRunUpsert {
- id: id.to_string(),
- kind: AgentRunKind::Subagent,
- parent_run_id: None,
- parent_thread_id: Some("thread-1".into()),
- agent_id: Some("researcher".into()),
- status,
- prompt_ref: None,
- worker_thread_id: None,
- checkpoint_path: None,
- checkpoint: None,
- summary: None,
- error: if status == AgentRunStatus::Failed {
- Some("boom".into())
- } else {
- None
- },
- metadata: json!({}),
- started_at: None,
- completed_at: if status.is_terminal() {
- Some(Utc::now())
- } else {
- None
- },
- },
- )
- .unwrap();
-}
-
-// ---- pure planner -----------------------------------------------------
-
-#[test]
-fn parse_round_trips_known_verbs_and_rejects_unknown() {
- for verb in [
- ControlVerb::Stop,
- ControlVerb::Retry,
- ControlVerb::Continue,
- ControlVerb::FollowUp,
- ] {
- assert_eq!(ControlVerb::parse(verb.as_str()), Some(verb));
- }
- assert_eq!(ControlVerb::parse("nonsense"), None);
- assert_eq!(ControlVerb::parse(" stop "), Some(ControlVerb::Stop));
-}
-
-#[test]
-fn message_requirement_is_verb_specific() {
- assert!(ControlVerb::Continue.requires_message());
- assert!(ControlVerb::FollowUp.requires_message());
- assert!(!ControlVerb::Stop.requires_message());
- assert!(!ControlVerb::Retry.requires_message());
-}
-
-#[test]
-fn stop_allowed_only_while_non_terminal() {
- for status in [
- AgentRunStatus::Pending,
- AgentRunStatus::Running,
- AgentRunStatus::AwaitingUser,
- AgentRunStatus::Paused,
- ] {
- let plan = plan_transition(status, ControlVerb::Stop).unwrap();
- assert_eq!(plan.target_status, AgentRunStatus::Cancelled);
- assert_eq!(plan.event_type, "control_stopped");
- }
- for status in [
- AgentRunStatus::Completed,
- AgentRunStatus::Failed,
- AgentRunStatus::Cancelled,
- AgentRunStatus::Interrupted,
- ] {
- assert!(matches!(
- plan_transition(status, ControlVerb::Stop),
- Err(ControlError::InvalidTransition { .. })
- ));
- }
-}
-
-#[test]
-fn retry_allowed_only_from_error_terminals() {
- for status in [
- AgentRunStatus::Failed,
- AgentRunStatus::Cancelled,
- AgentRunStatus::Interrupted,
- ] {
- let plan = plan_transition(status, ControlVerb::Retry).unwrap();
- assert_eq!(plan.target_status, AgentRunStatus::Pending);
- assert_eq!(plan.event_type, "control_retry");
- }
- for status in [
- AgentRunStatus::Pending,
- AgentRunStatus::Running,
- AgentRunStatus::AwaitingUser,
- AgentRunStatus::Paused,
- AgentRunStatus::Completed,
- ] {
- assert!(matches!(
- plan_transition(status, ControlVerb::Retry),
- Err(ControlError::InvalidTransition { .. })
- ));
- }
-}
-
-#[test]
-fn continue_allowed_only_from_awaiting_user() {
- let plan = plan_transition(AgentRunStatus::AwaitingUser, ControlVerb::Continue).unwrap();
- assert_eq!(plan.target_status, AgentRunStatus::Running);
- assert_eq!(plan.event_type, "control_continued");
- for status in [
- AgentRunStatus::Pending,
- AgentRunStatus::Running,
- AgentRunStatus::Paused,
- AgentRunStatus::Completed,
- AgentRunStatus::Failed,
- ] {
- assert!(matches!(
- plan_transition(status, ControlVerb::Continue),
- Err(ControlError::InvalidTransition { .. })
- ));
- }
-}
-
-#[test]
-fn follow_up_keeps_status_from_any_state() {
- for status in [
- AgentRunStatus::Running,
- AgentRunStatus::Completed,
- AgentRunStatus::Failed,
- ] {
- let plan = plan_transition(status, ControlVerb::FollowUp).unwrap();
- assert_eq!(plan.target_status, status);
- assert_eq!(plan.event_type, "control_follow_up");
- }
-}
-
-// ---- ledger-backed apply ---------------------------------------------
-
-#[test]
-fn stop_cancels_a_running_run_and_records_an_event() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::Running);
-
- let row = apply_control(&config, "run-1", ControlVerb::Stop, None, Some("manual")).unwrap();
- assert_eq!(row.status, "cancelled");
- assert_eq!(row.bucket.as_str(), "stopped");
- assert_eq!(row.error.as_deref(), Some("manual"));
-
- let events = list_recent_run_events(
- &config.workspace_dir,
- &RunEventListRequest {
- run_id: "run-1".into(),
- after_sequence: None,
- limit: None,
- },
- )
- .unwrap();
- assert_eq!(events.events.len(), 1);
- assert_eq!(events.events[0].event_type, "control_stopped");
- assert_eq!(events.events[0].payload["toStatus"], "cancelled");
-}
-
-#[test]
-fn retry_requeues_a_failed_run_and_clears_error() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::Failed);
-
- let row = apply_control(&config, "run-1", ControlVerb::Retry, None, None).unwrap();
- assert_eq!(row.status, "pending");
- assert_eq!(row.bucket.as_str(), "working");
- // The stale failure reason is dropped (upsert COALESCE could not do this).
- assert_eq!(row.error, None);
-}
-
-#[test]
-fn continue_resumes_an_awaiting_user_run() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::AwaitingUser);
-
- let row = apply_control(
- &config,
- "run-1",
- ControlVerb::Continue,
- Some("use the staging bucket"),
- None,
- )
- .unwrap();
- assert_eq!(row.status, "running");
- assert_eq!(row.bucket.as_str(), "working");
-}
-
-#[test]
-fn continue_without_message_is_rejected_before_touching_the_ledger() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::AwaitingUser);
-
- let err =
- apply_control(&config, "run-1", ControlVerb::Continue, Some(" "), None).unwrap_err();
- assert!(matches!(err, ControlError::MessageRequired("continue")));
- // Status untouched.
- let run = get_agent_run(&config.workspace_dir, "run-1")
- .unwrap()
- .unwrap();
- assert_eq!(run.status, AgentRunStatus::AwaitingUser);
-}
-
-#[test]
-fn follow_up_records_an_event_without_changing_status() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::Completed);
-
- let row = apply_control(
- &config,
- "run-1",
- ControlVerb::FollowUp,
- Some("now summarize it"),
- None,
- )
- .unwrap();
- assert_eq!(row.status, "completed");
-
- let events = list_recent_run_events(
- &config.workspace_dir,
- &RunEventListRequest {
- run_id: "run-1".into(),
- after_sequence: None,
- limit: None,
- },
- )
- .unwrap();
- assert_eq!(events.events[0].event_type, "control_follow_up");
- assert_eq!(events.events[0].payload["message"], "now summarize it");
-}
-
-#[test]
-fn invalid_transition_is_rejected() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- seed_run(&config, "run-1", AgentRunStatus::Completed);
-
- let err = apply_control(&config, "run-1", ControlVerb::Stop, None, None).unwrap_err();
- assert!(matches!(
- err,
- ControlError::InvalidTransition {
- verb: "stop",
- status: "completed"
- }
- ));
-}
-
-#[test]
-fn unknown_run_is_not_found() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let err = apply_control(&config, "ghost", ControlVerb::Stop, None, None).unwrap_err();
- assert!(matches!(err, ControlError::RunNotFound(id) if id == "ghost"));
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/mod.rs b/crates/openhuman-core/src/agent/orchestration/command_center/mod.rs
index c7b3ee017b..3320031fcf 100644
--- a/crates/openhuman-core/src/agent/orchestration/command_center/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/command_center/mod.rs
@@ -1,25 +1,17 @@
//! Background agent command center (issue #3373).
//!
-//! A read-only product surface over the durable run ledger
-//! (`tinyagents_session::run_ledger`): it lists recent background agent runs grouped by
-//! a normalized status model (needs-input / working / completed / failed /
-//! stopped) so users can see what is in flight, what is blocked on them, and
-//! what finished. Live run state already persists to the ledger via the spawn
-//! tools + `web_chat::progress_bridge`; this module only
-//! projects and groups it for display.
-//!
-//! Control verbs (stop / retry / continue / follow-up) live in [`control`]:
-//! durable run-ledger transitions exposed over `openhuman.agent_work_control`.
+//! A read-only product surface over the durable run ledger: it lists recent
+//! background agent runs grouped by a normalized status model (needs-input /
+//! working / completed / failed / stopped) and lets a reviewer stop, retry,
+//! continue or follow up on a run. The projection, bucket mapping and control
+//! transitions live upstream in
+//! `tinyagents_session::run_ledger::command_center`; this module is the
+//! `openhuman.agent_work_*` RPC surface and the agent-registry display-name
+//! lookup.
-mod control;
-mod ops;
mod schemas;
-pub mod types;
-pub use control::{apply_control, ControlError, ControlVerb};
-pub use ops::{bucket_for, build_view, list_agent_work};
pub use schemas::{
all_controller_schemas as all_command_center_controller_schemas,
all_registered_controllers as all_command_center_registered_controllers,
};
-pub use types::{AgentWorkBucket, AgentWorkRow, CommandCenterGroup, CommandCenterView};
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/ops.rs b/crates/openhuman-core/src/agent/orchestration/command_center/ops.rs
deleted file mode 100644
index 3f01166841..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/command_center/ops.rs
+++ /dev/null
@@ -1,132 +0,0 @@
-//! Read-only command-center projection over the durable run ledger.
-//!
-//! [`list_agent_work`] fetches recent background agent runs from
-//! `tinyagents_session::run_ledger` and projects them into a [`CommandCenterView`]
-//! grouped by normalized [`AgentWorkBucket`]. The projection is split so the
-//! pure grouping logic ([`build_view`]) is unit-testable without a database,
-//! while [`list_agent_work`] owns the one ledger read.
-
-use anyhow::Result;
-
-use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::config::Config;
-use tinyagents_session::run_ledger::{
- list_agent_runs, AgentRun, AgentRunListRequest, AgentRunStatus,
-};
-
-use super::types::{AgentWorkBucket, AgentWorkRow, CommandCenterGroup, CommandCenterView};
-
-/// Default number of recent runs scanned for the command center.
-const DEFAULT_LIMIT: u32 = 200;
-/// Hard ceiling, mirroring the ledger's own `list_agent_runs` cap.
-const MAX_LIMIT: u32 = 500;
-
-/// Map a fine-grained ledger status to its command-center bucket.
-///
-/// Exhaustive on [`AgentRunStatus`] so a new ledger status variant fails to
-/// compile here until its bucket is decided.
-pub fn bucket_for(status: AgentRunStatus) -> AgentWorkBucket {
- match status {
- AgentRunStatus::AwaitingUser => AgentWorkBucket::NeedsInput,
- AgentRunStatus::Pending | AgentRunStatus::Running | AgentRunStatus::Paused => {
- AgentWorkBucket::Working
- }
- AgentRunStatus::Completed => AgentWorkBucket::Completed,
- AgentRunStatus::Failed => AgentWorkBucket::Failed,
- AgentRunStatus::Cancelled | AgentRunStatus::Interrupted => AgentWorkBucket::Stopped,
- }
-}
-
-/// List recent background agent work, grouped by command-center bucket.
-///
-/// Reads at most `limit` (default 200, capped 500) most-recently-updated runs
-/// across every parent thread and projects them. Read-only: no ledger writes.
-pub fn list_agent_work(config: &Config, limit: Option<u32>) -> Result<CommandCenterView> {
- let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);
- log::debug!(
- target: "command_center",
- "[command_center] list_agent_work.entry limit={limit}"
- );
- let request = AgentRunListRequest {
- status: None,
- kind: None,
- parent_run_id: None,
- parent_thread_id: None,
- limit: Some(limit),
- offset: None,
- };
- let response = list_agent_runs(&config.workspace_dir, &request)?;
- let view = build_view(response.runs);
- log::debug!(
- target: "command_center",
- "[command_center] list_agent_work.done total={}",
- view.total
- );
- Ok(view)
-}
-
-/// Project + group a set of ledger runs into the command-center view.
-///
-/// Pure: input order is preserved within each bucket, so callers that pass
-/// runs already ordered most-recently-updated-first (as `list_agent_runs`
-/// does) get recent-first rows per group. All five buckets are always present.
-pub fn build_view(runs: Vec<AgentRun>) -> CommandCenterView {
- let rows: Vec<AgentWorkRow> = runs.into_iter().map(project_row).collect();
- let total = rows.len();
- let groups = AgentWorkBucket::ALL
- .iter()
- .map(|&bucket| {
- let bucket_rows: Vec<AgentWorkRow> = rows
- .iter()
- .filter(|r| r.bucket == bucket)
- .cloned()
- .collect();
- CommandCenterGroup {
- bucket,
- count: bucket_rows.len(),
- rows: bucket_rows,
- }
- })
- .collect();
- CommandCenterView { groups, total }
-}
-
-/// Project one ledger run into a lean command-center row.
-///
-/// `pub(super)` so the control verbs ([`super::control`]) can re-project a run
-/// after a durable status transition without duplicating the mapping.
-pub(super) fn project_row(run: AgentRun) -> AgentWorkRow {
- let display_name = run.agent_id.as_deref().and_then(resolve_display_name);
- let telemetry = run.telemetry;
- AgentWorkRow {
- run_id: run.id,
- kind: run.kind.as_str().to_string(),
- agent_id: run.agent_id,
- display_name,
- bucket: bucket_for(run.status),
- status: run.status.as_str().to_string(),
- parent_thread_id: run.parent_thread_id,
- worker_thread_id: run.worker_thread_id,
- summary: run.summary,
- error: run.error,
- started_at: run.started_at.to_rfc3339(),
- updated_at: run.updated_at.to_rfc3339(),
- elapsed_ms: telemetry.as_ref().and_then(|t| t.elapsed_ms),
- input_tokens: telemetry.as_ref().map(|t| t.input_tokens).unwrap_or(0),
- output_tokens: telemetry.as_ref().map(|t| t.output_tokens).unwrap_or(0),
- cost_usd: telemetry.as_ref().map(|t| t.cost_usd).unwrap_or(0.0),
- tool_count: telemetry.as_ref().map(|t| t.tool_count).unwrap_or(0),
- }
-}
-
-/// Resolve an agent id to its registry display name, if the registry is up and
-/// the agent is known. Returns `None` otherwise (e.g. custom/removed agents).
-fn resolve_display_name(agent_id: &str) -> Option<String> {
- AgentDefinitionRegistry::global()
- .and_then(|registry| registry.get(agent_id))
- .map(|definition| definition.display_name().to_string())
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/ops_tests.rs b/crates/openhuman-core/src/agent/orchestration/command_center/ops_tests.rs
deleted file mode 100644
index 3e42563f9d..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/command_center/ops_tests.rs
+++ /dev/null
@@ -1,129 +0,0 @@
-use super::*;
-use chrono::{TimeZone, Utc};
-use serde_json::json;
-
-fn run_with(id: &str, status: AgentRunStatus, updated_secs: i64) -> AgentRun {
- AgentRun {
- id: id.to_string(),
- kind: tinyagents_session::run_ledger::AgentRunKind::Subagent,
- parent_run_id: None,
- parent_thread_id: Some("thread-1".to_string()),
- agent_id: Some("researcher".to_string()),
- status,
- prompt_ref: None,
- worker_thread_id: None,
- checkpoint_path: None,
- checkpoint: None,
- summary: None,
- error: None,
- metadata: json!({}),
- telemetry: None,
- started_at: Utc.timestamp_opt(1_700_000_000, 0).unwrap(),
- updated_at: Utc.timestamp_opt(1_700_000_000 + updated_secs, 0).unwrap(),
- completed_at: None,
- }
-}
-
-#[test]
-fn bucket_for_maps_every_status_to_its_group() {
- assert_eq!(
- bucket_for(AgentRunStatus::AwaitingUser),
- AgentWorkBucket::NeedsInput
- );
- assert_eq!(
- bucket_for(AgentRunStatus::Pending),
- AgentWorkBucket::Working
- );
- assert_eq!(
- bucket_for(AgentRunStatus::Running),
- AgentWorkBucket::Working
- );
- assert_eq!(bucket_for(AgentRunStatus::Paused), AgentWorkBucket::Working);
- assert_eq!(
- bucket_for(AgentRunStatus::Completed),
- AgentWorkBucket::Completed
- );
- assert_eq!(bucket_for(AgentRunStatus::Failed), AgentWorkBucket::Failed);
- assert_eq!(
- bucket_for(AgentRunStatus::Cancelled),
- AgentWorkBucket::Stopped
- );
- assert_eq!(
- bucket_for(AgentRunStatus::Interrupted),
- AgentWorkBucket::Stopped
- );
-}
-
-#[test]
-fn build_view_always_emits_five_buckets_in_display_order() {
- let view = build_view(vec![]);
- assert_eq!(view.total, 0);
- let order: Vec<AgentWorkBucket> = view.groups.iter().map(|g| g.bucket).collect();
- assert_eq!(order, AgentWorkBucket::ALL.to_vec());
- assert!(view
- .groups
- .iter()
- .all(|g| g.rows.is_empty() && g.count == 0));
-}
-
-#[test]
-fn build_view_groups_runs_into_correct_buckets() {
- let runs = vec![
- run_with("a", AgentRunStatus::Running, 1),
- run_with("b", AgentRunStatus::AwaitingUser, 2),
- run_with("c", AgentRunStatus::Completed, 3),
- run_with("d", AgentRunStatus::Failed, 4),
- run_with("e", AgentRunStatus::Cancelled, 5),
- run_with("f", AgentRunStatus::Pending, 6),
- ];
- let view = build_view(runs);
- assert_eq!(view.total, 6);
-
- let group = |bucket: AgentWorkBucket| {
- view.groups
- .iter()
- .find(|g| g.bucket == bucket)
- .expect("bucket present")
- };
- assert_eq!(group(AgentWorkBucket::NeedsInput).count, 1);
- assert_eq!(group(AgentWorkBucket::Working).count, 2); // running + pending
- assert_eq!(group(AgentWorkBucket::Completed).count, 1);
- assert_eq!(group(AgentWorkBucket::Failed).count, 1);
- assert_eq!(group(AgentWorkBucket::Stopped).count, 1);
-}
-
-#[test]
-fn build_view_preserves_input_order_within_a_bucket() {
- // Caller passes recent-first; projection must not reorder.
- let runs = vec![
- run_with("newest", AgentRunStatus::Running, 30),
- run_with("middle", AgentRunStatus::Running, 20),
- run_with("oldest", AgentRunStatus::Running, 10),
- ];
- let view = build_view(runs);
- let working = view
- .groups
- .iter()
- .find(|g| g.bucket == AgentWorkBucket::Working)
- .unwrap();
- let ids: Vec<&str> = working.rows.iter().map(|r| r.run_id.as_str()).collect();
- assert_eq!(ids, vec!["newest", "middle", "oldest"]);
-}
-
-#[test]
-fn project_row_defaults_telemetry_to_zero_when_absent() {
- let view = build_view(vec![run_with("x", AgentRunStatus::Completed, 1)]);
- let row = view
- .groups
- .iter()
- .flat_map(|g| &g.rows)
- .find(|r| r.run_id == "x")
- .unwrap();
- assert_eq!(row.input_tokens, 0);
- assert_eq!(row.output_tokens, 0);
- assert_eq!(row.cost_usd, 0.0);
- assert_eq!(row.tool_count, 0);
- assert_eq!(row.elapsed_ms, None);
- assert_eq!(row.status, "completed");
- assert_eq!(row.kind, "subagent");
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
index a6959e0517..2b2b377b91 100644
--- a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
@@ -4,6 +4,9 @@
use serde_json::{Map, Value};
+use tinyagents_session::run_ledger::command_center::{apply_control, list_agent_work, ControlVerb};
+
+use crate::agent::harness::definition::AgentDefinitionRegistry;
use crate::config::rpc as config_rpc;
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::Outcome;
@@ -95,7 +98,7 @@ fn handle_agent_work_list(params: Map<String, Value>) -> ControllerFuture {
.get("limit")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
- let view = super::ops::list_agent_work(&config, limit).map_err(|e| {
+ let view = list_agent_work(&config.workspace_dir, limit, &resolve_display_name).map_err(|e| {
let s = e.to_string();
log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.error err={s}");
s
@@ -115,7 +118,7 @@ fn handle_agent_work_control(params: Map<String, Value>) -> ControllerFuture {
})?;
let run_id = require_str(&params, "runId")?;
let action = require_str(&params, "action")?;
- let verb = super::ControlVerb::parse(&action).ok_or_else(|| {
+ let verb = ControlVerb::parse(&action).ok_or_else(|| {
let s = format!("unknown control action: {action}");
log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.unknown_action action={action}");
s
@@ -123,12 +126,13 @@ fn handle_agent_work_control(params: Map<String, Value>) -> ControllerFuture {
let message = opt_str(&params, "message");
let reason = opt_str(&params, "reason");
log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.parsed run_id={run_id} verb={}", verb.as_str());
- let row = super::apply_control(
- &config,
+ let row = apply_control(
+ &config.workspace_dir,
&run_id,
verb,
message.as_deref(),
reason.as_deref(),
+ &resolve_display_name,
)
.map_err(|e| {
let s = e.to_string();
@@ -140,6 +144,14 @@ fn handle_agent_work_control(params: Map<String, Value>) -> ControllerFuture {
})
}
+/// Resolve an agent id to its registry display name, if the registry is up and
+/// the agent is known. Returns `None` otherwise (e.g. custom/removed agents).
+fn resolve_display_name(agent_id: &str) -> Option<String> {
+ AgentDefinitionRegistry::global()
+ .and_then(|registry| registry.get(agent_id))
+ .map(|definition| definition.display_name().to_string())
+}
+
fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
Outcome::new(value, vec![]).into_cli_compatible_json()
}
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/schemas_tests.rs b/crates/openhuman-core/src/agent/orchestration/command_center/schemas_tests.rs
index cc5c2a2e37..f49288b594 100644
--- a/crates/openhuman-core/src/agent/orchestration/command_center/schemas_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/command_center/schemas_tests.rs
@@ -10,3 +10,8 @@ fn registered_controllers_match_schemas() {
assert_eq!(schema_for("agent_work_list").function, "list");
assert_eq!(schema_for("agent_work_control").function, "control");
}
+
+#[test]
+fn unknown_agent_has_no_display_name() {
+ assert_eq!(resolve_display_name("__definitely_not_an_agent__"), None);
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/types.rs b/crates/openhuman-core/src/agent/orchestration/command_center/types.rs
deleted file mode 100644
index b3aa22db84..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/command_center/types.rs
+++ /dev/null
@@ -1,121 +0,0 @@
-//! Command-center view types for the background agent surface (issue #3373).
-//!
-//! The durable run ledger (`tinyagents_session::run_ledger`) stores fine-grained
-//! `AgentRunStatus` values for every background agent run. The background
-//! agent command center groups that work into five user-facing buckets so a
-//! reviewer can see, at a glance, what needs input, what is still working, and
-//! what finished, failed, or was stopped. These types are the read-only
-//! projection the command center renders; nothing here mutates ledger state.
-
-use serde::Serialize;
-
-/// Normalized command-center status bucket.
-///
-/// Collapses the ledger's eight `AgentRunStatus` values into the five groups
-/// the command center renders. The mapping lives in
-/// [`super::ops::bucket_for`]; the order of [`AgentWorkBucket::ALL`] is the
-/// display order (needs-input first so blocked work is most visible).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum AgentWorkBucket {
- /// A run paused waiting for user input (`awaiting_user`).
- NeedsInput,
- /// A run still executing or queued (`pending` / `running` / `paused`).
- Working,
- /// A run that finished successfully (`completed`).
- Completed,
- /// A run that ended in error (`failed`).
- Failed,
- /// A run cancelled or interrupted before completion.
- Stopped,
-}
-
-impl AgentWorkBucket {
- /// Display order: needs-input first, then in-flight, then terminal states.
- pub const ALL: [AgentWorkBucket; 5] = [
- AgentWorkBucket::NeedsInput,
- AgentWorkBucket::Working,
- AgentWorkBucket::Completed,
- AgentWorkBucket::Failed,
- AgentWorkBucket::Stopped,
- ];
-
- /// Stable wire string for this bucket.
- pub fn as_str(self) -> &'static str {
- match self {
- AgentWorkBucket::NeedsInput => "needs_input",
- AgentWorkBucket::Working => "working",
- AgentWorkBucket::Completed => "completed",
- AgentWorkBucket::Failed => "failed",
- AgentWorkBucket::Stopped => "stopped",
- }
- }
-}
-
-/// One command-center row, projected from a durable [`AgentRun`].
-///
-/// Kept deliberately lean — transcripts and checkpoints stay in the ledger /
-/// thread stores and are fetched on demand when a user opens a row.
-///
-/// [`AgentRun`]: tinyagents_session::run_ledger::AgentRun
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AgentWorkRow {
- /// Ledger run id (open/peek key).
- pub run_id: String,
- /// Run kind wire string (`subagent` / `worker_thread` / ...).
- pub kind: String,
- /// Agent definition id, when known.
- pub agent_id: Option<String>,
- /// Human-friendly name resolved from the agent registry, when available.
- pub display_name: Option<String>,
- /// Normalized command-center bucket.
- pub bucket: AgentWorkBucket,
- /// Raw ledger status wire string (preserved for detail views).
- pub status: String,
- /// Parent conversation thread, for deterministic "open thread".
- pub parent_thread_id: Option<String>,
- /// Linked worker thread, for "open worker transcript".
- pub worker_thread_id: Option<String>,
- /// Latest summary, when the run produced one.
- pub summary: Option<String>,
- /// Failure reason, when the run failed.
- pub error: Option<String>,
- /// RFC3339 start timestamp.
- pub started_at: String,
- /// RFC3339 last-activity timestamp.
- pub updated_at: String,
- /// Wall-clock elapsed milliseconds, when telemetry recorded it.
- pub elapsed_ms: Option<u64>,
- /// Input tokens spent (0 when no telemetry).
- pub input_tokens: u64,
- /// Output tokens spent (0 when no telemetry).
- pub output_tokens: u64,
- /// Cost in USD (0 when no telemetry).
- pub cost_usd: f64,
- /// Tool-call count (0 when no telemetry).
- pub tool_count: u64,
-}
-
-/// One status group in the command-center view.
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CommandCenterGroup {
- /// The bucket this group represents.
- pub bucket: AgentWorkBucket,
- /// Number of rows in this group.
- pub count: usize,
- /// Rows, most-recently-updated first.
- pub rows: Vec<AgentWorkRow>,
-}
-
-/// The full command-center view: all five buckets in display order plus a total.
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CommandCenterView {
- /// Always exactly five groups, in [`AgentWorkBucket::ALL`] order (empty
- /// groups included so the UI can render stable section headers).
- pub groups: Vec<CommandCenterGroup>,
- /// Total rows across all buckets.
- pub total: usize,
-}