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

> Capture original conversations and retrieve optional context in your existing Ruby agent.

Keep your model/tool loop. Add Mirrors where your harness records history,
assembles the next model request, and finishes the user turn.
For other languages, see the [TypeScript](https://mirrors.dev/docs/quickstart.md) and
[Python](https://mirrors.dev/docs/quickstart-python.md) quickstarts.

## 1. Install and configure

The Ruby SDK requires **Ruby 3.3 or later** and has no runtime gem dependencies.
Add the published `mirrors-sdk` 0.2.0 release to your Gemfile:

```ruby theme={null}
gem "mirrors-sdk", "~> 0.2.0", require: "mirrors_sdk"
```

Run `bundle install` and keep the resolved version in `Gemfile.lock`. Without
Bundler, use `gem install mirrors-sdk -v 0.2.0`.

No account yet? [Sign up free](https://platform.runmirrors.com/signup); the Hobby
plan needs no card. In the [dashboard](https://platform.runmirrors.com), open your
agent's **Agent setup → SDK connection settings**. Store its API origin, generated
agent ID, and SDK key as `MIRRORS_API_URL`, `MIRRORS_AGENT_ID`, and `MIRRORS_API_KEY`.
The key needs `runtime:read` and `runtime:write`; keep it in server secrets.
Use the API origin without `/v1` or a runtime route.

Create one reusable client per agent configuration **after worker processes fork**:

```ruby theme={null}
require "mirrors_sdk"
require "securerandom"

mirrors = MirrorsSDK::Mirrors.new(
  api_url: ENV.fetch("MIRRORS_API_URL"),
  api_key: ENV.fetch("MIRRORS_API_KEY"),
  agent_id: ENV.fetch("MIRRORS_AGENT_ID")
)
```

A client inherited across a fork stays inactive. Construct a new client inside
each child process and reuse it across that process's turns.

## 2. Capture history and prepare the model request

At user-turn entry, start a timer and give the execution a fresh ID. Map your full
original history into [canonical messages](https://mirrors.dev/docs/guides/trace-capture.md). Ruby methods use
snake\_case, but canonical hashes require **string keys** such as `"messages"` and
`"callId"`. Symbol keys and custom objects are rejected.

In this example, `full_original_history`, the `request` hash, `model.complete`, and
`application_cancellation_error` belong to your application. The last is your
existing cancellation exception. Connect your cancellation hook to `cancel.cancel`.

```ruby theme={null}
turn = mirrors.start_turn
cancel = MirrorsSDK::Cancellation.new
trace = {
  "id" => SecureRandom.uuid,
  "messages" => full_original_history
}
base_system = request.fetch(:system)
mirrors.capture_trace(trace)

selected = mirrors.get_context(trace, timeout_ms: 1000, cancel: cancel)
raise application_cancellation_error if cancel.canceled?

system = selected.context.empty? ? base_system : "#{base_system}\n\n#{selected.context}"
response = model.complete(**request.merge(system: system))
# Continue your existing response, tool, and stream handling.
```

Capture copies and queues evidence without waiting for network delivery. Retrieval
sends its own snapshot and has one total foreground budget of **at most 1,000 ms
from call entry**, including copying and scheduling. Set `timeout_ms` from 1–1000
to shorten it. Ruby or operating-system scheduling can delay return beyond that
budget. This synchronous method blocks its calling thread; use your application's
existing background execution facility when integrating with an event loop.

Empty context is normal in shadow/off mode, on no match, before the first mode
refresh, or during a fallback. Use the returned text promptly for this model call.
Changed history requires fresh retrieval, and every retrieval adds another bounded
wait. Preserve the original request and history; injected context belongs only in
the outgoing prompt.

## 3. Finalize the whole turn

Capture updated original snapshots at your existing history logging points. After
all model calls, tools, retries, and response streaming finish, send the final
original history under the same execution ID:

```ruby theme={null}
ticket = mirrors.capture_trace(
  trace.merge(
    "messages" => completed_original_history,
    "agentContext" => { "systemPrompt" => base_system },
    "turnLatencyMs" => turn.finish
  ),
  final: true,
  terminal: "completed"
)
```

`agentContext` captures the original prompt once on the turn's final snapshot.
It accepts exactly one `"systemPrompt"` string; omit the object when that prompt
is unknown. Earlier snapshots do not supply a missing final prompt. Version 0.2.0
rejects `agentContext.skills`, even beside a valid prompt. Preserve original system
messages without adding duplicate ones.

On failure or cancellation, use `terminal: "failed"` or `"canceled"` in your
existing ending hook, preserving your error handling and available original history.
If no final evidence is available, call `mirrors.release_trace(trace["id"])` for
local cleanup. Terminal status describes how execution ended, not task success.
Returning a stream handle is too early to finalize.

The next turn needs a new execution ID. Use the
[conversation fields](https://mirrors.dev/docs/guides/trace-capture.md#conversation-identity) to group turns
in a continuing chat; send the full cumulative original history each time.

## 4. Inspect delivery and shut down

Inspect `ticket.receipt` outside model execution. If confirmation matters,
`receipt = ticket.wait(2)` waits up to **two seconds** and may still return
`pending`. Other SDK timeout arguments use milliseconds. An `accepted` receipt
with `receipt.ingestion["status"] == "queued"` means analysis is pending.
An `unconfirmed` write may already have committed.

At shutdown, stop admitting turns and let active turns finish:

```ruby theme={null}
delivery = mirrors.close(timeout_ms: 2000)
```

`close` flushes captures pending at entry, then disposes the client. Inspect
`delivery.dropped`, `unconfirmed`, and `pending`; `delivery.complete?` is true only
when every covered ticket was accepted, or there were none. Keep individual
receipts for captures that settled before shutdown. Queues are in memory and
background threads do not keep a finished process alive.

## 5. Verify your integration

Start in [shadow mode](https://mirrors.dev/docs/guides/runtime-modes.md). Run a test conversation, inspect its
final receipt, and confirm the conversation appears in Mirrors. Then verify an
active correction reaches the outgoing model request while stored history stays
original. Exercise tool loops, streaming, cancellation, and an unreachable API.

See the [Ruby SDK reference](https://mirrors.dev/docs/sdk/ruby-reference.md) for methods and limits, or
[troubleshooting](https://mirrors.dev/docs/guides/troubleshooting.md) for empty context and missing captures.


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