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
1 change: 1 addition & 0 deletions docs/en/docs/integrations/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ when updating a plugin; this policy adds credential checks without changing capt
| WorkBuddy | Submitted joined prompt text | `POWERCONTEXT_WORKBUDDY_CAPTURE_PROMPTS=false` |
| OpenCode | User text parts, excluding synthetic parts | `POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=false` |
| Pi | `before_agent_start` prompt | `POWERCONTEXT_PI_CAPTURE_PROMPTS=false` |
| OpenClaw | Latest user text at `agent_end` and `before_compaction` | plugin config `autoCapture=false` |
| ZCode | `UserPromptSubmit` text | `POWERCONTEXT_ZCODE_CAPTURE_PROMPTS=false` |
| Kimi Code (experimental) | Text parts of `UserPromptSubmit` | setup `--no-capture-prompts` |

Expand Down
17 changes: 11 additions & 6 deletions docs/en/docs/integrations/openclaw.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,24 @@ both default to `true` and operate independently; restart the gateway after conf

| Event/entry | Data sent | Direct recipient | Default/trigger | Disable | Effect when disabled |
| --- | --- | --- | --- | --- | --- |
| `before_prompt_build` | Latest user text (or prompt fallback), bounded to 8192 UTF-8 bytes without credential scrubbing, plus Scope and prepare budget | Configured PowerContext Server; returned context enters the host model request | `autoRecall=true`, eligible private session | `autoRecall=false` | Automatic preparation/injection stops; capture and explicit tools remain independent |
| Successful `agent_end` | Latest user text prefixed with `User:`, deterministic Source ID and origin metadata | Configured PowerContext Server | `autoCapture=true`, eligible private session | `autoCapture=false` | New automatic Sources stop; recall and explicit writes remain available |
| `before_prompt_build` | Latest user text (or prompt fallback) with recognized credentials replaced by `[REDACTED]`, bounded to 8192 UTF-8 bytes, plus Scope and prepare budget | Configured PowerContext Server; returned context enters the host model request | `autoRecall=true`, eligible private session | `autoRecall=false` | Automatic preparation/injection stops; capture and explicit tools remain independent |
| Successful `agent_end` | Latest user text prefixed with `User:`, deterministic Source ID and origin metadata; nothing when the text contains a recognized credential | Configured PowerContext Server | `autoCapture=true`, eligible private session | `autoCapture=false` | New automatic Sources stop; recall and explicit writes remain available |
| `before_compaction` | Same bounded latest-user Source when capture is enabled; Scope for bounded flush | Configured PowerContext Server | Best-effort boundary event | `autoCapture=false` disables new capture, not pending flush | Previously accepted positions can still be flushed; compaction is not blocked |
| `session_end` / `gateway_stop` | Scope for flushing already accepted pending positions; no new transcript | Configured PowerContext Server | Pending positions and available extraction | No separate flush-off setting | Turning off capture prevents new Sources, but does not cancel existing pending work |
| Explicit search/get/store/revise/retire | Requested query, reference, or mutation payload | Configured PowerContext Server | Explicit tool execution subject to host controls and access checks | Do not invoke, or restrict the tools in OpenClaw | Automatic recall/capture switches do not disable explicit tools |

Automatic capture excludes group, channel and incognito sessions. `captureMaxChars` defaults to `4000`
(range `128`–`20000`): the latest user text including the `User: ` prefix is **truncated**, not rejected,
using JavaScript string length/slicing. This is not a UTF-8 byte limit or complete transcript synchronization.
Neither automatic recall nor capture performs credential detection or scrubbing, and the plugin has no secret-detection
configuration. Session eligibility and truncation are not secret filtering. To stop these automatic paths from sending
prompt text to the Server, set both `autoCapture=false` and `autoRecall=false`, or exclude the session. Explicit tools
remain independent and can still send their arguments.
Automatic recall and capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) policy.
Recognized credentials are credential assignments such as `api_key=…` or `password: …`, `Authorization` and
`Cookie` headers, bearer and provider tokens, private keys, and the token in the configured `tokenEnv` variable.
The recall query replaces them with `[REDACTED]` before it is bounded, and a latest user text that contains any of
them is not captured; the check reads the whole text before `captureMaxChars` truncation. Ordinary words that only
contain a marker, such as `token budgets`, are not credentials. The rule recognizes common shapes, not every secret.
Session eligibility and truncation are not secret filtering. To stop these automatic paths from sending prompt text
to the Server, set both `autoCapture=false` and `autoRecall=false`, or exclude the session. Explicit tools remain
independent and can still send their arguments.

There are three separate data directions: OpenClaw sends queries, Sources and explicit operations to the configured
Server; enabled Server embedding/reranking/generation may send queries, candidates or evidence to its configured
Expand Down
1 change: 1 addition & 0 deletions docs/zh/docs/integrations/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ powercontext setup
| WorkBuddy | 宿主提交的拼接 prompt 文本 | `POWERCONTEXT_WORKBUDDY_CAPTURE_PROMPTS=false` |
| OpenCode | 用户文本部分,排除 synthetic 部分 | `POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=false` |
| Pi | `before_agent_start` prompt | `POWERCONTEXT_PI_CAPTURE_PROMPTS=false` |
| OpenClaw | `agent_end` 和 `before_compaction` 时的最新用户文本 | 插件配置 `autoCapture=false` |
| ZCode | `UserPromptSubmit` 文本 | `POWERCONTEXT_ZCODE_CAPTURE_PROMPTS=false` |
| Kimi Code(实验性) | `UserPromptSubmit` 中的文本部分 | setup `--no-capture-prompts` |

Expand Down
10 changes: 7 additions & 3 deletions docs/zh/docs/integrations/openclaw.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,19 @@ openclaw

| 事件/入口 | 发送的数据 | 直接接收方 | 默认/触发条件 | 关闭方式 | 关闭后影响 |
| --- | --- | --- | --- | --- | --- |
| `before_prompt_build` | 最新用户文本(或 prompt 回退值),限制为 8192 UTF-8 字节且不做凭据脱敏,以及 Scope 和 prepare 预算 | 配置的 PowerContext Server;返回上下文进入宿主模型请求 | `autoRecall=true`,符合条件的私密会话 | `autoRecall=false` | 停止自动准备/注入;捕获和显式工具仍独立工作 |
| 成功的 `agent_end` | 加上 `User:` 前缀的最新用户文本、确定性 Source ID 和来源元数据 | 配置的 PowerContext Server | `autoCapture=true`,符合条件的私密会话 | `autoCapture=false` | 停止新增自动 Source;召回和显式写入仍可用 |
| `before_prompt_build` | 最新用户文本(或 prompt 回退值),识别出的凭据替换为 `[REDACTED]` 后限制为 8192 UTF-8 字节,以及 Scope 和 prepare 预算 | 配置的 PowerContext Server;返回上下文进入宿主模型请求 | `autoRecall=true`,符合条件的私密会话 | `autoRecall=false` | 停止自动准备/注入;捕获和显式工具仍独立工作 |
| 成功的 `agent_end` | 加上 `User:` 前缀的最新用户文本、确定性 Source ID 和来源元数据;文本含有识别出的凭据时不发送 | 配置的 PowerContext Server | `autoCapture=true`,符合条件的私密会话 | `autoCapture=false` | 停止新增自动 Source;召回和显式写入仍可用 |
| `before_compaction` | 捕获启用时发送同样有界的最新用户 Source;发送 Scope 执行有界 flush | 配置的 PowerContext Server | best-effort 边界事件 | `autoCapture=false` 关闭新增捕获,不关闭 pending flush | 仍可 flush 已接受的 position;不会阻止压缩 |
| `session_end` / `gateway_stop` | 用于 flush 已接受 pending position 的 Scope;不发送新 transcript | 配置的 PowerContext Server | 存在 pending position 且 extraction 可用 | 没有独立的 flush 关闭设置 | 关闭捕获会阻止新增 Source,但不会取消已有 pending 工作 |
| 显式 search/get/store/revise/retire | 请求的 query、引用或修改载荷 | 配置的 PowerContext Server | 显式工具执行,受宿主控制和访问检查约束 | 不调用,或在 OpenClaw 中限制工具 | 自动召回/捕获开关不会关闭显式工具 |

自动捕获排除 group、channel 和 incognito 会话。`captureMaxChars` 默认 `4000`(范围 `128`–`20000`):
包含 `User: ` 前缀的最新用户文本超限时会被**截断**,而不是拒绝,使用 JavaScript 字符串长度和切片。
这不是 UTF-8 字节限制,也不是完整 transcript 同步。自动召回和捕获都不做凭据识别或脱敏,插件也没有 secret 检测配置。
这不是 UTF-8 字节限制,也不是完整 transcript 同步。
自动召回和捕获遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略)。识别的凭据包括 `api_key=…`、`password: …` 等凭据赋值,
`Authorization` 和 `Cookie` 头,bearer 与服务商 token,私钥,以及 `tokenEnv` 所指环境变量中的 token。召回查询在截断前
把它们替换为 `[REDACTED]`;最新用户文本含有其中任一项时不采集,检查针对 `captureMaxChars` 截断前的完整文本。
只是包含标记字样的普通词语(例如 `token budgets`)不算凭据。该规则识别常见形态,不能覆盖所有 secret。
会话资格筛选和截断不是 secret 过滤。要阻止这些自动路径向 Server 发送 prompt 文本,需同时设置
`autoCapture=false` 与 `autoRecall=false`,或排除该会话。显式工具仍独立工作,仍可发送其操作参数。

Expand Down
2 changes: 1 addition & 1 deletion integrations/capabilities.toml
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,7 @@ tests = ["integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.t
[integrations.evidence]
implementation = ["integrations/openclaw/plugins/memory-powercontext/src/tools.ts", "integrations/openclaw/plugins/memory-powercontext/src/lifecycle.ts"]
documentation = ["docs/en/docs/integrations/openclaw.md", "docs/zh/docs/integrations/openclaw.md"]
tests = ["integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts"]
tests = ["integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts", "integrations/openclaw/plugins/memory-powercontext/src/prompt-privacy.test.ts"]

[[integrations]]
id = "opencode"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import type { PowerContextClient } from "./http.js";
import { createDiagnosticEmitter, failureEvent } from "./diagnostics.js";
import { resolvePowerContextScope } from "./scope.js";
import { containsSecret, scrubSecrets } from "./secrets.js";
import { isPowerContextCapabilities, isPreparedContext } from "./types.js";

type LifecycleDependencies = {
Expand Down Expand Up @@ -106,6 +107,11 @@ function scopeCorrelation(scopeId: string): string {
return createHash("sha256").update(scopeId).digest("hex").slice(0, 16);
}

// Fetch trims the Authorization header value, so the Server sees the trimmed token.
function serverToken(config: PowerContextConfig): string | undefined {
return process.env[config.tokenEnv]?.trim() || undefined;
}

export function registerPowerContextLifecycle(api: OpenClawPluginApi, deps: LifecycleDependencies) {
const safeWarn = (message: string) => {
try {
Expand Down Expand Up @@ -337,6 +343,11 @@ export function registerPowerContextLifecycle(api: OpenClawPluginApi, deps: Life
) {
return;
}
// Check the whole latest user text, because truncation can shorten a credential below a recognizable shape.
const text = latestUserText(params.messages);
if (!text || containsSecret(text, serverToken(config))) {
return;
}
const content = captureTranscript(params.messages, config.captureMaxChars);
if (!content) {
return;
Expand Down Expand Up @@ -453,7 +464,7 @@ export function registerPowerContextLifecycle(api: OpenClawPluginApi, deps: Life
});
const prepared = await deps.client.post<unknown>("/v1/context/prepare", {
scope_id: scopeId,
query: truncateUtf8(query, 8192),
query: truncateUtf8(scrubSecrets(query, serverToken(config)), 8192),
max_bytes: config.prepareMaxBytes,
...(config.contextAssembly !== undefined ? { assembly: config.contextAssembly } : {}),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* 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.
*/

import { readFileSync } from "node:fs";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
import { describe, expect, it } from "vitest";
import { resolvePowerContextConfig } from "./config.js";
import type { PowerContextClient } from "./http.js";
import { registerPowerContextLifecycle } from "./lifecycle.js";
import { containsSecret, scrubSecrets } from "./secrets.js";

type PrivacyCase = { id: string; prompt: string; sensitive: boolean; authorization?: string };
type Hook = (event: unknown, context: unknown) => unknown;

const { cases } = JSON.parse(readFileSync(
new URL("../../../../../tests/fixtures/automatic_prompt_privacy.json", import.meta.url),
"utf8",
)) as { cases: PrivacyCase[] };

function expectNoSyntheticSecret(value: string): void {
expect(value).not.toContain("synthetic-value-2084");
expect(value).not.toContain("synthetic_value_2084");
}

describe("shared automatic prompt privacy policy", () => {
it.each(cases)("$id", ({ prompt, sensitive, authorization }) => {
expect(containsSecret(prompt, authorization)).toBe(sensitive);
const query = scrubSecrets(prompt, authorization);
if (sensitive) expectNoSyntheticSecret(query);
else expect(query).toBe(prompt);
});
});

const TOKEN_ENV = "POWERCONTEXT_PRIVACY_TEST_TOKEN";
const CONTEXT = { agentId: "main", sessionId: "session-privacy", sessionKey: "agent:main:direct:user-1" };

function createHarness(options: { captureMaxChars?: number } = {}) {
const config = resolvePowerContextConfig(undefined, {
endpoint: "https://powercontext.test",
tokenEnv: TOKEN_ENV,
...options,
});
const requests: Array<{ path: string; body: Record<string, unknown> }> = [];
const client = {
async get() {
return { memory_extraction: true };
},
async post(path: string, body: Record<string, unknown>) {
requests.push({ path, body });
if (path === "/v1/scope-bindings/resolve") return { scope_id: "scp_privacy" };
if (path === "/v1/sources/content") return { status: "accepted", position: 1 };
return { schema: "powercontext.prepared-context.v1", status: "empty", content: null, content_bytes: 0 };
},
} as unknown as PowerContextClient;
const hooks = new Map<string, Hook>();
registerPowerContextLifecycle({
on: (name: string, handler: Hook) => hooks.set(name, handler),
logger: { warn() {}, debug() {} },
} as unknown as OpenClawPluginApi, {
client,
getConfig: () => config,
isPrivateSession: () => true,
createClosingSignal: () => new AbortController().signal,
});
return {
requests,
hook: (name: string) => hooks.get(name)!,
prepare: () => requests.find(({ path }) => path === "/v1/context/prepare"),
captures: () => requests.filter(({ path }) => path === "/v1/sources/content"),
};
}

async function withServerToken(token: string | undefined, run: () => Promise<void>): Promise<void> {
const previous = process.env[TOKEN_ENV];
if (token === undefined) delete process.env[TOKEN_ENV];
else process.env[TOKEN_ENV] = token;
try {
await run();
} finally {
if (previous === undefined) delete process.env[TOKEN_ENV];
else process.env[TOKEN_ENV] = previous;
}
}

describe("automatic recall and capture", () => {
it.each(cases)("$id", async ({ prompt, sensitive, authorization }) => {
const harness = createHarness();
const messages = [{ role: "user", content: prompt }];
await withServerToken(authorization?.replace(/^Bearer\s+/u, ""), async () => {
await harness.hook("before_prompt_build")({ messages, prompt }, CONTEXT);
await harness.hook("agent_end")({ success: true, runId: "run-privacy", messages }, CONTEXT);
});

expect(harness.prepare()).toBeDefined();
if (sensitive) {
expect(harness.captures()).toEqual([]);
expectNoSyntheticSecret(JSON.stringify(harness.requests));
} else {
expect(harness.prepare()!.body.query).toBe(prompt.trim());
expect(harness.captures()).toHaveLength(1);
expect(harness.captures()[0]!.body.content).toBe(`User: ${prompt.trim()}`);
}
});

it("recognizes the Server token the client sends after trimming the environment value", async () => {
const harness = createHarness();
const messages = [{ role: "user", content: "Use synthetic-value-2084 in the request." }];
await withServerToken(" synthetic-value-2084\n", async () => {
await harness.hook("before_prompt_build")({ messages }, CONTEXT);
await harness.hook("agent_end")({ success: true, runId: "run-token", messages }, CONTEXT);
});

expect(harness.prepare()!.body.query).toBe("Use [REDACTED] in the request.");
expect(harness.captures()).toEqual([]);
});

it("skips a pre-compaction capture whose credential lies beyond the capture truncation", async () => {
const harness = createHarness({ captureMaxChars: 128 });
const messages = [{ role: "user", content: `${"context ".repeat(40)}api_key=synthetic-value-2084` }];
await withServerToken(undefined, async () => {
await harness.hook("before_compaction")({ messages, messageCount: 1, compactingCount: 1 }, CONTEXT);
});

expect(harness.captures()).toEqual([]);
expectNoSyntheticSecret(JSON.stringify(harness.requests));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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.
*/

const SECRET_PATTERNS = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 自动 prompt 隐私规则在 openclaw 侧是手写副本,未进入 scripts/generate_integration_lifecycle.py 的生成链

本文件 17-33 行的规则与 integrations/lifecycle/prompt-privacy.ts(并行 PR #2644 head b91159a4)除 2 行注释外逐字节相同;用仓库自带 fixture tests/fixtures/automatic_prompt_privacy.json 实测 23 个 case 全通过(node 22.22.2 直接类型擦除执行,探针 D:\test\github\review\oceanbase-powercontext-pr-2636\probes\probe_privacy.mjs)。问题不在规则本身,而在副本的登记方式。

证据:

影响:make integration-lifecycle-check 只校验已登记的副本,于是这条规则现在有 4 份实现、只有 3 份受校验。此后修改 integrations/lifecycle/prompt-privacy.ts 时,openclaw 的 secrets.ts 漂移不会被任何门禁发现,而 docs/{en,zh}/docs/integrations/openclaw.md 已改成「自动召回和捕获遵循同一策略」,两份文档会先于代码失真。

建议:把本文件改名为 src/prompt-privacy.ts,在 TYPESCRIPT_COPIES["prompt-privacy.ts"] 追加 {_OPENCLAW}/src/prompt-privacy.ts,lifecycle.ts 改 import 路径。若 openclaw 因打包或加载方式必须保留独立文件名,请在生成器注释中写明这条例外,使后续改动有据可循。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: this rule should be a registered copy. #2644 adds the prompt-privacy.ts entry to TYPESCRIPT_COPIES and has not merged yet, so this PR cannot register against it today. Whichever of #2636 and #2644 merges second will move this rule to src/prompt-privacy.ts, add {_OPENCLAW}/src/prompt-privacy.ts to that entry, and update the import in lifecycle.ts, so make integration-lifecycle-check covers all four copies.

/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/giu,
// Consume complete headers before the assignment rule can consume just a scheme or first cookie.
/(?<![\w-])["']?\b(?:authorization|proxy-authorization|cookie|set-cookie)\b["']?[ \t]*[:=][ \t]*[^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*/giu,
/(?<![\w-])["']?\b(?:api[_ -]?key|access[_ -]?(?:key|token)|client[_ -]?secret|secret(?:[_ -]?key)?|private[_ -]?key|password|passwd|passphrase|token|authorization|cookie)\b["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|`[^`\r\n]*`|[^\s,;}\]]+)/giu,
/(?<![\w-])bearer\s+[A-Za-z0-9._~+/=-]{8,}(?![\w-])/giu,
/(?<![\w-])(?:sk-[A-Za-z0-9][A-Za-z0-9_-]{7,}|github_pat_[A-Za-z0-9_]{8,}|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,})(?![\w-])/giu,
] as const

/** Return text with recognized credential-shaped values replaced. */
export function scrubSecrets(text: string, authorization?: string): string {
const credential = authorization?.replace(/^Bearer\s+/iu, '')
if (credential) text = text.replaceAll(credential, '[REDACTED]')
return SECRET_PATTERNS.reduce((scrubbed, pattern) => scrubbed.replace(pattern, '[REDACTED]'), text)
}

/** Detect secrets without rejecting ordinary words that merely contain a marker. */
export function containsSecret(text: string, authorization?: string): boolean {
return scrubSecrets(text, authorization) !== text
}
Loading