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

# Routine documents

> Copy, edit, check, and save a whole routine as YAML or JSON in Cloud or through the API.

A routine document is one text describing a whole routine: its trigger, devices, ordered steps, and settings. YAML and JSON describe the same object. The API calls a routine a **flow** and accepts JSON on the wire.

## Quick start

**1. Copy a template**

Copy the YAML from [Run manually](#run-manually) below. It works without resource IDs or input.

**2. Paste it into Cloud**

Open **Routines** → **New routine**, enter a **Name**, and choose **Create routine**. Open that routine’s **Steps** → **Document** → **Edit**, choose **YAML**, and replace the text with your template. For an existing routine, this replaces its configuration.
Open Routines

**3. Check and save**

Choose **Check**, fix any listed issues, then **Save**. A check does not run the steps. Use [Test run](https://docs.mobilerun.ai/routines/runs.md) before enabling recurring work. Prefer code? Save the JSON as `routine.json` and use the [create call](#create-from-a-document).

## Copy a template

The first four templates need no resource IDs. Each YAML/JSON pair is identical. Document creation starts disabled; saving over an existing routine preserves its enabled state.

### Run manually

No placeholders or input required. Create it, then use **Run now** to save a short note.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Save a note
on:
  custom: {}
steps:
  - id: save
    uses: files.upload
    with:
      filename: note.txt
      mimeType: text/plain
      content: Hello from my routine
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "Save a note",
  "on": {
    "custom": {}
  },
  "steps": [
    {
      "id": "save",
      "uses": "files.upload",
      "with": {
        "filename": "note.txt",
        "mimeType": "text/plain",
        "content": "Hello from my routine"
      }
    }
  ]
}
```

### Schedule with cron

Runs daily at 09:00 in Amsterdam. Check a real run before enabling it.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Daily note
on:
  schedule:
    cron: 0 9 * * *
    timezone: Europe/Amsterdam
steps:
  - id: save
    uses: files.upload
    with:
      filename: note.txt
      mimeType: text/plain
      content: Hello from my routine
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "Daily note",
  "on": {
    "schedule": {
      "cron": "0 9 * * *",
      "timezone": "Europe/Amsterdam"
    }
  },
  "steps": [
    {
      "id": "save",
      "uses": "files.upload",
      "with": {
        "filename": "note.txt",
        "mimeType": "text/plain",
        "content": "Hello from my routine"
      }
    }
  ]
}
```

### Schedule once

Runs once at the UTC time shown. Choose a future time before enabling it.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: One-time note
on:
  schedule:
    once: 2027-01-15T09:00:00Z
steps:
  - id: save
    uses: files.upload
    with:
      filename: note.txt
      mimeType: text/plain
      content: Hello from my routine
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "One-time note",
  "on": {
    "schedule": {
      "once": "2027-01-15T09:00:00Z"
    }
  },
  "steps": [
    {
      "id": "save",
      "uses": "files.upload",
      "with": {
        "filename": "note.txt",
        "mimeType": "text/plain",
        "content": "Hello from my routine"
      }
    }
  ]
}
```

### Custom trigger via API

Accepts a text input. After creation, use the returned flow’s `triggerId` in the [custom fire call](https://docs.mobilerun.ai/routines/triggers.md#custom-trigger), with `payload: { text: "My note" }`.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Save input text
on:
  custom:
    inputs:
      type: object
      properties:
        text:
          type: string
      required:
        - text
steps:
  - id: save
    uses: files.upload
    with:
      filename: note.txt
      content: "{{event.payload.text}}"
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "Save input text",
  "on": {
    "custom": {
      "inputs": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string"
          }
        },
        "required": [
          "text"
        ]
      }
    }
  },
  "steps": [
    {
      "id": "save",
      "uses": "files.upload",
      "with": {
        "filename": "note.txt",
        "content": "{{event.payload.text}}"
      }
    }
  ]
}
```

### Serverless Function

Replace `11111111-1111-4111-8111-111111111111` (`FUNCTION_ID`) with your [ready Serverless Function](https://docs.mobilerun.ai/routines/functions.md). This template assumes it accepts an empty input object; adapt `input` to its manifest.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Run my function
on:
  custom: {}
steps:
  - id: compute
    uses: functions.run
    with:
      functionId: 11111111-1111-4111-8111-111111111111
      version: latest
      input: {}
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "Run my function",
  "on": {
    "custom": {}
  },
  "steps": [
    {
      "id": "compute",
      "uses": "functions.run",
      "with": {
        "functionId": "11111111-1111-4111-8111-111111111111",
        "version": "latest",
        "input": {}
      }
    }
  ]
}
```

### Agent task

Replace `22222222-2222-4222-8222-222222222222` (`DEVICE_ID`) with a device you own. A real run uses device minutes and AI credits.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Read the open screen
on:
  custom: {}
steps:
  - id: inspect
    uses: tasks.run
    with:
      task: Read the open screen and summarize what is visible.
devices:
  - 22222222-2222-4222-8222-222222222222
```

```json JSON theme={null}
{
  "$schema": "https://api.mobilerun.ai/v1/flows/document-schema",
  "version": 1,
  "name": "Read the open screen",
  "on": {
    "custom": {}
  },
  "steps": [
    {
      "id": "inspect",
      "uses": "tasks.run",
      "with": {
        "task": "Read the open screen and summarize what is visible."
      }
    }
  ],
  "devices": [
    "22222222-2222-4222-8222-222222222222"
  ]
}
```

## View, copy, download, and edit in Cloud

**1. Open the document**

Open **Routines**, select a routine, then **Steps** → **Document**. YAML appears first; choose **JSON** to switch formats. **Copy** copies the displayed text; **Download** saves it as a file.

**2. Edit and check**

Choose **Edit**, select **YAML** or **JSON**, and change the text. **Check** validates without saving or executing. A successful check shows **The document is valid.** Errors identify the field and what to fix.

**3. Save the whole document**

**Save** replaces the routine’s document configuration and returns to reading. **Discard changes** abandons edits. If the routine changed elsewhere, use **Reload and discard my edits** before trying again. If the format cannot represent the routine, choose **Edit in Builder**.

## Through the API or SDK

Use your [API key](https://docs.mobilerun.ai/api-keys.md). These examples use the typed HTTP methods in `@mobilerun/sdk` and `mobilerun-sdk` **6.3.0**. Save a template’s JSON as `routine.json`; for YAML, parse it with a YAML 1.2 parser and send the resulting JSON object. All write bodies wrap it as `{ "document": ... }`.

### Export

`GET /v1/flows/{flowId}/document` returns the canonical document in `data`, including defaults, settings, and scheduled inputs.

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';
import { writeFileSync } from 'node:fs';

const mobilerun = new MobilerunSDK();
const exported = await mobilerun.api.workflows.flows.retrieveDocument('FLOW_ID');
writeFileSync('routine.json', JSON.stringify(exported.data, null, 2));
```

```python Python theme={null}
import json
from pathlib import Path
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()
exported = mobilerun.api.workflows.flows.retrieve_document("FLOW_ID")
Path("routine.json").write_text(json.dumps(exported.data, indent=2))
```

```bash cURL theme={null}
curl --fail-with-body "https://api.mobilerun.ai/v1/flows/$FLOW_ID/document" \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" | jq '.data' > routine.json
```

### Validate

`POST /v1/flows/document/validate` checks without writing or running. A `200` response can have `data.valid: false`: inspect `errors` and `warnings`. Errors contain `code`, `field` (a JSON Pointer), `message`, and `repair` hints. An empty pointer means the document root.

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';
import { readFileSync } from 'node:fs';

const mobilerun = new MobilerunSDK();
const document = JSON.parse(readFileSync('routine.json', 'utf8'));
const checked = await mobilerun.api.workflows.flows.validateDocument({ document });
console.log(checked.data.valid, checked.data.errors, checked.data.warnings);
```

```python Python theme={null}
import json
from pathlib import Path
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()
document = json.loads(Path("routine.json").read_text())
checked = mobilerun.api.workflows.flows.validate_document(document=document)
print(checked.data.valid, checked.data.errors, checked.data.warnings)
```

```bash cURL theme={null}
curl --fail-with-body https://api.mobilerun.ai/v1/flows/document/validate \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  --data "$(jq -c '{document: .}' routine.json)"
```

### Create from a document

`POST /v1/flows/document` creates the trigger, steps, and disabled routine together. The `201` response contains `data.flow` and `data.document`. Reuse the same optional idempotency key and unchanged document when retrying creation. Check a [real verification run before activation](https://docs.mobilerun.ai/routines/runs.md#enable).

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';
import { readFileSync } from 'node:fs';

const mobilerun = new MobilerunSDK();
const document = JSON.parse(readFileSync('routine.json', 'utf8'));
const created = await mobilerun.api.workflows.flows.createFromDocument(
  { document }, { headers: { 'Idempotency-Key': 'create-note-1' } },
);
console.log(created.data.flow.id, created.data.flow.enabled);
```

```python Python theme={null}
import json
from pathlib import Path
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()
document = json.loads(Path("routine.json").read_text())
created = mobilerun.api.workflows.flows.create_from_document(
    document=document, idempotency_key="create-note-1",
)
print(created.data.flow.id, created.data.flow.enabled)
```

```bash cURL theme={null}
curl --fail-with-body https://api.mobilerun.ai/v1/flows/document \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: create-note-1' \
  --data "$(jq -c '{document: .}' routine.json)"
```

### Replace

`PUT /v1/flows/{flowId}/document` atomically replaces the whole document, not a patch. Enabled state is preserved. Omitted description, devices, and trigger options clear those values. Omitted `settings` preserves stored settings; a supplied `settings` object replaces them, defaulting omitted fields. A successful response contains `data.flow` and `data.document`.

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';
import { readFileSync } from 'node:fs';

const mobilerun = new MobilerunSDK();
const document = JSON.parse(readFileSync('routine.json', 'utf8'));
const replaced = await mobilerun.api.workflows.flows.replaceDocument('FLOW_ID', { document });
console.log(replaced.data.flow.id);
```

```python Python theme={null}
import json
from pathlib import Path
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()
document = json.loads(Path("routine.json").read_text())
replaced = mobilerun.api.workflows.flows.replace_document("FLOW_ID", document=document)
print(replaced.data.flow.id)
```

```bash cURL theme={null}
curl --fail-with-body -X PUT "https://api.mobilerun.ai/v1/flows/$FLOW_ID/document" \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  --data "$(jq -c '{document: .}' routine.json)"
```

Agent-managed routines require a new version deployed through the agent. Replacement also refuses shared triggers or a deployment in progress. A failed replacement leaves the routine unchanged.

## Editor setup

The schema URL is `https://api.mobilerun.ai/v1/flows/document-schema`. It returns raw JSON Schema **2020-12**, without a `data` envelope. Fetching it requires an API key, including from an editor. If your editor cannot attach an authorization header, download it once:

```bash theme={null}
curl --fail-with-body https://api.mobilerun.ai/v1/flows/document-schema -H "Authorization: Bearer $MOBILERUN_API_KEY" -o routine-schema.json
```

Keep the schema next to your document. For a JSON editor that supports `$schema`, use `"$schema": "./routine-schema.json"` while editing. For YAML Language Server (including the VS Code YAML extension), add:

```yaml theme={null}
# yaml-language-server: $schema=./routine-schema.json
```

Before submitting JSON, restore `$schema` to the API URL shown in the templates, or remove the property: the backend accepts only that URL. The YAML comment is editor-only and does not enter the JSON request. Refresh the downloaded schema when available steps change.

For agent authoring, download `https://api.mobilerun.ai/v1/flows/document-schema?profile=agent_routine` instead. It lists only agent-eligible steps; it is guidance, and backend validation remains authoritative. Step branches specify `uses`, `with`, and `x-mobilerun-output`. Do not invent step names.

## Field reference

Document-owned objects reject unknown fields. A step’s `with` follows the selected step’s parameter schema.

| Field | Meaning |
| - | - |
| `$schema` | Optional on input; the API schema URL above. Always included on export. |
| `version` | Required; `1`. |
| `name` | Required, 1–256 characters; also names the trigger. |
| `description` | Optional, up to 2,048 characters; omission on replace clears it. |
| `on` | Exactly one of `custom`, `schedule`, or `event` (**Soon**). See [Triggers](https://docs.mobilerun.ai/routines/triggers.md) for snippets. |
| `on.custom.inputs` | Optional payload JSON Schema draft-07 without `$ref`. |
| `on.schedule` | Exactly one of `cron`, `once`, or `rrule`; optional IANA `timezone`, `jitter`, `inputs`, and `values`. |
| `on.schedule.inputs` / `values` | Input JSON Schema draft-07 without `$ref`, and stored values satisfying it (maximum 1 MiB JSON). Steps read `event.payload`; request overrides are ignored for scheduled runs. |
| `devices` | Up to 256 distinct device UUIDs you own; omitted means none, including on replace. |
| `steps` | Nonempty array in execution order. |
| `steps[].id` | Unique stable key; follow the schema’s pattern and reserved-name restrictions. |
| `steps[].uses` | Public step name from the schema (catalog `stepName`). |
| `steps[].name` | Optional trimmed display name, 1–256 characters; defaults to the step ID. |
| `steps[].with` | Step parameters; defaults to `{}`. Required parameters still need values. |
| `settings.delivery` | Delivery destination and options from the schema; defaults to no delivery. Disconnected destinations warn during validation but must pass connection checks on writes. |
| `settings.recording` | `mode`: `off` (default), `flow`, or `steps`. For `steps`, supply unique existing step IDs in `steps`. |
| `settings.health` | `monitoring` defaults to true; `selfHealing` defaults to monitoring; `maxAttempts` is 1–5 (default 2). Self-healing requires monitoring. |
| `settings.cooldown` | Nonnegative integer `seconds` (omitted means no cooldown), `scope`: `flow` (default) or `device`. |
| `settings.ownerWake` | `final` (default) or `off`. |

Read inputs with `{{event.payload.text}}` and earlier results with `{{steps.save.body.fileId}}`. A whole template preserves its JSON type; interpolation in a longer string produces text. These are paths, not general expressions.

## Common errors

| Code or exact message | What to change |
| - | - |
| `document_invalid`: `Unknown field: <key>` | Remove the unknown key or use the field name in the schema. If the key is `true` instead of `on`, switch to a YAML 1.2 parser. |
| `Invalid cron expression: expected 5 valid fields (minute hour dom month dow)` | Use five cron fields, such as `0 9 * * *`. |
| `Provide exactly one of cron, once or rrule` | Keep only one schedule rule. |
| `Provide exactly one of schedule, event or custom` | Keep exactly one trigger under `on`. |
| `params_invalid` | Follow the step’s `with` schema and the error’s field pointer; supply required parameters and correct their types. |
| `The document must be an object.` | Paste one document object, not an array or a scalar. |
| `The document has a number that JSON cannot carry (.inf, -.inf or .nan).` | Replace the YAML value with a finite number. This is a Cloud text error before the API call. |
| `document_unsupported` | Use **Edit in Builder** or the regular flow API for stored behavior outside document v1. |
| `routine_agent_managed` | Ask the agent to deploy a new routine version. |
| `trigger_shared` | Use a separate trigger for this routine before replacing its document. |
| `idempotency_key_reused` | Retry the unchanged creation with the same key, or use a fresh key for a new creation. |

## Limits and gotchas

* Use YAML **1.2**. A YAML 1.1 parser may read the key `on` as boolean `true`. JSON is the API wire format; non-finite YAML numbers cannot be sent.
* Check validates configuration; it does not execute steps or prove a live result.
* Document v1 is an authoring format, not a backup of every flow setting. Unsupported behavior, including loops, child steps, and continue-on-error, cannot be exported or replaced through it.
* When replacing settings, include every setting you want to keep. `settings: {}` restores defaults; omitting `settings` preserves them.


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