# TypeScript

The official TypeScript/JavaScript SDK for SteelEngine provides full type safety and lets you execute workflows programmatically from Node.js applications, serverless functions, and backend services.

The TypeScript SDK provides full type safety, async execution support, streaming with `onChunk`, automatic rate limiting with exponential backoff, and usage tracking. It runs on Node.js only, because it depends on `node-fetch` and `Buffer`. Call it from your backend and keep your API key server-side.

## Installation

Install the SDK using your preferred package manager:

**npm**

```bash
npm install @steelengine/sdk
```

**yarn**

```bash
yarn add @steelengine/sdk
```

**bun**

```bash
bun add @steelengine/sdk
```

## Quick Start

Here's a simple example to get you started:

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

// Initialize the client
const client = new SteelEngineClient({
  apiKey: 'your-api-key-here',
  baseUrl: 'https://steelengine.com' // optional, defaults to https://steelengine.com
});

// Execute a workflow
try {
  const result = await client.executeWorkflow('workflow-id');
  console.log('Workflow executed successfully:', result);
} catch (error) {
  console.error('Workflow execution failed:', error);
}
```

## API Reference

### SteelEngineClient

#### Constructor

```typescript
new SteelEngineClient(config: SteelEngineConfig)
```

**Configuration:**

* `config.apiKey` (string): Your SteelEngine API key
* `config.baseUrl` (string, optional): Base URL for the SteelEngine API (defaults to `https://steelengine.com`)

#### Methods

##### executeWorkflow()

Execute a workflow with optional input data.

The SDK's `timeout` limits the HTTP request. To limit the run itself, set [Execution timeout](/execution#workflow-timeouts) on the workflow. That deadline applies to sync and async runs, continues during waits and approvals, and is unaffected by the SDK option.

```typescript
const result = await client.executeWorkflow('workflow-id', { message: 'Hello, world!' }, {
  timeout: 30000 // 30 seconds
});
```

**Parameters:**

* `workflowId` (string): The ID of the workflow to execute
* `input` (any, optional): Input data to pass to the workflow. An object is sent as the top-level fields of the request body. A string, number, or array is wrapped as `{ input: value }`. The client converts `File` objects anywhere in the input to base64
* `options` (ExecutionOptions, optional):
  * `timeout` (number): Timeout in milliseconds (default: 30000). Cancels the HTTP request only. The workflow keeps running
  * `signal` (AbortSignal): Cancels this HTTP request, not the durable workflow
  * `stream` (boolean): Enable streaming responses (default: false)
  * `selectedOutputs` (string\[]): Block outputs to stream in `blockName.attribute` format (e.g., `["agent1.content"]`)
  * `onChunk` (`(chunk: ExecutionStreamChunk) => void | Promise<void>`): Receives each streamed chunk. Without it, the client reads and discards chunks
  * `maxStreamFrameBytes` (number): Per-frame SSE memory bound (default: 64 MiB). Raise it for large authored results
  * `async` (boolean): Send `X-Execution-Mode: async` and return as soon as the run is queued (default: false)
  * `useDraftState` (boolean): Execute the draft (unpublished) state. The API rejects this for API-key callers with `400`
  * `includeFileBase64` (boolean): Include base64 file content in outputs (server default: true)
  * `base64MaxBytes` (number): Cap on per-file base64 payload size in bytes
  * `stopAfterBlockId` (string): Stop execution after the given block completes

**Returns:** `Promise<WorkflowExecutionResult | AsyncExecutionResult | PendingExecutionResult>`

When `async: true`, returns HTTP 202 with a `jobId`, `executionId`, and `statusUrl` for polling. The `jobId` is the execution ID. A synchronous request waits for completion, but may also return HTTP 202 with `pending: true` if its wait window expires. Poll that execution ID; another POST would start another run.

| Mode               | Initial HTTP response                                                                 | Where the result appears                                                                   |
| ------------------ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Sync               | The executed root Response block's status and raw JSON data, or an execution envelope | The SDK normalizes Response data into `result.output`                                      |
| Async              | HTTP 202 admission receipt                                                            | `getJobStatus(jobId).output` when `status === 'completed'`                                 |
| Stream             | HTTP 200 opens an SSE connection                                                      | `onChunk` receives selected outputs; the final message reports execution status and timing |
| Sync still running | HTTP 202 with `pending: true`                                                         | `getJobStatus(executionId)` retrieves the same run                                         |

A Response block's authored status applies to sync HTTP delivery. In async output it is represented as `{ data, status, headers }`; job lookup still returns HTTP 200. Streaming also keeps HTTP 200 and reports the execution outcome in its terminal message. A child workflow's Response does not override the parent HTTP response.

##### executeWorkflowResponse()

Use this method to inspect the response kind, raw Response body, status, and headers without normalization:

```typescript
const response = await client.executeWorkflowResponse<{ answer: number }>('workflow-id');
if (response.kind === 'response') {
  console.log(response.status, response.headers, response.body);
} else if (response.kind === 'async' || response.kind === 'pending') {
  console.log(response.body.executionId, response.body.statusUrl);
} else {
  console.log(response.body);
}
```

Kinds come from the server's `X-SteelEngine-Response-Type` header, so authored fields such as `success`, `async`, or `output` are never mistaken for transport control fields. Bodyless Response statuses (204/205) return `null`. Non-2xx responses, including authored Response errors, throw `SteelEngineError` with `status` and `body`; they do not by themselves prove an engine failure.

HTTP 503 with `code: 'RESULT_UNAVAILABLE'` means the run's exact result could not be recovered. `STREAM_INCOMPLETE` means selected delivery could not be verified. Use the error's `executionId` or `statusUrl` to retrieve the existing run. An SDK timeout, abort, or disconnected stream cancels the HTTP request only. API-key callers can poll with the same authorized key; the builder's reconnect endpoint requires a session.

##### executeWorkflowSync()

Execute a workflow synchronously. `async` is always `false`.

```typescript
const result = await client.executeWorkflowSync('workflow-id', { data: 'some input' }, {
  timeout: 60000
});
```

**Parameters:** Same as `executeWorkflow()` without `async`

**Returns:** `Promise<WorkflowExecutionResult | PendingExecutionResult>`

##### getWorkflowStatus()

Get the status of a workflow (deployment status, etc.).

```typescript
const status = await client.getWorkflowStatus('workflow-id');
console.log('Is deployed:', status.isDeployed);
```

**Parameters:**

* `workflowId` (string): The ID of the workflow

**Returns:** `Promise<WorkflowStatus>`

The endpoint also returns `isPublished`, which the `WorkflowStatus` type does not declare.

##### validateWorkflow()

Validate that a workflow is ready for execution.

```typescript
const isReady = await client.validateWorkflow('workflow-id');
if (isReady) {
  // Workflow is deployed and ready
}
```

**Parameters:**

* `workflowId` (string): The ID of the workflow

**Returns:** `Promise<boolean>`

##### getWorkflow()

Get a workflow's full definition and deployment metadata (`GET /api/workflows/{id}`).

```typescript
const workflow = await client.getWorkflow('workflow-id');
console.log('Deployed:', workflow.isDeployed);
console.log('Blocks:', Object.keys(workflow.state.blocks));
```

**Parameters:**

* `workflowId` (string): The ID of the workflow

**Returns:** `Promise<any>` — the workflow record, including `name`, `description`, `workspaceId`, `isDeployed`, `deployedAt`, `variables`, and a `state` object with `blocks`, `edges`, `loops`, `parallels`, and `wireTies` (layout-only wire ties drawn on the canvas)

##### getJobStatus()

Get the status of an execution by its execution ID.

```typescript
const status = await client.getJobStatus(result.jobId);
console.log('Status:', status.status); // 'pending', 'processing', 'paused', 'completed', 'failed', 'cancelled'
if (status.status === 'completed') {
  console.log('Output:', status.output);
}
```

**Parameters:**

* `jobId` (string): The execution ID returned from async execution (`AsyncExecutionResult.jobId`)

**Returns:** `Promise<JobStatus>`

**Response fields:**

* `success` (boolean): Whether the lookup was successful
* `jobId` (string): The execution ID
* `taskId` (string): The same value as `jobId`
* `status` (string): One of `'pending'`, `'processing'`, `'paused'`, `'completed'`, `'failed'`, `'cancelled'`. Paused runs need input and are not complete
* `metadata` (object): Contains `workflowId`, `workspaceId`, `userId`, and `executionId`. Once the run has finished, it also contains `startTime`, `endTime`, and `duration`. After the run's execution record expires (7 days after it finishes on SteelEngine Cloud), the status comes from run history and `metadata` holds `workflowId`, `workspaceId`, `executionId`, and `source: 'run-history'`
* `output` (any, optional): Present once the run has a result. For an async execution this is the workflow output, or `{ data, status, headers }` when the workflow ended in a Response block. When `metadata.source` is `'run-history'`, this is the run-history copy of the output, which is size-capped and has secrets removed
* `error` (string, optional): Error message (when failed or cancelled)
* `startedAt`, `completedAt` (string, optional): ISO 8601 timestamps, present once the result is available. `completedAt` is absent for paused runs
* `executedAt` (string, optional): Same as `completedAt`, present for async executions only

##### cancelExecution()

Cancel a running or queued execution. Requires write-level access to the workflow.

```typescript
const cancel = await client.cancelExecution('workflow-id', result.executionId);
console.log('Cancelled:', cancel.success);
```

**Parameters:**

* `workflowId` (string): The workflow the execution belongs to
* `executionId` (string): The execution to cancel (`AsyncExecutionResult.executionId` or `WorkflowExecutionResult.executionId`)

**Returns:** `Promise<CancelExecutionResult>`

##### executeWithRetry()

Execute a workflow with automatic retry on rate limit errors using exponential backoff.

```typescript
const result = await client.executeWithRetry('workflow-id', { message: 'Hello' }, {
  timeout: 30000
}, {
  maxRetries: 3,           // Maximum number of retries
  initialDelay: 1000,      // Initial delay in ms (1 second)
  maxDelay: 30000,         // Maximum delay in ms (30 seconds)
  backoffMultiplier: 2     // Exponential backoff multiplier
});
```

**Parameters:**

* `workflowId` (string): The ID of the workflow to execute
* `input` (any, optional): Input data to pass to the workflow
* `options` (ExecutionOptions, optional): Same as `executeWorkflow()`
* `retryOptions` (RetryOptions, optional):
  * `maxRetries` (number): Maximum number of retries (default: 3)
  * `initialDelay` (number): Initial delay in ms (default: 1000)
  * `maxDelay` (number): Maximum delay in ms (default: 30000)
  * `backoffMultiplier` (number): Backoff multiplier (default: 2)

**Returns:** `Promise<WorkflowExecutionResult | AsyncExecutionResult | PendingExecutionResult>`

The retry logic uses exponential backoff (1s → 2s → 4s → 8s...) with ±25% jitter to prevent thundering herd. If the API provides a `retry-after` header, it will be used instead. The client retries only `RATE_LIMIT_EXCEEDED` errors. It throws every other `SteelEngineError` immediately. To retry any other client call the same way, wrap it in [`withRetry()`](#withretry).

##### getRateLimitInfo()

Get the rate limit information parsed from the `X-RateLimit-*` and `Retry-After` headers of the last API response.

```typescript
const rateLimitInfo = client.getRateLimitInfo();
if (rateLimitInfo) {
  console.log('Limit:', rateLimitInfo.limit);
  console.log('Remaining:', rateLimitInfo.remaining);
}
```

**Returns:** `RateLimitInfo | null`

The `/api/v1` workflows, logs, and audit logs endpoints send these headers on every response. The other `/api/v1` endpoints send them only with a `429`. The execution, job status, and usage limits endpoints do not send them, so after only those calls this returns `null`. Use `getUsageLimits()` to read your execution rate limit status.

##### getUsageLimits()

Get current usage limits and quota information for your account.

```typescript
const limits = await client.getUsageLimits();
console.log('Sync requests remaining:', limits.rateLimit.sync.remaining);
console.log('Async requests remaining:', limits.rateLimit.async.remaining);
console.log('Current period cost:', limits.usage.currentPeriodCost);
console.log('Plan:', limits.usage.plan);
console.log('Storage used:', limits.storage.usedBytes);
```

**Returns:** `Promise<UsageLimits>`

**Response structure:**

```typescript
{
  success: boolean
  rateLimit: {
    sync: {
      isLimited: boolean
      requestsPerMinute: number
      maxBurst: number
      remaining: number
      resetAt: string
    }
    async: {
      isLimited: boolean
      requestsPerMinute: number
      maxBurst: number
      remaining: number
      resetAt: string
    }
    authType: string  // 'api' or 'manual'
  }
  usage: {
    currentPeriodCost: number
    limit: number
    plan: string  // e.g., 'free', 'pro'
  }
  storage: {
    usedBytes: number
    limitBytes: number
    percentUsed: number
  }
}
```

##### listWorkspaces()

List the workspaces the API key has access to (`GET /api/v1/workspaces`).

```typescript
const page = await client.listWorkspaces({ scope: 'active', limit: 50 });
for (const workspace of page.workspaces) {
  console.log(workspace.id, workspace.name, workspace.roleKey);
}
```

**Parameters:**

* `params.scope` (`'active' | 'archived' | 'all'`, optional): Which workspaces to list (default `active`)
* `params.limit` (number, optional): Page size
* `params.offset` (number, optional): Number of workspaces to skip

**Returns:** `Promise<WorkspacesList>` with `workspaces`, `totalCount`, `limit`, and `offset`

##### createWorkspace()

Create a workspace (`POST /api/v1/workspaces`). Only unscoped personal API keys can create workspaces. Workspace, scoped, and organization keys receive `403`.

```typescript
const workspace = await client.createWorkspace('Engineering', { color: '#2563eb' });
console.log('Created:', workspace.id);
```

**Parameters:**

* `name` (string): Workspace display name
* `options.color` (string, optional): Workspace color
* `options.skipDefaultWorkflow` (boolean, optional): Don't create the default agent workflow

**Returns:** `Promise<Workspace>`

##### getWorkspace()

Get one workspace (`GET /api/v1/workspaces/{id}`).

```typescript
const workspace = await client.getWorkspace('workspace-id');
```

**Returns:** `Promise<WorkspaceDetails>`

##### updateWorkspace()

Update a workspace (`PATCH /api/v1/workspaces/{id}`). Send only the fields to change. Requires admin permission on the workspace.

```typescript
const workspace = await client.updateWorkspace('workspace-id', {
  name: 'Engineering',
  allowPersonalApiKeys: false,
});
```

**Parameters:**

* `updates.name`, `updates.color` (string, optional)
* `updates.billedAccountUserId` (string, optional): The user billed for this workspace's usage. Must already be an admin on the workspace
* `updates.allowPersonalApiKeys` (boolean, optional): Whether members can create personal API keys for this workspace

**Returns:** `Promise<WorkspaceDetails>`

##### setApiKey()

Update the API key.

```typescript
client.setApiKey('new-api-key');
```

##### setBaseUrl()

Update the base URL.

```typescript
client.setBaseUrl('https://my-custom-domain.com');
```

## Resource Methods

These methods call the `/api/v1` resource endpoints and the human-in-the-loop endpoints. Every method throws `SteelEngineError` on failure, with the server's `error` message, `code`, HTTP `status`, and the parsed error `body`. A `429` throws with code `RATE_LIMIT_EXCEEDED`. Path IDs are URL-encoded for you. All request and response types are exported from the package.

### Pagination

`listWorkflows()`, `queryLogs()`, and `listAuditLogs()` return one page as `{ data, nextCursor, limits }`. `nextCursor` is absent or `null` on the last page. Each has an `iterate*()` companion that fetches pages as you read:

```typescript
for await (const log of client.iterateLogs({ workspaceId, level: 'error' })) {
  console.log(log.executionId, log.startedAt);
}
```

For any other cursor endpoint, pass a page fetcher to `paginate()`. Set `maxPages` to stop early:

```typescript
import { paginate } from '@steelengine/sdk';

const logs = paginate((cursor) => client.queryLogs({ workspaceId, cursor }), { maxPages: 5 });
for await (const log of logs) console.log(log.id);
```

Table rows and knowledge base documents page with `limit` and `offset` instead.

### withRetry()

Run any client call with the same rate-limit retry as `executeWithRetry()`: exponential backoff with ±25% jitter, honoring `Retry-After`, retrying only `RATE_LIMIT_EXCEEDED`.

```typescript
const page = await client.withRetry(() => client.queryLogs({ workspaceId }), { maxRetries: 5 });
```

**Parameters:** `call` (`() => Promise<T>`) and `retryOptions` (`RetryOptions`, optional, same defaults as `executeWithRetry()`)

### Workflows

| Method                                                                      | Endpoint                     | Returns                                                |
| --------------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------ |
| `listWorkflows({ workspaceId, folderId?, deployedOnly?, limit?, cursor? })` | `GET /api/v1/workflows`      | `CursorPage<WorkflowSummary>`                          |
| `iterateWorkflows(params, options?)`                                        | same, every page             | `AsyncGenerator<WorkflowSummary>`                      |
| `getWorkflowMetadata(workflowId)`                                           | `GET /api/v1/workflows/{id}` | `WorkflowMetadata`, including `inputs` and `variables` |

`inputs` lists the start block's input fields as `{ name, type, description? }`. `getWorkflow()` still returns the full block definition from `GET /api/workflows/{id}`.

```typescript
for await (const workflow of client.iterateWorkflows({ workspaceId, deployedOnly: true })) {
  const { inputs } = await client.getWorkflowMetadata(workflow.id);
  console.log(workflow.name, inputs);
}
```

### Logs

| Method                          | Endpoint                                    | Returns                                              |
| ------------------------------- | ------------------------------------------- | ---------------------------------------------------- |
| `queryLogs(params)`             | `GET /api/v1/logs`                          | `CursorPage<LogEntry>`                               |
| `iterateLogs(params, options?)` | same, every page                            | `AsyncGenerator<LogEntry>`                           |
| `getLog(logId)`                 | `GET /api/v1/logs/{id}`                     | `LogDetail` with trace spans, final output, and cost |
| `getExecution(executionId)`     | `GET /api/v1/logs/executions/{executionId}` | `ExecutionDetails` with the workflow state snapshot  |

`queryLogs()` takes `workspaceId` and the filters of [Query Logs](/api-reference/logs/queryLogs). Pass `workflowIds`, `folderIds`, and `triggers` as arrays. They are sent comma-separated. `includeTraceSpans` and `includeFinalOutput` apply only with `details: 'full'`.

```typescript
const page = await client.queryLogs({
  workspaceId,
  triggers: ['api', 'schedule'],
  level: 'error',
  startDate: '2026-10-01T00:00:00Z',
  limit: 50,
});
```

### Audit Logs

| Method                                          | Endpoint                      | Returns                         |
| ----------------------------------------------- | ----------------------------- | ------------------------------- |
| `listAuditLogs(params?)`                        | `GET /api/v1/audit-logs`      | `CursorPage<AuditLogEntry>`     |
| `iterateAuditLogs(params?, options?)`           | same, every page              | `AsyncGenerator<AuditLogEntry>` |
| `getAuditLog(auditLogId, { organizationId? }?)` | `GET /api/v1/audit-logs/{id}` | `AuditLogEntry`                 |

Filters: `action`, `resourceType`, `resourceId`, `workspaceId`, `organizationId`, `actorId`, `startDate`, `endDate`, `includeDeparted`, and `limit`. A personal API key in more than one organization picks one with `organizationId`, on both list and get.

### Tables

Every table method takes the table's `workspaceId`.

| Method                                                                            | Endpoint                          | Returns                   |
| --------------------------------------------------------------------------------- | --------------------------------- | ------------------------- |
| `listTables(workspaceId)`                                                         | `GET /api/v1/tables`              | `{ tables, totalCount }`  |
| `createTable({ workspaceId, name, description?, columns })`                       | `POST /api/v1/tables`             | `Table`                   |
| `getTable(tableId, workspaceId)`                                                  | `GET /api/v1/tables/{tableId}`    | `Table`                   |
| `deleteTable(tableId, workspaceId)`                                               | `DELETE /api/v1/tables/{tableId}` | `void`                    |
| `addColumn(tableId, { workspaceId, column })`                                     | `POST …/columns`                  | `ColumnDefinition[]`      |
| `updateColumn(tableId, { workspaceId, columnName, updates })`                     | `PATCH …/columns`                 | `ColumnDefinition[]`      |
| `deleteColumn(tableId, { workspaceId, columnName })`                              | `DELETE …/columns`                | `ColumnDefinition[]`      |
| `listRows(tableId, { workspaceId, filter?, sort?, limit?, offset? })`             | `GET …/rows`                      | `RowsPage`                |
| `insertRow(tableId, { workspaceId, data })`                                       | `POST …/rows`                     | `TableRow`                |
| `insertRows(tableId, { workspaceId, rows })`                                      | `POST …/rows`                     | `{ rows, insertedCount }` |
| `updateRows(tableId, { workspaceId, filter, data, limit? })`                      | `PUT …/rows`                      | `UpdateRowsResult`        |
| `deleteRows(tableId, { workspaceId, filter, limit? } \| { workspaceId, rowIds })` | `DELETE …/rows`                   | `DeleteRowsResult`        |
| `getRow(tableId, rowId, workspaceId)`                                             | `GET …/rows/{rowId}`              | `TableRow`                |
| `updateRow(tableId, rowId, { workspaceId, data })`                                | `PATCH …/rows/{rowId}`            | `TableRow`                |
| `deleteRow(tableId, rowId, workspaceId)`                                          | `DELETE …/rows/{rowId}`           | `void`                    |
| `upsertRow(tableId, { workspaceId, data, conflictTarget? })`                      | `POST …/rows/upsert`              | `{ row, operation }`      |
| `claimRow(tableId, { workspaceId, filter, data })`                                | `POST …/rows/claim`               | `RowClaim \| null`        |

Column types are `string`, `number`, `boolean`, `date`, and `json`. `listRows()` sends `filter` and `sort` as JSON, for example `filter: { age: { $gt: 18 } }` and `sort: { createdAt: 'desc' }`. See [List Rows](/api-reference/tables/listRows) for the filter operators.

`claimRow()` atomically finds one row that matches an exact-value filter and writes `data` to it, so only one of several competing workers gets each row. At least one filtered field must change. It returns `null` when no row matches:

```typescript
const claim = await client.claimRow(tableId, {
  workspaceId,
  filter: { status: 'queued' },
  data: { status: 'processing' },
});
if (claim) await processLead(claim.row.data);
```

### Docs

| Method                                              | Endpoint                       | Returns                                   |
| --------------------------------------------------- | ------------------------------ | ----------------------------------------- |
| `listDocs({ workspaceId, folderId?, scope? })`      | `GET /api/v1/docs`             | `{ docs, totalCount }`                    |
| `uploadDoc({ workspaceId, file, folderId? })`       | `POST /api/v1/docs`            | `DocMetadata`                             |
| `downloadDoc(fileId, workspaceId)`                  | `GET /api/v1/docs/{fileId}`    | `DownloadedDoc` with `data` as a `Buffer` |
| `deleteDoc(fileId, workspaceId)`                    | `DELETE /api/v1/docs/{fileId}` | `void`                                    |
| `listDocFolders(workspaceId)`                       | `GET /api/v1/docs/folders`     | `{ folders, totalCount }`                 |
| `createDocFolder({ workspaceId, name, parentId? })` | `POST /api/v1/docs/folders`    | `DocFolder`                               |

Uploads take an `UploadFile`: `{ data, filename, contentType? }`, where `data` is a `Buffer`, `Uint8Array`, `ArrayBuffer`, or `Blob`. The SDK uses `contentType` when supplied, otherwise the Blob's type or the MIME type inferred from a supported document filename such as `.pdf`, `.txt`, or `.json`. Unknown extensions fall back to `application/octet-stream`. This also applies to knowledge document uploads. The SDK sends it as multipart form data. Docs can be up to 100 MB. `deleteDoc()` archives the doc. List with `scope: 'archived'` to see archived docs.

```typescript
import { readFile, writeFile } from 'node:fs/promises';

const doc = await client.uploadDoc({
  workspaceId,
  file: { data: await readFile('./report.pdf'), filename: 'report.pdf', contentType: 'application/pdf' },
});
const download = await client.downloadDoc(doc.id, workspaceId);
await writeFile(download.filename, download.data);
```

### Knowledge Bases

| Method                                                                                                                    | Endpoint                          | Returns                          |
| ------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | -------------------------------- |
| `listKnowledgeBases(workspaceId)`                                                                                         | `GET /api/v1/knowledge`           | `{ knowledgeBases, totalCount }` |
| `createKnowledgeBase({ workspaceId, name, description?, chunkingConfig? })`                                               | `POST /api/v1/knowledge`          | `KnowledgeBase`                  |
| `getKnowledgeBase(knowledgeBaseId, workspaceId)`                                                                          | `GET /api/v1/knowledge/{id}`      | `KnowledgeBase`                  |
| `updateKnowledgeBase(knowledgeBaseId, { workspaceId, name?, description?, chunkingConfig? })`                             | `PUT /api/v1/knowledge/{id}`      | `KnowledgeBase`                  |
| `deleteKnowledgeBase(knowledgeBaseId, workspaceId)`                                                                       | `DELETE /api/v1/knowledge/{id}`   | `void`                           |
| `listKnowledgeDocuments(knowledgeBaseId, { workspaceId, limit?, offset?, search?, enabledFilter?, sortBy?, sortOrder? })` | `GET …/documents`                 | `KnowledgeDocumentsPage`         |
| `uploadKnowledgeDocument(knowledgeBaseId, { workspaceId, file })`                                                         | `POST …/documents`                | `KnowledgeDocument`              |
| `getKnowledgeDocument(knowledgeBaseId, documentId, workspaceId)`                                                          | `GET …/documents/{documentId}`    | `KnowledgeDocumentDetail`        |
| `deleteKnowledgeDocument(knowledgeBaseId, documentId, workspaceId)`                                                       | `DELETE …/documents/{documentId}` | `void`                           |
| `searchKnowledge({ workspaceId, knowledgeBaseIds, query?, topK?, tagFilters? })`                                          | `POST /api/v1/knowledge/search`   | `KnowledgeSearchResponse`        |

`updateKnowledgeBase()` replaces the whole `chunkingConfig`, so pass all of `maxSize`, `minSize`, and `overlap`.

A document is chunked and embedded after upload. Poll `getKnowledgeDocument()` until `processingStatus` is `completed` or `failed` before you search it:

```typescript
const doc = await client.uploadKnowledgeDocument(kbId, {
  workspaceId,
  file: { data: await readFile('./handbook.md'), filename: 'handbook.md' },
});

let status = doc.processingStatus;
while (status === 'pending' || status === 'processing') {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  status = (await client.getKnowledgeDocument(kbId, doc.id, workspaceId)).processingStatus;
}

const { results } = await client.searchKnowledge({
  workspaceId,
  knowledgeBaseIds: [kbId],
  query: 'How many vacation days do I get?',
  topK: 5,
});
```

### Human in the Loop

These methods work with runs paused by a [Human in the Loop block](/blocks/human-in-the-loop).

| Method                                                                    | Endpoint                                                  | Returns                 |
| ------------------------------------------------------------------------- | --------------------------------------------------------- | ----------------------- |
| `listPausedExecutions(workflowId, { status? })`                           | `GET /api/workflows/{id}/paused`                          | `PausedExecution[]`     |
| `getPausedExecution(workflowId, executionId)`                             | `GET /api/workflows/{id}/paused/{executionId}`            | `PausedExecution`       |
| `resumeExecution(workflowId, executionId, contextId, input?, { async? })` | `POST /api/resume/{workflowId}/{executionId}/{contextId}` | `ResumeExecutionResult` |

`listPausedExecutions()` filters on `status`, which defaults to `paused`. Pass an array to match several statuses. Each pause point has a `contextId`. Pass it to `resumeExecution()` with the human's answer as `input`. Resuming needs write access to the workflow.

`resumeExecution()` waits for the resumed run to finish and returns its `output`. The server waits up to 330 seconds. If the run is still going, the result has a `statusUrl`. With `{ async: true }` it returns at once with a `statusUrl`. Poll it, or call `getJobStatus(result.jobId ?? result.executionId)`. A result with `status: 'queued'` is waiting behind other resumes of the same run, at `queuePosition`:

```typescript
const [paused] = await client.listPausedExecutions(workflowId);
const pausePoint = paused.pausePoints[0];

const result = await client.resumeExecution(
  workflowId,
  paused.executionId,
  pausePoint.contextId,
  { approved: true, comment: 'Looks good' },
  { async: true }
);
const job = await client.getJobStatus(result.jobId ?? result.executionId);
```

## Types

### WorkflowExecutionResult

```typescript
interface WorkflowExecutionResult {
  success: boolean;
  executionId?: string;
  status?: 'success' | 'failed' | 'cancelled' | 'paused';
  output?: any;
  error?: string;
  logs?: any[];
  metadata?: ExecutionMetadata;
  traceSpans?: any[];
  totalDuration?: number;
}

interface ExecutionMetadata {
  duration?: number;
  startTime?: string;
  endTime?: string;
  timingSemanticsVersion?: number;
  activeDurationMs?: number;
  waitDurationMs?: number;
  elapsedDurationMs?: number;
  [key: string]: any;
}
```

The execute endpoint fills `success`, `executionId`, `status`, `output`, `error`, and `metadata`. The API does not return `logs`, `traceSpans`, or `totalDuration`.

### AsyncExecutionResult

```typescript
interface AsyncExecutionResult {
  success: boolean;
  async: true;
  jobId: string;       // the execution ID
  executionId: string;
  message: string;
  statusUrl: string;   // e.g., "https://steelengine.com/api/jobs/{executionId}"
}
```

### PendingExecutionResult

```typescript
interface PendingExecutionResult {
  success: true;
  pending: true;
  executionId: string;
  jobId?: string;
  message: string;
  statusUrl: string;
}
```

### JobStatus

```typescript
type JobStatusValue =
  | 'queued'
  | 'pending'
  | 'processing'
  | 'paused'
  | 'completed'
  | 'failed'
  | 'cancelled';

interface JobStatus {
  jobId: string;
  taskId?: string;
  status: JobStatusValue;
  output?: any;
  error?: string;
  startedAt?: string;
  completedAt?: string;
  metadata?: ExecutionMetadata & { startedAt?: string; completedAt?: string };
  [key: string]: any;
}
```

The type keeps `'queued'` for compatibility. The server emits `'pending'` for a run that is admitted but not started.

### WorkflowStatus

```typescript
interface WorkflowStatus {
  isDeployed: boolean;
  deployedAt?: string;
  needsRedeployment: boolean;
}
```

### CancelExecutionResult

```typescript
interface CancelExecutionResult {
  success: boolean;
  executionId: string;
  durablyRecorded: boolean;
  locallyAborted: boolean;
  redisAvailable: boolean;
  reason?: string;
}
```

### Workspace and WorkspacesList

```typescript
interface Workspace {
  id: string;
  name: string;
  [key: string]: any;  // slug, color, organizationId, roleKey, roleKeys, ...
}

interface WorkspacesList {
  workspaces: Workspace[];
  totalCount: number;
  limit: number;
  offset: number;
}
```

### ExecutionStreamChunk

```typescript
interface ExecutionStreamChunk {
  blockId: string;
  chunk: string;
  outputId?: string;      // selected output path, distinguishes fields
  invocationId?: string;  // distinguishes repeated blocks
}
```

### RateLimitInfo

```typescript
interface RateLimitInfo {
  limit: number;
  remaining: number;
  reset: number;        // Unix time in seconds when the window resets
  retryAfter?: number;  // milliseconds, from Retry-After
}
```

### UsageLimits

```typescript
interface RateLimitWindow {
  isLimited: boolean;
  requestsPerMinute: number;
  maxBurst: number;
  remaining: number;
  resetAt: string;
}

interface UsageLimits {
  success: boolean;
  rateLimit: {
    sync: RateLimitWindow;
    async: RateLimitWindow;
    authType: string;
  };
  usage: {
    currentPeriodCost: number;
    limit: number;
    plan: string;
  };
  storage: {
    usedBytes: number;
    limitBytes: number;
    percentUsed: number;
  };
}
```

### SteelEngineError

```typescript
class SteelEngineError extends Error {
  name: 'SteelEngineError';
  code?: string;
  status?: number;
  body?: unknown;
  executionId?: string;
  statusUrl?: string;
}
```

HTTP errors carry the response `status` (`401`, `402`, `403`, `404`, `409`, `429`, `500`, `503`), the parsed `body`, and, when the server included one, its `code`. Execution errors also carry `executionId` and `statusUrl` when the run was admitted. Codes set by the client itself:

* `TIMEOUT`: The request exceeded `timeout`
* `ABORTED`: The request was cancelled through `signal`
* `INVALID_OPTIONS`: `timeout` was not a positive number
* `RATE_LIMIT_EXCEEDED`: The API returned `429`
* `EXECUTION_ERROR`: The execute request failed at the transport level
* `STREAM_ERROR`: The SSE stream was malformed or closed before its terminal result
* `STATUS_ERROR`, `CANCEL_ERROR`, `WORKFLOW_ERROR`, `WORKSPACE_ERROR`, `USAGE_ERROR`: The corresponding lookup request failed at the transport level
* `LOGS_ERROR`, `AUDIT_LOG_ERROR`, `TABLE_ERROR`, `DOCS_ERROR`, `KNOWLEDGE_ERROR`, `PAUSED_EXECUTION_ERROR`, `RESUME_ERROR`: A resource method failed at the transport level
* `PAGINATION_ERROR`: A paginated endpoint returned the same cursor twice
* `MAX_RETRIES_EXCEEDED`: `executeWithRetry()` or `withRetry()` ran out of attempts

Codes passed through from the server include `INVALID_SELECTED_OUTPUT` (`400`), `RESULT_UNAVAILABLE` (`503`), and `STREAM_INCOMPLETE` (stream `error` event). A `401` response has no code. Check `error.status` instead.

## Examples

### Basic Workflow Execution

**Initialize the client**

Set up the SteelEngineClient with your API key.

**Validate the workflow**

Check if the workflow is deployed and ready for execution.

**Execute the workflow**

Run the workflow with your input data.

**Handle the result**

Process the execution result and handle any errors.

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function runWorkflow() {
  try {
    // Check if workflow is ready
    const isReady = await client.validateWorkflow('my-workflow-id');
    if (!isReady) {
      throw new Error('Workflow is not deployed or ready');
    }

    // Execute the workflow
    const result = await client.executeWorkflow('my-workflow-id', {
      message: 'Process this data',
      userId: '12345'
    });

    if ('pending' in result || 'async' in result) {
      console.log('Still running, poll:', result.statusUrl);
    } else if (result.success) {
      console.log('Output:', result.output);
      console.log('Duration:', result.metadata?.duration);
    } else {
      console.error('Workflow failed:', result.error);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

runWorkflow();
```

### Error Handling

Handle different types of errors that may occur during workflow execution:

```typescript
import { SteelEngineClient, SteelEngineError } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function executeWithErrorHandling() {
  try {
    const result = await client.executeWorkflow('workflow-id');
    return result;
  } catch (error) {
    if (error instanceof SteelEngineError) {
      if (error.status === 401) {
        console.error('Invalid API key');
      } else if (error.status === 402) {
        console.error('Usage limit exceeded');
      } else {
        switch (error.code) {
          case 'TIMEOUT':
            console.error('Workflow execution timed out; poll', error.statusUrl);
            break;
          case 'RATE_LIMIT_EXCEEDED':
            console.error('Rate limit exceeded');
            break;
          case 'RESULT_UNAVAILABLE':
            console.error('Result unavailable; poll', error.statusUrl);
            break;
          default:
            console.error('Workflow error:', error.message);
        }
      }
    } else {
      console.error('Unexpected error:', error);
    }
    throw error;
  }
}
```

### Environment Configuration

Configure the client using environment variables:

**Development**

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

// Development configuration
const apiKey = process.env.STEELENGINE_API_KEY;
if (!apiKey) {
  throw new Error('STEELENGINE_API_KEY environment variable is required');
}

const client = new SteelEngineClient({
  apiKey,
  baseUrl: process.env.STEELENGINE_BASE_URL // optional
});
```

**Production**

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

// Production configuration with validation
const apiKey = process.env.STEELENGINE_API_KEY;
if (!apiKey) {
  throw new Error('STEELENGINE_API_KEY environment variable is required');
}

const client = new SteelEngineClient({
  apiKey,
  baseUrl: process.env.STEELENGINE_BASE_URL || 'https://steelengine.com'
});
```

### Node.js Express Integration

Integrate with an Express.js server:

```typescript
import express from 'express';
import { SteelEngineClient } from '@steelengine/sdk';

const app = express();
const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

app.use(express.json());

app.post('/execute-workflow', async (req, res) => {
  try {
    const { workflowId, input } = req.body;
    
    const result = await client.executeWorkflow(workflowId, input, {
      timeout: 60000
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('Workflow execution error:', error);
    res.status(500).json({
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

### Next.js API Route

Use with Next.js API routes:

```typescript
// pages/api/workflow.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { SteelEngineClient } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { workflowId, input } = req.body;

    const result = await client.executeWorkflow(workflowId, input, {
      timeout: 30000
    });

    res.status(200).json(result);
  } catch (error) {
    console.error('Error executing workflow:', error);
    res.status(500).json({
      error: 'Failed to execute workflow'
    });
  }
}
```

### Calling From the Browser

The SDK does not run in the browser, because it depends on `node-fetch` and `Buffer`. Keep the SDK and your API key on the server. Expose your own endpoint to the browser, such as the Express or Next.js routes above. A client-side call is then a normal fetch to your backend:

```typescript
const response = await fetch('/api/workflow', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    workflowId: 'workflow-id',
    input: { userInput: 'Hello from browser' }
  })
});

const result = await response.json();
document.getElementById('result')!.textContent =
  JSON.stringify(result.output, null, 2);
```

### File Upload

`File` objects are automatically detected and converted to base64 format. Include them in your input under the field name matching your workflow's API trigger input format. Detection uses the global `File` class, which Node.js provides from version 20.

The SDK converts File objects to this format:

```typescript
{
  type: 'file',
  data: 'data:mime/type;base64,base64data',
  name: 'filename',
  mime: 'mime/type'
}
```

Alternatively, you can manually provide files using the URL format:

```typescript
{
  type: 'url',
  data: 'https://example.com/file.pdf',
  name: 'file.pdf',
  mime: 'application/pdf'
}
```

```typescript
import { SteelEngineClient } from '@steelengine/sdk';
import fs from 'fs';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

// Read file and create File object (global File requires Node.js 20+)
const fileBuffer = fs.readFileSync('./document.pdf');
const file = new File([fileBuffer], 'document.pdf', {
  type: 'application/pdf'
});

// Include files under the field name from your API trigger's input format
const result = await client.executeWorkflow('workflow-id', {
  documents: [file],  // Must match your workflow's "files" field name
  query: 'Summarize this document'
});
```

To accept uploads from a browser, receive the files on your backend first. Build the `File` objects there, then call the SDK.

### React Hook Example

Create a custom React hook that calls your backend route (see [Next.js API Route](#nextjs-api-route)) so the API key never reaches the browser:

```typescript
import { useState, useCallback } from 'react';
import type { WorkflowExecutionResult } from '@steelengine/sdk';

interface UseWorkflowResult {
  result: WorkflowExecutionResult | null;
  loading: boolean;
  error: Error | null;
  executeWorkflow: (workflowId: string, input?: any) => Promise<void>;
}

export function useWorkflow(): UseWorkflowResult {
  const [result, setResult] = useState<WorkflowExecutionResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const executeWorkflow = useCallback(async (workflowId: string, input?: any) => {
    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const response = await fetch('/api/workflow', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ workflowId, input })
      });
      if (!response.ok) {
        throw new Error(`Request failed with status ${response.status}`);
      }
      setResult((await response.json()) as WorkflowExecutionResult);
    } catch (err) {
      setError(err instanceof Error ? err : new Error('Unknown error'));
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    result,
    loading,
    error,
    executeWorkflow
  };
}

// Usage in component
function WorkflowComponent() {
  const { result, loading, error, executeWorkflow } = useWorkflow();

  const handleExecute = () => {
    executeWorkflow('my-workflow-id', {
      message: 'Hello from React!'
    });
  };

  return (
    <div>
      <button onClick={handleExecute} disabled={loading}>
        {loading ? 'Executing...' : 'Execute Workflow'}
      </button>

      {error && <div>Error: {error.message}</div>}
      {result && (
        <div>
          <h3>Result:</h3>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
```

### Async Workflow Execution

Execute workflows asynchronously for long-running tasks:

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function executeAsync() {
  try {
    // Start async execution
    const result = await client.executeWorkflow('workflow-id', { data: 'large dataset' }, {
      async: true  // Execute asynchronously
    });

    // Check if result is an async execution
    if ('async' in result && result.async) {
      console.log('Job ID:', result.jobId);
      console.log('Status endpoint:', result.statusUrl);

      // Poll for completion
      let status = await client.getJobStatus(result.jobId);

      while (status.status === 'pending' || status.status === 'processing') {
        console.log('Current status:', status.status);
        await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
        status = await client.getJobStatus(result.jobId);
      }

      if (status.status === 'completed') {
        console.log('Workflow completed!');
        console.log('Output:', status.output);
        console.log('Duration:', status.metadata?.duration);
      } else if (status.status === 'paused') {
        console.log('Workflow is waiting for human input');
      } else {
        console.error(`Workflow ${status.status}:`, status.error);
      }
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

executeAsync();
```

### Rate Limiting and Retry

Handle rate limits automatically with exponential backoff:

```typescript
import { SteelEngineClient, SteelEngineError } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function executeWithRetryHandling() {
  try {
    // Automatically retries on rate limit
    const result = await client.executeWithRetry('workflow-id', { message: 'Process this' }, {}, {
      maxRetries: 5,
      initialDelay: 1000,
      maxDelay: 60000,
      backoffMultiplier: 2
    });

    console.log('Success:', result);
  } catch (error) {
    if (error instanceof SteelEngineError && error.code === 'RATE_LIMIT_EXCEEDED') {
      console.error('Rate limit exceeded after all retries');

      // The execute endpoint sends no rate limit headers; read the bucket instead
      const limits = await client.getUsageLimits();
      console.log('Rate limit resets at:', limits.rateLimit.sync.resetAt);
    }
  }
}
```

### Usage Monitoring

Monitor your account usage and limits:

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function checkUsage() {
  try {
    const limits = await client.getUsageLimits();

    console.log('=== Rate Limits ===');
    console.log('Sync requests:');
    console.log('  Per minute:', limits.rateLimit.sync.requestsPerMinute);
    console.log('  Max burst:', limits.rateLimit.sync.maxBurst);
    console.log('  Remaining:', limits.rateLimit.sync.remaining);
    console.log('  Resets at:', limits.rateLimit.sync.resetAt);
    console.log('  Is limited:', limits.rateLimit.sync.isLimited);

    console.log('\nAsync requests:');
    console.log('  Per minute:', limits.rateLimit.async.requestsPerMinute);
    console.log('  Max burst:', limits.rateLimit.async.maxBurst);
    console.log('  Remaining:', limits.rateLimit.async.remaining);
    console.log('  Resets at:', limits.rateLimit.async.resetAt);
    console.log('  Is limited:', limits.rateLimit.async.isLimited);

    console.log('\n=== Usage ===');
    console.log('Current period cost: $' + limits.usage.currentPeriodCost.toFixed(2));
    console.log('Limit: $' + limits.usage.limit.toFixed(2));
    console.log('Plan:', limits.usage.plan);

    const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
    console.log('Usage: ' + percentUsed.toFixed(1) + '%');

    if (percentUsed > 80) {
      console.warn('⚠️  Warning: You are approaching your usage limit!');
    }

    console.log('\n=== Storage ===');
    console.log('Used:', limits.storage.usedBytes, 'of', limits.storage.limitBytes, 'bytes');
    console.log('Storage: ' + limits.storage.percentUsed.toFixed(1) + '%');
  } catch (error) {
    console.error('Error checking usage:', error);
  }
}

checkUsage();
```

### Streaming Workflow Execution

Execute workflows with real-time streaming responses:

```typescript
import { SteelEngineClient } from '@steelengine/sdk';

const client = new SteelEngineClient({
  apiKey: process.env.STEELENGINE_API_KEY!
});

async function executeWithStreaming() {
  try {
    // Enable streaming for specific block outputs
    const result = await client.executeWorkflow('workflow-id', { message: 'Count to five' }, {
      stream: true,
      selectedOutputs: ['agent1.content'], // Use blockName.attribute format
      onChunk: ({ blockId, outputId, invocationId, chunk }) => {
        // Accumulate each field/invocation separately when selecting several outputs.
        process.stdout.write(chunk);
      }
    });

    console.log('Workflow result:', result);
  } catch (error) {
    console.error('Error:', error);
  }
}
```

The SDK requests stream version 2 with `X-SteelEngine-Stream-Version: 2`. Direct HTTP clients should send that header too; callers without it retain the legacy nested `final` message. The streaming response follows the Server-Sent Events (SSE) format:

```
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One","outputId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f_content","invocationId":"inv_1"}

data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two","outputId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f_content","invocationId":"inv_1"}

data: {"event":"done","executionId":"exec_abc123","statusUrl":"https://steelengine.com/api/jobs/exec_abc123","success":true,"status":"success","output":{},"metadata":{"duration":610}}

data: [DONE]
```

Chunks also carry `outputId` and `invocationId`, distinguishing multiple fields and repeated blocks. A single selected `content` field can arrive as live text when its block supports it; other selected values arrive after their producing block settles. Strings are unchanged; other values are JSON-serialized. No separators are inserted. A successful selected stream ends with `done.output: {}` because the values were already delivered. Without selections, `done.output` contains the terminal workflow output.

The SDK resolves only after a terminal result and `[DONE]`. Received chunks or a closed connection alone are not success. A terminal `status: 'paused'` ends this stream segment while the run waits for input. Check `success` and `status` before treating the workflow as finished.

Timing values are milliseconds. When `timingSemanticsVersion` is 2, `duration` reflects active execution time, while `waitDurationMs` and `elapsedDurationMs` distinguish waiting from total wall time. Repeated polling retains the original completion timestamp and timing.

**Using streaming in a web app:**

Run the SDK on your backend and forward its `onChunk` messages through your application's authenticated streaming endpoint. In the UI, keep each selected field/invocation separate, show incoming chunks as progress, and clear the loading state only after the final result. Show a paused run as waiting for input, and a disconnected stream as incomplete with a link to check its execution status.

If you consume raw SSE instead, retain the decoder and an unfinished-frame buffer across network reads. A network read can end halfway through a UTF-8 character or a JSON message. Require the terminal result and `[DONE]`; do not ignore malformed JSON or treat transport closure as successful completion.

## Getting Your API Key

**Log in to SteelEngine**

Navigate to [SteelEngine](https://app.steelengine.com) and log in to your account.

**Open your workflow**

Navigate to the workflow you want to execute programmatically.

**Deploy your workflow**

Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.

**Create or select an API key**

During the deployment process, select or create an API key.

**Copy the API key**

Copy the API key to use in your TypeScript/JavaScript application.

## Requirements

* Node.js 16+ (Node.js 20+ to send `File` objects)
* TypeScript 4.7+ (for TypeScript projects). The package exposes its types through the `exports` field, so `moduleResolution` must be `node16`, `nodenext`, or `bundler`

## Common Questions

**Do I need to deploy a workflow before I can execute it via the SDK?**

Yes. Workflows must be deployed before they can be executed through the SDK. You can use the validateWorkflow() method to check whether a workflow is deployed and ready. If it returns false, deploy the workflow from the SteelEngine UI first and create or select an API key during deployment.

**What is the difference between sync and async execution?**

Sync execution waits for the result. If its wait window expires, it returns a pending receipt for the same execution. Async execution immediately returns a jobId (the execution ID) and statusUrl. Poll with getJobStatus() using the same API key. Statuses are pending, processing, paused, completed, failed, and cancelled. Paused means the run needs input. Another execution request starts a new run.

**How does streaming work with the SDK?**

Set stream: true and select fields using blockName.attribute (for example, ['agent1.content']). Pass an onChunk callback to receive chunks. Chunks identify the block, selected field, and invocation. Supported text can arrive live; other values arrive after their block settles. The SDK waits for both the terminal result and [DONE]. Check success and status: receiving chunks or opening the HTTP connection does not mean the run completed.

**How does the SDK handle rate limiting?**

The SDK provides built-in rate limiting support through the executeWithRetry() method. It uses exponential backoff (1s, 2s, 4s, 8s...) with 25% jitter to avoid thundering herd problems. If the API returns a retry-after header, that value is used instead. You can configure maxRetries, initialDelay, maxDelay, and backoffMultiplier. The execute endpoint does not send rate limit headers, so use getUsageLimits() rather than getRateLimitInfo() to check your current rate limit status.

**Is it safe to use the SDK in browser-side code?**

The SDK is built for Node.js. It depends on node-fetch and Buffer, so it does not run in the browser. Keep it on your backend behind your own authenticated endpoint. That also keeps your API key out of client-side code. If a workflow must be callable without credentials, use Public access in the Deploy modal instead of shipping a key.

**How do I send files to a workflow through the SDK?**

File objects are automatically detected and converted to base64 format. Include them in the input object under the field name that matches your workflow's API trigger input format. Detection uses the global File class, which Node.js provides from version 20. Receive browser uploads on your backend and build File objects there. You can also provide files as URL references with type, data, name, and mime fields.
