# Type SDK Reference (@type-dot-com/sdk)

> Install the official TypeScript SDK for Type.com, learn its entry points and exports, and see which SDK version your automation code runs with.

Canonical page: https://docs.type.com/automations/reference/sdk/

`@type-dot-com/sdk` is the official TypeScript SDK for Type. Use it to write code automations, custom webhook adapters, and scripts that call the Type API.

## Install

**bun**

```sh
bun add @type-dot-com/sdk zod@4 neverthrow@8
```

**npm**

```sh
npm install @type-dot-com/sdk zod@4 neverthrow@8
```

The SDK runs in Bun. It also includes ESM JavaScript and type declarations for Node 22 or later. Install `zod` and `neverthrow` directly, because automation code imports them.

## Which SDK version runs your code

> **Caution:** Your automation does not run with the SDK version that you install. Type runs all automation code with the SDK that is part of the current Type server release. The version on your computer is for types and editor help only.

- Type typechecks your code against its own SDK when you deploy. A deploy can fail even if your local typecheck passes.
- The npm release can be older than the SDK in Type. Use `0.5.0` or later for the API on these pages. If an import is missing locally, deploy to check it.
- Type records the automation API version for each saved revision. If a later Type release changes the API, Type.com marks older automations as `upgrade_available` or `unsupported`. See [Create and Manage Automations](https://docs.type.com/automations/deploy/index.md#upgrades).

## Allowed imports in automation code

Automation code runs in a QuickJS VM, not in Node or Bun. It can import only these modules:

| Module | Use it for |
| --- | --- |
| `@type-dot-com/sdk` | `TypeApiError` and shared types. |
| `@type-dot-com/sdk/automations` | The graph functions, event contracts, and helpers. |
| `@type-dot-com/sdk/webhooks` | Webhook adapter types and helpers. Use it in adapter files. |
| `zod` | Schemas. |
| `neverthrow` | `Result`, `ResultAsync`, `ok`, and `err`. |
| Relative files, for example `./format.ts` | Your own modules in the same project. |

Any other import fails the deploy with "QuickJS cannot import ...". These are not available: `fetch`, Node APIs, Bun APIs, the file system, a shell, other npm packages, and compiler macros. Use [`ctx.tools`, `ctx.read`, and `ctx.write`](https://docs.type.com/automations/reference/context/index.md) for network access. Use [sandbox commands](https://docs.type.com/automations/sandbox/index.md) for shell work. `process.env` holds only [environment variables](https://docs.type.com/automations/reference/context/index.md#environment-variables) from the Space.

## Entry points

| Import path | Contents |
| --- | --- |
| `@type-dot-com/sdk` | The `Type` API client, `TypeApiError`, `defineAutomation` and `defineTask` for skill scripts, `z`, and shared types. It also re-exports the graph functions. |
| `@type-dot-com/sdk/automations` | Everything for code automations. See [below](#type-dot-comsdkautomations). |
| `@type-dot-com/sdk/webhooks` | `IntegrationWebhook`, `webhookEvent()`, and adapter context types. See [Webhook Adapter API](https://docs.type.com/automations/reference/webhook-adapters/index.md). |
| `@type-dot-com/sdk/rpc` | `createTypeRpcClient()`, the client that Type CLI uses. |
| `@type-dot-com/sdk/contracts/*` | Zod wire schemas, for example `contracts/api` and `contracts/automation-matchers`. |
| `@type-dot-com/sdk/apps`, `/apps/react`, `/apps/templates` | The SDK for [Type Apps](https://docs.type.com/library/apps/index.md). React and Convex are optional peer dependencies. |

## `@type-dot-com/sdk/automations`

### Graph functions

An automation default-exports the result of `automation()`. The [Deployment API](https://docs.type.com/automations/reference/deployment/index.md) has the full signatures and rules.

| Export | Use it to |
| --- | --- |
| [`automation({ output, deployment, stages })`](https://docs.type.com/automations/reference/deployment/index.md#automation) | Define the automation: its result schema, its triggers, and its stages. |
| [`code({ input, transitions?, run })`](https://docs.type.com/automations/reference/deployment/index.md#code) | Declare a code stage. |
| [`agent({ input, output, instructions, onResult?, tools?, model? })`](https://docs.type.com/automations/reference/deployment/index.md#agent) | Declare an agent stage. |
| [`agentResult(stage)`](https://docs.type.com/automations/reference/deployment/index.md#agentresult) | Make the input schema of the code stage that gets an agent stage's result. |
| [`next(stage, input)`](https://docs.type.com/automations/reference/deployment/index.md#stage-decisions) | Return from a code stage to run another stage. |
| [`complete(output?)`](https://docs.type.com/automations/reference/deployment/index.md#stage-decisions) | Return from a code stage to finish the run. |
| [`blocked(reason, output?)`](https://docs.type.com/automations/reference/deployment/index.md#stage-decisions) | Return from a code stage to stop the run because it needs attention. |

### Event contracts

Each schema checks one kind of event. Use the same schema as the subscription's `schema` and the entry stage's `input`. See the [Events reference](https://docs.type.com/automations/reference/events/index.md).

| Schema | Type | Event |
| --- | --- | --- |
| `recurringEventSchema` | `RecurringEvent` | A tick of a recurring source: `{ scheduledAt }`. |
| `slackMessageEventSchema` | `SlackMessageEvent` | A Slack `message` event. |
| `slackAppMentionEventSchema` | `SlackAppMentionEvent` | A Slack `app_mention` event. |
| `slackReactionAddedEventSchema` | `SlackReactionAddedEvent` | A Slack `reaction_added` event. |
| `slackReactionRemovedEventSchema` | `SlackReactionRemovedEvent` | A Slack `reaction_removed` event. |
| — | `IntegrationEvent<Data>` | The envelope of every integration and event source event. |

### Helpers

```ts
function replyInSlackThread(
  ctx: { write: Pick<AutomationWriteApi, "call"> },
  event: SlackMessageEvent | SlackAppMentionEvent,
  options: { connectionId: string; text: string; effectKey?: string },
): ResultAsync<{ channelId: string; threadTs: string; ts: string }, TypeApiError>;
```

`replyInSlackThread` replies in the Slack thread of the message or mention that started the run. It posts under the message, or in the thread that the message is already in.

- It calls `ctx.write.call` with the `slack_post_message` tool of the connection `connectionId`.
- The default effect key is `slack-reply:<channel>:<ts>`.
- It fails if the event has no timestamp, if the tool returns an error, or if Slack does not confirm that the reply is in the same channel and thread.
- Don't use it to repost the last agent stage's text answer. Type already posts it in the triggering thread. See [Reply with an agent](https://docs.type.com/automations/slack/index.md#reply-with-an-agent).

In a fixture, add this response to `toolResponses`. The request has no effect key.

```json
{
  "request": {
    "service": "slack",
    "name": "slack_post_message",
    "organizationIntegrationId": "orgint_example",
    "arguments": { "channel_id": "C0123456789", "thread_ts": "1712345678.000100", "text": "On it." }
  },
  "response": {
    "content": [],
    "structuredContent": {
      "status": "sent",
      "channelId": "C0123456789",
      "ts": "1712345679.000200",
      "threadTs": "1712345678.000100"
    }
  }
}
```

For `reaction_added`, the helper first uses `ctx.read.call` to find the reacted
message's parent thread. The context must provide both `read.call` and
`write.call`. If the read fails, it does not post. A reaction fixture also needs
this read request, with a `structuredContent` response containing the matching
`channelId` and `messages`. For a reply, `messages` starts with its parent
(`ts`, `threadTs`). For any other message it is empty:

```json
{
  "service": "slack",
  "name": "slack_get_thread_replies",
  "organizationIntegrationId": "orgint_...",
  "arguments": {
    "channel_id": "C0123456789",
    "thread_ts": "1712345678.000100",
    "limit": 1
  }
}
```

### Types

| Type | Meaning |
| --- | --- |
| `AutomationDefinition` | The value that `automation()` returns. |
| `AutomationDefinitionDeployment` | The type of the `deployment` field of `automation()`. There is no separate deployment export. |
| `DeploymentSubscription` | One entry in `deployment.subscriptions`, without `entry`. |
| `AutomationStage`, `AutomationCodeStage`, `AutomationAgentStage`, `AutomationAskStage` | The values that `code()`, `agent()`, and `ask()` return. |
| `AutomationStageDecision` | The value that `next()`, `complete()`, or `blocked()` returns. |
| `AutomationStageReturn` | What a code stage's `run` can return: a decision, a `Promise`, a `Result`, or a `ResultAsync` of one. |
| `AutomationCodeContext` | The `ctx` of a code stage. See the [Context reference](https://docs.type.com/automations/reference/context/index.md). |
| `AutomationExecutionIdentity` | The fields of `ctx.identity`. |
| `AutomationCheckpoint` | `{ value, version }`, the value of `ctx.checkpoint`. |
| `AutomationReadApi`, `AutomationWriteApi` | `ctx.read` and `ctx.write`. |
| `AutomationMutationOptions` | `{ effectKey, signal?, timeoutMs? }` for writes. |
| `Action`, `ActionLog`, `AutomationActions` | `ctx.action` and `ctx.mutativeAction`. |
| `AutomationJevRequest`, `AutomationJevResult` | AI questions in a matcher, and their answers in `ctx.jev`. |
| `AutomationMatcher`, `AutomationMatcherEvaluation` | The `match` field, and its `evaluation` form. |
| `AutomationDebounce` | The `debounce` field. |
| `AutomationExpiration` | The `expiration` field. |
| `IntegrationEventSource`, `EventSource`, `RecurringSource` | The three kinds of `source`. `AutomationEventSource` is an integration source or an event source. |

### Schemas

These Zod schemas validate the same shapes as the server. Use them for your own checks.

`automationDebounceSchema`, `automationExpirationSchema`, `automationMatcherSchema`, `automationMatcherEvaluationSchema`, `automationJevRequestSchema`, `automationJevResultSchema`, `integrationEventSourceSchema`, `eventSourceSchema`, `automationEventSourceSchema`, `recurringSourceSchema`, `steppedScheduleSchema`, `automationStageNameSchema`, `subscriptionDefinitionSchema`, `automationManifestSchema`.

`subscriptionDefinitionSchema` checks the saved settings of a subscription: `title`, `description`, `source`, `match`, and `debounce`. It does not include `entry` or `schema`.

### Run a stage in a local test

Type.com runs your stages with these functions. You can also call them in a Bun test on your computer:

| Export | Meaning |
| --- | --- |
| `extractAutomationDefinition(value)` | Reads the graph and trigger settings from an `automation()` value without running stage code. Returns `Result<{ definition, webhooks }, Error>`. `definition` is the saved manifest. |
| `runAutomationDefinition(value, definition, invocation, ctx, checkpoint)` | Runs exactly one stage and resolves to `Result<receipt, TypeApiError>`. `invocation` is `{ subscriptionId, payload }` for an entry stage, or `{ stage, input }` for any stage. `ctx` is an `AutomationWriteContext`. `checkpoint` is an `AutomationCheckpoint` or `null`. |
| `isAutomationDefinition(value)` | `true` if `value` is the result of `automation()`. |

The receipt has the `stage`, its `transition` (`next`, `complete`, or `blocked`) or agent `task`, and the `output`, `nextCheckpoint`, and `summary` that the stage saved. To check a later stage, such as the `onResult` stage of an agent, use a [fixture with `stage`](https://docs.type.com/automations/testing/index.md#what-a-fixture-runs) or call `runAutomationDefinition`. This example tests the `record` stage of the [graph example](https://docs.type.com/automations/reference/deployment/index.md#an-example-graph):

```ts title="tests/record.test.ts"

import {
  type AutomationWriteContext,
  extractAutomationDefinition,
  runAutomationDefinition,
} from "@type-dot-com/sdk/automations";

// Clients that never reach Type. A call fails with "No test response".
const none = () => errAsync(new TypeApiError("No test response", "configuration"));
const type = new Type({ serverUrl: "https://unused.invalid", agentId: "agent_test", accessToken: "unused" });
const ctx: AutomationWriteContext = {
  identity: {
    organizationId: "org_test",
    automationId: "atask_test",
    revisionId: "rev_test",
    runId: "run_test",
    subscriptionId: "requests",
    eventId: "event_test",
    purpose: "test",
    phase: "execute",
  },
  read: { data: type.data, search: type.search, call: none, request: none },
  write: { call: none, request: none, sendMessage: none },
  tools: type.tools,
  signal: new AbortController().signal,
  action: none,
  mutativeAction: none,
  destructiveAction: none,
};

test("record completes with the agent result", async () => {
  const manifest = extractAutomationDefinition(definition)._unsafeUnwrap().definition;
  const result = { category: "bug", summary: "Login fails after a password reset." };
  const receipt = await runAutomationDefinition(
    definition,
    manifest,
    {
      stage: "record",
      input: { taskInput: { text: "Login fails" }, result, receipt: { taskId: "task_test", attempt: 1 } },
    },
    ctx,
    null,
  );
  expect(receipt._unsafeUnwrap()).toMatchObject({ transition: { kind: "complete" }, output: result });
});
```

This test runs in Bun, not in Type's QuickJS VM, and its clients do not reach Type. It checks your stage logic and the stage contracts. It does not replace the deploy typecheck, fixtures, or a live run.

### Saved definition types

`AutomationManifest`, `SubscriptionDefinition`, `AutomationOrchestration`, `AutomationTransition` (also `AutomationStageTransition`), `AutomationStageDefinition`, `ExtractedAutomationDeployment`, `RegisteredAutomationDefinition`, `AutomationReadContext`, `AutomationWriteContext`, and the schemas `automationOrchestrationSchema`, `automationOrchestrationStageSchema`, `automationTransitionSchema` (also `automationStageTransitionSchema`), and `automationStageDefinitionSchema` describe the definition that Type saves. `AutomationDeployment` is an older type for trigger settings. In `automation()`, use `AutomationDefinitionDeployment`. Automation code does not need these.

### Removed APIs

Type rejects class-based automations, a separate `export const deployment`, `ctx.setOutput`, and `failurePolicy: "pause_and_investigate"`. To move saved class code, rewrite it as `automation({ deployment, output, stages })` and test it before you enable it. See [Deployment API](https://docs.type.com/automations/reference/deployment/index.md#automation) for the errors.

## `TypeApiError`

All SDK errors are `TypeApiError` objects.

```ts
class TypeApiError extends Error {
  readonly code: TypeErrorCode;
  readonly status?: number; // HTTP status, if any
  readonly details?: unknown; // structured API details, if any
  get isVersionConflict(): boolean; // true for HTTP 409 version_conflict
}
```

| `code` | Meaning |
| --- | --- |
| `configuration` | The client has a missing or wrong setting. |
| `authentication` | Type.com did not accept the credentials. |
| `network` | The request did not get a response. A write can still be complete. |
| `timeout` | The request took too long. A write can still be complete. |
| `aborted` | The signal stopped the request. |
| `invalid_response` | The response did not match the expected shape or your schema. |
| `http_error` | Type returned an HTTP error. Read `status` and `details`. |
| `invalid_input` | The input was not valid. |

Create your own errors with the same class. A code stage that returns a `Result` or `ResultAsync` must use `TypeApiError` for its error type:

```ts
return err(new TypeApiError("The order has no ID", "invalid_response"));
```

See [Errors](https://docs.type.com/automations/reference/errors/index.md) for messages that the deploy and the runtime return.

## The `Type` API client

`Type` is a client for the Type agent HTTP API. Use it in scripts and skill code, not in automation code. In automation code, use `ctx`, which gives the same operations with automation access checks.

```ts

const type = Type.fromEnvironment(process.env);
const result = await type.search.workspace("quarterly plan");
if (result.isErr()) console.error(result.error.code, result.error.message);
```

| Resource | Operations |
| --- | --- |
| `data` | `read`, `record`, `list`, `delete`, `withSchema` |
| `tools` | `services`, `find`, `call`, `callWithSchema` |
| `integrations` | `search`, `connect`, `request`, `requestWithSchema`, `webhooks` |
| `skills` | `list`, `create`, `update`, `delete`, `files`, `readFile`, `addFile`, `updateFile`, `deleteFile`, `versions` |
| `tasks` | `list`, `get`, `create`, `update`, `testCode`, `delete` |
| `spaces` | `list`, `messages` |
| `threads` | `list`, `messages`, `batch` |
| `search` | `workspace`, `messages` |
| `messages` | `send` |

- Each method accepts a last argument `{ signal, timeoutMs }`. The default timeout is 60 seconds.
- The client does not retry. After a timeout or a network error, a write can still be complete.
- `Type.fromEnvironment()` reads `TYPE_SERVER_URL`, `TYPE_ACCESS_TOKEN`, `TYPE_AGENT_ID`, `TYPE_CHANNEL_ID`, and `TYPE_AUTOMATION_ID`.
- `tasks.delete` archives the task. It does not delete it permanently.

## Skill scripts are not automations

`defineAutomation` and `defineTask` from `@type-dot-com/sdk` are for skill scripts. They are not code automations. A skill script runs when an agent or a person runs the skill. A code automation runs on a schedule or an event. To make a code automation, default-export `automation({ deployment, output, stages })`.

The `AutomationContext` type from `@type-dot-com/sdk` is the context of a skill script. The `ctx` of a code stage is `AutomationCodeContext` from `@type-dot-com/sdk/automations`.
