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

# Claude Code (TypeScript)

> Wrap the Claude Agent SDK's query() to automatically track sessions, tool calls, tokens, costs, and conversation threading.

<Note>
  **Requires:** `@anthropic-ai/claude-agent-sdk` v0.2.0+ as a peer dependency. Works with the `query()` function for one-shot and multi-turn interactions.
</Note>

## What Gets Tracked Automatically

<CardGroup cols={2}>
  <Card title="Sessions">
    Created on init, completed on result — with agent name, user ID, and metadata.
  </Card>

  <Card title="Tool Calls">
    Every tool execution (Bash, Read, Write, etc.) with input, output, and tool use ID.
  </Card>

  <Card title="Tokens & Cost">
    Prompt tokens, completion tokens, total tokens, and estimated cost in USD.
  </Card>

  <Card title="Conversation Threading">
    Group related sessions with `convoId` — multi-turn conversations appear linked.
  </Card>

  <Card title="Errors">
    Failed tool calls, errored sessions, and generator exceptions — all recorded.
  </Card>

  <Card title="Duration">
    Wall-clock time from start to result, plus API-side duration when available.
  </Card>
</CardGroup>

<Note>
  Consume the stream until the `result` message to record final tokens/cost/output. If you close the
  generator early (for example via `break`/`return`), the session is marked failed with
  `Session interrupted (generator closed early)` so runs do not remain stuck in `running`.
</Note>

## Installation

```bash theme={null}
npm install @sentrial/sdk @anthropic-ai/claude-agent-sdk
```

## Quick Start

Wrap the `query()` function once, then use it exactly like normal.

```typescript theme={null}
import { query } from '@anthropic-ai/claude-agent-sdk';
import { SentrialClient, wrapClaudeAgent } from '@sentrial/sdk';

// 1. Create a Sentrial client
const sentrial = new SentrialClient({
  apiKey: process.env.SENTRIAL_API_KEY,
});

// 2. Wrap query()
const trackedQuery = wrapClaudeAgent(query, {
  client: sentrial,
  defaultAgent: 'my-agent',
  userId: 'user-123',
});

// 3. Use normally — everything is tracked
for await (const message of trackedQuery({
  prompt: 'Fix the failing tests in src/auth.ts',
  options: {
    maxTurns: 10,
    permissionMode: 'bypassPermissions',
  },
})) {
  if (message.type === 'assistant') {
    // Handle assistant messages
  }
}
// Session auto-completed with tokens, cost, duration, and all tool calls
```

## Configuration Options

```typescript theme={null}
const trackedQuery = wrapClaudeAgent(query, {
  client: sentrial,           // required — SentrialClient instance
  defaultAgent: 'my-agent',   // optional — agent name for grouping (default: 'claude-agent')
  userId: 'user-123',         // optional — ties sessions to your end users (default: 'anonymous')
  convoId: 'convo-abc',       // optional — group sessions into a conversation thread
  extraMetadata: {             // optional — merged into every session's metadata
    environment: 'production',
    version: '1.2.0',
  },
});
```

<Tip>
  **Fail-Safe by Default** — If Sentrial is unreachable, all messages pass through unchanged. Your agent never breaks due to tracking failures.
</Tip>

## Conversation Threading

Use `convoId` to group related sessions into a conversation. Each call to `trackedQuery()` creates a new session, but they appear linked in the dashboard.

```typescript theme={null}
const convoId = `user-${userId}-${Date.now()}`;

const trackedQuery = wrapClaudeAgent(query, {
  client: sentrial,
  defaultAgent: 'code-assistant',
  userId,
  convoId,
});

// Session 1: Explore the codebase
for await (const msg of trackedQuery({
  prompt: 'List all API routes and their handlers',
})) { /* ... */ }

// Session 2: Follow-up (same convoId, linked in dashboard)
for await (const msg of trackedQuery({
  prompt: 'Add rate limiting to the /api/users endpoint',
})) { /* ... */ }
```

## How Tool Tracking Works

The wrapper uses PostToolUse and PostToolUseFailure hooks to capture every tool execution. Hooks fire asynchronously and never block the agent. A session-ready gate ensures hooks wait for session creation before tracking.

```typescript theme={null}
// No extra code needed — tool calls are tracked automatically
for await (const message of trackedQuery({
  prompt: 'Read package.json and tell me the project name',
  options: {
    allowedTools: ['Bash', 'Read', 'Glob'],
  },
})) {
  // Each tool call (Read, Bash, etc.) is recorded as an event
  // with input args, output, and execution metadata
}
```

In the dashboard, each tool call appears as an event under the session timeline.

## Error Handling

If the agent errors, the generator throws, or the consumer closes the stream early, the session is
automatically marked as failed with a clear failure reason.

```typescript theme={null}
try {
  for await (const message of trackedQuery({
    prompt: 'Deploy to production',
  })) {
    // ...
  }
} catch (error) {
  // Session already marked as failed in Sentrial
  // with failure_reason = error.message
  console.error(error);
}
```

## Full Production Example

```typescript theme={null}
import { query } from '@anthropic-ai/claude-agent-sdk';
import { SentrialClient, wrapClaudeAgent } from '@sentrial/sdk';

const sentrial = new SentrialClient({
  apiKey: process.env.SENTRIAL_API_KEY!,
});

async function runAgent(userPrompt: string, userId: string) {
  const convoId = `session-${userId}-${Date.now()}`;

  const trackedQuery = wrapClaudeAgent(query, {
    client: sentrial,
    defaultAgent: 'code-review-agent',
    userId,
    convoId,
    extraMetadata: {
      environment: process.env.NODE_ENV,
    },
  });

  let result = '';

  for await (const message of trackedQuery({
    prompt: userPrompt,
    options: {
      model: 'claude-sonnet-4-20250514',
      maxTurns: 15,
      permissionMode: 'bypassPermissions',
      allowedTools: ['Bash', 'Read', 'Write', 'Glob', 'Grep'],
    },
  })) {
    if (message.type === 'result') {
      result = message.result ?? '';
    }
  }

  return result;
}
```

## What You See in the Dashboard

<CardGroup cols={2}>
  <Card title="Session Overview">
    Agent name, user ID, conversation thread, status, duration, cost.
  </Card>

  <Card title="Input / Output">
    The prompt and Claude's final response.
  </Card>

  <Card title="Tool Call Timeline">
    Every Bash, Read, Write, Glob call — with input, output, and tool use ID.
  </Card>

  <Card title="Token & Cost Breakdown">
    Prompt tokens, completion tokens, total, estimated USD cost.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Claude Code (Python)" icon="python" href="/integrations/claude-code-python">
    Same integration for the Python Claude Agent SDK.
  </Card>

  <Card title="TypeScript SDK Reference" icon="js" href="/sdk/typescript">
    Full SDK documentation with all methods and options.
  </Card>
</CardGroup>
