> For the complete documentation index, see [llms.txt](https://docs.useagentdock.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.useagentdock.xyz/sdk/javascript.md).

# JavaScript / TypeScript

The AgentDock SDK is a typed JavaScript/TypeScript client for the AgentDock API. It supports Node.js 18+ and modern browser environments.

***

## Installation

```bash
npm install @agentdock/sdk
```

***

## AgentDockClient

### Constructor

```typescript
new AgentDockClient(config: ClientConfig)
```

**ClientConfig:**

| Option    | Type   | Required | Description                                                              |
| --------- | ------ | -------- | ------------------------------------------------------------------------ |
| `apiKey`  | string | Yes      | Your AgentDock API key                                                   |
| `baseUrl` | string | No       | Override the API base URL. Defaults to `https://api.useagentdock.xyz/v1` |
| `timeout` | number | No       | Request timeout in milliseconds. Default: `10000`                        |
| `retries` | number | No       | Number of automatic retries on transient errors (5xx). Default: `2`      |

***

## client.retrieve()

Retrieve context chunks from a purchased knowledge base.

```typescript
client.retrieve(params: RetrieveParams): Promise<RetrieveResponse>
```

**RetrieveParams:**

| Parameter   | Type   | Required | Description                                                        |
| ----------- | ------ | -------- | ------------------------------------------------------------------ |
| `listingId` | string | Yes      | The knowledge base listing ID                                      |
| `query`     | string | Yes      | Natural-language search query                                      |
| `topK`      | number | No       | Number of chunks to return. Default: `5`. Max: `20`                |
| `minScore`  | number | No       | Minimum relevance score (0.0 to 1.0)                               |
| `filters`   | object | No       | Metadata filters (see [Retrieve docs](/api-reference/retrieve.md)) |

**RetrieveResponse:**

```typescript
{
  chunks: Array<{
    text: string;
    score: number;
    sourceMetadata: Record<string, unknown>;
  }>;
  listingId: string;
  queryId: string;
  latencyMs: number;
}
```

***

## client.retrieveStream()

Stream context chunks from a knowledge base as they are scored.

```typescript
client.retrieveStream(params: RetrieveParams): AsyncIterable<Chunk>
```

Parameters are identical to `retrieve()`. Each yielded item is a single chunk object.

```typescript
const stream = client.retrieveStream({
  listingId: 'lst_abc123',
  query: 'standard indemnification language',
  topK: 10,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.text + '\n');
}
```

***

## client.listings.search()

Search marketplace listings.

```typescript
client.listings.search(params?: ListingSearchParams): Promise<ListingSearchResponse>
```

**ListingSearchParams:**

| Parameter     | Type                                                                 | Description            |
| ------------- | -------------------------------------------------------------------- | ---------------------- |
| `q`           | string                                                               | Search query           |
| `domain`      | string                                                               | Domain filter          |
| `accessModel` | `'one_time' \| 'subscription' \| 'per_query'`                        | Access model filter    |
| `maxPrice`    | number                                                               | Maximum price in SOL   |
| `minRating`   | number                                                               | Minimum average rating |
| `sort`        | `'relevance' \| 'rating' \| 'price_asc' \| 'price_desc' \| 'newest'` | Sort order             |
| `limit`       | number                                                               | Results per page       |
| `offset`      | number                                                               | Pagination offset      |

***

## client.listings.get()

Fetch a single listing by ID.

```typescript
client.listings.get(listingId: string): Promise<Listing>
```

***

## client.credentials.list()

List your active access credentials.

```typescript
client.credentials.list(params?: CredentialListParams): Promise<CredentialListResponse>
```

**CredentialListParams:**

| Parameter | Type                                     | Description       |
| --------- | ---------------------------------------- | ----------------- |
| `status`  | `'active' \| 'expired' \| 'low_balance'` | Filter by status  |
| `limit`   | number                                   | Results per page  |
| `offset`  | number                                   | Pagination offset |

***

## client.credentials.verify()

Verify whether you hold a valid credential for a specific listing.

```typescript
client.credentials.verify(listingId: string): Promise<CredentialVerifyResponse>
```

**CredentialVerifyResponse:**

```typescript
{
  listingId: string;
  valid: boolean;
  status: 'active' | 'expired' | 'low_balance' | 'not_found';
  expiresAt?: string;
  pdaAddress?: string;
  onChainVerified: boolean;
}
```

***

## Error handling

The SDK throws typed errors for all failure cases:

```typescript
import { AgentDockClient, AgentDockAPIError } from '@agentdock/sdk';

try {
  const { chunks } = await client.retrieve({ listingId, query });
} catch (error) {
  if (error instanceof AgentDockAPIError) {
    console.error(error.code);     // e.g. 'credential_expired'
    console.error(error.status);   // HTTP status code
    console.error(error.message);  // Human-readable description
  }
}
```

**Error subclasses:**

| Class                     | When thrown                                                |
| ------------------------- | ---------------------------------------------------------- |
| `AgentDockAuthError`      | Authentication failed (401)                                |
| `AgentDockAccessError`    | Credential missing, expired, or insufficient balance (403) |
| `AgentDockNotFoundError`  | Listing not found (404)                                    |
| `AgentDockRateLimitError` | Rate limit exceeded (429). Includes `retryAfter: number`   |
| `AgentDockAPIError`       | All other API errors                                       |

***

## TypeScript types

All request and response types are exported from the package root:

```typescript
import type {
  RetrieveParams,
  RetrieveResponse,
  Chunk,
  Listing,
  AccessCredential,
  ClientConfig,
} from '@agentdock/sdk';
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.useagentdock.xyz/sdk/javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
