# Native helpers

Source: https://docs.lightair.app/developers/extend/helpers

> Build a helper program that runs beside Lightair in a sandbox and talks to it in newline-delimited JSON over stdin and stdout, with the helper protocol.

In short:
- A helper is a program in a package, one build per platform, that Lightair starts and keeps running in a sandbox.
- It reads and writes one JSON message per line on stdin and stdout. stderr goes to Lightair's log.
- It answers `hello` with `ready`, says what it adds, and asks Lightair for chat, its methods or a screenshot with `call`.
- Every call is checked against the package's permissions, and its sandbox opens only what they allow.

In the app: Window › Packages

A helper is a package with a `helper` content entry: a program built for each platform it
supports. Lightair starts it when it's installed, switched on and not withdrawn, and keeps it
running. The helper talks to Lightair with the **helper protocol, version 1**: newline-delimited
JSON over its stdin and stdout.

Use a helper when a [script plugin](/developers/extend/script-plugins) isn't enough: a program in
another language, a device, another app's local server or socket, or work that needs its own
process.

## Declare the helper

```json
{
  "id": "io.github.you.greeter",
  "name": "Greeter",
  "version": "1.0.0",
  "lightair": ">=1.0 <2",
  "licence": "MIT",
  "contents": [
    {
      "kind": "helper",
      "path": "helper",
      "entry": {
        "macos-arm64": "helper/bin/macos-arm64/greeter",
        "macos-x64": "helper/bin/macos-x64/greeter",
        "windows-x64": "helper/bin/windows-x64/greeter.exe"
      }
    }
  ],
  "permissions": ["chat.read", "chat.write"]
}
```

`entry` names the program for each platform, relative to the package's top folder: `macos-arm64`,
`macos-x64`, `windows-x64` or `windows-arm64`. A platform Lightair doesn't know is refused when
the manifest is read. Lightair starts the program for the computer it runs on; with
none for it, the helper doesn't start there.

## How Lightair runs it

- **Starting:** when the package is installed, switched on (it is, after install) and not
  withdrawn. The newest installed version runs. Its switch and settings are in its section of
  **Window › Packages**.
- **Restarting:** if it exits on its own, Lightair starts it again, at most three times in five
  minutes. After that it stays off until the person clicks **Start again**.
- **Stopping:** Lightair sends `stop` and closes stdin; after two seconds it kills the program.
  Exit when either happens. Taking a permission back, a withdrawal, an update, removing the
  package or switching it off stops it, and starts the right version again within a second.
- **Output:** stdout carries the protocol only. Write logs to stderr: each line goes to Lightair's
  log, under the package's name.
- **Its folder:** its working folder and `HOME` are its own data folder,
  `<Lightair's data>/PackageData/<package id>/`, the only place it may write. The same path comes
  in `hello` as `data_dir`. `LIGHTAIR_PACKAGE` holds its package id.

## Messages

Every message is one line of JSON with a `t`, its type. Requests carry an `id`, and the answer is
a `reply` with the same `id`. Lightair's ids are numbers; a helper's may be any JSON value.

### From Lightair

| `t` | Fields | What it means |
|---|---|---|
| `hello` | `version` (1), `lightair` `{ version }`, `package` `{ id, version }`, `data_dir`, `granted` (its permissions), `settings` (its settings' values) | The first line. Answer with `ready`. |
| `settings` | `values` | The person changed its settings. |
| `command` | `id`, `command` | The person ran one of its commands (or [plugins.command](/developers/remote-api/plugins.command) did). Answer with a `reply`; 20 seconds at most. |
| `step` | `id`, `step`, `params` (the step's fields as the automation set them) | An automation reached one of its steps (or [plugins.step](/developers/remote-api/plugins.step) did). Answer with a `reply`, whose `result` is the step's result; 30 seconds at most. |
| `chat` | `event` | A chat message from any platform Lightair reads. Only with `chat.read`, and only messages that arrive after it starts. The event's fields are in [Script plugins](/developers/extend/script-plugins#events). |
| `reply` | `id`, `result`, or `error` `{ code, message }` | The answer to one of its `call`s. |
| `stop` | none | Exit now. |

### From the helper

| `t` | Fields | What it means |
|---|---|---|
| `ready` | `version` (1), `provides` | It's running. `provides` says what it adds. |
| `call` | `id`, `method`, `params` | It asks Lightair for something (below). |
| `reply` | `id`, `result`, or `error` `{ message }` | The answer to a `command` or `step`. |

A helper ignores message types it doesn't know: new ones may be added within version 1.

### What it adds

```json
{
  "t": "ready",
  "version": 1,
  "provides": {
    "commands": [{ "id": "greet", "title": "Say hello" }],
    "steps": [
      {
        "id": "wave",
        "title": "Wave at someone",
        "fields": [{ "key": "who", "label": "Who", "kind": "text", "default": "chat" }]
      }
    ],
    "settings": [
      { "key": "greeting", "label": "Greeting", "kind": "text", "default": "Hi" },
      { "key": "loud", "label": "Loud", "kind": "toggle", "default": false },
      { "key": "style", "label": "Style", "kind": "choice", "options": ["Calm", "Wild"], "default": "Calm" }
    ]
  }
}
```

- **Commands** show in the command palette as "<package name>: <title>".
- **Steps** show in the automations' **Add step** menu as "<package name>: <title>". An
  automation stores one as a call to `plugins.step` with `package`, `step` and the fields.
- **Settings** are drawn in the package's section of **Window › Packages**: `kind` is `text`,
  `number`, `toggle` or `choice` (with `options`). Lightair keeps the values and sends them with
  `hello` and `settings`. A setting with `"secret": true`, or of kind `secret` or `password`, is
  never read or written over the Remote API. For a real key or token, use `secret.set`.

## Calls into Lightair

Each call is checked against the permissions the helper holds **now**. A refusal is a `reply`
with `error.code` `not_allowed`.

| `method` | Needs | Params and result |
|---|---|---|
| `api.call` | `api.call` | `{ method, params }` → the result of any [Remote API](/developers/remote-api/state.get) method, made as the package. `plugins.*` and `chat.send` aren't reachable this way. |
| `chat.send` | `chat.write` | `{ text, platform? }` → sends a chat message. |
| `screen.capture` | `screen.capture` | `{ display?, max_width? }` → `{ image, width, height, display }`: a JPEG, base64, of the display under the pointer (or `display`), at most `max_width` wide (1280 by default, 320 to 1920), with Lightair's own windows blacked out. macOS only; on Windows it answers `unsupported`. |
| `secret.get` | `secrets` | `{ name }` → `{ value }`, `null` when unset. |
| `secret.set` | `secrets` | `{ name, value }` → `{}`. Without `value`, it deletes the secret. Secrets are kept in the system's keychain under the package's id, never in its folder. |
| `notifications.show` | `notifications` | `{ text }` → `{}`: a notice from the plugin, 200 characters at most. |
| `audio.levels` | `audio.levels` | `{}` → `{ tracks: [{ track, name, peak: [l, r], rms: [l, r] }] }`, in dBFS, silence as `null`. |
| `settings.get` | none | `{}` → its settings' values. |
| `permissions.request` | declared in `optional_permissions` | `{ permissions, reason }` → `{ granted }`: the optional permissions it holds after the person answers on a second screen. Waits for the answer, 10 minutes at most. One not declared as optional is refused with `not_optional`. |
| `permissions.release` | none | `{ permissions }` → `{ released }`: gives optional permissions back. |

Other error codes: `unknown_method` for a method Lightair doesn't know, `invalid` for bad
parameters, `failed` when the work itself failed, and `not_ready` while Lightair is starting.

Optional permissions granted while the helper runs are checked at once. Their sandbox rules take
effect the next time it starts.

## A small helper

This helper, in Rust with `serde_json`, adds one command that greets chat with its **Greeting**
setting.

```rust
use std::io::{self, BufRead, Write};

use serde_json::{json, Value};

fn send(out: &mut impl Write, message: Value) -> io::Result<()> {
    writeln!(out, "{message}")?;
    out.flush()
}

fn main() -> io::Result<()> {
    let mut out = io::stdout().lock();
    let mut greeting = String::from("Hi");
    let mut next_call = 0u64;

    for line in io::stdin().lock().lines() {
        let line = line?;
        let Ok(message) = serde_json::from_str::<Value>(&line) else {
            eprintln!("not JSON: {line}");
            continue;
        };
        match message["t"].as_str() {
            Some("hello") | Some("settings") => {
                let values = if message["t"] == "hello" { &message["settings"] } else { &message["values"] };
                if let Some(text) = values["greeting"].as_str() {
                    greeting = text.to_string();
                }
                if message["t"] == "hello" {
                    send(&mut out, json!({
                        "t": "ready",
                        "version": 1,
                        "provides": {
                            "commands": [{ "id": "greet", "title": "Say hello" }],
                            "settings": [{ "key": "greeting", "label": "Greeting", "kind": "text", "default": "Hi" }]
                        }
                    }))?;
                }
            }
            Some("command") => {
                let reply = if message["command"] == "greet" {
                    next_call += 1;
                    send(&mut out, json!({
                        "t": "call", "id": next_call, "method": "chat.send",
                        "params": { "text": greeting }
                    }))?;
                    json!({ "t": "reply", "id": message["id"], "result": { "sent": true } })
                } else {
                    json!({ "t": "reply", "id": message["id"], "error": { "message": "no such command" } })
                };
                send(&mut out, reply)?;
            }
            Some("reply") => {
                if let Some(error) = message.get("error") {
                    eprintln!("call {} failed: {error}", message["id"]);
                }
            }
            Some("stop") => break,
            _ => {}
        }
    }
    Ok(())
}
```

Its manifest needs `chat.write`. Build it for each platform you list in `entry`.

## The sandbox

A helper runs in a sandbox written from its permissions, unless it has full access.

- **Files:** it reads its own package folder and reads and writes its data folder. Nothing else
  of the person's is open to it.
- **Network:** none of its own. With a `network:` permission it gets a proxy, set in
  `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY`, that reaches only its declared hosts. Use an HTTP
  library that honours these variables. Each connection, allowed or refused, shows in the plugin
  activity.
- **Listening:** with `network.listen:<port>`, it listens on the port in `LIGHTAIR_LISTEN_<port>`
  (on Windows it may differ from the declared port: always read the variable). With
  `network.listen:any`, Lightair picks a free port: it listens on `LIGHTAIR_LISTEN_ANY`, and
  others reach it on `LIGHTAIR_LISTEN_ANY_OUTSIDE`.
- **Powers:** the screen, the camera, the microphone, chat and Lightair's methods aren't opened
  in the sandbox. The helper asks Lightair for them over the protocol, where the permission is
  checked.

| | macOS | Windows |
|---|---|---|
| Sandbox | A deny-by-default sandbox profile, started without Lightair's privacy permissions (camera, microphone, screen recording, Accessibility) | An AppContainer of its own, at low integrity, in a job object that caps its memory and CPU and lets it start no other programs |
| Temporary folder | `TMPDIR`, inside its data folder | `TEMP` and `TMP`, inside its data folder |
| `PATH` | `/usr/bin:/bin` | The Windows system folders |
| `screen.capture` call | Yes | No |

**Full access.** A helper that asks for `full-access`, or `full-access:<platform>` for one
platform, runs there as a plain program with the person's own environment and no sandbox. Only
helpers may ask for it, never as an optional permission, and the package shows as running with
full access.

## Build for each platform

`lightair-pack build` makes one `.airpkg` per platform when `entry` names several: each holds the
shared files and that platform's program, named `<name>-<version>-<platform>.airpkg`. See
[Publish a package](/developers/extend/publish).

The catalog's checks read each program and fail it, unless it has full access, when it:

- captures the screen, posts or watches keyboard and mouse input, uses Accessibility to control
  other apps, opens the camera or microphone, reads or writes other processes, or installs
  privileged helpers, login items or launch agents itself;
- on macOS, has an entitlement other than these: `com.apple.security.cs.allow-jit`,
  `com.apple.security.cs.allow-unsigned-executable-memory`,
  `com.apple.security.cs.disable-library-validation`, `com.apple.security.app-sandbox`,
  `com.apple.security.inherit` and `com.apple.security.network.client`.

A macOS program that isn't signed with a Developer ID is noted: sign and notarize it. The helper
is also started in Lightair's own sandbox on macOS and Windows runners, and anything it reaches
outside its permissions fails the check. Every helper then waits for an admin's review before
Lightair's catalog lists it.

## Related

- [Permissions](/developers/extend/permissions)
- [Script plugins](/developers/extend/script-plugins)
- [Publish a package](/developers/extend/publish)
