From 1890f5f2bfaf1a1f3b247b3a1e32f534ff985b9b Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Sun, 22 Nov 2026 17:07:54 -0500 Subject: [PATCH] fix(openclaw): recall with the end of a long prompt The automatic recall query kept the first 8192 UTF-8 bytes of the latest user text, so a long prompt lost its end, which usually holds the request. Bound it with the shared recall-query rule instead: trim, keep the longest trailing text within 8192 characters and 8192 bytes without splitting a character, trim again. Credentials are still scrubbed before the bound. --- docs/en/docs/integrations/openclaw.md | 2 +- docs/zh/docs/integrations/openclaw.md | 2 +- .../memory-powercontext/src/content.ts | 23 +++++++++++ .../memory-powercontext/src/lifecycle.test.ts | 21 ++++++++++ .../memory-powercontext/src/lifecycle.ts | 3 +- .../src/recall-query.spec.ts | 39 +++++++++++++++++++ 6 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 integrations/openclaw/plugins/memory-powercontext/src/recall-query.spec.ts diff --git a/docs/en/docs/integrations/openclaw.md b/docs/en/docs/integrations/openclaw.md index 3e24005185..0b109c97e3 100644 --- a/docs/en/docs/integrations/openclaw.md +++ b/docs/en/docs/integrations/openclaw.md @@ -43,7 +43,7 @@ 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) 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 | +| `before_prompt_build` | Latest user text (or prompt fallback) with recognized credentials replaced by `[REDACTED]`, then trimmed; when longer than 8192 characters or 8192 UTF-8 bytes, cut to its most recent text within both bounds; 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 | diff --git a/docs/zh/docs/integrations/openclaw.md b/docs/zh/docs/integrations/openclaw.md index c207ce201a..e2a1083bd7 100644 --- a/docs/zh/docs/integrations/openclaw.md +++ b/docs/zh/docs/integrations/openclaw.md @@ -43,7 +43,7 @@ openclaw | 事件/入口 | 发送的数据 | 直接接收方 | 默认/触发条件 | 关闭方式 | 关闭后影响 | | --- | --- | --- | --- | --- | --- | -| `before_prompt_build` | 最新用户文本(或 prompt 回退值),识别出的凭据替换为 `[REDACTED]` 后限制为 8192 UTF-8 字节,以及 Scope 和 prepare 预算 | 配置的 PowerContext Server;返回上下文进入宿主模型请求 | `autoRecall=true`,符合条件的私密会话 | `autoRecall=false` | 停止自动准备/注入;捕获和显式工具仍独立工作 | +| `before_prompt_build` | 最新用户文本(或 prompt 回退值),识别出的凭据替换为 `[REDACTED]` 后去掉首尾空白,超过 8192 个字符或 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 工作 | diff --git a/integrations/openclaw/plugins/memory-powercontext/src/content.ts b/integrations/openclaw/plugins/memory-powercontext/src/content.ts index d93db33e34..69787dbc9d 100644 --- a/integrations/openclaw/plugins/memory-powercontext/src/content.ts +++ b/integrations/openclaw/plugins/memory-powercontext/src/content.ts @@ -148,6 +148,29 @@ export function truncateUtf8(text: string, maxBytes: number): string { return encoded.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/u, ""); } +// `POST /v1/context/prepare` bounds `query` at 8,192 characters. The byte bound is the hosts' own +// margin, shared with the hook-based hosts, so a recall also fits a server that measures bytes. +export const MAX_QUERY_CHARACTERS = 8_192; +export const MAX_QUERY_BYTES = 8_192; + +/** + * Reduce a prompt to the recall query. A prompt within both bounds is sent as submitted, trimmed. + * A longer prompt keeps its most recent text, which holds the turn in hand, cut between characters + * so that the query fits both bounds and splits no character. + */ +export function boundedRecallQuery(prompt: string): string { + const characters = Array.from(prompt.trim()); + let start = characters.length; + let bytes = 0; + while (start > 0 && characters.length - start < MAX_QUERY_CHARACTERS) { + const size = Buffer.byteLength(characters[start - 1]!, "utf8"); + if (bytes + size > MAX_QUERY_BYTES) break; + bytes += size; + start -= 1; + } + return characters.slice(start).join("").trim(); +} + export function escapePowerContextBoundary(text: string): string { return text.replace(/<\/?powercontext_memory>/giu, (tag) => tag.replaceAll("<", "<").replaceAll(">", ">"), diff --git a/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts b/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts index 88818c7113..15e4bec19a 100644 --- a/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts +++ b/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.test.ts @@ -573,6 +573,27 @@ describe("PowerContext lifecycle", () => { expect(harness.warnings).toEqual([]); }); + it("recalls with the end of a long prompt", async () => { + const harness = createLifecycleHarness(); + const beforePromptBuild = harness.hooks.get("before_prompt_build")!; + const request = "Where did we leave the cache migration?"; + + await beforePromptBuild( + { messages: [{ role: "user", content: `${"pasted log line\n".repeat(1000)}${request}` }], prompt: "" }, + { + agentId: "main", + sessionId: "session-long-prompt", + sessionKey: "agent:main:telegram:direct:user-1", + }, + ); + + expect(harness.contextQueries).toHaveLength(1); + const query = harness.contextQueries[0]; + expect(query.endsWith(`\n${request}`)).toBe(true); + expect(query.length).toBe(8192); + expect(harness.warnings).toEqual([]); + }); + it("captures a turn under the projects its prompt was built with", async () => { const harness = createLifecycleHarness(); const beforePromptBuild = harness.hooks.get("before_prompt_build")!; diff --git a/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.ts b/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.ts index 15226180c3..ccad5d5e25 100644 --- a/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.ts +++ b/integrations/openclaw/plugins/memory-powercontext/src/lifecycle.ts @@ -20,6 +20,7 @@ import { normalizeAgentId, parseAgentSessionKey } from "openclaw/plugin-sdk/rout import type { PowerContextConfig } from "./config.js"; import { opaqueSessionId } from "./config.js"; import { + boundedRecallQuery, captureTranscript, deterministicSourceId, escapePowerContextBoundary, @@ -438,7 +439,7 @@ export function registerPowerContextLifecycle(api: OpenClawPluginApi, deps: Life }); const prepared = await deps.client.post("/v1/context/prepare", { scope_id: scopeId, - query: truncateUtf8(scrubSecrets(query, serverToken(config)), 8192), + query: boundedRecallQuery(scrubSecrets(query, serverToken(config))), max_bytes: config.prepareMaxBytes, ...(config.contextAssembly !== undefined ? { assembly: config.contextAssembly } : {}), }); diff --git a/integrations/openclaw/plugins/memory-powercontext/src/recall-query.spec.ts b/integrations/openclaw/plugins/memory-powercontext/src/recall-query.spec.ts new file mode 100644 index 0000000000..b2a03f9f27 --- /dev/null +++ b/integrations/openclaw/plugins/memory-powercontext/src/recall-query.spec.ts @@ -0,0 +1,39 @@ +/* + * 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 { describe, expect, it } from "vitest"; +import { boundedRecallQuery, MAX_QUERY_BYTES, MAX_QUERY_CHARACTERS } from "./content.js"; + +interface Segment { text: string; repeat?: number } + +const fixture = JSON.parse(readFileSync( + new URL("../../../../../tests/fixtures/recall_query_bound.json", import.meta.url), "utf8", +)) as { max_characters: number; max_bytes: number; cases: { id: string; prompt: Segment[]; query: Segment[] }[] }; + +function expand(segments: Segment[]): string { + return segments.map(({ text, repeat = 1 }) => text.repeat(repeat)).join(""); +} + +describe("shared recall query bound", () => { + it("uses the shared bounds", () => { + expect([MAX_QUERY_CHARACTERS, MAX_QUERY_BYTES]).toEqual([fixture.max_characters, fixture.max_bytes]); + }); + + it.each(fixture.cases)("$id", ({ prompt, query }) => { + expect(boundedRecallQuery(expand(prompt))).toBe(expand(query)); + }); +});