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
7 changes: 7 additions & 0 deletions docs/en/docs/integrations/evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ The Bub plugin connects to the Server through the Python Client and provides Mem
preparation, including context before model calls. Event capture is disabled by default. When enabled, completed
events become Sources and can be flushed periodically. No Handoff capability is declared.

Automatic recall and capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) rule. The
recall query is the user's text with recognized credentials replaced by `[REDACTED]`; the replacement happens before
the query is trimmed and, when longer than 8,192 characters or 8,192 UTF-8 bytes, cut to its most recent text. With
event capture on, an initial task that contains a recognized credential is not captured as a `user_prompt` event; the
optional capture log records the skip with the reason `sensitive_content` and without the text. LLM and tool events
keep their key-based and known-credential redaction.

Loopback HTTP is allowed by default. Non-loopback HTTP requires `POWERCONTEXT_BUB_ALLOW_INSECURE_HTTP=true` or
`PowerContextSettings(allow_insecure_http=True)`, covering both plugin hooks and tools. HTTPS certificate validation
stays enabled. See [Connect to a remote Server](../operate/connect-remote-server.md) for shared client settings;
Expand Down
7 changes: 7 additions & 0 deletions docs/zh/docs/integrations/evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ Bub 插件通过 Python Client 连接 Server,提供 Memory 搜索、写入和
模型调用前可准备上下文。事件采集默认关闭,启用后可将已完成的事件作为 Sources,并定期 flush。
它没有 Handoff 能力声明。

自动召回和采集遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)。
召回查询是用户文本:先将识别出的凭据替换为 `[REDACTED]`,
再去除首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时,截取最近的文本。
启用事件采集时,含有识别出的凭据的初始任务不会作为 `user_prompt` 事件采集;
可选的采集日志记录这次跳过,原因为 `sensitive_content`,不含文本。
LLM 和工具事件仍按敏感键和已知凭据清洗。

环回 HTTP 默认可用;非环回 HTTP 需要设置 `POWERCONTEXT_BUB_ALLOW_INSECURE_HTTP=true`,或传入
`PowerContextSettings(allow_insecure_http=True)`,对插件 Hook 和工具调用都生效。HTTPS 证书校验仍然启用。
共享客户端配置见[连接远程 Server](../operate/connect-remote-server.md);Bub 没有 PowerContext setup 安装命令。
Expand Down
1 change: 1 addition & 0 deletions e2e/bub/src/powercontext_e2e/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ class CaptureRecord(EvidenceModel):
source_id: str | None = None
source_position: int | None = None
error: str | None = None
reason: str | None = None
final: bool | None = None
target_position: int | None = None
previous_cursor: int | None = None
Expand Down
162 changes: 162 additions & 0 deletions e2e/bub/tests/test_bub_prompt_privacy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# 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.

"""Bub's automatic recall and capture keep recognized credentials out, like the other automatic adapters."""

from __future__ import annotations

import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any, ClassVar

import httpx2
import pytest
from bub.channels.message import ChannelMessage
from bub.framework import BubFramework
from powercontext_bub import plugin as plugin_module
from powercontext_bub.plugin import PowerContextPlugin, PowerContextSettings
from pydantic import SecretStr

from powercontext_e2e.models import CaptureRecord

_ROOT = Path(__file__).resolve().parents[3]
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")
ANSWER = "Noted."


class RecordingClient:
prepared: ClassVar[list[Any]] = []
captured: ClassVar[list[Any]] = []

def __init__(self, base_url: str, **options: object) -> None:
del base_url, options

async def __aenter__(self) -> RecordingClient:
return self

async def __aexit__(self, *exc_info: object) -> None:
del exc_info

async def resolve_scope_binding(self, request: Any) -> SimpleNamespace:
del request
return SimpleNamespace(scope_id="scp_00000000000000000000000000")

async def prepare_context(self, request: Any) -> SimpleNamespace:
self.prepared.append(request)
return SimpleNamespace(content="remembered context", content_bytes=18, status=SimpleNamespace(value="ready"))

async def capture_content_source(self, request: Any) -> SimpleNamespace:
self.captured.append(request)
return SimpleNamespace(position=len(self.captured))

async def flush_memory(self, request: Any) -> SimpleNamespace:
del request
position = len(self.captured)
return SimpleNamespace(
status=SimpleNamespace(value="completed"),
previous_cursor=0,
current_cursor=position,
high_watermark=position,
processed_source_count=position,
remaining_work=False,
)


def _token(case: dict[str, Any]) -> SecretStr | None:
authorization = case.get("authorization")
return None if authorization is None else SecretStr(str(authorization).removeprefix("Bearer "))


def _run_turn(monkeypatch, tmp_path: Path, prompt: str, *, token: SecretStr | None) -> list[dict[str, Any]]:
"""Run one message through Bub's own turn with a stub model and return the capture log's records."""
RecordingClient.prepared.clear()
RecordingClient.captured.clear()
capture_log = tmp_path / "capture.jsonl"
settings = PowerContextSettings(
base_url="http://127.0.0.1:8000",
api_token=token,
capture_events=True,
capture_checkpoint_every=100,
capture_log=capture_log,
)
monkeypatch.setattr(plugin_module, "ensure_config", lambda _: settings)
monkeypatch.setattr(plugin_module, "PowerContextClient", RecordingClient)

def model_reply(request: httpx2.Request) -> httpx2.Response:
del request
events = [{"choices": [{"delta": {"content": ANSWER}, "finish_reason": "stop"}]}, "[DONE]"]
body = "".join(f"data: {event if isinstance(event, str) else json.dumps(event)}\n\n" for event in events)
return httpx2.Response(200, headers={"content-type": "text/event-stream"}, text=body)

client = httpx2.AsyncClient
monkeypatch.setattr(
httpx2, "AsyncClient", lambda **options: client(**{"transport": httpx2.MockTransport(model_reply), **options})
)
for name, value in {
"BUB_HOME": str(tmp_path / "home"),
"BUB_MODEL": "openai:test-model",
"BUB_API_KEY": "stub-model-credential",
"BUB_CLIENT_ARGS": '{"api_format": "chat"}',
# Keep the known-credential redaction of captured events to this test's own environment.
"CODEX_HOME": str(tmp_path / "codex"),
}.items():
monkeypatch.setenv(name, value)
monkeypatch.chdir(tmp_path)
framework = BubFramework(config_file=tmp_path / "bub.yml")
framework.load_builtin_hooks()
framework.plugin_manager.register(PowerContextPlugin(framework), name="powercontext")
message = ChannelMessage(
session_id="cli:local", channel="cli", chat_id="local", content=prompt, context={"sender_id": "human"}
)

async def turn() -> None:
async with framework.running():
await framework.process_inbound(message)

asyncio.run(turn())
return [json.loads(line) for line in capture_log.read_text(encoding="utf-8").splitlines()]


@pytest.mark.parametrize("case", CASES, ids=[case["id"] for case in CASES])
def test_turn_keeps_recognized_credentials_out_of_recall_and_capture(
monkeypatch, tmp_path: Path, case: dict[str, Any]
) -> None:
prompt = str(case["prompt"])

records = _run_turn(monkeypatch, tmp_path, prompt, token=_token(case))
# The harness reads the same capture log as run evidence.
for record in records:
CaptureRecord.model_validate(record)

# Recall runs either way.
assert len(RecordingClient.prepared) == 1
events = [captured.metadata["event"] for captured in RecordingClient.captured]
sent = json.dumps([RecordingClient.prepared[0].query, *(captured.content for captured in RecordingClient.captured)])
log = json.dumps(records)
if case["sensitive"]:
for marker in VALUE_MARKERS:
assert marker not in sent
assert marker not in log
# The initial task is not stored as a redacted copy; the model's reply is still captured.
assert events == ["llm_result"]
skip = {"event": "user_prompt", "status": "skipped", "reason": "sensitive_content"}
assert skip.items() <= records[0].items()
else:
assert RecordingClient.prepared[0].query == prompt.strip()
assert events == ["user_prompt", "llm_result"]
assert json.dumps(prompt)[1:-1] in RecordingClient.captured[0].content
9 changes: 9 additions & 0 deletions integrations/bub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ to resolve the configured explicit Scope first, then an opaque stable binding ke
and finally the Server default. Only the real Scope returned by the Server is cached and used for recall, capture, and
tools.

The recall query is the user's text, trimmed, with recognized credentials, such as `api_key=…` assignments, Bearer
values, and common provider tokens, replaced by `[REDACTED]`. When a prompt longer than 8,192 characters or 8,192
UTF-8 bytes is cut to its most recent text, the replacement happens first, so the cut cannot leave a bare credential.
With capture enabled, an initial task that contains a recognized credential is not captured; the capture log records
a `user_prompt` event with status `skipped` and reason `sensitive_content`, without the text. Bub applies the same
recognition as the other automatic PowerContext integrations, described in the
[automatic prompt privacy](../../docs/en/docs/integrations/index.md#automatic-prompt-privacy) guide. Recognition is
best effort.

Captured tool arguments redact values under credential-like keys. Known credential environment values are also
removed from serialized event content. Keep the PowerContext scope and optional capture log protected because normal
tool output can still contain sensitive project data.
Expand Down
73 changes: 73 additions & 0 deletions integrations/bub/src/powercontext_bub/_prompt_privacy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# 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

# Horizontal space, spelled out so that Python's ASCII \s and JavaScript's Unicode \s agree: NBSP and the full-width
# space that Chinese input methods produce separate a value just as a space does.
_SPACES = r" \t\f\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
# A value starts on the separator's line or on an indented continuation line, as in YAML, so an empty .env value
# cannot reach into the next line.
_GAP = rf"[{_SPACES}]*(?:\r?\n[{_SPACES}]+)?"
# A boolean or null literal or an unexpanded ${NAME} or ${{ expression }} placeholder is a setting, not a credential.
# A placeholder with a literal default, such as ${NAME:-value}, is not excluded.
_PLACEHOLDER = r"(?:\$\{\{[^{}\r\n]*\}\}|\$\{[A-Za-z_][A-Za-z0-9_]*\})"
_SETTING = rf"""(?:true|false|yes|no|on|off|null|none|{_PLACEHOLDER}|"{_PLACEHOLDER}"|'{_PLACEHOLDER}')"""
_NOT_A_SETTING = rf"""(?!{_GAP}{_SETTING}(?:[\s,;)\]}}`'"{_SPACES}]|\.(?![^\s{_SPACES}])|$))"""
# A header value is a setting only when nothing more of the header follows it: the line ends, optionally after closing
# punctuation, and the next line is not an indented continuation. Anything else, as in Cookie: on; sid=…,
# Cookie: ${THEME} sid=…, or a setting followed by an indented line, keeps the whole header.
_NOT_A_HEADER_SETTING = rf"""(?![ \t]*{_SETTING}[`")'\]}}]*[,.;]?[{_SPACES}]*(?:$|\r?\n(?![ \t])))"""
# Applied in order, like the TypeScript source, so an earlier rule consumes the whole of what a later one would cut.
_PATTERNS = tuple(
re.compile(pattern, re.IGNORECASE | re.ASCII)
for pattern in (
r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)",
# Headers can contain schemes, multiple cookies, and folded continuation lines. A hyphenated prefix such as
# Proxy-, Set-, or X-Forwarded-, or the CGI form HTTP_, names another header of the same kind.
r"""(?<![\w-])["']?(?:HTTP(?:_[A-Za-z0-9]+)*_|(?:[A-Za-z0-9]+-)*)(?:authorization|cookie)\b["'`*]*"""
rf"[ \t]*[:=]\**{_NOT_A_HEADER_SETTING}[ \t]*[^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*",
# A key name may carry any prefix, as in OPENAI_API_KEY, X-Api-Key, --password, or dbPassword, but must end
# with the marker, so max_tokens and password_min_length stay ordinary. Markdown emphasis or code around
# the name, as in **Password:** or `DB_PASSWORD`:, is part of it. Tokenizer special tokens such as pad_token
# are configuration. A scheme word belongs to the value that follows it.
r"""(?<![\w-])["']?(?!(?:bos|eos|pad|unk|sep|cls|mask)_token\b)[\w-]*?(?:api[_ -]?key"""
r"""|access[_ -]?(?:key(?:[_-]id)?|token)|client[_ -]?secret|secret(?:[_ -]?key)?|private[_ -]?key|password"""
rf"""|passwd|passphrase|token|authorization|cookie)\b["'`*]*[\s{_SPACES}]*[:=]\**{_NOT_A_SETTING}{_GAP}"""
rf"""(?:(?:bearer|basic)[{_SPACES}]+)?(?:"[^"\r\n]*"|'[^'\r\n]*'|`[^`\r\n]*`|[^\s,;}}\]{_SPACES}]+)""",
rf"(?<![\w-])bearer[\s{_SPACES}]+[A-Za-z0-9._~+/=-]{{8,}}(?![\w-])",
r"(?<![\w-])(?:sk-[A-Za-z0-9][A-Za-z0-9_-]{7,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{8,}"
r"|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,})(?![\w-])",
)
)


def scrub_secrets(text: str, authorization: str | None = None) -> 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]")
# The private-key rule runs first, so a header or assignment cannot consume just a PEM block's BEGIN marker.
for pattern in _PATTERNS:
text = pattern.sub("[REDACTED]", text)
return text
24 changes: 17 additions & 7 deletions integrations/bub/src/powercontext_bub/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
# Older core releases support legacy recall but cannot accept assembly settings.
from types import NoneType as ContextAssembly

from ._prompt_privacy import scrub_secrets
from .scope import resolve_scope_id, workspace_binding_key

STATE_KEY = "_powercontext"
Expand Down Expand Up @@ -232,12 +233,16 @@ async def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LL
capture_state = state[STATE_KEY]
if self.settings.capture_events and not capture_state["prompt_captured"]:
capture_state["prompt_captured"] = True
await self._capture_event(
event="user_prompt",
run_id=request.run_id,
payload={"text": prompt},
state=state,
)
if scrub_secrets(prompt, self._authorization()) != prompt:
# A recognized credential skips the event rather than storing a redacted copy of the prompt.
self._write_capture_record(event="user_prompt", status="skipped", reason="sensitive_content")
Comment thread
PsiACE marked this conversation as resolved.
Resolved
else:
await self._capture_event(
event="user_prompt",
run_id=request.run_id,
payload={"text": prompt},
state=state,
)

if any(_contains_context_marker(message) for message in request.messages):
return None
Expand Down Expand Up @@ -295,6 +300,10 @@ async def save_state(self, session_id: str, state: TurnState, message: Any, mode
async with self._capture_lock:
await self._flush_captured_sources(state, final=True)

def _authorization(self) -> str | None:
token = self.settings.api_token
return None if token is None else f"Bearer {token.get_secret_value()}"

def _client(self) -> AbstractAsyncContextManager[PowerContextClient]:
return open_client(
self.base_url,
Expand Down Expand Up @@ -338,7 +347,8 @@ async def _scope_id(self, state: TurnState) -> str | None:

async def _prepare_context(self, query: str, scope_id: str, state: TurnState) -> str | None:
try:
bounded_query = _bounded_recall_query(query)
# Scrubbing first means a cut cannot leave a bare credential behind.
bounded_query = _bounded_recall_query(scrub_secrets(query, self._authorization()))
except UnicodeEncodeError as exc:
# Unpaired surrogates, such as a file name decoded with ``surrogateescape``, have no UTF-8 form to send.
self._write_capture_record(
Expand Down
2 changes: 1 addition & 1 deletion integrations/capabilities.toml
Original file line number Diff line number Diff line change
Expand Up @@ -1140,7 +1140,7 @@ toolsets = ["bub-tools", "bub-lifecycle"]
[integrations.evidence]
implementation = ["integrations/bub/src/powercontext_bub/tools.py", "integrations/bub/src/powercontext_bub/plugin.py"]
documentation = ["integrations/bub/README.md"]
tests = ["e2e/bub/tests/test_workload_catalog.py", "tests/e2e/test_bub_service_chain.py"]
tests = ["e2e/bub/tests/test_workload_catalog.py", "e2e/bub/tests/test_bub_prompt_privacy.py", "tests/e2e/test_bub_service_chain.py"]

[[integrations]]
id = "dify"
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ 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/bub/src/powercontext_bub/_prompt_privacy.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,_prompt_privacy}.py" = "py39"
Expand Down
Loading
Loading