npm package: @retaindb/sdk
Description: TypeScript SDK for RetainDB Context API - Add reliable context to your AI agents
Author: RetainDB
Latest version: 4.8.0

# @usewhisper/sdk

Official TypeScript SDK for [Whisper Context API](https://usewhisper.dev) - Give your AI agents perfect context.

`WhisperClient` is the primary SDK surface. `WhisperContext` remains available for compatibility, but automatic memory/retrieval behavior now lives in `WhisperClient.createAgentRuntime()`.

## What's New in v3.6

- Automatic runtime for scope resolution, pre-retrieval, session continuity, and background capture.
- Legacy wrapper turn helpers now run through the automatic runtime by default.
- Context query responses expose `meta.source_scope`.
- URL/domain queries automatically narrow to matching sources when possible.

## Installation

```bash
npm install @usewhisper/sdk
```

## Simple API (quickstart)

Four methods cover the most common use cases. The full `learn()` / `query()` signatures with all options are documented further below for power users.

```typescript
import { WhisperClient } from '@usewhisper/sdk';

const whisper = new WhisperClient({
  apiKey: process.env.WHISPER_API_KEY!,
  project: 'my-project',
});

// Store a conversation — sessionId is auto-generated if omitted
await whisper.remember({
  messages: [
    { role: 'user', content: 'I prefer TypeScript over JavaScript' },
    { role: 'assistant', content: 'Got it, I will use TypeScript.' },
  ],
  userId: req.user.id,  // required unless getIdentity() is configured on the client
});

// Index a source — type is auto-detected from the URL
await whisper.ingest({ url: 'https://github.com/your-org/your-repo' });
await whisper.ingest({ url: 'https://docs.example.com' });
await whisper.ingest({ url: 'https://youtube.com/watch?v=abc123' });

// Query with short aliases — include_memories defaults to true when not specified
const { context } = await whisper.query({ q: userMessage, userId: req.user.id });

// Get everything Whisper knows about a user
const profile = await whisper.userProfile(req.user.id);
```

## Quick Start

```typescript
import { WhisperClient } from '@usewhisper/sdk';

const client = new WhisperClient({
  apiKey: 'wsk_your_api_key_here',
  project: 'my-docs'
});

const result = await client.query({
  query: 'How does authentication work?'
});

console.log(result.meta.total);
```

### Typed errors

```typescript
import { WhisperError } from '@usewhisper/sdk';

try {
  await client.query({ query: 'How do I authenticate users?' });
} catch (error) {
  if (error instanceof WhisperError) {
    console.error(error.code, error.retryable, error.requestId, error.hint);
  }
}
```

### Preflight (recommended before production)

```typescript
const preflight = await client.preflight({ requireIdentity: false });
if (!preflight.ok) {
  console.error(preflight.checks);
}
```

### Framework-native adapters

```typescript
import { withWhisper } from '@usewhisper/sdk/ai-sdk';
import { whisperTools } from '@usewhisper/sdk/tools';

const wrappedModel = withWhisper(model, {
  apiKey: process.env.WHISPER_API_KEY!,
  project: 'my-docs',
});

const tools = whisperTools({
  apiKey: process.env.WHISPER_API_KEY!,
  project: 'my-docs',
});
```

### Experimental Memory Router (beta)

```typescript
import { createMemoryRouter } from '@usewhisper/sdk/router';

const router = createMemoryRouter({
  beta: true, // required until GA
  apiKey: process.env.WHISPER_API_KEY!,
  project: 'my-docs',
  providerBaseUrl: 'https://api.openai.com',
  providerApiKey: process.env.OPENAI_API_KEY!,
});

const response = await router.chatCompletions({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'What did we decide about retries?' }],
});
```

### SDK ownership contract

- SDK owns:
  - auth header wiring and base URL resolution
  - retries for retryable failures
  - typed `WhisperError` surface
  - `client.preflight()` readiness checks
  - identity-mode guardrails (`demo-local` vs `app-identity`)
- Caller owns:
  - authenticated app identity source (`getIdentity` and/or per-call identity)
  - app-specific retry overrides
  - application authorization decisions

### Migration policy

- Release `N`: additive contract changes only, deprecations warn.
- Release `N+1`: deprecated paths may be enforced/removed.
- Current behavior: `demo-local` in non-local environments emits warnings (warn-only).

## Authentication

Get your API key from the [Whisper dashboard](https://usewhisper.dev/dashboard):

```typescript
const client = new WhisperClient({
  apiKey: 'wsk_...',  // Your API key
  baseUrl: 'https://context.usewhisper.dev'  // Optional, defaults to production
});
```

## Core Features

### Context Query

```typescript
const result = await client.query({
  project: 'my-docs',
  query: 'Your question here',
  top_k: 10,              // Number of results
  source_ids: ['src_abc'], // Optional explicit source isolation
  include_memories: true,  // Include conversational memory
  include_graph: true,     // Include knowledge graph
  hybrid: true,            // Hybrid vector + keyword search
  rerank: true            // Rerank results for better relevance
});

console.log(result.meta.source_scope);
```

### Project Management

```typescript
// Create project
await whisper.createProject({ name: 'my-project' });

// List projects
const { projects } = await whisper.listProjects();

// Get project details
const project = await whisper.getProject(projectId);

// Delete project
await whisper.deleteProject(projectId);
```

### Data Sources

Connect 15+ auto-sync sources:

```typescript
// GitHub repository
await whisper.addSource(projectId, {
  name: 'GitHub Repo',
  connector_type: 'github',
  config: { 
    repo: 'owner/repo',
    token: 'ghp_...',
    branch: 'main'
  },
  sync_schedule: '0 */6 * * *'  // Sync every 6 hours
});

// Notion workspace
await whisper.addSource(projectId, {
  name: 'Notion Docs',
  connector_type: 'notion',
  config: { 
    token: 'secret_...',
    database_id: '...'
  }
});

// Sync source manually
await whisper.syncSource(sourceId);
```

### Direct Ingestion

```typescript
await whisper.ingest(projectId, [
  {
    title: 'Document Title',
    content: 'Document content...',
    metadata: { 
      author: 'John Doe',
      tags: ['api', 'docs']
    }
  }
]);
```

### Conversational Memory

```typescript
// Add memory
await whisper.addMemory({
  project: 'my-docs',
  content: 'User prefers dark mode',
  memory_type: 'factual',
  user_id: 'user123',
  importance: 0.8
});

// Search memories
const { memories } = await whisper.searchMemories({
  project: 'my-docs',
  query: 'user preferences',
  user_id: 'user123',
  top_k: 10
});
```

## Supported Connectors

- **GitHub** - Repositories, issues, PRs
- **GitLab** - Projects, issues, MRs
- **Notion** - Pages, databases
- **Confluence** - Spaces, pages
- **Slack** - Channels, messages
- **Discord** - Channels, messages
- **URLs** - Web pages
- **Sitemaps** - Entire websites
- **PDFs** - PDF documents
- **API Specs** - OpenAPI/Swagger
- **Databases** - PostgreSQL, MySQL
- **npm** - Package documentation
- **PyPI** - Package documentation
- **arXiv** - Research papers
- **HuggingFace** - Model docs

## API Reference

### WhisperContext

#### Constructor

```typescript
new WhisperContext(config: {
  apiKey: string;
  baseUrl?: string;
})
```

#### Methods

**Projects:**
- `createProject(params)` - Create a new project
- `listProjects()` - List all projects
- `getProject(id)` - Get project details
- `deleteProject(id)` - Delete a project

**Sources:**
- `addSource(projectId, params)` - Add a data source
- `listSources(projectId)` - List project sources
- `syncSource(sourceId)` - Manually sync a source
- `deleteSource(sourceId)` - Delete a source

**Context:**
- `query(params)` - Query context from your data
- `ingest(projectId, documents)` - Directly ingest documents

**Memory:**
- `addMemory(params)` - Add conversational memory
- `searchMemories(params)` - Search memories
- `listMemories(params)` - List all memories
- `updateMemory(id, params)` - Update a memory
- `deleteMemory(id)` - Delete a memory

**API Keys:**
- `createApiKey(params)` - Create a new API key
- `listApiKeys()` - List all API keys
- `deleteApiKey(id)` - Delete an API key

**Usage:**
- `getUsage(days)` - Get usage statistics

## Error Handling

```typescript
try {
  const result = await whisper.query({
    project: 'my-docs',
    query: 'test'
  });
} catch (error) {
  if (error.message.includes('401')) {
    console.error('Invalid API key');
  } else if (error.message.includes('404')) {
    console.error('Project not found');
  } else {
    console.error('Query failed:', error.message);
  }
}
```

## TypeScript Support

Full TypeScript support with type definitions included:

```typescript
import { WhisperContext, QueryParams, QueryResult } from '@usewhisper/sdk';
```

## Links

- [Documentation](https://docs.usewhisper.dev)
- [API Reference](https://context.usewhisper.dev)
- [GitHub](https://github.com/usewhisper/whisper)
- [Website](https://usewhisper.dev)

## License

MIT