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

# Write Send

> Write an Adapter's send function in seven steps: send messages, continue sessions, record usage, map tool events, handle human-in-the-loop (HITL), connect OTel traces, and pass through Experiment flags.

[Adapter](https://niceeval.com/docs/explanation/adapter.md) defines the `send` contract: it receives `TurnInput` and `AgentContext`, and returns a `Turn`. This tutorial starts with one message, then adds the capabilities for a complete integration. Each step adds a little code; existing parts are marked `// … omitted`. Each step ends with the assertions its data supports. Add those assertions to an eval, rerun `pnpm exec niceeval exp`, then use `pnpm exec niceeval show` in the terminal or `pnpm exec niceeval view` in the browser to inspect conversations, usage, tool events, and pending requests.

Five principles run through the tutorial:

* **Connect the interface your users already use.** The Adapter calls the same endpoint and receives the same shape. Do not create an interface just for Evals or import internal application code to call a function directly. See [Connect Your Agent](https://niceeval.com/docs/tutorials/connect-your-agent.md) for why.
* **Keep service lifecycle outside the Adapter.** Start and check the real target with the project's development command, deployment script, or CI before running an Experiment. `send` does not spawn services, and evals do not install, start, or replace the system under test.
* **Limit access to credentials.** The target process and Adapter each read only the credentials they need. Keep secrets out of source code, eval workspaces, events, and final replies.
* **Hand-write transport only.** The URL, authentication, and request body depend on the application. `niceeval/adapter` supplies converters from raw responses to the standard event stream. `ctx.session` supplies the state APIs needed to continue sessions and resume a paused HITL interaction.
* **Send runtime feedback through `ctx`, not directly to the terminal.** Use `ctx.progress(...)` for long steps. Use `ctx.diagnostic(...)` for degradation or error context you need to inspect after a run. Throw when execution cannot continue. Do not call `console.log/error` or write `process.stdout/stderr` from an Adapter.

A complete t.send round trip

▸ Outbound ·
◂ Inbound

evals/\*.eval.ts

NiceEval

Adapter (you write)

Your application

Your frontend's API

Response / SSE stream

No changes

await t.send("...")

▸

Build TurnInput + ctx

▸

send(input, ctx)

▸

t.reply

◂

Reduce events into facts

◂

Translate into events

◂

t.calledTool()...

Update t.reply and usage

return Turn

t.send
t.sendFile
t.respond

These are unified event entry points on the runner side; the Adapter only implements send.

## Confirm the application interface shape

Before writing `send`, identify your application's response shape. [NiceEval](https://niceeval.com/) does not define a new application protocol. Its built-in converters support the common shapes below; choosing the matching converter saves you from writing event mappings:

| Protocol | Defined by | Description | Reference |
| - | - | - | - |
| **Chat Completions** | OpenAI. An industry de facto standard; almost every model provider offers a compatible endpoint. | Stateless request/response: the client sends the complete `messages` list every turn and receives one JSON response. | [API reference](https://platform.openai.com/docs/api-reference/chat) |
| **Responses / Open Responses** | OpenAI (Responses API). Open Responses is an open specification based on it, initiated by OpenAI and built with communities such as Hugging Face for multi-provider interoperability. | Stateful and Agent-oriented: a request carries `previous_response_id` so the server continues history, and its `output` array promises a complete process record. | [API reference](https://platform.openai.com/docs/api-reference/responses) · [Open Responses specification](https://www.openresponses.org/specification) |
| **AI SDK (Vercel)** | Vercel. A de facto standard in the TypeScript ecosystem. | It is an SDK rather than an online protocol: `generateText` returns a complete result, while `useChat` uses its defined UI Message Stream protocol. | [generateText reference](https://ai-sdk.dev/docs/reference/ai-sdk-core/generate-text) · [UI Message Stream protocol](https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol) |

The following steps use a Chat Completions-shaped interface. Steps two and four show the replacements for a Responses-shaped interface and streaming interfaces.

## Step 1: send one message and receive a reply

First let the eval send a message and receive a reply. This is the starting point for every assertion. The smallest `send` does three things: send `input.text` to the application API, put the reply in a `message` event, and report the Turn's `status`:

```ts theme={null}
// agents/chat-app.ts
import { completeEvidenceCoverage, defineAgent } from "niceeval/adapter";

const BASE_URL = "http://localhost:8080";   // To switch addresses by Experiment, make this a factory argument; see the connection guide.

export default defineAgent({
  name: "chat-app",
  evidenceCoverage: completeEvidenceCoverage,
  async send(input, ctx) {
    ctx.progress({ message: "Waiting for the Chat API" });
    const res = await fetch(`${BASE_URL}/v1/chat/completions`, {  // ← The interface the frontend already uses
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        messages: [{ role: "user", content: input.text }],
        model: ctx.model,                                         // ← experiment.model arrives here through ctx.model. Delete this line if the application interface cannot select a model.
      }),
      signal: ctx.signal,                                         // ← Runner timeout and cancellation
    }).then((r) => r.json());

    return {
      status: "completed",
      events: [{ type: "message", role: "assistant", text: res.choices[0].message.content }],
    };
  },
});
```

When an interface returns a response you can continue processing but whose evidence is incomplete, report a diagnostic instead of printing the full raw response:

```ts theme={null}
if (!res.requestId) {
  ctx.diagnostic({
    code: "missing-request-id",
    level: "warning",
    message: "The response has no request id and cannot be correlated with server logs",
  });
}
```

`progress` appears only while running and is not saved. A diagnostic is saved with the Attempt's results and appears in its details after the run. Throw if the HTTP connection fails or the response cannot be parsed. The Attempt is marked `errored`, with the error phase `agent.run`. Use `pnpm exec niceeval show @<locator>` to read the full error.

**This step supports** direct value checks on `t.reply` (`t.check(t.reply, includes(...))` or `pattern(...)`), all Judge conversation material, and **model comparison** on the Experiment side. `ctx.model` comes from an Experiment's `model`. The Runner passes it through unchanged; the Adapter only forwards it. See [Tier](https://niceeval.com/docs/explanation/tier.md) for the integration tiers.

It has two obvious limits: every Turn is a new conversation, so a second `t.send` cannot continue the first; and it cannot see tool calls at all. The next two steps solve one of those limits each.

## Step 2: carry earlier messages

The first version of `send` starts a new conversation every turn. A second `t.send` cannot continue the first. To test a multi-turn conversation, `send` must remember earlier messages.

The Runner promises one thing for sessions: **every `send` in one session line receives the same `ctx.session`; a new session line—the Eval's first Turn or the line after `t.newSession()`—receives a completely new one.**

How you continue a session depends on the application interface shape:

* **The client supplies complete history**—the server is stateless and receives the full messages list each Turn, as with Chat Completions—→ create an Adapter-private key with `createSessionKey<TMsg[]>()`, then read and write it with `ctx.session.get(key)` / `set(key, messages)`.
* **The server keeps history**—the interface accepts a session ID, such as a Responses-shaped `previous_response_id` or an SDK-native session/thread—→ use `ctx.session.id` and `ctx.session.capture(id)`.

The main example uses the first form:

```ts theme={null}
// agents/chat-app.ts
import { completeEvidenceCoverage, createSessionKey, defineAgent } from "niceeval/adapter";

const BASE_URL = "http://localhost:8080";

interface Msg { role: "user" | "assistant"; content: string | null }
const historyKey = createSessionKey<Msg[]>("chat-app/history");

export default defineAgent({
  name: "chat-app",
  evidenceCoverage: completeEvidenceCoverage,
  async send(input, ctx) {
    const history = ctx.session.get(historyKey) ?? []; // ← This key has not been written on a new session line.
    const messages = [...history, { role: "user" as const, content: input.text }];

    const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
      // … method, headers, and signal are the same as step one; omitted
      body: JSON.stringify({ messages, model: ctx.model }),        // ← The change: send complete history. Forward model as in step one.
    }).then((r) => r.json());

    const reply = res.choices[0].message;
    ctx.session.set(historyKey, [...messages, reply]); // ← Write it back. The next Turn on this line gets it automatically.

    return {
      status: "completed",
      events: [{ type: "message", role: "assistant", text: reply.content }],
    };
  },
});
```

No first-turn branch is needed. On a new session line, `ctx.session.get(historyKey)` returns `undefined`; `?? []` turns it into empty history. The first turn is simply empty history plus a new message. There is no extra capability to declare on `defineAgent`: use `ctx.session` to continue the conversation, or omit it to start a new one each turn.

When the application interface accepts a session ID, history lives on the server and the Adapter records only that ID. Change only these two places inside `send`:

```ts theme={null}
// Inside send:
//   Send the prior Turn's id in the request body … previous_response_id: ctx.session.id   ← It is naturally undefined on a new session line.
//   Capture a returned id … ctx.session.capture(res.id)                                   ← The next Turn continues from it.
```

`capture` writes only when no ID has been recorded. A backend that repeats an ID—or even changes it due to a fork—cannot overwrite the line currently being continued.

**This step supports** multi-turn conversations and session isolation through `t.newSession()`. Write a two-turn eval where the second refers to the first. If the reply loses context, check that the request includes the history or session ID.

## Step 3: record usage

An Agent that answers correctly but spends ten times as many tokens should not score the same as a frugal one. To limit usage and cost, `send` must report usage for each turn in the `Turn.usage` field, alongside `events` and `status`. Report what the application returns; the runner adds it across the session and run. A Chat Completions response includes `usage`, so copy it over. The rest of `send` is unchanged from step two:

```ts theme={null}
    // … transport and session are the same as step two; omitted
    return {
      status: "completed",
      events: [{ type: "message", role: "assistant", text: reply.content }],
      usage: {                                        // ← The change: report the usage returned by the interface truthfully.
        inputTokens: res.usage.prompt_tokens,
        outputTokens: res.usage.completion_tokens,
      },
    };
```

`Usage` also has optional fields: `cacheReadTokens`, `cacheCreationTokens`, `reasoningTokens`, `requests`, and `costUSD`. Fill each only when the API provides it. If no usage is returned, omit `usage` entirely; other assertions are unaffected.

Fill `costUSD` only with actual USD cost returned by the Provider or application. Do not put upstream estimates, model price tables, or local calculations in it.

Budgets and `t.maxCost()` use a separate value: the runner calculates `estimatedCostUSD` from `model`, reported token usage, and the price table. It does so even when `costUSD` is present. See the [defineConfig reference](https://niceeval.com/docs/reference/define-config.md) for prices and [Control run cost](https://niceeval.com/docs/tutorials/control-run-cost.md) for budgets.

If the model has no price in the table, the runner cannot estimate its cost and `t.maxCost()` returns `unavailable`, not zero. If an explicitly configured zero rate produces `estimatedCostUSD: 0`, that zero is a valid estimate and is compared with the limit.

**This step supports** `t.maxTokens()` / `t.maxCost()` and usage in `niceeval show @<locator> usage` and `niceeval view`. If `show` has no usage, check whether the API response includes it and whether `send` returned it.

## Step 4: parse tools into events

To assert which tools the Agent called and in what order, `send` must report tool calls. The response can contain more than reply text: Chat Completions uses `tool_calls` to record calls from this turn.

The Adapter's main job is to **translate the API response into the standard event stream**: one object for each event, in its actual order, in `Turn.events`. Each object uses one of the types below. For field values, see the [complete one-turn example](https://niceeval.com/docs/explanation/adapter.md).

```ts theme={null}
import type { CommandProjection } from "niceeval/adapter";

type StreamEvent =
  | { type: "message"; role: "assistant" | "user"; text: string }
  | { type: "operation.started"; operationId: string; operation:
      | { kind: "tool"; name: string; input: JsonValue;
          tool?: ToolName; command?: CommandProjection }
      | { kind: "subagent"; name: string; remoteUrl?: string } }
  | { type: "operation.finished"; operationId: string; kind: "tool";
      output?: JsonValue; status: "completed" | "failed" | "rejected" }
  | { type: "operation.finished"; operationId: string; kind: "subagent";
      output?: JsonValue; status: "completed" | "failed" }
  | { type: "skill.loaded"; skill: string; operationId?: string }
  | { type: "input.requested"; request: InputRequest }
  | { type: "thinking"; text: string }
  | { type: "compaction"; reason?: string }
  | { type: "error"; message: string };
```

Parsing is a “response field → event” map. Hand-written, it looks like this; the rest of `send` is exactly the same as step two:

```ts theme={null}
    // … transport and session are the same as step two; usage is the same as step three; omitted
    const reply = res.choices[0].message;

    const events: StreamEvent[] = [];
    for (const call of reply.tool_calls ?? []) {
      events.push({
        type: "operation.started",
        operationId: call.id,
        operation: {
          kind: "tool",
          name: call.function.name,
          input: JSON.parse(call.function.arguments),
        },
      });
    }
    if (reply.content) events.push({ type: "message", role: "assistant", text: reply.content });

    return { events, status: "completed", usage };
```

Usually you **do not need to write this loop**. When a response has a standard shape, one official converter line replaces all of it. The return value includes `events`, `status`, and even the manually copied `usage` from step three, so return it directly:

```ts theme={null}
    // … transport and session are the same as step two; omitted
    return turnFromChatCompletion(res);            // ← The mapping above plus step three's usage, in the official version.
```

For a different interface shape, use the matching piece:

| Interface response shape | Built-in piece | Code you need to write |
| - | - | - |
| Chat Completions-shaped response | `turnFromChatCompletion(res)` | No mapping to hand-write |
| Responses-shaped response | `turnFromResponses(res)` | No mapping to hand-write |
| Complete result from AI SDK `generateText` | `turnFromAiSdk(result)` | No mapping to hand-write |
| Streaming: SDK-native events passed through, with one complete unit per frame | `createClaudeSdkEventStream()` / `createPiAgentEventStream()` / `createCodexThreadEventStream()` | No mapping to hand-write |
| Streaming: the AI SDK UI Message Stream, the `useChat` protocol | `uiMessageStreamAgent()` | No `send` or event mapping to hand-write |
| Streaming: token-by-token or argument-by-argument deltas | The protocol's official reducer; use `deltaStream({ toOps })` only when it has none | One “frame type → operation” mapping table |
| Final answer only | A few hand-written events | Start with one `message`; step one is this tier |

Built-in converters use the response shape, not the application's business protocol. Write a mapping only for a delta stream whose protocol provides no reducer. The mapping states what each frame does; `deltaStream` handles concatenation, pairing, and when to form a complete event.

After normalization, the events you emit determine the assertion families Eval authors can write:

| Events you emit | Assertions unlocked |
| - | - |
| `message` | `t.reply`, `t.check(turn.reply, includes(...))` / `pattern(...)`, Judge conversation material |
| Tool `operation.started` / `operation.finished`, paired by `operationId` | `turn.calledTool()` / `turn.toolOrder()` / `turn.maxToolCalls()` / `turn.noFailedActions()`… |
| `input.requested`, with status `"waiting"` | `t.check(turn.status, equals("waiting"))`, `t.requireInputRequest()`, `t.respond()` (step five) |
| `thinking` / `compaction` / `error` | Reports and diagnostics; you can also pass raw `events` to an ordinary `check(events, match)` |

A Chat Completions response **does not guarantee a complete process record**. An application can finish its tool loop server-side and return only a final answer. Therefore, `turnFromChatCompletion` returns no completeness proof. Positive assertions such as `calledTool` work, while negative assertions such as `notCalledTool` report incomplete evidence. The Responses protocol requires the `output` array to record the complete process, so `turnFromResponses` carries a completeness proof and negative assertions are trustworthy. The difference in trustworthiness comes from the interface contract.

**This step supports** `turn.calledTool()`, `turn.toolOrder()`, `turn.maxToolCalls()`, and `turn.noFailedActions()`. For ordering across Turns, use `session` instead of `turn`. After the run, inspect tools with `pnpm exec niceeval show @<locator> execution`. If a tool is missing, check the response's tool fields and your mapping.

## Step 5: HITL

When an application stops mid-Turn to wait for a person—for tool approval or missing information—both sides of `send` have obligations:

* **The pausing Turn** returns `status: "waiting"` and emits an `input.requested` event with a stable `id` for every pending question. `t.check(turn.status, equals("waiting"))` and `t.requireInputRequest()` read them, and answers match by this `id`.
* **The answer Turn** reaches the Adapter from an Eval's `t.respond(...)` as **another ordinary `send`** on the same session line with the same state. A human decision arrives structurally through `input.responses`; each entry carries `requestId`, `optionId`, or `text`. See [Inputs for the Different Answers](https://niceeval.com/docs/explanation/adapter.md#inputs-for-the-different-answers) for the shapes. The Adapter gives that decision back to the application, then continues fetching the result. For a call a human rejects, set the tool `operation.finished` event's `status` to `"rejected"`, not `"failed"`: rejection is a human decision, not a tool failure, so `noFailedActions()` does not misfire.

Store unfinished work, such as a partly read SSE stream, in `ctx.session` too. Declare private state with `createSessionKey<Pending>()`, save it with `ctx.session.set(...)` when waiting, and retrieve it with `ctx.session.take(...)` at the start of the answering turn. Taking clears the value, so it can be consumed only once.

HITL almost always occurs on a streaming interface because the pause happens in the middle of a stream. This example therefore switches to an application that passes native events through SSE. It exercises every preceding step together; see the complete runnable version in the [tier1 example](https://github.com/CorrectRoadH/niceeval/tree/main/examples/zh/tier1):

```ts theme={null}
// agents/my-app.ts
import { completeEvidenceCoverage, createSessionKey, defineAgent, sseJsonFrames, createPiAgentEventStream, driveFrameStream } from "niceeval/adapter";
import type { AgentContext, PiAgentStream, SseFrameCursor } from "niceeval/adapter";
import type { Turn, TurnInput } from "niceeval";

const BASE_URL = "http://localhost:5299";               // The application's own port; evals do not manage its process.

interface Pending { cursor: SseFrameCursor<Frame>; stream: PiAgentStream; callId: string }
const pendingKey = createSessionKey<Pending>("my-app/pending");

function readStream(cursor: SseFrameCursor<Frame>, ctx: AgentContext, stream: PiAgentStream): Promise<Turn> {
  return driveFrameStream(cursor, stream, ctx, (frame) => {
    if (frame.type === "session") {
      ctx.session.capture(frame.sessionId);             // ← Step two: write the returned id back so the next Turn continues.
      return;
    }
    if (frame.type === "approval_request") {            // ← This step: the application pauses for approval, so retain the scene.
      ctx.session.set(pendingKey, { cursor, stream, callId: frame.toolCallId });
      return { pause: { id: frame.toolCallId, action: frame.toolName,
                        options: [{ id: "approve" }, { id: "deny" }] } };
      // On pause, driveFrameStream adds input.requested, sets status to "waiting", and stops reading the stream.
    }
    if (frame.type === "server_error") return { fail: frame.message };
  });
}

export default defineAgent({
  name: "my-app",
  evidenceCoverage: completeEvidenceCoverage,
  async send(input: TurnInput, ctx: AgentContext): Promise<Turn> {
    const held = ctx.session.take(pendingKey);
    if (held) {                                         // ← t.respond("approve"): an ordinary send; deliver the decision first.
      const approved = input.responses?.[0]?.optionId === "approve";  // Match by requestId when several requests are pending.
      if (!approved) held.stream.markRejected(held.callId);
      await fetch(`${BASE_URL}/api/chat/approve`, { method: "POST", signal: ctx.signal,
        body: JSON.stringify({ toolUseId: held.callId, approved }) });
      return readStream(held.cursor, ctx, held.stream); // Then keep reading the same stream; do not send a new request.
    }

    const res = await fetch(`${BASE_URL}/api/chat`, {   // ← Transport: the only part you truly hand-write.
      method: "POST",
      body: JSON.stringify({
        message: input.text,                            // ← Step one: send the message.
        model: ctx.model,                               // ← Step one: forward experiment.model.
        sessionId: ctx.session.id,                      // ← Step two: naturally absent on the first send and present afterward.
      }),
      signal: ctx.signal,
    });
    return readStream(sseJsonFrames<Frame>(res.body!), ctx, createPiAgentEventStream());  // ← Step four: official converter with no mapping.
  },
});
```

For an interface without HITL, remove the three waiting-related parts: `Pending`, `pendingKey`, and the initial `take` branch. Keep the rest. See [HITL](https://niceeval.com/docs/explanation/hitl.md) for the complete waiting, answering, and resuming flow.

**This step supports** `t.check(turn.status, equals("waiting"))`, `t.requireInputRequest()`, and `t.respond()` / `t.respondAll()`. Assert a rejected call with `calledTool(toolMatch(..., { status: "rejected" }))`. If `t.requireInputRequest()` finds no request, check that the waiting turn returned both `status: "waiting"` and an `input.requested` event.

## Step 6: connect OTel traces

To inspect each turn's model calls and tool duration in the browser, connect the application's OTel traces. Standard OTel HTTP server instrumentation is enough. Configure one part once at application startup; pass the other part through `send` on every turn.

**Configure the receiver address at application startup, outside `send`.** [NiceEval](https://niceeval.com/) uses the same OTLP receiver address for each run. Fix its port in `niceeval.config.ts` and point the application's OTel exporter to it at startup; subsequent eval runs need no changes:

```ts theme={null}
// niceeval.config.ts
import { defineConfig } from "niceeval";

export default defineConfig({
  telemetry: { port: 4318 },   // The receiver always listens on http://localhost:4318/v1/traces.
});
```

```bash theme={null}
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces node server.js
```

**What `send` passes is this Turn's trace context, not the endpoint.** `ctx.telemetry.headers` is a W3C `traceparent` header the Runner generates freshly for every Turn. Spread it into the request and the spans the application produces for this Turn attach precisely to this Turn's trace, without misattribution when Evals run concurrently. Back in the main `chat-app`, `send` gains exactly one line:

```ts theme={null}
    const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
      // … the rest is the same as step four; omitted
      headers: { "content-type": "application/json", ...ctx.telemetry?.headers },  // ← The only added line.
    }).then((r) => r.json());
```

`ctx.telemetry` appears only when OTel integration is configured. Spreading `undefined` when it is not configured is safe, so this line can remain permanently. Spans still arrive without this header, but attribution degrades to time windows and that Agent's Turns fall back to serial execution. Carrying it is what makes attribution accurate under concurrency.

**This step supports** a per-turn waterfall in `niceeval view`, including model calls, tool execution, duration, and tokens. Assertions still read events from the earlier steps; spans only supply the waterfall. For an empty or incomplete waterfall, see [OTel integration](https://niceeval.com/docs/tutorials/connect-otel.md).

## Step 7: pass through Experiment flags for A/B comparison

To compare prompt versions or strategies, expose them as switchable application configuration. The Experiment declares `flags`; the runner passes them unchanged to `send` through `ctx.flags` on every turn. The Adapter forwards them without interpreting them, and the application selects its variant:

```ts theme={null}
      // … the rest of send is the same as before; omitted
      body: JSON.stringify({
        messages,
        model: ctx.model,        // ← experiment.model has been forwarded since step one; it appears here with flags.
        flags: ctx.flags,      // ← experiment.flags passes through unchanged. It is {} when not configured.
      }),
```

```ts theme={null}
// experiments/concise.ts
import { defineExperiment } from "niceeval";
import chatApp from "../agents/chat-app.ts";

export default defineExperiment({
  agent: chatApp,
  model: "gpt-5.4",                      // ← Reaches send through ctx.model.
  flags: { promptVariant: "concise" },  // ← Reaches send through ctx.flags every Turn.
});
```

Declare `flags` in two Experiment files and run the same evals with `pnpm exec niceeval exp` to compare them. This is Tier 3 integration because the application must expose the switches. See [Tier](https://niceeval.com/docs/explanation/tier.md) for effort and benefits, and [Write experiments](https://niceeval.com/docs/tutorials/write-experiment.md) for `flags`, `model`, `attempts`, and other fields.

**This step supports** comparing the same evals across variants. After both runs finish, compare them with `pnpm exec niceeval show exp:<id> exp:<id>` or `pnpm exec niceeval view`. If the scores are almost identical, first confirm the application actually reads the request's `flags`.

## Reference: the five t APIs as send sees them

After these seven steps, revisit the five APIs that drive conversations from evals. On the Adapter side, each uses the same `send` function with different fields; there is no second method to implement:

| Eval-side API | Adapter call | What `send` receives |
| - | - | - |
| `t.send(text)` | One `send` | `input.text`; `ctx.session` is this session line's own state. |
| `t.sendFile(path, text?)` | One `send` | The same, plus `input.files` (base64 `InputFile[]`). Put them in the request as the application interface expects, or ignore them when it is not multimodal. |
| `t.newSession()` | Does not trigger `send` itself | Opens a second session line. That line's next first `send` receives **completely empty** state, exactly like the Eval's first `send`. |
| `t.respond(...answers)` | One **ordinary** `send` | `input.text` is the answer text. `input.responses` has one `{ requestId, optionId }` per request, or `{ requestId, text }` for free-text answers. It is still the same line and state. |
| `t.respondAll(optionId)` | One **ordinary** `send` | The same, with one answer for every pending request. `optionId` is validated against every request on the Eval side; a typo throws instead of silently reaching the application. |

## Related reading

* [Adapter](https://niceeval.com/docs/explanation/adapter.md) — `send` inputs, outputs, three integration tiers, and capability sources.
* [Connect Your Agent](https://niceeval.com/docs/tutorials/connect-your-agent.md) — minimal integration, parameter passing, and optional capabilities.
* [HITL](https://niceeval.com/docs/explanation/hitl.md) — the complete concept of pausing to wait for a person: handshake timing and both sides' obligations.
* [Drive](https://niceeval.com/docs/explanation/drive.md) — how an Eval uses `t.send()`, `t.newSession()`, and HITL.
* [Assert](https://niceeval.com/docs/explanation/assert.md) — the complete assertion vocabulary driven by the standard event stream.


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