# TypeScript SDK

Call the Hecaton API with `@hecaton-io/sdk`, an ESM client with TypeScript declarations generated from OpenAPI.

## Set up the SDK

The client uses Web APIs available in Node.js 20 and later. When the [npm package](https://www.npmjs.com/package/@hecaton-io/sdk) is available, install the version you want to use. Create a [project-scoped API token](tokens.md) and supply it in `HECATON_TOKEN`. Set `HECATON_PROJECT_ID` to the project ID. The example runs from a file named `run-workspace.mjs` with Node.js.

## Start a workspace and read its results

```js
import { HecatonApiError, HecatonClient } from '@hecaton-io/sdk';

const projectId = process.env.HECATON_PROJECT_ID;
if (!projectId) throw new Error('Set HECATON_PROJECT_ID.');
const client = new HecatonClient({ origin: process.env.HECATON_API_ORIGIN });
const signal = AbortSignal.timeout(900_000);

try {
  const { id } = await client.createWorkspace(
    {
      projectId,
      prompt: 'Run the checks and publish the result with a summary.',
      resultContract: { fields: { summary: { type: 'string' } } },
    },
    { signal },
  );
  console.log(id);
  for await (const event of client.streamWorkspaceEvents(id, { signal })) {
    if (event.type === 'question.asked') {
      throw new Error('Answer question ' + event.data.questionId + ' in Hecaton.');
    }
    if (event.type === 'turn.failed') throw new Error('Turn failed: ' + event.data.turnId);
    if (event.type === 'turn.completed') break;
  }
  console.log(JSON.stringify(await client.getWorkspaceResults(id, { signal })));
} catch (error) {
  if (error instanceof HecatonApiError) console.error(error.code, error.status, error.requestId);
  throw error;
}
```

## Call and retry behavior

- Method names match `operationId` in the [REST API reference](api.md). Pass path parameters in URL order, then the body when required, then options such as `signal` and `cursor`.
- The default API origin is `https://api.hecaton.io`. Pass `{ origin, token }` to override the origin or token. The SDK appends `/v1`. For browser use, keep personal tokens server-side and call through your own backend.
- The SDK uses a fresh UUID on operations that require an idempotency key. Supply `idempotencyKey` to keep the key across calls. It retries GETs and keyed POSTs on 429 and 5xx up to twice, honoring `Retry-After` up to 60 seconds per retry.
- The event iterator resumes after its last yielded ID. Persist the ID as a string and use `lastEventId` to resume after restarting a process. For 410 `event_cursor_expired`, read the latest workspace and turn state before resuming.
- Stop event iteration with `break` or an `AbortSignal`. Keep `requestId` from `HecatonApiError` when reporting a failure.
