Skip to content
Changelog

Report a bug

Context Reference

Type calls a code stage’s run with { ctx, input }. input is the validated stage input. For the events that entry stages get, see the Events reference. This page lists every property and method of ctx.

src/main.ts
import { automation, code, complete, recurringEventSchema } from "@type-dot-com/sdk/automations";
import { err } from "neverthrow";
import { z } from "zod";
const counter = z.object({ runs: z.number().int().nonnegative() });
export default automation({
deployment: {
subscriptions: {
hourly: {
entry: "count",
title: "Hourly count",
description: "Count the scheduled runs",
source: { kind: "recurring", schedule: { kind: "interval", everySeconds: 3600 } },
},
},
},
output: z.object({ runs: z.number() }),
stages: {
count: code({
input: recurringEventSchema,
transitions: [],
run({ ctx }) {
// Read the last saved count. The first run has no checkpoint.
const saved = counter.safeParse(ctx.checkpoint?.value);
const runs = (saved.success ? saved.data.runs : 0) + 1;
// Type saves the checkpoint when this stage succeeds.
const staged = ctx.saveCheckpoint({ runs });
if (staged.isErr()) {
return err(staged.error);
}
return complete({ runs });
},
}),
},
});

The type of ctx is AutomationCodeContext. Import it from @type-dot-com/sdk/automations.

  • Methods that call Type return ResultAsync<T, TypeApiError> from neverthrow. They do not throw. Check isErr() before you use the value.
  • Each code stage can send at most 128 requests to Type. This count includes tool calls, reads, writes, messages, data reads, and searches. Action logs have their own budget.
  • At most 8 requests can be in progress at the same time. Await calls, or limit Promise.all to small groups.
  • Each response to a request can be at most 2 MiB. Ask for smaller pages if a response is larger.
  • Each request body can be at most 1 MiB.
  • Type does not retry a request automatically. If a write times out, the write can still be complete. Read the destination before you try again.
  • console.log and the other console methods do nothing. Use complete(), ctx.setSummary(), or action logs to see values in run history.

See Limits for all limits.

MemberTypeUse it to
ctx.identityAutomationExecutionIdentityRead the IDs of this automation, run, and event.
ctx.checkpointAutomationCheckpoint | nullRead the state that the subscription saved last.
ctx.saveCheckpoint()(value) => Result<void, TypeApiError>Save state for later stages and runs.
ctx.setSummary()(text) => Result<void, TypeApiError>Show one sentence about what the run did. Needs reports to be on.
ctx.setVisualization()(value) => Result<void, TypeApiError>Save a report of the results. Needs reports to be on.
ctx.toolsTool clientFind and call integration tools and sandbox commands.
ctx.readRead clientRead tool data, API data, saved data, and search results.
ctx.writeWrite clientChange data in a connected app, or post in a Space.
ctx.action()ActionRecord an important step in run history.
ctx.mutativeAction()ActionRecord a step that changes data.
ctx.jevAutomationJevResult | nullRead answers to AI questions about the event.
ctx.signalAbortSignalStop work when the stage deadline comes.

ctx has no setOutput, agent, or handoff methods. A code stage returns its result with complete() or blocked(), and gives work to the managed agent with next() to an agent stage. See Stage decisions.

Read-only IDs for the current stage run.

FieldTypeMeaning
organizationIdstringThe workspace that owns the automation.
automationIdstringThe automation.
revisionIdstringThe saved code revision that runs now.
runIdstringThis run of the stage. Each stage of a graph has its own run ID.
subscriptionIdstringThe subscription key that started the run.
eventIdstringThe event that started the run.
purpose"live" | "test" | "repair"Why Type started the run.
phase"execute"Always "execute".

These IDs are information only. Type does not use them to give access. Type checks access with a short-lived token for each stage run.

The state that this subscription saved last. The value is null before the first save.

interface AutomationCheckpoint {
readonly value: JsonValue;
readonly version: string;
}
  • Each subscription has its own checkpoint. Two subscriptions in the same automation do not share it. All stages of a run read and save the checkpoint of the subscription that started the run.
  • Each stage reads the newest saved value when it starts. A later stage sees what an earlier stage of the same run saved. While an agent stage works, other runs of the subscription can save first.
  • The checkpoint stays when you deploy new code, if the subscription key stays the same.
  • If you rename a subscription key, the new key starts with no checkpoint.
saveCheckpoint(value: JsonValue): Result<void, TypeApiError>

Saves value as the next checkpoint for this subscription.

  • The value must be JSON.
  • Type saves the checkpoint only when the stage succeeds, together with its decision. If the stage fails, the old checkpoint stays. A later failed stage does not undo a checkpoint that an earlier stage saved.
  • If you call it more than one time in a stage, the last value is saved.
  • The call is synchronous. It returns a Result, not a ResultAsync.
  • If the value is not JSON, the stage fails, even if your code ignores the error.

See Keep State Between Runs.

setSummary(value: string): Result<void, TypeApiError>

Sets one plain sentence that says what this run did. An example is “Two tickets arrived; one is about billing.” Type shows it as the headline of the run in run history, and under the report.

  • The text must be 1 to 300 characters after Type trims spaces. Otherwise the stage fails, even if your code ignores the error.
  • If more than one stage sets a summary, run history shows the last one.
  • Describe the change, not the steps of the code.
  • Do not set a summary for a run that did nothing.
setVisualization(value: JsonValue): Result<void, TypeApiError>

Saves a report for the automation, for example a chart, a table, or metric cards. The report shows on the automation page. The value is a json-render spec: { root, elements, state }.

  • Set a report only when it helps people understand the results. Do not save a placeholder.
  • null, or no call, keeps the current report. complete() never makes a report.
  • The report shares the 2 MiB limit of the stage result.
  • If the report is not valid, Type keeps the earlier report and records a warning. The run still succeeds.
  • Fixture runs do not change the saved report.
  • Saving a report does not send it anywhere.
  • Limits: charts have at most 500 points and 12 series. A report has at most 200 elements after Type expands repeats.

The integration tool client. Type checks the automation’s access on every call.

MethodReturnsUse it to
services(options?){ services }List the services that the automation can use.
find({ service, organizationIntegrationId?, includeRelatedConnections? }, options?)Tool listGet tool names and input schemas for a service.
call(call, options?)ToolResultCall a tool and get the raw result.
callWithSchema(call, schema, options?)ToolResult with parsed structuredContentCall a tool and parse its structured result.

A call object has these fields:

interface ToolCall {
service: string; // for example "slack" or "managed-sandbox"
name: string; // the tool name from find()
arguments?: Record<string, JsonValue>;
organizationIntegrationId?: string; // the connection ID, "orgint_..."
rawSlug?: string;
}

A ToolResult has this shape:

interface ToolResult {
content: Array<{ type: string; text?: string }>;
structuredContent?: unknown;
isError?: boolean;
}

Sandbox commands use ctx.tools.call with service: "managed-sandbox". Pass an automationEffectKey option for a command that can change something, so that run history records the call as a write. See Run Commands in the Sandbox.

Reads data. Use ctx.read only for operations that do not change data.

call<S extends z.ZodType>(call: ToolCall, schema: S, options?: RequestOptions): ResultAsync<z.output<S>, TypeApiError>

Calls a tool, then parses its structuredContent with your Zod schema. It returns the parsed value.

  • It fails if the tool returns isError: true.
  • It fails if structuredContent does not match the schema.
  • JSON text in content[].text is not structuredContent. For tools that return only text, use ctx.tools.call.
request<S extends z.ZodType>(request: IntegrationRequest, schema: S, options?: RequestOptions): ResultAsync<z.output<S>, TypeApiError>

Sends an HTTP request to a Custom API connection. Type adds the credentials. Your code never sees them. It parses the response body with your schema and returns the parsed value.

interface IntegrationRequest {
organizationIntegrationId: string;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
path: string; // relative to the connection's base URL
query?: Record<string, string | number | boolean>;
headers?: Record<string, string>;
body?: JsonValue;
}

It fails if the response is not successful, if Type truncated the response, or if the body does not match the schema.

Reads saved data for this automation.

MethodReturns
read(key, scope?, options?){ found: true, key, value, version, updatedAt } or { found: false, key, version: null }
list({ after?, limit? }, options?){ items: [{ key, version, updatedAt }], nextCursor }

Automation code cannot write saved data. Use checkpoints for state between runs.

Searches the Type workspace.

MethodUse it to
workspace(query, options?)Search people, Spaces, docs, apps, files, threads, and messages.
messages({ query?, channelIds?, limit?, from?, to? }, options?)Search messages, with optional channel and date filters.

Changes data. Each method needs an effectKey.

interface AutomationMutationOptions {
effectKey: string; // stable for the same logical change, across retries and runs
signal?: AbortSignal;
timeoutMs?: number;
}

An effect key has 1 to 200 characters. It starts with a letter or a digit, and has only letters, digits, and ., _, :, /, -. Other keys fail with “automationEffectKey is invalid”.

MethodReturnsUse it to
call(call, schema, { effectKey })The parsed structuredContentCall a tool that changes data.
request(request, schema, { effectKey })The parsed response bodySend an HTTP request that changes data to a Custom API connection.
sendMessage({ channelId, content, parentMessageId? }, { effectKey }){ success: true, messageId }Post a message in the automation’s Space. Set channelId to the Space ID (ch_...). Set parentMessageId to reply in a thread.

call and request fail in the same cases as ctx.read.call() and ctx.read.request().

Only live runs make real writes. In a fixture, Type gives your code the responses from the fixture.

type Action = <T>(
run: () => Result<T, TypeApiError> | ResultAsync<T, TypeApiError>,
before: { id: string; message: string; data?: JsonValue },
after: (result: T) => { message: string; data?: JsonValue },
) => ResultAsync<T, TypeApiError>;

Records an important step in run history. Type saves the before log, runs run, then saves the after log.

  • Use mutativeAction for steps that change data. Use action for other important steps.
  • id must be unique in the stage run, and 1 to 200 characters. It must not start or end with a space.
  • message must be 1 to 2,000 characters. Each log must fit in 8 KiB.
  • A stage run can record at most 100 actions.
  • If run fails, Type records a failed step and returns the error.
  • If Type cannot save the after log, the call fails with “Do not repeat the action”. The step itself can be complete.

Action logs do not retry, and they do not undo earlier changes. ctx.destructiveAction is an old name for ctx.mutativeAction. Do not use it in new code.

const created = await ctx.mutativeAction(
() => ctx.write.call(createIssue, issueSchema, { effectKey: `issue:${input.id}` }),
{ id: "create-issue", message: `Create an issue for ${input.id}` },
(issue) => ({ message: `Created issue ${issue.id}`, data: { id: issue.id } }),
);
if (created.isErr()) return err(created.error);

Answers to the AI questions that the subscription’s matcher asked about the event. The value is null when the matcher asks no questions. Only the entry stage gets the answers. In later stages, ctx.jev is null.

interface AutomationJevResult {
model: string;
answers: Record<string, JevAnswer>; // keyed by your question IDs
}

Each answer has the type of its question: noul (a probability from 0 to 1), choice, or score. See Filter Events with AI Questions.

An AbortSignal that aborts when the deadline of the stage run comes. Pass it to long operations as the signal option.

When environment variables are on for your organization, a code stage can read the variables saved for the automation’s Space with process.env.NAME:

const region = process.env.DEPLOY_REGION;
const token = process.env.SERVICE_TOKEN;
  • process.env has only these saved values. Type’s own access tokens and the server’s environment are not in it.
  • Type reads the values once for each stage run. A later stage reads the current values again.
  • Removing or changing a value does not change saved code.
  • Source validation gets no saved values. Fixtures get only the environment map of the fixture. See Test environment variables.
  • Keep secrets out of source, output, checkpoints, action logs, and messages. Code that can read a secret can also reveal it.