* feat: better composer etc * docs: add desktop and dashboard run instructions * fix(desktop): address security scan findings * fix(dashboard): resolve @nous-research/ui path under npm workspaces The sync-assets prebuild step shelled out to 'cp -r node_modules/@nous-research/ui/dist/fonts ...' with a path relative to apps/dashboard/. That works only when the dep is installed locally in the dashboard workspace, but 'npm install' at the repo root (the documented setup — see apps/desktop/README.md) hoists shared deps to the root node_modules under npm workspaces. The relative cp then fails with 'No such file or directory', sync-assets exits 1, the Vite build aborts, and 'hermes dashboard' surfaces a generic 'Web UI build failed' message. Replace the shell one-liner with scripts/sync-assets.cjs, which walks up from the dashboard directory looking for node_modules/ @nous-research/ui — working in both the hoisted (workspaces) and co-located (standalone) layouts. Also guards against a missing dist/fonts or dist/assets with a clearer error pointing at a rebuild of the UI package rather than silently copying nothing. * feat(desktop): support connecting to a remote Hermes backend Add HERMES_DESKTOP_REMOTE_URL and HERMES_DESKTOP_REMOTE_TOKEN env vars that, when set, short-circuit the local-child spawn in startHermes() and connect the Electron renderer to an already- running 'hermes dashboard' server reachable over the network. Motivating use case: WSL2 users who want to run the Hermes core (agent loop, tools, filesystem access) inside their WSL distribution while rendering the Electron GUI on native Windows. Before this change, the desktop app always spawned a local Python child on the same host as the renderer, which doesn't cross the WSL/Windows boundary. The remote path reuses waitForHermes() as a liveness probe (/api/status is in the backend's public endpoint allowlist), so the connection is only returned once the backend is actually ready. WebSocket URL derivation picks ws:// or wss:// based on the input scheme. URL validation rejects non-http(s) schemes and requires both env vars together to avoid a half-configured connection that would silently fall through to the spawn path. No behaviour change when the env vars are unset — the default local-spawn flow is untouched. Typical usage: # in WSL2 hermes dashboard --tui --no-open --host 0.0.0.0 --port 9119 --insecure # on Windows set HERMES_DESKTOP_REMOTE_URL=http://localhost:9119 set HERMES_DESKTOP_REMOTE_TOKEN=<session token> set HERMES_DESKTOP_IGNORE_EXISTING=1 (launch Hermes desktop) * ci(desktop): automate desktop releases Add GitHub Actions release channels for signed desktop installers and document the stable/nightly download paths. * feat: file tabs * refactor(desktop): tighten right-rail tab close API Promote closeRightRailTab/closeActiveRightRailTab as the single public entry point. Drops the activeTabRef + handleCloseDocument indirection in ChatPreviewRail, the unused $rightRailHasContent atom, and the legacy dismissFilePreviewTarget alias. -70 LOC. * feat(desktop): polish composer pill toward reference look Solid foreground-on-background send/voice-conversation circle (black-on-white in light, white-on-black in dark) anchors the right edge as the primary CTA instead of the orange theme primary. Bumps the primary control to 2.125rem so it visually outranks the ghost mic/plus controls. Opens up the surface padding (0.625rem x / 0.5rem y) so the input row breathes around its controls, and nudges the corner radius from 20 to 24px for a slightly pill-ier silhouette. LiquidGlass distortion is preserved. * feat(desktop): add startup and onboarding flow Add phase-based desktop boot progress, fresh-install sandbox testing, and first-run provider credential onboarding so packaged installs can start cleanly without manual settings detours. * fix(desktop): gate prompts on provider setup Show the desktop provider onboarding flow before prompt submission when no inference provider is configured, preventing fresh installs from falling through to backend credential errors. * fix(desktop): surface provider onboarding from session warnings Propagate credential warnings through session runtime info and open desktop onboarding whenever a session reports no usable provider, so unconfigured installs cannot fall through to prompt errors. * fix(desktop): route gateway provider errors to onboarding The "No inference provider configured" auth error reaches the renderer through gateway error events, not the prompt.submit promise; the previous patch only caught the latter, so the error toast still surfaced and onboarding never opened. Also strip credential-shaped env vars from the test:desktop:fresh sandbox so the packaged backend can't see provider keys leaking from the launching shell. * fix(desktop): use strict runtime check to drive onboarding setup.status returned True whenever any provider auth state was discoverable, including indirect fallbacks like a gh-CLI Copilot token. That made desktop think the user was set up while the agent's actual resolve_runtime_provider call still raised AuthError, leaving the user with a useless toast and no onboarding. Add a setup.runtime_check gateway method that runs the same resolver the agent uses on session creation, and switch the desktop onboarding overlay and prompt precheck to use it. * feat(desktop): OAuth-first onboarding using existing dashboard provider API Replace the engineer-flavored API key form with a Sign-in-first onboarding overlay that uses the dashboard's existing /api/providers/oauth catalog and PKCE/device-code endpoints (Anthropic, Nous, OpenAI Codex, etc.). API key entry is now a fallback tab with friendly provider names instead of env var prefixes, and the loud raw resolver error is gone in favor of a one-line welcome message. * fix(desktop): polish onboarding provider list Reorder OAuth providers so Nous Portal is first, give the segmented Sign in / API key control equal column widths, and replace the engineer-flavored backend names like "Anthropic (Claude API)" / "MiniMax (OAuth)" with friendlier in-app titles. External-CLI providers now show a softer subtitle and an external-link icon instead of a chevron. * refactor(desktop): split onboarding overlay into store + view Move the OAuth state machine, runtime check, copy-to-clipboard, and api-key save into store/onboarding.ts (matching the boot.ts pattern), leaving the overlay as a presentation layer that subscribes via useStore. Tabs are now table-driven, child panels read flow from the store instead of prop-drilling, and the polling/PKCE/error/success branches share a small Status atom. * fix(desktop): external CLI providers + center mode tabs External-CLI providers (Claude Code, Qwen Code) now open an in-overlay panel with the CLI command, copy button, and an "I've signed in" recheck instead of firing an invisible toast. Center the Sign in / API key tab control so it sits under the heading instead of hugging the left edge. * fix(desktop): drop onboarding tabs for an inline link, group device-code waiting state Replace the Sign in / API key tab pair with an "I have an API key" footer link under the OAuth provider list, with a "Back to sign in" affordance inside the API key form. Group the device-code "Waiting for you to authorize..." status next to the Cancel button so the alignment matches the action. * refactor(desktop): tighten onboarding store + overlay Drop the dead isOnboardingBusy/BUSY set, factor the catch-fallback dance into safeReq, and share a single reloadAndConnect helper between PKCE submit, device-code success, external recheck, and api-key save. In the overlay, extract Step / CodeBlock / FlowFooter / CancelBtn / DocsLink atoms so the four sign-in panels share the same chrome instead of repeating it inline. Net effect: fewer literal divs, one place to touch the spacing, and the code-block + footer rows are reusable across future flows. * fix(desktop): mount onboarding from frame 1 to kill the FOUT Default onboarding.configured to null (unknown until the runtime check resolves) and have the onboarding overlay render whenever it's not yet confirmed true. The boot overlay now yields to it, so the very first paint is the Welcome card with a "While we get you set up..." progress strip instead of a flash of the chat shell between boot dismiss and onboarding mount. The picker swaps in cleanly once the gateway opens and the runtime check confirms the user is not configured. Already-configured users see the same prep card briefly while their existing runtime warms up, then the overlay dismisses without touching the chat shell. * fix(desktop): top-align empty sessions placeholder The "Start a chat to build your history." empty state used a min-h-35 grid place-items-center container, which floated the text in a tall dead zone. Render it as a flat paragraph that sits right under the section header like the empty pinned state does. * refactor(desktop): drop dead boot overlay Onboarding overlay subsumes the boot card now that it mounts from frame 1 and renders boot progress inline. The standalone DesktopBootOverlay is unreachable in every flow (yields whenever onboarding has not confirmed configured, dismisses once it has). * fix(desktop): hide pinned/recents sections until first session A fresh sidebar showed the Pinned and Recent chats headers with floating empty-state copy underneath. Drop both sections (and the now-orphan SidebarEmptySessionState) when there are no sessions yet — they reappear after the first chat. Skeletons during initial load are unchanged. * feat(gui): route embedded TUI through dashboard gateway (#21979) Inject HERMES_TUI_GATEWAY_URL into dashboard PTY sessions so embedded ui-tui instances attach to the in-process websocket gateway, with coverage for the new env wiring. * Add desktop remote gateway settings Make the desktop gateway connection configurable from settings so local remains the default while remote backends can be saved, tested, and applied without environment variables. * feat(gui): first-class Messaging page + gateway menu redesign - Add Messaging page to the desktop app with per-platform setup, status, and inline guidance. Catalog derives from gateway.config Platform enum + plugin registry, so every messaging adapter the CLI supports (Telegram, Discord, Slack, Mattermost, Matrix, WhatsApp, Signal, BlueBubbles, Home Assistant, Email, SMS, DingTalk, Feishu, WeCom, Weixin, QQ, Yuanbao, API server, Webhooks, plugins) shows up without per-platform code. - New REST endpoints: GET /api/messaging/platforms, PUT and POST /test on the same path. Secrets go through the existing .env pipeline; enable/disable writes config.yaml. - Replace gateway statusbar dropdown with a richer panel: status row, icon-only restart + system-panel actions, recent activity (with timestamps trimmed in display, full text on hover), platform list. - Auto-poll the messaging page every 6s (paused when hidden) so status updates without a manual check. - Drop Settings / Command Center from the sidebar nav (still reachable via shortcuts and the titlebar cog). - Flatten top corners on Messaging/Skills/Artifacts/Chat panes. - Share new StatusDot component across messaging + gateway menu. - Fix gateway/config.py so an explicit platforms.<name>.enabled=false in config.yaml is honored when env tokens are present. - pb-9 on the chat content area for breathing room above the composer. * Potential fix for pull request finding 'CodeQL / Clear-text logging of sensitive information' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> * pin electron version * hide application menu on non-mac systems * interpret compactPreview for non-string vlaues as JSON or an empty string * fix(desktop): keep composer contenteditable mounted across stacked toggle The composer rendered {input} inside two different parent fragments depending on `stacked`. When auto-expand flipped `stacked` (e.g. the moment typed text wrapped past two lines), React reconciled the two branches as different positions and unmounted/remounted the contenteditable. The fresh mount started empty, so any in-flight characters — most reliably reproduced by holding a key — were lost. Replace the conditional with a single CSS Grid whose template-areas swap on `stacked`. The three children (menu, input, controls) keep stable identities across the toggle; only their grid placement changes, which the browser handles without React tearing down the editor. * refactor(desktop): align install layout with install.ps1 / install.sh Make the desktop app's runtime layout match what scripts/install.ps1 and scripts/install.sh produce, so a desktop-only user and a CLI-only user end up with the same files in the same places and can share one install. Layout - ACTIVE_HERMES_ROOT = HERMES_HOME/hermes-agent (was: process.resourcesPath/hermes-agent, read-only) - VENV_ROOT = HERMES_HOME/hermes-agent/venv (was: userData/hermes-runtime) - desktop.log = HERMES_HOME/logs/desktop.log (was: userData/desktop.log) - HERMES_HOME default: %LOCALAPPDATA%\hermes on Windows, ~/.hermes elsewhere The packaged .app/.exe still ships a read-only payload at process.resourcesPath/hermes-agent (FACTORY_HERMES_ROOT). On first launch or after an installer-driven upgrade we sync factory -> active, then provision the venv and run pip install -e . against the active root. Key behaviors - Pin HERMES_HOME in the spawned Python's env so get_hermes_home() resolves to the same path resolveHermesHome() picked. Without this, Python falls back to ~/.hermes on every platform - fine on mac/linux, a split-state bug on Windows where our default is %LOCALAPPDATA%\hermes. - Detect developer installs by .git presence at ACTIVE; never overwrite a user's checkout via factory sync. - Marker at ACTIVE/.hermes-desktop-runtime.json (schema v4) tracks pyproject hash + factory version + runtime schema version. depsFresh fast-paths when nothing changed. - Dev (npm run dev) prefers SOURCE_REPO_ROOT over ACTIVE so devs run their local edits, not whatever's under HERMES_HOME. - Better error messages distinguish "no payload" from "no Python". - Preserve a legacy ~/.hermes on Windows when no %LOCALAPPDATA%\hermes exists, so users with prior pip/manual installs aren't orphaned. pyproject.toml - Promote fastapi, uvicorn[standard], ptyprocess (non-Windows), and pywinpty (Windows) to main dependencies. The dashboard backend (hermes dashboard) needs them at runtime; the previous lazy-import fallback was a footgun for fresh installs. - Empty the [pty] optional-extra; kept as a no-op back-compat alias for any existing pip install hermes-agent[pty] invocations. Drops the hardcoded BUNDLED_RUNTIME_REQUIREMENTS list in main.cjs - the desktop now installs whatever pyproject.toml says, single source of truth. Files - apps/desktop/electron/main.cjs: runtime layout, HERMES_HOME pin, factory->active sync, marker v4 - apps/desktop/scripts/test-desktop.mjs: track new venv location - apps/desktop/README.md: new Setup, Runtime Bootstrap, and Debugging sections - pyproject.toml: fastapi/uvicorn/pty backends in main dependencies; [pty] extra emptied Tested locally on Windows: npm run dev boots cleanly, sessions land at the new location, type-check + lint + test:desktop:platforms all pass. Verified end-to-end on a fresh Win11 VM via dist:win installer. Known gaps (filed as follow-ups, not in this PR): - Skills not seeded on packaged installs (sync_skills only runs in cmd_chat, not cmd_dashboard). Need to move to shared pre-dispatch. - Git Bash not bundled or detected; agent's terminal tool errors out with a useful message but desktop bootstrapper should pre-flight it. - install.ps1 / install.sh should be decomposed into composable phase libraries so the desktop bootstrapper can reuse them as a single source of truth across all install surfaces. * feat(desktop): theme polish, prose chat typography, composer chrome - DS tokens/midground, Backdrop, scoped scrollbars, typography plugin + prose - Composer liquid/radius utilities, thread font parity, tool/thinking cues - File tree label scale, preview flex, thread retry loading + streaming tests * feat(desktop): NSIS prereq detection page + auto-install via winget The packaged Windows installer now detects Python 3.11+ and Git for Windows at install time and offers to install missing prereqs via winget. Mirrors the prereq logic scripts/install.ps1 already runs for CLI installs, so desktop installer users get the same out-of-the-box experience as install.ps1 users. Why - Hermes' terminal tool calls bash.exe directly (tools/environments/ local.py); on Windows that's Git Bash from Git for Windows. Without it, the agent fails on the first terminal() call. - Hermes' Python runtime needs 3.11+. Without it, the desktop bootstrapper errors out at venv creation. - Both gaps surfaced on a fresh Windows 11 VM smoke test: VM had Python pre-installed but no Git, so the agent's first terminal call failed with "Git Bash isn't installed." - install.ps1 has had Install-Git + Install-Uv functions for ages. The desktop installer was the asymmetric outlier. How — NSIS prereq page - New file: apps/desktop/installer/prereq-check.nsh (plugged into electron-builder via build.nsis.include) - Real Wizard page using nsDialogs, inserted via customPageAfterChangeDir hook (between the Directory page and InstFiles). - Group boxes for Python and Git, each showing detection status. - Pre-checked install checkboxes when winget is available. - Auto-skips silently if both prereqs are already installed. - Falls back to manual download URLs when winget itself is missing. - Detection: - Python: probes `py -3.11`/`-3.12`/`-3.13`/`-3.14` via the Python launcher. Microsoft Store "Python stub" (no py.exe) is correctly classified as not-installed. - Git: `where git`. - winget: `where winget` (Win10 1809+ / Win11 with App Installer). - Install execution (in customInstall macro): - Python: nsExec::ExecToLog with `--scope user --silent`. Per-user install, no UAC prompt, output streams to install log. - Git: ExecShellWait via Windows ShellExecute. Critical because Git always installs per-machine and triggers UAC; ShellExecute preserves the foreground focus chain across non-elevated → elevated process spawns, so UAC actually comes to the foreground. nsExec::ExecToLog breaks the chain because winget runs hidden. - Both pass `--disable-interactivity --accept-package-agreements --accept-source-agreements` to suppress winget's own dialogs. - Verification: probes Git's standard install locations via FileExists rather than `where git`. NSIS's process inherits PATH at startup, so a freshly-installed Git won't be visible to `where` until restart. - Silent installs (/S) skip the prompts; managed deploys handle prereqs out-of-band via Group Policy / Intune. How — Electron-side safety net - New findGitBash() in main.cjs, parallel to findSystemPython(). Probes the same locations as tools/environments/local.py:_find_bash() so a positive result here means the agent's terminal tool will work. - ensureRuntime now throws a clear, actionable error on Windows when Git Bash isn't found, matching the existing "Python 3.11+ is required" error path. - Catches users the NSIS page doesn't: .msi installer users (NSIS prereq page doesn't run for MSI), `npm run dev` users, manual installers, anyone who unchecked the install boxes on the NSIS prereq page. - All gated on `IS_WINDOWS`; macOS / Linux unaffected. NSIS build issue (resolved) - electron-builder defaults to `-WX` (warnings as errors). NSIS optimizer emits "warning 6010: function not referenced" for our page functions because Page custom directives don't count as references in its static-analysis pass. The functions ARE called at runtime when NSIS invokes the page; the optimizer just can't see it statically. - Set `build.nsis.warningsAsErrors=false` in package.json so this spurious warning doesn't fail the build. (Documented option from electron-builder's nsisOptions.) Out of scope (filed for future work) - MSI prereq detection: Windows Installer custom actions are a different mechanism. Enterprise deploys typically handle prereqs via GP/Intune. - Bundle PortableGit + python-build-standalone in extraResources for zero-network installs. ~80MB increase. - Mac / Linux GUI prereq flows (different installer formats; Xcode CLT covers most macOS prereqs already; Linux is per-distro hard). Files - apps/desktop/installer/prereq-check.nsh (new, ~290 lines NSIS) - apps/desktop/package.json (build.nsis.include + warningsAsErrors) - apps/desktop/electron/main.cjs (findGitBash + preflight) - apps/desktop/README.md (Runtime prerequisites section) Cross-platform impact - macOS / Linux builds (dist:mac, dist:mac:dmg, dist:mac:zip): nsis config is ignored entirely; .nsh is dormant. - npm run dev: .nsh dormant; main.cjs preflight gated on IS_WINDOWS. - scripts/install.ps1, scripts/install.sh: no reference to any new files; CLI install paths untouched. - Hermes CLI / dashboard / gateway: no reference; runtime untouched. - All checks: node --check on main.cjs and test-desktop.mjs pass; npm run test:desktop:platforms 4/4 passing; node --test green. Tested - npm run dist:win produces signed .exe and .msi without errors. - Fresh Win11 VM (Python pre-installed, no Git): prereq page renders, Python check shows detected, Git checkbox pre-checked. Click Next → Git installs via winget with UAC prompt in foreground. - After install completes, Hermes launches and the agent's terminal tool can run bash commands. Verified Git Bash is detected at `C:\Program Files\Git\bin\bash.exe` by ensureRuntime's preflight. * feat: theme changes, composer tweaks, in app update ux, finesse * fix(cli): seed bundled skills on dashboard + gateway entrypoints `sync_skills(quiet=True)` was only being called from inside `cmd_chat`, which meant `hermes dashboard` (the desktop GUI's backend) and `hermes gateway` (Telegram/Discord/Slack/etc daemons) never seeded the bundled skill library into ~/.hermes/skills/. This surfaced as "No skills found" in the desktop GUI's skills panel on fresh installs, despite the agent having access to the full bundled library when invoked via `hermes chat`. scripts/install.ps1 worked around it by running skills_sync.py as part of Copy-ConfigTemplates, but that's not part of the desktop installer's bootstrap chain. Fix - Extract the skills-sync block from cmd_chat into a module-level `_sync_bundled_skills_quietly()` helper. - Call the helper from cmd_chat (preserving existing behavior), cmd_dashboard (after the --status/--stop early-return paths and fastapi import check, so we don't run skills_sync on management commands or when deps aren't installed), and cmd_gateway. Why these three entrypoints - cmd_chat: the user's primary CLI entrypoint - cmd_dashboard: the desktop GUI's backend; this is what `hermes dashboard --tui` invokes when the desktop bootstrapper spawns Hermes - cmd_gateway: long-running daemons where the user expects the agent to have full skill access Other entrypoints (cmd_config, cmd_doctor, cmd_login, cmd_status, etc.) are management commands that don't need skill discovery and were never running skills_sync in the first place — leaving them alone. Idempotence - tools/skills_sync.py is manifest-based: skipped skills cost milliseconds. Calling it from multiple entrypoints adds no real cost, and users running `hermes chat` then `hermes dashboard` get two fast no-ops on the second call. Failure handling - Helper wraps skills_sync in try/except. Skills are an enhancement, not a hard dependency — Hermes runs fine with an empty skills/ dir. Files - hermes_cli/main.py: + new helper `_sync_bundled_skills_quietly()` at module level + cmd_chat: replace inline block with helper call + cmd_dashboard: add helper call after fastapi import succeeds + cmd_gateway: add helper call before delegating to gateway_command * feat(desktop): hoisted todo widget, JSON tool summaries, history grouping & timer fixes - Hoist todo to first-class widget (shadcn checkboxes, brand colors, no tool-accordion). Header derives label from active task; non-active rows fade. - Replace raw JSON dumps with structured key/value summaries via formatToolResultSummary; nested error extraction for clearer failures. - Fix loaded-session grouping: stitch interleaved assistant/tool iterations into one bubble instead of orphaned synthetic messages. - Stable tool/thinking timers via keyed registry so unmount/scroll doesn't reset elapsed counts; gate "running" on real live thread state. - Reorganize chat-only assistant-ui components under components/chat/. * fix(desktop): address CodeQL alerts on PR #20059 - settings/helpers.ts: harden setNested against prototype pollution. POLLUTING_PATH_PARTS check is now applied at every assignment site (loop + leaf) and uses Object.defineProperty so CodeQL can see the guard inline rather than via a helper function call. - lib/markdown-preprocess.ts: rebuild the dangling-fence close regex from a fence-char + length instead of marker.replace(...). The marker is captured by `(`{3,}|~{3,})` so it can only be backticks or tildes, but CodeQL was tracing tainted input text into the RegExp source and flagging hostname dots from input as part of the pattern (false positive js/incomplete-hostname-regexp on the test fixture URLs). Reconstructing from a literal char breaks the dataflow. - scripts/notarize-artifact.cjs: drop args from the run() rejection message. Args carry --key-id / --issuer / key file path; the existing outer catch already squashes errors to a generic line, but CodeQL was flagging the args.join(' ') as clear-text logging of APPLE_API_KEY_ID. Composer DOM-text-as-HTML alerts (composer/index.tsx:379, :547) are already addressed in 4dd9732a9 — innerHTML assignment was replaced with renderComposerContents which builds DOM via replaceChildren / append text nodes (no HTML interpretation). * fix(desktop): inline prototype-pollution guard so CodeQL sees it CodeQL's dataflow doesn't follow the helper-function guard inside `safeSet`, so it kept flagging Object.defineProperty as prototype- polluting. Inline the literal `__proto__`/`constructor`/`prototype` check at the assignment site to break the dataflow. Behavior unchanged — same set of disallowed keys, same throw. * feat(ui-tui): resolve links to readable page titles Mirror desktop pretty-link behavior in the TUI by resolving HTTP links to page titles with shared caching and safe fetch filters, plus slug-based fallbacks so chat links stay readable even when title fetch fails. * fix(desktop): drop RegExp from dangling-fence close detection Previous attempt tried to break the dataflow by reconstructing the close-fence regex from a literal char + marker.length, but CodeQL still traced marker.length back to input and kept flagging the test-fixture URLs as hostname-regex sources (js/incomplete-hostname-regexp). Replace `new RegExp(...)` + `closeRe.test(body)` with a string-only hasCloseFenceLine() helper that splits on '\n' and uses ===. No regex on this path now, so input data can no longer reach a RegExp source. Behavior preserved: matches lines that are (whitespace + marker + whitespace), which is what the original `\n[ \t]*${marker}[ \t]*(?=\n|$)` matched. All 12 markdown-text tests still pass. * fix(process-registry): suppress windows-footgun false positive on guarded killpg Keep the existing POSIX-only process-group teardown path, but make the signal selection explicit via getattr and add an inline windows-footgun suppression marker on the guarded os.killpg line so the Windows footgun check no longer blocks CI on this intentionally platform-gated code. * feat(desktop): reconcile live tool events, polish thread chrome, harden boot - chat-messages: match tool rows by overlapping query/context/preview values so preview-first `tool.progress` rows reliably adopt later stable-id `tool.start` payloads instead of spawning ghost rows or mis-merging parallel same-name calls; preserve prior args/result across phases. - tui_gateway: emit full args + parsed result on `tool.start` / `tool.complete`, drop redundant `tool.started` re-emit from `tool.progress`. - electron/main: prefer SOURCE_REPO_ROOT before PATH `hermes` in dev so local backend edits actually run; split hardening helpers into `electron/hardening.cjs` with tests. - thread/tool UI: one-shot enter animation keyed by stable ids, braille spinner for running rows, Cursor-like disclosure rows, drill-down + duration/count formatting via new tool-fallback-model. - composer: extract `text-utils`, drop liquid-glass overrides. - right-rail: split preview-pane into preview-console / preview-file. - runtime: incremental external-store runtime + runtime-readiness gate; onboarding store + tests; route-resume hook test. - regression tests for live tool reconciliation (parallel tools, id-less progress, preview-first rows, structured args/results). * feat(desktop): add ripgrep to NSIS prereq page + polish layout Add ripgrep as a third (recommended) prereq alongside Python and Git in the NSIS prereq detection page, and clean up the page layout based on on-VM testing. Why ripgrep - Hermes' search_files tool calls `rg` directly for content + filename search (tools/file_operations.py:1382). Falls back to grep/find from Git Bash when missing — works but slower and noisier (no .gitignore awareness). - ~5MB winget install via `BurntSushi.ripgrep.MSVC --scope user` — no UAC prompt, parallel to how Python installs. - scripts/install.ps1 already installs ripgrep as part of Install-SystemPackages; this brings the desktop installer to parity. Why "recommended" not "required" - Python and Git are hard requirements: without them the agent runtime or terminal tool refuses to start. The bootstrapper preflight throws. - ripgrep is a performance enhancement: missing it just means slower searches. Page wording reflects this; failure to install is logged but doesn't show a MessageBox or block. Layout polish (response to on-VM screenshot review) - Wizard header now correctly reads "System Requirements" instead of the leftover "Choose Install Location" from the previous page. Set via `GetDlgItem $HWNDPARENT 1037/1038` + WM_SETTEXT — the standard NSIS pattern for overriding the page header on a custom Page. - Removed redundant in-body title + verbose intro paragraph; the wizard header IS the title now. Body has one short intro line. - Group boxes tightened to 26u with content positioned just below the groupbox title (not top-anchored status + bottom-anchored checkbox with empty space in the middle). All three panels + footer fit comfortably in 126u, well under the 140u page limit. - Checkbox labels simplified: dropped "(per-user, no admin prompt)" and "(administrator approval required)" suffixes. The footer note still calls out UAC for Git when relevant. - Footer text trimmed to fit cleanly without clipping. Install order (in customInstall macro) - Python → ripgrep → Git - Python and ripgrep are silent and run first; Git's UAC prompt comes last so the user's approval interaction isn't interrupted by silent activity afterwards. Skip behavior unchanged - All three detected → page auto-skips via Abort - Silent install (/S) → customInstall winget block skips - User unchecks all → page advances without running winget Files - apps/desktop/installer/prereq-check.nsh: ripgrep detection block, ripgrep page panel + checkbox, ripgrep customInstall block, GetDlgItem header override, layout reflow - apps/desktop/README.md: Runtime prerequisites section updated to list ripgrep as recommended, with manual winget command * feat(desktop): add model-confirmation step to onboarding After OAuth/API-key login completes, onboarding now shows a confirmation card with the curated default model and a Change button before dropping the user into chat. Closes the gap where the desktop's `model.default` was empty after first launch and the agent had to fall back to whatever heuristic happened to fire — leaving users wondering "why am I getting sonnet-4 when I logged into Nous Portal?" Why - Desktop onboarding only persisted credentials, never `model.default`. The CLI's `hermes model` command pairs provider + model selection, but the desktop's onboarding skipped the model step entirely. - Result: users saw whichever model the agent's auto-fallback picked, unpredictably and undocumented. - For the BUILD demo we want users to land on the model they expect for their provider, with a clear "this is what you're getting" UI and a one-click path to change it before chatting. How - New `confirming_model` flow status carries the just-authenticated provider slug, current default model, label, and a saving flag. - `completeWithModelConfirm()` runs after credentials succeed: reloads env, verifies runtime, fetches /api/model/options to find the curated first-model for the provider, persists it via /api/model/set, then transitions into `confirming_model`. - If anything fails (no providers returned, network error), falls through to the previous behaviour — onboarding completes without the confirm step. Polish, not a hard requirement. - All four credential paths (device_code OAuth, PKCE OAuth, external CLI flow, API key) now use completeWithModelConfirm instead of reloadAndConnect. UI - `ConfirmingModelPanel` shows: green "<provider> connected" banner, card with "Default model: <name>" + Change button, and a "Start chatting" CTA that finalises onboarding. - Reuses the existing `ModelPickerDialog` (the same picker available from the chat shell) for the change-model UX. Search, filtering, multi-provider listing — all already built. - Stacking: ModelPickerDialog defaults to z-130, which renders UNDER the onboarding overlay (z-1300) and breaks pointer events. Added optional `contentClassName` prop to ModelPickerDialog so callers can override; onboarding passes `z-[1310]`. Provider-slug matching - For OAuth flows: pass `provider.id` directly as the preferred slug. - For API-key flows: `OPENROUTER_API_KEY` → "openrouter" via env-key prefix strip. Also includes the user-visible label as a fallback candidate. - fetchProviderDefaultModel falls back to the first authenticated provider in the response if no preferred slug matches — so even a miss still surfaces a reasonable default. Files - apps/desktop/src/store/onboarding.ts: + new `confirming_model` flow variant + fetchProviderDefaultModel + completeWithModelConfirm helpers + setOnboardingModel (optimistic update + revert on failure) + confirmOnboardingModel (finalises onboarding from the card) - reloadAndConnect (replaced; the four call sites now go through completeWithModelConfirm) - apps/desktop/src/components/desktop-onboarding-overlay.tsx: + ConfirmingModelPanel component + new branch in FlowPanel for status `confirming_model` + ModelPickerDialog usage with z-[1310] content class - apps/desktop/src/components/model-picker.tsx: + optional `contentClassName` prop on ModelPickerDialog so the dialog can be stacked on top of other fixed overlays Tested - `npm run type-check` passes - `npx eslint` clean on touched files - Live test in `npm run dev`: cleared onboarding cache, walked through Nous device-code flow, saw confirm card with curated default, clicked Change → ModelPickerDialog rendered above the onboarding overlay with working pointer events, picked a different model, "Start chatting" persisted to ~/.hermes/config.yaml. * fix(desktop): suppress generic provider warning in onboarding Hide the red setup notice when the message is the generic missing-provider guidance, since onboarding already presents provider auth actions. Centralize provider-setup matching across desktop hooks and add coverage for the matcher. * fix(desktop): add 2u clearance below prereq checkboxes Group box bottom border was clipping the checkboxes by 1-2px. Bumped each box height 26u→30u; checkboxes now sit 2u above the bottom border. * fix(nix): refresh dashboard lockfile hash Update the web npm deps hash in nix/web.nix to match the committed apps/dashboard/package-lock.json so bb/gui passes the nix lockfile check. * fix(desktop): install TUI deps in release workflow Ensure desktop release builds install the standalone ui-tui package before bundling the TUI payload. * fix(desktop): run release builder from app package Invoke the desktop builder through the package script so electron-builder uses apps/desktop/package.json. * fix(desktop): expand release artifact names safely Build desktop artifact names from workflow version/channel while preserving electron-builder platform macros. * fix(desktop): use package artifact naming in release workflow Let electron-builder's desktop package config provide platform-specific artifact extensions while the workflow injects the release version/channel metadata. * fix(nix): fetch dashboard npm deps from package root Point the dashboard npm dependency fetch at apps/dashboard so Nix can find the package lockfile after the dashboard move. * fix(nix): build dashboard from package directory Set the web package source root to apps/dashboard so npm patch/build phases run beside the dashboard lockfile while keeping apps/shared available as a sibling. * feat(desktop): render LaTeX math via KaTeX after streaming completes Add @streamdown/math plugin to the chat markdown renderer. Inline ($x^2$) and block ($$...$$) math both supported with singleDollarTextMath enabled. Plugin is gated to non-streaming state to match the existing pattern for syntax highlighting — math renders when the message completes, avoiding KaTeX re-render churn during streaming. KaTeX CSS is imported in styles.css; ~30KB CSS + ~430KB JS added to the bundle. Smoothness improvements during streaming deferred to a follow-up. * perf(desktop): memoize KaTeX renders so math streams without re-rendering Wrap rehype-katex with a per-equation LRU cache (keyed by displayMode + source text) and re-enable math during streaming. Stock @streamdown/math runs rehype-katex on every markdown commit, so each new token re-katexes every equation in the message. For math-heavy responses (an equation derived step-by-step) that's hundreds of ms of wasted work per token and the streaming UI chokes. With memoization, each equation pays katex.renderToString exactly once; subsequent tokens re-walk the tree but hit cache for unchanged equations. The wrapper mirrors rehype-katex's semantics exactly: same class detection (language-math, math-inline, math-display), same <pre>-walk-up for fenced math blocks, same parent.children.splice replacement, same SKIP traversal, same strict-then-lenient render strategy with VFile message reporting. Cached children are structuredCloned on each splice so downstream rehype plugins or toJsxRuntime can't mutate the cache. * fix(desktop): declare katex-memo deps directly + drop per-app lockfile katex-memo.ts (added in 112cad59b) imports hast-util-from-html-isomorphic, hast-util-to-text, remark-math, katex, and unist-util-visit-parents but those were never added to apps/desktop/package.json. They were silently resolving via @streamdown/math at the workspace root, which broke the moment `npm i --prefix apps/desktop` ran with the per-workspace lockfile because that install only consults apps/desktop/package.json. Add them as direct deps, plus unified/vfile/@types/hast for the type imports. Also delete apps/desktop/package-lock.json — root package.json declares workspaces: ["apps/*"], so npm manages all lockfile state at the root. The stale per-app lockfile is what made `npm i --prefix apps/desktop` diverge from the workspace install in the first place and left an empty apps/desktop/node_modules/@assistant-ui/ stub that Vite's dep optimizer then tried (and failed) to open at @assistant-ui/core/dist/internal.js. * feat(desktop): disable Backdrop noise overlay by default The noise overlay defaulted to on, which adds a busy speckle layer over the whole window for every new user. Flip the Leva default to off; the toggle stays in Backdrop / Noise for anyone who wants it back. * fix(desktop): polish LaTeX rendering — currency, code blocks, brackets Five distinct bugs surfaced from a math-heavy stress test: 1. Adjacent code fences glued together. scrubBacktickNoise's second-pass regex /``\s*``/g matched the LAST 2 backticks of one fence + whitespace + FIRST 2 backticks of the next, collapsing two blocks into one. Fixed with lookbehind/lookahead so we only match exactly 2 backticks not part of a longer run. 2. Whitespace eaten between fences and following content. stripPreviewTargets internally calls .trim() which strips leading/ trailing whitespace from each split-segment. For segments between two fences this collapsed \n\n to '', gluing fence close to next block. Fixed by capturing leading/trailing whitespace at the call site and restoring it after the transform. 3. Currency dollar signs eaten as math. With singleDollarTextMath:true remark-math greedy-matched any pair of $, so '$5 ... $10' became one inline math span. Added escapeCurrencyDollars to escape $<digit> patterns to \$<digit> in prose segments (not in code). Trade-off: math expressions starting with a digit (rare — '$5x = 10$') get escaped too. Mirrors the convention in ChatGPT/Claude's UIs. 4. \(...\) and \[...\] LaTeX brackets unsupported. Models often emit these instead of $...$ / $$...$$. Added rewriteLatexBracketDelimiters preprocessor pass. 5. ```latex / ```tex blocks were being routed to KaTeX via a rewrite to ```math. Aligns with GitHub markdown convention: ```math = render as math; ```latex / ```tex = LaTeX/TeX source code (syntax highlighted, not rendered). Conflating them broke teaching/showing-source use cases. MATH_FENCE_LANGUAGES pruned to {'math'} only. Also flipped parseIncompleteMarkdown to true (was !isStreaming) so the math parser can't see $ inside streaming-but-not-yet-closed code fences. Shiki was already deferred via defer={isStreaming} so this doesn't introduce new tokenization cost. Test: 18/18 existing tests still pass; one test updated to expect escaped \$ in currency-prose-with-URL case. * fix(desktop): detect Python via registry/filesystem; pin to 3.11–3.13 Two related fixes for Python detection on Windows: 1. py.exe (Python launcher) is missing from per-user installs that didn't check the launcher option, so 'py -3.X --version' alone misses real Python installs. User-reported case: clean Win11 + official Python.org 3.14 install -> 'where py' returned nothing, our installer offered to install Python again. Both NSIS prereq page and main.cjs now probe in this order: 1. py.exe launcher (when present) 2. PEP 514 registry: HKLM/HKCU\SOFTWARE\Python\PythonCore\<v>\InstallPath 3. Filesystem: %ProgramFiles%\Python<v>, %LocalAppData%\Programs\Python\Python<v> Crucially, we never fall back to running 'python.exe' from PATH on Windows — the WindowsApps stub at %LOCALAPPDATA%\Microsoft\ WindowsApps\python.exe is a redirector that opens the Microsoft Store window if no Store Python is installed. Triggering that during boot would be terrible UX. Registry/filesystem probes never execute the binary. 2. Drop 3.14 from the supported version set. Several Hermes deps (notably pywinpty, which carries Rust crates like windows_x86_64_msvc) don't yet publish 3.14 wheels. With wheels missing, 'pip install -e .' falls back to building from sdist, which needs a Rust toolchain — users see 'could not compile windows_x86_64_msvc build script' on first run. install.ps1 sidesteps this by pinning to 3.11 via uv; the desktop installer doesn't yet have the same uv-managed-Python pathway, so for now we accept 3.11/3.12/3.13 and tell winget to install 3.11 if none of those are present. Revisit when the wheel ecosystem catches up to 3.14 (~early 2026). * feat(desktop): Cron, Profiles, usage analytics, and titlebar fixes - Add Cron and Profiles sidebar routes with full CRUD-style flows and API wiring. - Extend Command Center with auxiliary task overrides and a Usage panel (7d/30d/90d). - Fix titlebar geometry for WSL/Windows (native overlay width, tool spacing). - Remove stray merge conflict markers from pyproject.toml optional deps. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(title-bar): position sidebar toggle button * feat(desktop): composer queue — queue many, edit/delete/cancel-edit, Cursor-style Press Enter while busy with a draft to queue it; with no draft to interrupt and send the next queued turn. Auto-drains one queued turn each time the session settles, same as Cursor. Queue persists across reloads so an interrupted-and-queued turn isn't lost on refresh. Each queued row supports edit-in-composer (with explicit Save/Cancel), send-now (↑), and delete. Drain skips only the entry currently being edited so the rest of the queue keeps flowing. Queue dequeue is transactional — an entry only leaves the queue after `prompt.submit` is accepted, so a rejected submit doesn't drop the turn. Also shrinks the `[interrupted]` marker to a muted one-liner and drops its assistant footer so it stops looking like a real reply. * fix(desktop): handle empty usage analytics totals Co-authored-by: Cursor <cursoragent@cursor.com> * fix(desktop): address PR review titlebar and usage races Co-authored-by: Cursor <cursoragent@cursor.com> * feat(desktop): add MCP settings and live subagent tree Surface configured MCP servers in Settings with JSON edit/save and a gateway-backed reload action so users can manage tool servers without falling back to slash commands. Track live subagent gateway events in a desktop store, show active subagent counts in the Agents statusbar item, and replace the Agents overlay stub with a live spawn tree for the active session. * fix(desktop): move power-user views out of sidebar Keep Cron and Profiles available through lower-prominence chrome entry points so the workspace sidebar stays focused on core chat navigation. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor(desktop): subagent overlay reads like a live transcript, not a dashboard Strip the card chrome and rewire /agents to feel like peeking into the child agent's stream: - subagents store: single `stream` of typed entries (thinking/tool/progress/ summary) replaces the parallel notes/thinking/tools arrays. Drop unused fields (toolsets, depth, apiCalls, reasoningTokens, sessionId). - agents view: no OverlayCards, no boxed stream, no per-row borders. Goal + status pill + indented stream lines, full row width. - Group root spawns into "Delegation N" sections when batch shape + spawn time match — hides task-index interleaving and makes hierarchy obvious. - Sort tree by spawn time, then task_index. Step indicator is one colored pill (primary while running, emerald when done) inside the row, not a trailing pill that wrapped under the chevron. - Tree picks up `subagent.start` (not only `spawn_requested`) and prunes delegate-tool fallback rows once native subagent events land for the session — fixes duplicate "Delegated task" rows alongside the real ones. * feat(desktop): Esc closes every OverlayView-based overlay Lift the keyboard handler into the shared OverlayView so Agents, Settings, Command Center — and anything we build on top of it later — all dismiss on Esc by default. Nested Radix dialogs stop propagation themselves, so a modal opened inside an overlay (e.g. model picker inside Settings) still closes the modal first, not the overlay underneath. Drop the now-redundant Esc handlers in Settings (kept Cmd/Ctrl+P) and Command Center. * fix(desktop): drop numbered step pill on subagent rows The pill was getting clipped at the overlay edge anyway. Just use the status glyph (●/✓/✗/■/○) — the delegation header already conveys "3 workers, 3 active", and order in the list implies which step you're looking at. * fix(desktop): drop noisy "returned N items / empty object" stub strings When a tool returns nothing useful, the row should be silent — the title ("Search Files", etc.) already tells the user what happened. Counting the fields in an opaque payload is engineer-noise. `formatToolResultSummary` and `minimalValueSummary` now return '' for empty arrays / records / unrecognized values; tool-fallback already hides the detail section when its body is empty. * refactor(desktop): subagent rows borrow chat tool patterns (fade-in, lucide glyphs, shimmer) Pull the agents view closer to how chat tool blocks render: - statusGlyph() returns the same lucide BrailleSpinner / CheckCircle2 / AlertCircle vocabulary as tool-fallback's statusGlyph - Stream lines fade-in via useEnterAnimation (one-shot WAAPI), keyed per entry so streamed deltas settle in instead of popping - Subagent rows fade in too, and pick up the existing data-slot=tool-block spacing rules between blocks - Active stream line trails a BrailleSpinner instead of a hand-rolled pulsing rectangle - Goal text drops FadeText (which forces nowrap); keep FadeText only for the single-line meta subtitle - Running rows shimmer the title — same affordance the chat thinking row uses * refactor(desktop): make /agents subagent-only, drop sidebar + dead sections Activity rail and History stub were both noise. Strip the split layout, sidebar, route enum, and the rail/stub helpers — the overlay is now just the spawn tree, centered in a max-w-3xl column so it stops claiming the whole screen for one section's worth of content. * feat: update cron modals * Add dedicated GUI log stream for dashboard debugging. Capture dashboard and PTY websocket lifecycle failures in gui.log and expose it via hermes logs. * Improve desktop runtime UX by surfacing inference readiness in gateway status and hardening WSL link opening. This also stabilizes markdown code/table block spacing and adds root-install guards so desktop dev runs use a healthy workspace dependency tree. * Log detailed GUI websocket failure metadata. Capture richer reject/disconnect/send/parse context for dashboard gateway websocket flows so GUI connection failures are diagnosable from logs. * Default dashboard startup logging to GUI mode. Detect the dashboard subcommand during early CLI bootstrap so gui.log is attached from process start and GUI startup failures are always captured. * Clean up gateway status conditionals and logging bootstrap mode detection. Simplify nested dashboard gateway status branches for readability and use a concise first-subcommand check when selecting early GUI logging mode. * add logging to nsis installer * feat: glass ui pass * fix(desktop): persist inline assistant errors across hydrate/resume - Detect provider failure text arriving via message.complete (HTTP 4xx, "API call failed after N retries", Provider/Gateway error: ...) and persist as an inline assistant error instead of regular completion text, blocking the hydrate that was wiping it. - preserveLocalAssistantErrors: merge by id so same-id hydrated messages keep their local error, and preserve the optimistic user+error pair as a unit (with tail-user dedupe). - Hook all hydrate/resume writers (use-session-actions resume + fallback, hydrateFromStoredSession, syncSessionStateToView) into the merge so stale snapshots can't clobber a failed turn. - Add error to chatMessagesEquivalent so the resume diff actually sees error-only changes and paints them. - editMessage on a failed turn now submits a plain resend (no truncate_before_user_ordinal) and retries plainly on the "no longer in session history" race. Style polish on touched files: - Inline error: text-only treatment (no card). - User stop / edit-composer send: shared Tabler IconPlayerStopFilled glyph + shared icon-button class slot for parity. * feat(desktop): theme xterm with active light/dark mode The right-sidebar terminal hardcoded a light palette, which read poorly on the dark glass surface. Subscribe to `useTheme().resolvedMode` and hot-swap `term.options.theme` so Shift+X (and any other mode change) updates the terminal in place without tearing down the PTY session. Dark mode uses xterm's built-in defaults (white fg/cursor + vivid ANSI 16) with just a transparent background so the glass shows through; light mode keeps the existing hand-tuned overrides for legibility on a bright surface. * feat(sidebar): right-click + drag-reorder sessions and workspaces - Wire right-click on session rows to open the same actions menu; suppresses the OS-native context menu so Windows stops looking awful. - Share dropdown + context menu items via useSessionActions() driving a single declarative ItemSpec[]; render polymorphic over MenuItem. - New shadcn ContextMenu primitive mirroring DropdownMenu styling. - Restore drag-and-drop reordering for Agents (lost during the cwd cleanup) and add reordering of workspace groups via a right-side grab handle. Pinned reorder unchanged. - Generic orderByIds<T> replaces the duplicated session/group orderers; useSortableBindings() hook collapses the two Sortable wrappers. - cursor-pointer on every actionable element; cursor-grab on handles. - KISS pass: baseName() helper, AGE_TICKS table, single WORKSPACE_PAGE constant, flatter SidebarSessionsSection render. * feat(desktop): solarize the xterm palette in both light & dark xterm's default ANSI 16 is tuned for dark and reads candy-bright on the light glass surface (vivid cyans/greens). Ship the canonical Solarized palette (Schoonover) for both modes — same 16 accents either way, only fg/cursor swap between `base00/01` (light) and `base0/1` (dark), so a prompt's colors look uniform across a Shift+X toggle. Background stays transparent in both modes — Solarized's cream/slate backgrounds would fight the glass. * feat(desktop): virtualize chat thread + sidebar via TanStack Virtual Replaces `use-stick-to-bottom` and per-row session rendering with `@tanstack/react-virtual`, matching what Cursor uses. Chat thread (`thread-virtualizer.tsx`): - Natural-flow virtualization (padding spacers, not absolute items) so `position: sticky` on the human bubble still resolves cleanly against the scroller. - Custom at-bottom anchor: pins when armed, disarms on user-driven upward scroll, re-arms at bottom, jumps on session switch + `thread.runStart`. - Loading indicator and `--thread-last-message-clearance` move to a real `[data-slot=aui_composer-clearance]` node; drops the brittle `:nth-last-child(1 of …)` rule that can't fire reliably under virtualization. Sidebar (`virtual-session-list.tsx`): - Flat agents list virtualizes at >=25 rows; pinned and workspace-grouped paths stay direct-render. - `SortableContext` keeps all IDs; only the window mounts; dnd-kit's `setNodeRef` is merged with `virtualizer.measureElement` so rows participate in both DnD hit-testing and TanStack measurement. Drops `use-stick-to-bottom`. Streaming test gets a global `offsetWidth/offsetHeight` stub so the virtualizer's viewport sizing works in jsdom; the scroll-up-doesn't-pull-back invariant still passes. * feat: more ui qa * fix(desktop): trim sidebar terminal startup spacer Drop zsh's initial spacer row before writing the first terminal prompt so new sidebar terminal sessions do not open with a selectable blank line. * chore: uptick * feat(desktop): thin installer + first-launch install.ps1 bootstrap Converges the Windows packaged desktop installer onto a single canonical install topology: drop the Electron shell only (~80MB instead of ~500MB), clone Hermes Agent at a build-time-pinned commit on first launch via install.ps1's stage protocol, and treat the resulting git checkout at %LOCALAPPDATA%\hermes\hermes-agent\ as the canonical install location (same path the CLI installer uses). Future updates flow through the existing applyUpdates() git-pull path. Replaces the previous fat-installer architecture where the .exe bundled a pre-staged hermes-agent source tree under resources/hermes-agent/ that was then sync'd into ACTIVE_HERMES_ROOT at launch -- a complicated factory-vs-active dance with several footguns (FACTORY_HERMES_ROOT mismatch on path resolve, isGitCheckout guard regressions, pyproject hash drift detection inside the sync loop). Architecture overview --------------------- Build time apps/desktop/scripts/write-build-stamp.cjs writes apps/desktop/build/install-stamp.json with {commit, branch, builtAt, dirty}. Honours $GITHUB_SHA / $GITHUB_REF_NAME in CI, falls back to `git rev-parse HEAD` locally. apps/desktop/scripts/stage-native-deps.cjs copies the runtime subset of @homebridge/node-pty-prebuilt-multiarch from the workspace-root node_modules into apps/desktop/build/native-deps/. Workspace dedup hoists this dep to the root, out of reach of electron-builder's `files:`-restricted collector; staging gives us a deterministic path to extraResources. electron-builder ships both into resources/install-stamp.json and resources/native-deps/ respectively. Boot resolver (electron/main.cjs) Resolver order: 1. HERMES_DESKTOP_HERMES_ROOT override 2. SOURCE_REPO_ROOT (dev mode) 3. ACTIVE_HERMES_ROOT git checkout WITH .hermes-bootstrap-complete marker -- the post-install fast path 4. `hermes` on PATH (CLI-installed user adding the desktop) 5. pip-installed hermes_cli via system Python 6. bootstrap-needed sentinel -> hand off to runBootstrap Deletes the entire FACTORY_HERMES_ROOT / RUNTIME_MARKER / syncTreeExcludingVenv machinery (-200 lines). The isGitCheckout guard that bit us in the install.ps1 PR is gone. First-launch bootstrap (electron/bootstrap-runner.cjs) 1. Resolve install.ps1: prefer SOURCE_REPO_ROOT/scripts (dev), else download from GitHub raw at INSTALL_STAMP.commit (cached at HERMES_HOME\bootstrap-cache\install-<sha>.ps1). 2. Fetch the stage manifest via install.ps1 -Manifest -Commit X -Branch Y. 3. Iterate stages: install.ps1 -Stage <name> -NonInteractive -Json -Commit X -Branch Y per stage. 4. On all stages green: write the .hermes-bootstrap-complete marker with {schemaVersion, pinnedCommit, pinnedBranch, completedAt, desktopVersion}. Per-run log to HERMES_HOME\logs\bootstrap-<ts>.log. Cancellation via AbortSignal. Manifest cache so retries don't re-download. Install overlay (src/components/desktop-install-overlay.tsx) Mounted alongside the existing onboarding overlay; flexbox card with header (static) + middle (scrollable) + footer (failure-only, static). Subscribes to hermes:bootstrap:event IPC + resyncs from hermes:bootstrap:get on mount/reload. Renders: - 14-stage checklist with per-stage state icons - Overall progress bar + current-stage spotlight - Auto-expanded installer-output panel on failure - "Copy output" button (full ring buffer + error to clipboard) - "Reload and retry" wired through hermes:bootstrap:reset to clear main.cjs's latched failure Synthetic empty-manifest event from main.cjs flips the overlay to 'active' immediately so the slow install.ps1 download doesn't leave the user staring at the generic Preparing splash. Failure latching (main.cjs) bootstrapFailure module-scope variable holds the rejection after install.ps1 fails. startHermes() throws the latched error immediately when set, bypassing the entire ensureRuntime + runBootstrap chain. Without this, the renderer's ensureGatewayOpen retries would re-run install.ps1 in a 5-10 min hot loop while the user was still reading the failure overlay. Cleared via hermes:bootstrap:reset on user-driven retry. Unsupported-platform overlay (1F) macOS / Linux packaged builds (no install.sh stage protocol yet) emit an unsupported-platform event with a copy-pasteable install command + docs URL. Dedicated overlay branch with "Copy command" + "I've run it -- retry" buttons. install.ps1 additions (Phase 1F.3 + 1F.5) ----------------------------------------- New -Commit and -Tag string params. Precedence Commit > Tag > Branch. Honoured by all three code paths (update / fresh clone / ZIP fallback), with archive URL selection that handles each ref-type variant. Detached-HEAD checkouts intentionally -- they're pins, not branches the user pulls into. EAP=Continue wrap around the new pin-step git invocations. `git fetch origin <commit>` writes the routine 'From <url>' info line to stderr; under the script's global EAP=Stop that terminates the script even though fetch+checkout succeed. Matches the established pattern in Install-Uv, Test-Python, _Run-NpmInstall. Backend fix (hermes_cli/web_server.py) -------------------------------------- CORS allow_origin_regex now accepts Origin: 'null'. Packaged Electron loads index.html via file://; Chromium sets the WebSocket upgrade Origin header to the opaque origin 'null', which the old regex rejected with HTTP 403 before gateway_ws() ever ran. This failure mode was masked in the older FACTORY_HERMES_ROOT architecture because the resolver often found an existing hermes on PATH with different binding behavior. Security maintained: localhost-only bind keeps cross-machine pages out; per-process session token still gates every authenticated /api/ endpoint regardless of Origin. Desktop QoL ----------- DevTools is now enabled in packaged builds (F12 / Cmd+Opt+I). Field-debugging trade-off: tiny attack surface increase versus a much better support story when CSP / WS / theme issues surface. NSIS prereq-check page deleted (-767 lines). The standard Welcome -> License -> Directory -> InstallFiles -> Finish wizard now installs without custom Python/Git/ripgrep detection -- those prereqs are install.ps1's job at first launch. Test infrastructure (Phase 1G) ------------------------------ apps/desktop/scripts/test-desktop.mjs rewritten as a cross-platform bundle validator (was darwin-only and asserted on dead factory- payload paths): NEGATIVE: hermes_cli/main.py is NOT shipped (regression guard) POSITIVE: install-stamp.json carries a real commit + branch POSITIVE: node-pty native deps shipped under resources/native-deps POSITIVE: renderer dist/index.html reachable (asar or unpacked) New nsis mode and npm run test:desktop:nsis script. Validated end-to-end on clean Win10 VM -------------------------------------- Confirmed: NSIS installer drops Electron shell, app launches, install overlay shows progress, install.ps1 clones the pinned commit, 14 stages run to completion, marker written, backend spawns, WebSocket connects, onboarding overlay asks for API key, main UI loads, integrated terminal works. Failures handled: bootstrap stays failed (no hot-loop retry), "Copy output" gives actionable transcript, "Reload and retry" explicitly re-runs install.ps1. What's deferred --------------- - MSIX wrapping (Phase 2): same Electron .exe under MSIX manifest with runFullTrust, signed and submitted to Microsoft Store. - install.sh stage protocol parity (Phase 2): once shipped, the unsupported-platform overlay becomes drive-it-yourself and macOS/Linux packaged installers gain feature parity with Windows. * feat(desktop): persistent terminal pane + fullscreen takeover Adds a VSCode-style "focus terminal" toggle to the right sidebar's Terminal tab that takes over the chat pane area without unmounting the shell. The xterm host is mounted once at the layout root and CSS-overlayed onto whichever <TerminalSlot /> is currently active, so the PTY session, scrollback, selection, focus, and WebGL renderer survive every toggle. Also: - WebGL renderer (matching dashboard ChatPage) so Hermes' TUI skins paint faithfully instead of muting through xterm's default DOM renderer - File drag/drop from the project tree or OS into xterm — paths are shell-quoted (zsh/bash/pwsh/cmd) and written straight into the PTY - Solarized dark canvas with brights promoted to real accent variants (Schoonover's UI-gray brights washed out every TUI accent) - Strip NO_COLOR/FORCE_COLOR/COLORFGBG/TERM=dumb leaking from non-tty parents (CI runners, Cursor's agent shell) so the embedded shell gets truecolor regardless of how Electron was launched - rAF-debounced ResizeObserver — running fit.fit() synchronously during sibling pane transitions crashed the WebGL texture-atlas rebuild * fix(install.ps1): strip UTF-8 BOM regression that broke 'irm | iex' The canonical install flow irm https://raw.githubusercontent.com/.../scripts/install.ps1 | iex fails on PowerShell 5.1 with a cascade of 'The assignment expression is not valid' errors at every param() default value: [string]$Branch = 'main', ~~~~~~ The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments... Root cause: scripts/install.ps1 carries a UTF-8 BOM (0xEF 0xBB 0xBF) as its first three bytes. 'irm' returns the response body as a string; on PS 5.1 the BOM survives into that string as a leading \ufeff character. 'iex' then evaluates the string and PS's parser chokes on the invisible character before param() -- error recovery proceeds into the body but every assignment is reported as broken. This was the exact failure mode the install.ps1 hardening pass (PR #27224) deliberately fixed by stripping the BOM and ensuring the file body is pure ASCII. Commit 4279da4db ('fix(windows): make PowerShell installer parse in 5.1') re-introduced the BOM later, unintentionally undoing the irm|iex compatibility fix; the merge that brought it into bb/gui carried it forward. Fix: strip the three BOM bytes. File body is verified pure ASCII (any-byte > 127 returns false), so PS 5.1 with no BOM falls back to Windows-1252 decoding which is identical to ASCII for our content. Both install paths now work: - 'irm ... | iex' (canonical CLI) - 'powershell -File install.ps1' (programmatic / desktop bootstrap) * install.ps1: detect ARM64 Windows reliably for Node and Git stages Add a Get-WindowsArch helper that reads Win32_Processor.Architecture via CIM (invariant to PowerShell host bitness) with PROCESSOR_ARCHITEW6432 fallback. Use it in: - Install-Git: previously only triggered the arm64 PortableGit asset when invoked from a native-ARM64 PowerShell host. WoW64 / emulated x64 hosts (the default powershell.exe on Windows-on-ARM) saw PROCESSOR_ARCHITECTURE=AMD64 and fell through to the x64 PortableGit build, leaving ARM64 users on emulated Git for Windows. - Test-Node: previously hardcoded the Node download to win-x64 on any 64-bit OS, so ARM64 users always got x64 Node under Prism emulation even though Node ships an arm64 build for Windows. The winget fallback now also passes --architecture arm64 on ARM64. Python remains x86_64 by design: uv intentionally prefers windows-x86_64 cpython on ARM64 hosts for ecosystem (wheel) compatibility (see astral-sh/uv#19015). * install.ps1: harden Install-SystemPackages against winget msstore failures The previous winget invocation discarded stdout/stderr and trusted no signal at all -- not the exit code (winget exits 0 even when it bails "please specify --source"), not output (sent to Out-Null), not the catch handler (winget returning 0 means no exception fires). The only trust signal was a post-install Get-Command rg / Get-Command ffmpeg check, which would also miss the package because %LOCALAPPDATA%\ Microsoft\WinGet\Links (where winget puts command aliases) is added to PATH by AppExecutionAlias machinery only in fresh shells. End result on machines where the msstore source has a cert problem (0x8a15005e -- common on Windows-on-ARM and some corporate networks): silent failure, no log, no breadcrumb, and the user is told the install succeeded. Specifically: - Pin --source winget on every winget install call. Defeats the broken- msstore-source path. We ship nothing from msstore so this is safe and forward-compatible. - Add --exact --id for a tighter package match. - Capture each winget invocation's combined stdout/stderr + exit code to %TEMP%\hermes-winget-<pkg>-<n>.log instead of Out-Null. On the happy path the log is deleted after the post-install check confirms the binary is on PATH; on failure the log is kept and its path is named in a Write-Warn so the user has something to grep. - Refresh PATH to include %LOCALAPPDATA%\Microsoft\WinGet\Links in addition to the User/Machine env-var hives, so Get-Command sees newly- installed winget aliases in the same process. - No behavior change on the happy path. Same Write-Info/Success/Warn cadence, same fallback order (winget -> choco -> scoop -> manual), same $script:HasRipgrep / $script:HasFfmpeg outputs. Verified end-to-end on a real Snapdragon ARM64 Windows host: ripgrep uninstalled, stage re-run, [OK] ripgrep installed in 1.4s, ok:true. * desktop: swap node-pty fork for upstream microsoft/node-pty 1.1.0 The previous dependency, @homebridge/node-pty-prebuilt-multiarch@0.13.1, publishes no win32-arm64 prebuilds on its v0.13.x line, and its v0.14.x betas (which do add an arm64 Windows build) ship no electron-vXXX-win32- arm64 prebuilds at all -- so packaged Electron 40 builds (NMV 143) would fail at runtime even on a successful npm install. Net effect: the desktop's integrated terminal was unbuildable on Windows-on-ARM, in both dev (npm install fails: 404 fetching the node-vXXX-win32-arm64 prebuilt) and packaged builds (no Electron-ABI prebuilt exists). The homebridge fork was originally created because upstream node-pty shipped no prebuilds at all. That hasn't been true since node-pty@1.0 (April 2024), which: - bundles prebuilts for mac (arm64+x64) and Windows (arm64+x64) directly inside the npm tarball -- no GitHub-Releases fetch, no missing-binary failure mode - uses N-API (node-addon-api) for ABI stability across Node and Electron major versions, so the same pty.node binary loads under Node 22 (dev) and Electron 40+ (packaged) without per-ABI rebuilds - is what VS Code, Hyper, and Theia actually ship API surface is identical (spawn / onData / onExit / write / resize / kill) -- no call-site changes needed. Specifically: - apps/desktop/package.json: replace the @homebridge fork with node-pty@1.1.0 (exact pin). Widen `asarUnpack` from `["**/*.node"]` to also unpack `**/prebuilds/**`, because node-pty ships runtime- execed helpers alongside its .node files (darwin spawn-helper has no extension and would not be matched by `**/*.node`; conpty.dll, OpenConsole.exe, winpty.dll, winpty-agent.exe on Windows are also exec'd at runtime and cannot live inside asar). - apps/desktop/electron/main.cjs: update both require() strings to match the new package name and the new staged path under resources/native-deps/node-pty/. - apps/desktop/scripts/stage-native-deps.cjs: point at node_modules/ node-pty. node-pty's prebuilts live under prebuilds/<plat>-<arch>/ (not build/Release/), so update the include glob to copy that dir. Per-arch staging keeps the resource bundle small (target arch comes from npm_config_arch when electron-builder cross-builds, else process.arch). Explicitly enumerate file types in the prebuilds glob so the ~25 MB of .pdb debug symbols that prebuild-install bundles for Windows crash analysis don't bloat the installer (29 MB -> 2.6 MB staged on win32-arm64). Re-assert +x on the darwin spawn-helper defensively, since a stripped mode bit would manifest as a silent ENOENT at first pty.spawn(). - apps/desktop/scripts/test-desktop.mjs: update expectedNativeDepPaths() and its assertion site to look at prebuilds/<plat>-<arch>/ instead of build/Release/. Add an explicit spawn-helper-exists check on darwin so a regression in the asarUnpack glob would fail loudly in CI rather than at first PTY spawn. Trade-off: Linux end-users lose prebuilts and fall back to building node-pty from source on `npm install`. Acceptable because Hermes ships no Linux desktop builds (desktop-release.yml matrix is mac + win only, package.json declares no `linux` target), and Linux developers hacking on the desktop already need a C++ toolchain for the rest of the stack. Verified on Windows 11 ARM64 (Snapdragon): npm install -> exit 0 node -e "require('node-pty').spawn(...)" round-trip -> OK stage-native-deps -> 27 files, 2.6 MB load from staged tree (simulates packaged fallback) -> ConPTY round-trip OK * desktop+gateway: harden Slack socket recovery and Windows restart dedupe (#28873) * desktop+gateway: harden Slack socket recovery and Windows restart dedupe Fix Slack Socket Mode reliability by adding a watchdog/reconnect path so silent socket task drops no longer leave the adapter stuck. Harden Windows gateway lifecycle by avoiding desktop-binary path collisions, making gateway PID scans case/extension tolerant, and reusing in-flight restart actions to prevent duplicate gateway spawns. * test(slack): add Socket Mode watchdog/reconnect behavioural coverage Drive the new Slack Socket Mode self-healing logic through a fake AsyncSocketModeHandler so we can simulate the P0 silent-hang failure mode (task exit, transport disconnected, intentional shutdown, concurrent reconnect attempts) without touching real Slack. * fix(slack,desktop): address Copilot review on watchdog races and path normalization - connect(): explicitly cancel + await the prior socket watchdog before flipping _running, so an old monitor cannot exit between teardown and respawn (Copilot #1) - _socket_watchdog_loop: wrap the body in try/except + add a done-callback that respawns on unexpected crash, so a transient bug cannot permanently disable self-healing (Copilot #2) - normalizeExecutablePathForCompare: use the resolved path for realpathSync so non-string inputs cannot leak through (Copilot #3) - Add tests for crash-recovery and atomic watchdog replacement across reconnects * fix(slack): tighten connect() error path and clarify watchdog test intent Address Copilot review round 2. - connect(): wrap _start_socket_mode_handler/_ensure_socket_watchdog in a focused try/except so any failure rolls back partially-started handler/task state and leaves _running=False, ensuring the platform lock is always released by the outer finally - Defer _running=True until after the handler is actually started so the watchdog observes a live socket task immediately and never spins against a half-built adapter - Rename test_watchdog_self_restarts_after_unexpected_crash to test_watchdog_cancellation_does_not_respawn (matches what it actually asserts) and add test_watchdog_unexpected_exit_respawns_via_done_callback that drives a real RuntimeError through _on_socket_watchdog_done and verifies a fresh task replaces the crashed one * fix(web_server): serialize action spawn check+store under a threading lock Address Copilot review round 3. FastAPI runs sync handlers on its threadpool, so two near-simultaneous /api/gateway/restart (or /api/hermes/update) requests could both observe "no live process" in _spawn_hermes_action's poll-based dedupe and double-spawn. Add a module-level _ACTION_SPAWN_LOCK around the entire check + Popen + _ACTION_PROCS store sequence so the dedupe is atomic across threads. * fix: address Copilot review round 4 - slack.disconnect(): mirror connect()'s defensive cleanup — catch the broad Exception path on watchdog await so handler shutdown and lock release still run if the watchdog raised before cancellation took effect - web_server._spawn_hermes_action: wrap subprocess.Popen in try/except so a missing executable / permission error closes the log file handle, writes a failure marker, and re-raises instead of leaking a file descriptor - gateway._scan_gateway_pids: drop the over-broad "hermes.exe --profile" / "hermes.exe -p" patterns that would match any Hermes CLI subcommand using a profile flag (e.g. `hermes.exe --profile foo dashboard`); rely on the "hermes.exe gateway" + "hermes-gateway.exe" tokens instead - tests: tighten _fake_create_task to assert coroutine input and return a real asyncio.Task that stays pending until pytest teardown, and update the three callsites whose mocked AsyncSocketModeHandler.start_async returned a non-coroutine value * fix(slack): reset multi-workspace state on reconnect Address Copilot review round 5. connect() is reentrant (gateway restart, in-process reconnect), but it was leaving _bot_user_id / _team_clients / _team_bot_user_ids populated from the previous session. A reconnect that rotated the primary token or dropped a workspace would silently keep the stale bot user id and stale workspace client maps, leading to dispatch against gone workspaces. Clear these three pieces of state right after _stop_socket_mode_handler() and before the auth_test loop, then let the loop repopulate from the current tokens. Add test_reconnect_refreshes_multi_workspace_state to lock it in. * nix: package apps/desktop as .#desktop (#28964) Adds nix/desktop.nix building the Electron renderer with buildNpmPackage and wrapping nixpkgs' electron binary. Reuses .#default by setting HERMES_DESKTOP_HERMES to its hermes binary, so the desktop's resolver picks up the fully-wired nix hermes (venv, bundled skills/plugins, runtime PATH) without reimplementing agent resolution. - nix/desktop.nix: renderer + electron wrapper - nix/hermes-agent.nix: finalAttrs form, exposes hermesDesktop in passthru - nix/packages.nix: exposes .#desktop + adds to fix-lockfiles - apps/desktop/package-lock.json: standalone hermetic lockfile nix build .#desktop && nix run .#desktop both clean. * fix(desktop): probe steps 4 & 5 of resolveHermesBackend before trusting A user-reported failure on Windows-on-ARM: a pre-installed Python 3.13 on PATH makes findSystemPython() succeed, so resolveHermesBackend returns a backend pointing at it -- but hermes_cli isn't in that interpreter's site-packages. The spawn dies with ModuleNotFoundError and the user sees a dead GUI instead of the first-launch installer. Same shape can hit step 4 (existing `hermes` on PATH) when a stale shim survives a partial uninstall. Add cheap exit-code probes -- `python -c "import hermes_cli"` for step 5, `<hermes> --version` for step 4 -- and fall through to step 6 (bootstrap-needed) on failure. install.ps1 then runs as if on a clean box and the venv gets built. Probes live in a standalone electron/backend-probes.cjs module so they can be unit-tested with node --test, same pattern as bootstrap-platform.cjs and hardening.cjs. New test file wired into test:desktop:platforms. * test(desktop): allow `node-pty` bare-require in packaged entrypoints Pre-existing failure on bb/gui since c858484b4 swapped the node-pty fork for upstream microsoft/node-pty 1.1.0. main.cjs intentionally bare-requires node-pty (it's hoisted by workspace dedup in dev, and staged to resources/native-deps via scripts/stage-native-deps.cjs + extraResources for packaged builds, with a try/catch fallback at line ~38). The allowlist hadn't been updated to match -- same shape as `electron`, which was already allowed. * chore(deps): refresh root lockfile for dashboard @nous-research/ui 0.14.0 apps/dashboard/package.json was bumped to @nous-research/ui 0.14.0 (+ flag-icons ^7.5.0, motion ^12.38.0) but the root package-lock.json was never refreshed. Running `npm install` from the repo root now materialises 0.14.0's transitive closure (launder, bumps for @nanostores/react, nanostores, sanitize-html, tailwind-merge). No code changes; purely a lockfile catch-up so fresh checkouts on bb/gui get a working dashboard install. * chore(desktop): bump version to 0.0.1 First non-placeholder version so electron-builder's artifactName template produces `Hermes-0.0.1-win-x64.exe` instead of the obviously-unreleased `Hermes-0.0.0-...`. No release process yet; this just stops the artifact filename from telling users "you got a debug build." Bumped in three slots that all carry the desktop app's version: - apps/desktop/package.json (source of truth) - apps/desktop/package-lock.json (per-app lockfile, kept for CI parity) - root package-lock.json's apps/desktop workspace entry Identity-of-build for first-launch bootstrap continues to come from build/install-stamp.json (commit SHA + builtAt), unchanged. * fix: fs icon color * perf(desktop): cut per-keystroke layout + listener churn in chat composer Empirical work via CDP harnesses under apps/desktop/scripts/ (see profile-typing-lag.md): jsListeners growth (per round of 200 chars + GC): before: +35 (verified leak — listeners stuck after 1st trigger popover use) after: +0 Four narrow edits in src/app/chat/composer/index.tsx: 1. Drop the per-keystroke `editorRef.current.scrollHeight` read used to decide composer expansion. Replace with `draft.length > 60` heuristic; the existing ResizeObserver still catches edge cases. `scrollHeight` is a forced-layout call and was firing on every char until the first wrap. 2. Bucket measured composer height to 8px before writing `--composer-measured-height` / `--composer-surface-measured-height` on `documentElement`. Without this, the editor grows ~1px per char, setProperty fires every keystroke, computed style is invalidated tree- wide. 3. Remove the dead `$composerDraft` two-way sync. Nothing outside the composer subscribed to that atom (verified via grep). Two useEffects on `[draft]` were pushing draft→atom and atom→aui per keystroke for no consumer. Also drop the per-keystroke `reconcileComposerTerminalSelections` call; it was pruning stale labels for `terminalContextBlocksFromDraft`, but that helper already ignores labels not in the current submitted text, so pruning per keystroke was just bookkeeping. 4. `refreshTrigger` fast-bails when the draft contains neither `@` nor `/`. Previously `textBeforeCaret(editor)` ran on every input/keyup regardless; `range.toString()` inside is O(n) over draft length. Synthetic typing latency p50/p90/p99 is similar before vs after on a freshly-loaded session (Blink can already handle ~30cps typing into a contentEditable on its own); the real win is the listener leak being gone and the global computed-style invalidations dropping ~8× when the composer is sitting at a fixed height row. The `Enter → stall` follow-up (see profile-typing-lag.md §"Submit / TTFT stall") is unmeasured here — needs a throwaway session because the harness fires a real prompt. Not blocking this commit. * perf(desktop): cut FadeText forced layouts during streaming The slowest user-felt path is typing into the composer while the assistant is streaming. Profile (scripts/profile-under-stream.mjs): FadeText measureOverflow self time: 35.8 ms → 18.1 ms (-50%) total active CPU during 7s window: ~150 ms → ~50 ms Two changes in src/components/ui/fade-text.tsx: 1. Drop the `useEffect([children])` that re-ran `measureOverflow` (reads scrollWidth + clientWidth — forced layout) on every parent re-render. `useResizeObserver` already fires the same callback on mount and whenever the host span's box size changes; that covers the only case where overflow state can legitimately change. The previous explicit useEffect was a forced-layout flush on every parent render, which during streaming meant every token tick. 2. Wrap the component in `memo` with a custom comparator that short-circuits the entire render when scalar string `children` and the className/fadeWidth/style props are unchanged. The hot path was tool-fallback's title chips being re-rendered by parent streaming updates even though their text was stable; memo+ comparator skips that. Also adds two harness scripts under apps/desktop/scripts/: - latency-under-stream.mjs (key→paint latency while a turn streams) - profile-under-stream.mjs (CPU profile while a turn streams) Updates profile-typing-lag.md with the streaming numbers and confirms the Enter→paint submit path is already fast (≤320ms on the populated session; the 2s "stall after Enter" the user noticed once was a one-time cold-start, not reproducible at the UI layer). I'd guess the felt jank in real use is fast-burst typing during a long-form streaming reply (code blocks + markdown lists multiply the per-token render cost). The CPU savings here scale linearly with token volume. * chore(desktop): drop diag scratch scripts no longer needed * docs(desktop): correct leak-typing numbers on a real session Re-ran the leak harness on a populated session (Phaser thread) for both unpatched and patched builds. The original 'listener leak' was transient warm-up cost, not a steady-state leak — both versions show 0 listener growth/round in steady state. The load-bearing number is forced layouts per character: unpatched (HEAD~2): 7.02 layouts/char patched (HEAD): 2.35 layouts/char (3× fewer) The patches reduce per-char forced-layout work to Blink's natural floor. Document node count and heap are flat in both builds. * perf(desktop): fix "Enter jumps up" on long threads User reported: after pressing Enter on a long thread, the view jumps up — the just-submitted message disappears below the fold. Confirmed via apps/desktop/scripts/measure-jump.mjs: before: distFromBottom 0 → 49.5px, sticks there permanently after: distFromBottom 0 → ~0 (worst case 4px for one frame) Root cause in useThreadScrollAnchor (thread-virtualizer.tsx): 1. The sticky-bottom logic disarmed on any scroll event where `scrollTop < lastTopRef.current`. That check can't distinguish a user scrolling up from a programmatic `pinToBottom` write that the browser clamped short of bottom (because content also grew in the same frame, so `scrollTop = scrollHeight` lands at `scrollHeight - clientHeight` for the OLD scrollHeight, which is now below the NEW scrollHeight). Result: sticky-bottom disarmed permanently on the user's first submit. 2. There was no synchronous pin tied to React's commit phase. By the time the ResizeObserver fired and re-pinned, the user had already seen ~50ms of "message below the fold" — visually that reads as the view jumping up. Fix: - `programmaticScrollPendingRef` counter tracks scroll events we expect to be ours (one per `pinToBottom` write). The scroll handler skips the disarm check when consuming a pending tick, keeps the arm bit true, and re-pins synchronously if the browser clamped us short of bottom. A depth cap (8) breaks runaway loops in pathological streaming-burst layouts. - `useLayoutEffect` on `groupCount` increase pins BEFORE the browser paints, eliminating the visible ~50ms window between optimistic user-message insert and the RO/scroll-event chain firing. Verified on the long Cloud Shadows thread (7-8 turns, ~11k px tall): all three repro runs now hold within 0–4 px of bottom across the post-Enter transition. Submit latency unchanged (paint 77–107 ms), streaming-typing latency unchanged. Also adds three debug harnesses: - measure-jump.mjs — sample thread scroll across Enter - probe-thread.mjs — dump current thread / scroll state - diag-jump.mjs — intercept scrollTop + RO + mutations across Enter * perf(desktop): rate-limit thread auto-pin during streaming Follow-up to the Enter-jump fix. The first version did a synchronous re-pin loop inside the on-scroll handler when the browser clamped our `scrollTop = scrollHeight` write short of the new bottom; that gave a tight 4 px visible jump on Enter, but during streaming the ResizeObserver fires many times per second as content grows, and each RO callback re-entered the pin loop. CPU profile showed `Virtualizer.getMaxScrollOffset` climbing to 22 ms self over a typing- during-streaming window — the sync re-pin path was paying tanstack- virtual's recompute cost ~3× per token. Re-architect: - RO callback coalesces to one pin per animation frame. Streaming-rate RO bursts now cost the same as a single per-frame pin. - The on-scroll programmatic-counter guard remains (it's what prevents the false-disarm bug when the browser clamps a write). It no longer does sync re-pins; the next RO/rAF will catch up. - The useLayoutEffect on groupCount (the path that fires on user submit / new turn arrival) ALSO schedules one rAF pin in addition to the synchronous pin. This catches the case where React mounts the new message in a second commit (after our layout effect ran), which grows scrollHeight again. Two pins instead of a tight loop, paid only once per turn change. Net effect on the Cloud Shadows long thread: enter-jump transient: 12–20 px for 1 frame (was 49 px permanent) CPU during stream+type: `getMaxScrollOffset` dropped out of top-5 self-time list typing-during-stream: p50 ~10 ms paint, p99 ~20 ms (1 frame), occasional 40 ms+ outliers during burst token arrivals Also adds scripts/profile-long-stream.mjs: 20-second streaming profile with per-500ms FPS histogram + content-length tracking, so we can see whether streaming render cost grows with message length (it doesn't — sustained 60 fps). * perf(desktop): use textContent for trigger precondition Replace composerPlainText() call inside refreshTrigger's no-trigger fast-bail with a textContent check. textContent is a browser-native flat traversal; composerPlainText walks recursively with chip-aware logic. We only need to know if @ or / appears; either way the trigger char will be in textContent because chips contain @ in their refText. Profile shows composerPlainText was ~18ms self over a 12s typing-during- stream window, called from refreshTrigger on every keystroke. Most of that was the precondition check (the trigger detection path is the slow path but only runs when a trigger char is present). * Revert "perf(desktop): use textContent for trigger precondition" This reverts commit a6a78ff08a31129a3a47fa55aca260d93af913a5. * Revert "perf(desktop): cut FadeText forced layouts during streaming" This reverts commit 88e7d7537cdab87200405edf298e38cb37e0a950. * Revert "perf(desktop): cut per-keystroke layout + listener churn in chat composer" This reverts commit bff1b3261d18a2427ac6c345c99f8312728346dd. * Revert "Revert "perf(desktop): cut per-keystroke layout + listener churn in chat composer"" This reverts commit b7b378e3a43f94b9f4a1a34155707c6301c0fd87. * Revert "Revert "perf(desktop): use textContent for trigger precondition"" This reverts commit 0739588f4896902f7f0d4ded8b5eaeb92bfdf042. * chore(desktop): synthetic-stream perf harness + scripts Drops the React `<Profiler>` approach (no-op because Vite is currently serving the production React build) in favor of an externally-observable measurement stack: rAF frame intervals, `PerformanceObserver({entryTypes: ['longtask']})`, and a `MutationObserver` on the live streaming message. Adds a synthetic stream driver — `window.__PERF_DRIVE__.stream({...})` — that pushes tokens through the live `$messages` atom at a controlled rate, so the assistant-ui runtime, incremental repository, and Streamdown markdown pipeline see the same workload they'd see during a real LLM stream, without the LLM cost. The driver lives in `src/app/chat/perf-probe.tsx`; `main.tsx` side-imports it under `import.meta.env.MODE !== 'production'` so it tree-shakes out of prod builds. (Using `MODE` rather than `DEV` because our Vite setup currently reports `DEV=false` even under `vite dev` — see the dev-build note in `profile-typing-lag.md`.) Scripts: - measure-synthetic-stream.mjs drive synthetic + record frame/longtask/mutation - profile-synth-stream.mjs CPU profile + top self-time during synthetic - measure-real-stream.mjs same harness, real LLM stream - profile-real-stream.mjs CPU profile bracketing the real stream window - eval.mjs / reload.mjs small CDP helpers A real-LLM measurement on Cloud Shadows (gpt-4o-mini, 39 s window) showed 12 longtasks in the same 75-127 ms range the synthetic predicted, so the synthetic is a faithful proxy. * perf(desktop): memo FadeText so it skips re-renders when text unchanged FadeText is used 110+ times inside `tool-fallback.tsx` on a tool-heavy thread. During streaming each parent re-render previously triggered the component's `useEffect([children])`, which forced a `scrollWidth` layout read even when the title text was unchanged. The `useResizeObserver` was already covering the genuine resize case, so that effect was strictly redundant work. Drops the effect and wraps the component in `React.memo` with a custom comparator that field-compares `className`, `fadeWidth`, and `style`, plus identity-compares `children` (scalar fast-path; correct for JSX nodes too since a new node should force a re-render). Verified via temporary render counter on the 34 MB `session_20260514_215353_fe0ac8` thread (110 FadeText instances): a 2 s synthetic stream went from ~11k FadeText render calls to 122 — roughly one render per truly-new instance instead of one per parent commit per instance. Doesn't move the longtask needle on its own (Streamdown's markdown re-parse dwarfs it) but eliminates a steady CPU floor and a class of forced layouts during streaming. Profile-typing-lag.md documents the full investigation, including the remaining Streamdown cost as the real source of the perceived "5 fps moment" hitches. * perf(desktop): memoize MarkdownText plugins to stop churning Streamdown The inline `plugins={{ math: mathPlugin, ...(isStreaming ? {} : { code }) }}` on `<StreamdownTextPrimitive>` constructed a new object literal on every parent render. That broke `<Streamdown>`'s outer memo and forced its internal `rehypePlugins` / `remarkPlugins` array useMemos to rebuild, which propagates a new identity into every `<Block>` and defeats Block's memoization for stable historical blocks. After memoizing on `[isStreaming]` (the only real dimension of variance), CPU profile during a 5 s synthetic stream on the 34 MB session shows `parser` self-time dropping out of the top 10, `compile` cut roughly in half, and `bn$1` / `m$1` (micromark internals) leaving the top entries. Doesn't move the visible longtask count on its own — Streamdown's per-Block parse cost still dominates whenever the last block's content changes — but it removes a class of unnecessary re-parses for historical blocks during streaming. See `scripts/profile-typing-lag.md` for the full investigation. * perf(desktop): floor assistant-text flush gap to 33ms for predictable batching `scheduleDeltaFlush` previously coalesced via `requestAnimationFrame` only. The "at most one flush per frame" guarantee that gives you is fine for fast streams (>~80 tok/sec) where multiple tokens arrive within a single frame, but breaks down at typical LLM token rates (30-80 tok/sec) where each token arrives slower than the rAF cadence and triggers its own React commit + Streamdown markdown re-parse. Track `lastFlushAt` and require at least 33 ms between two flushes. React 18+ auto-batching probabilistically already collapsed some of these, but the floor makes it deterministic. A/B on the 34 MB session, 300 tokens at 50 tok/sec (markdown chunks): | | avgFps | p99 frame | LTs / 5 s | max LT | |---|---|---|---|---| | no floor (current rAF) | 54.0 | 38 ms | 2.0 | 145 ms | | 33 ms floor (this PR) | 54.3 | 41 ms | 1.7 | 110 ms | `inter-mutation` p50 also tightens from 22-28 ms to a clean 33 ms, which is the expected signature of a deterministic floor. Doesn't fully solve the user's perceived hitches — Streamdown's per-Block parse cost when the last block grows past ~2 k chars is still the elephant — but it consistently shaves the worst-case longtask and makes the streaming cadence visibly steadier. Also threads a matching `flushMinMs` option through the synthetic stream driver in `perf-probe.tsx` + `scripts/measure-synthetic-stream.mjs` so the harness can A/B both regimes without spending LLM credits. See `scripts/profile-typing-lag.md` for the full investigation. * perf(desktop): useDeferredValue for streaming markdown so parses don't block input Streamdown's per-Block parse cost grows with the live tail's length and is unavoidable inside the block-memo pattern (industry standard, see findings doc). The fix is to stop having that work block the main thread. `<DeferStreamingText>` is a 12-line wrapper that reads message-part state via `useMessagePartText`, runs it through `useDeferredValue`, and re-publishes via assistant-ui's `<TextMessagePartProvider>`. The inner `<StreamdownTextPrimitive>` reads the deferred value through the normal `useMessagePartText` hook — no fork, no internal-path imports, fully on assistant-ui's public API. React's concurrent scheduler then: - abandons in-flight deferred renders when a newer token arrives, so intermediate states get skipped under fast streams - deprioritises the markdown render when the main thread has urgent work (typing, scroll), so input stays responsive even while a 100ms parse is queued Streamdown already uses `useTransition` for its block-array setState; this lifts the deferral up to the consumer boundary so it covers the whole pipeline (preprocess → split → repair → parse → render). A/B on the 34 MB session, 300 tokens at 50 tok/sec, markdown chunks (four trials each, with the 33ms flush throttle on for both): | | avgFps | p99 frame | LTs/5s | max LT | typing-while-stream p95 | |---|---|---|---|---|---| | pre | 54.3 | 41 ms | 1.7 | 110 ms | ~17 ms | | post | 58.5 | 31 ms | 2.0 | 117 ms | 14-18 ms | Longtask count + max LT unchanged — useDeferredValue doesn't reduce CPU, only its priority. The avgFps lift and p99 frame drop are the proof that the existing CPU is no longer blocking 60 fps cadence. One clean run logged MUTATIONS=0 — React skipped every intermediate text state and only committed the final one (textbook deferred-value behaviour). The actually-reduce-CPU path is replacing the parser with a state machine like Flowdown — left for a future PR; see `apps/desktop/scripts/profile-typing-lag.md` for the full investigation. * feat(desktop): add hermes gui launcher * feat(desktop): launch packaged gui builds by default * bump gui version to 0.0.2 * fix(dashboard): allow file:// origin on loopback WS + diagnostic logging Upstream commit 2e66eefbc ("fix(dashboard): validate WebSocket Host and Origin") added a WebSocket Host/Origin guard to block DNS rebinding against the dashboard. The guard rejects any Origin whose scheme is not http/https or whose netloc is empty — which includes Electron's renderer Origin: file:// when the desktop app loads its bundle from disk in production mode. That makes the bb/gui Electron desktop unable to open the gateway WebSocket against the embedded backend on Windows / macOS prod builds. The renderer reports "Desktop boot failed" and the backend logs: WARNING hermes_cli.web_server: gateway-ws reject peer=127.0.0.1:NNNN reason=non_loopback_or_bad_origin bound_host=127.0.0.1 close_code=4403 DNS-rebinding requires a DNS-resolvable hostname; file:// has no host component and therefore cannot be the attack vector this guard exists to block. When bound to a loopback interface (127.0.0.1 / ::1 / localhost), accept file:// origins so desktop wrappers can attach. Non-loopback binds (operator opted into network exposure) keep rejecting file:// — the loose policy doesn't apply. Also adds per-reason diagnostic logging in _ws_host_origin_is_allowed, so future ws-guard rejections name the specific clause that fired (bad_host / bad_origin_scheme / origin_host_mismatch) instead of the opaque "non_loopback_or_bad_origin" surfaced at the call site. Verified against tests/hermes_cli/test_web_server_host_header.py (all 11 upstream tests still pass) and hand-tested by opening the bb/gui Electron desktop dev build against the patched backend. * fix(tui_gateway): restore _content_display_text helper Bb/gui had dropped the helper but the orchestrator code merged from main still calls it (_inflight_text, _message_preview). Re-add the definition verbatim from main so session.create / _start_inflight_turn don't crash with NameError on first prompt submit. * fix(tui-gateway): restore _content_display_text helper lost in main merge The May 27 merge of origin/main into bb/gui re-introduced two callers of _content_display_text (in _inflight_text and _history_to_messages) but dropped the helper definition itself, leaving an unresolved reference. NameError fires on every user message via _start_inflight_turn -> _inflight_text, taking down both the TUI and the desktop (which share this gateway backend) the moment input is dispatched. Restores the helper verbatim from main (commit 36c99af37) -- pure structured-content text extractor, no other dependencies. * fix(telegram): import Set for _dm_topic_chat_ids annotation self._dm_topic_chat_ids: Set[str] = {...} at line 460 references Set but only Dict, List, Optional, Any are imported from typing. The file has no 'from __future__ import annotations', so the annotation is evaluated at runtime and raises NameError on TelegramAdapter construction. * fix(setup): drop shadowing inner importlib.util re-imports _print_setup_summary and _setup_tts_provider each had 'import importlib.util' inside a try: block nested deeper in the function body. Python flips importlib to function-local for the whole scope, so earlier references in the same function (the neutts branches at lines 493 / 1109) hit UnboundLocalError before the late import can run. The top-of-module 'import importlib.util' at line 14 already covers both call sites, so dropping the redundant inner imports restores the intended behavior. * feat(install.ps1): add -IncludeDesktop switch + Stage-Desktop The new Hermes-Setup.exe (Tauri bootstrap installer) passes -IncludeDesktop so users who install via the GUI end up with a launchable Hermes.exe at apps/desktop/release/<os>-unpacked/. Existing flows are unchanged: * The 'irm install.ps1 | iex' CLI one-liner omits the flag — terminal users don't need a prebuilt desktop binary; 'hermes desktop' builds on demand. * The Electron desktop's bootstrap-runner.cjs also omits the flag — rebuilding apps/desktop from inside a running Hermes.exe would try to overwrite the live binary on disk and fail. Stage-Desktop runs after Stage-NodeDeps so workspace npm is already installed when electron-builder fires. It does: 1. 'npm install' at repo root so apps/* workspaces resolve their deps (Electron itself arrives via npm here, ~150MB) 2. 'npm run pack' in apps/desktop (tsc + vite + electron-builder --dir) 3. Probes apps/desktop/release/{win-unpacked,win-arm64-unpacked}/Hermes.exe The --dir mode produces an unpacked launchable binary without an NSIS/MSI installer artifact — we don't need one because Hermes-Setup.exe spawns the unpacked binary directly via launch_hermes_desktop. * feat(installer): Tauri bootstrap installer for first-time onboarding Hermes-Setup.exe is a small signed Rust+Tauri binary that drives scripts/install.ps1 stage-by-stage with a native UI matching the desktop's design language. Replaces the chicken-and-egg pattern of shipping a 200MB Electron app whose first launch existed only to run install.ps1. The architecture: Rust backend (src-tauri/): bootstrap.rs orchestrator -- Tauri commands, stage iteration install_script.rs resolve install.ps1 (dev checkout, cache, GitHub raw) powershell.rs spawn powershell, line-stream stdout/stderr, parse JSON events.rs BootstrapEvent types -- mirror bootstrap-runner.cjs paths.rs HERMES_HOME resolution + tracing log setup build.rs bakes BUILD_PIN_COMMIT / BUILD_PIN_BRANCH from 'git rev-parse HEAD' at compile time React frontend (src/): Tauri webview rendering 4 screens (welcome / progress / success / failure), driven by nanostores subscribing to the Rust event stream. Visual layer reuses the desktop's styles.css wholesale via @import so the installer and desktop never drift visually. Distribution: targets = ['app', 'dmg', 'appimage'] -- no NSIS/MSI wrapper. The raw target/release/Hermes-Setup.exe IS the artifact on Windows; .dmg + .app on macOS; AppImage on Linux. One file, double-click, no installer-installing-an-installer pattern. Compile-time pinning: build.rs reads 'git rev-parse HEAD' and emits cargo:rustc-env=BUILD_PIN_COMMIT=<sha> + BUILD_PIN_BRANCH=<branch>. bootstrap.rs's option_env!() picks these up so the binary fetches install.ps1 from the exact SHA it was tested against. CI / release builds can override via HERMES_BUILD_PIN_COMMIT env var. Windows manifest: hermes-setup.manifest declares level='asInvoker' so the productName 'Hermes Setup' doesn't trip Windows's installer- detection heuristic and refuse to launch without elevation. Also declares PerMonitorV2 DPI + UTF-8 active code page + Common Controls v6. Limitations of this initial version: * No code signing -- Windows SmartScreen will warn once on Hermes-Setup.exe ('More info -> Run anyway'). The downstream binaries it produces (Hermes.exe in win-unpacked/, the hermes CLI) are locally-built and therefore don't carry MOTW, so they launch without SmartScreen intervention. Cert procurement tracked separately. * macOS and Linux build paths defined but untested -- Windows-only V1. * fix(installer): pass -IncludeDesktop to manifest, surface launch errors, alias hermes desktop Three bugs found in the first VM end-to-end test: 1. install.ps1 -Manifest was called WITHOUT -IncludeDesktop, so the manifest came back with the 14-stage list (no desktop stage), the UI showed '14 steps' and Stage-Desktop never ran. Pass the flag to both the manifest fetch and the per-stage runs — install.ps1 gates the desktop stage's inclusion on the flag. 2. The Success screen's Launch button silently swallowed the Tauri error when no Hermes.exe existed (e.g. Stage-Desktop was skipped). Wire the error through to inline UI with an alert callout, so the user gets actionable text ('Hermes.exe missing, run hermes desktop from a terminal') instead of an unresponsive button. 3. The Success screen tells users to run 'hermes desktop' from a terminal but the CLI only accepted 'hermes gui' — invalid choice for 'desktop'. Rename the subcommand canonically to 'desktop' with 'gui' as a backwards-compatible alias. Update the _SUBCOMMANDS sets used by session-flag arg parsing + logging-mode probe so both names route to the same logic. * fix(install.ps1): pre-warm electron-builder winCodeSign cache + fix Stage-Desktop $HasNode false-skip Two bugs caught in the second VM end-to-end run: 1. electron-builder's winCodeSign extraction fails on grandma-class Windows boxes because the .7z archive contains macOS symlinks (darwin/10.12/lib/libcrypto.dylib and libssl.dylib pointing at versioned siblings). Creating symlinks on Windows requires SeCreateSymbolicLinkPrivilege, a per-user right that non-admin accounts don't have on stock Windows. Result: every fresh install on a non-admin user fails Stage-Desktop with a 7-Zip 'cannot create symbolic link' error, retried four times, then bails. Fix: Initialize-ElectronBuilderCache pre-extracts winCodeSign-2.6.0.7z ourselves with -snl (don't preserve symlinks, store as resolved file content) AND -x!darwin (skip the entire macOS subtree — irrelevant on Windows). Writes to electron-builder's expected cache dir before electron-builder gets a chance to try its own broken extraction. Idempotent — fast-paths via signtool.exe sentinel check. 2. Install-Desktop's first guard was 'if (-not $HasNode) skip'. $HasNode is set by Stage-Node into $script:HasNode, but in cross-process driver mode (each -Stage NAME is a fresh powershell.exe spawned by Hermes-Setup.exe), that script-scope variable from the PREVIOUS process is invisible — so the guard always fired and Install-Desktop returned in 900ms with a misleading 'Node.js not available' reason. The real npm probe below it never got to run. Fix: re-probe npm directly via Get-Command when $HasNode is empty/false, since by that point Stage-Node has already verified Node is installed and the only question is whether *this* process can see it on PATH (it can — installer-wide PATH update from Stage-Node). * fix(install.ps1): tell electron-builder we're NOT signing instead of pre-extracting winCodeSign The previous commit (c7e46f9f3) worked around the winCodeSign-symlinks- on-Windows extraction crash by pre-extracting the archive ourselves with -snl + -x!darwin. That fix was correct but addressed the wrong layer. The deeper question: why was electron-builder fetching winCodeSign at all when we have no signing cert configured? Answer: electron-builder unconditionally pre-warms the toolchain assuming any build MIGHT sign. The cert auto-discovery never finds anything (we never set CSC_LINK or anything else), so the signing never happens — but the 100MB fetch of winCodeSign and its broken-on-Windows symlink extraction does. Set CSC_IDENTITY_AUTO_DISCOVERY=false (with WIN_CSC_LINK and WIN_CSC_KEY_PASSWORD also explicitly cleared as belt-and-suspenders) before invoking npm run pack, and electron-builder skips the entire winCodeSign apparatus. No download, no extraction, no privilege check. Env vars are saved/restored around the invocation so we don't leak the override into Stage-PlatformSdks etc. Net: removes the 100-line Initialize-ElectronBuilderCache helper that manually downloaded + extracted winCodeSign-2.6.0.7z. Replaced with 3 env-var assignments. The produced Hermes.exe is functionally identical — just no longer carries a code-signing-machinery dependency we never used. * fix(installer): bump bootstrap-installer.log to capture stage transitions + every install.ps1 line Diagnosing the second VM failure was impossible because bootstrap-installer.log contained only the 'starting' banner. Two causes: 1. emit_log() inside run_bootstrap() was tracing::debug! — dropped on the floor under the default INFO env-filter. 2. The per-stage sink callbacks (on_stdout_line / on_stderr_line) only emitted Tauri events to the frontend; they never tee'd to the log file at all. When the failure route mounts, the Tauri event stream is the only place the script output lived, and it gets discarded. 3. The Failed / Stage / Manifest / Complete lifecycle frames in emit_event() were also Tauri-only — so even the 'which stage failed' frame never reached the log. Fixes: * emit_log() → tracing::info! * Sink callbacks tee stdout to info!, stderr to warn!, with stage label as a structured field for grep'ability * emit_event() now matches on the variant and logs each lifecycle frame at the right level: Failed → tracing::error!, others → info! Result: a failing install leaves a complete forensic trail in bootstrap-installer.log — manifest stage list, every install.ps1 stdout/stderr line tagged by stage, the stage transitions, and the final error. Same path as before so nothing the user does changes. * fix(install.ps1): Stage-NodeDeps cross-process $HasNode + stream npm install output to bootstrap log VM run 3 diagnosis: node-deps stage skipped on the VM (logged 'Skipping Node.js dependencies (Node not installed)') and then desktop's npm install failed with exit 1 and zero diagnostic detail. Two root causes: 1. $HasNode false-skip in Stage-NodeDeps — same cross-process bug pattern we fixed for Stage-Desktop in c7e46f9f3. Stage-Node ran in process A and set $script:HasNode = $true, then exited. Stage- NodeDeps ran in fresh process B (Hermes-Setup.exe -Stage NAME spawns each stage independently), where that variable doesn't exist. Re-probe via Get-Command npm instead of trusting the stale script-scope global. The previous stage already verified Node so the re-probe succeeds. 2. npm install --silent + Tee to TEMP file hid the real error. When the workspace install failed on the VM, the actual reason was buffered in $env:TEMP\hermes-npm-desktop-install-*.log and the user saw only 'exit 1'. Drop --silent so npm streams its full output, drop the TEMP-file dance — the Tauri installer's streaming sink already tees every stdout/stderr line to the rolling bootstrap-installer.log, so a side log file is dead weight that hides the very error we need. After this, the bootstrap log on a failure will contain npm's full output (deprecation warnings, ETARGET, native-module compile errors, whatever) tagged with stage=desktop, making the actual cause diagnosable instead of an opaque exit code. * fix(install.ps1): restore Initialize-ElectronBuilderCache (CSC env vars alone aren't enough) VM run 4 diagnosis: even with CSC_IDENTITY_AUTO_DISCOVERY=false set, electron-builder still fetches winCodeSign and signs bundled binaries. The log shows the signing happens BEFORE the cache extraction: • signing with signtool.exe ...\winpty-agent.exe • signing with signtool.exe ...\OpenConsole.exe • downloading winCodeSign-2.6.0.7z • <symlink privilege error> Cause: node-pty's bundled prebuilds are listed in apps/desktop's asarUnpack ['**/*.node', '**/prebuilds/**']. electron-builder re-signs anything unpacked from asar, regardless of whether OUR binary gets signed. The signtool invocation needs winCodeSign on disk, which needs the .7z extracted, which hits the macOS-symlink crash on non-admin Windows. The CSC env vars I added in d5fe46727 only kill IDENTITY DISCOVERY (so OUR Hermes.exe stays unsigned, which is fine — we have no cert). They don't prevent the toolchain fetch for the bundled-prebuild re-sign. I removed the pre-extract in d5fe46727 thinking the env vars subsumed it; that was wrong. Both are needed. Restoring Initialize-ElectronBuilderCache verbatim from c7e46f9f3 and keeping the CSC env vars. Wrote a clearer doc-comment at the call site explaining the two-knob interaction so future maintainers don't drop one half again. * fix(desktop): disable signtool via signtoolOptions.sign=null, drop dead winCodeSign pre-extract VM run 5 diagnosis: the pre-extract from 3b29e65c1 ran (extracted 83 files, 24MB) but produced ZERO files at the expected sentinel path '/winCodeSign-2.6.0/windows-10/x64/signtool.exe'. Cause: the .7z archive's root entries are 'windows-10/', 'darwin/', 'linux/', etc. — not 'winCodeSign-2.6.0/<arch>'. Extracting with '-o$cacheRoot' put files at $cacheRoot/windows-10/..., NOT at $cacheRoot/winCodeSign-2.6.0/windows-10/.... I had the directory nesting wrong from the start. And then we observed: electron-builder downloads winCodeSign-2.6.0.7z under a random numeric filename ('384387955.7z') regardless of what's already extracted in the parent dir. The cache key isn't the dirname; it's content-addressed. So the pre-extract approach was doomed even if the path nesting had been right. Actual fix: signtoolOptions.sign=null in apps/desktop/package.json's win build config. electron-builder honors this and skips the bundled- prebuild signing entirely — no signtool invocation, no winCodeSign fetch, no symlink-privilege crash. The previous failures all stemmed from electron-builder pre-signing node-pty's bundled .exes (winpty-agent.exe, OpenConsole.exe) which are already author-signed upstream; re-signing with our nonexistent cert was overwriting good sigs with nothing useful anyway. Cost: when we DO get a real cert later, we'll add it back with the sign function pointing at the cert chain. Until then, all-null is the correct config and unblocks every non-admin Windows user. Removed Initialize-ElectronBuilderCache (the dead pre-extract). Removed the call site. Kept the CSC_IDENTITY_AUTO_DISCOVERY env vars as belt-and-suspenders against a future electron-builder change that might revive cert auto-discovery. * fix(desktop): use no-op sign function instead of sign=null VM run 6 still hit the symlink crash even with signtoolOptions.sign=null. electron-builder 26.8.1 treats null as 'use the default signtool path' rather than 'skip signing', so the winCodeSign fetch + extraction still fired for the bundled prebuild re-sign. The Electron docs (electronjs.org/docs/latest/tutorial/code-signing) make it clear signing is OPTIONAL and unsigned apps work fine — users just see SmartScreen on first launch. The electron-builder mechanism for 'don't actually sign anything' is to supply a custom sign function (via signtoolOptions.sign: '<path-to-cjs-module>') that resolves without invoking signtool. build-noop-sign.cjs is that module — a 5-line async function that returns undefined. electron-builder calls it for every binary it would have signed, gets back a resolved promise, and considers each binary 'signed.' No signtool spawn, no winCodeSign fetch, no symlink crash. When Nous's cert arrives, replace this file with a real signing hook (@electron/windows-sign-based or a direct signtool invocation). The architecture's signing-ready and the cutover is a one-file edit. * fix(desktop): signAndEditExecutable=false to skip signtool path entirely After reading app-builder-lib/winPackager.js line 216 + 231 directly: signAndEditExecutable is the ACTUAL hardcoded gate that short-circuits both signApp() (which signs Hermes.exe + every shouldSignFile match including bundled prebuilds) AND createTransformerForExtraFiles(). None of signtoolOptions.sign / sign:null / sign:<custom-fn> gate the winCodeSign download — that happens before they're consulted. What we lose: rcedit also runs through signAndEditResources, so disabling this drops PE metadata (file properties showing 'Hermes' / 'Nous Research' / file description). Cost is real but bounded: * Hermes.exe filename, icon, asar contents, app identity intact * Task Manager shows 'Hermes.exe' (the filename) not 'Hermes' (PE description) — minor downgrade * Start menu, taskbar, window title all work normally * SmartScreen will warn once (unsigned, same as before) When the cert lands, flip signAndEditExecutable back to default true, both signing AND rcedit return, PE metadata is restored. Removes the no-op sign function (build-noop-sign.cjs) since signAndEditExecutable=false prevents signtool from being invoked at all — the custom hook never gets called either. * feat(install.ps1): write .hermes-bootstrap-complete marker at end of install The desktop app's main.cjs resolver ladder has a 'bootstrap-needed' rung that fires when .hermes-bootstrap-complete is missing from ACTIVE_HERMES_ROOT. Pre-Hermes-Setup, this marker was written by the packaged-desktop's own bootstrap-runner.cjs at the end of its install flow. Now that Hermes-Setup.exe runs install.ps1 directly, install.ps1 needs to own the marker — otherwise the desktop sees no marker on first launch and triggers its legacy first-launch bootstrap (re-running install.ps1 from inside Electron, the exact recursion Hermes-Setup.exe was supposed to obviate). Implementation: * New Stage-BootstrapMarker (worker) → Write-BootstrapMarker (helper) * Slotted in the manifest right after platform-sdks, before the interactive configure/gateway stages, so it runs unconditionally when the install reaches the finalize phase * Schema mirrors apps/desktop/electron/main.cjs writeBootstrapMarker / isBootstrapComplete EXACTLY: {schemaVersion: 1, pinnedCommit, pinnedBranch, completedAt}. Schema version stays at 1 so old desktops that read marker files written by future install.ps1s can still parse them. * pinnedCommit comes from -Commit flag (Hermes-Setup.exe passes it) or falls back to 'git rev-parse HEAD' in InstallDir * pinnedBranch from -Branch flag, defaults to 'main' matching install.ps1's own param default Two PS-5.1 gotchas baked into comments: * The ?. null-conditional operator doesn't exist pre-PS7; use explicit if-checks on Get-Command results * Set-Content -Encoding UTF8 emits a BOM in 5.1 and Node's plain JSON.parse rejects BOM — write via .NET's UTF8Encoding(false) to produce BOM-less JSON the desktop's readJson() can parse * feat(installer): drive in-app updates through the Tauri installer Converge update on the same principle as bootstrap: one driver owns all repo mutation. The desktop becomes a pure consumer that hands off to Hermes-Setup.exe --update instead of re-implementing git/pip in Electron. - hermes desktop --build-only: build without launching, so the installer owns the post-update launch (CLI keeps build logic single-sourced). - Installer AppMode {Install,Update} from argv; get_mode exposed to the UI. - Installer self-copies to HERMES_HOME/hermes-setup.exe on install success (no-op guard during --update re-invocation to avoid the locked-exe copy). - Installer --update flow (update.rs): wait for the desktop to release the venv shim, run 'hermes update --yes --gateway' (branch on exit 0/2/other), then 'hermes desktop --build-only', then launch the rebuilt desktop. Reuses the bootstrap event channel + progress UI via a synthetic two-stage manifest. - Desktop applyUpdates() gutted (~105 lines of git/stash/pull/pyproject/pip removed) -> thin handoff: spawn updater, app.quit() to free the shim. Detection (checkUpdates, commit changelog, behind-count) kept intact. - install.ps1 creates Start Menu + Desktop shortcuts to the packed Hermes.exe (never bare 'hermes desktop', which would rebuild every launch). * test update * fix(installer): pass --branch to hermes update in the --update flow The install is a detached-HEAD checkout of a pinned commit. Without --branch, 'hermes update' fell back to its default (main) and switched the checkout to main — a divergent branch that lacks the desktop CLI command — so the update targeted the wrong branch and the rebuild stage failed with 'invalid choice: desktop'. Thread BUILD_PIN_BRANCH (the branch this installer was built against, and the same branch the desktop detected the update on) into 'hermes update --branch <b>' so update + rebuild stay on-branch. * test update * fix(installer): stamp Hermes icon onto Hermes.exe via rcedit (no winCodeSign) The unpacked Hermes.exe showed the stock Electron icon + name in the taskbar because build.win.signAndEditExecutable=false disables BOTH electron-builder's signing AND its rcedit metadata/icon stamping. That flag is load-bearing: enabling it re-triggers signtool -> winCodeSign, whose macOS symlinks crash 7-Zip on non-admin Windows (unfixable dead end). Decouple identity-stamping from signing entirely: after npm run pack, run rcedit ourselves on the produced exe. - Add rcedit as a direct devDependency of apps/desktop (the transitive electron-winstaller copy is fragile). - apps/desktop/scripts/set-exe-identity.cjs: Node helper that calls rcedit's named export to set icon + ProductName/FileDescription/ CompanyName. Node builds argv natively — avoids the PowerShell->exe ->JSON double-escaping that broke the app-builder rcedit path. - install.ps1 Set-DesktopExeIdentity invokes the script after the build, before shortcuts. Best-effort: failure keeps the stock icon, never fails the install. rcedit is a pure PE editor — no signtool, no winCodeSign, no symlinks. Verified locally: stamping a copy of the built Hermes.exe embeds the 32x32 icon and sets ProductName=Hermes. Also fix update-path success-screen flash: in update mode the installer hands off + exits in ~600ms, so don't route to the 'launch Hermes' success view (it flashed before the window closed). * update test * fix(desktop): show 'hermes update' guidance for CLI installs instead of dead-end error A user who installed via the CLI (irm|iex / install.sh) then ran `hermes desktop` has no staged hermes-setup.exe, so clicking Update in-app hit resolveUpdaterBinary()=null and showed a misleading error ('re-run the Hermes installer') with a Try-again button that could never succeed — a dead loop for a perfectly valid install. Treat the no-updater case as an intentional outcome, not a failure: - main.cjs applyUpdates returns { ok:true, manual:true, command:'hermes update' } (no throw, no 'error' stage) when no updater binary exists. - New 'manual' update stage + apply-state.command thread the command to the UI. - updates-overlay ManualView: a polished terminal-native card with the exact command and a copy button, framed as the correct path for a CLI user rather than an error. GUI-installer users are unaffected — hermes-setup.exe present => seamless auto-update runs as before. Zero new process orchestration; can't fail the update demo. * update test * fix(gui): pin /api/hermes/update to the current branch The desktop command-center 'update' action hits POST /api/hermes/update, which spawned bare `hermes update` with no --branch. cmd_update then falls back to its default (main) and checks the working tree OUT of the tracked branch — a bb/gui install silently jumped to main and lost the desktop CLI. Resolve the checkout's current branch and pass --branch <current> from this endpoint only. The engine default (main) is DELIBERATELY unchanged: bare `hermes update` from a terminal, the gateway /update bot command, and the CLI/TUI relaunch path all keep their long-standing 'update against main' contract for the existing user base. Only the GUI button is scoped to update-the-branch-you're-on. Detached HEAD / git failure falls back to the bare default. * update test * fix(desktop): branch-pin the CLI manual-update command card The 'Update from your terminal' card (shown to CLI installs with no staged updater) hardcoded bare `hermes update` — which defaults to main and would switch a bb/gui (or any non-main) checkout off-branch. Same bug we fixed for the GUI button, leaked into the card's copy text. Resolve the checkout's current branch and show `hermes update --branch <current>` for non-main checkouts; keep it bare for main so the card stays clean. Best-effort: bare fallback if branch detection fails. Matches the GUI button + installer --update contract; bare terminal/bot/TUI update paths still default to main, unchanged. * docs: phragg was here * feat(desktop): lead onboarding with Nous Portal + fix fresh-install detection (#34970) - Feature Nous Portal as the primary onboarding card (Recommended tag, app logo, single pitch line); collapse other OAuth providers behind an "Other providers" disclosure whose open/closed state persists. - Surface OpenRouter as a one-click API-key option inside the disclosure; move "I have an API key" to a quiet bottom-right link. - Treat "no provider configured" as a normal onboarding state, not a red error banner (provider-setup-errors copy match). - Fix setup.runtime_check: it reported ready when the resolved runtime had an empty credential or only implicit Bedrock/IAM, so fresh installs never saw onboarding. Now requires a usable credential. - Auto-wire Windows fonts for WSL2 users so the renderer renders real Segoe UI instead of the DejaVu fallback; make WSL detection env-independent via the /proc kernel marker. * feat(desktop): live elapsed timer on install bootstrap steps The first-launch install overlay showed a static "Installing" with no motion, so long steps (notably the repo clone) looked frozen. Stamp each stage's start time on the running transition and tick once a second so the active step shows live elapsed (e.g. "Installing · 1:23"), plus elapsed on the overall current-step line. Completed steps keep their final duration. * fix(desktop): resolve PortableGit for update checks + reserve titlebar tools space - runGit() hardcoded spawn('git'), which ENOENTs on fresh installer-driven Windows installs (git is PortableGit under %LOCALAPPDATA%\hermes\git, never on PATH) — so "Check for updates" failed with "Couldn't check for updates". Add resolveGitBinary() mirroring findGitBash (PortableGit → Git-for-Windows → PATH) and use it in runGit. - PageSearchShell rendered a full-width search input in the titlebar row, so on Windows its right edge slid under the fixed top-right tools + native window controls. Reserve that footprint via --titlebar-tools-* vars. * fix(desktop): stop streaming caret from shifting layout on completion The streaming caret (::after on the running message's last child) was an in-flow inline-block adding ~0.78em of inline width, which could wrap the last line mid-stream; when the caret is removed on completion the line un-wraps and reflows — the visible post-response layout shift. Net-zero its inline advance with a compensating negative margin so it paints at the text end without consuming layout width. * fix(desktop): stop completed-message layout shift while streaming The assistant message action bar used `hideWhenRunning`, which unmounts it whenever the thread is streaming. Since the bar reserves vertical space in each completed assistant message's footer (it's invisible-until-hover via opacity, not via mount), unmounting it collapsed every prior turn by the bar's height — then remounting on resolve grew them back, shifting the whole conversation (visible as "padding appears above the last user message"). Drop hideWhenRunning so the footer height is constant; the bar stays invisible during streaming via its existing opacity/pointer-events gating. * fix(merge): keep windows-footgun suppressions inline * fix(merge): keep remaining gateway footgun suppressions inline * fix(merge): restore contracts caught by main-target CI * fix(dashboard): honor injected HERMES_DASHBOARD_SESSION_TOKEN The desktop shell mints a session token and signs its /api + /api/ws calls with it via HERMES_DASHBOARD_SESSION_TOKEN, but the main-merge restored a web_server.py that ignored the env var and minted its own random _SESSION_TOKEN -- so every desktop request 401'd and the UI reported "gateway offline". Read the injected token (fall back to a fresh random one) so loopback HTTP + WS auth line up. Adds a regression test so a future merge can't silently drop the read. * fix(desktop): align fresh-install home so upgraders don't brick Two related first-launch bugs on machines with a legacy ~/.hermes: - install.ps1 hardcoded $HermesHome/$InstallDir to %LOCALAPPDATA%\hermes and ignored the HERMES_HOME the desktop passes through. The desktop freezes HERMES_HOME at module load and prefers a legacy ~/.hermes when %LOCALAPPDATA%\hermes is absent, so the installer wrote to a different home than the shell read -> "Could not connect to Hermes gateway". Honor $env:HERMES_HOME in the param defaults. - isBootstrapComplete() trusted the marker + checkout without verifying a runnable venv, so an interrupted/split install spawned a dead backend instead of re-bootstrapping. Also require the venv python to exist. * fix(dashboard): allow packaged desktop file:// origin on loopback WS The packaged Electron desktop loads its renderer over file://, so its /api/ws handshake carries Origin: file:// (or null). The DNS-rebinding WebSocket Origin guard only accepted http(s) origins matching the bound host, so it rejected the desktop's own renderer with 4403 -> "Could not connect to Hermes gateway" on macOS. A browser DNS-rebinding attacker can only ever present an http(s) origin (the site hosting the malicious page); it cannot forge file://, null, or a custom app scheme AND hold the loopback session token. So on loopback binds we now trust non-web origins -- the token in _ws_auth_ok remains the real authenticator. Public/gated binds still reject them, and cross-site http(s) origins are still rejected everywhere. * fix(desktop): resolve renderer assets relative to BASE_URL Absolute public asset paths (/apple-touch-icon.png, /ds-assets/...) work under the dev server but break in the packaged app, where the renderer is loaded from file://.../index.html and a leading slash resolves to the filesystem root -> broken onboarding provider icon and backdrop image on macOS. Prefix these with import.meta.env.BASE_URL so they resolve next to the bundled index.html in both dev and packaged builds. * feat(desktop): automate first-launch bootstrap on macOS/Linux Previously a packaged macOS/Linux app with no Hermes install hit a dead-end ("first-launch install is not yet automated -- run install.sh manually") because install.sh lacked the staged protocol install.ps1 exposes. Now both platforms bootstrap on first launch with the same structured, per-step progress UI as Windows. - install.sh: add --manifest / --stage / --json / --non-interactive plus a stage dispatcher (prerequisites, repository, venv, python-deps, node-deps, path, config, setup, gateway, complete). User-input stages (setup, gateway) are skipped under --non-interactive; the in-app onboarding overlay owns API keys/model, matching the Windows flow. Each stage runs inside the install dir (its own process) and a new --commit flag pins the checkout to the build-stamp SHA. - bootstrap-runner.cjs: drive the staged manifest/stage/JSON protocol for both install.ps1 (PowerShell) and install.sh (bash), selected by installer kind; removed the single-blob POSIX shim. - main.cjs: drop the macOS/Linux unsupported-platform dead-end so the bootstrap-needed path runs the installer on every platform. * fix(dashboard): return 404 JSON for unmatched /api paths instead of SPA HTML The SPA catch-all (serve_spa) served index.html for any unmatched GET, including unregistered /api/* endpoints. A missing API route therefore came back as <!doctype html> with status 200, and JSON clients (the desktop app's fetchJson) crashed with an opaque 'SyntaxError: Unexpected token <' instead of a clear error. - web_server.py: unmatched /api or /api/... now returns 404 JSON ('No such API endpoint'); non-api paths still serve the SPA for client-side routing. - main.cjs fetchJson: detect an HTML body / text/html content-type on a 2xx response and reject with a clear message naming the URL, rather than a raw JSON.parse SyntaxError. Empty bodies resolve to null; malformed JSON reports the URL plus a snippet. * say 'OS appearance' instead of 'macOS appearance' * feat(install): add --include-desktop stage + PowerShell-style flags to install.sh Brings install.sh to parity with install.ps1's bootstrap surface so the shared Rust/Tauri bootstrapper (apps/bootstrap-installer) can drive a macOS/Linux install the same way it drives Windows. - Accept the PowerShell-style aliases the bootstrapper emits to both installers: -Commit / -Branch (alongside existing -Manifest / -Stage / -Json / -NonInteractive). - Add --include-desktop / -IncludeDesktop. When set, the manifest gains a 'desktop' stage (immediately before 'complete'), and a new install_desktop runs a root workspace `npm install` + `npm run pack` (electron-builder --dir, signing auto-discovery disabled) to produce release/mac*/Hermes.app -- mirroring install.ps1's Install-Desktop / Stage-Desktop. - The flag is opt-in, exactly like Windows: the signed bootstrap installer passes it; the Electron app's own first-launch bootstrap and the CLI one-liner omit it (building the desktop from inside the running app would clobber it). * fix: tts endpoints * macOS desktop: install + in-app self-update (#35607) * fix(installer): align macOS HERMES_HOME with the rest of the stack paths.rs computed the macOS Hermes home as ~/Library/Application Support/ hermes, but nothing else does: hermes_constants.get_hermes_home() (Python), scripts/install.sh, and the Electron desktop's resolveHermesHome() all use ~/.hermes on macOS. The drift meant the Tauri installer wrote the install to one directory and the desktop looked for it in another, so a fresh GUI install never found its backend (the file's own comment warned this exact drift would break things). Use ~/.hermes on macOS to match. * fix(install.sh): always emit a stage result frame on failure Stage helpers (clone_repo, install_deps, check_python, …) were written for the monolithic flow and call `exit 1` on failure. Under `--stage`, that terminated the process before the JSON result frame was printed, so the installer's parse_stage_result saw "no frame" instead of a clean {ok:false,...} contract response. Run the stage body in a subshell so an `exit` only unwinds the subshell and the parent still emits the frame. * feat(install.sh): auto-provision git on macOS/Linux (parity with install.ps1) install.ps1 downloads PortableGit on Windows, but install.sh just printed a "please install git" hint and exited — so a fresh Mac with no developer tools (no Xcode CLT → no git) couldn't get past the clone step. check_git now tries to install git before bailing: - macOS: Homebrew if present (headless), else `xcode-select --install` (the CLT prompt also provides the compiler some wheels need), polling for git to appear. - Linux: apt/dnf/pacman via sudo when available. Falls back to the manual instructions only if auto-provision fails. * feat(desktop): in-app GUI+backend self-update on macOS/Linux On Windows the staged Hermes-Setup binary drives updates (quit → hermes update → hermes desktop --build-only → relaunch). The mac drag-install has no such binary, so "Update now" previously just printed `hermes update`. Since there's no venv-shim file lock on POSIX, the desktop can drive the whole update itself. applyUpdates now, when no staged updater exists on mac/linux: 1. runs `hermes update --yes [--branch <current>]` (backend git pull + deps), 2. runs `hermes desktop --build-only` (OS-aware GUI rebuild) with the Hermes-managed Node + venv on PATH, 3. spawns a detached swapper that waits for this process to exit, dittos the freshly built Hermes.app over the running bundle, clears quarantine, and relaunches. Degrades to "backend updated — restart to load the new GUI" if the rebuild fails or there's no .app bundle to swap (dev run, Linux AppImage). * chore: uptick * chore: uptick * chore: linux build * fix(install): detect xcode-select git stub on fresh macOS * chore: bump * fix(desktop): repair voice dictation on Windows Voice dictation was broken on Windows in two ways: 1. Mic access was denied. The Electron permission request handler only granted 'media' requests whose details.mediaTypes included 'audio', but Chromium on Windows frequently fires the mic request with an empty mediaTypes array, so getUserMedia threw NotAllowedError. The handler now grants audio-capture when mediaTypes includes 'audio' OR is empty/absent, handles the 'audioCapture' permission name, and adds a setPermissionCheckHandler (the synchronous path Chromium also consults for getUserMedia on Windows). Video is still denied. 2. Transcripts went nowhere. The composer's insertText handler (used by dictation and other inserts) only updated the assistant-ui composer store via setText, never the contentEditable editor DOM. The draft->editor sync effect only re-renders the editor when it is NOT focused, and dictation runs while the editor has/regains focus, so the transcript was stored but never shown and could not be sent. insertText now renders into the editor DOM and places the caret, mirroring appendExternalText. Also hardens fetchJson: a 2xx response with an HTML body (or text/html content-type) now rejects with a clear message naming the URL instead of an opaque JSON.parse 'Unexpected token <' error. * feat(desktop): route Nous subscribers onto the Tool Gateway from the GUI When the GUI sets the main provider to Nous via POST /api/model/set, call the same apply_nous_managed_defaults the CLI uses after model selection, so GUI/onboarding users land on the Nous Tool Gateway the same way CLI users do — no separate prompt, no duplicated logic. Purely additive: apply_nous_managed_defaults skips any tool where the user has a direct key (FIRECRAWL_API_KEY, FAL_KEY, etc.) or explicit config, so it never overwrites a user's own setup. Only unconfigured tools get routed. - web_server.py: in set_model_assignment (scope=main, provider=nous), resolve enabled toolsets and apply managed defaults; guarded so a Portal hiccup never blocks saving the model. Returns routed tools as gateway_tools. - onboarding.ts: surface a 'Tool Gateway enabled' toast listing routed tools. - types/hermes.ts: add gateway_tools to ModelAssignmentResponse. - tests: cover nous-applies, non-nous-skips, and failure-doesnt-block-save. * feat(desktop): mirror hermes model free/paid curation in GUI onboarding GUI onboarding picked models[0] from /api/model/options, which ignores the Nous free/paid tier — a free user could land on a paid default (e.g. anthropic/claude-opus-4). Now the recommended default mirrors what `hermes model` does. - web_server.py: new GET /api/model/recommended-default?provider=<slug>. For Nous it runs the same curation as the CLI (get_curated_nous_model_ids + pricing + check_nous_free_tier + union_with_portal_{free,paid}_recommendations + partition_nous_models_by_tier) so free users get a free model and paid users get the curated default. Other providers fall back to the first curated model. Never 500s — returns empty model on error so onboarding degrades gracefully. - hermes.ts: getRecommendedDefaultModel client + RecommendedDefaultModel type. - onboarding.ts: fetchProviderDefaultModel prefers the recommended endpoint, falls back to models[0] when unavailable. - tests: free-tier picks free model, paid-tier picks curated default, failure returns empty without 500. * feat(desktop): show model pricing + free/paid tier gating in GUI picker The CLI `hermes model` picker shows per-model $/Mtok pricing and gates paid models on free Nous accounts. The GUI picker showed bare model names. Bring it to parity across both the model-picker dialog and onboarding confirm card. Backend: - inventory.build_models_payload gains a pricing=True flag → _apply_pricing enriches each provider row with formatted per-model pricing ({input,output,cache,free}) via the same _format_price_per_mtok the CLI uses, and for Nous adds free_tier + unavailable_models (paid models a free user can't select) via check_nous_free_tier + partition_nous_models_by_tier. Best-effort: any pricing/tier failure is swallowed and fails open (no gating). - /api/model/options and TUI model.options now pass pricing=True so the global picker and in-session picker both carry pricing. Frontend: - ModelOptionProvider gains pricing/free_tier/unavailable_models; new ModelPricing type. - model-picker dialog renders In/Out $/Mtok (or a Free pill) per model, a Free tier/Pro badge on the Nous heading, and disables + grays unavailable paid models for free users with a 'Pro models need a paid subscription' note. - onboarding confirm card shows the chosen model's price + tier badge. Tests: test_inventory_pricing covers price formatting, free-tier gating, paid no-gating, providers without pricing, and swallowed failures. * fix(desktop): GUI model picker shows curated Nous list in curated order Two bugs made the GUI Nous model list diverge from the `hermes model` CLI picker: 1. Backend (model_switch.py): the Nous row in list_authenticated_providers fell through to cached_provider_model_ids("nous"), dumping the full live /v1/models catalog (~50 vendor-prefixed models, alphabetical). Now it uses the curated list AND applies the Portal free/paid recommendation union — exactly like _model_flow_nous in main.py — so newly-launched models such as stepfun/step-3.7-flash:free surface in curated order. Best-effort: falls back to the curated list alone if the Portal fetch fails. 2. Frontend (model-picker.tsx): cmdk's Command had shouldFilter on (default), which re-sorts items by fuzzy-match score (≈alphabetical) and ignores array order. Set shouldFilter={false} + own the search term and do an order-preserving substring filter, so the backend's curated order is shown verbatim. * feat(desktop): add/switch providers from the model picker via onboarding reuse The model picker could only select models from already-authenticated providers. Switching to a new provider had no in-app path. Rather than duplicate provider UI, reuse the existing onboarding provider selector (featured Nous + other providers + API-key form + device-code/PKCE flow + model-confirm with pricing/tier). - onboarding store: add a 'manual' flag with startManualOnboarding() / closeManualOnboarding(). Manual mode forces the onboarding overlay to show even when configured===true and refreshOnboarding no longer auto-dismisses on runtime-ready (the app is already working — the user is just adding or switching a provider). - onboarding overlay: render when manual even if configured; show a Close button (the first-run flow has none since the app can't run yet). - model picker: 'Add provider' footer button opens the onboarding selector; ModelResults lists only configured (model-bearing) providers. * feat(desktop): add PUT /api/tools/toolsets/{name} enable/disable endpoint * feat(desktop): add toggleToolset RPC binding * feat(desktop): toolset enable/disable switch in Tools settings * feat(desktop): tool configuration parity in GUI Tools settings Bring the desktop GUI Tools settings to parity with the CLI `hermes tools` for provider selection and API-key configuration. Backend (hermes_cli/web_server.py): - GET /api/tools/toolsets/{name}/config - provider matrix + key status - PUT /api/tools/toolsets/{name}/provider - persist provider selection Shared core (hermes_cli/tools_config.py): - Extract apply_provider_selection / _write_provider_config from the interactive _configure_provider so the CLI and GUI write identical config keys (web.backend, tts.provider, browser.cloud_provider, plugin image/video providers, use_gateway flags) through one code path. Desktop UI: - ToolsetConfigPanel: provider list with select, per-provider API-key entry (set/replace/clear/reveal via the shared env RPCs), Ready/Needs keys state, guidance for Nous-auth and post-setup providers. - Wire the Configured/Needs keys pill to expand the panel inline; refresh the toolset list after key changes so the pill updates live. - Add getToolsetConfig / selectToolsetProvider RPC bindings + types. Post-setup (OAuth/install) flows still defer to the CLI; see docs spike findings for the planned /api/tools/setup/* endpoint family. Tests: backend round-trip + 400 cases for the new endpoints and apply_provider_selection; desktop vitest coverage for the config panel (provider render, select, key save). No change-detector tests. Also removes three stale completed plan docs. * fix(desktop): show real Hermes version + sync package.json on release The desktop app version was disconnected from the Hermes version: the release script bumped pyproject.toml + hermes_cli/__init__.py but never touched apps/desktop/package.json, which sat stale at 0.0.2 (lockfile at 0.0.1). - main.cjs: hermes:version IPC now resolves __version__ from hermes_cli/__init__.py (the canonical source release.py bumps) via a new resolveHermesVersion() helper, falling back to app.getVersion() when the source tree isn't readable. The About panel now always shows the live Hermes version and can't drift. - release.py: update_version_files() also bumps apps/desktop/package.json in lockstep with pyproject (top-level version only; dep specs untouched). - One-time catch-up: package.json 0.0.2 -> 0.15.1 and the lockfile root mirrors 0.0.1 -> 0.15.1. * fix(desktop): stamp exe identity in afterPack hook so updates stay branded The packed Hermes.exe reverted to the stock Electron icon + "Electron" name after an in-app update. The icon/identity stamp (rcedit) lived only in install.ps1, but the installer's --update path rebuilds the desktop via `hermes desktop --build-only` -> `npm run pack`, which never ran install.ps1 and so never stamped the rebuilt exe. Move the stamp into an electron-builder afterPack hook so it runs for EVERY packed build regardless of caller (first install, hermes desktop, the update rebuild, or a manual npm run pack): - set-exe-identity.cjs: refactor to export stampExeIdentity(exe, desktopRoot); still runnable as a standalone CLI. - after-pack.cjs (new): afterPack hook calling stampExeIdentity. Windows-only guard; best-effort (logs + resolves on failure, never fails the build). - package.json: register build.afterPack. - install.ps1: remove the now-redundant Set-DesktopExeIdentity function + call; the hook handles it during npm run pack. electron-builder's own rcedit step stays disabled (signAndEditExecutable=false) to avoid the signtool -> winCodeSign -> 7-Zip macOS-symlink crash on non-admin Windows; the hook runs rcedit directly (pure PE resource edit, no signing). * fix(desktop): export afterPack hook as exports.default so electron-builder runs it The afterPack hook used `module.exports = fn`, which electron-builder's hook loader doesn't pick up — it expects the function as the module's default export (the same shape afterSign/notarize.cjs uses). The hook silently never ran, so even first install shipped the stock "Electron" exe. Switch to `exports.default = async function afterPack(...)`. Verified with a real `npm run pack`: electron-builder now invokes the hook and the produced release/win-unpacked/Hermes.exe carries ProductName/FileDescription=Hermes. * chore(desktop): drop auto-build release CI in favor of manual build + upload Remove desktop-release.yml (nightly-on-main + stable publish). Installers are now built locally per platform and uploaded to a GitHub Release by hand; the website points at them via NEXT_PUBLIC_HERMES_DL_* env. Update README + docs and drop the dead desktop-nightly channel links. * fix(desktop): stable shortcut icon + bust icon cache so updates repaint Symptom on a freshly-installed laptop: Hermes.exe itself shows the correct Hermes icon (Explorer reads the live exe's stamped PE resource), but the desktop shortcut still draws the stock Electron icon. Cause: New-DesktopShortcuts set IconLocation to "<exe>,0", so Windows cached the icon it extracted from the exe at shortcut-creation time. On an update the exe gets re-stamped, but the shortcut keeps rendering the stale cached bitmap. - package.json: ship assets/icon.ico beside the exe via extraResources (-> resources/icon.ico). Verified with a real npm run pack. - install.ps1 New-DesktopShortcuts: point IconLocation at resources/icon.ico (fallback to <exe>,0 if absent) — a dedicated .ico is cache-stable and skips the per-exe extraction that goes stale. Then run `ie4uinit.exe -show` to bust the shell icon cache so the shortcut repaints immediately instead of showing the old Electron icon until reboot. Both best-effort; never fail an otherwise-good install. * dummy update * feat(desktop): self-heal update branch + backend contract guard Two fixes for the bb/gui→main transition: - Self-update self-heals: if the tracked branch (e.g. bb/gui) no longer exists on origin (merged + deleted), the desktop updater falls back to main and persists it. Read-only ls-remote probe that only flips on a definitive "ref absent" (exit 2), never on a transient network error, so already-installed clients migrate themselves with no manual flip. - Backend contract guard: tui_gateway reports DESKTOP_BACKEND_CONTRACT in session runtime info; the desktop warns with a one-click "Update Hermes" when the backend predates the GUI's required contract (e.g. a bb/gui app pointed at a main checkout) instead of failing cryptically downstream. * docs(desktop): rewrite README to match current install/update/build flow The old README contradicted itself (claimed a bundled Python payload while also saying it no longer bundles source) and predated cross-platform support. Rewrite for accuracy: Linux is a first-class build target, install.sh/install.ps1 both drive the staged bootstrap, the real self-update handoff (Windows Hermes-Setup vs in-app macOS/Linux), and the bb/gui→main self-heal + backend contract guard. * docs(desktop): rewrite README as a real product readme Lead with what the app is and how to get it (download an installer, or `hermes desktop` for existing CLI users) plus a plain-language feature list, then keep contributor/build/internals as a clearly separated secondary section. * docs(desktop): fix install framing — releases no longer auto-build installers Lead with the install-with-Hermes path (`--include-desktop` / `hermes desktop`), which always works, and describe prebuilt installers as manually published when a release ships them rather than implying CI attaches them to every release. * docs(desktop): match base repo README style Adopt the root README's conventions: centered title + badge row, bold one-liner intro, a feature <table> grid, --- section dividers, and a Community / License footer. * feat(desktop): recover from gateway boot failures + validate API keys on entry (#35864) Fresh installs that hit a gateway boot failure had no recovery path: the shell rendered dead ("gateway offline"), logs were undiscoverable, and a mistyped API key was accepted because onboarding only checked credential presence, not validity. - Add BootFailureOverlay: a top-level recovery surface (Retry, Repair install, Use local gateway, Open logs + inline recent logs) that mounts on any hard boot failure, including post-install. Trims the now-redundant recovery button from the onboarding Preparing panel. - Add hermes:logs:reveal / :recent IPC (reveal desktop.log) and a hermes:bootstrap:repair IPC that drops the bootstrap marker to force a clean reinstall. Surface "Open logs" in Gateway settings too. - Add POST /api/providers/validate: a live per-provider probe (OpenRouter/OpenAI/xAI/Gemini key check, local endpoint connectivity) wired into saveOnboardingApiKey so a rejected key blocks before it's persisted, while an unreachable probe falls through (offline-safe). * test(model-catalog): fix stale nous picker test after curated-list change ac2e48907 made the GUI/picker Nous row use the curated list (curated["nous"] = get_curated_nous_model_ids()) + Portal union, matching the `hermes model` CLI — but test_picker_nous_row_uses_manifest still asserted the old 2-model manifest snapshot, breaking the test shard. Rewrite it as an invariant: stub the Portal union to passthrough and assert the row equals get_curated_nous_model_ids() computed under the same conditions, so it tracks the real contract instead of a hardcoded model list that rots on every catalog update. --------- Co-authored-by: emozilla <emozilla@nousresearch.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Co-authored-by: Austin Pickett <pickett.austin@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: ethernet <arilotter@gmail.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
7743 lines
276 KiB
Python
7743 lines
276 KiB
Python
import atexit
|
|
import concurrent.futures
|
|
import contextvars
|
|
import copy
|
|
import inspect
|
|
import json
|
|
import logging
|
|
import os
|
|
import queue
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
from hermes_constants import get_hermes_home
|
|
from hermes_cli.env_loader import load_hermes_dotenv
|
|
from utils import is_truthy_value
|
|
from tui_gateway.transport import (
|
|
StdioTransport,
|
|
Transport,
|
|
bind_transport,
|
|
current_transport,
|
|
reset_transport,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_hermes_home = get_hermes_home()
|
|
load_hermes_dotenv(
|
|
hermes_home=_hermes_home, project_env=Path(__file__).parent.parent / ".env"
|
|
)
|
|
|
|
|
|
# ── Panic logger ─────────────────────────────────────────────────────
|
|
# Gateway crashes in a TUI session leave no forensics: stdout is the
|
|
# JSON-RPC pipe (TUI side parses it, doesn't log raw), the root logger
|
|
# only catches handled warnings, and the subprocess exits before stderr
|
|
# flushes through the stderr->gateway.stderr event pump. This hook
|
|
# appends every unhandled exception to ~/.hermes/logs/tui_gateway_crash.log
|
|
# AND re-emits a one-line summary to stderr so the TUI can surface it in
|
|
# Activity — exactly what was missing when the voice-mode turns started
|
|
# exiting the gateway mid-TTS.
|
|
_CRASH_LOG = os.path.join(_hermes_home, "logs", "tui_gateway_crash.log")
|
|
|
|
|
|
def _panic_hook(exc_type, exc_value, exc_tb):
|
|
import traceback
|
|
|
|
trace = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
|
|
try:
|
|
os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
|
|
with open(_CRASH_LOG, "a", encoding="utf-8") as f:
|
|
f.write(
|
|
f"\n=== unhandled exception · {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n"
|
|
)
|
|
f.write(trace)
|
|
except Exception:
|
|
pass
|
|
# Stderr goes through to the TUI as a gateway.stderr Activity line —
|
|
# the first line here is what the user will see without opening any
|
|
# log files. Rest of the stack is still in the log for full context.
|
|
first = (
|
|
str(exc_value).strip().splitlines()[0]
|
|
if str(exc_value).strip()
|
|
else exc_type.__name__
|
|
)
|
|
print(f"[gateway-crash] {exc_type.__name__}: {first}", file=sys.stderr, flush=True)
|
|
# Chain to the default hook so the process still terminates normally.
|
|
sys.__excepthook__(exc_type, exc_value, exc_tb)
|
|
|
|
|
|
sys.excepthook = _panic_hook
|
|
|
|
|
|
def _thread_panic_hook(args):
|
|
# threading.excepthook signature: SimpleNamespace(exc_type, exc_value, exc_traceback, thread)
|
|
import traceback
|
|
|
|
trace = "".join(
|
|
traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)
|
|
)
|
|
try:
|
|
os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
|
|
with open(_CRASH_LOG, "a", encoding="utf-8") as f:
|
|
f.write(
|
|
f"\n=== thread exception · {time.strftime('%Y-%m-%d %H:%M:%S')} "
|
|
f"· thread={args.thread.name} ===\n"
|
|
)
|
|
f.write(trace)
|
|
except Exception:
|
|
pass
|
|
first_line = (
|
|
str(args.exc_value).strip().splitlines()[0]
|
|
if str(args.exc_value).strip()
|
|
else args.exc_type.__name__
|
|
)
|
|
print(
|
|
f"[gateway-crash] thread {args.thread.name} raised {args.exc_type.__name__}: {first_line}",
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
|
|
|
|
threading.excepthook = _thread_panic_hook
|
|
|
|
try:
|
|
from hermes_cli.banner import prefetch_update_check
|
|
|
|
prefetch_update_check()
|
|
except Exception:
|
|
pass
|
|
|
|
from tui_gateway.render import make_stream_renderer, render_diff, render_message
|
|
|
|
_sessions: dict[str, dict] = {}
|
|
_methods: dict[str, callable] = {}
|
|
_pending: dict[str, tuple[str, threading.Event]] = {}
|
|
_pending_prompt_payloads: dict[str, tuple[str, dict]] = {}
|
|
_answers: dict[str, str] = {}
|
|
_db = None
|
|
_db_error: str | None = None
|
|
_stdout_lock = threading.Lock()
|
|
_cfg_lock = threading.Lock()
|
|
_cfg_cache: dict | None = None
|
|
_cfg_mtime: float | None = None
|
|
_cfg_path = None
|
|
try:
|
|
_slash_timeout = float(os.environ.get("HERMES_TUI_SLASH_TIMEOUT_S") or "45")
|
|
except (ValueError, TypeError):
|
|
_slash_timeout = 45.0
|
|
_SLASH_WORKER_TIMEOUT_S = max(5.0, _slash_timeout)
|
|
_DETAIL_SECTION_NAMES = ("thinking", "tools", "subagents", "activity")
|
|
_DETAIL_MODES = frozenset({"hidden", "collapsed", "expanded"})
|
|
|
|
# ── Async RPC dispatch (#12546) ──────────────────────────────────────
|
|
# A handful of handlers block the dispatcher loop in entry.py for seconds
|
|
# to minutes (slash.exec, cli.exec, shell.exec, session.resume,
|
|
# session.branch, session.compress, skills.manage). While they're running, inbound RPCs —
|
|
# notably approval.respond and session.interrupt — sit unread in the
|
|
# stdin pipe. We route only those slow handlers onto a small thread pool;
|
|
# everything else stays on the main thread so ordering stays sane for the
|
|
# fast path. write_json is already _stdout_lock-guarded, so concurrent
|
|
# response writes are safe.
|
|
_LONG_HANDLERS = frozenset(
|
|
{
|
|
"browser.manage",
|
|
"cli.exec",
|
|
"session.branch",
|
|
"session.compress",
|
|
"session.resume",
|
|
"shell.exec",
|
|
"skills.manage",
|
|
"slash.exec",
|
|
}
|
|
)
|
|
|
|
try:
|
|
_rpc_pool_workers = max(
|
|
2, int(os.environ.get("HERMES_TUI_RPC_POOL_WORKERS") or "4")
|
|
)
|
|
except (ValueError, TypeError):
|
|
_rpc_pool_workers = 4
|
|
_pool = concurrent.futures.ThreadPoolExecutor(
|
|
max_workers=_rpc_pool_workers,
|
|
thread_name_prefix="tui-rpc",
|
|
)
|
|
atexit.register(lambda: _pool.shutdown(wait=False, cancel_futures=True))
|
|
|
|
# Reserve real stdout for JSON-RPC only; redirect Python's stdout to stderr
|
|
# so stray print() from libraries/tools becomes harmless gateway.stderr instead
|
|
# of corrupting the JSON protocol.
|
|
_real_stdout = sys.stdout
|
|
sys.stdout = sys.stderr
|
|
|
|
# Module-level stdio transport — fallback sink when no transport is bound via
|
|
# contextvar or session. Stream resolved through a lambda so runtime monkey-
|
|
# patches of `_real_stdout` (used extensively in tests) still land correctly.
|
|
_stdio_transport = StdioTransport(lambda: _real_stdout, _stdout_lock)
|
|
|
|
|
|
class _SlashWorker:
|
|
"""Persistent HermesCLI subprocess for slash commands."""
|
|
|
|
def __init__(self, session_key: str, model: str):
|
|
self._lock = threading.Lock()
|
|
self._seq = 0
|
|
self.stderr_tail: list[str] = []
|
|
self.stdout_queue: queue.Queue[dict | None] = queue.Queue()
|
|
|
|
argv = [
|
|
sys.executable,
|
|
"-m",
|
|
"tui_gateway.slash_worker",
|
|
"--session-key",
|
|
session_key,
|
|
]
|
|
if model:
|
|
argv += ["--model", model]
|
|
|
|
self.proc = subprocess.Popen(
|
|
argv,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
bufsize=1,
|
|
cwd=os.getcwd(),
|
|
env=os.environ.copy(),
|
|
)
|
|
threading.Thread(target=self._drain_stdout, daemon=True).start()
|
|
threading.Thread(target=self._drain_stderr, daemon=True).start()
|
|
|
|
def _drain_stdout(self):
|
|
for line in self.proc.stdout or []:
|
|
try:
|
|
self.stdout_queue.put(json.loads(line))
|
|
except json.JSONDecodeError:
|
|
continue
|
|
self.stdout_queue.put(None)
|
|
|
|
def _drain_stderr(self):
|
|
for line in self.proc.stderr or []:
|
|
if text := line.rstrip("\n"):
|
|
self.stderr_tail = (self.stderr_tail + [text])[-80:]
|
|
|
|
def run(self, command: str) -> str:
|
|
if self.proc.poll() is not None:
|
|
raise RuntimeError("slash worker exited")
|
|
|
|
with self._lock:
|
|
self._seq += 1
|
|
rid = self._seq
|
|
self.proc.stdin.write(json.dumps({"id": rid, "command": command}) + "\n")
|
|
self.proc.stdin.flush()
|
|
|
|
while True:
|
|
try:
|
|
msg = self.stdout_queue.get(timeout=_SLASH_WORKER_TIMEOUT_S)
|
|
except queue.Empty:
|
|
raise RuntimeError("slash worker timed out")
|
|
if msg is None:
|
|
break
|
|
if msg.get("id") != rid:
|
|
continue
|
|
if not msg.get("ok"):
|
|
raise RuntimeError(msg.get("error", "slash worker failed"))
|
|
return str(msg.get("output", "")).rstrip()
|
|
|
|
raise RuntimeError(
|
|
f"slash worker closed pipe{': ' + chr(10).join(self.stderr_tail[-8:]) if self.stderr_tail else ''}"
|
|
)
|
|
|
|
def close(self):
|
|
try:
|
|
if self.proc.poll() is None:
|
|
self.proc.terminate()
|
|
self.proc.wait(timeout=1)
|
|
except Exception:
|
|
try:
|
|
self.proc.kill()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _load_busy_input_mode() -> str:
|
|
display = _load_cfg().get("display")
|
|
if not isinstance(display, dict):
|
|
display = {}
|
|
raw = str(display.get("busy_input_mode", "") or "").strip().lower()
|
|
return raw if raw in {"queue", "steer", "interrupt"} else "interrupt"
|
|
|
|
|
|
def _notify_session_boundary(event_type: str, session_id: str | None) -> None:
|
|
"""Fire session lifecycle hooks with CLI parity."""
|
|
try:
|
|
from hermes_cli.plugins import invoke_hook as _invoke_hook
|
|
|
|
_invoke_hook(event_type, session_id=session_id, platform="tui")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> None:
|
|
"""Best-effort finalize hook + memory commit for a session."""
|
|
if not session or session.get("_finalized"):
|
|
return
|
|
session["_finalized"] = True
|
|
stop_event = session.get("_notif_stop")
|
|
if stop_event is not None:
|
|
stop_event.set()
|
|
|
|
agent = session.get("agent")
|
|
lock = session.get("history_lock")
|
|
if lock is not None:
|
|
with lock:
|
|
history = list(session.get("history", []))
|
|
else:
|
|
history = list(session.get("history", []))
|
|
if agent is not None and history and hasattr(agent, "commit_memory_session"):
|
|
try:
|
|
agent.commit_memory_session(history)
|
|
except Exception:
|
|
pass
|
|
|
|
session_key = session.get("session_key")
|
|
session_id = getattr(agent, "session_id", None) or session_key
|
|
_notify_session_boundary("on_session_finalize", session_id)
|
|
|
|
# Mark session ended in DB so it doesn't linger as a ghost row in /resume.
|
|
# Use session_id (from agent.session_id) not session_key — after compression,
|
|
# session_key may be stale (the ended parent) while session_id is the live
|
|
# continuation. Fix for #20001.
|
|
if session_id:
|
|
try:
|
|
db = _get_db()
|
|
if db is not None:
|
|
db.end_session(session_id, end_reason)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _shutdown_sessions() -> None:
|
|
for session in list(_sessions.values()):
|
|
_finalize_session(session, end_reason="tui_shutdown")
|
|
try:
|
|
worker = session.get("slash_worker")
|
|
if worker:
|
|
worker.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
atexit.register(_shutdown_sessions)
|
|
|
|
|
|
# ── Plumbing ──────────────────────────────────────────────────────────
|
|
|
|
|
|
def _get_db():
|
|
global _db, _db_error
|
|
if _db is None:
|
|
from hermes_state import SessionDB
|
|
|
|
try:
|
|
_db = SessionDB()
|
|
_db_error = None
|
|
except Exception as exc:
|
|
_db_error = str(exc)
|
|
logger.warning(
|
|
"TUI session store unavailable — continuing without state.db features: %s",
|
|
exc,
|
|
)
|
|
return None
|
|
return _db
|
|
|
|
|
|
def _db_unavailable_error(rid, *, code: int):
|
|
detail = _db_error or "state.db unavailable"
|
|
return _err(rid, code, f"state.db unavailable: {detail}")
|
|
|
|
|
|
def write_json(obj: dict) -> bool:
|
|
"""Emit one JSON frame. Routes via the most-specific transport available.
|
|
|
|
Precedence:
|
|
|
|
1. Event frames with a session id → the transport stored on that session,
|
|
so async events land with the client that owns the session even if
|
|
the emitting thread has no contextvar binding.
|
|
2. Otherwise the transport bound on the current context (set by
|
|
:func:`dispatch` for the lifetime of a request).
|
|
3. Otherwise the module-level stdio transport, matching the historical
|
|
behaviour and keeping tests that monkey-patch ``_real_stdout`` green.
|
|
"""
|
|
if obj.get("method") == "event":
|
|
sid = ((obj.get("params") or {}).get("session_id")) or ""
|
|
if sid and (t := (_sessions.get(sid) or {}).get("transport")) is not None:
|
|
return t.write(obj)
|
|
|
|
return (current_transport() or _stdio_transport).write(obj)
|
|
|
|
|
|
def _emit(event: str, sid: str, payload: dict | None = None):
|
|
params = {"type": event, "session_id": sid}
|
|
if payload is not None:
|
|
params["payload"] = payload
|
|
write_json({"jsonrpc": "2.0", "method": "event", "params": params})
|
|
|
|
|
|
def _status_update(sid: str, kind: str, text: str | None = None):
|
|
body = (text if text is not None else kind).strip()
|
|
if not body:
|
|
return
|
|
_emit(
|
|
"status.update",
|
|
sid,
|
|
{"kind": kind if text is not None else "status", "text": body},
|
|
)
|
|
|
|
|
|
def _estimate_image_tokens(width: int, height: int) -> int:
|
|
"""Very rough UI estimate for image prompt cost.
|
|
|
|
Uses 512px tiles at ~85 tokens/tile as a lightweight cross-provider hint.
|
|
This is intentionally approximate and only used for attachment display.
|
|
"""
|
|
if width <= 0 or height <= 0:
|
|
return 0
|
|
return max(1, (width + 511) // 512) * max(1, (height + 511) // 512) * 85
|
|
|
|
|
|
def _image_meta(path: Path) -> dict:
|
|
meta = {"name": path.name}
|
|
try:
|
|
from PIL import Image
|
|
|
|
with Image.open(path) as img:
|
|
width, height = img.size
|
|
meta["width"] = int(width)
|
|
meta["height"] = int(height)
|
|
meta["token_estimate"] = _estimate_image_tokens(int(width), int(height))
|
|
except Exception:
|
|
pass
|
|
return meta
|
|
|
|
|
|
def _ok(rid, result: dict) -> dict:
|
|
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
|
|
|
|
|
def _err(rid, code: int, msg: str) -> dict:
|
|
return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": msg}}
|
|
|
|
|
|
def method(name: str):
|
|
def dec(fn):
|
|
_methods[name] = fn
|
|
return fn
|
|
|
|
return dec
|
|
|
|
|
|
def _normalize_request(req: Any) -> tuple[Any, str, dict] | dict:
|
|
"""Validate a JSON-RPC request enough for safe local dispatch."""
|
|
if not isinstance(req, dict):
|
|
return _err(None, -32600, "invalid request: expected an object")
|
|
|
|
rid = req.get("id")
|
|
method = req.get("method")
|
|
if not isinstance(method, str) or not method:
|
|
return _err(rid, -32600, "invalid request: method must be a non-empty string")
|
|
|
|
params = req.get("params", {})
|
|
if params is None:
|
|
params = {}
|
|
elif not isinstance(params, dict):
|
|
return _err(rid, -32602, "invalid params: expected an object")
|
|
|
|
return rid, method, params
|
|
|
|
|
|
def handle_request(req: dict) -> dict | None:
|
|
normalized = _normalize_request(req)
|
|
if isinstance(normalized, dict):
|
|
return normalized
|
|
|
|
rid, method, params = normalized
|
|
fn = _methods.get(method)
|
|
if not fn:
|
|
return _err(rid, -32601, f"unknown method: {method}")
|
|
return fn(rid, params)
|
|
|
|
|
|
def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:
|
|
"""Route inbound RPCs — long handlers to the pool, everything else inline.
|
|
|
|
Returns a response dict when handled inline. Returns None when the
|
|
handler was scheduled on the pool; the worker writes its own response
|
|
via the bound transport when done.
|
|
|
|
*transport* (optional): pins every write produced by this request —
|
|
including any events emitted by the handler — to the given transport.
|
|
Omitting it falls back to the module-level stdio transport, preserving
|
|
the original behaviour for ``tui_gateway.entry``.
|
|
"""
|
|
t = transport or _stdio_transport
|
|
token = bind_transport(t)
|
|
try:
|
|
normalized = _normalize_request(req)
|
|
if isinstance(normalized, dict):
|
|
return normalized
|
|
|
|
_rid, method, _params = normalized
|
|
if method not in _LONG_HANDLERS:
|
|
return handle_request(req)
|
|
|
|
# Snapshot the context so the pool worker sees the bound transport.
|
|
ctx = contextvars.copy_context()
|
|
|
|
def run():
|
|
try:
|
|
resp = handle_request(req)
|
|
except Exception as exc:
|
|
resp = _err(req.get("id"), -32000, f"handler error: {exc}")
|
|
if resp is not None:
|
|
t.write(resp)
|
|
|
|
_pool.submit(lambda: ctx.run(run))
|
|
|
|
return None
|
|
finally:
|
|
reset_transport(token)
|
|
|
|
|
|
def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
|
|
ready = session.get("agent_ready")
|
|
if ready is not None and not ready.wait(timeout=timeout):
|
|
return _err(rid, 5032, "agent initialization timed out")
|
|
err = session.get("agent_error")
|
|
return _err(rid, 5032, err) if err else None
|
|
|
|
|
|
def _start_agent_build(sid: str, session: dict) -> None:
|
|
"""Start building the real AIAgent for a TUI session, once.
|
|
|
|
Classic `hermes` shows the prompt before constructing AIAgent; the TUI used
|
|
to eagerly build it during session.create, making startup feel blocked on
|
|
tool discovery/model metadata even though the composer was visible. Keep
|
|
the shell responsive by deferring this work until the first prompt (or any
|
|
command that actually needs the agent), while retaining the same ready/error
|
|
event contract for the frontend.
|
|
"""
|
|
ready = session.get("agent_ready")
|
|
if ready is None:
|
|
return
|
|
lock = session.setdefault("agent_build_lock", threading.Lock())
|
|
with lock:
|
|
if ready.is_set() or session.get("agent_build_started"):
|
|
return
|
|
session["agent_build_started"] = True
|
|
key = session["session_key"]
|
|
|
|
def _build() -> None:
|
|
current = _sessions.get(sid)
|
|
if current is None:
|
|
ready.set()
|
|
return
|
|
|
|
worker = None
|
|
notify_registered = False
|
|
try:
|
|
tokens = _set_session_context(key)
|
|
try:
|
|
agent = _make_agent(sid, key)
|
|
finally:
|
|
_clear_session_context(tokens)
|
|
|
|
# Session DB row deferred to first run_conversation() call.
|
|
# pending_title applied post-first-message (see cli.exec handler).
|
|
current["agent"] = agent
|
|
|
|
try:
|
|
worker = _SlashWorker(key, getattr(agent, "model", _resolve_model()))
|
|
current["slash_worker"] = worker
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
from tools.approval import (
|
|
register_gateway_notify,
|
|
load_permanent_allowlist,
|
|
)
|
|
|
|
register_gateway_notify(
|
|
key, lambda data: _emit("approval.request", sid, data)
|
|
)
|
|
notify_registered = True
|
|
load_permanent_allowlist()
|
|
except Exception:
|
|
pass
|
|
|
|
_wire_callbacks(sid)
|
|
_sessions[sid]["_notif_stop"] = _start_notification_poller(sid, _sessions[sid])
|
|
_notify_session_boundary("on_session_reset", key)
|
|
|
|
info = _session_info(agent, current)
|
|
cfg_warn = _probe_config_health(_load_cfg())
|
|
if cfg_warn:
|
|
info["config_warning"] = cfg_warn
|
|
logger.warning(cfg_warn)
|
|
_emit("session.info", sid, info)
|
|
except Exception as e:
|
|
current["agent_error"] = str(e)
|
|
_emit("error", sid, {"message": f"agent init failed: {e}"})
|
|
finally:
|
|
if _sessions.get(sid) is not current:
|
|
if worker is not None:
|
|
try:
|
|
worker.close()
|
|
except Exception:
|
|
pass
|
|
if notify_registered:
|
|
try:
|
|
from tools.approval import unregister_gateway_notify
|
|
|
|
unregister_gateway_notify(key)
|
|
except Exception:
|
|
pass
|
|
ready.set()
|
|
|
|
threading.Thread(target=_build, daemon=True).start()
|
|
|
|
|
|
def _sess_nowait(params, rid):
|
|
s = _sessions.get(params.get("session_id") or "")
|
|
return (s, None) if s else (None, _err(rid, 4001, "session not found"))
|
|
|
|
|
|
def _sess(params, rid):
|
|
s, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return (None, err)
|
|
_start_agent_build(params.get("session_id") or "", s)
|
|
return (s, _wait_agent(s, rid))
|
|
|
|
|
|
def _normalize_completion_path(path_part: str) -> str:
|
|
expanded = os.path.expanduser(path_part)
|
|
if os.name != "nt":
|
|
normalized = expanded.replace("\\", "/")
|
|
if (
|
|
len(normalized) >= 3
|
|
and normalized[1] == ":"
|
|
and normalized[2] == "/"
|
|
and normalized[0].isalpha()
|
|
):
|
|
return f"/mnt/{normalized[0].lower()}/{normalized[3:]}"
|
|
return expanded
|
|
|
|
|
|
def _completion_cwd(params: dict | None = None) -> str:
|
|
raw = (
|
|
(params or {}).get("cwd")
|
|
or _sessions.get((params or {}).get("session_id") or "", {}).get("cwd")
|
|
or os.environ.get("TERMINAL_CWD")
|
|
or os.getcwd()
|
|
)
|
|
try:
|
|
resolved = os.path.abspath(os.path.expanduser(str(raw)))
|
|
if os.path.isdir(resolved):
|
|
return resolved
|
|
except Exception:
|
|
pass
|
|
return os.getcwd()
|
|
|
|
|
|
def _git_branch_for_cwd(cwd: str) -> str:
|
|
try:
|
|
result = subprocess.run(
|
|
["git", "-C", cwd, "branch", "--show-current"],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=1.5,
|
|
check=False,
|
|
)
|
|
if result.returncode == 0:
|
|
branch = result.stdout.strip()
|
|
if branch:
|
|
return branch
|
|
head = subprocess.run(
|
|
["git", "-C", cwd, "rev-parse", "--short", "HEAD"],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=1.5,
|
|
check=False,
|
|
)
|
|
return head.stdout.strip() if head.returncode == 0 else ""
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def _session_cwd(session: dict | None) -> str:
|
|
if session and session.get("cwd"):
|
|
return str(session["cwd"])
|
|
return _completion_cwd()
|
|
|
|
|
|
def _register_session_cwd(session: dict | None) -> None:
|
|
if not session:
|
|
return
|
|
try:
|
|
from tools.terminal_tool import register_task_env_overrides
|
|
|
|
register_task_env_overrides(
|
|
session["session_key"], {"cwd": _session_cwd(session)}
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _set_session_cwd(session: dict, cwd: str) -> str:
|
|
resolved = os.path.abspath(os.path.expanduser(str(cwd)))
|
|
if not os.path.isdir(resolved):
|
|
raise ValueError(f"working directory does not exist: {cwd}")
|
|
session["cwd"] = resolved
|
|
_register_session_cwd(session)
|
|
db = _get_db()
|
|
if db is not None:
|
|
try:
|
|
db.update_session_cwd(session.get("session_key", ""), resolved)
|
|
except Exception:
|
|
logger.debug("failed to persist session cwd", exc_info=True)
|
|
try:
|
|
from tools.terminal_tool import cleanup_vm
|
|
|
|
cleanup_vm(session["session_key"])
|
|
except Exception:
|
|
pass
|
|
return resolved
|
|
|
|
|
|
# ── Config I/O ────────────────────────────────────────────────────────
|
|
|
|
|
|
# Keep aligned with `INDICATOR_STYLES` / `DEFAULT_INDICATOR_STYLE` in
|
|
# ``ui-tui/src/app/interfaces.ts`` — both ends validate against the
|
|
# same shape so `config.get indicator` and the live TUI render agree.
|
|
_INDICATOR_STYLES: tuple[str, ...] = ("ascii", "emoji", "kaomoji", "unicode")
|
|
_INDICATOR_DEFAULT = "kaomoji"
|
|
|
|
|
|
def _load_cfg() -> dict:
|
|
global _cfg_cache, _cfg_mtime, _cfg_path
|
|
try:
|
|
import yaml
|
|
|
|
p = _hermes_home / "config.yaml"
|
|
mtime = p.stat().st_mtime if p.exists() else None
|
|
with _cfg_lock:
|
|
if _cfg_cache is not None and _cfg_mtime == mtime and _cfg_path == p:
|
|
return copy.deepcopy(_cfg_cache)
|
|
if p.exists():
|
|
with open(p, encoding="utf-8") as f:
|
|
data = yaml.safe_load(f) or {}
|
|
else:
|
|
data = {}
|
|
with _cfg_lock:
|
|
_cfg_cache = copy.deepcopy(data)
|
|
_cfg_mtime = mtime
|
|
_cfg_path = p
|
|
return data
|
|
except Exception:
|
|
pass
|
|
return {}
|
|
|
|
|
|
def _save_cfg(cfg: dict):
|
|
global _cfg_cache, _cfg_mtime, _cfg_path
|
|
import yaml
|
|
|
|
path = _hermes_home / "config.yaml"
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
yaml.safe_dump(cfg, f)
|
|
with _cfg_lock:
|
|
_cfg_cache = copy.deepcopy(cfg)
|
|
_cfg_path = path
|
|
try:
|
|
_cfg_mtime = path.stat().st_mtime
|
|
except Exception:
|
|
_cfg_mtime = None
|
|
|
|
|
|
def _set_session_context(session_key: str) -> list:
|
|
try:
|
|
from gateway.session_context import set_session_vars
|
|
|
|
return set_session_vars(session_key=session_key)
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def _clear_session_context(tokens: list) -> None:
|
|
if not tokens:
|
|
return
|
|
try:
|
|
from gateway.session_context import clear_session_vars
|
|
|
|
clear_session_vars(tokens)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _enable_gateway_prompts() -> None:
|
|
"""Route approvals through gateway callbacks instead of CLI input()."""
|
|
os.environ["HERMES_GATEWAY_SESSION"] = "1"
|
|
os.environ["HERMES_EXEC_ASK"] = "1"
|
|
os.environ["HERMES_INTERACTIVE"] = "1"
|
|
|
|
|
|
# ── Blocking prompt factory ──────────────────────────────────────────
|
|
|
|
|
|
def _block(event: str, sid: str, payload: dict, timeout: int = 300) -> str:
|
|
rid = uuid.uuid4().hex[:8]
|
|
ev = threading.Event()
|
|
_pending[rid] = (sid, ev)
|
|
payload["request_id"] = rid
|
|
_pending_prompt_payloads[rid] = (event, dict(payload))
|
|
try:
|
|
_emit(event, sid, payload)
|
|
ev.wait(timeout=timeout)
|
|
finally:
|
|
_pending.pop(rid, None)
|
|
_pending_prompt_payloads.pop(rid, None)
|
|
return _answers.pop(rid, "")
|
|
|
|
|
|
def _clear_pending(sid: str | None = None) -> None:
|
|
"""Release pending prompts with an empty answer.
|
|
|
|
When *sid* is provided, only prompts owned by that session are
|
|
released — critical for session.interrupt, which must not
|
|
collaterally cancel clarify/sudo/secret prompts on unrelated
|
|
sessions sharing the same tui_gateway process. When *sid* is
|
|
None, every pending prompt is released (used during shutdown).
|
|
"""
|
|
for rid, (owner_sid, ev) in list(_pending.items()):
|
|
if sid is None or owner_sid == sid:
|
|
_answers[rid] = ""
|
|
ev.set()
|
|
|
|
|
|
# ── Agent factory ────────────────────────────────────────────────────
|
|
|
|
|
|
def resolve_skin() -> dict:
|
|
try:
|
|
from hermes_cli.skin_engine import init_skin_from_config, get_active_skin
|
|
|
|
init_skin_from_config(_load_cfg())
|
|
skin = get_active_skin()
|
|
return {
|
|
"name": skin.name,
|
|
"colors": skin.colors,
|
|
"branding": skin.branding,
|
|
"banner_logo": skin.banner_logo,
|
|
"banner_hero": skin.banner_hero,
|
|
"tool_prefix": skin.tool_prefix,
|
|
"help_header": (skin.branding or {}).get("help_header", ""),
|
|
}
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def _resolve_model() -> str:
|
|
env = (
|
|
os.environ.get("HERMES_MODEL", "")
|
|
or os.environ.get("HERMES_INFERENCE_MODEL", "")
|
|
).strip()
|
|
if env:
|
|
return env
|
|
m = _load_cfg().get("model", "")
|
|
if isinstance(m, dict):
|
|
return str(m.get("default", "") or "").strip()
|
|
if isinstance(m, str) and m:
|
|
return m.strip()
|
|
return "anthropic/claude-sonnet-4"
|
|
|
|
|
|
def _resolve_startup_runtime() -> tuple[str, str | None]:
|
|
model = _resolve_model()
|
|
explicit_provider = os.environ.get("HERMES_TUI_PROVIDER", "").strip()
|
|
if explicit_provider:
|
|
return model, explicit_provider
|
|
|
|
explicit_model = (
|
|
os.environ.get("HERMES_MODEL", "")
|
|
or os.environ.get("HERMES_INFERENCE_MODEL", "")
|
|
).strip()
|
|
if not explicit_model:
|
|
return model, None
|
|
|
|
try:
|
|
from hermes_cli.models import detect_static_provider_for_model
|
|
|
|
cfg = _load_cfg().get("model") or {}
|
|
current_provider = (
|
|
(
|
|
str(cfg.get("provider") or "").strip().lower()
|
|
if isinstance(cfg, dict)
|
|
else ""
|
|
)
|
|
or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower()
|
|
or "auto"
|
|
)
|
|
detected = detect_static_provider_for_model(explicit_model, current_provider)
|
|
if detected:
|
|
provider, detected_model = detected
|
|
return detected_model, provider
|
|
except Exception:
|
|
pass
|
|
return model, None
|
|
|
|
|
|
def _write_config_key(key_path: str, value):
|
|
cfg = _load_cfg()
|
|
current = cfg
|
|
keys = key_path.split(".")
|
|
for key in keys[:-1]:
|
|
if key not in current or not isinstance(current.get(key), dict):
|
|
current[key] = {}
|
|
current = current[key]
|
|
current[keys[-1]] = value
|
|
_save_cfg(cfg)
|
|
|
|
|
|
_STATUSBAR_MODES = frozenset({"off", "top", "bottom"})
|
|
|
|
|
|
def _coerce_statusbar(raw) -> str:
|
|
if raw is False:
|
|
return "off"
|
|
if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES:
|
|
return s
|
|
return "top"
|
|
|
|
|
|
_MOUSE_TRACKING_ALIASES = {
|
|
"0": "off",
|
|
"1": "all",
|
|
"all": "all",
|
|
"any": "all",
|
|
"button": "buttons",
|
|
"buttons": "buttons",
|
|
"click": "buttons",
|
|
"false": "off",
|
|
"full": "all",
|
|
"no": "off",
|
|
"off": "off",
|
|
"on": "all",
|
|
"scroll": "wheel",
|
|
"true": "all",
|
|
"wheel": "wheel",
|
|
"yes": "all",
|
|
}
|
|
|
|
|
|
def _display_mouse_tracking(display: dict) -> str:
|
|
"""Resolve display.mouse_tracking to one of ``off|wheel|buttons|all``.
|
|
|
|
Boolean values keep their legacy meaning (``True`` → ``all``, ``False`` →
|
|
``off``). The ``wheel`` preset (DEC 1000+1006) is the tmux-friendly
|
|
subset — wheel + click only, no hover events to trigger prompt-row
|
|
clipboard probes. Legacy ``tui_mouse`` is honored only when
|
|
``mouse_tracking`` is absent.
|
|
"""
|
|
if not isinstance(display, dict):
|
|
return "all"
|
|
if "mouse_tracking" in display:
|
|
raw = display.get("mouse_tracking")
|
|
else:
|
|
raw = display.get("tui_mouse", True)
|
|
if raw is False or raw == 0:
|
|
return "off"
|
|
if raw is True or raw is None:
|
|
return "all"
|
|
if isinstance(raw, (int, float)):
|
|
return "all"
|
|
if isinstance(raw, str):
|
|
return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")
|
|
return "all"
|
|
|
|
|
|
def _load_reasoning_config() -> dict | None:
|
|
from hermes_constants import parse_reasoning_effort
|
|
|
|
effort = str(
|
|
(_load_cfg().get("agent") or {}).get("reasoning_effort", "") or ""
|
|
).strip()
|
|
return parse_reasoning_effort(effort)
|
|
|
|
|
|
def _load_service_tier() -> str | None:
|
|
raw = (
|
|
str((_load_cfg().get("agent") or {}).get("service_tier", "") or "")
|
|
.strip()
|
|
.lower()
|
|
)
|
|
if not raw or raw in {"normal", "default", "standard", "off", "none"}:
|
|
return None
|
|
if raw in {"fast", "priority", "on"}:
|
|
return "priority"
|
|
return None
|
|
|
|
|
|
def _load_show_reasoning() -> bool:
|
|
return bool((_load_cfg().get("display") or {}).get("show_reasoning", False))
|
|
|
|
|
|
def _load_tool_progress_mode() -> str:
|
|
env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()
|
|
if env in {"off", "new", "all", "verbose"}:
|
|
return env
|
|
raw = (_load_cfg().get("display") or {}).get("tool_progress", "all")
|
|
if raw is False:
|
|
return "off"
|
|
if raw is True:
|
|
return "all"
|
|
mode = str(raw or "all").strip().lower()
|
|
return mode if mode in {"off", "new", "all", "verbose"} else "all"
|
|
|
|
|
|
def _load_enabled_toolsets() -> list[str] | None:
|
|
explicit = [
|
|
item.strip()
|
|
for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",")
|
|
if item.strip()
|
|
]
|
|
cfg = None
|
|
fallback_notice = None
|
|
|
|
try:
|
|
from toolsets import validate_toolset
|
|
except Exception:
|
|
validate_toolset = None
|
|
|
|
if explicit and validate_toolset is not None:
|
|
built_in = [name for name in explicit if validate_toolset(name)]
|
|
unresolved = [name for name in explicit if name not in built_in]
|
|
|
|
if unresolved:
|
|
try:
|
|
from hermes_cli.plugins import discover_plugins
|
|
|
|
discover_plugins()
|
|
plugin_valid = [name for name in unresolved if validate_toolset(name)]
|
|
except Exception:
|
|
plugin_valid = []
|
|
|
|
if plugin_valid:
|
|
built_in.extend(plugin_valid)
|
|
unresolved = [name for name in unresolved if name not in plugin_valid]
|
|
|
|
if any(name in {"all", "*"} for name in built_in):
|
|
ignored = [name for name in explicit if name not in {"all", "*"}]
|
|
if ignored:
|
|
print(
|
|
"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; "
|
|
f"ignoring additional entries: {', '.join(ignored)}",
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
return None
|
|
|
|
if not unresolved:
|
|
return built_in
|
|
|
|
mcp_names: set[str] = set()
|
|
mcp_disabled: set[str] = set()
|
|
try:
|
|
from hermes_cli.config import read_raw_config
|
|
from hermes_cli.tools_config import _parse_enabled_flag
|
|
|
|
raw_cfg = read_raw_config()
|
|
mcp_servers = (
|
|
raw_cfg.get("mcp_servers")
|
|
if isinstance(raw_cfg.get("mcp_servers"), dict)
|
|
else {}
|
|
)
|
|
for name, server_cfg in mcp_servers.items():
|
|
if not isinstance(server_cfg, dict):
|
|
continue
|
|
if _parse_enabled_flag(server_cfg.get("enabled", True), default=True):
|
|
mcp_names.add(str(name))
|
|
else:
|
|
mcp_disabled.add(str(name))
|
|
except Exception:
|
|
mcp_names = set()
|
|
mcp_disabled = set()
|
|
|
|
mcp_valid = [name for name in unresolved if name in mcp_names]
|
|
disabled = [name for name in unresolved if name in mcp_disabled]
|
|
unknown = [
|
|
name
|
|
for name in unresolved
|
|
if name not in mcp_names and name not in mcp_disabled
|
|
]
|
|
valid = built_in + mcp_valid
|
|
|
|
if unknown:
|
|
print(
|
|
f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}",
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
if disabled:
|
|
print(
|
|
"[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "
|
|
"(set enabled: true in config.yaml to use): "
|
|
f"{', '.join(disabled)}",
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
|
|
if valid:
|
|
return valid
|
|
|
|
fallback_notice = (
|
|
"[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"
|
|
)
|
|
|
|
try:
|
|
from hermes_cli.config import load_config
|
|
from hermes_cli.tools_config import _get_platform_tools
|
|
|
|
cfg = cfg if cfg is not None else load_config()
|
|
|
|
# Runtime toolset resolution must include default MCP servers so the
|
|
# agent can actually call them. Passing ``False`` here is the
|
|
# config-editing variant — used when we need to persist a toolset
|
|
# list without baking in implicit MCP defaults. Using the wrong
|
|
# variant at agent creation time makes MCP tools silently missing
|
|
# from the TUI. See PR #3252 for the original design split.
|
|
enabled = sorted(
|
|
_get_platform_tools(cfg, "cli", include_default_mcp_servers=True)
|
|
)
|
|
if fallback_notice is not None:
|
|
print(fallback_notice, file=sys.stderr, flush=True)
|
|
return enabled or None
|
|
except Exception:
|
|
if fallback_notice is not None:
|
|
print(
|
|
"[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets",
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
return None
|
|
|
|
|
|
def _session_tool_progress_mode(sid: str) -> str:
|
|
return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")
|
|
|
|
|
|
def _session_verbose(sid: str) -> bool:
|
|
return _session_tool_progress_mode(sid) == "verbose"
|
|
|
|
|
|
def _tool_progress_enabled(sid: str) -> bool:
|
|
return _session_tool_progress_mode(sid) != "off"
|
|
|
|
|
|
def _restart_slash_worker(session: dict):
|
|
worker = session.get("slash_worker")
|
|
if worker:
|
|
try:
|
|
worker.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
session["slash_worker"] = _SlashWorker(
|
|
session["session_key"],
|
|
getattr(session.get("agent"), "model", _resolve_model()),
|
|
)
|
|
except Exception:
|
|
session["slash_worker"] = None
|
|
|
|
|
|
def _persist_model_switch(result) -> None:
|
|
from hermes_cli.config import save_config
|
|
|
|
cfg = _load_cfg()
|
|
model_cfg = cfg.get("model")
|
|
if not isinstance(model_cfg, dict):
|
|
model_cfg = {}
|
|
cfg["model"] = model_cfg
|
|
|
|
model_cfg["default"] = result.new_model
|
|
model_cfg["provider"] = result.target_provider
|
|
if result.base_url:
|
|
model_cfg["base_url"] = result.base_url
|
|
else:
|
|
model_cfg.pop("base_url", None)
|
|
save_config(cfg)
|
|
|
|
|
|
def _apply_model_switch(sid: str, session: dict, raw_input: str) -> dict:
|
|
from hermes_cli.model_switch import parse_model_flags, switch_model
|
|
from hermes_cli.runtime_provider import resolve_runtime_provider
|
|
|
|
model_input, explicit_provider, persist_global, _force_refresh = parse_model_flags(raw_input)
|
|
if not model_input:
|
|
raise ValueError("model value required")
|
|
|
|
agent = session.get("agent")
|
|
if agent:
|
|
current_provider = getattr(agent, "provider", "") or ""
|
|
current_model = getattr(agent, "model", "") or ""
|
|
current_base_url = getattr(agent, "base_url", "") or ""
|
|
current_api_key = getattr(agent, "api_key", "") or ""
|
|
else:
|
|
runtime = resolve_runtime_provider(requested=None)
|
|
current_provider = str(runtime.get("provider", "") or "")
|
|
current_model = _resolve_model()
|
|
current_base_url = str(runtime.get("base_url", "") or "")
|
|
# Preserve a callable api_key (Azure Foundry Entra ID bearer
|
|
# provider) unchanged — ``str(...)`` would produce
|
|
# ``"<function ...>"`` and poison downstream switch_model
|
|
# validation. Match the agent-present branch's behavior at the
|
|
# top of this block.
|
|
_runtime_key = runtime.get("api_key", "")
|
|
if callable(_runtime_key) and not isinstance(_runtime_key, str):
|
|
current_api_key = _runtime_key
|
|
else:
|
|
current_api_key = str(_runtime_key or "")
|
|
|
|
# Load user-defined providers so switch_model can resolve named custom
|
|
# endpoints (e.g. "ollama-launch") and validate against saved model lists.
|
|
user_provs = None
|
|
custom_provs = None
|
|
try:
|
|
from hermes_cli.config import get_compatible_custom_providers, load_config
|
|
|
|
cfg = load_config()
|
|
user_provs = cfg.get("providers")
|
|
custom_provs = get_compatible_custom_providers(cfg)
|
|
except Exception:
|
|
pass
|
|
|
|
result = switch_model(
|
|
raw_input=model_input,
|
|
current_provider=current_provider,
|
|
current_model=current_model,
|
|
current_base_url=current_base_url,
|
|
current_api_key=current_api_key,
|
|
is_global=persist_global,
|
|
explicit_provider=explicit_provider,
|
|
user_providers=user_provs,
|
|
custom_providers=custom_provs,
|
|
)
|
|
if not result.success:
|
|
raise ValueError(result.error_message or "model switch failed")
|
|
|
|
if agent:
|
|
agent.switch_model(
|
|
new_model=result.new_model,
|
|
new_provider=result.target_provider,
|
|
api_key=result.api_key,
|
|
base_url=result.base_url,
|
|
api_mode=result.api_mode,
|
|
)
|
|
_restart_slash_worker(session)
|
|
_emit("session.info", sid, _session_info(agent, session))
|
|
|
|
os.environ["HERMES_MODEL"] = result.new_model
|
|
os.environ["HERMES_INFERENCE_MODEL"] = result.new_model
|
|
# Keep the process-level provider env vars in sync with the user's
|
|
# explicit choice so any ambient re-resolution (credential pool refresh,
|
|
# compressor rebuild, aux clients) and startup re-resolution on /new
|
|
# both pick up the new provider instead of the original one persisted
|
|
# in config or env.
|
|
#
|
|
# HERMES_TUI_PROVIDER is the canonical "explicit-this-process" carrier
|
|
# consumed by _resolve_startup_runtime() — set it unconditionally on
|
|
# /model so /new can't fall through to static-catalog detection and
|
|
# pick a coincidentally-matching native provider (fixes #16857).
|
|
if result.target_provider:
|
|
os.environ["HERMES_INFERENCE_PROVIDER"] = result.target_provider
|
|
os.environ["HERMES_TUI_PROVIDER"] = result.target_provider
|
|
if persist_global:
|
|
_persist_model_switch(result)
|
|
return {"value": result.new_model, "warning": result.warning_message or ""}
|
|
|
|
|
|
def _compress_session_history(
|
|
session: dict,
|
|
focus_topic: str | None = None,
|
|
approx_tokens: int | None = None,
|
|
before_messages: list | None = None,
|
|
history_version: int | None = None,
|
|
) -> tuple[int, dict]:
|
|
from agent.model_metadata import estimate_request_tokens_rough
|
|
|
|
agent = session["agent"]
|
|
# Snapshot history under the lock so the LLM-bound compression call
|
|
# below does NOT hold history_lock for the duration of the request —
|
|
# otherwise other handlers acquiring the lock (prompt.submit etc.)
|
|
# block on the dispatcher loop while compaction runs.
|
|
if before_messages is None or history_version is None:
|
|
with session["history_lock"]:
|
|
before_messages = list(session.get("history", []))
|
|
history_version = int(session.get("history_version", 0))
|
|
history = before_messages
|
|
if len(history) < 4:
|
|
usage = _get_usage(agent)
|
|
return 0, usage
|
|
if approx_tokens is None:
|
|
# Include system prompt + tool schemas so the figure reflects real
|
|
# request pressure, not a transcript-only underestimate (#6217).
|
|
_sys_prompt = getattr(agent, "_cached_system_prompt", "") or ""
|
|
_tools = getattr(agent, "tools", None) or None
|
|
approx_tokens = estimate_request_tokens_rough(
|
|
history, system_prompt=_sys_prompt, tools=_tools
|
|
)
|
|
# Pass system_message=None so AIAgent._compress_context rebuilds the
|
|
# system prompt cleanly via _build_system_prompt(None). Passing the
|
|
# cached prompt (which already contains the agent identity block)
|
|
# makes the rebuild append the identity a second time. Mirrors the
|
|
# CLI's _manual_compress fix for issue #15281.
|
|
compressed, _ = agent._compress_context(
|
|
history,
|
|
None,
|
|
approx_tokens=approx_tokens,
|
|
focus_topic=focus_topic or None,
|
|
)
|
|
with session["history_lock"]:
|
|
if int(session.get("history_version", 0)) != history_version:
|
|
# External mutation during compaction — drop the compressed
|
|
# result so we don't clobber concurrent edits.
|
|
usage = _get_usage(agent)
|
|
return 0, usage
|
|
session["history"] = compressed
|
|
session["history_version"] = history_version + 1
|
|
usage = _get_usage(agent)
|
|
return len(history) - len(compressed), usage
|
|
|
|
|
|
def _sync_session_key_after_compress(
|
|
sid: str,
|
|
session: dict,
|
|
*,
|
|
clear_pending_title: bool = True,
|
|
restart_slash_worker: bool = True,
|
|
) -> None:
|
|
"""Re-anchor session_key when AIAgent._compress_context rotates session_id.
|
|
|
|
AIAgent._compress_context ends the current SessionDB session and creates
|
|
a new continuation session, rotating ``agent.session_id``. The TUI
|
|
gateway keeps the gateway-side ``session_key`` separate (used for
|
|
approval routing, slash worker init, DB title/history lookups, yolo
|
|
state). Without this sync, those operations would target the ended
|
|
parent session while the agent writes to the new continuation session.
|
|
|
|
Policy flags:
|
|
clear_pending_title: True for manual /compress (title belongs to old
|
|
session). False for post-turn auto-compression (preserve user
|
|
intent so pending_title can be applied to the continuation).
|
|
restart_slash_worker: True for manual /compress and post-turn
|
|
auto-compression (worker holds stale session key). False only
|
|
if the caller manages the worker lifecycle separately.
|
|
"""
|
|
agent = session.get("agent")
|
|
new_session_id = getattr(agent, "session_id", None) or ""
|
|
old_key = session.get("session_key", "") or ""
|
|
if not new_session_id or new_session_id == old_key:
|
|
return
|
|
|
|
try:
|
|
from tools.approval import (
|
|
disable_session_yolo,
|
|
enable_session_yolo,
|
|
is_session_yolo_enabled,
|
|
register_gateway_notify,
|
|
unregister_gateway_notify,
|
|
)
|
|
|
|
try:
|
|
unregister_gateway_notify(old_key)
|
|
except Exception:
|
|
pass
|
|
session["session_key"] = new_session_id
|
|
try:
|
|
yolo_was_on = is_session_yolo_enabled(old_key)
|
|
except Exception:
|
|
yolo_was_on = False
|
|
if yolo_was_on:
|
|
try:
|
|
enable_session_yolo(new_session_id)
|
|
disable_session_yolo(old_key)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
register_gateway_notify(
|
|
new_session_id,
|
|
lambda data: _emit("approval.request", sid, data),
|
|
)
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
# Even if the approval module fails to import, still anchor the
|
|
# session_key on the new continuation id so downstream lookups
|
|
# don't keep targeting the ended row.
|
|
session["session_key"] = new_session_id
|
|
|
|
if clear_pending_title:
|
|
session["pending_title"] = None
|
|
if restart_slash_worker:
|
|
try:
|
|
_restart_slash_worker(session)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _get_usage(agent) -> dict:
|
|
g = lambda k, fb=None: getattr(agent, k, 0) or (getattr(agent, fb, 0) if fb else 0)
|
|
usage = {
|
|
"model": getattr(agent, "model", "") or "",
|
|
"input": g("session_input_tokens", "session_prompt_tokens"),
|
|
"output": g("session_output_tokens", "session_completion_tokens"),
|
|
"cache_read": g("session_cache_read_tokens"),
|
|
"cache_write": g("session_cache_write_tokens"),
|
|
"reasoning": g("session_reasoning_tokens"),
|
|
"prompt": g("session_prompt_tokens"),
|
|
"completion": g("session_completion_tokens"),
|
|
"total": g("session_total_tokens"),
|
|
"calls": g("session_api_calls"),
|
|
}
|
|
comp = getattr(agent, "context_compressor", None)
|
|
if comp:
|
|
ctx_used = getattr(comp, "last_prompt_tokens", 0) or usage["total"] or 0
|
|
ctx_max = getattr(comp, "context_length", 0) or 0
|
|
if ctx_max:
|
|
usage["context_used"] = ctx_used
|
|
usage["context_max"] = ctx_max
|
|
usage["context_percent"] = max(0, min(100, round(ctx_used / ctx_max * 100)))
|
|
usage["compressions"] = getattr(comp, "compression_count", 0) or 0
|
|
try:
|
|
from agent.usage_pricing import CanonicalUsage, estimate_usage_cost
|
|
|
|
cost = estimate_usage_cost(
|
|
usage["model"],
|
|
CanonicalUsage(
|
|
input_tokens=usage["input"],
|
|
output_tokens=usage["output"],
|
|
cache_read_tokens=usage["cache_read"],
|
|
cache_write_tokens=usage["cache_write"],
|
|
),
|
|
provider=getattr(agent, "provider", None),
|
|
base_url=getattr(agent, "base_url", None),
|
|
)
|
|
usage["cost_status"] = cost.status
|
|
if cost.amount_usd is not None:
|
|
usage["cost_usd"] = float(cost.amount_usd)
|
|
except Exception:
|
|
pass
|
|
return usage
|
|
|
|
|
|
def _probe_credentials(agent) -> str:
|
|
"""Light credential check at session creation — returns warning or ''."""
|
|
try:
|
|
key = getattr(agent, "api_key", "") or ""
|
|
provider = getattr(agent, "provider", "") or ""
|
|
if not key or key == "no-key-required":
|
|
return f"No API key configured for provider '{provider}'. First message will fail."
|
|
except Exception:
|
|
pass
|
|
return ""
|
|
|
|
|
|
def _probe_config_health(cfg: dict) -> str:
|
|
"""Flag bare YAML keys (`agent:` with no value → None) that silently
|
|
drop nested settings. Returns warning or ''."""
|
|
if not isinstance(cfg, dict):
|
|
return ""
|
|
warnings: list[str] = []
|
|
null_keys = sorted(k for k, v in cfg.items() if v is None)
|
|
if not null_keys:
|
|
pass
|
|
else:
|
|
keys = ", ".join(f"`{k}`" for k in null_keys)
|
|
warnings.append(
|
|
f"config.yaml has empty section(s): {keys}. "
|
|
f"Remove the line(s) or set them to `{{}}` — "
|
|
f"empty sections silently drop nested settings."
|
|
)
|
|
display_cfg = cfg.get("display")
|
|
agent_cfg = cfg.get("agent")
|
|
if isinstance(display_cfg, dict):
|
|
personality = str(display_cfg.get("personality", "") or "").strip().lower()
|
|
if (
|
|
personality
|
|
and personality not in {"default", "none", "neutral"}
|
|
and isinstance(agent_cfg, dict)
|
|
and agent_cfg.get("personalities") is None
|
|
):
|
|
warnings.append(
|
|
"`display.personality` is set but `agent.personalities` is empty/null; "
|
|
"personality overlay will be skipped."
|
|
)
|
|
return " ".join(warnings).strip()
|
|
|
|
|
|
def _current_profile_name() -> str:
|
|
try:
|
|
from hermes_cli.profiles import get_active_profile_name
|
|
|
|
return get_active_profile_name() or "default"
|
|
except Exception:
|
|
return "default"
|
|
|
|
|
|
# Monotonic GUI<->backend contract version. The desktop app refuses to drive a
|
|
# backend reporting less than its required value (or none at all — a pre-GUI
|
|
# checkout), surfacing a one-click "update to align" prompt instead of failing
|
|
# cryptically downstream. Bump whenever the desktop's backend contract changes.
|
|
DESKTOP_BACKEND_CONTRACT = 1
|
|
|
|
|
|
def _session_info(agent, session: dict | None = None) -> dict:
|
|
if session is None:
|
|
for candidate in _sessions.values():
|
|
if candidate.get("agent") is agent:
|
|
session = candidate
|
|
break
|
|
cwd = _session_cwd(session)
|
|
cfg_personality = ((_load_cfg().get("display") or {}).get("personality") or "")
|
|
personality = (session or {}).get("personality", cfg_personality)
|
|
reasoning_config = getattr(agent, "reasoning_config", None)
|
|
reasoning_effort = ""
|
|
if (
|
|
isinstance(reasoning_config, dict)
|
|
and reasoning_config.get("enabled") is not False
|
|
):
|
|
reasoning_effort = str(reasoning_config.get("effort", "") or "")
|
|
service_tier = getattr(agent, "service_tier", None) or ""
|
|
info: dict = {
|
|
"model": getattr(agent, "model", ""),
|
|
"reasoning_effort": reasoning_effort,
|
|
"service_tier": service_tier,
|
|
"fast": service_tier == "priority",
|
|
"tools": {},
|
|
"skills": {},
|
|
"cwd": cwd,
|
|
"branch": _git_branch_for_cwd(cwd),
|
|
"personality": str(personality or ""),
|
|
"running": bool((session or {}).get("running")),
|
|
"desktop_contract": DESKTOP_BACKEND_CONTRACT,
|
|
"version": "",
|
|
"release_date": "",
|
|
"update_behind": None,
|
|
"update_command": "",
|
|
"usage": _get_usage(agent),
|
|
"profile_name": _current_profile_name(),
|
|
}
|
|
try:
|
|
from hermes_cli import __version__, __release_date__
|
|
|
|
info["version"] = __version__
|
|
info["release_date"] = __release_date__
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from model_tools import get_toolset_for_tool
|
|
|
|
for t in getattr(agent, "tools", []) or []:
|
|
name = t["function"]["name"]
|
|
info["tools"].setdefault(get_toolset_for_tool(name) or "other", []).append(
|
|
name
|
|
)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from hermes_cli.banner import get_available_skills
|
|
|
|
info["skills"] = get_available_skills()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from tools.mcp_tool import get_mcp_status
|
|
|
|
info["mcp_servers"] = get_mcp_status()
|
|
except Exception:
|
|
info["mcp_servers"] = []
|
|
try:
|
|
info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from hermes_cli.banner import get_update_result
|
|
from hermes_cli.config import recommended_update_command
|
|
|
|
info["update_behind"] = get_update_result(timeout=0.5)
|
|
info["update_command"] = recommended_update_command()
|
|
except Exception:
|
|
pass
|
|
warn = _probe_credentials(agent)
|
|
if warn:
|
|
info["credential_warning"] = warn
|
|
return info
|
|
|
|
|
|
def _tool_ctx(name: str, args: dict) -> str:
|
|
try:
|
|
from agent.display import build_tool_preview
|
|
|
|
return build_tool_preview(name, args, max_len=80) or ""
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
_TUI_VERBOSE_TEXT_MAX_CHARS = 16_000
|
|
_TUI_VERBOSE_TEXT_MAX_LINES = 240
|
|
|
|
|
|
def _cap_tui_verbose_text(text: str) -> str:
|
|
if (
|
|
len(text) <= _TUI_VERBOSE_TEXT_MAX_CHARS
|
|
and text.count("\n") < _TUI_VERBOSE_TEXT_MAX_LINES
|
|
):
|
|
return text
|
|
|
|
idx = len(text)
|
|
start = 0
|
|
for _ in range(_TUI_VERBOSE_TEXT_MAX_LINES):
|
|
idx = text.rfind("\n", 0, idx)
|
|
if idx < 0:
|
|
start = 0
|
|
break
|
|
start = idx + 1
|
|
|
|
line_start = start
|
|
start = max(line_start, len(text) - _TUI_VERBOSE_TEXT_MAX_CHARS)
|
|
if start > line_start:
|
|
next_break = text.find("\n", start)
|
|
if 0 <= next_break < len(text) - 1:
|
|
start = next_break + 1
|
|
|
|
tail = text[start:].lstrip()
|
|
omitted_chars = max(0, len(text) - len(tail))
|
|
omitted_lines = text[:start].count("\n")
|
|
if omitted_lines:
|
|
label = (
|
|
"[showing verbose tail; omitted "
|
|
f"{omitted_lines} lines / {omitted_chars} chars]\n"
|
|
)
|
|
else:
|
|
label = f"[showing verbose tail; omitted {omitted_chars} chars]\n"
|
|
return f"{label}{tail}"
|
|
|
|
|
|
def _redact_tui_verbose_text(text: str) -> str:
|
|
try:
|
|
from agent.redact import redact_sensitive_text
|
|
|
|
redacted = redact_sensitive_text(str(text), force=True)
|
|
except Exception:
|
|
return ""
|
|
return _cap_tui_verbose_text(redacted)
|
|
|
|
|
|
def _tool_args_text(args: dict) -> str:
|
|
try:
|
|
raw = json.dumps(args or {}, indent=2, ensure_ascii=False, default=str)
|
|
except Exception:
|
|
raw = str(args or {})
|
|
return _redact_tui_verbose_text(raw)
|
|
|
|
|
|
def _tool_result_text(result: object) -> str:
|
|
try:
|
|
from agent.tool_dispatch_helpers import _multimodal_text_summary
|
|
|
|
raw = _multimodal_text_summary(result)
|
|
except Exception:
|
|
raw = str(result)
|
|
return _redact_tui_verbose_text(raw)
|
|
|
|
|
|
def _fmt_tool_duration(seconds: float | None) -> str:
|
|
if seconds is None:
|
|
return ""
|
|
if seconds < 10:
|
|
return f"{seconds:.1f}s"
|
|
if seconds < 60:
|
|
return f"{round(seconds)}s"
|
|
mins, secs = divmod(int(round(seconds)), 60)
|
|
return f"{mins}m {secs}s" if secs else f"{mins}m"
|
|
|
|
|
|
def _count_list(obj: object, *path: str) -> int | None:
|
|
cur = obj
|
|
for key in path:
|
|
if not isinstance(cur, dict):
|
|
return None
|
|
cur = cur.get(key)
|
|
return len(cur) if isinstance(cur, list) else None
|
|
|
|
|
|
def _tool_summary(name: str, result: str, duration_s: float | None) -> str | None:
|
|
try:
|
|
data = json.loads(result)
|
|
except Exception:
|
|
data = None
|
|
|
|
dur = _fmt_tool_duration(duration_s)
|
|
suffix = f" in {dur}" if dur else ""
|
|
text = None
|
|
|
|
if name == "web_search" and isinstance(data, dict):
|
|
n = _count_list(data, "data", "web")
|
|
if n is not None:
|
|
text = f"Did {n} {'search' if n == 1 else 'searches'}"
|
|
|
|
elif name == "web_extract" and isinstance(data, dict):
|
|
n = _count_list(data, "results") or _count_list(data, "data", "results")
|
|
if n is not None:
|
|
text = f"Extracted {n} {'page' if n == 1 else 'pages'}"
|
|
|
|
if isinstance(data, dict) and data.get("fallback_warning"):
|
|
warning = str(data.get("fallback_warning") or "").strip()
|
|
if warning:
|
|
return f"{warning}{suffix}"
|
|
|
|
return f"{text}{suffix}" if text else None
|
|
|
|
|
|
def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
|
|
session = _sessions.get(sid)
|
|
if session is not None:
|
|
try:
|
|
from agent.display import capture_local_edit_snapshot
|
|
|
|
snapshot = capture_local_edit_snapshot(name, args)
|
|
if snapshot is not None:
|
|
session.setdefault("edit_snapshots", {})[tool_call_id] = snapshot
|
|
except Exception:
|
|
pass
|
|
session.setdefault("tool_started_at", {})[tool_call_id] = time.time()
|
|
if _tool_progress_enabled(sid):
|
|
payload = {
|
|
"tool_id": tool_call_id,
|
|
"name": name,
|
|
"context": _tool_ctx(name, args),
|
|
}
|
|
if _session_verbose(sid):
|
|
args_text = _tool_args_text(args)
|
|
if args_text:
|
|
payload["args_text"] = args_text
|
|
# tool.complete is the source of truth for todos (full list from the
|
|
# tool result). args.todos here may be a partial merge update.
|
|
_emit("tool.start", sid, payload)
|
|
|
|
|
|
def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result: str):
|
|
payload = {"tool_id": tool_call_id, "name": name, "args": args}
|
|
session = _sessions.get(sid)
|
|
snapshot = None
|
|
started_at = None
|
|
if session is not None:
|
|
snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None)
|
|
started_at = session.setdefault("tool_started_at", {}).pop(tool_call_id, None)
|
|
duration_s = time.time() - started_at if started_at else None
|
|
if duration_s is not None:
|
|
payload["duration_s"] = duration_s
|
|
try:
|
|
payload["result"] = json.loads(result)
|
|
except Exception:
|
|
payload["result"] = result
|
|
summary = _tool_summary(name, result, duration_s)
|
|
if summary:
|
|
payload["summary"] = summary
|
|
if _session_verbose(sid):
|
|
result_text = _tool_result_text(result)
|
|
if result_text:
|
|
payload["result_text"] = result_text
|
|
if name == "todo":
|
|
try:
|
|
data = json.loads(result)
|
|
if isinstance(data, dict) and isinstance(data.get("todos"), list):
|
|
payload["todos"] = data.get("todos")
|
|
except Exception:
|
|
pass
|
|
try:
|
|
from agent.display import render_edit_diff_with_delta
|
|
|
|
rendered: list[str] = []
|
|
if render_edit_diff_with_delta(
|
|
name,
|
|
result,
|
|
function_args=args,
|
|
snapshot=snapshot,
|
|
print_fn=rendered.append,
|
|
):
|
|
payload["inline_diff"] = "\n".join(rendered)
|
|
except Exception:
|
|
pass
|
|
if _tool_progress_enabled(sid) or payload.get("inline_diff"):
|
|
_emit("tool.complete", sid, payload)
|
|
|
|
|
|
def _on_tool_progress(
|
|
sid: str,
|
|
event_type: str,
|
|
name: str | None = None,
|
|
preview: str | None = None,
|
|
_args: dict | None = None,
|
|
**_kwargs,
|
|
):
|
|
if not _tool_progress_enabled(sid):
|
|
return
|
|
if event_type == "tool.started" and name:
|
|
# `_on_tool_start` already emits the authoritative `tool.start` with
|
|
# the stable tool id and args. Emitting another id-less progress row
|
|
# here makes the desktop live view diverge from hydrated history.
|
|
return
|
|
if event_type == "reasoning.available" and preview:
|
|
payload: dict[str, object] = {"text": str(preview)}
|
|
if _session_verbose(sid):
|
|
payload["verbose"] = True
|
|
_emit("reasoning.available", sid, payload)
|
|
return
|
|
if event_type.startswith("subagent."):
|
|
payload = {
|
|
"goal": str(_kwargs.get("goal") or ""),
|
|
"task_count": int(_kwargs.get("task_count") or 1),
|
|
"task_index": int(_kwargs.get("task_index") or 0),
|
|
}
|
|
# Identity fields for the TUI spawn tree. All optional — older
|
|
# emitters that omit them fall back to flat rendering client-side.
|
|
if _kwargs.get("subagent_id"):
|
|
payload["subagent_id"] = str(_kwargs["subagent_id"])
|
|
if _kwargs.get("parent_id"):
|
|
payload["parent_id"] = str(_kwargs["parent_id"])
|
|
if _kwargs.get("depth") is not None:
|
|
payload["depth"] = int(_kwargs["depth"])
|
|
if _kwargs.get("model"):
|
|
payload["model"] = str(_kwargs["model"])
|
|
if _kwargs.get("tool_count") is not None:
|
|
payload["tool_count"] = int(_kwargs["tool_count"])
|
|
if _kwargs.get("toolsets"):
|
|
payload["toolsets"] = [str(t) for t in _kwargs["toolsets"]]
|
|
# Per-branch rollups emitted on subagent.complete (features 1+2+4).
|
|
for int_key in (
|
|
"input_tokens",
|
|
"output_tokens",
|
|
"reasoning_tokens",
|
|
"api_calls",
|
|
):
|
|
val = _kwargs.get(int_key)
|
|
if val is not None:
|
|
try:
|
|
payload[int_key] = int(val)
|
|
except (TypeError, ValueError):
|
|
pass
|
|
if _kwargs.get("cost_usd") is not None:
|
|
try:
|
|
payload["cost_usd"] = float(_kwargs["cost_usd"])
|
|
except (TypeError, ValueError):
|
|
pass
|
|
if _kwargs.get("files_read"):
|
|
payload["files_read"] = [str(p) for p in _kwargs["files_read"]]
|
|
if _kwargs.get("files_written"):
|
|
payload["files_written"] = [str(p) for p in _kwargs["files_written"]]
|
|
if _kwargs.get("output_tail"):
|
|
payload["output_tail"] = list(_kwargs["output_tail"]) # list of dicts
|
|
if name:
|
|
payload["tool_name"] = str(name)
|
|
if preview:
|
|
payload["text"] = str(preview)
|
|
if _kwargs.get("status"):
|
|
payload["status"] = str(_kwargs["status"])
|
|
if _kwargs.get("summary"):
|
|
payload["summary"] = str(_kwargs["summary"])
|
|
if _kwargs.get("duration_seconds") is not None:
|
|
payload["duration_seconds"] = float(_kwargs["duration_seconds"])
|
|
if preview and event_type == "subagent.tool":
|
|
payload["tool_preview"] = str(preview)
|
|
payload["text"] = str(preview)
|
|
_emit(event_type, sid, payload)
|
|
|
|
|
|
def _agent_cbs(sid: str) -> dict:
|
|
return {
|
|
"tool_start_callback": lambda tc_id, name, args: _on_tool_start(
|
|
sid, tc_id, name, args
|
|
),
|
|
"tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(
|
|
sid, tc_id, name, args, result
|
|
),
|
|
"tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
|
|
sid, event_type, name, preview, args, **kwargs
|
|
),
|
|
"tool_gen_callback": lambda name: _tool_progress_enabled(sid)
|
|
and _emit("tool.generating", sid, {"name": name}),
|
|
"thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
|
|
"reasoning_callback": lambda text: _emit(
|
|
"reasoning.delta",
|
|
sid,
|
|
{"text": text, **({"verbose": True} if _session_verbose(sid) else {})},
|
|
),
|
|
"status_callback": lambda kind, text=None: _status_update(
|
|
sid, str(kind), None if text is None else str(text)
|
|
),
|
|
"clarify_callback": lambda q, c: _block(
|
|
"clarify.request", sid, {"question": q, "choices": c}
|
|
),
|
|
}
|
|
|
|
|
|
def _wire_callbacks(sid: str):
|
|
from tools.terminal_tool import set_sudo_password_callback
|
|
from tools.skills_tool import set_secret_capture_callback
|
|
|
|
set_sudo_password_callback(lambda: _block("sudo.request", sid, {}, timeout=120))
|
|
|
|
def secret_cb(env_var, prompt, metadata=None):
|
|
pl = {"prompt": prompt, "env_var": env_var}
|
|
if metadata:
|
|
pl["metadata"] = metadata
|
|
val = _block("secret.request", sid, pl)
|
|
if not val:
|
|
return {
|
|
"success": True,
|
|
"stored_as": env_var,
|
|
"validated": False,
|
|
"skipped": True,
|
|
"message": "skipped",
|
|
}
|
|
from hermes_cli.config import save_env_value_secure
|
|
|
|
return {
|
|
**save_env_value_secure(env_var, val),
|
|
"skipped": False,
|
|
"message": "ok",
|
|
}
|
|
|
|
set_secret_capture_callback(secret_cb)
|
|
|
|
|
|
def _render_personality_prompt(value) -> str:
|
|
if isinstance(value, dict):
|
|
parts = [value.get("system_prompt", "")]
|
|
if value.get("tone"):
|
|
parts.append(f'Tone: {value["tone"]}')
|
|
if value.get("style"):
|
|
parts.append(f'Style: {value["style"]}')
|
|
return "\n".join(p for p in parts if p)
|
|
return str(value)
|
|
|
|
|
|
def _available_personalities(cfg: dict | None = None) -> dict:
|
|
try:
|
|
from cli import load_cli_config
|
|
|
|
return (load_cli_config().get("agent") or {}).get("personalities", {}) or {}
|
|
except Exception:
|
|
try:
|
|
from hermes_cli.config import load_config as _load_full_cfg
|
|
|
|
return (_load_full_cfg().get("agent") or {}).get("personalities", {}) or {}
|
|
except Exception:
|
|
cfg = cfg or _load_cfg()
|
|
return (cfg.get("agent") or {}).get("personalities", {}) or {}
|
|
|
|
|
|
def _validate_personality(value: str, cfg: dict | None = None) -> tuple[str, str]:
|
|
raw = str(value or "").strip()
|
|
name = raw.lower()
|
|
if not name or name in {"none", "default", "neutral"}:
|
|
return "", ""
|
|
|
|
personalities = _available_personalities(cfg)
|
|
if name not in personalities:
|
|
names = sorted(personalities)
|
|
available = ", ".join(f"`{n}`" for n in names)
|
|
base = f"Unknown personality: `{raw}`."
|
|
if available:
|
|
base += f"\n\nAvailable: `none`, {available}"
|
|
else:
|
|
base += "\n\nNo personalities configured."
|
|
raise ValueError(base)
|
|
|
|
return name, _render_personality_prompt(personalities[name])
|
|
|
|
|
|
def _prompt_text(value) -> str:
|
|
"""Normalize config prompt values from YAML before handing them to AIAgent."""
|
|
if value is None:
|
|
return ""
|
|
if isinstance(value, str):
|
|
return value.strip()
|
|
if isinstance(value, list):
|
|
return "\n".join(str(item).strip() for item in value if str(item).strip())
|
|
return str(value).strip()
|
|
|
|
|
|
def _apply_personality_to_session(
|
|
sid: str, session: dict, new_prompt: str, personality: str = ""
|
|
) -> tuple[bool, dict | None]:
|
|
"""Apply a personality change to an existing session without resetting history.
|
|
|
|
Updates the agent's ephemeral system prompt in-place so the new personality
|
|
takes effect on the next turn. The cached base system prompt is left intact
|
|
(ephemeral_system_prompt is appended at API-call time, not baked into the
|
|
cache), which preserves prompt-cache hits.
|
|
|
|
Also injects a system-role marker into the conversation history so the model
|
|
knows to pivot its style from this point forward (without this, LLMs tend to
|
|
continue the tone established by earlier messages in the transcript).
|
|
|
|
Returns (history_reset, info) — history_reset is always False since we
|
|
preserve the conversation.
|
|
"""
|
|
if not session:
|
|
return False, None
|
|
session["personality"] = personality
|
|
|
|
agent = session.get("agent")
|
|
if agent:
|
|
agent.ephemeral_system_prompt = new_prompt or None
|
|
# Inject a pivot marker into history so the model sees the change point.
|
|
# This prevents it from pattern-matching its prior style.
|
|
if new_prompt:
|
|
marker = (
|
|
"[System: The user has changed the assistant's personality. "
|
|
"From this point forward, adopt the following persona and respond "
|
|
f"accordingly: {new_prompt}]"
|
|
)
|
|
else:
|
|
marker = (
|
|
"[System: The user has cleared the personality overlay. "
|
|
"From this point forward, respond in your normal default style.]"
|
|
)
|
|
with session["history_lock"]:
|
|
session["history"].append({"role": "user", "content": marker})
|
|
session["history_version"] = int(session.get("history_version", 0)) + 1
|
|
info = _session_info(agent)
|
|
_emit("session.info", sid, info)
|
|
return False, info
|
|
return False, None
|
|
|
|
|
|
def _cfg_max_turns(cfg: dict, default: int) -> int:
|
|
try:
|
|
env_max = int(os.environ.get("HERMES_TUI_MAX_TURNS", "") or 0)
|
|
if env_max > 0:
|
|
return env_max
|
|
except (TypeError, ValueError):
|
|
pass
|
|
agent_cfg = cfg.get("agent") or {}
|
|
return int(agent_cfg.get("max_turns") or cfg.get("max_turns") or default)
|
|
|
|
|
|
def _parse_tui_skills_env() -> list[str]:
|
|
raw = os.environ.get("HERMES_TUI_SKILLS", "")
|
|
skills: list[str] = []
|
|
seen: set[str] = set()
|
|
for part in raw.replace("\n", ",").split(","):
|
|
item = part.strip()
|
|
if item and item not in seen:
|
|
seen.add(item)
|
|
skills.append(item)
|
|
return skills
|
|
|
|
|
|
def _background_agent_kwargs(agent, task_id: str) -> dict:
|
|
cfg = _load_cfg()
|
|
|
|
return {
|
|
"base_url": getattr(agent, "base_url", None) or None,
|
|
"api_key": getattr(agent, "api_key", None) or None,
|
|
"provider": getattr(agent, "provider", None) or None,
|
|
"api_mode": getattr(agent, "api_mode", None) or None,
|
|
"acp_command": getattr(agent, "acp_command", None) or None,
|
|
"acp_args": getattr(agent, "acp_args", None) or None,
|
|
"model": getattr(agent, "model", None) or _resolve_model(),
|
|
"max_iterations": _cfg_max_turns(cfg, 25),
|
|
"enabled_toolsets": getattr(agent, "enabled_toolsets", None)
|
|
or _load_enabled_toolsets(),
|
|
"quiet_mode": True,
|
|
"verbose_logging": False,
|
|
"ephemeral_system_prompt": getattr(agent, "ephemeral_system_prompt", None)
|
|
or None,
|
|
"providers_allowed": getattr(agent, "providers_allowed", None),
|
|
"providers_ignored": getattr(agent, "providers_ignored", None),
|
|
"providers_order": getattr(agent, "providers_order", None),
|
|
"provider_sort": getattr(agent, "provider_sort", None),
|
|
"provider_require_parameters": getattr(
|
|
agent, "provider_require_parameters", False
|
|
),
|
|
"provider_data_collection": getattr(agent, "provider_data_collection", None),
|
|
"openrouter_min_coding_score": getattr(agent, "openrouter_min_coding_score", None),
|
|
"session_id": task_id,
|
|
"reasoning_config": getattr(agent, "reasoning_config", None)
|
|
or _load_reasoning_config(),
|
|
"service_tier": getattr(agent, "service_tier", None) or _load_service_tier(),
|
|
"request_overrides": dict(getattr(agent, "request_overrides", {}) or {}),
|
|
"platform": "tui",
|
|
"session_db": _get_db(),
|
|
"fallback_model": getattr(agent, "_fallback_model", None),
|
|
}
|
|
|
|
|
|
def _ephemeral_preview_agent_kwargs(agent, task_id: str) -> dict:
|
|
kwargs = _background_agent_kwargs(agent, task_id)
|
|
kwargs.update(
|
|
{
|
|
"enabled_toolsets": ["terminal", "file"],
|
|
"session_db": None,
|
|
"skip_memory": True,
|
|
}
|
|
)
|
|
return kwargs
|
|
|
|
|
|
def _preview_restart_history(session: dict, max_messages: int = 24, max_tool_chars: int = 1200) -> list[dict]:
|
|
"""Distill the parent session's recent history into a context the
|
|
ephemeral preview-restart agent can actually use.
|
|
|
|
The restart agent has no idea what app the user was building, what
|
|
server they ran, what cwd was active, or which port belongs to which
|
|
project. Without this, it would take the bare URL + console logs and
|
|
guess — usually starting the wrong thing.
|
|
|
|
We keep the last ``max_messages`` messages from the parent session so
|
|
the restart agent sees recent user prompts, assistant replies, and
|
|
most importantly any terminal/tool calls. Tool result payloads are
|
|
truncated so we don't blow the context window with file dumps.
|
|
"""
|
|
try:
|
|
with session["history_lock"]:
|
|
history = list(session.get("history", []) or [])
|
|
except Exception:
|
|
history = list(session.get("history", []) or [])
|
|
|
|
if not history:
|
|
return []
|
|
|
|
# Anchor on the last user turn so we always include at least the most
|
|
# recent request and the assistant/tool work that followed it. Then
|
|
# extend backwards up to max_messages so we capture the prior context.
|
|
last_user_idx = None
|
|
for idx in range(len(history) - 1, -1, -1):
|
|
if history[idx].get("role") == "user":
|
|
last_user_idx = idx
|
|
break
|
|
|
|
start = max(0, len(history) - max_messages)
|
|
if last_user_idx is not None:
|
|
start = min(start, last_user_idx)
|
|
|
|
trimmed: list[dict] = []
|
|
for msg in history[start:]:
|
|
if not isinstance(msg, dict):
|
|
continue
|
|
role = msg.get("role")
|
|
if role not in ("user", "assistant", "tool", "system"):
|
|
continue
|
|
|
|
copy = {k: v for k, v in msg.items() if k != "reasoning"}
|
|
# Truncate heavy tool outputs so a single 50KB file read doesn't
|
|
# crowd out the rest of the context.
|
|
if role == "tool":
|
|
content = copy.get("content")
|
|
if isinstance(content, str) and len(content) > max_tool_chars:
|
|
copy["content"] = (
|
|
content[:max_tool_chars]
|
|
+ f"\n... (truncated, original {len(content)} chars)"
|
|
)
|
|
trimmed.append(copy)
|
|
|
|
return trimmed
|
|
|
|
|
|
def _preview_tool_result_preview(name: str, result: str) -> str:
|
|
try:
|
|
data = json.loads(result)
|
|
except Exception:
|
|
return ""
|
|
|
|
if not isinstance(data, dict):
|
|
return ""
|
|
|
|
if name == "terminal":
|
|
output = str(data.get("output") or "").strip()
|
|
exit_code = data.get("exit_code")
|
|
if output:
|
|
return output[-1200:]
|
|
if data.get("session_id"):
|
|
return f"Background process started: {data.get('session_id')}"
|
|
if exit_code is not None:
|
|
return f"terminal exited with code {exit_code}"
|
|
|
|
return str(data.get("error") or "").strip()[:1200]
|
|
|
|
|
|
def _preview_restart_callbacks(parent: str, task_id: str) -> dict:
|
|
started_at: dict[str, float] = {}
|
|
|
|
def progress(message: str, level: str = "info") -> None:
|
|
text = str(message or "").strip()
|
|
if text:
|
|
_emit("preview.restart.progress", parent, {"task_id": task_id, "level": level, "text": text})
|
|
|
|
def tool_start(tool_call_id: str, name: str, args: dict) -> None:
|
|
started_at[tool_call_id] = time.time()
|
|
ctx = _tool_ctx(name, args)
|
|
progress(f"Running {name}{f': {ctx}' if ctx else ''}")
|
|
|
|
def tool_complete(tool_call_id: str, name: str, _args: dict, result: str) -> None:
|
|
duration_s = time.time() - started_at.get(tool_call_id, time.time())
|
|
summary = _tool_summary(name, result, duration_s) or f"Finished {name}{f' in {_fmt_tool_duration(duration_s)}' if duration_s else ''}"
|
|
output = _preview_tool_result_preview(name, result)
|
|
progress(summary + (f"\n{output}" if output else ""))
|
|
|
|
def tool_progress(event_type: str, name: str | None = None, preview: str | None = None, **_kwargs) -> None:
|
|
if preview:
|
|
progress(str(preview))
|
|
elif name:
|
|
progress(f"{event_type.replace('.', ' ')}: {name}")
|
|
|
|
return {
|
|
"tool_start_callback": tool_start,
|
|
"tool_complete_callback": tool_complete,
|
|
"tool_progress_callback": tool_progress,
|
|
"tool_gen_callback": lambda name: progress(f"Preparing {name}"),
|
|
"status_callback": lambda kind, text=None: progress(text if text is not None else kind),
|
|
}
|
|
|
|
|
|
def _reset_session_agent(sid: str, session: dict) -> dict:
|
|
tokens = _set_session_context(session["session_key"])
|
|
try:
|
|
new_agent = _make_agent(
|
|
sid, session["session_key"], session_id=session["session_key"]
|
|
)
|
|
finally:
|
|
_clear_session_context(tokens)
|
|
session["agent"] = new_agent
|
|
session["attached_images"] = []
|
|
session["edit_snapshots"] = {}
|
|
session["image_counter"] = 0
|
|
session["running"] = False
|
|
session["show_reasoning"] = _load_show_reasoning()
|
|
session["tool_progress_mode"] = _load_tool_progress_mode()
|
|
session["tool_started_at"] = {}
|
|
with session["history_lock"]:
|
|
session["history"] = []
|
|
session["history_version"] = int(session.get("history_version", 0)) + 1
|
|
info = _session_info(new_agent, session)
|
|
_emit("session.info", sid, info)
|
|
_restart_slash_worker(session)
|
|
return info
|
|
|
|
|
|
def _make_agent(sid: str, key: str, session_id: str | None = None):
|
|
from run_agent import AIAgent
|
|
from hermes_cli.runtime_provider import resolve_runtime_provider
|
|
|
|
# MCP tool discovery runs in a background daemon thread at startup so a
|
|
# dead server can't freeze the shell (see tui_gateway/entry.py). The agent
|
|
# snapshots its tool list once here and never re-reads it, so briefly wait
|
|
# for in-flight discovery to land before building — bounded, so a slow/dead
|
|
# server still can't block. No-op once discovery has finished (every build
|
|
# after the first during a slow startup).
|
|
try:
|
|
from tui_gateway.entry import wait_for_mcp_discovery
|
|
|
|
wait_for_mcp_discovery()
|
|
except Exception:
|
|
pass
|
|
|
|
cfg = _load_cfg()
|
|
agent_cfg = cfg.get("agent") or {}
|
|
system_prompt = _prompt_text(agent_cfg.get("system_prompt", ""))
|
|
startup_skills = _parse_tui_skills_env()
|
|
if startup_skills:
|
|
from agent.skill_commands import build_preloaded_skills_prompt
|
|
|
|
skills_prompt, _loaded_skills, missing_skills = build_preloaded_skills_prompt(
|
|
startup_skills,
|
|
task_id=session_id or key,
|
|
)
|
|
if missing_skills:
|
|
raise ValueError(f"Unknown skill(s): {', '.join(missing_skills)}")
|
|
if skills_prompt:
|
|
system_prompt = "\n\n".join(
|
|
part for part in (system_prompt, skills_prompt) if part
|
|
).strip()
|
|
model, requested_provider = _resolve_startup_runtime()
|
|
runtime = resolve_runtime_provider(
|
|
requested=requested_provider,
|
|
target_model=model or None,
|
|
)
|
|
return AIAgent(
|
|
model=model,
|
|
max_iterations=_cfg_max_turns(cfg, 90),
|
|
provider=runtime.get("provider"),
|
|
base_url=runtime.get("base_url"),
|
|
api_key=runtime.get("api_key"),
|
|
api_mode=runtime.get("api_mode"),
|
|
acp_command=runtime.get("command"),
|
|
acp_args=runtime.get("args"),
|
|
credential_pool=runtime.get("credential_pool"),
|
|
quiet_mode=True,
|
|
# verbose_logging controls DEBUG-level agent logging; it is intentionally
|
|
# independent of tool_progress_mode (which only controls per-tool
|
|
# display detail). See cli.py PR (decoupling fix) for the matching
|
|
# change on the classic CLI side.
|
|
verbose_logging=False,
|
|
reasoning_config=_load_reasoning_config(),
|
|
service_tier=_load_service_tier(),
|
|
enabled_toolsets=_load_enabled_toolsets(),
|
|
platform="tui",
|
|
session_id=session_id or key,
|
|
session_db=_get_db(),
|
|
ephemeral_system_prompt=system_prompt or None,
|
|
checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),
|
|
pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),
|
|
skip_context_files=is_truthy_value(os.environ.get("HERMES_IGNORE_RULES")),
|
|
skip_memory=is_truthy_value(os.environ.get("HERMES_IGNORE_RULES")),
|
|
**_agent_cbs(sid),
|
|
)
|
|
|
|
|
|
def _init_session(sid: str, key: str, agent, history: list, cols: int = 80):
|
|
now = time.time()
|
|
_sessions[sid] = {
|
|
"agent": agent,
|
|
"session_key": key,
|
|
"history": history,
|
|
"history_lock": threading.Lock(),
|
|
"history_version": 0,
|
|
"inflight_turn": None,
|
|
"created_at": now,
|
|
"last_active": now,
|
|
"running": False,
|
|
"attached_images": [],
|
|
"image_counter": 0,
|
|
"cwd": _completion_cwd(),
|
|
"cols": cols,
|
|
"slash_worker": None,
|
|
"show_reasoning": _load_show_reasoning(),
|
|
"tool_progress_mode": _load_tool_progress_mode(),
|
|
"edit_snapshots": {},
|
|
"tool_started_at": {},
|
|
# Pin async event emissions to whichever transport created the
|
|
# session (stdio for Ink, JSON-RPC WS for the dashboard sidebar).
|
|
"transport": current_transport() or _stdio_transport,
|
|
}
|
|
db = _get_db()
|
|
if db is not None:
|
|
row = db.get_session(key)
|
|
if row and row.get("cwd"):
|
|
_sessions[sid]["cwd"] = row["cwd"]
|
|
else:
|
|
try:
|
|
db.update_session_cwd(key, _sessions[sid]["cwd"])
|
|
except Exception:
|
|
logger.debug("failed to persist resumed session cwd", exc_info=True)
|
|
_register_session_cwd(_sessions[sid])
|
|
try:
|
|
_sessions[sid]["slash_worker"] = _SlashWorker(
|
|
key, getattr(agent, "model", _resolve_model())
|
|
)
|
|
except Exception:
|
|
# Defer hard-failure to slash.exec; chat still works without slash worker.
|
|
_sessions[sid]["slash_worker"] = None
|
|
try:
|
|
from tools.approval import register_gateway_notify, load_permanent_allowlist
|
|
|
|
register_gateway_notify(key, lambda data: _emit("approval.request", sid, data))
|
|
load_permanent_allowlist()
|
|
except Exception:
|
|
pass
|
|
# Surface the self-improvement background review's "💾 …" summary as a
|
|
# review.summary event so Ink can render it as a persistent system line
|
|
# in the transcript. In the CLI path this message is printed via
|
|
# prompt_toolkit; the TUI has no equivalent print surface, so without
|
|
# this callback the review would write the skill/memory change silently.
|
|
try:
|
|
agent.background_review_callback = lambda message, _sid=sid: _emit(
|
|
"review.summary", _sid, {"text": str(message)}
|
|
)
|
|
except Exception:
|
|
# Bare AIAgents that don't expose the attribute (unlikely, but keep
|
|
# session startup resilient).
|
|
pass
|
|
_wire_callbacks(sid)
|
|
_sessions[sid]["_notif_stop"] = _start_notification_poller(sid, _sessions[sid])
|
|
_notify_session_boundary("on_session_reset", key)
|
|
_emit("session.info", sid, _session_info(agent, _sessions[sid]))
|
|
|
|
|
|
def _new_session_key() -> str:
|
|
return f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
|
|
|
|
|
|
def _with_checkpoints(session, fn):
|
|
return fn(session["agent"]._checkpoint_mgr, _session_cwd(session))
|
|
|
|
|
|
def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:
|
|
try:
|
|
checkpoints = mgr.list_checkpoints(cwd)
|
|
idx = int(ref) - 1
|
|
except ValueError:
|
|
return ref
|
|
if 0 <= idx < len(checkpoints):
|
|
return checkpoints[idx].get("hash", ref)
|
|
raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")
|
|
|
|
|
|
def _enrich_with_attached_images(user_text: str, image_paths: list[str]) -> str:
|
|
"""Pre-analyze attached images via vision and prepend descriptions to user text."""
|
|
import asyncio, json as _json
|
|
from tools.vision_tools import vision_analyze_tool
|
|
|
|
prompt = (
|
|
"Describe everything visible in this image in thorough detail. "
|
|
"Include any text, code, data, objects, people, layout, colors, "
|
|
"and any other notable visual information."
|
|
)
|
|
|
|
parts: list[str] = []
|
|
for path in image_paths:
|
|
p = Path(path)
|
|
if not p.exists():
|
|
continue
|
|
hint = f"[You can examine it with vision_analyze using image_url: {p}]"
|
|
try:
|
|
r = _json.loads(
|
|
asyncio.run(vision_analyze_tool(image_url=str(p), user_prompt=prompt))
|
|
)
|
|
desc = r.get("analysis", "") if r.get("success") else None
|
|
parts.append(
|
|
f"[The user attached an image:\n{desc}]\n{hint}"
|
|
if desc
|
|
else f"[The user attached an image but analysis failed.]\n{hint}"
|
|
)
|
|
except Exception:
|
|
parts.append(f"[The user attached an image but analysis failed.]\n{hint}")
|
|
|
|
text = user_text or ""
|
|
prefix = "\n\n".join(parts)
|
|
if prefix:
|
|
return f"{prefix}\n\n{text}" if text else prefix
|
|
return text or "What do you see in this image?"
|
|
|
|
|
|
def _content_display_text(content: Any) -> str:
|
|
if content is None:
|
|
return ""
|
|
if isinstance(content, str):
|
|
return content
|
|
if isinstance(content, (int, float)):
|
|
return str(content)
|
|
if isinstance(content, list):
|
|
parts = []
|
|
for part in content:
|
|
text = _content_display_text(part).strip()
|
|
if text:
|
|
parts.append(text)
|
|
return "\n".join(parts)
|
|
if isinstance(content, dict):
|
|
kind = content.get("type")
|
|
if kind in {"text", "input_text", "output_text"}:
|
|
return str(content.get("text") or content.get("content") or "")
|
|
if kind in {"image_url", "input_image", "image"}:
|
|
return "[image]"
|
|
if kind in {"input_audio", "audio"}:
|
|
return "[audio]"
|
|
if kind:
|
|
return f"[{kind}]"
|
|
if "text" in content:
|
|
return str(content.get("text") or "")
|
|
return "[structured content]"
|
|
return str(content)
|
|
|
|
|
|
def _coerce_message_text(content: Any) -> str:
|
|
"""Render ``message['content']`` as a plain string for transport.
|
|
|
|
Provider-side, ``content`` may be a string (most common), a list of
|
|
multimodal parts (e.g. ``[{"type": "text", "text": "..."},
|
|
{"type": "image_url", "image_url": {...}}]``), or a single structured
|
|
dict. Calling ``.strip()`` on a list raises ``'list' object has no
|
|
attribute 'strip'`` and breaks session resume entirely.
|
|
|
|
Image parts (``image_url``) are preserved by appending the underlying
|
|
URL (data: or http:) into the text. The desktop renderer pulls these
|
|
back out via ``extractEmbeddedImages`` so the user sees the image
|
|
instead of the URL — and it stops the resume payload from disagreeing
|
|
with the cached message (which would otherwise cause the inline image
|
|
to flash, then disappear when the resume payload overwrites the cache).
|
|
|
|
Other structured dict shapes (audio, unknown types) fall back to a
|
|
bracketed placeholder so resume doesn't drop the message entirely.
|
|
"""
|
|
if content is None:
|
|
return ""
|
|
if isinstance(content, str):
|
|
return content
|
|
if isinstance(content, (int, float)):
|
|
return str(content)
|
|
if isinstance(content, list):
|
|
chunks: list[str] = []
|
|
for part in content:
|
|
if isinstance(part, str):
|
|
chunks.append(part)
|
|
continue
|
|
if not isinstance(part, dict):
|
|
continue
|
|
text = part.get("text")
|
|
if isinstance(text, str):
|
|
chunks.append(text)
|
|
continue
|
|
kind = part.get("type")
|
|
if kind in {"text", "input_text", "output_text"}:
|
|
t = part.get("text") or part.get("content") or ""
|
|
if t:
|
|
chunks.append(str(t))
|
|
continue
|
|
if kind in {"image_url", "input_image", "image"}:
|
|
image_url = part.get("image_url")
|
|
url = ""
|
|
if isinstance(image_url, dict):
|
|
candidate = image_url.get("url")
|
|
if isinstance(candidate, str):
|
|
url = candidate
|
|
elif isinstance(image_url, str):
|
|
url = image_url
|
|
if url:
|
|
chunks.append(f"\n{url}")
|
|
else:
|
|
chunks.append("\n[image]")
|
|
continue
|
|
if kind in {"input_audio", "audio"}:
|
|
chunks.append("\n[audio]")
|
|
continue
|
|
if kind:
|
|
chunks.append(f"\n[{kind}]")
|
|
return "".join(chunks)
|
|
if isinstance(content, dict):
|
|
kind = content.get("type")
|
|
if kind in {"text", "input_text", "output_text"}:
|
|
return str(content.get("text") or content.get("content") or "")
|
|
if kind in {"image_url", "input_image", "image"}:
|
|
image_url = content.get("image_url")
|
|
url = ""
|
|
if isinstance(image_url, dict):
|
|
candidate = image_url.get("url")
|
|
if isinstance(candidate, str):
|
|
url = candidate
|
|
elif isinstance(image_url, str):
|
|
url = image_url
|
|
return url or "[image]"
|
|
if kind in {"input_audio", "audio"}:
|
|
return "[audio]"
|
|
if kind:
|
|
return f"[{kind}]"
|
|
if "text" in content:
|
|
return str(content.get("text") or "")
|
|
return "[structured content]"
|
|
return str(content)
|
|
|
|
|
|
def _history_to_messages(history: list[dict]) -> list[dict]:
|
|
messages = []
|
|
tool_call_args = {}
|
|
|
|
for m in history:
|
|
if not isinstance(m, dict):
|
|
continue
|
|
role = m.get("role")
|
|
if role not in {"user", "assistant", "tool", "system"}:
|
|
continue
|
|
content_text = _coerce_message_text(m.get("content"))
|
|
if role == "assistant" and m.get("tool_calls"):
|
|
for tc in m["tool_calls"]:
|
|
fn = tc.get("function", {})
|
|
tc_id = tc.get("id", "")
|
|
if tc_id and fn.get("name"):
|
|
try:
|
|
args = json.loads(fn.get("arguments", "{}"))
|
|
except (json.JSONDecodeError, TypeError):
|
|
args = {}
|
|
tool_call_args[tc_id] = (fn["name"], args)
|
|
if not content_text.strip():
|
|
continue
|
|
if role == "tool":
|
|
tc_id = m.get("tool_call_id", "")
|
|
tc_info = tool_call_args.get(tc_id) if tc_id else None
|
|
name = (tc_info[0] if tc_info else None) or m.get("tool_name") or "tool"
|
|
args = (tc_info[1] if tc_info else None) or {}
|
|
messages.append(
|
|
{"role": "tool", "name": name, "context": _tool_ctx(name, args)}
|
|
)
|
|
continue
|
|
if not content_text.strip():
|
|
continue
|
|
msg = {"role": role, "text": content_text}
|
|
if role == "assistant":
|
|
for key in (
|
|
"reasoning",
|
|
"reasoning_content",
|
|
"reasoning_details",
|
|
"codex_reasoning_items",
|
|
):
|
|
if key in m and m.get(key) is not None:
|
|
msg[key] = m.get(key)
|
|
messages.append(msg)
|
|
|
|
return messages
|
|
|
|
|
|
def _coerce_seed_history(value: Any) -> list[dict]:
|
|
if not isinstance(value, list):
|
|
return []
|
|
|
|
history = []
|
|
for item in value:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
|
|
role = item.get("role")
|
|
if role not in ("user", "assistant", "system"):
|
|
continue
|
|
|
|
content = item.get("content")
|
|
if content is None:
|
|
content = item.get("text")
|
|
if not isinstance(content, str) or not content.strip():
|
|
continue
|
|
|
|
history.append({"role": role, "content": content})
|
|
|
|
return history
|
|
|
|
|
|
def _content_display_text(content: Any) -> str:
|
|
if content is None:
|
|
return ""
|
|
if isinstance(content, str):
|
|
return content
|
|
if isinstance(content, (int, float)):
|
|
return str(content)
|
|
if isinstance(content, list):
|
|
parts = []
|
|
for part in content:
|
|
text = _content_display_text(part).strip()
|
|
if text:
|
|
parts.append(text)
|
|
return "\n".join(parts)
|
|
if isinstance(content, dict):
|
|
kind = content.get("type")
|
|
if kind in {"text", "input_text", "output_text"}:
|
|
return str(content.get("text") or content.get("content") or "")
|
|
if kind in {"image_url", "input_image", "image"}:
|
|
return "[image]"
|
|
if kind in {"input_audio", "audio"}:
|
|
return "[audio]"
|
|
if kind:
|
|
return f"[{kind}]"
|
|
if "text" in content:
|
|
return str(content.get("text") or "")
|
|
return "[structured content]"
|
|
return str(content)
|
|
|
|
|
|
def _inflight_text(value: Any) -> str:
|
|
return _content_display_text(value).strip()
|
|
|
|
|
|
def _start_inflight_turn(session: dict, text: Any) -> None:
|
|
now = time.time()
|
|
session["inflight_turn"] = {
|
|
"assistant": "",
|
|
"started_at": now,
|
|
"streaming": True,
|
|
"updated_at": now,
|
|
"user": _inflight_text(text),
|
|
}
|
|
|
|
|
|
def _append_inflight_delta(session: dict, delta: Any) -> None:
|
|
text = "" if delta is None else str(delta)
|
|
if not text:
|
|
return
|
|
turn = session.get("inflight_turn")
|
|
if not isinstance(turn, dict):
|
|
turn = {"assistant": "", "streaming": True, "user": ""}
|
|
turn["assistant"] = f"{turn.get('assistant') or ''}{text}"
|
|
turn["streaming"] = True
|
|
turn["updated_at"] = time.time()
|
|
session["inflight_turn"] = turn
|
|
|
|
|
|
def _clear_inflight_turn(session: dict) -> None:
|
|
session["inflight_turn"] = None
|
|
|
|
|
|
def _inflight_snapshot(session: dict) -> dict | None:
|
|
turn = session.get("inflight_turn")
|
|
if not isinstance(turn, dict):
|
|
return None
|
|
user = str(turn.get("user") or "").strip()
|
|
assistant = str(turn.get("assistant") or "")
|
|
streaming = bool(turn.get("streaming"))
|
|
if not user and not assistant and not streaming:
|
|
return None
|
|
return {
|
|
"assistant": assistant,
|
|
"streaming": streaming,
|
|
"user": user,
|
|
}
|
|
|
|
|
|
# ── Methods: session ─────────────────────────────────────────────────
|
|
|
|
|
|
@method("session.create")
|
|
def _(rid, params: dict) -> dict:
|
|
sid = uuid.uuid4().hex[:8]
|
|
key = _new_session_key()
|
|
cols = int(params.get("cols", 80))
|
|
history = _coerce_seed_history(params.get("messages"))
|
|
title = str(params.get("title") or "").strip()
|
|
_enable_gateway_prompts()
|
|
|
|
ready = threading.Event()
|
|
now = time.time()
|
|
|
|
_sessions[sid] = {
|
|
"agent": None,
|
|
"agent_error": None,
|
|
"agent_ready": ready,
|
|
"attached_images": [],
|
|
"cols": cols,
|
|
"created_at": now,
|
|
"edit_snapshots": {},
|
|
"history": history,
|
|
"history_lock": threading.Lock(),
|
|
"history_version": 0,
|
|
"image_counter": 0,
|
|
"cwd": _completion_cwd(params),
|
|
"inflight_turn": None,
|
|
"last_active": now,
|
|
"pending_title": title or None,
|
|
"running": False,
|
|
"session_key": key,
|
|
"show_reasoning": _load_show_reasoning(),
|
|
"slash_worker": None,
|
|
"tool_progress_mode": _load_tool_progress_mode(),
|
|
"tool_started_at": {},
|
|
"transport": current_transport() or _stdio_transport,
|
|
}
|
|
_register_session_cwd(_sessions[sid])
|
|
db = _get_db()
|
|
if db is not None:
|
|
try:
|
|
db.create_session(
|
|
key,
|
|
source="tui",
|
|
model=_resolve_model(),
|
|
cwd=_sessions[sid]["cwd"],
|
|
)
|
|
except Exception:
|
|
logger.debug("failed to pre-create desktop session row", exc_info=True)
|
|
|
|
# Return the lightweight session immediately so Ink can paint the composer
|
|
# + skeleton panel, then build the real AIAgent just after this response is
|
|
# flushed. This keeps startup responsive while still hydrating tools/skills
|
|
# without requiring the user to submit a first prompt.
|
|
def _deferred_build() -> None:
|
|
session = _sessions.get(sid)
|
|
if session is not None:
|
|
_start_agent_build(sid, session)
|
|
|
|
build_timer = threading.Timer(0.05, _deferred_build)
|
|
build_timer.daemon = True
|
|
build_timer.start()
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"session_id": sid,
|
|
"stored_session_id": key,
|
|
"message_count": len(history),
|
|
"messages": _history_to_messages(history),
|
|
"info": {
|
|
"model": _resolve_model(),
|
|
"tools": {},
|
|
"skills": {},
|
|
"cwd": _sessions[sid]["cwd"],
|
|
"branch": _git_branch_for_cwd(_sessions[sid]["cwd"]),
|
|
"lazy": True,
|
|
"profile_name": _current_profile_name(),
|
|
},
|
|
},
|
|
)
|
|
|
|
|
|
@method("session.list")
|
|
def _(rid, params: dict) -> dict:
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5006)
|
|
try:
|
|
# Resume picker should surface human conversation sessions from every
|
|
# user-facing surface — CLI, TUI, all gateway platforms (including new
|
|
# ones not enumerated here), ACP adapter clients, webhook sessions,
|
|
# custom `HERMES_SESSION_SOURCE` values, and older installs with
|
|
# different source labels. We deny-list only the noisy internal
|
|
# sources (``tool`` sub-agent runs) rather than allow-listing a
|
|
# fixed set of platform names that goes stale whenever a new
|
|
# platform is added or a user names their own source.
|
|
deny = frozenset({"tool"})
|
|
|
|
limit = int(params.get("limit", 200) or 200)
|
|
# Over-fetch modestly so per-source filtering doesn't leave us
|
|
# short; the compression-tip projection in ``list_sessions_rich``
|
|
# can also merge rows.
|
|
fetch_limit = max(limit * 2, 200)
|
|
rows = [
|
|
s
|
|
for s in db.list_sessions_rich(source=None, limit=fetch_limit)
|
|
if (s.get("source") or "").strip().lower() not in deny
|
|
][:limit]
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"sessions": [
|
|
{
|
|
"id": s["id"],
|
|
"title": s.get("title") or "",
|
|
"preview": s.get("preview") or "",
|
|
"started_at": s.get("started_at") or 0,
|
|
"message_count": s.get("message_count") or 0,
|
|
"source": s.get("source") or "",
|
|
}
|
|
for s in rows
|
|
]
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5006, str(e))
|
|
|
|
|
|
@method("session.most_recent")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Return the most recent human-facing session id, or ``None``.
|
|
|
|
Mirrors ``session.list``'s deny-list behaviour (drops ``tool``
|
|
sub-agent rows). Used by TUI auto-resume when
|
|
``display.tui_auto_resume_recent`` is on; the field is also handy
|
|
for any CLI tooling that wants "latest session" without paginating
|
|
the full list.
|
|
|
|
Contract: a ``{"session_id": null}`` result means "no eligible
|
|
session found right now". Errors are also folded into that
|
|
null-result shape (and logged) so callers don't have to special-
|
|
case JSON-RPC error envelopes for what is a normal "no answer".
|
|
"""
|
|
db = _get_db()
|
|
if db is None:
|
|
return _ok(rid, {"session_id": None})
|
|
try:
|
|
deny = frozenset({"tool"})
|
|
# Over-fetch by a generous bounded amount so heavy sub-agent
|
|
# users (lots of recent ``tool`` rows) don't get a false
|
|
# "no eligible session" answer. ``session.list`` uses a
|
|
# similar over-fetch strategy.
|
|
rows = db.list_sessions_rich(source=None, limit=200)
|
|
for row in rows:
|
|
src = (row.get("source") or "").strip().lower()
|
|
if src in deny:
|
|
continue
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"session_id": row.get("id"),
|
|
"title": row.get("title") or "",
|
|
"started_at": row.get("started_at") or 0,
|
|
"source": row.get("source") or "",
|
|
},
|
|
)
|
|
return _ok(rid, {"session_id": None})
|
|
except Exception:
|
|
logger.exception("session.most_recent failed")
|
|
return _ok(rid, {"session_id": None})
|
|
|
|
|
|
@method("session.resume")
|
|
def _(rid, params: dict) -> dict:
|
|
target = params.get("session_id", "")
|
|
if not target:
|
|
return _err(rid, 4006, "session_id required")
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5000)
|
|
found = db.get_session(target)
|
|
if not found:
|
|
found = db.get_session_by_title(target)
|
|
if found:
|
|
target = found["id"]
|
|
else:
|
|
return _err(rid, 4007, "session not found")
|
|
sid = uuid.uuid4().hex[:8]
|
|
_enable_gateway_prompts()
|
|
try:
|
|
db.reopen_session(target)
|
|
history = db.get_messages_as_conversation(target)
|
|
display_history = db.get_messages_as_conversation(
|
|
target, include_ancestors=True
|
|
)
|
|
messages = _history_to_messages(display_history)
|
|
tokens = _set_session_context(target)
|
|
try:
|
|
agent = _make_agent(sid, target, session_id=target)
|
|
finally:
|
|
_clear_session_context(tokens)
|
|
_init_session(sid, target, agent, history, cols=int(params.get("cols", 80)))
|
|
except Exception as e:
|
|
return _err(rid, 5000, f"resume failed: {e}")
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"session_id": sid,
|
|
"resumed": target,
|
|
"message_count": len(messages),
|
|
"messages": messages,
|
|
"info": _session_info(agent, _sessions.get(sid)),
|
|
},
|
|
)
|
|
|
|
|
|
@method("session.cwd.set")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
if session.get("running"):
|
|
return _err(rid, 4009, "session busy")
|
|
raw = str(params.get("cwd", "") or "").strip()
|
|
if not raw:
|
|
return _err(rid, 4016, "cwd required")
|
|
try:
|
|
cwd = _set_session_cwd(session, raw)
|
|
except ValueError as e:
|
|
return _err(rid, 4017, str(e))
|
|
agent = session.get("agent")
|
|
info = _session_info(agent, session) if agent is not None else {
|
|
"cwd": cwd,
|
|
"branch": _git_branch_for_cwd(cwd),
|
|
"lazy": True,
|
|
}
|
|
_emit("session.info", params.get("session_id", ""), info)
|
|
return _ok(rid, info)
|
|
|
|
|
|
def _session_pending_kind(sid: str) -> str:
|
|
for rid, (owner_sid, _ev) in list(_pending.items()):
|
|
if owner_sid != sid:
|
|
continue
|
|
event, _payload = _pending_prompt_payloads.get(rid, ("input.request", {}))
|
|
return str(event).removesuffix(".request")
|
|
return ""
|
|
|
|
|
|
def _session_live_status(sid: str, session: dict) -> str:
|
|
if _session_pending_kind(sid):
|
|
return "waiting"
|
|
ready = session.get("agent_ready")
|
|
if ready is not None and not ready.is_set():
|
|
return "starting"
|
|
if session.get("running"):
|
|
return "working"
|
|
return "idle"
|
|
|
|
|
|
def _message_preview(history: list) -> str:
|
|
for msg in reversed(history or []):
|
|
text = _content_display_text(msg.get("content", msg.get("text", ""))).strip()
|
|
if text:
|
|
return " ".join(text.split())[:160]
|
|
return ""
|
|
|
|
|
|
def _session_live_title(session: dict, key: str) -> str:
|
|
title = str(session.get("pending_title") or "").strip()
|
|
db = _get_db()
|
|
if db is not None:
|
|
try:
|
|
title = str(db.get_session_title(key) or title or "").strip()
|
|
except Exception:
|
|
pass
|
|
return title
|
|
|
|
|
|
def _session_live_item(sid: str, session: dict, current_sid: str = "") -> dict:
|
|
key = str(session.get("session_key") or sid)
|
|
agent = session.get("agent")
|
|
history = list(session.get("history") or [])
|
|
status = _session_live_status(sid, session)
|
|
inflight = _inflight_snapshot(session)
|
|
preview = _message_preview(history)
|
|
if inflight:
|
|
preview = inflight.get("assistant") or inflight.get("user") or preview
|
|
preview = " ".join(str(preview).split())[:160]
|
|
now = time.time()
|
|
return {
|
|
"current": sid == current_sid,
|
|
"id": sid,
|
|
"last_active": float(session.get("last_active") or session.get("created_at") or now),
|
|
"message_count": len(history),
|
|
"model": str(getattr(agent, "model", "") or _resolve_model()),
|
|
"preview": preview,
|
|
"session_key": key,
|
|
"started_at": float(session.get("created_at") or now),
|
|
"status": status,
|
|
"title": _session_live_title(session, key),
|
|
}
|
|
|
|
|
|
def _fallback_session_info(session: dict) -> dict:
|
|
agent = session.get("agent")
|
|
if agent is not None:
|
|
return _session_info(agent)
|
|
return {
|
|
"cwd": os.getenv("TERMINAL_CWD", os.getcwd()),
|
|
"lazy": True,
|
|
"model": _resolve_model(),
|
|
"skills": {},
|
|
"tools": {},
|
|
}
|
|
|
|
|
|
@method("session.active_list")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Return live TUI sessions in this gateway process.
|
|
|
|
Unlike ``session.list`` this is not a historical DB browser: it reports only
|
|
sessions with in-memory agents/workers that the current TUI can switch to
|
|
without closing siblings.
|
|
"""
|
|
current = str(params.get("current_session_id") or "")
|
|
try:
|
|
snapshot = list(_sessions.items())
|
|
except Exception as e:
|
|
return _err(rid, 5036, f"could not enumerate active sessions: {e}")
|
|
|
|
# Keep the natural creation/insertion order from ``_sessions``. The
|
|
# frontend marks the focused session with ``current``; it should not jump to
|
|
# the top just because the user switched to it.
|
|
rows = [_session_live_item(sid, session, current) for sid, session in snapshot]
|
|
return _ok(rid, {"sessions": rows})
|
|
|
|
|
|
@method("session.activate")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Attach the frontend to an already-live TUI session.
|
|
|
|
This intentionally does not close the previously focused session; it merely
|
|
returns enough state for Ink to redraw around another live session id.
|
|
"""
|
|
sid = str(params.get("session_id") or "")
|
|
session, err = _sess_nowait({"session_id": sid}, rid)
|
|
if err:
|
|
return err
|
|
|
|
with session["history_lock"]:
|
|
session["last_active"] = time.time()
|
|
history = list(session.get("display_history") or session.get("history") or [])
|
|
inflight = _inflight_snapshot(session)
|
|
running = bool(session.get("running"))
|
|
status = _session_live_status(sid, session)
|
|
payload = {
|
|
"info": _fallback_session_info(session),
|
|
"message_count": len(history),
|
|
"messages": _history_to_messages(history),
|
|
"running": running,
|
|
"session_id": sid,
|
|
"session_key": session.get("session_key") or sid,
|
|
"started_at": float(session.get("created_at") or time.time()),
|
|
"status": status,
|
|
}
|
|
if inflight:
|
|
payload["inflight"] = inflight
|
|
return _ok(
|
|
rid,
|
|
payload,
|
|
)
|
|
|
|
|
|
@method("session.delete")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Delete a stored session and its on-disk transcript files.
|
|
|
|
Used by the TUI resume picker (``d`` key) so users can prune old
|
|
sessions without dropping to the CLI. Refuses to delete a session
|
|
that is currently active in this gateway process — those rows are
|
|
still being written to and removing them out from under the live
|
|
agent corrupts message ordering and trips FK constraints when the
|
|
next message append flushes.
|
|
"""
|
|
target = params.get("session_id", "")
|
|
if not target:
|
|
return _err(rid, 4006, "session_id required")
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5036)
|
|
# Block deletion of any session currently bound to a live TUI session
|
|
# in this process. The picker hides the active session anyway, but a
|
|
# racing caller could still target it. Snapshot via ``list(...)``
|
|
# because ``_sessions`` is mutated by concurrent RPCs on the thread
|
|
# pool — iterating the dict directly can raise ``RuntimeError:
|
|
# dictionary changed size during iteration``. If even the snapshot
|
|
# raises, fail closed (refuse the delete) rather than fail open.
|
|
try:
|
|
snapshot = list(_sessions.values())
|
|
except Exception as e:
|
|
return _err(rid, 5036, f"could not enumerate active sessions: {e}")
|
|
active = {s.get("session_key") for s in snapshot if s.get("session_key")}
|
|
if target in active:
|
|
return _err(rid, 4023, "cannot delete an active session")
|
|
sessions_dir = get_hermes_home() / "sessions"
|
|
try:
|
|
deleted = db.delete_session(target, sessions_dir=sessions_dir)
|
|
except Exception as e:
|
|
return _err(rid, 5036, f"delete failed: {e}")
|
|
if not deleted:
|
|
return _err(rid, 4007, "session not found")
|
|
return _ok(rid, {"deleted": target})
|
|
|
|
|
|
@method("session.title")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5007)
|
|
key = session["session_key"]
|
|
if "title" not in params:
|
|
fallback = session.get("pending_title") or ""
|
|
try:
|
|
resolved_title = db.get_session_title(key) or ""
|
|
if fallback:
|
|
if db.set_session_title(key, fallback):
|
|
session["pending_title"] = None
|
|
resolved_title = fallback
|
|
else:
|
|
existing_row = db.get_session(key)
|
|
existing_title = ((existing_row or {}).get("title") or "").strip()
|
|
if existing_title == fallback:
|
|
session["pending_title"] = None
|
|
resolved_title = fallback
|
|
elif not resolved_title:
|
|
resolved_title = fallback
|
|
elif resolved_title:
|
|
session["pending_title"] = None
|
|
except Exception:
|
|
resolved_title = fallback
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"title": resolved_title,
|
|
"session_key": key,
|
|
},
|
|
)
|
|
title = (params.get("title", "") or "").strip()
|
|
if not title:
|
|
return _err(rid, 4021, "title required")
|
|
try:
|
|
if db.set_session_title(key, title):
|
|
session["pending_title"] = None
|
|
return _ok(rid, {"pending": False, "title": title})
|
|
# rowcount == 0 can mean "same value" as well as "missing row".
|
|
# Queue only when the session row truly does not exist yet.
|
|
existing_row = db.get_session(key)
|
|
if existing_row:
|
|
session["pending_title"] = None
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"pending": False,
|
|
"title": (existing_row.get("title") or title),
|
|
},
|
|
)
|
|
session["pending_title"] = title
|
|
return _ok(rid, {"pending": True, "title": title})
|
|
except ValueError as e:
|
|
return _err(rid, 4022, str(e))
|
|
except Exception as e:
|
|
return _err(rid, 5007, str(e))
|
|
|
|
|
|
@method("session.usage")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
agent = session.get("agent")
|
|
return _ok(
|
|
rid,
|
|
(
|
|
_get_usage(agent)
|
|
if agent is not None
|
|
else {"calls": 0, "input": 0, "output": 0, "total": 0}
|
|
),
|
|
)
|
|
|
|
|
|
@method("session.status")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
|
|
from hermes_constants import display_hermes_home
|
|
|
|
key = session.get("session_key") or params.get("session_id") or ""
|
|
agent = session.get("agent")
|
|
meta = {}
|
|
db = _get_db()
|
|
if db and key:
|
|
try:
|
|
meta = db.get_session(key) or {}
|
|
except Exception:
|
|
meta = {}
|
|
|
|
def _dt(value, fallback: datetime | None = None) -> datetime:
|
|
if value:
|
|
try:
|
|
return datetime.fromtimestamp(float(value))
|
|
except Exception:
|
|
pass
|
|
return fallback or datetime.now()
|
|
|
|
created = _dt(meta.get("started_at"))
|
|
updated = created
|
|
for field in ("updated_at", "last_updated_at", "last_activity_at"):
|
|
if meta.get(field):
|
|
updated = _dt(meta.get(field), created)
|
|
break
|
|
|
|
usage = _get_usage(agent) if agent is not None else {}
|
|
provider = getattr(agent, "provider", None) or "unknown"
|
|
model = getattr(agent, "model", None) or "(unknown)"
|
|
lines = [
|
|
"Hermes TUI Status",
|
|
"",
|
|
f"Session ID: {key}",
|
|
f"Path: {display_hermes_home()}",
|
|
]
|
|
title = (meta.get("title") or "").strip()
|
|
if title:
|
|
lines.append(f"Title: {title}")
|
|
lines.extend(
|
|
[
|
|
f"Model: {model} ({provider})",
|
|
f"Created: {created.strftime('%Y-%m-%d %H:%M')}",
|
|
f"Last Activity: {updated.strftime('%Y-%m-%d %H:%M')}",
|
|
f"Tokens: {int(usage.get('total') or 0):,}",
|
|
f"Agent Running: {'Yes' if session.get('running') else 'No'}",
|
|
]
|
|
)
|
|
return _ok(rid, {"output": "\n".join(lines)})
|
|
|
|
|
|
@method("session.history")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
history = list(session.get("history", []))
|
|
db = _get_db()
|
|
if db is not None and session.get("session_key"):
|
|
try:
|
|
history = db.get_messages_as_conversation(
|
|
session["session_key"], include_ancestors=True
|
|
)
|
|
except Exception:
|
|
pass
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"count": len(history),
|
|
"messages": _history_to_messages(history),
|
|
},
|
|
)
|
|
|
|
|
|
@method("session.undo")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
# Reject during an in-flight turn. If we mutated history while
|
|
# the agent thread is running, prompt.submit's post-run history
|
|
# write would either clobber the undo (version matches) or
|
|
# silently drop the agent's output (version mismatch, see below).
|
|
# Neither is what the user wants — make them /interrupt first.
|
|
if session.get("running"):
|
|
return _err(
|
|
rid, 4009, "session busy — /interrupt the current turn before /undo"
|
|
)
|
|
removed = 0
|
|
with session["history_lock"]:
|
|
history = session.get("history", [])
|
|
while history and history[-1].get("role") in {"assistant", "tool"}:
|
|
history.pop()
|
|
removed += 1
|
|
if history and history[-1].get("role") == "user":
|
|
history.pop()
|
|
removed += 1
|
|
if removed:
|
|
session["history_version"] = int(session.get("history_version", 0)) + 1
|
|
return _ok(rid, {"removed": removed})
|
|
|
|
|
|
@method("session.compress")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
if session.get("running"):
|
|
return _err(
|
|
rid, 4009, "session busy — /interrupt the current turn before /compress"
|
|
)
|
|
sid = params.get("session_id", "")
|
|
focus_topic = str(params.get("focus_topic", "") or "").strip()
|
|
try:
|
|
from agent.manual_compression_feedback import summarize_manual_compression
|
|
from agent.model_metadata import estimate_request_tokens_rough
|
|
|
|
with session["history_lock"]:
|
|
before_messages = list(session.get("history", []))
|
|
history_version = int(session.get("history_version", 0))
|
|
before_count = len(before_messages)
|
|
_agent = session["agent"]
|
|
_sys_prompt = getattr(_agent, "_cached_system_prompt", "") or ""
|
|
_tools = getattr(_agent, "tools", None) or None
|
|
before_tokens = (
|
|
estimate_request_tokens_rough(
|
|
before_messages, system_prompt=_sys_prompt, tools=_tools
|
|
)
|
|
if before_count
|
|
else 0
|
|
)
|
|
|
|
if before_count >= 4:
|
|
focus_suffix = f', focus: "{focus_topic}"' if focus_topic else ""
|
|
_status_update(
|
|
sid,
|
|
"compressing",
|
|
f"⠋ compressing {before_count} messages "
|
|
f"(~{before_tokens:,} tok){focus_suffix}…",
|
|
)
|
|
|
|
try:
|
|
removed, usage = _compress_session_history(
|
|
session,
|
|
focus_topic,
|
|
approx_tokens=before_tokens,
|
|
before_messages=before_messages,
|
|
history_version=history_version,
|
|
)
|
|
with session["history_lock"]:
|
|
messages = list(session.get("history", []))
|
|
after_count = len(messages)
|
|
# Re-read system prompt + tools after compression — _compress_context
|
|
# may have rebuilt the system prompt (_cached_system_prompt=None).
|
|
_sys_prompt_after = (
|
|
getattr(_agent, "_cached_system_prompt", "") or _sys_prompt
|
|
)
|
|
_tools_after = getattr(_agent, "tools", None) or _tools
|
|
after_tokens = (
|
|
estimate_request_tokens_rough(
|
|
messages,
|
|
system_prompt=_sys_prompt_after,
|
|
tools=_tools_after,
|
|
)
|
|
if after_count
|
|
else 0
|
|
)
|
|
agent = session["agent"]
|
|
_sync_session_key_after_compress(sid, session)
|
|
summary = summarize_manual_compression(
|
|
before_messages, messages, before_tokens, after_tokens
|
|
)
|
|
info = _session_info(agent, session)
|
|
_emit("session.info", sid, info)
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"status": "compressed",
|
|
"removed": removed,
|
|
"before_messages": before_count,
|
|
"after_messages": after_count,
|
|
"before_tokens": before_tokens,
|
|
"after_tokens": after_tokens,
|
|
"summary": summary,
|
|
"usage": usage,
|
|
"info": info,
|
|
"messages": messages,
|
|
},
|
|
)
|
|
finally:
|
|
# Always clear the pinned compressing status so the bar
|
|
# reverts to neutral whether compaction succeeded, was a
|
|
# no-op, or raised.
|
|
_status_update(sid, "ready")
|
|
except Exception as e:
|
|
return _err(rid, 5005, str(e))
|
|
|
|
|
|
@method("session.save")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
import time as _time
|
|
|
|
filename = os.path.abspath(
|
|
f"hermes_conversation_{_time.strftime('%Y%m%d_%H%M%S')}.json"
|
|
)
|
|
try:
|
|
with open(filename, "w", encoding="utf-8") as f:
|
|
json.dump(
|
|
{
|
|
"model": getattr(session["agent"], "model", ""),
|
|
"messages": session.get("history", []),
|
|
},
|
|
f,
|
|
indent=2,
|
|
ensure_ascii=False,
|
|
)
|
|
return _ok(rid, {"file": filename})
|
|
except Exception as e:
|
|
return _err(rid, 5011, str(e))
|
|
|
|
|
|
@method("session.close")
|
|
def _(rid, params: dict) -> dict:
|
|
sid = params.get("session_id", "")
|
|
session = _sessions.pop(sid, None)
|
|
if not session:
|
|
return _ok(rid, {"closed": False})
|
|
_finalize_session(session)
|
|
try:
|
|
from tools.approval import unregister_gateway_notify
|
|
|
|
unregister_gateway_notify(session["session_key"])
|
|
except Exception:
|
|
pass
|
|
try:
|
|
agent = session.get("agent")
|
|
if agent and hasattr(agent, "close"):
|
|
agent.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
worker = session.get("slash_worker")
|
|
if worker:
|
|
worker.close()
|
|
except Exception:
|
|
pass
|
|
return _ok(rid, {"closed": True})
|
|
|
|
|
|
@method("session.branch")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5008)
|
|
old_key = session["session_key"]
|
|
with session["history_lock"]:
|
|
history = [dict(msg) for msg in session.get("history", [])]
|
|
if not history:
|
|
return _err(rid, 4008, "nothing to branch — send a message first")
|
|
new_key = _new_session_key()
|
|
branch_name = params.get("name", "")
|
|
try:
|
|
if branch_name:
|
|
title = branch_name
|
|
else:
|
|
current = db.get_session_title(old_key) or "branch"
|
|
title = (
|
|
db.get_next_title_in_lineage(current)
|
|
if hasattr(db, "get_next_title_in_lineage")
|
|
else f"{current} (branch)"
|
|
)
|
|
db.create_session(
|
|
new_key,
|
|
source="tui",
|
|
model=_resolve_model(),
|
|
parent_session_id=old_key,
|
|
cwd=_session_cwd(session),
|
|
)
|
|
for msg in history:
|
|
db.append_message(
|
|
session_id=new_key,
|
|
role=msg.get("role", "user"),
|
|
content=msg.get("content"),
|
|
)
|
|
db.set_session_title(new_key, title)
|
|
except Exception as e:
|
|
return _err(rid, 5008, f"branch failed: {e}")
|
|
new_sid = uuid.uuid4().hex[:8]
|
|
try:
|
|
tokens = _set_session_context(new_key)
|
|
try:
|
|
agent = _make_agent(new_sid, new_key, session_id=new_key)
|
|
finally:
|
|
_clear_session_context(tokens)
|
|
_init_session(
|
|
new_sid, new_key, agent, list(history), cols=session.get("cols", 80)
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5000, f"agent init failed on branch: {e}")
|
|
return _ok(rid, {"session_id": new_sid, "title": title, "parent": old_key})
|
|
|
|
|
|
@method("session.interrupt")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
if hasattr(session["agent"], "interrupt"):
|
|
session["agent"].interrupt()
|
|
# Scope the pending-prompt release to THIS session. A global
|
|
# _clear_pending() would collaterally cancel clarify/sudo/secret
|
|
# prompts on unrelated sessions sharing the same tui_gateway
|
|
# process, silently resolving them to empty strings.
|
|
_clear_pending(params.get("session_id", ""))
|
|
try:
|
|
from tools.approval import resolve_gateway_approval
|
|
|
|
resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)
|
|
except Exception:
|
|
pass
|
|
return _ok(rid, {"status": "interrupted"})
|
|
|
|
|
|
# ── Delegation: subagent tree observability + controls ───────────────
|
|
# Powers the TUI's /agents overlay (see ui-tui/src/components/agentsOverlay).
|
|
# The registry lives in tools/delegate_tool — these handlers are thin
|
|
# translators between JSON-RPC and the Python API.
|
|
|
|
|
|
@method("delegation.status")
|
|
def _(rid, params: dict) -> dict:
|
|
from tools.delegate_tool import (
|
|
is_spawn_paused,
|
|
list_active_subagents,
|
|
_get_max_concurrent_children,
|
|
_get_max_spawn_depth,
|
|
)
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"active": list_active_subagents(),
|
|
"paused": is_spawn_paused(),
|
|
"max_spawn_depth": _get_max_spawn_depth(),
|
|
"max_concurrent_children": _get_max_concurrent_children(),
|
|
},
|
|
)
|
|
|
|
|
|
@method("delegation.pause")
|
|
def _(rid, params: dict) -> dict:
|
|
from tools.delegate_tool import set_spawn_paused
|
|
|
|
paused = bool(params.get("paused", True))
|
|
return _ok(rid, {"paused": set_spawn_paused(paused)})
|
|
|
|
|
|
@method("subagent.interrupt")
|
|
def _(rid, params: dict) -> dict:
|
|
from tools.delegate_tool import interrupt_subagent
|
|
|
|
subagent_id = str(params.get("subagent_id") or "").strip()
|
|
if not subagent_id:
|
|
return _err(rid, 4000, "subagent_id required")
|
|
ok = interrupt_subagent(subagent_id)
|
|
return _ok(rid, {"found": ok, "subagent_id": subagent_id})
|
|
|
|
|
|
# ── Spawn-tree snapshots: TUI-written, disk-persisted ────────────────
|
|
# The TUI is the source of truth for subagent state (it assembles payloads
|
|
# from the event stream). On turn-complete it posts the final tree here;
|
|
# /replay and /replay-diff fetch past snapshots by session_id + filename.
|
|
#
|
|
# Layout: $HERMES_HOME/spawn-trees/<session_id>/<timestamp>.json
|
|
# Each file contains { session_id, started_at, finished_at, subagents: [...] }.
|
|
|
|
|
|
def _spawn_trees_root():
|
|
from hermes_constants import get_hermes_home
|
|
|
|
root = get_hermes_home() / "spawn-trees"
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
return root
|
|
|
|
|
|
def _spawn_tree_session_dir(session_id: str):
|
|
safe = (
|
|
"".join(c if c.isalnum() or c in "-_" else "_" for c in session_id) or "unknown"
|
|
)
|
|
d = _spawn_trees_root() / safe
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return d
|
|
|
|
|
|
# Per-session append-only index of lightweight snapshot metadata. Read by
|
|
# `spawn_tree.list` so scanning doesn't require reading every full snapshot
|
|
# file (Copilot review on #14045). One JSON object per line.
|
|
_SPAWN_TREE_INDEX = "_index.jsonl"
|
|
|
|
|
|
def _append_spawn_tree_index(session_dir, entry: dict) -> None:
|
|
try:
|
|
with (session_dir / _SPAWN_TREE_INDEX).open("a", encoding="utf-8") as f:
|
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
except OSError as exc:
|
|
# Index is a cache — losing a line just means list() falls back
|
|
# to a directory scan for that entry. Never block the save.
|
|
logger.debug("spawn_tree index append failed: %s", exc)
|
|
|
|
|
|
def _read_spawn_tree_index(session_dir) -> list[dict]:
|
|
index_path = session_dir / _SPAWN_TREE_INDEX
|
|
if not index_path.exists():
|
|
return []
|
|
out: list[dict] = []
|
|
try:
|
|
with index_path.open("r", encoding="utf-8") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
out.append(json.loads(line))
|
|
except json.JSONDecodeError:
|
|
continue
|
|
except OSError:
|
|
return []
|
|
return out
|
|
|
|
|
|
@method("spawn_tree.save")
|
|
def _(rid, params: dict) -> dict:
|
|
session_id = str(params.get("session_id") or "").strip()
|
|
subagents = params.get("subagents") or []
|
|
if not isinstance(subagents, list) or not subagents:
|
|
return _err(rid, 4000, "subagents list required")
|
|
|
|
from datetime import datetime
|
|
|
|
started_at = params.get("started_at")
|
|
finished_at = params.get("finished_at") or time.time()
|
|
label = str(params.get("label") or "")
|
|
ts = datetime.utcfromtimestamp(float(finished_at)).strftime("%Y%m%dT%H%M%S")
|
|
fname = f"{ts}.json"
|
|
d = _spawn_tree_session_dir(session_id or "default")
|
|
path = d / fname
|
|
try:
|
|
payload = {
|
|
"session_id": session_id,
|
|
"started_at": float(started_at) if started_at else None,
|
|
"finished_at": float(finished_at),
|
|
"label": label,
|
|
"subagents": subagents,
|
|
}
|
|
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
|
except OSError as exc:
|
|
return _err(rid, 5000, f"spawn_tree.save failed: {exc}")
|
|
|
|
_append_spawn_tree_index(
|
|
d,
|
|
{
|
|
"path": str(path),
|
|
"session_id": session_id,
|
|
"started_at": payload["started_at"],
|
|
"finished_at": payload["finished_at"],
|
|
"label": label,
|
|
"count": len(subagents),
|
|
},
|
|
)
|
|
|
|
return _ok(rid, {"path": str(path), "session_id": session_id})
|
|
|
|
|
|
@method("spawn_tree.list")
|
|
def _(rid, params: dict) -> dict:
|
|
session_id = str(params.get("session_id") or "").strip()
|
|
limit = int(params.get("limit") or 50)
|
|
cross_session = bool(params.get("cross_session"))
|
|
|
|
if cross_session:
|
|
root = _spawn_trees_root()
|
|
roots = [p for p in root.iterdir() if p.is_dir()]
|
|
else:
|
|
roots = [_spawn_tree_session_dir(session_id or "default")]
|
|
|
|
entries: list[dict] = []
|
|
for d in roots:
|
|
indexed = _read_spawn_tree_index(d)
|
|
if indexed:
|
|
# Skip index entries whose snapshot file was manually deleted.
|
|
entries.extend(
|
|
e for e in indexed if (p := e.get("path")) and Path(p).exists()
|
|
)
|
|
continue
|
|
|
|
# Fallback for legacy (pre-index) sessions: full scan. O(N) reads
|
|
# but only runs once per session until the next save writes the index.
|
|
for p in d.glob("*.json"):
|
|
if p.name == _SPAWN_TREE_INDEX:
|
|
continue
|
|
try:
|
|
stat = p.stat()
|
|
try:
|
|
raw = json.loads(p.read_text(encoding="utf-8"))
|
|
except Exception:
|
|
raw = {}
|
|
subagents = raw.get("subagents") or []
|
|
entries.append(
|
|
{
|
|
"path": str(p),
|
|
"session_id": raw.get("session_id") or d.name,
|
|
"finished_at": raw.get("finished_at") or stat.st_mtime,
|
|
"started_at": raw.get("started_at"),
|
|
"label": raw.get("label") or "",
|
|
"count": len(subagents) if isinstance(subagents, list) else 0,
|
|
}
|
|
)
|
|
except OSError:
|
|
continue
|
|
|
|
entries.sort(key=lambda e: e.get("finished_at") or 0, reverse=True)
|
|
return _ok(rid, {"entries": entries[:limit]})
|
|
|
|
|
|
@method("spawn_tree.load")
|
|
def _(rid, params: dict) -> dict:
|
|
from pathlib import Path
|
|
|
|
raw_path = str(params.get("path") or "").strip()
|
|
if not raw_path:
|
|
return _err(rid, 4000, "path required")
|
|
|
|
# Reject paths escaping the spawn-trees root.
|
|
root = _spawn_trees_root().resolve()
|
|
try:
|
|
resolved = Path(raw_path).resolve()
|
|
resolved.relative_to(root)
|
|
except (ValueError, OSError) as exc:
|
|
return _err(rid, 4030, f"path outside spawn-trees root: {exc}")
|
|
|
|
try:
|
|
payload = json.loads(resolved.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError) as exc:
|
|
return _err(rid, 5000, f"spawn_tree.load failed: {exc}")
|
|
|
|
return _ok(rid, payload)
|
|
|
|
|
|
@method("session.steer")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Inject a user message into the next tool result without interrupting.
|
|
|
|
Mirrors AIAgent.steer(). Safe to call while a turn is running — the text
|
|
lands on the last tool result of the next tool batch and the model sees
|
|
it on its next iteration. No interrupt, no new user turn, no role
|
|
alternation violation.
|
|
"""
|
|
text = (params.get("text") or "").strip()
|
|
if not text:
|
|
return _err(rid, 4002, "text is required")
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
agent = session.get("agent")
|
|
if agent is None or not hasattr(agent, "steer"):
|
|
return _err(rid, 4010, "agent does not support steer")
|
|
try:
|
|
accepted = agent.steer(text)
|
|
except Exception as exc:
|
|
return _err(rid, 5000, f"steer failed: {exc}")
|
|
return _ok(rid, {"status": "queued" if accepted else "rejected", "text": text})
|
|
|
|
|
|
@method("terminal.resize")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
session["cols"] = int(params.get("cols", 80))
|
|
return _ok(rid, {"cols": session["cols"]})
|
|
|
|
|
|
# ── Methods: prompt ──────────────────────────────────────────────────
|
|
|
|
|
|
@method("prompt.submit")
|
|
def _(rid, params: dict) -> dict:
|
|
sid, text = params.get("session_id", ""), params.get("text", "")
|
|
truncate_user_ordinal = params.get("truncate_before_user_ordinal")
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
# Re-bind to the current client transport for this request. This keeps
|
|
# streaming events on the active websocket even if an earlier disconnect
|
|
# or fallback moved the session transport to stdio.
|
|
if (t := current_transport()) is not None:
|
|
session["transport"] = t
|
|
with session["history_lock"]:
|
|
if session.get("running"):
|
|
return _err(rid, 4009, "session busy")
|
|
if truncate_user_ordinal is not None:
|
|
try:
|
|
ordinal = int(truncate_user_ordinal)
|
|
except (TypeError, ValueError):
|
|
return _err(rid, 4004, "truncate_before_user_ordinal must be an integer")
|
|
history = session.get("history", [])
|
|
user_indices = [i for i, m in enumerate(history) if m.get("role") == "user"]
|
|
if ordinal >= len(user_indices):
|
|
return _err(rid, 4018, "target user message is no longer in session history")
|
|
truncated = history[: user_indices[ordinal]]
|
|
session["history"] = truncated
|
|
session["history_version"] = int(session.get("history_version", 0)) + 1
|
|
if (db := _get_db()) is not None:
|
|
try:
|
|
db.replace_messages(session["session_key"], truncated)
|
|
except Exception as exc:
|
|
print(f"[tui_gateway] prompt.submit: replace_messages failed: {exc}", file=sys.stderr)
|
|
session["running"] = True
|
|
session["last_active"] = time.time()
|
|
_start_inflight_turn(session, text)
|
|
|
|
_start_agent_build(sid, session)
|
|
|
|
def run_after_agent_ready() -> None:
|
|
err = _wait_agent(session, rid)
|
|
if err:
|
|
_emit(
|
|
"error",
|
|
sid,
|
|
{
|
|
"message": err.get("error", {}).get(
|
|
"message", "agent initialization failed"
|
|
)
|
|
},
|
|
)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
_clear_inflight_turn(session)
|
|
return
|
|
_run_prompt_submit(rid, sid, session, text)
|
|
|
|
threading.Thread(target=run_after_agent_ready, daemon=True).start()
|
|
return _ok(rid, {"status": "streaming"})
|
|
|
|
|
|
def _notification_poller_loop(
|
|
stop_event: threading.Event, sid: str, session: dict
|
|
) -> None:
|
|
"""Poll completion_queue and dispatch notifications autonomously.
|
|
|
|
Runs in a daemon thread started by _init_session(). Emits a
|
|
status.update (kind=process) for user visibility, then chains an
|
|
agent turn via _run_prompt_submit if the session is idle.
|
|
|
|
NOTE: The completion_queue is global (one per process). If multiple
|
|
TUI sessions coexist, whichever poller wakes first grabs the event,
|
|
even if the process was started by a different session. This matches
|
|
CLI/gateway behavior (single session per process).
|
|
"""
|
|
from tools.process_registry import process_registry, format_process_notification
|
|
|
|
while not stop_event.is_set() and not session.get("_finalized"):
|
|
try:
|
|
evt = process_registry.completion_queue.get(timeout=0.5)
|
|
except Exception:
|
|
continue
|
|
|
|
_evt_sid = evt.get("session_id", "")
|
|
if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
|
|
continue
|
|
|
|
text = format_process_notification(evt)
|
|
if not text:
|
|
continue
|
|
|
|
_emit("status.update", sid, {"kind": "process", "text": text})
|
|
|
|
with session["history_lock"]:
|
|
if session.get("running"):
|
|
process_registry.completion_queue.put(evt)
|
|
continue
|
|
session["running"] = True
|
|
|
|
rid = f"__notif__{int(time.time() * 1000)}"
|
|
try:
|
|
_emit("message.start", sid)
|
|
_run_prompt_submit(rid, sid, session, text)
|
|
except Exception as exc:
|
|
print(
|
|
f"[tui_gateway] notification poller dispatch failed: "
|
|
f"{type(exc).__name__}: {exc}",
|
|
file=sys.stderr,
|
|
)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
|
|
# Drain any remaining events after stop signal (process all pending
|
|
# before exiting so nothing is lost on shutdown).
|
|
while not process_registry.completion_queue.empty():
|
|
try:
|
|
evt = process_registry.completion_queue.get_nowait()
|
|
except Exception:
|
|
break
|
|
_evt_sid = evt.get("session_id", "")
|
|
if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
|
|
continue
|
|
text = format_process_notification(evt)
|
|
if not text:
|
|
continue
|
|
|
|
_emit("status.update", sid, {"kind": "process", "text": text})
|
|
|
|
with session["history_lock"]:
|
|
if session.get("running"):
|
|
process_registry.completion_queue.put(evt)
|
|
break
|
|
session["running"] = True
|
|
|
|
rid = f"__notif__{int(time.time() * 1000)}"
|
|
try:
|
|
_emit("message.start", sid)
|
|
_run_prompt_submit(rid, sid, session, text)
|
|
except Exception as exc:
|
|
print(
|
|
f"[tui_gateway] notification poller dispatch failed: "
|
|
f"{type(exc).__name__}: {exc}",
|
|
file=sys.stderr,
|
|
)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
|
|
|
|
def _start_notification_poller(sid: str, session: dict) -> threading.Event:
|
|
"""Start the background notification poller for a TUI session."""
|
|
stop = threading.Event()
|
|
t = threading.Thread(
|
|
target=_notification_poller_loop,
|
|
args=(stop, sid, session),
|
|
daemon=True,
|
|
)
|
|
t.start()
|
|
return stop
|
|
|
|
|
|
def _run_prompt_submit(rid, sid: str, session: dict, text: Any) -> None:
|
|
with session["history_lock"]:
|
|
history = list(session["history"])
|
|
history_version = int(session.get("history_version", 0))
|
|
images = list(session.get("attached_images", []))
|
|
session["attached_images"] = []
|
|
if not isinstance(session.get("inflight_turn"), dict):
|
|
_start_inflight_turn(session, text)
|
|
agent = session["agent"]
|
|
_emit("message.start", sid)
|
|
|
|
def run():
|
|
approval_token = None
|
|
session_tokens = []
|
|
goal_followup = None # set by the post-turn goal hook below
|
|
try:
|
|
from tools.approval import (
|
|
reset_current_session_key,
|
|
set_current_session_key,
|
|
)
|
|
|
|
approval_token = set_current_session_key(session["session_key"])
|
|
session_tokens = _set_session_context(session["session_key"])
|
|
cwd = _session_cwd(session)
|
|
_register_session_cwd(session)
|
|
cols = session.get("cols", 80)
|
|
streamer = make_stream_renderer(cols)
|
|
prompt = text
|
|
|
|
if isinstance(prompt, str) and "@" in prompt:
|
|
from agent.context_references import preprocess_context_references
|
|
from agent.model_metadata import get_model_context_length
|
|
|
|
ctx_len = get_model_context_length(
|
|
getattr(agent, "model", "") or _resolve_model(),
|
|
base_url=getattr(agent, "base_url", "") or "",
|
|
api_key=getattr(agent, "api_key", "") or "",
|
|
provider=getattr(agent, "provider", "") or "",
|
|
config_context_length=getattr(
|
|
agent, "_config_context_length", None
|
|
),
|
|
)
|
|
ctx = preprocess_context_references(
|
|
prompt,
|
|
cwd=cwd,
|
|
allowed_root=cwd,
|
|
context_length=ctx_len,
|
|
)
|
|
if ctx.blocked:
|
|
_emit(
|
|
"error",
|
|
sid,
|
|
{
|
|
"message": "\n".join(ctx.warnings)
|
|
or "Context injection refused."
|
|
},
|
|
)
|
|
return
|
|
prompt = ctx.message
|
|
|
|
# Decide image routing per-turn based on active provider/model.
|
|
# "native" → pass pixels to the main model as OpenAI-style content
|
|
# parts (adapters translate for Anthropic/Gemini/Bedrock/etc.).
|
|
# "text" → pre-analyze with vision_analyze and prepend the text.
|
|
# See agent/image_routing.py for the full decision table.
|
|
run_message: Any = prompt
|
|
if images:
|
|
try:
|
|
from agent.image_routing import (
|
|
decide_image_input_mode,
|
|
build_native_content_parts,
|
|
)
|
|
from agent.auxiliary_client import (
|
|
_read_main_model,
|
|
_read_main_provider,
|
|
)
|
|
from hermes_cli.config import load_config as _tui_load_config
|
|
|
|
_cfg = _tui_load_config()
|
|
_mode = decide_image_input_mode(
|
|
_read_main_provider(),
|
|
_read_main_model(),
|
|
_cfg,
|
|
)
|
|
if getattr(agent, "api_mode", "") == "codex_app_server":
|
|
_mode = "text"
|
|
except Exception as _img_exc:
|
|
print(
|
|
f"[tui_gateway] image_routing decision failed, defaulting to text: {_img_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
_mode = "text"
|
|
|
|
if _mode == "native":
|
|
try:
|
|
_parts, _skipped = build_native_content_parts(
|
|
prompt,
|
|
images,
|
|
)
|
|
if _skipped:
|
|
print(
|
|
f"[tui_gateway] native image attachment skipped {len(_skipped)} unreadable path(s)",
|
|
file=sys.stderr,
|
|
)
|
|
if any(p.get("type") == "image_url" for p in _parts):
|
|
run_message = _parts
|
|
else:
|
|
run_message = _enrich_with_attached_images(prompt, images)
|
|
except Exception as _img_exc:
|
|
print(
|
|
f"[tui_gateway] native attach failed, falling back to text: {_img_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
run_message = _enrich_with_attached_images(prompt, images)
|
|
else:
|
|
run_message = _enrich_with_attached_images(prompt, images)
|
|
|
|
def _stream(delta):
|
|
with session["history_lock"]:
|
|
_append_inflight_delta(session, delta)
|
|
payload = {"text": delta}
|
|
if streamer and (r := streamer.feed(delta)) is not None:
|
|
payload["rendered"] = r
|
|
_emit("message.delta", sid, payload)
|
|
|
|
run_kwargs = {
|
|
"conversation_history": list(history),
|
|
"stream_callback": _stream,
|
|
}
|
|
try:
|
|
if "task_id" in inspect.signature(agent.run_conversation).parameters:
|
|
run_kwargs["task_id"] = session["session_key"]
|
|
except (TypeError, ValueError):
|
|
pass
|
|
result = agent.run_conversation(run_message, **run_kwargs)
|
|
|
|
last_reasoning = None
|
|
status_note = None
|
|
if isinstance(result, dict):
|
|
if isinstance(result.get("messages"), list):
|
|
with session["history_lock"]:
|
|
current_version = int(session.get("history_version", 0))
|
|
if current_version == history_version:
|
|
session["history"] = result["messages"]
|
|
session["history_version"] = history_version + 1
|
|
else:
|
|
# History mutated externally during the turn
|
|
# (undo/compress/retry/rollback now guard on
|
|
# session.running, but this is the defensive
|
|
# backstop for any path that slips past).
|
|
# Surface the desync rather than silently
|
|
# dropping the agent's output — the UI can
|
|
# show the response and warn that it was
|
|
# not persisted.
|
|
print(
|
|
f"[tui_gateway] prompt.submit: history_version mismatch "
|
|
f"(expected={history_version} current={current_version}) — "
|
|
f"agent output NOT written to session history",
|
|
file=sys.stderr,
|
|
)
|
|
status_note = (
|
|
"History changed during this turn — the response above is visible "
|
|
"but was not saved to session history."
|
|
)
|
|
|
|
# If auto-compression fired inside run_conversation(), agent.session_id
|
|
# may have rotated. Sync session_key before downstream title/goal/finalize
|
|
# handling uses it. Preserve pending_title (user intent) so it can be
|
|
# applied to the continuation. Restart slash worker so subsequent
|
|
# worker-backed commands (/title etc.) target the live session.
|
|
# Fix for #20001.
|
|
_sync_session_key_after_compress(
|
|
sid, session, clear_pending_title=False, restart_slash_worker=True,
|
|
)
|
|
|
|
raw = result.get("final_response", "")
|
|
status = (
|
|
"interrupted"
|
|
if result.get("interrupted")
|
|
else "error" if result.get("error") else "complete"
|
|
)
|
|
# When the backend produced no visible response AND reported a
|
|
# real error (e.g. invalid model slug → provider 4xx), surface
|
|
# that error as the visible text instead of shipping an empty
|
|
# turn to Ink. Mirrors classic CLI behavior at cli.py where
|
|
# (failed|partial) + no final_response → "Error: <detail>".
|
|
# Leaves the None-with-no-error path untouched: an empty
|
|
# successful turn still renders as empty, and the existing
|
|
# "(empty)" sentinel handling stays in its own lane.
|
|
if (not raw) and result.get("error") and (
|
|
result.get("failed") or result.get("partial")
|
|
):
|
|
raw = f"Error: {result.get('error')}"
|
|
lr = result.get("last_reasoning")
|
|
if isinstance(lr, str) and lr.strip():
|
|
last_reasoning = lr.strip()
|
|
else:
|
|
raw = str(result)
|
|
status = "complete"
|
|
|
|
payload = {"text": raw, "usage": _get_usage(agent), "status": status}
|
|
if last_reasoning:
|
|
payload["reasoning"] = last_reasoning
|
|
if status_note:
|
|
payload["warning"] = status_note
|
|
rendered = render_message(raw, cols)
|
|
if rendered:
|
|
payload["rendered"] = rendered
|
|
with session["history_lock"]:
|
|
_clear_inflight_turn(session)
|
|
_emit("message.complete", sid, payload)
|
|
|
|
# ── /goal continuation (Ralph-style loop) ─────────────────
|
|
# After every TUI turn, if a /goal is active, ask the judge
|
|
# whether the goal is done and — if not and we're still under
|
|
# budget — queue a continuation prompt to run after this
|
|
# thread releases session["running"]. The verdict message
|
|
# ("✓ Goal achieved" / "⏸ budget exhausted") is surfaced as
|
|
# a system line so the user sees progress regardless of
|
|
# outcome. Mirrors gateway/run._post_turn_goal_continuation.
|
|
if status == "complete" and isinstance(raw, str) and raw.strip():
|
|
try:
|
|
from hermes_cli.goals import GoalManager
|
|
|
|
sid_key = session.get("session_key") or ""
|
|
if sid_key:
|
|
try:
|
|
goals_cfg = _load_cfg().get("goals") or {}
|
|
goal_max_turns = int(goals_cfg.get("max_turns", 20) or 20)
|
|
except Exception:
|
|
goal_max_turns = 20
|
|
goal_mgr = GoalManager(
|
|
session_id=sid_key,
|
|
default_max_turns=goal_max_turns,
|
|
)
|
|
if goal_mgr.is_active():
|
|
decision = goal_mgr.evaluate_after_turn(
|
|
raw,
|
|
user_initiated=True,
|
|
)
|
|
verdict_msg = decision.get("message") or ""
|
|
if verdict_msg:
|
|
_emit(
|
|
"status.update",
|
|
sid,
|
|
{"kind": "goal", "text": verdict_msg},
|
|
)
|
|
if decision.get("should_continue"):
|
|
cont_prompt = decision.get("continuation_prompt") or ""
|
|
if cont_prompt:
|
|
goal_followup = cont_prompt
|
|
except Exception as _goal_exc:
|
|
print(
|
|
f"[tui_gateway] goal continuation hook failed: "
|
|
f"{type(_goal_exc).__name__}: {_goal_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
# Apply pending_title now that the DB row exists.
|
|
_pending = session.get("pending_title")
|
|
if _pending and status == "complete":
|
|
_pdb = _get_db()
|
|
if _pdb:
|
|
_session_key = session.get("session_key") or sid
|
|
try:
|
|
if _pdb.set_session_title(_session_key, _pending):
|
|
session["pending_title"] = None
|
|
except ValueError as exc:
|
|
# Invalid/duplicate title — non-retryable, drop it.
|
|
# Auto-title will take over. Fix for #19029.
|
|
session["pending_title"] = None
|
|
logger.info(
|
|
"Dropping pending title for session %s: %s",
|
|
_session_key, exc,
|
|
)
|
|
except Exception:
|
|
# Transient DB failure — keep pending_title for retry.
|
|
pass
|
|
|
|
if (
|
|
status == "complete"
|
|
and isinstance(raw, str)
|
|
and raw.strip()
|
|
and isinstance(text, str)
|
|
and text.strip()
|
|
):
|
|
try:
|
|
from agent.title_generator import maybe_auto_title
|
|
|
|
maybe_auto_title(
|
|
_get_db(),
|
|
session.get("session_key") or sid,
|
|
text,
|
|
raw,
|
|
session.get("history", []),
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
# CLI parity: when voice-mode TTS is on, speak the agent reply
|
|
# (cli.py:_voice_speak_response). Only the final text — tool
|
|
# calls / reasoning already stream separately and would be
|
|
# noisy to read aloud.
|
|
if (
|
|
status == "complete"
|
|
and isinstance(raw, str)
|
|
and raw.strip()
|
|
and _voice_tts_enabled()
|
|
):
|
|
try:
|
|
from hermes_cli.voice import speak_text
|
|
|
|
spoken = raw
|
|
threading.Thread(
|
|
target=speak_text, args=(spoken,), daemon=True
|
|
).start()
|
|
except ImportError:
|
|
logger.warning("voice TTS skipped: hermes_cli.voice unavailable")
|
|
except Exception as e:
|
|
logger.warning("voice TTS dispatch failed: %s", e)
|
|
except Exception as e:
|
|
import traceback
|
|
|
|
trace = traceback.format_exc()
|
|
try:
|
|
os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
|
|
with open(_CRASH_LOG, "a", encoding="utf-8") as f:
|
|
f.write(
|
|
f"\n=== turn-dispatcher exception · "
|
|
f"{time.strftime('%Y-%m-%d %H:%M:%S')} · sid={sid} ===\n"
|
|
)
|
|
f.write(trace)
|
|
except Exception:
|
|
pass
|
|
print(
|
|
f"[gateway-turn] {type(e).__name__}: {e}", file=sys.stderr, flush=True
|
|
)
|
|
_emit("error", sid, {"message": str(e)})
|
|
finally:
|
|
try:
|
|
if approval_token is not None:
|
|
reset_current_session_key(approval_token)
|
|
except Exception:
|
|
pass
|
|
_clear_session_context(session_tokens)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
session["last_active"] = time.time()
|
|
_clear_inflight_turn(session)
|
|
_emit("session.info", sid, _session_info(agent, session))
|
|
|
|
# Chain a goal-continuation turn if the judge said so. We do
|
|
# this AFTER the finally releases session["running"], so the
|
|
# nested _run_prompt_submit doesn't deadlock on the busy
|
|
# guard. A real user prompt that races us wins because
|
|
# prompt.submit sets running=True under the history_lock and
|
|
# we check that guard before re-firing.
|
|
if goal_followup:
|
|
with session["history_lock"]:
|
|
if session.get("running"):
|
|
# User already sent something — their turn wins,
|
|
# the judge will re-run on the next turn anyway.
|
|
return
|
|
session["running"] = True
|
|
try:
|
|
_emit("message.start", sid)
|
|
_run_prompt_submit(rid, sid, session, goal_followup)
|
|
except Exception as _cont_exc:
|
|
print(
|
|
f"[tui_gateway] goal continuation dispatch failed: "
|
|
f"{type(_cont_exc).__name__}: {_cont_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
|
|
# Drain completion notifications that arrived during this turn.
|
|
# The background poller handles between-turn delivery; this is
|
|
# the safety net for events that arrived mid-turn.
|
|
try:
|
|
from tools.process_registry import process_registry
|
|
|
|
for _evt, synth in process_registry.drain_notifications():
|
|
with session["history_lock"]:
|
|
if session.get("running"):
|
|
process_registry.completion_queue.put(_evt)
|
|
break
|
|
session["running"] = True
|
|
try:
|
|
_emit("message.start", sid)
|
|
_run_prompt_submit(rid, sid, session, synth)
|
|
except Exception as _n_exc:
|
|
print(
|
|
f"[tui_gateway] completion notification dispatch failed: "
|
|
f"{type(_n_exc).__name__}: {_n_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
with session["history_lock"]:
|
|
session["running"] = False
|
|
except Exception as _drain_exc:
|
|
print(
|
|
f"[tui_gateway] completion queue drain failed: "
|
|
f"{type(_drain_exc).__name__}: {_drain_exc}",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
threading.Thread(target=run, daemon=True).start()
|
|
|
|
|
|
@method("clipboard.paste")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
try:
|
|
from hermes_cli.clipboard import has_clipboard_image, save_clipboard_image
|
|
except Exception as e:
|
|
return _err(rid, 5027, f"clipboard unavailable: {e}")
|
|
|
|
session["image_counter"] = session.get("image_counter", 0) + 1
|
|
img_dir = _hermes_home / "images"
|
|
img_dir.mkdir(parents=True, exist_ok=True)
|
|
img_path = (
|
|
img_dir
|
|
/ f"clip_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{session['image_counter']}.png"
|
|
)
|
|
|
|
# Save-first: mirrors CLI keybinding path; more robust than has_image() precheck
|
|
if not save_clipboard_image(img_path):
|
|
session["image_counter"] = max(0, session["image_counter"] - 1)
|
|
msg = (
|
|
"Clipboard has image but extraction failed"
|
|
if has_clipboard_image()
|
|
else "No image found in clipboard"
|
|
)
|
|
return _ok(rid, {"attached": False, "message": msg})
|
|
|
|
session.setdefault("attached_images", []).append(str(img_path))
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"attached": True,
|
|
"path": str(img_path),
|
|
"count": len(session["attached_images"]),
|
|
**_image_meta(img_path),
|
|
},
|
|
)
|
|
|
|
|
|
@method("image.attach")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
raw = str(params.get("path", "") or "").strip()
|
|
if not raw:
|
|
return _err(rid, 4015, "path required")
|
|
try:
|
|
from cli import (
|
|
_IMAGE_EXTENSIONS,
|
|
_detect_file_drop,
|
|
_resolve_attachment_path,
|
|
_split_path_input,
|
|
)
|
|
|
|
dropped = _detect_file_drop(raw)
|
|
if dropped:
|
|
image_path = dropped["path"]
|
|
remainder = dropped["remainder"]
|
|
else:
|
|
path_token, remainder = _split_path_input(raw)
|
|
image_path = _resolve_attachment_path(path_token)
|
|
if image_path is None:
|
|
return _err(rid, 4016, f"image not found: {path_token}")
|
|
if image_path.suffix.lower() not in _IMAGE_EXTENSIONS:
|
|
return _err(rid, 4016, f"unsupported image: {image_path.name}")
|
|
session.setdefault("attached_images", []).append(str(image_path))
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"attached": True,
|
|
"path": str(image_path),
|
|
"count": len(session["attached_images"]),
|
|
"remainder": remainder,
|
|
"text": remainder or f"[User attached image: {image_path.name}]",
|
|
**_image_meta(image_path),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5027, str(e))
|
|
|
|
|
|
@method("image.detach")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
raw = str(params.get("path", "") or "").strip()
|
|
if not raw:
|
|
return _err(rid, 4015, "path required")
|
|
images = session.setdefault("attached_images", [])
|
|
before = len(images)
|
|
session["attached_images"] = [path for path in images if path != raw]
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"detached": len(session["attached_images"]) != before,
|
|
"count": len(session["attached_images"]),
|
|
},
|
|
)
|
|
|
|
|
|
@method("input.detect_drop")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess_nowait(params, rid)
|
|
if err:
|
|
return err
|
|
try:
|
|
from cli import _detect_file_drop
|
|
|
|
raw = str(params.get("text", "") or "")
|
|
dropped = _detect_file_drop(raw)
|
|
if not dropped:
|
|
return _ok(rid, {"matched": False})
|
|
|
|
drop_path = dropped["path"]
|
|
remainder = dropped["remainder"]
|
|
if dropped["is_image"]:
|
|
session.setdefault("attached_images", []).append(str(drop_path))
|
|
text = remainder or f"[User attached image: {drop_path.name}]"
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"matched": True,
|
|
"is_image": True,
|
|
"path": str(drop_path),
|
|
"count": len(session["attached_images"]),
|
|
"text": text,
|
|
**_image_meta(drop_path),
|
|
},
|
|
)
|
|
|
|
text = f"[User attached file: {drop_path}]" + (
|
|
f"\n{remainder}" if remainder else ""
|
|
)
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"matched": True,
|
|
"is_image": False,
|
|
"path": str(drop_path),
|
|
"name": drop_path.name,
|
|
"text": text,
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5027, str(e))
|
|
|
|
|
|
@method("prompt.background")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
text, parent = params.get("text", ""), params.get("session_id", "")
|
|
if not text:
|
|
return _err(rid, 4012, "text required")
|
|
task_id = f"bg_{uuid.uuid4().hex[:6]}"
|
|
|
|
def run():
|
|
session_tokens = _set_session_context(task_id)
|
|
try:
|
|
from run_agent import AIAgent
|
|
|
|
result = AIAgent(
|
|
**_background_agent_kwargs(session["agent"], task_id)
|
|
).run_conversation(
|
|
user_message=text,
|
|
task_id=task_id,
|
|
)
|
|
_emit(
|
|
"background.complete",
|
|
parent,
|
|
{
|
|
"task_id": task_id,
|
|
"text": (
|
|
result.get("final_response", str(result))
|
|
if isinstance(result, dict)
|
|
else str(result)
|
|
),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
_emit(
|
|
"background.complete",
|
|
parent,
|
|
{"task_id": task_id, "text": f"error: {e}"},
|
|
)
|
|
finally:
|
|
_clear_session_context(session_tokens)
|
|
|
|
threading.Thread(target=run, daemon=True).start()
|
|
return _ok(rid, {"task_id": task_id})
|
|
|
|
|
|
@method("preview.restart")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
|
|
url = str(params.get("url") or "").strip()
|
|
cwd = str(params.get("cwd") or "").strip()
|
|
context = str(params.get("context") or "").strip()
|
|
|
|
if not url:
|
|
return _err(rid, 4012, "url required")
|
|
|
|
task_id = f"preview_{uuid.uuid4().hex[:6]}"
|
|
parent = params.get("session_id", "")
|
|
parent_history = _preview_restart_history(session)
|
|
has_history = bool(parent_history)
|
|
prompt = "\n".join(
|
|
line
|
|
for line in [
|
|
"The desktop preview pane cannot load a local server URL.",
|
|
"",
|
|
f"Preview URL: {url}",
|
|
f"Current working directory: {cwd or '(unknown)'}",
|
|
"",
|
|
f"Preview console:\n{context}" if context else "",
|
|
"" if context else "",
|
|
(
|
|
"The conversation history above is from the user's main session — including the commands you (the assistant) previously ran to start servers, edit files, or check ports. Use it to figure out exactly which server should be running at this Preview URL. The user did not start a brand new task; recover what they had working."
|
|
if has_history
|
|
else None
|
|
),
|
|
"Restart exactly the app intended for the Preview URL, not Hermes Desktop itself.",
|
|
"The Preview URL and port are the target. Preserve that target unless you conclude it is impossible.",
|
|
"If the prior conversation shows a specific command that bound this URL/port, prefer re-running THAT exact command (in the same cwd) over guessing a new one.",
|
|
"First inspect what process, if any, owns the Preview URL port. If a stale server exists, inspect its cwd and prefer that cwd over the Hermes/Desktop process cwd.",
|
|
"The Current working directory is only a hint. Do not assume it is the preview app root when the port owner or files indicate another root.",
|
|
"If the console shows a module-script MIME error for src/main.tsx or similar, a static server is serving source files. Do not restart python -m http.server or any dumb static server for that app.",
|
|
"For module-script MIME failures, inspect package.json/vite config in the candidate app root and start the real dev server/bundler (for example npm/pnpm/yarn dev) so module transforms happen.",
|
|
"Before declaring success, verify the Preview URL responds with the intended app, not Hermes Desktop. If it serves Hermes/Desktop UI or another unrelated app, stop that process and report failure.",
|
|
"Do not modify files. Do not ask the user unless blocked.",
|
|
"Prefer existing project scripts or commands when they are clear.",
|
|
"If a stale process owns the needed port, handle it safely.",
|
|
"Start long-running servers detached/in the background, then return immediately.",
|
|
"Do not run a foreground dev server command that blocks this background task.",
|
|
"Keep the final response short: what command/server was started, or why it could not be restarted.",
|
|
]
|
|
if line
|
|
)
|
|
|
|
def run():
|
|
session_tokens = _set_session_context(task_id)
|
|
try:
|
|
from run_agent import AIAgent
|
|
from tools.terminal_tool import register_task_env_overrides
|
|
|
|
if cwd and os.path.isdir(os.path.abspath(os.path.expanduser(cwd))):
|
|
register_task_env_overrides(task_id, {"cwd": os.path.abspath(os.path.expanduser(cwd))})
|
|
|
|
history_note = (
|
|
f" (with {len(parent_history)} parent-session messages of context)"
|
|
if parent_history
|
|
else ""
|
|
)
|
|
_emit(
|
|
"preview.restart.progress",
|
|
parent,
|
|
{"task_id": task_id, "text": f"Starting hidden restart agent{history_note}"},
|
|
)
|
|
result = AIAgent(
|
|
**_ephemeral_preview_agent_kwargs(session["agent"], task_id),
|
|
**_preview_restart_callbacks(parent, task_id),
|
|
).run_conversation(
|
|
user_message=prompt,
|
|
task_id=task_id,
|
|
conversation_history=parent_history or None,
|
|
)
|
|
text = (
|
|
result.get("final_response", str(result))
|
|
if isinstance(result, dict)
|
|
else str(result)
|
|
)
|
|
_emit("preview.restart.complete", parent, {"task_id": task_id, "text": text})
|
|
except Exception as e:
|
|
_emit(
|
|
"preview.restart.complete",
|
|
parent,
|
|
{"task_id": task_id, "text": f"error: {e}"},
|
|
)
|
|
finally:
|
|
try:
|
|
from tools.terminal_tool import clear_task_env_overrides
|
|
|
|
clear_task_env_overrides(task_id)
|
|
except Exception:
|
|
pass
|
|
_clear_session_context(session_tokens)
|
|
|
|
threading.Thread(target=run, daemon=True).start()
|
|
return _ok(rid, {"task_id": task_id})
|
|
|
|
|
|
# ── Methods: respond ─────────────────────────────────────────────────
|
|
|
|
|
|
def _respond(rid, params, key):
|
|
r = params.get("request_id", "")
|
|
entry = _pending.get(r)
|
|
if not entry:
|
|
return _err(rid, 4009, f"no pending {key} request")
|
|
_, ev = entry
|
|
_answers[r] = params.get(key, "")
|
|
ev.set()
|
|
return _ok(rid, {"status": "ok"})
|
|
|
|
|
|
@method("clarify.respond")
|
|
def _(rid, params: dict) -> dict:
|
|
return _respond(rid, params, "answer")
|
|
|
|
|
|
@method("sudo.respond")
|
|
def _(rid, params: dict) -> dict:
|
|
return _respond(rid, params, "password")
|
|
|
|
|
|
@method("secret.respond")
|
|
def _(rid, params: dict) -> dict:
|
|
return _respond(rid, params, "value")
|
|
|
|
|
|
@method("approval.respond")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
try:
|
|
from tools.approval import resolve_gateway_approval
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"resolved": resolve_gateway_approval(
|
|
session["session_key"],
|
|
params.get("choice", "deny"),
|
|
resolve_all=params.get("all", False),
|
|
)
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5004, str(e))
|
|
|
|
|
|
# ── Methods: config ──────────────────────────────────────────────────
|
|
|
|
|
|
@method("config.set")
|
|
def _(rid, params: dict) -> dict:
|
|
key, value = params.get("key", ""), params.get("value", "")
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
|
|
if key == "model":
|
|
try:
|
|
if not value:
|
|
return _err(rid, 4002, "model value required")
|
|
if session:
|
|
# Reject during an in-flight turn. agent.switch_model()
|
|
# mutates self.model / self.provider / self.base_url /
|
|
# self.client in place; the worker thread running
|
|
# agent.run_conversation is reading those on every
|
|
# iteration. A mid-turn swap can send an HTTP request
|
|
# with the new base_url but old model (or vice versa),
|
|
# producing 400/404s the user never asked for. Parity
|
|
# with the gateway's running-agent /model guard.
|
|
if session.get("running"):
|
|
return _err(
|
|
rid,
|
|
4009,
|
|
"session busy — /interrupt the current turn before switching models",
|
|
)
|
|
if session.get("agent") is None:
|
|
session_id = params.get("session_id", "")
|
|
_start_agent_build(session_id, session)
|
|
init_err = _wait_agent(session, rid)
|
|
if init_err:
|
|
return init_err
|
|
if session.get("agent") is None:
|
|
return _err(rid, 5032, "agent initialization failed")
|
|
result = _apply_model_switch(
|
|
params.get("session_id", ""), session, value
|
|
)
|
|
else:
|
|
result = _apply_model_switch("", {"agent": None}, value)
|
|
return _ok(
|
|
rid,
|
|
{"key": key, "value": result["value"], "warning": result["warning"]},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5001, str(e))
|
|
|
|
if key == "fast":
|
|
raw = str(value or "").strip().lower()
|
|
agent = session.get("agent") if session else None
|
|
if agent is not None:
|
|
current_fast = getattr(agent, "service_tier", None) == "priority"
|
|
else:
|
|
current_fast = _load_service_tier() == "priority"
|
|
|
|
if raw in {"status"}:
|
|
return _ok(
|
|
rid,
|
|
{"key": key, "value": "fast" if current_fast else "normal"},
|
|
)
|
|
|
|
if raw in {"", "toggle"}:
|
|
nv = "normal" if current_fast else "fast"
|
|
elif raw in {"fast", "on"}:
|
|
nv = "fast"
|
|
elif raw in {"normal", "off"}:
|
|
nv = "normal"
|
|
else:
|
|
return _err(rid, 4002, f"unknown fast mode: {value}")
|
|
|
|
overrides = None
|
|
if nv == "fast":
|
|
from hermes_cli.models import resolve_fast_mode_overrides
|
|
|
|
target_model = (
|
|
getattr(agent, "model", None) if agent is not None else _resolve_model()
|
|
)
|
|
if not target_model:
|
|
return _err(
|
|
rid,
|
|
4002,
|
|
"fast mode is not available without a selected model",
|
|
)
|
|
overrides = resolve_fast_mode_overrides(target_model)
|
|
if overrides is None:
|
|
return _err(
|
|
rid,
|
|
4002,
|
|
"fast mode is not available for this model",
|
|
)
|
|
|
|
_write_config_key("agent.service_tier", nv)
|
|
if agent is not None:
|
|
agent.service_tier = "priority" if nv == "fast" else None
|
|
current_overrides = dict(getattr(agent, "request_overrides", {}) or {})
|
|
current_overrides.pop("service_tier", None)
|
|
current_overrides.pop("speed", None)
|
|
if nv == "fast":
|
|
current_overrides.update(overrides)
|
|
agent.request_overrides = current_overrides
|
|
_emit(
|
|
"session.info",
|
|
params.get("session_id", ""),
|
|
_session_info(agent, session),
|
|
)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "busy":
|
|
raw = str(value or "").strip().lower()
|
|
if raw in {"", "status"}:
|
|
return _ok(rid, {"key": key, "value": _load_busy_input_mode()})
|
|
if raw not in {"queue", "steer", "interrupt"}:
|
|
return _err(rid, 4002, f"unknown busy mode: {value}")
|
|
_write_config_key("display.busy_input_mode", raw)
|
|
return _ok(rid, {"key": key, "value": raw})
|
|
|
|
if key == "verbose":
|
|
cycle = ["off", "new", "all", "verbose"]
|
|
cur = (
|
|
session.get("tool_progress_mode", _load_tool_progress_mode())
|
|
if session
|
|
else _load_tool_progress_mode()
|
|
)
|
|
if value and value != "cycle":
|
|
nv = str(value).strip().lower()
|
|
if nv not in cycle:
|
|
return _err(rid, 4002, f"unknown verbose mode: {value}")
|
|
else:
|
|
try:
|
|
idx = cycle.index(cur)
|
|
except ValueError:
|
|
idx = 2
|
|
nv = cycle[(idx + 1) % len(cycle)]
|
|
_write_config_key("display.tool_progress", nv)
|
|
if session:
|
|
session["tool_progress_mode"] = nv
|
|
agent = session.get("agent")
|
|
if agent is not None:
|
|
agent.verbose_logging = nv == "verbose"
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "yolo":
|
|
try:
|
|
if session:
|
|
from tools.approval import (
|
|
disable_session_yolo,
|
|
enable_session_yolo,
|
|
is_session_yolo_enabled,
|
|
)
|
|
|
|
current = is_session_yolo_enabled(session["session_key"])
|
|
if current:
|
|
disable_session_yolo(session["session_key"])
|
|
nv = "0"
|
|
else:
|
|
enable_session_yolo(session["session_key"])
|
|
nv = "1"
|
|
else:
|
|
current = is_truthy_value(os.environ.get("HERMES_YOLO_MODE"))
|
|
if current:
|
|
os.environ.pop("HERMES_YOLO_MODE", None)
|
|
nv = "0"
|
|
else:
|
|
os.environ["HERMES_YOLO_MODE"] = "1"
|
|
nv = "1"
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
except Exception as e:
|
|
return _err(rid, 5001, str(e))
|
|
|
|
if key == "reasoning":
|
|
try:
|
|
from hermes_constants import parse_reasoning_effort
|
|
|
|
arg = str(value or "").strip().lower()
|
|
if arg in {"show", "on"}:
|
|
cfg = _load_cfg()
|
|
display = (
|
|
cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
|
|
)
|
|
sections = (
|
|
display.get("sections")
|
|
if isinstance(display.get("sections"), dict)
|
|
else {}
|
|
)
|
|
display["show_reasoning"] = True
|
|
sections["thinking"] = "expanded"
|
|
display["sections"] = sections
|
|
cfg["display"] = display
|
|
_save_cfg(cfg)
|
|
if session:
|
|
session["show_reasoning"] = True
|
|
return _ok(rid, {"key": key, "value": "show"})
|
|
if arg in {"hide", "off"}:
|
|
cfg = _load_cfg()
|
|
display = (
|
|
cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
|
|
)
|
|
sections = (
|
|
display.get("sections")
|
|
if isinstance(display.get("sections"), dict)
|
|
else {}
|
|
)
|
|
display["show_reasoning"] = False
|
|
sections["thinking"] = "hidden"
|
|
display["sections"] = sections
|
|
cfg["display"] = display
|
|
_save_cfg(cfg)
|
|
if session:
|
|
session["show_reasoning"] = False
|
|
return _ok(rid, {"key": key, "value": "hide"})
|
|
|
|
parsed = parse_reasoning_effort(arg)
|
|
if parsed is None:
|
|
return _err(rid, 4002, f"unknown reasoning value: {value}")
|
|
_write_config_key("agent.reasoning_effort", arg)
|
|
if session and session.get("agent") is not None:
|
|
session["agent"].reasoning_config = parsed
|
|
return _ok(rid, {"key": key, "value": arg})
|
|
except Exception as e:
|
|
return _err(rid, 5001, str(e))
|
|
|
|
if key == "details_mode":
|
|
nv = str(value or "").strip().lower()
|
|
if nv not in _DETAIL_MODES:
|
|
return _err(rid, 4002, f"unknown details_mode: {value}")
|
|
cfg = _load_cfg()
|
|
display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
|
|
sections = (
|
|
display.get("sections") if isinstance(display.get("sections"), dict) else {}
|
|
)
|
|
display["details_mode"] = nv
|
|
for section in _DETAIL_SECTION_NAMES:
|
|
sections[section] = nv
|
|
display["sections"] = sections
|
|
cfg["display"] = display
|
|
_save_cfg(cfg)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key.startswith("details_mode."):
|
|
# Per-section override: `details_mode.<section>` writes to
|
|
# `display.sections.<section>`. Empty value clears the explicit
|
|
# override and lets frontend resolution apply built-in section defaults
|
|
# before the global details_mode.
|
|
section = key.split(".", 1)[1]
|
|
if section not in _DETAIL_SECTION_NAMES:
|
|
return _err(rid, 4002, f"unknown section: {section}")
|
|
|
|
cfg = _load_cfg()
|
|
display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
|
|
sections_cfg = (
|
|
display.get("sections") if isinstance(display.get("sections"), dict) else {}
|
|
)
|
|
|
|
nv = str(value or "").strip().lower()
|
|
if not nv:
|
|
sections_cfg.pop(section, None)
|
|
display["sections"] = sections_cfg
|
|
cfg["display"] = display
|
|
_save_cfg(cfg)
|
|
return _ok(rid, {"key": key, "value": ""})
|
|
|
|
if nv not in _DETAIL_MODES:
|
|
return _err(rid, 4002, f"unknown details_mode: {value}")
|
|
|
|
sections_cfg[section] = nv
|
|
display["sections"] = sections_cfg
|
|
cfg["display"] = display
|
|
_save_cfg(cfg)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "thinking_mode":
|
|
nv = str(value or "").strip().lower()
|
|
allowed_tm = frozenset({"collapsed", "truncated", "full"})
|
|
if nv not in allowed_tm:
|
|
return _err(rid, 4002, f"unknown thinking_mode: {value}")
|
|
_write_config_key("display.thinking_mode", nv)
|
|
# Backward compatibility bridge: keep details_mode aligned.
|
|
_write_config_key(
|
|
"display.details_mode", "expanded" if nv == "full" else "collapsed"
|
|
)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "compact":
|
|
raw = str(value or "").strip().lower()
|
|
cfg0 = _load_cfg()
|
|
d0 = cfg0.get("display") if isinstance(cfg0.get("display"), dict) else {}
|
|
cur_b = bool(d0.get("tui_compact", False))
|
|
if raw in {"", "toggle"}:
|
|
nv_b = not cur_b
|
|
elif raw == "on":
|
|
nv_b = True
|
|
elif raw == "off":
|
|
nv_b = False
|
|
else:
|
|
return _err(rid, 4002, f"unknown compact value: {value}")
|
|
_write_config_key("display.tui_compact", nv_b)
|
|
return _ok(rid, {"key": key, "value": "on" if nv_b else "off"})
|
|
|
|
if key == "statusbar":
|
|
raw = str(value or "").strip().lower()
|
|
display = _load_cfg().get("display")
|
|
d0 = display if isinstance(display, dict) else {}
|
|
current = _coerce_statusbar(d0.get("tui_statusbar", "top"))
|
|
|
|
if raw in {"", "toggle"}:
|
|
nv = "top" if current == "off" else "off"
|
|
elif raw == "on":
|
|
nv = "top"
|
|
elif raw in _STATUSBAR_MODES:
|
|
nv = raw
|
|
else:
|
|
return _err(rid, 4002, f"unknown statusbar value: {value}")
|
|
|
|
_write_config_key("display.tui_statusbar", nv)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "mouse":
|
|
# Explicit None check rather than `value or ""` so falsy non-string
|
|
# inputs (0, False) reach the alias map as themselves — both map to
|
|
# 'off' via _MOUSE_TRACKING_ALIASES — instead of being collapsed to
|
|
# '' and triggering the toggle path. The slash command always passes
|
|
# a string, but programmatic JSON-RPC callers may send booleans.
|
|
raw = ("" if value is None else str(value)).strip().lower()
|
|
cfg = _load_cfg()
|
|
display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
|
|
current = _display_mouse_tracking(display)
|
|
|
|
if raw in {"", "toggle"}:
|
|
nv = "all" if current == "off" else "off"
|
|
elif raw in _MOUSE_TRACKING_ALIASES:
|
|
nv = _MOUSE_TRACKING_ALIASES[raw]
|
|
else:
|
|
return _err(rid, 4002, f"unknown mouse value: {value}")
|
|
|
|
_write_config_key("display.mouse_tracking", nv)
|
|
return _ok(rid, {"key": key, "value": nv})
|
|
|
|
if key == "indicator":
|
|
# Use an explicit None check rather than `value or ""` so falsy
|
|
# non-string inputs (0, False, []) still surface as themselves
|
|
# in the error message instead of looking like a blank value.
|
|
raw = ("" if value is None else str(value)).strip().lower()
|
|
if raw not in _INDICATOR_STYLES:
|
|
return _err(
|
|
rid,
|
|
4002,
|
|
f"unknown indicator: {raw!r}; pick one of {'|'.join(_INDICATOR_STYLES)}",
|
|
)
|
|
_write_config_key("display.tui_status_indicator", raw)
|
|
return _ok(rid, {"key": key, "value": raw})
|
|
|
|
if key in {"cwd", "terminal.cwd", "workdir"}:
|
|
raw = str(value or "").strip()
|
|
if not raw:
|
|
return _err(rid, 4002, "cwd required")
|
|
cwd = os.path.abspath(os.path.expanduser(raw))
|
|
if not os.path.isdir(cwd):
|
|
return _err(rid, 4002, f"working directory does not exist: {raw}")
|
|
_write_config_key("terminal.cwd", cwd)
|
|
os.environ["TERMINAL_CWD"] = cwd
|
|
return _ok(
|
|
rid,
|
|
{"key": "terminal.cwd", "value": cwd, "cwd": cwd, "branch": _git_branch_for_cwd(cwd)},
|
|
)
|
|
|
|
if key in {"prompt", "personality", "skin"}:
|
|
try:
|
|
cfg = _load_cfg()
|
|
if key == "prompt":
|
|
if value == "clear":
|
|
cfg.pop("custom_prompt", None)
|
|
nv = ""
|
|
else:
|
|
cfg["custom_prompt"] = value
|
|
nv = value
|
|
_save_cfg(cfg)
|
|
elif key == "personality":
|
|
sid_key = params.get("session_id", "")
|
|
pname, new_prompt = _validate_personality(str(value or ""), cfg)
|
|
_write_config_key("display.personality", pname)
|
|
_write_config_key("agent.system_prompt", new_prompt)
|
|
nv = str(value or "none")
|
|
history_reset, info = _apply_personality_to_session(
|
|
sid_key, session, new_prompt, pname
|
|
)
|
|
else:
|
|
_write_config_key(f"display.{key}", value)
|
|
nv = value
|
|
if key == "skin":
|
|
_emit("skin.changed", "", resolve_skin())
|
|
resp = {"key": key, "value": nv}
|
|
if key == "personality":
|
|
resp["history_reset"] = history_reset
|
|
if info is not None:
|
|
resp["info"] = info
|
|
return _ok(rid, resp)
|
|
except Exception as e:
|
|
return _err(rid, 5001, str(e))
|
|
|
|
return _err(rid, 4002, f"unknown config key: {key}")
|
|
|
|
|
|
@method("config.get")
|
|
def _(rid, params: dict) -> dict:
|
|
key = params.get("key", "")
|
|
if key == "provider":
|
|
try:
|
|
from hermes_cli.models import list_available_providers, normalize_provider
|
|
|
|
model = _resolve_model()
|
|
parts = model.split("/", 1)
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"model": model,
|
|
"provider": (
|
|
normalize_provider(parts[0]) if len(parts) > 1 else "unknown"
|
|
),
|
|
"providers": list_available_providers(),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5013, str(e))
|
|
if key == "profile":
|
|
from hermes_constants import display_hermes_home
|
|
|
|
return _ok(rid, {"home": str(_hermes_home), "display": display_hermes_home()})
|
|
if key == "project":
|
|
cfg_terminal = _load_cfg().get("terminal") or {}
|
|
raw = str(params.get("cwd", "") or cfg_terminal.get("cwd", "") or "").strip()
|
|
cwd = _completion_cwd({"cwd": raw} if raw else {})
|
|
return _ok(rid, {"cwd": cwd, "branch": _git_branch_for_cwd(cwd)})
|
|
if key == "full":
|
|
return _ok(rid, {"config": _load_cfg()})
|
|
if key == "prompt":
|
|
return _ok(rid, {"prompt": _load_cfg().get("custom_prompt", "")})
|
|
if key == "skin":
|
|
return _ok(
|
|
rid, {"value": (_load_cfg().get("display") or {}).get("skin", "default")}
|
|
)
|
|
if key == "indicator":
|
|
# Normalize so a hand-edited config.yaml with stray casing or
|
|
# an unknown value reads back the SAME value the TUI actually
|
|
# rendered (frontend's `normalizeIndicatorStyle` falls back to
|
|
# `_INDICATOR_DEFAULT` for the same inputs). Otherwise
|
|
# `/indicator` would print one thing while the UI shows another.
|
|
raw = (_load_cfg().get("display") or {}).get("tui_status_indicator", "")
|
|
norm = str(raw).strip().lower()
|
|
return _ok(
|
|
rid,
|
|
{"value": norm if norm in _INDICATOR_STYLES else _INDICATOR_DEFAULT},
|
|
)
|
|
if key == "personality":
|
|
return _ok(
|
|
rid,
|
|
{"value": (_load_cfg().get("display") or {}).get("personality") or "none"},
|
|
)
|
|
if key == "reasoning":
|
|
cfg = _load_cfg()
|
|
effort = str(
|
|
(cfg.get("agent") or {}).get("reasoning_effort", "medium") or "medium"
|
|
)
|
|
display = (
|
|
"show"
|
|
if bool((cfg.get("display") or {}).get("show_reasoning", False))
|
|
else "hide"
|
|
)
|
|
return _ok(rid, {"value": effort, "display": display})
|
|
if key == "fast":
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"value": (
|
|
"fast"
|
|
if (session := _sessions.get(params.get("session_id", "")))
|
|
and getattr(session.get("agent"), "service_tier", None)
|
|
== "priority"
|
|
else ("fast" if _load_service_tier() == "priority" else "normal")
|
|
),
|
|
},
|
|
)
|
|
if key == "busy":
|
|
return _ok(rid, {"value": _load_busy_input_mode()})
|
|
if key == "details_mode":
|
|
allowed_dm = frozenset({"hidden", "collapsed", "expanded"})
|
|
raw = (
|
|
str(
|
|
(_load_cfg().get("display") or {}).get("details_mode", "collapsed")
|
|
or "collapsed"
|
|
)
|
|
.strip()
|
|
.lower()
|
|
)
|
|
nv = raw if raw in allowed_dm else "collapsed"
|
|
return _ok(rid, {"value": nv})
|
|
if key == "thinking_mode":
|
|
allowed_tm = frozenset({"collapsed", "truncated", "full"})
|
|
cfg = _load_cfg()
|
|
raw = (
|
|
str((cfg.get("display") or {}).get("thinking_mode", "") or "")
|
|
.strip()
|
|
.lower()
|
|
)
|
|
if raw in allowed_tm:
|
|
nv = raw
|
|
else:
|
|
dm = (
|
|
str(
|
|
(cfg.get("display") or {}).get("details_mode", "collapsed")
|
|
or "collapsed"
|
|
)
|
|
.strip()
|
|
.lower()
|
|
)
|
|
nv = "full" if dm == "expanded" else "collapsed"
|
|
return _ok(rid, {"value": nv})
|
|
if key == "compact":
|
|
on = bool((_load_cfg().get("display") or {}).get("tui_compact", False))
|
|
return _ok(rid, {"value": "on" if on else "off"})
|
|
if key == "statusbar":
|
|
display = _load_cfg().get("display")
|
|
raw = (
|
|
display.get("tui_statusbar", "top") if isinstance(display, dict) else "top"
|
|
)
|
|
return _ok(rid, {"value": _coerce_statusbar(raw)})
|
|
if key == "mouse":
|
|
display = _load_cfg().get("display")
|
|
return _ok(rid, {"value": _display_mouse_tracking(display)})
|
|
if key == "mtime":
|
|
cfg_path = _hermes_home / "config.yaml"
|
|
try:
|
|
return _ok(
|
|
rid, {"mtime": cfg_path.stat().st_mtime if cfg_path.exists() else 0}
|
|
)
|
|
except Exception:
|
|
return _ok(rid, {"mtime": 0})
|
|
return _err(rid, 4002, f"unknown config key: {key}")
|
|
|
|
|
|
@method("setup.status")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from hermes_cli.main import _has_any_provider_configured
|
|
|
|
return _ok(rid, {"provider_configured": bool(_has_any_provider_configured())})
|
|
except Exception as e:
|
|
return _err(rid, 5016, str(e))
|
|
|
|
|
|
@method("setup.runtime_check")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Strict provider check: does the configured/default model actually resolve to a usable runtime?
|
|
|
|
Unlike setup.status (which returns True if ANY provider auth state is
|
|
discoverable, including indirect fallbacks like ``gh auth token`` for
|
|
Copilot), this runs the same resolve_runtime_provider() call the agent
|
|
uses on session creation. It returns ok=False with the auth error message
|
|
when the user's configured model cannot actually be served, so UIs can
|
|
surface onboarding before the user submits a doomed prompt.
|
|
"""
|
|
try:
|
|
from hermes_cli.runtime_provider import resolve_runtime_provider
|
|
from hermes_cli.auth import has_usable_secret
|
|
from hermes_cli.main import _has_any_provider_configured
|
|
|
|
runtime = resolve_runtime_provider(requested=None)
|
|
provider_configured = bool(_has_any_provider_configured())
|
|
provider = runtime.get("provider") or "provider"
|
|
source = str(runtime.get("source") or "")
|
|
if not provider_configured and provider == "bedrock" and source in {
|
|
"iam-role",
|
|
"aws-sdk-default-chain",
|
|
}:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"ok": False,
|
|
"provider": provider,
|
|
"model": runtime.get("model"),
|
|
"source": source,
|
|
"error": "No Hermes provider is configured.",
|
|
},
|
|
)
|
|
|
|
api_key = runtime.get("api_key")
|
|
api_key_text = "" if callable(api_key) else str(api_key or "").strip()
|
|
credential_ok = (
|
|
callable(api_key)
|
|
or api_key_text in {"aws-sdk", "no-key-required"}
|
|
or has_usable_secret(api_key_text)
|
|
or bool(runtime.get("command"))
|
|
)
|
|
|
|
if not credential_ok:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"ok": False,
|
|
"provider": provider,
|
|
"model": runtime.get("model"),
|
|
"source": runtime.get("source"),
|
|
"error": f"No usable credentials found for {provider}.",
|
|
},
|
|
)
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"ok": True,
|
|
"provider": runtime.get("provider"),
|
|
"model": runtime.get("model"),
|
|
"source": runtime.get("source"),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _ok(rid, {"ok": False, "error": str(e)})
|
|
|
|
|
|
# ── Methods: tools & system ──────────────────────────────────────────
|
|
|
|
|
|
@method("process.stop")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from tools.process_registry import process_registry
|
|
|
|
return _ok(rid, {"killed": process_registry.kill_all()})
|
|
except Exception as e:
|
|
return _err(rid, 5010, str(e))
|
|
|
|
|
|
@method("reload.mcp")
|
|
def _(rid, params: dict) -> dict:
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
try:
|
|
# Gate: /reload-mcp invalidates the prompt cache for this session.
|
|
# Respect the ``approvals.mcp_reload_confirm`` config toggle — if
|
|
# set (default true) AND the caller did not pass ``confirm=true``
|
|
# in params, surface a warning to the transcript instead of just
|
|
# reloading silently. Users pass confirm=true either by
|
|
# re-invoking after reading the warning, or by setting the
|
|
# config key to false permanently.
|
|
user_confirm = bool(params.get("confirm", False))
|
|
if not user_confirm:
|
|
try:
|
|
from hermes_cli.config import load_config as _load_config
|
|
|
|
_cfg = _load_config()
|
|
_approvals = _cfg.get("approvals") if isinstance(_cfg, dict) else None
|
|
_confirm_required = True
|
|
if isinstance(_approvals, dict):
|
|
_confirm_required = bool(_approvals.get("mcp_reload_confirm", True))
|
|
except Exception:
|
|
_confirm_required = True
|
|
if _confirm_required:
|
|
# Return a structured response the Ink client can surface
|
|
# as a warning/confirmation without actually reloading yet.
|
|
# Ink's ops.ts reads ``status`` and prints ``message`` to
|
|
# the transcript; a follow-up invocation with confirm=true
|
|
# (or an `always` choice that flips the config) proceeds.
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"status": "confirm_required",
|
|
"message": (
|
|
"⚠️ /reload-mcp invalidates the prompt cache (next "
|
|
"message re-sends full input tokens). Reply `/reload-mcp "
|
|
"now` to proceed, or `/reload-mcp always` to proceed and "
|
|
"silence this prompt permanently."
|
|
),
|
|
},
|
|
)
|
|
|
|
from tools.mcp_tool import shutdown_mcp_servers, discover_mcp_tools
|
|
|
|
shutdown_mcp_servers()
|
|
discover_mcp_tools()
|
|
if session:
|
|
agent = session["agent"]
|
|
# Rebuild the cached agent's tool snapshot so the current session
|
|
# picks up added/removed MCP tools without `/new` (which discards
|
|
# history). The agent snapshots tools once at build and never
|
|
# re-reads the registry, so an explicit rebuild is required here.
|
|
# The user already consented to the prompt-cache invalidation via
|
|
# the confirm gate above. Mirrors gateway/run.py::_execute_mcp_reload.
|
|
try:
|
|
from model_tools import get_tool_definitions
|
|
|
|
new_defs = get_tool_definitions(
|
|
enabled_toolsets=_load_enabled_toolsets(),
|
|
quiet_mode=True,
|
|
)
|
|
agent.tools = new_defs
|
|
agent.valid_tool_names = (
|
|
{t["function"]["name"] for t in new_defs} if new_defs else set()
|
|
)
|
|
except Exception as _exc:
|
|
logger.warning(
|
|
"Failed to refresh cached agent tools after /reload-mcp: %s",
|
|
_exc,
|
|
)
|
|
_emit(
|
|
"session.info",
|
|
params.get("session_id", ""),
|
|
_session_info(agent, session),
|
|
)
|
|
|
|
# Honor `always=true` by persisting the opt-out to config.
|
|
if bool(params.get("always", False)):
|
|
try:
|
|
from cli import save_config_value as _save_cfg
|
|
|
|
_save_cfg("approvals.mcp_reload_confirm", False)
|
|
except Exception as _exc:
|
|
logger.warning("Failed to persist mcp_reload_confirm=false: %s", _exc)
|
|
|
|
return _ok(rid, {"status": "reloaded"})
|
|
except Exception as e:
|
|
return _err(rid, 5015, str(e))
|
|
|
|
|
|
@method("reload.env")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Re-read ``~/.hermes/.env`` into the gateway process via
|
|
``hermes_cli.config.reload_env``, matching classic CLI's ``/reload``
|
|
handler. Newly added API keys take effect on the next agent call
|
|
without restarting the TUI.
|
|
|
|
The credential pool / provider routing for any *already-constructed*
|
|
agent does not auto-rebuild — that's the same behaviour as classic
|
|
CLI's ``/reload``. Users who want a brand-new credential resolution
|
|
should follow with ``/new``.
|
|
"""
|
|
try:
|
|
from hermes_cli.config import reload_env
|
|
|
|
count = reload_env()
|
|
return _ok(rid, {"updated": int(count)})
|
|
except Exception as e:
|
|
return _err(rid, 5015, str(e))
|
|
|
|
|
|
_TUI_HIDDEN: frozenset[str] = frozenset(
|
|
{
|
|
"sethome",
|
|
"set-home",
|
|
"commands",
|
|
"approve",
|
|
"deny",
|
|
}
|
|
)
|
|
|
|
_TUI_EXTRA: list[tuple[str, str, str]] = [
|
|
("/compact", "Toggle compact display mode", "TUI"),
|
|
("/logs", "Show recent gateway log lines", "TUI"),
|
|
(
|
|
"/mouse",
|
|
"Set mouse tracking preset [on|off|toggle|wheel|buttons|all]",
|
|
"TUI",
|
|
),
|
|
("/sessions", "Switch between live TUI sessions", "TUI"),
|
|
]
|
|
|
|
# Commands that queue messages onto _pending_input in the CLI.
|
|
# In the TUI the slash worker subprocess has no reader for that queue,
|
|
# so slash.exec rejects them → TUI falls through to command.dispatch.
|
|
_PENDING_INPUT_COMMANDS: frozenset[str] = frozenset(
|
|
{
|
|
"retry",
|
|
"queue",
|
|
"q",
|
|
"steer",
|
|
"plan",
|
|
"goal",
|
|
}
|
|
)
|
|
|
|
_WORKER_BLOCKED_COMMANDS: frozenset[str] = frozenset({"snapshot", "snap"})
|
|
|
|
|
|
@method("commands.catalog")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Registry-backed slash metadata for the TUI — categorized, no aliases."""
|
|
try:
|
|
from hermes_cli.commands import (
|
|
COMMAND_REGISTRY,
|
|
SUBCOMMANDS,
|
|
_build_description,
|
|
)
|
|
|
|
all_pairs: list[list[str]] = []
|
|
canon: dict[str, str] = {}
|
|
categories: list[dict] = []
|
|
cat_map: dict[str, list[list[str]]] = {}
|
|
cat_order: list[str] = []
|
|
|
|
for cmd in COMMAND_REGISTRY:
|
|
if cmd.name in _TUI_HIDDEN or cmd.gateway_only:
|
|
continue
|
|
|
|
c = f"/{cmd.name}"
|
|
canon[c.lower()] = c
|
|
for a in cmd.aliases:
|
|
canon[f"/{a}".lower()] = c
|
|
|
|
desc = _build_description(cmd)
|
|
all_pairs.append([c, desc])
|
|
|
|
cat = cmd.category
|
|
if cat not in cat_map:
|
|
cat_map[cat] = []
|
|
cat_order.append(cat)
|
|
cat_map[cat].append([c, desc])
|
|
|
|
for name, desc, cat in _TUI_EXTRA:
|
|
all_pairs.append([name, desc])
|
|
if cat not in cat_map:
|
|
cat_map[cat] = []
|
|
cat_order.append(cat)
|
|
cat_map[cat].append([name, desc])
|
|
|
|
warning = ""
|
|
try:
|
|
qcmds = _load_cfg().get("quick_commands", {}) or {}
|
|
if isinstance(qcmds, dict) and qcmds:
|
|
bucket = "User commands"
|
|
if bucket not in cat_map:
|
|
cat_map[bucket] = []
|
|
cat_order.append(bucket)
|
|
for qname, qc in sorted(qcmds.items()):
|
|
if not isinstance(qc, dict):
|
|
continue
|
|
key = f"/{qname}"
|
|
canon[key.lower()] = key
|
|
qtype = qc.get("type", "")
|
|
if qtype == "exec":
|
|
default_desc = f"exec: {qc.get('command', '')}"
|
|
elif qtype == "alias":
|
|
default_desc = f"alias → {qc.get('target', '')}"
|
|
else:
|
|
default_desc = qtype or "quick command"
|
|
qdesc = str(qc.get("description") or default_desc)
|
|
qdesc = qdesc[:120] + ("…" if len(qdesc) > 120 else "")
|
|
all_pairs.append([key, qdesc])
|
|
cat_map[bucket].append([key, qdesc])
|
|
except Exception as e:
|
|
if not warning:
|
|
warning = f"quick_commands discovery unavailable: {e}"
|
|
|
|
skill_count = 0
|
|
try:
|
|
from agent.skill_commands import scan_skill_commands
|
|
|
|
for k, info in sorted(scan_skill_commands().items()):
|
|
d = str(info.get("description", "Skill"))
|
|
all_pairs.append([k, d[:120] + ("…" if len(d) > 120 else "")])
|
|
skill_count += 1
|
|
except Exception as e:
|
|
warning = f"skill discovery unavailable: {e}"
|
|
|
|
for cat in cat_order:
|
|
categories.append({"name": cat, "pairs": cat_map[cat]})
|
|
|
|
sub = {k: v[:] for k, v in SUBCOMMANDS.items()}
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"pairs": all_pairs,
|
|
"sub": sub,
|
|
"canon": canon,
|
|
"categories": categories,
|
|
"skill_count": skill_count,
|
|
"warning": warning,
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5020, str(e))
|
|
|
|
|
|
def _cli_exec_blocked(argv: list[str]) -> str | None:
|
|
"""Return user hint if this argv must not run headless in the gateway process."""
|
|
if not argv:
|
|
return "bare `hermes` is interactive — use `/hermes chat -q …` or run `hermes` in another terminal"
|
|
a0 = argv[0].lower()
|
|
if a0 == "setup":
|
|
return "`hermes setup` needs a full terminal — run it outside the TUI"
|
|
if a0 == "gateway":
|
|
return "`hermes gateway` is long-running — run it in another terminal"
|
|
if a0 == "sessions" and len(argv) > 1 and argv[1].lower() == "browse":
|
|
return "`hermes sessions browse` is interactive — use /resume here, or run browse in another terminal"
|
|
if a0 == "config" and len(argv) > 1 and argv[1].lower() == "edit":
|
|
return "`hermes config edit` needs $EDITOR in a real terminal"
|
|
return None
|
|
|
|
|
|
@method("cli.exec")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Run `python -m hermes_cli.main` with argv; capture stdout/stderr (non-interactive only)."""
|
|
argv = params.get("argv", [])
|
|
if not isinstance(argv, list) or not all(isinstance(x, str) for x in argv):
|
|
return _err(rid, 4003, "argv must be list[str]")
|
|
hint = _cli_exec_blocked(argv)
|
|
if hint:
|
|
return _ok(rid, {"blocked": True, "hint": hint, "code": -1, "output": ""})
|
|
try:
|
|
r = subprocess.run(
|
|
[sys.executable, "-m", "hermes_cli.main", *argv],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=min(int(params.get("timeout", 240)), 600),
|
|
cwd=os.getcwd(),
|
|
env=os.environ.copy(),
|
|
)
|
|
parts = [r.stdout or "", r.stderr or ""]
|
|
out = "\n".join(p for p in parts if p).strip() or "(no output)"
|
|
return _ok(
|
|
rid, {"blocked": False, "code": r.returncode, "output": out[:48_000]}
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return _err(rid, 5016, "cli.exec: timeout")
|
|
except Exception as e:
|
|
return _err(rid, 5017, str(e))
|
|
|
|
|
|
@method("command.resolve")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from hermes_cli.commands import resolve_command
|
|
|
|
r = resolve_command(params.get("name", ""))
|
|
if r:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"canonical": r.name,
|
|
"description": r.description,
|
|
"category": r.category,
|
|
},
|
|
)
|
|
return _err(rid, 4011, f"unknown command: {params.get('name')}")
|
|
except Exception as e:
|
|
return _err(rid, 5012, str(e))
|
|
|
|
|
|
def _resolve_name(name: str) -> str:
|
|
try:
|
|
from hermes_cli.commands import resolve_command
|
|
|
|
r = resolve_command(name)
|
|
return r.name if r else name
|
|
except Exception:
|
|
return name
|
|
|
|
|
|
@method("command.dispatch")
|
|
def _(rid, params: dict) -> dict:
|
|
name, arg = params.get("name", "").lstrip("/"), params.get("arg", "")
|
|
resolved = _resolve_name(name)
|
|
if resolved != name:
|
|
name = resolved
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
|
|
qcmds = _load_cfg().get("quick_commands", {})
|
|
if name in qcmds:
|
|
qc = qcmds[name]
|
|
if qc.get("type") == "exec":
|
|
r = subprocess.run(
|
|
qc.get("command", ""),
|
|
shell=True,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=30,
|
|
)
|
|
output = (
|
|
(r.stdout or "")
|
|
+ ("\n" if r.stdout and r.stderr else "")
|
|
+ (r.stderr or "")
|
|
).strip()[:4000]
|
|
if r.returncode != 0:
|
|
return _err(
|
|
rid,
|
|
4018,
|
|
output or f"quick command failed with exit code {r.returncode}",
|
|
)
|
|
return _ok(rid, {"type": "exec", "output": output})
|
|
if qc.get("type") == "alias":
|
|
return _ok(rid, {"type": "alias", "target": qc.get("target", "")})
|
|
|
|
try:
|
|
from hermes_cli.plugins import (
|
|
get_plugin_command_handler,
|
|
resolve_plugin_command_result,
|
|
)
|
|
|
|
handler = get_plugin_command_handler(name)
|
|
if handler:
|
|
result = resolve_plugin_command_result(handler(arg))
|
|
return _ok(rid, {"type": "plugin", "output": str(result or "")})
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
from agent.skill_commands import (
|
|
scan_skill_commands,
|
|
build_skill_invocation_message,
|
|
)
|
|
|
|
cmds = scan_skill_commands()
|
|
key = f"/{name}"
|
|
if key in cmds:
|
|
msg = build_skill_invocation_message(
|
|
key, arg, task_id=session.get("session_key", "") if session else ""
|
|
)
|
|
if msg:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"type": "skill",
|
|
"message": msg,
|
|
"name": cmds[key].get("name", name),
|
|
},
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
# ── Commands that queue messages onto _pending_input in the CLI ───
|
|
# In the TUI the slash worker subprocess has no reader for that queue,
|
|
# so we handle them here and return a structured payload.
|
|
|
|
if name in {"queue", "q"}:
|
|
if not arg:
|
|
return _err(rid, 4004, "usage: /queue <prompt>")
|
|
return _ok(rid, {"type": "send", "message": arg})
|
|
|
|
if name == "retry":
|
|
if not session:
|
|
return _err(rid, 4001, "no active session to retry")
|
|
if session.get("running"):
|
|
return _err(
|
|
rid, 4009, "session busy — /interrupt the current turn before /retry"
|
|
)
|
|
history = session.get("history", [])
|
|
if not history:
|
|
return _err(rid, 4018, "no previous user message to retry")
|
|
# Walk backwards to find the last user message
|
|
last_user_idx = None
|
|
for i in range(len(history) - 1, -1, -1):
|
|
if history[i].get("role") == "user":
|
|
last_user_idx = i
|
|
break
|
|
if last_user_idx is None:
|
|
return _err(rid, 4018, "no previous user message to retry")
|
|
content = history[last_user_idx].get("content", "")
|
|
if isinstance(content, list):
|
|
content = " ".join(
|
|
p.get("text", "")
|
|
for p in content
|
|
if isinstance(p, dict) and p.get("type") == "text"
|
|
)
|
|
if not content:
|
|
return _err(rid, 4018, "last user message is empty")
|
|
# Truncate history: remove everything from the last user message onward
|
|
# (mirrors CLI retry_last() which strips the failed exchange)
|
|
with session["history_lock"]:
|
|
session["history"] = history[:last_user_idx]
|
|
session["history_version"] = int(session.get("history_version", 0)) + 1
|
|
return _ok(rid, {"type": "send", "message": content})
|
|
|
|
if name == "steer":
|
|
if not arg:
|
|
return _err(rid, 4004, "usage: /steer <prompt>")
|
|
agent = session.get("agent") if session else None
|
|
if agent and hasattr(agent, "steer"):
|
|
try:
|
|
accepted = agent.steer(arg)
|
|
if accepted:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"type": "exec",
|
|
"output": f"⏩ Steer queued — arrives after the next tool call: {arg[:80]}{'...' if len(arg) > 80 else ''}",
|
|
},
|
|
)
|
|
except Exception:
|
|
pass
|
|
# Fallback: no active run, treat as next-turn message
|
|
return _ok(rid, {"type": "send", "message": arg})
|
|
|
|
if name == "goal":
|
|
if not session:
|
|
return _err(rid, 4001, "no active session")
|
|
try:
|
|
from hermes_cli.goals import GoalManager
|
|
except Exception as exc:
|
|
return _err(rid, 5030, f"goals unavailable: {exc}")
|
|
|
|
sid_key = session.get("session_key") or ""
|
|
if not sid_key:
|
|
return _err(rid, 4001, "no session key")
|
|
|
|
try:
|
|
goals_cfg = _load_cfg().get("goals") or {}
|
|
max_turns = int(goals_cfg.get("max_turns", 20) or 20)
|
|
except Exception:
|
|
max_turns = 20
|
|
mgr = GoalManager(session_id=sid_key, default_max_turns=max_turns)
|
|
|
|
lower = arg.strip().lower()
|
|
if not arg.strip() or lower == "status":
|
|
return _ok(rid, {"type": "exec", "output": mgr.status_line()})
|
|
if lower == "pause":
|
|
state = mgr.pause(reason="user-paused")
|
|
out = "No goal set." if state is None else f"⏸ Goal paused: {state.goal}"
|
|
return _ok(rid, {"type": "exec", "output": out})
|
|
if lower == "resume":
|
|
state = mgr.resume()
|
|
if state is None:
|
|
return _ok(rid, {"type": "exec", "output": "No goal to resume."})
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"type": "exec",
|
|
"output": (
|
|
f"▶ Goal resumed: {state.goal}\n"
|
|
"Send any message to continue, or wait — I'll take the next step on the next turn."
|
|
),
|
|
},
|
|
)
|
|
if lower in {"clear", "stop", "done"}:
|
|
had = mgr.has_goal()
|
|
mgr.clear()
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"type": "exec",
|
|
"output": "✓ Goal cleared." if had else "No active goal.",
|
|
},
|
|
)
|
|
|
|
# Otherwise — treat the remaining text as the new goal.
|
|
try:
|
|
state = mgr.set(arg)
|
|
except ValueError as exc:
|
|
return _err(rid, 4004, f"invalid goal: {exc}")
|
|
|
|
notice = (
|
|
f"⊙ Goal set ({state.max_turns}-turn budget): {state.goal}\n"
|
|
"I'll keep working until the goal is done, you pause/clear it, or the budget is exhausted.\n"
|
|
"Controls: /goal status · /goal pause · /goal resume · /goal clear"
|
|
)
|
|
# Send the goal text as the kickoff prompt. The TUI client sees
|
|
# {type: send, notice, message} → renders `notice` as a sys line,
|
|
# then submits `message` as a user turn. The post-turn judge
|
|
# wired in _run_prompt_submit takes over from there.
|
|
return _ok(
|
|
rid,
|
|
{"type": "send", "notice": notice, "message": state.goal},
|
|
)
|
|
|
|
if name in {"snapshot", "snap"}:
|
|
subcommand = arg.split(maxsplit=1)[0].lower() if arg else ""
|
|
if subcommand in {"restore", "rewind"}:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"type": "exec",
|
|
"output": (
|
|
"/snapshot restore is blocked in the TUI because it changes "
|
|
"config/state on disk while the live agent has cached settings. "
|
|
"Run it in the classic CLI, then restart the TUI."
|
|
),
|
|
},
|
|
)
|
|
|
|
return _err(rid, 4018, f"not a quick/plugin/skill command: {name}")
|
|
|
|
|
|
# ── Methods: paste ────────────────────────────────────────────────────
|
|
|
|
_paste_counter = 0
|
|
|
|
|
|
@method("paste.collapse")
|
|
def _(rid, params: dict) -> dict:
|
|
global _paste_counter
|
|
text = params.get("text", "")
|
|
if not text:
|
|
return _err(rid, 4004, "empty paste")
|
|
|
|
_paste_counter += 1
|
|
line_count = text.count("\n") + 1
|
|
paste_dir = _hermes_home / "pastes"
|
|
paste_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
from datetime import datetime
|
|
|
|
paste_file = (
|
|
paste_dir / f"paste_{_paste_counter}_{datetime.now().strftime('%H%M%S')}.txt"
|
|
)
|
|
paste_file.write_text(text, encoding="utf-8")
|
|
|
|
placeholder = (
|
|
f"[Pasted text #{_paste_counter}: {line_count} lines \u2192 {paste_file}]"
|
|
)
|
|
return _ok(
|
|
rid, {"placeholder": placeholder, "path": str(paste_file), "lines": line_count}
|
|
)
|
|
|
|
|
|
# ── Methods: complete ─────────────────────────────────────────────────
|
|
|
|
_FUZZY_CACHE_TTL_S = 5.0
|
|
_FUZZY_CACHE_MAX_FILES = 20000
|
|
_FUZZY_FALLBACK_EXCLUDES = frozenset(
|
|
{
|
|
".git",
|
|
".hg",
|
|
".svn",
|
|
".next",
|
|
".cache",
|
|
".venv",
|
|
"venv",
|
|
"node_modules",
|
|
"__pycache__",
|
|
"dist",
|
|
"build",
|
|
"target",
|
|
".mypy_cache",
|
|
".pytest_cache",
|
|
".ruff_cache",
|
|
}
|
|
)
|
|
_fuzzy_cache_lock = threading.Lock()
|
|
_fuzzy_cache: dict[str, tuple[float, list[str]]] = {}
|
|
|
|
|
|
def _list_repo_files(root: str) -> list[str]:
|
|
"""Return file paths relative to ``root``.
|
|
|
|
Uses ``git ls-files`` from the repo top (resolved via
|
|
``rev-parse --show-toplevel``) so the listing covers tracked + untracked
|
|
files anywhere in the repo, then converts each path back to be relative
|
|
to ``root``. Files outside ``root`` (parent directories of cwd, sibling
|
|
subtrees) are excluded so the picker stays scoped to what's reachable
|
|
from the gateway's cwd. Falls back to a bounded ``os.walk(root)`` when
|
|
``root`` isn't inside a git repo. Result cached per-root for
|
|
``_FUZZY_CACHE_TTL_S`` so rapid keystrokes don't respawn git processes.
|
|
"""
|
|
now = time.monotonic()
|
|
with _fuzzy_cache_lock:
|
|
cached = _fuzzy_cache.get(root)
|
|
if cached and now - cached[0] < _FUZZY_CACHE_TTL_S:
|
|
return cached[1]
|
|
|
|
files: list[str] = []
|
|
try:
|
|
top_result = subprocess.run(
|
|
["git", "-C", root, "rev-parse", "--show-toplevel"],
|
|
capture_output=True,
|
|
timeout=2.0,
|
|
check=False,
|
|
)
|
|
if top_result.returncode == 0:
|
|
top = top_result.stdout.decode("utf-8", "replace").strip()
|
|
list_result = subprocess.run(
|
|
[
|
|
"git",
|
|
"-C",
|
|
top,
|
|
"ls-files",
|
|
"-z",
|
|
"--cached",
|
|
"--others",
|
|
"--exclude-standard",
|
|
],
|
|
capture_output=True,
|
|
timeout=2.0,
|
|
check=False,
|
|
)
|
|
if list_result.returncode == 0:
|
|
for p in list_result.stdout.decode("utf-8", "replace").split("\0"):
|
|
if not p:
|
|
continue
|
|
rel = os.path.relpath(os.path.join(top, p), root).replace(
|
|
os.sep, "/"
|
|
)
|
|
# Skip parents/siblings of cwd — keep the picker scoped
|
|
# to root-and-below, matching Cmd-P workspace semantics.
|
|
if rel.startswith("../"):
|
|
continue
|
|
files.append(rel)
|
|
if len(files) >= _FUZZY_CACHE_MAX_FILES:
|
|
break
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
|
|
if not files:
|
|
# Fallback walk: skip vendor/build dirs + dot-dirs so the walk stays
|
|
# tractable. Dotfiles themselves survive — the ranker decides based
|
|
# on whether the query starts with `.`.
|
|
try:
|
|
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
dirnames[:] = [
|
|
d
|
|
for d in dirnames
|
|
if d not in _FUZZY_FALLBACK_EXCLUDES and not d.startswith(".")
|
|
]
|
|
rel_dir = os.path.relpath(dirpath, root)
|
|
for f in filenames:
|
|
rel = f if rel_dir == "." else f"{rel_dir}/{f}"
|
|
files.append(rel.replace(os.sep, "/"))
|
|
if len(files) >= _FUZZY_CACHE_MAX_FILES:
|
|
break
|
|
if len(files) >= _FUZZY_CACHE_MAX_FILES:
|
|
break
|
|
except OSError:
|
|
pass
|
|
|
|
with _fuzzy_cache_lock:
|
|
_fuzzy_cache[root] = (now, files)
|
|
|
|
return files
|
|
|
|
|
|
def _fuzzy_basename_rank(name: str, query: str) -> tuple[int, int] | None:
|
|
"""Rank ``name`` against ``query``; lower is better. Returns None to reject.
|
|
|
|
Tiers (kind):
|
|
0 — exact basename
|
|
1 — basename prefix (e.g. `app` → `appChrome.tsx`)
|
|
2 — word-boundary / camelCase hit (e.g. `chrome` → `appChrome.tsx`)
|
|
3 — substring anywhere in basename
|
|
4 — subsequence match (every query char appears in order)
|
|
|
|
Secondary key is `len(name)` so shorter names win ties.
|
|
"""
|
|
if not query:
|
|
return (3, len(name))
|
|
|
|
nl = name.lower()
|
|
ql = query.lower()
|
|
|
|
if nl == ql:
|
|
return (0, len(name))
|
|
|
|
if nl.startswith(ql):
|
|
return (1, len(name))
|
|
|
|
# Word-boundary split: `foo-bar_baz.qux` → ["foo","bar","baz","qux"].
|
|
# camelCase split: `appChrome` → ["app","Chrome"]. Cheap approximation;
|
|
# falls through to substring/subsequence if it misses.
|
|
parts: list[str] = []
|
|
buf = ""
|
|
for ch in name:
|
|
if ch in "-_." or (ch.isupper() and buf and not buf[-1].isupper()):
|
|
if buf:
|
|
parts.append(buf)
|
|
buf = ch if ch not in "-_." else ""
|
|
else:
|
|
buf += ch
|
|
if buf:
|
|
parts.append(buf)
|
|
for p in parts:
|
|
if p.lower().startswith(ql):
|
|
return (2, len(name))
|
|
|
|
if ql in nl:
|
|
return (3, len(name))
|
|
|
|
i = 0
|
|
for ch in nl:
|
|
if ch == ql[i]:
|
|
i += 1
|
|
if i == len(ql):
|
|
return (4, len(name))
|
|
|
|
return None
|
|
|
|
|
|
@method("complete.path")
|
|
def _(rid, params: dict) -> dict:
|
|
word = params.get("word", "")
|
|
if not word:
|
|
return _ok(rid, {"items": []})
|
|
|
|
items: list[dict] = []
|
|
try:
|
|
root = _completion_cwd(params)
|
|
is_context = word.startswith("@")
|
|
query = word[1:] if is_context else word
|
|
|
|
if is_context and not query:
|
|
items = [
|
|
{"text": "@diff", "display": "@diff", "meta": "git diff"},
|
|
{"text": "@staged", "display": "@staged", "meta": "staged diff"},
|
|
{"text": "@file:", "display": "@file:", "meta": "attach file"},
|
|
{"text": "@folder:", "display": "@folder:", "meta": "attach folder"},
|
|
{"text": "@url:", "display": "@url:", "meta": "fetch url"},
|
|
{"text": "@git:", "display": "@git:", "meta": "git log"},
|
|
]
|
|
return _ok(rid, {"items": items})
|
|
|
|
# Accept both `@folder:path` and the bare `@folder` form so the user
|
|
# sees directory listings as soon as they finish typing the keyword,
|
|
# without first accepting the static `@folder:` hint.
|
|
if is_context and query in {"file", "folder"}:
|
|
prefix_tag, path_part = query, ""
|
|
elif is_context and query.startswith(("file:", "folder:")):
|
|
prefix_tag, _, tail = query.partition(":")
|
|
path_part = tail
|
|
else:
|
|
prefix_tag = ""
|
|
path_part = query if is_context else query
|
|
|
|
# Fuzzy basename search across the repo when the user types a bare
|
|
# name with no path separator — `@appChrome` surfaces every file
|
|
# whose basename matches, regardless of directory depth. Matches what
|
|
# editors like Cursor / VS Code do for Cmd-P. Path-ish queries (with
|
|
# `/`, `./`, `~/`, `/abs`) fall through to the directory-listing
|
|
# path so explicit navigation intent is preserved.
|
|
if (
|
|
is_context
|
|
and path_part
|
|
and len(path_part.strip()) >= 2
|
|
and "/" not in path_part
|
|
and prefix_tag != "folder"
|
|
):
|
|
ranked: list[tuple[tuple[int, int], str, str]] = []
|
|
for rel in _list_repo_files(root):
|
|
basename = os.path.basename(rel)
|
|
if basename.startswith(".") and not path_part.startswith("."):
|
|
continue
|
|
rank = _fuzzy_basename_rank(basename, path_part)
|
|
if rank is None:
|
|
continue
|
|
ranked.append((rank, rel, basename))
|
|
|
|
ranked.sort(key=lambda r: (r[0], len(r[1]), r[1]))
|
|
tag = prefix_tag or "file"
|
|
for _, rel, basename in ranked[:30]:
|
|
items.append(
|
|
{
|
|
"text": f"@{tag}:{rel}",
|
|
"display": basename,
|
|
"meta": os.path.dirname(rel),
|
|
}
|
|
)
|
|
|
|
return _ok(rid, {"items": items})
|
|
|
|
expanded = _normalize_completion_path(path_part) if path_part else "."
|
|
if expanded == "." or not expanded:
|
|
search_dir, match = ".", ""
|
|
elif expanded.endswith("/"):
|
|
search_dir, match = expanded, ""
|
|
else:
|
|
search_dir = os.path.dirname(expanded) or "."
|
|
match = os.path.basename(expanded)
|
|
|
|
search_dir = (
|
|
search_dir if os.path.isabs(search_dir) else os.path.join(root, search_dir)
|
|
)
|
|
if not os.path.isdir(search_dir):
|
|
return _ok(rid, {"items": []})
|
|
|
|
want_dir = prefix_tag == "folder"
|
|
match_lower = match.lower()
|
|
for entry in sorted(os.listdir(search_dir)):
|
|
if match and not entry.lower().startswith(match_lower):
|
|
continue
|
|
if is_context and entry in _FUZZY_FALLBACK_EXCLUDES:
|
|
continue
|
|
if is_context and not prefix_tag and entry.startswith("."):
|
|
continue
|
|
full = os.path.join(search_dir, entry)
|
|
is_dir = os.path.isdir(full)
|
|
# Explicit `@folder:` / `@file:` — honour the user's filter. Skip
|
|
# the opposite kind instead of auto-rewriting the completion tag,
|
|
# which used to defeat the prefix and let `@folder:` list files.
|
|
if prefix_tag and want_dir != is_dir:
|
|
continue
|
|
rel = os.path.relpath(full, root).replace(os.sep, "/")
|
|
suffix = "/" if is_dir else ""
|
|
|
|
if is_context and prefix_tag:
|
|
text = f"@{prefix_tag}:{rel}{suffix}"
|
|
elif is_context:
|
|
kind = "folder" if is_dir else "file"
|
|
text = f"@{kind}:{rel}{suffix}"
|
|
elif word.startswith("~"):
|
|
text = "~/" + os.path.relpath(full, os.path.expanduser("~")) + suffix
|
|
elif word.startswith("./"):
|
|
text = "./" + rel + suffix
|
|
else:
|
|
text = rel + suffix
|
|
|
|
items.append(
|
|
{
|
|
"text": text,
|
|
"display": entry + suffix,
|
|
"meta": "dir" if is_dir else "",
|
|
}
|
|
)
|
|
if len(items) >= 30:
|
|
break
|
|
except Exception as e:
|
|
return _err(rid, 5021, str(e))
|
|
|
|
return _ok(rid, {"items": items})
|
|
|
|
|
|
def _details_completion_item(value: str, meta: str = "") -> dict:
|
|
return {"text": value, "display": value, "meta": meta}
|
|
|
|
|
|
def _details_root_completion_item(
|
|
value: str, meta: str, needs_leading_space: bool
|
|
) -> dict:
|
|
return _details_completion_item(
|
|
f" {value}" if needs_leading_space else value,
|
|
meta,
|
|
)
|
|
|
|
|
|
def _details_completions(text: str) -> list[dict] | None:
|
|
if not text.lower().startswith("/details"):
|
|
return None
|
|
|
|
stripped = text.strip()
|
|
if stripped and not "/details".startswith(stripped.lower().split()[0]):
|
|
return None
|
|
|
|
body = text[len("/details") :]
|
|
if body.startswith(" "):
|
|
body = body[1:]
|
|
parts = body.split()
|
|
has_trailing_space = text.endswith(" ")
|
|
sections = ("thinking", "tools", "subagents", "activity")
|
|
modes = ("hidden", "collapsed", "expanded")
|
|
|
|
if not body or (len(parts) == 0 and has_trailing_space):
|
|
return [
|
|
*[
|
|
_details_root_completion_item(
|
|
mode, "global mode", not has_trailing_space
|
|
)
|
|
for mode in modes
|
|
],
|
|
_details_root_completion_item(
|
|
"cycle", "cycle global mode", not has_trailing_space
|
|
),
|
|
*[
|
|
_details_root_completion_item(
|
|
section, "section override", not has_trailing_space
|
|
)
|
|
for section in sections
|
|
],
|
|
]
|
|
|
|
if len(parts) == 1 and not has_trailing_space:
|
|
prefix = parts[0].lower()
|
|
candidates = [*modes, "cycle", *sections]
|
|
return [
|
|
_details_completion_item(
|
|
candidate,
|
|
(
|
|
"section override"
|
|
if candidate in sections
|
|
else "cycle global mode" if candidate == "cycle" else "global mode"
|
|
),
|
|
)
|
|
for candidate in candidates
|
|
if candidate.startswith(prefix) and candidate != prefix
|
|
]
|
|
|
|
if len(parts) == 1 and has_trailing_space and parts[0].lower() in sections:
|
|
return [
|
|
*[
|
|
_details_completion_item(mode, f"set {parts[0].lower()}")
|
|
for mode in modes
|
|
],
|
|
_details_completion_item("reset", f"clear {parts[0].lower()} override"),
|
|
]
|
|
|
|
if len(parts) == 2 and not has_trailing_space and parts[0].lower() in sections:
|
|
prefix = parts[1].lower()
|
|
return [
|
|
_details_completion_item(
|
|
candidate,
|
|
(
|
|
f"clear {parts[0].lower()} override"
|
|
if candidate == "reset"
|
|
else f"set {parts[0].lower()}"
|
|
),
|
|
)
|
|
for candidate in (*modes, "reset")
|
|
if candidate.startswith(prefix) and candidate != prefix
|
|
]
|
|
|
|
return []
|
|
|
|
|
|
@method("complete.slash")
|
|
def _(rid, params: dict) -> dict:
|
|
text = params.get("text", "")
|
|
if not text.startswith("/"):
|
|
return _ok(rid, {"items": []})
|
|
|
|
try:
|
|
from hermes_cli.commands import SlashCommandCompleter
|
|
from prompt_toolkit.document import Document
|
|
from prompt_toolkit.formatted_text import to_plain_text
|
|
|
|
from agent.skill_commands import get_skill_commands
|
|
from agent.skill_bundles import get_skill_bundles
|
|
|
|
completer = SlashCommandCompleter(
|
|
skill_commands_provider=lambda: get_skill_commands(),
|
|
skill_bundles_provider=lambda: get_skill_bundles(),
|
|
)
|
|
doc = Document(text, len(text))
|
|
items = [
|
|
{
|
|
"text": c.text,
|
|
# prompt_toolkit gives us FormattedText (a list of (style,
|
|
# text) tuples) for display/display_meta. Serialize both as
|
|
# plain strings — the TUI's CompletionItem.display contract
|
|
# is a string, and sending the raw list trips Ink's row
|
|
# layout into 1-char truncation of the next column.
|
|
"display": to_plain_text(c.display) if c.display else c.text,
|
|
"meta": to_plain_text(c.display_meta) if c.display_meta else "",
|
|
}
|
|
for c in completer.get_completions(doc, None)
|
|
][:30]
|
|
text_lower = text.lower()
|
|
extras = [
|
|
{
|
|
"text": "/compact",
|
|
"display": "/compact",
|
|
"meta": "Toggle compact display mode",
|
|
},
|
|
{
|
|
"text": "/details",
|
|
"display": "/details",
|
|
"meta": "Control agent detail visibility",
|
|
},
|
|
{
|
|
"text": "/logs",
|
|
"display": "/logs",
|
|
"meta": "Show recent gateway log lines",
|
|
},
|
|
{
|
|
"text": "/mouse",
|
|
"display": "/mouse",
|
|
"meta": "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]",
|
|
},
|
|
]
|
|
for extra in extras:
|
|
if extra["text"].startswith(text_lower) and not any(
|
|
item["text"] == extra["text"] for item in items
|
|
):
|
|
items.append(extra)
|
|
|
|
details_items = _details_completions(text)
|
|
if details_items is not None:
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"items": details_items,
|
|
"replace_from": text.rfind(" ") + 1 if " " in text else len(text),
|
|
},
|
|
)
|
|
|
|
return _ok(
|
|
rid,
|
|
{"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5020, str(e))
|
|
|
|
|
|
@method("model.options")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from hermes_cli.inventory import build_models_payload, load_picker_context
|
|
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
agent = session.get("agent") if session else None
|
|
# Layer agent-session state on top of disk config — once an agent
|
|
# is spawned, IT owns the live provider/model/base_url. Empty
|
|
# agent attributes must NOT clobber disk config (with_overrides
|
|
# is truthy-only).
|
|
ctx = load_picker_context().with_overrides(
|
|
current_provider=getattr(agent, "provider", "") if agent else "",
|
|
current_model=(
|
|
(getattr(agent, "model", "") if agent else "") or _resolve_model()
|
|
),
|
|
current_base_url=getattr(agent, "base_url", "") if agent else "",
|
|
)
|
|
# picker_hints + canonical_order produce the TUI's required shape:
|
|
# `authenticated`/`auth_type`/`key_env`/`warning` per row, in
|
|
# CANONICAL_PROVIDERS declaration order. include_unconfigured=True
|
|
# so the picker can show the full provider universe (with the
|
|
# setup-hint warning attached) instead of only authed rows.
|
|
# Curated model lists are preserved — list_authenticated_providers
|
|
# populates `models` from the curated catalog, not provider_model_ids
|
|
# (which would pull non-agentic models like TTS/embeddings/etc.).
|
|
payload = build_models_payload(
|
|
ctx,
|
|
include_unconfigured=True,
|
|
picker_hints=True,
|
|
canonical_order=True,
|
|
pricing=True,
|
|
max_models=50,
|
|
)
|
|
return _ok(rid, payload)
|
|
except Exception as e:
|
|
return _err(rid, 5033, str(e))
|
|
|
|
|
|
@method("model.save_key")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Save an API key for a provider, then return its refreshed model list.
|
|
|
|
Params:
|
|
slug: provider slug (e.g. "deepseek", "xai")
|
|
api_key: the key value to save
|
|
|
|
Returns the provider dict with models populated (same shape as
|
|
model.options entries) on success.
|
|
"""
|
|
try:
|
|
from hermes_cli.auth import PROVIDER_REGISTRY
|
|
from hermes_cli.config import is_managed, save_env_value
|
|
from hermes_cli.inventory import build_models_payload, load_picker_context
|
|
|
|
slug = (params.get("slug") or "").strip()
|
|
api_key = (params.get("api_key") or "").strip()
|
|
if not slug or not api_key:
|
|
return _err(rid, 4001, "slug and api_key are required")
|
|
|
|
if is_managed():
|
|
return _err(rid, 4006, "managed install — credentials are read-only")
|
|
|
|
pconfig = PROVIDER_REGISTRY.get(slug)
|
|
if not pconfig:
|
|
return _err(rid, 4002, f"unknown provider: {slug}")
|
|
if pconfig.auth_type != "api_key":
|
|
return _err(
|
|
rid,
|
|
4003,
|
|
f"{pconfig.name} uses {pconfig.auth_type} auth — "
|
|
f"run `hermes model` to configure",
|
|
)
|
|
if not pconfig.api_key_env_vars:
|
|
return _err(rid, 4004, f"no env var defined for {pconfig.name}")
|
|
|
|
# Save the key to ~/.hermes/.env
|
|
env_var = pconfig.api_key_env_vars[0]
|
|
save_env_value(env_var, api_key)
|
|
# Also set in current process so the refreshed inventory sees it.
|
|
import os
|
|
|
|
os.environ[env_var] = api_key
|
|
|
|
# Refresh provider data via the shared inventory builder so this
|
|
# surface stays in lock-step with model.options + dashboard
|
|
# /api/model/options. picker_hints=True ensures the returned row
|
|
# carries `authenticated` for the TUI frontend.
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
agent = session.get("agent") if session else None
|
|
ctx = load_picker_context().with_overrides(
|
|
current_provider=getattr(agent, "provider", "") if agent else "",
|
|
current_model=(
|
|
(getattr(agent, "model", "") if agent else "") or _resolve_model()
|
|
),
|
|
current_base_url=getattr(agent, "base_url", "") if agent else "",
|
|
)
|
|
payload = build_models_payload(
|
|
ctx, picker_hints=True, max_models=50,
|
|
)
|
|
provider_data = next(
|
|
(p for p in payload["providers"] if p["slug"] == slug), None
|
|
)
|
|
if provider_data is None:
|
|
# Key was saved but provider didn't appear — still return success.
|
|
provider_data = {
|
|
"slug": slug,
|
|
"name": pconfig.name,
|
|
"is_current": False,
|
|
"models": [],
|
|
"total_models": 0,
|
|
"authenticated": True,
|
|
}
|
|
# picker_hints sets `authenticated` from the row state, but the
|
|
# synthetic fallback above doesn't go through that path.
|
|
provider_data["authenticated"] = True
|
|
return _ok(rid, {"provider": provider_data})
|
|
except Exception as e:
|
|
return _err(rid, 5034, str(e))
|
|
|
|
|
|
@method("model.disconnect")
|
|
def _(rid, params: dict) -> dict:
|
|
"""Remove credentials for a provider.
|
|
|
|
Params:
|
|
slug: provider slug (e.g. "deepseek", "xai")
|
|
|
|
Returns success status and the provider's slug.
|
|
"""
|
|
try:
|
|
from hermes_cli.auth import PROVIDER_REGISTRY, clear_provider_auth
|
|
from hermes_cli.config import remove_env_value
|
|
|
|
slug = (params.get("slug") or "").strip()
|
|
if not slug:
|
|
return _err(rid, 4001, "slug is required")
|
|
|
|
pconfig = PROVIDER_REGISTRY.get(slug)
|
|
cleared_env = False
|
|
cleared_auth = False
|
|
|
|
# Remove API key env vars from .env and process
|
|
if pconfig and pconfig.api_key_env_vars:
|
|
for ev in pconfig.api_key_env_vars:
|
|
if remove_env_value(ev):
|
|
cleared_env = True
|
|
|
|
# Clear OAuth / credential pool state
|
|
cleared_auth = clear_provider_auth(slug)
|
|
|
|
if not cleared_env and not cleared_auth:
|
|
return _err(rid, 4005, f"no credentials found for {slug}")
|
|
|
|
provider_name = pconfig.name if pconfig else slug
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"slug": slug,
|
|
"name": provider_name,
|
|
"disconnected": True,
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5035, str(e))
|
|
|
|
|
|
# ── Methods: slash.exec ──────────────────────────────────────────────
|
|
|
|
|
|
def _mirror_slash_side_effects(sid: str, session: dict, command: str) -> str:
|
|
"""Apply side effects that must also hit the gateway's live agent."""
|
|
parts = command.lstrip("/").split(None, 1)
|
|
if not parts:
|
|
return ""
|
|
name, arg, agent = (
|
|
parts[0],
|
|
(parts[1].strip() if len(parts) > 1 else ""),
|
|
session.get("agent"),
|
|
)
|
|
|
|
# Reject agent-mutating commands during an in-flight turn. These
|
|
# all do read-then-mutate on live agent/session state that the
|
|
# worker thread running agent.run_conversation is using. Parity
|
|
# with the session.compress / session.undo guards and the gateway
|
|
# runner's running-agent /model guard.
|
|
_MUTATES_WHILE_RUNNING = {"model", "personality", "prompt", "compress"}
|
|
if name in _MUTATES_WHILE_RUNNING and session.get("running"):
|
|
return f"session busy — /interrupt the current turn before running /{name}"
|
|
|
|
try:
|
|
if name == "model" and arg and agent:
|
|
result = _apply_model_switch(sid, session, arg)
|
|
return result.get("warning", "")
|
|
elif name == "personality" and arg and agent:
|
|
pname, new_prompt = _validate_personality(arg, _load_cfg())
|
|
_apply_personality_to_session(sid, session, new_prompt, pname)
|
|
elif name == "prompt" and agent:
|
|
cfg = _load_cfg()
|
|
new_prompt = _prompt_text((cfg.get("agent") or {}).get("system_prompt", ""))
|
|
agent.ephemeral_system_prompt = new_prompt or None
|
|
agent._cached_system_prompt = None
|
|
elif name == "compress" and agent:
|
|
_compress_session_history(session, arg)
|
|
_sync_session_key_after_compress(sid, session)
|
|
_emit("session.info", sid, _session_info(agent, session))
|
|
elif name == "fast" and agent:
|
|
mode = arg.lower()
|
|
if mode in {"fast", "on"}:
|
|
agent.service_tier = "priority"
|
|
elif mode in {"normal", "off"}:
|
|
agent.service_tier = None
|
|
_emit("session.info", sid, _session_info(agent, session))
|
|
elif name == "reload-mcp" and agent and hasattr(agent, "reload_mcp_tools"):
|
|
agent.reload_mcp_tools()
|
|
elif name == "stop":
|
|
from tools.process_registry import process_registry
|
|
|
|
process_registry.kill_all()
|
|
except Exception as e:
|
|
return f"live session sync failed: {e}"
|
|
return ""
|
|
|
|
|
|
@method("slash.exec")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
|
|
cmd = params.get("command", "").strip()
|
|
if not cmd:
|
|
return _err(rid, 4004, "empty command")
|
|
|
|
# Skill slash commands and _pending_input commands must NOT go through the
|
|
# slash worker — see _PENDING_INPUT_COMMANDS definition above. Plugin
|
|
# commands must also avoid the worker, but unlike skills/pending-input they
|
|
# still return normal slash.exec output so the TUI keeps the pager path.
|
|
_cmd_text = cmd.lstrip("/") if cmd.startswith("/") else cmd
|
|
_cmd_parts = _cmd_text.split(maxsplit=1)
|
|
_cmd_base = (_cmd_parts[0] if _cmd_parts else "").lower()
|
|
_cmd_arg = _cmd_parts[1] if len(_cmd_parts) > 1 else ""
|
|
|
|
if _cmd_base in _PENDING_INPUT_COMMANDS:
|
|
return _err(
|
|
rid, 4018, f"pending-input command: use command.dispatch for /{_cmd_base}"
|
|
)
|
|
|
|
if _cmd_base in _WORKER_BLOCKED_COMMANDS:
|
|
subcommand = _cmd_arg.split(maxsplit=1)[0].lower() if _cmd_arg else ""
|
|
if subcommand in {"restore", "rewind"}:
|
|
return _err(
|
|
rid,
|
|
4018,
|
|
"snapshot restore mutates live config/state; use command.dispatch for /snapshot restore",
|
|
)
|
|
|
|
try:
|
|
from agent.skill_commands import get_skill_commands
|
|
|
|
_cmd_key = f"/{_cmd_base}"
|
|
if _cmd_key in get_skill_commands():
|
|
return _err(
|
|
rid, 4018, f"skill command: use command.dispatch for {_cmd_key}"
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
plugin_handler = None
|
|
resolve_plugin_command_result = None
|
|
if _cmd_base:
|
|
try:
|
|
from hermes_cli.plugins import (
|
|
get_plugin_command_handler,
|
|
resolve_plugin_command_result,
|
|
)
|
|
|
|
plugin_handler = get_plugin_command_handler(_cmd_base)
|
|
except Exception:
|
|
plugin_handler = None
|
|
resolve_plugin_command_result = None
|
|
|
|
if plugin_handler and resolve_plugin_command_result:
|
|
try:
|
|
result = resolve_plugin_command_result(plugin_handler(_cmd_arg))
|
|
return _ok(rid, {"output": str(result or "(no output)")})
|
|
except Exception as e:
|
|
return _ok(rid, {"output": f"Plugin command error: {e}"})
|
|
|
|
worker = session.get("slash_worker")
|
|
if not worker:
|
|
try:
|
|
worker = _SlashWorker(
|
|
session["session_key"],
|
|
getattr(session.get("agent"), "model", _resolve_model()),
|
|
)
|
|
session["slash_worker"] = worker
|
|
except Exception as e:
|
|
return _err(rid, 5030, f"slash worker start failed: {e}")
|
|
|
|
try:
|
|
output = worker.run(cmd)
|
|
warning = _mirror_slash_side_effects(params.get("session_id", ""), session, cmd)
|
|
payload = {"output": output or "(no output)"}
|
|
if warning:
|
|
payload["warning"] = warning
|
|
return _ok(rid, payload)
|
|
except Exception as e:
|
|
try:
|
|
worker.close()
|
|
except Exception:
|
|
pass
|
|
session["slash_worker"] = None
|
|
return _err(rid, 5030, str(e))
|
|
|
|
|
|
# ── Methods: voice ───────────────────────────────────────────────────
|
|
|
|
|
|
_voice_sid_lock = threading.Lock()
|
|
_voice_event_sid: str = ""
|
|
|
|
|
|
def _voice_emit(event: str, payload: dict | None = None) -> None:
|
|
"""Emit a voice event toward the session that most recently turned the
|
|
mode on. Voice is process-global (one microphone), so there's only ever
|
|
one sid to target; the TUI handler treats an empty sid as "active
|
|
session". Kept separate from _emit to make the lack of per-call sid
|
|
argument explicit."""
|
|
with _voice_sid_lock:
|
|
sid = _voice_event_sid
|
|
_emit(event, sid, payload)
|
|
|
|
|
|
def _voice_mode_enabled() -> bool:
|
|
"""Current voice-mode flag (runtime-only, CLI parity).
|
|
|
|
cli.py initialises ``_voice_mode = False`` at startup and only flips
|
|
it via ``/voice on``; it never reads a persisted enable bit from
|
|
config.yaml. We match that: no config lookup, env var only. This
|
|
avoids the TUI auto-starting in REC the next time the user opens it
|
|
just because they happened to enable voice in a prior session.
|
|
"""
|
|
return os.environ.get("HERMES_VOICE", "").strip() == "1"
|
|
|
|
|
|
def _voice_tts_enabled() -> bool:
|
|
"""Whether agent replies should be spoken back via TTS (runtime only)."""
|
|
return os.environ.get("HERMES_VOICE_TTS", "").strip() == "1"
|
|
|
|
|
|
def _voice_cfg_dict() -> dict:
|
|
"""Shape-safe accessor for the ``voice:`` block in config.yaml.
|
|
|
|
``_load_cfg()`` returns raw ``yaml.safe_load()`` output, so both the
|
|
root AND ``voice`` may be any YAML scalar / list / None. A hand-edit
|
|
like ``voice: true`` or a malformed top-level config that parses to
|
|
a scalar would otherwise break ``.get("…")`` and take every
|
|
``voice.*`` branch down with it (Copilot round-3..7 review on
|
|
#19835). Coerce through ``isinstance`` at every level so malformed
|
|
config falls back to an empty dict instead of crashing /voice.
|
|
"""
|
|
cfg = _load_cfg()
|
|
voice_cfg = cfg.get("voice") if isinstance(cfg, dict) else None
|
|
|
|
return voice_cfg if isinstance(voice_cfg, dict) else {}
|
|
|
|
|
|
def _voice_record_key() -> str:
|
|
"""Current ``voice.record_key`` value, documented default on error."""
|
|
record_key = _voice_cfg_dict().get("record_key")
|
|
|
|
return str(record_key) if isinstance(record_key, str) and record_key else "ctrl+b"
|
|
|
|
|
|
@method("voice.toggle")
|
|
def _(rid, params: dict) -> dict:
|
|
"""CLI parity for the ``/voice`` slash command.
|
|
|
|
Subcommands:
|
|
|
|
* ``status`` — report mode + TTS flags (default when action is unknown).
|
|
* ``on`` / ``off`` — flip voice *mode* (the umbrella bit). Turning it
|
|
off also tears down any active continuous recording loop. Does NOT
|
|
start recording on its own; recording is driven by ``voice.record``
|
|
(Ctrl+B) after mode is on, matching cli.py's enable/Ctrl+B split.
|
|
* ``tts`` — toggle speech-output of agent replies. Requires mode on
|
|
(mirrors CLI's _toggle_voice_tts guard).
|
|
"""
|
|
action = params.get("action", "status")
|
|
|
|
if action == "status":
|
|
# Mirror CLI's _show_voice_status: include STT/TTS provider
|
|
# availability so the user can tell at a glance *why* voice mode
|
|
# isn't working ("STT provider: MISSING ..." is the common case).
|
|
# ``record_key`` mirrors the configured ``voice.record_key`` so the
|
|
# TUI can both bind it (frontend ``isVoiceToggleKey``) and display
|
|
# it in /voice status — previously the TUI hardcoded Ctrl+B and
|
|
# ignored the config (#18994).
|
|
payload: dict = {
|
|
"enabled": _voice_mode_enabled(),
|
|
"record_key": _voice_record_key(),
|
|
"tts": _voice_tts_enabled(),
|
|
}
|
|
try:
|
|
from tools.voice_mode import check_voice_requirements
|
|
|
|
reqs = check_voice_requirements()
|
|
payload["available"] = bool(reqs.get("available"))
|
|
payload["audio_available"] = bool(reqs.get("audio_available"))
|
|
payload["stt_available"] = bool(reqs.get("stt_available"))
|
|
payload["details"] = reqs.get("details") or ""
|
|
except Exception as e:
|
|
# check_voice_requirements pulls optional transcription deps —
|
|
# swallow so /voice status always returns something useful.
|
|
logger.warning("voice.toggle status: requirements probe failed: %s", e)
|
|
|
|
return _ok(rid, payload)
|
|
|
|
if action in {"on", "off"}:
|
|
enabled = action == "on"
|
|
# Runtime-only flag (CLI parity) — no _write_config_key, so the
|
|
# next TUI launch starts with voice OFF instead of auto-REC from a
|
|
# persisted stale toggle.
|
|
os.environ["HERMES_VOICE"] = "1" if enabled else "0"
|
|
|
|
if not enabled:
|
|
# Disabling the mode must tear the continuous loop down; the
|
|
# loop holds the microphone and would otherwise keep running.
|
|
try:
|
|
from hermes_cli.voice import stop_continuous
|
|
|
|
stop_continuous()
|
|
except ImportError:
|
|
pass
|
|
except Exception as e:
|
|
logger.warning("voice: stop_continuous failed during toggle off: %s", e)
|
|
|
|
# Clear TTS so it can be toggled independently after voice is off.
|
|
os.environ["HERMES_VOICE_TTS"] = "0"
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"enabled": enabled,
|
|
"record_key": _voice_record_key(),
|
|
"tts": _voice_tts_enabled(),
|
|
},
|
|
)
|
|
|
|
if action == "tts":
|
|
if not _voice_mode_enabled():
|
|
return _err(rid, 4014, "enable voice mode first: /voice on")
|
|
new_value = not _voice_tts_enabled()
|
|
# Runtime-only flag (CLI parity) — see voice.toggle on/off above.
|
|
os.environ["HERMES_VOICE_TTS"] = "1" if new_value else "0"
|
|
# Include ``record_key`` on every branch so a /voice tts toggle
|
|
# doesn't reset the TUI's cached shortcut to the default when a
|
|
# user has a custom binding configured (Copilot review, round 2
|
|
# on #19835). Keeps parity with the status/on/off branches above.
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"enabled": True,
|
|
"record_key": _voice_record_key(),
|
|
"tts": new_value,
|
|
},
|
|
)
|
|
|
|
return _err(rid, 4013, f"unknown voice action: {action}")
|
|
|
|
|
|
@method("voice.record")
|
|
def _(rid, params: dict) -> dict:
|
|
"""VAD-bounded push-to-talk capture, CLI-parity.
|
|
|
|
``start`` begins one VAD-bounded capture and emits ``voice.transcript``
|
|
after silence stops the recorder. ``stop`` forces transcription of the
|
|
active buffer, matching classic CLI push-to-talk. The voice wrapper retains
|
|
no-speech counts across single-shot starts, so three consecutive silent
|
|
captures emit ``voice.transcript`` with ``no_speech_limit=True``.
|
|
"""
|
|
action = params.get("action", "start")
|
|
|
|
if action not in {"start", "stop"}:
|
|
return _err(rid, 4019, f"unknown voice action: {action}")
|
|
|
|
try:
|
|
if action == "start":
|
|
if not _voice_mode_enabled():
|
|
return _err(rid, 4015, "voice mode is off — enable with /voice on")
|
|
|
|
with _voice_sid_lock:
|
|
global _voice_event_sid
|
|
_voice_event_sid = params.get("session_id") or _voice_event_sid
|
|
|
|
from hermes_cli.voice import start_continuous
|
|
|
|
# Shape-safe lookups: malformed ``voice:`` YAML (bool/scalar/list)
|
|
# must not crash /voice with a 5025 — fall back to VAD defaults.
|
|
#
|
|
# Exclude ``bool`` from the numeric check since Python's bool is
|
|
# a subclass of int — a hand-edit like ``silence_threshold: true``
|
|
# would otherwise forward as ``1`` instead of falling back to
|
|
# the documented 200 / 3.0 defaults (Copilot round-12 on #19835).
|
|
voice_cfg = _voice_cfg_dict()
|
|
threshold = voice_cfg.get("silence_threshold")
|
|
duration = voice_cfg.get("silence_duration")
|
|
safe_threshold = (
|
|
threshold
|
|
if isinstance(threshold, (int, float))
|
|
and not isinstance(threshold, bool)
|
|
else 200
|
|
)
|
|
safe_duration = (
|
|
duration
|
|
if isinstance(duration, (int, float)) and not isinstance(duration, bool)
|
|
else 3.0
|
|
)
|
|
started = start_continuous(
|
|
on_transcript=lambda t: _voice_emit("voice.transcript", {"text": t}),
|
|
on_status=lambda s: _voice_emit("voice.status", {"state": s}),
|
|
on_silent_limit=lambda: _voice_emit(
|
|
"voice.transcript", {"no_speech_limit": True}
|
|
),
|
|
silence_threshold=safe_threshold,
|
|
silence_duration=safe_duration,
|
|
auto_restart=False,
|
|
)
|
|
if started is False:
|
|
return _ok(rid, {"status": "busy"})
|
|
return _ok(rid, {"status": "recording"})
|
|
|
|
# action == "stop"
|
|
with _voice_sid_lock:
|
|
_voice_event_sid = params.get("session_id") or _voice_event_sid
|
|
|
|
from hermes_cli.voice import stop_continuous
|
|
|
|
stop_continuous(force_transcribe=True)
|
|
return _ok(rid, {"status": "stopped"})
|
|
except ImportError:
|
|
return _err(
|
|
rid, 5025, "voice module not available — install audio dependencies"
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5025, str(e))
|
|
|
|
|
|
@method("voice.tts")
|
|
def _(rid, params: dict) -> dict:
|
|
text = params.get("text", "")
|
|
if not text:
|
|
return _err(rid, 4020, "text required")
|
|
try:
|
|
from hermes_cli.voice import speak_text
|
|
|
|
threading.Thread(target=speak_text, args=(text,), daemon=True).start()
|
|
return _ok(rid, {"status": "speaking"})
|
|
except ImportError:
|
|
return _err(rid, 5026, "voice module not available")
|
|
except Exception as e:
|
|
return _err(rid, 5026, str(e))
|
|
|
|
|
|
# ── Methods: insights ────────────────────────────────────────────────
|
|
|
|
|
|
@method("insights.get")
|
|
def _(rid, params: dict) -> dict:
|
|
days = params.get("days", 30)
|
|
db = _get_db()
|
|
if db is None:
|
|
return _db_unavailable_error(rid, code=5017)
|
|
try:
|
|
cutoff = time.time() - days * 86400
|
|
rows = [
|
|
s
|
|
for s in db.list_sessions_rich(limit=500)
|
|
if (s.get("started_at") or 0) >= cutoff
|
|
]
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"days": days,
|
|
"sessions": len(rows),
|
|
"messages": sum(s.get("message_count", 0) for s in rows),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5017, str(e))
|
|
|
|
|
|
# ── Methods: rollback ────────────────────────────────────────────────
|
|
|
|
|
|
@method("rollback.list")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
try:
|
|
|
|
def go(mgr, cwd):
|
|
if not mgr.enabled:
|
|
return _ok(rid, {"enabled": False, "checkpoints": []})
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"enabled": True,
|
|
"checkpoints": [
|
|
{
|
|
"hash": c.get("hash", ""),
|
|
"timestamp": c.get("timestamp", ""),
|
|
"message": c.get("message", ""),
|
|
}
|
|
for c in mgr.list_checkpoints(cwd)
|
|
],
|
|
},
|
|
)
|
|
|
|
return _with_checkpoints(session, go)
|
|
except Exception as e:
|
|
return _err(rid, 5020, str(e))
|
|
|
|
|
|
@method("rollback.restore")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
target = params.get("hash", "")
|
|
file_path = params.get("file_path", "")
|
|
if not target:
|
|
return _err(rid, 4014, "hash required")
|
|
# Full-history rollback mutates session history. Rejecting during
|
|
# an in-flight turn prevents prompt.submit from silently dropping
|
|
# the agent's output (version mismatch path) or clobbering the
|
|
# rollback (version-matches path). A file-scoped rollback only
|
|
# touches disk, so we allow it.
|
|
if not file_path and session.get("running"):
|
|
return _err(
|
|
rid,
|
|
4009,
|
|
"session busy — /interrupt the current turn before full rollback.restore",
|
|
)
|
|
try:
|
|
|
|
def go(mgr, cwd):
|
|
resolved = _resolve_checkpoint_hash(mgr, cwd, target)
|
|
result = mgr.restore(cwd, resolved, file_path=file_path or None)
|
|
if result.get("success") and not file_path:
|
|
removed = 0
|
|
with session["history_lock"]:
|
|
history = session.get("history", [])
|
|
while history and history[-1].get("role") in {"assistant", "tool"}:
|
|
history.pop()
|
|
removed += 1
|
|
if history and history[-1].get("role") == "user":
|
|
history.pop()
|
|
removed += 1
|
|
if removed:
|
|
session["history_version"] = (
|
|
int(session.get("history_version", 0)) + 1
|
|
)
|
|
result["history_removed"] = removed
|
|
return result
|
|
|
|
return _ok(rid, _with_checkpoints(session, go))
|
|
except Exception as e:
|
|
return _err(rid, 5021, str(e))
|
|
|
|
|
|
@method("rollback.diff")
|
|
def _(rid, params: dict) -> dict:
|
|
session, err = _sess(params, rid)
|
|
if err:
|
|
return err
|
|
target = params.get("hash", "")
|
|
if not target:
|
|
return _err(rid, 4014, "hash required")
|
|
try:
|
|
r = _with_checkpoints(
|
|
session,
|
|
lambda mgr, cwd: mgr.diff(cwd, _resolve_checkpoint_hash(mgr, cwd, target)),
|
|
)
|
|
raw = r.get("diff", "")[:4000]
|
|
payload = {"stat": r.get("stat", ""), "diff": raw}
|
|
rendered = render_diff(raw, session.get("cols", 80))
|
|
if rendered:
|
|
payload["rendered"] = rendered
|
|
return _ok(rid, payload)
|
|
except Exception as e:
|
|
return _err(rid, 5022, str(e))
|
|
|
|
|
|
# ── Methods: browser / plugins / cron / skills ───────────────────────
|
|
|
|
|
|
def _resolve_browser_cdp_url() -> str:
|
|
"""Return the configured browser CDP override without network I/O.
|
|
|
|
``/browser status`` must be fast — calling
|
|
``tools.browser_tool._get_cdp_override`` would invoke
|
|
``_resolve_cdp_override``, which performs an HTTP probe to
|
|
``.../json/version`` for discovery-style URLs. That probe has
|
|
a multi-second timeout and would block the TUI on a slow or
|
|
unreachable host even though status only needs to report whether
|
|
an override is set.
|
|
|
|
Mirrors the env/config precedence of ``_get_cdp_override`` (env
|
|
var first, then ``browser.cdp_url`` from config.yaml) without the
|
|
websocket-resolution step, so the answer reflects user intent
|
|
even when the configured host is not currently reachable. The
|
|
actual WS normalization happens in ``browser_navigate`` on the
|
|
next tool call.
|
|
"""
|
|
env_url = os.environ.get("BROWSER_CDP_URL", "").strip()
|
|
if env_url:
|
|
return env_url
|
|
try:
|
|
from hermes_cli.config import read_raw_config
|
|
|
|
cfg = read_raw_config()
|
|
browser_cfg = cfg.get("browser", {}) if isinstance(cfg, dict) else {}
|
|
if isinstance(browser_cfg, dict):
|
|
return str(browser_cfg.get("cdp_url", "") or "").strip()
|
|
except Exception:
|
|
pass
|
|
return ""
|
|
|
|
|
|
def _is_default_local_cdp(parsed) -> bool:
|
|
"""Match the discovery-style local default; never the concrete WS form.
|
|
|
|
A user-supplied ``ws://127.0.0.1:9222/devtools/browser/<id>`` is a
|
|
real, connectable endpoint — collapsing it to bare ``http://...:9222``
|
|
would strip the path and break the connect.
|
|
"""
|
|
try:
|
|
port = parsed.port or 80
|
|
except ValueError:
|
|
return False
|
|
|
|
discovery_path = parsed.path in {"", "/", "/json", "/json/version"}
|
|
return (
|
|
parsed.scheme in {"http", "ws"}
|
|
and parsed.hostname in {"127.0.0.1", "localhost"}
|
|
and port == 9222
|
|
and discovery_path
|
|
)
|
|
|
|
|
|
def _http_ok(url: str, timeout: float) -> bool:
|
|
import urllib.request
|
|
|
|
try:
|
|
with urllib.request.urlopen(url, timeout=timeout) as resp:
|
|
return 200 <= getattr(resp, "status", 200) < 300
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def _probe_urls(parsed) -> list[str]:
|
|
scheme = {"ws": "http", "wss": "https"}.get(parsed.scheme, parsed.scheme)
|
|
root = f"{scheme}://{parsed.netloc}".rstrip("/")
|
|
return [f"{root}/json/version", f"{root}/json"]
|
|
|
|
|
|
def _normalize_cdp_url(parsed) -> str:
|
|
# Concrete ``/devtools/browser/<id>`` endpoints (Browserbase et al.)
|
|
# are connectable as-is. Discovery-style inputs collapse to bare
|
|
# ``scheme://host:port`` so ``_resolve_cdp_override`` can append
|
|
# ``/json/version`` later without doubling the path.
|
|
if parsed.path.startswith("/devtools/browser/"):
|
|
return parsed.geturl()
|
|
return parsed._replace(path="", params="", query="", fragment="").geturl()
|
|
|
|
|
|
def _failure_messages(url: str, port: int, system: str) -> list[str]:
|
|
from hermes_cli.browser_connect import manual_chrome_debug_command
|
|
|
|
command = manual_chrome_debug_command(port, system)
|
|
hint = (
|
|
["Start a Chromium-family browser with remote debugging, then retry /browser connect:", command]
|
|
if command
|
|
else [
|
|
"No supported Chromium-family browser executable was found in this environment.",
|
|
f"Install one or start a Chromium-family browser with --remote-debugging-port={port}, then retry /browser connect.",
|
|
]
|
|
)
|
|
return [
|
|
f"Browser CDP is not reachable at {url}.",
|
|
*hint,
|
|
"Browser not connected — start a Chromium-family browser with remote debugging and retry /browser connect",
|
|
]
|
|
|
|
|
|
@method("browser.manage")
|
|
def _(rid, params: dict) -> dict:
|
|
action = params.get("action", "status")
|
|
|
|
if action == "status":
|
|
url = _resolve_browser_cdp_url()
|
|
return _ok(rid, {"connected": bool(url), "url": url})
|
|
|
|
if action == "disconnect":
|
|
return _browser_disconnect(rid)
|
|
|
|
if action != "connect":
|
|
return _err(rid, 4015, f"unknown action: {action}")
|
|
|
|
return _browser_connect(rid, params)
|
|
|
|
|
|
def _browser_connect(rid, params: dict) -> dict:
|
|
import platform
|
|
|
|
from hermes_cli.browser_connect import DEFAULT_BROWSER_CDP_URL
|
|
from tools.browser_tool import cleanup_all_browsers
|
|
from urllib.parse import urlparse
|
|
|
|
raw_url = params.get("url")
|
|
if raw_url is not None and not isinstance(raw_url, str):
|
|
return _err(
|
|
rid, 4015, f"browser url must be a string, got {type(raw_url).__name__}"
|
|
)
|
|
url = (raw_url or "").strip() or DEFAULT_BROWSER_CDP_URL
|
|
|
|
sid = params.get("session_id") or ""
|
|
system = platform.system()
|
|
messages: list[str] = []
|
|
|
|
def announce(message: str, *, level: str = "info") -> None:
|
|
messages.append(message)
|
|
# Without a session id the TUI prints `messages` from the
|
|
# response; emitting an event would double-render. Only stream
|
|
# progress when there's a real session to scope it to.
|
|
if sid:
|
|
_emit("browser.progress", sid, {"message": message, "level": level})
|
|
|
|
parsed = urlparse(url if "://" in url else f"http://{url}")
|
|
if parsed.scheme not in {"http", "https", "ws", "wss"}:
|
|
return _err(rid, 4015, f"unsupported browser url: {url}")
|
|
if not parsed.hostname:
|
|
return _err(rid, 4015, f"missing host in browser url: {url}")
|
|
try:
|
|
port = parsed.port or (443 if parsed.scheme in {"https", "wss"} else 80)
|
|
except ValueError:
|
|
return _err(rid, 4015, f"invalid port in browser url: {url}")
|
|
|
|
# Always normalize default-local to 127.0.0.1:9222 so downstream
|
|
# comparisons + messaging match what we'll actually persist.
|
|
if _is_default_local_cdp(parsed):
|
|
url = DEFAULT_BROWSER_CDP_URL
|
|
parsed = urlparse(url)
|
|
port = parsed.port or 9222
|
|
|
|
try:
|
|
# ws[s]://.../devtools/browser/<id> endpoints (hosted CDP
|
|
# providers) don't serve the HTTP discovery path; just check
|
|
# TCP-level reachability and let browser_navigate handshake.
|
|
if parsed.scheme in {"ws", "wss"} and parsed.path.startswith(
|
|
"/devtools/browser/"
|
|
):
|
|
import socket
|
|
|
|
try:
|
|
with socket.create_connection((parsed.hostname, port), timeout=2.0):
|
|
pass
|
|
except OSError as e:
|
|
return _err(rid, 5031, f"could not reach browser CDP at {url}: {e}")
|
|
else:
|
|
probes = _probe_urls(parsed)
|
|
ok = any(_http_ok(p, timeout=2.0) for p in probes)
|
|
|
|
if not ok and _is_default_local_cdp(parsed):
|
|
from hermes_cli.browser_connect import try_launch_chrome_debug
|
|
|
|
announce(
|
|
"Chromium-family browser isn't running with remote debugging — attempting to launch..."
|
|
)
|
|
|
|
if try_launch_chrome_debug(port, system):
|
|
for _ in range(20):
|
|
time.sleep(0.5)
|
|
if any(_http_ok(p, timeout=1.0) for p in probes):
|
|
ok = True
|
|
break
|
|
|
|
if ok:
|
|
announce(f"Chromium-family browser launched and listening on port {port}")
|
|
else:
|
|
for line in _failure_messages(url, port, system)[1:]:
|
|
announce(line, level="error")
|
|
return _ok(
|
|
rid, {"connected": False, "url": url, "messages": messages}
|
|
)
|
|
elif not ok:
|
|
return _err(rid, 5031, f"could not reach browser CDP at {url}")
|
|
elif _is_default_local_cdp(parsed):
|
|
announce(f"Chromium-family browser is already listening on port {port}")
|
|
|
|
normalized = _normalize_cdp_url(parsed)
|
|
|
|
# Order matters: reap sessions BEFORE publishing the new env
|
|
# so an in-flight tool call sees the old supervisor closed,
|
|
# then again AFTER so the default task's cached supervisor
|
|
# is drained against the new URL.
|
|
cleanup_all_browsers()
|
|
os.environ["BROWSER_CDP_URL"] = normalized
|
|
cleanup_all_browsers()
|
|
except Exception as e:
|
|
return _err(rid, 5031, str(e))
|
|
|
|
payload: dict[str, object] = {"connected": True, "url": normalized}
|
|
if messages:
|
|
payload["messages"] = messages
|
|
return _ok(rid, payload)
|
|
|
|
|
|
def _browser_disconnect(rid) -> dict:
|
|
# Reap, drop the env override, reap again — closes the same swap
|
|
# window covered by ``_browser_connect``.
|
|
def reap() -> None:
|
|
try:
|
|
from tools.browser_tool import cleanup_all_browsers
|
|
|
|
cleanup_all_browsers()
|
|
except Exception:
|
|
pass
|
|
|
|
reap()
|
|
os.environ.pop("BROWSER_CDP_URL", None)
|
|
reap()
|
|
return _ok(rid, {"connected": False})
|
|
|
|
|
|
@method("plugins.list")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from hermes_cli.plugins import get_plugin_manager
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"plugins": [
|
|
{
|
|
"name": n,
|
|
"version": getattr(i, "version", "?"),
|
|
"enabled": getattr(i, "enabled", True),
|
|
}
|
|
for n, i in get_plugin_manager()._plugins.items()
|
|
]
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5032, str(e))
|
|
|
|
|
|
@method("config.show")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
cfg = _load_cfg()
|
|
model = _resolve_model()
|
|
api_key = os.environ.get("HERMES_API_KEY", "") or cfg.get("api_key", "")
|
|
masked = f"****{api_key[-4:]}" if len(api_key) > 4 else "(not set)"
|
|
base_url = os.environ.get("HERMES_BASE_URL", "") or cfg.get("base_url", "")
|
|
|
|
sections = [
|
|
{
|
|
"title": "Model",
|
|
"rows": [
|
|
["Model", model],
|
|
["Base URL", base_url or "(default)"],
|
|
["API Key", masked],
|
|
],
|
|
},
|
|
{
|
|
"title": "Agent",
|
|
"rows": [
|
|
["Max Turns", str(_cfg_max_turns(cfg, 90))],
|
|
["Toolsets", ", ".join(cfg.get("enabled_toolsets", [])) or "all"],
|
|
["Verbose", str(cfg.get("verbose", False))],
|
|
],
|
|
},
|
|
{
|
|
"title": "Environment",
|
|
"rows": [
|
|
["Working Dir", os.getcwd()],
|
|
["Config File", str(_hermes_home / "config.yaml")],
|
|
],
|
|
},
|
|
]
|
|
return _ok(rid, {"sections": sections})
|
|
except Exception as e:
|
|
return _err(rid, 5030, str(e))
|
|
|
|
|
|
@method("tools.list")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from toolsets import get_all_toolsets, get_toolset_info
|
|
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
enabled = (
|
|
set(getattr(session["agent"], "enabled_toolsets", []) or [])
|
|
if session
|
|
else set(_load_enabled_toolsets() or [])
|
|
)
|
|
|
|
items = []
|
|
for name in sorted(get_all_toolsets().keys()):
|
|
info = get_toolset_info(name)
|
|
if not info:
|
|
continue
|
|
items.append(
|
|
{
|
|
"name": name,
|
|
"description": info["description"],
|
|
"tool_count": info["tool_count"],
|
|
"enabled": name in enabled if enabled else True,
|
|
"tools": info["resolved_tools"],
|
|
}
|
|
)
|
|
return _ok(rid, {"toolsets": items})
|
|
except Exception as e:
|
|
return _err(rid, 5031, str(e))
|
|
|
|
|
|
@method("tools.show")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from model_tools import get_toolset_for_tool, get_tool_definitions
|
|
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
enabled = (
|
|
getattr(session["agent"], "enabled_toolsets", None)
|
|
if session
|
|
else _load_enabled_toolsets()
|
|
)
|
|
tools = get_tool_definitions(enabled_toolsets=enabled, quiet_mode=True)
|
|
sections = {}
|
|
|
|
for tool in sorted(tools, key=lambda t: t["function"]["name"]):
|
|
name = tool["function"]["name"]
|
|
desc = str(tool["function"].get("description", "") or "").split("\n")[0]
|
|
if ". " in desc:
|
|
desc = desc[: desc.index(". ") + 1]
|
|
sections.setdefault(get_toolset_for_tool(name) or "unknown", []).append(
|
|
{
|
|
"name": name,
|
|
"description": desc,
|
|
}
|
|
)
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"sections": [
|
|
{"name": name, "tools": rows}
|
|
for name, rows in sorted(sections.items())
|
|
],
|
|
"total": len(tools),
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5034, str(e))
|
|
|
|
|
|
@method("tools.configure")
|
|
def _(rid, params: dict) -> dict:
|
|
action = str(params.get("action", "") or "").strip().lower()
|
|
targets = [
|
|
str(name).strip() for name in params.get("names", []) or [] if str(name).strip()
|
|
]
|
|
if action not in {"disable", "enable"}:
|
|
return _err(rid, 4017, f"unknown tools action: {action}")
|
|
if not targets:
|
|
return _err(rid, 4018, "names required")
|
|
|
|
try:
|
|
from hermes_cli.config import load_config, save_config
|
|
from hermes_cli.tools_config import (
|
|
CONFIGURABLE_TOOLSETS,
|
|
_apply_mcp_change,
|
|
_apply_toolset_change,
|
|
_get_platform_tools,
|
|
_get_plugin_toolset_keys,
|
|
)
|
|
|
|
cfg = load_config()
|
|
valid_toolsets = {
|
|
ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS
|
|
} | _get_plugin_toolset_keys()
|
|
toolset_targets = [name for name in targets if ":" not in name]
|
|
mcp_targets = [name for name in targets if ":" in name]
|
|
unknown = [name for name in toolset_targets if name not in valid_toolsets]
|
|
toolset_targets = [name for name in toolset_targets if name in valid_toolsets]
|
|
|
|
if toolset_targets:
|
|
_apply_toolset_change(cfg, "cli", toolset_targets, action)
|
|
|
|
missing_servers = (
|
|
_apply_mcp_change(cfg, mcp_targets, action) if mcp_targets else set()
|
|
)
|
|
save_config(cfg)
|
|
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
info = (
|
|
_reset_session_agent(params.get("session_id", ""), session)
|
|
if session
|
|
else None
|
|
)
|
|
enabled = sorted(
|
|
_get_platform_tools(load_config(), "cli", include_default_mcp_servers=False)
|
|
)
|
|
changed = [
|
|
name
|
|
for name in targets
|
|
if name not in unknown
|
|
and (":" not in name or name.split(":", 1)[0] not in missing_servers)
|
|
]
|
|
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"changed": changed,
|
|
"enabled_toolsets": enabled,
|
|
"info": info,
|
|
"missing_servers": sorted(missing_servers),
|
|
"reset": bool(session),
|
|
"unknown": unknown,
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5035, str(e))
|
|
|
|
|
|
@method("toolsets.list")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from toolsets import get_all_toolsets, get_toolset_info
|
|
|
|
session = _sessions.get(params.get("session_id", ""))
|
|
enabled = (
|
|
set(getattr(session["agent"], "enabled_toolsets", []) or [])
|
|
if session
|
|
else set(_load_enabled_toolsets() or [])
|
|
)
|
|
|
|
items = []
|
|
for name in sorted(get_all_toolsets().keys()):
|
|
info = get_toolset_info(name)
|
|
if not info:
|
|
continue
|
|
items.append(
|
|
{
|
|
"name": name,
|
|
"description": info["description"],
|
|
"tool_count": info["tool_count"],
|
|
"enabled": name in enabled if enabled else True,
|
|
}
|
|
)
|
|
return _ok(rid, {"toolsets": items})
|
|
except Exception as e:
|
|
return _err(rid, 5032, str(e))
|
|
|
|
|
|
@method("agents.list")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from tools.process_registry import process_registry
|
|
|
|
procs = process_registry.list_sessions()
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"processes": [
|
|
{
|
|
"session_id": p["session_id"],
|
|
"command": p["command"][:80],
|
|
"status": p["status"],
|
|
"uptime": p["uptime_seconds"],
|
|
}
|
|
for p in procs
|
|
]
|
|
},
|
|
)
|
|
except Exception as e:
|
|
return _err(rid, 5033, str(e))
|
|
|
|
|
|
@method("cron.manage")
|
|
def _(rid, params: dict) -> dict:
|
|
action, jid = params.get("action", "list"), params.get("name", "")
|
|
try:
|
|
from tools.cronjob_tools import cronjob
|
|
|
|
if action == "list":
|
|
return _ok(rid, json.loads(cronjob(action="list")))
|
|
if action == "add":
|
|
return _ok(
|
|
rid,
|
|
json.loads(
|
|
cronjob(
|
|
action="create",
|
|
name=jid,
|
|
schedule=params.get("schedule", ""),
|
|
prompt=params.get("prompt", ""),
|
|
)
|
|
),
|
|
)
|
|
if action in {"remove", "pause", "resume"}:
|
|
return _ok(rid, json.loads(cronjob(action=action, job_id=jid)))
|
|
return _err(rid, 4016, f"unknown cron action: {action}")
|
|
except Exception as e:
|
|
return _err(rid, 5023, str(e))
|
|
|
|
|
|
@method("skills.manage")
|
|
def _(rid, params: dict) -> dict:
|
|
action, query = params.get("action", "list"), params.get("query", "")
|
|
try:
|
|
if action == "list":
|
|
from hermes_cli.banner import get_available_skills
|
|
|
|
return _ok(rid, {"skills": get_available_skills()})
|
|
if action == "search":
|
|
from tools.skills_hub import (
|
|
GitHubAuth,
|
|
create_source_router,
|
|
unified_search,
|
|
)
|
|
|
|
raw = (
|
|
unified_search(
|
|
query,
|
|
create_source_router(GitHubAuth()),
|
|
source_filter="all",
|
|
limit=20,
|
|
)
|
|
or []
|
|
)
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"results": [
|
|
{"name": r.name, "description": r.description} for r in raw
|
|
]
|
|
},
|
|
)
|
|
if action == "install":
|
|
from hermes_cli.skills_hub import do_install
|
|
|
|
class _Q:
|
|
def print(self, *a, **k):
|
|
pass
|
|
|
|
do_install(query, skip_confirm=True, console=_Q())
|
|
return _ok(rid, {"installed": True, "name": query})
|
|
if action == "browse":
|
|
from hermes_cli.skills_hub import browse_skills
|
|
|
|
pg = int(params.get("page", 0) or 0) or (
|
|
int(query) if query.isdigit() else 1
|
|
)
|
|
return _ok(
|
|
rid, browse_skills(page=pg, page_size=int(params.get("page_size", 20)))
|
|
)
|
|
if action == "inspect":
|
|
from hermes_cli.skills_hub import inspect_skill
|
|
|
|
return _ok(rid, {"info": inspect_skill(query) or {}})
|
|
return _err(rid, 4017, f"unknown skills action: {action}")
|
|
except Exception as e:
|
|
return _err(rid, 5024, str(e))
|
|
|
|
|
|
@method("skills.reload")
|
|
def _(rid, params: dict) -> dict:
|
|
try:
|
|
from agent.skill_commands import reload_skills
|
|
|
|
result = reload_skills()
|
|
added = result.get("added") or []
|
|
removed = result.get("removed") or []
|
|
total = int(result.get("total") or 0)
|
|
|
|
lines = ["Reloading skills..."]
|
|
if not added and not removed:
|
|
lines.append("No new skills detected.")
|
|
if added:
|
|
lines.append("Added skills:")
|
|
lines.extend(f" - {item.get('name', '')}" for item in added)
|
|
if removed:
|
|
lines.append("Removed skills:")
|
|
lines.extend(f" - {item.get('name', '')}" for item in removed)
|
|
lines.append(f"{total} skill(s) available")
|
|
return _ok(rid, {"output": "\n".join(lines), "result": result})
|
|
except Exception as e:
|
|
return _err(rid, 5025, str(e))
|
|
|
|
|
|
# ── Methods: shell ───────────────────────────────────────────────────
|
|
|
|
|
|
@method("shell.exec")
|
|
def _(rid, params: dict) -> dict:
|
|
cmd = params.get("command", "")
|
|
if not cmd:
|
|
return _err(rid, 4004, "empty command")
|
|
try:
|
|
from tools.approval import detect_dangerous_command
|
|
|
|
is_dangerous, _, desc = detect_dangerous_command(cmd)
|
|
if is_dangerous:
|
|
return _err(
|
|
rid, 4005, f"blocked: {desc}. Use the agent for dangerous commands."
|
|
)
|
|
except ImportError:
|
|
pass
|
|
try:
|
|
r = subprocess.run(
|
|
cmd, shell=True, capture_output=True, text=True, timeout=30, cwd=os.getcwd()
|
|
)
|
|
return _ok(
|
|
rid,
|
|
{
|
|
"stdout": r.stdout[-4000:],
|
|
"stderr": r.stderr[-2000:],
|
|
"code": r.returncode,
|
|
},
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return _err(rid, 5002, "command timed out (30s)")
|
|
except Exception as e:
|
|
return _err(rid, 5003, str(e))
|