﻿Run a task on a daemon on another machine, from a script, a CI job, or your
laptop, and get its output and exit code back:

```bash
export RUNWISP_PASSWORD='…'   # the remote daemon's password
runwisp run backup --url https://runwisp.example.com
```

This logs in, starts `backup`, streams its output to your terminal, and exits
with the task's exit code. So `runwisp run backup --url … && ./deploy.sh` stops
when the backup fails. The run is stored in the daemon's history like any
scheduled run.

## What the daemon needs

- **It must be reachable.** The daemon listens on loopback by default. Bind it
  with `--host 0.0.0.0` and turn on [TLS](/configuration/daemon/#tls-tls_cert-tls_key)
  or put it behind a [reverse proxy](/operations/auth/#reverse-proxies). Without
  TLS, the session token and the task output cross the network in plain text.
- **The task must allow manual runs.** That's the default. With
  [`manual_trigger = false`](/configuration/tasks/#manual_trigger), the trigger
  gets `403`.

## With the runwisp CLI

Put the `runwisp` binary on the machine that triggers the task. It doesn't need a
daemon or a data directory there.

```bash
export RUNWISP_URL=https://runwisp.example.com
export RUNWISP_PASSWORD='…'

runwisp run backup                              # wait and stream output
runwisp run export-org-data --param ORG_ID=acme # fill in a parameter
runwisp run backup --detach                     # print the run ID and exit
```

- The CLI caches the session token in your user cache directory
  (`~/.cache/runwisp/` on Linux, `~/Library/Caches/runwisp/` on macOS) and
  reuses it, so frequent triggers skip the login handshake.
- Prefer `RUNWISP_PASSWORD` to `--password`. It keeps the password out of shell
  history and the process list.
- `--json` prints the outcome as one JSON document. All flags are in
  [`runwisp run`](/reference/cli/#runwisp-run).

## With curl

When you can't install the binary, use the REST API. The shortest way is an
[API token](/operations/auth/#api-tokens) (since 1.9). Add one to the daemon's
config, with the value in its environment:

```toml title="runwisp.toml"
[daemon]
api_tokens = ["${RUNWISP_API_TOKEN}"]
```

Then trigger the task with one request:

```bash
curl -sSf -X POST "$RUNWISP_URL/api/tasks/backup/run?wait=true" \
  -H "Authorization: Bearer $RUNWISP_API_TOKEN" | jq '{id, status, endReason, exitCode}'
```

### Logging in with the password

Without a token, log in first. This script needs `curl`, `jq`, and `python3`:

```bash
#!/usr/bin/env bash
# runwisp-trigger.sh TASK: run TASK on a RunWisp daemon and wait for it.
# Needs RUNWISP_URL and RUNWISP_PASSWORD exported.
set -euo pipefail
TASK=$1

# 1. Log in: answer the challenge with PBKDF2-HMAC-SHA256(password, nonce).
NONCE=$(curl -sSf "$RUNWISP_URL/api/auth/challenge" | jq -r .nonce)
RESP=$(python3 -c 'import hashlib, os, sys
print(hashlib.pbkdf2_hmac("sha256", os.environ["RUNWISP_PASSWORD"].encode(),
      sys.argv[1].encode(), 600000).hex())' "$NONCE")
TOKEN=$(curl -sSf -X POST "$RUNWISP_URL/api/auth/login" \
  -H 'Content-Type: application/json' \
  -d "$(jq -nc --arg n "$NONCE" --arg r "$RESP" '{nonce: $n, response: $r}')" \
  | jq -r .token)

# 2. Start the task and wait for it to finish.
RUN=$(curl -sSf -X POST "$RUNWISP_URL/api/tasks/$TASK/run?wait=true" \
  -H "Authorization: Bearer $TOKEN")

jq '{id, status, endReason, exitCode}' <<<"$RUN"
[ "$(jq -r .endReason <<<"$RUN")" = succeeded ]
```

- The response is the run: `id`, `status`, `endReason`, `exitCode`, and more.
  The script exits non-zero unless the run succeeded.
- `wait=true` holds the request open for up to `waitTimeout` seconds (default
  `120`, max `240`). If the run is still going by then, you get it back with
  `status: "running"`.
- The token is valid for 24 hours. Reuse it across calls instead of logging in
  each time, or you'll hit the [rate limit](/operations/auth/#rate-limiting).

### Passing parameters

The examples below send `$TOKEN`: an API token, or the session token from the
login above.

If the task declares [parameters](/concepts/parameters/), send their values in a
[`params`](/configuration/tasks/#params) object:

```bash
curl -sSf -X POST "$RUNWISP_URL/api/tasks/export-org-data/run?wait=true" \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"params": {"ORG_ID": "acme", "--region": "eu", "--include-attachments": "true"}}'
```

The keys are what you declared: the [`env`](/configuration/tasks/#env) or `arg` name, or the `option` or
`flag` token. For each key:

- a string (even `""`) passes that value,
- `null` leaves the parameter out, even if it has a default,
- a missing key uses the declared default.

Values reach your command as arguments or environment variables, never as shell
code.

### Long runs: poll or stream

For runs longer than your HTTP timeout (or your proxy's), start the run without
`wait` and poll it:

```bash
RUN_ID=$(curl -sSf -X POST "$RUNWISP_URL/api/tasks/backup/run" \
  -H "Authorization: Bearer $TOKEN" | jq -r .id)

until [ "$(curl -sSf "$RUNWISP_URL/api/runs/$RUN_ID" \
  -H "Authorization: Bearer $TOKEN" | jq -r .status)" = ended ]; do
  sleep 5
done
```

For live output, follow `GET /api/runs/{id}/log/stream`, a server-sent event
stream with `line` events and a final `done` event. The
[API reference](/api/) has every endpoint.

## Deploy hooks from CI

A deploy hook is a task with no [`cron`](/configuration/tasks/#cron) that your CI starts after a build. Every
deploy is stored as a run with its output and exit code, and anyone can re-run
it from the Web UI or TUI.

```toml title="runwisp.toml"
[tasks.deploy-app]
group       = "Deploys"
description = "Pull the new image, migrate, restart"
on_overlap  = "kill"      # a new deploy replaces one that's still running
keep_for    = "180d"
notify      = ["slack-ops"]
params      = [{ env = "VERSION", required = true }]
hook_tokens = ["${CI_DEPLOY_TOKEN}"]
run = """
cd /srv/app
docker pull "ghcr.io/example/app:$VERSION"
docker run --rm --env-file=/etc/app/migrate.env "ghcr.io/example/app:$VERSION" migrate up
docker tag "ghcr.io/example/app:$VERSION" ghcr.io/example/app:current
docker compose up -d --no-deps app
curl -fsS --max-time 10 https://app.example.com/healthz
"""

[[route]]
match     = { task = "deploy-app", kinds = ["succeeded"] }
notifiers = ["slack-deploys"]
```

- **No `cron`:** the task runs only when triggered. `runwisp list` shows it as
  `(manual)`.
- **[`on_overlap = "kill"`](/configuration/tasks/#on_overlap):** the newest deploy wins. The older run ends as
  `stopped`.
- **[`params`](/configuration/tasks/#params):** CI passes the version to deploy. See
  [`params`](/configuration/tasks/#params).
- **[`hook_tokens`](/configuration/tasks/#hook_tokens):** CI holds a token that
  controls this task only, not the daemon's password.
- **[`notify`](/configuration/tasks/#notify) and `[[route]]`:** `notify` alerts on failures. The route also
  announces successes to the team channel. See
  [`[[route]]`](/configuration/routes/).

In CI, call the task's [hook](/operations/auth/#hooks) with the token. In GitHub
Actions:

```yaml
- name: Deploy
  env:
      DEPLOY_TOKEN: ${{ secrets.RUNWISP_DEPLOY_TOKEN }}
  run: |
      RUN=$(curl -fsS -X POST "https://runwisp.example.com/api/hooks/tasks/deploy-app/run?wait=true&tail=100" \
        -H "Authorization: Bearer $DEPLOY_TOKEN" \
        -H 'Content-Type: application/json' \
        -d '{"params": {"VERSION": "${{ github.sha }}"}}')
      jq -r '.log[].text' <<<"$RUN"
      [ "$(jq -r .endReason <<<"$RUN")" = succeeded ]
```

The step prints the last 100 lines of the deploy's output and fails when the
deploy fails. `wait=true` holds the request for up to 240 seconds; for a longer
deploy, or to stream the output live, run `runwisp run` with the daemon's
password instead:

```yaml
- name: Deploy
  env:
      RUNWISP_URL: https://runwisp.example.com
      RUNWISP_PASSWORD: ${{ secrets.RUNWISP_PASSWORD }}
  run: npx --yes runwisp run deploy-app --param VERSION=${{ github.sha }}
```

To run migrations on their own, use a second manual task with
`on_overlap = "skip"`. Killing a migration halfway is dangerous; with `skip`, a
trigger that arrives while one is running is recorded as `skipped` and doesn't
start.

Secrets the task needs live on the RunWisp host, not in CI. Keep the data
directory and any [`env_file`](/configuration/tasks/#env_file) readable only by
the daemon's user.

## Restart a service from a task that runs as another user

A deploy usually pulls code as the app's user and then restarts the app. A task
with [`user`](/configuration/tasks/#user) can't open the daemon's local socket,
so `runwisp restart shop` inside it fails. Give the service a hook token and
hand the same token to the task:

```toml title="runwisp.toml"
[services.shop]
run         = "node server.js"
working_dir = "/srv/shop"
hook_tokens = [{ token = "${file:/etc/runwisp/shop-restart.token}", allow = ["restart"] }]

[tasks.deploy-shop]
user        = "ops"
working_dir = "/srv/shop"
run = """
git pull
npm ci
runwisp restart shop
"""

[tasks.deploy-shop.env]
RUNWISP_URL = "http://127.0.0.1:9477"

[tasks.deploy-shop.secrets]
RUNWISP_HOOK_TOKEN = "${file:/etc/runwisp/shop-restart.token}"
```

`runwisp start`, `stop`, and `restart` read the token from `RUNWISP_HOOK_TOKEN`
(or `--token`) and send the action to the service's hook at `RUNWISP_URL`
instead of the local socket. The token only restarts `shop`, so the deploy task
gets no other control over the daemon. See
[`runwisp restart`](/reference/cli/#runwisp-restart) for the flags.
