kagura-memory 0.7.0 → 0.8.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/README.md CHANGED
@@ -1,495 +1,548 @@
1
- <p align="center">
2
- <strong>Kagura Memory SDK for TypeScript</strong> — Node.js client for <a href="https://github.com/kagura-ai/memory-cloud">Kagura Memory Cloud</a>
3
- </p>
4
-
5
- ## What is this?
6
-
7
- This SDK connects your TypeScript/JavaScript code to [Kagura Memory Cloud](https://github.com/kagura-ai/memory-cloud), giving AI agents the ability to **remember, search, and learn** from past interactions. It is a TypeScript port of the [Python SDK](https://github.com/kagura-ai/kagura-memory-python-sdk) core:
8
-
9
- | Client | Protocol | Use Case |
10
- |--------|----------|----------|
11
- | **`KaguraClient`** | MCP (JSON-RPC) | Direct memory ops — remember, recall, explore, reference, forget |
12
- | **`ResourceClient`** | REST API | External data ingestion — push data from Slack, CI/CD, CRM into Kagura |
13
- | **`FilesClient`** | REST + presigned PUT | File uploads with sha256 integrity binding (R2) |
14
- | **`WorkspaceClient`** | REST API | Workspace member, invitation, and API key management |
15
- | **`AgentsClient`** | REST API | Agent bootstrap for API-key-only callers (no MCP session) |
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install kagura-memory
21
- ```
22
-
23
- Requires Node.js >= 18 (native `fetch`). Zero runtime dependencies —
24
- the one optional peer dependency, for
25
- [zero-knowledge secrets](#the-crypto-package-is-opt-in), is never installed
26
- unless you ask for it.
27
-
28
- ## Quick Start
29
-
30
- ```ts
31
- import { KaguraClient } from "kagura-memory";
32
-
33
- // Credentials resolve automatically: explicit apiKey > KAGURA_API_KEY env
34
- // > OAuth profile (~/.kagura/credentials.json, shared with the Python CLI)
35
- // > .kagura.json
36
- const client = new KaguraClient();
37
-
38
- // Store a memory
39
- const stored = await client.remember({
40
- contextId: "your-context-id",
41
- summary: "User prefers TypeScript strict mode",
42
- content: "Enabled strict + noUncheckedIndexedAccess in all new projects.",
43
- type: "note",
44
- tags: ["typescript", "preferences"],
45
- });
46
-
47
- // Search memories (hybrid semantic + keyword)
48
- const hits = await client.recall({
49
- contextId: "your-context-id",
50
- query: "typescript preferences",
51
- k: 5,
52
- });
53
-
54
- for (const memory of hits.results as Array<Record<string, unknown>>) {
55
- console.log(memory.summary);
56
- }
57
-
58
- await client.close();
59
- ```
60
-
61
- ### Authentication
62
-
63
- Four ways to authenticate, in resolution order:
64
-
65
- 1. **Explicit key** — `new KaguraClient({ apiKey: "kagura_..." })`
66
- 2. **Environment** — `KAGURA_API_KEY` (+ optional `KAGURA_MCP_URL`)
67
- 3. **OAuth profile** — `~/.kagura/credentials.json`, written by `login()`
68
- (below) or the Python CLI's `kagura auth login`. Profiles
69
- (`KAGURA_PROFILE` env or `{ profile: "name" }`) and auto-refresh work
70
- exactly like the Python SDK; the credentials file is shared between both
71
- SDKs.
72
- 4. **Config file** — `.kagura.json` in the working directory or home:
73
-
74
- ```json
75
- {
76
- "api_key": "kagura_your_api_key",
77
- "mcp_url": "https://memory.kagura-ai.com/mcp"
78
- }
79
- ```
80
-
81
- #### Logging in from the terminal
82
-
83
- To authenticate a machine without writing any code:
84
-
85
- ```bash
86
- npx kagura-memory auth login
87
- ```
88
-
89
- `login` / `refresh` / `status` / `use` / `logout`, with the same flag names
90
- as the Python CLI's `kagura auth …`, writing the same
91
- `~/.kagura/credentials.json`. Either tool can create a profile the other
92
- then uses.
93
-
94
- ```bash
95
- npx kagura-memory auth login --profile work --read-only
96
- npx kagura-memory auth status
97
- npx kagura-memory auth use work
98
- npx kagura-memory auth refresh --scope "memory:read"
99
- npx kagura-memory auth logout --profile work
100
- ```
101
-
102
- `status` reports whether each profile is `active`, `expired (refreshable)`,
103
- or `expired` — a profile whose access token lapsed is still usable when it
104
- can refresh.
105
-
106
- This bin covers **authentication only**. Memory operations stay
107
- library-only; use the Python CLI or write TypeScript.
108
-
109
- #### Logging in from TypeScript
110
-
111
- `login()` runs the OAuth 2.0 Device Authorization Grant (RFC 8628) and
112
- writes `~/.kagura/credentials.json` in exactly the format the Python CLI
113
- writes — no Python install needed, and the profile stays interchangeable
114
- between both SDKs.
115
-
116
- ```ts
117
- import { login, KaguraClient } from "kagura-memory";
118
-
119
- const creds = await login({
120
- onUserCode: ({ userCode, verificationUri, verificationUriComplete }) => {
121
- console.log(`Open ${verificationUri} and enter ${userCode}`);
122
- // Or, in a desktop app: shell.openExternal(verificationUriComplete)
123
- },
124
- });
125
-
126
- console.log(`Logged in as ${creds.userEmail} (${creds.workspaceName})`);
127
-
128
- // Subsequent clients pick the profile up automatically.
129
- const client = new KaguraClient();
130
- ```
131
-
132
- There is no terminal IO and no browser launching inside the SDK —
133
- `onUserCode` hands the code back and the host app decides how to show it.
134
-
135
- Scope defaults to `DEFAULT_SCOPE` (`"memory:read memory:write"`) — the same
136
- default as the CLI's `kagura auth login`, and exactly what the server's
137
- pre-registered `kagura-cli` client is seeded with. Pass
138
- `scope: READ_ONLY_SCOPE` for the CLI's `--read-only` behaviour. The two SDKs
139
- share the credentials file, so a profile should not end up with different
140
- authority depending on which one created it.
141
-
142
- The server is resolved as `mcpUrl` > `KAGURA_MCP_URL` > the public default,
143
- matching the CLI's `--server` chain — so a self-hosted deployment is picked
144
- up from the environment. Plain HTTP is rejected for non-loopback hosts: the
145
- flow carries a bearer token.
146
-
147
- Nothing is written unless the exchange succeeds, so a failed login never
148
- disturbs an existing profile: a denial throws `KaguraAuthDeniedError` and an
149
- unapproved expiry throws `KaguraAuthExpiredError`. A response with no
150
- `refresh_token` warns and still persists — the Python CLI treats a
151
- non-refreshable profile as a valid degraded state, and the shared file must
152
- mean the same thing to both SDKs. Check the returned `refreshToken` if you
153
- need to react.
154
-
155
- For a custom flow (your own polling UI, multi-profile management), the
156
- primitives are exported too: `authorizeDevice`, `pollForToken`,
157
- `refreshAccessToken`, `revokeToken`, plus the credentials store
158
- (`loadCredentialsFile`, `updateProfile`, `setDefaultProfile`,
159
- `deleteProfile`, …).
160
-
161
- #### Refreshing
162
-
163
- Clients auto-refresh as tokens near expiry, so most code never calls this.
164
- `refresh()` covers what skew-driven rotation cannot:
165
-
166
- ```ts
167
- import { refresh, READ_ONLY_SCOPE } from "kagura-memory";
168
-
169
- // Forced rotation — e.g. after an upstream 401, when the token was
170
- // revoked out-of-band and is not yet inside the skew window.
171
- await refresh();
172
-
173
- // Narrow an existing grant, no re-consent needed.
174
- await refresh({ scope: READ_ONLY_SCOPE });
175
-
176
- // Widening needs fresh consent, so it re-runs the device flow.
177
- await refresh({
178
- scope: "memory:read memory:write profile:read",
179
- onUserCode: ({ userCode, verificationUri }) =>
180
- console.log(`Open ${verificationUri} and enter ${userCode}`),
181
- });
182
- ```
183
-
184
- The stored refresh token, scope, and workspace identity are preserved when
185
- the server omits them. An expired refresh token throws
186
- `KaguraAuthExpiredError` and leaves the stored profile untouched.
187
-
188
- Callers holding their own provider can use `KaguraOAuth` directly — its
189
- `forceRefresh()` is what `refresh()` builds on, including the
190
- cross-process lock and the "another process already rotated" dedup.
191
-
192
- ### Error handling
193
-
194
- All errors extend `KaguraError`:
195
-
196
- ```ts
197
- import { KaguraNotFoundError, KaguraRateLimitError } from "kagura-memory";
198
-
199
- try {
200
- await client.recall({ contextId, query: "..." });
201
- } catch (e) {
202
- if (e instanceof KaguraNotFoundError) {
203
- // context or memory missing
204
- } else if (e instanceof KaguraRateLimitError) {
205
- console.log(`retry after ${e.retryAfter}s`);
206
- }
207
- }
208
- ```
209
-
210
- Server-side domain errors (`{"status": "error", ...}`) are translated into
211
- exceptions — `KaguraNotFoundError` for missing contexts/memories/reports/
212
- agents/bindings, `KaguraError` otherwise — so you never need to inspect
213
- `result.status`.
214
-
215
- ## `KaguraClient` method reference
216
-
217
- Methods return the parsed server response. Most take a single camelCase
218
- options object; `getAgent`, `deleteAgent`, `listAgentBindings` and
219
- `deleteContext` take the id directly, and the workspace-wide calls
220
- (`listContexts`, `listAgents`, `getUsage`, `getServerInfo`,
221
- `checkServerVersion`, `getEmbeddingStatus`, `listEmbeddingModels`,
222
- `getToolDefinitions`, `close`) take no arguments. The wire stays
223
- snake_case; optional fields are omitted from the request when `undefined`.
224
-
225
- ### Memories
226
-
227
- | Method | What it does |
228
- |--------|--------------|
229
- | `remember` | Store a memory. `details` accepts arbitrary JSON (including `location`, see below); `supersedes` declares this the newer version of an existing memory, shadowing the old one from default recall without destroying it; `deliveryMode: "always"` pins it. |
230
- | `recall` | Hybrid semantic + keyword search. Takes `filters` (`type`, `tags`, `tags_match`, date bounds, `trust_tier`), `searchMode`, `useRerank`, `includeExploreHints`, `includeSuperseded` (read back what `supersedes` shadowed, annotated with `superseded_by`), and `contextIds` for 2–20-context search. |
231
- | `reference` | Full detail for one memory, under `result.memory`. |
232
- | `updateMemory` | Update in place by `memoryId`, or upsert by `externalId`. `details` **replaces** the stored object wholesale — round-trip keys you want to keep. |
233
- | `forget` | Soft-delete (30-day retention) by `memoryId` or by `query`. |
234
- | `listMemories` | Browse with substring, facet, and time-window filters. Omit `contextId` for the caller's cross-context view. |
235
-
236
- ### Deterministic lanes
237
-
238
- These bypass ranking entirely — same inputs, same rows, every call. They are
239
- the counterpart to `recall`'s probabilistic search.
240
-
241
- | Method | Axis |
242
- |--------|------|
243
- | `loadPinned` | The complete, unranked `deliveryMode: "always"` set. Bounded: check `truncated` / `total_available` rather than assuming you got everything. |
244
- | `recallUpcoming` | WHEN — `type: "time"` memories whose window overlaps `from`/`until`, soonest first. |
245
- | `recallNearby` | WHERE — memories near a point, nearest first with `distance_m`. See [the WHERE axis](#the-where-axis--geospatial-memories). |
246
-
247
- ### Tags and the neural graph
248
-
249
- | Method | What it does |
250
- |--------|--------------|
251
- | `listTags` | Tag vocabulary with counts and recency. `prefix` narrows by spelling; `withTags` is a multi-tag AND drill-down that also excludes those tags from the result — the two compose into server-side faceted browsing with no local index. |
252
- | `explore` | Graph traversal from a seed memory (`depth` 1–5, `minWeight`). |
253
- | `listEdges` | Edges touching a memory, incoming and outgoing, deduplicated. |
254
- | `createEdge` / `updateEdge` / `deleteEdge` | Manual edge curation. `(sourceId, targetId)` is the identity; self-loops are rejected. |
255
- | `findDuplicates` | Near-duplicate pairs above `threshold` (0.5–1.0, default 0.90). |
256
- | `feedback` | Record whether a recalled memory was useful — an append-only signal in its own lane, not a memory edit. |
257
-
258
- ### Contexts
259
-
260
- | Method | What it does |
261
- |--------|--------------|
262
- | `listContexts` | All contexts, with the workspace's `can_create` quota flag. |
263
- | `createContext` | New context. Throws `KaguraQuotaError` when the workspace limit is reached. `embeddingModel` is immutable afterwards. |
264
- | `getContextInfo` | Metadata plus, by default, a memory-count breakdown. |
265
- | `updateContext` | Change display name, summary, usage guide, visibility, lock. |
266
- | `deleteContext` | Delete by id. Locked contexts are refused. |
267
- | `mergeContexts` | Move memories between contexts. Both must share an embedding model and workspace. |
268
- | `updateSearchConfig` | Hybrid-search weights (must sum to 1.0 ±0.01). Owner/editor only. |
269
- | `setupResource` | Context + resource entity + ingestion token in one transaction. The returned token is plaintext and shown once. |
270
-
271
- ### Agent run-state
272
-
273
- Ephemeral, TTL-bounded, and excluded from recall — deliberately not memories.
274
-
275
- | Method | What it does |
276
- |--------|--------------|
277
- | `setState` / `getState` | Key/value at `(contextId, key)`. Omit `key` on read to list all live keys. |
278
-
279
- ### Sleep maintenance
280
-
281
- | Method | What it does |
282
- |--------|--------------|
283
- | `getSleepHistory` | Recent runs, newest first. |
284
- | `getSleepReport` | One run in detail, including the per-action audit log. |
285
- | `rollbackSleepRun` | Reverse a completed run. The server commits per step, so a partial rollback is possible — read the returned summary. |
286
-
287
- ### Workspace and server
288
-
289
- | Method | What it does |
290
- |--------|--------------|
291
- | `getServerInfo` | Version and capabilities. |
292
- | `checkServerVersion` | Compare against `MIN_SERVER_VERSION`. Advisory: logs, never throws. |
293
- | `getUsage` | Workspace quota and usage. |
294
- | `getMemoryStats` | Per-memory usage stats, sortable and paged. |
295
- | `getEmbeddingStatus` / `listEmbeddingModels` | Embedding backend state and the models available for `createContext`. |
296
- | `getToolDefinitions` | Raw MCP `tools/list` output — every tool the server exposes, including any this SDK does not wrap yet. |
297
- | `callRawTool` | Call any MCP tool by name — the escape hatch for tools with no typed wrapper. Args pass through verbatim (wire form: `context_id`, not `contextId`) and the result is untyped. Prefer a wrapper where one exists; use this so a missing one is a detour, not a dead end. |
298
- | `close` | Drop the MCP session. The next call re-initializes automatically. |
299
-
300
- Agent Registry and binding methods are covered in
301
- [Agent control plane](#agent-control-plane-memory-cloud-v0490) below.
302
-
303
- ## Agent control plane (memory-cloud v0.49.0+)
304
-
305
- `KaguraClient` wraps the RFC-0002 agent platform: the **Agent Registry**
306
- (`registerAgent` / `listAgents` / `getAgent` / `updateAgent` /
307
- `deleteAgent`), subtractive **context bindings** (`bindAgentContext` /
308
- `listAgentBindings` / `updateAgentBinding` / `unbindAgentContext`), and
309
- the session-start `getAgentBootstrap` call. Registry and binding methods are
310
- **owner/admin-gated** server-side; `deleteAgent` is permanent and
311
- cascades every API key bound to the agent (prefer
312
- `updateAgent({ status: "retired" })` for operational retirement).
313
-
314
- ```ts
315
- // One-time provisioning (owner/admin): register the agent, bind its context
316
- const agent = await client.registerAgent({ name: "ci-agent", framework: "claude-code" });
317
- await client.bindAgentContext({ agentId: agent.id, contextId: "ctx-uuid", isDefault: true });
318
-
319
- // Session start: rehydrate cognitive state in one call
320
- const bootstrap = await client.getAgentBootstrap({
321
- agentId: agent.id, // contextId omitted → default binding
322
- sessionId: "run-42", // echoed in the correlation block
323
- query: "session summary", // enables the trusted-only recall component
324
- });
325
- if (bootstrap.degraded) {
326
- // some component failed fail-soft; inspect bootstrap.components
327
- }
328
- ```
329
-
330
- Deployed agents holding only an API key (e.g. an agent-bound member key)
331
- can bootstrap over REST without an MCP session:
332
-
333
- ```ts
334
- import { AgentsClient } from "kagura-memory";
335
-
336
- const agents = AgentsClient.fromMcpUrl();
337
- const bootstrap = await agents.bootstrap({ agentId: "agent-uuid" });
338
- ```
339
-
340
- Requires memory-cloud **v0.49.0+** — older servers return MCP "tool not
341
- found" / REST 404 on this surface; everything else in the SDK keeps
342
- working against `MIN_SERVER_VERSION`.
343
-
344
- ## The WHERE axis — geospatial memories
345
-
346
- Any memory can carry a location under `details.location`, which makes it
347
- reachable from `recallNearby()` — a deterministic spatial query (nearest
348
- first, each result carrying `distance_m`), not semantic search.
349
-
350
- ```ts
351
- await client.remember({
352
- contextId,
353
- summary: "Coffee shop with reliable wifi",
354
- content: "...",
355
- details: { location: { lat: 35.6812, lon: 139.7671, label: "Tokyo Station" } },
356
- });
357
-
358
- const near = await client.recallNearby({ contextId, lat: 35.68, lon: 139.76, radiusM: 500 });
359
- ```
360
-
361
- `lat`/`lon` must be JSON **numbers** — argument coercion does not recurse
362
- into `details`, so `"35.68"` is rejected server-side with HTTP 422.
363
- `recallNearby()` returns a typed `RecallNearbyResponse`
364
- (`results[].distance_m`); `MemoryLocation` and `NearbyMemory` are exported
365
- too. Out-of-range coordinates throw locally rather than round-tripping.
366
-
367
- > **Gotcha:** `updateMemory()` replaces `details` **wholesale** — the
368
- > server does not deep-merge. Round-trip `location` when updating details
369
- > or the memory silently drops off the spatial axis.
370
-
371
- ## Zero-knowledge secrets
372
-
373
- `SecretClient` is the fourth REST client, alongside Files, Resource and
374
- Workspace. The server stores **only opaque ciphertext**: values are
375
- encrypted to [age](https://age-encryption.org) recipients on your machine
376
- and decrypted there, so a workspace admin — or the server operator — can
377
- enumerate secret names and grants but never read a value.
378
-
379
- ```ts
380
- import { SecretClient, KeyManager, decrypt } from "kagura-memory";
381
-
382
- const secrets = SecretClient.fromMcpUrl();
383
-
384
- // One-time: enroll this machine's age key and register the public half.
385
- // `store` is yours to supply — see "Key custody is yours to wire" below.
386
- const keys = new KeyManager({ store: myKeyStore });
387
- const { recipient, fingerprint } = await keys.enroll();
388
- await secrets.registerPubkey(recipient, "ci-runner");
389
- // ...an owner approves it (verify `fingerprint` out of band first).
390
-
391
- // Store a value, encrypted to every approved recipient.
392
- const active = (await secrets.listPubkeys()).filter((p) => p.status === "active");
393
- await secrets.putSecretForRecipients({
394
- name: "openai/api-key",
395
- plaintext: "sk-live-...",
396
- recipients: active,
397
- });
398
-
399
- // Read it back.
400
- const { ciphertext } = await secrets.fetchSecret("openai/api-key");
401
- const value = await decrypt(ciphertext, await keys.getIdentity());
402
- ```
403
-
404
- Also: `listSecrets`, `revokeGrant`, `deleteSecret`, `verifyAudit`,
405
- `approvePubkey` / `revokePubkey` / `listMyPubkeys`, and the low-level
406
- `putSecret` when you want to build the grant lists yourself.
407
-
408
- Names may contain `/` — `cloudflare/api-token` is addressable, and each
409
- segment is percent-encoded so the separators stay structural. `deleteSecret`
410
- rejects a name with an empty, `.`, or `..` segment rather than encoding it:
411
- those are RFC 3986 *unreserved*, so encoding does not neutralize them and the
412
- URL parser would resolve them away — `cloudflare/../openai` would have
413
- deleted `openai`.
414
-
415
- ### The crypto package is opt-in
416
-
417
- Encryption needs [`age-encryption`](https://www.npmjs.com/package/age-encryption)
418
- (typage, by age's author — the counterpart of the Rust `pyrage` binding the
419
- Python SDK uses). It is an **optional peer dependency**, so a plain
420
- `npm install kagura-memory` still pulls in nothing:
421
-
422
- ```bash
423
- npm install age-encryption
424
- ```
425
-
426
- Everything except `putSecretForRecipients`, `encrypt`, `decrypt`,
427
- `generateKeypair` and `recipientFromIdentity` works without it —
428
- including the whole REST surface, `fingerprint()`, and the armor codec. Call
429
- one of those without the package and you get a `KaguraCryptoError` naming
430
- the install command, not a module-resolution stack trace.
431
-
432
- > **On Node 18.** This SDK supports Node 18 and CI exercises the crypto
433
- > round-trip there on every push. But `age-encryption`'s `@noble/*`
434
- > dependencies declare `engines.node: ">= 20.19.0"`, so `npm install
435
- > age-encryption` on Node 18 prints `EBADENGINE` warnings, and an
436
- > `engine-strict=true` npmrc will refuse the install outright. It works —
437
- > WebCrypto is not a global before Node 19, so the SDK installs
438
- > `node:crypto`'s `webcrypto` itself — but if you want the warnings gone,
439
- > use Node 20.19+.
440
-
441
- Recipients are X25519-only. `age1pq1…` (post-quantum) and plugin
442
- recipients are rejected even though `age-encryption` would accept them,
443
- because `pyrage` cannot read them and the Python CLI has to be able to
444
- decrypt whatever this SDK writes.
445
-
446
- ### Key custody is yours to wire
447
-
448
- Whoever holds the age private key can decrypt every ciphertext ever shared
449
- with the matching recipient, so `KeyManager` takes a `KeyStore` and this SDK
450
- ships **no default backend**:
451
-
452
- ```ts
453
- interface KeyStore {
454
- get(name: string): Promise<string | null>;
455
- set(name: string, value: string): Promise<void>;
456
- delete(name: string): Promise<void>;
457
- }
458
- ```
459
-
460
- The Python SDK defaults to the OS keychain via `keyring`. Node has no
461
- stdlib equivalent, and every option is a native module — so a default here
462
- would mean either a native runtime dependency or a plaintext file, and
463
- Python explicitly refuses the latter. Asking you for a store keeps the
464
- fail-closed property with no insecure fallback to land in by accident.
465
- Back it with `keytar`/libsecret in an app, or with the ambient secret
466
- manager in CI. Keys are stored under `identity:{profile}`, the same names
467
- Python uses, so a shared backend interoperates.
468
-
469
- ## Relationship to the Python SDK
470
-
471
- This package ports the Python SDK's core (client, auth, REST clients,
472
- models). Of the `kagura` CLI only the `auth` subcommands are provided
473
- (`npx kagura-memory auth …`, above); the memory, context, and ingestion
474
- commands are not ported, nor is the document-ingestion pipeline
475
- (`FileIngestor`). The zero-knowledge secret **client** is ported (above);
476
- its `kagura secret` CLI subcommands are not.
477
- (`KaguraAgent` was removed from the Python SDK in v0.37.0 — the actor
478
- role lives in the [kagura-agent](https://pypi.org/project/kagura-agent/)
479
- package, so it will not be ported here.) Use the Python SDK for those;
480
- both SDKs share the same credential files and server APIs. See
481
- [`docs/design/2026-07-05-typescript-port-design.md`](docs/design/2026-07-05-typescript-port-design.md)
482
- for the scope decisions.
483
-
484
- ## Development
485
-
486
- ```bash
487
- npm install
488
- npm test # vitest
489
- npm run typecheck # tsc --noEmit
490
- npm run build # tsup → dist/ (ESM + CJS + d.ts)
491
- ```
492
-
493
- ## License
494
-
495
- MIT
1
+ <p align="center">
2
+ <strong>Kagura Memory SDK for TypeScript</strong> — Node.js client for <a href="https://github.com/kagura-ai/memory-cloud">Kagura Memory Cloud</a>
3
+ </p>
4
+
5
+ ## What is this?
6
+
7
+ This SDK connects your TypeScript/JavaScript code to [Kagura Memory Cloud](https://github.com/kagura-ai/memory-cloud), giving AI agents the ability to **remember, search, and learn** from past interactions. It is a TypeScript port of the [Python SDK](https://github.com/kagura-ai/kagura-memory-python-sdk) core:
8
+
9
+ | Client | Protocol | Use Case |
10
+ |--------|----------|----------|
11
+ | **`KaguraClient`** | MCP (JSON-RPC) | Direct memory ops — remember, recall, explore, reference, forget |
12
+ | **`ResourceClient`** | REST API | External data ingestion — push data from Slack, CI/CD, CRM into Kagura |
13
+ | **`FilesClient`** | REST + presigned PUT | File uploads with sha256 integrity binding (R2) |
14
+ | **`WorkspaceClient`** | REST API | Workspace member, invitation, and API key management |
15
+ | **`SecretClient`** | REST API | [Zero-knowledge secrets](#zero-knowledge-secrets) — age-encrypted on your machine, opaque to the server |
16
+ | **`AgentsClient`** | REST API | Agent bootstrap for API-key-only callers (no MCP session) |
17
+
18
+ A `kagura-memory` command-line tool ships alongside it, mirroring the Python
19
+ CLI's `kagura` command — see [Command line](#command-line).
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install kagura-memory
25
+ ```
26
+
27
+ Requires Node.js >= 18 (native `fetch`). Zero runtime dependencies —
28
+ the one optional peer dependency, for
29
+ [zero-knowledge secrets](#the-crypto-package-is-opt-in), is never installed
30
+ unless you ask for it.
31
+
32
+ ## Quick Start
33
+
34
+ ```ts
35
+ import { KaguraClient } from "kagura-memory";
36
+
37
+ // Credentials resolve automatically: explicit apiKey > KAGURA_API_KEY env
38
+ // > OAuth profile (~/.kagura/credentials.json, shared with the Python CLI)
39
+ // > .kagura.json
40
+ const client = new KaguraClient();
41
+
42
+ // Store a memory
43
+ const stored = await client.remember({
44
+ contextId: "your-context-id",
45
+ summary: "User prefers TypeScript strict mode",
46
+ content: "Enabled strict + noUncheckedIndexedAccess in all new projects.",
47
+ type: "note",
48
+ tags: ["typescript", "preferences"],
49
+ });
50
+
51
+ // Search memories (hybrid semantic + keyword)
52
+ const hits = await client.recall({
53
+ contextId: "your-context-id",
54
+ query: "typescript preferences",
55
+ k: 5,
56
+ });
57
+
58
+ for (const memory of hits.results as Array<Record<string, unknown>>) {
59
+ console.log(memory.summary);
60
+ }
61
+
62
+ await client.close();
63
+ ```
64
+
65
+ ### Authentication
66
+
67
+ Four ways to authenticate, in resolution order:
68
+
69
+ 1. **Explicit key** — `new KaguraClient({ apiKey: "kagura_..." })`
70
+ 2. **Environment** — `KAGURA_API_KEY` (+ optional `KAGURA_MCP_URL`)
71
+ 3. **OAuth profile** — `~/.kagura/credentials.json`, written by `login()`
72
+ (below) or the Python CLI's `kagura auth login`. Profiles
73
+ (`KAGURA_PROFILE` env or `{ profile: "name" }`) and auto-refresh work
74
+ exactly like the Python SDK; the credentials file is shared between both
75
+ SDKs.
76
+ 4. **Config file** — `.kagura.json` in the working directory or home:
77
+
78
+ ```json
79
+ {
80
+ "api_key": "kagura_your_api_key",
81
+ "mcp_url": "https://memory.kagura-ai.com/mcp"
82
+ }
83
+ ```
84
+
85
+ ### Command line
86
+
87
+ `kagura-memory` mirrors the Python CLI's `kagura` command — same
88
+ subcommands, same flag names, same JSON on stdout, same exit codes (2 for
89
+ a usage error, 1 for a runtime failure).
90
+
91
+ ```bash
92
+ npx kagura-memory --help
93
+ ```
94
+
95
+ | Group | Commands |
96
+ |---|---|
97
+ | `auth` | `login` `logout` `refresh` `status` `use` `list` `token` |
98
+ | `context` | `list` `create` `update` `delete` `search-config` (plus the `contexts` alias) |
99
+ | memory | `remember` `recall` `reference` `forget` `update-memory` `explore` |
100
+ | `edge` | `list` `create` `update` `delete` |
101
+ | `sleep` | `history` `report` `rollback` |
102
+ | `files` | `upload` `list` `delete` `download-url` |
103
+ | `resource` | `tokens {list,create,update,revoke}` `list` `setup` `schema` `stats` `indexer-status` `events` `ingest` `ingest-batch` `import` |
104
+ | `secret` | `keygen` `list` `put` `get` `grant` `revoke` `rotate` `delete` `pubkeys` `approve` `audit-verify` `exec` |
105
+ | other | `config show` `doctor` `setup claude` |
106
+
107
+ ```bash
108
+ npx kagura-memory auth login --profile work --read-only
109
+ npx kagura-memory recall "OAuth setup" -c dev -k 10
110
+ npx kagura-memory remember -s "FastAPI DI" --content "Use Depends()" --tags "python,fastapi"
111
+ npx kagura-memory doctor
112
+ ```
113
+
114
+ The context id comes from `-c/--context-id`, or from `context_id` in
115
+ `.kagura.json`. Credentials live in `~/.kagura/credentials.json` and are
116
+ shared with the Python CLI, so either tool can create a profile the other
117
+ then uses.
118
+
119
+ **Not ported.** `kagura ingest` needs the text-extraction pipeline (PDF,
120
+ Office, EPUB, audio) and `kagura process` needs the litellm-backed agent;
121
+ neither exists in this package and both would cost the zero-dependency
122
+ promise. Use the Python CLI for those.
123
+
124
+ **Three deliberate divergences.**
125
+
126
+ - `secret` needs the optional `age-encryption` peer (`npm install
127
+ age-encryption`), exactly as Python's `[secret]` extra works. Key
128
+ custody differs: Python uses the OS keychain via `keyring`, which has no
129
+ zero-dependency equivalent in Node, so this CLI reads the age identity
130
+ from `KAGURA_AGE_IDENTITY` or `KAGURA_AGE_IDENTITY_FILE` and fails
131
+ closed when neither is set. **A key custodied by the Python CLI is not
132
+ readable here, and vice versa.**
133
+ - `setup claude --profile` (the OAuth path) writes an `.mcp.json` that
134
+ launches Python's `kagura-mcp` stdio proxy, which this package does not
135
+ install; that flag reports the fact instead of writing a config that
136
+ would fail at launch. The `--api-key` path works here.
137
+ - `config show` does not reproduce Python's key mask
138
+ (`key[:8] + "..." + key[-4:]`), whose halves overlap below 12 characters
139
+ and print the whole secret twice.
140
+
141
+ One divergence runs the other way, and it is small: `--profile=` and
142
+ `--scope=` reject an explicitly empty value, where click would accept it.
143
+ An empty profile name would create a nameless profile and an empty scope
144
+ would go to the server verbatim. Every other option treats `--flag=` as
145
+ Python does.
146
+
147
+ #### Logging in from TypeScript
148
+
149
+ `login()` runs the OAuth 2.0 Device Authorization Grant (RFC 8628) and
150
+ writes `~/.kagura/credentials.json` in exactly the format the Python CLI
151
+ writes — no Python install needed, and the profile stays interchangeable
152
+ between both SDKs.
153
+
154
+ ```ts
155
+ import { login, KaguraClient } from "kagura-memory";
156
+
157
+ const creds = await login({
158
+ onUserCode: ({ userCode, verificationUri, verificationUriComplete }) => {
159
+ console.log(`Open ${verificationUri} and enter ${userCode}`);
160
+ // Or, in a desktop app: shell.openExternal(verificationUriComplete)
161
+ },
162
+ });
163
+
164
+ console.log(`Logged in as ${creds.userEmail} (${creds.workspaceName})`);
165
+
166
+ // Subsequent clients pick the profile up automatically.
167
+ const client = new KaguraClient();
168
+ ```
169
+
170
+ There is no terminal IO and no browser launching inside the SDK —
171
+ `onUserCode` hands the code back and the host app decides how to show it.
172
+
173
+ Scope defaults to `DEFAULT_SCOPE` (`"memory:read memory:write"`) — the same
174
+ default as the CLI's `kagura auth login`, and exactly what the server's
175
+ pre-registered `kagura-cli` client is seeded with. Pass
176
+ `scope: READ_ONLY_SCOPE` for the CLI's `--read-only` behaviour. The two SDKs
177
+ share the credentials file, so a profile should not end up with different
178
+ authority depending on which one created it.
179
+
180
+ The server is resolved as `mcpUrl` > `KAGURA_MCP_URL` > the public default,
181
+ matching the CLI's `--server` chain — so a self-hosted deployment is picked
182
+ up from the environment. Plain HTTP is rejected for non-loopback hosts: the
183
+ flow carries a bearer token.
184
+
185
+ Nothing is written unless the exchange succeeds, so a failed login never
186
+ disturbs an existing profile: a denial throws `KaguraAuthDeniedError` and an
187
+ unapproved expiry throws `KaguraAuthExpiredError`. A response with no
188
+ `refresh_token` warns and still persists — the Python CLI treats a
189
+ non-refreshable profile as a valid degraded state, and the shared file must
190
+ mean the same thing to both SDKs. Check the returned `refreshToken` if you
191
+ need to react.
192
+
193
+ For a custom flow (your own polling UI, multi-profile management), the
194
+ primitives are exported too: `authorizeDevice`, `pollForToken`,
195
+ `refreshAccessToken`, `revokeToken`, plus the credentials store
196
+ (`loadCredentialsFile`, `updateProfile`, `setDefaultProfile`,
197
+ `deleteProfile`, …).
198
+
199
+ #### Refreshing
200
+
201
+ Clients auto-refresh as tokens near expiry, so most code never calls this.
202
+ `refresh()` covers what skew-driven rotation cannot:
203
+
204
+ ```ts
205
+ import { refresh, READ_ONLY_SCOPE } from "kagura-memory";
206
+
207
+ // Forced rotation — e.g. after an upstream 401, when the token was
208
+ // revoked out-of-band and is not yet inside the skew window.
209
+ await refresh();
210
+
211
+ // Narrow an existing grant, no re-consent needed.
212
+ await refresh({ scope: READ_ONLY_SCOPE });
213
+
214
+ // Widening needs fresh consent, so it re-runs the device flow.
215
+ await refresh({
216
+ scope: "memory:read memory:write profile:read",
217
+ onUserCode: ({ userCode, verificationUri }) =>
218
+ console.log(`Open ${verificationUri} and enter ${userCode}`),
219
+ });
220
+ ```
221
+
222
+ The stored refresh token, scope, and workspace identity are preserved when
223
+ the server omits them. An expired refresh token throws
224
+ `KaguraAuthExpiredError` and leaves the stored profile untouched.
225
+
226
+ Callers holding their own provider can use `KaguraOAuth` directly — its
227
+ `forceRefresh()` is what `refresh()` builds on, including the
228
+ cross-process lock and the "another process already rotated" dedup.
229
+
230
+ ### Error handling
231
+
232
+ All errors extend `KaguraError`:
233
+
234
+ ```ts
235
+ import { KaguraNotFoundError, KaguraRateLimitError } from "kagura-memory";
236
+
237
+ try {
238
+ await client.recall({ contextId, query: "..." });
239
+ } catch (e) {
240
+ if (e instanceof KaguraNotFoundError) {
241
+ // context or memory missing
242
+ } else if (e instanceof KaguraRateLimitError) {
243
+ console.log(`retry after ${e.retryAfter}s`);
244
+ }
245
+ }
246
+ ```
247
+
248
+ Server-side domain errors (`{"status": "error", ...}`) are translated into
249
+ exceptions — `KaguraNotFoundError` for missing contexts/memories/reports/
250
+ agents/bindings, `KaguraError` otherwise — so you never need to inspect
251
+ `result.status`.
252
+
253
+ ## `KaguraClient` method reference
254
+
255
+ Methods return the parsed server response. Most take a single camelCase
256
+ options object; `getAgent`, `deleteAgent`, `listAgentBindings` and
257
+ `deleteContext` take the id directly, and the workspace-wide calls
258
+ (`listContexts`, `listAgents`, `getUsage`, `getServerInfo`,
259
+ `checkServerVersion`, `getEmbeddingStatus`, `listEmbeddingModels`,
260
+ `getToolDefinitions`, `close`) take no arguments. The wire stays
261
+ snake_case; optional fields are omitted from the request when `undefined`.
262
+
263
+ ### Memories
264
+
265
+ | Method | What it does |
266
+ |--------|--------------|
267
+ | `remember` | Store a memory. `details` accepts arbitrary JSON (including `location`, see below); `supersedes` declares this the newer version of an existing memory, shadowing the old one from default recall without destroying it; `deliveryMode: "always"` pins it. |
268
+ | `recall` | Hybrid semantic + keyword search. Takes `filters` (`type`, `tags`, `tags_match`, date bounds, `trust_tier`), `searchMode`, `useRerank`, `includeExploreHints`, `includeSuperseded` (read back what `supersedes` shadowed, annotated with `superseded_by`), and `contextIds` for 2–20-context search. |
269
+ | `reference` | Full detail for one memory, under `result.memory`. |
270
+ | `updateMemory` | Update in place by `memoryId`, or upsert by `externalId`. `details` **replaces** the stored object wholesale — round-trip keys you want to keep. |
271
+ | `forget` | Soft-delete (30-day retention) by `memoryId` or by `query`. |
272
+ | `listMemories` | Browse with substring, facet, and time-window filters. Omit `contextId` for the caller's cross-context view. |
273
+
274
+ ### Deterministic lanes
275
+
276
+ These bypass ranking entirely — same inputs, same rows, every call. They are
277
+ the counterpart to `recall`'s probabilistic search.
278
+
279
+ | Method | Axis |
280
+ |--------|------|
281
+ | `loadPinned` | The complete, unranked `deliveryMode: "always"` set. Bounded: check `truncated` / `total_available` rather than assuming you got everything. |
282
+ | `recallUpcoming` | WHEN — `type: "time"` memories whose window overlaps `from`/`until`, soonest first. |
283
+ | `recallNearby` | WHERE — memories near a point, nearest first with `distance_m`. See [the WHERE axis](#the-where-axis--geospatial-memories). |
284
+
285
+ ### Tags and the neural graph
286
+
287
+ | Method | What it does |
288
+ |--------|--------------|
289
+ | `listTags` | Tag vocabulary with counts and recency. `prefix` narrows by spelling; `withTags` is a multi-tag AND drill-down that also excludes those tags from the result — the two compose into server-side faceted browsing with no local index. |
290
+ | `explore` | Graph traversal from a seed memory (`depth` 1–5, `minWeight`). |
291
+ | `listEdges` | Edges touching a memory, incoming and outgoing, deduplicated. |
292
+ | `createEdge` / `updateEdge` / `deleteEdge` | Manual edge curation. `(sourceId, targetId)` is the identity; self-loops are rejected. |
293
+ | `findDuplicates` | Near-duplicate pairs above `threshold` (0.5–1.0, default 0.90). |
294
+ | `feedback` | Record whether a recalled memory was useful — an append-only signal in its own lane, not a memory edit. |
295
+
296
+ ### Contexts
297
+
298
+ | Method | What it does |
299
+ |--------|--------------|
300
+ | `listContexts` | All contexts, with the workspace's `can_create` quota flag. |
301
+ | `createContext` | New context. Throws `KaguraQuotaError` when the workspace limit is reached. `embeddingModel` is immutable afterwards. |
302
+ | `getContextInfo` | Metadata plus, by default, a memory-count breakdown. |
303
+ | `updateContext` | Change display name, summary, usage guide, visibility, lock. |
304
+ | `deleteContext` | Delete by id. Locked contexts are refused. |
305
+ | `mergeContexts` | Move memories between contexts. Both must share an embedding model and workspace. |
306
+ | `updateSearchConfig` | Hybrid-search weights (must sum to 1.0 ±0.01). Owner/editor only. |
307
+ | `setupResource` | Context + resource entity + ingestion token in one transaction. The returned token is plaintext and shown once. |
308
+
309
+ ### Agent run-state
310
+
311
+ Ephemeral, TTL-bounded, and excluded from recall — deliberately not memories.
312
+
313
+ | Method | What it does |
314
+ |--------|--------------|
315
+ | `setState` / `getState` | Key/value at `(contextId, key)`. Omit `key` on read to list all live keys. |
316
+
317
+ ### Sleep maintenance
318
+
319
+ | Method | What it does |
320
+ |--------|--------------|
321
+ | `getSleepHistory` | Recent runs, newest first. |
322
+ | `getSleepReport` | One run in detail, including the per-action audit log. |
323
+ | `rollbackSleepRun` | Reverse a completed run. The server commits per step, so a partial rollback is possible — read the returned summary. |
324
+
325
+ ### Workspace and server
326
+
327
+ | Method | What it does |
328
+ |--------|--------------|
329
+ | `getServerInfo` | Version and capabilities. |
330
+ | `checkServerVersion` | Compare against `MIN_SERVER_VERSION`. Advisory: logs, never throws. |
331
+ | `getUsage` | Workspace quota and usage. |
332
+ | `getMemoryStats` | Per-memory usage stats, sortable and paged. |
333
+ | `getEmbeddingStatus` / `listEmbeddingModels` | Embedding backend state and the models available for `createContext`. |
334
+ | `getToolDefinitions` | Raw MCP `tools/list` output — every tool the server exposes, including any this SDK does not wrap yet. |
335
+ | `callRawTool` | Call any MCP tool by name — the escape hatch for tools with no typed wrapper. Args pass through verbatim (wire form: `context_id`, not `contextId`) and the result is untyped. Prefer a wrapper where one exists; use this so a missing one is a detour, not a dead end. |
336
+ | `close` | Drop the MCP session. The next call re-initializes automatically. |
337
+
338
+ Agent Registry and binding methods are covered in
339
+ [Agent control plane](#agent-control-plane-memory-cloud-v0490) below.
340
+
341
+ ## Agent control plane (memory-cloud v0.49.0+)
342
+
343
+ `KaguraClient` wraps the RFC-0002 agent platform: the **Agent Registry**
344
+ (`registerAgent` / `listAgents` / `getAgent` / `updateAgent` /
345
+ `deleteAgent`), subtractive **context bindings** (`bindAgentContext` /
346
+ `listAgentBindings` / `updateAgentBinding` / `unbindAgentContext`), and
347
+ the session-start `getAgentBootstrap` call. Registry and binding methods are
348
+ **owner/admin-gated** server-side; `deleteAgent` is permanent and
349
+ cascades every API key bound to the agent (prefer
350
+ `updateAgent({ status: "retired" })` for operational retirement).
351
+
352
+ ```ts
353
+ // One-time provisioning (owner/admin): register the agent, bind its context
354
+ const agent = await client.registerAgent({ name: "ci-agent", framework: "claude-code" });
355
+ await client.bindAgentContext({ agentId: agent.id, contextId: "ctx-uuid", isDefault: true });
356
+
357
+ // Session start: rehydrate cognitive state in one call
358
+ const bootstrap = await client.getAgentBootstrap({
359
+ agentId: agent.id, // contextId omitted → default binding
360
+ sessionId: "run-42", // echoed in the correlation block
361
+ query: "session summary", // enables the trusted-only recall component
362
+ });
363
+ if (bootstrap.degraded) {
364
+ // some component failed fail-soft; inspect bootstrap.components
365
+ }
366
+ ```
367
+
368
+ Deployed agents holding only an API key (e.g. an agent-bound member key)
369
+ can bootstrap over REST without an MCP session:
370
+
371
+ ```ts
372
+ import { AgentsClient } from "kagura-memory";
373
+
374
+ const agents = AgentsClient.fromMcpUrl();
375
+ const bootstrap = await agents.bootstrap({ agentId: "agent-uuid" });
376
+ ```
377
+
378
+ Requires memory-cloud **v0.49.0+** — older servers return MCP "tool not
379
+ found" / REST 404 on this surface; everything else in the SDK keeps
380
+ working against `MIN_SERVER_VERSION`.
381
+
382
+ ## The WHERE axis — geospatial memories
383
+
384
+ Any memory can carry a location under `details.location`, which makes it
385
+ reachable from `recallNearby()` — a deterministic spatial query (nearest
386
+ first, each result carrying `distance_m`), not semantic search.
387
+
388
+ ```ts
389
+ await client.remember({
390
+ contextId,
391
+ summary: "Coffee shop with reliable wifi",
392
+ content: "...",
393
+ details: { location: { lat: 35.6812, lon: 139.7671, label: "Tokyo Station" } },
394
+ });
395
+
396
+ const near = await client.recallNearby({ contextId, lat: 35.68, lon: 139.76, radiusM: 500 });
397
+ ```
398
+
399
+ `lat`/`lon` must be JSON **numbers** — argument coercion does not recurse
400
+ into `details`, so `"35.68"` is rejected server-side with HTTP 422.
401
+ `recallNearby()` returns a typed `RecallNearbyResponse`
402
+ (`results[].distance_m`); `MemoryLocation` and `NearbyMemory` are exported
403
+ too. Out-of-range coordinates throw locally rather than round-tripping.
404
+
405
+ > **Gotcha:** `updateMemory()` replaces `details` **wholesale** — the
406
+ > server does not deep-merge. Round-trip `location` when updating details
407
+ > or the memory silently drops off the spatial axis.
408
+
409
+ ## Zero-knowledge secrets
410
+
411
+ `SecretClient` is the fourth REST client, alongside Files, Resource and
412
+ Workspace. The server stores **only opaque ciphertext**: values are
413
+ encrypted to [age](https://age-encryption.org) recipients on your machine
414
+ and decrypted there, so a workspace admin — or the server operator — can
415
+ enumerate secret names and grants but never read a value.
416
+
417
+ ```ts
418
+ import { SecretClient, KeyManager, decrypt } from "kagura-memory";
419
+
420
+ const secrets = SecretClient.fromMcpUrl();
421
+
422
+ // One-time: enroll this machine's age key and register the public half.
423
+ // `store` is yours to supply — see "Key custody is yours to wire" below.
424
+ const keys = new KeyManager({ store: myKeyStore });
425
+ const { recipient, fingerprint } = await keys.enroll();
426
+ await secrets.registerPubkey(recipient, "ci-runner");
427
+ // ...an owner approves it (verify `fingerprint` out of band first).
428
+
429
+ // Store a value, encrypted to every approved recipient.
430
+ const active = (await secrets.listPubkeys()).filter((p) => p.status === "active");
431
+ await secrets.putSecretForRecipients({
432
+ name: "openai/api-key",
433
+ plaintext: "sk-live-...",
434
+ recipients: active,
435
+ });
436
+
437
+ // Read it back.
438
+ const { ciphertext } = await secrets.fetchSecret("openai/api-key");
439
+ const value = await decrypt(ciphertext, await keys.getIdentity());
440
+ ```
441
+
442
+ Also: `listSecrets`, `revokeGrant`, `deleteSecret`, `verifyAudit`,
443
+ `approvePubkey` / `revokePubkey` / `listMyPubkeys`, and the low-level
444
+ `putSecret` when you want to build the grant lists yourself.
445
+
446
+ Names may contain `/` — `cloudflare/api-token` is addressable, and each
447
+ segment is percent-encoded so the separators stay structural. `deleteSecret`
448
+ rejects a name with an empty, `.`, or `..` segment rather than encoding it:
449
+ those are RFC 3986 *unreserved*, so encoding does not neutralize them and the
450
+ URL parser would resolve them away — `cloudflare/../openai` would have
451
+ deleted `openai`.
452
+
453
+ ### The crypto package is opt-in
454
+
455
+ Encryption needs [`age-encryption`](https://www.npmjs.com/package/age-encryption)
456
+ (typage, by age's author — the counterpart of the Rust `pyrage` binding the
457
+ Python SDK uses). It is an **optional peer dependency**, so a plain
458
+ `npm install kagura-memory` still pulls in nothing:
459
+
460
+ ```bash
461
+ npm install age-encryption
462
+ ```
463
+
464
+ Everything except `putSecretForRecipients`, `encrypt`, `decrypt`,
465
+ `generateKeypair` and `recipientFromIdentity` works without it —
466
+ including the whole REST surface, `fingerprint()`, and the armor codec. Call
467
+ one of those without the package and you get a `KaguraCryptoError` naming
468
+ the install command, not a module-resolution stack trace.
469
+
470
+ > **On Node 18.** This SDK supports Node 18 and CI exercises the crypto
471
+ > round-trip there on every push. But `age-encryption`'s `@noble/*`
472
+ > dependencies declare `engines.node: ">= 20.19.0"`, so `npm install
473
+ > age-encryption` on Node 18 prints `EBADENGINE` warnings, and an
474
+ > `engine-strict=true` npmrc will refuse the install outright. It works —
475
+ > WebCrypto is not a global before Node 19, so the SDK installs
476
+ > `node:crypto`'s `webcrypto` itself — but if you want the warnings gone,
477
+ > use Node 20.19+.
478
+
479
+ Recipients are X25519-only. `age1pq1…` (post-quantum) and plugin
480
+ recipients are rejected even though `age-encryption` would accept them,
481
+ because `pyrage` cannot read them and the Python CLI has to be able to
482
+ decrypt whatever this SDK writes.
483
+
484
+ ### Key custody is yours to wire
485
+
486
+ Whoever holds the age private key can decrypt every ciphertext ever shared
487
+ with the matching recipient, so `KeyManager` takes a `KeyStore` and this SDK
488
+ ships **no default backend**:
489
+
490
+ ```ts
491
+ interface KeyStore {
492
+ get(name: string): Promise<string | null>;
493
+ set(name: string, value: string): Promise<void>;
494
+ delete(name: string): Promise<void>;
495
+ }
496
+ ```
497
+
498
+ The Python SDK defaults to the OS keychain via `keyring`. Node has no
499
+ stdlib equivalent, and every option is a native module — so a default here
500
+ would mean either a native runtime dependency or a plaintext file, and
501
+ Python explicitly refuses the latter. Asking you for a store keeps the
502
+ fail-closed property with no insecure fallback to land in by accident.
503
+ Back it with `keytar`/libsecret in an app, or with the ambient secret
504
+ manager in CI. Keys are stored under `identity:{profile}`, the same names
505
+ Python uses, so a shared backend interoperates.
506
+
507
+ ## Relationship to the Python SDK
508
+
509
+ This package ports the Python SDK's core (client, auth, REST clients,
510
+ models, the zero-knowledge secret client) and, since 0.8.0, 17 of the
511
+ `kagura` CLI's 19 top-level commands — see [Command line](#command-line).
512
+
513
+ Two things are deliberately not ported, and both would cost the
514
+ zero-dependency promise:
515
+
516
+ - **The document-ingestion pipeline** (`FileIngestor`, `kagura ingest`),
517
+ which needs text extraction from PDF, Office, EPUB and audio plus LLM
518
+ providers.
519
+ - **`kagura process`**, which needs the litellm-backed agent.
520
+
521
+ (`KaguraAgent` was removed from the Python SDK in v0.37.0 — the actor role
522
+ lives in the [kagura-agent](https://pypi.org/project/kagura-agent/)
523
+ package, so it will not be ported here either.)
524
+
525
+ Use the Python SDK for those. Both SDKs share the same credential files
526
+ and server APIs, so they interoperate — with one exception, noted above:
527
+ age private keys are custodied differently and are **not** readable across
528
+ the two. See
529
+ [`docs/design/2026-07-05-typescript-port-design.md`](docs/design/2026-07-05-typescript-port-design.md)
530
+ for the original scope decisions.
531
+
532
+ ## Development
533
+
534
+ ```bash
535
+ npm install
536
+ npm test # vitest
537
+ npm run test:no-webcrypto # the same suite with globalThis.crypto deleted
538
+ npm run typecheck # tsc --noEmit
539
+ npm run build # tsup → dist/ (ESM + CJS + d.ts)
540
+ ```
541
+
542
+ `test:no-webcrypto` reproduces Node 18, which has no WebCrypto global —
543
+ the crypto path installs `node:crypto`'s `webcrypto` itself, and that used
544
+ to break in CI only. `prepublishOnly` runs all four.
545
+
546
+ ## License
547
+
548
+ MIT