Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(openclaw): gate agent-visible tools (#2566)
Mingjian Que61203e84b27a
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex 8c9df465b..c24642d6d 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -45,6 +45,12 @@ export type MemoryOpenVikingConfig = {emitStandardDiagnostics?: boolean;/** When true, log tenant routing for semantic find and session writes (messages/commit) to the plugin logger. */logFindRequests?: boolean;+ /** Agent-visible add_resource tool is disabled by default; manual /add-resource remains available. */+ enableAddResourceTool?: boolean;+ /** Agent-visible tool allowlist. Supports exact tool names or groups such as "memory" and "resource_query". */+ enabledTools?: string[] | string;+ /** Agent-visible tool blocklist applied after enabledTools. Supports exact tool names or groups. */+ disabledTools?: string[] | string;agentExperience?: {enabled?: boolean;recallLimit?: number;@@ -78,6 +84,40 @@ const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;const DEFAULT_PEER_ROLE = "none" as const;const DEFAULT_PEER_PREFIX = "";+export const OPENVIKING_ADD_RESOURCE_TOOL_NAME = "add_resource" as const;+export const OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES = [+ "add_skill",+ "ov_search",+ "ov_read",+ "ov_multi_read",+ "ov_list",+ "memory_recall",+ "memory_store",+ "memory_forget",+ "ov_archive_search",+ "ov_archive_expand",+ "openviking_tool_result_read",+ "openviking_tool_result_search",+ "openviking_tool_result_list",+] as const;+export const OPENVIKING_ALL_TOOL_NAMES = [+ OPENVIKING_ADD_RESOURCE_TOOL_NAME,+ ...OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,+] as const;+export type OpenVikingToolName = typeof OPENVIKING_ALL_TOOL_NAMES[number];+export const OPENVIKING_TOOL_GROUPS: Record<string, readonly OpenVikingToolName[]> = {+ all: OPENVIKING_ALL_TOOL_NAMES,+ default: OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,+ memory: ["memory_recall", "memory_store", "memory_forget"],+ resource_query: ["ov_search", "ov_read", "ov_multi_read", "ov_list"],+ import: ["add_resource", "add_skill"],+ archive: ["ov_archive_search", "ov_archive_expand"],+ tool_result: [+ "openviking_tool_result_read",+ "openviking_tool_result_search",+ "openviking_tool_result_list",+ ],+};const DEFAULT_AGENT_EXPERIENCE = {enabled: false,recallLimit: 3,@@ -153,6 +193,62 @@ function toRecord(value: unknown): Record<string, unknown> {: {};}+function expandToolSelectors(value: unknown, fallback: string[], label: string): OpenVikingToolName[] {+ const entries = toStringArray(value, fallback);+ const seen = new Set<OpenVikingToolName>();+ const normalized: OpenVikingToolName[] = [];+ const unknown: string[] = [];++ for (const rawEntry of entries) {+ const entry = rawEntry.trim();+ const group = OPENVIKING_TOOL_GROUPS[entry];+ const tools = group ??+ ((OPENVIKING_ALL_TOOL_NAMES as readonly string[]).includes(entry)+ ? [entry as OpenVikingToolName]+ : undefined);+ if (!tools) {+ unknown.push(entry);+ continue;+ }+ for (const tool of tools) {+ if (!seen.has(tool)) {+ seen.add(tool);+ normalized.push(tool);+ }+ }+ }++ if (unknown.length > 0) {+ throw new Error(`openviking ${label} contains unknown tool selectors: ${unknown.join(", ")}`);+ }+ return normalized;+}++function normalizeEnabledTools(cfg: Record<string, unknown>): {+ enabledTools: OpenVikingToolName[];+ disabledTools: OpenVikingToolName[];+} {+ const enableAddResourceTool = cfg.enableAddResourceTool === true;+ const defaultTools = enableAddResourceTool+ ? [OPENVIKING_ADD_RESOURCE_TOOL_NAME, ...OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES]+ : [...OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES];+ const selected = expandToolSelectors(cfg.enabledTools, defaultTools, "enabledTools");+ const disabled = expandToolSelectors(cfg.disabledTools, [], "disabledTools");+ const disabledSet = new Set(disabled);+ if (!enableAddResourceTool) {+ disabledSet.add(OPENVIKING_ADD_RESOURCE_TOOL_NAME);+ }+ const enabledTools = selected.filter((tool) =>+ !disabledSet.has(tool) &&+ (tool !== OPENVIKING_ADD_RESOURCE_TOOL_NAME || enableAddResourceTool)+ );++ return {+ enabledTools,+ disabledTools: Array.from(disabledSet),+ };+}+/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */function envFlag(name: string): boolean {const v = getEnv(name);@@ -219,6 +315,9 @@ export const memoryOpenVikingConfigSchema = {"ingestReplyAssistIgnoreSessionPatterns","emitStandardDiagnostics","logFindRequests",+ "enableAddResourceTool",+ "enabledTools",+ "disabledTools","agentExperience",],"openviking config",@@ -266,6 +365,7 @@ export const memoryOpenVikingConfigSchema = {),),);+ const { enabledTools, disabledTools } = normalizeEnabledTools(cfg);return {mode,@@ -330,6 +430,9 @@ export const memoryOpenVikingConfigSchema = {cfg.logFindRequests === true ||envFlag("OPENVIKING_LOG_ROUTING") ||envFlag("OPENVIKING_DEBUG"),+ enableAddResourceTool: cfg.enableAddResourceTool === true,+ enabledTools,+ disabledTools,agentExperience: {enabled:typeof agentExperienceRaw.enabled === "boolean"@@ -503,5 +606,23 @@ export const memoryOpenVikingConfigSchema = {"Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1 (no JSON edit).",advanced: true,},+ enableAddResourceTool: {+ label: "Enable Add Resource Tool",+ placeholder: "false",+ help: "Disabled by default so search and read flows cannot call add_resource. Set true only when agents should import resources; manual /add-resource remains available.",+ advanced: true,+ },+ enabledTools: {+ label: "Enabled Tools",+ placeholder: "default",+ help: "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, import, archive, tool_result. add_resource also requires enableAddResourceTool=true.",+ advanced: true,+ },+ disabledTools: {+ label: "Disabled Tools",+ placeholder: "memory",+ help: "Agent-visible tool blocklist applied after enabledTools. Accepts the same tool names or groups.",+ advanced: true,+ },},};diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 2d721c961..426c8b4a2 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -650,6 +650,22 @@ const contextEnginePlugin = {const defaultMemoryPolicy = defaultMemoryPolicyForPeerRole(cfg.peer_role);const tenantAccount = cfg.accountId;const tenantUser = cfg.userId;+ const enabledToolNames = new Set<string>(cfg.enabledTools);+ const registerOpenVikingTool = (+ toolOrFactory: ToolDefinition | ((ctx: ToolContext) => ToolDefinition),+ opts: { name: string; names?: string[] },+ ) => {+ const names = opts.names ?? [opts.name];+ if (!names.some((name) => enabledToolNames.has(name))) {+ api.logger.debug?.(`openviking: tool ${opts.name} disabled by config`);+ return;+ }+ if (typeof toolOrFactory === "function") {+ api.registerTool(toolOrFactory, opts);+ } else {+ api.registerTool(toolOrFactory, opts);+ }+ };const clientPromise = Promise.resolve(new OpenVikingClient(@@ -1043,44 +1059,47 @@ const contextEnginePlugin = {};};- api.registerTool(- (ctx: ToolContext) => ({- name: "add_resource",- label: "Add Resource (OpenViking)",- description:- "Use only when the user explicitly asks to import, add, upload, save, or index a document, directory, URL, Git repository, or OpenClaw media attachment into OpenViking resources. " +- "For a '[media attached: /path ...]' document, set source to that exact local media path. " +- "Set either to for an exact target URI or parent for a parent directory, never both. " +- "Do not invent OpenViking upload REST endpoints.",- parameters: Type.Object({- source: Type.String({ description: "Local path, OpenClaw media attachment path, directory path, public URL, or Git URL" }),- to: Type.Optional(Type.String({ description: "Exact target URI, e.g. viking://resources/project-docs. Mutually exclusive with parent." })),- parent: Type.Optional(Type.String({ description: "Parent URI under viking://resources. Mutually exclusive with to." })),- reason: Type.Optional(Type.String({ description: "Reason or note for adding this resource" })),- instruction: Type.Optional(Type.String({ description: "Processing instruction for semantic extraction" })),- wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),+ if (cfg.enableAddResourceTool) {+ registerOpenVikingTool(+ (ctx: ToolContext) => ({+ name: "add_resource",+ label: "Add Resource (OpenViking)",+ description:+ "Use only when the user explicitly asks to import, add, upload, save, or index a document, directory, URL, Git repository, or OpenClaw media attachment into OpenViking resources. " ++ "Never use this during search, retrieval, URI reading, or search-result optimization; use ov_search, ov_list, ov_read, and ov_multi_read for those flows. " ++ "For a '[media attached: /path ...]' document, set source to that exact local media path. " ++ "Set either to for an exact target URI or parent for a parent directory, never both. " ++ "Do not invent OpenViking upload REST endpoints.",+ parameters: Type.Object({+ source: Type.String({ description: "Local path, OpenClaw media attachment path, directory path, public URL, or Git URL" }),+ to: Type.Optional(Type.String({ description: "Exact target URI, e.g. viking://resources/project-docs. Mutually exclusive with parent." })),+ parent: Type.Optional(Type.String({ description: "Parent URI under viking://resources. Mutually exclusive with to." })),+ reason: Type.Optional(Type.String({ description: "Reason or note for adding this resource" })),+ instruction: Type.Optional(Type.String({ description: "Processing instruction for semantic extraction" })),+ wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),+ timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (isBypassedSession(ctx)) {+ return makeBypassedToolResult("add_resource");+ }+ const session = resolvePluginSessionRouting(ctx);+ return addResourceOpenViking({+ source: typeof params.source === "string" ? params.source : undefined,+ to: typeof params.to === "string" ? params.to : undefined,+ parent: typeof params.parent === "string" ? params.parent : undefined,+ reason: typeof params.reason === "string" ? params.reason : undefined,+ instruction: typeof params.instruction === "string" ? params.instruction : undefined,+ wait: typeof params.wait === "boolean" ? params.wait : undefined,+ timeout: typeof params.timeout === "number" ? params.timeout : undefined,+ }, session.agentId);+ },}),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("add_resource");- }- const session = resolvePluginSessionRouting(ctx);- return addResourceOpenViking({- source: typeof params.source === "string" ? params.source : undefined,- to: typeof params.to === "string" ? params.to : undefined,- parent: typeof params.parent === "string" ? params.parent : undefined,- reason: typeof params.reason === "string" ? params.reason : undefined,- instruction: typeof params.instruction === "string" ? params.instruction : undefined,- wait: typeof params.wait === "boolean" ? params.wait : undefined,- timeout: typeof params.timeout === "number" ? params.timeout : undefined,- }, session.agentId);- },- }),- { name: "add_resource" },- );+ { name: "add_resource" },+ );+ }- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "add_skill",label: "Add Skill (OpenViking)",@@ -1109,7 +1128,7 @@ const contextEnginePlugin = {{ name: "add_skill" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_search",label: "Search (OpenViking)",@@ -1138,7 +1157,7 @@ const contextEnginePlugin = {{ name: "ov_search" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_read",label: "Read (OpenViking)",@@ -1162,7 +1181,7 @@ const contextEnginePlugin = {{ name: "ov_read" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_multi_read",label: "Multi Read (OpenViking)",@@ -1188,7 +1207,7 @@ const contextEnginePlugin = {{ name: "ov_multi_read" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_list",label: "List (OpenViking)",@@ -1277,7 +1296,7 @@ const contextEnginePlugin = {},});- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "memory_recall",label: "Memory Recall (OpenViking)",@@ -1451,7 +1470,7 @@ const contextEnginePlugin = {{ name: "memory_recall" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "memory_store",label: "Memory Store (OpenViking)",@@ -1601,7 +1620,7 @@ const contextEnginePlugin = {{ name: "memory_store" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "memory_forget",label: "Memory Forget (OpenViking)",@@ -1715,7 +1734,7 @@ const contextEnginePlugin = {{ name: "memory_forget" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_archive_search",label: "Archive Search (OpenViking)",@@ -1816,7 +1835,7 @@ const contextEnginePlugin = {{ name: "ov_archive_search" },);- api.registerTool((ctx: ToolContext) => ({+ registerOpenVikingTool((ctx: ToolContext) => ({name: "ov_archive_expand",label: "Archive Expand (OpenViking)",description:@@ -1895,7 +1914,7 @@ const contextEnginePlugin = {},}), { name: "ov_archive_expand" });- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "openviking_tool_result_read",label: "Tool Result Read (OpenViking)",@@ -1992,7 +2011,7 @@ const contextEnginePlugin = {{ name: "openviking_tool_result_read" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "openviking_tool_result_search",label: "Tool Result Search (OpenViking)",@@ -2096,7 +2115,7 @@ const contextEnginePlugin = {{ name: "openviking_tool_result_search" },);- api.registerTool(+ registerOpenVikingTool((ctx: ToolContext) => ({name: "openviking_tool_result_list",label: "Tool Result List (OpenViking)",diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex fe3bcdcb7..1600ea71c 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -12,7 +12,6 @@},"contracts": {"tools": [- "add_resource","add_skill","ov_search","ov_read",@@ -210,6 +209,24 @@"label": "Log find requests","help": "Log tenant routing: /search/find + session messages/commit (X-OpenViking-*; not apiKey). Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1.","advanced": true+ },+ "enableAddResourceTool": {+ "label": "Enable Add Resource Tool",+ "placeholder": "false",+ "help": "Disabled by default so search and read flows cannot call add_resource. Set true only when agents should import resources; manual /add-resource remains available.",+ "advanced": true+ },+ "enabledTools": {+ "label": "Enabled Tools",+ "placeholder": "default",+ "help": "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, import, archive, tool_result. add_resource also requires enableAddResourceTool=true.",+ "advanced": true+ },+ "disabledTools": {+ "label": "Disabled Tools",+ "placeholder": "memory",+ "help": "Agent-visible tool blocklist applied after enabledTools. Accepts the same tool names or groups.",+ "advanced": true}},"configSchema": {@@ -329,6 +346,35 @@"logFindRequests": {"type": "boolean"},+ "enableAddResourceTool": {+ "type": "boolean"+ },+ "enabledTools": {+ "oneOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "string"+ }+ ]+ },+ "disabledTools": {+ "oneOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "string"+ }+ ]+ },"agentExperience": {"type": "object","additionalProperties": false,diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.tsindex d9a543739..7f68f803c 100644--- a/examples/openclaw-plugin/tests/ut/config.test.ts+++ b/examples/openclaw-plugin/tests/ut/config.test.ts@@ -27,9 +27,56 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.peer_role).toBe("none");expect(cfg.peer_prefix).toBe("");expect(cfg.emitStandardDiagnostics).toBe(false);+ expect(cfg.enableAddResourceTool).toBe(false);+ expect(cfg.enabledTools).toContain("ov_search");+ expect(cfg.enabledTools).toContain("ov_read");+ expect(cfg.enabledTools).not.toContain("add_resource");+ expect(cfg.disabledTools).toContain("add_resource");expect(cfg.agentExperience.enabled).toBe(false);});+ it("enables add_resource only when explicitly allowed", () => {+ const disabled = memoryOpenVikingConfigSchema.parse({});+ expect(disabled.enableAddResourceTool).toBe(false);+ expect(disabled.enabledTools).not.toContain("add_resource");++ const enabled = memoryOpenVikingConfigSchema.parse({ enableAddResourceTool: true });+ expect(enabled.enableAddResourceTool).toBe(true);+ expect(enabled.enabledTools).toContain("add_resource");+ expect(enabled.disabledTools).not.toContain("add_resource");+ });++ it("expands enabled and disabled tool groups", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({+ enabledTools: ["resource_query", "memory"],+ disabledTools: "memory_forget",+ });+ expect(cfg.enabledTools).toEqual([+ "ov_search",+ "ov_read",+ "ov_multi_read",+ "ov_list",+ "memory_recall",+ "memory_store",+ ]);+ expect(cfg.disabledTools).toEqual(["memory_forget", "add_resource"]);+ });++ it("does not expose add_resource through enabledTools without enableAddResourceTool", () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ enabledTools: "all" });+ expect(cfg.enabledTools).not.toContain("add_resource");+ expect(cfg.disabledTools).toContain("add_resource");+ });++ it("throws on unknown tool selectors", () => {+ expect(() =>+ memoryOpenVikingConfigSchema.parse({ enabledTools: ["resource_query", "nope"] }),+ ).toThrow("unknown tool selectors");+ expect(() =>+ memoryOpenVikingConfigSchema.parse({ disabledTools: "nope" }),+ ).toThrow("unknown tool selectors");+ });+it("defaults recallMaxInjectedChars to the 4000-character memory budget", () => {const cfg = memoryOpenVikingConfigSchema.parse({});expect(cfg.recallMaxInjectedChars).toBe(4000);diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex fa7528e13..b5feba420 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -887,12 +887,19 @@ describe("Tool: OpenViking tool result access", () => {});describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {- it("registers add_resource tool with expected parameters", () => {+ it("does not register add_resource by default", () => {const { tools, api } = setupPlugin();contextEnginePlugin.register(api as any);+ expect(tools.get("add_resource")).toBeUndefined();+ });++ it("registers add_resource tool with expected parameters when explicitly enabled", () => {+ const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });+ contextEnginePlugin.register(api as any);const tool = tools.get("add_resource");expect(tool).toBeDefined();expect(tool!.description).toContain("explicitly asks");+ expect(tool!.description).toContain("Never use this during search");expect(tool!.description).toContain("[media attached: /path");expect(tool!.description).toContain("Set either to");expect(tool!.description).toContain("never both");@@ -944,6 +951,24 @@ describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {expect(props).toHaveProperty("limit");});+ it("applies enabledTools and disabledTools to runtime tool registration", () => {+ const { tools, api } = setupPlugin(undefined, {+ enabledTools: ["resource_query", "memory"],+ disabledTools: ["memory_forget"],+ });+ contextEnginePlugin.register(api as any);++ expect(tools.get("ov_search")).toBeDefined();+ expect(tools.get("ov_read")).toBeDefined();+ expect(tools.get("ov_multi_read")).toBeDefined();+ expect(tools.get("ov_list")).toBeDefined();+ expect(tools.get("memory_recall")).toBeDefined();+ expect(tools.get("memory_store")).toBeDefined();+ expect(tools.get("memory_forget")).toBeUndefined();+ expect(tools.get("add_skill")).toBeUndefined();+ expect(tools.get("add_resource")).toBeUndefined();+ });+it("registers ov_read and ov_multi_read tools for original evidence retrieval", () => {const { tools, api } = setupPlugin();contextEnginePlugin.register(api as any);@@ -1397,9 +1422,15 @@ describe("OpenViking ov_search command parsing", () => {});describe("Plugin registration", () => {- it("registers all 14 tools", () => {+ it("registers all 13 default tools", () => {const { api } = setupPlugin();contextEnginePlugin.register(api as any);+ expect(api.registerTool).toHaveBeenCalledTimes(13);+ });++ it("registers all 14 tools when add_resource is explicitly enabled", () => {+ const { api } = setupPlugin(undefined, { enableAddResourceTool: true });+ contextEnginePlugin.register(api as any);expect(api.registerTool).toHaveBeenCalledTimes(14);});@@ -1477,7 +1508,7 @@ describe("Plugin registration", () => {);vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin();+ const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });api.pluginConfig = {...api.pluginConfig,accountId: "acct-shared",@@ -1510,7 +1541,7 @@ describe("Plugin registration", () => {vi.stubGlobal("fetch", fetchMock);try {- const { tools, api } = setupPlugin();+ const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });contextEnginePlugin.register(api as any);const tool = tools.get("add_resource")!;