The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): keep tool-call uids paired through rewrites, folds of repeated ids and chunked copies
kshitijk4poordd66c132f231
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 7a4d0f9ca2e..205226bddfc 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -19,7 +19,8 @@ from hermes_cli.timeouts import get_provider_request_timeoutfrom agent.message_sanitization import (_FULL_ARGS_LOG_BOUND, coalesce_tool_call_id, coerce_tool_name, tool_call_id_variants, tool_result_id_variants)-from agent.message_metadata import TOOL_CALL_UIDS, merge_tool_call_uids, record_absorbed_message+from agent.message_metadata import (+ TOOL_CALL_UIDS, merge_tool_call_uids, per_occurrence_tool_call_uids, record_absorbed_message)from agent.prompt_builder import STEER_DISPLAY_KIND, steer_user_rowfrom agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_messagefrom agent.think_scrubber import THINK_TAG_NAMES@@ -392,8 +393,10 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> bool:if new_calls:prev["tool_calls"] = prev_calls + new_calls# The absorbed turn's calls keep the per-occurrence ids they were persisted with.- if extra := msg.get(TOOL_CALL_UIDS):- prev[TOOL_CALL_UIDS] = merge_tool_call_uids(prev.get(TOOL_CALL_UIDS) or {}, extra)+ if isinstance(extra := msg.get(TOOL_CALL_UIDS), dict) and extra:+ prev[TOOL_CALL_UIDS] = merge_tool_call_uids(+ per_occurrence_tool_call_uids(prev.get(TOOL_CALL_UIDS) or {}, prev_calls),+ per_occurrence_tool_call_uids(extra, new_calls))calls_changed = Trueelif prev_calls:prev["tool_calls"] = prev_callsdiff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex cc49ab1cd49..4c3ee14f2fd 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections import Counterfrom time import time as wall_timefrom uuid import uuid4from typing import Any, List, Mapping, MutableMapping, Optional, TypeVar@@ -148,6 +149,21 @@ def _uid_occurrences(value: Any) -> list:return list(value) if isinstance(value, list) else [value]+def per_occurrence_tool_call_uids(uids: Mapping[str, Any], tool_calls: List[Mapping[str, Any]]) -> dict:+ """*uids* with every provider id this row names more than once spelled out as one uid per occurrence. A+ single response that repeats an id shares ONE uid (its results carry it, so every call stays paired);+ before a fold appends another turn's occurrences, the shared uid must fill each of this row's slots or+ the appended uids would align with the wrong calls."""+ from agent.message_sanitization import coalesce_tool_call_id++ counts = Counter(call_id for tc in tool_calls if (call_id := coalesce_tool_call_id(tc)))+ expanded = dict(uids)+ for call_id, count in counts.items():+ if count > 1 and isinstance(uid := uids.get(call_id), str):+ expanded[call_id] = [uid] * count+ return expanded++def index_tool_call_uids(index: MutableMapping[str, str], assistant: Mapping[str, Any]) -> frozenset:"""Register an assistant dict's ``_tool_call_uids`` under every pairing-id variant of its tool calls, so alater tool-result row can be resolved by any spelling of its ``tool_call_id``. Provider ids repeat, sodiff --git a/agent/transcript_repair.py b/agent/transcript_repair.pyindex 04b89f51e1e..e8e0d740541 100644--- a/agent/transcript_repair.py+++ b/agent/transcript_repair.py@@ -12,7 +12,7 @@ from agent.context_compressor import _DB_PERSISTED_MARKERfrom agent.message_metadata import (CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, copy_identity_fields)from hermes_state_common import _id_chunks, _placeholders-from hermes_state_identity import _restore_row_identity+from hermes_state_identity import _fill_missing_tool_call_uids, _restore_row_identityfrom hermes_state_messages import _MESSAGE_WRITE_COLUMNS@@ -116,6 +116,7 @@ def resolve_and_repair_transcript_batch(target_id = int(target_row["id"])msg["_row_id"] = target_id+ _fill_missing_tool_call_uids(target_row, msg) # a dict that lost its uids must not rewrite them awayexpected = msg.get(DB_ROW_SNAPSHOT)canonical = Noneadopt = wrote = Falsediff --git a/hermes_state_identity.py b/hermes_state_identity.pyindex 0d6c8f82d71..623ab6124a8 100644--- a/hermes_state_identity.py+++ b/hermes_state_identity.py@@ -8,6 +8,7 @@ import jsonfrom typing import Any, Dict, List, Mapping, MutableMapping, Optionalfrom agent.message_metadata import ABSORBED_MESSAGE_UIDS, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS, uid_list+from agent.message_sanitization import coalesce_tool_call_idfrom hermes_state_common import _json_or@@ -55,15 +56,35 @@ def _tool_call_uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:return uid if isinstance(uid, str) and uid else None+def _live_extends(live_uid: Any, stored_uid: Any) -> bool:+ """A live per-occurrence list that starts with every stored occurrence: a fold's union not yet written."""+ stored = stored_uid if isinstance(stored_uid, list) else [stored_uid]+ return isinstance(live_uid, list) and live_uid[:len(stored)] == stored+++def _fill_missing_tool_call_uids(row: Any, msg: MutableMapping[str, Any]) -> None:+ """Before a row-addressed rewrite serializes *msg*: stored uids for calls it still names but whose uid it+ lost (a clone), so the rewrite does not null them. A call the live dict dropped keeps no uid."""+ if not row["tool_call_uids"] or not isinstance(calls := msg.get("tool_calls"), list):+ return+ live = msg.get(TOOL_CALL_UIDS)+ live = live if isinstance(live, dict) else {}+ named = {coalesce_tool_call_id(tc) for tc in calls}+ if missing := {k: v for k, v in _uid_map(row["tool_call_uids"]).items() if k in named and k not in live}:+ msg[TOOL_CALL_UIDS] = {**live, **missing}++def _restore_row_identity(row: Any, msg: MutableMapping[str, Any]) -> None:- """A stored row's uid and tool-call uids onto its live dict: the stored value wins; pairings only the live- dict knows (an un-persisted merge's union) stay."""+ """A stored row's uid and tool-call uids onto its live dict (the stored value wins). A live per-occurrence+ list that already holds the stored uid is kept: it is a fold's union the row has not been rewritten+ with yet, and replacing it with the stored single uid would strip the later occurrence."""if row[MESSAGE_UID]:msg[MESSAGE_UID] = row[MESSAGE_UID]if row["tool_call_uids"] and (stored := _uid_map(row["tool_call_uids"])):live = msg.get(TOOL_CALL_UIDS)live = live if isinstance(live, dict) else {}- msg[TOOL_CALL_UIDS] = {**live, **stored}+ msg[TOOL_CALL_UIDS] = {**live, **{call_id: uid for call_id, uid in stored.items()+ if not _live_extends(live.get(call_id), uid)}}if row["tool_call_uid"]:msg[TOOL_CALL_UID] = row["tool_call_uid"]diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 7c137c04bc7..7e34ef49d59 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -298,7 +298,7 @@ class SessionMessagesMixin:for tc in tool_calls:call_id = coalesce_tool_call_id(tc)if call_id and call_id not in uids:- uids[call_id] = mint_uid()+ uids[call_id] = mint_uid() # one per provider id: a repeat in one response shares itif uids:msg[TOOL_CALL_UIDS] = uidsindex_tool_call_uids(batch_index, msg) # this row's ids shadow any earlier occurrence's@@ -455,6 +455,9 @@ class SessionMessagesMixin:if not messages:return 0if chunk_rows is not None and len(messages) > chunk_rows:+ tool_uid_index: Dict[str, str] = {}+ for msg in messages: # each chunk indexes only its own rows: pair results across chunk boundaries+ self._stamp_tool_call_uids(msg, _parse_tool_calls(msg.get("tool_calls")), tool_uid_index)return sum(self.append_messages_batch(session_id, messages[start:start + chunk_rows],compression_lock_holder=compression_lock_holder, turn_lease_holder=turn_lease_holder,turn_lease_ttl_seconds=turn_lease_ttl_seconds)diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex fc49ac08265..4a8e6f876d0 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -398,7 +398,7 @@ class TestPersistedMergeWitness:assistant = {"role": "assistant", "content": "partial","tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}db.append_messages_batch("s", [assistant])- uids = dict(assistant["_tool_call_uids"])+ uids = assistant.pop("_tool_call_uids") # a restored/cloned dict that lost its map: the row keeps itassistant["content"] = "partial, then filled by the sanitizer"db.append_messages_batch("s", [assistant])rows = _rows(db, "s")@@ -465,3 +465,77 @@ def test_a_result_pairs_with_the_assistant_that_named_it_not_the_nearest_one(db)owners: dict = {}assert [tool_call_uid_from_history(live, i, owners) for i in (3, 4)] == [second, first]++def test_one_response_repeating_a_provider_id_shares_one_uid_its_results_all_carry(db):+ """Two calls sharing a provider id in ONE response share one uid: both results carry it, so neither call+ looks unanswered to a context engine."""+ db.create_session("s", "cli")+ call = {"role": "assistant", "content": "", "tool_calls": [_call("call_x"), _call("call_x")]}+ results = [{"role": "tool", "content": c, "tool_call_id": "call_x", "tool_name": "t"} for c in "ab"]+ db.append_messages_batch("s", [{"role": "user", "content": "q"}, call, *results])+ shared = call["_tool_call_uids"]["call_x"]+ assert isinstance(shared, str) and [r["_tool_call_uid"] for r in results] == [shared, shared]+++def test_a_fold_after_a_shared_uid_row_keeps_each_call_aligned_with_its_uid():+ """The shared uid fills each of the row's own slots before the absorbed turn's occurrence is appended, so+ the absorbed call (third) keeps its own uid instead of sliding onto the second."""+ from agent.agent_runtime_helpers import _merge_consecutive_assistants+ from agent.message_metadata import index_tool_call_uids, resolve_tool_call_uid++ shared, own = "1" * 32, "2" * 32+ first = {"role": "assistant", "content": "", "tool_calls": [_call("call_x"), _call("call_x")],+ "_tool_call_uids": {"call_x": shared}}+ second = {"role": "assistant", "content": "", "tool_calls": [_call("call_x")], "_tool_call_uids": {"call_x": own}}+ _merge_consecutive_assistants([first, second])+ assert first["_tool_call_uids"] == {"call_x": [shared, shared, own]}+ index: dict = {}+ index_tool_call_uids(index, first)+ assert resolve_tool_call_uid(index, "call_x") == own+++def test_a_rewrite_keeps_a_fold_that_extends_a_stored_occurrence_list(db):+ db.create_session("s", "cli")+ a = {"role": "assistant", "content": "a", "tool_calls": [_call("call_0"), _call("call_0")],+ "_tool_call_uids": {"call_0": ["1" * 32, "2" * 32]}}+ b = {"role": "assistant", "content": "b", "tool_calls": [_call("call_0")], "_tool_call_uids": {"call_0": "3" * 32}}+ db.append_messages_batch("s", [{"role": "user", "content": "q"}, a, b])+ survivor = db.get_messages_as_conversation("s", repair_alternation=True, include_row_ids=True)[1]+ survivor.pop("_db_row_snapshot", None)+ db.append_messages_batch("s", [survivor])+ assert survivor["_tool_call_uids"] == {"call_0": ["1" * 32, "2" * 32, "3" * 32]}+++def test_a_rewrite_that_drops_a_call_does_not_write_its_uid_back(db):+ db.create_session("s", "cli")+ assistant = {"role": "assistant", "content": "x", "tool_calls": [_call("c1"), _call("c2")]}+ db.append_messages_batch("s", [assistant])+ assistant["tool_calls"] = [_call("c1")]+ assistant["_tool_call_uids"] = {"c1": assistant["_tool_call_uids"]["c1"]}+ db.append_messages_batch("s", [assistant])+ stored = db._conn.execute("SELECT tool_call_uids FROM messages").fetchone()[0]+ assert sorted(json.loads(stored)) == ["c1"]+++def test_a_rewrite_keeps_a_folds_per_occurrence_list_over_the_stored_single_uid(db):+ """Restore folds two stored turns that reuse an id; re-flushing the survivor must not let the stored+ pre-fold map collapse the list back to one uid (the later occurrence's results would pair with nothing)."""+ db.create_session("s", "cli")+ a = {"role": "assistant", "content": "a", "tool_calls": [_call("call_0")]}+ b = {"role": "assistant", "content": "b", "tool_calls": [_call("call_0")]}+ db.append_messages_batch("s", [{"role": "user", "content": "q"}, a, b])+ occurrences = [a["_tool_call_uids"]["call_0"], b["_tool_call_uids"]["call_0"]]+ survivor = db.get_messages_as_conversation("s", repair_alternation=True, include_row_ids=True)[1]+ survivor.pop("_db_row_snapshot", None) # the digest-less re-flush path (replay heal, adopt mismatch)+ assert survivor["_tool_call_uids"] == {"call_0": occurrences}+ db.append_messages_batch("s", [survivor])+ assert survivor["_tool_call_uids"] == {"call_0": occurrences}+++def test_a_chunked_copy_pairs_a_result_with_a_call_in_the_previous_chunk(db):+ db.create_session("s", "cli")+ call = {"role": "assistant", "content": "", "tool_calls": [_call("call_1")]}+ result = {"role": "tool", "content": "r", "tool_call_id": "call_1", "tool_name": "t"}+ db.append_messages_batch("s", [{"role": "user", "content": "q"}, call, result], chunk_rows=2)+ stored = db._conn.execute("SELECT tool_call_uid FROM messages WHERE role = 'tool'").fetchone()[0]+ assert stored == call["_tool_call_uids"]["call_1"]diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.mdindex bf18aa0c125..8ffc9822a03 100644--- a/website/docs/developer-guide/context-engine-plugin.md+++ b/website/docs/developer-guide/context-engine-plugin.md@@ -194,9 +194,11 @@ What the host guarantees:(Hermes mints deterministic `call_<12hex>` ids for identical calls, and modelsreuse ids), so an assistant message carries `_tool_call_uids`, a`{tool_call_id: uid}` map for its `tool_calls`, and each tool-result message- carries the matching `_tool_call_uid`. When a fold leaves one message with two- calls that share a provider id, that id maps to a list of uids, one per- occurrence in `tool_calls` order. The provider-facing `id` inside+ carries the matching `_tool_call_uid`. Calls that repeat a provider id inside+ one response share one uid (every result carries it, so no call looks+ unanswered). When a fold leaves one message holding calls from two turns+ that share an id, that id maps to a list of uids, one per occurrence in+ `tool_calls` order. The provider-facing `id` inside`tool_calls` is untouched. Both are minted at the assistant row's firstinsert, paired onto the result when it is flushed (same batch, or from thelive list when the result lands in a later flush) and on restore (from thediff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex ed421f9ba48..1bacf56e8f5 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -245,7 +245,7 @@ Notes:- Timestamps are Unix epoch floats (`time.time()`)- `message_uid` is the durable per-message id (32 hex, `uuid4().hex`): minted once at a row's first insert and copied by every clone (in-place compaction generations, rotation children, concurrent-tail clones, `replace_messages` re-issues, export/import), so one logical message keeps one uid while its physical `id` changes. Row-addressed rewrites leave it alone. It is restored on every projection (`get_messages_as_conversation` sets it unconditionally; `_row_id` stays opt-in) and stripped from provider requests. Context engines key their own per-message state on it — see [Context Engine Plugins](./context-engine-plugin.md#stable-message-identity-message_uid).- `absorbed_message_uids` is the merge witness: a JSON list of the `message_uid`s the host folded into this row (alternation repair's user and assistant merges, the compressor's in-flight restatement and anchor folds, micro-compaction's adjacent-user merge; the composite keeps the first constituent's uid). Written when the survivor is flushed, rewritten with it, restored as the live `_absorbed_message_uids`, `NULL` on rows that absorbed nothing.-- `tool_call_uids` (assistant rows) is a JSON `{tool_call_id: uid}` map giving each entry of `tool_calls` a per-occurrence id, because provider tool-call ids repeat (an id repeated inside one row, after two assistant turns are folded, maps to a list of uids in call order); `tool_call_uid` (tool rows) is the matching value for the result. The `tool_calls` JSON itself is never modified. Minted at the assistant row's first insert, paired onto the result at flush or, when the column is `NULL`, derived on restore from the preceding assistant row; restored as the live `_tool_call_uids` / `_tool_call_uid`.+- `tool_call_uids` (assistant rows) is a JSON `{tool_call_id: uid}` map giving each entry of `tool_calls` a per-occurrence id, because provider tool-call ids repeat (calls repeating an id inside one response share its uid; after two assistant turns are folded, an id both name maps to a list of uids, one per occurrence in call order); `tool_call_uid` (tool rows) is the matching value for the result. The `tool_calls` JSON itself is never modified. Minted at the assistant row's first insert, paired onto the result at flush or, when the column is `NULL`, derived on restore from the preceding assistant row; restored as the live `_tool_call_uids` / `_tool_call_uid`.### FTS5 Full-Text Search