Skip to content

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

feat(openclaw-plugin): add bypass session patterns (#1194)

Mingjian Que7bcdb85647b6
diff --git a/examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts b/examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts
similarity index 69%
rename from examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts
rename to examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts
index b769fb246..f4ffb7023 100644
--- a/examples/openclaw-plugin/__tests__/ingest-reply-assist-session-patterns.test.ts
+++ b/examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts
@@ -4,27 +4,39 @@ import { memoryOpenVikingConfigSchema } from "../config.js";
import {
compileSessionPatterns,
matchesSessionPattern,
- shouldSkipIngestReplyAssistSession,
+ shouldBypassSession,
} from "../text-utils.js";
-describe("ingest reply assist session patterns", () => {
- it("parses ignore session patterns from config", () => {
+describe("bypass session patterns", () => {
+ it("parses bypass session patterns from config", () => {
const cfg = memoryOpenVikingConfigSchema.parse({
- ingestReplyAssistIgnoreSessionPatterns: [
+ bypassSessionPatterns: [
"agent:*:cron:**",
"agent:ops:maintenance:**",
],
});
- expect(cfg.ingestReplyAssistIgnoreSessionPatterns).toEqual([
+ expect(cfg.bypassSessionPatterns).toEqual([
"agent:*:cron:**",
"agent:ops:maintenance:**",
]);
});
- it("defaults ignore session patterns to an empty list", () => {
+ it("supports ingestReplyAssistIgnoreSessionPatterns as a deprecated alias", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ ingestReplyAssistIgnoreSessionPatterns: [
+ "agent:*:cron:**",
+ ],
+ });
+
+ expect(cfg.bypassSessionPatterns).toEqual([
+ "agent:*:cron:**",
+ ]);
+ });
+
+ it("defaults bypass session patterns to an empty list", () => {
const cfg = memoryOpenVikingConfigSchema.parse({});
- expect(cfg.ingestReplyAssistIgnoreSessionPatterns).toEqual([]);
+ expect(cfg.bypassSessionPatterns).toEqual([]);
});
it("matches lossless-claw style session globs", () => {
@@ -38,11 +50,11 @@ describe("ingest reply assist session patterns", () => {
expect(matchesSessionPattern("agent:main:main", patterns)).toBe(false);
});
- it("prefers sessionKey over sessionId when deciding whether to skip assist", () => {
+ it("prefers sessionKey over sessionId when deciding whether to bypass", () => {
const patterns = compileSessionPatterns(["agent:*:cron:**"]);
expect(
- shouldSkipIngestReplyAssistSession(
+ shouldBypassSession(
{
sessionId: "agent:main:cron:from-id",
sessionKey: "agent:main:main",
@@ -56,7 +68,7 @@ describe("ingest reply assist session patterns", () => {
const patterns = compileSessionPatterns(["agent:*:cron:**"]);
expect(
- shouldSkipIngestReplyAssistSession(
+ shouldBypassSession(
{
sessionId: "agent:main:cron:nightly:run:1",
},
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index c4781d8ba..10ad5706b 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -24,9 +24,11 @@ export type MemoryOpenVikingConfig = {
recallPreferAbstract?: boolean;
recallTokenBudget?: number;
commitTokenThreshold?: number;
+ bypassSessionPatterns?: string[];
ingestReplyAssist?: boolean;
ingestReplyAssistMinSpeakerTurns?: number;
ingestReplyAssistMinChars?: number;
+ /** Deprecated alias for bypassSessionPatterns. */
ingestReplyAssistIgnoreSessionPatterns?: string[];
/**
* When true (default), emit structured `openviking: diag {...}` lines (and any future
@@ -49,6 +51,7 @@ const DEFAULT_RECALL_MAX_CONTENT_CHARS = 500;
const DEFAULT_RECALL_PREFER_ABSTRACT = true;
const DEFAULT_RECALL_TOKEN_BUDGET = 2000;
const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;
+const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];
const DEFAULT_INGEST_REPLY_ASSIST = true;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS = 2;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS = 120;
@@ -157,6 +160,7 @@ export const memoryOpenVikingConfigSchema = {
"recallPreferAbstract",
"recallTokenBudget",
"commitTokenThreshold",
+ "bypassSessionPatterns",
"ingestReplyAssist",
"ingestReplyAssistMinSpeakerTurns",
"ingestReplyAssistMinChars",
@@ -227,6 +231,13 @@ export const memoryOpenVikingConfigSchema = {
0,
Math.min(100_000, Math.floor(toNumber(cfg.commitTokenThreshold, DEFAULT_COMMIT_TOKEN_THRESHOLD))),
),
+ bypassSessionPatterns: toStringArray(
+ cfg.bypassSessionPatterns,
+ toStringArray(
+ cfg.ingestReplyAssistIgnoreSessionPatterns,
+ DEFAULT_BYPASS_SESSION_PATTERNS,
+ ),
+ ),
ingestReplyAssist: cfg.ingestReplyAssist !== false,
ingestReplyAssistMinSpeakerTurns: Math.max(
1,
@@ -350,6 +361,12 @@ export const memoryOpenVikingConfigSchema = {
advanced: true,
help: "Maximum estimated tokens for auto-recall memory injection. Injection stops when budget is exhausted.",
},
+ bypassSessionPatterns: {
+ label: "Bypass Session Patterns",
+ placeholder: "agent:*:cron:**",
+ help: "Completely bypass OpenViking for matching session keys. Use * within one segment and ** across segments.",
+ advanced: true,
+ },
commitTokenThreshold: {
label: "Commit Token Threshold",
placeholder: String(DEFAULT_COMMIT_TOKEN_THRESHOLD),
@@ -374,9 +391,9 @@ export const memoryOpenVikingConfigSchema = {
advanced: true,
},
ingestReplyAssistIgnoreSessionPatterns: {
- label: "Ingest Ignore Session Patterns",
+ label: "Deprecated Ingest Ignore Session Patterns",
placeholder: "agent:*:cron:**",
- help: "Skip ingest reply assist when the session key matches any glob pattern. Use * within one segment and ** across segments.",
+ help: "Deprecated alias for bypassSessionPatterns. Matching sessions now bypass OpenViking entirely.",
advanced: true,
},
emitStandardDiagnostics: {
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index aef6ae25d..244f75ad0 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -2,8 +2,10 @@ import { createHash } from "node:crypto";
import type { OpenVikingClient, OVMessage } from "./client.js";
import type { MemoryOpenVikingConfig } from "./config.js";
import {
+ compileSessionPatterns,
getCaptureDecision,
extractNewTurnTexts,
+ shouldBypassSession,
} from "./text-utils.js";
import {
trimForLog,
@@ -90,7 +92,7 @@ type ContextEngine = {
export type ContextEngineWithCommit = ContextEngine & {
/** Commit (archive + extract) the OV session. Returns true on success. */
- commitOVSession: (sessionId: string) => Promise<boolean>;
+ commitOVSession: (sessionId: string, sessionKey?: string) => Promise<boolean>;
};
type Logger = {
@@ -483,19 +485,30 @@ export function createMemoryOpenVikingContextEngine(params: {
} = params;
const diagEnabled = cfg.emitStandardDiagnostics;
+ const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);
const diag = (stage: string, sessionId: string, data: Record<string, unknown>) =>
emitDiag(logger, stage, sessionId, data, diagEnabled);
- async function doCommitOVSession(sessionId: string): Promise<boolean> {
+ const isBypassedSession = (params: { sessionId?: string; sessionKey?: string }): boolean =>
+ shouldBypassSession(params, bypassSessionPatterns);
+
+ async function doCommitOVSession(sessionId: string, sessionKey?: string): Promise<boolean> {
+ if (isBypassedSession({ sessionId, sessionKey })) {
+ warnOrInfo(
+ logger,
+ `openviking: commit skipped because session is bypassed (sessionId=${sessionId}, sessionKey=${sessionKey ?? "none"})`,
+ );
+ return false;
+ }
try {
const client = await getClient();
- const ovId = openClawSessionRefToOvStorageId(sessionId);
+ const ovId = openClawSessionToOvStorageId(sessionId, sessionKey);
rememberSessionAgentId?.({
sessionId,
- sessionKey: sessionId,
+ sessionKey,
ovSessionId: ovId,
});
- const agentId = resolveAgentId(sessionId, sessionId, ovId);
+ const agentId = resolveAgentId(sessionId, sessionKey, ovId);
const commitResult = await client.commitSession(ovId, { wait: true, agentId });
const memCount = totalExtractedMemories(commitResult.memories_extracted);
if (commitResult.status === "failed") {
@@ -611,6 +624,19 @@ export function createMemoryOpenVikingContextEngine(params: {
messages: messageDigest(messages),
});
+ if (isBypassedSession({ sessionId: assembleParams.sessionId, sessionKey })) {
+ diag("assemble_result", OVSessionId, {
+ passthrough: true,
+ reason: "session_bypassed",
+ outputMessagesCount: messages.length,
+ inputTokenEstimate: originalTokens,
+ estimatedTokens: originalTokens,
+ tokensSaved: 0,
+ savingPct: 0,
+ });
+ return { messages, estimatedTokens: originalTokens };
+ }
+
try {
if (!(await runLocalPrecheck("assemble", OVSessionId, {
tokenBudget,
@@ -757,6 +783,14 @@ export function createMemoryOpenVikingContextEngine(params: {
afterTurnParams.sessionId ?? sessionKey ?? OVSessionId;
const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);
+ if (isBypassedSession({ sessionId: afterTurnParams.sessionId, sessionKey })) {
+ diag("afterTurn_skip", OVSessionId, {
+ reason: "session_bypassed",
+ totalMessages: afterTurnParams.messages?.length ?? 0,
+ });
+ return;
+ }
+
const messages = afterTurnParams.messages ?? [];
if (messages.length === 0) {
diag("afterTurn_skip", OVSessionId, {
@@ -873,6 +907,7 @@ export function createMemoryOpenVikingContextEngine(params: {
async compact(compactParams): Promise<CompactResult> {
const OVSessionId = compactParams.sessionId;
+ const sessionKey = extractSessionKey(compactParams.runtimeContext);
const tokenBudget = validTokenBudget(compactParams.tokenBudget) ?? 128_000;
diag("compact_entry", OVSessionId, {
tokenBudget,
@@ -883,6 +918,19 @@ export function createMemoryOpenVikingContextEngine(params: {
compactParams.customInstructions.trim().length > 0,
});
+ if (isBypassedSession({ sessionId: compactParams.sessionId, sessionKey })) {
+ diag("compact_result", OVSessionId, {
+ ok: true,
+ compacted: false,
+ reason: "session_bypassed",
+ });
+ return {
+ ok: true,
+ compacted: false,
+ reason: "session_bypassed",
+ };
+ }
+
const client = await getClient();
const agentId = resolveAgentId(OVSessionId);
const tokensBeforeOriginal = validTokenBudget(compactParams.currentTokenCount);
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index a47fac2ce..2bf71daf2 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -11,7 +11,7 @@ import {
compileSessionPatterns,
isTranscriptLikeIngest,
extractLatestUserText,
- shouldSkipIngestReplyAssistSession,
+ shouldBypassSession,
} from "./text-utils.js";
import {
clampScore,
@@ -275,9 +275,7 @@ const contextEnginePlugin = {
? (api.pluginConfig as Record<string, unknown>)
: {};
const cfg = memoryOpenVikingConfigSchema.parse(api.pluginConfig);
- const ingestReplyAssistIgnoreSessionPatterns = compileSessionPatterns(
- cfg.ingestReplyAssistIgnoreSessionPatterns,
- );
+ const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);
const rawAgentId = rawCfg.agentId;
if (cfg.logFindRequests) {
api.logger.info(
@@ -367,6 +365,25 @@ const contextEnginePlugin = {
const getClient = (): Promise<OpenVikingClient> => clientPromise;
+ const isBypassedSession = (ctx?: {
+ sessionId?: string;
+ sessionKey?: string;
+ }): boolean => shouldBypassSession(ctx ?? {}, bypassSessionPatterns);
+
+ const makeBypassedToolResult = (toolName: string) => ({
+ content: [
+ {
+ type: "text" as const,
+ text: `OpenViking is bypassed for this session by bypassSessionPatterns; ${toolName} was skipped.`,
+ },
+ ],
+ details: {
+ action: "bypassed",
+ reason: "session_bypassed",
+ toolName,
+ },
+ });
+
api.registerTool(
(ctx: ToolContext) => ({
name: "memory_recall",
@@ -386,6 +403,9 @@ const contextEnginePlugin = {
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ if (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("memory_recall");
+ }
rememberSessionAgentId(ctx);
const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const { query } = params as { query: string };
@@ -501,6 +521,9 @@ const contextEnginePlugin = {
sessionId: Type.Optional(Type.String({ description: "Existing OpenViking session ID" })),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ if (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("memory_store");
+ }
rememberSessionAgentId(ctx);
const storeAgentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const { text } = params as { text: string };
@@ -609,6 +632,9 @@ const contextEnginePlugin = {
),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ if (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("memory_forget");
+ }
rememberSessionAgentId(ctx);
const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const client = await getClient();
@@ -715,6 +741,9 @@ const contextEnginePlugin = {
}),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
+ if (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("ov_archive_expand");
+ }
rememberSessionAgentId(ctx);
const archiveId = String((params as { archiveId?: string }).archiveId ?? "").trim();
const sessionId = ctx.sessionId ?? "";
@@ -833,6 +862,12 @@ const contextEnginePlugin = {
})}`,
);
}
+ if (isBypassedSession(ctx)) {
+ verboseRoutingInfo(
+ `openviking: bypassing before_prompt_build due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,
+ );
+ return;
+ }
const agentId = resolveAgentId(ctx?.sessionId, ctx?.sessionKey);
let client: OpenVikingClient;
try {
@@ -934,28 +969,22 @@ const contextEnginePlugin = {
}
if (cfg.ingestReplyAssist) {
- if (shouldSkipIngestReplyAssistSession(ctx ?? {}, ingestReplyAssistIgnoreSessionPatterns)) {
+ const decision = isTranscriptLikeIngest(queryText, {
+ minSpeakerTurns: cfg.ingestReplyAssistMinSpeakerTurns,
+ minChars: cfg.ingestReplyAssistMinChars,
+ });
+ if (decision.shouldAssist) {
verboseRoutingInfo(
- `openviking: skipping ingest-reply-assist due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,
+ `openviking: ingest-reply-assist applied (reason=${decision.reason}, speakerTurns=${decision.speakerTurns}, chars=${decision.chars})`,
+ );
+ prependContextParts.push(
+ "<ingest-reply-assist>\n" +
+ "The latest user input looks like a multi-speaker transcript used for memory ingestion.\n" +
+ "Reply with 1-2 concise sentences to acknowledge or summarize key points.\n" +
+ "Do not output NO_REPLY or an empty reply.\n" +
+ "Do not fabricate facts beyond the provided transcript and recalled memories.\n" +
+ "</ingest-reply-assist>",
);
- } else {
- const decision = isTranscriptLikeIngest(queryText, {
- minSpeakerTurns: cfg.ingestReplyAssistMinSpeakerTurns,
- minChars: cfg.ingestReplyAssistMinChars,
- });
- if (decision.shouldAssist) {
- verboseRoutingInfo(
- `openviking: ingest-reply-assist applied (reason=${decision.reason}, speakerTurns=${decision.speakerTurns}, chars=${decision.chars})`,
- );
- prependContextParts.push(
- "<ingest-reply-assist>\n" +
- "The latest user input looks like a multi-speaker transcript used for memory ingestion.\n" +
- "Reply with 1-2 concise sentences to acknowledge or summarize key points.\n" +
- "Do not output NO_REPLY or an empty reply.\n" +
- "Do not fabricate facts beyond the provided transcript and recalled memories.\n" +
- "</ingest-reply-assist>",
- );
- }
}
}
@@ -969,10 +998,16 @@ const contextEnginePlugin = {
rememberSessionAgentId(ctx ?? {});
});
api.on("before_reset", async (_event: unknown, ctx?: HookAgentContext) => {
+ if (isBypassedSession(ctx)) {
+ verboseRoutingInfo(
+ `openviking: bypassing before_reset due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,
+ );
+ return;
+ }
const sessionId = ctx?.sessionId;
if (sessionId && contextEngineRef) {
try {
- const ok = await contextEngineRef.commitOVSession(sessionId);
+ const ok = await contextEngineRef.commitOVSession(sessionId, ctx?.sessionKey);
if (ok) {
api.logger.info(`openviking: committed OV session on reset for session=${sessionId}`);
}
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index a5ebecf1b..5b5d1a2c2 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -90,6 +90,12 @@
"advanced": true,
"help": "Maximum estimated tokens for auto-recall memory injection"
},
+ "bypassSessionPatterns": {
+ "label": "Bypass Session Patterns",
+ "placeholder": "agent:*:cron:**",
+ "help": "Completely bypass OpenViking for matching session keys. Use * within one segment and ** across segments.",
+ "advanced": true
+ },
"commitTokenThreshold": {
"label": "Commit Token Threshold",
"placeholder": "2000",
@@ -114,9 +120,9 @@
"advanced": true
},
"ingestReplyAssistIgnoreSessionPatterns": {
- "label": "Ingest Ignore Session Patterns",
+ "label": "Deprecated Ingest Ignore Session Patterns",
"placeholder": "agent:*:cron:**",
- "help": "Skip ingest reply assist when the session key matches any glob pattern. Use * within one segment and ** across segments.",
+ "help": "Deprecated alias for bypassSessionPatterns. Matching sessions now bypass OpenViking entirely.",
"advanced": true
},
"emitStandardDiagnostics": {
@@ -188,6 +194,12 @@
"commitTokenThreshold": {
"type": "number"
},
+ "bypassSessionPatterns": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"ingestReplyAssist": {
"type": "boolean"
},
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
index e7e7927ce..23d9b95c0 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
@@ -96,6 +96,28 @@ describe("context-engine afterTurn()", () => {
expect(client.addSessionMessage).not.toHaveBeenCalled();
});
+ it("skips afterTurn completely when the session matches bypassSessionPatterns", async () => {
+ const { engine, client, getClient, logger } = makeEngine({
+ cfgOverrides: {
+ bypassSessionPatterns: ["agent:*:cron:**"],
+ },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:cron:nightly:run:1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "hello" }],
+ prePromptMessageCount: 0,
+ });
+
+ expect(getClient).not.toHaveBeenCalled();
+ expect(client.addSessionMessage).not.toHaveBeenCalled();
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("\"reason\":\"session_bypassed\""),
+ );
+ });
+
it("skips when messages array is empty", async () => {
const { engine, client, logger } = makeEngine();
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
index 358836711..f6be428a4 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -155,6 +155,38 @@ describe("context-engine assemble()", () => {
});
});
+ it("passes through live messages when the session matches bypassSessionPatterns", async () => {
+ const { engine, client, getClient } = makeEngine(
+ {
+ latest_archive_overview: "unused",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 123,
+ stats: makeStats(),
+ },
+ {
+ cfgOverrides: {
+ bypassSessionPatterns: ["agent:*:cron:**"],
+ },
+ },
+ );
+
+ const liveMessages = [{ role: "user", content: "fallback live message" }];
+ const result = await engine.assemble({
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:cron:nightly:run:1",
+ messages: liveMessages,
+ tokenBudget: 4096,
+ });
+
+ expect(getClient).not.toHaveBeenCalled();
+ expect(client.getSessionContext).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ messages: liveMessages,
+ estimatedTokens: roughEstimate(liveMessages),
+ });
+ });
+
it("falls back immediately when local precheck reports OpenViking unavailable", async () => {
const quickPrecheck = vi.fn().mockResolvedValue({
ok: false as const,
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 cc866ee50..600392673 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -126,9 +126,77 @@ describe("context-engine commitOVSession()", () => {
expect.stringContaining("memories=4"),
);
});
+
+ it("skips commitOVSession when the session matches bypassSessionPatterns", async () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: false,
+ autoRecall: false,
+ ingestReplyAssist: 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,
+ getClient: getClient as any,
+ resolveAgentId,
+ });
+
+ const ok = await engine.commitOVSession("runtime-session", "agent:main:cron:nightly:run:1");
+
+ expect(ok).toBe(false);
+ expect(getClient).not.toHaveBeenCalled();
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining("session is bypassed"),
+ );
+ });
});
describe("context-engine compact()", () => {
+ it("returns compacted=false when the session matches bypassSessionPatterns", async () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: false,
+ autoRecall: false,
+ ingestReplyAssist: 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,
+ getClient: getClient as any,
+ resolveAgentId,
+ });
+
+ const result = await engine.compact({
+ sessionId: "agent:main:cron:nightly:run:1",
+ sessionFile: "",
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ compacted: false,
+ reason: "session_bypassed",
+ });
+ expect(getClient).not.toHaveBeenCalled();
+ });
+
it("returns compacted=true when commit succeeds with archived=true", async () => {
const { engine } = makeEngine({
status: "completed",
diff --git a/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts b/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts
new file mode 100644
index 000000000..88e2e61d3
--- /dev/null
+++ b/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from "vitest";
+
+import contextEnginePlugin from "../../index.js";
+
+type HookHandler = (event: unknown, ctx?: Record<string, unknown>) => unknown;
+
+function setupPlugin(pluginConfig?: Record<string, unknown>) {
+ const handlers = new Map<string, HookHandler>();
+ const logger = {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ };
+ const registerContextEngine = vi.fn();
+
+ contextEnginePlugin.register({
+ logger,
+ on: (name, handler) => {
+ handlers.set(name, handler as HookHandler);
+ },
+ pluginConfig: {
+ mode: "remote",
+ baseUrl: "http://127.0.0.1:1933",
+ autoCapture: true,
+ autoRecall: true,
+ ingestReplyAssist: true,
+ ...pluginConfig,
+ },
+ registerContextEngine,
+ registerService: vi.fn(),
+ registerTool: vi.fn(),
+ } as any);
+
+ return {
+ handlers,
+ logger,
+ registerContextEngine,
+ };
+}
+
+describe("plugin bypass session patterns", () => {
+ it("bypasses before_prompt_build before any OV client work", async () => {
+ const { handlers, logger } = setupPlugin({
+ bypassSessionPatterns: ["agent:*:cron:**"],
+ });
+
+ const hook = handlers.get("before_prompt_build");
+ expect(hook).toBeTruthy();
+
+ const result = await hook!(
+ {
+ messages: [{ role: "user", content: "Alice: hi\nBob: hello" }],
+ prompt: "Alice: hi\nBob: hello",
+ },
+ {
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:cron:nightly:run:1",
+ },
+ );
+
+ expect(result).toBeUndefined();
+ expect(logger.warn).not.toHaveBeenCalledWith(
+ expect.stringContaining("failed to get client"),
+ );
+ });
+
+ it("bypasses before_reset without calling commitOVSession", async () => {
+ const { handlers, registerContextEngine } = setupPlugin({
+ bypassSessionPatterns: ["agent:*:cron:**"],
+ });
+
+ const factory = registerContextEngine.mock.calls[0]?.[1] as (() => { commitOVSession: ReturnType<typeof vi.fn> }) | undefined;
+ expect(factory).toBeTruthy();
+ const engine = factory!();
+ engine.commitOVSession = vi.fn().mockResolvedValue(true);
+
+ const hook = handlers.get("before_reset");
+ expect(hook).toBeTruthy();
+
+ await hook!(
+ {},
+ {
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:cron:nightly:run:1",
+ },
+ );
+
+ expect(engine.commitOVSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/examples/openclaw-plugin/text-utils.ts b/examples/openclaw-plugin/text-utils.ts
index b3c264bf0..0e5bea927 100644
--- a/examples/openclaw-plugin/text-utils.ts
+++ b/examples/openclaw-plugin/text-utils.ts
@@ -109,7 +109,7 @@ export function resolveSessionPatternCandidate(params: {
return sessionId || undefined;
}
-export function shouldSkipIngestReplyAssistSession(
+export function shouldBypassSession(
params: {
sessionId?: string;
sessionKey?: string;
@@ -126,6 +126,16 @@ export function shouldSkipIngestReplyAssistSession(
return matchesSessionPattern(candidate, patterns);
}
+export function shouldSkipIngestReplyAssistSession(
+ params: {
+ sessionId?: string;
+ sessionKey?: string;
+ },
+ patterns: RegExp[],
+): boolean {
+ return shouldBypassSession(params, patterns);
+}
+
function countSpeakerTurns(text: string): number {
let count = 0;
for (const _match of text.matchAll(SPEAKER_TAG_RE)) {