Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,8 @@ jobs:
RELEASE_TAG: ${{ github.ref_name }}
run: |
release_notes=""
if [ "$RELEASE_TAG" = "v0.20.2.1" ]; then
release_notes='Async revision 1: this release tracks Hermes Agent v2026.8.16 (Python 0.20.2). Reinstall explicitly when moving from the legacy v0.20.4 fork release; future fork-only releases increment the fourth numeric segment.'
if [ "$RELEASE_TAG" = "v0.20.4.1" ]; then
release_notes='Async revision 1: this release tracks Hermes Agent v2026.8.18 (Python 0.20.4). Reinstall explicitly when moving from the legacy v0.20.4 fork release; future fork-only releases increment the fourth numeric segment.'
fi
if is_draft="$(gh release view "$RELEASE_TAG" --repo "$GH_REPO" --json isDraft --jq .isDraft 2>/dev/null)"; then
test "$is_draft" = true
Expand Down
10 changes: 5 additions & 5 deletions README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Distribución nativa asíncrona y orientada a biblioteca de
[NousResearch/hermes-agent](https://github.com/NousResearch/hermes-agent), basada
en la etiqueta upstream `v2026.8.16` (versión del paquete Python `0.20.2`).
en la etiqueta upstream `v2026.8.18` (versión del paquete Python `0.20.4`).

Este repositorio conserva el bucle del agente Hermes, los proveedores de
modelos, la ejecución de herramientas, MCP, habilidades, memoria y sesiones
Expand Down Expand Up @@ -55,15 +55,15 @@ paralelo.
Se admite Python 3.11 a 3.13.

```bash
uv pip install "async-hermes-agent==0.20.2.1"
uv pip install "async-hermes-agent==0.20.4.1"
```

Las versiones se publican en PyPI mediante OIDC Trusted Publishing de GitHub.
La misma rueda, distribución fuente y sumas de comprobación verificadas se
adjuntan a la versión correspondiente de GitHub.

La versión tiene cuatro segmentos numéricos: `0.20.2.1` indica la versión
Python upstream `0.20.2` y la revisión `1` de esta distribución asíncrona. Las
La versión tiene cuatro segmentos numéricos: `0.20.4.1` indica la versión
Python upstream `0.20.4` y la revisión `1` de esta distribución asíncrona. Las
versiones exclusivas del fork incrementan el cuarto segmento; al portar una
nueva versión upstream, los tres primeros segmentos se actualizan y la revisión
vuelve a `1`.
Expand All @@ -74,7 +74,7 @@ se instaló desde esa etiqueta Git, la migración requiere una reinstalación
explícita una sola vez:

```bash
uv pip install --reinstall "async-hermes-agent==0.20.2.1"
uv pip install --reinstall "async-hermes-agent==0.20.4.1"
```

Para desarrollo:
Expand Down
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Native-async, library-focused distribution of
[NousResearch/hermes-agent](https://github.com/NousResearch/hermes-agent), based
on upstream tag `v2026.8.16` (Python package version `0.20.2`).
on upstream tag `v2026.8.18` (Python package version `0.20.4`).

This repository keeps the Hermes agent loop, model providers, tool execution,
MCP, skills, persistent memory and sessions, trajectory generation, runner, and
Expand Down Expand Up @@ -56,23 +56,23 @@ instances can run concurrently.
Python 3.11 through 3.13 is supported.

```bash
uv pip install "async-hermes-agent==0.20.2.1"
uv pip install "async-hermes-agent==0.20.4.1"
```

Versioned packages are published to PyPI through GitHub OIDC Trusted
Publishing. The same verified wheel, source distribution, and checksums are
attached to the corresponding GitHub Release.

The package version has four numeric segments: `0.20.2.1` means upstream
Python version `0.20.2` plus async-distribution revision `1`. Fork-only releases
The package version has four numeric segments: `0.20.4.1` means upstream
Python version `0.20.4` plus async-distribution revision `1`. Fork-only releases
increment the fourth segment. When a new upstream version is ported, the first
three segments change to match it and the async revision restarts at `1`.

The earlier `0.20.4` GitHub release used the old independent version scheme.
If it was installed from that Git tag, migrate explicitly once:

```bash
uv pip install --reinstall "async-hermes-agent==0.20.2.1"
uv pip install --reinstall "async-hermes-agent==0.20.4.1"
```

For development:
Expand Down Expand Up @@ -106,12 +106,12 @@ runtime.
The Honcho extra pins the native-async SDK version validated by this package.
Select `memory.provider: honcho` in `config.yaml`; connection, identity,
cadence, and session settings are documented in the
[Honcho provider guide](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.2.1/plugins/memory/honcho/README.md).
[Honcho provider guide](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.4.1/plugins/memory/honcho/README.md).

OpenViking uses the core native-async HTTP transport and needs no Python
extra. Server setup, provider configuration, async lifecycle, recall, and tool
behavior are documented in the
[OpenViking provider guide](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.2.1/plugins/memory/openviking/README.md).
[OpenViking provider guide](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.4.1/plugins/memory/openviking/README.md).

## Sessions

Expand Down Expand Up @@ -401,9 +401,9 @@ uv build

## Contributing and security

Read [CONTRIBUTING.md](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.2.1/CONTRIBUTING.md)
Read [CONTRIBUTING.md](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.4.1/CONTRIBUTING.md)
before submitting changes and
[SECURITY.md](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.2.1/SECURITY.md)
[SECURITY.md](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.4.1/SECURITY.md)
for private vulnerability reporting.

## Upstream relationship
Expand All @@ -412,9 +412,9 @@ The repository preserves original core file and function names to keep future
upstream imports reviewable. It is a divergent async distribution, not a claim
that these changes are drop-in mergeable to the synchronous upstream product.

The deliberate differences from upstream `v2026.8.16` are documented in the
The deliberate differences from upstream `v2026.8.18` are documented in the
[upstream differences table](https://ykoh42.github.io/async-hermes-agent/developer-guide/upstream-differences).

Hermes Agent is built by [Nous Research](https://nousresearch.com). This
distribution retains the upstream MIT license; see
[LICENSE](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.2.1/LICENSE).
[LICENSE](https://github.com/ykoh42/async-hermes-agent/blob/v0.20.4.1/LICENSE).
32 changes: 22 additions & 10 deletions agent/agent_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
from hermes_cli import managed_scope as _managed_scope_bootstrap # noqa: F401
from hermes_cli import model_normalize as _model_normalize_bootstrap # noqa: F401
from hermes_cli import models as _models_bootstrap # noqa: F401
from hermes_cli import providers as _providers_bootstrap # noqa: F401
from hermes_cli.config import cfg_get
from hermes_cli.route_identity import normalize_route_base_url
from hermes_constants import get_hermes_home
Expand Down Expand Up @@ -1222,30 +1223,31 @@ def init_agent(
elif (provider_name is None) and agent._base_url_hostname == "api.x.ai":
agent.api_mode = "codex_responses"
agent.provider = "xai"
elif agent.provider == "anthropic" or (provider_name is None and agent._base_url_hostname == "api.anthropic.com"):
elif agent.provider == "anthropic" or (
provider_name is None and agent._base_url_hostname == "api.anthropic.com"
):
agent.api_mode = "anthropic_messages"
agent.provider = "anthropic"
elif agent._base_url_lower.rstrip("/").endswith("/anthropic"):
# Third-party Anthropic-compatible endpoints (e.g. MiniMax, DashScope)
# use a URL convention ending in /anthropic. Auto-detect these so the
# Anthropic Messages API adapter is used instead of chat completions.
agent.api_mode = "anthropic_messages"
elif agent.provider == "bedrock" or (
agent._base_url_hostname.startswith("bedrock-runtime.")
and base_url_host_matches(agent._base_url_lower, "amazonaws.com")
):
# AWS Bedrock — auto-detect from provider name or base URL
# (bedrock-runtime.<region>.amazonaws.com).
agent.api_mode = "bedrock_converse"
elif agent.provider in {"nous", "nous-portal", "nousresearch"}:
# Portal is dual-wire: anthropic/* → Messages, everything else →
# chat_completions. Callers that already pass api_mode win above;
# this covers direct AIAgent construction without a resolved runtime.
from hermes_cli.providers import nous_api_mode

agent.api_mode = nous_api_mode(agent.model)
else:
agent.api_mode = "chat_completions"
# Hosts may mandate a wire protocol without owning a provider slug.
# Keep this fallback after URL-based provider rewrites so credentials
# for endpoints such as api.anthropic.com retain their provider id.
try:
mandated_mode = _providers_bootstrap.host_mandated_api_mode(base_url or "")
except Exception:
mandated_mode = None
agent.api_mode = mandated_mode or "chat_completions"

# Credential-pool validation runs AFTER provider auto-detection so
# a pool scoped to e.g. "anthropic" is not rejected when the agent
Expand Down Expand Up @@ -2035,6 +2037,16 @@ def init_agent(
_agent_section = {}
agent._tool_use_enforcement = _agent_section.get("tool_use_enforcement", "auto")

# Empty-response retry guard config (NS-503): additive
# ``agent.empty_response_guard`` subsection. Resolution is tolerant —
# a malformed section falls back to the schema defaults (guard on,
# $0.25 threshold), matching the guard's overall fail-open posture.
from agent.empty_response_guard import resolve_guard_settings
(
agent._empty_guard_enabled,
agent._empty_guard_cost_threshold_usd,
) = resolve_guard_settings(_agent_section.get("empty_response_guard"))

# Intent-ack continuation config: "auto" (default — codex_responses only,
# the historical gate), true (all api_modes), false (never), or a list of
# model-name substrings. Resolved against the active api_mode/model in the
Expand Down
25 changes: 21 additions & 4 deletions agent/agent_runtime_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3268,9 +3268,21 @@ def sanitize_api_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]
# tool result. This is the final pre-API chokepoint, so dedup defensively
# here even though repair_message_sequence also consumes matched ids.
# (a) collapse duplicate tool_calls WITHIN an assistant message
# (b) drop later tool result messages reusing an already-seen id
# (b) drop tool results that answer no OUTSTANDING tool call
#
# (b) tracks outstanding calls rather than every id ever seen, because
# ``tool_call_id`` is NOT globally unique in practice: llama.cpp emits a
# single constant id for every tool call it ever returns (verified: three
# separate completions from one server all carry the same id). A
# seen-once-drop-forever rule reads the SECOND legitimate tool result of
# such a session as a duplicate and deletes it, so from the second tool
# call onward the model never sees any result — it announces its next
# action and the turn dies with the work unfinished. Outstanding-call
# semantics keep both protections intact: a re-emitted result still
# answers no pending call and is still dropped, while a genuine new call
# that reuses the id re-arms that id first.
seen_assistant_call_ids: set = set()
seen_result_call_ids: set = set()
outstanding_call_ids: set = set()
deduped: list[dict[str, Any]] = []
removed_dupes = 0
for msg in messages:
Expand All @@ -3284,17 +3296,22 @@ def sanitize_api_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]
continue
if cid:
seen_assistant_call_ids.add(cid)
outstanding_call_ids.add(cid)
kept_tcs.append(tc)
if len(kept_tcs) != len(msg.get("tool_calls") or []):
msg = {**msg, "tool_calls": kept_tcs}
deduped.append(msg)
elif role == "tool":
cid = (msg.get("tool_call_id") or "").strip()
if cid and cid in seen_result_call_ids:
if cid and cid not in outstanding_call_ids:
removed_dupes += 1
continue
if cid:
seen_result_call_ids.add(cid)
# Answered: this id is no longer outstanding, so a second
# result replaying it is still caught above.
outstanding_call_ids.discard(cid)
# A reused id must be re-armable by the next assistant call.
seen_assistant_call_ids.discard(cid)
deduped.append(msg)
else:
deduped.append(msg)
Expand Down
3 changes: 3 additions & 0 deletions agent/anthropic_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,9 @@ def _requires_bearer_auth(base_url: str | None) -> bool:
# Hostname match (not substring) so e.g. evil.com/palantirfoundry
# paths don't trigger Bearer auth.
or base_url_host_matches(normalized, "palantirfoundry.com")
# CommandCode's /provider/v1/messages endpoint uses Bearer auth,
# not Anthropic's native x-api-key header.
or base_url_host_matches(normalized, "api.commandcode.ai")
)


Expand Down
74 changes: 72 additions & 2 deletions agent/conversation_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -2673,13 +2673,64 @@ async def _refresh_lock_lease() -> None:
# the current-turn user message before preflight runs, so
# messages[:idx] is exactly the persisted prefix; only the
# current turn's new messages get written.
#
# Bound to old_session_id, hoisted above the flush: the
# ``except`` handler below keys its in-memory rollback off
# this name, so anything that fails from here on rolls the
# transcript back instead of leaving the failed attempt's
# compacted snapshot in place.
old_session_id = agent.session_id
current_idx = getattr(agent, "_persist_user_message_idx", None)
persisted_history = (
messages[:current_idx]
if isinstance(current_idx, int)
and 0 <= current_idx <= len(messages)
else None
)
# The #47202 flush below is a DURABLE append to the parent
# and it is NOT undone when the rotation aborts: the
# ``except`` handler restores the in-memory transcript and
# keeps agent.session_id on the parent, but the rows it just
# wrote stay. Survivable for a one-off failure; pathological
# for a STICKY one. A parent row that already carries
# ``ended_at`` fails publish_compression_child on every
# attempt and nothing in this path clears it, so each
# auto-compaction appends another copy of the current turn to
# the transcript it was supposed to shrink — the session grows
# until the provider rejects the request outright (#88197:
# 303 unique messages stored as 2,611 rows after 7 aborted
# attempts, ~1.66M tokens, HTTP 400).
#
# So check that one precondition BEFORE writing. It is a plain
# read of the row the publish is about to read anyway, it
# raises the publish's own message so the log line, telemetry
# and rollback path are all unchanged, and it cannot mask a
# real rotation — a live parent reaches the flush exactly as
# before. Deliberately NOT extended to the compression lease:
# a lease is re-acquirable, so a transient miss here would
# abort a rotation that would otherwise have committed.
_parent_row_reader = getattr(agent._session_db, "get_session", None)
_parent_already_ended = False
if callable(_parent_row_reader):
try:
_parent_row = await _parent_row_reader(old_session_id) or {}
_parent_already_ended = (
_parent_row.get("ended_at") is not None
)
except Exception:
# Fail OPEN: an unreadable row must not turn a cheap
# guard into a new way to lose compression.
_parent_already_ended = False
if _parent_already_ended:
raise RuntimeError(
f"Compression parent already ended: {old_session_id}"
)
# Foreign-tail ceiling (#75316): the flush below writes OUR
# OWN input transcript to the parent — those rows are
# already represented in the compacted handoff and must
# not be cloned into the child. Everything at or below
# this MAX(id) but above the start-watermark is a foreign
# concurrent append; everything above it is our flush.
try:
_foreign_tail_ceiling = (
await agent._session_db.get_active_message_watermark(
Expand Down Expand Up @@ -2710,8 +2761,7 @@ async def _refresh_lock_lease() -> None:
_profile_for_child = None
except Exception:
_profile_for_child = None
old_title = await _lock_db.get_session_title(agent.session_id)
old_session_id = agent.session_id
old_title = await _lock_db.get_session_title(old_session_id)
new_session_id = (
f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_"
f"{uuid.uuid4().hex[:6]}"
Expand Down Expand Up @@ -2812,6 +2862,26 @@ async def _refresh_lock_lease() -> None:
)
_boundary_parent = _old_sid or agent.session_id or ""

# The compression heartbeat is persisted against the parent before an
# out-of-place rotation publishes its child. Clear those labels after
# the transaction commits so an archived parent does not advertise a
# fresh compression activity forever; the child keeps the live labels.
if _old_sid and _session_commit_succeeded:
try:
clear_labels = getattr(
_lock_db, "clear_session_activity_labels", None
)
if callable(clear_labels):
await clear_labels(_old_sid)
except asyncio.CancelledError:
raise
except Exception:
logger.debug(
"failed to clear archived compression parent's activity "
"labels (ignored)",
exc_info=True,
)

# Notify the context engine that a compaction boundary occurred. Plugin
# engines (e.g. hermes-lcm) use boundary_reason="compression" to preserve
# DAG lineage / checkpoint per-session state across the boundary instead of
Expand Down
Loading
Loading