> ## 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.

# Capture conversation traces

> Preserve original history, tool associations, and completion state.

A trace describes one execution. Send the full original history
available at each capture point, using the same `id` until that execution ends.
Create a new ID for a new execution, including after restarting your process.
For a chat agent, use one execution per user turn, covering all of its model calls,
tool calls and streaming. See [agent harness integration](https://usereflect.dev/docs/guides/agent-harness.md)
for the placement of capture, retrieval and completion hooks.

## Map your harness history

Capture from the history your application owns, before adding Reflect context to
the provider request. Each capture is a complete snapshot, not a message delta.

| In your harness | In the canonical trace |
| - | - |
| Base system prompt | `system` message containing the original instructions. |
| User input and model replies | `user` and `assistant` messages in their original order. |
| Model's tool request | An assistant `tool-call` block with its actual ID, name and arguments. |
| Tool execution result | A `tool-result` block using the same call ID and name, with its value and error flag. |
| Available reasoning | A `reasoning` block in its original position; include only what your source supplies. |
| Reflect context | Keep it in the outgoing prompt only; exclude it from the original trace. |

If your provider stores the system prompt separately from `messages`, include that
base prompt when building the canonical snapshot. Do not pass a native provider
request with signals, functions or tool definitions as a trace.

The examples below use TypeScript. Python uses dictionaries and Ruby uses
string-key hashes with the same canonical keys, including camelCase `callId`,
`entryPoint`, `conversationId`, and `conversationRevision`; do not convert these
keys to snake\_case or Ruby symbols. See the [Python](https://usereflect.dev/docs/quickstart-python.md) and
[Ruby](https://usereflect.dev/docs/quickstart-ruby.md) quickstarts for examples.

```ts theme={null}
import { randomUUID } from "node:crypto";
import type { CanonicalTrace } from "reflect-sdk";

const trace: CanonicalTrace = {
  id: randomUUID(),
  messages: [
    { role: "system", content: "Answer questions using the order lookup tool." },
    { role: "user", content: "Has order 123 shipped?" },
    {
      role: "assistant",
      content: [{
        type: "tool-call",
        callId: "lookup-1",
        name: "lookup_order",
        arguments: { orderId: "123" },
      }],
    },
    {
      role: "tool",
      content: [{
        type: "tool-result",
        callId: "lookup-1",
        name: "lookup_order",
        value: { status: "shipped" },
        error: false,
      }],
    },
    { role: "assistant", content: "Order 123 has shipped." },
  ],
};
```

This is an illustrative completed conversation. Map your application's actual
history into this format; do not substitute the example for real evidence.

## System prompt

With a compatible TypeScript SDK artifact and backend, pass configuration from the
same application state you use to assemble the provider request:

```ts theme={null}
const trace: CanonicalTrace = {
  id: executionId,
  messages: originalMessages, // Includes user prompts and original system messages.
  agentContext: {
    systemPrompt: baseSystemPrompt,
  },
};
reflect.captureTrace({ trace, final: true }); // At the execution's actual end.
```

Use the base prompt before adding Reflect context. This is an explicit text input;
the SDK does not inspect files or provider requests. This does not replace the
original message history or change what the model receives.

The same optional field can accompany `getContext`. Include it again on the final
capture to retain it in `annotations.agent_context`; omission on the final means
unknown even if an earlier snapshot included it. Snapshots are independent, so
concurrent runs can supply different prompts. See the
[SDK reference](https://usereflect.dev/docs/sdk/reference.md#system-prompt) for bounds. Verify both the
installed artifact and deployed API/worker readers support this source feature
before sending it; publication and deployment are separate steps.
Ruby accepts the same prompt-only object as
`{ "agentContext" => { "systemPrompt" => base_system_prompt } }`; see the
[Ruby reference](https://usereflect.dev/docs/sdk/ruby-reference.md#system-prompt).

## Conversation identity

TypeScript SDK 0.7.0, Python source SDK 0.1.0, and Ruby SDK 0.2.0 can connect successive executions
to one logical conversation. Add both fields to every capture and context request
after the compatible backend is deployed:

```ts theme={null}
const trace: CanonicalTrace = {
  id: persistedRun.executionId,
  conversationId: persistedRun.conversationId,
  conversationRevision: persistedRun.conversationRevision,
  messages: fullOriginalHistory,
};
```

`persistedRun` is the application's durable run record, not an SDK helper. Allocate
the revision atomically when the run starts, persist it before any SDK request, and
reuse it for every snapshot and retry in that execution. It must be a positive safe
integer greater than all earlier revisions for this conversation. Do not use a
timestamp, message count or in-memory counter. Gaps between revisions are allowed.

Use the same conversation ID for later turns and after restarting the application,
with a fresh execution ID and revision for each new run. Give branched/copied chats
distinct conversation IDs. IDs allow letters, digits, `_`, `.`, and `-`, with a
maximum of 128 characters; scope them uniquely within each agent.
Two executions claiming the same conversation revision conflict.

The compatible backend keeps the latest finalized revision as the conversation's
current snapshot, even if older executions arrive later. Older snapshots and their
evidence links are retired. This is why later runs must send full cumulative original
history: they cannot depend on the older snapshots remaining available.
Keep the two fields fixed within the execution. They are optional together: legacy
integrations omitting both retain their independent-trace behavior.

## Preserve the source

Messages support `system`, `user`, `assistant`, and `tool` roles. Content can be a
string or ordered blocks: `text`, `reasoning`, `tool-call`, `tool-result`, or `media`.
Preserve tool-call IDs and their corresponding results, including error flags.
Include reasoning only when it is already present in the source history.
The canonical wire format can represent more than the current analysis pipeline
supports: media and provider-executed tools can produce an `unsupported_history`
ingestion receipt. Do not remove them to make a trace appear supported.

Do not invent missing messages, flatten tool results into unrelated text, mutate
original history, or capture Reflect-added context as an original instruction.
If the source is incomplete, use the trace's `completeness` fields to describe that
fact rather than representing it as a complete execution.

Keep `completeness`, `model`, `entryPoint`, and the conversation fields unchanged for a trace across capture
and context requests. Use `final` and `terminal` to report live completion; these
metadata fields are not a progress indicator.

The SDK rejects malformed evidence and limits a canonical snapshot to 1,000,000
encoded bytes and 10,000 messages. Do not silently truncate data to fit. Decide
which conversations can be captured faithfully and inspect dropped receipts.

## Capture and completion

TypeScript's `captureTrace({ trace, final: false })`, Python's
`capture_trace(trace, final=False)`, and Ruby's `capture_trace(trace, final: false)`
queue background capture without waiting for network delivery. On completion,
send the full final snapshot with `final: true` (TypeScript and Ruby) or
`final=True` (Python), and the appropriate terminal status.
Accepted final captures queue ingestion when the history supports analysis. A
receipt with ingestion `unsupported_history` has no analysis job; inspect the
original message structure and supported content.

One execution is one billable turn. It is counted as soon as Reflect returns context for
it, and otherwise when its `final` capture is stored. A finished execution ID cannot be
used again.

`final` ends this execution; the logical chat can continue with a new execution ID
and revision. Preserve the application's existing run completion, failure and
cancellation hooks. Returning a stream object or receiving a tool result does not
mean the execution ended. An explicit end-chat button is not required.

If execution fails or is canceled, capture the original evidence available at that
point with terminal status `"failed"` or `"canceled"`. If no final evidence is available,
use `releaseTrace(traceId)` in TypeScript or `release_trace(trace_id)` in Python and Ruby
for local cleanup. Do not reuse the ID. A `completed` terminal status means the
loop finished, not that the agent's answer was correct.

| Receipt | Meaning |
| - | - |
| `pending` | The SDK has not settled delivery. |
| `accepted` | The server accepted the request. Inspect ingestion separately. |
| `dropped` | The SDK rejected or could not queue the request; inspect `reason`. |
| `unconfirmed` | Transport did not establish acceptance. The write may still have committed. |

All three SDKs expose `ticket.receipt`. Outside model execution, TypeScript can await
`ticket.done`; Python can call `ticket.wait(timeout=2)` or
`await ticket.wait_async(timeout=2)`; Ruby can call `ticket.wait(2)`.
Python and Ruby ticket timeouts are **seconds**, and a bounded wait may still
return a `pending` receipt.

Capture uses bounded in-memory queues; it does not promise durable delivery after a
crash. At shutdown, flush pending captures before disposing the client. Python and
TypeScript give the flush result's `complete` flag different meanings; see
[shutdown troubleshooting](https://usereflect.dev/docs/guides/troubleshooting.md#shutdown-loses-pending-captures)
and the [Python SDK reference](https://usereflect.dev/docs/sdk/python-reference.md). Ruby's `close(timeout_ms: 2000)`
flushes and disposes; its `complete?` is true only when all covered tickets were
accepted. See the [Ruby lifecycle reference](https://usereflect.dev/docs/sdk/ruby-reference.md#lifecycle).


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