npm package: @spect-tools/track
Description: The tracking library for spect.tools. Currently in alpha.
Latest version: 0.0.1-alpha.16

# @spect-tools/track

The tracking library for spect.tools. Currently in alpha.

Supporting:
- Vercel AI SDK as middleware and OpenTelemetry
- Claude Agent SDK

See https://docs.spect.tools/quickstart to use Spect in your application.

## Installation

```bash
npm install @spect-tools/track
# or
pnpm add @spect-tools/track
# or
yarn add @spect-tools/track
```

### Peer Dependencies

```bash
# For Vercel AI SDK
npm install ai @ai-sdk/provider

# For OpenTelemetry export
npm install @opentelemetry/core @opentelemetry/sdk-trace-base

# For Claude Agent SDK
npm install @anthropic-ai/claude-agent-sdk
```

## Usage

### Vercel AI SDK

Wrap your language model to enable automatic trace collection:

```typescript
import { wrap } from '@spect-tools/track';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';

const wrappedModel = wrap(openai('gpt-4o'), {
  organizationId: 'your-org-id',
  apiKey: 'your-spect-api-key',
});

const result = await generateText({
  model: wrappedModel,
  prompt: 'Hello!',
});
```

#### Custom Trace IDs

Pass trace metadata via provider options:

```typescript
await generateText({
  model: wrappedModel,
  prompt: 'Hello!',
  experimental_providerMetadata: {
    spect: {
      traceId: 'custom-trace-id',
      name: 'my-operation',
    },
  },
});
```

### Claude Agent SDK

Track Claude Agent sessions:

```typescript
import { streamClaudeAgentSession } from '@spect-tools/track';

const session = streamClaudeAgentSession({
  organizationId: 'your-org-id',
  apiKey: 'your-spect-api-key',
  prompt: 'Build a hello world app',
  claudeOptions: {
    // Claude Agent SDK options
  },
});

for await (const message of session) {
  console.log(message);
}
```

### OpenTelemetry Integration

Export spans to Spect collector:

```typescript
import { Exporter } from '@spect-tools/track';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';

const exporter = new Exporter(
  'https://collect.spect.tools',
  'your-org-id',
  'your-spect-api-key'
);

const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
provider.register();
```

### Local Development Mode

Skip sending traces to collector (useful for local dev):

```typescript
const wrappedModel = wrap(openai('gpt-4o'), {
  organizationId: 'your-org-id',
  apiKey: '', // Not required in local mode
  local: true,
  onTrace: (payload) => console.log('Trace:', payload),
});
```

### Viewer Component (React)

Embed a trace viewer in your app:

```tsx
import { Viewer } from '@spect-tools/track/components';

export default function App() {
  return (
    <div>
      <Viewer spectBaseUrl="https://spect.tools" />
    </div>
  );
}
```

The Viewer polls for local traces and provides a button to open them in Spect.

## Configuration Options

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `organizationId` | `string` | Yes | Your organization identifier |
| `apiKey` | `string` | Yes* | Spect API key (*not required if `local: true`) |
| `collectorUrl` | `string` | No | Collector URL (default: `https://collect.spect.tools`) |
| `provider` | `string` | No | Provider name override (e.g., `'openai'`, `'anthropic'`) |
| `operationName` | `string` | No | Custom operation name for traces |
| `local` | `boolean` | No | Local-only mode, skip sending to collector |
| `onTrace` | `(payload) => void` | No | Callback when trace is collected |
| `sendFailuresToConsole` | `boolean` | No | Log send failures (default: `true`) |
| `headers` | `HeadersInit` | No | Additional headers for collector requests |
| `fetchImpl` | `typeof fetch` | No | Custom fetch implementation |

## Local Trace Storage

Access traces stored locally during development:

```typescript
import { storeTrace, getLatest, get, list, clear } from '@spect-tools/track';

// Get latest trace
const latest = getLatest();

// Get all traces (up to 10 buffered)
const all = list();

// Get by ID
const trace = get('trace-id');

// Clear all stored traces
clear();
```

Traces are persisted to `.spect/data.json` in your project root and cleaned up on process exit.

## Exports

### Main (`@spect-tools/track`)

- `wrap(model, options)` - Wrap a language model with tracing
- `spectMiddleware(options)` - Get the middleware directly
- `Exporter` - OpenTelemetry span exporter class
- `streamClaudeAgentSession(options)` - Claude Agent SDK wrapper
- `generateTraceId()` - Generate a unique trace ID
- `storeTrace`, `getLatest`, `get`, `list`, `clear` - Local storage utilities

### Components (`@spect-tools/track/components`)

- `Viewer` - React component for in-app trace viewing

## TypeScript

Types are included. Key exports:

```typescript
import type {
  SpectOptions,
  ClaudeAgentWrapOptions,
  ClaudeAgentSessionStream,
  CollectorTracePayload,
} from '@spect-tools/track';
```