Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(openclaw-plugin): fall back to native compaction for bypassed sessions (#4704)

Zayn Jarvise86642cac2c6
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index 5c70f8c90..fca6a9f68 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -907,7 +907,7 @@ export const memoryOpenVikingConfigSchema = {
bypassSessionPatterns: {
label: "Bypass Session Patterns",
placeholder: "agent:*:cron:**",
- help: "Completely bypass OpenViking for matching session keys. Use * within one segment and ** across segments.",
+ help: "Completely bypass OpenViking for matching session keys (no capture, recall, or commit; compaction falls back to OpenClaw's native compactor). Use * within one segment and ** across segments.",
advanced: true,
},
commitTokenThresholdRatio: {
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index 8fc2959a6..5bcd71503 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -19,6 +19,7 @@ import {
compactOpenVikingSession,
commitOpenVikingSession,
} from "./services/context-lifecycle-service.js";
+import { loadRuntimeCompactionDelegate } from "./plugin/openclaw-runtime-compaction.js";
type ContextEngineInfo = {
id: string;
@@ -437,6 +438,10 @@ export function createMemoryOpenVikingContextEngine(params: {
logger,
resolveAgentId,
isBypassedSession,
+ runtimeCompact: async () => {
+ const delegate = await loadRuntimeCompactionDelegate();
+ return delegate ? delegate(compactParams) : undefined;
+ },
diag,
});
},
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index c7e78efd1..1cf9e3c2a 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -195,7 +195,7 @@
"bypassSessionPatterns": {
"label": "Bypass Session Patterns",
"placeholder": "agent:*:cron:**",
- "help": "Completely bypass OpenViking for matching session keys. Use * within one segment and ** across segments.",
+ "help": "Completely bypass OpenViking for matching session keys (no capture, recall, or commit; compaction falls back to OpenClaw's native compactor). Use * within one segment and ** across segments.",
"advanced": true
},
"commitTokenThresholdRatio": {
diff --git a/examples/openclaw-plugin/plugin/openclaw-runtime-compaction.ts b/examples/openclaw-plugin/plugin/openclaw-runtime-compaction.ts
new file mode 100644
index 000000000..67b43cbb8
--- /dev/null
+++ b/examples/openclaw-plugin/plugin/openclaw-runtime-compaction.ts
@@ -0,0 +1,41 @@
+// Bridge to OpenClaw's built-in compactor for sessions that bypass OpenViking.
+// The host exports `delegateCompactionToRuntime` from `openclaw/plugin-sdk/core`
+// (present since the earliest supported host); it is resolved lazily because the
+// plugin builds without the host SDK installed.
+
+export type RuntimeCompactionResult = {
+ ok: boolean;
+ compacted: boolean;
+ reason?: string;
+ result?: {
+ summary?: string;
+ firstKeptEntryId?: string;
+ tokensBefore: number;
+ tokensAfter?: number;
+ details?: unknown;
+ };
+};
+
+export type RuntimeCompactionDelegate = (
+ params: Record<string, unknown>,
+) => Promise<RuntimeCompactionResult>;
+
+const PLUGIN_SDK_CORE_SPECIFIER = "openclaw/plugin-sdk/core";
+
+let cached: Promise<RuntimeCompactionDelegate | undefined> | undefined;
+
+export function loadRuntimeCompactionDelegate(): Promise<RuntimeCompactionDelegate | undefined> {
+ cached ??= (async () => {
+ try {
+ const mod = (await import(PLUGIN_SDK_CORE_SPECIFIER)) as {
+ delegateCompactionToRuntime?: unknown;
+ };
+ return typeof mod?.delegateCompactionToRuntime === "function"
+ ? (mod.delegateCompactionToRuntime as RuntimeCompactionDelegate)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+ })();
+ return cached;
+}
diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.ts
index b6757744b..0dbc8f3c9 100644
--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts
+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts
@@ -117,6 +117,8 @@ export type CompactOpenVikingSessionParams = {
logger: ContextEngineLifecycleLogger;
resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;
isBypassedSession: (params: { sessionId?: string; sessionKey?: string }) => boolean;
+ /** Host-native compaction for bypassed sessions; resolves undefined when unavailable. */
+ runtimeCompact?: () => Promise<CompactOpenVikingSessionResult | undefined>;
diag: (stage: string, sessionId: string, data: Record<string, unknown>) => void;
};
@@ -1014,6 +1016,7 @@ export async function compactOpenVikingSession({
logger,
resolveAgentId,
isBypassedSession,
+ runtimeCompact,
diag,
}: CompactOpenVikingSessionParams): Promise<CompactOpenVikingSessionResult> {
const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);
@@ -1027,6 +1030,18 @@ export async function compactOpenVikingSession({
});
if (isBypassedSession({ sessionId, sessionKey })) {
+ // Bypassed sessions store nothing in OV, but the host still needs a real
+ // compaction (preflight hard-fails on an unknown skip reason), so hand the
+ // request to OpenClaw's native compactor.
+ const delegated = await runtimeCompact?.();
+ if (delegated) {
+ diag("compact_result", ovSessionId, {
+ ok: delegated.ok,
+ compacted: delegated.compacted,
+ reason: delegated.reason ?? "session_bypassed_runtime_compaction",
+ });
+ return delegated;
+ }
diag("compact_result", ovSessionId, {
ok: true,
compacted: false,
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
index 41e3b5601..8ac40bc20 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -1,10 +1,19 @@
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenVikingClient } from "../../client.js";
import { memoryOpenVikingConfigSchema } from "../../config.js";
import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
+import { loadRuntimeCompactionDelegate } from "../../plugin/openclaw-runtime-compaction.js";
import { openClawSessionToOvStorageId } from "../../routing/identity-routing.js";
+vi.mock("../../plugin/openclaw-runtime-compaction.js", () => ({
+ loadRuntimeCompactionDelegate: vi.fn().mockResolvedValue(undefined),
+}));
+
+beforeEach(() => {
+ vi.mocked(loadRuntimeCompactionDelegate).mockResolvedValue(undefined);
+});
+
function makeLogger() {
return {
info: vi.fn(),
@@ -177,7 +186,7 @@ describe("context-engine commitOVSession()", () => {
});
describe("context-engine compact()", () => {
- it("returns compacted=false when the session matches bypassSessionPatterns", async () => {
+ function makeBypassEngine() {
const cfg = memoryOpenVikingConfigSchema.parse({
mode: "remote",
baseUrl: "http://127.0.0.1:1933",
@@ -185,19 +194,43 @@ describe("context-engine compact()", () => {
autoRecall: false,
bypassSessionPatterns: ["agent:*:cron:**"],
});
- const logger = makeLogger();
const getClient = vi.fn();
- const resolveAgentId = vi.fn((_sid: string) => "test-agent");
-
const engine = createMemoryOpenVikingContextEngine({
id: "openviking",
name: "Test Engine",
version: "test",
cfg,
- logger,
+ logger: makeLogger(),
getClient: getClient as any,
- resolveAgentId,
+ resolveAgentId: vi.fn((_sid: string) => "test-agent"),
});
+ return { engine, getClient };
+ }
+
+ it("delegates bypassed sessions to the OpenClaw native compactor without touching OV", async () => {
+ const delegated = { ok: true, compacted: true, result: { summary: "s", firstKeptEntryId: "e1", tokensBefore: 90_000, tokensAfter: 10_000 } };
+ const delegate = vi.fn().mockResolvedValue(delegated);
+ vi.mocked(loadRuntimeCompactionDelegate).mockResolvedValue(delegate);
+ const { engine, getClient } = makeBypassEngine();
+
+ const compactParams = {
+ sessionId: "agent:main:cron:nightly:run:1",
+ sessionKey: "agent:main:cron:nightly",
+ sessionFile: "",
+ tokenBudget: 100_000,
+ currentTokenCount: 90_000,
+ force: true,
+ runtimeContext: { workspaceDir: "/tmp/ws" },
+ };
+ const result = await engine.compact(compactParams);
+
+ expect(result).toBe(delegated);
+ expect(delegate).toHaveBeenCalledWith(compactParams);
+ expect(getClient).not.toHaveBeenCalled();
+ });
+
+ it("returns session_bypassed when the host exposes no native compactor", async () => {
+ const { engine, getClient } = makeBypassEngine();
const result = await engine.compact({
sessionId: "agent:main:cron:nightly:run:1",