From efce16d45d774525484eec9d88d1ed05c254b47e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Szyma=C5=84ski?= Date: Thu, 19 Nov 2026 17:32:51 +0100 Subject: [PATCH] feat(agents): add Hermes Agent with a profile picker and richer tool-call view (#4542) Adds Hermes Agent as a built-in ACP agent, with a Hermes profile picker. The tool-call view also gets richer: kind icons, duration, status, exit codes, a terminal block for commands, and links to the files a tool touched (omitted when the title already names the file). Co-authored-by: PawelSzymanski89 <26041449+PawelSzymanski89@users.noreply.github.com> --- crates/ide-agent/src/config.rs | 23 +++- crates/ide-agent/src/hermes.rs | 111 +++++++++++++++ crates/ide-agent/src/lib.rs | 38 +++++- crates/ide-agent/src/model.rs | 31 +++++ crates/ide-agent/src/provider.rs | 12 +- crates/ide-agent/src/skills.rs | 34 ++++- crates/ide-agent/src/tests.rs | 53 +++++++- crates/ide-agent/src/timeline.rs | 45 ++++++- crates/ide-host/src/ops/agent.rs | 11 ++ docs/en/guide/agents.mdx | 1 + docs/zh/guide/agents.mdx | 1 + e2e/agentMarkdown.spec.ts | 5 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 35 ++++- src/features/agents/AgentList.tsx | 10 +- src/features/agents/HermesProfilePicker.tsx | 75 +++++++++++ src/features/agents/HomeEditor.test.tsx | 45 ++++++- src/features/agents/HomeEditor.tsx | 5 + src/features/agents/McpServersPage.tsx | 1 + src/features/agents/Session.module.css | 126 ++++++++++++++++++ src/features/agents/composerModel.ts | 9 ++ src/features/agents/model.ts | 20 ++- src/features/agents/session/ProcessRows.tsx | 4 + .../agents/session/SessionComposer.tsx | 2 + src/features/agents/session/SessionStatus.tsx | 9 +- src/features/agents/session/Stream.tsx | 15 ++- src/features/agents/session/messages.tsx | 13 +- src/features/agents/session/toolEntries.tsx | 77 +++++++++-- src/features/agents/timeline.test.ts | 54 +++++++- src/features/agents/timeline.ts | 55 ++++++++ src/platform/locales/text/en.json | 9 ++ src/platform/locales/text/zh.json | 8 ++ src/ui/icons.tsx | 1 + src/ui/openidea/agents/hermes.svg | 5 + 34 files changed, 898 insertions(+), 46 deletions(-) create mode 100644 crates/ide-agent/src/hermes.rs create mode 100644 src/features/agents/HermesProfilePicker.tsx create mode 100644 src/ui/openidea/agents/hermes.svg diff --git a/crates/ide-agent/src/config.rs b/crates/ide-agent/src/config.rs index 49953e1cc..53f5cb72a 100644 --- a/crates/ide-agent/src/config.rs +++ b/crates/ide-agent/src/config.rs @@ -3,7 +3,7 @@ use crate::model::{ AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit, - AgentModelPricing, AgentUsage, + AgentModelPricing, AgentTokens, AgentUsage, }; use serde_json::{Value, json}; @@ -272,6 +272,18 @@ pub(crate) fn usage_of(update: &Value) -> Option { Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost }) } +/// The `usage` of a `session/prompt` result: `{ inputTokens, cachedReadTokens, outputTokens }`. +pub(crate) fn tokens_of(result: &Value) -> Option { + let usage = result.get("usage")?; + let tokens = |key: &str| usage.get(key).and_then(Value::as_u64).map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX)); + let tokens = AgentTokens { + input: tokens("inputTokens"), + cached: tokens("cachedReadTokens"), + output: tokens("outputTokens"), + }; + (tokens != AgentTokens::default()).then_some(tokens) +} + /// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped. pub(crate) fn limits_of(update: &Value) -> Vec { let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten(); @@ -368,6 +380,15 @@ mod tests { c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect() } + #[test] + fn a_hermes_prompt_result_reports_the_turns_tokens() { + let result = json!({"stopReason": "end_turn", "usage": {"cachedReadTokens": 51306, "inputTokens": 77284, + "outputTokens": 509, "thoughtTokens": 0, "totalTokens": 77793}}); + assert_eq!(tokens_of(&result), Some(AgentTokens { input: 77284, cached: 51306, output: 509 })); + assert_eq!(tokens_of(&json!({"stopReason": "end_turn"})), None); + assert_eq!(tokens_of(&json!({"usage": {}})), None); + } + #[test] fn config_options_win_over_the_older_fields() { let r = json!({ diff --git a/crates/ide-agent/src/hermes.rs b/crates/ide-agent/src/hermes.rs new file mode 100644 index 000000000..bfc494b78 --- /dev/null +++ b/crates/ide-agent/src/hermes.rs @@ -0,0 +1,111 @@ +//! Hermes Agent profiles on disk: `default` is the Hermes home itself, the others are +//! `/profiles/` directories holding one of Hermes' identity files. + +use std::path::{Path, PathBuf}; + +use serde::Serialize; +use specta::Type; + +const PROFILE_FILES: &[&str] = &["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"]; + +/// Hermes' home directory (`~/.hermes`; `%LOCALAPPDATA%\hermes` on Windows). +pub fn root(home: Option<&Path>) -> Option { + #[cfg(windows)] + if let Some(local) = std::env::var_os("LOCALAPPDATA") { + return Some(PathBuf::from(local).join("hermes")); + } + home.map(|h| h.join(".hermes")) +} + +/// The profile names under `root`: `default` first, then the others by name; none without `root`. +pub fn profiles(root: &Path) -> Vec { + if !root.is_dir() { + return Vec::new(); + } + let mut named: Vec = std::fs::read_dir(root.join("profiles")) + .into_iter() + .flatten() + .flatten() + .filter(|e| PROFILE_FILES.iter().any(|f| e.path().join(f).exists())) + .filter_map(|e| e.file_name().to_str().map(str::to_owned)) + .filter(|name| name != "default") + .collect(); + named.sort(); + std::iter::once("default".to_owned()).chain(named).collect() +} + +/// A profile and the name Hermes shows for it (`hermes profile list`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] +pub struct HermesProfile { + /// What `hermes -p` takes; `default` is the Hermes home itself. + pub name: String, + /// `display_name` from the profile's `profile.yaml`, else the name. + pub label: String, +} + +/// [`profiles`] with the names Hermes shows for them. +pub fn labeled_profiles(root: &Path) -> Vec { + profiles(root) + .into_iter() + .map(|name| { + let home = if name == "default" { root.to_path_buf() } else { root.join("profiles").join(&name) }; + let label = display_name(&home).unwrap_or_else(|| name.clone()); + HermesProfile { name, label } + }) + .collect() +} + +/// The top-level `display_name:` of `/profile.yaml`, the only key read (no YAML parser). +fn display_name(home: &Path) -> Option { + let text = std::fs::read_to_string(home.join("profile.yaml")).ok()?; + let value = text.lines().find_map(|l| l.strip_prefix("display_name:"))?; + let value = value.trim().trim_matches(['"', '\'']).trim(); + (!value.is_empty()).then(|| value.to_owned()) +} + +/// The home of the profile an agent id stands for: `hermes` and `hermes-default` are the +/// default profile, `hermes-` the profile whose name slugifies to ``. +pub fn profile_home(root: &Path, provider: &str) -> Option { + let slug = match provider { + "hermes" | "hermes-default" => return Some(root.to_path_buf()), + _ => provider.strip_prefix("hermes-")?, + }; + profiles(root).into_iter().find(|p| crate::provider::slugify_id(p) == slug).map(|p| root.join("profiles").join(p)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_default_and_profiles_with_an_identity_file() { + let dir = tempfile::tempdir().unwrap(); + assert!(profiles(&dir.path().join("missing")).is_empty()); + let root = dir.path().join(".hermes"); + std::fs::create_dir_all(root.join("profiles/empty")).unwrap(); + assert_eq!(profiles(&root), ["default"]); + for (name, file) in [("work", "config.yaml"), ("Dom 2", "SOUL.md"), ("db", "state.db")] { + std::fs::create_dir_all(root.join("profiles").join(name)).unwrap(); + std::fs::write(root.join("profiles").join(name).join(file), "").unwrap(); + } + std::fs::write(root.join("profiles/stray.yaml"), "").unwrap(); + assert_eq!(profiles(&root), ["default", "Dom 2", "db", "work"]); + assert_eq!(profile_home(&root, "hermes"), Some(root.clone())); + assert_eq!(profile_home(&root, "hermes-dom-2"), Some(root.join("profiles/Dom 2"))); + assert_eq!(profile_home(&root, "hermes-empty"), None); + assert_eq!(profile_home(&root, "claude"), None); + } + + #[test] + fn labels_profiles_with_their_display_name() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join(".hermes"); + std::fs::create_dir_all(root.join("profiles/work")).unwrap(); + std::fs::write(root.join("profile.yaml"), "description: mine\ndisplay_name: \"qb\"\n").unwrap(); + std::fs::write(root.join("profiles/work/profile.yaml"), "ui_meta:\n display_name: nested\n").unwrap(); + let label = |name: &str, label: &str| HermesProfile { name: name.into(), label: label.into() }; + assert_eq!(labeled_profiles(&root), [label("default", "qb"), label("work", "work")]); + std::fs::remove_file(root.join("profile.yaml")).unwrap(); + assert_eq!(labeled_profiles(&root)[0], label("default", "default")); + } +} diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index a0eb4e4c8..06e0a92e6 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -14,6 +14,7 @@ mod config; mod conversation; mod elicitation; mod external; +pub mod hermes; pub mod mcp; mod model; mod native; @@ -709,7 +710,8 @@ impl AgentManager { /// The slash commands to complete for `provider`, in `task`'s directory or (without one) /// in the project: what the agent offered last time there, unadvertised builtins, - /// and, for Claude Code, skills and custom commands on disk it has not listed. + /// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes, + /// its profile's skills). pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult> { let (provider, offered, cwd) = match task { Some(id) => { @@ -743,10 +745,18 @@ impl AgentManager { offered.push(command); } } + let home = self.shared.paths.home_dir.clone(); + if provider == "hermes" || provider.starts_with("hermes-") { + let found = blocking(move || { + let profile = hermes::root(home.as_deref()).and_then(|root| hermes::profile_home(&root, &provider)); + Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default()) + }) + .await?; + return Ok(skills::merge(offered, found)); + } if provider != "claude" && provider != "claude-acp" { return Ok(offered); } - let home = self.shared.paths.home_dir.clone(); let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?; Ok(skills::merge(offered, found)) } @@ -832,6 +842,7 @@ impl AgentManager { retry: None, background: Box::default(), mcp_overrides: BTreeMap::new(), + stats: Box::default(), }; let file = TaskFile { task: task.clone(), @@ -949,6 +960,7 @@ impl AgentManager { retry: None, background: Box::default(), mcp_overrides: req.mcp_overrides, + stats: Box::default(), }; let file = TaskFile { task: task.clone(), @@ -1316,6 +1328,7 @@ impl AgentManager { resets_ms: None, retry: None, background: Box::default(), + stats: Box::default(), ..s.task.clone() }; TaskFile { @@ -2653,7 +2666,13 @@ impl Task { .await; } match result { - Ok(v) => Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned()), + Ok(v) => { + if let Some(tokens) = config::tokens_of(&v) { + self.state.lock().task.stats.tokens = Some(tokens); + self.emit_task(); + } + Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned()) + } Err(e) => Err(self.failure(e)), } } @@ -3187,6 +3206,17 @@ impl Task { return; } if kind == "session_info_update" { + let depth = update.pointer("/_meta/hermes/sessionProvenance/compressionDepth").and_then(Value::as_u64); + if let Some(depth) = depth.and_then(|d| u32::try_from(d).ok()) { + let changed = { + let mut s = self.state.lock(); + std::mem::replace(&mut s.task.stats.compressions, depth) != depth + }; + if changed { + self.persist(); + self.emit_task(); + } + } // The agent's own title for the session replaces the first line of the prompt, // unless the user named the task. let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()); @@ -4038,7 +4068,7 @@ fn entry_event( entry: &AgentEntry, ) -> AgentEvent { let text = match entry { - AgentEntry::Agent { text } | AgentEntry::Thought { text } => Some(text), + AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text), _ => None, }; let Some(text) = text else { diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index e08be1378..203b01d01 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -108,6 +108,29 @@ pub struct AgentTask { /// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub mcp_overrides: BTreeMap, + /// Token counts of the last turn and context compressions, when the agent reports them. + // Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows. + #[serde(default)] + pub stats: Box, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct AgentSessionStats { + /// The last turn's tokens (`session/prompt` result `usage`). + #[serde(default)] + pub tokens: Option, + /// How many times the agent compressed the conversation (Hermes `compressionDepth`). + #[serde(default)] + pub compressions: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct AgentTokens { + pub input: u32, + pub cached: u32, + pub output: u32, } /// A task the agent runs in the background while the conversation goes on. @@ -479,6 +502,9 @@ pub enum AgentEntry { }, Thought { text: String, + /// When the reasoning started (ms since the epoch); `None` in tasks saved before. + #[serde(default)] + started_ms: Option, }, Tool { id: String, @@ -490,6 +516,11 @@ pub enum AgentEntry { /// Text the tool reported (command output…), truncated. output: Option, diffs: Vec, + /// When the call started and ended (ms since the epoch); `None` in tasks saved before. + #[serde(default)] + started_ms: Option, + #[serde(default)] + ended_ms: Option, }, Plan { items: Vec, diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index f78662a2a..8db709499 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -82,6 +82,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[ ("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."), ("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."), ("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."), + ("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."), ]; fn builtins() -> Vec { @@ -503,7 +504,7 @@ fn validated_custom_id(id: &str) -> IdeResult { } /// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`). -fn slugify_id(name: &str) -> String { +pub(crate) fn slugify_id(name: &str) -> String { let mut id = String::with_capacity(name.len()); for c in name.chars() { if c.is_ascii_alphanumeric() { @@ -716,6 +717,15 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn hermes_is_built_in_over_acp() { + let spec = builtin_spec("hermes").unwrap(); + assert_eq!(spec.driver, Driver::Acp); + let info = describe(&spec); + assert_eq!((info.name.as_str(), info.command.as_str()), ("Hermes Agent", "hermes acp")); + assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal.")); + } + #[test] fn qoder_global_and_cn_editions_are_both_built_in() { let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap()); diff --git a/crates/ide-agent/src/skills.rs b/crates/ide-agent/src/skills.rs index 48b69e264..01994045f 100644 --- a/crates/ide-agent/src/skills.rs +++ b/crates/ide-agent/src/skills.rs @@ -1,6 +1,7 @@ //! Claude Code's slash commands on disk, for completion before (or without) a session: //! skills (`.claude/skills//SKILL.md`) and custom commands (`.claude/commands/**/*.md`) -//! of the working directory and every directory above it, then the user's `~/.claude`. +//! of the working directory and every directory above it, then the user's `~/.claude`; and +//! the skills of a Hermes profile (`/skills`). use crate::{AgentCommand, AgentCommandSource}; use std::collections::HashSet; @@ -34,6 +35,19 @@ pub(crate) fn discover(cwd: &Path, home: Option<&Path>) -> Vec { out } +/// The skills of a Hermes profile: `/skills/` and `/skills//`; +/// the first of a name wins. +pub(crate) fn hermes(profile: &Path) -> Vec { + let root = profile.join("skills"); + let mut found = skills(&root); + for category in sorted(&root).into_iter().filter(|p| !p.join("SKILL.md").exists()) { + found.extend(skills(&category)); + } + let mut seen = HashSet::new(); + found.retain(|c| seen.insert(c.name.clone())); + found +} + /// `first` (the agent's own list) plus the commands of `more` it lacks. pub(crate) fn merge(first: Vec, more: Vec) -> Vec { let mut out = first; @@ -256,6 +270,24 @@ mod tests { ); } + #[test] + fn hermes_skills_flat_and_in_categories() { + let tmp = tempfile::tempdir().unwrap(); + let profile = tmp.path(); + assert!(hermes(profile).is_empty()); + for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan", "skills/empty"] { + std::fs::create_dir_all(profile.join(dir)).unwrap(); + } + for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan"] { + std::fs::write(profile.join(dir).join("SKILL.md"), "---\ndescription: d\n---\n").unwrap(); + } + let names: Vec<_> = hermes(profile).into_iter().map(|c| (c.name, c.source)).collect(); + assert_eq!( + names, + [("plan".to_owned(), AgentCommandSource::Skill), ("review".to_owned(), AgentCommandSource::Skill)] + ); + } + #[test] fn nothing_without_claude_dirs() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 25d2016c8..7308f39f1 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -909,6 +909,27 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() { mgr3.shutdown(); } +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn hermes_profiles_complete_their_own_skills() { + let tmp = tempfile::tempdir().unwrap(); + let skill = |dir: &str, name: &str| { + let dir = tmp.path().join(dir).join(name); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("SKILL.md"), format!("---\nname: {name}\ndescription: d\n---\n")).unwrap(); + }; + skill(".hermes/skills", "plan"); + skill(".hermes/profiles/dom/skills/home", "lights"); + std::fs::write(tmp.path().join(".hermes/profiles/dom/config.yaml"), "").unwrap(); + let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), Arc::new(FakeAgent::default())); + let names = |c: Vec| c.into_iter().map(|c| c.name).collect::>(); + assert!(names(mgr.commands("hermes", None).await.unwrap()).contains(&"plan".to_owned())); + let dom = names(mgr.commands("hermes-dom", None).await.unwrap()); + assert!(dom.contains(&"lights".to_owned()) && !dom.contains(&"plan".to_owned())); + assert!(!names(mgr.commands("claude", None).await.unwrap()).contains(&"plan".to_owned())); + mgr.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() { let tmp = tempfile::tempdir().unwrap(); @@ -1877,6 +1898,32 @@ async fn real_claude_task_in_a_worktree() { mgr.shutdown(); } +#[tokio::test(flavor = "multi_thread")] +async fn hermes_session_info_names_the_task_and_counts_compressions() { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let task = mgr + // "again" ends the turn at once; the default prompt waits for a permission answer. + .create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let handle = mgr.task(&task.id).unwrap(); + let info = |title: &str, depth: u32| { + json!({"sessionUpdate": "session_info_update", "title": title, "updatedAt": "2026-11-18T18:35:32.068362+00:00", + "_meta": {"hermes": {"sessionProvenance": {"sessionKind": "root", "parentHermesSessionId": null, + "compressionDepth": depth}}}}) + }; + handle.on_update(None, &info("Make a 3-step plan and carry it out: 1) list the…", 0)); + handle.on_update(None, &info("List files and edit notes.txt", 0)); + let t = handle.state.lock().task.clone(); + assert_eq!(t.title, "List files and edit notes.txt", "the agent's latest title wins"); + assert_eq!(t.stats.compressions, 0); + handle.on_update(None, &info("List files and edit notes.txt", 2)); + assert_eq!(handle.state.lock().task.stats.compressions, 2); + mgr.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn renamed_titles_survive_updates_forks_and_restart() { let tmp = tempfile::tempdir().unwrap(); @@ -3531,11 +3578,13 @@ fn streamed_text_is_sent_as_appends() { ); let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other")); assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole"); - let thought = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm…".into() }); + let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None }; + let thought = entry_event("t", &mut streamed, None, 4, &thought); assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole"); let tool = AgentEntry::Error { message: "x".into() }; entry_event("t", &mut streamed, None, 4, &tool); - let again = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm… ok".into() }); + let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None }; + let again = entry_event("t", &mut streamed, None, 4, &again); assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text"); let long = "é".repeat(5000); diff --git a/crates/ide-agent/src/timeline.rs b/crates/ide-agent/src/timeline.rs index 2c83c6ef3..f74118aae 100644 --- a/crates/ide-agent/src/timeline.rs +++ b/crates/ide-agent/src/timeline.rs @@ -85,6 +85,8 @@ impl Timeline { locations: locations(update.get("locations")), output: None, diffs: Vec::new(), + started_ms: Some(crate::now_ms()), + ended_ms: None, }; let index = match self.tools.get(&id) { Some(&i) => { @@ -134,17 +136,22 @@ impl Timeline { fn append_text(&mut self, thought: bool, text: &str) -> usize { match self.entries.last_mut() { Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text), - Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text), + Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text), _ => { let text = text.to_owned(); - return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } }); + return self.push(if thought { + AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) } + } else { + AgentEntry::Agent { text } + }); } } self.entries.len() - 1 } fn merge_tool(&mut self, index: usize, update: &Value) { - let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index] + let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } = + &mut self.entries[index] else { return; }; @@ -156,6 +163,9 @@ impl Timeline { } if let Some(s) = tool_status(update.get("status")) { *status = s; + if matches!(s, AgentToolStatus::Completed | AgentToolStatus::Failed) && ended_ms.is_none() { + *ended_ms = Some(crate::now_ms()); + } } if update.get("locations").is_some_and(Value::is_array) { *locs = locations(update.get("locations")); @@ -183,6 +193,11 @@ impl Timeline { } } if !text.is_empty() { + // The command a call announced (`$ cmd`) stays above the result that replaces it. + let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ ")); + if let Some(command) = command.filter(|c| !text.starts_with(c)) { + text = format!("{command}\n{text}"); + } *output = Some(tail(text)); } if !new_diffs.is_empty() { @@ -432,11 +447,14 @@ mod tests { assert_eq!(t.apply(&chunk("lo")).changed, vec![0]); t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}})); t.apply(&chunk("again")); + // The thought's start is the clock's: it is there, and the rest compares exactly. + let AgentEntry::Thought { started_ms, .. } = &mut t.entries[1] else { panic!("{:?}", t.entries) }; + assert!(started_ms.take().is_some()); assert_eq!( t.entries, vec![ AgentEntry::Agent { text: "Hello".into() }, - AgentEntry::Thought { text: "hmm".into() }, + AgentEntry::Thought { text: "hmm".into(), started_ms: None }, AgentEntry::Agent { text: "again".into() }, ] ); @@ -528,6 +546,25 @@ mod tests { assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. })); } + #[test] + fn a_hermes_terminal_call_keeps_its_command_and_times() { + let text = |t: &str| serde_json::json!([{"type": "content", "content": {"type": "text", "text": t}}]); + let mut t = Timeline::default(); + t.apply(&serde_json::json!({"sessionUpdate": "tool_call", "toolCallId": "tc-0b98b5e30a28", + "kind": "execute", "title": "terminal: echo ok + 2 commands", "locations": [], + "content": text("$ echo ok >> notes.txt && wc -l notes.txt")})); + let AgentEntry::Tool { started_ms, ended_ms, .. } = &t.entries[0] else { panic!() }; + assert!(started_ms.is_some() && ended_ms.is_none()); + t.apply(&serde_json::json!({"sessionUpdate": "tool_call_update", "toolCallId": "tc-0b98b5e30a28", + "kind": "execute", "status": "completed", + "content": text("terminal result\n- **output:** 3 notes.txt\n- **exit_code:** 0")})); + let AgentEntry::Tool { output, status, ended_ms, .. } = &t.entries[0] else { panic!() }; + assert_eq!(*status, AgentToolStatus::Completed); + assert!(ended_ms.is_some()); + let expected = "$ echo ok >> notes.txt && wc -l notes.txt\nterminal result\n- **output:** 3 notes.txt\n"; + assert_eq!(output.as_deref(), Some(format!("{expected}- **exit_code:** 0").as_str())); + } + #[test] fn long_output_keeps_its_tail() { let s = tail("é".repeat(MAX_OUTPUT)); diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 9c00a5730..69f1a81c3 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -33,6 +33,16 @@ pub fn agent_providers(host: &Host, window: &str) -> IdeResult IdeResult> { + host.require_trust(window)?; + let root = ide_agent::hermes::root(dirs::home_dir().as_deref()); + tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default()) + .await + .map_err(join_err) +} + /// Refreshes the model catalog; force bypasses freshness, not the cooldown. #[command(trust = trusted)] pub fn agent_refresh_models( @@ -1075,6 +1085,7 @@ ide_command::domain!( agent_external_sessions, agent_fork, agent_grouped_changes, + agent_hermes_profiles, agent_import_session, agent_mcp_discover_sources, agent_mcp_import, diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index bbbc00f82..89f8c3442 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -27,6 +27,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter | Auggie | `auggie --acp` | `auggie login` | | Kiro | `kiro-cli acp` | `kiro-cli login` | | Mistral Vibe | `vibe-acp` | `vibe` | +| Hermes Agent | `hermes acp` | `hermes model` | **Claude Code** and **Codex** are driven through their own protocols (Claude Code's stream-json mode and `codex app-server`). Their ACP adapters (`claude-acp`, `codex-acp`) are no longer listed; tasks that already use them keep working, and an [agent file](#add-a-custom-agent) for either id lists it again. If an agent needs you to sign in, the task tells you which command to run. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index 227786cbf..c04c1f49c 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -27,6 +27,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent | Auggie | `auggie --acp` | `auggie login` | | Kiro | `kiro-cli acp` | `kiro-cli login` | | Mistral Vibe | `vibe-acp` | `vibe` | +| Hermes Agent | `hermes acp` | `hermes model` | **Claude Code** 和 **Codex** 通过它们自己的协议驱动(Claude Code 的 stream-json 模式和 `codex app-server`)。它们的 ACP 适配器(`claude-acp`、`codex-acp`)不再列出;已经在用它们的任务照常运行,为这两个 id 写一个 [agent 文件](#添加自定义-agent)也会重新列出。agent 需要登录时,任务中会提示该运行哪条命令。 diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index af73f069f..8f3199083 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -947,8 +947,9 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less const expandableToolChevron = toolRows[0]! .querySelector("[class*='_toolChevron_']")! .getBoundingClientRect(); - const completedReadIcon = [...toolRows[1]!.querySelectorAll("svg")].at(-1)!.getBoundingClientRect(); - const runningReadIcon = toolRows[2]!.querySelector("svg")!.getBoundingClientRect(); + const kindIcon = (row: HTMLElement) => row.querySelector("[class*='_toolKindIcon_']")!; + const completedReadIcon = kindIcon(toolRows[1]!).getBoundingClientRect(); + const runningReadIcon = kindIcon(toolRows[2]!).getBoundingClientRect(); return { summaryChevronCenter: summaryChevron.left + summaryChevron.width / 2, guideLeft: processBody.left, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 9e16d8d72..deb5860a2 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -16,6 +16,7 @@ agent_entries always project_host bin agent_external_sessions trusted project_host bindings async agent_fork trusted project_host bindings async agent_grouped_changes trusted project_host bindings async +agent_hermes_profiles trusted project_host bindings async agent_import_session trusted project_host bindings async agent_mcp_discover_sources always project_host bindings async agent_mcp_import always project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 6cf6477f0..6159407e7 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -57,6 +57,8 @@ export const commands = { agentFork: (task: string, turns: number | null) => typedError(__TAURI_INVOKE("agent_fork", { task, turns })), /** The task's uncommitted changes and the commits made since it started. */ agentGroupedChanges: (task: string) => typedError(__TAURI_INVOKE("agent_grouped_changes", { task })), + /** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */ + agentHermesProfiles: () => typedError(__TAURI_INVOKE("agent_hermes_profiles")), /** Imports an external session as a task: its first turn loads and replays it. */ agentImportSession: (provider: string, sessionId: string) => typedError(__TAURI_INVOKE("agent_import_session", { provider, sessionId })), /** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */ @@ -2267,11 +2269,15 @@ steered?: boolean } | { type: "agent"; text: string } | /** A question that can be answered while the agent keeps working, or after the turn ends. */ { type: "question"; id: string; title: string; questions: AgentQuestion[]; /** The submitted answers, or `Skipped`; `None` while unanswered. */ -chosen: string | null } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string; +chosen: string | null } | { type: "thought"; text: string; +/** When the reasoning started (ms since the epoch); `None` in tasks saved before. */ +startedMs?: number | null } | { type: "tool"; id: string; title: string; /** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */ kind: string; status: AgentToolStatus; locations: IpcPath[]; /** Text the tool reported (command output…), truncated. */ -output: string | null; diffs: AgentToolDiff[] } | { type: "plan"; items: AgentPlanItem[] } | +output: string | null; diffs: AgentToolDiff[]; +/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */ +startedMs?: number | null; endedMs?: number | null } | { type: "plan"; items: AgentPlanItem[] } | /** A subagent the agent started: its own session, whose entries are listed separately. */ { type: "subagent"; /** The subagent's session id. */ @@ -2570,6 +2576,13 @@ export type AgentSecuritySettings = { blockedCommands?: string[], }; +export type AgentSessionStats = { + /** The last turn's tokens (`session/prompt` result `usage`). */ + tokens?: AgentTokens | null, + /** How many times the agent compressed the conversation (Hermes `compressionDepth`). */ + compressions?: number, +}; + /** Settings › Agents: what the conversation shows and how messages are sent. */ export type AgentSettings = AgentSettings_Serialize | AgentSettings_Deserialize; @@ -2749,6 +2762,8 @@ export type AgentTask_Deserialize = { background?: AgentBackgroundTask[], /** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */ mcpOverrides?: { [key in string]: boolean }, + /** Token counts of the last turn and context compressions, when the agent reports them. */ + stats?: AgentSessionStats, }; export type AgentTask_Serialize = { @@ -2797,6 +2812,8 @@ export type AgentTask_Serialize = { background: AgentBackgroundTask[], /** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */ mcpOverrides?: { [key in string]: boolean }, + /** Token counts of the last turn and context compressions, when the agent reports them. */ + stats: AgentSessionStats, }; /** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */ @@ -2808,6 +2825,12 @@ export type AgentTokenPricing = { contextTokens?: number | null, }; +export type AgentTokens = { + input: number, + cached: number, + output: number, +}; + export type AgentToolDiff = { path: IpcPath, added: number, @@ -6760,6 +6783,14 @@ export type HeapSummary = { analysisMs: number, }; +/** A profile and the name Hermes shows for it (`hermes profile list`). */ +export type HermesProfile = { + /** What `hermes -p` takes; `default` is the Hermes home itself. */ + name: string, + /** `display_name` from the profile's `profile.yaml`, else the name. */ + label: string, +}; + export type HierarchyChoice = { id: string, makeAbstract: boolean, diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index 65533e2e9..965342d37 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -22,7 +22,7 @@ import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField import { useSettingsForm } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; import { isPerModelOption } from "./composerModel"; -import { providerIcon } from "./model"; +import { providerIcon, slugifyId } from "./model"; import { DISTRIBUTION_LABEL, afterInstall, @@ -621,14 +621,6 @@ function Details({ ); } -/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */ -function slugifyId(name: string): string { - return name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, ""); -} - /** Splits arguments on whitespace, honoring single and double quotes. */ function parseArgs(text: string): string[] { const out: string[] = []; diff --git a/src/features/agents/HermesProfilePicker.tsx b/src/features/agents/HermesProfilePicker.tsx new file mode 100644 index 000000000..eab759a94 --- /dev/null +++ b/src/features/agents/HermesProfilePicker.tsx @@ -0,0 +1,75 @@ +/** The Hermes profile a task runs in, next to the model picker. */ +import { useEffect, useState } from "react"; +import type { HermesProfile } from "@/bindings"; +import { useTx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Icon, Select } from "@/ui"; +import { hermesAgentId, providerIcon } from "./model"; +import { refreshProviders, useAgents } from "./store"; + +const isHermes = (provider: string | undefined) => provider === "hermes" || !!provider?.startsWith("hermes-"); + +/** The profiles on this computer; empty for other agents or without Hermes. */ +function useHermesProfiles(provider: string | undefined): HermesProfile[] { + const [profiles, setProfiles] = useState([]); + const hermes = isHermes(provider); + useEffect(() => { + if (!hermes) return; + let live = true; + void call(commands.agentHermesProfiles()) + .then((list) => live && setProfiles(list)) + .catch(() => {}); + return () => { + live = false; + }; + }, [hermes]); + return hermes ? profiles : []; +} + +/** The profile `provider` runs in, by the name Hermes shows for it. */ +const hermesProfileOf = (profiles: readonly HermesProfile[], provider: string) => + profiles.find((p) => hermesAgentId(p.name) === provider) ?? null; + +/** + * Each profile is an agent of its own (`hermes -p acp`, `hermes` for `default`), made + * on first choice, so the agent picker's memory keeps the profile like it keeps the model. + */ +export function HermesProfilePicker({ + provider, + onChange, +}: { + provider: string | undefined; + /** Without it the picker only shows the profile: a session stays in the one it started in. */ + onChange?: (provider: string) => void; +}) { + const tx = useTx(); + const profiles = useHermesProfiles(provider); + const providers = useAgents((s) => s.providers); + if (!provider || profiles.length < 2) return null; + const choose = async (name: string) => { + const id = hermesAgentId(name); + if (!providers.some((p) => p.id === id)) { + const label = profiles.find((p) => p.name === name)?.label ?? name; + await call( + commands.agentCustomSave({ id, name: `Hermes (${label})`, command: "hermes", args: ["-p", name, "acp"] }), + ); + await refreshProviders(); + } + onChange?.(id); + }; + return ( +