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

# Steps and Functions

> Save versioned Python automation, run it in a fresh sandbox, and read its results and logs.

## Steps

A routine runs its steps in order. Inputs can come from the trigger, stored scheduled values, or previous step outputs. Choose supported actions from the action catalog; see the [step kinds](https://docs.mobilerun.ai/routines#step-kinds) for an overview.

A device script (`scripts.run`) is distinct from an uploaded Serverless Function (`functions.run`). Loops can repeat steps, but nested loops and task steps inside loops are rejected. Nested steps cannot currently be edited in the routine builder.

### Save files (`files.upload`)

Use the **Upload file** step (`files.upload`) to save content produced by earlier steps to
Mobilerun storage: a function's result, a report, or bytes from a screenshot or app capture.
It does not upload to Google Drive or OneDrive, and it needs no phone of its own.

| Parameter | Required | What to pass |
| - | - | - |
| `filename` | Yes | One file name, up to 255 characters, without path separators. |
| `content` | Yes | Text or a template resolving to text, an object, or an array. Objects and arrays are serialized as JSON. |
| `mimeType` | No | Content type; defaults to `application/json` for objects/arrays and `application/octet-stream` for strings. |
| `contentEncoding` | No | `utf8` (default) or `base64` for string content; ignored for objects/arrays. Use base64 for binary image bytes. |

Pass the actual content, not a local path or a download URL. Empty content is rejected; the
encoded file must be at most 50 MiB. A `.json` file must contain one complete JSON value, without
prose or Markdown fences.

This [routine document](https://docs.mobilerun.ai/routines/documents.md) runs an existing function and saves its result as
JSON. Replace the function ID with a ready function you own; adapt `input` to its schema.

```yaml YAML theme={null}
$schema: https://api.mobilerun.ai/v1/flows/document-schema
version: 1
name: Save a function report
on:
  custom: {}
steps:
  - id: compute
    uses: functions.run
    with:
      functionId: 11111111-1111-4111-8111-111111111111
      version: latest
      input: {}
  - id: save
    uses: files.upload
    with:
      filename: report.json
      mimeType: application/json
      content: "{{steps.compute.body.result}}"
settings:
  delivery:
    destination: mobilerun
    folder: /Reports/{{meta.today}}
```

The step returns `fileId`, `filename`, `mimeType`, `sizeBytes`, and `zone: workflow` in its output.
To keep a durable **routine file**, choose **Delivery → Mobilerun storage** and supply a folder,
as above. Live runs copy their `files.upload` outputs into that folder; this copy can finish
after the run's steps. A successful upload step does not by itself confirm that the saved copy is ready.

Files go directly into the configured folder, with the step's filename; no execution subfolder
is added. Folder templates are resolved once per run. Here, `meta.today` groups reports by date;
files retain their own IDs and `executionId`, even when names repeat. Recordings and screenshots
selected in Delivery can be saved there too, without an extra upload step.

Saved files use your [storage allowance](https://docs.mobilerun.ai/credits.md#storage). They stay until you delete them or
their routine; there is no fixed expiry for ready saved copies. See
[Find and download files](https://docs.mobilerun.ai/routines/runs.md#find-and-download-files) to retrieve or remove them.

## Serverless Functions

[Source on GitHub](https://github.com/droidrun/mobilerun-functions)

A Serverless Function is saved, versioned Python code with typed inputs and returns, executed in a fresh sandbox. Use it for repeatable code, a [task](https://docs.mobilerun.ai/tasks.md) for an agent instruction, or a [sandbox](https://docs.mobilerun.ai/sandboxes.md) for an interactive session. Create it in the dashboard or API, run it directly or in a routine, then read its result and logs.

## How it works

```mermaid theme={null}
%%{init: {"flowchart": {"rankSpacing": 18, "nodeSpacing": 14}}}%%
flowchart TD
  A[Python source + manifest] --> B[Upload and inspect]
  B --> C[Immutable ready version]
  C --> D[Run directly]
  C --> E[Routine step]
  C --> F[Agent invokes function]
  D --> G[Fresh sandbox]
  E --> G
  F --> G
  G --> H[Result + logs]
```

1. Write a Python file and declare any network hosts, credentials, and scopes in its manifest.
2. Upload it. Inspection checks the code and discovers its input and output schemas; only a `ready` version can run.
3. Run directly, attach the function to a routine, or ask the agent to use it. Each run executes a version in an isolated sandbox.
4. Read the result and logs. To change the code or manifest, upload a new immutable version.

## Write a function

Keep the code in one `.py` file: adjacent helper modules are not uploaded. Save the [greeting example](https://docs.mobilerun.ai/agents/functions.md#install-and-create-a-function) as `hello.py`; the requests below pass `{"name":"Ada"}` and receive a greeting in the result.

Use exactly one bare `@script` entry point, with a Pydantic input model and a supported return annotation: a Pydantic output model, optional output, `None`, or a dataset. See [Writing Serverless Functions](https://docs.mobilerun.ai/agents/functions.md) for the Python format, device access, and package availability.

The optional upload `manifest` contains `hosts` (exact allowed hostnames), `credentials` (objects with `packageName` and `name`), and `scopes` (permission names). These default to empty lists; the greeting needs none. Supply the manifest as JSON alongside `source`, rather than as a second code file. Keep secrets out of source, inputs, returns, and logs.

## Create it

**1. Open Functions**

In **Routines**, choose **Manage functions** to open the **Serverless Functions** tab.
Open Functions

**2. Upload your code**

Choose **Upload function** and select your `.py` file.

**3. Check the contract**

Select the function to inspect **Code**, **Inputs & returns**, and **Runs**. Wait for its version to be ready before running it.

### Upload through the API

All requests use your [API key](https://docs.mobilerun.ai/api-keys.md). TypeScript and Python examples require SDK 6.3.1 or later.

Through the API, upload source as JSON, with a required `Idempotency-Key`. A new function returns `201` with its stable ID in `data.id` and its first version in `data.latestVersion`.

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

const mobilerun = new MobilerunSDK();

const { data: fn } = await mobilerun.api.compute.functions.create({
  name: 'hello', source: await readFile('hello.py', 'utf8'),
}, { headers: { 'Idempotency-Key': crypto.randomUUID() } });
console.log(fn.id, fn.latestVersion);
```

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

mobilerun = MobilerunSDK()

fn = mobilerun.api.compute.functions.create(
    name="hello", source=Path("hello.py").read_text(), idempotency_key=str(uuid4()),
).data
print(fn.id, fn.latest_version)
```

```bash cURL theme={null}
jq -n --rawfile source hello.py '{name:"hello",source:$source}' > upload.json
curl --fail-with-body https://api.mobilerun.ai/v1/compute/functions \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  --data-binary @upload.json
```

A version starts at `pending_inspection`, then becomes `ready` or `rejected`. Poll `GET /v1/compute/functions/{functionId}/versions/{version}` and run only a ready version. For rejection details, inspect `inspectError`; fix the source and upload a new version.

For a source-only check, send `source` and optional `manifest` to `POST /v1/compute/functions/validations?waitS=25` with an `Idempotency-Key` header. If the response is still `pending`, poll `GET /v1/compute/functions/validations/{validationId}`. Validation reports errors and warnings without saving a function; it does not prove success against a live app.

## Run it

Open the function and choose **Run** to enter its input in **Run function**. In the API, choose a version or omit it for the latest ready version. `waitS` controls how long the HTTP request waits, independently of `timeoutS`.

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

const mobilerun = new MobilerunSDK();

const functionId = 'FUNCTION_ID';
const { data: run } = await mobilerun.api.compute.functions.runs.create(
  functionId,
  { input: { name: 'Ada' }, timeoutS: 60, waitS: 30 },
  { headers: { 'Idempotency-Key': crypto.randomUUID() } },
);
console.log(run.id, run.status, run.result);
```

```python Python theme={null}
from uuid import uuid4
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()

function_id = "FUNCTION_ID"
run = mobilerun.api.compute.functions.runs.create(
    function_id,
    input={"name": "Ada"}, timeout_s=60, wait_s=30, idempotency_key=str(uuid4()),
).data
print(run.id, run.status, run.result)
```

```bash cURL theme={null}
curl --fail-with-body \
  "https://api.mobilerun.ai/v1/compute/functions/$FUNCTION_ID/runs" \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"input":{"name":"Ada"},"timeoutS":60,"waitS":30}'
```

A `200` response contains a finished run; `202` means it is still running. Poll `GET /v1/compute/runs/{runId}?waitS=30` for its result, or request cancellation with `POST /v1/compute/runs/{runId}/cancel`. A completed run's `outcome` tells you whether it succeeded, partially succeeded, or failed; inspect `errorCode` on failure.

### Read results and logs

List runs with `GET /v1/compute/functions/{functionId}/runs`, or `GET /v1/compute/runs?functionId={functionId}`. List items omit `input`, `result`, `stdout`, and `stderr`; read an individual run for those fields.

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

const mobilerun = new MobilerunSDK();

const handle = mobilerun.compute.runs.fromId('RUN_ID');
const { data: run } = await handle.refresh({ waitS: 30 });
console.log(run.status, run.outcome, run.result, run.errorCode);
await handle.waitLogs();
const logs = await handle.logs();
console.log(logs.data.url);
```

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

mobilerun = MobilerunSDK()

handle = mobilerun.compute.runs.from_id("RUN_ID")
run = handle.refresh(wait_s=30).data
print(run.status, run.outcome, run.result, run.error_code)
handle.wait_logs()
logs = handle.logs()
print(logs.data.url)
```

```bash cURL theme={null}
curl --fail-with-body   "https://api.mobilerun.ai/v1/compute/runs/$RUN_ID?waitS=30"   -H "Authorization: Bearer $MOBILERUN_API_KEY"
# When the run's logs field is available:
curl --fail-with-body   "https://api.mobilerun.ai/v1/compute/runs/$RUN_ID/logs"   -H "Authorization: Bearer $MOBILERUN_API_KEY"
```

The log route returns `url`, `expiresAt`, and `sizeBytes`, rather than file bytes. Download from `url`; request a new link when it expires. `waitLogs()` (Python `wait_logs()`) waits until the log is ready. For cURL, the log link can return `404` with `logs_not_available` for a few seconds after the run ends.

## Use it in a routine

Add a Serverless Function as one of the ordered steps in a [routine](https://docs.mobilerun.ai/routines). Its [trigger](https://docs.mobilerun.ai/routines/triggers.md) decides when the steps run; app, device, and platform event triggers are **Soon**. Choose the function and its input as a routine step; use the newest ready version or pin a version number. Follow [Working with routines](https://docs.mobilerun.ai/routines) for setup, verification, and execution results.

## Versions

A function has a stable ID; each uploaded version has immutable source and manifest. In the dashboard, choose **Edit**, then **Save as new version**. Through the API, send `source` and optional `manifest` to `POST /v1/compute/functions/{functionId}/versions` with an `Idempotency-Key` header. Wait for the new version to become `ready`.

Read version metadata with `GET /v1/compute/functions/{functionId}/versions/{version}`. Read code with `GET /v1/compute/functions/{functionId}/source?version=1`; omit `version` for the latest ready version.

## Limits

| Limit | Value |
| - | - |
| Direct run timeout | 1–300 seconds. |
| Direct run concurrency | 1 per organization. |
| Direct run daily allowance | 900 seconds per day. |
| Direct run starts | 30 per hour. |
| Minimum counted duration | 10 seconds per started direct run. |
| Function source | 1 MiB per version. |
| Inline stdout/stderr | Tail of up to 16 KiB each; check `truncated`. |
| Direct run log retention | Seven days; download links expire after five minutes. |
| Outbound requests | 100 per 10 seconds per run; excess requests receive `429` and `Retry-After: 10`. |

Function steps in routines have a separate timeout: see [function step limits](https://docs.mobilerun.ai/agents/functions.md#limits). External requests must use HTTPS on the default port and match an allowed hostname exactly; redirect targets are not followed automatically. Mobilerun API access uses platform-controlled credentials and permissions.

## Cost

Functions use function minutes and concurrent-run capacity. Direct runs have the allowance and minimum counted duration above. See [Credits & usage](https://docs.mobilerun.ai/credits.md) for usage and pricing.


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