> ## Documentation Index
> Fetch the complete documentation index at: https://docs.asteroid.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Script runtime

> The runtime contract for a node script: the entry signature, timeouts, the sandbox, the filesystem, how require resolves, and secret tokens.

This page is the exact contract a node script runs under. For how to attach a script and route from one, start with [Script a step](https://docs.asteroid.ai/operate/scripts.md).

***

## The entry function

A script exports one async function. The runtime calls it with a single object.

```javascript theme={null}
const asteroid = require('asteroid');

module.exports = async ({ page, browser, context, args }) => {
  // page     - the active Playwright Page, on the live browser session
  // browser  - the Playwright Browser
  // context  - the Playwright BrowserContext
  // args     - the node's resolved inputs (present when the node has an input schema)

  // Golden path: end with a handoff, which chooses the next node.
  return asteroid.handoff({ to: 'next_node', summary: 'Did the work.' });
};
```

| Field | What it is |
| - | - |
| `page` | The active [Playwright](https://playwright.dev) `Page`, already on the live session. |
| `browser` | The Playwright `Browser`, for a second tab or context. |
| `context` | The Playwright `BrowserContext`. |
| `args` | The node's resolved inputs. See [Pass data into a script](https://docs.asteroid.ai/operate/scripts.md#pass-data-into-a-script). |

Notes on the shape:

* **CommonJS is the norm:** `module.exports = async (...) => { ... }`. `export default` works too, and an ESM file with top-level `await` is loaded as a module.
* A node with an **input schema** must destructure `args`. The `async (page) => { ... }` form does not receive `args` and fails validation when the node declares inputs.
* The **return value** decides output and routing. **The golden path is to return `asteroid.handoff(...)`**, which chooses the next node and carries its data. An object instead becomes output variables, a string becomes `script_output`, and a throw is a failure. See [Route to the next node yourself](https://docs.asteroid.ai/operate/scripts.md#route-to-the-next-node-yourself).

***

## Timeouts

> [!WARNING]
>
> The whole script has a hard limit of **5 minutes**. When it is reached the run is killed and treated as a failure, so the node's failure action decides what happens next. Design a script to finish well inside that. Time spent waiting in [`requireConfirmation`](#pause-for-approval) does not count.

Inside that budget, Playwright actions carry their own defaults, kept short so a wrong selector fails fast instead of stalling.

| Default | Value |
| - | - |
| Per-action timeout (click, fill, wait for selector) | 10 seconds |
| Navigation timeout | 30 seconds |

Raise a limit for a genuinely slow step:

```javascript theme={null}
const asteroid = require('asteroid');

module.exports = async ({ page }) => {
  page.setDefaultTimeout(30000);          // all actions on this page
  page.setDefaultNavigationTimeout(60000); // navigations on this page

  await page.click('#slow-report', { timeout: 45000 }); // one call only
  return asteroid.handoff({ to: 'report_ready', summary: 'Report loaded.' });
};
```

***

## The sandbox

A script runs in the execution's sandbox, next to the browser.

* **Node.js 22.** Node built-in modules (`node:fs`, `node:path`, `node:crypto`, and the rest) are available.
* **Playwright** drives a headless Chromium over the live session. You get it through `page`, `browser`, and `context`, so you do not launch a browser yourself.
* **`python3`** is present, with `python3-yaml`, reachable from the workflow's Bash tool.
* **No PDF or OCR libraries.** To read a PDF or a print-only page, parse it in the browser page with `pdf.js`, not with a Node module. See [the PDF pattern](https://docs.asteroid.ai/operate/scripts.md#a-document-that-arrives-as-a-pdf-or-a-print-only-page).

***

## The filesystem

The working directory is `/home/agent`. A script reads and writes files with `node:fs`, using absolute paths.

| Directory | What it holds |
| - | - |
| `/home/agent/shared/` | The workflow's own files, placed when the workflow was built: the node scripts themselves, plus any library or reference data they read, such as a bundled parser or a field map. Read these from a script. |
| `/home/agent/workspace/` | Scratch for the current execution. It survives every step and loop-back in the run, then is cleared. Use it for within-run state. |
| `/home/agent/downloads/` | Where browser downloads land, for the current execution. |
| `/home/agent/uploads/` | Files the caller staged for this execution. |

A script's own file lives under `/home/agent/shared/<node-slug>/`, where the runtime derives `<node-slug>` from the node's display name. Because it re-derives the slug, a rename never breaks how the runtime finds the entry script. It does not, however, rewrite absolute paths you wrote by hand. A hardcoded `/home/agent/shared/<node-slug>/...` path (a required helper, a reference file) breaks when you rename the node, so update those yourself.

> [!WARNING]
>
> Do not use `shared/` to carry state from one run to the next. A running script's writes to `shared/` are not saved back to the workflow. Durable `shared/` content comes from how the workflow is built, not from a running script. Keep per-run state in `workspace/`, and treat `shared/` as read-only reference.

> [card] [Workflow filesystem](https://docs.asteroid.ai/concepts/filesystem.md)
>
> The full directory layout, the quotas, and how files get in and out

***

## Requiring modules

* **`require('asteroid')`** is provided by the runtime. Its whole surface is `handoff(...)`, `generateTotp(...)`, `emit(...)` and `requireConfirmation(...)`. See [Route to the next node yourself](https://docs.asteroid.ai/operate/scripts.md#route-to-the-next-node-yourself), [Two-factor codes](#two-factor-codes), [Emit your own event](#emit-your-own-event) and [Pause for approval](#pause-for-approval).
* **Node built-ins** resolve normally.
* **Helper modules** must be required by their **absolute path** under `shared/`, for example `require('/home/agent/shared/file_claim/lib/dates.js')`. A relative `require('./dates.js')` does not resolve, because the runtime runs your script from a private copy that holds no sibling files.
* **Use absolute `/home/agent/...` paths.** They work exactly as written from the entry script. Pass a required helper the paths it needs as arguments, rather than letting it compute its own, so it never depends on where the runtime placed your script.

```javascript theme={null}
const asteroid = require('asteroid');
const dates = require('/home/agent/shared/file_claim/lib/dates.js');

module.exports = async ({ page, args }) => {
  const dob = dates.toEhrFormat(args.date_of_birth);
  await page.fill('#dob', dob);
  return asteroid.handoff({ to: 'saved', summary: 'Filled the date of birth.' });
};
```

***

## Secret tokens

A script fills a secret with a `##ITEM_KEY.FIELD##` token. The runtime replaces it from the
secret attached to the profile, just before the script runs, so the value never reaches the model.
The usage is in [Secrets in a script](https://docs.asteroid.ai/operate/scripts.md#secrets-in-a-script), and the full
model is in [Secrets & 2FA](https://docs.asteroid.ai/concepts/credentials.md).

### Two-factor codes

`asteroid.generateTotp(secret, options?)` returns the current authenticator code as a string. Pass
the token of a TOTP seed field. The runtime fills the token before the script runs, so the seed
stays inside the script run. Only the generated code reaches the page.

```javascript theme={null}
const asteroid = require('asteroid');

module.exports = async ({ page }) => {
  await page.fill('#otp', asteroid.generateTotp('##MY_PORTAL.TOTP_SEED##'));
  await page.click('#verify');
  return asteroid.handoff({ to: 'dashboard', summary: 'Passed 2FA.' });
};
```

| Option | Default |
| - | - |
| `digits` | `6` |
| `period` | `30` seconds |
| `algorithm` | `'sha1'`. Also `'sha256'` or `'sha512'`, in any case. |

The secret may be a bare base32 seed or an `otpauth://totp/` URI. A URI's own `digits`, `period`
and `algorithm` apply unless an option overrides them.

* A token the run does not fill throws, and the error names the token.
* An unusable seed throws a fixed message that never quotes the seed.
* Generate the code immediately before you submit it. If the site rejects it, generate a fresh code
  and retry once.

***

## Emit your own event

`await asteroid.emit(name, options?)` publishes an event from inside the run. It reaches every
webhook and Slack integration on the workflow's **Notifications** tab that subscribes to
**Custom Event**, either every custom event or those whose `name` matches a filter. The script
holds no token and no URL.

```javascript theme={null}
const asteroid = require('asteroid');

module.exports = async ({ page, args }) => {
  await page.screenshot({ path: '/home/agent/downloads/referral.png' });
  await asteroid.emit('referral_result', {
    text: `Referral ${args.status} for member ${args.member_id}`,
    payload: { status: args.status, auth_number: args.auth_number },
    files: ['/home/agent/downloads/referral.png'],
  });
  return asteroid.handoff({ to: 'done', summary: 'Reported the result.' });
};
```

| Argument | Rule |
| - | - |
| `name` | 1 to 64 characters of `a-z`, `0-9`, `_`, `.` or `-`. Starts with a letter or a digit. This is what a notification filters on, so keep it stable: `referral_result`, not `event1`. |
| `text` | Optional. A summary of up to 3,000 characters. Slack shows it as the message body. |
| `payload` | Optional. A plain object of JSON values, up to 64 KB. |
| `files` | Optional. Up to 5 absolute paths under `/home/agent/downloads`, `/home/agent/uploads` or `/home/agent/workspace`. Each file must exist when you call `emit`. |

**Files** are sent by reference. The runtime uploads each one before the event goes out, and the
event carries a signed download link that works for one hour. Slack shows an image inline and
any other file as a link. A webhook gets the link in `files[]`. A file under `shared/` cannot be
attached: that directory is read-only and never synced from a run.

* **Await the call.** It resolves to `{ id }`. Delivery to your endpoint happens after that, so a
  slow or failing endpoint never fails the script.
* **A malformed call throws**, and the error names the argument. So does the 101st emit of one
  execution.
* **Do not send an event again after "did not confirm".** That error means the runtime gave no
  answer in time. The event can still arrive, and a second call is a second event with a new `id`.
* **A secret never leaves the run.** If `text` or `payload` contains the value of a secret from
  the profile, the runtime swaps it for its `'##ITEM_KEY.FIELD##'` placeholder before the event is
  sent, so the receiver sees the placeholder, not the value. A `name` or a file path that
  contains a secret value is refused. File contents are sent as written.
* **A test-run in Astro sends nothing.** It checks the call, logs the event, and resolves to
  `{ id: null, dryRun: true }`.
* **Do not use it for the final result.** A run that fails, is cancelled or times out never reaches
  your `emit`. `EXECUTION_COMPLETED`, `EXECUTION_FAILED` and `EXECUTION_CANCELLED` always fire. Use
  `emit` for progress and for content the lifecycle events do not carry.

The payload your endpoint receives is in [Webhooks & Slack](https://docs.asteroid.ai/operate/webhooks-and-slack.md#custom-events).

***

## Pause for approval

`await asteroid.requireConfirmation(message)` pauses the run at that line until a person approves
it. Put it right before a submit, so the user approves a filled form, not an empty one. The run
goes to `awaiting_confirmation`, and the execution page shows `message`, the live browser and the
approval controls. The browser, the page and the script keep their state while they wait.

```javascript theme={null}
const asteroid = require('asteroid');

module.exports = async ({ page, args }) => {
  await page.fill('#patient', args.patient_name);
  await page.fill('#reason', args.reason);
  await asteroid.requireConfirmation(`Submit the referral for ${args.patient_name}?`);
  await page.click('#submit');
  return asteroid.handoff({ to: 'done', summary: 'Submitted the referral.' });
};
```

| Answer | What happens |
| - | - |
| Approve: **Continue** on the execution page, or `asteroid execution resume <execution-id>` | The script runs on from the next line. |
| Reject: **Cancel** on the execution page, or `asteroid execution cancel <execution-id>` | The run is cancelled. The call throws and nothing after it runs. |
| No answer in 5 minutes | The run is cancelled with reason `timeout`. |

* **Await the call.** Without `await`, the script runs on to the submit.
* `message` is 1 to 500 characters. Say what the user approves.
* One confirmation at a time. A second call while one waits throws.
* It works in a script the node runs itself. A script the agent runs during an AI turn gets an
  error at the call.
* **A test-run in Astro stops at the call.** It logs the message and throws, so a test never
  submits. Run the workflow to see the pause.
* A rejected step is not a script failure. The run shows as cancelled by the user.

***

## Related

> [card] [Script a step](https://docs.asteroid.ai/operate/scripts.md)
>
> Attach a script, route from it, and pin its inputs

> [card] [Workflow filesystem](https://docs.asteroid.ai/concepts/filesystem.md)
>
> Directories, quotas, and file transfer

> [card] [Secrets & 2FA](https://docs.asteroid.ai/concepts/credentials.md)
>
> How a `##ITEM_KEY.FIELD##` token gets its value

> [card] [Nodes](https://docs.asteroid.ai/concepts/nodes.md)
>
> Where a script file lives on a node


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.