Files
hermes-agent/cli.py
Jeffrey Quesnelle fe9a4b58ec feat(profiles): never run a profile on the host while a plugin runs it elsewhere (#156725)
* feat(profiles): never run a profile on the host while a plugin runs it elsewhere

One host gateway serves every profile by default and runs each profile's
cron, messaging platforms, Kanban dispatch and Webapp; the CLI, TUI and
desktop build agents on the host too. A plugin that runs a profile's whole
backend somewhere else (for example in a sandbox, through its own host
launcher) had no way to stop the host from also running that profile outside
it, reading config the sandbox can write.

A host-side plugin now marks such a profile in host-only storage under the
Hermes root, never in a profile home:

  <hermes root>/profiles_run_elsewhere/<profile>.json
  {"plugin": "<plugin name>", "since": "<ISO 8601 UTC>"}

The file's presence is the marker, and an unreadable marker still marks the
profile. Writers write a dot-prefixed temp file in the folder and rename it
over <profile>.json. hermes_cli.profiles_run_elsewhere reads it and gives
host-side plugin code mark_profile_run_elsewhere() and
clear_profile_run_elsewhere().

For a marked profile:

- profiles_to_serve() leaves it out, the default profile included, unless
  the caller passes include_run_elsewhere=True. The host gateway stops
  serving it at its next rescan, and the desktop cron ticker, /p/<profile>/
  routing and the dashboard's cron and session fan-outs skip it. Callers
  that only look for live gateways, count installed homes or read which
  worktrees a resumable subagent pins opt in (host attach, the launch
  profile policy, the multiplex counts, the worktree sweep's pin view).
- AIAgent refuses to build an agent for it (ProfileRunsElsewhere), whichever
  frontend asks, including a multi-profile host building a sibling's agent.
- CLI commands that run a turn exit 1 before any banner, TUI or gateway
  contact; `hermes serve` and `hermes dashboard` exit 78 before attaching or
  binding; the gateway process exits 78 before reading config.
- ensure_gateway_runtime() answers inaccessible / profile_runs_elsewhere
  before discovery, so nothing starts or attaches to it on the host.
- The dashboard's cron, session, file and Webapp requests for it answer 409,
  the desktop cron ticker's gate refuses it, and the Kanban dispatcher
  leaves its cards in ready (skipped_nonspawnable).

A process that cannot list the marker folder (permission denied) is the
backend the plugin runs, not the host: it refuses nothing. Any other error
reading the folder fails closed. A profiles folder the process cannot list
shows only the process's own profile instead of raising PermissionError.

_seed_file_if_missing moves to profiles_initialization.py, its only caller,
to keep profiles.py under its size cap.

* fix(profiles): close review gaps in the run-elsewhere marker

Follow-up to "feat(profiles): never run a profile on the host while a
plugin runs it elsewhere", from the first review of #156725.

Checks added where a host process could still run a marked profile:

- cron.scheduler_tick.tick() returns before the tick lock, the due scan or
  any job for a marked profile, so every in-process ticker skips it: the
  gateway's (its launch profile included), the desktop's, and the built-in
  fallback an external provider starts. CronScheduler.claim_fire() claims
  nothing for it, for a provider's inbound fires and the misfire sweep.
- AIAgent.run_conversation() makes the check AIAgent.__init__ makes, so an
  agent built before the profile was marked (a gateway's cached agent, an
  open dashboard or TUI session) runs no further turn.
- The dashboard's deferred agent build refuses first, before it binds the
  profile's scope or starts its MCP servers.
- `hermes gateway run` exits 78 in _prepare_agent_startup, with or without
  --force: before plugin discovery, shell-hook registration and the
  host-gateway attach guards.

The marker module:

- run_elsewhere_for_home() reads the home as written and as resolved, and
  refuses when either reading is marked. A symlink or junction to a profile
  home, a relative or `..` path, or the profile id in another letter case
  now reaches that profile's marker.
- mark_profile_run_elsewhere() publishes a new marker with a hard link,
  which never replaces a file: of two plugins that both found no marker,
  one claims the profile and the other gets the ValueError. Where the
  filesystem has no hard links it renames as before.
  clear_profile_run_elsewhere() returns False without unlinking when it
  finds no marker, so it cannot remove one published after it looked. No
  lock is taken.
- Only a missing marker folder means nothing is marked. A regular file in
  its place refuses every profile, like any other read error.
- The folder reader returns one shape, _MarkerFolder(names, error).
- mark_profile_run_elsewhere, clear_profile_run_elsewhere and run_elsewhere
  are listed in plugin_api.json and public-api.md is regenerated, so
  `hermes plugins validate` accepts a plugin that imports them by name.

Corrections to that commit's message:

- "A profiles folder the process cannot list shows only the process's own
  profile instead of raising PermissionError" now holds only for a process
  whose own home is a named profile under that folder (the backend a
  plugin runs elsewhere). Any other process gets the PermissionError, as on
  main, so activate_multi_profile_hosting_eagerly() fails closed again for
  a default-profile host that cannot list the folder.
- "Any other error reading the folder fails closed" did not hold for a
  regular file at the folder's path, which read as "nothing marked". It
  holds now.
- "Writers write a dot-prefixed temp file in the folder and rename it over
  <profile>.json": the Python API's first write of a marker is the hard
  link above. Its rewrite of an existing marker, and other writers, still
  rename.

Not changed: a gateway or a serve/dashboard backend already running as the
marked profile is not stopped. It runs no further turn and no cron job for
the profile, and stays up until it is stopped.

* fix(profiles): load no env file or secret source from a marked home

Second follow-up to "feat(profiles): never run a profile on the host while
a plugin runs it elsewhere", for the review finding "CLI runs code before
refusing" on #156725.

While a plugin runs a profile elsewhere, the backend it runs writes the
profile's home. Every `hermes` start loads that home when hermes_cli.main
is imported (load_hermes_dotenv), before argparse and before any refusal,
and so does the plugin's own host process. A `secrets:` source that
backend wrote into its own config.yaml therefore ran on the host as the
user: `secrets.command` through /bin/sh on Linux and macOS,
`secrets.onepassword.binary_path` as a program on every OS. A .env it
wrote reached the environment of every such start, overriding what the
process already had.

Now a dotenv load whose home is marked takes nothing from that home:

- load_hermes_dotenv() does not read, rewrite or publish the home's .env,
  does not load .op.env and resolves no `secrets:` source. It asks once
  per load (run_elsewhere_for_home: a path resolve and a listing of a
  folder that is normally not there) and treats the two files as absent,
  so the project .env takes the precedence it has for a home without a
  .env. The project .env, the administrator-managed .env, the
  config-backend boot and the terminal bridge are unchanged.
- The config-backend bootstrap (_bootstrap_env) takes no selector or plane
  credential from a marked home's .env or .op.env, also when it runs
  before the first load. bootstrap_deployment() passes the load's answer
  on, so one load asks once.
- hydrate_profile_secret_sources() resolves nothing for a marked home, so
  a host gateway or dashboard that serves the profile runs none of its
  sources either.

A process that is denied the marker folder is the backend the plugin runs:
its home reads as not marked and it loads its own files as before. A
marker folder that cannot be read for any other reason already refuses
every profile; no profile's env files or secret sources are loaded either
until it can be read, and the log line says so.

What this changes for a marked profile: a host process started under its
home has none of its .env values in the process environment and none of
the keys its secret sources supply. The marking plugin supplies what its
own host process needs.

Not covered: hermes_cli.config.load_env() and the readers built on it
(get_env_value, reload_env) still open the .env file when asked, and the
secret scope a multi-profile host builds for a profile it serves still
reads it. Neither runs anything.

* fix(profiles): start no command and read no env value from a marked home

Third follow-up to "feat(profiles): never run a profile on the host
while a plugin runs it elsewhere" (#156725), on top of "load no env file
or secret source from a marked home".

While a plugin runs a profile elsewhere, the backend it runs writes the
profile's home. Two kinds of host process still acted on what that
backend wrote there (measured under a marked profile with stand-ins that
only append a line to a file):

- Commands that start a command the profile's own files name, without
  building an agent. `hermes hooks test` ran a shell hook from
  config.yaml. `hermes mcp test` started an `mcp_servers` stdio command,
  and sent an HTTP server's request to the address in its entry.
  `hermes secrets onepassword status` and `sync` ran the program
  `secrets.onepassword.binary_path` names. `hermes send` loaded the
  home's .env into the process with a loader of its own.
- Code that reads one env value on demand. The previous commit stopped
  the dotenv load; load_env() and get_env_value() still opened the
  home's .env. So `hermes status` listed keys that backend wrote as
  configured, `status --all` sent a request with a bearer from the file
  to a URL from the file, `status`, `dump` and `auth list` copied its
  keys into the profile's auth.json, and HERMES_REDACT_SECRETS was taken
  from it.

Now, for a home that is marked:

- tools.hosted_tool_policy: the four host features that start a process
  from the profile's files (RUNS_PROFILE_COMMANDS: shell_hooks,
  mcp_stdio, cron_scripts, skill_inline_shell) are off, at the place
  each already asks whether it may run in a hosted scope, and
  host_feature_refusal() answers with the run-elsewhere message. The
  one subprocess site of shell hooks starts nothing (`hooks test`,
  `hooks doctor`, a hook registered before the profile was marked), and
  the MCP stdio transport starts nothing, whoever asks.
- The MCP probe (_probe_single_server: `mcp test`, `mcp add`,
  `mcp configure`, `doctor`, the dashboard and TUI routes) raises
  ProfileRunsElsewhere before it validates, resolves, starts or calls a
  server, stdio or HTTP. `mcp login` and `mcp reauth` refuse first,
  before they drop the stored tokens or the device flow calls the
  entry's server.
- `hermes secrets <source> <verb>` exits 1 with the message of the
  commands that run a turn (one wrapper where the verbs are registered).
- `hermes send` exits 1 the same way, before its own loader reads the
  home's .env and config.yaml credentials into the process.
- agent.secret_scope.load_env_file(), the one .env tokenizer, reads a
  file in a marked home as empty and does not open it. That covers
  hermes_cli.config.load_env(), get_env_value(),
  get_env_value_prefer_dotenv(), reload_env(), the credential pool's
  seeding from .env, and the secret scope a multi-profile host builds
  for a profile. Hermes's own .env writers (save_env_value,
  remove_env_value) do not read through it and still write the file, so
  a key the user saves through the marking plugin's host process lands
  there. A file in any other folder (a plugin's host-only copy) reads as
  before.
- `hermes status --all` does not probe LM Studio at model.base_url: with
  the .env values out of reach, the address in config.yaml still sent a
  request from the host.
- `hermes status` and `hermes config` print one line saying that the
  profile's .env keys are not read on this host, because they now show
  as not set.

The check behind the tokenizer and the features is
profiles_run_elsewhere.home_runs_elsewhere(home): the answer of
run_elsewhere_for_home, kept per process and home. Each call stats the
marker folder and the home's marker file, and asks again when that
differs from the stat taken before the last asking, so a marker written
or removed by any process is seen at the next call. A marker folder that
cannot be read marks every home, as it does for running a profile, and
is asked about again every time. A process that is denied the folder is
the backend the plugin runs: it reads its own .env and runs its own
hooks and MCP servers as before.

This corrects the previous commit's message, which said "Not covered:
hermes_cli.config.load_env() and the readers built on it (get_env_value,
reload_env) still open the .env file when asked, and the secret scope a
multi-profile host builds for a profile it serves still reads it". Both
are covered now.

Not covered: config.yaml of a marked home is still read (`hermes status`
and `hermes config` show it). `quick_commands` of type exec still run in
a chat client, gateway or TUI backend that was already running when the
profile was marked. resolve_home_dotenv() (two config migrations) still
parses the home's .env. Plugins in the home are still discovered.

* fix(profiles): no quick command runs for a profile that runs elsewhere

A quick_commands entry of type exec is a shell command in the profile's
config.yaml, a file the backend the plugin runs writes. The refusals so
far keep a hermes command from starting, on a marked home, a process
that dispatches one. Three cases still reached the three places that
start the command (the classic CLI, the gateway, the TUI / dashboard
backend):

- a chat client, gateway or backend that was already running as the
  profile when it was marked: its turns are refused, its slash commands
  were not;
- a dashboard or `hermes serve` backend on another profile's home, whose
  command.dispatch takes the profile with the request (the `profile`
  parameter, or a session of that profile);
- a multiplexing gateway: its own quick commands are the default
  profile's whichever profile's process started it
  (load_gateway_config_for_runner), so a gateway started from a named
  profile while `default` is marked had them.

Each of the three places now asks run_elsewhere_refusal() before it
starts the command and answers with the run-elsewhere message instead.
The home asked is the one whose config.yaml names the command: the home
bound for the request in the TUI / dashboard backend and for a local
session of the gateway, the process's own in the classic CLI, and for a
gateway's messaging commands the home its config was loaded from
(_hm_quick_commands_home: the default profile's when it multiplexes).

Alias quick commands are unchanged, and so is the backend the plugin
runs, which does not see the marker.

* test(profiles): fire the marker race helper after the module's own look

`_between_look_and_change` runs an action right after the marker module's
next look at a profile's marker, to play the writer that gets in between a
look and a change. It patched `os.listdir`, `os.lstat` and `_read_entry`,
and fired as soon as a call for the marker returned.

The suite's home guard (`tests/home_io_guard.py`) wraps `os.lstat` too, and
resolves the path before it calls the real function. On POSIX
`os.path.realpath` lstats every component of the path through `os.lstat`,
so the helper saw the guard's own lstat of `<profile>.json` first and fired
inside the guard, before the module's lstat had run. In
`test_a_clear_that_found_no_marker_never_removes_one_published_after_it_looked`
the other plugin's marker was therefore already in place when
`clear_profile_run_elsewhere` looked, and the call raised `ValueError`
instead of returning False. On Windows `realpath` does not call `os.lstat`,
so the test passed there and failed on Linux only.

The three wrappers now share a depth counter and fire only when the
outermost patched call returns: a look made inside a look is part of it.
The action runs at the same point on both systems, after the module's own
look and before its change. No product code changes.

* fix(mcp): refuse "mcp add" first for a profile a plugin runs elsewhere

`hermes mcp add` reached the run-elsewhere refusal only inside its probe,
and treated it like any failed connection: it printed "Failed to connect"
and offered "Save config anyway", which wrote the server entry (disabled)
into the marked profile's config.yaml. For an HTTP server it had by then
asked for a bearer token and saved it to the profile's `.env`.

`cmd_mcp_add` now refuses before its first question, the way `send` and
the `secrets` verbs do: the message on stderr, exit 1, nothing asked and
no file of the profile changed.

The probe's other callers leave nothing written when the probe refuses
(`mcp test`, `mcp configure`, the dashboard and TUI test routes, the
connector install, the OAuth flows) and are unchanged.

* test(profiles): gate the Windows letter-case test with the platforms marker

`test_a_profiles_folder_spelled_in_another_letter_case_reads_the_marker_on_windows`
was gated with a bare `skipif(os.name != "nt")`. The Windows lane imports
only files that carry a `platforms(...)` spec covering Windows and selects
with `-m platforms`, so the test ran on no CI host (tests/AGENTS.md: "Use
the marker, never a bare `skipif`"). It now carries
`@pytest.mark.platforms("windows")`. No other test this branch adds gates
on the host with a `skipif`.

* docs(dashboard): say which requests _cron_profile_home() refuses

The helper's docstring said that the host "neither reads nor runs" a marked
profile's "jobs, sessions or files". The helper answers 409 only to the
requests that resolve their profile through it: every cron request (an omitted
profile resolves to the backend's own), and the session and file requests that
name the profile. A session or file request with no profile uses the backend's
own home without asking the helper, as the description's "Not covered" section
says. The docstring now says that. No code change.

Found in review.

* fix(profiles): ask again when a home's link leads to another profile

home_runs_elsewhere() keeps its answer per process and home path, and held it
valid while a stat of the marker files it had worked out was unchanged. Those
files belong to the directory the path led to at the first asking. When the
home is a symlink or junction and the link is pointed at another profile, no
marker is written or removed, so the kept answer stayed: pointed at a marked
profile, run_elsewhere_for_home() refused the home while load_env_file() still
read the marked profile's .env; pointed away from one, the unmarked home's
.env read as empty. Reproduced with a symlink on Linux and with a symlink and
a junction on Windows. A link above the home (the root itself) was already
seen, because the marker paths are read through it.

The kept answer is now also for the directory the path leads to: each call
stats the home and compares device and file id with the stat taken before the
home was resolved. That is one more stat per call. Measured for a plain home,
the cached check goes from 2.5 to 5.4 us on Linux and from 7.0 to 12.3 us on
Windows, and load_env_file() from 17 to 20 us and from 104 to 112 us; through
a link on Windows the check goes from 27 to 71 us. Resolving the home at every
call instead would add 23 us on Linux and 87 us on Windows, more than the
whole check.

Found in review.

* fix(profiles): a second name for a marked profile's home is not served either

Found in review. With profiles/alias a link to profiles/ops (a symlink, or a
junction on Windows), marking ops took only the name ops out of
profiles_to_serve(): the list was filtered by name, so the host gateway kept
alias in its served set, although every check that asks by home refused it.
Two more checks asked by name and let the link through: the Kanban
dispatcher's profile_exists_here(), and the dashboard's profile resolution
_cron_profile_home(), behind the cron, session, history and file requests
that name a profile.

All three now ask by home. The served list and the dispatcher use the kept
answer of home_runs_elsewhere(), which costs stats per profile instead of a
resolve and a folder listing; the dashboard asks run_elsewhere_for_home()
and answers 409 with the marked profile's name. The kept answers hold 4096
homes instead of 256, so a host with several hundred profiles still answers
its list from stats.

* fix(profiles): a clone made under a marked name keeps the keys it was cloned with

Found in review. Creating a profile mirrors the launch profile's .env into
it, but only over the seeded comment-only stub, never over the keys a clone
brought. That check asked the .env tokenizer what the new file holds, and
the tokenizer answers with nothing for a home a plugin runs elsewhere. A
profile cloned under a name whose marker was already there (left behind
when an earlier profile of that name was deleted) therefore looked empty,
and the launch profile's .env was copied over the cloned keys.

The check now reads the destination as the file it is
(load_env_file(..., for_overwrite_check=True)). Nothing else reads a marked
home's .env: every value reader still gets nothing from it. A new profile
whose .env is the stub still receives the launch keys, marked name or not,
as every new profile does.

* fix(profiles): a marker covers its profile's directory under every name

Found in review, as the mirror of the link case fixed before: with
profiles/ops a symlink or junction to profiles/real and ops marked, the
directory's own name real was still listed, served, built and run on this
host, and its .env was read. A home was followed to the profile its path
leads to, but not to the other names that lead to its directory, while the
backend elsewhere runs in that one directory whatever it is called.

run_elsewhere_for_home() and home_runs_elsewhere() are the two functions
every refusal asks. Both now also compare the home's directory (device and
file id) with the home of each profile the root's marker folder marks, so a
marked name that is itself a link marks the directory it leads to, under
that directory's own name too. An error or a filesystem without file ids is
never a match.

The kept answer of home_runs_elsewhere() adds one stat per other marked
profile, which also sees a marked link pointed at another directory. It
learns of a new marker under another name from the marker folder's time, so
a listing taken less than two seconds after the folder changed is not
relied on and is taken again at the next call, without resolving the home
again: two changes can share one tick of a filesystem's clock.

* fix(profiles): home maintenance waits while a plugin runs the profile elsewhere

After an installed revision changes, the first start of each profile runs
home maintenance for its own home (boot_bootstrap): the config migration,
which first copies config.yaml and .env beside themselves as
<name>.bak-<stamp>, the plugin-catalog cache drop, launcher publication and
the default-plugin check. Every hermes command and the gateway process make
that call before any command can refuse. A host start under a marked
profile, the marking plugin's own status and switch-off commands included,
therefore rewrote config.yaml under the backend the plugin runs and left a
byte copy of the keys file in a home that backend reads and writes.

run_boot_bootstrap now asks run_elsewhere_for_home() for this process's
home when maintenance is due (a new revision, or a step still owed), before
it takes the record lock. For a marked home it runs no step and writes no
record, so the maintenance stays owed and the first start after the marker
is gone does it. The question is asked by home: a marked home reached
through a link, and the directory behind a marked link, are covered. The
backend the plugin runs (it is denied the marker folder) and every unmarked
profile, the default one included, are maintained as before. A marker
folder that cannot be read holds maintenance back, as it refuses every
profile.

A start whose record says this revision is done reads its record and
returns as before; nothing is asked on that path.

One log line says why: "home maintenance: the '<plugin>' plugin runs
profile '<name>' elsewhere, so this host leaves its home alone; it is owed
until the profile runs here".

* fix(profiles): the backend migration does not move a profile a plugin runs elsewhere

`hermes gateway migrate --backends --apply` and the dashboard's "move to the
gateway" request (`POST /api/gateway/migrate/backends/apply?profile=`) went
ahead for a profile a plugin runs elsewhere. The move wrote `.env` and
`config.yaml` in that profile's home, installed and started a gateway service
for it and stopped its old backend. The gateway then refused to run the profile
and exited, so the run could only end in its rollback, which put the saved
`.env` and `config.yaml` back over whatever the backend the plugin runs had
written in the meantime.

The refusal a marked profile gets everywhere else is now one of the blockers
the apply path adds before anything changes. The command exits 3 with it, the
dry run and `GET /api/gateway/migrate/backends/plan` list it, and the
dashboard's request answers 409 and starts no run.

* fix(profiles): the config.yaml of a profile a plugin runs elsewhere sets no host environment variable

Importing `gateway.run` copies settings of the launch home's `config.yaml` into
the process environment. Among them is every top-level scalar of the file,
under the scalar's own name when that name is not set yet. `hermes -p <profile>
gateway status` imports the module, and so does the gateway process before it
refuses a marked profile. While a plugin runs the profile elsewhere, the
backend it runs writes that file, so it could choose `LD_PRELOAD`,
`NODE_OPTIONS`, `PYTHONPATH` or a proxy for that host process and for every
program the process starts afterwards. The home's `.env` was already closed for
this reason; `config.yaml` was a second way in.

`load_launch_home_dotenv()` in `env_loader.py` asks once whether a plugin runs
the launch profile elsewhere, runs the dotenv load with that answer
(`load_hermes_dotenv(home_elsewhere=...)`, the keyword the bootstraps already
take) and returns it. `gateway.run` calls it where it called
`load_hermes_dotenv`, and for a marked home it does not read the file for its
bridge. A home without a marker is asked about as often as before, and its
bridge is unchanged.

* fix(profiles): reading an env file under a folder named like ~user no longer raises

`load_env_file()` asks whether the file's folder is the home of a profile a
plugin runs elsewhere. That question expanded a leading `~name` with
`Path.expanduser()`, which raises `RuntimeError` when no user has that name.
So on Linux and macOS, with no marker anywhere, a relative path whose first
folder is named like `~someone` made the tokenizer raise ("Could not determine
home directory."), where it had always read the file as written or returned
`{}`. Windows guesses a folder for any `~name` and did not raise.

The marker question now expands with `os.path.expanduser()`, as its stat of the
home already did: a `~name` that is no user's stays as written, which is the
path the read opens.

* fix(profiles): the refusal says how to get a profile back when its plugin is gone

A marker can outlive the plugin that wrote it: the plugin was removed or
disabled, it no longer loads, or the Hermes root came back from a backup taken
while the profile ran elsewhere. The owner then meets the refusal at every
command that runs the profile, and its advice was to turn this off in a plugin
he no longer has. Core has no command that clears a marker, and the refusal
named neither the file nor another way.

The refusal for a marker that names its plugin keeps its sentences and ends
with one more: if that plugin is no longer installed or no longer loads,
deleting the marker file (named by its path) lets Hermes run the profile on
this computer again, and the file is not to be deleted while the plugin still
runs the profile. The user guide says the same.

* test(profiles): marking a profile leaves the marker folder listable by other local users

On Linux and macOS `mark_profile_run_elsewhere()` sets the marker folder to
0755. A host service that runs as another local user must be able to list the
folder: a listing that is denied reads as "this process is the backend the
plugin runs", and such a process refuses nothing. No test noticed when that
`chmod` was removed. This one marks under umask 077, and marks again after the
folder was made 0700, and expects 0755 both times.

* test(profiles): the quiet-folder test no longer depends on how fast it runs

`test_a_marker_folder_that_has_been_quiet_is_not_listed_again` expects 150
listings of the marker folder "a moment after the marker was written". The
module stops listing once the folder's time is two seconds old, so a test run
that stalls for two seconds between writing the marker and the end of that loop
counts fewer listings and fails. It did once on a loaded machine.

The test now stands the module's clock at the folder's own time before it asks
for the first time, as it already moved that clock forward for its second half.

* test(profiles): the marker question by home does not raise for a folder named like ~user

The dotenv load asks whether a plugin runs a home's profile elsewhere through
`run_elsewhere_for_home()`, which expanded a leading `~name` the way the
tokenizer's question did. The test of a folder named like a user that does not
exist now asks through both, so each of the two expansions has a test that
fails when it raises again.

* fix(profiles): the backend migration plans no step against a profile a plugin runs elsewhere

The block for a marked profile sat among the blockers of the apply path, which
a plan that can only be done by hand never reaches. On Windows every plan is of
that kind, and there the backend a plugin runs is a process of this host
(`hermes serve --isolated` under the profile's home). So `hermes gateway
migrate --backends --apply`, with or without `--dry-run`, found that process as
an old backend of the marked home, exited 6 and printed the steps of a move by
hand: `taskkill /PID <its pid> /T /F`, then installing a gateway for the
profile.

The refusal is now the first answer of the plan's own owner check, which every
form of the plan passes before a step is chosen. A marked home gets a blocked
plan (exit 3) with the run-elsewhere message and no step, on every platform;
the dashboard's plan and apply routes read the same plan.

* test(profiles): the public marker functions are pinned by what the validator does

`test_the_user_guides_marker_example_validates_clean` read the user guide from
the repository, cut its Python example out, parsed it and compared the names
it imports with a list. That is a test of a file's text. What it guarded is
that `hermes plugins validate` calls the three documented marker functions
public, and `test_the_documented_marker_functions_are_public_plugin_api`
already pins that by running the validator on a plugin that imports them:
with one of the three taken out of the public list, that test fails.

The guide-reading test is removed. The other tests of this branch read only
files under their own temporary homes.

* fix(profiles): no form of the backend migration acts on a profile a plugin runs elsewhere

The block for a marked profile sat in the migration's plan, and several
forms of `hermes gateway migrate --backends` never reach the plan or act
before it:

- `--apply --detach` started the run in the background and reported it as
  started; only that run then refused.
- `--restore` undid a move that was made before the profile was marked: it
  stopped and removed the gateway service, wrote `config.yaml` and `.env`
  back from the move's backups and started the old backend.
- A move that did not finish was rolled back the same way by the next
  `--apply` or `--restore`, and the dry run named the command that does it.
- A second `--apply` on a moved home named `--restore`.
- Every form but the dry run made the run lock in the marked home first.

The command now refuses where every form enters: for a marked profile
`--apply` and `--restore`, with any other flag, exit 3 with the
run-elsewhere message before the home's record is read or its lock is made.
Nothing is written, started or stopped, and the record of an earlier move
stays for when the profile runs on this host again. `--status` still reads.

The dashboard's `POST /api/gateway/migrate/backends/apply` and
`.../restore` answer 409 `blocked` with the same message for a marked
profile, start no run and name no command.

* fix(profiles): the lists of old backends say when a plugin runs the profile elsewhere

The backend a plugin runs for a profile can be a `hermes serve` process of
this machine, which the backend migration's scan finds like any other old
backend of that home:

- `hermes gateway migrate --backends` listed it without a word about the
  plugin and ended with the line that offers the dry run of its move.
- After `hermes update`, the notice called it "an old Hermes backend for
  this profile" and offered the same dry run.
- The rows the dashboard's plan route returns said nothing about it either.

A listed backend whose home's profile a plugin runs elsewhere now carries
one more note, in the report's text and JSON and in the dashboard's rows:
"Profile 'ops' runs elsewhere (the 'x' plugin runs its backend): Hermes
does not move this backend to the gateway on this host." The report offers
no dry run when its own profile is marked, and the update prints no notice
for such a profile. The move itself is already refused for it.

* fix(profiles): the blocked plan of a profile a plugin runs elsewhere lists no backend to move by hand

Where a backend can only be moved by hand (on Windows every one), the plan
of a marked profile printed no step but kept the entry above the blocker:
"manual cannot be migrated automatically ... Run the steps below in
PowerShell or Command Prompt ... Steps, in this order", with nothing under
it. The dashboard's card prints "This server cannot be moved from here" and
those instructions for every such entry.

The marker's check is now its own step of the plan, before the checks of
which gateway serves the home, and the plan it blocks lists no backend at
all: the text is the home and the blocker, and the JSON has an empty
`unsupported`. The other reasons a plan is blocked print as before.

* fix(profiles): the refusal's last sentence says "on this host" like the sentences before it

The sentence the refusal gained for a plugin that is gone said that deleting
the marker file "lets Hermes run the profile on this computer again", two
sentences after "Hermes does not run it on this host". The message and the
user guide say "host" everywhere else, so this sentence does too.

* test(profiles): the line for a listed backend says what the marker tells

The line a listed backend of a marked home carries has three forms: the
plugin by name, "a plugin" when the marker file cannot be read, and "Hermes
cannot read <folder>" when the marker folder cannot be read. The tests of
the report covered the first. This one reads all three from real markers.

* fix(ci): a change to the run-elsewhere marker module starts the update suite

The notice `hermes update` prints about an old backend
(hermes_cli/update_backend_notice.py) now asks whether a plugin runs the
profile elsewhere, so it imports hermes_cli/profiles_run_elsewhere.py. The
change classifier did not route that module to the upgrade E2E lane, and
tests/ci/test_update_ci_routing.py failed for it:

    e2e_upgrade: imported by the update path but not routed to it:
    {'hermes_cli/profiles_run_elsewhere.py': ['hermes_cli/update_backend_notice.py']}

The module joins the lane's owner list, beside the backend-migration marker
the same notice reads.

* fix(profiles): a marked profile's key_cmd is not run on this host

`providers.<id>.key_cmd`, and a custom provider's `key_cmd`, is a shell
command line in the profile's own `config.yaml`. Hermes runs it to get the
provider's key, with the profile's environment and credentials. For a
profile a plugin runs elsewhere, the backend there writes that file, and
nothing on this path asked the marker: the dashboard's
`GET /api/model/options?profile=<name>` ran a marked profile's command once,
as it does for any profile.

`_mint`, the one place every `key_cmd` runs, now raises `CommandTokenError`
with the run-elsewhere message for a marked profile. The model picker turns
that error into a probe without a key, so it still answers; the same request
now runs the command zero times.

The fix and its test are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a dashboard file request never dials a marked profile's SSH workspace

A file request that names a profile is answered 409 when a plugin runs that
profile elsewhere. For a profile whose workspace is on an SSH host the
request went another way first: `_fs_backend` read `terminal` from the
profile's `config.yaml` and dialed the host named there before the route
reached the refusal. `GET /api/fs/list?profile=<name>` and
`GET /api/fs/default-cwd?profile=<name>` dialed the host a marked profile's
config names.

`_fs_backend` now resolves the profile first, which answers 409 for a marked
one before its config is read. Every file route that can go to an SSH host
passes through it. A request that names no profile behaves as before. Two
existing tests call the real `_fs_backend` with a profile that is not on
disk; they now stand in for the lookup.

The fix and its tests are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): gateway ensure and attach refuse a marked profile whose directory is a link out of the root

A marker covers the profile's directory whatever path leads to it. But
`ensure_gateway_runtime` made the home canonical before it asked the marker.
When `profiles/ops` is a link to a directory outside the Hermes root, the
canonical path has no Hermes root above it and so no marker: `gateway ensure`
went on to discovery for a marked profile and did not answer
`profile_runs_elsewhere`. `attach_gateway` resolves the home before it calls
`ensure`, so it went the same way.

Both now ask about the home as it was given too. In `ensure` the check sits
inside the existing assignment, which keeps the function at the complexity
cap; `attach_gateway` checks before it resolves. The answer for a marked
profile is the one `ensure` already gave: `inaccessible`,
`profile_runs_elsewhere`, the refusal in `detail`.

The fix and its test are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): marked profiles still count when an external cron registry may be shared

An external cron provider keeps one remote registry that is not scoped to a
profile, so Hermes uses it only on a host with a single profile. Two callers
decide that by counting the served profiles, and a profile a plugin runs
elsewhere is no longer in that list:

- The gateway chose its scheduler with the number of profiles it ticks. On a
  host with `default` and a marked `ops` that number is 1, so the gateway
  kept the external provider, which reconciles the registry toward
  `default`'s jobs when it starts.
- The dashboard skips an external reconcile when it counts more than one
  profile. With the other profiles marked, the reconcile ran.

On main both counts included `ops`. If the backend elsewhere arms that
profile's jobs through the same provider account, such a reconcile can
cancel them.

Both callers now count the marked profiles where the question is who may
share the registry. The profiles the gateway ticks and the dashboard lists
are unchanged. Three existing stand-ins for `_cron_profile_dicts` accept the
new keyword.

The fix and its tests are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's speech command is not run on this host

`tts.providers.<name>.command` and `stt.providers.<name>.command` are shell
command lines in the profile's own `config.yaml`, and one runner starts
both. The dashboard reaches it for a named profile without building an
agent: `POST /api/audio/speak?profile=<name>` ran a marked profile's TTS
command, and `POST /api/audio/transcribe?profile=<name>` ran its STT command
and returned what it printed. The backend a plugin runs elsewhere writes
that file, so this is the host starting a command line that backend wrote,
as with a provider's `key_cmd`.

`run_command_provider`, the one place both kinds run, now raises
`RuntimeError` with the run-elsewhere message for a marked profile. The
callers already turn a `RuntimeError` of the runner into their own failure
answer, so the speak request answers 400 with the message and the
transcribe request answers that the transcription failed.

* fix(profiles): the gateway's clients ask about a linked profile's home before they resolve it

`gateway ensure` and `gateway attach` now ask the marker about the home as
it was given. Two callers resolve the home before those functions see it,
so a marked profile whose directory is a link out of the Hermes root still
got past them:

- `connect_gateway`, which `hermes sessions discard` and `adopt` and the
  cron and Kanban clients call. None of them passes the command line's own
  refusal first, and for such a profile it went on to discovery and could
  start a gateway.
- The TUI's bootstrap script, which an open TUI runs again whenever its
  gateway is gone. A TUI that was open before a plugin took the profile
  over started a gateway for it again.

`connect_gateway` asks about this process's home before it resolves it and
raises the error it already raises for a gateway it may not attach to
(`inaccessible`, `profile_runs_elsewhere`). The bootstrap script passes the
home to `attach_gateway` as the environment names it; `attach_gateway`
resolves it after its own check.

* fix(profiles): the plugin host takes no launcher and no package from a marked profile's home

With `plugins.isolation: host` every plugin of the profile loads in a child
process. Its command line began with `plugins.host.launcher` from the
profile's own `config.yaml`, and the child started in the profile home with
that folder first on its import path. For a profile a plugin runs elsewhere
the backend there writes both: `hermes -p <name> status` started the launcher
that file named, and a `hermes_cli` package placed in the home ran in the
child instead of Hermes's own.

For a marked profile `host_launcher()` now reads the launcher from the
managed overlay only, which that backend cannot write; with none set there,
the child starts without a launcher. The child is started with `-P`, as the
profile extraction already was, so the folder it starts in is no longer on
its import path. That part applies to every profile: a module that sits in
the profile home can no longer be imported by name from a hosted plugin.
Hermes's own packages still come from `PYTHONPATH`, and a plugin's own
package is loaded by its path as before.

The fix and its tests are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's password manager binary is not run on this host

`vault.bitwarden.binary_path` and `vault.onepassword.binary_path` name a
password manager's command line program in the profile's own `config.yaml`.
The Settings dialog's `vault.unlock` request hands that program the master
password the person typed, without building an agent. For a profile a plugin
runs elsewhere the backend there writes that file, and nothing on this path
asked the marker: the request ran a marked profile's program and gave it the
password.

`_bw` and `_op`, the one place each manager's program is looked up for
unlock, list and fill, now raise `RuntimeError` with the run-elsewhere
message for a marked profile. `vault.unlock` answers with its usual error
5095 carrying that message. The local vault does not pass either function.

The fix and its test are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's browser executable is not started on this host

`browser.executable_path` names the Chromium a local browser session starts,
in the profile's own `config.yaml`. `hermes doctor --live` launches it to
check that a browser can start, without building an agent. For a profile a
plugin runs elsewhere the backend there writes that file, and nothing on this
path asked the marker: `hermes -p <name> doctor --live` started the program a
marked profile named.

`launch_chromium`, the one place a local Chromium is started, now returns its
usual `(None, error)` with the run-elsewhere message for a marked profile.
`doctor --live` reports the browser probe as failed with that message.

The fix and its test are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): the cron registry count sees a marked default beside a standalone gateway

Whether an external cron provider's registry may be shared was decided from
the larger of two counts: the profiles the gateway ticks and the installed
ones. A gateway that runs as a standalone profile ticks only itself, and the
installed list leaves a standalone profile out. With `default` marked and the
gateway running as a standalone `ops`, both counts were 1, so the gateway
took the external provider and reconciled its registry toward `ops`'s jobs
alone, although the marked `default`'s backend may arm jobs there too.

The count is now the number of different profile names in the two lists
together. With no marker every profile in the installed list is one the
gateway ticks, so the count is the number of profiles it ticks, as before.

The fix and its test case are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a managed launcher expands its env refs for a marked profile too

For a profile a plugin runs elsewhere the plugin host's launcher is read
from the managed overlay alone. That read took the overlay's file as
parsed, so a ${VAR} in plugins.host.launcher reached the child's command
line unexpanded, while every other profile got the expanded value.
host_launcher() now asks apply_managed_overlay({}), which expands refs
against the process env the way the config loader does.

* fix(profiles): a marked profile linked out of the root does not get its own launcher

`hermes -p ops` names the home `<root>/profiles/ops`. When that is a link
to a directory outside the Hermes root, the plugin manager is keyed by the
directory the link leads to, and the plugin host asked the marker about
that directory, which has no marker folder above it. So the host child of
such a profile still started under the `plugins.host.launcher` its own
`config.yaml` names.

The manager now keeps the home as it was named (`owner_home`), and the
host passes it to `host_launcher()`, which asks the marker about that
home. Other callers of `host_launcher()` are unchanged.

The fix and its test are the reviewer's patch from the review of
b3d3693bb6a, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): an empty PYTHONPATH entry does not put the profile home on the host's path

The plugin host's child starts in the profile home, with `-P` so that
folder is not on its import path. `-P` drops only Python's own first
entry: an empty entry in `PYTHONPATH` (`PYTHONPATH=:/x`, or a trailing
separator) still means the current directory, and the child inherited
such entries as they were. A module placed in the profile home then ran
in the host child again, ahead of the standard library.

The inherited entries are now made absolute against the parent's working
directory before the child gets them, so an empty or relative entry means
for the child what it means for the parent. This applies to every
profile, like `-P` itself.

The fix and its test are the reviewer's patch from the review of
b3d3693bb6a, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

---------

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-23 21:37:40 -05:00

1802 lines
81 KiB
Python

#!/usr/bin/env python3
"""Hermes Agent CLI — interactive terminal interface (``python cli.py --help`` for usage)."""
# Must be the very first import (UTF-8 stdio on Windows). Missing only mid-``hermes update``.
try:
import hermes_bootstrap
except ModuleNotFoundError as exc:
if exc.name != "hermes_bootstrap" and not "hermes_bootstrap".startswith(f"{exc.name}."):
raise # the bootstrap exists but cannot load: skipping it would skip PM activation
import logging
import os
import functools
# Tests patch shutil/time/datetime through the cli facade; siblings also resolve datetime
# lazily through it — these imports are load-bearing despite being unused in this file.
import shutil
import sys
import re
import atexit
import errno
import time
from collections import deque
from dataclasses import dataclass
from contextlib import contextmanager, suppress
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
os.environ["HERMES_QUIET"] = "1" # suppress our modules' startup chatter
from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin
from hermes_cli.cli_commands_mixin import CLICommandsMixin
from hermes_cli.cli_billing_mixin import CLIBillingMixin
from hermes_cli.cli_loops_mixin import CLILoopsMixin
from hermes_cli.cli_info_mixin import CLIInfoMixin
from hermes_cli.cli_terminal_mixin import CLITerminalMixin
from hermes_cli.cli_modal_mixin import CLIModalMixin
from hermes_cli.cli_stream_mixin import CLIStreamMixin
from hermes_cli.cli_session_mixin import CLISessionMixin
from hermes_cli.cli_model_switch_mixin import CLIModelSwitchMixin
from hermes_cli.cli_voice_mixin import CLIVoiceMixin
from hermes_cli.cli_status_bar_mixin import CLIStatusBarMixin
from hermes_cli.cli_tui_mixin import CLITuiMixin
from hermes_cli.cli_process_notifications import CLIProcessNotificationsMixin
from hermes_cli.cli_init_mixin import CLIInitMixin
from hermes_cli.cli_tui_runtime_mixin import CLITuiRuntimeMixin
from hermes_cli.cli_backtrack import CLIBacktrackMixin
# Extracted clusters (mechanical split, #116911); re-exported here so `cli.<name>` stays the seam.
from hermes_cli.cli_shutdown import (
_CLEANUP_STEPS,
_arm_exit_watchdog,
_emit_interrupted_session_end,
_exit_watchdog_timeout,
_finalize_single_query,
_float_env,
_flush_logging_and_stdio,
_flush_one_shot_session_store,
_interrupt_async_delegations,
_invoke_interrupted_session_end,
_notify_session_finalize,
_notify_single_query_session_finalize,
_oneshot_agent_and_session,
_should_emit_cleanup_session_finalize,
_shutdown_agent_memory_provider,
_shutdown_cached_aux_clients,
_shutdown_mcp_servers,
_stop_cli_wake_word,
_sync_process_session_id,
_wait_for_oneshot_background_completions,
)
from hermes_cli.cli_auto_maintenance import (
_run_state_db_auto_maintenance,
)
from hermes_cli.cli_render import (
ChatConsole,
_ACCENT,
_ACCENT_ANSI_DEFAULT,
_BOLD,
_DA1_REPLY_RE,
_DIM,
_FALSE_RE,
_LIGHT_DEFAULT_TERM_PROGRAMS,
_LIGHT_MODE_REMAP,
_LIGHT_MODE_REMAP_UPPER,
_REASONING_TAGS,
_RST,
_STREAM_PAD,
_STREAM_PARTIAL_PREVIEW_LEN,
_SkinAwareAnsi,
_TOOL_CALL_TAGS,
_TRUE_RE,
_WINDOWS_PATH_WITH_DOT_SEGMENT_RE,
_accent_hex,
_add_suspect_rows,
_append_blank_panel_line,
_append_panel_line,
_assistant_content_as_text,
_assistant_copy_text,
_b,
_build_compact_banner,
_clear_output_history,
_cli_visible_print,
_coerce_output_history_limit,
_cprint,
_d,
_detect_light_mode_uncached,
_heal_cooked_mode_drift,
_hex_to_ansi,
_install_skin_light_mode_hook,
_line_rows,
_luminance_from_hex,
_maybe_remap_for_light_mode,
_output_history_lines,
_output_history_recording,
_output_history_rows,
_output_tail_fitting,
_painted_columns,
_PaintedLine,
_panel_box_width,
_post_stream_transform_output,
_prepend_note_to_message,
_preserve_windows_dot_segments_for_markdown,
_pt_app_is_running,
_pt_print_ansi,
_query_osc11_background,
_record_output_history,
_record_output_history_entry,
_release_paints,
_render_final_assistant_content,
_rich_text_from_ansi,
_set_chrome_floor,
_strip_markdown_syntax,
_strip_reasoning_tags,
_terminal_columns,
_terminal_reflows,
_terminal_width_for_streaming,
_tty_wrap,
_wrap_panel_text,
_wrap_panel_text_keep_ws,
)
from hermes_cli.cli_config_load import (
_AUXILIARY_TASK_ENV,
_CWD_PLACEHOLDERS,
_TERMINAL_ENV_MAPPINGS,
_cli_config_defaults,
_init_logging_and_display_from_config,
_load_prefill_messages,
_merge_file_config,
_mirror_config_to_env,
_parse_reasoning_config,
_parse_service_tier_config,
_resolve_prefill_messages_file,
load_cli_config,
)
from hermes_cli.cli_terminal_input import (
_BACKSLASH_LINE_CONTINUATION_RE,
_DSR_CPR_ESC_RE,
_DSR_CPR_VISIBLE_RE,
_EXTENDED_ENTER_KEYS_SEQ,
_IMAGE_EXTENSIONS,
_KITTY_KEYBOARD_PUSH_SEQ,
_MODIFY_OTHER_KEYS_SEQ,
_SGR_MOUSE_BARE_RE,
_SGR_MOUSE_ESC_RE,
_SGR_MOUSE_VISIBLE_RE,
_TERMINAL_INPUT_MODE_RESET_SEQ,
_apply_backslash_line_continuation,
_apply_bracketed_paste_timeout_patch,
_bind_prompt_submit_keys,
_build_cpr_disabled_output,
_cli_multiline_shortcuts_enabled,
_collect_query_images,
_detect_file_drop,
_disable_prompt_toolkit_cpr_warning,
_enable_extended_enter_keys,
_estimate_tui_input_height,
_file_drop_result,
_format_image_attachment_badges,
_hermes_call_output_screen_diff,
_is_backslash_line_continuation,
_is_ghostty_terminal,
_preserve_ctrl_enter_newline,
_resolve_attachment_path,
_select_classic_cli_pt_output,
_should_auto_attach_clipboard_image_on_paste,
_split_path_input,
_status_bar_visible_from_display_config,
_strip_leaked_terminal_responses_with_meta,
_terminal_may_leak_cpr,
_terminal_supports_extended_enter_keys,
_termux_example_image_path,
)
from hermes_cli.cli_single_query import (
_TERMINAL_PROVIDER_REASONS,
_TRANSIENT_PROVIDER_REASONS,
_collect_kanban_task_images,
_configure_quiet_agent,
_install_single_query_signal_handlers,
_int_or,
_interrupt_agent_for_signal,
_route_single_query_images,
_run_kanban_goal_loop_chat,
_run_kanban_goal_loop_q,
_run_quiet_single_query,
_run_single_query_mode,
_single_query_exit_code,
_sync_cli_session_id_from_agent,
)
try:
from prompt_toolkit.patch_stdout import patch_stdout
except ImportError: # partial/broken prompt_toolkit (#96075); sole use is a `with patch_stdout():`
from contextlib import nullcontext as patch_stdout
try:
from prompt_toolkit.enums import EditingMode
except ImportError: # partial prompt_toolkit stubs in tests
EditingMode = None
from prompt_toolkit import print_formatted_text as _pt_print
from prompt_toolkit.formatted_text import ANSI as _PT_ANSI
try:
from prompt_toolkit.cursor_shapes import CursorShape
_STEADY_CURSOR = CursorShape.BLOCK
except (ImportError, AttributeError):
_STEADY_CURSOR = None
try:
from hermes_cli import pt_input_extras as _pt_extras
_pt_extras.install_shift_enter_alias()
_pt_extras.install_ctrl_enter_alias()
_pt_extras.install_cmd_backspace_alias()
_pt_extras.install_modify_other_keys_aliases()
_pt_extras.install_keypress_data_normalization()
_pt_extras.install_ignored_terminal_sequences()
del _pt_extras
except Exception:
pass
import threading
import queue
from hermes_cli._startup_fast import project_root_str
def _lazy_shim(module: str, name: str, alias: str | None = None):
"""Import ``module.name`` on first call; keeps heavy imports off startup while ``cli.<name>`` stays patchable."""
import importlib
def shim(*args, **kwargs):
return getattr(importlib.import_module(module), name)(*args, **kwargs)
shim.__name__ = shim.__qualname__ = alias or name
return shim
def format_duration_compact(*args, **kwargs):
seconds = float(args[0] if args else kwargs.get("seconds", 0.0))
if seconds < 60:
return f"{seconds:.0f}s"
minutes = seconds / 60
if minutes < 60:
return f"{minutes:.0f}m"
hours = minutes / 60
if hours < 24:
remaining_min = int(minutes % 60)
return f"{int(hours)}h {remaining_min}m" if remaining_min else f"{int(hours)}h"
days = hours / 24
return f"{days:.1f}d"
# model id -> shortest configured alias (process-lifetime cache; config is read once).
_REVERSE_ALIAS_CACHE: dict[str, str] | None = None
def _reverse_alias_for_display(model_name: str) -> str:
"""Shortest alias for ``model_name`` from ``model_aliases:`` or ``model.aliases:``, else ``model_name``."""
global _REVERSE_ALIAS_CACHE
if not model_name:
return model_name
if _REVERSE_ALIAS_CACHE is None:
rmap: dict[str, str] = {}
def _put(m: str, alias: str) -> None:
if m and (m not in rmap or len(alias) < len(rmap[m])):
rmap[m] = alias
try:
from hermes_cli.config import load_config
cfg = load_config() or {}
ma = cfg.get("model_aliases")
if isinstance(ma, dict):
for alias, entry in ma.items():
if isinstance(entry, dict):
_put(str(entry.get("model", "") or "").strip(), alias)
mdl = cfg.get("model", {}) or {}
if isinstance(mdl, dict):
simple = mdl.get("aliases")
if isinstance(simple, dict):
for alias, val in simple.items():
if isinstance(val, str) and val.strip():
v = val.strip()
_put(v.split("/", 1)[1] if "/" in v else v, alias)
except Exception:
pass
_REVERSE_ALIAS_CACHE = rmap
return _REVERSE_ALIAS_CACHE.get(model_name, model_name)
def format_token_count_compact(*args, **kwargs):
value = int(args[0] if args else kwargs.get("value", 0))
abs_value = abs(value)
if abs_value < 1_000:
return str(value)
sign = "-" if value < 0 else ""
units = ((1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K"))
for threshold, suffix in units:
if abs_value >= threshold:
scaled = abs_value / threshold
text = f"{scaled:.{2 if scaled < 10 else 1 if scaled < 100 else 0}f}"
if "." in text:
text = text.rstrip("0").rstrip(".")
return f"{sign}{text}{suffix}"
return f"{value:,}"
realign_markdown_tables = _lazy_shim("agent.markdown_tables", "realign_markdown_tables")
_COMMAND_SPINNER_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
# ~/.hermes/.env first, project .env as dev fallback; user env files override stale shell exports.
from hermes_constants import get_hermes_home
from hermes_cli.env_loader import load_hermes_dotenv
from agent.i18n import t as _t
_hermes_home = get_hermes_home()
_project_env = Path(project_root_str()) / '.env'
load_hermes_dotenv(hermes_home=_hermes_home, project_env=_project_env)
CLI_CONFIG = load_cli_config()
_init_logging_and_display_from_config()
# Neuter AsyncHttpxClientWrapper.__del__ before any AsyncOpenAI client exists: it
# schedules aclose() on the running loop (prompt_toolkit's, during idle), closing
# transports bound to dead worker loops ("Event loop is closed" / "Press ENTER to
# continue..."). A meta_path finder patches ``openai._base_client`` at first import —
# eager import costs ~166ms/30MB cold, and the patch is guaranteed to land before
# instantiation. See ``agent.auxiliary_client.neuter_async_httpx_del``.
try:
import sys as _httpx_neuter_sys
import importlib.util as _httpx_neuter_imp_util
class _AsyncHttpxDelNeuter:
"""Patch ``AsyncHttpxClientWrapper.__del__`` to a no-op when ``openai._base_client`` loads."""
_armed = True
def find_spec(self, fullname, path=None, target=None):
if not self._armed or fullname != "openai._base_client":
return None
# Disarm before delegating so the recursive find_spec doesn't loop through us.
self._armed = False
try:
_httpx_neuter_sys.meta_path.remove(self)
except ValueError:
pass
spec = _httpx_neuter_imp_util.find_spec(fullname)
if spec is None or spec.loader is None:
return None
_orig_exec = spec.loader.exec_module
def _patched_exec(module):
_orig_exec(module)
try:
cls = getattr(module, "AsyncHttpxClientWrapper", None)
if cls is not None:
cls.__del__ = lambda self: None # type: ignore[assignment]
except Exception:
pass
spec.loader.exec_module = _patched_exec # type: ignore[method-assign]
return spec
_httpx_neuter_sys.meta_path.insert(0, _AsyncHttpxDelNeuter())
except Exception:
pass
# Agent/tool systems load lazily: bare startup only needs the prompt.
def get_tool_definitions(*args, **kwargs):
from hermes_cli.mcp_startup import wait_for_mcp_discovery
from model_tools import get_tool_definitions as _get_tool_definitions
wait_for_mcp_discovery()
return _get_tool_definitions(*args, **kwargs)
validate_toolset = _lazy_shim("toolsets", "validate_toolset")
_cleanup_all_terminals = _lazy_shim("tools.terminal_tool", "cleanup_all_environments", "_cleanup_all_terminals")
set_sudo_password_callback = _lazy_shim("tools.terminal_tool", "set_sudo_password_callback")
set_approval_callback = _lazy_shim("tools.terminal_tool", "set_approval_callback")
set_secret_capture_callback = _lazy_shim("tools.skills_tool", "set_secret_capture_callback")
_cleanup_all_browsers = _lazy_shim("tools.browser_session_lifecycle", "emergency_cleanup_all_sessions", "_cleanup_all_browsers")
_cleanup_done = False # _run_cleanup runs exactly once
_cleanup_in_progress = False
_session_end_messages: list[str] = [] # plugin on_session_finalize text awaiting the exit summary
_cli_wake_owner = None
# One-shot finalization runs before process cleanup (plugins see the boundary while the
# agent is attached); atexit cleanup must not finalize those sessions again.
_single_query_finalize_attempted_session_ids: set[str | None] = set()
# /handoff sessions belong to the gateway: finalizing them here would stamp end_reason on
# a row the gateway just reopened, making the handoff leg vanish from history.
# Session IDs that were handed off to the gateway via /handoff. The CLI process exits after a successful
# handoff, but the gateway now owns the session lifecycle — _run_cleanup must NOT call finalize_session on
# these, because doing so sets end_reason on a row the gateway just reopened and is actively writing to
# (#88234). The race made the handoff leg vanish from session history and broke session_search recall for
# the handed-off session.
_handed_off_session_ids: set[str | None] = set()
_active_agent_ref = None # active AIAgent, for memory-provider shutdown at exit
# Set once the TUI app starts (focus reporting + mouse tracking on); gates the on-exit
# terminal reset so non-TUI one-shot runs never emit codes for modes they never enabled.
_tui_input_modes_active = False
# Set True once the TUI's prompt_toolkit app starts (which enables focus reporting + mouse tracking). Gates
# the on-exit terminal reset so non-TUI one-shot CLI runs — which also register _run_cleanup via atexit —
# don't emit escape codes for modes they never enabled (#36823).
def _mark_tui_input_modes_active() -> None:
"""Record that the TUI app started, so _run_cleanup resets input modes."""
global _tui_input_modes_active
_tui_input_modes_active = True
_signal_watchdog_armed = False
def _arm_exit_watchdog_on_shutdown_signal() -> None:
"""Arm the exit backstop the moment a termination signal arrives (idempotent; never raises).
The graceful unwind has wedge points BEFORE ``_run_cleanup`` arms its own watchdog
(main thread in a syscall, prompt_toolkit teardown never returning). Leash is 2x
the cleanup timeout so a progressing cleanup is never cut short. Never arm at
startup: the timer exits unconditionally.
SIGTERM/SIGHUP establish unambiguous shutdown intent, but the graceful path from signal →
``agent.interrupt()`` → ``app.exit()`` / ``KeyboardInterrupt`` → ``finally`` → ``_run_cleanup`` has
several wedge points BEFORE ``_run_cleanup`` arms the normal watchdog: a main thread parked in a syscall
that never observes the unwind, a prompt_toolkit teardown that never returns, or an agent worker
blocking the ``finally``. When that happens the process has NO backstop and a "dead" CLI lingers
(observed: ``hermes --tui`` alive ~47 min at 4% CPU after terminal close — the #65998 class).
"""
global _signal_watchdog_armed
if _signal_watchdog_armed:
return
_signal_watchdog_armed = True
base = _exit_watchdog_timeout()
if base <= 0:
return # explicitly disabled
with suppress(Exception): # never let the backstop break signal handling
_arm_exit_watchdog(timeout_s=base * 2, from_signal=True)
def _run_cleanup(*, notify_session_finalize: bool = True):
"""Run resource cleanup exactly once."""
global _cleanup_done, _cleanup_in_progress
if _cleanup_done:
return
_cleanup_done = True
_cleanup_in_progress = True
try:
_arm_exit_watchdog()
# Reset terminal input modes FIRST: teardown below can take seconds and a later
# step raising must not skip the reset. No-op unless the TUI ran.
# See #36823.
_reset_terminal_input_modes_on_exit()
for step, swallow in _CLEANUP_STEPS:
with suppress(swallow):
globals()[step]()
if notify_session_finalize:
cleanup_session_id = _active_agent_ref.session_id if _active_agent_ref else None
if _should_emit_cleanup_session_finalize(cleanup_session_id):
# Printed by _print_exit_summary, which clears the screen first.
_session_end_messages.extend(
_notify_session_finalize(session_id=cleanup_session_id, platform="cli", reason="shutdown"))
try:
_shutdown_agent_memory_provider(_active_agent_ref)
except Exception as e:
logger.warning("CLI cleanup memory shutdown failed: %s", e, exc_info=True)
finally:
_cleanup_in_progress = False
def _reset_terminal_input_modes_on_exit() -> None:
"""Disable focus reporting + mouse tracking on TUI exit (best-effort).
Ctrl+C / SIGTERM / crashes bypass prompt_toolkit's unwind, leaving focus events and
mouse reports as visible text in the next shell. Writes to stdout when it is the
terminal, else /dev/tty (the TUI may have run with stdout redirected).
Called from ``_run_cleanup`` (atexit-registered + invoked on the normal / EOF / interrupt exit paths)
this covers normal quit, Ctrl+C and SIGTERM/SIGHUP. ``kill -9`` is uncatchable, and the kanban worker's
``os._exit(0)`` path bypasses ``atexit``; neither runs this — but both are non-TTY / non-TUI, so there
is nothing to reset there. See #36823.
"""
global _tui_input_modes_active
if not _tui_input_modes_active:
return
# Clear first so a re-armed _run_cleanup doesn't re-emit.
_tui_input_modes_active = False
try:
stream = sys.stdout
if stream is not None and stream.isatty():
stream.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
stream.flush()
return
except Exception:
pass
with suppress(Exception), open("/dev/tty", "w", encoding="ascii") as tty:
tty.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
tty.flush()
from hermes_cli.worktree_ops import (
_git_quiet,
_git_repo_root,
_maintain_pack_health,
_prune_stale_worktrees,
_repo_is_shallow,
_setup_worktree,
_worktree_has_unpushed_commits,
_worktree_is_dirty,
release_lsp_clients,
)
# ============================================================================= Git Worktree Isolation
# (#652) =============================================================================
_active_worktree: Optional[dict[str, str]] = None
def _cleanup_worktree(info: dict[str, str] | None = None) -> None:
"""Remove a clean worktree and its branch on exit; preserve recoverable work."""
global _active_worktree
info = info or _active_worktree
if not info:
return
wt_path, branch, repo_root = info["path"], info["branch"], info["repo_root"]
if not Path(wt_path).exists():
return
_active_worktree = None
from hermes_cli.worktree_exit import apply_exit_choice
if apply_exit_choice(info, _cprint): # an exit-question answer not applied yet (normally none)
return
if _worktree_is_dirty(wt_path, repo_root, timeout=10):
# Uncommitted work: say so, and don't hint at `remove --force`, which would destroy it.
_cprint(f"\n\033[33m{_t('cli.worktree.uncommitted_keeping', path=wt_path)}\033[0m")
return
if _worktree_has_unpushed_commits(wt_path, timeout=10):
if _repo_is_shallow(repo_root):
# Shallow boundary makes the unpushed verdict unreliable; the startup pruner reaps later.
_cprint(f"\n\033[33m{_t('cli.worktree.shallow_clone_keeping', path=wt_path)}\033[0m")
print(f" {_t('cli.worktree.next_session_deepens')}")
else:
_cprint(f"\n\033[33m{_t('cli.worktree.unpushed_keeping', path=wt_path)}\033[0m")
print(f" {_t('cli.worktree.clean_up_manually', path=wt_path)}")
return
from hermes_cli.worktree_ops import removal_blocked
blocked = removal_blocked(wt_path) # an embedded repo or private ref dies with it
if blocked:
_cprint(f"\n\033[33m{_t('cli.worktree.kept_reason', path=wt_path, reason=blocked[1])}\033[0m")
return
# Release the tree's language servers while the path still exists, then unlock so `remove`
# isn't blocked by the lock placed at creation. Fail-soft.
release_lsp_clients(wt_path)
_git_quiet(["worktree", "unlock", wt_path], repo_root, log="git worktree unlock failed (non-fatal)")
_git_quiet(["worktree", "remove", wt_path, "--force"], repo_root, timeout=15, log="Failed to remove worktree")
# `branch -D` runs the repository's reference-transaction hook under a plain environment.
from hermes_cli._subprocess_compat import noninteractive_git_env
_git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}", env=noninteractive_git_env())
_cprint(f"\033[32m{_t('cli.worktree.cleaned_up', path=wt_path)}\033[0m")
# Light/dark terminal detection (mirrors ui-tui/src/theme.ts detectLightMode()). Priority:
# HERMES_LIGHT/HERMES_TUI_LIGHT env, HERMES_TUI_THEME, HERMES_TUI_BACKGROUND, COLORFGBG
# (bg slot 7/15 = light), OSC 11 query, default dark. Cached so the terminal is queried once.
_LIGHT_MODE_CACHE: bool | None = None
def _detect_light_mode() -> bool:
global _LIGHT_MODE_CACHE
if _LIGHT_MODE_CACHE is not None:
return _LIGHT_MODE_CACHE
try:
result = _detect_light_mode_uncached()
except Exception:
result = False
_LIGHT_MODE_CACHE = result
return result
_install_skin_light_mode_hook()
# Prime the light-mode cache when interactive so OSC 11 happens before prompt_toolkit owns the tty.
with suppress(Exception):
if sys.stdin.isatty() and sys.stdout.isatty():
_detect_light_mode()
_OUTPUT_HISTORY_ENABLED = True
_OUTPUT_HISTORY_REPLAYING = False
_OUTPUT_HISTORY_SUPPRESSED = False
_OUTPUT_HISTORY_MAX_LINES = 200
_OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
def _configure_output_history(enabled: bool, max_lines=200) -> None:
"""Configure recent CLI output replayed after terminal redraws."""
global _OUTPUT_HISTORY_ENABLED, _OUTPUT_HISTORY_MAX_LINES, _OUTPUT_HISTORY
_OUTPUT_HISTORY_ENABLED = bool(enabled)
_OUTPUT_HISTORY_MAX_LINES = _coerce_output_history_limit(max_lines)
_OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
@contextmanager
def _suspend_output_history():
global _OUTPUT_HISTORY_SUPPRESSED
old_value = _OUTPUT_HISTORY_SUPPRESSED
_OUTPUT_HISTORY_SUPPRESSED = True
try:
yield
finally:
_OUTPUT_HISTORY_SUPPRESSED = old_value
def _replay_output_history(fit=None, output=None) -> None:
"""Repaint recent output above the prompt after a full screen clear.
``fit=(rows, columns, painted, top)`` replays only the newest lines whose wrapped height
fits ``rows`` (see ``_output_tail_fitting``) — the older ones are still in scrollback
(#95375) — from screen row ``top`` when known (``_set_chrome_floor``). ``output``: paint
now, straight to this prompt_toolkit output, where the caller just erased the viewport and
reset the renderer — ``run_in_terminal`` would first erase below the top row, which
scroll-on-clear terminals (tmux) take as a clear and copy the blank screen into scrollback.
"""
global _OUTPUT_HISTORY_REPLAYING
if not _OUTPUT_HISTORY_ENABLED or not _OUTPUT_HISTORY:
return
_OUTPUT_HISTORY_REPLAYING = True
try:
rendered_lines = _output_history_lines()
top = None
if fit is not None:
rows, columns, painted, top = fit
rendered_lines = _output_tail_fitting(rendered_lines, rows, columns, painted)
if rendered_lines:
# One payload: per-line pt prints each force a sync redraw (a waterfall of old output).
if output is None:
_pt_print(_PT_ANSI("\n".join(rendered_lines)))
else:
from prompt_toolkit.renderer import print_formatted_text as _paint_formatted_text
from prompt_toolkit.styles import Style
_paint_formatted_text(output, _PT_ANSI("\n".join(rendered_lines) + "\n"), Style([]))
size = output.get_size()
if top is not None: # the chrome's top is now this many rows down
top += sum(_line_rows(line, columns) for line in rendered_lines)
_set_chrome_floor(max(0, size.rows - top))
if size.columns != columns:
_add_suspect_rows(top + 1 - size.rows)
width = _painted_columns() if fit is None else columns
for line in rendered_lines: # repainted: they wrap at today's width from now on
if isinstance(line, _PaintedLine):
line.width = width
except Exception:
pass
finally:
_OUTPUT_HISTORY_REPLAYING = False
_strip_leaked_bracketed_paste_wrappers = _lazy_shim(
"hermes_cli.input_sanitize", "strip_leaked_bracketed_paste_wrappers", "_strip_leaked_bracketed_paste_wrappers"
)
# OSC sequences (e.g. OSC-8 links): pt's ANSI parser strips the ESC but leaks the payload as text.
_OSC_ESCAPE_RE = re.compile(r"\x1b\][\s\S]*?(?:\x07|\x1b\\)")
def _looks_like_slash_command(text: str) -> bool:
"""``/help`` yes, ``/Users/x/file.md`` no: a command's first word has no further ``/``."""
if not text or not text.startswith("/"):
return False
return "/" not in text.split()[0][1:]
_skill_commands = None
_skill_bundles = None
def _slash_args(cmd: str) -> str:
"""Text after the slash-command word, stripped ("" when absent)."""
parts = cmd.split(None, 1)
return parts[1].strip() if len(parts) > 1 else ""
def _ensure_skill_commands() -> dict:
if _skill_commands is not None:
return _skill_commands
from agent.skill_commands import get_interactive_skill_commands
return get_interactive_skill_commands()
def get_skill_commands() -> dict:
return _ensure_skill_commands()
def _session_skill_commands(cli) -> dict:
"""Skill commands for ``cli``: on its gateway session the gateway's (its plugin skills included), so
this process scans no plugin to list them; otherwise this process's own."""
from hermes_cli import gateway_plugin_commands
found = gateway_plugin_commands.skills(cli)
return _ensure_skill_commands() if found is None else found
build_skill_invocation_message = _lazy_shim("agent.skill_commands", "build_skill_invocation_message")
build_preloaded_skills_prompt = _lazy_shim("agent.skill_commands", "build_preloaded_skills_prompt")
def get_skill_bundles() -> dict:
global _skill_bundles
if _skill_bundles is None:
from agent.skill_bundles import get_skill_bundles as _impl
_skill_bundles = _impl()
return _skill_bundles
build_bundle_invocation_message = _lazy_shim("agent.skill_bundles", "build_bundle_invocation_message")
def _get_plugin_cmd_handler_names() -> set:
"""Return plugin command names (without slash prefix) for dispatch matching."""
try:
from hermes_cli.plugins import get_plugin_commands
return set(get_plugin_commands().keys())
except Exception:
return set()
def _parse_skills_argument(skills: str | list[str] | tuple[str, ...] | None) -> list[str]:
"""Normalize a CLI skills flag into a deduplicated list of skill identifiers."""
if not skills:
return []
raw_values = [str(item) for item in skills if item is not None] if isinstance(skills, (list, tuple)) else [str(skills)]
parts = (p.strip() for raw in raw_values for p in raw.split(","))
return list(dict.fromkeys(p for p in parts if p))
def save_config_value(key_path: str, value: any) -> bool:
"""Persist dot-separated ``key_path`` = value into HERMES_HOME/config.yaml; True on success.
Never the repo's cli-config.yaml: no config reader loads it, so the value would vanish.
"""
config_path = get_hermes_home() / 'config.yaml'
try:
from hermes_constants import mkdir_under_hermes_home
mkdir_under_hermes_home(config_path.parent)
from hermes_cli.config_backend import write_config_key
write_config_key(config_path, key_path, value)
try: # owner-only: config files contain API keys
os.chmod(config_path, 0o600)
except (OSError, NotImplementedError):
pass
return True
except Exception as e:
logger.error("Failed to save config: %s", e)
return False
def _normalize_moa_model(model: Optional[str]) -> tuple[Optional[str], Optional[str]]:
"""``moa:<preset>`` -> ``("moa", preset)`` (same routing as ``/moa``); anything else -> ``(None, model)``.
Returns ``("moa", "<preset>")`` when *model* selects the MoA virtual provider, otherwise ``(None,
model)`` unchanged. This gives non-interactive ``hermes chat -Q -m moa:<preset>`` the same routing the
interactive ``/moa`` command and the model picker already use: ``resolve_runtime_provider`` handles
``requested_provider == "moa"`` and ``agent_init`` builds the MoAClient off ``provider == "moa"``.
Without this the raw ``moa:<preset>`` string is sent to the real provider and rejected with a 401/400
"model not supported" (#56828).
"""
if isinstance(model, str) and model.strip().lower().startswith("moa:"):
preset = model.strip().split(":", 1)[1].strip()
if preset:
return "moa", preset
return None, model
_split_model_config_default = _lazy_shim("hermes_cli.config", "split_model_config_default", "_split_model_config_default")
class _VoiceInputMessage:
"""Sentinel for voice-transcribed input so the concise voice prefix never applies to typed text.
Distinguishes STT output from manually typed text while voice mode is active, so the
concise-voice-response prefix is applied only to messages that actually came from the microphone
(#65827).
"""
__slots__ = ("text",)
def __init__(self, text: str):
self.text = text
def __str__(self) -> str:
return self.text
class _SeededQueryMessage:
"""Sentinel for a ``-q`` prompt seeded into an interactive session; treated LITERALLY (no slash/!/file-drop)."""
__slots__ = ("admission_id", "images", "text")
def __init__(self, text: str, images=None, admission_id=None):
self.text = text or ""
self.images = list(images or [])
# A ``/queue`` admission the gateway is running (#134889 N5): ``run_conversation`` pumps that
# admission by this id, never by comparing the (sanitized) text.
self.admission_id = admission_id
def __str__(self) -> str:
return self.text
def _should_seed_interactive(query, image, quiet: bool, oneshot: bool) -> bool:
"""``-q`` seeds an interactive session only on a real TTY without ``--oneshot``/``-Q`` (automation answers and exits)."""
if not (query or image) or oneshot or quiet:
return False
try:
return bool(sys.stdin.isatty() and sys.stdout.isatty())
except Exception:
return False
@dataclass
class _ChatTurn:
"""Per-turn state shared by the ``chat()`` phases and the agent worker thread.
``result`` is written by the worker and read after the join; ``tts_normal_exit`` is
set only when the TTS worker drained on its own so the last sentence is never cut.
"""
result: Optional[dict] = None
mute_notification_reply: bool = False
use_streaming_tts: bool = False
box_opened: bool = False
thinking_started: bool = False
text_queue: Optional[queue.Queue] = None
tts_thread: Optional[threading.Thread] = None
stream_callback: Optional[Any] = None
stop_event: Optional[threading.Event] = None
tts_normal_exit: bool = False
voice_prefix: str = ""
from hermes_cli.cli_chat_turn_mixin import CLIChatTurnMixin
_PASTE_REF_RE = re.compile(r'\[Pasted text #\d+: \d+ lines \u2192 (.+?)\]')
class HermesCLI(CLIBacktrackMixin, CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixin, CLIStatusBarMixin, CLIVoiceMixin, CLIModelSwitchMixin, CLISessionMixin, CLIStreamMixin, CLIModalMixin, CLITerminalMixin, CLIInfoMixin, CLILoopsMixin, CLIChatTurnMixin):
"""Interactive REPL for the Hermes Agent."""
# Seeded -q first message (see _should_seed_interactive); run() re-creates
# _pending_input, so it is enqueued only after the fresh queue exists.
_seeded_first_message: Optional[_SeededQueryMessage] = None
# Inspection surfaces (banner, /tools, status line) read this on partially built instances too.
disabled_toolsets: Optional[list[str]] = None
def __init__(
self,
model: str | None = None,
toolsets: list[str] | None = None,
provider: str | None = None,
reasoning: str | None = None,
api_key: str | None = None,
base_url: str | None = None,
max_turns: int | None = None,
run_budget: float | None = None,
verbose: Optional[bool] = None,
compact: bool = False,
resume: str | None = None,
checkpoints: bool = False,
pass_session_id: bool = False,
ignore_rules: bool = False,
):
"""CLI args win over config; ``reasoning`` is per-run only; ``resume`` restores history from SQLite."""
self._init_display_options(verbose, compact)
self._init_model_routing(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
checkpoints, pass_session_id, ignore_rules)
self._init_runtime_state(resume)
def _claim_active_session(self, surface: str = "cli", *, stderr: bool = False) -> bool:
"""Claim a global active-session slot for this CLI process."""
if self._active_session_lease is not None:
return True
try:
from hermes_cli.active_sessions import format_refusal_stderr, try_acquire_active_session
lease, message = try_acquire_active_session(
session_id=self.session_id,
surface=surface,
config=self.config,
# Writer identity: a re-claim by this process replaces its own entry.
# See #94595.
metadata={"live_session_id": str(self.session_id)},
)
except Exception as exc:
logger.warning("Failed to claim active session slot: %s", exc)
return True
if message:
print(format_refusal_stderr(message), file=sys.stderr) if stderr else self._console_print(f"[bold red]{message}[/]")
return False
self._active_session_lease = lease
with suppress(Exception):
atexit.register(self._release_active_session)
return True
def _release_active_session(self) -> None:
lease = getattr(self, "_active_session_lease", None)
if lease is None:
return
try:
lease.release()
except Exception:
logger.debug("Failed to release active session slot", exc_info=True)
finally:
self._active_session_lease = None
_PET_FRAME_INTERVAL = 0.16
_PET_CFG_INTERVAL = 2.5
def _install_tool_callbacks(self) -> None:
"""Install tool callbacks that need the live prompt UI."""
if self._tool_callbacks_installed:
return
set_sudo_password_callback(self._sudo_password_callback)
set_approval_callback(self._approval_callback)
set_secret_capture_callback(self._secret_capture_callback)
from agent.vault_backends.unlock import set_code_prompt_callback, set_save_login_prompt_callback, set_unlock_prompt_callback
set_unlock_prompt_callback(self._vault_unlock_callback)
set_save_login_prompt_callback(self._vault_save_login_callback)
set_code_prompt_callback(self._vault_code_callback)
self._tool_callbacks_installed = True
def _show_security_advisories(self):
"""Startup banner for unacked security advisories, on stderr (piped stdout stays clean); 24h rate-limited."""
try:
from hermes_cli.security_advisories import detect_compromised, startup_banner
banner = startup_banner(detect_compromised())
if banner:
print(banner, file=sys.stderr, flush=True)
except Exception:
pass # never block startup
def finalize_preloaded_skills(self) -> None:
"""Join the background --skills preload and fold it into the prompt (idempotent).
Raises ``ValueError`` only when EVERY requested skill was unknown.
"""
if getattr(self, "_preload_skills_finalized", False):
return
thread = getattr(self, "_preload_skills_thread", None)
if thread is None:
self._preload_skills_finalized = True
return
thread.join(timeout=120)
self._preload_skills_finalized = True
err = getattr(self, "_preload_skills_error", None)
if err is not None:
raise err
auto_result = getattr(self, "_auto_load_skills_result", None)
if auto_result and auto_result[2]:
logger.warning("skills.auto_load: skill(s) not found or disabled, skipped: %s", ", ".join(auto_result[2]))
# auto_load names first, then explicit -s names that were not already pinned.
self.preloaded_skills = list(auto_result[1]) if auto_result else []
result = getattr(self, "_preload_skills_result", None)
if not result:
return
skills_prompt, loaded_skills, missing_skills = result
if missing_skills:
from agent.skill_commands import format_missing_skills
# A typo'd name must not crash a kanban worker; only a fully-missing set fails loudly.
if not loaded_skills:
raise ValueError(format_missing_skills(missing_skills))
logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
format_missing_skills(missing_skills), ", ".join(loaded_skills))
if skills_prompt:
self.system_prompt = "\n\n".join(p for p in (self.system_prompt, skills_prompt) if p).strip()
self.preloaded_skills += [name for name in loaded_skills if name not in self.preloaded_skills]
def _show_tool_availability_warnings(self):
"""Warn about toolsets switched off at startup (missing API keys, unusable terminal backend)."""
try:
# Runs on a daemon thread on the snapshot fast path: keep the imports to modules the
# registry walk already loaded plus the pure notices module (a heavy import here races
# importlib's module locks against the main thread).
from model_tools import check_tool_availability
from hermes_cli.tool_availability_notices import (
current_terminal_backend, filter_to_enabled_toolsets, tool_availability_warning_lines,
)
from tools.terminal_tool import terminal_backend_unavailable_reason
from toolsets import resolve_toolset
_, unavailable = check_tool_availability()
# Only toolsets this CLI session actually has. The selection is usually a composite bundle
# (``hermes-cli``), so expand it to tool names before matching — a raw name comparison
# matched nothing on a default install and silently dropped the terminal notice.
unavailable = filter_to_enabled_toolsets(unavailable, self.enabled_toolsets or [], resolve_toolset)
lines = tool_availability_warning_lines(
unavailable, terminal_reason=terminal_backend_unavailable_reason(),
terminal_backend=current_terminal_backend())
if lines:
self._console_print()
for line in lines:
self._console_print(line)
except Exception:
pass
def show_config(self):
"""Display current configuration with kawaii ASCII art."""
from hermes_cli.config_backend import config_exists
from hermes_cli.config import DEFAULT_CONFIG, cfg_get
from hermes_cli.config_turn_limit import turn_limit_label
terminal_env = os.getenv("TERMINAL_ENV", "local")
terminal_cwd = os.getenv("TERMINAL_CWD", os.getcwd())
terminal_timeout = os.getenv("TERMINAL_TIMEOUT") or cfg_get(DEFAULT_CONFIG, "terminal", "timeout")
config_path = _hermes_home / 'config.yaml'
config_status = _t("cli.config.loaded") if config_exists(config_path) else _t("cli.config.not_found")
from hermes_cli.config_backend import get_config_backend
if not get_config_backend().supports_file_tooling(): # no local file: name where config comes from
config_path, config_status = get_config_backend().describe(_hermes_home), ""
# ``api_key`` may be a callable bearer provider (Entra ID, Vertex OAuth, key_cmd, ...):
# label it by its tagged source and never invoke it (that would mint a token just to mask
# it). Prefer the LIVE agent's key: the constructor seeds self.api_key from env before
# provider resolution, so on non-OpenAI providers it can be another vendor's key.
from agent.credential_source import credential_label
display_key = self.api_key
if self.agent is not None and getattr(self.agent, "api_key", None):
display_key = self.agent.api_key
if label := credential_label(display_key):
api_key_display = label
elif isinstance(display_key, str) and len(display_key) > 12:
api_key_display = f"{display_key[:8]}...{display_key[-4:]}"
else:
api_key_display = _t("cli.config.api_key_not_set")
title = _t("cli.config.title")
width = 50
pad = width - len(title)
_unset = _t("cli.config.value_not_set")
ssh_target = (
f"{os.getenv('TERMINAL_SSH_USER', _unset)}@{os.getenv('TERMINAL_SSH_HOST', _unset)}"
f":{os.getenv('TERMINAL_SSH_PORT', '22')}"
) if terminal_env == "ssh" else None
# (section key, ((label key, value), ...)); labels are re-padded at print time so
# translated widths still line up instead of carrying alignment spaces in the catalog.
sections = (
("cli.config.section_model", (
("cli.config.label_model", self.model),
("cli.config.label_base_url", self.base_url),
("cli.config.label_api_key", api_key_display))),
("cli.config.section_terminal", (
("cli.config.label_environment", terminal_env),
*((("cli.config.label_ssh_target", ssh_target),) if ssh_target else ()),
("cli.config.label_working_dir", terminal_cwd),
("cli.config.label_timeout", f"{terminal_timeout}s"),
)),
("cli.config.section_agent", (
("cli.config.label_max_turns", turn_limit_label(self.max_turns)),
("cli.config.label_toolsets", ", ".join(self.enabled_toolsets) if self.enabled_toolsets else "all"),
("cli.config.label_verbose", self.verbose),
)),
("cli.config.section_session", (
("cli.config.label_started", self.session_start.strftime("%Y-%m-%d %H:%M:%S")),
("cli.config.label_config_file", f"{config_path} {config_status}"),
)),
)
print()
print("+" + "-" * width + "+")
print("|" + " " * (pad // 2) + title + " " * (pad - pad // 2) + "|")
print("+" + "-" * width + "+")
for section_key, rows in sections:
print()
print(f" -- {_t(section_key)} --")
label_width = max(len(_t(label_key)) for label_key, _ in rows)
for label_key, value in rows:
print(f" {_t(label_key):<{label_width}} {value}")
print()
# canonical command -> (method name, pass cmd_original?). Absent commands resolve to
# ``_handle_<name>_command(cmd)``. Looked up via getattr at dispatch time so
# monkeypatching works. A handler returning False exits the REPL.
_SLASH_DISPATCH: dict[str, tuple[str, bool]] = {
"exit": ("_cmd_exit", True), "quit": ("_cmd_exit", True), "help": ("_cmd_help", True),
"palette": ("_open_command_palette", False), "whoami": ("_handle_whoami_command", False),
"profile": ("_handle_profile_command", False), "toolsets": ("show_toolsets", False),
"config": ("show_config", False), "redraw": ("_cmd_redraw", True), "clear": ("_cmd_clear", True),
"history": ("show_history", False), "title": ("_cmd_title", True), "new": ("_cmd_new", True),
"model": ("_handle_model_switch", True), "codex-runtime": ("_handle_codex_runtime", True),
"retry": ("_cmd_retry", True), "prompt": ("_handle_prompt_compose_command", True),
"undo": ("_cmd_undo", True), "save": ("save_conversation", True), "skills": ("_cmd_skills", True),
"platforms": ("_show_gateway_status", False), "status": ("_show_session_status", False),
"context": ("_show_context_breakdown", True), "egress": ("_cmd_egress", True),
"statusbar": ("_cmd_statusbar", True), "verbose": ("_toggle_verbose", False), "yolo": ("_toggle_yolo", False),
"compress": ("_manual_compress", True), "subscription": ("_show_subscription", False),
"topup": ("_show_billing", True), "insights": ("_show_insights", True), "update": ("_cmd_update", True),
"version": ("_cmd_version", True), "paste": ("_handle_paste_command", False), "reload": ("_cmd_reload", True),
"reload-mcp": ("_confirm_and_reload_mcp", True), "reload-skills": ("_cmd_reload_skills", True),
"plugins": ("_cmd_plugins", True), "stop": ("_handle_stop_command", False),
"agents": ("_handle_agents_command", False), "bg": ("_handle_background_command", True),
"queue": ("_cmd_queue", True), "steer": ("_cmd_steer", True), "moa": ("_cmd_moa", True),
}
@classmethod
def _slash_handler(cls, canonical: str) -> tuple[str, bool] | None:
"""(method name, pass cmd_original?) for a registered command, else None."""
entry = cls._SLASH_DISPATCH.get(canonical)
if entry is None:
name = f"_handle_{canonical.replace('-', '_')}_command"
if callable(getattr(cls, name, None)):
entry = (name, True)
return entry
# Shared-metrics surface for user-typed commands; None where another process owns the count
# (the TUI slash worker: tui_gateway records the command it forwards).
_slash_metrics_surface: str | None = "cli"
def process_command(self, command: str, *, redispatch: bool = False) -> bool:
"""Dispatch a slash command; returns False to exit the REPL. ``redispatch`` marks an internal
re-entry (quick-command alias, prefix expansion) so the user's command is counted once."""
cmd_lower = command.lower().strip() # lowercase only for matching; args keep their case
cmd_original = command.strip()
# Aliases resolve via the central registry (hermes_cli/commands.py).
from hermes_cli.commands import resolve_command as _resolve_cmd
_base_word = cmd_lower.split()[0].lstrip("/")
_cmd_def = _resolve_cmd(_base_word)
canonical = _cmd_def.name if _cmd_def else _base_word
if not redispatch and self._slash_metrics_surface:
from hermes_cli.observability.shared_metrics_events import record_slash_command
record_slash_command(command=canonical, surface=self._slash_metrics_surface)
# A bare `/resume` prompt is one-shot: any other command disarms it so a later
# number isn't swallowed as a stale selection.
# See #34584.
if canonical not in {"resume", "sessions"}:
# Armed when a bare `/resume` prints the recent-sessions list so the very next bare numeric
# input (e.g. `3`) resolves to that session. Holds the exact list used for index resolution;
# one-shot (cleared on the next submitted input, whether it's the selection or anything else).
# See #34584.
self._pending_resume_sessions = None
entry = self._slash_handler(canonical)
from hermes_cli.gateway_setting_commands import run as run_gateway_setting
if entry is not None and run_gateway_setting(self, canonical, cmd_original):
return True # a per-session setting the gateway's handler applied (pre_command fired there)
# Observer-only pre_command plugin hook (return values ignored; never raises), fired by the gateway
# for a command this process runs (not a named refusal, not a command with no handler here).
from hermes_cli.gateway_cli_commands import REFUSED
from hermes_cli.gateway_plugin_commands import observe
runs = entry is not None and canonical not in REFUSED
if _cmd_def is not None and not observe(self, _base_word, _slash_args(cmd_original), runs=runs):
from hermes_cli.plugins import fire_pre_command_hook
fire_pre_command_hook(
surface="cli", command=canonical, alias_used=_base_word, args_raw=_slash_args(cmd_original),
session_key=getattr(self, "session_id", None), platform="cli",
)
if entry is None:
return self._process_unregistered_slash(cmd_original, cmd_lower)
from hermes_cli.gateway_cli_commands import EXIT_SESSION, run as run_gateway_command
if answered := run_gateway_command(self, canonical, cmd_original):
return answered is not EXIT_SESSION # state the gateway session owns (checkpoints, .env, handoff)
method_name, pass_arg = entry
handler = getattr(self, method_name)
result = handler(cmd_original) if pass_arg else handler()
return result is not False
def _process_unregistered_slash(self, cmd_original: str, cmd_lower: str) -> bool:
"""Slash input with no built-in handler; precedence: quick_commands -> plugins -> bundles -> skills -> prefix expansion."""
base_cmd = cmd_lower.split()[0]
bare = base_cmd.lstrip("/")
skill_bundles = get_skill_bundles()
quick_commands = self.config.get("quick_commands", {})
user_args = cmd_original[len(base_cmd):].strip()
if bare in quick_commands:
return self._run_quick_command(base_cmd, quick_commands[bare], user_args)
from hermes_cli import gateway_plugin_commands
try:
plugin = gateway_plugin_commands.lookup(self, bare) # the gateway's; None off the gateway
except gateway_plugin_commands.CatalogUnavailable:
return True # printed; an unreadable catalog never selects a skill, bundle or expansion
gone = False
skill_commands = _session_skill_commands(self) # after lookup: the catalog its miss re-read
if plugin or (plugin is None and bare in _get_plugin_cmd_handler_names()):
gone = self._run_plugin_slash_command(base_cmd, user_args) is gateway_plugin_commands.GONE
if not gone:
return True
skill_commands = _session_skill_commands(self) # the reload may have changed the skills
if base_cmd in skill_bundles: # also a name a gateway plugin reload just dropped (GONE)
self._run_skill_bundle_command(base_cmd, skill_bundles[base_cmd], user_args)
elif base_cmd in skill_commands:
self._run_skill_slash_command(base_cmd, skill_commands[base_cmd], user_args)
elif not (gone and gateway_plugin_commands.report_gone(bare, skill_commands, skill_bundles)):
return self._expand_slash_prefix(cmd_original, cmd_lower, skill_commands, skill_bundles)
return True
def _run_quick_command(self, base_cmd: str, qcmd: dict, user_args: str) -> bool:
"""User-defined quick command (config.yaml): ``exec`` runs a shell snippet, ``alias`` re-dispatches."""
qtype = qcmd.get("type")
if qtype == "alias":
target = qcmd.get("target", "").strip()
if target:
target = target if target.startswith("/") else f"/{target}"
return self.process_command(f"{target} {user_args}".strip(), redispatch=True)
self._console_print(f"[bold red]{_t('cli.quick.no_target', command=base_cmd)}[/]")
return True
if qtype != "exec":
self._console_print(f"[bold red]{_t('cli.quick.unsupported_type', command=base_cmd)}[/]")
return True
import subprocess
exec_cmd = qcmd.get("command", "")
if not exec_cmd:
self._console_print(f"[bold red]{_t('cli.quick.no_command', command=base_cmd)}[/]")
return True
from hermes_cli.profiles_run_elsewhere import run_elsewhere_refusal
if refused := run_elsewhere_refusal(): # asked per command: this chat may predate the marker
self._console_print(f"[bold red]{refused}[/]")
return True
try:
# shell=True is intentional (user-authored config snippets, never LLM controlled);
# the env is sanitized because this process holds every API key.
from tools.environments.local import build_subprocess_env
from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
exec_cmd, shell=True, capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=30, env=build_subprocess_env(),
creationflags=windows_hide_flags(), # no console flash on Windows (#56747),
check=False,
)
# See #56747.
output = result.stdout.strip() or result.stderr.strip()
if output:
from agent.redact import redact_sensitive_text
self._console_print(_rich_text_from_ansi(redact_sensitive_text(output)))
else:
self._console_print(f"[dim]{_t('cli.quick.no_output')}[/]")
except subprocess.TimeoutExpired:
self._console_print(f"[bold red]{_t('cli.quick.timed_out')}[/]")
except Exception as e:
self._console_print(f"[bold red]{_t('cli.quick.error', error=str(e))}[/]")
return True
def _run_plugin_slash_command(self, base_cmd: str, user_args: str):
from hermes_cli import gateway_plugin_commands
answered = gateway_plugin_commands.run(self, base_cmd.lstrip("/"), user_args)
if answered:
return answered # ran beside the plugin's hooks, tools and MCP servers in the gateway, or GONE
from hermes_cli.plugin_command_dispatch import invoke_plugin_command
from hermes_cli.plugins import get_plugin_command_handler, resolve_plugin_command_result
plugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))
if not plugin_handler:
return
session_id = getattr(self, "session_id", None) or ""
from hermes_cli.plugin_choices import bind_asker, clarify_asker
try:
with bind_asker(clarify_asker(self._clarify_callback)): # ctx.ask_choice: the clarify panel
result = resolve_plugin_command_result(invoke_plugin_command(
plugin_handler, user_args, source=None, session_id=session_id, session_key=session_id,
platform="cli"))
if result:
_cprint(str(result))
except Exception as e:
_cprint(f"\033[1;31m{_t('cli.plugin.command_error', error=str(e))}{_RST}")
def _queue_skill_message(self, msg) -> None:
if hasattr(self, '_pending_input'):
self._pending_input.put(msg)
def _run_skill_bundle_command(self, base_cmd: str, bundle_info: dict, user_instruction: str) -> None:
"""``/<bundle>`` loads several skills at once (bundles win over same-named skills)."""
bundle_result = build_bundle_invocation_message(base_cmd, user_instruction, task_id=self.session_id)
if not bundle_result:
ChatConsole().print(f"[bold red]{_t('cli.skills.bundle_load_failed', command=base_cmd)}[/]")
return
msg, loaded_names, missing = bundle_result
self._queue_loaded_skills(
msg, _t("cli.skills.loading_bundle", name=bundle_info['name'], count=str(len(loaded_names))), missing)
def _queue_loaded_skills(self, msg, label: str, missing) -> None:
print(f"\n⚡ {label}")
if missing:
ChatConsole().print(f"[yellow]{_t('cli.skills.skipped_missing', names=', '.join(missing))}[/]")
self._queue_skill_message(msg)
def _run_skill_slash_command(self, base_cmd: str, skill_info: dict, rest: str) -> None:
"""``/<skill> ...``; stacked ``/skill-a /skill-b do XYZ`` loads every leading skill (up to 5)."""
from hermes_cli import gateway_plugin_commands
if gateway_plugin_commands.run_skill(self, base_cmd, rest):
return # the gateway session's skill, loaded there
from agent.skill_commands import build_stacked_skill_invocation_message, split_stacked_skill_commands
# Interactive surface: stacked tokens resolve against the interactive
# map so plugin skills stack in the CLI like native skills.
extra_keys, user_instruction = split_stacked_skill_commands(rest, interactive=True)
if extra_keys:
stacked_result = build_stacked_skill_invocation_message(
[base_cmd, *extra_keys], user_instruction, task_id=self.session_id,
)
if not stacked_result:
ChatConsole().print(f"[bold red]{_t('cli.skills.stacked_load_failed', command=base_cmd)}[/]")
return
msg, loaded_names, missing = stacked_result
self._queue_loaded_skills(
msg, _t("cli.skills.loading_stacked", count=str(len(loaded_names)), names=', '.join(loaded_names)),
missing,
)
return
msg = build_skill_invocation_message(base_cmd, rest, task_id=self.session_id)
if msg:
self._queue_loaded_skills(msg, _t("cli.skills.loading_skill", name=skill_info['name']), None)
else:
ChatConsole().print(f"[bold red]{_t('cli.skills.skill_load_failed', command=base_cmd)}[/]")
def _expand_slash_prefix(self, cmd_original: str, cmd_lower: str, skill_commands, skill_bundles) -> bool:
"""Unique-prefix expansion against built-in COMMANDS + skill commands/bundles (agrees with tab-completion)."""
from hermes_cli.commands import COMMANDS
typed_base = cmd_lower.split()[0]
all_known = set(COMMANDS) | set(skill_commands) | set(skill_bundles)
matches = [c for c in all_known if c.startswith(typed_base)]
if len(matches) > 1:
if typed_base in matches:
matches = [typed_base]
else:
# Unique shortest match wins: /qui -> /quit (5) over /quint-pipeline (15)
min_len = min(len(c) for c in matches)
shortest = [c for c in matches if len(c) == min_len]
if len(shortest) == 1:
matches = shortest
if len(matches) == 1 and matches[0] != typed_base:
# Expand to the full name, preserving arguments.
return self.process_command(matches[0] + cmd_original.strip()[len(typed_base):], redispatch=True)
if len(matches) > 1:
_cprint(f"{_ACCENT}{_t('cli.command.ambiguous', command=cmd_lower)}{_RST}")
_cprint(f"{_DIM}{_t('cli.command.did_you_mean_many', candidates=', '.join(sorted(matches)))}{_RST}")
else:
# Exact token with no handler (never re-dispatch the same token: recursion), or no match.
from hermes_cli.cli_unknown_command import unknown_command_lines
lead, pointer = unknown_command_lines(cmd_lower, all_known)
_cprint(f"\033[1;31m{lead}{_RST}")
_cprint(f"{_DIM}{_ACCENT}{pointer}{_RST}")
return True
def _drain_interrupt_queue_to_pending_input(self) -> None:
"""Move stray ``_interrupt_queue`` messages into ``_pending_input`` after every turn.
Busy-time input lands in ``_interrupt_queue`` and is only drained by the explicit
interrupt path; a turn that finishes naturally would otherwise strand it and the
CLI appears to hang. Never raises.
Called once at the end of every turn from ``process_loop``'s ``finally`` block. Catches and swallows
``Exception`` because the drain must never break the main loop. (#20271)
"""
try:
while not self._interrupt_queue.empty():
stray = self._interrupt_queue.get_nowait()
if stray:
self._pending_input.put(stray)
except Exception:
pass
def _on_reasoning(self, reasoning_text: str):
"""Callback for intermediate reasoning display during tool-call loops."""
if not reasoning_text:
return
self._reasoning_preview_buf = getattr(self, "_reasoning_preview_buf", "") + reasoning_text
self._flush_reasoning_preview(force=False)
# Inline tokens that bypass the destructive-slash confirmation modal (scripting, or
# when the modal can't be marshaled onto the app loop).
# A general escape hatch for non-interactive use (scripting/automation) and for the degraded path where
# the modal can't be marshaled onto the app loop — lets users self-serve without flipping
# approvals.destructive_slash_confirm in config. (Native Windows now drives the modal normally — see
# #33961.)
_DESTRUCTIVE_SKIP_TOKENS = frozenset({"now", "--yes", "-y"})
def run(self):
"""Run the interactive CLI loop with persistent input at bottom."""
if not self._claim_active_session("cli"):
return
self._tui_print_startup()
self._tui_init_run_state()
kb = self._tui_build_key_bindings()
layout, style = self._tui_build_layout(kb)
app = self._tui_build_application(layout, kb, style)
_disable_prompt_toolkit_cpr_warning(app)
app.after_render += self._pet_flush_kitty_frame
from hermes_cli.observability.shared_metrics_startup import cli_prompt_ready_handler
app.after_render += cli_prompt_ready_handler()
self._app = app
# Ghost status-bar lines on resize: pt's renderer scrolls the terminal after each
# paint, pushing chrome into scrollback where a column-shrink reflows it into
# duplicates. Wrapping _output_screen_diff keeps its reserve-space branch from firing.
try:
# Background: prompt_toolkit's renderer (renderer.py L232-242) explicitly moves the cursor to
# the bottom of the canvas after painting "to make sure the terminal scrolls up, even when the
# lower lines of the canvas just contain whitespace". In non-fullscreen mode this scrolls chrome
# content (status bar, input rules) into terminal scrollback on every render. When the terminal
# column-shrinks, the emulator reflows the previously rendered full-width rows into multiple
# narrower rows that get pushed up — leaving ghost duplicates AND polluting scrollback. Same
# issue as pt #29 (open since 2014), #1675, #1933. Surgical fix: wrap _output_screen_diff so
# that when its internal `if current_height > previous_screen.height` branch fires (the one that
# does the bottom-cursor-move), we make it fall through by inflating previous_screen.height
# first.
import prompt_toolkit.renderer as _pt_renderer
from prompt_toolkit.renderer import _output_screen_diff as _orig_osd
if not getattr(_pt_renderer, "_hermes_osd_patched", False):
_pt_renderer._output_screen_diff = functools.partial(
_hermes_call_output_screen_diff, _orig_osd
)
_pt_renderer._hermes_osd_patched = True
except Exception:
pass
_apply_bracketed_paste_timeout_patch()
self._install_resize_recovery(app)
threading.Thread(target=self._tui_spinner_loop, daemon=True).start()
threading.Thread(target=self._tui_process_loop, daemon=True).start()
# Wake word listener off-thread so a first-run engine install never blocks the prompt.
threading.Thread(target=self._tui_wake_startup, daemon=True, name="wake-startup").start()
atexit.register(_run_cleanup)
self._tui_install_signal_handlers()
if not self._tui_stdin_usable():
_run_cleanup()
self._print_exit_summary()
return
try:
with patch_stdout():
try:
# run_in_terminal() may return either: • a coroutine / Future (prompt_toolkit ≥ 3.0) —
# must be scheduled via ensure_future so the coroutine is actually awaited; calling it
# bare would leave it unawaited and silently drop the output (fixes #23185 Bug A). •
# None (some mocks / older PT builds) — just call the inner function directly since PT
# already executed it synchronously. Do NOT fall back to a bare _pt_print when
# ensure_future raises, because run_in_terminal already invoked the lambda in that case
# (the mock path), which would double-print the line.
import asyncio as _aio
_aio.get_running_loop().set_exception_handler(self._tui_suppress_closed_loop_errors)
except Exception:
pass # no running loop -- nothing to patch
# Record that the app enables focus reporting + mouse tracking so _run_cleanup
# resets them; extended key modes are popped by the same reset.
# When multiline shortcuts are on, also ask supported terminals (e.g. iTerm2) to report
# modified keys distinctly (kitty protocol + modifyOtherKeys); the cleanup reset pops both
# modes. See #36823.
_mark_tui_input_modes_active()
if self._tui_multiline_shortcuts:
_enable_extended_enter_keys(app.output)
self._pet_start_anim()
app.run()
except (EOFError, KeyboardInterrupt, BrokenPipeError):
pass
except (KeyError, OSError) as _stdin_err:
# Selector registration failures from broken stdin and I/O errors from a
# broken stdout during interrupt (EIO is suppressed).
_errno = getattr(_stdin_err, "errno", None) if isinstance(_stdin_err, OSError) else None
_msg = str(_stdin_err)
if _errno == errno.EIO:
pass
elif _errno in {errno.EINVAL, errno.EBADF} or any(
s in _msg for s in ("is not registered", "Bad file descriptor", "Invalid argument")
):
print(_t("cli.startup.stdin_unusable", error=str(_stdin_err)))
else:
raise
finally:
# A resize right before exit leaves its recovery (and the paints it held) unrun.
_release_paints()
self._tui_shutdown()
# /update relaunch happens here, after prompt_toolkit restored terminal modes, on the
# main thread (the process_loop thread would skip cleanup / only exit itself on Windows).
if self._pending_relaunch:
from hermes_cli.relaunch import relaunch
relaunch(self._pending_relaunch, preserve_inherited=False)
def _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget, verbose, compact, resume, checkpoints, pass_session_id, ignore_rules, skills):
"""Resolve the toolset list (explicit / coding posture / platform default), construct HermesCLI, and start the background skills preload."""
toolsets_list = None
if isinstance(toolsets, str) and toolsets:
toolsets_list = [t.strip() for t in toolsets.split(",")]
elif isinstance(toolsets, (list, tuple)) and toolsets:
# Fire may pass multiple --toolsets as a tuple
toolsets_list = []
for t in toolsets:
toolsets_list.extend([x.strip() for x in t.split(",")] if isinstance(t, str) else [str(t)])
elif not toolsets:
# Coding posture inside a code workspace, else the profile default the gateway resolves (its
# platform resolver reads plugin toolsets, which only the gateway loads: adopted when the session
# opens). Neither is a pick: this list only feeds the display.
try:
from agent.coding_context import coding_selection
toolsets_list = coding_selection(platform="cli", config=CLI_CONFIG)
except Exception:
toolsets_list = None
parsed_skills = _parse_skills_argument(skills)
try:
cli = HermesCLI(
model=model,
toolsets=toolsets_list,
provider=provider,
reasoning=reasoning,
api_key=api_key,
base_url=base_url,
max_turns=max_turns,
run_budget=run_budget,
verbose=verbose,
compact=compact,
resume=resume,
checkpoints=checkpoints,
pass_session_id=pass_session_id,
ignore_rules=ignore_rules,
)
except ImportError as e:
# Direct `python cli.py` bypasses cmd_chat's partial-update ImportError handler.
from hermes_constants import emit_partial_update_hint
if emit_partial_update_hint(e):
sys.exit(1)
raise
if not toolsets:
cli._explicit_toolsets = False # the gateway resolves the default and coding posture itself
# Only a typed -t is checked against a resumed session's frozen toolsets.
cli._typed_toolsets = toolsets_list if toolsets else None
# skills.auto_load rides the same background preload as -s; --ignore-rules skips it with
# the rest of the auto-injected context. Resolved here (not lazily in the agent) so the
# session id is real for ${HERMES_SESSION_ID} and -s can dedupe against it.
from agent.skill_commands import build_auto_load_prompt, resolve_auto_load_skills
auto_load_names = [] if getattr(cli, "ignore_rules", ignore_rules) else resolve_auto_load_skills(CLI_CONFIG)
if not auto_load_names:
cli._auto_load_skills_result = ("", [], [])
if parsed_skills or auto_load_names:
cli._preload_skills_requested = [*auto_load_names, *(s for s in parsed_skills if s not in auto_load_names)]
from hermes_cli.gateway_session_store import GatewaySessionStore
if isinstance(getattr(cli, "_session_db", None), GatewaySessionStore):
# The gateway session renders -s at creation and its agent loads skills.auto_load (plugin
# skills included); this process's prompt never reaches it, so nothing is loaded here.
return cli
# Load the skill payloads in the background: skill_view walks the full skills
# tree per skill (~0.5s for a large library) and the result is only consumed
# at agent init, not by the banner. finalize_preloaded_skills() joins the
# thread before any consumer reads cli.system_prompt.
def _load_preloaded_skills() -> None:
try:
if auto_load_names:
cli._auto_load_skills_result = build_auto_load_prompt(task_id=cli.session_id, user_config=CLI_CONFIG)
if parsed_skills:
cli._preload_skills_result = build_preloaded_skills_prompt(
parsed_skills, task_id=cli.session_id, excluded_loaded_names=set(cli._auto_load_skills_result[1]))
except Exception as exc: # surfaced by finalize
cli._preload_skills_error = exc
cli._preload_skills_thread = threading.Thread(target=_load_preloaded_skills, name="skills-preload", daemon=True)
cli._preload_skills_thread.start()
return cli
def _run_legacy_gateway():
"""Legacy `cli.py --gateway` entry: arm the startup watchdog (before importing the gateway graph), then run it."""
import asyncio
from hermes_cli.resource_limits import apply_malloc_arena_max
apply_malloc_arena_max() # before the watchdog thread: glibc latches its arena limit
with suppress(Exception):
from hermes_startup_watchdog import arm_startup_watchdog
arm_startup_watchdog()
from gateway.run import start_gateway
print(_t("cli.gateway.starting"))
asyncio.run(start_gateway())
def _start_worktree_setup(list_tools, list_toolsets, worktree, w):
"""Start isolated-worktree creation (+ tool prewarm) in the background.
Returns a join callable that publishes ``_active_worktree``/TERMINAL_CWD and
schedules stale-worktree GC, or None when no worktree is wanted.
"""
if list_tools or list_toolsets or not (worktree or w or CLI_CONFIG.get("worktree", False)):
return None
# Overlap tool discovery with the I/O-bound worktree setup so show_banner() hits a warm
# cache (~0.4s). Only on the -w path: plain `hermes` has no I/O wait to hide.
def _prewarm_tools() -> None:
try:
import model_tools as _mt
_mt.get_tool_definitions(quiet_mode=True)
except Exception:
logger.debug("tool prewarm failed", exc_info=True)
threading.Thread(target=_prewarm_tools, name="tool-prewarm", daemon=True).start()
_sync_base = CLI_CONFIG.get("worktree_sync", True)
_wt_result: dict = {}
def _create_worktree() -> None:
try:
# The session freezes this cwd: recorded so a resume recreates the tree quit removed (N8).
from hermes_cli.worktree_ops import _retention_store
_wt_result["info"] = _setup_worktree(sync_base=_sync_base, retain_db=_retention_store())
except Exception:
logger.debug("worktree setup failed", exc_info=True)
_wt_result["info"] = None
_wt_thread = threading.Thread(target=_create_worktree, name="worktree-setup", daemon=True)
_wt_thread.start()
def _worktree_maintenance(repo: str) -> None:
_prune_stale_worktrees(repo)
_maintain_pack_health(repo)
def _join_worktree() -> Optional[dict[str, str]]:
_wt_thread.join(timeout=120)
info = _wt_result.get("info")
if not info:
return info
global _active_worktree
_active_worktree = info
os.environ["TERMINAL_CWD"] = info["path"]
atexit.register(_cleanup_worktree, info)
# GC stale worktrees AFTER _setup_worktree so they never race on git's worktree
# metadata (the new tree is immune: <24h age gate + live pid lock); then repack
# once refs are final so lookups stay fast on multi-agent boxes.
_repo = _git_repo_root()
if _repo:
threading.Thread(target=_worktree_maintenance, args=(_repo,), name="worktree-prune", daemon=True).start()
return info
return _join_worktree
def main(
query: str | None = None,
q: str | None = None,
oneshot: bool = False,
image: str | None = None,
toolsets: str | None = None,
skills: str | list[str] | tuple[str, ...] | None = None,
model: str | None = None,
provider: str | None = None,
reasoning: str | None = None,
api_key: str | None = None,
base_url: str | None = None,
max_turns: int | None = None,
run_budget: float | None = None,
verbose: Optional[bool] = None,
quiet: bool = False,
compact: bool = False,
list_tools: bool = False,
list_toolsets: bool = False,
gateway: bool = False,
resume: str | None = None,
worktree: bool = False,
w: bool = False,
checkpoints: bool = False,
pass_session_id: bool = False,
output_format: str = "text",
ignore_user_config: bool = False,
ignore_rules: bool = False,
):
"""
Hermes Agent CLI - Interactive AI Assistant
Args:
query: Query to run. On a real TTY this seeds an interactive session
(submitted literally as the first turn); with --oneshot/-Q or a
non-TTY it answers and exits. Alias: -q
q: Shorthand for --query
oneshot: With -q: force the legacy answer-and-exit single-query mode
even on a TTY.
image: Optional local image path to attach to a single query
toolsets: Comma-separated list of toolsets to enable (e.g., "web,terminal")
skills: Comma-separated or repeated list of skills to preload for the session
model: Model to use (default: anthropic/claude-opus-4-20250514)
provider: Inference provider ("auto", "openrouter", "nous", "openai-codex", "zai", "kimi-coding", "minimax", "minimax-cn")
reasoning: Reasoning effort for this run (none|minimal|low|medium|high|xhigh|max|ultra). Overrides agent.reasoning_effort.
api_key: API key for authentication
base_url: Base URL for the API
max_turns: Maximum tool-calling iterations (default: 60)
verbose: Enable verbose logging
compact: Use compact display mode
list_tools: List available tools and exit
list_toolsets: List available toolsets and exit
resume: Resume a previous session by its ID (e.g., 20260225_143052_a1b2c3)
worktree: Run in an isolated git worktree (for parallel agents). Alias: -w
w: Shorthand for --worktree
Examples:
python cli.py # Start interactive mode
python cli.py --toolsets web,terminal # Use specific toolsets
python cli.py --skills hermes-agent-dev,github-auth
python cli.py -q "What is Python?" # Single query mode
python cli.py -q "Describe this" --image ~/storage/shared/Pictures/cat.png
python cli.py --list-tools # List tools and exit
python cli.py --resume 20260225_143052_a1b2c3 # Resume session
python cli.py -w # Start in isolated git worktree
python cli.py -w -q "Fix issue #123" # Single query in worktree
"""
# UTF-8 stdio on Windows before any print (Rich box-drawing would UnicodeEncodeError on cp1252).
with suppress(Exception):
from hermes_cli.stdio import configure_windows_stdio
configure_windows_stdio()
os.environ["HERMES_INTERACTIVE"] = "1" # terminal_tool: interactive sudo prompts with timeout
if gateway:
_run_legacy_gateway()
return
if not (list_tools or list_toolsets):
from hermes_cli.process_identity import register_self
from hermes_cli.shared_profile_warning import shared_profile_warning
register_self("cli")
warning = shared_profile_warning()
if warning:
print(_t("cli.startup.warning", warning=warning), file=sys.stderr)
_join_worktree = _start_worktree_setup(list_tools, list_toolsets, worktree, w)
query = query or q
# ``hermes chat`` already validated this; the direct Fire entry point gets the same contract.
if output_format == "stream-json":
if not query:
raise ValueError("--format stream-json requires -q/--query")
quiet = True
cli = _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
verbose, compact, resume, checkpoints, pass_session_id, ignore_rules, skills)
# Join the background worktree creation before anything consumes TERMINAL_CWD.
# A requested worktree whose setup failed aborts: never silently run without isolation.
wt_info = _join_worktree() if _join_worktree is not None else None
if _join_worktree is not None and not wt_info:
return
# The worktree note is rendered by the gateway from the session's folder (agent/coding_context.py).
if list_tools or list_toolsets:
cli.show_banner()
(cli.show_tools if list_tools else cli.show_toolsets)()
sys.exit(0)
atexit.register(_run_cleanup) # interactive mode registers again in run() (idempotent)
_install_single_query_signal_handlers(cli)
if query or image:
_run_single_query_mode(cli, query, image, quiet, oneshot, stream_json=output_format == "stream-json")
return
cli.run()
if __name__ == "__main__":
import fire
fire.Fire(main)