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

# Ruby SDK reference

> Ruby client methods, canonical input, delivery receipts, and lifecycle controls.

This reference covers the published `mirrors-sdk` gem **0.2.0**, for Ruby 3.3 or
later. Start with the [Ruby quickstart](https://mirrors.dev/docs/quickstart-ruby.md) to connect your model loop.
The gem has no runtime dependencies beyond Ruby's standard libraries.

## Client and context

Require `"mirrors_sdk"` and create
`MirrorsSDK::Mirrors.new(api_url: ..., api_key: ..., agent_id: ...)` once per agent
configuration. Keep the key in server secrets. Create clients after processes fork;
an inherited client returns `forked_process` and must be replaced in the child.

`get_context(trace, timeout_ms: 1000, cancel: nil)` synchronously returns a
`ContextResult` with these attributes:

| Attribute | Meaning |
| - | - |
| `context` | Text to append to the original system prompt; empty on no match or fallback. |
| `mode` | `active`, `shadow`, or `off`. |
| `delivery` | `accepted`, `unconfirmed`, or `canceled`. |
| `reason` | Decision or fallback reason. |
| `elapsed_ms` | Time spent in retrieval. |
| `freshness` | `nil`, or bindings with `request_id`, `trace_id`, `decision_id`, `mode_version`, `issued_at`, and `expires_at`. |

The total foreground budget is 1–1,000 ms from method entry, including copying and
scheduling. Retrieval sends current history independently of capture uploads.
Scheduling delays can exceed the budget. The method blocks its calling thread;
there is no Ruby async retrieval API.

Use returned text promptly for the same model request. If dispatch is delayed,
check `result.freshness.expires_at`; if history changes, retrieve again. A newer
retrieval, changed evidence, finalization, release, mode change, expiry, disable,
or disposal invalidates pending context. Text already returned cannot be recalled.
`accepted` confirms a response arrived, not that your application used it.

Unknown or expired mode returns empty fallback immediately. Confirmed shadow also
returns empty while evaluating in the background; off performs no retrieval.
Capture continues in every server mode. See [runtime modes](https://mirrors.dev/docs/guides/runtime-modes.md).

## Cancellation

Pass a `MirrorsSDK::Cancellation` token and call its `cancel` method from your
application's cancellation hook:

```ruby theme={null}
cancel = MirrorsSDK::Cancellation.new
# Connect the application's cancellation hook to cancel.cancel.
selected = mirrors.get_context(trace, timeout_ms: 1000, cancel: cancel)
raise application_cancellation_error if cancel.canceled?
```

`application_cancellation_error` is your existing exception, not an SDK class.
Preserve your application's cancellation check before calling its model provider.
A canceled retrieval returns empty context with `delivery == "canceled"`;
the SDK does not cancel a provider call or raise your application's exception.

## Trace capture

`capture_trace(trace, final: false, terminal: nil)` returns a `DeliveryTicket`
without waiting for network delivery. Use full original snapshots, excluding
Mirrors-added context. Canonical hashes use string keys with the JSON field names:
`"conversationId"`, `"conversationRevision"`, `"entryPoint"`, and `"callId"`.
Do not convert keys to symbols or snake\_case. Only builtin JSON values are accepted;
custom objects, cycles, and malformed or oversized data are rejected without
coercion or truncation. Accepted input is copied.

After all model calls, tools, and response streaming end, capture the final history
with `final: true` and `terminal: "completed"`, `"failed"`, or `"canceled"`.
Each new user turn needs a fresh execution ID. See
[trace capture](https://mirrors.dev/docs/guides/trace-capture.md) for message structure and conversation IDs.

| Ticket access | Meaning |
| - | - |
| `ticket.receipt` | Current receipt with `status`, `reason`, and optional `ingestion`. |
| `ticket.wait(2)` | Wait up to two seconds outside model execution; may still return `pending`. |

Receipt statuses are `pending`, `accepted`, `dropped`, and `unconfirmed`.
When ingestion is present, `receipt.ingestion["status"] == "queued"` means analysis
was queued, not completed. `unsupported_history` means no analysis job was queued.
An `unconfirmed` request may already have committed. Final delivery can retry once
within its original deadline using identical request bytes and identity.
Ticket waits accept 0–30 seconds; other SDK timeout arguments use milliseconds.

## System prompt

Optionally include the application's original system prompt on final capture:

```ruby theme={null}
trace["agentContext"] = { "systemPrompt" => original_system_prompt }
```

The object requires exactly one string field. An empty string explicitly means
no prompt; omission means unknown. The prompt permits at most 100,000 UTF-16 code
units, and the complete object permits 262,144 UTF-8 JSON bytes within the snapshot
limit. Capture the prompt before appending Mirrors context.

Intermediate captures and retrieval may also include this object. Include it again
on final capture to retain it; earlier values are never inherited. Preserve original
system messages without adding duplicates. Upgrading from 0.1.0 requires removing
`agentContext.skills`; 0.2.0 rejects it with or without a prompt.

## Optional user and turn timing

* `"user"`: `{ "id" => opaque_internal_id, "segment" => cohort }`. Use an internal
  ID, not an email; `segment` is optional. Trimmed limits are 1–256 UTF-16 code units
  for the ID and 1–64 for the segment, without control characters. The final value is retained.
* `"turnLatencyMs"`: whole-turn duration on **final captures only**. Start
  `turn = mirrors.start_turn` when the message is accepted, before retrieval. Call
  `turn.finish` after models, tools, retries, and streaming finish; its first result
  freezes elapsed milliseconds. Omit unknown duration.

Never send `turnLatencyMs` in a non-final capture or `get_context` call.
Conversation identity requires both `conversationId` and `conversationRevision`;
allocate and persist each new execution's revision atomically, and keep the pair
fixed through that execution. See the
[conversation identity rules](https://mirrors.dev/docs/guides/trace-capture.md#conversation-identity).

## Lifecycle

| Method | Purpose |
| - | - |
| `release_trace(trace_id)` | Local cleanup when no final evidence is available; does not claim server completion. |
| `flush(timeout_ms: 2000)` | Wait for captures pending at call entry and return a `FlushResult`. |
| `close(timeout_ms: 2000)` | Stop new work, flush, and dispose; return the flush result. |
| `dispose` | Cancel optional work without waiting for network completion. |
| `set_enabled(false)` / `set_enabled(true)` | Disable or re-enable locally; use fresh execution IDs after re-enabling. |
| `diagnostics` | Return local capture and execution counters. |

`FlushResult` has `accepted`, `dropped`, `unconfirmed`, and `pending` counts.
`complete?` (also `complete`) is true only when all covered tickets were accepted,
or none were pending at entry. Already-settled tickets and later captures are
excluded. Retain individual receipts when their outcomes matter.

At shutdown, stop admitting turns and finish active work before calling `close`.
The client owns bounded background worker threads, which do not keep a finished
Ruby process alive. Capture queues are in memory and cannot survive a crash.
Use fresh execution IDs after finalization, release, restart, or re-enabling.

## Limits

| Boundary | Limit or default |
| - | - |
| Encoded snapshot | 1,000,000 bytes; 10,000 messages; 50,000 JSON nodes; depth 32. |
| Pending captures | 16 non-final and 16 final snapshots, independently. |
| Active executions / recent final receipts | 64 / 128 per client. |
| Pending retrievals | 16, independent of capture. |
| Capture delivery timeout | 1,000 ms non-final; 6,000 ms final. Constructor `timeout_ms` accepts an integer from 1–30,000 and overrides both. |
| Retrieved context / HTTP response | 32,768 / 65,536 bytes. |

Use HTTPS except for loopback development addresses. Redirects are refused.
Bounded queues and deadlines limit optional work; they do not provide durable
delivery or hard real-time scheduling guarantees.


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