@theokit/memory-supermemory 3.0.0 → 3.0.3
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 +137 -0
- package/LICENSE +2 -2
- package/README.md +13 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +63 -6
- package/dist/index.d.ts +63 -6
- package/dist/index.js.map +1 -1
- package/package.json +16 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,142 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.0.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e3f2a82: Public-API documentation reviewed file by file, and corrected wherever it disagreed
|
|
8
|
+
with the code. The docblocks ship in the `.d.ts`, so these read as behaviour changes
|
|
9
|
+
in an editor even though no behaviour changed.
|
|
10
|
+
|
|
11
|
+
The corrections that change what a caller would do:
|
|
12
|
+
|
|
13
|
+
- **`sdk-cache` documented its own premise backwards.** The header example labelled a
|
|
14
|
+
semantic hit as if it avoided the provider call. `asPlugin()` returns the cached
|
|
15
|
+
answer as `recalledContext`, which the agent loop injects as a `<memory-context>`
|
|
16
|
+
block _before_ the prompt — the request still goes to the provider. The two modes
|
|
17
|
+
are now labelled separately, with a table saying which one short-circuits and which
|
|
18
|
+
one seeds.
|
|
19
|
+
- **`sdk-handoff`'s five error classes said "throw".** Under the plugin wiring the
|
|
20
|
+
handler never throws; every failure becomes a tool result `{"ok":false,…}` handed
|
|
21
|
+
back to the model. Each class now says where it is actually observable. The header
|
|
22
|
+
also told readers to `import { Handoff } from "@theokit/sdk"`, from which it was
|
|
23
|
+
extracted.
|
|
24
|
+
- **`sdk-budget`'s `charge()` claimed idempotency across concurrent calls.** The mutex
|
|
25
|
+
serialises, it does not deduplicate: two identical calls record twice. Related, and
|
|
26
|
+
newly documented: with `maxUsd` set, a model missing from the pricing table denies
|
|
27
|
+
every request rather than passing it — and the table matches by exact string, so
|
|
28
|
+
`"openai/gpt-4o"` does not match `"gpt-4o"`.
|
|
29
|
+
- **The three `memory-*` adapters advertised an env-var fallback they do not read**,
|
|
30
|
+
and their peer dependencies are required rather than optional. Their behavioural
|
|
31
|
+
differences are now stated where they break the "interchangeable adapter"
|
|
32
|
+
assumption — honcho ignores `k` and always throws on `delete`; mem0 recalls across
|
|
33
|
+
sessions by design; supermemory ignores `sessionId` entirely.
|
|
34
|
+
- **`sdk-memory`'s `truncated` flag was documented as its own inverse**, and its
|
|
35
|
+
dreaming sweep claimed a mutex it never takes against the writer it names.
|
|
36
|
+
- **`sdk-tools`** corrected `run_vitest`'s unreachable `no_vitest` code, `truncation`'s
|
|
37
|
+
replacement-character claim, and two return shapes missing a live error code.
|
|
38
|
+
- **`acp`/`cli`** corrected sixteen statements including a named error class that is
|
|
39
|
+
not the one raised, a handler documented as calling `fork()` that refuses
|
|
40
|
+
unconditionally, handlers described as pure that mint ids and mutate a store, a
|
|
41
|
+
config loader credited to Zod in a package that does not import it, and a `--force`
|
|
42
|
+
scaffold described as atomic that deletes the destination before the rename.
|
|
43
|
+
|
|
44
|
+
Undocumented public symbols were documented across every package, with each claim
|
|
45
|
+
checked against the implementation rather than inferred from the name.
|
|
46
|
+
|
|
47
|
+
- e368fc1: Every published declaration file now compiles without `skipLibCheck` (#345). The
|
|
48
|
+
DTS rollup emitted symbols as a re-export from a chunk while omitting them from
|
|
49
|
+
that chunk's `import`, and dropped type-only imports from external packages —
|
|
50
|
+
leaving 51 unresolved references across ten of the twelve packages. Nothing broke
|
|
51
|
+
at runtime, and `tsc` stayed green for anyone with `skipLibCheck` on, but a
|
|
52
|
+
consumer running type-aware lint saw every type reached through one degrade to
|
|
53
|
+
`error`.
|
|
54
|
+
|
|
55
|
+
The declarations are repaired at build time from the compiler's own diagnostics.
|
|
56
|
+
No source or API change.
|
|
57
|
+
|
|
58
|
+
- 1ac974f: **`@theokit/sdk-pty` declares its licence.** Every published version up to now shipped with no `license` field in the manifest. npm reads the field, not the directory, so the tarball was all-rights-reserved to whoever installed it — the terms were sitting in the `LICENSE` file it already shipped, saying nothing. The field now says `Apache-2.0`, which is what that file has always been and what all eleven sibling packages declare.
|
|
59
|
+
|
|
60
|
+
**Four packages now ship the licence they declare.** `@theokit/cli`, `@theokit/memory-honcho`, `@theokit/memory-mem0` and `@theokit/memory-supermemory` declared `Apache-2.0` and listed `LICENSE` in `files`, and no such file existed. npm omits a declared-but-absent path in silence, so every published tarball asserted the licence while carrying none of its terms — and §4(a) requires a copy to travel with the distribution. The file is there now, byte-identical to the one the other packages ship.
|
|
61
|
+
|
|
62
|
+
**Six packages complete the rest of their published metadata.** Each field is here for what its absence costs a consumer:
|
|
63
|
+
|
|
64
|
+
- `homepage` and `bugs` — the npm page renders both; without them someone who hits a defect has no route back to the project.
|
|
65
|
+
- `engines.node` — npm warns on an unsupported runtime only when the range is declared. `@theokit/sdk-pty` declared none, so a Node 18 install failed later and somewhere unrelated.
|
|
66
|
+
- `sideEffects` — a bundler keeps every module of a package that stays silent. Declared only after checking: a clean scan of each built ESM entry found zero top-level statements, the residual hits being closing tokens of declarations. `@theokit/sdk` keeps its path-array form, which is the honest shape for a package whose agent entry registers on import.
|
|
67
|
+
- `publishConfig.access` — a scoped package defaults to `restricted`. Three declared none and reached npm public only because the release flow supplied the flag; the manifest states it now instead of depending on how it is invoked.
|
|
68
|
+
- `@theokit/sdk-pty` also ships its `CHANGELOG.md`, which existed on disk and was absent from `files`.
|
|
69
|
+
|
|
70
|
+
The gate that should have caught any of this covered three packages out of twelve, by way of a hand-written list. It now derives the list from `packages/`, asserts the whole contract, and fails when the sweep discovers nothing rather than passing by having nothing to check.
|
|
71
|
+
|
|
72
|
+
- e699569: **The repository moved to the official `usetheokit` organization.** Every `repository`, `bugs` and `homepage` field now points there, along with the README, `CONTRIBUTING.md`, `SECURITY.md` and the issue templates. Existing clones and any URL already published keep working — GitHub redirects a transferred repository permanently — so this is a correctness fix for the metadata npm renders, not a break.
|
|
73
|
+
|
|
74
|
+
**The Apache-2.0 text every package ships was replaced with the official one.** The copy distributed until now had paragraph 4(d) truncated: it read "except as required for describing the origin of the Work and reproducing the content of the NOTICE file", dropping "reasonable and customary use" from the licensed clause. §4(d) governs what a redistributor must do with attribution notices, and the omission narrowed it.
|
|
75
|
+
|
|
76
|
+
That matters more than a typo would. The manifests declare the SPDX identifier `Apache-2.0`, which is an assertion that the terms are _the_ Apache-2.0 terms — a licence scanner resolves the identifier and never reads the file. A consumer's compliance review, which does read the file, would find a body that no longer matches the identifier and has no name of its own. Every `LICENSE` in this repository is now byte-identical to the canonical text, with the appendix filled in.
|
|
77
|
+
|
|
78
|
+
Nothing else about the terms changed: the licence is the same licence it has always been meant to be, and no package changes what it grants.
|
|
79
|
+
|
|
80
|
+
- c7385d2: Test runs no longer claim every core on the host.
|
|
81
|
+
|
|
82
|
+
None of the package configs capped `maxWorkers`, so vitest's default applied: `os.availableParallelism()`,
|
|
83
|
+
one fork per core, each booting a full test environment. The repo's `test` script is
|
|
84
|
+
`turbo run test --filter='./packages/*'`, so that default is paid once per package _concurrently_ —
|
|
85
|
+
nproc forks times turbo's concurrency, on nproc cores. Measured on a 12-thread machine during an
|
|
86
|
+
unrelated investigation, two vitest pools alone were enough to reach load average 33.89 with the
|
|
87
|
+
desktop unusable; a full fan-out is several times that.
|
|
88
|
+
|
|
89
|
+
`@theokit/sdk` is the interesting case. B-104 recorded on 2026-08-19 that the `poolOptions.forks.*`
|
|
90
|
+
block was 100% dead in Vitest 4, deleted it, and noted that `fileParallelism: false` was forcing
|
|
91
|
+
`maxWorkers` to 1 unconditionally, so a fork-count knob could not act. B-059 then flipped
|
|
92
|
+
`fileParallelism` to `true` on 2026-08-20, which made the knob able to act again — and nothing
|
|
93
|
+
reintroduced one, so the package silently went back to the uncapped default. That comment has been
|
|
94
|
+
corrected along with the config; it claimed no knob existed, which is no longer true.
|
|
95
|
+
|
|
96
|
+
The cap leaves 4 cores free (`Math.max(2, cpus().length - 4)`), scaling with the runner rather than
|
|
97
|
+
hard-coding one machine's core count. It costs no wall-clock: measured in `theokit-ui`, the full
|
|
98
|
+
suite ran 73.96s at 4 workers against 74.36s at 12, so the parallelism above the cap was already
|
|
99
|
+
noise. Verified as resolved config rather than as file contents — `createVitest` reports
|
|
100
|
+
`maxWorkers: 8` on a 12-thread host, which is the formula, not the default.
|
|
101
|
+
|
|
102
|
+
This changes no published behaviour; it is test tooling only. Refs usetheokit/theokit-ui#51.
|
|
103
|
+
|
|
104
|
+
## 3.0.2
|
|
105
|
+
|
|
106
|
+
### Patch Changes
|
|
107
|
+
|
|
108
|
+
- a3ae640: Declare `repository` so these packages can publish with provenance.
|
|
109
|
+
|
|
110
|
+
npm cross-checks a manifest's `repository.url` against the repository recorded in the signed
|
|
111
|
+
provenance statement, and an empty value cannot match — the PUT is refused with E422 after the
|
|
112
|
+
statement has been signed and written to the public transparency log. Six of the twelve publishable
|
|
113
|
+
packages carried an empty field; it went unnoticed because nothing needed it until provenance was
|
|
114
|
+
enabled, and because each package publishes independently, so the release run went red while the
|
|
115
|
+
package everyone was watching succeeded.
|
|
116
|
+
|
|
117
|
+
`directory` is set alongside the URL, so the registry links to each package rather than to the
|
|
118
|
+
repository root.
|
|
119
|
+
|
|
120
|
+
## 3.0.1
|
|
121
|
+
|
|
122
|
+
### Patch Changes
|
|
123
|
+
|
|
124
|
+
- 8790f70: Refuse a `workspace:` range before it can reach npm.
|
|
125
|
+
|
|
126
|
+
Five of this repo's twelve publishable packages declare internal dependencies as `workspace:^`, which
|
|
127
|
+
is correct on disk and becomes an unrecoverable defect if the publish goes out through a tool that
|
|
128
|
+
does not rewrite it: `pnpm` resolves the protocol while packing, `npm` ships the manifest verbatim.
|
|
129
|
+
A version published that way fails to install for everyone and cannot be corrected — only
|
|
130
|
+
deprecated.
|
|
131
|
+
|
|
132
|
+
Every publishable package now runs the guard in `prepublishOnly`, so it fires whichever way the
|
|
133
|
+
publish is invoked, and `pnpm release` runs it once across the repo before `changeset publish`.
|
|
134
|
+
|
|
135
|
+
Note for anyone reading a published manifest: the `prepublishOnly` entry points at a path inside
|
|
136
|
+
this repository. It never runs for a consumer — the hook only fires when the package itself is
|
|
137
|
+
published — and guarding the entry point that a hand-run `npm publish` actually uses was worth the
|
|
138
|
+
cosmetic wart of shipping the line.
|
|
139
|
+
|
|
3
140
|
## 3.0.0
|
|
4
141
|
|
|
5
142
|
### Patch Changes
|
package/LICENSE
CHANGED
|
@@ -137,8 +137,8 @@
|
|
|
137
137
|
|
|
138
138
|
6. Trademarks. This License does not grant permission to use the trade
|
|
139
139
|
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for
|
|
141
|
-
reproducing the content of the NOTICE file.
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
142
|
|
|
143
143
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
144
|
agreed to in writing, Licensor provides the Work (and each
|
package/README.md
CHANGED
|
@@ -77,6 +77,19 @@ supermemoryMemory({
|
|
|
77
77
|
| Network/timeout | `MemoryAdapterError(code: "network")` | true |
|
|
78
78
|
| Other | `MemoryAdapterError(code: "unknown")` | false |
|
|
79
79
|
|
|
80
|
+
## API reference
|
|
81
|
+
|
|
82
|
+
Every symbol this package exports, with the exact specifier to import it from, is in the generated
|
|
83
|
+
capability map that ships inside `@theokit/sdk`:
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
node_modules/@theokit/sdk/docs/harness-capability-map.md # symbol -> import specifier
|
|
87
|
+
node_modules/@theokit/sdk/docs/error-codes.md # every `code` an error can carry
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Both are generated from the built type declarations, so they describe the version you installed
|
|
91
|
+
rather than the version someone wrote a page about.
|
|
92
|
+
|
|
80
93
|
## License
|
|
81
94
|
|
|
82
95
|
Apache-2.0. See [LICENSE](./LICENSE).
|
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","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,MAAM,UAAA,GAAa,kBAAA,CAAmB,MAAA,EAAQ,QAAQ,CAAA;AACtD,EAAA,MAAM,IAAA,GAAiB,CAAC,CAAA,EAAG,UAAU,CAAA,MAAA,EAAS,mBAAmB,GAAA,CAAI,MAAA,EAAQ,QAAQ,CAAC,CAAA,CAAE,CAAA;AACxF,EAAA,IAAI,GAAA,CAAI,YAAY,MAAA,EAAW;AAC7B,IAAA,IAAA,CAAK,IAAA,CAAK,GAAG,UAAU,CAAA,OAAA,EAAU,mBAAmB,GAAA,CAAI,OAAA,EAAS,SAAS,CAAC,CAAA,CAAE,CAAA;AAAA,EA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A,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,QACzE,SAAA,EAAWC,WAAAA;AAAA,QACX,IAAA,EAAM,WAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,IAAI,WAAW,MAAA,IAAa,OAAA,CAAQ,aAAY,CAAE,QAAA,CAAS,SAAS,CAAA,EAAG;AACrE,MAAA,OAAO,IAAID,sBAAAA,CAAmB,CAAA,2BAAA,EAA8B,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,QAC7E,SAAA,EAAWC,WAAAA;AAAA,QACX,IAAA,EAAM,SAAA;AAAA,QACN,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAID,sBAAAA,CAAmB,CAAA,mBAAA,EAAsB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MACrE,SAAA,EAAWC,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;AC5PO,SAAS,kBAAkB,OAAA,EAA4C;AAC5E,EAAA,OAAOI,WAAO,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.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"]}
|
|
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,EAA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CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAID,sBAAAA,CAAmB,CAAA,mBAAA,EAAsB,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,MACrE,SAAA,EAAWC,WAAAA;AAAA,MACX,IAAA,EAAM,SAAA;AAAA,MACN,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF,CAAA;;;ACnPO,SAAS,kBAAkB,OAAA,EAA4C;AAC5E,EAAA,OAAOI,WAAO,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.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/**\n * Configuration accepted by the `supermemoryMemory(...)` factory.\n *\n * @public\n */\nexport interface SupermemoryAdapterOptions {\n /**\n * Supermemory API key, forwarded verbatim to `new Supermemory({ apiKey })`.\n *\n * REQUIRED by this type. The `supermemory` client does default to `SUPERMEMORY_API_KEY` when it\n * receives `undefined`, but this adapter's `isAvailable()` reports `false` for an empty or\n * missing key, and the client is only built on the first `write` / `recall` — so an absent key\n * surfaces as `MemoryAdapterError(code: \"auth_failed\")` at the first call rather than at\n * `Agent.create`.\n */\n apiKey: string;\n /**\n * Base URL for a self-hosted Supermemory, forwarded as the vendor's `baseURL`.\n *\n * Omit it for Supermemory cloud; the vendor then reads `SUPERMEMORY_BASE_URL` and falls back to\n * its own production URL.\n */\n baseUrl?: string;\n /**\n * First segment of every containerTag this adapter writes and searches. Default `\"theokit\"`.\n *\n * Changing it PARTITIONS the memory: entries written under one prefix are invisible to an\n * adapter configured with another, which is what makes it useful for test isolation and\n * dangerous as a casual rename. Must match `/^[a-zA-Z0-9_-]+$/` — a bad value is rejected on the\n * first `write` / `recall`, not at construction.\n */\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 * Wire Supermemory as the agent's long-term memory.\n *\n * ```ts\n * const agent = await Agent.create({\n * model: { id: \"openai/gpt-4o-mini\" },\n * plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],\n * });\n * ```\n *\n * Needs `supermemory@^4.21.0` — a REQUIRED peer dependency, not an optional one; without it the\n * import throws at load time.\n *\n * Scope and shape:\n *\n * - **`sessionId` IS IGNORED** (`capabilities.sessions === false`). Every write for a user lands\n * in the same container regardless of session, and every recall reads it back. If two\n * conversations must not see each other's memories, give them different `ctx.userId` values —\n * `ctx.sessionId` will not separate them.\n * - **Writes are scoped more finely than reads.** `write` tags a document with\n * `<prefix>:user:<userId>` plus `<prefix>:agent:<agentId>`, `<prefix>:tenant:<tenantId>` and one\n * tag per `ctx.tags` entry — but `recall` searches the USER tag alone. The agent/tenant/tag tags\n * are write-side labels, not recall filters.\n * - **`recall` defaults to `k = 10`** with server-side rerank; `k <= 0` returns `[]` without a\n * network call.\n * - **`delete(id)` removes the whole document** that `write` created, not a single extracted fact.\n * - **`history` is unsupported** (`capabilities.history === false`).\n *\n * Trap: every identifier is validated against `/^[a-zA-Z0-9_-]+$/` at CALL time, not at\n * construction. A `userId` such as `\"user:123\"`, an email address, or a\n * {@link SupermemoryAdapterOptions.containerTagPrefix} with a dot makes the FIRST `write` /\n * `recall` throw `MemoryAdapterError(code: \"invalid_input\")`, long after `Agent.create` succeeded.\n *\n * Errors are always `MemoryAdapterError` with `adapterId: \"supermemory\"` and one of\n * `auth_failed` (401/403) | `rate_limited` (429) | `not_found` (404) | `network` |\n * `invalid_input` | `unknown`.\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
|
@@ -10,19 +10,76 @@ import { Plugin } from '@theokit/sdk';
|
|
|
10
10
|
*
|
|
11
11
|
* @public
|
|
12
12
|
*/
|
|
13
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Configuration accepted by the `supermemoryMemory(...)` factory.
|
|
15
|
+
*
|
|
16
|
+
* @public
|
|
17
|
+
*/
|
|
14
18
|
interface SupermemoryAdapterOptions {
|
|
15
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Supermemory API key, forwarded verbatim to `new Supermemory({ apiKey })`.
|
|
21
|
+
*
|
|
22
|
+
* REQUIRED by this type. The `supermemory` client does default to `SUPERMEMORY_API_KEY` when it
|
|
23
|
+
* receives `undefined`, but this adapter's `isAvailable()` reports `false` for an empty or
|
|
24
|
+
* missing key, and the client is only built on the first `write` / `recall` — so an absent key
|
|
25
|
+
* surfaces as `MemoryAdapterError(code: "auth_failed")` at the first call rather than at
|
|
26
|
+
* `Agent.create`.
|
|
27
|
+
*/
|
|
16
28
|
apiKey: string;
|
|
17
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Base URL for a self-hosted Supermemory, forwarded as the vendor's `baseURL`.
|
|
31
|
+
*
|
|
32
|
+
* Omit it for Supermemory cloud; the vendor then reads `SUPERMEMORY_BASE_URL` and falls back to
|
|
33
|
+
* its own production URL.
|
|
34
|
+
*/
|
|
18
35
|
baseUrl?: string;
|
|
19
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* First segment of every containerTag this adapter writes and searches. Default `"theokit"`.
|
|
38
|
+
*
|
|
39
|
+
* Changing it PARTITIONS the memory: entries written under one prefix are invisible to an
|
|
40
|
+
* adapter configured with another, which is what makes it useful for test isolation and
|
|
41
|
+
* dangerous as a casual rename. Must match `/^[a-zA-Z0-9_-]+$/` — a bad value is rejected on the
|
|
42
|
+
* first `write` / `recall`, not at construction.
|
|
43
|
+
*/
|
|
20
44
|
containerTagPrefix?: string;
|
|
21
45
|
}
|
|
22
46
|
|
|
23
47
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
48
|
+
* Wire Supermemory as the agent's long-term memory.
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* const agent = await Agent.create({
|
|
52
|
+
* model: { id: "openai/gpt-4o-mini" },
|
|
53
|
+
* plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* Needs `supermemory@^4.21.0` — a REQUIRED peer dependency, not an optional one; without it the
|
|
58
|
+
* import throws at load time.
|
|
59
|
+
*
|
|
60
|
+
* Scope and shape:
|
|
61
|
+
*
|
|
62
|
+
* - **`sessionId` IS IGNORED** (`capabilities.sessions === false`). Every write for a user lands
|
|
63
|
+
* in the same container regardless of session, and every recall reads it back. If two
|
|
64
|
+
* conversations must not see each other's memories, give them different `ctx.userId` values —
|
|
65
|
+
* `ctx.sessionId` will not separate them.
|
|
66
|
+
* - **Writes are scoped more finely than reads.** `write` tags a document with
|
|
67
|
+
* `<prefix>:user:<userId>` plus `<prefix>:agent:<agentId>`, `<prefix>:tenant:<tenantId>` and one
|
|
68
|
+
* tag per `ctx.tags` entry — but `recall` searches the USER tag alone. The agent/tenant/tag tags
|
|
69
|
+
* are write-side labels, not recall filters.
|
|
70
|
+
* - **`recall` defaults to `k = 10`** with server-side rerank; `k <= 0` returns `[]` without a
|
|
71
|
+
* network call.
|
|
72
|
+
* - **`delete(id)` removes the whole document** that `write` created, not a single extracted fact.
|
|
73
|
+
* - **`history` is unsupported** (`capabilities.history === false`).
|
|
74
|
+
*
|
|
75
|
+
* Trap: every identifier is validated against `/^[a-zA-Z0-9_-]+$/` at CALL time, not at
|
|
76
|
+
* construction. A `userId` such as `"user:123"`, an email address, or a
|
|
77
|
+
* {@link SupermemoryAdapterOptions.containerTagPrefix} with a dot makes the FIRST `write` /
|
|
78
|
+
* `recall` throw `MemoryAdapterError(code: "invalid_input")`, long after `Agent.create` succeeded.
|
|
79
|
+
*
|
|
80
|
+
* Errors are always `MemoryAdapterError` with `adapterId: "supermemory"` and one of
|
|
81
|
+
* `auth_failed` (401/403) | `rate_limited` (429) | `not_found` (404) | `network` |
|
|
82
|
+
* `invalid_input` | `unknown`.
|
|
26
83
|
*
|
|
27
84
|
* @public
|
|
28
85
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -10,19 +10,76 @@ import { Plugin } from '@theokit/sdk';
|
|
|
10
10
|
*
|
|
11
11
|
* @public
|
|
12
12
|
*/
|
|
13
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Configuration accepted by the `supermemoryMemory(...)` factory.
|
|
15
|
+
*
|
|
16
|
+
* @public
|
|
17
|
+
*/
|
|
14
18
|
interface SupermemoryAdapterOptions {
|
|
15
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Supermemory API key, forwarded verbatim to `new Supermemory({ apiKey })`.
|
|
21
|
+
*
|
|
22
|
+
* REQUIRED by this type. The `supermemory` client does default to `SUPERMEMORY_API_KEY` when it
|
|
23
|
+
* receives `undefined`, but this adapter's `isAvailable()` reports `false` for an empty or
|
|
24
|
+
* missing key, and the client is only built on the first `write` / `recall` — so an absent key
|
|
25
|
+
* surfaces as `MemoryAdapterError(code: "auth_failed")` at the first call rather than at
|
|
26
|
+
* `Agent.create`.
|
|
27
|
+
*/
|
|
16
28
|
apiKey: string;
|
|
17
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Base URL for a self-hosted Supermemory, forwarded as the vendor's `baseURL`.
|
|
31
|
+
*
|
|
32
|
+
* Omit it for Supermemory cloud; the vendor then reads `SUPERMEMORY_BASE_URL` and falls back to
|
|
33
|
+
* its own production URL.
|
|
34
|
+
*/
|
|
18
35
|
baseUrl?: string;
|
|
19
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* First segment of every containerTag this adapter writes and searches. Default `"theokit"`.
|
|
38
|
+
*
|
|
39
|
+
* Changing it PARTITIONS the memory: entries written under one prefix are invisible to an
|
|
40
|
+
* adapter configured with another, which is what makes it useful for test isolation and
|
|
41
|
+
* dangerous as a casual rename. Must match `/^[a-zA-Z0-9_-]+$/` — a bad value is rejected on the
|
|
42
|
+
* first `write` / `recall`, not at construction.
|
|
43
|
+
*/
|
|
20
44
|
containerTagPrefix?: string;
|
|
21
45
|
}
|
|
22
46
|
|
|
23
47
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
48
|
+
* Wire Supermemory as the agent's long-term memory.
|
|
49
|
+
*
|
|
50
|
+
* ```ts
|
|
51
|
+
* const agent = await Agent.create({
|
|
52
|
+
* model: { id: "openai/gpt-4o-mini" },
|
|
53
|
+
* plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* Needs `supermemory@^4.21.0` — a REQUIRED peer dependency, not an optional one; without it the
|
|
58
|
+
* import throws at load time.
|
|
59
|
+
*
|
|
60
|
+
* Scope and shape:
|
|
61
|
+
*
|
|
62
|
+
* - **`sessionId` IS IGNORED** (`capabilities.sessions === false`). Every write for a user lands
|
|
63
|
+
* in the same container regardless of session, and every recall reads it back. If two
|
|
64
|
+
* conversations must not see each other's memories, give them different `ctx.userId` values —
|
|
65
|
+
* `ctx.sessionId` will not separate them.
|
|
66
|
+
* - **Writes are scoped more finely than reads.** `write` tags a document with
|
|
67
|
+
* `<prefix>:user:<userId>` plus `<prefix>:agent:<agentId>`, `<prefix>:tenant:<tenantId>` and one
|
|
68
|
+
* tag per `ctx.tags` entry — but `recall` searches the USER tag alone. The agent/tenant/tag tags
|
|
69
|
+
* are write-side labels, not recall filters.
|
|
70
|
+
* - **`recall` defaults to `k = 10`** with server-side rerank; `k <= 0` returns `[]` without a
|
|
71
|
+
* network call.
|
|
72
|
+
* - **`delete(id)` removes the whole document** that `write` created, not a single extracted fact.
|
|
73
|
+
* - **`history` is unsupported** (`capabilities.history === false`).
|
|
74
|
+
*
|
|
75
|
+
* Trap: every identifier is validated against `/^[a-zA-Z0-9_-]+$/` at CALL time, not at
|
|
76
|
+
* construction. A `userId` such as `"user:123"`, an email address, or a
|
|
77
|
+
* {@link SupermemoryAdapterOptions.containerTagPrefix} with a dot makes the FIRST `write` /
|
|
78
|
+
* `recall` throw `MemoryAdapterError(code: "invalid_input")`, long after `Agent.create` succeeded.
|
|
79
|
+
*
|
|
80
|
+
* Errors are always `MemoryAdapterError` with `adapterId: "supermemory"` and one of
|
|
81
|
+
* `auth_failed` (401/403) | `rate_limited` (429) | `not_found` (404) | `network` |
|
|
82
|
+
* `invalid_input` | `unknown`.
|
|
26
83
|
*
|
|
27
84
|
* @public
|
|
28
85
|
*/
|
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,EA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IC,kBAAAA,CAAmB,CAAA,2BAAA,EAA8B,EAAE,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA,EAAI;AAAA,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;;;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"]}
|
|
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,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,IAAI,kBAAA;AAAA,MACR,CAAA,qBAAA,EAAwB,SAAS,CAAA,EAAA,EAAK,KAAK,CAAA,oDAAA,CAAA;AAAA,MAC3C,EAAE,SAAA,EAAW,UAAA,EAAY,IAAA,EAAM,eAAA;A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AO,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/**\n * Configuration accepted by the `supermemoryMemory(...)` factory.\n *\n * @public\n */\nexport interface SupermemoryAdapterOptions {\n /**\n * Supermemory API key, forwarded verbatim to `new Supermemory({ apiKey })`.\n *\n * REQUIRED by this type. The `supermemory` client does default to `SUPERMEMORY_API_KEY` when it\n * receives `undefined`, but this adapter's `isAvailable()` reports `false` for an empty or\n * missing key, and the client is only built on the first `write` / `recall` — so an absent key\n * surfaces as `MemoryAdapterError(code: \"auth_failed\")` at the first call rather than at\n * `Agent.create`.\n */\n apiKey: string;\n /**\n * Base URL for a self-hosted Supermemory, forwarded as the vendor's `baseURL`.\n *\n * Omit it for Supermemory cloud; the vendor then reads `SUPERMEMORY_BASE_URL` and falls back to\n * its own production URL.\n */\n baseUrl?: string;\n /**\n * First segment of every containerTag this adapter writes and searches. Default `\"theokit\"`.\n *\n * Changing it PARTITIONS the memory: entries written under one prefix are invisible to an\n * adapter configured with another, which is what makes it useful for test isolation and\n * dangerous as a casual rename. Must match `/^[a-zA-Z0-9_-]+$/` — a bad value is rejected on the\n * first `write` / `recall`, not at construction.\n */\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 * Wire Supermemory as the agent's long-term memory.\n *\n * ```ts\n * const agent = await Agent.create({\n * model: { id: \"openai/gpt-4o-mini\" },\n * plugins: [supermemoryMemory({ apiKey: process.env.SUPERMEMORY_API_KEY! })],\n * });\n * ```\n *\n * Needs `supermemory@^4.21.0` — a REQUIRED peer dependency, not an optional one; without it the\n * import throws at load time.\n *\n * Scope and shape:\n *\n * - **`sessionId` IS IGNORED** (`capabilities.sessions === false`). Every write for a user lands\n * in the same container regardless of session, and every recall reads it back. If two\n * conversations must not see each other's memories, give them different `ctx.userId` values —\n * `ctx.sessionId` will not separate them.\n * - **Writes are scoped more finely than reads.** `write` tags a document with\n * `<prefix>:user:<userId>` plus `<prefix>:agent:<agentId>`, `<prefix>:tenant:<tenantId>` and one\n * tag per `ctx.tags` entry — but `recall` searches the USER tag alone. The agent/tenant/tag tags\n * are write-side labels, not recall filters.\n * - **`recall` defaults to `k = 10`** with server-side rerank; `k <= 0` returns `[]` without a\n * network call.\n * - **`delete(id)` removes the whole document** that `write` created, not a single extracted fact.\n * - **`history` is unsupported** (`capabilities.history === false`).\n *\n * Trap: every identifier is validated against `/^[a-zA-Z0-9_-]+$/` at CALL time, not at\n * construction. A `userId` such as `\"user:123\"`, an email address, or a\n * {@link SupermemoryAdapterOptions.containerTagPrefix} with a dot makes the FIRST `write` /\n * `recall` throw `MemoryAdapterError(code: \"invalid_input\")`, long after `Agent.create` succeeded.\n *\n * Errors are always `MemoryAdapterError` with `adapterId: \"supermemory\"` and one of\n * `auth_failed` (401/403) | `rate_limited` (429) | `not_found` (404) | `network` |\n * `invalid_input` | `unknown`.\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,9 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/memory-supermemory",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.3",
|
|
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
|
+
"homepage": "https://github.com/usetheokit/theokit-sdk#readme",
|
|
7
|
+
"bugs": "https://github.com/usetheokit/theokit-sdk/issues",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/usetheokit/theokit-sdk.git",
|
|
11
|
+
"directory": "packages/memory-supermemory"
|
|
12
|
+
},
|
|
6
13
|
"type": "module",
|
|
14
|
+
"sideEffects": false,
|
|
7
15
|
"engines": {
|
|
8
16
|
"node": ">=22.12.0"
|
|
9
17
|
},
|
|
@@ -28,19 +36,23 @@
|
|
|
28
36
|
"LICENSE",
|
|
29
37
|
"CHANGELOG.md"
|
|
30
38
|
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"provenance": true,
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
31
43
|
"peerDependencies": {
|
|
32
44
|
"supermemory": "^4.21.0",
|
|
33
|
-
"@theokit/sdk": "^4.0
|
|
45
|
+
"@theokit/sdk": "^4.54.0"
|
|
34
46
|
},
|
|
35
47
|
"devDependencies": {
|
|
36
48
|
"supermemory": "^4.21.1",
|
|
37
49
|
"tsup": "^8.5.0",
|
|
38
50
|
"typescript": "^5.8.0",
|
|
39
51
|
"vitest": "^4.1.8",
|
|
40
|
-
"@theokit/sdk": "4.0
|
|
52
|
+
"@theokit/sdk": "4.54.0"
|
|
41
53
|
},
|
|
42
54
|
"scripts": {
|
|
43
|
-
"build": "tsup",
|
|
55
|
+
"build": "tsup && node ../../tools/repair-dts-imports.mjs .",
|
|
44
56
|
"typecheck": "tsc --noEmit",
|
|
45
57
|
"test": "vitest run"
|
|
46
58
|
}
|