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

# DocloClient

> Reference for the Doclo Cloud client SDK

The `DocloClient` is the main entry point for interacting with Doclo Cloud. It provides methods for executing flows, managing runs, and handling authentication.

## Installation

```bash theme={null}
pnpm add @doclo/client
```

## Initialization

```typescript theme={null}
import { DocloClient } from '@doclo/client';

const client = new DocloClient({
  apiKey: process.env.DOCLO_API_KEY!
});
```

### Configuration Options

| Option      | Type     | Default                | Description                              |
| ----------- | -------- | ---------------------- | ---------------------------------------- |
| `apiKey`    | `string` | Required               | API key (`dc_live_...` or `dc_test_...`) |
| `baseUrl`   | `string` | `https://app.doclo.ai` | Base URL for the API                     |
| `convexUrl` | `string` | Same as `baseUrl`      | URL for Convex data operations           |
| `timeout`   | `number` | `300000`               | Request timeout in ms (5 minutes)        |

```typescript theme={null}
const client = new DocloClient({
  apiKey: process.env.DOCLO_API_KEY!,
  timeout: 60000  // 1 minute timeout
});
```

<Note>
  API keys must be at least 50 characters and start with `dc_live_` (production) or `dc_test_` (test mode). Production keys cannot be used with localhost or private IP addresses.
</Note>

## Resources

The client exposes several resource namespaces:

| Resource               | Description                                            |
| ---------------------- | ------------------------------------------------------ |
| `client.flows`         | Execute flows and retrieve flow information            |
| `client.runs`          | Get execution status, poll for completion, cancel runs |
| `client.definitions`   | Flow definitions for local/hybrid execution            |
| `client.prompts`       | Prompt assets management                               |
| `client.schemas`       | Schema assets management                               |
| `client.assets`        | Flow assets bundles                                    |
| `client.observability` | Observability event ingestion                          |

<Note>
  The `definitions`, `prompts`, `schemas`, `assets`, and `observability` resources are used for advanced hybrid execution and asset management. See [Hybrid Client](/cloud/hybrid-client) for details.
</Note>

## Flows Resource

### `flows.run(flowId, options)`

Execute a flow with a document.

```typescript theme={null}
const result = await client.flows.run<InvoiceOutput>('flow_abc123', {
  input: {
    document: {
      base64: '...',
      filename: 'invoice.pdf',
      mimeType: 'application/pdf'
    },
    variables: {
      extractLineItems: true
    }
  },
  wait: true,
  timeout: 60000
});
```

**Parameters:**

| Option                    | Type      | Description                                      |
| ------------------------- | --------- | ------------------------------------------------ |
| `input.document.base64`   | `string`  | Base64-encoded document content                  |
| `input.document.filename` | `string`  | Original filename                                |
| `input.document.mimeType` | `string`  | MIME type (`application/pdf`, `image/png`, etc.) |
| `input.variables`         | `object`  | Optional variables to pass to the flow           |
| `wait`                    | `boolean` | Wait for completion before returning             |
| `timeout`                 | `number`  | Timeout for sync mode in ms (default: 30000)     |
| `webhookUrl`              | `string`  | URL to receive completion notification           |
| `metadata`                | `object`  | Custom metadata to attach                        |
| `idempotencyKey`          | `string`  | Prevent duplicate executions                     |
| `version`                 | `string`  | Specific flow version to run                     |

**Returns:** `Execution<T>`

### `flows.list(options?)`

List flows available in your organization.

```typescript theme={null}
const flows = await client.flows.list({ limit: 20 });

for (const flow of flows.data) {
  console.log(flow.id, flow.name);
}

// Pagination
if (flows.hasMore) {
  const nextPage = await client.flows.list({ cursor: flows.nextCursor });
}
```

**Parameters:**

| Option   | Type     | Description                                 |
| -------- | -------- | ------------------------------------------- |
| `limit`  | `number` | Max items to return (default: 20, max: 100) |
| `cursor` | `string` | Cursor from previous response               |

**Returns:** `PaginatedResponse<FlowInfo>`

### `flows.get(flowId, version?)`

Get information about a specific flow.

```typescript theme={null}
const flow = await client.flows.get('flow_abc123');

console.log(flow.name);
console.log(flow.inputSchema);  // JSON Schema for required input
```

**Returns:** `FlowInfo`

## Runs Resource

### `runs.get(executionId)`

Get the current status and result of an execution.

```typescript theme={null}
const execution = await client.runs.get<InvoiceOutput>('exec_abc123');

switch (execution.status) {
  case 'queued':
  case 'running':
    console.log('Still processing...');
    break;
  case 'success':
    console.log('Output:', execution.output);
    break;
  case 'failed':
    console.error('Error:', execution.error?.message);
    break;
  case 'cancelled':
    console.log('Execution was cancelled');
    break;
}
```

**Returns:** `Execution<T>`

### `runs.waitForCompletion(executionId, options?)`

Poll until an execution completes.

```typescript theme={null}
const result = await client.runs.waitForCompletion('exec_abc123', {
  interval: 2000,  // Poll every 2 seconds
  timeout: 300000  // Wait up to 5 minutes
});

console.log('Final status:', result.status);
console.log('Output:', result.output);
```

**Parameters:**

| Option     | Type     | Default  | Description            |
| ---------- | -------- | -------- | ---------------------- |
| `interval` | `number` | `1000`   | Polling interval in ms |
| `timeout`  | `number` | `300000` | Max wait time in ms    |

**Returns:** `Execution<T>`

**Throws:** `TimeoutError` if execution doesn't complete within timeout.

### `runs.cancel(executionId)`

Cancel a running execution.

```typescript theme={null}
await client.runs.cancel('exec_abc123');
```

## Types

### Execution

The result of a flow execution:

```typescript theme={null}
interface Execution<T = unknown> {
  id: string;                    // Unique execution ID
  flowId: string;                // Flow that was executed
  status: ExecutionStatus;       // Current status
  createdAt: string;             // When execution started
  completedAt?: string;          // When execution finished
  duration?: number;             // Duration in ms
  output?: T;                    // Extracted data (if successful)
  metrics?: ExecutionMetrics;    // Usage metrics
  traceId?: string;              // Distributed tracing ID
  metadata?: Record<string, unknown>;
  error?: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  };
}

type ExecutionStatus =
  | 'queued'
  | 'running'
  | 'success'
  | 'failed'
  | 'cancelled';

interface ExecutionMetrics {
  tokensUsed: number;
  cost: number;
  stepsRun: number;
  stepsTotal: number;
}
```

### FlowInfo

Information about a flow:

```typescript theme={null}
interface FlowInfo {
  id: string;
  name: string;
  description?: string;
  inputSchema?: object;  // JSON Schema for variables
  version: string;
  createdAt: string;
  updatedAt: string;
}
```

### DocumentInput

Document input structure:

```typescript theme={null}
interface DocumentInput {
  base64: string;    // Base64-encoded content
  filename: string;  // Original filename
  mimeType: string;  // MIME type
}
```

## Properties

### `client.isTestMode`

Check if using a test API key:

```typescript theme={null}
if (client.isTestMode) {
  console.log('Running in test mode');
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Error Handling" icon="triangle-exclamation" href="/cloud/executing-flows#error-handling">
    Handle errors gracefully
  </Card>

  <Card title="Webhooks" icon="webhook" href="/cloud/webhooks">
    Receive completion notifications
  </Card>
</CardGroup>
