Airpost
Plugins

Service plugins

Run plugin logic in the background as a separate program on the engine socket, also while the desktop app is closed.

Logic that must run while the desktop is closed, such as sending something at a set time or acting on new mail, goes in a service: a separate program on the engine socket, run by launchd on macOS or systemd --user on Linux. No plugin code runs inside the engine.

A service is a program that runs at login with your user’s rights and the engine’s local methods, whether Airpost is open or not. Airpost shows what will run before installing it and records its hash, but that is information, not a sandbox.

Declaring a service

A plugin declares its service in package.json:

{
  "name": "my-plugin",
  "version": "1.0.0",
  "engines": { "airpost": "^1.27.0" },
  "airpost": {
    "service": {
      "bin": { "darwin-arm64": "bin/mac/my-service", "linux-x64": "bin/linux/my-service" },
      "args": ["--quiet"]
    }
  }
}
  • airpost.service.bin is a path inside the package, or an object keyed by Node’s <platform>-<arch>: darwin-arm64, darwin-x64, linux-x64, linux-arm64.
  • airpost.service.args is an optional list of arguments.

A plugin can have both a service and a main with UI, or only a service.

Installing

In Preferences > Plugins, a plugin with a service offers Set up service…. Before anything is written it shows the binary, its SHA-256, the copy it will run and the exact unit text. The install refuses a binary whose hash changed in between. From a terminal:

airpost service install my-plugin --dry-run   # show what would be written
airpost service install my-plugin
airpost service list
airpost service uninstall my-plugin

See Services for the command reference.

Installing copies the binary to <profile>/services/<package>/, and the unit runs that copy. So:

  • The binary must be self-contained: a compiled program, or a single script.
  • Updating the plugin changes nothing until the service is installed again.

Source, binary, hash and unit are recorded in <profile>/services.json.

The runtime environment

The unit sets two environment variables:

VariableValue
AIRPOST_CONFIG_DIRThe profile directory
AIRPOST_SERVICE_PACKAGEThe package name, which is also the plugin id for its metadata

The engine’s own unit (serve --detached) is installed first if it is missing. On systemd the service starts after the engine; launchd has no start order, so your service must wait for the engine’s socket and reconnect when the engine restarts. Units restart after a failed exit, not after a clean one.

Getting work

  • Due work: give a thread or message plugin metadata with an expiration (a Unix timestamp). When it comes due, the engine sends metadata-expiration deltas for your plugin id on every scan until you clear the expiration.
  • New mail: mail.new notifications.
  • Lists: metadata.list.

Rust services use crates/airpost-client to find the engine and crates/airpost-ipc for the protocol types. Services in other languages speak JSON-RPC 2.0 over newline-delimited JSON on <profile>/run/engine.sock.

The sample service

examples/service-plugin in the repository is a complete “remind me” plugin: when a thread’s airpost-sample-service metadata reaches its expiration, the service stars the thread, marks it unread and clears the expiration. It connects with airpost_client::Engines::connect, subscribes to Thread and Message deltas, and acts on metadata-expiration rows for its own plugin id.

Build it and put the binary where package.json points:

cargo build --release -p airpost-sample-service
mkdir -p examples/service-plugin/bin
cp target/release/airpost-sample-service examples/service-plugin/bin/

In Airpost, use Preferences > Plugins > Install from a folder…, pick examples/service-plugin, then set up its service. To test it, give a thread a reminder one minute from now, then quit Airpost:

airpost task queue '{"__cls": "SyncbackMetadataTask", "modelId": "<thread id>",
  "modelClassName": "thread", "pluginId": "airpost-sample-service",
  "value": {"expiration": '$(( $(date +%s) + 60 ))'}}'

Its log is <profile>/services/airpost-sample-service/service.log on macOS, and journalctl --user -u airpost-service-airpost-sample-service on Linux. To run it by hand against a running engine:

airpost-sample-service --config-dir <profile>

How the sample works

examples/service-plugin/src/main.rs is about 270 lines, tests included. Its dependencies are airpost-client, airpost-ipc and serde_json (see its Cargo.toml). The parts worth copying:

Options

The unit passes nothing on the command line; the service reads AIRPOST_CONFIG_DIR and AIRPOST_SERVICE_PACKAGE, and accepts --config-dir and --plugin-id for running by hand. Without either, it falls back to airpost_client::discovery::default_config_dir().

Connect, and keep reconnecting

loop {
    let mut engines = Engines::connect(&opts.config_dir, CLIENT_NAME, "airpost-sample-service");
    // A serve engine holds every account, so one engine is the whole profile.
    let Some(engine) = engines.engines.drain(..).next() else {
        // No engine yet: log engines.problems once, sleep, back off up to 30 s.
        std::thread::sleep(retry);
        retry = (retry * 2).min(MAX_RETRY);
        continue;
    };
    retry = Duration::from_secs(1);
    match serve(engine, &opts.plugin_id, &mut handled) {
        Ok(()) => event(json!({"event": "disconnected", "pid": pid})),
        Err(e) => error(&format!("engine pid {pid}: {e}")),
    }
    std::thread::sleep(retry);
}

Engines::connect finds the engine for the profile and does the hello handshake for you. The outer loop is what makes the service survive engine restarts and the missing start order on launchd.

Subscribe to deltas

let params = SubscribeParams {
    accounts: None,
    classes: Some(vec!["Thread".into(), "Message".into()]),
    since: None,
};
engine.client.subscribe(&params)?;
engine.client.set_read_timeout(None)?;
loop {
    let n = engine.client.next_notification()?;
    if n.method == method::DISCONNECT { return Ok(()); }
    if n.method != method::DELTA { continue; }
    let Ok(delta) = serde_json::from_value::<DeltaParams>(n.params) else { continue };
    if delta.kind != "metadata-expiration" { continue; }
    // ...
}

Error handling is trimmed here; the file maps each error to a string. classes limits the deltas to the model classes you care about, and accounts: None means all accounts. A metadata-expiration delta carries the models in model_jsons; each has a metadata array of {pluginId, value, v} rows, including other plugins’ rows, so filter on your own pluginId.

Act once per due row

The engine repeats the delta on every scan until the expiration is cleared, so the sample keeps a HashSet<(model_id, expiration)> and acts only on new pairs. It then queues three tasks with task.queue:

for task in [
    tasks::change_starred(account_id, &threads, true),
    tasks::change_unread(account_id, &threads, true),
    clear, // syncback_thread_metadata or syncback_message_metadata without "expiration"
] {
    engine.client.call(method::TASK_QUEUE, json!({"accountId": account_id, "task": task}))?;
}

airpost_client::tasks builds the metadata tasks (syncback_thread_metadata, syncback_message_metadata). Clearing the expiration (it replaces it with firedAt) is what stops the engine from announcing the row again.

As of this writing the sample doesn’t build: airpost_client::tasks no longer has change_starred or change_unread, because star and read changes moved to the engine’s intents (threads.star, threads.markRead, listed in crates/airpost-ipc/src/lib.rs). cargo build -p airpost-sample-service fails with “not found in tasks” until the example is updated. In your own service, call those intent methods with engine.client.call instead; check their params in crates/airpost-ipc before relying on them.

Logging

Each event is one JSON line on stdout and errors go to stderr; the unit sends both to the log above. Keep that shape if you want the log to be greppable.

Tests

The due() function is pure, so the file tests it directly (once the example builds again):

cargo test -p airpost-sample-service

Writing your own

  1. Copy examples/service-plugin into the workspace (or depend on airpost-client and airpost-ipc from a git checkout) and rename the package in Cargo.toml and package.json.
  2. Change DEFAULT_PLUGIN_ID and the classes you subscribe to.
  3. Replace act() with your logic. Queue changes as tasks; a service never writes to the database.
  4. Build per platform and list each binary under airpost.service.bin.
  5. Install the plugin folder, then run airpost service install <name> --dry-run to check the unit before installing it for real.

If the plugin also has UI, set the metadata from the desktop side with SyncbackMetadataTask (see Plugin API) and let the service act on it.