@theokit/memory-mem0 0.1.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 +14 -0
- package/LICENSE +201 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +0 -9
- package/dist/index.d.ts +0 -9
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +11 -11
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@
|
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @theokit/sdk@3.0.0
|
|
9
|
+
|
|
10
|
+
## 1.0.0
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- Updated dependencies [b9f30a6]
|
|
15
|
+
- @theokit/sdk@2.0.0
|
|
16
|
+
|
|
17
|
+
## 2.0.0
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
7
21
|
- Updated dependencies
|
|
8
22
|
- @theokit/sdk@1.3.0
|
|
9
23
|
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 usetheo.dev
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.cjs
CHANGED
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/circuit-breaker.ts","../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["MemoryAdapterError","ADAPTER_ID","mkMemoryId","extractRawId","MemoryClient","definePlugin"],"mappings":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,IAClB,IAAA,EAAM,sBAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,WAAA,CAAY,OAAO;AAAA,GAC9C,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * In-memory circuit breaker for Mem0Adapter (T5.1, EC-K).\n *\n * Trips after `threshold` consecutive 5xx-class failures. 429 / 401 /\n * 404 / invalid_input do NOT count toward the threshold — rate limits\n * are a caller-pace signal, not a provider-down signal (EC-K).\n *\n * @internal\n */\n\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst ADAPTER_ID = \"mem0\";\n\nexport interface CircuitBreakerOptions {\n threshold?: number;\n cooldownMs?: number;\n}\n\nexport class CircuitBreaker {\n readonly threshold: number;\n readonly cooldownMs: number;\n #failures = 0;\n #openUntil = 0;\n\n constructor(opts: CircuitBreakerOptions = {}) {\n this.threshold = opts.threshold ?? 5;\n this.cooldownMs = opts.cooldownMs ?? 2 * 60 * 1000;\n }\n\n /** Throws `MemoryAdapterError(code: \"rate_limited\")` if breaker is open. */\n ensureClosed(op: string): void {\n if (Date.now() < this.#openUntil) {\n const secondsLeft = Math.ceil((this.#openUntil - Date.now()) / 1000);\n throw new MemoryAdapterError(\n `Mem0 circuit breaker open (${op}): ${secondsLeft}s cooldown remaining.`,\n { adapterId: ADAPTER_ID, code: \"rate_limited\" },\n );\n }\n }\n\n /** Increment failure counter. Trips when threshold reached. Only call for 5xx-class errors. */\n recordFailure(): void {\n this.#failures += 1;\n if (this.#failures >= this.threshold) {\n this.#openUntil = Date.now() + this.cooldownMs;\n }\n }\n\n /** Reset on first success — closes the breaker (EC-K). */\n recordSuccess(): void {\n this.#failures = 0;\n this.#openUntil = 0;\n }\n\n /** Test-only inspector. @internal */\n state(): { failures: number; isOpen: boolean; openUntil: number } {\n return {\n failures: this.#failures,\n isOpen: Date.now() < this.#openUntil,\n openUntil: this.#openUntil,\n };\n }\n}\n","/**\n * `MemoryContext` → Mem0 add/search options translation (T5.1).\n *\n * Mem0 keeps `user_id`, `agent_id`, `app_id`, `run_id` orthogonal —\n * we map each `MemoryContext` field onto its native primitive.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\n\ninterface Mem0Options {\n user_id?: string;\n agent_id?: string;\n run_id?: string;\n app_id?: string;\n categories?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport function toMem0Options(ctx: MemoryContext): Mem0Options {\n const out: Mem0Options = { user_id: ctx.userId };\n if (ctx.agentId !== undefined) out.agent_id = ctx.agentId;\n if (ctx.sessionId !== undefined) out.run_id = ctx.sessionId;\n if (ctx.tenantId !== undefined) out.app_id = ctx.tenantId;\n if (ctx.tags !== undefined) out.categories = ctx.tags;\n if (ctx.metadata !== undefined) out.metadata = ctx.metadata;\n return out;\n}\n","/**\n * Mem0Adapter — `@theokit/memory-mem0` core (T5.1, ADR D141 / D148).\n *\n * Wraps `mem0ai` `MemoryClient` (cloud-only per D148). Implements\n * `MemoryAdapter` with the unique `history(id)` capability — the only\n * adapter today that exposes per-memory versioning.\n *\n * Includes a circuit breaker (EC-K: 5xx counts; 429 does NOT trip).\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 MemoryRevision,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport MemoryClient from \"mem0ai\";\n\nimport { CircuitBreaker, type CircuitBreakerOptions } from \"./circuit-breaker.js\";\nimport { toMem0Options } from \"./translate.js\";\n\n/** Configuration accepted by the `mem0Memory(...)` factory. @public */\nexport interface Mem0AdapterOptions {\n /** Mem0 API key. Required. */\n apiKey: string;\n /** Override host (default mem0 cloud). */\n host?: string;\n organizationId?: string;\n projectId?: string;\n /** Circuit breaker tuning (EC-K). */\n breaker?: CircuitBreakerOptions;\n}\n\nconst ADAPTER_ID = \"mem0\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: true, // ← unique to Mem0\n sessions: true,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/** @internal */\nexport class Mem0Adapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: Mem0AdapterOptions;\n readonly #breaker: CircuitBreaker;\n #client?: MemoryClient;\n\n constructor(opts: Mem0AdapterOptions) {\n this.#opts = opts;\n this.#breaker = new CircuitBreaker(opts.breaker);\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: client constructed on first call.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n this.#breaker.ensureClosed(\"write\");\n const messages = this.#toMessages(content);\n if (messages.length === 0) {\n throw new MemoryAdapterError(\"write: empty messages\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().add(messages, opts);\n this.#breaker.recordSuccess();\n const first = resp[0];\n const rawId = first?.id ?? `mem0-${Date.now()}`;\n return mkMemoryId(ADAPTER_ID, rawId);\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 this.#breaker.ensureClosed(\"recall\");\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().search(query, {\n // Read filter: cross-session recall keyed by user_id (Hermes pattern).\n ...(opts.user_id !== undefined ? { filters: { user_id: opts.user_id } } : {}),\n topK: k,\n rerank: true,\n });\n this.#breaker.recordSuccess();\n const list = Array.isArray(resp) ? resp : ((resp as { results?: unknown[] }).results ?? []);\n return (list as Array<Record<string, unknown>>).map((r) => ({\n id: mkMemoryId(ADAPTER_ID, String(r.id ?? \"\")),\n content: String(r.memory ?? r.content ?? \"\"),\n ...(typeof r.score === \"number\" ? { score: r.score as number } : {}),\n ...(r.createdAt !== undefined ? { createdAt: String(r.createdAt) } : {}),\n ...(r.metadata !== undefined ? { metadata: r.metadata as Record<string, unknown> } : {}),\n }));\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n this.#breaker.ensureClosed(\"delete\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().delete(rawId);\n this.#breaker.recordSuccess();\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n async history(id: MemoryId): Promise<MemoryRevision[]> {\n this.#breaker.ensureClosed(\"history\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n const rows = await this.#sdk().history(rawId);\n this.#breaker.recordSuccess();\n return rows.map((r, i) => {\n const u = (r as unknown as { updatedAt?: unknown }).updatedAt;\n const changedAt =\n u instanceof Date\n ? u.toISOString()\n : typeof u === \"string\"\n ? u\n : new Date().toISOString();\n return {\n id: mkMemoryId(ADAPTER_ID, r.memoryId ?? rawId),\n content: String(r.newMemory ?? r.oldMemory ?? \"\"),\n version: i + 1,\n changedAt,\n };\n });\n } catch (err) {\n throw this.#translateError(err, \"history\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a turn to Mem0 long-term memory. Server-side extraction populates facts.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Turn text to persist.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description: \"Retrieve up to k semantically relevant facts from Mem0 (server-side rerank).\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n k: { type: \"integer\", minimum: 1, maximum: 50 },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_history\",\n description:\n \"Retrieve the version history of a specific memory by id. Mem0-unique capability — \" +\n \"shows how a fact has evolved over time (e.g., user changed preferences).\",\n parameters: {\n type: \"object\",\n properties: { memoryId: { type: \"string\" } },\n required: [\"memoryId\"],\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 id = await this.write(String(args.content ?? \"\"), ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(String(args.query ?? \"\"), ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n if (name === \"memory_history\") {\n const rawId = String(args.memoryId ?? \"\");\n const wrapped = rawId.startsWith(`${ADAPTER_ID}:`)\n ? (rawId as MemoryId)\n : mkMemoryId(ADAPTER_ID, rawId);\n const revisions = await this.history(wrapped);\n return JSON.stringify({ ok: true, revisions });\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 /** Test-only: inspect breaker state. @internal */\n _breakerState(): { failures: number; isOpen: boolean; openUntil: number } {\n return this.#breaker.state();\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #toMessages(\n content: string | MemoryTurnMessage[],\n ): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n if (typeof content === \"string\") {\n return content.trim().length === 0 ? [] : [{ role: \"user\", content }];\n }\n // Mem0 SDK accepts only user/assistant roles. System turns are merged\n // into user content with a \"[system] \" prefix.\n return content\n .filter((m) => m.content.trim().length > 0)\n .map((m) =>\n m.role === \"system\"\n ? { role: \"user\" as const, content: `[system] ${m.content}` }\n : { role: m.role, content: m.content },\n );\n }\n\n #sdk(): MemoryClient {\n if (this.#client === undefined) {\n this.#client = new MemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.host !== undefined ? { host: this.#opts.host } : {}),\n ...(this.#opts.organizationId !== undefined\n ? { organizationId: this.#opts.organizationId }\n : {}),\n ...(this.#opts.projectId !== undefined ? { projectId: this.#opts.projectId } : {}),\n });\n }\n return this.#client;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder maps provider error classes to typed codes + breaker policy (EC-K: 429 does NOT trip); inlining keeps the policy decisions in one place.\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) {\n if (err.code === \"rate_limited\") {\n // EC-K: do NOT trip breaker on rate limit.\n } else if (\n err.code === \"auth_failed\" ||\n err.code === \"not_found\" ||\n err.code === \"invalid_input\"\n ) {\n // No trip — these are caller-side or stateful conditions.\n } else {\n this.#breaker.recordFailure();\n }\n return err;\n }\n const status =\n (err as { status?: number; statusCode?: number; response?: { status?: number } })?.status ??\n (err as { statusCode?: number })?.statusCode ??\n (err as { response?: { status?: number } })?.response?.status;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Mem0 auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n // EC-K: rate-limited; do NOT increment breaker.\n return new MemoryAdapterError(`Mem0 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(`Mem0 not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (typeof status === \"number\" && status >= 500) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 server error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Mem0 error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","/**\n * `@theokit/memory-mem0` — Mem0 cloud memory adapter for @theokit/sdk.\n *\n * Cloud-only per ADR D148. Wraps `mem0ai` `MemoryClient`. Unique\n * capability among `@theokit/memory-*` adapters: `history(id)`.\n *\n * @public\n */\n\nimport type { Plugin } from \"@theokit/sdk\";\nimport { definePlugin } from \"@theokit/sdk\";\n\nimport { Mem0Adapter, type Mem0AdapterOptions } from \"./adapter.js\";\n\nexport type { Mem0AdapterOptions } from \"./adapter.js\";\n\n/** Build a `Plugin { kind: \"memory\" }`. @public */\nexport function mem0Memory(options: Mem0AdapterOptions): Plugin {\n return definePlugin({\n name: \"@theokit/memory-mem0\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new Mem0Adapter(options),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/circuit-breaker.ts","../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["MemoryAdapterError","ADAPTER_ID","mkMemoryId","extractRawId","MemoryClient","Plugin"],"mappings":";;;;;;;;;;AAYA,IAAM,UAAA,GAAa,MAAA;AAOZ,IAAM,iBAAN,MAAqB;AAAA,EACjB,SAAA;AAAA,EACA,UAAA;AAAA,EACT,SAAA,GAAY,CAAA;AAAA,EACZ,UAAA,GAAa,CAAA;AAAA,EAEb,WAAA,CAAY,IAAA,GAA8B,EAAC,EAAG;AAC5C,IAAA,IAAA,CAAK,SAAA,GAAY,KAAK,SAAA,IAAa,CAAA;AACnC,IAAA,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,UAAA,IAAc,CAAA,GAAI,EAAA,GAAK,GAAA;AAAA,EAChD;AAAA;AAAA,EAGA,aAAa,EAAA,EAAkB;AAC7B,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,GAAI,IAAA,CAAK,UAAA,EAAY;AAChC,MAAA,MAAM,WAAA,GAAc,KAAK,IAAA,CAAA,CAAM,IAAA,CAAK,aAAa,IAAA,CAAK,GAAA,MAAS,GAAI,CA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,WAAW,MAAA,IAAa,OAAA,CAAQ,aAAY,CAAE,QAAA,CAAS,SAAS,CAAA,EAAG;AACrE,MAAA,IAAA,CAAK,SAAS,aAAA,EAAc;AAC5B,MAAA,OAAO,IAAID,sBAAAA,CAAmB,CAAA,oBAAA,EAAuB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,QACtE,SAAA,EAAWC,WAAAA;AAAA,QACX,IAAA,EAAM,SAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAID,sBAAAA,CAAmB,CAAA,YAAA,EAAe,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MAC9D,SAAA,EAAWC,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;ACrUO,SAAS,WAAW,OAAA,EAAqC;AAC9D,EAAA,OAAOI,WAAO,MAAA,CAAO;AAAA,IACnB,IAAA,EAAM,sBAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,WAAA,CAAY,OAAO;AAAA,GAC9C,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * In-memory circuit breaker for Mem0Adapter (T5.1, EC-K).\n *\n * Trips after `threshold` consecutive 5xx-class failures. 429 / 401 /\n * 404 / invalid_input do NOT count toward the threshold — rate limits\n * are a caller-pace signal, not a provider-down signal (EC-K).\n *\n * @internal\n */\n\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst ADAPTER_ID = \"mem0\";\n\nexport interface CircuitBreakerOptions {\n threshold?: number;\n cooldownMs?: number;\n}\n\nexport class CircuitBreaker {\n readonly threshold: number;\n readonly cooldownMs: number;\n #failures = 0;\n #openUntil = 0;\n\n constructor(opts: CircuitBreakerOptions = {}) {\n this.threshold = opts.threshold ?? 5;\n this.cooldownMs = opts.cooldownMs ?? 2 * 60 * 1000;\n }\n\n /** Throws `MemoryAdapterError(code: \"rate_limited\")` if breaker is open. */\n ensureClosed(op: string): void {\n if (Date.now() < this.#openUntil) {\n const secondsLeft = Math.ceil((this.#openUntil - Date.now()) / 1000);\n throw new MemoryAdapterError(\n `Mem0 circuit breaker open (${op}): ${secondsLeft}s cooldown remaining.`,\n { adapterId: ADAPTER_ID, code: \"rate_limited\" },\n );\n }\n }\n\n /** Increment failure counter. Trips when threshold reached. Only call for 5xx-class errors. */\n recordFailure(): void {\n this.#failures += 1;\n if (this.#failures >= this.threshold) {\n this.#openUntil = Date.now() + this.cooldownMs;\n }\n }\n\n /** Reset on first success — closes the breaker (EC-K). */\n recordSuccess(): void {\n this.#failures = 0;\n this.#openUntil = 0;\n }\n\n /** Test-only inspector. @internal */\n state(): { failures: number; isOpen: boolean; openUntil: number } {\n return {\n failures: this.#failures,\n isOpen: Date.now() < this.#openUntil,\n openUntil: this.#openUntil,\n };\n }\n}\n","/**\n * `MemoryContext` → Mem0 add/search options translation (T5.1).\n *\n * Mem0 keeps `user_id`, `agent_id`, `app_id`, `run_id` orthogonal —\n * we map each `MemoryContext` field onto its native primitive.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\n\ninterface Mem0Options {\n user_id?: string;\n agent_id?: string;\n run_id?: string;\n app_id?: string;\n categories?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport function toMem0Options(ctx: MemoryContext): Mem0Options {\n const out: Mem0Options = { user_id: ctx.userId };\n if (ctx.agentId !== undefined) out.agent_id = ctx.agentId;\n if (ctx.sessionId !== undefined) out.run_id = ctx.sessionId;\n if (ctx.tenantId !== undefined) out.app_id = ctx.tenantId;\n if (ctx.tags !== undefined) out.categories = ctx.tags;\n if (ctx.metadata !== undefined) out.metadata = ctx.metadata;\n return out;\n}\n","/**\n * Mem0Adapter — `@theokit/memory-mem0` core (T5.1, ADR D141 / D148).\n *\n * Wraps `mem0ai` `MemoryClient` (cloud-only per D148). Implements\n * `MemoryAdapter` with the unique `history(id)` capability — the only\n * adapter today that exposes per-memory versioning.\n *\n * Includes a circuit breaker (EC-K: 5xx counts; 429 does NOT trip).\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 MemoryRevision,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport MemoryClient from \"mem0ai\";\n\nimport { CircuitBreaker, type CircuitBreakerOptions } from \"./circuit-breaker.js\";\nimport { toMem0Options } from \"./translate.js\";\n\n/** Configuration accepted by the `mem0Memory(...)` factory. @public */\nexport interface Mem0AdapterOptions {\n /** Mem0 API key. Required. */\n apiKey: string;\n /** Override host (default mem0 cloud). */\n host?: string;\n organizationId?: string;\n projectId?: string;\n /** Circuit breaker tuning (EC-K). */\n breaker?: CircuitBreakerOptions;\n}\n\nconst ADAPTER_ID = \"mem0\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: true, // ← unique to Mem0\n sessions: true,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/** @internal */\nexport class Mem0Adapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: Mem0AdapterOptions;\n readonly #breaker: CircuitBreaker;\n #client?: MemoryClient;\n\n constructor(opts: Mem0AdapterOptions) {\n this.#opts = opts;\n this.#breaker = new CircuitBreaker(opts.breaker);\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: client constructed on first call.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n this.#breaker.ensureClosed(\"write\");\n const messages = this.#toMessages(content);\n if (messages.length === 0) {\n throw new MemoryAdapterError(\"write: empty messages\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().add(messages, opts);\n this.#breaker.recordSuccess();\n const first = resp[0];\n const rawId = first?.id ?? `mem0-${Date.now()}`;\n return mkMemoryId(ADAPTER_ID, rawId);\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 this.#breaker.ensureClosed(\"recall\");\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().search(query, {\n // Read filter: cross-session recall keyed by user_id (Hermes pattern).\n ...(opts.user_id !== undefined ? { filters: { user_id: opts.user_id } } : {}),\n topK: k,\n rerank: true,\n });\n this.#breaker.recordSuccess();\n const list = Array.isArray(resp) ? resp : ((resp as { results?: unknown[] }).results ?? []);\n return (list as Array<Record<string, unknown>>).map((r) => ({\n id: mkMemoryId(ADAPTER_ID, String(r.id ?? \"\")),\n content: String(r.memory ?? r.content ?? \"\"),\n ...(typeof r.score === \"number\" ? { score: r.score as number } : {}),\n ...(r.createdAt !== undefined ? { createdAt: String(r.createdAt) } : {}),\n ...(r.metadata !== undefined ? { metadata: r.metadata as Record<string, unknown> } : {}),\n }));\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n this.#breaker.ensureClosed(\"delete\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().delete(rawId);\n this.#breaker.recordSuccess();\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n async history(id: MemoryId): Promise<MemoryRevision[]> {\n this.#breaker.ensureClosed(\"history\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n const rows = await this.#sdk().history(rawId);\n this.#breaker.recordSuccess();\n return rows.map((r, i) => {\n const u = (r as unknown as { updatedAt?: unknown }).updatedAt;\n const changedAt =\n u instanceof Date\n ? u.toISOString()\n : typeof u === \"string\"\n ? u\n : new Date().toISOString();\n return {\n id: mkMemoryId(ADAPTER_ID, r.memoryId ?? rawId),\n content: String(r.newMemory ?? r.oldMemory ?? \"\"),\n version: i + 1,\n changedAt,\n };\n });\n } catch (err) {\n throw this.#translateError(err, \"history\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a turn to Mem0 long-term memory. Server-side extraction populates facts.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Turn text to persist.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description: \"Retrieve up to k semantically relevant facts from Mem0 (server-side rerank).\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n k: { type: \"integer\", minimum: 1, maximum: 50 },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_history\",\n description:\n \"Retrieve the version history of a specific memory by id. Mem0-unique capability — \" +\n \"shows how a fact has evolved over time (e.g., user changed preferences).\",\n parameters: {\n type: \"object\",\n properties: { memoryId: { type: \"string\" } },\n required: [\"memoryId\"],\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 id = await this.write(String(args.content ?? \"\"), ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(String(args.query ?? \"\"), ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n if (name === \"memory_history\") {\n const rawId = String(args.memoryId ?? \"\");\n const wrapped = rawId.startsWith(`${ADAPTER_ID}:`)\n ? (rawId as MemoryId)\n : mkMemoryId(ADAPTER_ID, rawId);\n const revisions = await this.history(wrapped);\n return JSON.stringify({ ok: true, revisions });\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 /** Test-only: inspect breaker state. @internal */\n _breakerState(): { failures: number; isOpen: boolean; openUntil: number } {\n return this.#breaker.state();\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #toMessages(\n content: string | MemoryTurnMessage[],\n ): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n if (typeof content === \"string\") {\n return content.trim().length === 0 ? [] : [{ role: \"user\", content }];\n }\n // Mem0 SDK accepts only user/assistant roles. System turns are merged\n // into user content with a \"[system] \" prefix.\n return content\n .filter((m) => m.content.trim().length > 0)\n .map((m) =>\n m.role === \"system\"\n ? { role: \"user\" as const, content: `[system] ${m.content}` }\n : { role: m.role, content: m.content },\n );\n }\n\n #sdk(): MemoryClient {\n if (this.#client === undefined) {\n this.#client = new MemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.host !== undefined ? { host: this.#opts.host } : {}),\n ...(this.#opts.organizationId !== undefined\n ? { organizationId: this.#opts.organizationId }\n : {}),\n ...(this.#opts.projectId !== undefined ? { projectId: this.#opts.projectId } : {}),\n });\n }\n return this.#client;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder maps provider error classes to typed codes + breaker policy (EC-K: 429 does NOT trip); inlining keeps the policy decisions in one place.\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) {\n if (err.code === \"rate_limited\") {\n // EC-K: do NOT trip breaker on rate limit.\n } else if (\n err.code === \"auth_failed\" ||\n err.code === \"not_found\" ||\n err.code === \"invalid_input\"\n ) {\n // No trip — these are caller-side or stateful conditions.\n } else {\n this.#breaker.recordFailure();\n }\n return err;\n }\n const status =\n (err as { status?: number; statusCode?: number; response?: { status?: number } })?.status ??\n (err as { statusCode?: number })?.statusCode ??\n (err as { response?: { status?: number } })?.response?.status;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Mem0 auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n // EC-K: rate-limited; do NOT increment breaker.\n return new MemoryAdapterError(`Mem0 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(`Mem0 not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (typeof status === \"number\" && status >= 500) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 server error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Mem0 error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","import { Plugin } from \"@theokit/sdk\";\n\nimport { Mem0Adapter, type Mem0AdapterOptions } from \"./adapter.js\";\n\nexport type { Mem0AdapterOptions } from \"./adapter.js\";\n\n/** Build a `Plugin { kind: \"memory\" }`. @public */\nexport function mem0Memory(options: Mem0AdapterOptions): Plugin {\n return Plugin.create({\n name: \"@theokit/memory-mem0\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new Mem0Adapter(options),\n });\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -38,15 +38,6 @@ interface Mem0AdapterOptions {
|
|
|
38
38
|
breaker?: CircuitBreakerOptions;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
* `@theokit/memory-mem0` — Mem0 cloud memory adapter for @theokit/sdk.
|
|
43
|
-
*
|
|
44
|
-
* Cloud-only per ADR D148. Wraps `mem0ai` `MemoryClient`. Unique
|
|
45
|
-
* capability among `@theokit/memory-*` adapters: `history(id)`.
|
|
46
|
-
*
|
|
47
|
-
* @public
|
|
48
|
-
*/
|
|
49
|
-
|
|
50
41
|
/** Build a `Plugin { kind: "memory" }`. @public */
|
|
51
42
|
declare function mem0Memory(options: Mem0AdapterOptions): Plugin;
|
|
52
43
|
|
package/dist/index.d.ts
CHANGED
|
@@ -38,15 +38,6 @@ interface Mem0AdapterOptions {
|
|
|
38
38
|
breaker?: CircuitBreakerOptions;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
* `@theokit/memory-mem0` — Mem0 cloud memory adapter for @theokit/sdk.
|
|
43
|
-
*
|
|
44
|
-
* Cloud-only per ADR D148. Wraps `mem0ai` `MemoryClient`. Unique
|
|
45
|
-
* capability among `@theokit/memory-*` adapters: `history(id)`.
|
|
46
|
-
*
|
|
47
|
-
* @public
|
|
48
|
-
*/
|
|
49
|
-
|
|
50
41
|
/** Build a `Plugin { kind: "memory" }`. @public */
|
|
51
42
|
declare function mem0Memory(options: Mem0AdapterOptions): Plugin;
|
|
52
43
|
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Plugin, MemoryAdapterError, mkMemoryId, extractRawId } from '@theokit/sdk';
|
|
2
2
|
import MemoryClient from 'mem0ai';
|
|
3
3
|
|
|
4
4
|
// src/index.ts
|
|
@@ -296,7 +296,7 @@ var Mem0Adapter = class {
|
|
|
296
296
|
|
|
297
297
|
// src/index.ts
|
|
298
298
|
function mem0Memory(options) {
|
|
299
|
-
return
|
|
299
|
+
return Plugin.create({
|
|
300
300
|
name: "@theokit/memory-mem0",
|
|
301
301
|
version: "0.1.0",
|
|
302
302
|
kind: "memory",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/circuit-breaker.ts","../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["ADAPTER_ID","MemoryA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,IAClB,IAAA,EAAM,sBAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,WAAA,CAAY,OAAO;AAAA,GAC9C,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * In-memory circuit breaker for Mem0Adapter (T5.1, EC-K).\n *\n * Trips after `threshold` consecutive 5xx-class failures. 429 / 401 /\n * 404 / invalid_input do NOT count toward the threshold — rate limits\n * are a caller-pace signal, not a provider-down signal (EC-K).\n *\n * @internal\n */\n\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst ADAPTER_ID = \"mem0\";\n\nexport interface CircuitBreakerOptions {\n threshold?: number;\n cooldownMs?: number;\n}\n\nexport class CircuitBreaker {\n readonly threshold: number;\n readonly cooldownMs: number;\n #failures = 0;\n #openUntil = 0;\n\n constructor(opts: CircuitBreakerOptions = {}) {\n this.threshold = opts.threshold ?? 5;\n this.cooldownMs = opts.cooldownMs ?? 2 * 60 * 1000;\n }\n\n /** Throws `MemoryAdapterError(code: \"rate_limited\")` if breaker is open. */\n ensureClosed(op: string): void {\n if (Date.now() < this.#openUntil) {\n const secondsLeft = Math.ceil((this.#openUntil - Date.now()) / 1000);\n throw new MemoryAdapterError(\n `Mem0 circuit breaker open (${op}): ${secondsLeft}s cooldown remaining.`,\n { adapterId: ADAPTER_ID, code: \"rate_limited\" },\n );\n }\n }\n\n /** Increment failure counter. Trips when threshold reached. Only call for 5xx-class errors. */\n recordFailure(): void {\n this.#failures += 1;\n if (this.#failures >= this.threshold) {\n this.#openUntil = Date.now() + this.cooldownMs;\n }\n }\n\n /** Reset on first success — closes the breaker (EC-K). */\n recordSuccess(): void {\n this.#failures = 0;\n this.#openUntil = 0;\n }\n\n /** Test-only inspector. @internal */\n state(): { failures: number; isOpen: boolean; openUntil: number } {\n return {\n failures: this.#failures,\n isOpen: Date.now() < this.#openUntil,\n openUntil: this.#openUntil,\n };\n }\n}\n","/**\n * `MemoryContext` → Mem0 add/search options translation (T5.1).\n *\n * Mem0 keeps `user_id`, `agent_id`, `app_id`, `run_id` orthogonal —\n * we map each `MemoryContext` field onto its native primitive.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\n\ninterface Mem0Options {\n user_id?: string;\n agent_id?: string;\n run_id?: string;\n app_id?: string;\n categories?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport function toMem0Options(ctx: MemoryContext): Mem0Options {\n const out: Mem0Options = { user_id: ctx.userId };\n if (ctx.agentId !== undefined) out.agent_id = ctx.agentId;\n if (ctx.sessionId !== undefined) out.run_id = ctx.sessionId;\n if (ctx.tenantId !== undefined) out.app_id = ctx.tenantId;\n if (ctx.tags !== undefined) out.categories = ctx.tags;\n if (ctx.metadata !== undefined) out.metadata = ctx.metadata;\n return out;\n}\n","/**\n * Mem0Adapter — `@theokit/memory-mem0` core (T5.1, ADR D141 / D148).\n *\n * Wraps `mem0ai` `MemoryClient` (cloud-only per D148). Implements\n * `MemoryAdapter` with the unique `history(id)` capability — the only\n * adapter today that exposes per-memory versioning.\n *\n * Includes a circuit breaker (EC-K: 5xx counts; 429 does NOT trip).\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 MemoryRevision,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport MemoryClient from \"mem0ai\";\n\nimport { CircuitBreaker, type CircuitBreakerOptions } from \"./circuit-breaker.js\";\nimport { toMem0Options } from \"./translate.js\";\n\n/** Configuration accepted by the `mem0Memory(...)` factory. @public */\nexport interface Mem0AdapterOptions {\n /** Mem0 API key. Required. */\n apiKey: string;\n /** Override host (default mem0 cloud). */\n host?: string;\n organizationId?: string;\n projectId?: string;\n /** Circuit breaker tuning (EC-K). */\n breaker?: CircuitBreakerOptions;\n}\n\nconst ADAPTER_ID = \"mem0\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: true, // ← unique to Mem0\n sessions: true,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/** @internal */\nexport class Mem0Adapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: Mem0AdapterOptions;\n readonly #breaker: CircuitBreaker;\n #client?: MemoryClient;\n\n constructor(opts: Mem0AdapterOptions) {\n this.#opts = opts;\n this.#breaker = new CircuitBreaker(opts.breaker);\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: client constructed on first call.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n this.#breaker.ensureClosed(\"write\");\n const messages = this.#toMessages(content);\n if (messages.length === 0) {\n throw new MemoryAdapterError(\"write: empty messages\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().add(messages, opts);\n this.#breaker.recordSuccess();\n const first = resp[0];\n const rawId = first?.id ?? `mem0-${Date.now()}`;\n return mkMemoryId(ADAPTER_ID, rawId);\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 this.#breaker.ensureClosed(\"recall\");\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().search(query, {\n // Read filter: cross-session recall keyed by user_id (Hermes pattern).\n ...(opts.user_id !== undefined ? { filters: { user_id: opts.user_id } } : {}),\n topK: k,\n rerank: true,\n });\n this.#breaker.recordSuccess();\n const list = Array.isArray(resp) ? resp : ((resp as { results?: unknown[] }).results ?? []);\n return (list as Array<Record<string, unknown>>).map((r) => ({\n id: mkMemoryId(ADAPTER_ID, String(r.id ?? \"\")),\n content: String(r.memory ?? r.content ?? \"\"),\n ...(typeof r.score === \"number\" ? { score: r.score as number } : {}),\n ...(r.createdAt !== undefined ? { createdAt: String(r.createdAt) } : {}),\n ...(r.metadata !== undefined ? { metadata: r.metadata as Record<string, unknown> } : {}),\n }));\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n this.#breaker.ensureClosed(\"delete\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().delete(rawId);\n this.#breaker.recordSuccess();\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n async history(id: MemoryId): Promise<MemoryRevision[]> {\n this.#breaker.ensureClosed(\"history\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n const rows = await this.#sdk().history(rawId);\n this.#breaker.recordSuccess();\n return rows.map((r, i) => {\n const u = (r as unknown as { updatedAt?: unknown }).updatedAt;\n const changedAt =\n u instanceof Date\n ? u.toISOString()\n : typeof u === \"string\"\n ? u\n : new Date().toISOString();\n return {\n id: mkMemoryId(ADAPTER_ID, r.memoryId ?? rawId),\n content: String(r.newMemory ?? r.oldMemory ?? \"\"),\n version: i + 1,\n changedAt,\n };\n });\n } catch (err) {\n throw this.#translateError(err, \"history\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a turn to Mem0 long-term memory. Server-side extraction populates facts.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Turn text to persist.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description: \"Retrieve up to k semantically relevant facts from Mem0 (server-side rerank).\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n k: { type: \"integer\", minimum: 1, maximum: 50 },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_history\",\n description:\n \"Retrieve the version history of a specific memory by id. Mem0-unique capability — \" +\n \"shows how a fact has evolved over time (e.g., user changed preferences).\",\n parameters: {\n type: \"object\",\n properties: { memoryId: { type: \"string\" } },\n required: [\"memoryId\"],\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 id = await this.write(String(args.content ?? \"\"), ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(String(args.query ?? \"\"), ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n if (name === \"memory_history\") {\n const rawId = String(args.memoryId ?? \"\");\n const wrapped = rawId.startsWith(`${ADAPTER_ID}:`)\n ? (rawId as MemoryId)\n : mkMemoryId(ADAPTER_ID, rawId);\n const revisions = await this.history(wrapped);\n return JSON.stringify({ ok: true, revisions });\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 /** Test-only: inspect breaker state. @internal */\n _breakerState(): { failures: number; isOpen: boolean; openUntil: number } {\n return this.#breaker.state();\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #toMessages(\n content: string | MemoryTurnMessage[],\n ): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n if (typeof content === \"string\") {\n return content.trim().length === 0 ? [] : [{ role: \"user\", content }];\n }\n // Mem0 SDK accepts only user/assistant roles. System turns are merged\n // into user content with a \"[system] \" prefix.\n return content\n .filter((m) => m.content.trim().length > 0)\n .map((m) =>\n m.role === \"system\"\n ? { role: \"user\" as const, content: `[system] ${m.content}` }\n : { role: m.role, content: m.content },\n );\n }\n\n #sdk(): MemoryClient {\n if (this.#client === undefined) {\n this.#client = new MemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.host !== undefined ? { host: this.#opts.host } : {}),\n ...(this.#opts.organizationId !== undefined\n ? { organizationId: this.#opts.organizationId }\n : {}),\n ...(this.#opts.projectId !== undefined ? { projectId: this.#opts.projectId } : {}),\n });\n }\n return this.#client;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder maps provider error classes to typed codes + breaker policy (EC-K: 429 does NOT trip); inlining keeps the policy decisions in one place.\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) {\n if (err.code === \"rate_limited\") {\n // EC-K: do NOT trip breaker on rate limit.\n } else if (\n err.code === \"auth_failed\" ||\n err.code === \"not_found\" ||\n err.code === \"invalid_input\"\n ) {\n // No trip — these are caller-side or stateful conditions.\n } else {\n this.#breaker.recordFailure();\n }\n return err;\n }\n const status =\n (err as { status?: number; statusCode?: number; response?: { status?: number } })?.status ??\n (err as { statusCode?: number })?.statusCode ??\n (err as { response?: { status?: number } })?.response?.status;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Mem0 auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n // EC-K: rate-limited; do NOT increment breaker.\n return new MemoryAdapterError(`Mem0 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(`Mem0 not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (typeof status === \"number\" && status >= 500) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 server error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Mem0 error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","/**\n * `@theokit/memory-mem0` — Mem0 cloud memory adapter for @theokit/sdk.\n *\n * Cloud-only per ADR D148. Wraps `mem0ai` `MemoryClient`. Unique\n * capability among `@theokit/memory-*` adapters: `history(id)`.\n *\n * @public\n */\n\nimport type { Plugin } from \"@theokit/sdk\";\nimport { definePlugin } from \"@theokit/sdk\";\n\nimport { Mem0Adapter, type Mem0AdapterOptions } from \"./adapter.js\";\n\nexport type { Mem0AdapterOptions } from \"./adapter.js\";\n\n/** Build a `Plugin { kind: \"memory\" }`. @public */\nexport function mem0Memory(options: Mem0AdapterOptions): Plugin {\n return definePlugin({\n name: \"@theokit/memory-mem0\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new Mem0Adapter(options),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/circuit-breaker.ts","../src/translate.ts","../src/adapter.ts","../src/index.ts"],"names":["ADAPTER_ID","MemoryAdapterError"],"mappings":";;;;AAYA,IAAM,UAAA,GAAa,MAAA;AAOZ,IAAM,iBAAN,MAAqB;AAAA,EACjB,SAAA;AAAA,EACA,UAAA;AAAA,EACT,SAAA,GAAY,CAAA;AAAA,EACZ,UAAA,GAAa,CAAA;AAAA,EAEb,WAAA,CAAY,IAAA,GAA8B,EAAC,EAAG;AAC5C,IAAA,IAAA,CAAK,SAAA,GAAY,KAAK,SAAA,IAAa,CAAA;AACnC,IAAA,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,UAAA,IAAc,CAAA,GAAI,EAAA,GAAK,GAAA;AAAA,EAChD;AAAA;AAAA,EAGA,aAAa,EAAA,EAAkB;AAC7B,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,GAAI,IAAA,CAAK,UAAA,EAAY;AAChC,MAAA,MAAM,WAAA,GAAc,KAAK,IAAA,CAAA,CAAM,IAAA,CAAK,aAAa,IAAA,CAAK,GAAA,MAAS,GAAI,CAAA;AACnE,MAAA,MAAM,IAAI,kBAAA;AAAA,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AA,CAAS,SAAS,CAAA,EAAG;AACrE,MAAA,IAAA,CAAK,SAAS,aAAA,EAAc;AAC5B,MAAA,OAAO,IAAIC,kBAAAA,CAAmB,CAAA,oBAAA,EAAuB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,QACtE,SAAA,EAAWD,WAAAA;AAAA,QACX,IAAA,EAAM,SAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAIC,kBAAAA,CAAmB,CAAA,YAAA,EAAe,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MAC9D,SAAA,EAAWD,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;ACrUO,SAAS,WAAW,OAAA,EAAqC;AAC9D,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,IAAA,EAAM,sBAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,IAAA,EAAM,QAAA;AAAA,IACN,cAAA,EAAgB,MAAM,IAAI,WAAA,CAAY,OAAO;AAAA,GAC9C,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * In-memory circuit breaker for Mem0Adapter (T5.1, EC-K).\n *\n * Trips after `threshold` consecutive 5xx-class failures. 429 / 401 /\n * 404 / invalid_input do NOT count toward the threshold — rate limits\n * are a caller-pace signal, not a provider-down signal (EC-K).\n *\n * @internal\n */\n\nimport { MemoryAdapterError } from \"@theokit/sdk\";\n\nconst ADAPTER_ID = \"mem0\";\n\nexport interface CircuitBreakerOptions {\n threshold?: number;\n cooldownMs?: number;\n}\n\nexport class CircuitBreaker {\n readonly threshold: number;\n readonly cooldownMs: number;\n #failures = 0;\n #openUntil = 0;\n\n constructor(opts: CircuitBreakerOptions = {}) {\n this.threshold = opts.threshold ?? 5;\n this.cooldownMs = opts.cooldownMs ?? 2 * 60 * 1000;\n }\n\n /** Throws `MemoryAdapterError(code: \"rate_limited\")` if breaker is open. */\n ensureClosed(op: string): void {\n if (Date.now() < this.#openUntil) {\n const secondsLeft = Math.ceil((this.#openUntil - Date.now()) / 1000);\n throw new MemoryAdapterError(\n `Mem0 circuit breaker open (${op}): ${secondsLeft}s cooldown remaining.`,\n { adapterId: ADAPTER_ID, code: \"rate_limited\" },\n );\n }\n }\n\n /** Increment failure counter. Trips when threshold reached. Only call for 5xx-class errors. */\n recordFailure(): void {\n this.#failures += 1;\n if (this.#failures >= this.threshold) {\n this.#openUntil = Date.now() + this.cooldownMs;\n }\n }\n\n /** Reset on first success — closes the breaker (EC-K). */\n recordSuccess(): void {\n this.#failures = 0;\n this.#openUntil = 0;\n }\n\n /** Test-only inspector. @internal */\n state(): { failures: number; isOpen: boolean; openUntil: number } {\n return {\n failures: this.#failures,\n isOpen: Date.now() < this.#openUntil,\n openUntil: this.#openUntil,\n };\n }\n}\n","/**\n * `MemoryContext` → Mem0 add/search options translation (T5.1).\n *\n * Mem0 keeps `user_id`, `agent_id`, `app_id`, `run_id` orthogonal —\n * we map each `MemoryContext` field onto its native primitive.\n *\n * @internal\n */\n\nimport type { MemoryContext } from \"@theokit/sdk\";\n\ninterface Mem0Options {\n user_id?: string;\n agent_id?: string;\n run_id?: string;\n app_id?: string;\n categories?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport function toMem0Options(ctx: MemoryContext): Mem0Options {\n const out: Mem0Options = { user_id: ctx.userId };\n if (ctx.agentId !== undefined) out.agent_id = ctx.agentId;\n if (ctx.sessionId !== undefined) out.run_id = ctx.sessionId;\n if (ctx.tenantId !== undefined) out.app_id = ctx.tenantId;\n if (ctx.tags !== undefined) out.categories = ctx.tags;\n if (ctx.metadata !== undefined) out.metadata = ctx.metadata;\n return out;\n}\n","/**\n * Mem0Adapter — `@theokit/memory-mem0` core (T5.1, ADR D141 / D148).\n *\n * Wraps `mem0ai` `MemoryClient` (cloud-only per D148). Implements\n * `MemoryAdapter` with the unique `history(id)` capability — the only\n * adapter today that exposes per-memory versioning.\n *\n * Includes a circuit breaker (EC-K: 5xx counts; 429 does NOT trip).\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 MemoryRevision,\n type MemoryToolSchema,\n type MemoryTurnMessage,\n mkMemoryId,\n} from \"@theokit/sdk\";\nimport MemoryClient from \"mem0ai\";\n\nimport { CircuitBreaker, type CircuitBreakerOptions } from \"./circuit-breaker.js\";\nimport { toMem0Options } from \"./translate.js\";\n\n/** Configuration accepted by the `mem0Memory(...)` factory. @public */\nexport interface Mem0AdapterOptions {\n /** Mem0 API key. Required. */\n apiKey: string;\n /** Override host (default mem0 cloud). */\n host?: string;\n organizationId?: string;\n projectId?: string;\n /** Circuit breaker tuning (EC-K). */\n breaker?: CircuitBreakerOptions;\n}\n\nconst ADAPTER_ID = \"mem0\";\n\nconst CAPS: MemoryAdapterCapabilities = {\n history: true, // ← unique to Mem0\n sessions: true,\n tenancy: true,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n};\n\n/** @internal */\nexport class Mem0Adapter implements MemoryAdapter {\n readonly id = ADAPTER_ID;\n readonly capabilities = CAPS;\n readonly #opts: Mem0AdapterOptions;\n readonly #breaker: CircuitBreaker;\n #client?: MemoryClient;\n\n constructor(opts: Mem0AdapterOptions) {\n this.#opts = opts;\n this.#breaker = new CircuitBreaker(opts.breaker);\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: client constructed on first call.\n }\n\n async write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId> {\n this.#breaker.ensureClosed(\"write\");\n const messages = this.#toMessages(content);\n if (messages.length === 0) {\n throw new MemoryAdapterError(\"write: empty messages\", {\n adapterId: ADAPTER_ID,\n code: \"invalid_input\",\n });\n }\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().add(messages, opts);\n this.#breaker.recordSuccess();\n const first = resp[0];\n const rawId = first?.id ?? `mem0-${Date.now()}`;\n return mkMemoryId(ADAPTER_ID, rawId);\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 this.#breaker.ensureClosed(\"recall\");\n try {\n const opts = toMem0Options(ctx);\n const resp = await this.#sdk().search(query, {\n // Read filter: cross-session recall keyed by user_id (Hermes pattern).\n ...(opts.user_id !== undefined ? { filters: { user_id: opts.user_id } } : {}),\n topK: k,\n rerank: true,\n });\n this.#breaker.recordSuccess();\n const list = Array.isArray(resp) ? resp : ((resp as { results?: unknown[] }).results ?? []);\n return (list as Array<Record<string, unknown>>).map((r) => ({\n id: mkMemoryId(ADAPTER_ID, String(r.id ?? \"\")),\n content: String(r.memory ?? r.content ?? \"\"),\n ...(typeof r.score === \"number\" ? { score: r.score as number } : {}),\n ...(r.createdAt !== undefined ? { createdAt: String(r.createdAt) } : {}),\n ...(r.metadata !== undefined ? { metadata: r.metadata as Record<string, unknown> } : {}),\n }));\n } catch (err) {\n throw this.#translateError(err, \"recall\");\n }\n }\n\n async delete(id: MemoryId): Promise<void> {\n this.#breaker.ensureClosed(\"delete\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n await this.#sdk().delete(rawId);\n this.#breaker.recordSuccess();\n } catch (err) {\n throw this.#translateError(err, \"delete\");\n }\n }\n\n async history(id: MemoryId): Promise<MemoryRevision[]> {\n this.#breaker.ensureClosed(\"history\");\n const rawId = extractRawId(id, ADAPTER_ID);\n try {\n const rows = await this.#sdk().history(rawId);\n this.#breaker.recordSuccess();\n return rows.map((r, i) => {\n const u = (r as unknown as { updatedAt?: unknown }).updatedAt;\n const changedAt =\n u instanceof Date\n ? u.toISOString()\n : typeof u === \"string\"\n ? u\n : new Date().toISOString();\n return {\n id: mkMemoryId(ADAPTER_ID, r.memoryId ?? rawId),\n content: String(r.newMemory ?? r.oldMemory ?? \"\"),\n version: i + 1,\n changedAt,\n };\n });\n } catch (err) {\n throw this.#translateError(err, \"history\");\n }\n }\n\n getToolSchemas(): MemoryToolSchema[] {\n return [\n {\n name: \"memory_write\",\n description:\n \"Persist a turn to Mem0 long-term memory. Server-side extraction populates facts.\",\n parameters: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"Turn text to persist.\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_recall\",\n description: \"Retrieve up to k semantically relevant facts from Mem0 (server-side rerank).\",\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n k: { type: \"integer\", minimum: 1, maximum: 50 },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_history\",\n description:\n \"Retrieve the version history of a specific memory by id. Mem0-unique capability — \" +\n \"shows how a fact has evolved over time (e.g., user changed preferences).\",\n parameters: {\n type: \"object\",\n properties: { memoryId: { type: \"string\" } },\n required: [\"memoryId\"],\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 id = await this.write(String(args.content ?? \"\"), ctx);\n return JSON.stringify({ ok: true, id });\n }\n if (name === \"memory_recall\") {\n const k = typeof args.k === \"number\" ? args.k : 10;\n const facts = await this.recall(String(args.query ?? \"\"), ctx, k);\n return JSON.stringify({ ok: true, facts });\n }\n if (name === \"memory_history\") {\n const rawId = String(args.memoryId ?? \"\");\n const wrapped = rawId.startsWith(`${ADAPTER_ID}:`)\n ? (rawId as MemoryId)\n : mkMemoryId(ADAPTER_ID, rawId);\n const revisions = await this.history(wrapped);\n return JSON.stringify({ ok: true, revisions });\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 /** Test-only: inspect breaker state. @internal */\n _breakerState(): { failures: number; isOpen: boolean; openUntil: number } {\n return this.#breaker.state();\n }\n\n // ── helpers ────────────────────────────────────────────────────────\n\n #toMessages(\n content: string | MemoryTurnMessage[],\n ): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n if (typeof content === \"string\") {\n return content.trim().length === 0 ? [] : [{ role: \"user\", content }];\n }\n // Mem0 SDK accepts only user/assistant roles. System turns are merged\n // into user content with a \"[system] \" prefix.\n return content\n .filter((m) => m.content.trim().length > 0)\n .map((m) =>\n m.role === \"system\"\n ? { role: \"user\" as const, content: `[system] ${m.content}` }\n : { role: m.role, content: m.content },\n );\n }\n\n #sdk(): MemoryClient {\n if (this.#client === undefined) {\n this.#client = new MemoryClient({\n apiKey: this.#opts.apiKey,\n ...(this.#opts.host !== undefined ? { host: this.#opts.host } : {}),\n ...(this.#opts.organizationId !== undefined\n ? { organizationId: this.#opts.organizationId }\n : {}),\n ...(this.#opts.projectId !== undefined ? { projectId: this.#opts.projectId } : {}),\n });\n }\n return this.#client;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: error-translation ladder maps provider error classes to typed codes + breaker policy (EC-K: 429 does NOT trip); inlining keeps the policy decisions in one place.\n #translateError(err: unknown, op: string): MemoryAdapterError {\n if (err instanceof MemoryAdapterError) {\n if (err.code === \"rate_limited\") {\n // EC-K: do NOT trip breaker on rate limit.\n } else if (\n err.code === \"auth_failed\" ||\n err.code === \"not_found\" ||\n err.code === \"invalid_input\"\n ) {\n // No trip — these are caller-side or stateful conditions.\n } else {\n this.#breaker.recordFailure();\n }\n return err;\n }\n const status =\n (err as { status?: number; statusCode?: number; response?: { status?: number } })?.status ??\n (err as { statusCode?: number })?.statusCode ??\n (err as { response?: { status?: number } })?.response?.status;\n const message = (err as Error)?.message ?? String(err);\n if (status === 401 || status === 403) {\n return new MemoryAdapterError(`Mem0 auth failed (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"auth_failed\",\n cause: err,\n });\n }\n if (status === 429) {\n // EC-K: rate-limited; do NOT increment breaker.\n return new MemoryAdapterError(`Mem0 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(`Mem0 not found (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"not_found\",\n cause: err,\n });\n }\n if (typeof status === \"number\" && status >= 500) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 server error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n if (status === undefined && message.toLowerCase().includes(\"network\")) {\n this.#breaker.recordFailure();\n return new MemoryAdapterError(`Mem0 network error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"network\",\n cause: err,\n });\n }\n return new MemoryAdapterError(`Mem0 error (${op}): ${message}`, {\n adapterId: ADAPTER_ID,\n code: \"unknown\",\n cause: err,\n });\n }\n}\n","import { Plugin } from \"@theokit/sdk\";\n\nimport { Mem0Adapter, type Mem0AdapterOptions } from \"./adapter.js\";\n\nexport type { Mem0AdapterOptions } from \"./adapter.js\";\n\n/** Build a `Plugin { kind: \"memory\" }`. @public */\nexport function mem0Memory(options: Mem0AdapterOptions): Plugin {\n return Plugin.create({\n name: \"@theokit/memory-mem0\",\n version: \"0.1.0\",\n kind: \"memory\",\n createProvider: () => new Mem0Adapter(options),\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/memory-mem0",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Mem0 cloud memory adapter for @theokit/sdk — wraps mem0ai MemoryClient with the MemoryAdapter contract (ADR D141).",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -28,20 +28,20 @@
|
|
|
28
28
|
"LICENSE",
|
|
29
29
|
"CHANGELOG.md"
|
|
30
30
|
],
|
|
31
|
-
"scripts": {
|
|
32
|
-
"build": "tsup",
|
|
33
|
-
"typecheck": "tsc --noEmit",
|
|
34
|
-
"test": "vitest run"
|
|
35
|
-
},
|
|
36
31
|
"peerDependencies": {
|
|
37
|
-
"
|
|
38
|
-
"
|
|
32
|
+
"mem0ai": "^3.0.0",
|
|
33
|
+
"@theokit/sdk": "^3.0.0"
|
|
39
34
|
},
|
|
40
35
|
"devDependencies": {
|
|
41
|
-
"@theokit/sdk": "workspace:*",
|
|
42
36
|
"mem0ai": "^3.0.3",
|
|
43
37
|
"tsup": "^8.5.0",
|
|
44
38
|
"typescript": "^5.8.0",
|
|
45
|
-
"vitest": "^
|
|
39
|
+
"vitest": "^4.1.8",
|
|
40
|
+
"@theokit/sdk": "3.0.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "vitest run"
|
|
46
46
|
}
|
|
47
|
-
}
|
|
47
|
+
}
|