# @persistmemory/sdk

The official TypeScript client for the **PersistMemory** API — memory that persists across every
model, tool and session you use.

[![npm](https://img.shields.io/npm/v/@persistmemory/sdk.svg)](https://www.npmjs.com/package/@persistmemory/sdk)
[![node](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](https://nodejs.org)
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)

- **Typed end to end** — every request and response, including the search explanation
- **Zero dependencies** — ESM and CommonJS builds, nothing transitive
- **Retries that are safe** — GETs retry with jittered backoff; POSTs only with an idempotency key
- **Cursor pagination as an async iterator** — `for await (const memory of client.memories.list())`
- **Errors you can branch on** — `NotFoundError`, `RateLimitError`, `ValidationError`, and more
- **Injectable `fetch`** — your tests cannot open a socket by accident

---

## Table of contents

1. [Install](#install)
2. [Get an API key](#get-an-api-key)
3. [Quick start](#quick-start)
4. [Spaces](#spaces)
5. [Memories](#memories)
6. [Search](#search)
7. [Context assembly](#context-assembly)
8. [Pagination](#pagination)
9. [Errors](#errors)
10. [Retries, timeouts and idempotency](#retries-timeouts-and-idempotency)
11. [Configuration reference](#configuration-reference)
12. [Testing](#testing)
13. [Troubleshooting](#troubleshooting)
14. [FAQ](#faq)

---

## Install

```bash
npm install @persistmemory/sdk
# or
yarn add @persistmemory/sdk
# or
pnpm add @persistmemory/sdk
```

Node 20 or newer. Works in ESM and CommonJS:

```ts
import { PersistMemory } from "@persistmemory/sdk";   // ESM
```
```js
const { PersistMemory } = require("@persistmemory/sdk"); // CommonJS
```

---

## Get an API key

The key is created on the website, and it is shown to you exactly once.

1. **Sign in** to an account with access at <https://persistmemory.com/signin>.
   If you do not have access yet, contact <mailto:support@persistmemory.com>.
2. **Open Settings.** Once you are signed in, *Settings* appears in the header —
   or go straight to <https://persistmemory.com/settings#keys>.
3. **Find “API keys”** and give the new key a name. Name it after *the thing that
   will use it* — `billing-worker`, `laptop`, `staging` — not after yourself. The
   name is how you decide which key to revoke when a laptop goes missing.
4. **Press Create, then copy it immediately.** The key looks like
   `pm_live_` followed by 43 characters. It is stored only as a hash, so nobody —
   including us — can show it to you again. A lost key is revoked and replaced,
   never recovered.
5. **Put it in your environment**, never in your source:

```bash
export PERSISTMEMORY_API_KEY=pm_live_...
```

```ts
const client = new PersistMemory({ apiKey: process.env.PERSISTMEMORY_API_KEY! });
```

### What a key can and cannot do

| A key can | A key cannot |
| --- | --- |
| Read and write your memories | Change your password |
| Create, update and archive your spaces | Create another API key |
| Run search and context assembly | Read anybody else's data |

That asymmetry is deliberate: a leaked key is something you revoke, not an account takeover.
Revoke one at any time in **Settings → API keys → Revoke**; anything using it stops working
immediately.

> **Never commit a key.** If one reaches a git history, a CI log or a screenshot, revoke it and
> create a new one. That takes fifteen seconds and is always the right move.

---

## Quick start

```ts
import { PersistMemory } from "@persistmemory/sdk";

const client = new PersistMemory({
  apiKey: process.env.PERSISTMEMORY_API_KEY!
});

// Choose an existing writable Space explicitly.
const spaceId = process.env.PERSISTMEMORY_SPACE_ID!;
const accepted = await client.memories.remember({
  text: "We chose Postgres for the ledger. Transactions across accounts.",
  spaceIds: [spaceId]
});

console.log(accepted.jobId); // Check processing before searching for this capture.
```

Review the capture as described below. Once it has saved memories and indexing
has finished, search the same Space:

```ts
const found = await client.search.query({
  query: "what did we decide about the ledger database",
  scope: "space",
  spaceIds: [spaceId]
});

for (const result of found.results) {
  console.log(result.score.toFixed(2), result.memory.title);
}
```

> **`remember` returns a job, not a memory.** Extraction, entity resolution and consolidation
> run afterwards, and may produce one memory, several, or none — the same fact said twice
> produces one memory with two pieces of evidence. What comes back is
> `{ status, jobId, note }`. A completed ingestion job is only one stage.
> Use its `documentId`, when available, to review the capture's actual results:

```ts
const job = await client.jobs.get(accepted.jobId);
if (job.documentId) {
  const captured = await client.documents.get(job.documentId);
  console.log(captured.content); // Normalized source, not a document-list summary.
  if (captured.outcome) {
    console.log(captured.outcome.readState, captured.outcome.memoryCount);
    console.log(captured.outcome.pendingCandidateCount);
  }
}
```

`outcome` is absent on older servers. Counts describe currently retained results
citing the document, including previous versions; they do not reconstruct what a
model returned before candidates were pruned. A completed read can have zero
saved memories. An image may not have a readable document until OCR finishes.
The same review is available at `/dashboard/documents/<documentId>`.

### Inspect scan recovery

`jobs.scans` reads `GET /api/v1/jobs/scans` and returns a `Promise<ScanRecoveryPage>`
for one bounded page. The default is `{ limit: 20, state: "open" }`; `limit` must
be an integer from 1 to 100 and `state` is `"open"` or `"all"`. A cursor is an
opaque base64url token of 1–256 characters. Invalid input throws `ValidationError`
before sending a request. Malformed pages throw `INVALID_RESPONSE`, including
unknown statuses, duplicate scan IDs, invalid dates and out-of-range counters.
Returned objects contain only the public fields, including at nested levels.

```ts
const page = await client.jobs.scans({ limit: 20, state: "open" });
for (const scan of page.data) {
  console.log(scan.filename ?? "Scan", scan.recovery);
  if (scan.job) console.log(scan.job.id, scan.job.status);
}
// Keep this token for a later, explicit request; no pages are fetched automatically.
const nextCursor = page.pagination.nextCursor;
// await client.jobs.scans({ limit: 20, state: "open", cursor: nextCursor! });
```

`waiting` describes the first hour; `scheduled` has a future eligibility time;
`due` means eligible, without confirming a dispatch. `nextAttemptAt`, when
present, is an eligibility time and is only allowed for those three states.
`window_ending` means no further automatic recovery is due before the recovery
window closes. A previously accepted attempt may still finish. It has no
`nextAttemptAt`. `exhausted` means four recovery dispatches were used; `expired` means the
seven-day automatic window ended. Neither proves prior jobs have stopped.
`blocked` includes a reason: `space_unavailable` or `capture_changed`.
`completed` and `superseded` are explicit terminal recovery flags retained by
the server. Recovery dispatches are separate from job attempts; inspect an
actual job's status to check its processing. A scan may have neither a document
nor a job yet, so `documentId` and `job` can both be absent. Listing enqueues no
work. An empty page can still carry `pagination.nextCursor`; API errors propagate.

### Replay a failed capture

Use owner credentials (an ordinary API key or session); `pm_space` keys cannot
list or replay failures. `jobs.dead` returns a Promise for one bounded page,
with a default limit of 20 (1–100) and an optional `type`. There is no cursor.

```ts
const failures = await client.jobs.dead({ limit: 20, type: "extract" });
for (const failure of failures.data) {
  console.log(failure.jobId, failure.reason, failure.replay);
}

// Choose one failure after reviewing availability, reason, and requiresForce.
const replay = await client.jobs.replay("chosen-failed-job", { force: false });
console.log(replay.status, replay.warning); // "replayed" or "already-queued"
const progress = await client.jobs.get(replay.jobId);
```

The API checks ownership and current eligibility again when replay is requested.
Pass `force: true` only to explicitly acknowledge a failure requiring it. The
returned job ID can differ from the original failure: poll the returned ID.
Repeating the same failure targets a stable replay job; an already terminal
replay may return 409 without queuing new work.

Replay makes exactly one transport attempt, even with `Retry-After`, an
idempotency key, or a larger `maxAttempts`. It requires a valid 202 response;
malformed replies, timeouts, and network loss throw without resubmitting. After
an uncertain reply, inspect processing jobs before submitting again. Acceptance
or `already-queued` acknowledges queueing, not completed processing or saved memories.

---

## Spaces

A **space** is a boundary around memories. Search inside one and you see only what is in it;
that is the whole point. Use spaces to separate work from personal, one client from another,
or a shared team memory from your own.

### Create a space

```ts
const work = await client.spaces.create({
  name: "Work",
  description: "Decisions, commitments and context for my job",
  kind: "project"
});

console.log(work.id); // pass this to remember/search
```

### Kinds

| `kind` | Use it for |
| --- | --- |
| `user` | Your own personal memory (the default home for anything uncategorised) |
| `project` | One project, client or repository |
| `organizational` | A team or company space, shared by several people |
| `temporary` | Short-lived context — a trip, an incident, a sprint |
| `system` | Reserved for spaces PersistMemory manages for you |

### Multiple spaces

Nothing stops you having many, and a memory can belong to more than one.

```ts
const [work, acme, personal] = await Promise.all([
  client.spaces.create({ name: "Work", kind: "project" }),
  client.spaces.create({ name: "Acme migration", kind: "project", parentId: undefined }),
  client.spaces.create({ name: "Personal", kind: "user" })
]);

// Write into two at once.
await client.memories.remember({
  text: "Acme's cutover is the 14th; Priya signs off.",
  spaceIds: [work.id, acme.id]
});

// Read from one.
const inAcme = await client.search.query({
  query: "when is the cutover",
  spaceIds: [acme.id],
  scope: "space"
});
```

`scope` decides where search is allowed to look:

| `scope` | Meaning |
| --- | --- |
| `"space"` | Only the spaces you named. Nothing else can leak in. |
| `"universal"` | Everything you have, ignoring space boundaries. |
| `"combined"` | The named spaces first, then everything else, ranked together. |

### Deleting a Space

```ts
// The label only — every memory is detached and kept.
await client.spaces.delete(acme.id, { memories: "keep" });

// Everything in it as well.
const { deleted, kept } = await client.spaces.delete(acme.id, { memories: "delete" });
```

There is no default, deliberately: "delete this Space" means the label to some
people and everything inside it to others.

**A memory filed in another Space too is never destroyed** — it is detached and
left where it still belongs. `kept` counts those, `deleted` counts the ones this
Space was the last home for.

### Merging Spaces

```ts
const { space, added } = await client.spaces.merge({
  sourceIds: [work.id, acme.id],
  name: "Everything client-facing"
});
```

Additive, never destructive. Both sources keep exactly what they had, a memory
in both is filed once, and undoing it is deleting the Space that comes back.

### There is no default Space

A capture that names none is REFUSED. `client.memories.remember({ text })` with
no `spaceIds` answers 400, naming the Spaces this account has; the Telegram bot
with no `/space` set keeps nothing and says so; an MCP `remember` with no
`spaceIds` and no `work_in_space` returns an error rather than filing. Nothing
picks a Space on anybody's behalf.

`spaces.setDefault` and `spaces.getDefault` are gone with the two endpoints
they called. What replaces them is per-context rather than per-account: which
Space THIS command line, or this account's ingest address, is working in.

```ts
await client.spaces.chooseWorking(work.id);                   // this profile
await client.spaces.chooseWorking(work.id, { surface: "email" }); // the inbox
const here = await client.spaces.working();                   // { scope, chosen? }
await client.spaces.chooseWorking(null);                       // stop; nothing is kept
```

`null` clears it and is not the same as omitting the field. `chosen` absent
means nothing sent from that context is kept — not that it is kept somewhere
else.

### Nesting, listing, updating, archiving

```ts
// A child space — "Acme" under "Work".
const acme = await client.spaces.create({
  name: "Acme",
  kind: "project",
  parentId: work.id
});

// List them all (paginated; see below).
for await (const space of client.spaces.list()) {
  console.log(space.name, space.kind, space.memoryCount);
}

// Rename, or set a retention window.
await client.spaces.update(acme.id, { description: "Migration, phase 2", retentionDays: 365 });

// Archive rather than delete: the memories stay, the space stops appearing.
await client.spaces.update(acme.id, { archived: true });
```

### Moving memories between spaces

```ts
await client.spaces.addMemories(acme.id, [id1, id2]);
await client.spaces.removeMemories(work.id, [id1]);

// Everything in one space.
for await (const memory of client.spaces.memories(acme.id)) {
  console.log(memory.title);
}
```

---

## Memories

```ts
// Capture. Optionally title it and file it into spaces.
const job = await client.memories.remember({
  text: "Priya prefers async updates over standups.",
  title: "Priya — working style",
  spaceIds: [work.id]
});

// Read one.
const memory = await client.memories.get(memoryId);

// List, filtered by type.
for await (const decision of client.memories.list({ type: "decision" })) {
  console.log(decision.title);
}
```

Memory types: `fact`, `preference`, `decision`, `task`, `commitment`, `event`, and more —
the union is exported as `MemoryType`.

---

## Search

```ts
const found = await client.search.query({
  query: "what did we decide about the ledger",
  types: ["decision"],
  spaceIds: [work.id],
  scope: "space",
  limit: 10,
  minScore: 0.4,
  explain: true
});

if (found.diagnostics.degraded) {
  // Embeddings were unavailable and this fell back to deterministic retrieval.
  // The results are still real; the ranking is weaker. Worth surfacing.
  console.warn("degraded:", found.diagnostics.unavailable);
}

for (const result of found.results) {
  console.log(result.score, result.memory.title, result.explanation?.paths);
}
```

**Read `diagnostics.degraded`.** It is not decoration. Search falls back rather than failing,
and a silent fallback that nobody checks is how a search quietly gets worse for a week.

### Asking about the past

```ts
// What did we believe on the 1st of March, not what we believe now?
const then = await client.search.query({
  query: "our pricing",
  asOf: "2026-03-01T00:00:00Z",
  includeHistorical: true
});
```

---

## Context assembly

For putting memory into a prompt without blowing the window:

```ts
const context = await client.search.context({
  query: userMessage,
  tokenBudget: 1500,
  spaceIds: [work.id],
  scope: "space"
});

const prompt = `${context.context}\n\nUser: ${userMessage}`;

console.log(context.usedTokens, "of 1500", context.truncated ? "(truncated)" : "");
```

`context.context` is a formatted block, ready to paste into a system prompt.
`context.memories` tells you what went into it, so you can cite or debug it.

---

## Pagination

Every list endpoint returns a `Paginated<T>` — four ways to consume it, all lazy:

```ts
// 1. Iterate every item, fetching pages as needed.
for await (const memory of client.memories.list({ type: "task" })) { … }

// 2. One page, for a UI that renders one page.
const page = await client.memories.list({ limit: 50 }).first();
page.data;        // T[]
page.nextCursor;  // undefined means there is no more

// 3. Page by page.
for await (const page of client.memories.list().pages()) { … }

// 4. Up to N items, with a hard ceiling so a bug cannot page forever.
const first200 = await client.memories.list().all(200);
```

> `nextCursor` being absent is the **only** signal to stop. An empty `data` array is not the
> same thing — a page can come back empty because everything in it was filtered out.

---

## Errors

Every failure is an instance of `PersistMemoryError` with a subclass you can branch on:

```ts
import {
  PersistMemory,
  NotFoundError,
  RateLimitError,
  ValidationError,
  AuthenticationError,
  PersistMemoryError
} from "@persistmemory/sdk";

try {
  await client.memories.get(id);
} catch (error) {
  if (error instanceof NotFoundError) return null;
  if (error instanceof RateLimitError) {
    await sleep((error.retryAfterSeconds ?? 1) * 1000);
    return retry();
  }
  if (error instanceof AuthenticationError) throw new Error("Check PERSISTMEMORY_API_KEY");
  if (error instanceof PersistMemoryError) {
    console.error(error.status, error.code, error.requestId);
  }
  throw error;
}
```

| Class | HTTP | Means |
| --- | --- | --- |
| `AuthenticationError` | 401 | Missing, malformed or revoked key |
| `PermissionDeniedError` | 403 | The key is valid but not allowed to do this |
| `NotFoundError` | 404 | No such memory, space or job |
| `ValidationError` | 422 | The request shape was wrong — read `.message` |
| `ConflictError` | 409 | Something changed underneath you |
| `RateLimitError` | 429 | Slow down; carries `retryAfterSeconds` |
| `ServerError` | 5xx | Ours. Retried automatically for GETs |
| `ConnectionError` | — | The request never reached us |
| `TimeoutError` | — | It reached us and did not come back in time |
| `AbortError` | — | You aborted it via `signal` |

Every error carries `requestId` — quote it if you contact support, it is how a request is
found in our logs.

**The key never appears in an error, a log line, or a stringified client.**
`JSON.stringify(client)` prints `{ baseUrl, apiKey: "[redacted]" }`, and so does
`console.log(client)`.

---

## Retries, timeouts and idempotency

GETs are retried with jittered exponential backoff. **POSTs are not** — a POST that timed out
may already have been processed, and this client will not guess. Opt in per request when the
operation is safe to repeat:

```ts
await client.memories.remember(
  { text: "…" },
  { idempotencyKey: crypto.randomUUID(), maxAttempts: 3 }
);
```

Per-request overrides:

```ts
await client.search.query(
  { query: "…" },
  { timeoutMs: 5_000, signal: controller.signal }
);
```

---

## Configuration reference

```ts
const client = new PersistMemory({
  apiKey: process.env.PERSISTMEMORY_API_KEY!,  // required
  baseUrl: "https://api.persistmemory.com",     // default
  timeoutMs: 30_000,
  maxAttempts: 3,
  backoff: { baseMs: 250, maxMs: 8_000, factor: 2, jitter: 0.2 },
  userAgent: "my-app/1.2.3",
  fetch: myFetch                                 // injectable, see Testing
});
```

| Option | Default | Notes |
| --- | --- | --- |
| `apiKey` | — | Required. From <https://persistmemory.com/settings#keys> |
| `baseUrl` | `https://api.persistmemory.com` | Trailing slashes are stripped for you |
| `timeoutMs` | `30000` | Per attempt, not per call |
| `maxAttempts` | `3` | GETs only, unless you pass `idempotencyKey` |
| `backoff` | jittered | `DEFAULT_BACKOFF` is exported if you want to read it |
| `fetch` | `globalThis.fetch` | Anything with the same signature |
| `userAgent` | SDK name and version | Yours is appended, not substituted |

Environment variables the SDK itself reads: **none.** It takes what you pass it, so a test
cannot pick up a real key from your shell by accident. Read `process.env` yourself, once,
where you construct the client.

---

## Testing

Inject a `fetch` and your test can never reach the network:

```ts
const client = new PersistMemory({
  apiKey: "pm_live_test",
  fetch: async (url, init) => {
    expect(String(url)).toContain("/api/v1/search");
    return new Response(JSON.stringify({ results: [], diagnostics: { steps: [], degraded: false, tookMs: 1 }, query: "x" }), {
      status: 200,
      headers: { "content-type": "application/json" }
    });
  }
});
```

`sleep` is injectable too, so a retry test does not spend real seconds waiting.

---

## Troubleshooting

**`AuthenticationError: 401`**
The key is missing, mistyped, or revoked. Check `process.env.PERSISTMEMORY_API_KEY` is actually
set in the process you are running (a `.env` file is not read for you), and that it starts with
`pm_live_`. If in doubt, create a fresh key — it costs nothing.

**`remember` succeeded but `search` finds nothing**
`remember` is asynchronous. Extraction runs after the call returns, so there is a short window
where the job exists and the memory does not. Poll the job id, or search a moment later.

**`search` returns fewer results than expected**
Check `scope`. With `scope: "space"` and a `spaceIds` list, anything outside those spaces is
invisible by design. Try `scope: "combined"`.

**`diagnostics.degraded` is `true`**
Embeddings were unavailable and search fell back to deterministic retrieval. Results are real
but ranked more weakly. Usually transient.

**Rate limited**
`RateLimitError.retryAfterSeconds` comes from the `Retry-After` header. Wait that long, not a
guess of your own.

---

## FAQ

**Does it work in the browser?**
Technically yes, but do not. An API key in a browser is a key you have given away — every
visitor can read it. Call your own server, and let the server hold the key.

**Does it work in Cloudflare Workers / Deno / Bun?**
Yes. The package is dependency-free and uses only `fetch` and standard globals. Pass your
runtime's `fetch` explicitly if it is not on `globalThis`.

**Is there a Python client?**
Yes — `pip install persistmemory`. Same endpoints, same retry policy, same paginator.

**How do I use this from a terminal instead?**
`npm install -g @persistmemory/cli`, then `pm auth login`. It signs in through your browser
with OAuth, so no key is needed at all.

---

## Links

- Documentation — <https://persistmemory.com/docs/sdk>
- API keys — <https://persistmemory.com/settings#keys>
- CLI — <https://persistmemory.com/docs/cli>
- Support — <mailto:hello@persistmemory.com>

## License

MIT © PersistMemory
