@supermemory/tools
Advanced tools
| import { t as SupermemoryToolsConfig } from "./types-hFkPVawQ.js"; | ||
| import Supermemory from "supermemory"; | ||
| import * as ai0 from "ai"; | ||
| import { LanguageModelV2 } from "@ai-sdk/provider"; | ||
| //#region src/vercel/index.d.ts | ||
| interface WrapVercelLanguageModelOptions { | ||
| conversationId?: string; | ||
| verbose?: boolean; | ||
| mode?: "profile" | "query" | "full"; | ||
| addMemory?: "always" | "never"; | ||
| apiKey?: string; | ||
| baseUrl?: string; | ||
| } | ||
| /** | ||
| * Wraps a language model with supermemory middleware to automatically inject relevant memories | ||
| * into the system prompt based on the user's message content. | ||
| * | ||
| * This middleware searches the supermemory API for relevant memories using the container tag | ||
| * and user message, then either appends memories to an existing system prompt or creates | ||
| * a new system prompt with the memories. | ||
| * | ||
| * @param model - The language model to wrap with supermemory capabilities | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation | ||
| * @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false) | ||
| * @param options.mode - Optional mode for memory search: "profile", "query", or "full" (default: "profile") | ||
| * @param options.addMemory - Optional mode for memory search: "always", "never" (default: "never") | ||
| * @param options.apiKey - Optional Supermemory API key to use instead of the environment variable | ||
| * | ||
| * @returns A wrapped language model that automatically includes relevant memories in prompts | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { withSupermemory } from "@supermemory/tools/ai-sdk" | ||
| * import { openai } from "@ai-sdk/openai" | ||
| * | ||
| * const modelWithMemory = withSupermemory(openai("gpt-4"), "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always" | ||
| * }) | ||
| * | ||
| * const result = await generateText({ | ||
| * model: modelWithMemory, | ||
| * messages: [{ role: "user", content: "What's my favorite programming language?" }] | ||
| * }) | ||
| * ``` | ||
| * | ||
| * @throws {Error} When neither `options.apiKey` nor `process.env.SUPERMEMORY_API_KEY` are set | ||
| * @throws {Error} When supermemory API request fails | ||
| */ | ||
| declare const wrapVercelLanguageModel: (model: LanguageModelV2, containerTag: string, options?: WrapVercelLanguageModelOptions) => LanguageModelV2; | ||
| //#endregion | ||
| //#region src/ai-sdk.d.ts | ||
| declare const searchMemoriesTool: (apiKey: string, config?: SupermemoryToolsConfig) => ai0.Tool<{ | ||
| informationToGet: string; | ||
| includeFullDocs: boolean; | ||
| limit: number; | ||
| }, { | ||
| success: boolean; | ||
| results: Supermemory.Search.SearchExecuteResponse.Result[]; | ||
| count: number; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| results?: undefined; | ||
| count?: undefined; | ||
| }>; | ||
| declare const addMemoryTool: (apiKey: string, config?: SupermemoryToolsConfig) => ai0.Tool<{ | ||
| memory: string; | ||
| }, { | ||
| success: boolean; | ||
| memory: Supermemory.Memories.MemoryAddResponse; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| memory?: undefined; | ||
| }>; | ||
| /** | ||
| * Create Supermemory tools for AI SDK | ||
| */ | ||
| declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| searchMemories: ai0.Tool<{ | ||
| informationToGet: string; | ||
| includeFullDocs: boolean; | ||
| limit: number; | ||
| }, { | ||
| success: boolean; | ||
| results: Supermemory.Search.SearchExecuteResponse.Result[]; | ||
| count: number; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| results?: undefined; | ||
| count?: undefined; | ||
| }>; | ||
| addMemory: ai0.Tool<{ | ||
| memory: string; | ||
| }, { | ||
| success: boolean; | ||
| memory: Supermemory.Memories.MemoryAddResponse; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| memory?: undefined; | ||
| }>; | ||
| }; | ||
| //#endregion | ||
| export { addMemoryTool, searchMemoriesTool, supermemoryTools, wrapVercelLanguageModel as withSupermemory }; |
| import { t as SupermemoryToolsConfig } from "./types-hFkPVawQ.js"; | ||
| //#region src/claude-memory.d.ts | ||
| interface ClaudeMemoryConfig extends SupermemoryToolsConfig { | ||
| memoryContainerTag?: string; | ||
| } | ||
| interface MemoryCommand { | ||
| command: "view" | "create" | "str_replace" | "insert" | "delete" | "rename"; | ||
| path: string; | ||
| view_range?: [number, number]; | ||
| file_text?: string; | ||
| old_str?: string; | ||
| new_str?: string; | ||
| insert_line?: number; | ||
| insert_text?: string; | ||
| new_path?: string; | ||
| } | ||
| interface MemoryResponse { | ||
| success: boolean; | ||
| content?: string; | ||
| error?: string; | ||
| } | ||
| interface MemoryToolResult { | ||
| type: "tool_result"; | ||
| tool_use_id: string; | ||
| content: string; | ||
| is_error: boolean; | ||
| } | ||
| /** | ||
| * Claude Memory Tool - Client-side implementation | ||
| * Maps Claude's memory tool commands to supermemory document operations | ||
| */ | ||
| declare class ClaudeMemoryTool { | ||
| private client; | ||
| private containerTags; | ||
| private memoryContainerPrefix; | ||
| /** | ||
| * Normalize file path to be used as customId (replace / with --) | ||
| */ | ||
| private normalizePathToCustomId; | ||
| /** | ||
| * Convert customId back to file path (replace -- with /) | ||
| */ | ||
| private customIdToPath; | ||
| constructor(apiKey: string, config?: ClaudeMemoryConfig); | ||
| /** | ||
| * Main method to handle all Claude memory tool commands | ||
| */ | ||
| handleCommand(command: MemoryCommand): Promise<MemoryResponse>; | ||
| /** | ||
| * Handle command and return properly formatted tool result | ||
| */ | ||
| handleCommandForToolResult(command: MemoryCommand, toolUseId: string): Promise<MemoryToolResult>; | ||
| /** | ||
| * View command: List directory contents or read file with optional line range | ||
| */ | ||
| private view; | ||
| /** | ||
| * List directory contents | ||
| */ | ||
| private listDirectory; | ||
| /** | ||
| * Read file contents with optional line range | ||
| */ | ||
| private readFile; | ||
| /** | ||
| * Create command: Create or overwrite a memory file | ||
| */ | ||
| private create; | ||
| /** | ||
| * String replace command: Replace text in existing file | ||
| */ | ||
| private strReplace; | ||
| /** | ||
| * Insert command: Insert text at specific line | ||
| */ | ||
| private insert; | ||
| /** | ||
| * Delete command: Delete memory file | ||
| */ | ||
| private delete; | ||
| /** | ||
| * Rename command: Move/rename memory file | ||
| */ | ||
| private rename; | ||
| /** | ||
| * Helper: Get document by file path | ||
| */ | ||
| private getFileDocument; | ||
| /** | ||
| * Validate that path starts with /memories for security | ||
| */ | ||
| private isValidPath; | ||
| } | ||
| /** | ||
| * Create a Claude memory tool instance | ||
| */ | ||
| declare function createClaudeMemoryTool(apiKey: string, config?: ClaudeMemoryConfig): ClaudeMemoryTool; | ||
| //#endregion | ||
| export { ClaudeMemoryConfig, ClaudeMemoryTool, MemoryCommand, MemoryResponse, MemoryToolResult, createClaudeMemoryTool }; |
| import { t as SupermemoryToolsConfig } from "./types-hFkPVawQ.js"; | ||
| import { p as OpenAIMiddlewareOptions } from "./index-Phe7YYY4.js"; | ||
| export { type OpenAIMiddlewareOptions, type SupermemoryToolsConfig }; |
| import { t as SupermemoryToolsConfig } from "./types-hFkPVawQ.js"; | ||
| import Supermemory from "supermemory"; | ||
| import OpenAI from "openai"; | ||
| //#region src/openai/middleware.d.ts | ||
| interface OpenAIMiddlewareOptions { | ||
| conversationId?: string; | ||
| verbose?: boolean; | ||
| mode?: "profile" | "query" | "full"; | ||
| addMemory?: "always" | "never"; | ||
| baseUrl?: string; | ||
| } | ||
| /** | ||
| * Creates SuperMemory middleware for OpenAI clients. | ||
| * | ||
| * This function creates middleware that automatically injects relevant memories | ||
| * into OpenAI chat completions and optionally saves new memories. The middleware | ||
| * can wrap existing OpenAI clients or create new ones with SuperMemory capabilities. | ||
| * | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages for contextual memory generation | ||
| * @param options.verbose - Enable detailed logging of memory operations (default: false) | ||
| * @param options.mode - Memory search mode: "profile" (all memories), "query" (search-based), or "full" (both) (default: "profile") | ||
| * @param options.addMemory - Automatic memory storage mode: "always" or "never" (default: "never") | ||
| * @returns Object with `wrapClient` and `createClient` methods | ||
| * @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const openaiWithSupermemory = createOpenAIMiddleware(openai, "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always", | ||
| * verbose: true | ||
| * }) | ||
| * | ||
| * ``` | ||
| */ | ||
| //#endregion | ||
| //#region src/openai/tools.d.ts | ||
| /** | ||
| * Result types for memory operations | ||
| */ | ||
| interface MemorySearchResult { | ||
| success: boolean; | ||
| results?: Awaited<ReturnType<Supermemory["search"]["execute"]>>["results"]; | ||
| count?: number; | ||
| error?: string; | ||
| } | ||
| interface MemoryAddResult { | ||
| success: boolean; | ||
| memory?: Awaited<ReturnType<Supermemory["memories"]["add"]>>; | ||
| error?: string; | ||
| } | ||
| /** | ||
| * Function schemas for OpenAI function calling | ||
| */ | ||
| declare const memoryToolSchemas: { | ||
| readonly searchMemories: { | ||
| name: string; | ||
| description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| informationToGet: { | ||
| type: string; | ||
| description: "Terms to search for in the user's memories"; | ||
| }; | ||
| includeFullDocs: { | ||
| type: string; | ||
| description: "Whether to include the full document content in the response. Defaults to true for better AI context."; | ||
| default: true; | ||
| }; | ||
| limit: { | ||
| type: string; | ||
| description: "Maximum number of results to return"; | ||
| default: 10; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| readonly addMemory: { | ||
| name: string; | ||
| description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| memory: { | ||
| type: string; | ||
| description: "The text content of the memory to add. This should be a single sentence or a short paragraph."; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| /** | ||
| * Search memories function | ||
| */ | ||
| declare function createSearchMemoriesFunction(apiKey: string, config?: SupermemoryToolsConfig): ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| /** | ||
| * Add memory function | ||
| */ | ||
| declare function createAddMemoryFunction(apiKey: string, config?: SupermemoryToolsConfig): ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| /** | ||
| * Create all memory tools functions | ||
| */ | ||
| declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| searchMemories: ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| addMemory: ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| }; | ||
| /** | ||
| * Get OpenAI function definitions for all memory tools | ||
| */ | ||
| declare function getToolDefinitions(): OpenAI.Chat.Completions.ChatCompletionTool[]; | ||
| /** | ||
| * Execute a tool call based on the function name and arguments | ||
| */ | ||
| declare function createToolCallExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => Promise<string>; | ||
| /** | ||
| * Execute tool calls from OpenAI function calling | ||
| */ | ||
| declare function createToolCallsExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => Promise<OpenAI.Chat.Completions.ChatCompletionToolMessageParam[]>; | ||
| /** | ||
| * Individual tool creators for more granular control | ||
| */ | ||
| declare function createSearchMemoriesTool(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| definition: { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| informationToGet: { | ||
| type: string; | ||
| description: "Terms to search for in the user's memories"; | ||
| }; | ||
| includeFullDocs: { | ||
| type: string; | ||
| description: "Whether to include the full document content in the response. Defaults to true for better AI context."; | ||
| default: true; | ||
| }; | ||
| limit: { | ||
| type: string; | ||
| description: "Maximum number of results to return"; | ||
| default: 10; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| execute: ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| }; | ||
| declare function createAddMemoryTool(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| definition: { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| memory: { | ||
| type: string; | ||
| description: "The text content of the memory to add. This should be a single sentence or a short paragraph."; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| execute: ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| }; | ||
| //#endregion | ||
| //#region src/openai/index.d.ts | ||
| /** | ||
| * Wraps an OpenAI client with SuperMemory middleware to automatically inject relevant memories | ||
| * into both Chat Completions and Responses APIs based on the user's input content. | ||
| * | ||
| * For Chat Completions API: Searches for memories using the user message content and injects | ||
| * them into the system prompt (appends to existing or creates new system prompt). | ||
| * | ||
| * For Responses API: Searches for memories using the input parameter and injects them into | ||
| * the instructions parameter (appends to existing or creates new instructions). | ||
| * | ||
| * @param openaiClient - The OpenAI client to wrap with SuperMemory middleware | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation | ||
| * @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false) | ||
| * @param options.mode - Optional mode for memory search: "profile" (default), "query", or "full" | ||
| * @param options.addMemory - Optional mode for memory addition: "always", "never" (default) | ||
| * | ||
| * @returns An OpenAI client with SuperMemory middleware injected for both Chat Completions and Responses APIs | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { withSupermemory } from "@supermemory/tools/openai" | ||
| * import OpenAI from "openai" | ||
| * | ||
| * // Create OpenAI client with supermemory middleware | ||
| * const openai = new OpenAI({ | ||
| * apiKey: process.env.OPENAI_API_KEY, | ||
| * }) | ||
| * const openaiWithSupermemory = withSupermemory(openai, "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always" | ||
| * }) | ||
| * | ||
| * // Use with Chat Completions API - memories injected into system prompt | ||
| * const chatResponse = await openaiWithSupermemory.chat.completions.create({ | ||
| * model: "gpt-4", | ||
| * messages: [ | ||
| * { role: "user", content: "What's my favorite programming language?" } | ||
| * ] | ||
| * }) | ||
| * | ||
| * // Use with Responses API - memories injected into instructions | ||
| * const response = await openaiWithSupermemory.responses.create({ | ||
| * model: "gpt-4o", | ||
| * instructions: "You are a helpful coding assistant", | ||
| * input: "What's my favorite programming language?" | ||
| * }) | ||
| * ``` | ||
| * | ||
| * @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set | ||
| * @throws {Error} When supermemory API request fails | ||
| */ | ||
| declare function withSupermemory(openaiClient: OpenAI, containerTag: string, options?: OpenAIMiddlewareOptions): OpenAI; | ||
| //#endregion | ||
| export { createAddMemoryTool as a, createToolCallExecutor as c, memoryToolSchemas as d, supermemoryTools as f, createAddMemoryFunction as i, createToolCallsExecutor as l, MemoryAddResult as n, createSearchMemoriesFunction as o, OpenAIMiddlewareOptions as p, MemorySearchResult as r, createSearchMemoriesTool as s, withSupermemory as t, getToolDefinitions as u }; |
| import { a as createAddMemoryTool, c as createToolCallExecutor, d as memoryToolSchemas, f as supermemoryTools, i as createAddMemoryFunction, l as createToolCallsExecutor, n as MemoryAddResult, o as createSearchMemoriesFunction, p as OpenAIMiddlewareOptions, r as MemorySearchResult, s as createSearchMemoriesTool, t as withSupermemory, u as getToolDefinitions } from "../index-Phe7YYY4.js"; | ||
| export { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory }; |
| const e={searchMemories:`Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.`,addMemory:`Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.`},t={informationToGet:`Terms to search for in the user's memories`,includeFullDocs:`Whether to include the full document content in the response. Defaults to true for better AI context.`,limit:`Maximum number of results to return`,memory:`The text content of the memory to add. This should be a single sentence or a short paragraph.`},n={includeFullDocs:!0,limit:10,chunkThreshold:.6},r={projectPrefix:`sm_project_`,defaultTags:[`sm_project_default`]};function i(e){return e?.projectId?[`${r.projectPrefix}${e.projectId}`]:e?.containerTags??r.defaultTags}export{i,t as n,e as r,n as t}; |
| //#region src/types.d.ts | ||
| /** | ||
| * Supermemory configuration | ||
| * Only one of `projectId` or `containerTags` can be provided. | ||
| */ | ||
| interface SupermemoryToolsConfig { | ||
| baseUrl?: string; | ||
| containerTags?: string[]; | ||
| projectId?: string; | ||
| } | ||
| //#endregion | ||
| export { SupermemoryToolsConfig as t }; |
| async function e(e){let t=`${e.baseUrl||`https://api.supermemory.ai`}/v4/conversations`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({conversationId:e.conversationId,messages:e.messages,containerTags:e.containerTags,metadata:e.metadata})});if(!n.ok){let e=await n.text().catch(()=>`Unknown error`);throw Error(`Failed to add conversation: ${n.status} ${n.statusText}. ${e}`)}return await n.json()}const t=e=>e?{debug:(e,t)=>{console.log(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},info:(e,t)=>{console.log(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{console.warn(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{console.error(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)}}:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function n(e){let t=[];return e.profile.static&&e.profile.static.length>0&&(t.push(`## Static Profile`),t.push(e.profile.static.map(e=>`- ${e}`).join(` | ||
| `))),e.profile.dynamic&&e.profile.dynamic.length>0&&(t.push(`## Dynamic Profile`),t.push(e.profile.dynamic.map(e=>`- ${e}`).join(` | ||
| `))),t.join(` | ||
| `)}const r=e=>e.prompt.slice().reverse().find(e=>e.role===`user`)?.content.filter(e=>e.type===`text`).map(e=>e.text).join(` `),i=e=>e.split(`User Supermemories: `)[0];export{e as a,t as i,i as n,r,n as t}; |
+3
-3
@@ -1,4 +0,4 @@ | ||
| import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"./shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a,filterOutSupermemories as o,getLastUserMessage as s}from"./util-D4fsPgmW.js";import c from"supermemory";import{tool as l,wrapLanguageModel as u}from"ai";import{z as d}from"zod";const f=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,p=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},m=async(e,t,n,r,a)=>{let o=e.prompt.some(e=>e.role===`system`),s=r===`profile`?``:e.prompt.slice().reverse().find(e=>e.role===`user`)?.content?.filter(e=>e.type===`text`)?.map(e=>e.type===`text`?e.text:``)?.join(` `)||``,c=await p(t,s,a),l=c.profile.static?.length||0,u=c.profile.dynamic?.length||0;n.info(`Memory search completed`,{containerTag:t,memoryCountStatic:l,memoryCountDynamic:u,queryText:s.substring(0,100)+(s.length>100?`...`:``),mode:r});let d=r===`query`?``:i(c),f=r===`profile`?``:`Search results for user's recent message: \n${c.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`,m=`User Supermemories: \n${d}\n${f}`.trim();return m&&n.debug(`Memory content preview`,{content:m,fullLength:m.length}),o?(n.debug(`Added memories to existing system prompt`),{...e,prompt:e.prompt.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${m}`}:e)}):(n.debug(`System prompt does not exist, created system prompt with memories`),{...e,prompt:[{role:`system`,content:m},...e.prompt]})},h=e=>e.prompt.filter(e=>e.role!==`system`&&e.role!==`tool`).map(e=>{let t=e.role===`user`?`User`:`Assistant`;if(typeof e.content==`string`)return`${t}: ${o(e.content)}`;let n=e.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?o(e.text):``).join(` `);return`${t}: ${n}`}).join(` | ||
| import{i as e,n as t,r as n,t as r}from"./shared-BnAhKdVy.js";import{a as i,i as a,n as o,r as s,t as c}from"./util-QkWioda_.js";import l from"supermemory";import{tool as u,wrapLanguageModel as d}from"ai";import{z as f}from"zod";const p=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,m=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},h=async(e,t,n,r,i)=>{let a=e.prompt.some(e=>e.role===`system`),o=r===`profile`?``:e.prompt.slice().reverse().find(e=>e.role===`user`)?.content?.filter(e=>e.type===`text`)?.map(e=>e.type===`text`?e.text:``)?.join(` `)||``,s=await m(t,o,i),l=s.profile.static?.length||0,u=s.profile.dynamic?.length||0;n.info(`Memory search completed`,{containerTag:t,memoryCountStatic:l,memoryCountDynamic:u,queryText:o.substring(0,100)+(o.length>100?`...`:``),mode:r});let d=`User Supermemories: \n${r===`query`?``:c(s)}\n${r===`profile`?``:`Search results for user's recent message: \n${s.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`}`.trim();return d&&n.debug(`Memory content preview`,{content:d,fullLength:d.length}),a?(n.debug(`Added memories to existing system prompt`),{...e,prompt:e.prompt.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${d}`}:e)}):(n.debug(`System prompt does not exist, created system prompt with memories`),{...e,prompt:[{role:`system`,content:d},...e.prompt]})},g=e=>e.prompt.filter(e=>e.role!==`system`&&e.role!==`tool`).map(e=>{let t=e.role===`user`?`User`:`Assistant`;return typeof e.content==`string`?`${t}: ${o(e.content)}`:`${t}: ${e.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?o(e.text):``).join(` `)}`}).join(` | ||
| `),g=async(e,t,n,r,i,a)=>{let o=s(i),c=n?`${h(i)} \n\n Assistant: ${r}`:`User: ${o} \n\n Assistant: ${r}`,l=n?`conversation:${n}`:void 0;try{let n=await e.memories.add({content:c,containerTags:[t],customId:l});a.info(`Memory saved successfully`,{containerTag:t,customId:l,content:c,contentLength:c.length,memoryId:n.id})}catch(e){a.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}},_=(e,t,n,r=!1,i=`profile`,o=`never`,l=`https://api.supermemory.ai`)=>{let u=a(r),d=f(l),p=new c({apiKey:t,...d===`https://api.supermemory.ai`?{}:{baseURL:d}});return{transformParams:async({params:t})=>{let r=s(t);return i!==`profile`&&!r?(u.debug(`No user message found, skipping memory search`),t):(u.info(`Starting memory search`,{containerTag:e,conversationId:n,mode:i}),await m(t,e,u,i,d))},wrapGenerate:async({doGenerate:t,params:r})=>{let i=s(r);try{let a=await t(),s=a.content.map(e=>e.type===`text`?e.text:``).join(``);return o===`always`&&i&&i.trim()&&g(p,e,n,s,r,u),a}catch(e){throw u.error(`Error generating response`,{error:e instanceof Error?e.message:`Unknown error`}),e}},wrapStream:async({doStream:t,params:r})=>{let i=s(r),a=``;try{let{stream:s,...c}=await t(),l=new TransformStream({transform(e,t){e.type===`text-delta`&&(a+=e.delta),t.enqueue(e)},flush:async()=>{a&&[].push({type:`text`,text:a}),o===`always`&&i&&i.trim()&&g(p,e,n,a,r,u)}});return{stream:s.pipeThrough(l),...c}}catch(e){throw u.error(`Error streaming response`,{error:e instanceof Error?e.message:`Unknown error`}),e}}}},v=(e,t,n)=>{let r=n?.apiKey??process.env.SUPERMEMORY_API_KEY;if(!r)throw Error("SUPERMEMORY_API_KEY is not set — provide it via `options.apiKey` or set `process.env.SUPERMEMORY_API_KEY`");let i=n?.conversationId,a=n?.verbose??!1,o=n?.mode??`profile`,s=n?.addMemory??`never`,c=n?.baseUrl;return u({model:e,middleware:_(t,r,i,a,o,s,c)})},y=(i,a)=>{let o=new c({apiKey:i,...a?.baseUrl?{baseURL:a.baseUrl}:{}}),s=r(a);return l({description:n.searchMemories,inputSchema:d.object({informationToGet:d.string().describe(t.informationToGet),includeFullDocs:d.boolean().optional().default(e.includeFullDocs).describe(t.includeFullDocs),limit:d.number().optional().default(e.limit).describe(t.limit)}),execute:async({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:r=e.limit})=>{try{let i=await o.search.execute({q:t,containerTags:s,limit:r,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:i.results,count:i.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})},b=(e,i)=>{let a=new c({apiKey:e,...i?.baseUrl?{baseURL:i.baseUrl}:{}}),o=r(i);return l({description:n.addMemory,inputSchema:d.object({memory:d.string().describe(t.memory)}),execute:async({memory:e})=>{try{let t={};return{success:!0,memory:await a.memories.add({content:e,containerTags:o,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})};function x(e,t){return{searchMemories:y(e,t),addMemory:b(e,t)}}export{b as addMemoryTool,y as searchMemoriesTool,x as supermemoryTools,v as withSupermemory}; | ||
| `),_=async(e,t,n,r,a,c,l,u)=>{let d=s(a),f=n?`${g(a)} \n\n Assistant: ${r}`:`User: ${d} \n\n Assistant: ${r}`,p=n?`conversation:${n}`:void 0;try{if(n&&l){let e=a.prompt.map(e=>{let t=e.role,n;return n=typeof e.content==`string`?o(e.content):e.content.filter(e=>e.type===`text`).map(e=>({type:`text`,text:o(e.text)})),{role:t,content:n,name:e.name,tool_calls:e.tool_calls,tool_call_id:e.tool_call_id}}).concat([{role:`assistant`,content:r}]),s=await i({conversationId:n,messages:e,containerTags:[t],apiKey:l,baseUrl:u});c.info(`Conversation saved successfully via /v4/conversations`,{containerTag:t,conversationId:n,messageCount:e.length,responseId:s.id});return}let s=await e.memories.add({content:f,containerTags:[t],customId:p});c.info(`Memory saved successfully`,{containerTag:t,customId:p,content:f,contentLength:f.length,memoryId:s.id})}catch(e){c.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}},v=(e,t,n,r=!1,i=`profile`,o=`never`,c=`https://api.supermemory.ai`)=>{let u=a(r),d=p(c),f=new l({apiKey:t,...d===`https://api.supermemory.ai`?{}:{baseURL:d}}),m=t,g=d;return{transformParams:async({params:t})=>{let r=s(t);return i!==`profile`&&!r?(u.debug(`No user message found, skipping memory search`),t):(u.info(`Starting memory search`,{containerTag:e,conversationId:n,mode:i}),await h(t,e,u,i,d))},wrapGenerate:async({doGenerate:t,params:r})=>{let i=s(r);try{let a=await t(),s=a.content.map(e=>e.type===`text`?e.text:``).join(``);return o===`always`&&i&&i.trim()&&_(f,e,n,s,r,u,m,g),a}catch(e){throw u.error(`Error generating response`,{error:e instanceof Error?e.message:`Unknown error`}),e}},wrapStream:async({doStream:t,params:r})=>{let i=s(r),a=``;try{let{stream:s,...c}=await t(),l=new TransformStream({transform(e,t){e.type===`text-delta`&&(a+=e.delta),t.enqueue(e)},flush:async()=>{a&&[].push({type:`text`,text:a}),o===`always`&&i&&i.trim()&&_(f,e,n,a,r,u,m,g)}});return{stream:s.pipeThrough(l),...c}}catch(e){throw u.error(`Error streaming response`,{error:e instanceof Error?e.message:`Unknown error`}),e}}}},y=(e,t,n)=>{let r=n?.apiKey??process.env.SUPERMEMORY_API_KEY;if(!r)throw Error("SUPERMEMORY_API_KEY is not set — provide it via `options.apiKey` or set `process.env.SUPERMEMORY_API_KEY`");let i=n?.conversationId,a=n?.verbose??!1,o=n?.mode??`profile`,s=n?.addMemory??`never`,c=n?.baseUrl;return d({model:e,middleware:v(t,r,i,a,o,s,c)})},b=(i,a)=>{let o=new l({apiKey:i,...a?.baseUrl?{baseURL:a.baseUrl}:{}}),s=e(a);return u({description:n.searchMemories,inputSchema:f.object({informationToGet:f.string().describe(t.informationToGet),includeFullDocs:f.boolean().optional().default(r.includeFullDocs).describe(t.includeFullDocs),limit:f.number().optional().default(r.limit).describe(t.limit)}),execute:async({informationToGet:e,includeFullDocs:t=r.includeFullDocs,limit:n=r.limit})=>{try{let i=await o.search.execute({q:e,containerTags:s,limit:n,chunkThreshold:r.chunkThreshold,includeFullDocs:t});return{success:!0,results:i.results,count:i.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})},x=(r,i)=>{let a=new l({apiKey:r,...i?.baseUrl?{baseURL:i.baseUrl}:{}}),o=e(i);return u({description:n.addMemory,inputSchema:f.object({memory:f.string().describe(t.memory)}),execute:async({memory:e})=>{try{let t={};return{success:!0,memory:await a.memories.add({content:e,containerTags:o,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})};function S(e,t){return{searchMemories:b(e,t),addMemory:x(e,t)}}export{x as addMemoryTool,b as searchMemoriesTool,S as supermemoryTools,y as withSupermemory}; |
@@ -1,2 +0,2 @@ | ||
| import{getContainerTags as e}from"./shared-CttEw8ws.js";import t from"supermemory";function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(n(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||`default`);if(n(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function i(e){var t=r(e,`string`);return n(t)==`symbol`?t:t+``}function a(e,t,n){return(t=i(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o=class{normalizePathToCustomId(e){return e.replace(/\//g,`--`)}customIdToPath(e){return e.replace(/--/g,`/`)}constructor(n,r){a(this,`client`,void 0),a(this,`containerTags`,void 0),a(this,`memoryContainerPrefix`,void 0),this.client=new t({apiKey:n,...r?.baseUrl&&{baseURL:r.baseUrl}}),this.memoryContainerPrefix=r?.memoryContainerTag||`claude_memory`,this.containerTags=[...e(r),this.memoryContainerPrefix]}async handleCommand(e){try{if(!this.isValidPath(e.path))return{success:!1,error:`Invalid path: ${e.path}. All paths must start with /memories/`};switch(e.command){case`view`:return await this.view(e.path,e.view_range);case`create`:return e.file_text?await this.create(e.path,e.file_text):{success:!1,error:`file_text is required for create command`};case`str_replace`:return!e.old_str||!e.new_str?{success:!1,error:`old_str and new_str are required for str_replace command`}:await this.strReplace(e.path,e.old_str,e.new_str);case`insert`:return e.insert_line===void 0||!e.insert_text?{success:!1,error:`insert_line and insert_text are required for insert command`}:await this.insert(e.path,e.insert_line,e.insert_text);case`delete`:return await this.delete(e.path);case`rename`:return e.new_path?await this.rename(e.path,e.new_path):{success:!1,error:`new_path is required for rename command`};default:return{success:!1,error:`Unknown command: ${e.command}`}}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}async handleCommandForToolResult(e,t){let n=await this.handleCommand(e);return{type:`tool_result`,tool_use_id:t,content:n.success?n.content||`Operation completed successfully`:`Error: ${n.error}`,is_error:!n.success}}async view(e,t){if(e.endsWith(`/`)||e===`/memories`){let t=e.endsWith(`/`)?e:e+`/`;return await this.listDirectory(t)}return await this.readFile(e,t)}async listDirectory(e){try{let t=await this.client.search.execute({q:`*`,containerTags:this.containerTags,limit:100,includeFullDocs:!1});if(!t.results)return{success:!0,content:`Directory: ${e}\n(empty)`};let n=[],r=new Set;for(let i of t.results){let t=i.metadata?.file_path;if(!t||!t.startsWith(e))continue;let a=t.substring(e.length);if(!a)continue;let o=a.indexOf(`/`);o>0?r.add(a.substring(0,o)+`/`):a!==``&&n.push(a)}let i=[...Array.from(r).sort(),...n.sort()];return i.length===0?{success:!0,content:`Directory: ${e}\n(empty)`}:{success:!0,content:`Directory: ${e}\n${i.map(e=>`- ${e}`).join(` | ||
| import{i as e}from"./shared-BnAhKdVy.js";import t from"supermemory";function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}function r(e,t){if(n(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||`default`);if(n(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function i(e){var t=r(e,`string`);return n(t)==`symbol`?t:t+``}function a(e,t,n){return(t=i(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o=class{normalizePathToCustomId(e){return e.replace(/\//g,`--`)}customIdToPath(e){return e.replace(/--/g,`/`)}constructor(n,r){a(this,`client`,void 0),a(this,`containerTags`,void 0),a(this,`memoryContainerPrefix`,void 0),this.client=new t({apiKey:n,...r?.baseUrl&&{baseURL:r.baseUrl}}),this.memoryContainerPrefix=r?.memoryContainerTag||`claude_memory`,this.containerTags=[...e(r),this.memoryContainerPrefix]}async handleCommand(e){try{if(!this.isValidPath(e.path))return{success:!1,error:`Invalid path: ${e.path}. All paths must start with /memories/`};switch(e.command){case`view`:return await this.view(e.path,e.view_range);case`create`:return e.file_text?await this.create(e.path,e.file_text):{success:!1,error:`file_text is required for create command`};case`str_replace`:return!e.old_str||!e.new_str?{success:!1,error:`old_str and new_str are required for str_replace command`}:await this.strReplace(e.path,e.old_str,e.new_str);case`insert`:return e.insert_line===void 0||!e.insert_text?{success:!1,error:`insert_line and insert_text are required for insert command`}:await this.insert(e.path,e.insert_line,e.insert_text);case`delete`:return await this.delete(e.path);case`rename`:return e.new_path?await this.rename(e.path,e.new_path):{success:!1,error:`new_path is required for rename command`};default:return{success:!1,error:`Unknown command: ${e.command}`}}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}async handleCommandForToolResult(e,t){let n=await this.handleCommand(e);return{type:`tool_result`,tool_use_id:t,content:n.success?n.content||`Operation completed successfully`:`Error: ${n.error}`,is_error:!n.success}}async view(e,t){if(e.endsWith(`/`)||e===`/memories`){let t=e.endsWith(`/`)?e:e+`/`;return await this.listDirectory(t)}return await this.readFile(e,t)}async listDirectory(e){try{let t=await this.client.search.execute({q:`*`,containerTags:this.containerTags,limit:100,includeFullDocs:!1});if(!t.results)return{success:!0,content:`Directory: ${e}\n(empty)`};let n=[],r=new Set;for(let i of t.results){let t=i.metadata?.file_path;if(!t||!t.startsWith(e))continue;let a=t.substring(e.length);if(!a)continue;let o=a.indexOf(`/`);o>0?r.add(a.substring(0,o)+`/`):a!==``&&n.push(a)}let i=[...Array.from(r).sort(),...n.sort()];return i.length===0?{success:!0,content:`Directory: ${e}\n(empty)`}:{success:!0,content:`Directory: ${e}\n${i.map(e=>`- ${e}`).join(` | ||
| `)}`}}catch(e){return{success:!1,error:`Failed to list directory: ${e instanceof Error?e.message:`Unknown error`}`}}}async readFile(e,t){try{let n=this.normalizePathToCustomId(e),r=await this.client.search.execute({q:n,containerTags:this.containerTags,limit:1,includeFullDocs:!0}),i=r.results?.find(e=>e.documentId===n)||r.results?.[0];if(!i)return{success:!1,error:`File not found: ${e}`};let a=i.content||``;if(t){let e=a.split(` | ||
@@ -3,0 +3,0 @@ `),[n,r]=t;a=e.slice(n-1,r).map((e,t)=>`${(n+t).toString().padStart(4)}\t${e}`).join(` |
@@ -1,5 +0,5 @@ | ||
| import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"../shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a}from"../util-D4fsPgmW.js";import o from"supermemory";const s=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,c=e=>{let t=e.slice().reverse().find(e=>e.role===`user`);return typeof t?.content==`string`?t.content:``},l=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},u=async(e,t,n,r,a)=>{let o=e.some(e=>e.role===`system`),s=r===`profile`?``:c(e),u=await l(t,s,a),d=u.profile.static?.length||0,f=u.profile.dynamic?.length||0;n.info(`Memory search completed for chat API`,{containerTag:t,memoryCountStatic:d,memoryCountDynamic:f,queryText:s.substring(0,100)+(s.length>100?`...`:``),mode:r});let p=r===`query`?``:i({profile:{static:u.profile.static?.map(e=>e.memory),dynamic:u.profile.dynamic?.map(e=>e.memory)},searchResults:{results:u.searchResults.results.map(e=>({memory:e.memory}))}}),m=r===`profile`?``:`Search results for user's recent message: \n${u.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`,h=`${p}\n${m}`.trim();return h&&n.debug(`Memory content preview for chat API`,{content:h,fullLength:h.length}),o?(n.debug(`Added memories to existing system prompt`),e.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${h}`}:e)):(n.debug(`System prompt does not exist, created system prompt with memories`),[{role:`system`,content:h},...e])},d=e=>e.map(e=>{let t=e.role===`user`?`User`:`Assistant`,n=typeof e.content==`string`?e.content:``;return`${t}: ${n}`}).join(` | ||
| import{i as e,n as t,r as n,t as r}from"../shared-BnAhKdVy.js";import{a as i,i as a,t as o}from"../util-QkWioda_.js";import s from"supermemory";const c=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,l=e=>{let t=e.slice().reverse().find(e=>e.role===`user`);return typeof t?.content==`string`?t.content:``},u=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},d=async(e,t,n,r,i)=>{let a=e.some(e=>e.role===`system`),s=r===`profile`?``:l(e),c=await u(t,s,i),d=c.profile.static?.length||0,f=c.profile.dynamic?.length||0;n.info(`Memory search completed for chat API`,{containerTag:t,memoryCountStatic:d,memoryCountDynamic:f,queryText:s.substring(0,100)+(s.length>100?`...`:``),mode:r});let p=`${r===`query`?``:o({profile:{static:c.profile.static?.map(e=>e.memory),dynamic:c.profile.dynamic?.map(e=>e.memory)},searchResults:{results:c.searchResults.results.map(e=>({memory:e.memory}))}})}\n${r===`profile`?``:`Search results for user's recent message: \n${c.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`}`.trim();return p&&n.debug(`Memory content preview for chat API`,{content:p,fullLength:p.length}),a?(n.debug(`Added memories to existing system prompt`),e.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${p}`}:e)):(n.debug(`System prompt does not exist, created system prompt with memories`),[{role:`system`,content:p},...e])},f=e=>e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${typeof e.content==`string`?e.content:``}`).join(` | ||
| `),f=async(e,t,n,r,i)=>{try{let a=await e.memories.add({content:n,containerTags:[t],customId:r});i.info(`Memory saved successfully`,{containerTag:t,customId:r,contentLength:n.length,memoryId:a.id})}catch(e){i.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}};function p(e,t,n){let r=a(n?.verbose??!1),p=s(n?.baseUrl),m=new o({apiKey:process.env.SUPERMEMORY_API_KEY,...p===`https://api.supermemory.ai`?{}:{baseURL:p}}),h=n?.conversationId,g=n?.mode??`profile`,_=n?.addMemory??`never`,v=e.chat.completions.create,y=e.responses?.create,b=async(e,t,n,r,a)=>{let o=await l(t,e,p),s=o.profile.static?.length||0,c=o.profile.dynamic?.length||0;n.info(`Memory search completed for ${a} API`,{containerTag:t,memoryCountStatic:s,memoryCountDynamic:c,queryText:e.substring(0,100)+(e.length>100?`...`:``),mode:r});let u=r===`query`?``:i({profile:{static:o.profile.static?.map(e=>e.memory),dynamic:o.profile.dynamic?.map(e=>e.memory)},searchResults:{results:o.searchResults.results.map(e=>({memory:e.memory}))}}),d=r===`profile`?``:`Search results for user's ${a===`chat`?`recent message`:`input`}: \n${o.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`,f=`${u}\n${d}`.trim();return f&&n.debug(`Memory content preview for ${a} API`,{content:f,fullLength:f.length}),f},x=async n=>{if(!y)throw Error(`Responses API is not available in this OpenAI client version`);let i=typeof n.input==`string`?n.input:``;if(g!==`profile`&&!i)return r.debug(`No input found for Responses API, skipping memory search`),y.call(e.responses,n);r.info(`Starting memory search for Responses API`,{containerTag:t,conversationId:h,mode:g});let a=[];if(_===`always`&&i?.trim()){let e=h?`Input: ${i}`:i,n=h?`conversation:${h}`:void 0;a.push(f(m,t,e,n,r))}let o=g===`profile`?``:i;a.push(b(o,t,r,g,`responses`));let s=await Promise.all(a),c=s[s.length-1],l=c?`${n.instructions||``}\n\n${c}`.trim():n.instructions;return y.call(e.responses,{...n,instructions:l})},S=async n=>{let i=Array.isArray(n.messages)?n.messages:[];if(g!==`profile`&&!c(i))return r.debug(`No user message found, skipping memory search`),v.call(e.chat.completions,n);r.info(`Starting memory search`,{containerTag:t,conversationId:h,mode:g});let a=[];if(_===`always`){let e=c(i);if(e?.trim()){let n=h?d(i):e,o=h?`conversation:${h}`:void 0;a.push(f(m,t,n,o,r))}}a.push(u(i,t,r,g,p));let o=await Promise.all(a),s=o[o.length-1];return v.call(e.chat.completions,{...n,messages:s})};return e.chat.completions.create=S,y&&(e.responses.create=x),e}const m={searchMemories:{name:`searchMemories`,description:n.searchMemories,parameters:{type:`object`,properties:{informationToGet:{type:`string`,description:t.informationToGet},includeFullDocs:{type:`boolean`,description:t.includeFullDocs,default:e.includeFullDocs},limit:{type:`number`,description:t.limit,default:e.limit}},required:[`informationToGet`]}},addMemory:{name:`addMemory`,description:n.addMemory,parameters:{type:`object`,properties:{memory:{type:`string`,description:t.memory}},required:[`memory`]}}};function h(e,t){let n=new o({apiKey:e,...t?.baseUrl&&{baseURL:t.baseUrl}}),i=r(t);return{client:n,containerTags:i}}function g(t,n){let{client:r,containerTags:i}=h(t,n);return async function({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:a=e.limit}){try{let o=await r.search.execute({q:t,containerTags:i,limit:a,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:o.results,count:o.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function _(e,t){let{client:n,containerTags:r}=h(e,t);return async function({memory:e}){try{let t={};return{success:!0,memory:await n.memories.add({content:e,containerTags:r,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function v(e,t){let n=g(e,t),r=_(e,t);return{searchMemories:n,addMemory:r}}function y(){return[{type:`function`,function:m.searchMemories},{type:`function`,function:m.addMemory}]}function b(e,t){let n=v(e,t);return async function(e){let t=e.function.name,r=JSON.parse(e.function.arguments);switch(t){case`searchMemories`:return JSON.stringify(await n.searchMemories(r));case`addMemory`:return JSON.stringify(await n.addMemory(r));default:return JSON.stringify({success:!1,error:`Unknown function: ${t}`})}}}function x(e,t){let n=b(e,t);return async function(e){return await Promise.all(e.map(async e=>{let t=await n(e);return{tool_call_id:e.id,role:`tool`,content:t}}))}}function S(e,t){let n=g(e,t);return{definition:{type:`function`,function:m.searchMemories},execute:n}}function C(e,t){let n=_(e,t);return{definition:{type:`function`,function:m.addMemory},execute:n}}function w(e,t,n){if(!process.env.SUPERMEMORY_API_KEY)throw Error(`SUPERMEMORY_API_KEY is not set`);let r=n?.conversationId,i=n?.verbose??!1,a=n?.mode??`profile`,o=n?.addMemory??`never`,s=n?.baseUrl;return p(e,t,{conversationId:r,verbose:i,mode:a,addMemory:o,baseUrl:s})}export{_ as createAddMemoryFunction,C as createAddMemoryTool,g as createSearchMemoriesFunction,S as createSearchMemoriesTool,b as createToolCallExecutor,x as createToolCallsExecutor,y as getToolDefinitions,m as memoryToolSchemas,v as supermemoryTools,w as withSupermemory}; | ||
| `),p=async(e,t,n,r,a,o,s,c)=>{try{if(r&&o&&s){let e=r.replace(`conversation:`,``),n=await i({conversationId:e,messages:o.map(e=>({role:e.role,content:typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.filter(e=>e.type===`text`).map(e=>({type:`text`,text:e.text})):``,name:e.name,tool_calls:e.tool_calls,tool_call_id:e.tool_call_id})),containerTags:[t],apiKey:s,baseUrl:c});a.info(`Conversation saved successfully via /v4/conversations`,{containerTag:t,conversationId:e,messageCount:o.length,responseId:n.id});return}let l=await e.memories.add({content:n,containerTags:[t],customId:r});a.info(`Memory saved successfully`,{containerTag:t,customId:r,contentLength:n.length,memoryId:l.id})}catch(e){a.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}};function m(e,t,n){let r=a(n?.verbose??!1),i=c(n?.baseUrl),m=new s({apiKey:process.env.SUPERMEMORY_API_KEY,...i===`https://api.supermemory.ai`?{}:{baseURL:i}}),h=n?.conversationId,g=n?.mode??`profile`,_=n?.addMemory??`never`,v=e.chat.completions.create,y=e.responses?.create,b=async(e,t,n,r,a)=>{let s=await u(t,e,i),c=s.profile.static?.length||0,l=s.profile.dynamic?.length||0;n.info(`Memory search completed for ${a} API`,{containerTag:t,memoryCountStatic:c,memoryCountDynamic:l,queryText:e.substring(0,100)+(e.length>100?`...`:``),mode:r});let d=`${r===`query`?``:o({profile:{static:s.profile.static?.map(e=>e.memory),dynamic:s.profile.dynamic?.map(e=>e.memory)},searchResults:{results:s.searchResults.results.map(e=>({memory:e.memory}))}})}\n${r===`profile`?``:`Search results for user's ${a===`chat`?`recent message`:`input`}: \n${s.searchResults.results.map(e=>`- ${e.memory}`).join(` | ||
| `)}`}`.trim();return d&&n.debug(`Memory content preview for ${a} API`,{content:d,fullLength:d.length}),d},x=async n=>{if(!y)throw Error(`Responses API is not available in this OpenAI client version`);let i=typeof n.input==`string`?n.input:``;if(g!==`profile`&&!i)return r.debug(`No input found for Responses API, skipping memory search`),y.call(e.responses,n);r.info(`Starting memory search for Responses API`,{containerTag:t,conversationId:h,mode:g});let a=[];if(_===`always`&&i?.trim()){let e=h?`Input: ${i}`:i,n=h?`conversation:${h}`:void 0;a.push(p(m,t,e,n,r))}let o=g===`profile`?``:i;a.push(b(o,t,r,g,`responses`));let s=await Promise.all(a),c=s[s.length-1],l=c?`${n.instructions||``}\n\n${c}`.trim():n.instructions;return y.call(e.responses,{...n,instructions:l})},S=async n=>{let a=Array.isArray(n.messages)?n.messages:[];if(g!==`profile`&&!l(a))return r.debug(`No user message found, skipping memory search`),v.call(e.chat.completions,n);r.info(`Starting memory search`,{containerTag:t,conversationId:h,mode:g});let o=[];if(_===`always`){let e=l(a);if(e?.trim()){let n=h?f(a):e,s=h?`conversation:${h}`:void 0;o.push(p(m,t,n,s,r,a,process.env.SUPERMEMORY_API_KEY,i))}}o.push(d(a,t,r,g,i));let s=await Promise.all(o),c=s[s.length-1];return v.call(e.chat.completions,{...n,messages:c})};return e.chat.completions.create=S,y&&(e.responses.create=x),e}const h={searchMemories:{name:`searchMemories`,description:n.searchMemories,parameters:{type:`object`,properties:{informationToGet:{type:`string`,description:t.informationToGet},includeFullDocs:{type:`boolean`,description:t.includeFullDocs,default:r.includeFullDocs},limit:{type:`number`,description:t.limit,default:r.limit}},required:[`informationToGet`]}},addMemory:{name:`addMemory`,description:n.addMemory,parameters:{type:`object`,properties:{memory:{type:`string`,description:t.memory}},required:[`memory`]}}};function g(t,n){return{client:new s({apiKey:t,...n?.baseUrl&&{baseURL:n.baseUrl}}),containerTags:e(n)}}function _(e,t){let{client:n,containerTags:i}=g(e,t);return async function({informationToGet:e,includeFullDocs:t=r.includeFullDocs,limit:a=r.limit}){try{let o=await n.search.execute({q:e,containerTags:i,limit:a,chunkThreshold:r.chunkThreshold,includeFullDocs:t});return{success:!0,results:o.results,count:o.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function v(e,t){let{client:n,containerTags:r}=g(e,t);return async function({memory:e}){try{let t={};return{success:!0,memory:await n.memories.add({content:e,containerTags:r,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function y(e,t){return{searchMemories:_(e,t),addMemory:v(e,t)}}function b(){return[{type:`function`,function:h.searchMemories},{type:`function`,function:h.addMemory}]}function x(e,t){let n=y(e,t);return async function(e){let t=e.function.name,r=JSON.parse(e.function.arguments);switch(t){case`searchMemories`:return JSON.stringify(await n.searchMemories(r));case`addMemory`:return JSON.stringify(await n.addMemory(r));default:return JSON.stringify({success:!1,error:`Unknown function: ${t}`})}}}function S(e,t){let n=x(e,t);return async function(e){return await Promise.all(e.map(async e=>{let t=await n(e);return{tool_call_id:e.id,role:`tool`,content:t}}))}}function C(e,t){let n=_(e,t);return{definition:{type:`function`,function:h.searchMemories},execute:n}}function w(e,t){let n=v(e,t);return{definition:{type:`function`,function:h.addMemory},execute:n}}function T(e,t,n){if(!process.env.SUPERMEMORY_API_KEY)throw Error(`SUPERMEMORY_API_KEY is not set`);let r=n?.conversationId,i=n?.verbose??!1,a=n?.mode??`profile`,o=n?.addMemory??`never`,s=n?.baseUrl;return m(e,t,{conversationId:r,verbose:i,mode:a,addMemory:o,baseUrl:s})}export{v as createAddMemoryFunction,w as createAddMemoryTool,_ as createSearchMemoriesFunction,C as createSearchMemoriesTool,x as createToolCallExecutor,S as createToolCallsExecutor,b as getToolDefinitions,h as memoryToolSchemas,y as supermemoryTools,T as withSupermemory}; |
+1
-1
| { | ||
| "name": "@supermemory/tools", | ||
| "type": "module", | ||
| "version": "1.3.14", | ||
| "version": "1.3.51", | ||
| "description": "Memory tools for AI SDK and OpenAI function calling with supermemory", | ||
@@ -6,0 +6,0 @@ "scripts": { |
-115
| import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js"; | ||
| import Supermemory from "supermemory"; | ||
| import * as ai0 from "ai"; | ||
| import { LanguageModelV2 } from "@ai-sdk/provider"; | ||
| //#region src/vercel/index.d.ts | ||
| interface WrapVercelLanguageModelOptions { | ||
| conversationId?: string; | ||
| verbose?: boolean; | ||
| mode?: "profile" | "query" | "full"; | ||
| addMemory?: "always" | "never"; | ||
| apiKey?: string; | ||
| baseUrl?: string; | ||
| } | ||
| /** | ||
| * Wraps a language model with supermemory middleware to automatically inject relevant memories | ||
| * into the system prompt based on the user's message content. | ||
| * | ||
| * This middleware searches the supermemory API for relevant memories using the container tag | ||
| * and user message, then either appends memories to an existing system prompt or creates | ||
| * a new system prompt with the memories. | ||
| * | ||
| * @param model - The language model to wrap with supermemory capabilities | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation | ||
| * @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false) | ||
| * @param options.mode - Optional mode for memory search: "profile", "query", or "full" (default: "profile") | ||
| * @param options.addMemory - Optional mode for memory search: "always", "never" (default: "never") | ||
| * @param options.apiKey - Optional Supermemory API key to use instead of the environment variable | ||
| * | ||
| * @returns A wrapped language model that automatically includes relevant memories in prompts | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { withSupermemory } from "@supermemory/tools/ai-sdk" | ||
| * import { openai } from "@ai-sdk/openai" | ||
| * | ||
| * const modelWithMemory = withSupermemory(openai("gpt-4"), "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always" | ||
| * }) | ||
| * | ||
| * const result = await generateText({ | ||
| * model: modelWithMemory, | ||
| * messages: [{ role: "user", content: "What's my favorite programming language?" }] | ||
| * }) | ||
| * ``` | ||
| * | ||
| * @throws {Error} When neither `options.apiKey` nor `process.env.SUPERMEMORY_API_KEY` are set | ||
| * @throws {Error} When supermemory API request fails | ||
| */ | ||
| declare const wrapVercelLanguageModel: (model: LanguageModelV2, containerTag: string, options?: WrapVercelLanguageModelOptions) => LanguageModelV2; | ||
| //#endregion | ||
| //#region src/ai-sdk.d.ts | ||
| declare const searchMemoriesTool: (apiKey: string, config?: SupermemoryToolsConfig) => ai0.Tool<{ | ||
| informationToGet: string; | ||
| includeFullDocs: boolean; | ||
| limit: number; | ||
| }, { | ||
| success: boolean; | ||
| results: Supermemory.Search.SearchExecuteResponse.Result[]; | ||
| count: number; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| results?: undefined; | ||
| count?: undefined; | ||
| }>; | ||
| declare const addMemoryTool: (apiKey: string, config?: SupermemoryToolsConfig) => ai0.Tool<{ | ||
| memory: string; | ||
| }, { | ||
| success: boolean; | ||
| memory: Supermemory.Memories.MemoryAddResponse; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| memory?: undefined; | ||
| }>; | ||
| /** | ||
| * Create Supermemory tools for AI SDK | ||
| */ | ||
| declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| searchMemories: ai0.Tool<{ | ||
| informationToGet: string; | ||
| includeFullDocs: boolean; | ||
| limit: number; | ||
| }, { | ||
| success: boolean; | ||
| results: Supermemory.Search.SearchExecuteResponse.Result[]; | ||
| count: number; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| results?: undefined; | ||
| count?: undefined; | ||
| }>; | ||
| addMemory: ai0.Tool<{ | ||
| memory: string; | ||
| }, { | ||
| success: boolean; | ||
| memory: Supermemory.Memories.MemoryAddResponse; | ||
| error?: undefined; | ||
| } | { | ||
| success: boolean; | ||
| error: string; | ||
| memory?: undefined; | ||
| }>; | ||
| }; | ||
| //#endregion | ||
| export { addMemoryTool, searchMemoriesTool, supermemoryTools, wrapVercelLanguageModel as withSupermemory }; |
| import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js"; | ||
| //#region src/claude-memory.d.ts | ||
| interface ClaudeMemoryConfig extends SupermemoryToolsConfig { | ||
| memoryContainerTag?: string; | ||
| } | ||
| interface MemoryCommand { | ||
| command: "view" | "create" | "str_replace" | "insert" | "delete" | "rename"; | ||
| path: string; | ||
| view_range?: [number, number]; | ||
| file_text?: string; | ||
| old_str?: string; | ||
| new_str?: string; | ||
| insert_line?: number; | ||
| insert_text?: string; | ||
| new_path?: string; | ||
| } | ||
| interface MemoryResponse { | ||
| success: boolean; | ||
| content?: string; | ||
| error?: string; | ||
| } | ||
| interface MemoryToolResult { | ||
| type: "tool_result"; | ||
| tool_use_id: string; | ||
| content: string; | ||
| is_error: boolean; | ||
| } | ||
| /** | ||
| * Claude Memory Tool - Client-side implementation | ||
| * Maps Claude's memory tool commands to supermemory document operations | ||
| */ | ||
| declare class ClaudeMemoryTool { | ||
| private client; | ||
| private containerTags; | ||
| private memoryContainerPrefix; | ||
| /** | ||
| * Normalize file path to be used as customId (replace / with --) | ||
| */ | ||
| private normalizePathToCustomId; | ||
| /** | ||
| * Convert customId back to file path (replace -- with /) | ||
| */ | ||
| private customIdToPath; | ||
| constructor(apiKey: string, config?: ClaudeMemoryConfig); | ||
| /** | ||
| * Main method to handle all Claude memory tool commands | ||
| */ | ||
| handleCommand(command: MemoryCommand): Promise<MemoryResponse>; | ||
| /** | ||
| * Handle command and return properly formatted tool result | ||
| */ | ||
| handleCommandForToolResult(command: MemoryCommand, toolUseId: string): Promise<MemoryToolResult>; | ||
| /** | ||
| * View command: List directory contents or read file with optional line range | ||
| */ | ||
| private view; | ||
| /** | ||
| * List directory contents | ||
| */ | ||
| private listDirectory; | ||
| /** | ||
| * Read file contents with optional line range | ||
| */ | ||
| private readFile; | ||
| /** | ||
| * Create command: Create or overwrite a memory file | ||
| */ | ||
| private create; | ||
| /** | ||
| * String replace command: Replace text in existing file | ||
| */ | ||
| private strReplace; | ||
| /** | ||
| * Insert command: Insert text at specific line | ||
| */ | ||
| private insert; | ||
| /** | ||
| * Delete command: Delete memory file | ||
| */ | ||
| private delete; | ||
| /** | ||
| * Rename command: Move/rename memory file | ||
| */ | ||
| private rename; | ||
| /** | ||
| * Helper: Get document by file path | ||
| */ | ||
| private getFileDocument; | ||
| /** | ||
| * Validate that path starts with /memories for security | ||
| */ | ||
| private isValidPath; | ||
| } | ||
| /** | ||
| * Create a Claude memory tool instance | ||
| */ | ||
| declare function createClaudeMemoryTool(apiKey: string, config?: ClaudeMemoryConfig): ClaudeMemoryTool; | ||
| //#endregion | ||
| export { ClaudeMemoryConfig, ClaudeMemoryTool, MemoryCommand, MemoryResponse, MemoryToolResult, createClaudeMemoryTool }; |
| import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js"; | ||
| import Supermemory from "supermemory"; | ||
| import OpenAI from "openai"; | ||
| //#region src/openai/middleware.d.ts | ||
| interface OpenAIMiddlewareOptions { | ||
| conversationId?: string; | ||
| verbose?: boolean; | ||
| mode?: "profile" | "query" | "full"; | ||
| addMemory?: "always" | "never"; | ||
| baseUrl?: string; | ||
| } | ||
| /** | ||
| * Creates SuperMemory middleware for OpenAI clients. | ||
| * | ||
| * This function creates middleware that automatically injects relevant memories | ||
| * into OpenAI chat completions and optionally saves new memories. The middleware | ||
| * can wrap existing OpenAI clients or create new ones with SuperMemory capabilities. | ||
| * | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages for contextual memory generation | ||
| * @param options.verbose - Enable detailed logging of memory operations (default: false) | ||
| * @param options.mode - Memory search mode: "profile" (all memories), "query" (search-based), or "full" (both) (default: "profile") | ||
| * @param options.addMemory - Automatic memory storage mode: "always" or "never" (default: "never") | ||
| * @returns Object with `wrapClient` and `createClient` methods | ||
| * @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const openaiWithSupermemory = createOpenAIMiddleware(openai, "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always", | ||
| * verbose: true | ||
| * }) | ||
| * | ||
| * ``` | ||
| */ | ||
| //#endregion | ||
| //#region src/openai/tools.d.ts | ||
| /** | ||
| * Result types for memory operations | ||
| */ | ||
| interface MemorySearchResult { | ||
| success: boolean; | ||
| results?: Awaited<ReturnType<Supermemory["search"]["execute"]>>["results"]; | ||
| count?: number; | ||
| error?: string; | ||
| } | ||
| interface MemoryAddResult { | ||
| success: boolean; | ||
| memory?: Awaited<ReturnType<Supermemory["memories"]["add"]>>; | ||
| error?: string; | ||
| } | ||
| /** | ||
| * Function schemas for OpenAI function calling | ||
| */ | ||
| declare const memoryToolSchemas: { | ||
| readonly searchMemories: { | ||
| name: string; | ||
| description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| informationToGet: { | ||
| type: string; | ||
| description: "Terms to search for in the user's memories"; | ||
| }; | ||
| includeFullDocs: { | ||
| type: string; | ||
| description: "Whether to include the full document content in the response. Defaults to true for better AI context."; | ||
| default: true; | ||
| }; | ||
| limit: { | ||
| type: string; | ||
| description: "Maximum number of results to return"; | ||
| default: 10; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| readonly addMemory: { | ||
| name: string; | ||
| description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| memory: { | ||
| type: string; | ||
| description: "The text content of the memory to add. This should be a single sentence or a short paragraph."; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| /** | ||
| * Search memories function | ||
| */ | ||
| declare function createSearchMemoriesFunction(apiKey: string, config?: SupermemoryToolsConfig): ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| /** | ||
| * Add memory function | ||
| */ | ||
| declare function createAddMemoryFunction(apiKey: string, config?: SupermemoryToolsConfig): ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| /** | ||
| * Create all memory tools functions | ||
| */ | ||
| declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| searchMemories: ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| addMemory: ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| }; | ||
| /** | ||
| * Get OpenAI function definitions for all memory tools | ||
| */ | ||
| declare function getToolDefinitions(): OpenAI.Chat.Completions.ChatCompletionTool[]; | ||
| /** | ||
| * Execute a tool call based on the function name and arguments | ||
| */ | ||
| declare function createToolCallExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => Promise<string>; | ||
| /** | ||
| * Execute tool calls from OpenAI function calling | ||
| */ | ||
| declare function createToolCallsExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => Promise<OpenAI.Chat.Completions.ChatCompletionToolMessageParam[]>; | ||
| /** | ||
| * Individual tool creators for more granular control | ||
| */ | ||
| declare function createSearchMemoriesTool(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| definition: { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| informationToGet: { | ||
| type: string; | ||
| description: "Terms to search for in the user's memories"; | ||
| }; | ||
| includeFullDocs: { | ||
| type: string; | ||
| description: "Whether to include the full document content in the response. Defaults to true for better AI context."; | ||
| default: true; | ||
| }; | ||
| limit: { | ||
| type: string; | ||
| description: "Maximum number of results to return"; | ||
| default: 10; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| execute: ({ | ||
| informationToGet, | ||
| includeFullDocs, | ||
| limit | ||
| }: { | ||
| informationToGet: string; | ||
| includeFullDocs?: boolean; | ||
| limit?: number; | ||
| }) => Promise<MemorySearchResult>; | ||
| }; | ||
| declare function createAddMemoryTool(apiKey: string, config?: SupermemoryToolsConfig): { | ||
| definition: { | ||
| type: "function"; | ||
| function: { | ||
| name: string; | ||
| description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation."; | ||
| parameters: { | ||
| type: string; | ||
| properties: { | ||
| memory: { | ||
| type: string; | ||
| description: "The text content of the memory to add. This should be a single sentence or a short paragraph."; | ||
| }; | ||
| }; | ||
| required: string[]; | ||
| }; | ||
| }; | ||
| }; | ||
| execute: ({ | ||
| memory | ||
| }: { | ||
| memory: string; | ||
| }) => Promise<MemoryAddResult>; | ||
| }; | ||
| //#endregion | ||
| //#region src/openai/index.d.ts | ||
| /** | ||
| * Wraps an OpenAI client with SuperMemory middleware to automatically inject relevant memories | ||
| * into both Chat Completions and Responses APIs based on the user's input content. | ||
| * | ||
| * For Chat Completions API: Searches for memories using the user message content and injects | ||
| * them into the system prompt (appends to existing or creates new system prompt). | ||
| * | ||
| * For Responses API: Searches for memories using the input parameter and injects them into | ||
| * the instructions parameter (appends to existing or creates new instructions). | ||
| * | ||
| * @param openaiClient - The OpenAI client to wrap with SuperMemory middleware | ||
| * @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID) | ||
| * @param options - Optional configuration options for the middleware | ||
| * @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation | ||
| * @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false) | ||
| * @param options.mode - Optional mode for memory search: "profile" (default), "query", or "full" | ||
| * @param options.addMemory - Optional mode for memory addition: "always", "never" (default) | ||
| * | ||
| * @returns An OpenAI client with SuperMemory middleware injected for both Chat Completions and Responses APIs | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { withSupermemory } from "@supermemory/tools/openai" | ||
| * import OpenAI from "openai" | ||
| * | ||
| * // Create OpenAI client with supermemory middleware | ||
| * const openai = new OpenAI({ | ||
| * apiKey: process.env.OPENAI_API_KEY, | ||
| * }) | ||
| * const openaiWithSupermemory = withSupermemory(openai, "user-123", { | ||
| * conversationId: "conversation-456", | ||
| * mode: "full", | ||
| * addMemory: "always" | ||
| * }) | ||
| * | ||
| * // Use with Chat Completions API - memories injected into system prompt | ||
| * const chatResponse = await openaiWithSupermemory.chat.completions.create({ | ||
| * model: "gpt-4", | ||
| * messages: [ | ||
| * { role: "user", content: "What's my favorite programming language?" } | ||
| * ] | ||
| * }) | ||
| * | ||
| * // Use with Responses API - memories injected into instructions | ||
| * const response = await openaiWithSupermemory.responses.create({ | ||
| * model: "gpt-4o", | ||
| * instructions: "You are a helpful coding assistant", | ||
| * input: "What's my favorite programming language?" | ||
| * }) | ||
| * ``` | ||
| * | ||
| * @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set | ||
| * @throws {Error} When supermemory API request fails | ||
| */ | ||
| declare function withSupermemory(openaiClient: OpenAI, containerTag: string, options?: OpenAIMiddlewareOptions): OpenAI; | ||
| //#endregion | ||
| export { type MemoryAddResult, type MemorySearchResult, type OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory }; |
| import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js"; | ||
| import { OpenAIMiddlewareOptions } from "./index-CSb8j3hw.js"; | ||
| export { type OpenAIMiddlewareOptions, type SupermemoryToolsConfig }; |
| import "../types-B1x7Kbsa.js"; | ||
| import { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory } from "../index-CSb8j3hw.js"; | ||
| export { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory }; |
| const e={searchMemories:`Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.`,addMemory:`Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.`},t={informationToGet:`Terms to search for in the user's memories`,includeFullDocs:`Whether to include the full document content in the response. Defaults to true for better AI context.`,limit:`Maximum number of results to return`,memory:`The text content of the memory to add. This should be a single sentence or a short paragraph.`},n={includeFullDocs:!0,limit:10,chunkThreshold:.6},r={projectPrefix:`sm_project_`,defaultTags:[`sm_project_default`]};function i(e){return e?.projectId?[`${r.projectPrefix}${e.projectId}`]:e?.containerTags??r.defaultTags}export{n as DEFAULT_VALUES,t as PARAMETER_DESCRIPTIONS,e as TOOL_DESCRIPTIONS,i as getContainerTags}; |
| //#region src/types.d.ts | ||
| /** | ||
| * Supermemory configuration | ||
| * Only one of `projectId` or `containerTags` can be provided. | ||
| */ | ||
| interface SupermemoryToolsConfig { | ||
| baseUrl?: string; | ||
| containerTags?: string[]; | ||
| projectId?: string; | ||
| } | ||
| //#endregion | ||
| export { SupermemoryToolsConfig }; |
| const e=e=>e?{debug:(e,t)=>{console.log(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},info:(e,t)=>{console.log(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{console.warn(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{console.error(`[supermemory] ${e}`,t?JSON.stringify(t,null,2):``)}}:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function t(e){let t=[];return e.profile.static&&e.profile.static.length>0&&(t.push(`## Static Profile`),t.push(e.profile.static.map(e=>`- ${e}`).join(` | ||
| `))),e.profile.dynamic&&e.profile.dynamic.length>0&&(t.push(`## Dynamic Profile`),t.push(e.profile.dynamic.map(e=>`- ${e}`).join(` | ||
| `))),t.join(` | ||
| `)}const n=e=>e.prompt.slice().reverse().find(e=>e.role===`user`)?.content.filter(e=>e.type===`text`).map(e=>e.text).join(` `),r=e=>e.split(`User Supermemories: `)[0];export{t as convertProfileToMarkdown,e as createLogger,r as filterOutSupermemories,n as getLastUserMessage}; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
57900
2.15%553
0.18%14
7.69%4
33.33%