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

# Desktop script runtime

> The runtime contract for a script on a Windows or Linux desktop: the desktop object, timeouts, secrets, what each desktop can reach, and the errors a script can branch on.

A node on a Windows or Linux environment can run a script before any model call, the same way a browser node does. The script gets a `desktop` object in place of a Playwright `page`. It finds windows and controls by name, sends real mouse and keyboard input, and hands off to the next node. No model runs.

This page is the contract a desktop script runs under. The parts it shares with browser scripts, such as `asteroid.handoff`, are in [Script runtime](https://docs.asteroid.ai/concepts/scripting-runtime.md) and [Script a step](https://docs.asteroid.ai/operate/scripts.md).

***

## The entry function

A desktop script is a JavaScript (`.js`) file. It exports one async function, and the runtime calls it with a single object.

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

module.exports = async ({ desktop, args }) => {
  // desktop - drives the execution's desktop: windows, controls, input, files
  // args    - the node's resolved inputs (present when the node has an input schema)

  const win = await desktop.window({ process: 'ehr', title: /Patient Search/ }).waitFor();
  await win.focus();
  await win.locator({ role: 'edit', name: 'Patient ID' }).fill(args.patient_id);
  await win.locator({ role: 'button', name: 'Search' }).click();
  return asteroid.handoff({ to: 'read_record', summary: `Searched for ${args.patient_id}.` });
};
```

| Field | What it is |
| - | - |
| `desktop` | The execution's desktop. Every method is listed in [The desktop object](#the-desktop-object). |
| `args` | The node's resolved inputs. See [Pass data into a script](https://docs.asteroid.ai/operate/scripts.md#pass-data-into-a-script). |

* On a Windows or Linux environment, every `.js` script gets `desktop`. There is no `page`, and a function whose first parameter is `page` fails.
* A node with an **input schema** must destructure `args`, or every run fails.
* The **return value** works as it does in a browser script. The golden path is to return `asteroid.handoff(...)`. See [What the script returns](https://docs.asteroid.ai/operate/scripts.md#what-the-script-returns).
* `asteroid.generateTotp`, `emit`, `requireConfirmation` and `waitForReply` work unchanged.

***

## What a script can reach

| Capability | Windows | Linux |
| - | - | - |
| Windows: list, wait for, focus, maximize, close, dialogs | Yes | Yes |
| Controls by role and name (`locator`) | Apps that expose UI Automation: Win32, WinForms, WPF and Qt | Not yet. Calls answer `NOT_SUPPORTED` |
| Window text and button press by name | Yes | Not yet |
| Mouse, keyboard, paste and clipboard | Yes | Yes |
| Screenshots, and waiting for the screen to settle | Yes | Yes |
| Files, processes, launching programs | Yes | Yes |
| Shell commands (`exec`) | `powershell`, `pwsh`, `cmd` | `bash`, `sh` |

Without controls to find, a script drives an app with keyboard shortcuts, paste, and clicks at coordinates relative to its window. It cannot read the screen, so it cannot check what state the app is in. Script only the steps that always go the same way, and let the next node check the result.

***

## Timeouts

> [!WARNING]
>
> The whole script has a hard limit of **5 minutes**, as a browser script does. When it is reached, the run is killed and treated as a failure. Time spent waiting in `requireConfirmation` or `waitForReply` does not count.

| Default | Value |
| - | - |
| An action (click, fill, focus, a read) | 10 seconds |
| A wait (`waitFor`, `waitForAny`, `settle`) | 30 seconds |
| A shell command (`exec`) | 60 seconds |

Pass `{ timeout }` to the one call that is slow. `desktop.timeLeft()` returns the milliseconds the script has left, and no call runs past it.

Waits on windows, controls, processes and files run on the desktop in one held call, so they react at once and cost one round trip. Prefer them to `desktop.waitFor(fn)`, which polls.

***

## Where the script runs

The script runs in Node.js in the execution's sandbox, not on the desktop. Each `desktop` method is a call to the desktop, which takes about 150 to 400 ms. Make fewer, larger calls: read every match with one `infos()`, and wait for several states with one `waitForAny`.

* **`node:fs` sees the sandbox**, under `/home/agent`, as in [Script runtime](https://docs.asteroid.ai/concepts/scripting-runtime.md#the-filesystem). Use `desktop.fs` for the desktop's own disk.
* **Input is real.** Clicks and keys go to the window in front, and they show on the recording. Focus the target window before you send input, and again after a dialog closes.
* **Programs start in the signed-in user's session.** A window that `desktop.launch` opens is visible and can be driven.
* **Files in and out.** A file the caller staged is in the desktop's Uploads folder. A file the app saves into the desktop's Downloads folder reaches `/home/agent/downloads/` within 5 to 10 seconds.

***

## Secrets

Write `##ITEM_KEY.FIELD##` in the script, as in a browser script. The runtime fills the token in the sandbox before the script runs. The value reaches the desktop only as typed or pasted input. It is never written to the desktop's disk.

* `fill()` pastes a secret, and never reads a password field back.
* `exec`, the arguments of `launch`, and `desktop.fs.write` refuse a secret. The call throws `BAD_REQUEST`.
* Secret values are removed from console logs, errors and the call log.

***

## Example

Launch a Windows app, sign in, handle the dialog that can follow, read a table and hand off.

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

const APP = 'C:\\Program Files (x86)\\ExampleEHR\\ExampleEHR.exe';
const COLUMNS = ['time', 'patient', 'reason'];

module.exports = async ({ desktop }) => {
  const main = desktop.window({ process: 'ExampleEHR', title: /Example EHR/i });
  const dialog = desktop.dialogs({ process: 'ExampleEHR' }).first();

  // A retry can find the app already open.
  if (!(await main.exists())) await desktop.launch(APP);
  const win = await main.waitFor({ timeout: 60_000 });
  await win.focus();

  const username = win.locator({ role: 'edit', name: 'Username' });
  const table = { role: 'table' };
  const start = await desktop.waitForAny({ login: username, home: win.locator(table) });

  if (start === 'login') {
    await username.fill('##EXAMPLE_EHR.USERNAME##');
    await win.locator({ role: 'edit', name: 'Password' }).fill('##EXAMPLE_EHR.PASSWORD##');
    await win.locator({ role: 'button', name: 'Log in' }).click();
    console.log('CREDENTIALS_SUBMITTED=true');

    const after = await desktop.waitForAny({ home: win.locator(table), dialog });
    if (after === 'dialog') {
      const message = await dialog.text();
      await dialog.press('OK');
      if (/incorrect|invalid|locked/i.test(message)) {
        return handoff({ to: 'failed', outcome: 'login_failed', summary: message });
      }
      await win.focus();
    }
  }

  // Cells come top to bottom, then left to right. Their role differs by app.
  const cells = await win.locator({ role: 'text', within: table }).infos();
  const rows = [];
  for (const cell of cells) {
    const last = rows[rows.length - 1];
    if (last && Math.abs(last.y - cell.rect.y) <= 4) last.cells.push(cell.name);
    else rows.push({ y: cell.rect.y, cells: [cell.name] });
  }
  const appointments = rows.map((r) => Object.fromEntries(COLUMNS.map((c, i) => [c, r.cells[i] ?? ''])));
  if (appointments.length === 0) throw new Error('The appointment table shows no rows');

  return handoff({ to: 'done', summary: `Read ${appointments.length} appointments.`, output: { appointments } });
};
```

> [!TIP]
>
> Log a marker for each action that must not repeat, such as `CREDENTIALS_SUBMITTED=true`. When the script fails, the node's instructions run, and they can say "never submit the sign-in again".

***

## The desktop object

### Windows

| Method | Returns |
| - | - |
| `desktop.window(match)` | A window handle. It finds the window again on each use, so it never goes stale. |
| `desktop.windows(match?)` | Every matching window's info, front to back. |
| `desktop.dialogs(match?)` | The dialog windows: `all()`, `first()` and `count()`. `first()` is the front-most match on each use. |

A match sets any of `title` (a string, or a RegExp with no flag or `i`), `process` (case and `.exe` are ignored), `pid`, `className`, `handle` and `dialog`. Every field you set must match.

| Window handle method | Does |
| - | - |
| `waitFor({ timeout?, state? })` | Waits for `visible` (the default), `gone` or `focused`. Resolves to a handle pinned to the window that matched. |
| `exists()`, `info()` | Whether a window matches, and its info: title, process, pid, class, rect, and its visible, minimized, maximized, focused and dialog flags. `info()` throws when more than one window matches. |
| `focus()`, `maximize()`, `minimize()`, `restore()`, `close()` | The window action. |
| `locator(query)` | Controls inside the window. |
| `text()`, `press(name)` | The window's text labels, joined, and a click on the button with that name. Windows only. |

### Controls

A locator query sets any of these. Every field you set must match.

| Field | Matches |
| - | - |
| `role` | The lower-case UI Automation control type: `edit`, `button`, `text`, `menuitem`, `checkbox`, `radiobutton`, `combobox`, `list`, `listitem`, `tabitem`, `table`, `tree`, `pane`, ... |
| `name` | The accessible name, usually the label: a string, or a RegExp with no flag or `i`. |
| `nameContains`, `nameNot` | A part of the name, or names to exclude. |
| `automationId`, `className` | The UI Automation id and class. |
| `index` | The nth match, from 0. Matches are ordered top to bottom, then left to right. |
| `within` | Another query. Searches only inside its first match. |

| Locator method | Does |
| - | - |
| `click()`, `dblclick()` | Real mouse input at the control's centre. |
| `fill(text, { method?, verify? })` | Clicks, selects all, enters the text, then reads it back. `method` is `type` (the default), `paste` (the default for a secret) or `setValue`. |
| `focus()`, `text()`, `value()` | Keyboard focus, the control's text, and its value. `value()` is refused on a password field. |
| `exists()`, `count()`, `info()`, `infos()`, `rect()` | Whether it matches, how many match, and the info of the first or every match: role, name, rect, and the enabled, focused, offscreen and password flags. |
| `all()`, `nth(i)`, `locator(query)` | One locator per match, the match at an index, and a query inside this one. |
| `waitFor({ timeout?, state? })` | Waits for `visible` (the default), `gone` or `enabled`. |

### Waits

| Method | Does |
| - | - |
| `desktop.waitForAny({ key: waitable, ... }, { timeout? })` | Waits for the first of several windows, controls, processes or files to appear, in one held call. Returns its key. |
| `desktop.process(name)`, `desktop.file(path)` | Waitables for a running process or an existing file. `.gone()` waits for the opposite. |
| `desktop.settle({ window?, quietMs?, timeout? })` | Waits until the screen, or one window, stops changing. |
| `desktop.waitFor(fn, { timeout?, interval? })` | Calls `fn` until it returns a truthy value. |
| `desktop.sleep(ms)`, `desktop.timeLeft()` | A fixed wait, and the milliseconds left. |

### Input, screen and clipboard

| Method | Does |
| - | - |
| `desktop.mouse.click(x, y, { button?, count?, window? })` | A real click. With `window`, `x` and `y` are relative to that window. |
| `desktop.mouse.move(x, y, { window? })`, `desktop.mouse.scroll(dy, { x?, y? })` | Moves the pointer, and scrolls by wheel notches. |
| `desktop.keyboard.type(text, { delay? })` | Types text. |
| `desktop.keyboard.press(...keys)` | A key or a chord, in Playwright key names: `press('Control', 'a')`. |
| `desktop.keyboard.paste(text)` | Pastes the text, then restores the clipboard. Use it where typed keys get dropped. |
| `desktop.clipboard.read()`, `write(text)` | The text clipboard. |
| `desktop.screenshot({ window?, region?, format?, save? })` | A JPEG or PNG. With `save: 'name.jpg'`, it is also saved to `/home/agent/workspace/screenshots/`. |

### Programs and files

| Method | Does |
| - | - |
| `desktop.launch(path, args?, { shellOpen?, cwd? })` | Starts a program in the user's session. |
| `desktop.processes(name?)` | The running processes, each with `kill()`. |
| `desktop.exec({ shell, script, args?, env?, timeout? })` | Runs a shell command in the user's session. Returns `{ exitCode, stdout, stderr }`. A non-zero exit code does not throw. |
| `desktop.fs.read`, `readText`, `write`, `list`, `remove`, `downloads()` | The desktop's files, by absolute path, up to 8 MiB each. `downloads()` lists the Downloads folder. |
| `desktop.step(name, fn)` | Runs `fn` and records its time in the execution's trace. |

***

## Errors

A failed call throws an error with a `code`. Branch on the code, never on the message, and rethrow the rest: `if (err.code !== 'NOT_FOUND') throw err;`.

| Code | Means |
| - | - |
| `NOT_FOUND` | No window or control matches. A changed title or label is the usual cause. |
| `TIMEOUT` | A wait ran out, or the script's 5 minutes did. |
| `NOT_ACTIONABLE` | The control is disabled, off screen or covered, or `fill` read back a different value. |
| `NOT_SUPPORTED` | The desktop cannot do this, such as finding controls on Linux. |
| `BAD_REQUEST` | The call is wrong, such as a secret passed to `exec`, or `info()` on a match that fits several windows. |
| `OUTCOME_UNKNOWN` | The connection dropped during an action, so it may have happened. Check the state before you repeat it. |
| `NO_INTERACTIVE_SESSION`, `LOCKED` | Nobody is signed in to the desktop, or it is locked. Not a problem in the script. |

***

## When a script fails

A thrown error fails the script, and the node's failure action decides what follows, as for a browser script. See [What happens when the script fails](https://docs.asteroid.ai/operate/scripts.md#what-happens-when-the-script-fails). With the default, the model runs the node from its instructions. It gets the error, everything the script logged, the last 20 desktop calls with the code of any that failed, and a screenshot of the desktop at the moment it failed. The **desktop\_run\_script** step of the execution shows the same.

***

## Limits

* **No reading text from pixels.** There is no OCR. A script finds controls only through `locator`.
* **No controls on Linux.** Use keys, paste and window-relative clicks there.
* **No controls inside a remote app window,** such as an app delivered through Citrix or RemoteApp. The app is one picture to the desktop.
* **No controls in Java apps** (AWT or Swing) yet.
* **No Playwright inside a desktop app.** There is no `page` on a desktop.
* **5 minutes per script.** Split a long flow across nodes, such as sign in, then select a clinic.

***

## Related

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

> [card] [Script runtime](https://docs.asteroid.ai/concepts/scripting-runtime.md)
>
> The browser contract, and the `asteroid` module both share

> [card] [Environments](https://docs.asteroid.ai/concepts/environments.md)
>
> Browser, Linux, and Windows, and what each one runs

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


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