> For the complete documentation index, see [llms.txt](https://docs.gitloom.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gitloom.cloud/documentation/typescript.md).

# TypeScript

```bash
npm install @gitloomhq/sdk   # current: 0.10.0
```

A **drop-in beside the OpenAI and Anthropic SDKs**: wrap the client you already use, your call sites stay exactly as they are — one field richer — and the conversation manages itself.

## Drop-in

```ts
import OpenAI from 'openai'
import { Gitloom, withMemory } from '@gitloomhq/sdk'

const memory = new Gitloom()                 // reads GITLOOM_API_KEY
const openai = withMemory(new OpenAI(), { memory })   // ← the only setup

const res = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'What camera do I own?' }],
  // @ts-expect-error -- GitLoom reads conversation and removes it before the request is sent
  conversation: 'chat-42',                   // ← the only change per call
})
```

`conversation` is not in OpenAI's parameter types yet, so TypeScript needs the `@ts-expect-error` above it; at runtime GitLoom takes the field off the request before OpenAI sees it.

That's the whole loop — you pass **only the new message, never append anything**. Behind the call: the stored conversation supplies the earlier turns, memory is retrieved and injected as background, both turns are stored with the response's real token usage, compaction runs on cadence (default every 5 exchanges) or window pressure, and every compaction feeds the summarized turns to memory ingestion. Untitled conversations get a title automatically. Anthropic clients (`client.messages.create`) wrap identically. Calls without `conversation:` pass through untouched.

Configure the conversations the wrapper opens:

```ts
const openai = withMemory(new OpenAI(), {
  memory,
  conversations: {
    summarize: 'server',      // GitLoom's model compacts…
    // summarize: myFn,       // …or yours, locally
    compactEvery: 5,
    namespace: userId,
  },
})
```

## Added features, on the same client

```ts
const conv = await openai.gitloom.conversation('chat-42')

await conv.rewind(6)                                              // fork after seq 6
await conv.edit(4, { role: 'user', content: 'ask differently' })  // fork at same seq
await conv.editInPlace(4, { content: '[redacted]' })              // destroy the original (PII)
await conv.setTitle('Camera shopping')
await conv.branches()
```

These act on the **same managed conversation** the completions flow through — a rewind here is what the next `create({ conversation })` continues from.

## Recall, filtered and answered

`openai.gitloom.memory` — or a bare `new Gitloom()` — reaches the memory directly.

```ts
// Ranked memories, no model call. Milliseconds.
const { memories } = await memory.recall('what camera do I own', {
  tiers: ['facts'],                 // facts | incidents | rules | skills
  paths: ['facts/gear'],            // any directories
  tags: ['camera'],
  since: '2026-01-01',
  minScore: 0.3,
  limit: 8,
})
for (const m of memories) console.log(m.score.toFixed(2), m.path, m.matched, m.content)

// One text answer from a fast model over that retrieval …
const { answer, memories: evidence } = await memory.answer('what camera do I own')
// … or let a stronger model search the memory itself with tools.
const agentic = await memory.answer('which of my trips had the longest flight', { agentic: true })
console.log(agentic.answer, agentic.trace)
```

Each entry is **one whole memory**, not a scattering of its sections — `content` is the full body and `sections` names the headings that matched. `score` is a calibrated relevance in `[0, 1]`, comparable across queries, so `minScore` means the same thing whatever was asked. `matched` says which arms produced it; matched only by `graph` is context that rode in beside a real match, and `via` names what pulled it in. Pass `detail: 'full'` for revision history, the last diff, relation snippets and cues.

Filters apply **inside every retrieval arm** server-side, so confining a query to a directory is a real boundary rather than a cut made after the fact.

`answer` is metered as a chat, not a read, and throws rather than returning an empty string when the model finds nothing to say. `recall` with `mode: 'summary'` or `mode: 'agentic'` is the same thing with the memories and timings alongside.

## Tags and when it happened

```ts
await memory.remember(
  [{ role: 'user', content: 'We signed the lease on the Koramangala flat today.' }],
  { tags: ['home', 'lease'], occurredAt: '2026-03-01', timezone: 'Asia/Kolkata' },
)
```

Every memory drawn from the conversation carries the tags, and is dated by when the conversation happened rather than when you sent it, so a backfill of last year's transcripts does not all land on today. `occurredAt` takes a `Date` (sent as epoch seconds), epoch seconds, or a string: RFC 3339 with an offset, a date (`YYYY-MM-DD`, that calendar day), or a datetime without an offset, read in `timezone`. `date` still works and is deprecated.

Tags are trimmed and lowercased, and hold letters, digits, spaces and `- _ . : / # @`, up to 32 tags of 64 characters. A refusal throws a `GitloomError` whose `code` is `invalid_tag`, `invalid_date` or `invalid_timezone`, and whose message names the field.

Recalled memories carry `userTags`, yours alone, lowercased and sorted rather than in the order you sent them; `tags` lists those first, then the inferred ones, also sorted. They carry `createdAt`, `updatedAt`, `occurredAt` and `expiresAt` as `Date`s. `occurredPrecision: 'day'` means only the date is known, held as noon UTC on it, so show it as a date; `occurredSource` says how it is known. The `created` and `updated` strings remain, deprecated.

## Listing without a question

```ts
// No question: every memory the filters match, newest first by timeField.
const { memories: leases } = await memory.recall({
  tags: ['lease'],
  timeField: 'occurred',   // occurred | created | updated (default)
  since: '2026-01-01',
  until: '2026-03-31',     // a date alone includes that whole day
  tz: 'Asia/Kolkata',      // reads dates and offset-less times
})
```

`since` and `until` take what `occurredAt` takes, and narrow a question the same way. Without a query, at least one of `tags`, `tagsAll`, `since`, `until`, `tiers` or `paths` is needed, and the SDK throws `missing_query` before sending otherwise. Every match scores 1, and `mode` must be `raw` with no `rank`.

## Direct memory

`remember` has a model decide what a conversation holds. When you already know what a memory says and where it belongs, such as in a migration or an agent filing its own conclusion, store it as written:

```ts
await memory.write([
  { path: 'facts/home/lease.md', content: 'The Koramangala lease runs to 2027-02-28.',
    tags: ['home', 'lease'], occurredAt: new Date('2026-03-01T10:30:00+05:30'),
    cues: ['when does my lease end'] },
])

// Seconds later, once the write has landed:
const file = await memory.get('facts/home/lease.md')        // or 'file.md#section'
const { topics } = await memory.topics({ like: 'home' })    // check before inventing a topic
const { tree } = await memory.tree({ path: 'facts', depth: 2 })
const { nodes, edges } = await memory.graph()
await memory.forget(['facts/home/lease.md'])
```

Paths sit under `facts/`, `incidents/`, `rules/` or `skills/`, and one that does not end in `.md` is refused before anything is sent. `write` and `forget` are asynchronous like `remember`, and `forget` leaves earlier revisions in git history. Send writes in batches: one call is one commit round.

## Vocabulary and skills

```ts
// Teach abbreviations and domain terms. A recall for "k8s" then also finds
// memories written "kubernetes", and the definition comes back as `defined`.
await memory.vocab.learn([
  { term: 'kubernetes', aliases: ['k8s', 'kube'], definition: 'Container orchestration.' },
])
await memory.vocab.lookup('k8s')          // → { term: 'kubernetes', aliases: [...] }
await memory.vocab.list({ like: 'kube' })
await memory.vocab.forget(['kubernetes'])

// Store how things are done; find the skill that fits a task.
await memory.skills.store([
  { name: 'Deploy to production', topic: 'ops', description: 'Ship a release.',
    content: '## Steps\n1. Tag the release.\n2. `make deploy ENV=prod`',
    triggers: ['how do I ship a release', 'deploy to prod'] },
])
const [skill] = await memory.skills.find('release the new build')
```

Skills are memories under the `skills/` tier, so `recall(q, { tiers: ['skills'] })` reaches them too, and `find_skill` is exported beside `recall_memory` and `save_memory` in every tool format — OpenAI, Anthropic and [MCP](/documentation/mcp.md).

In those tools, `recall_memory` takes `tags`, `since`, `until` and `time_field` (default `occurred`), and lists by filter when the model leaves out `query`. Each memory it hands back starts with the day it happened, such as `- [2026-03-01] …`. `save_memory` takes `tags` and `occurred_at`.

## Multimodal

```ts
// Upload the photo once and hand the model a short-lived URL to it, so the
// stored turn holds a reference rather than the bytes.
const { id } = await memory.media.upload({ contentType: 'image/png', base64: b64 })
const { url } = await memory.media.get(id)

await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: [
    { type: 'text', text: "what's in this photo?" },
    { type: 'image_url', image_url: { url } },
  ] }],
  // @ts-expect-error -- GitLoom reads conversation and removes it before the request is sent
  conversation: 'chat-42',
})
```

Content parts go to the model exactly as you write them, so they take the provider's own shape. `textPart`, `imagePart` and `imageData` build GitLoom's parts for `conv.append()` on a conversation you drive yourself, where `imageData`'s bytes are uploaded on append and stored by reference.

The URL expires after 15 minutes; in a conversation that stays open longer, fetch a fresh one with `memory.media.get(id)` before the image is sent again.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.gitloom.cloud/documentation/typescript.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
