---
name: driftrail-agents
description: Instrument an existing agent with DriftRail, verify its trace, and prepare reviewed regression or replay experiments. Use for DriftRail agent telemetry and harness evaluation setup.
---

# DriftRail agent setup

Use the application's existing orchestration and provider clients. Check installed package versions first: use `@drift_rail/sdk` 2.7.0+ or `@drift_rail/browser` 2.5.0+ for coordinated experiments and tool idempotency. The backend must support these releases and have `agents_execution.sql` applied.

1. Put a scoped `agents:write` key and application ID in the server's environment. Use `agents:read` for trace inspection and `agents:manage` only for authorized harness/dataset/experiment management. Never put a management key in a shipped browser bundle. Browser feedback can use a backend-issued one-run feedback token.
2. Register an immutable harness manifest when authorized, then reference its `harness_id` in `client.agents.withRun`. Use `run.model(name, callback, { model, provider })` around final provider responses and `run.wrapTool(name, tool)` around JSON-argument tools. Browser work uses explicit run/step handles; Node also supports ambient `client.agents.wrapTool` and `wrapModel` inside `withRun`.
3. Keep content capture off unless the user has authorized capturing task inputs, tool arguments/results and outputs. With `{ captureContent: true }`, pass task `input` and preserve safe JSON tool inputs/results. Credentials are redacted; tenant privacy policy may remove evidence required for replay. Await `withRun` in short-lived/serverless processes.
4. Mark task success only after verifying the result in the application's environment. Completion and success are separate. Pass final stream usage explicitly after consumption. Cache and reasoning token counts are subsets of inclusive totals; unknown cost is not zero. Explicit provider costs are appropriate for negotiated or nonstandard pricing.
5. Verify a synthetic task using the same app: `client.agents.getRun(runId)` and Agents → Runs. Check model/tool parent relationships, final status, usage coverage and harness version. Do not execute a real payment, email or other consequential tool merely to verify telemetry.

For existing exporters, the endpoint is `/api/agents/otlp`, authenticated with the same app/key headers. It accepts 1–100 spans of OTLP JSON using the documented `genai-openinference-json-v1` mapping. Content capture requires `?capture_content=true`. It does not accept OTLP protobuf or promise every framework attribute.

## Improve from evidence

Use Diagnosis to inspect observed check failures and inferred patterns. A first observed error is not proven root cause. Missing or redacted content makes checks unavailable. Checks belong to immutable harness manifests and use JSON pointers with `exists`, `equals`, `not_equals` or `max_chars`.

For an authorized reviewed change, `prepareImprovement(runId, {...})` creates a regression snapshot and pinned baseline/candidate experiments atomically. Reuse the same request ID and exact payload after a lost response. The source run must be finished, have task input and reference a registered harness. Review expected output and the new candidate version; preparation does not activate it.

Execute `runAgentExperiment(client.agents, { experimentId, task, evaluator })` in the customer process/CI. The task receives the pinned manifest in its context; it must actually apply those instructions/configuration. Reference answers go only to the evaluator.

Independent jobs must share the pinned experiment ID. The runner automatically acquires/renews/releases exclusive backend ownership, refreshes completed results and fences stale submissions. Competing owners receive 409 and can retry later; use the owner's `concurrency` for workers. Keep the evaluator version and live/replay measurement scope unchanged when resuming. Cancelled grading stays unscored.

For authorized side effects, set a stable business-action `idempotencyKey` on a tool step/wrapper, provide explicit JSON input and return a compact non-sensitive JSON receipt. Forward `step.idempotencyKey` to the provider; explicit callbacks can use `step.idempotencyInput` as the pinned input snapshot. Wrappers accept an argument-based key function. This opts into encrypted receipt storage even when trace capture is off and requires a trusted `agents:manage` credential. Completed actions reuse the receipt; changed input conflicts. Pending, uncertain or expired receipts must not trigger an automatic retry. Inspect with `getToolOperation`; reconcile with `resolveToolOperation` only after checking the provider and obtaining authorization to mark complete or permit another attempt. Receipt expiration retains a hash tombstone. Never claim exactly-once behavior for arbitrary external code; use provider idempotency and cooperative cancellation.

For replay, obtain `getReplay(sourceRunId)` and pass a case-ID keyed `replay` map to the experiment runner. Instrumented tools return recorded results; unmatched calls fail. Model calls and uninstrumented code still execute. Provide recordings for every case; do not mix live and replay trials in one experiment. Measurements exclude live recorded-tool cost/latency.

Replay inputs and recorded outputs must be lossless JSON. Sparse arrays, undefined/nonfinite values and non-JSON objects cannot be silently converted into matching recordings. Optimization preflights recordings for both training and held-out cases before executing tasks.

`runAgentOptimization` uses separate training and held-out dataset IDs, a baseline harness, task, versioned evaluator and training-only `propose` callback. It bounds proposal rounds to 1–5 and validates the selected candidate on held-out cases. Do not expose held-out answers to the proposer. Candidate versions and reports require review before activation; measured-cost limits are checked between experiments and exclude external proposer/evaluator work.

Read the maintained [setup and contract guide](https://driftrail.com/docs.html#agent-tracing-improvements) for examples and mapping limits. Keep integration changes within the user's requested scope; setup does not authorize deployment or unrelated configuration changes.

Users can inspect and reconcile actions in **Agents → Tool actions** without knowing the raw action key. Check the provider using the displayed provider key, then record a verified receipt or explicitly permit another attempt with a reason. Stale reviews require a refresh; retry authorization does not run the tool. The dashboard backend requires `agents_tool_review.sql`; current Node 2.7.0/browser 2.5.0 execution clients need no update.
