From 578b118432108ed20dbf45031b709a4af50431b9 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Fri, 13 Nov 2026 20:07:55 -0500 Subject: [PATCH 1/4] fix(integrations): keep recognized credentials out of automatic recall and capture in in-process adapters Hermes, LangChain, LangGraph, and Pydantic AI sent the user's prompt unchanged as the automatic recall query, which the Server may embed, and Hermes and LangChain stored it in completed-turn Sources. A credential typed into a prompt could therefore leave the host and be persisted. These adapters now apply the automatic prompt privacy rule the hook hosts share (powercontext_integration_lifecycle.prompt_privacy), with the same handling: - The automatic recall query replaces recognized credentials, including the configured Server credential, with [REDACTED] before it is bounded. Recall still runs. - An automatic capture whose user text contains one is skipped as a whole: the Hermes and LangChain completed turn, and the Pydantic AI user_prompt event. A redacted copy is never stored under the original event's identity. The skip is logged at debug level as sensitive_content. Only the user text is checked; assistant text is not. Pydantic AI model-response and tool events keep their key-based and known-credential redaction. Hermes evaluation traces apply the shared rule on top of the plugin's own patterns; pre-compression capture keeps its own redaction, because skipping a recognized message there would change what a checkpoint commits. Each adapter ships a generated copy of the rule, like the recall bound. The shared privacy fixture now also drives one real turn through each adapter against a recording Server. The integration docs list the four adapters in the automatic prompt privacy policy, and the Hermes data flow table no longer says recall and completed-turn capture are unscrubbed. --- docs/en/docs/integrations/hermes.md | 11 ++-- docs/en/docs/integrations/index.md | 16 ++++++ docs/en/docs/integrations/langchain.md | 10 ++-- docs/en/docs/integrations/langgraph.md | 5 +- docs/en/docs/integrations/pydantic-ai.md | 12 +++-- docs/zh/docs/integrations/hermes.md | 9 ++-- docs/zh/docs/integrations/index.md | 14 ++++++ docs/zh/docs/integrations/langchain.md | 10 ++-- docs/zh/docs/integrations/langgraph.md | 5 +- docs/zh/docs/integrations/pydantic-ai.md | 8 +-- integrations/capabilities.toml | 8 +-- .../plugins/powercontext/prompt_privacy.py | 50 +++++++++++++++++++ .../hermes/plugins/powercontext/provider.py | 29 +++++++---- .../powercontext_langchain/_prompt_privacy.py | 50 +++++++++++++++++++ .../src/powercontext_langchain/middleware.py | 11 +++- .../powercontext_langgraph/_prompt_privacy.py | 50 +++++++++++++++++++ .../src/powercontext_langgraph/recall.py | 10 ++-- .../_prompt_privacy.py | 50 +++++++++++++++++++ .../powercontext_pydantic_ai/capability.py | 13 ++++- pyproject.toml | 8 +-- scripts/generate_integration_lifecycle.py | 8 ++- tests/integrations/test_hermes_provider.py | 26 +++++++++- tests/test_automatic_prompt_privacy.py | 39 ++++++++++++++- 23 files changed, 396 insertions(+), 56 deletions(-) create mode 100644 integrations/hermes/plugins/powercontext/prompt_privacy.py create mode 100644 integrations/langchain/src/powercontext_langchain/_prompt_privacy.py create mode 100644 integrations/langgraph/src/powercontext_langgraph/_prompt_privacy.py create mode 100644 integrations/pydantic-ai/src/powercontext_pydantic_ai/_prompt_privacy.py diff --git a/docs/en/docs/integrations/hermes.md b/docs/en/docs/integrations/hermes.md index 16740b126a..2b3717a9a6 100644 --- a/docs/en/docs/integrations/hermes.md +++ b/docs/en/docs/integrations/hermes.md @@ -99,15 +99,18 @@ 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 | -| 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 | +| Recall / prefetch | Query (trimmed; when longer than 8192 characters or 8192 UTF-8 bytes, cut to its most recent text within both bounds; recognized credentials replaced with `[REDACTED]`), 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 | +| Completed turn | Bounded user/assistant text pair, plus session metadata; not the complete tool transcript. A turn whose user text contains a recognized credential is skipped as a whole; assistant text is not checked | 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 | | Explicit remember / built-in memory mirror | Requested Memory content or change, with exact references for updates | PowerContext Server | Explicit operation, or primary-context `on_memory_write` for add/replace/remove | Do not invoke the write or mirror-producing built-in operation; no dedicated mirror switch | Turning off turn capture does not disable these writes | | Evaluation trace | Prompt/query, recalled context and correlation metadata; detected secrets are redacted | Local JSONL files, by default under `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`; opt in with `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | Stops new trace records without disabling recall or capture; existing files remain sensitive | -Recall requests and completed-turn Sources do not scrub credentials. Redaction of evaluation traces does not redact -the query already sent to the Server; pre-compression filtering applies only to that separate capture path. +Recall queries and completed-turn capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) +policy: recognized credentials are replaced in the query, and a turn whose user text contains one is not captured. +Pre-compression capture redacts detected secrets with its own rules, which are separate from that policy and +recognize fewer credential formats. A turn that completed-turn capture skips can still reach the Server, redacted by +those rules, in a pre-compression window. Pre-compression capture prefers the host-normalized `evidence_messages` when supplied, so earlier compression summaries are not reintroduced as fresh evidence. The provider declares checkpoint API v2 and raises on an diff --git a/docs/en/docs/integrations/index.md b/docs/en/docs/integrations/index.md index ed3dece5ed..0fb7b35c3f 100644 --- a/docs/en/docs/integrations/index.md +++ b/docs/en/docs/integrations/index.md @@ -68,6 +68,22 @@ when updating a plugin; this policy adds credential checks without changing capt | ZCode | `UserPromptSubmit` text | `POWERCONTEXT_ZCODE_CAPTURE_PROMPTS=false` | | Kimi Code (experimental) | Text parts of `UserPromptSubmit` | setup `--no-capture-prompts` | +The in-process Python adapters apply the same recognition and handling to their automatic paths without changing +their capture defaults: + +| Adapter | Automatic input boundary | Checked automatic capture | Capture default | +| --- | --- | --- | --- | +| Hermes | `prefetch` and `queue_prefetch` query | Completed-turn Source | On; `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` | +| LangChain | Latest human message | Completed-turn Source | Off; `PowerContextMiddleware(auto_capture=True)` | +| LangGraph | Latest human message | None; LangGraph captures only through explicit tools | Not applicable | +| Pydantic AI | Latest textual user prompt | `user_prompt` event | Off; `POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true` | + +These adapters check the user text only. A recognized credential skips the whole completed turn (Hermes, LangChain) +or the `user_prompt` event (Pydantic AI); assistant text is not checked. Pydantic AI model-response and tool events keep +their key-based and known-credential redaction, and Hermes pre-compression capture keeps its own redaction. The +configured Server credential is the adapter's token, or Hermes's Authorization value. A skip is logged at debug level +with the reason `sensitive_content` and without the rejected text. + Before automatic capture, these adapters recognize conventional credential assignments (API/access keys and tokens, client/private keys, secrets, passwords, passphrases, authorization and cookies), Bearer values of at least eight token characters, common provider/GitHub/Slack token shapes, private-key blocks including diff --git a/docs/en/docs/integrations/langchain.md b/docs/en/docs/integrations/langchain.md index 3508b82149..2ac517d5a1 100644 --- a/docs/en/docs/integrations/langchain.md +++ b/docs/en/docs/integrations/langchain.md @@ -65,7 +65,9 @@ instead of calling a synchronous method inside its event loop. For every model step, the middleware: 1. reads the latest human message without changing state; -2. calls `/v1/context/prepare` with the resolved scope and configured byte limit. The query is the message, trimmed; +2. calls `/v1/context/prepare` with the resolved scope and configured byte limit. The query is the message, trimmed, + with recognized credentials replaced by `[REDACTED]` as described in + [automatic prompt privacy](index.md#automatic-prompt-privacy); a message longer than 8,192 characters or 8,192 UTF-8 bytes recalls from its most recent text, cut to the last 8,192 characters and then to the last 8,192 bytes; 3. appends a separate text block to the current system message; @@ -90,8 +92,10 @@ not store the recalled system block, tool outputs, or intermediate tool-calling Capture creates Source evidence, not an inferred Memory entry. The configured scheduler or an explicit `flush_memory` operation performs the normal Source-to-Memory extraction later. This keeps lineage intact and avoids -treating raw model output as an already reviewed durable fact. Captured content is bounded but is not guaranteed to be -free of secrets, so applications must apply their own input and output policy before opting in. +treating raw model output as an already reviewed durable fact. A turn whose user message contains a recognized +credential is skipped as a whole. Detection is best effort and the assistant response is not checked, so captured +content is not guaranteed to be free of secrets; applications must apply their own input and output policy before +opting in. LangChain does not run `after_agent` when a model or tool aborts the run, so a failed run without a final response is not captured. diff --git a/docs/en/docs/integrations/langgraph.md b/docs/en/docs/integrations/langgraph.md index 33f57f8db5..e3ffaaac69 100644 --- a/docs/en/docs/integrations/langgraph.md +++ b/docs/en/docs/integrations/langgraph.md @@ -129,8 +129,9 @@ from the Scope API rather than inventing it locally. ## Recall query -`PowerContextRecall` sends the latest human message, trimmed. A message longer than 8,192 characters or 8,192 UTF-8 -bytes recalls from its most recent text, cut to the last 8,192 characters and then to the last 8,192 bytes. +`PowerContextRecall` sends the latest human message, trimmed, with recognized credentials replaced by `[REDACTED]` as +described in [automatic prompt privacy](index.md#automatic-prompt-privacy). A message longer than 8,192 characters or +8,192 UTF-8 bytes recalls from its most recent text, cut to the last 8,192 characters and then to the last 8,192 bytes. ## Treat recalled context as untrusted history diff --git a/docs/en/docs/integrations/pydantic-ai.md b/docs/en/docs/integrations/pydantic-ai.md index 234f2c94a0..802f5b7f5d 100644 --- a/docs/en/docs/integrations/pydantic-ai.md +++ b/docs/en/docs/integrations/pydantic-ai.md @@ -44,9 +44,10 @@ agent = Agent( The capability adds `powercontext_search`, `powercontext_remember`, and `powercontext_context`. It also requests `prepare_context` from the latest textual user prompt and prepends at most one untrusted evidence block per run. A new -run prepares context again even when it starts from the previous run's message history. A prompt longer than 8,192 -characters or 8,192 UTF-8 bytes recalls from its most recent text, cut to the last 8,192 characters and then to the -last 8,192 bytes. +run prepares context again even when it starts from the previous run's message history. The query is the prompt, +trimmed, with recognized credentials replaced by `[REDACTED]` as described in +[automatic prompt privacy](index.md#automatic-prompt-privacy). A prompt longer than 8,192 characters or 8,192 UTF-8 +bytes recalls from its most recent text, cut to the last 8,192 characters and then to the last 8,192 bytes. Use only the toolset when automatic preparation and capture are not wanted: @@ -111,8 +112,9 @@ create Scope IDs. Capture is off by default. Set `POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true` only when sending the initial user text, visible model text and tool calls, and completed tool arguments and results to the configured scope is acceptable. -Thinking/reasoning content is excluded. Events are redacted for credential-like keys and known environment/Codex -credentials, rendered within the configured byte limit, and stored under +Thinking/reasoning content is excluded. A user prompt that contains a recognized credential is not captured; see +[automatic prompt privacy](index.md#automatic-prompt-privacy). Events are redacted for credential-like keys and known +environment/Codex credentials, rendered within the configured byte limit, and stored under `powercontext.pydantic-ai-capture-event/v1`. Every successful Capture advances the run-local Source position. A checkpoint Flush runs after the configured number diff --git a/docs/zh/docs/integrations/hermes.md b/docs/zh/docs/integrations/hermes.md index 9b64c64e2d..5609b0f6ce 100644 --- a/docs/zh/docs/integrations/hermes.md +++ b/docs/zh/docs/integrations/hermes.md @@ -95,15 +95,16 @@ Evaluation trace 包含 prompt 和召回上下文,应保留在本机并按敏 | 事件/入口 | 发送的数据 | 直接接收方 | 默认/触发条件 | 关闭方式 | 关闭后影响 | | --- | --- | --- | --- | --- | --- | -| 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;不做凭据脱敏)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;可能复用预取缓存 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 | -| 完成 turn | 有长度上限且不做 secret 脱敏的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript | PowerContext Server,保存为 Source | `capture_turns=true`;非主 Agent 上下文抑制自动写入 | 输入敏感文本前设置 `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` | 停止该 Source 捕获;召回、压缩前捕获和显式写入仍独立工作 | +| 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;识别到的凭据替换为 `[REDACTED]`)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;可能复用预取缓存 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 | +| 完成 turn | 有长度上限的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript。用户文本含可识别凭据的 turn 整条跳过;助手文本不做检查 | 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 会失败而非报告成功 | | 显式 remember / 内置 Memory mirror | 请求的 Memory 内容或变更,更新携带精确引用 | PowerContext Server | 显式操作,或主上下文中 add/replace/remove 的 `on_memory_write` | 不调用该写入或产生 mirror 的内置操作;没有专用 mirror 开关 | 关闭 turn 捕获不会禁用这些写入 | | Evaluation trace | prompt/query、召回上下文及关联元数据;检测到的 secret 会脱敏 | 本地 JSONL 文件,默认位于 `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`;用 `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` 显式开启 | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | 停止新增 trace,不禁用召回或捕获;已有文件仍是敏感数据 | -召回请求与完成 turn 的 Source 不做凭据脱敏。Evaluation trace 的脱敏不会处理已经发送到 Server 的 query; -压缩前过滤只作用于那条独立的捕获路径。 +召回 query 与完成 turn 捕获遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略):query 中识别到的凭据会被替换, +用户文本含凭据的 turn 不会被捕获。压缩前捕获使用自身规则脱敏检测到的 secret,与该策略相互独立, +能识别的凭据格式也更少。完成 turn 捕获跳过的 turn 仍可能出现在压缩前窗口中,按这些规则脱敏后发送到 Server。 压缩前捕获优先使用宿主提供的规范化 `evidence_messages`,避免把先前压缩摘要再次作为新证据。 provider 声明 checkpoint API v2,必需 checkpoint 未提交时会抛出异常。这描述的是 provider 契约:仓库的 diff --git a/docs/zh/docs/integrations/index.md b/docs/zh/docs/integrations/index.md index 2f8f0c7bcb..ddc2dba32b 100644 --- a/docs/zh/docs/integrations/index.md +++ b/docs/zh/docs/integrations/index.md @@ -63,6 +63,20 @@ powercontext setup | ZCode | `UserPromptSubmit` 文本 | `POWERCONTEXT_ZCODE_CAPTURE_PROMPTS=false` | | Kimi Code(实验性) | `UserPromptSubmit` 中的文本部分 | setup `--no-capture-prompts` | +进程内 Python 适配器在自动路径上使用同样的识别和处理方式,不改变各自的捕获默认值: + +| 适配器 | 自动输入边界 | 受检查的自动捕获 | 捕获默认值 | +| --- | --- | --- | --- | +| Hermes | `prefetch` 和 `queue_prefetch` 的 query | 完成轮次的 Source | 开启;`POWERCONTEXT_HERMES_CAPTURE_TURNS=false` 关闭 | +| LangChain | 最新的人类消息 | 完成轮次的 Source | 关闭;`PowerContextMiddleware(auto_capture=True)` 开启 | +| LangGraph | 最新的人类消息 | 无;LangGraph 只通过显式工具写入 | 不适用 | +| Pydantic AI | 最新的文本 User Prompt | `user_prompt` 事件 | 关闭;`POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true` 开启 | + +这些适配器只检查用户文本。识别到凭据时整轮跳过完成轮次捕获(Hermes、LangChain),或跳过 `user_prompt` 事件 +(Pydantic AI);助手文本不做检查。Pydantic AI 的模型响应和工具事件继续按键名和已知凭据值脱敏,Hermes 的压缩前 +捕获继续使用自身的脱敏规则。当前 Server 凭据指适配器配置的 token,或 Hermes 的 Authorization 值。跳过时在 debug +日志中记录原因 `sensitive_content`,不包含被拒绝的文本。 + 自动捕获前,适配器识别常见凭据赋值(API/access key 和 token、client/private key、secret、password、 passphrase、authorization、cookie)、至少八个 token 字符的 Bearer 值、常见服务商/GitHub/Slack token 形状、包含未闭合情况的私钥块,以及当前 Server 凭据在输入中的精确出现。这是尽力识别:未知格式、混淆或 diff --git a/docs/zh/docs/integrations/langchain.md b/docs/zh/docs/integrations/langchain.md index 5d3e356b2a..b914bfe725 100644 --- a/docs/zh/docs/integrations/langchain.md +++ b/docs/zh/docs/integrations/langchain.md @@ -63,8 +63,9 @@ middleware 本身支持同步 `invoke` 和 `stream`;异步应用应直接使 每个模型步骤中,middleware 都会: 1. 读取最新的人类消息,不修改 state; -2. 使用解析后的 scope 和字节上限调用 `/v1/context/prepare`。query 是去掉首尾空白的该消息;超过 8192 个字符或 - 8192 个 UTF-8 字节的消息改用最近的文本召回,先取末尾 8192 个字符,再截到末尾 8192 字节; +2. 使用解析后的 scope 和字节上限调用 `/v1/context/prepare`。query 是去掉首尾空白的该消息,识别到的凭据按 + [自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)替换为 `[REDACTED]`;超过 8192 个字符或 8192 个 UTF-8 + 字节的消息改用最近的文本召回,先取末尾 8192 个字符,再截到末尾 8192 字节; 3. 向当前 system message 追加一个独立文本块; 4. 文本块以 `PowerContext host-supplied context` 开头,后接 Server 准备的内容; 内容顶部的信任策略把其后的全部内容标为不可信的历史数据。 @@ -85,8 +86,9 @@ middleware = PowerContextMiddleware(auto_capture=True) LangChain 的 `structured_response` 序列化。采集不包含召回 system block、工具输出或中间的 tool-calling 模型消息。 采集结果是 Source 证据,不是推断完成的 Memory entry。配置的 scheduler 或显式 `flush_memory` 操作随后执行标准的 -Source-to-Memory 抽取。这样既保留 lineage,也不会把未经处理的模型输出直接当成已经审核的持久事实。采集内容有长度 -上限,但不保证一定不含 secret;应用必须先执行自己的输入和输出策略,再选择开启。 +Source-to-Memory 抽取。这样既保留 lineage,也不会把未经处理的模型输出直接当成已经审核的持久事实。用户消息含可识别 +凭据的轮次整轮跳过。识别是尽力而为,且不检查回答,因此采集内容不保证一定不含 secret;应用必须先执行自己的输入和 +输出策略,再选择开启。 模型或工具中止运行时,LangChain 不会执行 `after_agent`;因此,没有最终回答的失败运行不会被采集。 diff --git a/docs/zh/docs/integrations/langgraph.md b/docs/zh/docs/integrations/langgraph.md index 5aa43df7ee..0a022db945 100644 --- a/docs/zh/docs/integrations/langgraph.md +++ b/docs/zh/docs/integrations/langgraph.md @@ -120,8 +120,9 @@ Scope ID 是由 Server 拥有的不透明标识符。适配器绝不会从进程 ## 召回 query -`PowerContextRecall` 发送去掉首尾空白的最新人类消息。超过 8192 个字符或 8192 个 UTF-8 字节的消息改用最近的文本 -召回,先取末尾 8192 个字符,再截到末尾 8192 字节。 +`PowerContextRecall` 发送去掉首尾空白的最新人类消息,识别到的凭据按[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略) +替换为 `[REDACTED]`。超过 8192 个字符或 8192 个 UTF-8 字节的消息改用最近的文本召回,先取末尾 8192 个字符, +再截到末尾 8192 字节。 ## 把召回内容当作不可信历史 diff --git a/docs/zh/docs/integrations/pydantic-ai.md b/docs/zh/docs/integrations/pydantic-ai.md index 41f5a52544..52f91d9db6 100644 --- a/docs/zh/docs/integrations/pydantic-ai.md +++ b/docs/zh/docs/integrations/pydantic-ai.md @@ -43,8 +43,9 @@ agent = Agent( 该 Capability 提供 `powercontext_search`、`powercontext_remember` 和 `powercontext_context`。它还会从最新文本 User Prompt 请求 `prepare_context`,并在一个 run 内最多前置一次不可信证据块。即使新 run 复用旧 message -history,也会重新准备 Context。超过 8192 个字符或 8192 个 UTF-8 字节的 prompt 改用最近的文本召回,先取末尾 -8192 个字符,再截到末尾 8192 字节。 +history,也会重新准备 Context。query 是去掉首尾空白的该 prompt,识别到的凭据按 +[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)替换为 `[REDACTED]`。超过 8192 个字符或 8192 个 UTF-8 字节的 +prompt 改用最近的文本召回,先取末尾 8192 个字符,再截到末尾 8192 字节。 如果只需要工具,不需要自动准备与采集,可以只挂载 Toolset: @@ -106,7 +107,8 @@ Flush 和工具调用中复用 Server 返回的 Scope ID。显式 ID 必须对 ## 决定是否采集事件 Capture 默认关闭。只有在允许把初始用户文本、可见模型文本和工具调用、已完成的工具参数与结果发送到指定 scope -时,才设置 `POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true`。Thinking/reasoning 内容不会采集。事件会清洗敏感键、 +时,才设置 `POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true`。Thinking/reasoning 内容不会采集。含可识别凭据的用户 +prompt 不会采集,见[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)。事件会清洗敏感键、 已知环境凭证和 Codex 凭证,按配置的字节上限渲染,并使用 `powercontext.pydantic-ai-capture-event/v1` schema。 diff --git a/integrations/capabilities.toml b/integrations/capabilities.toml index 29e6920f54..1819589845 100644 --- a/integrations/capabilities.toml +++ b/integrations/capabilities.toml @@ -992,7 +992,7 @@ mode = "unsupported" [integrations.evidence] implementation = ["integrations/hermes/plugins/powercontext/operations.py", "integrations/hermes/plugins/powercontext/commands.py"] documentation = ["docs/en/docs/integrations/hermes.md", "docs/zh/docs/integrations/hermes.md"] -tests = ["tests/integrations/test_hermes_provider.py"] +tests = ["tests/integrations/test_hermes_provider.py", "tests/test_automatic_prompt_privacy.py"] [[integrations]] id = "openclaw" @@ -1083,7 +1083,7 @@ toolsets = ["pydantic-ai-tools"] [integrations.evidence] implementation = ["integrations/pydantic-ai/src/powercontext_pydantic_ai/toolset.py"] documentation = ["docs/en/docs/integrations/pydantic-ai.md", "docs/zh/docs/integrations/pydantic-ai.md"] -tests = ["tests/pydantic_ai_adapter/test_toolset.py"] +tests = ["tests/pydantic_ai_adapter/test_toolset.py", "tests/test_automatic_prompt_privacy.py"] [[integrations]] id = "langchain" @@ -1094,7 +1094,7 @@ toolsets = ["langchain-middleware"] [integrations.evidence] implementation = ["integrations/langchain/src/powercontext_langchain/middleware.py"] documentation = ["docs/en/docs/integrations/langchain.md", "docs/zh/docs/integrations/langchain.md"] -tests = ["tests/langchain_middleware/test_middleware.py"] +tests = ["tests/langchain_middleware/test_middleware.py", "tests/test_automatic_prompt_privacy.py"] [[integrations]] id = "langgraph" @@ -1105,7 +1105,7 @@ toolsets = ["langgraph-tools"] [integrations.evidence] implementation = ["integrations/langgraph/src/powercontext_langgraph/tools.py"] documentation = ["docs/en/docs/integrations/langgraph.md", "docs/zh/docs/integrations/langgraph.md"] -tests = ["tests/langgraph_adapter/test_tools.py"] +tests = ["tests/langgraph_adapter/test_tools.py", "tests/test_automatic_prompt_privacy.py"] [[integrations]] id = "bub" diff --git a/integrations/hermes/plugins/powercontext/prompt_privacy.py b/integrations/hermes/plugins/powercontext/prompt_privacy.py new file mode 100644 index 0000000000..0ebed59b33 --- /dev/null +++ b/integrations/hermes/plugins/powercontext/prompt_privacy.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated from src/powercontext_integration_lifecycle/prompt_privacy.py; do not edit. +# Edit the source and run `make integration-lifecycle` instead. + +"""Best-effort credential recognition for automatic host inputs.""" + +from __future__ import annotations + +import re + +_PRIVATE_KEY = re.compile( + r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", + re.IGNORECASE | re.ASCII, +) +_PATTERN = re.compile( + # Headers can contain schemes, multiple cookies, and folded continuation lines. + r"""(? str: + """Replace recognized values in a read-only query; never use this to rewrite a captured event.""" + + if authorization: + _, _, credential = authorization.partition(" ") + if credential: + text = text.replace(credential, "[REDACTED]") + # Remove whole PEM blocks before an earlier assignment/header can consume their BEGIN marker. + return _PATTERN.sub("[REDACTED]", _PRIVATE_KEY.sub("[REDACTED]", text)) diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index aa79550d1c..04e8824d87 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -98,6 +98,7 @@ resolve_allow_insecure_http, ) from .prepared_context import bounded_recall_query as _bounded_recall_query +from .prompt_privacy import scrub_secrets as _scrub_secrets try: from agent.memory_provider import MemoryProvider, RecallStatus # ty: ignore[unresolved-import] @@ -129,14 +130,15 @@ } -def _automatic_recall_query(prompt: str) -> str: +def _automatic_recall_query(prompt: str, authorization: str | None) -> str: """Return the query an automatic recall sends, or an empty query that skips the recall. - A prompt holding unpaired surrogates, such as a file name decoded with ``surrogateescape``, has no UTF-8 form, so - no request can carry it. Skipping the recall keeps that failure out of the Hermes turn. + Recognized credentials are scrubbed before the query is bounded. A prompt holding unpaired surrogates, such as a + file name decoded with ``surrogateescape``, has no UTF-8 form, so no request can carry it. Skipping the recall + keeps that failure out of the Hermes turn. """ try: - return _bounded_recall_query(prompt) + return _bounded_recall_query(_scrub_secrets(prompt, authorization)) except UnicodeEncodeError: logger.debug("Skipping PowerContext automatic recall: the query is not valid UTF-8 text") return "" @@ -839,7 +841,7 @@ def _prepared_content(response: dict[str, Any], options: dict[str, Any]) -> str: def prefetch(self, query: str, *, session_id: str = "") -> str: scope_id = self._scope_id client = self._client - recall_query = _automatic_recall_query(query) + recall_query = _automatic_recall_query(query, getattr(client, "authorization", None)) if not client or not recall_query or not scope_id: self._last_recall = None self._last_recall_scope_id = "" @@ -874,14 +876,15 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: self._last_recall_scope_id = "" return "" if self._trace_enabled: - # Redacting the whole prompt costs time in proportion to its length, so it runs only for a recorded trace. + authorization = getattr(client, "authorization", None) + # The trace keeps the plugin's own redaction on top of the shared rule, so it redacts at least what it did + # before the shared rule applied. The whole prompt is redacted before it is bounded, so a cut cannot leave + # a bare credential behind. self._record_trace_event( "powercontext_injection", session_id=session_key, - # Redact the whole prompt before bounding it: a cut inside ``api_key=`` would leave a bare value - # that redaction no longer recognizes. - query=_automatic_recall_query(_redact_secrets(query)), - injected_text=_redact_secrets(content.strip()), + query=_automatic_recall_query(_redact_secrets(query), authorization), + injected_text=_scrub_secrets(_redact_secrets(content.strip()), authorization), status=trace_status, content_bytes=len(content.encode("utf-8")), ) @@ -898,7 +901,7 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: def queue_prefetch(self, query: str, *, session_id: str = "") -> None: scope_id = self._scope_id client = self._client - recall_query = _automatic_recall_query(query) + recall_query = _automatic_recall_query(query, getattr(client, "authorization", None)) if not client or not scope_id or not recall_query: return session_key = session_id or self._session_id @@ -957,6 +960,10 @@ def sync_turn( assistant_content = _message_text(assistant_content) if not user_content and not assistant_content: return + if _scrub_secrets(user_content, getattr(self._client, "authorization", None)) != user_content: + # A recognized credential skips the whole turn; a redacted copy would be stored under the turn's identity. + logger.debug("Skipping PowerContext turn capture: sensitive_content") + return effective_session = session_id or self._session_id scope_id = self._scope_id projected = f"[user]\n{user_content}\n\n[assistant]\n{assistant_content}" diff --git a/integrations/langchain/src/powercontext_langchain/_prompt_privacy.py b/integrations/langchain/src/powercontext_langchain/_prompt_privacy.py new file mode 100644 index 0000000000..0ebed59b33 --- /dev/null +++ b/integrations/langchain/src/powercontext_langchain/_prompt_privacy.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated from src/powercontext_integration_lifecycle/prompt_privacy.py; do not edit. +# Edit the source and run `make integration-lifecycle` instead. + +"""Best-effort credential recognition for automatic host inputs.""" + +from __future__ import annotations + +import re + +_PRIVATE_KEY = re.compile( + r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", + re.IGNORECASE | re.ASCII, +) +_PATTERN = re.compile( + # Headers can contain schemes, multiple cookies, and folded continuation lines. + r"""(? str: + """Replace recognized values in a read-only query; never use this to rewrite a captured event.""" + + if authorization: + _, _, credential = authorization.partition(" ") + if credential: + text = text.replace(credential, "[REDACTED]") + # Remove whole PEM blocks before an earlier assignment/header can consume their BEGIN marker. + return _PATTERN.sub("[REDACTED]", _PRIVATE_KEY.sub("[REDACTED]", text)) diff --git a/integrations/langchain/src/powercontext_langchain/middleware.py b/integrations/langchain/src/powercontext_langchain/middleware.py index 453e33ea72..8f3e1ded64 100644 --- a/integrations/langchain/src/powercontext_langchain/middleware.py +++ b/integrations/langchain/src/powercontext_langchain/middleware.py @@ -31,6 +31,7 @@ from powercontext.http import CaptureContentSourceRequest, PrepareContextRequest, PreparedContext, PreparedContextStatus from ._prepared_context import bounded_recall_query +from ._prompt_privacy import scrub_secrets from .client import open_client, resolve_config, resolve_server_scope from .scope import PowerContextScope from .tracing import genai_client_context, recall_content_observation @@ -130,8 +131,8 @@ async def aafter_agent( async def _prepare(self, prompt: str, scope: PowerContextScope | None) -> str | None: try: - query = bounded_recall_query(prompt) config = resolve_config(scope) + query = bounded_recall_query(scrub_secrets(prompt, _authorization(config.token))) with ( recall_content_observation(query, enabled=self.trace_content) as record_output, genai_client_context(), @@ -176,6 +177,10 @@ async def _capture( ) -> None: try: config = resolve_config(scope) + if scrub_secrets(user_text, _authorization(config.token)) != user_text: + # A recognized credential skips the whole turn rather than storing a redacted copy of it. + _LOGGER.debug("PowerContext LangChain capture skipped: sensitive_content.") + return content, metadata = _source_content(user_text, assistant_text) with genai_client_context(): async with open_client(config) as client: @@ -226,6 +231,10 @@ def _log_client_failure(self, operation: str, exc: ClientError) -> None: _LOGGER.debug("PowerContext LangChain %s skipped after %s.", operation, type(exc).__name__) +def _authorization(token: str | None) -> str | None: + return f"Bearer {token}" if token else None + + def _runtime_scope(runtime: Any | None) -> PowerContextScope | None: context = None if runtime is None else runtime.context return context if isinstance(context, PowerContextScope) else None diff --git a/integrations/langgraph/src/powercontext_langgraph/_prompt_privacy.py b/integrations/langgraph/src/powercontext_langgraph/_prompt_privacy.py new file mode 100644 index 0000000000..0ebed59b33 --- /dev/null +++ b/integrations/langgraph/src/powercontext_langgraph/_prompt_privacy.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated from src/powercontext_integration_lifecycle/prompt_privacy.py; do not edit. +# Edit the source and run `make integration-lifecycle` instead. + +"""Best-effort credential recognition for automatic host inputs.""" + +from __future__ import annotations + +import re + +_PRIVATE_KEY = re.compile( + r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", + re.IGNORECASE | re.ASCII, +) +_PATTERN = re.compile( + # Headers can contain schemes, multiple cookies, and folded continuation lines. + r"""(? str: + """Replace recognized values in a read-only query; never use this to rewrite a captured event.""" + + if authorization: + _, _, credential = authorization.partition(" ") + if credential: + text = text.replace(credential, "[REDACTED]") + # Remove whole PEM blocks before an earlier assignment/header can consume their BEGIN marker. + return _PATTERN.sub("[REDACTED]", _PRIVATE_KEY.sub("[REDACTED]", text)) diff --git a/integrations/langgraph/src/powercontext_langgraph/recall.py b/integrations/langgraph/src/powercontext_langgraph/recall.py index 9bf67783bf..ada4d32c7d 100644 --- a/integrations/langgraph/src/powercontext_langgraph/recall.py +++ b/integrations/langgraph/src/powercontext_langgraph/recall.py @@ -28,6 +28,7 @@ from powercontext.http import PrepareContextRequest, PreparedContextStatus from ._prepared_context import bounded_recall_query +from ._prompt_privacy import scrub_secrets from .client import ResolvedConfig, open_client, resolve_config, resolve_server_scope from .runtime import current_scope @@ -120,9 +121,12 @@ async def _prepare(self, config: ResolvedConfig, messages: list[BaseMessage], qu return self._turn_cache[key] request = PrepareContextRequest( scope_id=scope_id, - # ``PrepareContextRequest.query`` has a public length limit that a human turn can exceed. The - # query keeps the end of a long turn so recall stays best-effort instead of failing validation. - query=bounded_recall_query(query), + # Recognized credentials never leave as part of the query. ``PrepareContextRequest.query`` also + # has a public length limit that a human turn can exceed; the query keeps the end of a long turn + # so recall stays best-effort instead of failing validation. + query=bounded_recall_query( + scrub_secrets(query, f"Bearer {config.token}" if config.token else None) + ), max_bytes=config.max_bytes, **({"assembly": config.context_assembly} if config.context_assembly is not None else {}), ) diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/_prompt_privacy.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/_prompt_privacy.py new file mode 100644 index 0000000000..0ebed59b33 --- /dev/null +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/_prompt_privacy.py @@ -0,0 +1,50 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated from src/powercontext_integration_lifecycle/prompt_privacy.py; do not edit. +# Edit the source and run `make integration-lifecycle` instead. + +"""Best-effort credential recognition for automatic host inputs.""" + +from __future__ import annotations + +import re + +_PRIVATE_KEY = re.compile( + r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", + re.IGNORECASE | re.ASCII, +) +_PATTERN = re.compile( + # Headers can contain schemes, multiple cookies, and folded continuation lines. + r"""(? str: + """Replace recognized values in a read-only query; never use this to rewrite a captured event.""" + + if authorization: + _, _, credential = authorization.partition(" ") + if credential: + text = text.replace(credential, "[REDACTED]") + # Remove whole PEM blocks before an earlier assignment/header can consume their BEGIN marker. + return _PATTERN.sub("[REDACTED]", _PRIVATE_KEY.sub("[REDACTED]", text)) diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py index db23b19905..b959d61779 100644 --- a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py @@ -41,6 +41,7 @@ from powercontext.client.capture import render_capture_event from powercontext.http import CaptureContentSourceRequest, FlushMemoryRequest, PrepareContextRequest, PreparedContext from powercontext_pydantic_ai._prepared_context import bounded_recall_query +from powercontext_pydantic_ai._prompt_privacy import scrub_secrets from powercontext_pydantic_ai.scope import ScopeId from powercontext_pydantic_ai.settings import PowerContextSettings from powercontext_pydantic_ai.toolset import ( @@ -126,7 +127,11 @@ async def before_model_request( prompt_text = _content_text(ctx.prompt) or query if prompt_text: state.prompt_captured = True - await self._capture_event(ctx, "user_prompt", {"text": prompt_text}) + if scrub_secrets(prompt_text, self._authorization()) != prompt_text: + # A recognized credential skips the event rather than storing a redacted copy of the prompt. + logger.debug("PowerContext event capture skipped: sensitive_content") + else: + await self._capture_event(ctx, "user_prompt", {"text": prompt_text}) if state.context_injected or _has_current_run_context(request_context.messages, ctx.run_id): state.context_injected = True @@ -227,7 +232,7 @@ async def after_run( async def _prepare_context(self, prompt: str) -> str | None: state = self._require_state() try: - query = bounded_recall_query(prompt) + query = bounded_recall_query(scrub_secrets(prompt, self._authorization())) except UnicodeEncodeError: # Unpaired surrogates, such as a file name decoded with ``surrogateescape``, have no UTF-8 form to send. logger.debug("PowerContext context preparation skipped: the query is not valid UTF-8 text") @@ -352,6 +357,10 @@ async def _flush_locked(self, *, final: bool) -> None: ) return + def _authorization(self) -> str | None: + token = self.settings.token + return f"Bearer {token.get_secret_value()}" if token is not None else None + def _require_state(self) -> _RunState: if self._state is None: raise RuntimeError("PowerContext capability must be bound with for_run before use") # noqa: TRY003 diff --git a/pyproject.toml b/pyproject.toml index 72580a57c7..caa88720b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -303,11 +303,11 @@ fix = true # fix that it applies to a copy makes the copy drift. "src/powercontext_integration_lifecycle/**/*.py" = "py39" "integrations/codex/plugins/powercontext/powercontext_lifecycle/**/*.py" = "py39" -"integrations/hermes/plugins/powercontext/{powercontext_client_config,prepared_context}.py" = "py39" +"integrations/hermes/plugins/powercontext/{powercontext_client_config,prepared_context,prompt_privacy}.py" = "py39" "integrations/workbuddy/plugins/powercontext/hooks/{powercontext_client_config,prepared_context,prompt_privacy}.py" = "py39" -"integrations/langchain/src/powercontext_langchain/_prepared_context.py" = "py39" -"integrations/langgraph/src/powercontext_langgraph/_prepared_context.py" = "py39" -"integrations/pydantic-ai/src/powercontext_pydantic_ai/_prepared_context.py" = "py39" +"integrations/langchain/src/powercontext_langchain/{_prepared_context,_prompt_privacy}.py" = "py39" +"integrations/langgraph/src/powercontext_langgraph/{_prepared_context,_prompt_privacy}.py" = "py39" +"integrations/pydantic-ai/src/powercontext_pydantic_ai/{_prepared_context,_prompt_privacy}.py" = "py39" [tool.ruff.lint] select = [ diff --git a/scripts/generate_integration_lifecycle.py b/scripts/generate_integration_lifecycle.py index 1f67815811..dd2f3d6176 100644 --- a/scripts/generate_integration_lifecycle.py +++ b/scripts/generate_integration_lifecycle.py @@ -60,7 +60,13 @@ f"{_LANGGRAPH}/_prepared_context.py", f"{_PYDANTIC_AI}/_prepared_context.py", ), - "prompt_privacy.py": (f"{_WORKBUDDY}/hooks/prompt_privacy.py",), + "prompt_privacy.py": ( + f"{_HERMES}/prompt_privacy.py", + f"{_WORKBUDDY}/hooks/prompt_privacy.py", + f"{_LANGCHAIN}/_prompt_privacy.py", + f"{_LANGGRAPH}/_prompt_privacy.py", + f"{_PYDANTIC_AI}/_prompt_privacy.py", + ), } # Each copy sits at the path its plugin imports. TYPESCRIPT_COPIES = { diff --git a/tests/integrations/test_hermes_provider.py b/tests/integrations/test_hermes_provider.py index 560db2fe0a..bbeff546bf 100644 --- a/tests/integrations/test_hermes_provider.py +++ b/tests/integrations/test_hermes_provider.py @@ -269,7 +269,8 @@ def test_evaluation_trace_redacts_a_credential_the_query_bound_cuts_through(tmp_ client_factory=lambda _config: client, ) provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") - # The query keeps the last 8,192 characters, so the cut drops ``api_key=`` and leaves the bare value. + # The query keeps the last 8,192 characters, so bounding before scrubbing would drop ``api_key=`` and leave the + # bare value. prompt = ("api_key=synthetic-value-2084 " + "filler " * 3000)[:8200] provider.prefetch(prompt) @@ -282,12 +283,33 @@ def test_evaluation_trace_redacts_a_credential_the_query_bound_cuts_through(tmp_ for line in path.read_text(encoding="utf-8").splitlines() ] injections = [event for event in events if event["event_type"] == "powercontext_injection"] - assert client.calls[0][1][1].startswith("synthetic-value-2084 ") + assert len(client.calls) == 1 + assert "synthetic-value-2084" not in client.calls[0][1][1] assert len(injections) == 1 assert prompt.endswith(injections[0]["query"][-100:]) assert "synthetic-value-2084" not in json.dumps(events) +def test_evaluation_trace_keeps_the_plugin_redaction_for_hyphenated_keys(tmp_path, hermes_modules): + provider_module, _cli_module = hermes_modules + client = FakeClient() + provider = provider_module.PowerContextMemoryProvider( + {"evaluation_trace": True}, + client_factory=lambda _config: client, + ) + provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") + + # The shared rule does not recognize a key name after a hyphen; the plugin's evaluation-trace redaction does. + provider.prefetch("Connect with db-password=synthetic-hunter-2084 and X-Api-Key: synthetic-header-2084") + provider.shutdown() + + trace_dir = tmp_path / "powercontext" / "evaluation-trace" + trace = "".join(path.read_text(encoding="utf-8") for path in (trace_dir / "sessions").glob("*.jsonl")) + assert "powercontext_injection" in trace + assert "synthetic-hunter-2084" not in trace + assert "synthetic-header-2084" not in trace + + def test_evaluation_trace_slash_command_reads_named_session(tmp_path, hermes_modules): provider_module, _cli_module = hermes_modules provider = provider_module.PowerContextMemoryProvider( diff --git a/tests/test_automatic_prompt_privacy.py b/tests/test_automatic_prompt_privacy.py index c2eb4d7995..b628b7decd 100644 --- a/tests/test_automatic_prompt_privacy.py +++ b/tests/test_automatic_prompt_privacy.py @@ -12,11 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Automatic hooks must not capture recognized credentials or forward them as queries.""" +"""Automatic hooks and in-process adapters must not capture recognized credentials or forward them as queries.""" from __future__ import annotations import json +import logging import os import shutil import subprocess @@ -27,6 +28,8 @@ import pytest +from tests.inprocess_adapter_turns import ADAPTERS, run_turn + ROOT = Path(__file__).resolve().parents[1] CASES = json.loads((ROOT / "tests/fixtures/automatic_prompt_privacy.json").read_text(encoding="utf-8"))["cases"] HOOKS = { @@ -145,3 +148,37 @@ def log_message(self, format, *_args): # noqa: A002 - BaseHTTPRequestHandler ov assert len(captures) == 1 assert captures[0]["content"] == case["prompt"] assert prepares[0]["query"] == case["prompt"] + + +@pytest.mark.parametrize("case", CASES, ids=[case["id"] for case in CASES]) +@pytest.mark.parametrize("adapter", ADAPTERS) +def test_inprocess_adapter_skips_credentials_without_disabling_recall( + adapter: str, + case: dict[str, object], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, +) -> None: + prompt = str(case["prompt"]) + token = str(case["authorization"]).removeprefix("Bearer ") if "authorization" in case else None + with caplog.at_level(logging.DEBUG): + turn = run_turn(adapter, prompt, monkeypatch=monkeypatch, home=tmp_path, token=token, capture=True) + + # Recall runs either way; the adapter reports the recalled context to its model (checked by run_turn). + assert len(turn.queries) == 1 + sent = json.dumps(turn.requests) + if case["sensitive"]: + assert "synthetic-value-2084" not in sent + assert "synthetic_value_2084" not in sent + assert "synthetic-value-2084" not in caplog.text + assert "synthetic_value_2084" not in caplog.text + if adapter in {"hermes", "langchain"}: # The completed turn is skipped as a whole. + assert turn.captures == [] + if adapter == "pydantic-ai": # Only the user_prompt event is skipped. + assert not any('"event": "user_prompt"' in content for content in turn.captures) + if adapter != "langgraph": # LangGraph has no automatic capture to skip. + assert "sensitive_content" in caplog.text + else: + assert turn.queries == [prompt] + if adapter != "langgraph": + assert any(prompt in content or json.dumps(prompt)[1:-1] in content for content in turn.captures) From b07d2754b068d47128fe1d060f6033e725d518bb Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Wed, 18 Nov 2026 13:32:49 -0500 Subject: [PATCH 2/4] fix(hermes): apply the shared credential rule before the plugin rule in evaluation traces The plugin's assignment pattern consumes a scheme word or the start of a private-key block, so running it first left values such as the token in `Authorization: Bearer ` that the shared rule no longer recognized. The trace now applies the shared rule first, then the plugin rule, to both the query and the injected text. --- .../hermes/plugins/powercontext/provider.py | 34 ++++++++++---- tests/integrations/test_hermes_provider.py | 46 +++++++++++++++++-- 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index 04e8824d87..7fcf7d84f6 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -133,17 +133,35 @@ def _automatic_recall_query(prompt: str, authorization: str | None) -> str: """Return the query an automatic recall sends, or an empty query that skips the recall. - Recognized credentials are scrubbed before the query is bounded. A prompt holding unpaired surrogates, such as a - file name decoded with ``surrogateescape``, has no UTF-8 form, so no request can carry it. Skipping the recall - keeps that failure out of the Hermes turn. + Recognized credentials are scrubbed before the query is bounded, so a cut cannot leave a bare credential behind. + """ + return _recall_query_tail(_scrub_secrets(prompt, authorization)) + + +def _recall_query_tail(text: str) -> str: + """Bound a redacted query, or return an empty query when it has no UTF-8 form. + + A prompt holding unpaired surrogates, such as a file name decoded with ``surrogateescape``, cannot be carried by + any request. Skipping the recall keeps that failure out of the Hermes turn. """ try: - return _bounded_recall_query(_scrub_secrets(prompt, authorization)) + return _bounded_recall_query(text) except UnicodeEncodeError: logger.debug("Skipping PowerContext automatic recall: the query is not valid UTF-8 text") return "" +def _trace_redaction(text: str, authorization: str | None) -> str: + """Redact evaluation-trace text with the shared rule and then the plugin's own rule. + + The trace redacts everything the recall query redacts, and the plugin's rule then redacts what it still recognizes. + The shared rule must run first: the plugin's assignment pattern consumes a scheme word or the start of a + private-key block (``Authorization: Bearer X`` becomes ``[REDACTED] X``), and the shared rule no longer recognizes + what is left. + """ + return _redact_secrets(_scrub_secrets(text, authorization)) + + def _precompress_content_for_entries( entries: list[tuple[str, dict[str, Any]]], *, @@ -877,14 +895,12 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: return "" if self._trace_enabled: authorization = getattr(client, "authorization", None) - # The trace keeps the plugin's own redaction on top of the shared rule, so it redacts at least what it did - # before the shared rule applied. The whole prompt is redacted before it is bounded, so a cut cannot leave - # a bare credential behind. + # The whole prompt is redacted before it is bounded, so a cut cannot leave a bare credential behind. self._record_trace_event( "powercontext_injection", session_id=session_key, - query=_automatic_recall_query(_redact_secrets(query), authorization), - injected_text=_scrub_secrets(_redact_secrets(content.strip()), authorization), + query=_recall_query_tail(_trace_redaction(query, authorization)), + injected_text=_trace_redaction(content.strip(), authorization), status=trace_status, content_bytes=len(content.encode("utf-8")), ) diff --git a/tests/integrations/test_hermes_provider.py b/tests/integrations/test_hermes_provider.py index bbeff546bf..b312760201 100644 --- a/tests/integrations/test_hermes_provider.py +++ b/tests/integrations/test_hermes_provider.py @@ -290,7 +290,7 @@ def test_evaluation_trace_redacts_a_credential_the_query_bound_cuts_through(tmp_ assert "synthetic-value-2084" not in json.dumps(events) -def test_evaluation_trace_keeps_the_plugin_redaction_for_hyphenated_keys(tmp_path, hermes_modules): +def test_evaluation_trace_keeps_the_plugin_redaction(tmp_path, hermes_modules): provider_module, _cli_module = hermes_modules client = FakeClient() provider = provider_module.PowerContextMemoryProvider( @@ -299,17 +299,55 @@ def test_evaluation_trace_keeps_the_plugin_redaction_for_hyphenated_keys(tmp_pat ) provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") - # The shared rule does not recognize a key name after a hyphen; the plugin's evaluation-trace redaction does. - provider.prefetch("Connect with db-password=synthetic-hunter-2084 and X-Api-Key: synthetic-header-2084") + # The plugin's own rule accepts a key name after a hyphen and takes its value from the next line; the shared rule + # does not recognize this value. + provider.prefetch("X-Api-Key:\nsynthetic-header-2084") provider.shutdown() trace_dir = tmp_path / "powercontext" / "evaluation-trace" trace = "".join(path.read_text(encoding="utf-8") for path in (trace_dir / "sessions").glob("*.jsonl")) assert "powercontext_injection" in trace - assert "synthetic-hunter-2084" not in trace assert "synthetic-header-2084" not in trace +PROMPT_PRIVACY_CASES = json.loads( + (Path(__file__).resolve().parents[2] / "tests/fixtures/automatic_prompt_privacy.json").read_text(encoding="utf-8") +)["cases"] + + +@pytest.mark.parametrize( + "case", + [case for case in PROMPT_PRIVACY_CASES if case["sensitive"]], + ids=[case["id"] for case in PROMPT_PRIVACY_CASES if case["sensitive"]], +) +def test_evaluation_trace_redacts_every_credential_the_recall_query_redacts(tmp_path, hermes_modules, case): + provider_module, _cli_module = hermes_modules + + class EchoingClient(FakeClient): + authorization = case.get("authorization") + + def prepare_context(self, scope_id, query, *, max_bytes): + super().prepare_context(scope_id, query, max_bytes=max_bytes) + # Recalled content can repeat a credential stored before this policy applied. + return {"status": "ready", "content": f"Remembered: {case['prompt']}"} + + client = EchoingClient() + provider = provider_module.PowerContextMemoryProvider( + {"evaluation_trace": True}, + client_factory=lambda _config: client, + ) + provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") + + provider.prefetch(case["prompt"]) + provider.shutdown() + + trace_dir = tmp_path / "powercontext" / "evaluation-trace" + trace = "".join(path.read_text(encoding="utf-8") for path in (trace_dir / "sessions").glob("*.jsonl")) + assert "powercontext_injection" in trace + assert "synthetic-value-2084" not in trace + assert "synthetic_value_2084" not in trace + + def test_evaluation_trace_slash_command_reads_named_session(tmp_path, hermes_modules): provider_module, _cli_module = hermes_modules provider = provider_module.PowerContextMemoryProvider( From 83aa8fabd877630123361cf607a9e4918dc5459d Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Wed, 18 Nov 2026 13:34:43 -0500 Subject: [PATCH 3/4] fix(integrations): skip Hermes and LangChain turn capture when the reply contains a credential The completed-turn Source stores the user text and the assistant reply, but only the user text was checked, so a reply that echoed a configuration file was captured with its credential. Both sides are now checked, and the debug log names the side that contained the credential. --- docs/en/docs/integrations/hermes.md | 4 +-- docs/en/docs/integrations/index.md | 11 +++--- docs/en/docs/integrations/langchain.md | 7 ++-- docs/zh/docs/integrations/hermes.md | 4 +-- docs/zh/docs/integrations/index.md | 9 ++--- docs/zh/docs/integrations/langchain.md | 6 ++-- .../hermes/plugins/powercontext/provider.py | 11 +++--- .../src/powercontext_langchain/middleware.py | 10 +++--- tests/inprocess_adapter_turns.py | 35 ++++++++++++------- tests/test_automatic_prompt_privacy.py | 30 ++++++++++++++++ 10 files changed, 87 insertions(+), 40 deletions(-) diff --git a/docs/en/docs/integrations/hermes.md b/docs/en/docs/integrations/hermes.md index 2b3717a9a6..ea9d493827 100644 --- a/docs/en/docs/integrations/hermes.md +++ b/docs/en/docs/integrations/hermes.md @@ -100,14 +100,14 @@ 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; recognized credentials replaced with `[REDACTED]`), 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 | -| Completed turn | Bounded user/assistant text pair, plus session metadata; not the complete tool transcript. A turn whose user text contains a recognized credential is skipped as a whole; assistant text is not checked | 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 | +| Completed turn | Bounded user/assistant text pair, plus session metadata; not the complete tool transcript. A turn whose user or assistant text contains a recognized credential is skipped as a whole | 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 | | Explicit remember / built-in memory mirror | Requested Memory content or change, with exact references for updates | PowerContext Server | Explicit operation, or primary-context `on_memory_write` for add/replace/remove | Do not invoke the write or mirror-producing built-in operation; no dedicated mirror switch | Turning off turn capture does not disable these writes | | Evaluation trace | Prompt/query, recalled context and correlation metadata; detected secrets are redacted | Local JSONL files, by default under `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`; opt in with `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | Stops new trace records without disabling recall or capture; existing files remain sensitive | Recall queries and completed-turn capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) -policy: recognized credentials are replaced in the query, and a turn whose user text contains one is not captured. +policy: recognized credentials are replaced in the query, and a turn whose user or assistant text contains one is not captured. Pre-compression capture redacts detected secrets with its own rules, which are separate from that policy and recognize fewer credential formats. A turn that completed-turn capture skips can still reach the Server, redacted by those rules, in a pre-compression window. diff --git a/docs/en/docs/integrations/index.md b/docs/en/docs/integrations/index.md index 0fb7b35c3f..96efa83412 100644 --- a/docs/en/docs/integrations/index.md +++ b/docs/en/docs/integrations/index.md @@ -78,11 +78,12 @@ their capture defaults: | LangGraph | Latest human message | None; LangGraph captures only through explicit tools | Not applicable | | Pydantic AI | Latest textual user prompt | `user_prompt` event | Off; `POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true` | -These adapters check the user text only. A recognized credential skips the whole completed turn (Hermes, LangChain) -or the `user_prompt` event (Pydantic AI); assistant text is not checked. Pydantic AI model-response and tool events keep -their key-based and known-credential redaction, and Hermes pre-compression capture keeps its own redaction. The -configured Server credential is the adapter's token, or Hermes's Authorization value. A skip is logged at debug level -with the reason `sensitive_content` and without the rejected text. +A recognized credential in the user text or the assistant reply skips the whole completed turn (Hermes, LangChain), +because the turn Source stores both; a recognized credential in the user prompt skips the `user_prompt` event +(Pydantic AI). Pydantic AI model-response and tool events keep their key-based and known-credential redaction, and +Hermes pre-compression capture keeps its own redaction. The configured Server credential is the adapter's token, or +Hermes's Authorization value. A skip is logged at debug level with the reason `sensitive_content` and without the +rejected text; a completed-turn skip also names the side, user or assistant, that contained the credential. Before automatic capture, these adapters recognize conventional credential assignments (API/access keys and tokens, client/private keys, secrets, passwords, passphrases, authorization and cookies), Bearer values diff --git a/docs/en/docs/integrations/langchain.md b/docs/en/docs/integrations/langchain.md index 2ac517d5a1..f8c220bb86 100644 --- a/docs/en/docs/integrations/langchain.md +++ b/docs/en/docs/integrations/langchain.md @@ -92,10 +92,9 @@ not store the recalled system block, tool outputs, or intermediate tool-calling Capture creates Source evidence, not an inferred Memory entry. The configured scheduler or an explicit `flush_memory` operation performs the normal Source-to-Memory extraction later. This keeps lineage intact and avoids -treating raw model output as an already reviewed durable fact. A turn whose user message contains a recognized -credential is skipped as a whole. Detection is best effort and the assistant response is not checked, so captured -content is not guaranteed to be free of secrets; applications must apply their own input and output policy before -opting in. +treating raw model output as an already reviewed durable fact. A turn whose user message or assistant response +contains a recognized credential is skipped as a whole. Detection is best effort, so captured content is not +guaranteed to be free of secrets; applications must apply their own input and output policy before opting in. LangChain does not run `after_agent` when a model or tool aborts the run, so a failed run without a final response is not captured. diff --git a/docs/zh/docs/integrations/hermes.md b/docs/zh/docs/integrations/hermes.md index 5609b0f6ce..42822b7dd8 100644 --- a/docs/zh/docs/integrations/hermes.md +++ b/docs/zh/docs/integrations/hermes.md @@ -96,14 +96,14 @@ Evaluation trace 包含 prompt 和召回上下文,应保留在本机并按敏 | 事件/入口 | 发送的数据 | 直接接收方 | 默认/触发条件 | 关闭方式 | 关闭后影响 | | --- | --- | --- | --- | --- | --- | | 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;识别到的凭据替换为 `[REDACTED]`)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;可能复用预取缓存 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 | -| 完成 turn | 有长度上限的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript。用户文本含可识别凭据的 turn 整条跳过;助手文本不做检查 | PowerContext Server,保存为 Source | `capture_turns=true`;非主 Agent 上下文抑制自动写入 | 输入敏感文本前设置 `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` | 停止该 Source 捕获;召回、压缩前捕获和显式写入仍独立工作 | +| 完成 turn | 有长度上限的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript。用户或助手文本含可识别凭据的 turn 整条跳过 | 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 会失败而非报告成功 | | 显式 remember / 内置 Memory mirror | 请求的 Memory 内容或变更,更新携带精确引用 | PowerContext Server | 显式操作,或主上下文中 add/replace/remove 的 `on_memory_write` | 不调用该写入或产生 mirror 的内置操作;没有专用 mirror 开关 | 关闭 turn 捕获不会禁用这些写入 | | Evaluation trace | prompt/query、召回上下文及关联元数据;检测到的 secret 会脱敏 | 本地 JSONL 文件,默认位于 `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`;用 `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` 显式开启 | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | 停止新增 trace,不禁用召回或捕获;已有文件仍是敏感数据 | 召回 query 与完成 turn 捕获遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略):query 中识别到的凭据会被替换, -用户文本含凭据的 turn 不会被捕获。压缩前捕获使用自身规则脱敏检测到的 secret,与该策略相互独立, +用户或助手文本含凭据的 turn 不会被捕获。压缩前捕获使用自身规则脱敏检测到的 secret,与该策略相互独立, 能识别的凭据格式也更少。完成 turn 捕获跳过的 turn 仍可能出现在压缩前窗口中,按这些规则脱敏后发送到 Server。 压缩前捕获优先使用宿主提供的规范化 `evidence_messages`,避免把先前压缩摘要再次作为新证据。 diff --git a/docs/zh/docs/integrations/index.md b/docs/zh/docs/integrations/index.md index ddc2dba32b..f80793a475 100644 --- a/docs/zh/docs/integrations/index.md +++ b/docs/zh/docs/integrations/index.md @@ -72,10 +72,11 @@ powercontext setup | LangGraph | 最新的人类消息 | 无;LangGraph 只通过显式工具写入 | 不适用 | | Pydantic AI | 最新的文本 User Prompt | `user_prompt` 事件 | 关闭;`POWERCONTEXT_PYDANTIC_AI_CAPTURE_EVENTS=true` 开启 | -这些适配器只检查用户文本。识别到凭据时整轮跳过完成轮次捕获(Hermes、LangChain),或跳过 `user_prompt` 事件 -(Pydantic AI);助手文本不做检查。Pydantic AI 的模型响应和工具事件继续按键名和已知凭据值脱敏,Hermes 的压缩前 -捕获继续使用自身的脱敏规则。当前 Server 凭据指适配器配置的 token,或 Hermes 的 Authorization 值。跳过时在 debug -日志中记录原因 `sensitive_content`,不包含被拒绝的文本。 +用户文本或助手回复中识别到凭据时,整轮跳过完成轮次捕获(Hermes、LangChain),因为轮次 Source 同时保存两者; +User Prompt 中识别到凭据时跳过 `user_prompt` 事件(Pydantic AI)。Pydantic AI 的模型响应和工具事件继续按键名和 +已知凭据值脱敏,Hermes 的压缩前捕获继续使用自身的脱敏规则。当前 Server 凭据指适配器配置的 token,或 Hermes 的 +Authorization 值。跳过时在 debug 日志中记录原因 `sensitive_content`,不包含被拒绝的文本;完成轮次的跳过还注明 +凭据所在的一侧(用户或助手)。 自动捕获前,适配器识别常见凭据赋值(API/access key 和 token、client/private key、secret、password、 passphrase、authorization、cookie)、至少八个 token 字符的 Bearer 值、常见服务商/GitHub/Slack token diff --git a/docs/zh/docs/integrations/langchain.md b/docs/zh/docs/integrations/langchain.md index b914bfe725..e004e9ce8d 100644 --- a/docs/zh/docs/integrations/langchain.md +++ b/docs/zh/docs/integrations/langchain.md @@ -86,9 +86,9 @@ middleware = PowerContextMiddleware(auto_capture=True) LangChain 的 `structured_response` 序列化。采集不包含召回 system block、工具输出或中间的 tool-calling 模型消息。 采集结果是 Source 证据,不是推断完成的 Memory entry。配置的 scheduler 或显式 `flush_memory` 操作随后执行标准的 -Source-to-Memory 抽取。这样既保留 lineage,也不会把未经处理的模型输出直接当成已经审核的持久事实。用户消息含可识别 -凭据的轮次整轮跳过。识别是尽力而为,且不检查回答,因此采集内容不保证一定不含 secret;应用必须先执行自己的输入和 -输出策略,再选择开启。 +Source-to-Memory 抽取。这样既保留 lineage,也不会把未经处理的模型输出直接当成已经审核的持久事实。用户消息或助手回答含可识别 +凭据的轮次整轮跳过。识别是尽力而为,因此采集内容不保证一定不含 secret;应用必须先执行自己的输入和输出策略, +再选择开启。 模型或工具中止运行时,LangChain 不会执行 `after_agent`;因此,没有最终回答的失败运行不会被采集。 diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index 7fcf7d84f6..cd35bec800 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -976,10 +976,13 @@ def sync_turn( assistant_content = _message_text(assistant_content) if not user_content and not assistant_content: return - if _scrub_secrets(user_content, getattr(self._client, "authorization", None)) != user_content: - # A recognized credential skips the whole turn; a redacted copy would be stored under the turn's identity. - logger.debug("Skipping PowerContext turn capture: sensitive_content") - return + authorization = getattr(self._client, "authorization", None) + for side, text in (("user", user_content), ("assistant", assistant_content)): + if _scrub_secrets(text, authorization) != text: + # A recognized credential on either side skips the whole turn; a redacted copy would be stored under + # the turn's identity. + logger.debug("Skipping PowerContext turn capture: sensitive_content in the %s text", side) + return effective_session = session_id or self._session_id scope_id = self._scope_id projected = f"[user]\n{user_content}\n\n[assistant]\n{assistant_content}" diff --git a/integrations/langchain/src/powercontext_langchain/middleware.py b/integrations/langchain/src/powercontext_langchain/middleware.py index 8f3e1ded64..fa86b24e2d 100644 --- a/integrations/langchain/src/powercontext_langchain/middleware.py +++ b/integrations/langchain/src/powercontext_langchain/middleware.py @@ -177,10 +177,12 @@ async def _capture( ) -> None: try: config = resolve_config(scope) - if scrub_secrets(user_text, _authorization(config.token)) != user_text: - # A recognized credential skips the whole turn rather than storing a redacted copy of it. - _LOGGER.debug("PowerContext LangChain capture skipped: sensitive_content.") - return + authorization = _authorization(config.token) + for side, text in (("user", user_text), ("assistant", assistant_text)): + if scrub_secrets(text, authorization) != text: + # A recognized credential on either side skips the whole turn rather than storing a redacted copy. + _LOGGER.debug("PowerContext LangChain capture skipped: sensitive_content in the %s text.", side) + return content, metadata = _source_content(user_text, assistant_text) with genai_client_context(): async with open_client(config) as client: diff --git a/tests/inprocess_adapter_turns.py b/tests/inprocess_adapter_turns.py index e3bc56a9eb..16081b5b4d 100644 --- a/tests/inprocess_adapter_turns.py +++ b/tests/inprocess_adapter_turns.py @@ -154,7 +154,9 @@ def log_message(self, format: str, *_args: object) -> None: # noqa: A002 - Base server.server_close() -def _hermes(url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None) -> bool: +def _hermes( + url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None, answer: str +) -> bool: 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)) @@ -171,7 +173,7 @@ def _hermes(url: str, prompt: str, *, token: str | None, capture: bool, home: Pa 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") + provider.sync_turn(prompt, answer, session_id="session-1") finally: provider.shutdown() return recalled @@ -182,7 +184,7 @@ def _hermes(url: str, prompt: str, *, token: str | None, capture: bool, home: Pa sys.modules.update(previous) -def _chat_model() -> Any: +def _chat_model(answer: str) -> Any: from langchain_core.language_models import BaseChatModel from langchain_core.messages import AIMessage from langchain_core.outputs import ChatGeneration, ChatResult @@ -193,7 +195,7 @@ class Model(BaseChatModel): def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResult: # type: ignore[no-untyped-def] self.inputs.append(list(messages)) - return ChatResult(generations=[ChatGeneration(message=AIMessage(content=ANSWER))]) + return ChatResult(generations=[ChatGeneration(message=AIMessage(content=answer))]) @property def _llm_type(self) -> str: @@ -206,13 +208,15 @@ def _system_texts(messages: list[Any]) -> str: return "\n".join(message.text for message in messages if message.type == "system") -def _langchain(url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None) -> bool: +def _langchain( + url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None, answer: str +) -> bool: del home from langchain.agents import create_agent from langchain_core.messages import HumanMessage from powercontext_langchain import PowerContextMiddleware, PowerContextScope - model = _chat_model() + model = _chat_model(answer) agent = create_agent( model, tools=[], @@ -228,13 +232,15 @@ def _langchain(url: str, prompt: str, *, token: str | None, capture: bool, home: return RECALLED in _system_texts(model.inputs[-1]) -def _langgraph(url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None) -> bool: +def _langgraph( + url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None, answer: str +) -> bool: del capture, home, entry # The LangGraph adapter captures only through explicit tools. from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent # ty: ignore[deprecated] from powercontext_langgraph import PowerContextRecall, PowerContextScope - model = _chat_model() + model = _chat_model(answer) # The adapter documents create_react_agent's pre_model_hook, which langchain.agents.create_agent does not offer. agent: Any = create_react_agent( # ty: ignore[deprecated] model, tools=[], pre_model_hook=PowerContextRecall(), context_schema=PowerContextScope @@ -247,7 +253,9 @@ def _langgraph(url: str, prompt: str, *, token: str | None, capture: bool, home: return RECALLED in _system_texts(model.inputs[-1]) -def _pydantic_ai(url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None) -> bool: +def _pydantic_ai( + url: str, prompt: str, *, token: str | None, capture: bool, home: Path, entry: str | None, answer: str +) -> bool: del home, entry from powercontext_pydantic_ai import PowerContext, PowerContextSettings from pydantic import SecretStr @@ -263,7 +271,7 @@ async def respond(messages: list[Any], _info: Any) -> ModelResponse: seen.extend( part.content for message in messages for part in message.parts if isinstance(part, SystemPromptPart) ) - return ModelResponse(parts=[TextPart(ANSWER)]) + return ModelResponse(parts=[TextPart(answer)]) secret = None if token is None else SecretStr(token) settings = PowerContextSettings(base_url=url, token=secret, capture_events=capture) @@ -291,11 +299,12 @@ def run_turn( capture: bool = False, entry: str | None = None, expect_recall: bool = True, + answer: str = ANSWER, ) -> Turn: """Submit ``prompt`` as one user turn and return what the adapter sent to the Server. ``entry`` names one of the adapter's ``ENTRIES``; the default is its first. Unless ``expect_recall`` is false, the - recalled context must have reached the model. + recalled context must have reached the model. ``answer`` is the model's reply. """ if adapter != "hermes": @@ -305,7 +314,9 @@ def run_turn( monkeypatch.delenv(name) turn = Turn() with _recording_server(turn) as url: - turn.recalled = _RUNNERS[adapter](url, prompt, token=token, capture=capture, home=home, entry=entry) + turn.recalled = _RUNNERS[adapter]( + url, prompt, token=token, capture=capture, home=home, entry=entry, answer=answer + ) if expect_recall: assert turn.recalled, "the recalled context did not reach the model" return turn diff --git a/tests/test_automatic_prompt_privacy.py b/tests/test_automatic_prompt_privacy.py index b628b7decd..5b22a18820 100644 --- a/tests/test_automatic_prompt_privacy.py +++ b/tests/test_automatic_prompt_privacy.py @@ -182,3 +182,33 @@ def test_inprocess_adapter_skips_credentials_without_disabling_recall( assert turn.queries == [prompt] if adapter != "langgraph": assert any(prompt in content or json.dumps(prompt)[1:-1] in content for content in turn.captures) + + +@pytest.mark.parametrize("case", [case for case in CASES if case["sensitive"]], ids=lambda case: case["id"]) +@pytest.mark.parametrize("adapter", ["hermes", "langchain"]) +def test_inprocess_turn_capture_skips_a_credential_only_in_the_assistant_reply( + adapter: str, + case: dict[str, object], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, +) -> None: + # The completed-turn Source stores the reply too, for example a reply that echoes a configuration file. + token = str(case["authorization"]).removeprefix("Bearer ") if "authorization" in case else None + with caplog.at_level(logging.DEBUG): + turn = run_turn( + adapter, + "Show me the deployment settings.", + monkeypatch=monkeypatch, + home=tmp_path, + token=token, + capture=True, + answer=str(case["prompt"]), + ) + + assert turn.queries == ["Show me the deployment settings."] + assert turn.captures == [] + sent = json.dumps(turn.requests) + assert "synthetic-value-2084" not in sent + assert "synthetic_value_2084" not in sent + assert "sensitive_content in the assistant text" in caplog.text From 256e46455b33e68a5daa1787f8b187b9ad5e5d6e Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Fri, 20 Nov 2026 13:34:37 -0500 Subject: [PATCH 4/4] test(integrations): check every fixture value marker in the in-process privacy tests The fixture's stripe-token case carries only the SyntheticValue2084 marker, so the in-process and Hermes trace value checks, which looked for two markers, asserted nothing for it. The plugin-redaction trace test's comment now names the one difference left between the two rules: a value on the unindented next line. --- tests/integrations/test_hermes_provider.py | 8 ++++---- tests/test_automatic_prompt_privacy.py | 13 +++++++------ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/integrations/test_hermes_provider.py b/tests/integrations/test_hermes_provider.py index b312760201..5eb37992a8 100644 --- a/tests/integrations/test_hermes_provider.py +++ b/tests/integrations/test_hermes_provider.py @@ -299,8 +299,8 @@ def test_evaluation_trace_keeps_the_plugin_redaction(tmp_path, hermes_modules): ) provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") - # The plugin's own rule accepts a key name after a hyphen and takes its value from the next line; the shared rule - # does not recognize this value. + # The plugin's own rule takes a value from the unindented next line; the shared rule keeps a value on its line and + # does not recognize this one. provider.prefetch("X-Api-Key:\nsynthetic-header-2084") provider.shutdown() @@ -344,8 +344,8 @@ def prepare_context(self, scope_id, query, *, max_bytes): trace_dir = tmp_path / "powercontext" / "evaluation-trace" trace = "".join(path.read_text(encoding="utf-8") for path in (trace_dir / "sessions").glob("*.jsonl")) assert "powercontext_injection" in trace - assert "synthetic-value-2084" not in trace - assert "synthetic_value_2084" not in trace + for marker in ("synthetic-value-2084", "synthetic_value_2084", "SyntheticValue2084"): + assert marker not in trace def test_evaluation_trace_slash_command_reads_named_session(tmp_path, hermes_modules): diff --git a/tests/test_automatic_prompt_privacy.py b/tests/test_automatic_prompt_privacy.py index bd0522b6cf..0d7f6d883c 100644 --- a/tests/test_automatic_prompt_privacy.py +++ b/tests/test_automatic_prompt_privacy.py @@ -32,6 +32,8 @@ ROOT = Path(__file__).resolve().parents[1] CASES = json.loads((ROOT / "tests/fixtures/automatic_prompt_privacy.json").read_text(encoding="utf-8"))["cases"] +# Every synthetic credential value in the fixture contains one of these markers. +VALUE_MARKERS = ("synthetic-value-2084", "synthetic_value_2084", "SyntheticValue2084") HOOKS = { "claude": "claude-code/plugins/powercontext/hooks/user_prompt_submit.py", "codex": "codex/plugins/powercontext/hooks/recall.py", @@ -167,10 +169,9 @@ def test_inprocess_adapter_skips_credentials_without_disabling_recall( assert len(turn.queries) == 1 sent = json.dumps(turn.requests) if case["sensitive"]: - assert "synthetic-value-2084" not in sent - assert "synthetic_value_2084" not in sent - assert "synthetic-value-2084" not in caplog.text - assert "synthetic_value_2084" not in caplog.text + for marker in VALUE_MARKERS: + assert marker not in sent + assert marker not in caplog.text if adapter in {"hermes", "langchain"}: # The completed turn is skipped as a whole. assert turn.captures == [] if adapter == "pydantic-ai": # Only the user_prompt event is skipped. @@ -208,6 +209,6 @@ def test_inprocess_turn_capture_skips_a_credential_only_in_the_assistant_reply( assert turn.queries == ["Show me the deployment settings."] assert turn.captures == [] sent = json.dumps(turn.requests) - assert "synthetic-value-2084" not in sent - assert "synthetic_value_2084" not in sent + for marker in VALUE_MARKERS: + assert marker not in sent assert "sensitive_content in the assistant text" in caplog.text