﻿<head><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4357510538660394"
     crossorigin="anonymous"></script></head>---
url: https://docs.puppetflow.com/reference/magic-methods.md
---
# Flow API Reference

Flow code can use Puppeteer alongside Puppetflow's helper functions and global objects.

## Flow objects

| Object | Description |
| --- | --- |
| `$input` | Input argument passed to the flow. |
| `$context` | Run metadata (`run_id`, `flow_id`, `legend`, `meta`), passed as the third argument of `run`. |
| `$page` | Proxy to the Puppeteer [Page](https://pptr.dev/api/puppeteer.page) of the active named tab. |
| `$browser` | The Puppeteer [Browser](https://pptr.dev/api/puppeteer.browser) instance. |
| `$client` | CDP session for low-level Chrome DevTools Protocol calls. |
| `$viewportWidth`, `$viewportHeight` | Effective browser viewport dimensions. |
| `$now`, `$today` | Luxon `DateTime` values for the current time and start of today. |

See [Flow Objects](./flow-api/globals) for details on the input structure and context metadata.

The editor builds this catalog from the same runtime metadata used by the help panel. Type `$` to browse every helper, `$page.` or `$client.` for the installed Puppeteer API, and `$$` for accessible snippets. Resource parameters autocomplete readable names while inserting stable IDs.

## Categories

### [Navigation](./flow-api/navigation)

Page navigation, viewport control, cookie persistence and login helpers.

`$gotoUrl`, `$gotoTab`, `$setViewport`, `$screenshot`, `$loginRemember`, `$saveCookies`, `$loadCookies`, `$clearCookies`

### [Interaction & Selectors](./flow-api/interaction)

Click, type, scroll, and query elements - including shadow DOM traversal.

* Input: `$keyboardSpeed`, `$keyboardPress`, `$keyboardShortcut`, `$fillInput`
* Click and scroll: `$clickElement`, `$clickElementAtIndex`, `$clickAtCoordinates`, `$scrollByPixels`, `$scrollToElement`
* Selectors: `$selectOneElement`, `$selectManyElements`, `$attributesFromOne`, `$attributesFromMany`, `$selectShadow`, `$shadowInputFill`, `$waitForSelectorCondition`

### [Page Evaluation](./flow-api/page-evaluation)

Run JavaScript inside the page context, send HTTP requests and capture browser network traffic.

`$injectScriptLibrary`, `$bridgeEvaluate`, `$httpRequest`, `$sniffNetwork`, `$stopSniffing`

### [Files & Downloads](./flow-api/files)

Download, upload, unzip, scan directories, and work with PDFs.

`$writeFile`, `$download`, `$downloadFromBrowser`, `$waitForFile`, `$upload`, `$unzipFile`, `$scanDirectory`, `$scanDownloadsDirectory`, `$moveDownloadedFile`, `$getDownloadsPathFile`, `$pdfSearch`, `$pdfGetText`

### [Data Tables](#data-tables)

Query rows, update data, branch on row existence, and manage data tables.

`$dataTableInsertRow`, `$dataTableUpdateRows`, `$dataTableUpsertRows`, `$dataTableRowExists`, `$dataTableRowDoesNotExist`, `$dataTableGetRows`, `$dataTableDeleteRows`, `$dataTableCreate`, `$dataTableDelete`, `$dataTableList`, `$dataTableUpdate`

### [Utilities](./flow-api/utilities)

Timing, logging, variables, date helpers and pattern matching.

`$sleep`, `$stopwatchStart`, `$stopwatchCheck`, `$stopwatchStop`, `$if`, `$ifEmpty`, `$max`, `$min`, `$log`, `$legend`, `$meta`, `$vars`, `$totp`, `$matchSequence`, `$parseDates`, `$sortDates`, `$currentDate`, `$currentDateMinusOneMonth`, `$currentDatePlusOneMonth`

### [Response & Output](./flow-api/response)

Build the flow's return value.

`$setOutput`, `$generateResponse`, `$generateResponseSuccess`, `$generateResponseError`, `$stopSuccess`, `$stopFail`

### [Notifications](./flow-api/notifications)

Send messages to Slack, Discord, or Telegram and pause for human validation.

`$notify`, `$waitHumanValidation`

### [Email](./flow-api/email)

Wait for incoming emails through mailbox watchers.

`$waitForEmail`

### AI&#x20;

Send prompts to configured AI models or let a vision model operate the browser.

`$mcpClientTool`, `$aiMessage`, `$aiControl`

### [Debugging](./flow-api/debugging)

Interactive breakpoints for step-by-step debugging.

`$breakpoint`

## Data Tables

Data Table helpers use stable table IDs that start with `dtbl_`. Existing-resource helpers accept `tableId` as their only resource identifier. In the code editor, autocomplete displays the table name and inserts its ID.

Rows are returned as plain objects. Custom values use their column names alongside the system fields:

```js
{
  id: 42,
  email: 'person@example.com',
  score: 18,
  active: true,
  processed_at: '2026-08-27T20:30:00+00:00',
  created_at: '2026-08-27 20:30:00',
  updated_at: '2026-08-27 20:35:00',
}
```

### Values

Write values as an object keyed by custom column name. Omitted columns and explicit `null` values are stored as `NULL`.

```js
const values = {
  email: 'person@example.com',
  score: 18,
  active: true,
  processed_at: null,
};
```

The accepted value depends on the column type:

| Type | Accepted values |
| --- | --- |
| `string` | A string or `null`. |
| `number` | A finite JavaScript number or `null`. |
| `boolean` | `true`, `false`, or `null`. |
| `datetime` | An ISO 8601 date and time string or `null`. Values are stored in UTC. |

System fields cannot be written through the Values object.

### Filters

Filters are arrays because one query may contain several conditions, including more than one condition on the same column.

```js
const filters = [
  { keyName: 'status', condition: 'eq', keyValue: 'active' },
  { keyName: 'score', condition: 'gte', keyValue: 10 },
];
```

Each filter has:

| Field | Description |
| --- | --- |
| `keyName` | Custom or system column name. |
| `condition` | Comparison to apply. |
| `keyValue` | Comparison value. Omit it for conditions that do not need a value. |

Conditions depend on the column type:

| Column type | Conditions |
| --- | --- |
| String | `eq`, `neq`, `like`, `ilike`, `isEmpty`, `isNotEmpty` |
| Number | `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `isEmpty`, `isNotEmpty` |
| Datetime | `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `isEmpty`, `isNotEmpty` |
| Boolean | `eq`, `neq`, `isTrue`, `isFalse`, `isEmpty`, `isNotEmpty` |

`like` contains the supplied text with case-sensitive matching. `ilike` is case-insensitive. Percent and underscore characters are treated as ordinary text, not SQL wildcards.

Use `options.matchType` to combine filters:

* `allConditions` requires every condition and is the default.
* `anyCondition` accepts a row when at least one condition matches.

### `$dataTableInsertRow(tableId, values)` {#data-table-insert-row}

Insert one row and return the complete stored row.

```js
const row = await $dataTableInsertRow(
  'data-table-id',
  {
    email: 'person@example.com',
    active: true,
  },
);
```

An empty Values object is valid and creates a row containing `NULL` in every custom column.

### `$dataTableUpdateRows(tableId, filters, values, options?)` {#data-table-update-rows}

Update all matching rows and return their stored values.

```js
const rows = await $dataTableUpdateRows(
  'data-table-id',
  [{ keyName: 'active', condition: 'isFalse' }],
  { active: true },
  {
    matchType: 'allConditions',
    dryRun: false,
  },
);
```

At least one filter is required. Set `options.updateAll` to `true` to update every row explicitly. Set `options.dryRun` to `true` to return before and after rows without saving changes.

### `$dataTableUpsertRows(tableId, filters, values, options?)` {#data-table-upsert-rows}

Update matching rows. When nothing matches, insert one row using `values`.

```js
const rows = await $dataTableUpsertRows(
  'data-table-id',
  [{ keyName: 'email', condition: 'eq', keyValue: 'person@example.com' }],
  {
    email: 'person@example.com',
    active: true,
  },
);
```

Filters are required. Filter values are not copied into a newly inserted row, so include those values in the Values object when needed. `matchType` and `dryRun` are available in `options`.

### `$dataTableRowExists(tableId, filters, options?)` {#data-table-row-exists}

Return `true` when at least one row matches.

```js
const exists = await $dataTableRowExists(
  'data-table-id',
  [{ keyName: 'email', condition: 'eq', keyValue: 'person@example.com' }],
);
```

### `$dataTableRowDoesNotExist(tableId, filters, options?)` {#data-table-row-does-not-exist}

Return `true` when no row matches. Both existence helpers require filters and accept `options.matchType`.

```js
const isNewCustomer = await $dataTableRowDoesNotExist(
  'data-table-id',
  [{ keyName: 'email', condition: 'eq', keyValue: 'ada@example.com' }],
);
```

In a nodal flow, these helpers are represented by conditional nodes with `true` and `false` outputs.

### `$dataTableGetRows(tableId, filters?, options?)` {#data-table-get-rows}

Return matching rows.

```js
const rows = await $dataTableGetRows(
  'data-table-id',
  [
    { keyName: 'score', condition: 'gte', keyValue: 10 },
    { keyName: 'active', condition: 'isTrue' },
  ],
  {
    matchType: 'allConditions',
    limit: 50,
    orderBy: 'updated_at',
    direction: 'desc',
  },
);
```

Options:

| Option | Default | Description |
| --- | --- | --- |
| `matchType` | `allConditions` | Combine filters with all or any matching. |
| `limit` | `50` | Maximum rows to return, from 1 to 10000. |
| `returnAll` | `false` | Return every matching row and ignore `limit`. |
| `orderBy` | `updated_at` | Custom or system column used for sorting. |
| `direction` | `desc` | `asc` or `desc`. |

Pass an empty array or omit `filters` to query the whole table.

### `$dataTableDeleteRows(tableId, filters, options?)` {#data-table-delete-rows}

Delete matching rows and return the rows that were deleted.

```js
const deleted = await $dataTableDeleteRows(
  'data-table-id',
  [{ keyName: 'status', condition: 'eq', keyValue: 'expired' }],
  { dryRun: true },
);
```

Filters are always required. Set `dryRun` to `true` to preview before and after rows without deleting them.

### `$dataTableCreate(name, columns?, options?)` {#data-table-create}

Create a data table and return its ID. The `id`, `created_at`, and `updated_at` system columns are added automatically.

```js
const tableId = await $dataTableCreate(
  'contacts',
  [
    { name: 'email', type: 'string' },
    { name: 'score', type: 'number' },
    { name: 'active', type: 'boolean' },
    { name: 'processed_at', type: 'datetime' },
  ],
  {
    description: 'Contacts collected by flows',
    visibility: 'team',
    teamId: 'team-id',
  },
);

const row = await $dataTableInsertRow(tableId, { email: 'ada@example.com' });
```

Column types are immutable after creation. Options can set `description`, `visibility`, `ownerId`, and `teamId`. Visibility is `owner` (the default), `team`, or `workspace`.

### `$dataTableDelete(tableId)` {#data-table-delete}

Permanently delete a table and all of its rows. The helper returns the deleted table ID.

```js
const deletedTableId = await $dataTableDelete('data-table-id');
```

### `$dataTableList(options?)` {#data-table-list}

Return accessible data tables with their metadata and custom columns. Optional filters can narrow the list by visibility, owner, or team.

```js
const tables = await $dataTableList({ visibility: 'workspace' });
```

### `$dataTableUpdate(tableId, changes)` {#data-table-update}

Update a table's name, description, visibility, owner, or team without changing its ID, physical storage, columns, or rows.

```js
const table = await $dataTableUpdate(
  'data-table-id',
  {
    name: 'archived_contacts',
    description: 'Archived contact records',
    visibility: 'owner',
  },
);
```

### Permissions and errors

Read helpers require access to the data table. Row mutations and table management operations require management access. Permissions are evaluated for the user who triggered the flow run.

Unknown columns, incompatible values, invalid conditions, missing filters, and inaccessible resources stop the helper with an error. Use dry-run mode before broad updates or deletions.

See [Data Tables in the Flows guide](/guide/flows#data-tables) for the table editor and [Using Data Tables](/guide/nodal-flows#using-data-tables) for visual nodes.

## AI&#x20;

AI methods require an active [AI integration](/guide/integrations#ai-integrations) and an accessible [AI model](/guide/flows#ai-models). Each configured `AiModel` contains exactly one provider model. Pass its `AiModel.id`, which starts with `aim_`.

### `$mcpClientTool(credentialId, include?, tools?, options?)` {#mcp-client-tool}

Create a toolkit from a stored MCP client credential for use with `$aiMessage` or `$aiControl`. Use `include` and `tools` to restrict the exposed tools. `options.maxToolCalls` limits tool calls and defaults to `20`.

### `$aiMessage(aiModelId, message, options?)` {#ai-message}

Send a text prompt through the provider model configured on an `AiModel`.

```js
const response = await $aiMessage(
  'ai-model-id',
  'Summarize the current invoice',
  {
    system: 'Answer in one sentence.',
    messages: [
      { role: 'user', content: 'The customer prefers concise answers.' },
    ],
    temperature: 0.2,
    top_p: 1,
    max_tokens: 200,
    timeout: 120000,
    outputMode: 'text',
  },
);

console.log(response.text);
```

| Parameter | Description |
| --- | --- |
| `aiModelId` | Configured `AiModel.id`, starting with `aim_`. |
| `message` | Current user message. |
| `options.system` | System instructions. |
| `options.messages` | Previous `{ role, content }` messages. Roles are `user`, `assistant`, or `system`. |
| `options.temperature` | Provider sampling temperature. |
| `options.top_p` | Provider nucleus sampling probability. |
| `options.max_tokens` | Maximum output tokens. |
| `options.timeout` | Request timeout in milliseconds. Default: `120000`. |
| `options.outputMode` | `text`, `json`, or `schema`. Default: `text`. |
| `options.schema` | JSON Schema. Supplying it selects `schema` mode unless `outputMode` is `text`. |
| `options.maxToolCalls` | Maximum MCP tool calls, from 1 to 100. Default: `20`. |

The response contains `text`, provider `content`, `usage`, `model`, `finishReason`, and `provider`. In `json` or `schema` mode it also contains parsed `json`, or `null` when the text is not valid JSON. Structured output availability depends on the selected AI model.

### `$aiControl(aiModelId, prompt, options?)` {#ai-control}

Repeatedly capture the current browser viewport, ask a vision-capable model for the next restricted action, validate that action, and execute it.

```js
const result = await $aiControl(
  'ai-model-id',
  'Submit the completed checkout form',
  {
    maxIterations: 10,
    timeout: 120000,
    screenshotQuality: 65,
    persistScreenshots: false,
    maxTokens: 4000,
    temperature: 0.1,
    allowPuppeteerFallback: true,
  },
);
```

| Option | Default | Description |
| --- | --- | --- |
| `maxIterations` | `10` | Maximum screenshot and action cycles, from 1 to 50. |
| `timeout` | `120000` | Overall timeout in milliseconds, from 5000 to 900000. |
| `screenshotQuality` | `65` | JPEG quality, from 20 to 90. |
| `persistScreenshots` | `false` | Save each decision screenshot as a run artifact. |
| `maxTokens` | `4000` | Maximum output tokens for each decision, from 4000 to 32000. |
| `temperature` | provider default | Sampling temperature for each decision. It is not sent unless specified. |
| `maxToolCalls` | `20` | Maximum MCP tool calls, from 1 to 100. |
| `allowPuppeteerFallback` | `true` | Allow restricted Puppeteer actions after a Puppetflow action fails and coordinate clicks for purely visual targets. |

The result contains:

| Field | Description |
| --- | --- |
| `status` | `success`, `error`, or `max_iterations`. |
| `message` | Final model or execution message. |
| `result` | Optional value returned by the model's finish action. |
| `iterations` | Number of screenshot and decision cycles used. |
| `actions` | Validated actions and their execution results. Values entered into fields are redacted from this log. |
| `model` | AI model that produced the result. |
| `usage` | Provider usage information when available. |

The generated program is limited to Puppetflow navigation, click, fill, scroll, wait, shadow DOM, and finish actions. It cannot run arbitrary page code.

Puppeteer fallback has the same restrictions. It is normally available only after a Pupp