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

# JavaScript/TypeScript SDK

> Complete guide to the 60db JavaScript/TypeScript SDK

## Installation

```bash theme={null}
npm install 60db-service
```

## Initialization

```typescript theme={null}
import { SixtyDBClient } from "60db-service";

// Simple initialization
const client = new SixtyDBClient("your-api-key");
```

## Text-to-Speech

### Basic TTS

```typescript theme={null}
const audio = await client.textToSpeech({
  text: 'Hello, world!',
  voice_id: 'default-voice',
  enhance: true,
  speed: 1.0,
  language:"en-us"
});

### Get all voices
const voices = await client.getVoices();

### Get all lanuages
const lanuages = await client.getLanguages();

### audio is an ArrayBuffer containing the audio data
```

## Speech-to-Text

### Transcribe Audio

```typescript theme={null}
const file = document.querySelector('input[type="file"]').files[0];

const result = await client.speechToText(file, {
  language: "en",
});

console.log(result.text);
```

### With Context Refinement

Supply a `context` string to enable server-side LLM polishing — proper nouns, filler removal, and punctuation are cleaned on the response text:

```typescript theme={null}
const result = await client.speechToText(file, {
  language: "hi",
  diarize: true,
  context:
    "Cricket coaching session. Players: Arjun Mehta, Ishaan Verma. Discussing batting technique.",
});
```

Omit `context` entirely to skip refinement. Note: this is the REST shape — the WebSocket streaming endpoint takes a `{general, text, terms}` object instead.

### Get Supported Languages

```typescript theme={null}
const languages = await client.getLanguages();
console.log(languages);
```

## Voice Management

### List All Voices

```typescript theme={null}
const voices = await client.getVoices();
voices.forEach((voice) => {
  console.log(`${voice.name} (${voice.id})`);
});
```

### Get Specific Voice

```typescript theme={null}
const voice = await client.getVoice("voice-id");
console.log(voice);
```

### Create Custom Voice

```typescript theme={null}
const files = [file1, file2, file3]; // File objects

const newVoice = await client.createVoice({
  name: "My Custom Voice",
  files: files,
  description: "A custom voice for my brand",
});

console.log("Created voice:", newVoice.id);
```

### Update Voice

```typescript theme={null}
await client.updateVoice("voice-id", {
  name: "Updated Voice Name",
  description: "Updated description",
});
```

### Delete Voice

```typescript theme={null}
await client.deleteVoice("voice-id");
```

## Music

### Create a Song

```typescript theme={null}
const result = await client.music.create({
  prompt: 'upbeat lo-fi hip hop',
  mode: 'simple'
});
const songId = result.data.songs[0].id;
```

### Wait for Completion

```typescript theme={null}
const song = await client.music.waitForCompletion(songId, {
  intervalMs: 4000,
  timeoutMs: 600000
});
```

### Download Song

```typescript theme={null}
const audioBuffer = await client.music.download(songId);
```

## Judge

Scores content against a rubric you define, and parses conversational turns.
A classifier, not a generator — every answer is a probability distribution over
**your** options, so results are comparable and sortable.

Authenticated with the **same 60db API key** as the rest of the SDK — the client
you already constructed works; there is no separate Judge credential.

### Evaluate content

```typescript theme={null}
const run = await client.judge.evaluate({
  state: callTranscript,
  questions: {
    tone: {
      type: 'choice',
      instructions: 'How did the agent come across?',
      criteria: {
        professional: 'Calm, courteous, takes ownership',
        dismissive: 'Brushes the caller off',
        unknown: 'Not enough of the call to tell',   // always add an escape hatch
      },
    },
    satisfaction: { type: 'score', criteria: ['Angry', 'Neutral', 'Happy'] },
    resolved: { type: 'noul', instructions: 'Was it solved?' },
  },
});

run.answers.tone.choice           // 'dismissive'
run.answers.tone.probabilities    // { dismissive: 0.86, professional: 0.11, unknown: 0.03 }
run.answers.tone.confidence       // 0.79
run.answers.satisfaction.score    // 1.87 — weighted position on your ladder, not an index
run.answers.resolved.noul         // 0.28 — raw probability of true, NOT a confidence
run.min_confidence                // lowest across the answers
run.credits_charged               // 0.00000161
```

Under `0.85` is the upstream's own escalation line — route those to a person
rather than trusting them.

### Save a rubric and re-run it

```typescript theme={null}
const rubric = await client.judge.rubrics.create({
  name: 'Call QA',
  description: 'Tone, satisfaction and outcome on inbound calls',
  questions,
  shared: true,              // workspace-wide; owner/admin only
});

await client.judge.evaluate({ state: transcript, rubric_id: rubric.id });
```

Runs of a saved rubric file themselves under it, so
`runs.list({ rubric_id })` returns the whole series.

```typescript theme={null}
await client.judge.rubrics.list();
await client.judge.rubrics.get(id);
await client.judge.rubrics.update(id, { description: 'updated' });
await client.judge.rubrics.delete(id);
```

### Extract from a turn

```typescript theme={null}
const turn = await client.judge.extract({
  text: 'move my 10am appointment to friday',
  schema: {
    intents:    { booking: 'Wants to arrange or change a booking' },
    operations: { reschedule: 'Move an existing booking' },
    entities:   { date: 'A calendar date', time: 'A clock time' },
    // responsePaths: { confirm: 'Read the change back' }   ← selects the v2 model
  },
});

turn.intent.label       // 'booking'
turn.operation.label    // 'reschedule'
turn.entities           // [{ label: 'date', text: 'friday', start: 28, end: 34, confidence: 0.8 }]
```

> [!WARNING]
>
> `start`/`end` are **Unicode code point** offsets, not UTF-16 indices. Slice
> with `Array.from(text).slice(start, end).join('')` — a plain `text.slice()`
> lands in the wrong place once the turn contains an emoji.

### The review queue

```typescript theme={null}
const { runs, pagination } = await client.judge.runs.list({
  needs_review: true,     // only runs the judge was under 85% sure about
  limit: 20,
});

await client.judge.runs.get(id);      // one run, with what was sent and returned
await client.judge.runs.delete(id);
```

### Models and spend

```typescript theme={null}
await client.judge.models();                // authoritative list — don't hardcode
await client.judge.usage('current_month');  // spend and run counts
await client.judge.health();                // upstream readiness (owner/admin)
```

### Pricing

Billed per **input token**. The upstream re-encodes the shared content once per
question, so a 10-question rubric costs ten times the transcript. Context is
**200,000 tokens per question**, and an over-long request is rejected with a `400`
before anything is charged (in practice the 512 KiB whole-request cap binds first).

A failed run — `429` busy, `503` unavailable, `400` invalid rubric — is
refunded automatically.

## Dialer

### Check Status

```typescript theme={null}
const status = await client.dialer.status();
console.log('Provisioned:', status.data.provisioned);
```

### Buy a Number

```typescript theme={null}
const bought = await client.dialer.numbers.buy();
console.log('Bought:', bought.data.number);
```

### List Calls

```typescript theme={null}
const calls = await client.dialer.calls.list({ limit: 50 });
```

### Get Recording

```typescript theme={null}
const url = await client.dialer.recordings.playbackUrl('recording-id');
console.log('Listen at:', url.data.playback_url);
```

## Agents

Phone voice agents (available in `60db-service` 1.2.0 and later). Agents place real calls, so every call costs money and rings a real phone. Methods return the API's `data` and throw `SixtyDBAgentsError` with `code`, `field` and `status`. See [Agents](https://docs.60db.ai/features/agents.md).

### Create an Agent and Place a Call

```typescript theme={null}
import { SixtyDBClient } from "60db-service";

const client = new SixtyDBClient("your-api-key");

const agent = await client.agents.create({
  name: "Front desk",
  script: "You are the receptionist for Juniper Kitchen. Keep replies short.",
  voice_id: "YOUR_VOICE_ID",
  greeting: "Hello, Juniper Kitchen. How can I help?",
  listen_languages: ["hi", "en"],
  call_defaults: { max_duration_secs: 300, record: true },
});
// agent.webhook_secret is shown once. Store it.

// A 60db Dialer number, or your own SIP trunk (BYO)
const { numbers } = await client.agents.phoneLines.availableNumbers();
const free = numbers.find((n) => !n.in_use);
const line = await client.agents.phoneLines.create({ kind: "sixtydb", number: free!.number, agentId: agent.id });

const call = await client.agents.call(agent.id, { to: "+919999999999", phoneLineId: line.id });
const done = await client.agents.calls.waitForCompletion(call.id);
console.log(done.status, done.duration_secs);
```

### Update, Rotate and Delete

```typescript theme={null}
await client.agents.update(agent.id, { greeting: "Hi there!" });
const { webhook_secret } = await client.agents.rotateWebhookSecret(agent.id);
await client.agents.delete(agent.id);
```

### Calls, Transcripts and Recordings

```typescript theme={null}
const { calls } = await client.agents.calls.list({ agentId: agent.id, status: "completed", limit: 20 });
const call = await client.agents.calls.get(callId);
const { turns } = await client.agents.calls.transcript(callId);
const wav = await client.agents.calls.recording(callId, { mix: true }); // ArrayBuffer
await client.agents.calls.deleteRecording(callId);
```

`calls.list()` takes `from` and `to` as ISO dates (a range), not phone numbers.

### Phone Lines

```typescript theme={null}
const { phone_lines } = await client.agents.phoneLines.list();
await client.agents.phoneLines.update(lineId, { agentId: null });
await client.agents.phoneLines.delete(lineId);

// Your own SIP trunk (the password is sent once and never returned)
await client.agents.phoneLines.create({
  kind: "byo",
  name: "Main office trunk",
  domain: "sip.carrier.example.com",
  username: "office-trunk",
  password: process.env.SIP_PASSWORD!,
  callerId: "+911204567890",
});
```

### Tools and Events

Give an agent `tools` and a `tool_webhook_url`. 60db calls that URL during a call and speaks your JSON reply. Set `event_webhook_url` to receive `call.completed`, `call.failed` and `recording.ready`. Verify every request with the raw body:

```typescript theme={null}
import { verifyWebhookSignature } from "60db-service";

const ok = verifyWebhookSignature({
  rawBody,                                     // the exact bytes received
  signature: req.headers["x-60db-signature"],
  timestamp: req.headers["x-60db-timestamp"],
  secret: process.env.SIXTYDB_WEBHOOK_SECRET!, // whsec_…
});
```

The tool-call log is available with `client.agents.toolEvents(agent.id)`. See [Tools and webhooks](https://docs.60db.ai/features/agents-tools-and-webhooks.md) and the examples in `examples/agents-quickstart.mjs` and `examples/agents-tool-webhook-server.mjs`.

### Errors

```typescript theme={null}
import { SixtyDBAgentsError } from "60db-service";

try {
  await client.agents.call(agent.id, { to: "+919999999999", phoneLineId: line.id });
} catch (err) {
  if (err instanceof SixtyDBAgentsError) {
    console.error(err.status, err.code, err.field, err.message);
  }
}
```

## Authentication

### Sign Up

```typescript theme={null}
const user = await client.signUp({
  email: "user@example.com",
  password: "secure-password",
  name: "John Doe",
});
```

### Sign In

```typescript theme={null}
const session = await client.signIn({
  email: "user@example.com",
  password: "secure-password",
});

console.log("Token:", session.token);
```

### Get Profile

```typescript theme={null}
const profile = await client.getProfile();
console.log(profile);
```

### Update Profile

```typescript theme={null}
await client.updateProfile({
  name: "Jane Doe",
  company: "Acme Inc",
});
```

## Workspace Management

### List Workspaces

```typescript theme={null}
const workspaces = await client.getWorkspaces();
```

### Create Workspace

```typescript theme={null}
const workspace = await client.createWorkspace({
  name: "My Workspace",
  description: "Team workspace",
});
```

## Billing

### Get Available Plans

```typescript theme={null}
const plans = await client.getPlans();
plans.forEach((plan) => {
  console.log(`${plan.name}: $${plan.price}/month`);
});
```

### Get Current Plan

```typescript theme={null}
const currentPlan = await client.getCurrentPlan();
console.log("Current plan:", currentPlan.name);
```

### Subscribe to Plan

```typescript theme={null}
await client.subscribe("plan-id");
```

## Analytics

### Get Usage Statistics

```typescript theme={null}
const usage = await client.getUsage();
console.log("Characters used:", usage.characters);
console.log("API calls:", usage.api_calls);
```

## API Key Management

### List API Keys

```typescript theme={null}
const apiKeys = await client.getApiKeys();
```

### Create API Key

```typescript theme={null}
const newKey = await client.createApiKey("Production Key");
console.log("New API key:", newKey.key);
```

### Delete API Key

```typescript theme={null}
await client.deleteApiKey("key-id");
```

## Webhooks

### List Webhooks

```typescript theme={null}
const webhooks = await client.getWebhooks();
```

### Create Webhook

```typescript theme={null}
const webhook = await client.createWebhook({
  url: "https://example.com/webhook",
  events: ["tts.completed", "stt.completed"],
});
```

### Delete Webhook

```typescript theme={null}
await client.deleteWebhook("webhook-id");
```

## Error Handling

```typescript theme={null}
try {
  const audio = await client.textToSpeech({
    text: "Hello, world!",
    voice_id: "invalid-voice",
  });
} catch (error) {
  if (error.response) {
    // API error
    console.error("API Error:", error.response.status);
    console.error("Message:", error.response.data.message);
  } else {
    // Network or other error
    console.error("Error:", error.message);
  }
}
```

## TypeScript Types

The SDK includes full TypeScript type definitions:

```typescript theme={null}
import { SixtyDBClient, SixtyDBConfig, TTSResponse } from "60db-service";
```


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