# Automation Core Concepts: Triggers, Stages, ctx

> The model behind every Type.com automation. Triggers start runs, stages do the work, ctx reaches the outside, and each run is checked and recorded.

Canonical page: https://docs.type.com/automations/how-it-works/

Every Type.com automation uses the same model: triggers start runs, stages do the work, `ctx` reaches the outside, and Type.com checks, records, and recovers each run. Each section links to the reference for the details. The snippets on this page are parts of a file. For complete files, see [Examples](https://docs.type.com/automations/examples/index.md).

## The automation

A code automation is one file, `src/main.ts`, with one default export:

```ts
export default automation({
  output,      // a Zod schema: the result of a finished run
  deployment,  // the triggers, called subscriptions
  stages,      // the steps of a run
});
```

An instruction automation has the same parts, made for you: its trigger is a subscription, and the managed agent follows your instructions in one agent stage.

## Triggers

A **subscription** connects a trigger to an **entry stage**, the first stage of a run. An automation can have several subscriptions, each with its own entry stage.

| `source.kind` | Starts a run when | Entry stage gets |
| --- | --- | --- |
| `recurring` | A schedule comes: cron, interval, or stepped | `{ scheduledAt }` |
| `integration` | A Slack, GitHub, or Linear event comes on a connection | The event: `{ type, id, resourceType, resourceId, data }` |
| `event_source` | A webhook URL, an email address, or an RSS feed gets an item | The same event envelope |

Before your code starts, Type.com can filter events on its server:

- **`resources`** keeps events from some resources, for example one Slack channel.
- **`match`** keeps events that match fields, for example merged pull requests into `main`. A matcher can also ask an [AI question](https://docs.type.com/automations/ai-filters/index.md).
- **`schema`** checks the event's shape. An event that does not match fails the run before your code.

An event that a filter skips starts no run. See [Schedules](https://docs.type.com/automations/scheduled-automations/index.md), [Slack](https://docs.type.com/automations/slack/index.md), [GitHub](https://docs.type.com/automations/github/index.md), [Linear](https://docs.type.com/automations/linear/index.md), [Webhooks](https://docs.type.com/automations/webhooks/index.md), and [Email and RSS](https://docs.type.com/automations/email-rss/index.md).

## Stages

A run moves through **stages**. There are three kinds.

**A code stage** runs your TypeScript. It declares the input that it accepts and the stages that it can go to, and it returns one **decision**:

```ts
checkMessage: code({
  input: slackMessageEventSchema,   // the data this stage accepts
  transitions: ["triage"],          // the stages it can go to
  run({ ctx, input }) {
    if (input.data.thread_ts) {
      return complete({ status: "skipped" });
    }
    return next("triage", { message: input });
  },
}),
```

| Decision | What happens |
| --- | --- |
| `next(stage, input)` | The named stage runs next with `input`. Type checks `input` against that stage's schema. |
| `complete(output)` | The run ends. `output` must match the automation's `output` schema. |
| `blocked(reason)` | The run ends and needs a person. This is not a failure: the automation stays on. |
| `err(error)` | The stage fails. See [Failures](#failures). |

**An agent stage** gives one step to the managed agent: Claude or Codex, with the Space's connections, skills, and memory. You give it instructions and two schemas. The agent works in a thread in the Space and returns a result that matches `output`. Omit `onResult` to finish the run with that result; the automation’s root `output` must also accept it. A terminal `z.string()` stage uses the agent’s final response. To continue in code, set `onResult` to a stage that accepts `{ taskInput, result, receipt }`:

```ts
triage: agent({
  input: triageInput,     // what the agent gets
  output: triageResult,   // what the agent must submit
  instructions: "Classify this request and write a reply.",
  onResult: "postReply",  // the code stage that gets the result
}),

postReply: code({
  input: agentResult({ input: triageInput, output: triageResult }),
  transitions: [],
  async run({ ctx, input }) {
    // input.taskInput, input.result, input.receipt
  },
}),
```

When a Slack event starts a run, a terminal agent stage’s final response is posted once in the triggering thread. Once a reply destination is known, agent stages automatically use the linked Type thread. Their commentary stays in Type unless they use `thread: "trigger"`, which also streams progress into Slack. A code stage can post a structured result with `replyInSlackThread`. See [Agent stages](https://docs.type.com/automations/agent-handoff/index.md).

**An ask stage** pauses for a person to answer questions, then continues at `onResult`. It can name the workspace members who may answer. **An approval stage** is an ask stage with one Approve or Deny question. It can name its approvers; otherwise any workspace member who can see the request may decide. A typed reply never approves. Questions from ask stages and agents appear in the triggering Slack thread when the run starts from Slack. Human input has no time limit. A task needs attention if its thread disappears, if the agent finishes without an accepted result, or if it makes no progress for 24 hours.

Type.com checks the graph when you deploy: each `next()` and `onResult` must name a declared stage, and its data must match that stage's input schema.

## `ctx`: how code reaches the outside

Each code stage runs in a new, isolated QuickJS VM. It has no `fetch`, no file system, and no shell. It reaches everything through `ctx`, and Type checks each call:

| You want to | Use |
| --- | --- |
| Read from a connected app, with a typed result | `ctx.read.call(tool, schema)` |
| Change data in a connected app | `ctx.write.call(tool, schema, { effectKey })` |
| Call a Custom API | `ctx.read.request(...)`, `ctx.write.request(..., { effectKey })` |
| Post in the Space | `ctx.write.sendMessage({ channelId, content }, { effectKey })` |
| Run a shell command in the sandbox | `ctx.tools.call({ service: "managed-sandbox", name: "exec_command", ... })` |
| Remember progress for the next run | `ctx.checkpoint`, `ctx.saveCheckpoint(value)` |

Every call returns a `Result`. Check it with `isErr()` before you use the value:

```ts
const sent = await ctx.write.sendMessage(
  { channelId: spaceId, content: "Deploy finished." },
  { effectKey: `deploy-note:${input.id}` },
);
if (sent.isErr()) {
  return err(sent.error);
}
```

See [Call connected apps](https://docs.type.com/automations/call-integrations/index.md), [Use the sandbox](https://docs.type.com/automations/sandbox/index.md), and the [Context reference](https://docs.type.com/automations/reference/context/index.md).

## State

Nothing in memory carries over from one stage to the next. Keep data in one of these places:

| To keep data | Use |
| --- | --- |
| From one stage to the next | The input of `next(stage, input)` |
| From one run to a later run | A checkpoint: `ctx.saveCheckpoint(value)`. One for each subscription. |
| For people to read | The output of `complete(output)`, in run history |

Type.com saves a stage's decision, its output, and its checkpoint together, and only when the stage succeeds. See [Keep state between runs](https://docs.type.com/automations/state/index.md).

## Writes

A write changes something outside the run: a message, an issue, a row. Every write needs an **effect key**, a stable name for that change, such as `` `report:${input.scheduledAt}` `` or `` `issue:${event.id}` ``.

An effect key records the write. It does not stop a second write. Make each write safe to repeat: use the provider's idempotency key, read before you write, or save progress in a checkpoint. See [Write safely](https://docs.type.com/automations/safe-writes/index.md).

## Access

A run acts as the person who created the automation, with the connections of its Space. Code gets a scoped token for each stage and never sees a provider credential. Access in a chat thread can be wider than access in an automation, so a call that works in a thread can fail in an automation.

## Tests

A **fixture** is a test case in `fixtures.json`. It gives one subscription a fixed event, and fixed responses for each call. Type runs every fixture when you deploy, with no credentials. If one fails, the deploy fails and the running version does not change.

A fixture runs one stage: the entry stage, or a later stage that it names with a mocked input. It never starts an agent stage. See [Test automations](https://docs.type.com/automations/testing/index.md).

## Deploys

`type-cli automations deploy <folder> --space <space>` checks the code, runs the fixtures, prepares the triggers, and activates the new version in one step. Each deploy saves a new **revision**. A failed deploy changes nothing. A run that already started finishes with the revision that it started with. See [Create and manage automations](https://docs.type.com/automations/deploy/index.md).

## Failures

- **Retries.** Type.com retries a stage only when waiting can help, such as a rate limit, and it can prove that the stage's code did not start. By default: three times, within 30 minutes.
- **Repair while running.** A failed run never pauses the automation, however many fail in a row. A code failure starts one repair agent, which tries to save corrected code while the automation keeps running.
- **Accounts.** If a saved account needs reconnecting, runs that use it fail until a member reconnects it. The automation stays on.
- **Alerts.** When most of an automation's recent runs have failed, Type alerts its owner that it keeps failing.
- **No replays.** Type never undoes the writes of a failed run, and never runs it again by itself.

See [Troubleshoot failed runs](https://docs.type.com/automations/test-troubleshoot/index.md) and [Runtime and guarantees](https://docs.type.com/automations/reference/runtime/index.md).

## Glossary

| Term | Meaning |
| --- | --- |
| Automation | A workflow that Type runs for a Space. |
| Instruction automation | An automation in which the managed agent follows your plain-language instructions. |
| Code automation | An automation written in TypeScript with `@type-dot-com/sdk`. |
| Subscription | A trigger and its entry stage. |
| Entry stage | The first stage of a run. |
| Code stage | A stage that runs TypeScript and returns a decision. |
| Agent stage | A stage that gives one step to the managed agent and returns a checked result. |
| Managed agent | Claude or Codex in the Space, with its connections, skills, memory, and sandbox. |
| Matcher | A filter that Type runs on events before your code. |
| Checkpoint | A JSON value that a subscription keeps from one run to the next. |
| Effect key | A stable name for one write. |
| Fixture | A test case that runs an entry stage with fixed data. |
| Revision | One deployed version of an automation's code. |
| Sandbox | An isolated Linux machine for shell commands, one for each run. |
