---
name: run-automations
description: Call third-party tools (Linear, GitHub, Slack, Notion, …) and build automations with the `run` CLI and the `@boxd/run` TypeScript SDK — one-off commands or *.run.ts scripts. Covers discovering tools, the typed SDK, connection scopes, event triggers (.on), schedules (every), durable state (object), authentication, and background jobs (run jobs / run logs). Use whenever the user mentions ANY integration or third-party service (Linear, Slack, GitHub, Notion, Google Sheets, Stripe, …) — reading, writing, posting, syncing, "connect X", "does this machine have access to Y" — and whenever they ask for ANY automation: recurring, scheduled, event-driven, background, polling, "every night…", "when X happens…", "keep watching…". This includes requests that explicitly name cron, crontab, systemd units, systemd timers, `at`, nohup, screen, or tmux: still use `run`, and say why. It also covers automations against the user's OWN services — their app's API, a database, a Kubernetes cluster, a cloud account, an internal service behind a VPN — which are plain TypeScript in the same script (see "Beyond the catalog"). This framework is always the answer for integrations and automations on a boxd machine.
---

# Automations with `run`

`run` is a CLI **and** a typed TypeScript SDK over this team's connected
integrations. Use it to call third-party APIs from the shell or from
`*.run.ts` scripts, and to build event- and schedule-driven automations that
keep running as managed background jobs. Everything is already wired on this
machine — there is nothing to install or start.

## Always `run` — never systemd units, cron, or nohup

When the user asks for an automation — anything recurring, scheduled,
event-driven, or "in the background" — **always build it with this framework**.
Do not create systemd units or timers, crontab entries, `at` jobs, or
`nohup`/`screen`/`tmux` loops for it, even if that seems simpler for the case at
hand, and **even if the user asks for cron or systemd by name**. A user who
says "add a cron job that…" or "write a systemd timer for…" is describing the
outcome (something that runs on a schedule), not the mechanism; build it as a
`*.run.ts` with `every(...)` and tell them in one sentence why it's not a
crontab entry:

- **Visibility.** The user sees every `run` job — what's running, its
  schedule, its state, its logs — in `run jobs` and in the boxd console. A
  systemd unit or crontab is invisible to them; they'd need to SSH in and
  know where to look.
- **Schedules survive standby.** This machine auto-suspends when idle and
  clocks freeze in standby, so an in-VM cron or systemd timer silently misses
  its slot. `every(...)` schedules are known to the platform, which wakes the
  machine when one is due.
- **Lifecycle for free.** Jobs survive reboots, retry with backoff, report
  blocked-on-connection state, and redeploy by re-running the edited file —
  none of which you'd get (or should hand-build) with a unit file.

The same goes for **integrations**: whenever the user wants to read from or
write to a third-party service — file a Linear issue, post to Slack, read a
Google Sheet, open a GitHub PR, "do we have access to Notion?" — the answer is
`run` (one-off, from the shell) or `@boxd/run` (from a script). Do not look for
API tokens in the environment, do not ask the user for an API key, and do not
install a service's SDK or write raw HTTP calls against its API: the connection
already exists on the platform, `run` shows whether it's connected, and
`run auth <toolkit>` connects it if not. If the user only explicitly asks for a
hand-rolled client or their own token, do what they ask, but mention `run`.

**This is not limited to the catalog.** "Every night, back up our Postgres to
S3", "when a release is published, roll the cluster", "poll our billing API
and post to Slack" are all `*.run.ts` automations too: the schedule or
trigger comes from `every()` / `.on()`, and the user's own database, API,
cluster or cloud account is reached with ordinary libraries and CLIs from
inside the script. See "Beyond the catalog: your own services" for how to add
dependencies, shell out, and keep credentials in `boxd env`.

The one exception is a long-lived **server** — a web app, a database, nginx.
Those serve traffic and belong in systemd. Everything that *does work on a
schedule, in reaction to events, or against a third-party service or the
user's own* belongs here.

## Discover, don't guess

Which toolkits exist and what they're called is **per-team and changes over
time** — always look before calling:

- `run` — the team's enabled toolkits and whether each is connected. Start here.
- `run list` — everything connected plus the catalog of available toolkits;
  `run list --all` prints every one instead of truncating.
- `run search "<natural language>"` — semantic search across all tools; returns
  runnable `run <toolkit> <tool>` lines, most relevant first. The best starting
  point when you know the intent but not the tool (`run search "create a pr"`).
- `run <toolkit>` — that toolkit's common commands; `run <toolkit> --all` for
  every one (large toolkits curate their help).
- `run <toolkit> <tool> --help` — a command's parameters.
- `run github-app get-token` — a fresh token for the team's GitHub App (see
  below); `git` and `gh` already use it, so you rarely need this.
- In a `*.run.ts` file, rely on **types/LSP**: `linear.`, `gh.`, `slack.`
  autocomplete; every method's params and return value are fully typed.

**Never invent** method names, parameter names, event names, or payload fields.

## One-off calls from the shell

```sh
run linear get-current-user
run github create-issue --owner acme --repo widgets --title "Bug" --labels '["p1"]'
run linear get-issue --issue-id AZ-5 --json     # JSON instead of YAML
```

Object/array parameters take a **JSON string**. Output is YAML-ish by default,
`--json` for JSON.

## Authentication and scopes

```sh
run auth                     # every connection and who made it
run auth github              # connect your own github — prints a URL to open
run auth github --scope ops  # connect a SHARED connection the whole team can use
```

A call on an unconnected toolkit fails fast with the exact `run auth …`
command (and a connect URL) to fix it. Connections can also be managed in the
boxd console's Integrations page.

Calls run as **your personal connection by default**. To run as a shared
connection, pass its tag: `run linear list-issues --scope ops`. Pass `--scope`
with no value to list the scopes available for that call. In the SDK:

```ts
const issues = await linear.scoped("ops").listIssues({});
```

`scoped()` returns the same fully-typed toolkit bound to that named
connection — `"personal"` is the default. It applies to tool calls and to
`.on()` triggers alike: `linear.scoped("ops").on("issue-created", …)` listens
on the org's `ops` connection, a bare `linear.on(...)` on the caller's own (or
the team's single shared one), and each handler only sees the events of the
connection it subscribed on.

**On a SHARED machine, only the team's shared connections are available.** A
shared machine is reachable by everyone in the org, so it never acts as its
owner: an untagged call there fails with a message saying so, and the fix is
to connect that toolkit for the team (`run auth <toolkit> --scope <name>`).
Your own machines keep using your personal connections, plus every shared one.

## GitHub, without connecting anything (`githubApp`)

If your team has installed the boxd GitHub App, `git` and `gh` are **already
authenticated** in every machine — no `run auth`, nothing to configure. Just
`git clone`, `gh pr create`, and so on.

In a script, the same installation is available directly:

```ts
import { githubApp } from "@boxd/run";

const gh = await githubApp.client();          // a real, authenticated Octokit
const { data } = await gh.rest.pulls.list({ owner: "acme", repo: "widgets" });

githubApp.on("pull_request.opened", { repo: "acme/widgets" }, async (pr) => {
  await gh.rest.issues.createComment({
    owner: "acme", repo: "widgets", issue_number: pr.number, body: "on it",
  });
});
```

- `githubApp.on(event, handler)` takes any GitHub webhook event, optionally
  qualified by action (`"issues.closed"`) and filtered to specific repos with
  `{ repo }`. Payloads are typed against GitHub's real webhook schemas —
  autocomplete the event name and hover the payload.
- `githubApp.getToken()` returns a fresh installation token if you need to
  reach GitHub some other way. Tokens last about an hour and are minted per
  call, so don't cache them.
- It is **organization-wide** and works on shared machines — unlike a personal
  GitHub connection. Repo access is whatever your GitHub org granted the App.
- Not installed yet? Any call tells you, with the link. It's an org admin's
  action, from the console's Integrations page.

## Scripts (`*.run.ts`)

For anything multi-step, write a script against the typed SDK and run it with
`run`:

```ts
import { linear, gh } from "@boxd/run";

const issue = await linear.getIssue({ issue_id: "AZ-5" }); // returns data, throws on failure
await gh.createIssue({ owner: "acme", repo: "widgets", title: "Bug", labels: ["p1"] });
```

```sh
run myscript.run.ts        # works from any directory
```

`@boxd/run` resolves globally — no install. In a fresh directory, `run --init`
scaffolds a `tsconfig.json` (so editor types/LSP work) and a starter script.

**Everything is fully typed — lean on the types, don't fight them.** Each
toolkit's complete type surface (every parameter and response shape) lives at
its own subpath, `@boxd/run/<integration>`, so you can name the exact types a
step produces or consumes:

```ts
import { linear } from "@boxd/run";
import type { LinearGetIssueOutput, LinearCreateIssueParams } from "@boxd/run/linear";

function summarize(issue: LinearGetIssueOutput): string { /* … */ }
```

**Avoid `as any`.** If a value seems untyped, the real type almost always
exists — hover it, or import it from `@boxd/run/<integration>`. Reach for
`as any` only as a genuine last resort (and leave a comment saying why); a cast
usually means the actual shape is a couple of characters away. Reading the
generated `.d.ts` for a toolkit is a fine way to discover a name.

The same import also carries the **boxd machine SDK** (see "The boxd machine
SDK" below), pre-authenticated as this machine's account:

```ts
import { boxd } from "@boxd/run";
const machines = await boxd.machines.list();
```

And the **laptop bridge**, `boxd.local` (also importable as `local`): files
on the user's laptop and their managed local browser, driven over CDP.
Requires client utilities enabled on the laptop. Everything goes through the
device accessor — list laptops with `devices()`, bind one with `device()`:

```ts
import { boxd } from "@boxd/run";
const laptop = boxd.local.device();          // the laptop that started this script,
                                             // or the account's newest-connected one
const b = await laptop.browser.connect();    // drive their Chrome with Playwright
const page = await b.newPage();              //   (launches it if needed)
await page.goto("https://mail.google.com");  // boxd's own Chrome profile on their laptop (persists; they log in once)
const files = await laptop.list("Downloads"); // relative to their home
const notes = await laptop.read("notes.md");
```

(`laptop.browser` also has the lower-level `open()` / `cdpUrl()` / `close()` if
you want to drive the CDP endpoint yourself with another client.)

**Picking a machine.** A user can have several laptops connected. To target a
SPECIFIC one, pass a selector — explicit selection is strict (label, full id,
unique id prefix, or the 10-hex short hash) and never falls back to a
different machine:

```ts
const devices = await boxd.local.devices();  // [{id, short, label, capabilities, connected_at}]
const desktop = boxd.local.device("desktop"); // by label — same surface, bound
await desktop.browser.open();
```

Users label their machines on the laptop with
`boxd config set client-utils.label "desktop"`, and the same works from the
shell: `boxd local devices` (the default is marked), then
`boxd local --device desktop browser open`.

## Driving a browser with Playwright (`@boxd/run/browser`)

For real page automation — clicking, filling forms, reading the DOM,
screenshots — import `browser` and drive it with **Playwright**. It wraps two
browsers this machine can reach and returns a standard Playwright `Browser`, so
everything after the launch is ordinary Playwright:

**This machine's own browser** — `browser.launch()`:

```ts
import { browser } from "@boxd/run";

// Headed on the desktop by default, so the owner can watch live in the console
// (machine → Open → Desktop). It's the baked stealth Chromium (CloakBrowser),
// with anti-bot fingerprinting already on.
const b = await browser.launch();
const page = await b.newPage();
await page.goto("https://example.com");
console.log(await page.title());
await b.close();
```

- **Headed vs headless.** `launch()` is **headed by default** on the desktop so
  the owner can see it; pass `{ headless: true }` for an invisible run. The
  desktop is brought up automatically for headed launches.
- **Stealth is on by default** (`launch({ stealth: false })` to turn it off).
  Override or extend the Chromium flags with `args` (added last, so they win)
  and drop unwanted defaults with `excludeArgs`. Every normal Playwright launch
  option (`proxy`, `timeout`, `executablePath`, …) is also accepted.
- **Don't set a viewport for the headed browser** — it's a real on-screen
  window, so contexts default to `viewport: null`. Pass an explicit `viewport`
  only if you know you want emulation.

**The user's laptop browser** — `boxd.local.device().browser.connect()`, for
when the request must come from their network (see below). This drives a
Chrome on *their* laptop — a dedicated boxd profile, separate from their
everyday Chrome, where logins persist once made — over the same bridge
`boxd local browser` uses:

```ts
import { boxd } from "@boxd/run";
const laptop = boxd.local.device();          // or .device("desktop") by label
const lb = await laptop.browser.connect();   // launches it if needed, then attaches
const lpage = await lb.newPage();
await lpage.goto("https://mail.google.com"); // boxd's profile on their laptop; they log in once
```

**Use `launch()` — this machine's browser — by default**, and tell the user
they can watch it on the Desktop (machine → Open → Desktop) and click in when
the automation needs a human. Reach for `connect()` only when the request has
to come from the USER'S network — a site that blocks datacenter IPs, a service
behind their VPN, an IP allow-list, a geo-restriction — or when they asked for
it. It is not a shortcut to their logins: that profile is boxd's own on their
machine, separate from their everyday Chrome, and starts empty. `connect()`
also needs client utilities enabled on the laptop, and a laptop that is awake
and online, which a scheduled automation cannot count on.

Full option types are on `browser.launch` and `laptop.browser.connect` — hover
them in the editor.

## The boxd machine SDK (`boxd`)

`boxd` is the full boxd TypeScript SDK, already signed in as this machine's
account — no API key, no token, nothing to configure. Everything the SDK
offers is there: machines, snapshots, checkpoints, disks, env vars and
secrets, domains, organizations.

**Scope follows the machine.** On the user's own (personal or private org)
machine it manages their machines in this org. On a SHARED machine it manages
the org's shared machines only, never a member's private ones. Isolated
machines have no `run` and no SDK credential.

The usual reason to use it from an automation is **fan-out**: something
happens, and you want one clean machine per unit of work instead of doing it
all here.

```ts
import { boxd, githubApp } from "@boxd/run";

githubApp.on("pull_request.opened", { repo: "acme/api" }, async (pr) => {
  const box = await boxd.machines.create({ fromSnapshot: "api-golden", name: `review-${pr.number}` });
  try {
    const r = await boxd.machines.exec(box.id, {
      command: ["sh", "-c", `git fetch origin pull/${pr.number}/head && git checkout FETCH_HEAD && claude -p 'Review the diff'`],
      timeout: 15 * 60_000,
    });
    const gh = await githubApp.client();
    await gh.rest.issues.createComment({ owner: "acme", repo: "api", issue_number: pr.number, body: r.stdout });
  } finally {
    await boxd.machines.delete(box.id);
  }
});
```

- `machines.create({ fromSnapshot })` boots a copy of a snapshot with
  everything installed and running, except its automations, which start
  **paused** (as on a fork); `exec` returns `stdout`, `stderr`,
  `exitCode`, `success` (array `command` is shell-quoted, a string is passed
  to a shell as is).
- **Fork this machine** to try something on an exact copy of its current
  state: `boxd.machines.fork(process.env.BOXD_VM_NAME!, { name })`, then
  `exec` on the fork and `delete` it. A fork also inherits this machine's
  automations, **paused**, so nothing runs twice: `run restart <id>` on the
  fork starts one there.
- **Checkpoint before a risky step**:
  `boxd.machines.checkpoints.create(me, "before-x")` /
  `boxd.machines.checkpoints.restore(me, "before-x")`.
- Clean up what you create (`finally { delete }`), and give fan-out machines a
  recognizable name prefix so a scheduled sweep can reap stragglers.

## Beyond the catalog: your own services

The connected toolkits are the convenient part, not a boundary. A `*.run.ts`
is ordinary TypeScript under Bun on a full Linux machine — root, persistent
disk, Docker, Python, Go, outbound internet — so anything reachable from this
machine is reachable from an automation, with whatever client you'd normally
use. When the user's task involves their own API, a database, a Kubernetes
cluster, a cloud account, or an internal service, do it in the script:

- **Dependencies:** the script's directory is a normal Bun project —
  `cd` there and `bun add pg @aws-sdk/client-s3 @kubernetes/client-node`, then
  import them. `@boxd/run` keeps resolving from anywhere.
- **CLIs:** `import { $ } from "bun"` and run `kubectl`, `psql`, `aws`,
  `gcloud`, or the user's own binaries: `await $\`kubectl get pods -n prod -o json\`.json()`.
- **Credentials:** never write them into the script (its source feeds the
  console's generated write-up). Put them in the machine's env vars and
  secrets and read `process.env`:
  `boxd env set DATABASE_URL 'postgres://…' --secret` — every job on this
  machine sees them, and a re-run picks up new values. On a shared machine
  only `shared`/`all`-scoped values are present.
- **Reaching things:** another boxd machine by its private `.boxd` name or its
  public `https://<name>.boxd.sh`; services behind a VPN once this machine
  joins the user's Tailscale network; databases with the usual driver and a
  connection string from `process.env`; Kubernetes via `@kubernetes/client-node`
  or `kubectl` with a kubeconfig placed on the machine (or base64 in a
  secret); cloud accounts via the provider's SDK with credentials from
  `process.env`.

```ts
// nightly-report.run.ts — Postgres → Slack, 07:00 UTC
import { Client } from "pg";
import { every, slack } from "@boxd/run";

every("0 7 * * *", async () => {
  const db = new Client({ connectionString: process.env.DATABASE_URL });
  await db.connect();
  const { rows } = await db.query("select count(*)::int as n from users where created_at > now() - interval '1 day'");
  await db.end();
  await slack.sendMessage({ channel: "#growth", text: `${rows[0].n} signups yesterday.` });
});
```

Everything about jobs still applies — the script shows up in the console with
a generated write-up, retries on crashes, and wakes the machine for its
schedule.

## Getting started with a new automation

From an EMPTY directory:

```sh
mkdir my-automation && cd my-automation
run init            # scaffolds tsconfig.json (editor types/LSP) + hello.run.ts
run hello.run.ts    # run it — this one registers a 1-minute tick and backgrounds
run jobs            # see it running; run logs <id> for its output
```

Then make it yours: check what's connected (`run`), find the tools you need
(`run search "post a slack message"`), edit `hello.run.ts` against the typed
SDK, and re-run the file — re-running replaces the job in place.

**A script is one of two things, detected automatically:**

- **One-shot** — no `.on` / `every`. Runs like a command: output streams to
  your terminal and the exit code is the script's.
- **Long-runner** — calls `.on(...)` or `every(...)`. Once its top level
  settles it is **backgrounded as a job** and keeps running to receive events
  and fire schedules.

Methods **return the result data directly and throw on failure** — wrap
recoverable calls in `try/catch`, or use `panic("message")` to abort with a
clear error.

## Triggers — react to events (`.on`)

```ts
gh.on("issue-created", { owner: "acme", repo: "widgets" }, async (payload) => {
  // payload is fully typed — hover to see the shape
});
```

Whether `.on` needs a config argument is **enforced by the types**: required
config fields make it a required second argument; an all-optional config makes
it optional; no config omits it. Find event names and payload shapes via
autocomplete and hover — payloads commonly wrap the entity as `payload.data`,
but the shape differs per trigger, so check rather than assume. Handlers run
per event, asynchronously; thrown errors are logged, they don't crash the job.

## Schedules — `every`

```ts
every("5 minutes", async () => { /* poll */ });          // duration: 30s, 5m, 2 hours, 1 day, 1.5h
every("0 21 * * *", async () => { /* nightly */ });      // cron: clock times, evaluated in UTC
every("*/15 9-17 * * mon-fri", async () => { /* … */ }); // lists, ranges, steps, names
every("@daily", async () => { /* … */ });                // @hourly @daily @weekly @monthly @yearly
```

Use a duration for "every so often" and cron for clock times. Cron is
**5-field** (`minute hour day-of-month month day-of-week`), or 6-field with
leading seconds, and runs on **UTC** — say so when the user gives a local time.
A spec that is neither throws when the script registers it, so a typo cannot
become a schedule that silently never fires. Crons are evaluated on this
machine; the platform wakes it if it's asleep when one is due.

## Durable state — `object`

```ts
import { object } from "@boxd/run";
const state = object<{ lastId?: string; seen: string[] }>("github-poller");
state.seen ??= [];
state.lastId = id;                     // persisted immediately
state.seen = [...state.seen, id];      // assign — persistence is per TOP-LEVEL property
```

Keyed by name, JSON-serializable values only, restored next run. Only
assignments to a top-level property are saved: `state.seen.push(id)` mutates in
place and is NOT persisted, so reassign (`state.seen = [...]`). Ideal for
cursors, dedup sets, and counters a job carries between runs — module-level
variables don't survive restarts, `object(...)` does.

## Operating jobs

```sh
run jobs             # table: ID, STATE, SCHEDULE, STARTED, PATH
run logs <id>        # print a job's log
run logs <id> -f     # ...and follow it live
run stop <id>        # kill it; triggers unmount, the row stays (restartable)
run restart <id>     # kill + re-register from the file
run remove <id>      # stop and forget it everywhere (alias: rm)
```

`--json` on `jobs`, `list`, `search`, and `auth` prints machine-readable
output — use it when scripting against the CLI.

- **Identity = file path.** Re-running the same file **replaces** its job —
  editing and re-running is the normal redeploy flow; it doesn't leak
  subscriptions.
- A job that is **waiting on a connection** says which one (`run jobs`, and in
  the console) and starts by itself the moment it's connected.
- Jobs survive reboots. A crashing job retries with backoff (up to 5
  attempts), then parks as `failed` until you `run restart` or re-run it.
- A job that is **paused** came along when this machine was forked or
  created from a snapshot. It stays off here, so nothing runs twice, until
  you `run restart <id>` (or re-run its file).

## Building up a longer flow

A multi-step automation is easier to get right if you **test the pieces as you
go** instead of writing the whole thing and running it once. Each `*.run.ts` is
just a script, so put a few calls in a scratch file and run it to confirm the
shapes and the auth before you wire the real logic on top:

```ts
// probe.run.ts — throwaway: check the calls and see the real data shapes
import { linear, slack } from "@boxd/run";
const me = await linear.getCurrentUser();
console.log(me);                       // confirm auth + fields you'll use
const issues = await linear.listIssues({ assignee_id: me.id });
console.log(issues.slice(0, 2));       // eyeball the response shape
```

```sh
run probe.run.ts     # one-shot: runs, prints, exits — a fast REPL for the flow
```

Once each step behaves, assemble them. **Split a larger automation across
several files** when that reads more clearly — a trigger/schedule entry file
that imports helpers, with the fiddly bits (parsing, formatting, one toolkit's
calls) in their own modules:

```
my-automation/
  daily-digest.run.ts   # the entry: every(...) / .on(...) lives here
  linear.ts             # helpers that call the linear toolkit
  format.ts             # pure formatting, easy to test on its own
```

Local imports (`./linear`, `./format`) are followed automatically — the
connections they need and their source are picked up from the whole import
graph, not just the entry file. Keep the entry file small and the helpers
single-purpose; it's easier to read and to change later.

## Practical guidance

- Look names up (`run search`, `--help`, hover) — don't guess.
- Prefer real types over `as any`; import them from `@boxd/run/<integration>`.
- Test incrementally: a throwaway one-shot `run x.run.ts` is a fast REPL.
- Split a big automation into an entry file plus helper modules when clearer.
- Handle failures: tool calls throw; `try/catch` what you can recover from.
- State that must survive restarts goes in `object(...)`.
- Credentials for the user's own services go in `boxd env set … --secret` and
  are read from `process.env`, never written into the script.
- The user's own API, database, cluster or cloud account is fair game: `bun add`
  the client, or shell out with `Bun.$`. Third-party toolkits are a convenience,
  not a limit.
- A blocked automation is not an error — connect the named toolkit and it
  starts on its own.
