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
2 changes: 1 addition & 1 deletion docs/en/docs/integrations/hermes.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ Turning off turn capture does not turn off recall, pre-compression capture, or e

| Event/entry | Data sent | Direct recipient | Default/trigger | Disable | Effect when disabled |
| --- | --- | --- | --- | --- | --- |
| Recall / prefetch | Query (trimmed; when longer than 8192 characters or 8192 UTF-8 bytes, cut to its most recent text within both bounds; not credential-scrubbed), Scope and preparation options; prepared context returns to Hermes | PowerContext Server | Active provider, nonempty query and resolved Scope; cached prefetch may be reused | Select a different memory provider to stop this provider's automatic recall; there is no separate recall switch here | PowerContext automatic recall stops; capture switches alone leave recall available |
| Recall / prefetch | Query (trimmed; when longer than 8192 characters or 8192 UTF-8 bytes, cut to its most recent text within both bounds; not credential-scrubbed), Scope and preparation options; prepared context returns to Hermes | PowerContext Server | Active provider, nonempty query and resolved Scope; each turn prepares its own prompt, and the post-turn background prefetch sends nothing | Select a different memory provider to stop this provider's automatic recall; there is no separate recall switch here | PowerContext automatic recall stops; capture switches alone leave recall available |
| Completed turn | Bounded user/assistant text pair without secret redaction, plus session metadata; not the complete tool transcript | PowerContext Server, as a Source | `capture_turns=true`; automatic writes are suppressed outside the primary agent context | Set `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` before entering sensitive text | Stops this Source capture; recall, pre-compression capture and explicit writes remain independent |
| Session end | Flush request for already accepted inputs, not another upload of the session transcript | PowerContext Server | `flush_on_session_end=true`; waits for background writes and checks extraction capability | `POWERCONTEXT_HERMES_FLUSH_ON_SESSION_END=false` | Stops this flush trigger; accepted Sources remain and other processing triggers are unaffected |
| Before compression | New user/assistant evidence window, excluding system/tool messages and redacting detected secrets | PowerContext Server, as a Source | `capture_pre_compress=false`; opt in with `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | Stops this capture and its subsequent extraction attempt; a required checkpoint fails rather than reporting success |
Expand Down
9 changes: 4 additions & 5 deletions docs/en/rfcs/1489_prepared_context_text_assembly.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ request-local text policy.
| Codex, Claude Code, WorkBuddy | Strictly validate the four-field response and deliver its body through the Hook. | Forward the explicit assembly configuration and deliver the same validated body unchanged. |
| OpenCode, DSH, Pi | Validate four fields, then place content in a Host message or prompt wrapper. | Forward configuration and preserve the body; Host notices stay outside it. |
| OpenClaw | Apply local UTF-8 truncation and XML boundary escaping before wrapping the legacy body. | Fully validate and reject oversized responses; add a notice outside the unchanged body. |
| Hermes | Use `status`/`content`, apply `strip()`, add a notice, and maintain a prefetch cache. | Validate the full response and byte count, deliver unchanged text, and distinguish configuration and budget in the cache. |
| Hermes | Use `status`/`content`, apply `strip()`, and add a notice; each turn prepares its own prompt. | Validate the full response and byte count, and deliver unchanged text. |
| LangChain, Pydantic AI, Bub | Request through the Python Client and use returned `content`. | Forward the explicit configuration through the Client and deliver the returned body. |
| LangGraph | Use the Python Client and cache preparation for the current human turn. | Forward options and include assembly configuration and byte budget in cache identity. |

Expand All @@ -364,10 +364,9 @@ invalid request; meaningful explicit `null` values in other operations retain th
JSON regression tests cover omission, explicit defaults, and empty sections.

Cache identity retains the existing Scope/turn/query identity and additionally distinguishes the normalized
effective assembly configuration and `max_bytes`; legacy mode uses a separate identity. Hermes prefetch producers
and consumers must use the same key. If new configuration takes effect during a turn, do not reuse text prepared
under other families, ordering, or budgets. If configuration is fixed at turn start, freeze it explicitly until
that turn ends.
effective assembly configuration and `max_bytes`; legacy mode uses a separate identity. If new configuration takes
effect during a turn, do not reuse text prepared under other families, ordering, or budgets. If configuration is
fixed at turn start, freeze it explicitly until that turn ends.

| Caller and Server combination | Expected behavior |
| --- | --- |
Expand Down
2 changes: 1 addition & 1 deletion docs/zh/docs/integrations/hermes.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Evaluation trace 包含 prompt 和召回上下文,应保留在本机并按敏

| 事件/入口 | 发送的数据 | 直接接收方 | 默认/触发条件 | 关闭方式 | 关闭后影响 |
| --- | --- | --- | --- | --- | --- |
| 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;不做凭据脱敏)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;可能复用预取缓存 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 |
| 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;不做凭据脱敏)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;每轮按当前 prompt 准备,turn 结束后的后台预取不发请求 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 |
| 完成 turn | 有长度上限且不做 secret 脱敏的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript | PowerContext Server,保存为 Source | `capture_turns=true`;非主 Agent 上下文抑制自动写入 | 输入敏感文本前设置 `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` | 停止该 Source 捕获;召回、压缩前捕获和显式写入仍独立工作 |
| 会话结束 | 针对已接受输入的 flush 请求,不会重新上传会话 transcript | PowerContext Server | `flush_on_session_end=true`;等待后台写入并检查提取能力 | `POWERCONTEXT_HERMES_FLUSH_ON_SESSION_END=false` | 停止此 flush 触发;已接受的 Source 保留,其他处理触发不受影响 |
| 压缩前 | 新 user/assistant 证据窗口,排除 system/tool 消息并脱敏检测到的 secret | PowerContext Server,保存为 Source | `capture_pre_compress=false`;用 `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` 显式开启 | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | 停止此捕获及其后续提取尝试;必需 checkpoint 会失败而非报告成功 |
Expand Down
5 changes: 2 additions & 3 deletions docs/zh/rfcs/1489_prepared_context_text_assembly.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ rank 继续递增。对应的丢弃计数等于这些记录数加上上限之后
| Codex、Claude Code、WorkBuddy | 严格校验四字段响应,取出正文交付 Hook。 | 传递显式组装配置,并原样交付校验后的正文。 |
| OpenCode、DSH、Pi | 校验四字段响应,再放入 Host 消息或提示词包装。 | 传递配置,保持正文不变;Host 附加说明位于正文之外。 |
| OpenClaw | 对旧格式执行本地 UTF-8 裁剪、XML 边界转义,再增加包装。 | 完整校验并拒绝超预算响应,在未改写的正文外添加说明。 |
| Hermes | 使用 `status`/`content`,调用 `strip()` 后增加说明,并维护预取缓存。 | 完整校验响应和字节数,原样交付正文,缓存区分组装配置与预算。 |
| Hermes | 使用 `status`/`content`,调用 `strip()` 后增加说明;每轮按当前 prompt 准备。 | 完整校验响应和字节数,原样交付正文。 |
| LangChain、Pydantic AI、Bub | 通过 Python Client 请求,并使用返回的 `content`。 | 通过 Client 传递显式配置,交付返回的正文。 |
| LangGraph | 使用 Python Client,并缓存当前用户回合的 prepare 结果。 | 传递配置,缓存同时区分组装配置与字节预算。 |

Expand All @@ -318,8 +318,7 @@ Python Client 沿用 `TypeAdapter(...).dump_python(..., by_alias=True)` 完成
`null` 保持原有语义。出站 JSON 回归覆盖字段省略、显式默认配置和空 sections。

缓存以现有 Scope/turn/query 身份为基础,额外区分规范化后的有效组装配置及 `max_bytes`;旧模式使用独立标识。
Hermes 的预取生产者与消费者必须使用同一个键。新增配置在当前回合生效时,不能复用此前其他类别、顺序或预算的
文本;配置固定在回合开始时则明确冻结到该回合结束。
新增配置在当前回合生效时,不能复用此前其他类别、顺序或预算的文本;配置固定在回合开始时则明确冻结到该回合结束。

| 请求方与 Server 组合 | 预期行为 |
| --- | --- |
Expand Down
2 changes: 1 addition & 1 deletion integrations/hermes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Hermes asks the Server to resolve an explicit Scope, durable session and workspa

| Event | PowerContext behavior |
| --- | --- |
| Context recall | Prepares bounded context and injects it under a `## PowerContext recalled context` heading; the Server's trust policy at the top of that context marks it as untrusted historical evidence. Background preparation caches the exact query for the next turn. |
| Context recall | Prepares bounded context and injects it under a `## PowerContext recalled context` heading; the Server's trust policy at the top of that context marks it as untrusted historical evidence. Each turn prepares its own prompt; Hermes' post-turn background prefetch sends nothing. |
| Completed primary-Agent turn | Queues Source capture without blocking the conversation. |
| Session end | Waits for queued writes and requests Memory extraction when the Server supports it. |
| Transcript compression | When enabled, captures filtered new user/assistant turns before compression and requests extraction. Overlapping captures use stable Source identities. |
Expand Down
1 change: 0 additions & 1 deletion integrations/hermes/plugins/powercontext/plugin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ description: "External long-term memory and context retrieval backed by PowerCon
hooks:
- system_prompt_block
- prefetch
- queue_prefetch
- sync_turn
- on_session_end
- on_pre_compress
Expand Down
67 changes: 16 additions & 51 deletions integrations/hermes/plugins/powercontext/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,6 @@ def __init__(self, config: dict[str, Any] | None = None, *, client_factory=None)
self._pending_memory_writes = 0
self._accept_memory_writes = False
self._dropped_memory_writes = 0
self._prefetch_cache: dict[tuple[str, str, str, str], str] = {}
self._prefetch_lock = threading.Lock()
self._last_recall: Any = None
self._last_recall_scope_id = ""
self._memory_extraction_supported: bool | None = None
Expand Down Expand Up @@ -630,8 +628,6 @@ def _switch_scope(self, scope_id: str) -> None:
scope_id,
)

with self._prefetch_lock:
self._prefetch_cache.clear()
self._last_recall = None
self._last_recall_scope_id = ""
self._precompress_stream_id = f"{self._session_id}:{scope_id}"
Expand Down Expand Up @@ -850,24 +846,18 @@ def prefetch(self, query: str, *, session_id: str = "") -> str:
except PowerContextError as error:
self._emit_failure_diagnostic("context_prepare", error)
return ""
cache_key = (scope_id, session_key, query, json.dumps(options, sort_keys=True))
with self._prefetch_lock:
cached = self._prefetch_cache.pop(cache_key, None)
content = cached
trace_status = "cache" if cached is not None else "empty"
if content is None:
try:
response = client.prepare_context(
scope_id,
recall_query,
**options,
)
content = self._prepared_content(response, options)
trace_status = str(response.get("status", "empty"))
except PowerContextError as error:
self._emit_failure_diagnostic("context_prepare", error)
content = ""
trace_status = "error"
try:
response = client.prepare_context(
scope_id,
recall_query,
**options,
)
content = self._prepared_content(response, options)
trace_status = str(response.get("status", "empty"))
except PowerContextError as error:
self._emit_failure_diagnostic("context_prepare", error)
content = ""
trace_status = "error"
if scope_id != self._scope_id:
if self._last_recall_scope_id == scope_id:
self._last_recall = None
Expand Down Expand Up @@ -896,34 +886,11 @@ def prefetch(self, query: str, *, session_id: str = "") -> str:
return "## PowerContext recalled context\n\n" + delivered

def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
scope_id = self._scope_id
client = self._client
recall_query = _automatic_recall_query(query)
if not client or not scope_id or not recall_query:
return
session_key = session_id or self._session_id
try:
options = self._prepare_options()
except PowerContextError as error:
self._emit_failure_diagnostic("context_prepare", error)
return
cache_key = (scope_id, session_key, query, json.dumps(options, sort_keys=True))
"""No-op: ``prefetch`` prepares the current prompt synchronously at turn start.

def prepare() -> None:
try:
response = client.prepare_context(
scope_id,
recall_query,
**options,
)
content = self._prepared_content(response, options)
if content.strip():
with self._prefetch_lock:
self._prefetch_cache[cache_key] = content
except PowerContextError as error:
self._emit_failure_diagnostic("context_prepare", error)

self._enqueue_memory_write(prepare)
Hermes queues this after turn N with that turn's text and prefetches turn N+1 with the
next prompt, so a result keyed on the earlier query is almost never the one recall needs.
"""

def recall_status(self):
if self._last_recall_scope_id and self._last_recall_scope_id != self._scope_id:
Expand Down Expand Up @@ -1045,8 +1012,6 @@ def on_session_switch(
self._session_id = new_session_id
self._parent_session_id = parent_session_id
self._trace_turn = 0
with self._prefetch_lock:
self._prefetch_cache.clear()
self._last_recall = None
self._last_recall_scope_id = ""
self._record_trace_event(
Expand Down
10 changes: 3 additions & 7 deletions tests/inprocess_adapter_turns.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@
)

ADAPTERS = ("hermes", "langchain", "langgraph", "pydantic-ai")
# Entry points beyond each adapter's default asynchronous turn: LangChain's synchronous ``invoke``, and Hermes's
# ``queue_prefetch`` ahead of the ``prefetch`` that consumes it.
ENTRIES = {"langchain": ("ainvoke", "invoke"), "hermes": ("prefetch", "queue_prefetch")}
# Entry points beyond each adapter's default asynchronous turn: LangChain's synchronous ``invoke``.
ENTRIES = {"langchain": ("ainvoke", "invoke")}
RECALLED = "safe historical context"
ANSWER = "Acknowledged."
_SCOPE_ID = "scp_00000000000000000000000000"
Expand Down Expand Up @@ -155,6 +154,7 @@ def log_message(self, format: str, *_args: object) -> None: # noqa: A002 - Base


def _hermes(url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None) -> bool:
del entry # Hermes has one recall entry: the turn-start prefetch.
names = [name for name in sys.modules if name == "plugins" or name.startswith("plugins.")]
previous = {name: sys.modules.pop(name) for name in names}
sys.path.insert(0, str(_HERMES_ROOT))
Expand All @@ -166,10 +166,6 @@ def _hermes(url: str, prompt: str, *, token: str | None, capture: bool, home: Pa
provider = plugin.PowerContextMemoryProvider(config)
provider.initialize("session-1", hermes_home=str(home), agent_identity="coder", user_id="user-1")
try:
if entry == "queue_prefetch":
# Hermes queues the next turn's recall in the background; the next prefetch consumes its result.
provider.queue_prefetch(prompt, session_id="session-1")
assert provider._wait_for_memory_writes(timeout=10)
recalled = RECALLED in provider.prefetch(prompt, session_id="session-1")
provider.sync_turn(prompt, ANSWER, session_id="session-1")
finally:
Expand Down
Loading