Skip to content
Changelog

Report a bug

SDK Reference

@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.

Terminal window
bun add @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.

  • 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 marks older automations as upgrade_available or unsupported. See Create and Manage Automations.

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

ModuleUse it for
@type-dot-com/sdkTypeApiError and shared types.
@type-dot-com/sdk/automationsThe graph functions, event contracts, and helpers.
@type-dot-com/sdk/webhooksWebhook adapter types and helpers. Use it in adapter files.
zodSchemas.
neverthrowResult, ResultAsync, ok, and err.
Relative files, for example ./format.tsYour 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 for network access. Use sandbox commands for shell work. process.env holds only environment variables from the Space.

Import pathContents
@type-dot-com/sdkThe 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/automationsEverything for code automations. See below.
@type-dot-com/sdk/webhooksIntegrationWebhook, webhookEvent(), and adapter context types. See Webhook Adapter API.
@type-dot-com/sdk/rpccreateTypeRpcClient(), 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/templatesThe SDK for Type Apps. React and Convex are optional peer dependencies.

An automation default-exports the result of automation(). The Deployment API has the full signatures and rules.

ExportUse it to
automation({ output, deployment, stages })Define the automation: its result schema, its triggers, and its stages.
code({ input, transitions?, run })Declare a code stage.
agent({ input, output, instructions, onResult?, tools?, model? })Declare an agent stage.
agentResult(stage)Make the input schema of the code stage that gets an agent stage’s result.
next(stage, input)Return from a code stage to run another stage.
complete(output?)Return from a code stage to finish the run.
blocked(reason, output?)Return from a code stage to stop the run because it needs attention.

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.

SchemaTypeEvent
recurringEventSchemaRecurringEventA tick of a recurring source: { scheduledAt }.
slackMessageEventSchemaSlackMessageEventA Slack message event.
slackAppMentionEventSchemaSlackAppMentionEventA Slack app_mention event.
slackReactionAddedEventSchemaSlackReactionAddedEventA Slack reaction_added event.
slackReactionRemovedEventSchemaSlackReactionRemovedEventA Slack reaction_removed event.
—IntegrationEvent<Data>The envelope of every integration and event source event.
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.

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

{
"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:

{
"service": "slack",
"name": "slack_get_thread_replies",
"organizationIntegrationId": "orgint_...",
"arguments": {
"channel_id": "C0123456789",
"thread_ts": "1712345678.000100",
"limit": 1
}
}
TypeMeaning
AutomationDefinitionThe value that automation() returns.
AutomationDefinitionDeploymentThe type of the deployment field of automation(). There is no separate deployment export.
DeploymentSubscriptionOne entry in deployment.subscriptions, without entry.
AutomationStage, AutomationCodeStage, AutomationAgentStage, AutomationAskStageThe values that code(), agent(), and ask() return.
AutomationStageDecisionThe value that next(), complete(), or blocked() returns.
AutomationStageReturnWhat a code stage’s run can return: a decision, a Promise, a Result, or a ResultAsync of one.
AutomationCodeContextThe ctx of a code stage. See the Context reference.
AutomationExecutionIdentityThe fields of ctx.identity.
AutomationCheckpoint{ value, version }, the value of ctx.checkpoint.
AutomationReadApi, AutomationWriteApictx.read and ctx.write.
AutomationMutationOptions{ effectKey, signal?, timeoutMs? } for writes.
Action, ActionLog, AutomationActionsctx.action and ctx.mutativeAction.
AutomationJevRequest, AutomationJevResultAI questions in a matcher, and their answers in ctx.jev.
AutomationMatcher, AutomationMatcherEvaluationThe match field, and its evaluation form.
AutomationDebounceThe debounce field.
AutomationExpirationThe expiration field.
IntegrationEventSource, EventSource, RecurringSourceThe three kinds of source. AutomationEventSource is an integration source or an event source.

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.

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

ExportMeaning
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. A fixture runs only the entry stage, so use runAutomationDefinition to check a later stage, such as the onResult stage of an agent. This example tests the record stage of the graph example:

tests/record.test.ts
import { expect, test } from "bun:test";
import { Type, TypeApiError } from "@type-dot-com/sdk";
import {
type AutomationWriteContext,
extractAutomationDefinition,
runAutomationDefinition,
} from "@type-dot-com/sdk/automations";
import { errAsync } from "neverthrow";
import definition from "../src/main.ts";
// 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.

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.

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 for the errors.

All SDK errors are TypeApiError objects.

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
}
codeMeaning
configurationThe client has a missing or wrong setting.
authenticationType did not accept the credentials.
networkThe request did not get a response. A write can still be complete.
timeoutThe request took too long. A write can still be complete.
abortedThe signal stopped the request.
invalid_responseThe response did not match the expected shape or your schema.
http_errorType returned an HTTP error. Read status and details.
invalid_inputThe 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:

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

See Errors for messages that the deploy and the runtime return.

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.

import { Type } from "@type-dot-com/sdk";
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);
ResourceOperations
dataread, record, list, delete, withSchema
toolsservices, find, call, callWithSchema
integrationssearch, connect, request, requestWithSchema, webhooks
skillslist, create, update, delete, files, readFile, addFile, updateFile, deleteFile, versions
taskslist, get, create, update, testCode, delete
spaceslist, messages
threadslist, messages, batch
searchworkspace, messages
messagessend
  • 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.

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.