> ## Documentation Index
> Fetch the complete documentation index at: https://usereflect.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK reference

> The public reflect-sdk methods for context retrieval and trace delivery.

This reference covers `reflect-sdk@0.7.0`. Start with the [quickstart](https://usereflect.dev/docs/quickstart.md),
then follow [agent harness integration](https://usereflect.dev/docs/guides/agent-harness.md) to place these calls
in your loop.
For Python methods and result types, see the [Python reference](https://usereflect.dev/docs/sdk/python-reference.md).

## Constructor

`new Reflect({ apiUrl, apiKey, agentId })` creates a client for one agent. Reuse it
across that agent's conversations. Keep keys in server secrets. Node.js 22 or later
is required; ES modules and CommonJS are supported.

## Context retrieval

`getContext({ trace }, { signal?, timeoutMs? })` returns a promise for:

| Field | Meaning |
| - | - |
| `context` | Plain text for the system prompt; empty on no-match or fallback. |
| `mode` | `active`, `shadow`, or `off`. |
| `delivery` | `accepted`, `unconfirmed`, or `canceled`. |
| `reason` | Server decision reason or local fallback reason. |
| `elapsedMs` | Time spent in retrieval. |
| `freshness` | Request, trace, decision, mode-version, issue-time, and expiry bindings; otherwise null. |

The call's `timeoutMs` may shorten the total 1,000 ms wait budget to 1–1,000 ms.
The SDK allows up to 16 concurrent context waits. A newer retrieval for the same
trace supersedes the older pending wait. Changed captured evidence, finalization,
release, local disable, and shutdown invalidate pending retrievals.

`accepted` means a server decision was received. It does not report that your
application applied the context or that the agent succeeded.

Retrieve once before the user turn's model/tool loop. This request carries its own
full original snapshot; it does not wait for a preceding capture to upload.
Use the text immediately. If dispatch is delayed, check `freshness.expiresAt`; if
history changes, retrieve again. The SDK cannot withdraw a string already returned
to your application. Never cache it for another turn.

Pass the application's abort signal and preserve its cancellation handling after
the wait, for example `signal.throwIfAborted()`. A canceled result is data; the SDK
does not abort or invoke your model for you.

Shadow, off, and unknown/expired mode return empty context immediately. The client
learns mode through a background heartbeat, so a first call may return
`mode_unknown`. See [runtime modes](https://usereflect.dev/docs/guides/runtime-modes.md).

## Trace capture

`captureTrace({ trace, final, terminal? })` returns a delivery ticket immediately.
It captures original history in the background without returning context. Call it
at your history logging boundary, then finalize after the last response, tool result
and stream completion have been recorded.

`ticket.receipt` is the current delivery status. `ticket.done` resolves with the
settled receipt. Observe it outside the model execution path. A final capture can
queue ingestion; queued analysis is not completed analysis.

The optional `terminal` value is `completed`, `failed`, or `canceled` and is valid
only on final capture. It describes the execution ending, not task success.
See [trace capture](https://usereflect.dev/docs/guides/trace-capture.md) for the schema and receipt meanings.

### CanonicalTrace

| Field | Meaning |
| - | - |
| `id` | Unique execution ID, minted by your application, unchanged for all snapshots in that run. One run is one billable turn: it is counted once, when Reflect first returns context for it or stores its final capture, whichever comes first, however many user messages, model calls and tool calls it holds. A new ID is a new run. |
| `messages` | Full original conversation history available at this point, including original system instructions. |
| `conversationId`, `conversationRevision` | Optional durable chat identity and increasing run revision; supply both or neither. |
| `model`, `entryPoint` | Optional source labels, fixed within an execution. |
| `completeness` | Optional source qualifications, fixed within an execution. Omit for complete original live history. |
| `agentContext` | Optional application-supplied `{systemPrompt: string}`; capture the original prompt before adding Reflect context. |

`trace.id` identifies the execution. Optional `trace.conversationId` and
`trace.conversationRevision` identify its logical chat and revision; supply both
or neither. The ID follows the execution ID's 1–128 character identifier format.
The revision is a positive safe integer, allocated atomically in durable storage
for each new execution and fixed across all its captures, retrievals and retries.
The server uses revisions to select the latest finalized snapshot. A new execution
cannot reuse another execution's revision. See
[conversation identity](https://usereflect.dev/docs/guides/trace-capture.md#conversation-identity).

Snapshots are limited to 1,000,000 encoded bytes and 10,000 messages. Use ordinary
JSON-compatible data: cyclic objects, accessors and native provider request objects
are not canonical history. Do not silently truncate evidence to fit the limits.

### System prompt

The application can pass its base system prompt through
`trace.agentContext` on capture and retrieval. User prompts stay in `messages`.
This is optional evidence: the SDK does not read files, assemble the provider's
prompt. Original system messages must still be
preserved in history. See the [capture example](https://usereflect.dev/docs/guides/trace-capture.md#system-prompt).

When `agentContext` is present, `systemPrompt` is required. An empty string is a
valid explicit empty prompt. Limits: 100,000 UTF-16 code units for the prompt
and 262,144 UTF-8 JSON bytes for the context. Other fields are rejected.
The context also counts against the complete snapshot limit. Invalid data is
rejected without truncation.

Only the final capture's context is retained in trace readback at
`annotations.agent_context`; earlier values are not carried forward. Values may
change between snapshots. Omission remains compatible with existing clients.
Check installed types and backend support before using this source addition.

## Lifecycle

| Method | Purpose |
| - | - |
| `releaseTrace(traceId)` | Release local execution state when no final evidence is available. Does not claim server completion. |
| `flush({ timeoutMs })` | Wait for captures pending at call time. Returns `complete`, `accepted`, `dropped`, `unconfirmed`, and `pending`. |
| `diagnostics()` | Inspect local delivery and execution counters. |
| `setEnabled(false)` | Locally disable the client and invalidate pending optional work. |
| `setEnabled(true)` | Re-enable a locally disabled client. |
| `dispose()` | Permanently stop the client, including heartbeat and optional work. |

Never reuse a released or completed execution ID. Call `flush` before `dispose`
when you want an explicit bounded capture drain.

`flush.complete` means no covered tickets remain pending, even if some were dropped
or unconfirmed. Inspect the counts and retain individual receipts; flush excludes
already-settled tickets and captures created after it began. It does not wait for
server analysis. Capture queues live in memory and cannot survive a process crash.

## Existing integrations

`sendTrace`, `prefetchTrace`, `submitTrace`, `injectSystemPrompt`, and `close` remain
available for compatibility. Awaiting legacy `sendTrace` does not wait for fresh
context. New integrations should use `getContext` and `captureTrace` directly.

## When the free plan's monthly turns are used up

On the Hobby plan, corrections pause when the month's free turns are used up; your agent
keeps running and capture continues. Three things soften the edge:

* The first time an account reaches the limit, corrections stay on for 100 more turns or
  48 hours, whichever comes first.
* A run that was already in progress when the pause began keeps receiving corrections,
  for up to 30 minutes.
* Responses say what is happening. While the limit is in play they carry a `corrections`
  object: `{ paused: false, reason: "hobby_grace", turns_left, ends_at }` during the
  grace, `{ paused: true, reason: "hobby_allowance", resumes_at }` once paused, and
  `{ paused: false, reason: "hobby_run_in_progress", ends_at }` for a run being served
  past the pause. A context request that is withheld also returns
  `reason: "hobby_allowance"`.

Corrections resume at the start of the next UTC month, or at once on an upgrade.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.