# ctx Context Reference for Code Stages

> Every property and method of the ctx object that Type.com gives to a code stage. Each stage's run is called with ctx and the validated stage input.

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

Type.com 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](https://docs.type.com/automations/reference/events/index.md). This page lists every property and method of `ctx`.

```ts title="src/main.ts"

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

- 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()`](#ctxsetsummary), or [action logs](#ctxaction-and-ctxmutativeaction) to see values in run history.

See [Limits](https://docs.type.com/automations/reference/limits/index.md) for all limits.

## Summary

| Member | Type | Use it to |
| --- | --- | --- |
| [`ctx.identity`](#ctxidentity) | `AutomationExecutionIdentity` | Read the IDs of this automation, run, and event. |
| [`ctx.checkpoint`](#ctxcheckpoint) | `AutomationCheckpoint \| null` | Read the state that the subscription saved last. |
| [`ctx.saveCheckpoint()`](#ctxsavecheckpoint) | `(value) => Result<void, TypeApiError>` | Save state for later stages and runs. |
| [`ctx.setSummary()`](#ctxsetsummary) | `(text) => Result<void, TypeApiError>` | Show one sentence about what the run did. Needs reports to be on. |
| [`ctx.setVisualization()`](#ctxsetvisualization) | `(value) => Result<void, TypeApiError>` | Save a report of the results. Needs reports to be on. |
| [`ctx.tools`](#ctxtools) | Tool client | Find and call integration tools and sandbox commands. |
| [`ctx.read`](#ctxread) | Read client | Read tool data, API data, saved data, and search results. |
| [`ctx.write`](#ctxwrite) | Write client | Change data in a connected app, or post in a Space. |
| [`ctx.action()`](#ctxaction-and-ctxmutativeaction) | `Action` | Record an important step in run history. |
| [`ctx.mutativeAction()`](#ctxaction-and-ctxmutativeaction) | `Action` | Record a step that changes data. |
| [`ctx.jev`](#ctxjev) | `AutomationJevResult \| null` | Read answers to AI questions about the event. |
| [`ctx.signal`](#ctxsignal) | `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](https://docs.type.com/automations/agent-handoff/index.md). See [Stage decisions](https://docs.type.com/automations/reference/deployment/index.md#stage-decisions).

## `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"`. |

> **Caution:** Do not change what your code does based on `purpose`. Tests must use the same code path as live runs. A fixture that gives recorded responses runs with `purpose: "live"`. See [Test with Fixtures](https://docs.type.com/automations/testing/index.md).

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`

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

```ts
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()`

```ts
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](https://docs.type.com/automations/state/index.md).

## `ctx.setSummary()`

```ts
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.com 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()`

```ts
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 }`.

> **Note:** `setSummary` and `setVisualization` are available in every code stage.

- 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.com 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`

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:

```ts
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:

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

> **Caution:** A tool can fail and still return `ok`. Check both `result.isErr()` and `result.value.isError`.

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](https://docs.type.com/automations/sandbox/index.md).

## `ctx.read`

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

### `ctx.read.call()`

```ts
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`.

### `ctx.read.request()`

```ts
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](https://docs.type.com/connectors-and-skills/custom-apis/index.md). Type adds the credentials. Your code never sees them. It parses the response body with your schema and returns the parsed value.

```ts
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`

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](#ctxsavecheckpoint) for state between runs.

### `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`

Changes data. Each method needs an `effectKey`.

```ts
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()`](#ctxreadcall) and [`ctx.read.request()`](#ctxreadrequest).

> **Caution:** An effect key does not stop a write from running two times. It identifies the change in records. If a write has an unknown result, read the destination before you try again. See [Write Safely](https://docs.type.com/automations/safe-writes/index.md).

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

## `ctx.action()` and `ctx.mutativeAction()`

```ts
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.com 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.

```ts
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`

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

```ts
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](https://docs.type.com/automations/ai-filters/index.md).

## `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

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`:

```ts
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](https://docs.type.com/automations/testing/index.md#test-environment-variables).
- Keep secrets out of source, output, checkpoints, action logs, and messages. Code that can read a secret can also reveal it.
