Review findings on the wake-turn notice skip.
A quota or billing failure keeps the fallback serving for a cooldown, so the
next turn the user sends makes no new switch: after a switch hidden on a wake
turn, the user's turn ran on the backup with no notice at all. The hidden notice
is now held; the next non-wake turn announces it before it runs if the fallback
is still serving, and drops it if the primary came back (the user never saw it
leave).
The turn-start "Primary model restored" line also fired on wake turns, so each
wake during an outage restored, re-failed and posted it again. It is now skipped
on wake turns and for a switch the user never saw. The restore line moves into
agent/fallback_notice.py beside the switch notice.
The test now drives real run_conversation turns against a loopback provider
(primary 402, backup streaming): two wakes, then a user turn, and a wake after
the cooldown. Both cases fail on main and on the previous head.
Since the fallback notice moved to the moment of the switch, every background
wake turn (a finished background process, a plugin's scheduled check) that
falls back posts it into the chat, and most of those turns then end silent.
One plugin posted it on 27 of 27 wakes during a primary outage (#137738).
Whether a turn is a wake is known when it starts (its persisted display kind),
so the notice is skipped there and logged instead. A turn the user sent still
gets it at the switch. A switch decided before a wake turn stays pending for
the next turn the user sees.
Holding the notice until the final reply is known (#137749's shape) would bring
back the at-the-end timing on every turn, which Teknium ruled against.
Refs #137738; supersedes #137749 by @KoNit-K.
Two review findings on the at-switch notice.
The notice rode the shared "lifecycle" status kind. Messaging adapters edit one
status message per kind in a turn (Telegram send_or_update_status), so the next
retry or re-prompt line replaced it. It now has its own "fallback" kind, which
Desktop already renders as a transcript line and the TUI as an activity line.
The provider's error text was pattern-masked only. It is now masked by value
against the failing route's credentials too (redact_error_text), recorded while
those credentials are still on the agent, so an echoed opaque key never shows.
A fallback switch was announced only after the fallback finished answering, so a
long turn ran on the backup model while every surface still showed the pick (a
two-hour task looked like it ran on Qwen and had run on Grok). The notice also
named only a category ("provider failure"), never the provider's error.
The switch now posts its notice at the switch, before the fallback model is
called, and quotes the provider's own error (the summary the error handler
already computes, redacted and capped at 200 chars). A switch decided before the
turn (primary credentials failed at build) is announced at turn start. The notice
stays display-only and still obeys display.suppress_warning_notifications.
The notice wording moves to agent/fallback_notice.py, which also takes
chat_completion_helpers.py back under its line cap.
tools/ holds model tools. These six files register none: they snapshot and
restore a working directory for the agent loop, /rollback, /undo's
changed-files line and `hermes checkpoints`. They move next to the agent
loop that takes the checkpoints:
tools/checkpoint_manager.py -> agent/checkpoints/manager.py
tools/checkpoint_maintenance.py -> agent/checkpoints/maintenance.py
tools/checkpoint_pruning.py -> agent/checkpoints/pruning.py
tools/checkpoint_refs.py -> agent/checkpoints/refs.py
tools/checkpoint_undo_hint.py -> agent/checkpoints/undo_hint.py
tools/checkpoint_manager_profile_rename.py -> agent/checkpoints/manager_profile_rename.py
agent/checkpoints/__init__.py is a docstring only. Nine test files move to
tests/agent/checkpoints/. Every importer changes its import line in place,
inside the same function. Nothing stays at the old paths: none of the six
names is on the plugin API list, the shipped-release list or the
old-updater list.
Behaviour is unchanged. The four loggers keep their tools.checkpoint_*
names, so the lines stay under `hermes logs --component tools`. The folder
is not a root checkpoints/ package because the checkpoint store is
HERMES_HOME/checkpoints, which is the same directory as such a package on an
install whose checkout root is HERMES_HOME. agent.* is already packaged, so
pyproject.toml and the lists of root packages do not change.
The import and docs rewrites were made by scripts/move/rewrite_imports.py
and rewrite_docs.py.
The delegate_tool_* siblings imported names back from tools.delegate_tool
inside functions only so tests could patch `tools.delegate_tool.<name>`
(routes said so: "the facade is the patch seam"). That kept a facade <->
sibling import cycle and a function-level import at each read.
- child_run owns the heartbeat/stale-grace constants (only it reads them)
and imports _get_child_timeout, _get_subagent_approval_callback,
_get_worktree_isolation, _resolve_workspace_hint and terminal_tool's
set_approval_callback at module top.
- config drops `_cfg()` (a loop back to its own `_load_config`) and the
loop back for `_get_max_concurrent_children`, defined in the same file.
- routes, dispatch and continue import their config getters at module top.
- `_load_config` is read through `delegate_tool_config._load_config` by the
facade, continue, results and process_registry_notifications, so one
patch target reaches every reader, as the facade target did before.
- cronjob_tools, process_registry_notifications and subagent_lifecycle read
these names from their owner; the facade stops importing the names its
body never used, so a stale facade patch now fails instead of silently
doing nothing.
Tests move their patches to the module whose code reads the name. Two
worktree tests that patched `_resolve_workspace_hint` on the facade relied
on it reaching both the facade's prompt build and child_run's worktree
setup, so they now patch both readers. Every delegate_tool* module imports
cleanly as the first import in a fresh interpreter.
_is_idempotent tested `not in mutating_tools and in idempotent_tools`. The two
sets share no name, and neither is read from config or passed by any caller, so
the first clause never changed the result. MUTATING_TOOL_NAMES and
ToolCallGuardrailConfig.mutating_tools had no other reader.
The other name sets are untouched: plugin tools such as the catalog's camofox
browser register browser_navigate, browser_click and browser_snapshot, so those
names do reach the guard.
agent/transcription_registry.py and agent/tts_registry.py held hand
copies of BUILTIN_STT_PROVIDERS and BUILTIN_TTS_PROVIDERS, guarded by two
TestBuiltinSync drift tests. Their comments said importing the real sets
would be a circular import. It is not: the sets live in
tools.transcription_common and tools.tts_command_provider, which import
only each other, hermes_cli.process_identity and utils, and load no
agent.* module. Both copies equal the real sets today.
The registries now import the real sets; the copies, the stale comments
and both drift tests are gone. An import probe shows no cycle and no
heavy module (openai, numpy, httpx, faster_whisper, tools.registry,
tools.tts_tool all stay unloaded). After hermes_cli.plugins, the import
that registers plugin providers, the new modules cost about 3.5 ms once.
Removed. A search for callers by name, attribute and string (Python, TypeScript,
docs, the plugin API list and the frozen old-updater list) finds no supported
path that reaches any of them:
- tools/openrouter_client.py (whole module; check_api_key had test callers only)
- tools/connectors/gateway/__init__.py: re-exports and __all__ (every importer names a submodule)
- tools/connectors/gateway/wire.py::WIRE_BATCH_MAX
- tools/managed_gateway_auth.py::managed_gateway_origin
- tools/discord_tool.py::_detect_capabilities
- tools/mcp_tool_health.py::MCPServerHealthMixin.ensure_healthy
- tools/mcp_oauth.py::build_oauth_auth, HermesOAuthClientProvider, _oauth_port
- tools/mcp_dashboard_oauth.py::DashboardOAuthFlow.profile (write-only field)
- tools/mcp_tool_events.py::EVENT_UTILITY_KEYS
- agent/tool_guardrails.py: mcp_filesystem_* entries in IDEMPOTENT_TOOL_NAMES
(MCP tools register as mcp__<server>__<tool>)
Tests that covered live code through a deleted symbol now call the live path
(MCPOAuthManager().get_or_build_provider, _fetch_capabilities,
build_vendor_gateway_url); tests that only exercised deleted code are removed.
Kept on purpose: _SSH_HINT_PROXY, its branch, the redirect_uri parameters and
build_provider_kwargs' ssh_proxy_hint. Nothing reaches them today, but they are the
proxy-user hint from d0afcb125ce; wiring it into MCPOAuthManager is a separate fix.
test_cache_is_keyed_by_token now covers _detect_capabilities_nonblocking (two tokens,
memory and disk). ensure_healthy leaves the SuspectableBackend Protocol, which no
backend implements any more.
Removed. A search for callers by name, attribute and string (Python, TypeScript,
docs, the plugin API list and the frozen old-updater list) finds no supported
path that reaches any of them:
- tools/environments/vercel_sandbox.py: _exception_chain, _extract_status_code,
_RETRY_BACKOFF_STEP, _MIN_SANDBOX_TIMEOUT, _MIN_RUNNING_WAIT,
_RUNNING_WAIT_POLL_INTERVAL, _STOP_TIMEOUT, _STOP_POLL_INTERVAL,
_SNAPSHOT_STORE_NAME
- tools/environments/sandbox_scope.py: CredentialRef (docstring in
agent/terminal_env_provider.py and the terminal-environment-plugin guide no
longer name it)
- tools/environments/streams.py: supports_streams() (the provider attribute of
the same name stays)
- completion_reason "failed_start": its producer left in cd818a4d054; drop the
lookups in process_registry_notifications._REASON_STATUS (and its
"Failed to Start" branch), cli_process_dock._STATUS_BY_REASON,
ui-tui processRoster REASON_STATUS, and the field comments
- tools/terminal_hints.py: _EXIT_CODE_HINTS[137] (exit 137 always carries a
SIGKILL exit note, which gates annotate_failure off)
- ProcessRegistry._config_value: unread `fallback` parameter
The package recipe told topic modules to late-import their facade inside
functions and named PEP 562 __getattr__ as the cure for an import cycle.
A cycle is fixed by moving the shared name into a lower module both
import; __getattr__ stays for a measured startup cost. Four more lines in
agent/, hermes_cli/ and tools/ AGENTS.md described in-function imports as
the way siblings reach their facade; they go too.
The move had turned the function-level imports of agent.provider_route_hooks
in agent/auxiliary_client.py and run_agent.py into module-top imports. That
module imports providers.base at top, so importing agent.auxiliary_client
began to need the providers package. The update child's check of configured
features runs in a target tree where that import fails, and it stopped naming
Feishu (tests/hermes_cli/test_update_missing_configured_deps.py).
Both callers already import route_answer from that module inside the function.
The rule now rides on the same line, so neither module's import-time
dependencies differ from main.
The rule knows OpenAI model family names, which utils (a product-agnostic helper module) should
not, and only agent code calls it. It now sits beside the provider profile max_tokens_param answer
it backs up in both callers. No re-export is left in utils.
agent/auxiliary_client.py imports route_answer at module top with the moved rule and drops its two
function-local imports of it, keeping the file at its line cap.
The test file moves to tests/agent/test_provider_route_hooks_max_completion_tokens.py.
The file-size fix text asks for a <stem>/ folder, but nothing said what
a good folder looks like. Root AGENTS.md's facade section becomes
"Packages and Python shape":
- <stem>/__init__.py is the facade: its docstring names each module's
job, __all__ is the surface, PEP 562 __getattr__ when eager imports
would cycle, and it holds no behaviour (tools/connectors/ is the model).
- A family folder keeps its ABC or Protocol, one module per variant and
a name-to-variant table (tools/environments/).
- Flat <stem>_<topic>.py siblings stay until touched; none are added.
- A Shape bullet: code imports on 3.11; importing has no side effects;
input is parsed where it enters into a frozen dataclass, Enum or
Literal; one return shape per function; dispatch by table; objects,
not mixins; no module constant kept only for tests to patch.
The rules live in AGENTS.md because that is what agents load on every
turn; root stays inside its 12,100-character budget (11,831). The
FILE_LINES fix text and CONTRIBUTING's Code Style section point at the
section.
A worker store has no durable generation reader, and an in-place archive
(prune, micro-compaction) leaves compression_count alone, so a later
response folded pre-rewrite coverage. RuntimeSessionStore.archive_and_compact
counts each committed rewrite locally; the clock adds it to its witness.
A worker read of prompt_cache_generation went through the required-write
journal: an RPC failure left the journal failed and blocked later writes.
The owner now stamps its durable generation onto the clock inside the
usage.main receipt that already carries it; no extra worker read.
- Every clock storage read (restore, prompt_cache_generation) is best-effort:
sqlite3.Error/OSError/WorkerPersistenceError log at DEBUG and the window
reports unknown (storage_unavailable); a successful reply is never lost.
- RuntimeSessionStore.prompt_cache_generation reads the owner's durable count
(session.cache_generation receipt op), so a managed worker's fresh write is
not reported compacted.
- The agentless /context read compares the saved clock with the row's
persisted model + model_config provider/base_url, and the breakdown cache
key includes them: a session.mutate model switch reports unknown.
The clock modelled every route as "expires = last touch + tier", which is wrong for OpenAI
GPT-5.6+: a read refreshes coverage to at least 30 minutes after it and never restarts a
12h write. It also treated documented minimums as expiries and lost or revived saved state.
- Coverage deadlines per tier with per-route refresh rules: Anthropic family restarts the tier
on read; OpenAI keeps max(existing, read + 30m) and a 12h deadline stays at write + 12h.
- Windows carry guaranteed_until (earliest deadline, so mixed tiers in one response are only as
warm as the shorter) and estimated_until (OpenAI: last touch + 24h retention ceiling; pre-5.6
in_memory 1h). cache_certainly_warm / cache_certainly_cold are the two consumer helpers.
/context: warm until / may still be warm until / expired / unknown.
- Events bind to the session's durable context generation (rows a compaction or prune archived,
SessionDB.prompt_cache_generation), kept as saved on restore; a resumed agent restores and
validates the saved event before folding its first response.
- Route identity is provider + normalize_route_base_url (scheme, host, port, path) + model.
- Agentless session.context_breakdown reads the saved clock (stored_cache_window).
- Codex app-server activity is recorded as an explicit unknown (it sets its own cache options).
- MoA records the resolved aggregator route and the payload the MoA client sent.
- effective_cache_ttl applies the route ceiling on the measured-provider path too.
CI: a new positional ProviderProfile field shifts plugin subclasses' positional slots, and
the redecoration path is driven by stub agents that carry no base_url.
Every consumer that needs "when does this session's cached prompt expire?" now reads one
answer, agent/prompt_cache_clock.py:cache_window(), instead of re-deriving it from _cache_ttl.
- Per successful attempt the clock records the tier actually on the wire (cache_control ttl,
prompt_cache_options.ttl, prompt_cache_retention, read from the sent payload), the send time,
and the tier the response proved: Anthropic cache_creation.ephemeral_5m/1h_input_tokens,
OpenAI Responses cache_write_tokens_details.ttl_30m/12h_tokens. normalize_usage keeps that
split as CanonicalUsage.cache_write_by_ttl instead of dropping it.
- Per-route rules are a dict of small handlers: native Anthropic proves via the split;
OpenRouter Claude is declared (live-probed to honour 1h); routes with a ceiling are clamped;
other Anthropic-wire gateways assume 5m; OpenAI GPT-5.6+ proves via ttl_30m/12h or declares
the documented 30m minimum; pre-5.6 assumes ~30m (5m on in_memory); implicit caches are
unknown. expires = latest read-or-write send time + the written tier. A route switch,
fallback, session rotation or compaction makes it unknown.
- Route TTL ceiling is data: ProviderProfile.prompt_cache_max_ttl (Nous ships "5m", because
the Portal's upstream drops 1h after ~7 min and bills 5m), overridden per provider by config
prompt_caching.route_ttl_ceilings. effective_cache_ttl uses the same helper, so Hermes stops
asking Nous for 1h. A custom endpoint at the Portal host gets the Nous ceiling.
- Persisted as nullable sessions.prompt_cache_clock (JSON) through the existing token batch;
restored lazily on resume, falling back to the newest assistant row (assumed).
- Codex app-server: read cacheWriteInputTokens instead of hard-coding cache_write_tokens=0.
- /context shows "Prompt cache: warm until HH:MM (…; 1h, proven)", "expired … ago" or
"unknown (…)". The surface is absorbed from #142387 (render/duration helpers, the
SessionContextBreakdownResult.prompt_cache contract and translations), reworked onto the clock.
Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
Both runners bound one call at timeouts.tools.sequential_call /
.concurrent_batch, 420s by default. Several tools are handed a longer budget by
their own schema and config: `terminal` advertises a 600s foreground cap
(FOREGROUND_MAX_TIMEOUT) and honours TERMINAL_TIMEOUT, `process_manage
action=wait` blocks for its `timeout` clamped by that same setting.
So a foreground `terminal(timeout=600)` — explicitly allowed, and below the cap
that would have promoted it to a background process — died at 420s with
"Error executing tool 'terminal': timed out after 420.0s" and no output at all,
where the tool's own timeout would have returned the partial output it had
collected plus exit code 124. `process_manage action=wait` is worse: the
background process keeps running, so the model gets nothing back and re-issues
the identical call.
A tool can now declare what one call may legitimately block for
(ToolEntry.deadline_floor, a fn(args) -> seconds | None, resolved through
registry.get_deadline_floor). Both runners raise their generic deadline to the
longest floor any member of the batch declared, plus a small grace so the
tool's own timeout is the one that fires. A tool that declares nothing keeps
exactly the bound it has today, and a floor never introduces a deadline where
the generic one is disabled.
Same shape as the instances already tracked in #110035 (wait_for_human asks for
600s) and #109089 (a2a_call ignores a2a_agents.<peer>.timeout); this fixes the
two terminal-toolset ones and gives those a mechanism to declare through.
The TERMINAL_TIMEOUT clamp that ProcessRegistry.wait() applies now lives in
process_registry_wait.py next to process_manage's floor, so the two read one
rule and process_registry.py, already past the 2,000-line target, shrinks
instead of growing.
rm/unlink/shred/truncate/mv of HERMES_HOME itself or a protected store
(state.db, sessions/, vault/, mcp-tokens/, ...), and cp/install/rsync/dd/tee/
redirection onto a store, were auto-approved: the patterns only special-cased
config.yaml and .env, and the resolved-home fold skipped the bare home word.
sqlite3 write verbs on a store prompt too, keyed on the verb rather than a
missing WHERE (`where 1=1` wipes the same rows).
The protected-store list moves to hermes_cli.home_data_layout so the file
tools' write deny and the shell gate share one source of truth. Prompt-grade
(DANGEROUS), not hardline: backup/doctor flows legitimately touch these paths.
Hardening (SECURITY.md §3.2), not a boundary.
Fixes#109367
Every approval-gated realpath skipped the credential deny, so with
~/.bashrc -> ~/.ssh/authorized_keys a write to authorized_keys itself became a
shell_rc_write prompt (approvable, or passed by --yolo). Exempt only the realpath
of each guarded home's .ssh/config, which is what the exemption exists for; rc
files are never credential-denied and need none. Covers the cross-home variant
(one guarded home's rc linked onto another home's credential). Drops the now
unused build_write_approval_paths.
Refs #84639
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
The approval exemption in _classify_resolved_write_denial returned early, so
~/.ssh/config (pre-existing) and the newly gated shell rc files escaped the
safe-root sandbox under --yolo or an approval. It now skips only the
credential deny; protected-subpath and safe-root checks still run.
A single-segment home folds only at a path start (/data/root/.bashrc no
longer becomes /data~/.bashrc), and the touch/mkdir/ln rules target home
credential/SSH/rc and Hermes env/config paths, not /etc.
Follow-up to the salvaged #85321 commit:
- agent/file_safety.SHELL_RC_FILES now drives both the file-tool approval list and the
terminal _SHELL_RC_FILES pattern, so the two gates cannot drift apart again.
- The file-tool gate keys each class separately (ssh_config_write / shell_rc_write) with its own
prompt text; a shared key let one approve-always for ~/.ssh/config authorize ~/.bashrc writes.
A batch spanning both classes must pass both gates.
- touch/mkdir and ln rules are command-position anchored, and ln only fires on the destination
operand: the salvaged rule flagged `ls -ln ~/.ssh`, `grep touch ~/.bashrc` and linking OUT of
~/.ssh.
- Tests move to tests/tools/test_approval_sensitive_home_writes.py (test_approval.py is over the
file-size cap).
Fixes#85321
Refs #84639
Login shell rc files were approval-gated on the terminal path but writable
through write_file/patch with no prompt. touch/mkdir/ln into the same
sensitive destinations were also ungated. Route rc writes through the
existing SSH-config approval list and flag those create/link commands.
`.pypirc` `password : a b c` read back in clear and `password: a b c` masked
only the first word: the INI pass only took `=`. configparser accepts `:` too.
The `:` form applies only when the text has an INI `[section]` header, so
config.yaml `api_key: "<placeholder>"` lines stay with the YAML assignment pass
(test_redact_leak_shapes placeholders). This only widens masking; the AWS
`credential_process` exemption stays `=`-only, so a `credential_process:` line
is masked whole.
Refs #124999
`gc` is Get-Content's built-in alias, and PowerShell binds a parameter value
with a colon (`Get-Content -Path:~\_netrc`), which the dash filter dropped
as a flag. Both left secret_file=False, so the netrc/pgpass passes never ran.
The colon form is not applied to grep/awk/sed, whose first positional is the
pattern.
Refs #124999
The netrc scan masked only `=correct` in a .pypirc `password =correct horse X`
line, which left the INI pass with no `=` to anchor on, so the tail stayed
visible. Running the INI pass first masks the whole value; the netrc scan then
treats `=«redacted…»` as already masked.
Refs #124999
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Windows PowerShell Get-Content reads _netrc directly, but the terminal
reader classifier only recognizes cat/type aliases. Add that canonical
reader and pin its credential output with a regression test.
Regression for NousResearch/hermes-agent#124999 (carrier PR #155442).
Original report: Adolanium. Credential-store fix: c2h5oh.
(cherry picked from commit 78b613d5b1f81180ec4204dbb88f850499bb6064)
Size offset for agent/redact.py's health cap: main already moved
_command_segments (this PR's earlier offset), so the credential-store
wiring needs a new one. Moved unchanged; agent.redact imports it, so
from agent.redact import _is_under_hermes_home still resolves.
Refs #124999
- netrc: track the previous keyword, so a login named `password` no longer
hides the real password, and mask `:x`/`=x` values (only a bare `=`/`:`
token is left to the INI pass).
- .pgpass: `#`/`=` are legal in database and user names; only host and
port exclude them.
- An INI section name never starts with whitespace, so a shell test
`[ -f x ]` no longer enables the credential_process exemption.
Refs #124999
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
The npm exemption from 4c1be3ea3c8 skipped a whole ${NAME} token followed by whitespace, and the value group was \S+, so '_authToken=${NPM_TOKEN} <literal>' (space or tab) read back the literal. Only a value that is nothing but the reference (optionally quoted, trailing blanks/CR) is exempt now, and any other value is masked to end of line.
Refs #124999
0fb4cc520d8 exempted a lowercase credential_process key inside the shared _should_redact_assignment gate, so every ENV/YAML/JSON pass on every source skipped it: credential_process=<opaque> in .env or ~/.zshrc, and credential_process: <opaque> in config.yaml, read back unmasked where origin/main masks them. The gate is back to main's behaviour. Instead, on a secret_file source, a 'credential_process =' key that sits below an INI [section] header is kept out of the INI and assignment passes only; vendor-prefix, --flag and private-key passes still run over the command.
Refs #124999
_INI_SPACED_ASSIGN_RE wrapped the secret word in two backtrackable key runs, so a long line with a secret word and no usable '=' ('token' * N) took O(n^2): 12.7s at 80k chars on any secret-file read (.env, shell rc, config.yaml, stores); origin/main takes 0.004s. The key run is now possessive and the secret word is checked in the callback; '(?<=api) (?=key)' keeps the 'api key = X' spelling. The match set is unchanged: 700k random lines diff-clean against the old pattern, and 80k redact_terminal_output / redact_sensitive_text outputs are identical to b030b3ac64b.
Refs #124999
agent/redact.py crossed its 2000-line health cap with the store fixes. The store patterns, the netrc tokenizer, the credential_process key and the shared line grammar (_SECRET_CFG_NAMES, _LINE_NUMBER_GUTTER) move to a sibling module; agent/redact.py keeps a thin wrapper that supplies its mask and assignment gate. No behaviour change.
Refs #124999
credential_process names the helper command AWS runs to fetch credentials; it passed the "credential" key gate and was masked whole, which hides exactly what one reads ~/.aws/config to debug. Exempt that exact lowercase AWS key; vendor-prefix and --password= passes still apply to its value.
Refs #124999
netrc is whitespace-separated keyword/value tokens, so "machine a ... password p1 machine b ... password p2" is one valid line; the anchored pattern stopped after p1. Tokenize netrc lines and mask the token after each password keyword.
Refs #124999
password=correct horse x in a .pypirc kept everything after the first word: the anchored assignment pass masked only the first word and the store pass then skipped the already-masked value. Run the store pass before the assignment passes and accept an unspaced = when the value has a second word that is not a # comment (keeps the .env inline-comment contract).
Refs #124999
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
npm expands ${NAME} in .npmrc, so a project .npmrc holding _authToken=${NPM_TOKEN} names a variable, not a token. Masking it hid that from the agent and, since the read came back redacted, made write_file refuse the file. Literal tokens are still masked.
Refs #124999
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Follow-up to the salvaged credential-store classification:
- netrc quoted passwords ("a b c") and INI values with internal spaces
(configparser keeps them) were masked only up to the first space, leaving
the rest of the secret visible.
- ~/.aws/config holds aws_secret_access_key / aws_session_token too, and
_netrc is the Windows name curl and git read; both are now secret-bearing
(and _netrc joins the write denylist through the shared basename list).
- Drop the salvaged URL-userinfo pattern: _redact_userinfo_passwords (#125664)
already masks .git-credentials lines on every read, and the extra regex
masked docs placeholders it deliberately keeps.
- Tests move to tests/agent/test_redact_credential_stores.py (size ratchet)
plus a live read_file + terminal cat E2E per store format.
Fixes#124999
read_file and terminal cat only treated .env files, shell rc files and the
Hermes config.yaml as secret-bearing. Reading ~/.aws/credentials, .netrc,
.pgpass, .npmrc, .pypirc or .git-credentials returned the stored secrets
in clear text.
Classify these files as secret-bearing (credentials only under a .aws
parent) using the same list the write denylist already uses. Most of these
files are not KEY=value, so add a secret-file-only pass for their line
formats: netrc password tokens, pgpass fields, URL user:password,
npmrc _authToken and INI "password = x". The terminal path now passes
secret_file too, so both surfaces use the same passes.
_iter_with_swallowed checked only the first match found from inside each
match. When that hit ended inside the outer match (an hf_ key inside an
sk-proj body), a 1//0 token that started after it and ran past the outer
match was never a candidate and stayed raw. Step from hit to hit until one
runs past the outer match or starts after it; each step starts at the last
hit's end, so the scan stays linear.
Also lift the linearity test's wall-clock bound to the repo's 2 s floor.
Refs #39654
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
a8377e63b9's gap-fill pass could start a candidate inside the field a
skipped glued match was exempted on (my-sk-learn-config.1//0<split>):
its span crossed the stripped newline and took the next line's glued
sk-, so that line's key was then judged glued and left raw where main
and the previous head mask it.
Both scans now report spans and the result is their union, so neither
can hide what the other masks. The contiguous pass gets the same
treatment: a match starting inside an earlier one and running past it
(1//0...log-sk-abc.<key>) is yielded too, found by one search from
inside each match, so both passes stay linear (100k chars of
my-sk-a.\n: 0.03 s).
Refs #39654
A skipped shadow match that ran across a stripped line break consumed
the next line, so a control-split key there (my-sk-learn-config.\n
ghp_<split>) was never a candidate and leaked where main masks it.
Run a second finditer with prefix_re (whose candidates never start
glued) and keep its spans only where they fill gaps between first-pass
spans. Rescanning from the next field after each skip (the review
suggestion) was quadratic on many short glued lines: 10.7 s at 100k
chars vs 0.05 s here.
Refs #39654
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
agent/redact.py is over its 2000-line target and may not grow past main's
2086; the refresh-token mask needs room. Moved unchanged and re-exported
from agent.redact.
Refs #39654
The control-split pass judged _is_glued_identifier on the shadow with every
control char stripped, so a glued non-opaque identifier ran on into the next
tab-separated column or line, looked opaque, and was masked together with it
(task_sk-learn<TAB>pip<TAB>Installed2024Version). Judge it on the candidate's
live text up to the first tab or line break; ESC, zero-width and CSI joins
still count, so a glued key split into short runs stays masked.
Refs #39654
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>