npm package: @kognitos/node
Description: Kognitos JavaScript/TypeScript SDK
Latest version: 1.0.2

# kognitos

[![CI](https://github.com/kognitos/kognitos-node/actions/workflows/ci.yml/badge.svg)](https://github.com/kognitos/kognitos-node/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/@kognitos/node.svg)](https://www.npmjs.com/package/@kognitos/node)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

TypeScript SDK for the [Kognitos](https://kognitos.com) API.

- Zero runtime dependencies (uses native `fetch`)
- Dual CJS/ESM output with full TypeScript declarations
- Automatic snake_case/camelCase conversion
- Built-in retry with exponential backoff
- Request timeouts via AbortController
- Async iteration for paginated endpoints
- NDJSON streaming with auto-reconnect

## Installation

```bash
npm install @kognitos/node
```

## Quick start

```typescript
import Kognitos from '@kognitos/node';

const client = new Kognitos({
  token: 'pat_...',
  region: 'us', // 'us' | 'eu' | 'uk'
});

// List organizations
const { data: orgs } = await client.organizations.list();

// Get a workspace
const workspace = await client.workspaces.get({
  organizationId: 'org-123',
  workspaceId: 'ws-456',
});

// List automations with pagination
const { data: automations, nextPageToken } = await client.automations.list({
  organizationId: 'org-123',
  workspaceId: 'ws-456',
  pageSize: 10,
});
```

## Pagination

All list endpoints return `{ data, nextPageToken, totalSize }`. Use the built-in async iterator to auto-paginate:

```typescript
import { autoPaginate } from '@kognitos/node';

const page = await client.automations.list({
  organizationId: 'org-123',
  workspaceId: 'ws-456',
});

for await (const automation of autoPaginate(page, (token) =>
  client.automations.list({
    organizationId: 'org-123',
    workspaceId: 'ws-456',
    pageToken: token,
  }),
)) {
  console.log(automation.displayName);
}
```

Or collect everything at once:

```typescript
import { collectAll } from '@kognitos/node';

const all = await collectAll(page, (token) =>
  client.automations.list({
    organizationId: 'org-123',
    workspaceId: 'ws-456',
    pageToken: token,
  }),
);
```

## Streaming

Stream real-time agent events over NDJSON:

```typescript
for await (const event of client.agents.streamEvents({
  organizationId: 'org-123',
  workspaceId: 'ws-456',
  automationId: 'auto-789',
  runId: 'run-001',
  agentId: 'agent-abc',
})) {
  console.log(event);
}
```

Cancel a stream with an AbortController:

```typescript
const controller = new AbortController();

for await (const event of client.agents.streamEvents({
  ...scope,
  signal: controller.signal,
})) {
  if (shouldStop(event)) {
    controller.abort();
  }
}
```

## Error handling

All errors extend `KognitosError`. HTTP errors include status code and API error details:

```typescript
import {
  ApiError,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
  ConnectionError,
  TimeoutError,
} from '@kognitos/node';

try {
  await client.automations.get({ ... });
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log('Not found:', err.message);
  } else if (err instanceof RateLimitError) {
    console.log('Rate limited, retry after:', err.retryAfter, 'seconds');
  } else if (err instanceof AuthenticationError) {
    console.log('Bad token');
  } else if (err instanceof TimeoutError) {
    console.log('Request timed out');
  } else if (err instanceof ApiError) {
    console.log('API error:', err.status, err.code, err.details);
  }
}
```

## Configuration

```typescript
const client = new Kognitos({
  token: 'pat_...',          // Required — personal access token
  region: 'us',              // Required — 'us' | 'eu' | 'uk'
  env: 'prod',               // Optional — 'prod' (default) | 'dev'
  timeout: 30000,            // Optional — request timeout in ms (default: 30000)
  retry: {                   // Optional — retry config, or false to disable
    maxRetries: 2,           //   default: 2
    initialDelayMs: 500,     //   default: 500
    maxDelayMs: 5000,        //   default: 5000
  },
});
```

Per-request overrides:

```typescript
await client.automations.get(
  { organizationId: 'org-123', workspaceId: 'ws-456', automationId: 'auto-789' },
  { timeout: 5000, retry: false },
);
```

## Resources

| Resource | Methods |
|---|---|
| `client.organizations` | `list`, `get`, `getPreferences`, `listUsers`, `getUser`, `listWorkspaces`, `listInvitations`, `countWorkspaceUsers` |
| `client.workspaces` | `list`, `get`, `getPreferences`, `listUsers`, `listRoles`, `listInvitations` |
| `client.automations` | `list`, `get`, `invoke`, `query`, `getRevision`, `listRevisions`, `getVisualization`, `addConnections`, `removeConnections`, `switchConnections`, `getConnectionUsage`, `traceConnectionUsage`, `deleteConnection`, `createSchedule`, `updateSchedule`, `deleteSchedule`, `listTriggers`, `createTrigger`, `listDefaultInputsHistory` |
| `client.runs` | `list`, `get`, `getEvents`, `cancel`, `pause`, `getAggregates`, `getDailyAggregates` |
| `client.agents` | `listEvents`, `getEvent`, `sendEvent`, `cancelGeneration`, `streamEvents` |
| `client.books` | `list`, `listLatest`, `get`, `getVersions`, `getConcepts`, `getProcedures`, `search`, `listWorkspaceBooks`, `listWorkspaceBookConnections`, `createWorkspaceBookConnection`, `updateWorkspaceBookConnection`, `upgradeWorkspaceBookConnection`, `createWorkspaceBookConnectionTrigger`, `getWorkspaceBookConcepts`, `getWorkspaceBookProcedures`, `searchWorkspaceBooks`, `searchWorkspaceConcepts`, `searchWorkspaceProcedures` |
| `client.connections` | `list`, `get`, `authorize`, `discover`, `listDiscoverables`, `listProcedures`, `searchProcedures`, `deleteTriggerInstance`, `getUserInfo` |
| `client.files` | `upload`, `download`, `delete`, `getMetadata`, `generateUploadUrl`, `generateDownloadUrl` |
| `client.exceptions` | `list`, `get`, `listGroups`, `countByAutomation`, `countByGroup`, `listGuideEntries`, `getGuideEntry`, `getExecutionOutputs` |
| `client.triggers` | `list`, `addAutomations` |
| `client.analytics` | `queryInsights`, `queryAutomationEstimates`, `queryMetrics`, `configureAutomationEstimates` |

## Development

```bash
npm install
npm run generate   # Regenerate types from OpenAPI spec
npm run build      # Build CJS + ESM + types
npm run check      # TypeScript type checking
npm run lint       # ESLint + Prettier
npm test           # Run tests
```

## License

[MIT](LICENSE)