Files
wehub-resource-sync 555e282cc4
pi-agent-plugin checks / lint (push) Has been cancelled
pi-agent-plugin checks / test (20) (push) Has been cancelled
pi-agent-plugin checks / test (22) (push) Has been cancelled
pi-agent-plugin checks / build (push) Has been cancelled
TypeScript SDK CI / check_changes (push) Has been cancelled
TypeScript SDK CI / changelog_check (push) Has been cancelled
ci / changelog_check (push) Has been cancelled
ci / check_changes (push) Has been cancelled
ci / build_mem0 (3.10) (push) Has been cancelled
ci / build_mem0 (3.11) (push) Has been cancelled
ci / build_mem0 (3.12) (push) Has been cancelled
CLI Node CI / lint (push) Has been cancelled
CLI Node CI / test (20) (push) Has been cancelled
CLI Node CI / test (22) (push) Has been cancelled
CLI Node CI / build (push) Has been cancelled
CLI Python CI / lint (push) Has been cancelled
CLI Python CI / test (3.10) (push) Has been cancelled
CLI Python CI / test (3.11) (push) Has been cancelled
CLI Python CI / test (3.12) (push) Has been cancelled
CLI Python CI / build (push) Has been cancelled
openclaw checks / lint (push) Has been cancelled
openclaw checks / test (20) (push) Has been cancelled
openclaw checks / test (22) (push) Has been cancelled
openclaw checks / build (push) Has been cancelled
opencode-plugin checks / build (push) Has been cancelled
TypeScript SDK CI / build_ts_sdk (20) (push) Has been cancelled
TypeScript SDK CI / build_ts_sdk (22) (push) Has been cancelled
TypeScript SDK CI / integration_ts_sdk (20) (push) Has been cancelled
TypeScript SDK CI / integration_ts_sdk (22) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:03:45 +08:00

88 lines
4.3 KiB
TypeScript

import { Type } from "@sinclair/typebox";
import type { MemoryItem, SearchOptions } from "../types.ts";
import type { ToolDeps } from "./index.ts";
export function createMemorySearchTool(deps: ToolDeps) {
const { cfg, provider, resolveUserId, buildSearchOptions, getCurrentSessionId } = deps;
return {
name: "memory_search",
label: "Memory Search",
description: "Search long-term memories stored in Mem0 by semantic meaning. Use this proactively before answering when the request may depend on the user's past work, preferences, or decisions -- relevant memories are not always already in context. For multi-part or comparative questions, run several searches with different phrasings and combine the results rather than stopping after one (multi-hop).",
parameters: Type.Object({
query: Type.String({ description: "Search query" }),
limit: Type.Optional(Type.Number({ description: `Max results (default: ${cfg.topK})` })),
userId: Type.Optional(Type.String({ description: "User ID to scope search" })),
agentId: Type.Optional(Type.String({ description: "Agent ID to search a specific agent's memories" })),
scope: Type.Optional(
Type.Union([Type.Literal("session"), Type.Literal("long-term"), Type.Literal("all")], {
description: 'Scope: "all" (default), "session", or "long-term"',
}),
),
categories: Type.Optional(Type.Array(Type.String(), { description: "Filter by category" })),
filters: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Advanced filters" })),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
const {
query, limit, userId, agentId, scope = "all",
categories: filterCategories, filters: agentFilters,
} = params as {
query: string; limit?: number; userId?: string; agentId?: string;
scope?: "session" | "long-term" | "all"; categories?: string[];
filters?: Record<string, unknown>;
};
const start = Date.now();
try {
let results: MemoryItem[] = [];
const uid = resolveUserId({ agentId, userId });
const currentSessionId = getCurrentSessionId();
const applyFilters = (opts: SearchOptions): SearchOptions => {
if (filterCategories?.length) opts.categories = filterCategories;
if (agentFilters) opts.filters = agentFilters;
return opts;
};
if (scope === "session") {
if (currentSessionId) {
results = await provider.search(query, applyFilters(buildSearchOptions(uid, limit, undefined, currentSessionId)));
}
} else if (scope === "long-term") {
results = await provider.search(query, applyFilters(buildSearchOptions(uid, limit)));
} else {
const longTerm = await provider.search(query, applyFilters(buildSearchOptions(uid, limit)));
let session: MemoryItem[] = [];
if (currentSessionId) {
session = await provider.search(query, applyFilters(buildSearchOptions(uid, limit, undefined, currentSessionId)));
}
const seen = new Set(longTerm.map((r) => r.id));
results = [...longTerm, ...session.filter((r) => !seen.has(r.id))];
}
deps.captureToolEvent("memory_search", { success: true, latency_ms: Date.now() - start, result_count: results.length });
if (!results || results.length === 0) {
return { content: [{ type: "text", text: "No relevant memories found." }], details: { count: 0 } };
}
const text = results.map((r, i) =>
`${i + 1}. ${r.memory} (score: ${((r.score ?? 0) * 100).toFixed(0)}%, id: ${r.id})`
).join("\n");
return {
content: [{ type: "text", text: `Found ${results.length} memories:\n\n${text}` }],
details: {
count: results.length,
memories: results.map((r) => ({ id: r.id, memory: r.memory, score: r.score, categories: r.categories, created_at: r.created_at })),
},
};
} catch (err) {
deps.captureToolEvent("memory_search", { success: false, latency_ms: Date.now() - start, error: String(err) });
return { content: [{ type: "text", text: `Memory search failed: ${String(err)}` }], details: { error: String(err) } };
}
},
};
}