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.
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.
Rules for all methods
Section titled “Rules for all methods”- Methods that call Type return
ResultAsync<T, TypeApiError>fromneverthrow. They do not throw. CheckisErr()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.allto 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.logand the otherconsolemethods do nothing. Usecomplete(),ctx.setSummary(), or action logs to see values in run history.
See Limits for all limits.
Summary
Section titled “Summary”| Member | Type | Use it to |
|---|---|---|
ctx.identity | AutomationExecutionIdentity | Read the IDs of this automation, run, and event. |
ctx.checkpoint | AutomationCheckpoint | null | Read 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.tools | Tool client | Find and call integration tools and sandbox commands. |
ctx.read | Read client | Read tool data, API data, saved data, and search results. |
ctx.write | Write client | Change data in a connected app, or post in a Space. |
ctx.action() | Action | Record an important step in run history. |
ctx.mutativeAction() | Action | Record a step that changes data. |
ctx.jev | AutomationJevResult | null | Read answers to AI questions about the event. |
ctx.signal | AbortSignal | Stop 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.
ctx.identity
Section titled “ctx.identity”Read-only IDs for the current stage run.
| Field | Type | Meaning |
|---|---|---|
organizationId | string | The workspace that owns the automation. |
automationId | string | The automation. |
revisionId | string | The saved code revision that runs now. |
runId | string | This run of the stage. Each stage of a graph has its own run ID. |
subscriptionId | string | The subscription key that started the run. |
eventId | string | The 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.
ctx.checkpoint
Section titled “ctx.checkpoint”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.
ctx.saveCheckpoint()
Section titled “ctx.saveCheckpoint()”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 aResultAsync. - If the value is not JSON, the stage fails, even if your code ignores the error.
ctx.setSummary()
Section titled “ctx.setSummary()”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.
ctx.setVisualization()
Section titled “ctx.setVisualization()”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.
ctx.tools
Section titled “ctx.tools”The integration tool client. Type checks the automation’s access on every call.
| Method | Returns | Use it to |
|---|---|---|
services(options?) | { services } | List the services that the automation can use. |
find({ service, organizationIntegrationId?, includeRelatedConnections? }, options?) | Tool list | Get tool names and input schemas for a service. |
call(call, options?) | ToolResult | Call a tool and get the raw result. |
callWithSchema(call, schema, options?) | ToolResult with parsed structuredContent | Call 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.
ctx.read
Section titled “ctx.read”Reads data. Use ctx.read only for operations that do not change data.
ctx.read.call()
Section titled “ctx.read.call()”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
structuredContentdoes not match the schema. - JSON text in
content[].textis notstructuredContent. For tools that return only text, usectx.tools.call.
ctx.read.request()
Section titled “ctx.read.request()”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.
ctx.read.data
Section titled “ctx.read.data”Reads saved data for this automation.
| Method | Returns |
|---|---|
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.
ctx.read.search
Section titled “ctx.read.search”Searches the Type workspace.
| Method | Use 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. |
ctx.write
Section titled “ctx.write”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”.
| Method | Returns | Use it to |
|---|---|---|
call(call, schema, { effectKey }) | The parsed structuredContent | Call a tool that changes data. |
request(request, schema, { effectKey }) | The parsed response body | Send 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.
ctx.action() and ctx.mutativeAction()
Section titled “ctx.action() and ctx.mutativeAction()”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
mutativeActionfor steps that change data. Useactionfor other important steps. idmust be unique in the stage run, and 1 to 200 characters. It must not start or end with a space.messagemust be 1 to 2,000 characters. Each log must fit in 8 KiB.- A stage run can record at most 100 actions.
- If
runfails, Type records a failed step and returns the error. - If Type cannot save the
afterlog, 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);ctx.jev
Section titled “ctx.jev”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.
ctx.signal
Section titled “ctx.signal”An AbortSignal that aborts when the deadline of the stage run comes. Pass it to long operations as the signal option.
Environment variables
Section titled “Environment variables”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.envhas 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
environmentmap 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.