@theokit/memory-supermemory 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +0 -24
- package/dist/index.d.ts +0 -24
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
package/dist/index.cjs
CHANGED
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["MemoryAdapterError","ADAPTER_ID","mkMemoryId","extractRawId","SupermemoryClient","definePlugin"],"mappings":";;;;;;;;;;AAeA,IAAM,UAAA,GAAa,kBAAA;AACnB,IAAM,UAAA,GAAa,aAAA;AAEZ,SAAS,kBAAA,CAAmB,OAAe,SAAA,EAA2B;AAC3E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,EAAG;AACnD,IAAA,MAAM,IAAIA,sBAAA,CAAmB,CAAA,qBAAA,EAAwB,SAAS,CAAA,2BAAA,CAAA,EAA+B;AAAA,MAC3F,SAAA,EAAW,UAAA;AAAA,MACX,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,KAAK,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAIA,sBAAA;AAAA,MACR,CAAA,qBAAA,EAAwB,SAAS,CAAA,EAAA,EAAK,KAAK,CAAA,oDAAA,CAAA;AAAA,MAC3C,EAAE,SAAA,EAAW,UAAA,EAAY,IAAA,EAAM,eAAA;AAAgB,KACjD;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AASO,SAAS,kBAAA,CAAmB,KAAoB,MAAA,EAA0B;AAC/E,EAAA,MAAM,UAAA,GAA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AAgB,MAAM,IAAI,kBAAA,CAAmB,OAAO;AAAA,GACrD,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * `MemoryContext` → Supermemory containerTags translation (T3.2).\n *\n * EC-C fix: every component runs through a strict identifier sanitizer\n * (regex `^[a-zA-Z0-9_-]+$`) before being joined with `:`. Rejects with\n * `MemoryAdapterError(code: \"invalid_input\")` on invalid input, so a\n * value like `userId: \"user:123\"` cannot silently land in a different\n * bucket via tag mis-parsing.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst SAFE_IDENT = /^[a-zA-Z0-9_-]+$/;\nconst ADAPTER_ID = \"supermemory\";\n\nexport function sanitizeIdentifier(value: string, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new MemoryAdapterError(`Supermemory adapter: ${fieldName} must be a non-empty string`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n if (!SAFE_IDENT.test(value)) {\n throw new MemoryAdapterError(\n `Supermemory adapter: ${fieldName} \"${value}\" contains invalid characters (allowed: a-zA-Z0-9_-)`,\n { adapterId: ADAPTER_ID, code: \"invalid_input\" },\n );\n }\n return value;\n}\n\n/**\n * Build the array of containerTags for `documents.add`. Each component\n * is sanitized; collisions across tag namespaces (user/agent/tenant/tag)\n * are intentional — Supermemory treats containerTags as a set.\n *\n * @internal\n */\nexport function buildContainerTags(ctx: MemoryContext, prefix: string): string[] {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n const tags: string[] = [`${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`];\n if (ctx.agentId !== undefined) {\n tags.push(`${safePrefix}:agent:${sanitizeIdentifier(ctx.agentId, \"agentId\")}`);\n }\n if (ctx.tenantId !== undefined) {\n tags.push(`${safePrefix}:tenant:${sanitizeIdentifier(ctx.tenantId, \"tenantId\")}`);\n }\n if (ctx.tags !== undefined) {\n for (const t of ctx.tags) {\n tags.push(`${safePrefix}:tag:${sanitizeIdentifier(t, \"tag\")}`);\n }\n }\n return tags;\n}\n\n/**\n * Pick the primary containerTag for `search.memories` (which takes a\n * single string, not an array). The user tag is canonical.\n *\n * @internal\n */\nexport function primaryContainerTag(ctx: MemoryContext, prefix: string): string {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n return `${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`;\n}\n","/**\n * SupermemoryAdapter — `@theokit-memory-supermemory` core (T3.2, ADR D141).\n *\n * Wraps `supermemory` SDK v4. Implements `MemoryAdapter` so the SDK's\n * `pre_user_send` / `post_assistant_reply` hooks (D145) and\n * `agent.memory.*` direct API (D142) work end-to-end against Supermemory's\n * managed memory + RAG service.\n *\n * @public\n */\n\nimport {\n extractRawId,\n type MemoryAdapter,\n type MemoryAdapterCapabilities,\n MemoryAdapterError,\n type MemoryContext,\n type MemoryFact,\n type MemoryId,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport type Supermemory from \"supermemory\";\nimport SupermemoryClient from \"supermemory\";\n\nimport { buildContainerTags, primaryContainerTag } from \"./translate.js\";\n\n/** Configuration accepted by the `supermemoryMemory(...)` factory. @public */\nexport interface SupermemoryAdapterOptions {\n /** Supermemory API key. Falls back to `SUPERMEMORY_API_KEY`. */\n apiKey: string;\n /** Base URL override for self-hosted Supermemory deployments. */\n baseUrl?: string;\n /** Prefix for every containerTag (default `\"theokit\"`). Useful for test isolation (EC-S). */\n containerTagPrefix?: string;\n}\n\nconst ADAPTER_ID = \"supermemory\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/**\n * SDK-internal adapter class. Construct via `supermemoryMemory(...)`\n * factory from `./index.ts`, not directly.\n *\n * @internal\n */\nexport class SupermemoryAdapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: SupermemoryAdapterOptions;\n #client?: Supermemory;\n\n constructor(opts: SupermemoryAdapterOptions) {\n this.#opts = opts;\n }\n\n isAvailable(): boolean {\n return typeof this.#opts.apiKey === \"string\" && this.#opts.apiKey.length > 0;\n }\n\n async initialize(): Promise<void> {\n // Lazy: defer the actual client construction until first call.\n // initialize() is idempotent — see EC-3 / EC-I.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n const text = this.#renderContent(content);\n if (text.length === 0) {\n throw new MemoryAdapterError(\"write: empty content\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n const containerTags = buildContainerTags(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().documents.add({\n content: text,\n containerTags,\n ...(ctx.metadata !== undefined ? { metadata: ctx.metadata as Record<string, string> } : {}),\n });\n return mkMemoryId(ADAPTER_ID, resp.id);\n } catch (err) {\n throw this.#translateError(err, \"write\");\n }\n }\n\n async recall(query: string, ctx: MemoryContext, k = 10): Promise<MemoryFact[]> {\n if (k <= 0) return [];\n const containerTag = primaryContainerTag(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().search.memories({\n q: query,\n containerTag,\n limit: k,\n rerank: true,\n });\n const results = resp.results ?? [];\n return results.map(this.#mapResult);\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().documents.delete(rawId);\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a fact about the user or context to Supermemory long-term memory. \" +\n \"Returns the stored memory ID.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Fact text to persist verbatim.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description:\n \"Retrieve up to k semantically relevant facts from Supermemory long-term memory. \" +\n \"Returns an array of {id, content, score, createdAt} objects.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Free-text query to search memory.\" },\n k: {\n type: \"integer\",\n minimum: 1,\n maximum: 50,\n description: \"Max results (default 10).\",\n },\n },\n required: [\"query\"],\n },\n },\n ];\n }\n\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ctx: MemoryContext,\n ): Promise<string> {\n if (name === \"memory_write\") {\n const content = String(args.content ?? \"\");\n const id = await this.write(content, ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const query = String(args.query ?? \"\");\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(query, ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n throw new MemoryAdapterError(`Unknown tool name: ${name}`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n\n async shutdown(): Promise<void> {\n this.#client = undefined;\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #prefix(): string {\n return this.#opts.containerTagPrefix ?? \"theokit\";\n }\n\n #renderContent(content: string | MemoryTurnMessage[]): string {\n if (typeof content === \"string\") return content.trim();\n return content\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\")\n .trim();\n }\n\n #mapResult = (r: unknown): MemoryFact => {\n const obj = (r as Record<string, unknown>) ?? {};\n // SDK shape: { memory?: { id, content, ... }, score, ... } or chunk shape.\n const memory = (obj.memory as Record<string, unknown> | undefined) ?? obj;\n const rawId = String(memory.id ?? obj.id ?? \"\");\n const content = String(memory.content ?? memory.text ?? obj.content ?? \"\");\n const score = typeof obj.score === \"number\" ? obj.score : undefined;\n const createdAt = typeof memory.createdAt === \"string\" ? memory.createdAt : undefined;\n return {\n id: mkMemoryId(ADAPTER_ID, rawId),\n content,\n ...(score !== undefined ? { score } : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n };\n };\n\n #sdk(): Supermemory {\n if (this.#client === undefined) {\n this.#client = new SupermemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.baseUrl !== undefined ? { baseURL: this.#opts.baseUrl } : {}),\n });\n }\n return this.#client;\n }\n\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) return err;\n const status =\n (err as { status?: number; statusCode?: number })?.status ??\n (err as { statusCode?: number })?.statusCode;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Supermemory auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n return new MemoryAdapterError(`Supermemory rate limited (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"rate_limited\",\n cause: err,\n });\n }\n if (status === 404) {\n return new MemoryAdapterError(`Supermemory not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n return new MemoryAdapterError(`Supermemory network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Supermemory error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","/**\n * `@theokit/memory-supermemory` — Supermemory memory adapter for @theokit/sdk.\n *\n * Usage:\n *\n * ```ts\n * import { Agent } from \"@theokit/sdk\";\n * import { supermemoryMemory } from \"@theokit/memory-supermemory\";\n *\n * const agent = await Agent.create({\n * apiKey: process.env.OPENROUTER_API_KEY,\n * model: { id: \"openai/gpt-4o-mini\" },\n * local: {},\n * plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],\n * memoryContext: { userId: \"demo\" },\n * });\n *\n * await agent.memory.write(\"User likes Brazilian jazz\", { userId: \"demo\" });\n * const facts = await agent.memory.recall(\"music preferences\", { userId: \"demo\" });\n * ```\n *\n * @public\n */\n\nimport type { Plugin } from \"@theokit/sdk\";\nimport { definePlugin } from \"@theokit/sdk\";\n\nimport { SupermemoryAdapter, type SupermemoryAdapterOptions } from \"./adapter.js\";\n\nexport type { SupermemoryAdapterOptions } from \"./adapter.js\";\n\n/**\n * Build a `Plugin { kind: \"memory\" }` ready to pass to\n * `Agent.create({ plugins: [...] })`.\n *\n * @public\n */\nexport function supermemoryMemory(options: SupermemoryAdapterOptions): Plugin {\n return definePlugin({\n name: \"@theokit/memory-supermemory\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new SupermemoryAdapter(options),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["MemoryAdapterError","ADAPTER_ID","mkMemoryId","extractRawId","SupermemoryClient","Plugin"],"mappings":";;;;;;;;;;AAeA,IAAM,UAAA,GAAa,kBAAA;AACnB,IAAM,UAAA,GAAa,aAAA;AAEZ,SAAS,kBAAA,CAAmB,OAAe,SAAA,EAA2B;AAC3E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,EAAG;AACnD,IAAA,MAAM,IAAIA,sBAAA,CAAmB,CAAA,qBAAA,EAAwB,SAAS,CAAA,2BAAA,CAAA,EAA+B;AAAA,MAC3F,SAAA,EAAW,UAAA;AAAA,MACX,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,KAAK,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAIA,sBAAA;AAAA,MACR,CAAA,qBAAA,EAAwB,SAAS,CAAA,EAAA,EAAK,KAAK,CAAA,oDAAA,CAAA;AAAA,MAC3C,EAAE,SAAA,EAAW,UAAA,EAAY,IAAA,EAAM,eAAA;AAAgB,KACjD;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AASO,SAAS,kBAAA,CAAmB,KAAoB,MAAA,EAA0B;AAC/E,EAAA,MA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AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,kBAAA,CAAmB,OAAO;AAAA,GACrD,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * `MemoryContext` → Supermemory containerTags translation (T3.2).\n *\n * EC-C fix: every component runs through a strict identifier sanitizer\n * (regex `^[a-zA-Z0-9_-]+$`) before being joined with `:`. Rejects with\n * `MemoryAdapterError(code: \"invalid_input\")` on invalid input, so a\n * value like `userId: \"user:123\"` cannot silently land in a different\n * bucket via tag mis-parsing.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst SAFE_IDENT = /^[a-zA-Z0-9_-]+$/;\nconst ADAPTER_ID = \"supermemory\";\n\nexport function sanitizeIdentifier(value: string, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new MemoryAdapterError(`Supermemory adapter: ${fieldName} must be a non-empty string`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n if (!SAFE_IDENT.test(value)) {\n throw new MemoryAdapterError(\n `Supermemory adapter: ${fieldName} \"${value}\" contains invalid characters (allowed: a-zA-Z0-9_-)`,\n { adapterId: ADAPTER_ID, code: \"invalid_input\" },\n );\n }\n return value;\n}\n\n/**\n * Build the array of containerTags for `documents.add`. Each component\n * is sanitized; collisions across tag namespaces (user/agent/tenant/tag)\n * are intentional — Supermemory treats containerTags as a set.\n *\n * @internal\n */\nexport function buildContainerTags(ctx: MemoryContext, prefix: string): string[] {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n const tags: string[] = [`${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`];\n if (ctx.agentId !== undefined) {\n tags.push(`${safePrefix}:agent:${sanitizeIdentifier(ctx.agentId, \"agentId\")}`);\n }\n if (ctx.tenantId !== undefined) {\n tags.push(`${safePrefix}:tenant:${sanitizeIdentifier(ctx.tenantId, \"tenantId\")}`);\n }\n if (ctx.tags !== undefined) {\n for (const t of ctx.tags) {\n tags.push(`${safePrefix}:tag:${sanitizeIdentifier(t, \"tag\")}`);\n }\n }\n return tags;\n}\n\n/**\n * Pick the primary containerTag for `search.memories` (which takes a\n * single string, not an array). The user tag is canonical.\n *\n * @internal\n */\nexport function primaryContainerTag(ctx: MemoryContext, prefix: string): string {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n return `${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`;\n}\n","/**\n * SupermemoryAdapter — `@theokit-memory-supermemory` core (T3.2, ADR D141).\n *\n * Wraps `supermemory` SDK v4. Implements `MemoryAdapter` so the SDK's\n * `pre_user_send` / `post_assistant_reply` hooks (D145) and\n * `agent.memory.*` direct API (D142) work end-to-end against Supermemory's\n * managed memory + RAG service.\n *\n * @public\n */\n\nimport {\n extractRawId,\n type MemoryAdapter,\n type MemoryAdapterCapabilities,\n MemoryAdapterError,\n type MemoryContext,\n type MemoryFact,\n type MemoryId,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport type Supermemory from \"supermemory\";\nimport SupermemoryClient from \"supermemory\";\n\nimport { buildContainerTags, primaryContainerTag } from \"./translate.js\";\n\n/** Configuration accepted by the `supermemoryMemory(...)` factory. @public */\nexport interface SupermemoryAdapterOptions {\n /** Supermemory API key. Falls back to `SUPERMEMORY_API_KEY`. */\n apiKey: string;\n /** Base URL override for self-hosted Supermemory deployments. */\n baseUrl?: string;\n /** Prefix for every containerTag (default `\"theokit\"`). Useful for test isolation (EC-S). */\n containerTagPrefix?: string;\n}\n\nconst ADAPTER_ID = \"supermemory\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/**\n * SDK-internal adapter class. Construct via `supermemoryMemory(...)`\n * factory from `./index.ts`, not directly.\n *\n * @internal\n */\nexport class SupermemoryAdapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: SupermemoryAdapterOptions;\n #client?: Supermemory;\n\n constructor(opts: SupermemoryAdapterOptions) {\n this.#opts = opts;\n }\n\n isAvailable(): boolean {\n return typeof this.#opts.apiKey === \"string\" && this.#opts.apiKey.length > 0;\n }\n\n async initialize(): Promise<void> {\n // Lazy: defer the actual client construction until first call.\n // initialize() is idempotent — see EC-3 / EC-I.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n const text = this.#renderContent(content);\n if (text.length === 0) {\n throw new MemoryAdapterError(\"write: empty content\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n const containerTags = buildContainerTags(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().documents.add({\n content: text,\n containerTags,\n ...(ctx.metadata !== undefined ? { metadata: ctx.metadata as Record<string, string> } : {}),\n });\n return mkMemoryId(ADAPTER_ID, resp.id);\n } catch (err) {\n throw this.#translateError(err, \"write\");\n }\n }\n\n async recall(query: string, ctx: MemoryContext, k = 10): Promise<MemoryFact[]> {\n if (k <= 0) return [];\n const containerTag = primaryContainerTag(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().search.memories({\n q: query,\n containerTag,\n limit: k,\n rerank: true,\n });\n const results = resp.results ?? [];\n return results.map(this.#mapResult);\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().documents.delete(rawId);\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a fact about the user or context to Supermemory long-term memory. \" +\n \"Returns the stored memory ID.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Fact text to persist verbatim.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description:\n \"Retrieve up to k semantically relevant facts from Supermemory long-term memory. \" +\n \"Returns an array of {id, content, score, createdAt} objects.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Free-text query to search memory.\" },\n k: {\n type: \"integer\",\n minimum: 1,\n maximum: 50,\n description: \"Max results (default 10).\",\n },\n },\n required: [\"query\"],\n },\n },\n ];\n }\n\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ctx: MemoryContext,\n ): Promise<string> {\n if (name === \"memory_write\") {\n const content = String(args.content ?? \"\");\n const id = await this.write(content, ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const query = String(args.query ?? \"\");\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(query, ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n throw new MemoryAdapterError(`Unknown tool name: ${name}`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n\n async shutdown(): Promise<void> {\n this.#client = undefined;\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #prefix(): string {\n return this.#opts.containerTagPrefix ?? \"theokit\";\n }\n\n #renderContent(content: string | MemoryTurnMessage[]): string {\n if (typeof content === \"string\") return content.trim();\n return content\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\")\n .trim();\n }\n\n #mapResult = (r: unknown): MemoryFact => {\n const obj = (r as Record<string, unknown>) ?? {};\n // SDK shape: { memory?: { id, content, ... }, score, ... } or chunk shape.\n const memory = (obj.memory as Record<string, unknown> | undefined) ?? obj;\n const rawId = String(memory.id ?? obj.id ?? \"\");\n const content = String(memory.content ?? memory.text ?? obj.content ?? \"\");\n const score = typeof obj.score === \"number\" ? obj.score : undefined;\n const createdAt = typeof memory.createdAt === \"string\" ? memory.createdAt : undefined;\n return {\n id: mkMemoryId(ADAPTER_ID, rawId),\n content,\n ...(score !== undefined ? { score } : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n };\n };\n\n #sdk(): Supermemory {\n if (this.#client === undefined) {\n this.#client = new SupermemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.baseUrl !== undefined ? { baseURL: this.#opts.baseUrl } : {}),\n });\n }\n return this.#client;\n }\n\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) return err;\n const status =\n (err as { status?: number; statusCode?: number })?.status ??\n (err as { statusCode?: number })?.statusCode;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Supermemory auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n return new MemoryAdapterError(`Supermemory rate limited (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"rate_limited\",\n cause: err,\n });\n }\n if (status === 404) {\n return new MemoryAdapterError(`Supermemory not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n return new MemoryAdapterError(`Supermemory network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Supermemory error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","import { Plugin } from \"@theokit/sdk\";\n\nimport { SupermemoryAdapter, type SupermemoryAdapterOptions } from \"./adapter.js\";\n\nexport type { SupermemoryAdapterOptions } from \"./adapter.js\";\n\n/**\n * Build a `Plugin { kind: \"memory\" }` ready to pass to\n * `Agent.create({ plugins: [...] })`.\n *\n * @public\n */\nexport function supermemoryMemory(options: SupermemoryAdapterOptions): Plugin {\n return Plugin.create({\n name: \"@theokit/memory-supermemory\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new SupermemoryAdapter(options),\n });\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -20,30 +20,6 @@ interface SupermemoryAdapterOptions {
|
|
|
20
20
|
containerTagPrefix?: string;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
/**
|
|
24
|
-
* `@theokit/memory-supermemory` — Supermemory memory adapter for @theokit/sdk.
|
|
25
|
-
*
|
|
26
|
-
* Usage:
|
|
27
|
-
*
|
|
28
|
-
* ```ts
|
|
29
|
-
* import { Agent } from "@theokit/sdk";
|
|
30
|
-
* import { supermemoryMemory } from "@theokit/memory-supermemory";
|
|
31
|
-
*
|
|
32
|
-
* const agent = await Agent.create({
|
|
33
|
-
* apiKey: process.env.OPENROUTER_API_KEY,
|
|
34
|
-
* model: { id: "openai/gpt-4o-mini" },
|
|
35
|
-
* local: {},
|
|
36
|
-
* plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],
|
|
37
|
-
* memoryContext: { userId: "demo" },
|
|
38
|
-
* });
|
|
39
|
-
*
|
|
40
|
-
* await agent.memory.write("User likes Brazilian jazz", { userId: "demo" });
|
|
41
|
-
* const facts = await agent.memory.recall("music preferences", { userId: "demo" });
|
|
42
|
-
* ```
|
|
43
|
-
*
|
|
44
|
-
* @public
|
|
45
|
-
*/
|
|
46
|
-
|
|
47
23
|
/**
|
|
48
24
|
* Build a `Plugin { kind: "memory" }` ready to pass to
|
|
49
25
|
* `Agent.create({ plugins: [...] })`.
|
package/dist/index.d.ts
CHANGED
|
@@ -20,30 +20,6 @@ interface SupermemoryAdapterOptions {
|
|
|
20
20
|
containerTagPrefix?: string;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
/**
|
|
24
|
-
* `@theokit/memory-supermemory` — Supermemory memory adapter for @theokit/sdk.
|
|
25
|
-
*
|
|
26
|
-
* Usage:
|
|
27
|
-
*
|
|
28
|
-
* ```ts
|
|
29
|
-
* import { Agent } from "@theokit/sdk";
|
|
30
|
-
* import { supermemoryMemory } from "@theokit/memory-supermemory";
|
|
31
|
-
*
|
|
32
|
-
* const agent = await Agent.create({
|
|
33
|
-
* apiKey: process.env.OPENROUTER_API_KEY,
|
|
34
|
-
* model: { id: "openai/gpt-4o-mini" },
|
|
35
|
-
* local: {},
|
|
36
|
-
* plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],
|
|
37
|
-
* memoryContext: { userId: "demo" },
|
|
38
|
-
* });
|
|
39
|
-
*
|
|
40
|
-
* await agent.memory.write("User likes Brazilian jazz", { userId: "demo" });
|
|
41
|
-
* const facts = await agent.memory.recall("music preferences", { userId: "demo" });
|
|
42
|
-
* ```
|
|
43
|
-
*
|
|
44
|
-
* @public
|
|
45
|
-
*/
|
|
46
|
-
|
|
47
23
|
/**
|
|
48
24
|
* Build a `Plugin { kind: "memory" }` ready to pass to
|
|
49
25
|
* `Agent.create({ plugins: [...] })`.
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Plugin, MemoryAdapterError, mkMemoryId, extractRawId } from '@theokit/sdk';
|
|
2
2
|
import SupermemoryClient from 'supermemory';
|
|
3
3
|
|
|
4
4
|
// src/index.ts
|
|
@@ -232,7 +232,7 @@ var SupermemoryAdapter = class {
|
|
|
232
232
|
|
|
233
233
|
// src/index.ts
|
|
234
234
|
function supermemoryMemory(options) {
|
|
235
|
-
return
|
|
235
|
+
return Plugin.create({
|
|
236
236
|
name: "@theokit/memory-supermemory",
|
|
237
237
|
version: "0.1.0",
|
|
238
238
|
kind: "memory",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["ADAPTER_ID","MemoryAdapterError"],"mappings":";;;;AAeA,IAAM,UAAA,GAAa,kBAAA;AACnB,IAAM,UAAA,GAAa,aAAA;AAEZ,SAAS,kBAAA,CAAmB,OAAe,SAAA,EAA2B;AAC3E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,EAAG;AACnD,IAAA,MAAM,I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AAA,QAC7E,SAAA,EAAWD,WAAAA;AAAA,QACX,IAAA,EAAM,SAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAIC,kBAAAA,CAAmB,CAAA,mBAAA,EAAsB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MACrE,SAAA,EAAWD,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;ACnOO,SAAS,kBAAkB,OAAA,EAA4C;AAC5E,EAAA,OAAO,YAAA,CAAa;AAAA,IAClB,IAAA,EAAM,6BAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,kBAAA,CAAmB,OAAO;AAAA,GACrD,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * `MemoryContext` → Supermemory containerTags translation (T3.2).\n *\n * EC-C fix: every component runs through a strict identifier sanitizer\n * (regex `^[a-zA-Z0-9_-]+$`) before being joined with `:`. Rejects with\n * `MemoryAdapterError(code: \"invalid_input\")` on invalid input, so a\n * value like `userId: \"user:123\"` cannot silently land in a different\n * bucket via tag mis-parsing.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst SAFE_IDENT = /^[a-zA-Z0-9_-]+$/;\nconst ADAPTER_ID = \"supermemory\";\n\nexport function sanitizeIdentifier(value: string, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new MemoryAdapterError(`Supermemory adapter: ${fieldName} must be a non-empty string`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n if (!SAFE_IDENT.test(value)) {\n throw new MemoryAdapterError(\n `Supermemory adapter: ${fieldName} \"${value}\" contains invalid characters (allowed: a-zA-Z0-9_-)`,\n { adapterId: ADAPTER_ID, code: \"invalid_input\" },\n );\n }\n return value;\n}\n\n/**\n * Build the array of containerTags for `documents.add`. Each component\n * is sanitized; collisions across tag namespaces (user/agent/tenant/tag)\n * are intentional — Supermemory treats containerTags as a set.\n *\n * @internal\n */\nexport function buildContainerTags(ctx: MemoryContext, prefix: string): string[] {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n const tags: string[] = [`${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`];\n if (ctx.agentId !== undefined) {\n tags.push(`${safePrefix}:agent:${sanitizeIdentifier(ctx.agentId, \"agentId\")}`);\n }\n if (ctx.tenantId !== undefined) {\n tags.push(`${safePrefix}:tenant:${sanitizeIdentifier(ctx.tenantId, \"tenantId\")}`);\n }\n if (ctx.tags !== undefined) {\n for (const t of ctx.tags) {\n tags.push(`${safePrefix}:tag:${sanitizeIdentifier(t, \"tag\")}`);\n }\n }\n return tags;\n}\n\n/**\n * Pick the primary containerTag for `search.memories` (which takes a\n * single string, not an array). The user tag is canonical.\n *\n * @internal\n */\nexport function primaryContainerTag(ctx: MemoryContext, prefix: string): string {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n return `${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`;\n}\n","/**\n * SupermemoryAdapter — `@theokit-memory-supermemory` core (T3.2, ADR D141).\n *\n * Wraps `supermemory` SDK v4. Implements `MemoryAdapter` so the SDK's\n * `pre_user_send` / `post_assistant_reply` hooks (D145) and\n * `agent.memory.*` direct API (D142) work end-to-end against Supermemory's\n * managed memory + RAG service.\n *\n * @public\n */\n\nimport {\n extractRawId,\n type MemoryAdapter,\n type MemoryAdapterCapabilities,\n MemoryAdapterError,\n type MemoryContext,\n type MemoryFact,\n type MemoryId,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport type Supermemory from \"supermemory\";\nimport SupermemoryClient from \"supermemory\";\n\nimport { buildContainerTags, primaryContainerTag } from \"./translate.js\";\n\n/** Configuration accepted by the `supermemoryMemory(...)` factory. @public */\nexport interface SupermemoryAdapterOptions {\n /** Supermemory API key. Falls back to `SUPERMEMORY_API_KEY`. */\n apiKey: string;\n /** Base URL override for self-hosted Supermemory deployments. */\n baseUrl?: string;\n /** Prefix for every containerTag (default `\"theokit\"`). Useful for test isolation (EC-S). */\n containerTagPrefix?: string;\n}\n\nconst ADAPTER_ID = \"supermemory\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/**\n * SDK-internal adapter class. Construct via `supermemoryMemory(...)`\n * factory from `./index.ts`, not directly.\n *\n * @internal\n */\nexport class SupermemoryAdapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: SupermemoryAdapterOptions;\n #client?: Supermemory;\n\n constructor(opts: SupermemoryAdapterOptions) {\n this.#opts = opts;\n }\n\n isAvailable(): boolean {\n return typeof this.#opts.apiKey === \"string\" && this.#opts.apiKey.length > 0;\n }\n\n async initialize(): Promise<void> {\n // Lazy: defer the actual client construction until first call.\n // initialize() is idempotent — see EC-3 / EC-I.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n const text = this.#renderContent(content);\n if (text.length === 0) {\n throw new MemoryAdapterError(\"write: empty content\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n const containerTags = buildContainerTags(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().documents.add({\n content: text,\n containerTags,\n ...(ctx.metadata !== undefined ? { metadata: ctx.metadata as Record<string, string> } : {}),\n });\n return mkMemoryId(ADAPTER_ID, resp.id);\n } catch (err) {\n throw this.#translateError(err, \"write\");\n }\n }\n\n async recall(query: string, ctx: MemoryContext, k = 10): Promise<MemoryFact[]> {\n if (k <= 0) return [];\n const containerTag = primaryContainerTag(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().search.memories({\n q: query,\n containerTag,\n limit: k,\n rerank: true,\n });\n const results = resp.results ?? [];\n return results.map(this.#mapResult);\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().documents.delete(rawId);\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a fact about the user or context to Supermemory long-term memory. \" +\n \"Returns the stored memory ID.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Fact text to persist verbatim.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description:\n \"Retrieve up to k semantically relevant facts from Supermemory long-term memory. \" +\n \"Returns an array of {id, content, score, createdAt} objects.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Free-text query to search memory.\" },\n k: {\n type: \"integer\",\n minimum: 1,\n maximum: 50,\n description: \"Max results (default 10).\",\n },\n },\n required: [\"query\"],\n },\n },\n ];\n }\n\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ctx: MemoryContext,\n ): Promise<string> {\n if (name === \"memory_write\") {\n const content = String(args.content ?? \"\");\n const id = await this.write(content, ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const query = String(args.query ?? \"\");\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(query, ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n throw new MemoryAdapterError(`Unknown tool name: ${name}`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n\n async shutdown(): Promise<void> {\n this.#client = undefined;\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #prefix(): string {\n return this.#opts.containerTagPrefix ?? \"theokit\";\n }\n\n #renderContent(content: string | MemoryTurnMessage[]): string {\n if (typeof content === \"string\") return content.trim();\n return content\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\")\n .trim();\n }\n\n #mapResult = (r: unknown): MemoryFact => {\n const obj = (r as Record<string, unknown>) ?? {};\n // SDK shape: { memory?: { id, content, ... }, score, ... } or chunk shape.\n const memory = (obj.memory as Record<string, unknown> | undefined) ?? obj;\n const rawId = String(memory.id ?? obj.id ?? \"\");\n const content = String(memory.content ?? memory.text ?? obj.content ?? \"\");\n const score = typeof obj.score === \"number\" ? obj.score : undefined;\n const createdAt = typeof memory.createdAt === \"string\" ? memory.createdAt : undefined;\n return {\n id: mkMemoryId(ADAPTER_ID, rawId),\n content,\n ...(score !== undefined ? { score } : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n };\n };\n\n #sdk(): Supermemory {\n if (this.#client === undefined) {\n this.#client = new SupermemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.baseUrl !== undefined ? { baseURL: this.#opts.baseUrl } : {}),\n });\n }\n return this.#client;\n }\n\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) return err;\n const status =\n (err as { status?: number; statusCode?: number })?.status ??\n (err as { statusCode?: number })?.statusCode;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Supermemory auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n return new MemoryAdapterError(`Supermemory rate limited (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"rate_limited\",\n cause: err,\n });\n }\n if (status === 404) {\n return new MemoryAdapterError(`Supermemory not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n return new MemoryAdapterError(`Supermemory network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Supermemory error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","/**\n * `@theokit/memory-supermemory` — Supermemory memory adapter for @theokit/sdk.\n *\n * Usage:\n *\n * ```ts\n * import { Agent } from \"@theokit/sdk\";\n * import { supermemoryMemory } from \"@theokit/memory-supermemory\";\n *\n * const agent = await Agent.create({\n * apiKey: process.env.OPENROUTER_API_KEY,\n * model: { id: \"openai/gpt-4o-mini\" },\n * local: {},\n * plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],\n * memoryContext: { userId: \"demo\" },\n * });\n *\n * await agent.memory.write(\"User likes Brazilian jazz\", { userId: \"demo\" });\n * const facts = await agent.memory.recall(\"music preferences\", { userId: \"demo\" });\n * ```\n *\n * @public\n */\n\nimport type { Plugin } from \"@theokit/sdk\";\nimport { definePlugin } from \"@theokit/sdk\";\n\nimport { SupermemoryAdapter, type SupermemoryAdapterOptions } from \"./adapter.js\";\n\nexport type { SupermemoryAdapterOptions } from \"./adapter.js\";\n\n/**\n * Build a `Plugin { kind: \"memory\" }` ready to pass to\n * `Agent.create({ plugins: [...] })`.\n *\n * @public\n */\nexport function supermemoryMemory(options: SupermemoryAdapterOptions): Plugin {\n return definePlugin({\n name: \"@theokit/memory-supermemory\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new SupermemoryAdapter(options),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["ADAPTER_ID","MemoryAdapterError"],"mappings":";;;;AAeA,IAAM,UAAA,GAAa,kBAAA;AACnB,IAAM,UAAA,GAAa,aAAA;AAEZ,SAAS,kBAAA,CAAmB,OAAe,SAAA,EAA2B;AAC3E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,WAAW,CAAA,EAAG;AACnD,IAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,qBAAA,E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AAA,QACX,IAAA,EAAM,SAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAIC,kBAAAA,CAAmB,CAAA,mBAAA,EAAsB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MACrE,SAAA,EAAWD,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;AC5PO,SAAS,kBAAkB,OAAA,EAA4C;AAC5E,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,IAAA,EAAM,6BAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,kBAAA,CAAmB,OAAO;AAAA,GACrD,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * `MemoryContext` → Supermemory containerTags translation (T3.2).\n *\n * EC-C fix: every component runs through a strict identifier sanitizer\n * (regex `^[a-zA-Z0-9_-]+$`) before being joined with `:`. Rejects with\n * `MemoryAdapterError(code: \"invalid_input\")` on invalid input, so a\n * value like `userId: \"user:123\"` cannot silently land in a different\n * bucket via tag mis-parsing.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst SAFE_IDENT = /^[a-zA-Z0-9_-]+$/;\nconst ADAPTER_ID = \"supermemory\";\n\nexport function sanitizeIdentifier(value: string, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new MemoryAdapterError(`Supermemory adapter: ${fieldName} must be a non-empty string`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n if (!SAFE_IDENT.test(value)) {\n throw new MemoryAdapterError(\n `Supermemory adapter: ${fieldName} \"${value}\" contains invalid characters (allowed: a-zA-Z0-9_-)`,\n { adapterId: ADAPTER_ID, code: \"invalid_input\" },\n );\n }\n return value;\n}\n\n/**\n * Build the array of containerTags for `documents.add`. Each component\n * is sanitized; collisions across tag namespaces (user/agent/tenant/tag)\n * are intentional — Supermemory treats containerTags as a set.\n *\n * @internal\n */\nexport function buildContainerTags(ctx: MemoryContext, prefix: string): string[] {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n const tags: string[] = [`${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`];\n if (ctx.agentId !== undefined) {\n tags.push(`${safePrefix}:agent:${sanitizeIdentifier(ctx.agentId, \"agentId\")}`);\n }\n if (ctx.tenantId !== undefined) {\n tags.push(`${safePrefix}:tenant:${sanitizeIdentifier(ctx.tenantId, \"tenantId\")}`);\n }\n if (ctx.tags !== undefined) {\n for (const t of ctx.tags) {\n tags.push(`${safePrefix}:tag:${sanitizeIdentifier(t, \"tag\")}`);\n }\n }\n return tags;\n}\n\n/**\n * Pick the primary containerTag for `search.memories` (which takes a\n * single string, not an array). The user tag is canonical.\n *\n * @internal\n */\nexport function primaryContainerTag(ctx: MemoryContext, prefix: string): string {\n const safePrefix = sanitizeIdentifier(prefix, \"prefix\");\n return `${safePrefix}:user:${sanitizeIdentifier(ctx.userId, \"userId\")}`;\n}\n","/**\n * SupermemoryAdapter — `@theokit-memory-supermemory` core (T3.2, ADR D141).\n *\n * Wraps `supermemory` SDK v4. Implements `MemoryAdapter` so the SDK's\n * `pre_user_send` / `post_assistant_reply` hooks (D145) and\n * `agent.memory.*` direct API (D142) work end-to-end against Supermemory's\n * managed memory + RAG service.\n *\n * @public\n */\n\nimport {\n extractRawId,\n type MemoryAdapter,\n type MemoryAdapterCapabilities,\n MemoryAdapterError,\n type MemoryContext,\n type MemoryFact,\n type MemoryId,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport type Supermemory from \"supermemory\";\nimport SupermemoryClient from \"supermemory\";\n\nimport { buildContainerTags, primaryContainerTag } from \"./translate.js\";\n\n/** Configuration accepted by the `supermemoryMemory(...)` factory. @public */\nexport interface SupermemoryAdapterOptions {\n /** Supermemory API key. Falls back to `SUPERMEMORY_API_KEY`. */\n apiKey: string;\n /** Base URL override for self-hosted Supermemory deployments. */\n baseUrl?: string;\n /** Prefix for every containerTag (default `\"theokit\"`). Useful for test isolation (EC-S). */\n containerTagPrefix?: string;\n}\n\nconst ADAPTER_ID = \"supermemory\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/**\n * SDK-internal adapter class. Construct via `supermemoryMemory(...)`\n * factory from `./index.ts`, not directly.\n *\n * @internal\n */\nexport class SupermemoryAdapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: SupermemoryAdapterOptions;\n #client?: Supermemory;\n\n constructor(opts: SupermemoryAdapterOptions) {\n this.#opts = opts;\n }\n\n isAvailable(): boolean {\n return typeof this.#opts.apiKey === \"string\" && this.#opts.apiKey.length > 0;\n }\n\n async initialize(): Promise<void> {\n // Lazy: defer the actual client construction until first call.\n // initialize() is idempotent — see EC-3 / EC-I.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n const text = this.#renderContent(content);\n if (text.length === 0) {\n throw new MemoryAdapterError(\"write: empty content\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n const containerTags = buildContainerTags(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().documents.add({\n content: text,\n containerTags,\n ...(ctx.metadata !== undefined ? { metadata: ctx.metadata as Record<string, string> } : {}),\n });\n return mkMemoryId(ADAPTER_ID, resp.id);\n } catch (err) {\n throw this.#translateError(err, \"write\");\n }\n }\n\n async recall(query: string, ctx: MemoryContext, k = 10): Promise<MemoryFact[]> {\n if (k <= 0) return [];\n const containerTag = primaryContainerTag(ctx, this.#prefix());\n try {\n const resp = await this.#sdk().search.memories({\n q: query,\n containerTag,\n limit: k,\n rerank: true,\n });\n const results = resp.results ?? [];\n return results.map(this.#mapResult);\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().documents.delete(rawId);\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a fact about the user or context to Supermemory long-term memory. \" +\n \"Returns the stored memory ID.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Fact text to persist verbatim.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description:\n \"Retrieve up to k semantically relevant facts from Supermemory long-term memory. \" +\n \"Returns an array of {id, content, score, createdAt} objects.\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Free-text query to search memory.\" },\n k: {\n type: \"integer\",\n minimum: 1,\n maximum: 50,\n description: \"Max results (default 10).\",\n },\n },\n required: [\"query\"],\n },\n },\n ];\n }\n\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ctx: MemoryContext,\n ): Promise<string> {\n if (name === \"memory_write\") {\n const content = String(args.content ?? \"\");\n const id = await this.write(content, ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const query = String(args.query ?? \"\");\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(query, ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n throw new MemoryAdapterError(`Unknown tool name: ${name}`, {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n\n async shutdown(): Promise<void> {\n this.#client = undefined;\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #prefix(): string {\n return this.#opts.containerTagPrefix ?? \"theokit\";\n }\n\n #renderContent(content: string | MemoryTurnMessage[]): string {\n if (typeof content === \"string\") return content.trim();\n return content\n .map((m) => `${m.role}: ${m.content}`)\n .join(\"\\n\")\n .trim();\n }\n\n #mapResult = (r: unknown): MemoryFact => {\n const obj = (r as Record<string, unknown>) ?? {};\n // SDK shape: { memory?: { id, content, ... }, score, ... } or chunk shape.\n const memory = (obj.memory as Record<string, unknown> | undefined) ?? obj;\n const rawId = String(memory.id ?? obj.id ?? \"\");\n const content = String(memory.content ?? memory.text ?? obj.content ?? \"\");\n const score = typeof obj.score === \"number\" ? obj.score : undefined;\n const createdAt = typeof memory.createdAt === \"string\" ? memory.createdAt : undefined;\n return {\n id: mkMemoryId(ADAPTER_ID, rawId),\n content,\n ...(score !== undefined ? { score } : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n };\n };\n\n #sdk(): Supermemory {\n if (this.#client === undefined) {\n this.#client = new SupermemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.baseUrl !== undefined ? { baseURL: this.#opts.baseUrl } : {}),\n });\n }\n return this.#client;\n }\n\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) return err;\n const status =\n (err as { status?: number; statusCode?: number })?.status ??\n (err as { statusCode?: number })?.statusCode;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Supermemory auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n return new MemoryAdapterError(`Supermemory rate limited (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"rate_limited\",\n cause: err,\n });\n }\n if (status === 404) {\n return new MemoryAdapterError(`Supermemory not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n return new MemoryAdapterError(`Supermemory network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Supermemory error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","import { Plugin } from \"@theokit/sdk\";\n\nimport { SupermemoryAdapter, type SupermemoryAdapterOptions } from \"./adapter.js\";\n\nexport type { SupermemoryAdapterOptions } from \"./adapter.js\";\n\n/**\n * Build a `Plugin { kind: \"memory\" }` ready to pass to\n * `Agent.create({ plugins: [...] })`.\n *\n * @public\n */\nexport function supermemoryMemory(options: SupermemoryAdapterOptions): Plugin {\n return Plugin.create({\n name: \"@theokit/memory-supermemory\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new SupermemoryAdapter(options),\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/memory-supermemory",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Supermemory memory adapter for @theokit/sdk — wraps supermemory@^4 with the MemoryAdapter contract (ADR D141).",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -30,14 +30,14 @@
|
|
|
30
30
|
],
|
|
31
31
|
"peerDependencies": {
|
|
32
32
|
"supermemory": "^4.21.0",
|
|
33
|
-
"@theokit/sdk": "^
|
|
33
|
+
"@theokit/sdk": "^3.0.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"supermemory": "^4.21.1",
|
|
37
37
|
"tsup": "^8.5.0",
|
|
38
38
|
"typescript": "^5.8.0",
|
|
39
39
|
"vitest": "^4.1.8",
|
|
40
|
-
"@theokit/sdk": "
|
|
40
|
+
"@theokit/sdk": "3.0.0"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "tsup",
|