> ## Documentation Index
> Fetch the complete documentation index at: https://cognitio-agent.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost, usage and telemetry

> Inspect per-run results, understand accounting limits and connect an OTLP collector.

For the TypeScript examples, use the [TypeScript setup](https://cognitio-agent.mintlify.site/installation.md#typescript-projects), including `"type": "module"` and the `tsx` runner.
Start with terminal results and typed stream events. Add OpenTelemetry when you need runtime signals in an existing collector. Avoid sending prompt text, tool arguments or credentials to application logs by default.

## Read usage without assuming it is present

Use the [quickstart](https://cognitio-agent.mintlify.site/quickstart.md) setup with `OPENAI_API_KEY`. Save this as `usage.ts` and run `node --env-file=.env --import tsx usage.ts`.

```ts theme={null}
import { Agent, shutdown } from "cognitio-agent-sdk"

const agent = new Agent({
  model: "openai/gpt-4.1-mini",
  disallowedTools: ["*"],
  maxTurns: 2,
  maxBudgetUsd: 0.10,
})
try {
  const session = await agent.createSession({ title: "Usage example" })
  const result = await session.send("Explain a database index in one sentence.")
  console.log({
    subtype: result.subtype,
    costUsd: result.totalCostUsd ?? null,
    inputTokens: result.usage?.inputTokens ?? null,
    outputTokens: result.usage?.outputTokens ?? null,
  })
  console.log("Usage observed by this handle", session.usage)
  if (result.subtype !== "success") throw new Error(`Run ended: ${result.subtype}`)
} finally {
  await agent.close().finally(() => shutdown())
}
```

Result usage and cost fields are optional. Missing data is not a zero-cost guarantee. `modelUsage` breaks available accounting down by model; see `UsageSummary`, `ModelUsageSummary` and `SessionUsage` in the API reference.

`session.usage` accumulates assistant usage observed by that local handle and reconciles each completed turn with its terminal result. Resumed/newly attached handles start at zero; this is not an all-time billing query for the persisted transcript. Rewind does not subtract prior usage. Child-session costs are reconciled when the parent turn completes.

## Interpret limits correctly

`maxTurns` limits assistant turns, not elapsed time. `maxBudgetUsd` checks estimated accumulated cost around completed model, child and compaction work. An in-flight call can exceed the threshold before the runtime stops subsequent work. Use an `AbortSignal` on `Agent.run()`/`Agent.stream()` for an application deadline; an existing low-level Session uses `session.interrupt()`/`abort()` instead. Use provider account controls for a billing limit.

Cost depends on provider-reported usage and catalog prices. Automatic permission-classifier calls are not included in terminal result accounting. Missing usage, nonstandard pricing or provider adjustments can make SDK estimates differ from your bill.

## Correlate events

`Agent.stream()` and `Session.stream()` provide typed `AgentMessage` values, including `rate_limit`, tool and task lifecycle messages where supported. Preserve session, message, task and tool identifiers when correlating events. A notification that a task is running does not imply a durable background job. Check the terminal result to determine the run's outcome.

Application logs are your responsibility: logging whole message objects can expose prompts and tool data even when runtime telemetry redaction is enabled.

## Send telemetry to your collector

Configure an existing OTLP collector before starting the runtime. For a local collector exposing OTLP/HTTP on port 4318:

```sh theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:4318"
export OTEL_SERVICE_NAME="my-cognitio-agent"
node --env-file=.env --import tsx usage.ts
```

The SDK forwards `OTEL_*` environment variables to locally spawned runtimes. For a remote runtime, configure these variables on the server instead. Collector installation, authentication and retention belong to your deployment.

With an OTLP endpoint configured, AI request instrumentation is enabled by default. `spawn.config.experimental.openTelemetry: false` disables that AI instrumentation. AI span input/output recording remains off unless `openTelemetryRecordInputs` or `openTelemetryRecordOutputs` is explicitly enabled under the same `experimental` configuration. Those opt-ins may expose model content; enable them only with an intentional data policy.

Close owned clients, or call `shutdown()` for the default facade runtime, to allow buffered telemetry to flush. Shutdown is bounded: an unreachable collector is not a delivery guarantee. Session identifiers on metrics are opt-in.

## Know what runtime log redaction covers

Every exported runtime log record passes through an OTLP serialization filter. The body becomes `[redacted]`; free-form messages, prompts/outputs, arguments, environment/configuration objects, error details, nested values and unrecognized annotations are omitted.

The filter retains severity, timestamps, trace/span identifiers, recognized built-in service labels, and approved numeric, boolean and status fields. Runtime-shaped session/message/workspace identifiers remain in their corresponding fields. Opaque identifiers, provider/model identifiers and custom service labels use stable SHA-256 hashes for correlation; hashing is not encryption.

This policy covers exported runtime logs. Local log files and stderr retain diagnostic content. Explicit resource configuration, including `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`, is unchanged. Application-managed logs and HTTP event payloads are separate interfaces.

V2 does not promise a frozen GenAI semantic-convention taxonomy or automatic end-to-end W3C propagation from an application control plane. Use the typed SDK event stream for application behavior, and treat telemetry as operational visibility.


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