Nine ContextCompressor helpers and message_metadata's _display_metadata_str had bodies equal to their session_rules.turns namesakes, so the two copies could drift apart. The nine helpers keep their names, decorators and docstrings and now return the session_rules.turns function's result; _display_metadata_str is imported from session_rules.turns. The constants the removed bodies read have the same values in both modules, so behaviour is unchanged.
326 lines
17 KiB
Python
326 lines
17 KiB
Python
"""Internal metadata attached to durable conversation messages."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from time import time as wall_time
|
|
from typing import Any, List, Mapping, MutableMapping, Optional, TypeVar
|
|
|
|
from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, RETIRED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS
|
|
from session_rules.turns import (
|
|
_display_metadata_str, index_tool_call_uids, message_uid_or_none, mint_uid, resolve_tool_call_uid,
|
|
withheld_prompt_text,
|
|
)
|
|
|
|
|
|
# These fields describe Hermes' durable record and timeline display, not
|
|
# provider-visible message content. The request builder strips them from every
|
|
# outgoing copy and the token estimator ignores them: one set, so an estimate
|
|
# never prices bytes the provider never receives (an edit's inline_diff in
|
|
# display_metadata is ~9KB and would trigger premature compaction).
|
|
# Transcript-repair bookkeeping riding on batch rows / live dicts (agent/transcript_repair.py): the
|
|
# stored-row CAS digest and the durable row adopted onto the live dict. Never transcript payload.
|
|
DB_ROW_SNAPSHOT = "_db_row_snapshot"
|
|
CANONICAL_ROW = "_canonical_row"
|
|
# Set by the agent flush on a batch row (never a live dict) whose ``message_uid`` the agent itself saw durable in
|
|
# this session (written by an earlier flush, or loaded from the store with its marker). Only such a row, with no
|
|
# row address or snapshot, may be skipped as a re-insert of an ACTIVE uid; a bare copied uid proves nothing.
|
|
RESTORED_FROM_STORE = "_restored_from_store"
|
|
REPAIR_BOOKKEEPING_FIELDS = frozenset({DB_ROW_SNAPSHOT, CANONICAL_ROW, RESTORED_FROM_STORE})
|
|
# Unanswered text a merged user row held before the current turn was absorbed
|
|
# (session_rules.turns._merge_consecutive_users); the persist override keeps it.
|
|
# It repeats the row's own content, so pricing it would double the estimate.
|
|
MERGED_TURN_PREFIX = "_merged_turn_prefix"
|
|
# The durable per-message id (``messages.message_uid``): minted once at the row's first insert and kept by
|
|
# every host copy of that logical message (in-place compaction generation, rotation child, concurrent-tail
|
|
# clone, replace re-issue, rewrite in place). Unlike ``_row_id`` (a physical id re-issued per copy, opt-in on
|
|
# restore) it is restored unconditionally, so context engines can key on it across restarts and boundaries.
|
|
MESSAGE_UID = "message_uid"
|
|
# The merge witness on a consecutive-user merge survivor: the ``message_uid`` of each absorbed row, in
|
|
# absorption order (the uid sibling of ``_absorbed_row_ids``; persisted as ``messages.absorbed_message_uids``).
|
|
# The survivor keeps the FIRST constituent's uid.
|
|
ABSORBED_MESSAGE_UIDS = "_absorbed_message_uids"
|
|
# Per-occurrence tool-call identity. Provider tool-call ids repeat (Hermes mints deterministic ``call_<12hex>``
|
|
# ids for identical calls, and models reuse ids), so an assistant row carries ``{provider id: uid}`` for its
|
|
# ``tool_calls`` (``messages.tool_call_uids``) and its tool-result rows carry the matching uid
|
|
# (``messages.tool_call_uid``). The provider-facing ``id`` is untouched; these never reach the wire.
|
|
TOOL_CALL_UIDS = "_tool_call_uids"
|
|
TOOL_CALL_UID = "_tool_call_uid"
|
|
PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(
|
|
# Membership is the real contract, NOT the leading underscore: the chat-completions transport happens
|
|
# to sweep underscore keys, but turn_context.py pops this set from every outgoing copy and a strict
|
|
# backend 400s on any key it does not know.
|
|
{"timestamp", "display_kind", "display_metadata", "_row_id", "_submit_row_session_id",
|
|
MERGED_TURN_PREFIX, MESSAGE_UID, ABSORBED_MESSAGE_UIDS, TOOL_CALL_UIDS, TOOL_CALL_UID,
|
|
# The alternation repair's row counts: an in-place compaction reads them off the live dict.
|
|
MERGED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS, RETIRED_DURABLE_ROWS}
|
|
) | REPAIR_BOOKKEEPING_FIELDS
|
|
|
|
|
|
# Connector data-use requirement on a tool message; persisted inside ``display_metadata``, never sent to a model.
|
|
DATA_USE = "data_use"
|
|
|
|
|
|
def _set_display_metadata_key(message: MutableMapping[str, Any], key: str, value: Any) -> None:
|
|
"""Set *key* in *message*'s ``display_metadata`` as a new dict (a non-dict value starts empty)."""
|
|
metadata = message.get("display_metadata")
|
|
message["display_metadata"] = {**(metadata if isinstance(metadata, dict) else {}), key: value}
|
|
|
|
|
|
def data_use_requirement(messages: Any) -> frozenset[str]:
|
|
"""The union of ``data_use`` over *messages*: what the model receiving them must guarantee."""
|
|
return frozenset(r for m in messages or () if isinstance(m, Mapping) for r in m.get(DATA_USE) or ())
|
|
|
|
|
|
def stamp_data_use(message: MutableMapping[str, Any], requires: list[str]) -> None:
|
|
"""Mark a tool message with its requirement. The ``display_metadata`` copy is the durable one: that
|
|
column already rides every writer, branch and compaction copy, and replay lifts it back (the session store)."""
|
|
if not requires:
|
|
return
|
|
message[DATA_USE] = list(requires)
|
|
_set_display_metadata_key(message, DATA_USE, list(requires))
|
|
|
|
|
|
# What the user typed on a turn a ``pre_llm_call`` hook vetoed, kept inside ``display_metadata``. The row's
|
|
# ``content`` is the withheld placeholder, so every reader that hands transcript text to a model (wire
|
|
# replay, compaction, session_search, memory providers, background review) only ever sees that; transcript
|
|
# views render this key instead (agent/turn_context.py::_withhold_blocked_prompt).
|
|
WITHHELD_PROMPT = "withheld_prompt"
|
|
PRE_LLM_BLOCK_WITHHELD_PROMPT = "[Message withheld: a pre_llm_call policy hook blocked it.]"
|
|
|
|
|
|
# The ask of a multimodal turn (the text of its persisted parts: image-path hints, not ``[screenshot]``), kept inside
|
|
# ``display_metadata`` when the turn's injected context (recalled memory, ``pre_llm_call`` and gateway notes)
|
|
# is appended to ``content`` as a text part: the DB stores that content as one flattened string, so nothing
|
|
# else can tell the ask from the injection.
|
|
TYPED_ASK = "typed_ask"
|
|
|
|
|
|
def stamp_typed_ask(message: MutableMapping[str, Any], text: str) -> None:
|
|
"""Record *text* as the ask ``previous_message`` reads for *message*."""
|
|
_set_display_metadata_key(message, TYPED_ASK, text)
|
|
|
|
|
|
def typed_ask_text(message: Any) -> Optional[str]:
|
|
"""The typed ask stamped on *message*, else None."""
|
|
return _display_metadata_str(message, TYPED_ASK)
|
|
|
|
|
|
def without_withheld_prompts(messages: Any) -> Any:
|
|
"""*messages* with the vetoed text dropped from each row's ``display_metadata`` (copies only where
|
|
one is present), for hand-offs that leave the host with whole row dicts (memory providers)."""
|
|
if not isinstance(messages, list) or not any(withheld_prompt_text(m) is not None for m in messages):
|
|
return messages
|
|
return [
|
|
{**m, "display_metadata": {k: v for k, v in m["display_metadata"].items() if k != WITHHELD_PROMPT}}
|
|
if withheld_prompt_text(m) is not None else m
|
|
for m in messages
|
|
]
|
|
|
|
|
|
def lift_data_use(message: MutableMapping[str, Any]) -> None:
|
|
"""Restore a replayed row's ``data_use`` key from its durable ``display_metadata`` copy."""
|
|
metadata = message.get("display_metadata")
|
|
if isinstance(metadata, dict) and metadata.get(DATA_USE):
|
|
message[DATA_USE] = list(metadata[DATA_USE])
|
|
|
|
|
|
# Reasoning tokens the provider billed for an assistant turn (``usage.*_tokens_details.reasoning_tokens``),
|
|
# kept inside ``display_metadata`` so it rides every writer, branch and compaction copy without a column.
|
|
# Encrypted reasoning (Codex/xAI ``encrypted_content``, Claude ``signature``) cannot be sized from its
|
|
# bytes, but the provider bills its replay as input at almost exactly this count (live A/B: gpt-5.6-sol
|
|
# 2,765 reported -> +2,767 billed; claude-opus-5.5 3,959 -> +3,959 while its summary text was ~1,016).
|
|
REPLAYED_REASONING_TOKENS = "reasoning_tokens"
|
|
# The same count on a per-call request copy: ``build_api_messages`` drops ``display_metadata`` from every
|
|
# outgoing copy, so the request estimate would lose it. ``assemble_api_request`` pops this key from the
|
|
# request once it is measured; it never reaches a provider.
|
|
REQUEST_REASONING_TOKENS = "_replayed_reasoning_tokens"
|
|
|
|
|
|
def stamp_reasoning_tokens(message: MutableMapping[str, Any], tokens: Any) -> None:
|
|
"""Record *tokens* as the provider-reported reasoning size of assistant *message*. An unknown or
|
|
zero count clears any earlier stamp: it priced reasoning the row no longer carries."""
|
|
if isinstance(tokens, int) and not isinstance(tokens, bool) and tokens > 0:
|
|
_set_display_metadata_key(message, REPLAYED_REASONING_TOKENS, tokens)
|
|
return
|
|
metadata = message.get("display_metadata")
|
|
if isinstance(metadata, dict) and REPLAYED_REASONING_TOKENS in metadata:
|
|
message["display_metadata"] = {k: v for k, v in metadata.items() if k != REPLAYED_REASONING_TOKENS}
|
|
|
|
|
|
def stamped_reasoning_tokens(message: Any) -> int:
|
|
"""The provider-reported reasoning size stamped on *message* (stored row or request copy), else 0."""
|
|
if not isinstance(message, Mapping):
|
|
return 0
|
|
value = message.get(REQUEST_REASONING_TOKENS)
|
|
if value is None:
|
|
metadata = message.get("display_metadata")
|
|
value = metadata.get(REPLAYED_REASONING_TOKENS) if isinstance(metadata, Mapping) else None
|
|
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
|
|
|
|
|
|
def drop_request_reasoning_tokens(messages: Any) -> None:
|
|
"""Pop the request-only reasoning count from every request copy in *messages* (in place)."""
|
|
for message in messages if isinstance(messages, list) else ():
|
|
if isinstance(message, dict):
|
|
message.pop(REQUEST_REASONING_TOKENS, None)
|
|
|
|
|
|
# Replay carriers the preflight estimate prices at 0, exactly as the compaction tail walk does (opaque signatures,
|
|
# duplicate reasoning copies, ordered sidecars); a mismatch between the two estimates loops compaction.
|
|
_UNPRICED_CORE_FIELDS = frozenset({"_anthropic_content_blocks", "reasoning_details", "extra_content",
|
|
"bedrock_content_blocks", DATA_USE, REQUEST_REASONING_TOKENS})
|
|
|
|
|
|
def unpriced_replay_fields() -> frozenset[str]:
|
|
"""The core unpriced carriers plus every message carrier key a registered profile declares
|
|
(``ProviderProfile.message_carrier_*``). Resolve once per message, never per key."""
|
|
from agent.reasoning_carriers import declared_carrier_keys
|
|
|
|
opaque, text = declared_carrier_keys()
|
|
return _UNPRICED_CORE_FIELDS.union(opaque, text)
|
|
|
|
|
|
def without_persistence_fields(msg: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
"""*msg* itself when it carries no persistence-only field, else a shallow copy without them."""
|
|
if PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(msg):
|
|
return msg
|
|
return {k: v for k, v in msg.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}
|
|
|
|
|
|
def stamp_message_uid(msg: MutableMapping[str, Any]) -> str:
|
|
"""The dict's ``message_uid``, minting one (``mint_uid``) when it carries none.
|
|
|
|
Minted ONCE per logical message, at its first insert, and stamped on the caller's dict so every later
|
|
insert of that dict (compaction generation, rotation handoff, replace) writes the same uid. Never
|
|
derived from content, timestamp or tool-call ids: two distinct messages may share all three.
|
|
"""
|
|
uid = message_uid_or_none(msg)
|
|
if uid is None:
|
|
uid = msg[MESSAGE_UID] = mint_uid()
|
|
return uid
|
|
|
|
|
|
# Producer-owned provenance for the compressor's standalone in-flight-task restatement. It rides in
|
|
# display_metadata (persisted by the session store, popped from every wire copy) so gateway replay can send the
|
|
# row unstamped, as the compaction turn did; a human pasting the header text carries no flag.
|
|
INFLIGHT_TASK_RESTATEMENT = "compaction_inflight_task_restatement"
|
|
|
|
|
|
def mark_inflight_restatement(msg: MutableMapping[str, Any]) -> None:
|
|
_set_display_metadata_key(msg, INFLIGHT_TASK_RESTATEMENT, True)
|
|
|
|
|
|
def scaffolding_replay_fields(msg: Mapping[str, Any]) -> dict:
|
|
"""The compaction-provenance fields replay keeps (summary flag, restatement flag), else ``{}``. A proactive
|
|
prune re-persists the replayed view, so a dropped flag would get the row stamped on the next replay."""
|
|
metadata = msg.get("display_metadata")
|
|
fields: dict = {"_compressed_summary": True} if msg.get("_compressed_summary") else {}
|
|
if isinstance(metadata, dict) and metadata.get(INFLIGHT_TASK_RESTATEMENT):
|
|
fields["display_metadata"] = {INFLIGHT_TASK_RESTATEMENT: True}
|
|
return fields
|
|
|
|
|
|
def typed_ask_fields(msg: Mapping[str, Any]) -> Optional[dict]:
|
|
"""``{TYPED_ASK: ...}`` when *msg* carries the stamp, else None: the only key a row rewrite that backfills
|
|
the stamp writes (merge-patched, so other writers' keys stay as committed)."""
|
|
typed = typed_ask_text(msg)
|
|
return None if typed is None else {TYPED_ASK: typed}
|
|
|
|
|
|
def replay_metadata_fields(msg: Mapping[str, Any]) -> dict:
|
|
"""``scaffolding_replay_fields`` plus the typed-ask stamp (``previous_message`` must not read a
|
|
multimodal turn's flattened injected context back)."""
|
|
fields = scaffolding_replay_fields(msg)
|
|
if (typed := typed_ask_text(msg)) is not None:
|
|
fields["display_metadata"] = {**fields.get("display_metadata", {}), TYPED_ASK: typed}
|
|
return fields
|
|
|
|
|
|
def is_compaction_scaffolding(msg: Mapping[str, Any]) -> bool:
|
|
"""Compaction sent its summary and restatement rows unstamped; a replay stamp would break the cached prefix."""
|
|
return bool(scaffolding_replay_fields(msg))
|
|
|
|
|
|
_IDENTITY_FIELD_TYPES = ((MESSAGE_UID, str), (ABSORBED_MESSAGE_UIDS, list), (TOOL_CALL_UIDS, dict), (TOOL_CALL_UID, str))
|
|
|
|
|
|
def copy_identity_fields(src: Mapping[str, Any], dst: MutableMapping[str, Any]) -> None:
|
|
"""Copy the non-empty identity fields (uid, merge witness, tool-call uids) from *src* onto *dst*: the
|
|
live dict to its flush row, and the committed row back onto the live dict."""
|
|
for key, kind in _IDENTITY_FIELD_TYPES:
|
|
value = src.get(key)
|
|
if isinstance(value, kind) and value:
|
|
dst[key] = kind(value)
|
|
|
|
|
|
def message_identity(msg: MutableMapping[str, Any], *, with_tool_uids: bool = False) -> dict:
|
|
"""The identity fields a new row copied from *msg* must carry, minting *msg*'s uid first when it has none:
|
|
a branch/seed copy writes fresh rows from the live dicts the new session keeps using, and a row without
|
|
them would restore with a different uid than the live dict carries. ``with_tool_uids`` only for a copy
|
|
that also carries ``tool_calls`` / ``tool_call_id``; a uid map on a row without its calls pairs nothing."""
|
|
stamp_message_uid(msg)
|
|
identity: dict = {}
|
|
copy_identity_fields(msg, identity)
|
|
if not with_tool_uids:
|
|
identity.pop(TOOL_CALL_UIDS, None)
|
|
identity.pop(TOOL_CALL_UID, None)
|
|
return identity
|
|
|
|
|
|
def tool_call_uid_from_history(messages: list[dict], tool_index: int, owners: dict) -> Optional[str]:
|
|
"""Resolve a tool-result dict's uid from the nearest preceding assistant dict in ``messages`` that
|
|
named its ``tool_call_id`` (the cross-flush case: the assistant row landed in an earlier batch).
|
|
``owners`` memoizes each assistant's (named variants, uid index) across one flush's results, so K
|
|
parallel results of one assistant cost O(K) variant work instead of O(K^2)."""
|
|
tool_call_id = messages[tool_index].get("tool_call_id")
|
|
if not isinstance(tool_call_id, str) or not tool_call_id:
|
|
return None
|
|
from session_rules.turns import tool_result_id_variants
|
|
|
|
result_variants = set(tool_result_id_variants(tool_call_id))
|
|
for prior_index in range(tool_index - 1, -1, -1): # no messages[:i] copy: this runs per flushed result
|
|
prior = messages[prior_index]
|
|
if not isinstance(prior, dict):
|
|
continue
|
|
if prior.get("role") == "user":
|
|
return None # a tool result never pairs across a user turn
|
|
if prior.get("role") != "assistant":
|
|
continue
|
|
if (entry := owners.get(id(prior))) is None:
|
|
index: dict = {}
|
|
entry = owners[id(prior)] = (index_tool_call_uids(index, prior), index)
|
|
named, index = entry
|
|
if result_variants.isdisjoint(named):
|
|
continue
|
|
# The nearest assistant naming this id owns the result: its uid, or none if it has no map (legacy).
|
|
return resolve_tool_call_uid(index, tool_call_id)
|
|
return None
|
|
|
|
_Message = TypeVar("_Message", bound=MutableMapping[str, Any])
|
|
|
|
|
|
def stamp_message_timestamp(
|
|
message: _Message,
|
|
*,
|
|
timestamp: Optional[float] = None,
|
|
) -> _Message:
|
|
"""Attach a creation timestamp without replacing source-provided time.
|
|
|
|
Gateway adapters can supply the platform event time; all other callers use
|
|
the local wall clock. Returns the same mapping for use at append sites.
|
|
"""
|
|
if message.get("timestamp") is None:
|
|
message["timestamp"] = wall_time() if timestamp is None else timestamp
|
|
return message
|
|
|
|
|
|
def append_message(
|
|
messages: list[Any],
|
|
message: _Message,
|
|
*,
|
|
timestamp: Optional[float] = None,
|
|
) -> _Message:
|
|
"""Stamp and append one live transcript message."""
|
|
messages.append(stamp_message_timestamp(message, timestamp=timestamp))
|
|
return message
|