Use the CLI
Trigger tasks, inspect runs, and operate workers from your terminal.
With createLocalLane(), runlane dev owns the runs in its memory. The app, CLI, and worker reach that store over a loopback bridge: a token-protected connection that only accepts traffic from your own machine (127.0.0.1). The app never keeps runs in its own memory. Without dev, the first trigger or read fails with storage_unavailable. Start dev and retry; no app restart is needed.
Use @runlane/cli for local workers, maintenance, triggers, run inspection, and operator actions. The CLI loads your app runtime. It does not own another task or lane setup.
Install and create the config
npm install --save-dev @runlane/cli
npm exec -- runlane init config \
--runtime ./src/runlane.ts \
--runtime-export runlaneThis writes runlane.config.ts with the same exported runtime your app uses. The CLI loads TypeScript configs with its packaged tsx loader. Local commands do not need an app prebuild.
The CLI does not load .env files itself. Load them before constructing the runtime, either from your runtime module or the CLI config. See load environment variables for the CLI.
Use --config <path> when the config is not one of the default runlane.config.* files.
Operate a deployed environment
Keep a separate config for production. Point it at a runtime module built from your deployed settings. That module must select the deployed lane, environment, queues, and task catalog rather than the local dev lane.
import { ErrorCode, RunlaneError } from '@runlane/core'
import { runlane } from './src/runlane.production.js'
if (!runlane.lane.capabilities.productionDurable) {
throw new RunlaneError({
code: ErrorCode.ConfigurationInvalid,
message: 'Production commands require a durable lane.',
})
}
export default { runtime: runlane }Supply settings through the shell or your secret manager before loading this module. The CLI does not read .env files. If storage is private, open network access first, such as a tunnel, and configure the runtime's connection accordingly.
Operator commands change production state. Check the selected environment with a read before running cancel, retry, rerun, queue, or schedule writes:
runlane --config runlane.production.config.ts runs list --json
runlane --config runlane.production.config.ts runs get <run-id> --json
runlane --config runlane.production.config.ts cancel <run-id> --reason customer_requestThe config selects the whole runtime; there is no CLI storage override. Use a producer catalog for reads and triggers when handlers are not needed. Worker commands require executable tasks.
Generate frontend types
When your frontend lives in another repository, run this command from the backend application directory:
runlane types --out src/runlane-types.tsThe command loads the runtime from runlane.config.ts and reads its registered tasks catalog. It converts each task's output and declared stream schemas into standalone TypeScript declarations. Use Zod 4.2+, ArkType 2.1.28+, or Valibot through @valibot/to-json-schema so the schemas expose Standard JSON Schema conversion.
Copy the generated file into the frontend and commit it there. Install @runlane/realtime in that frontend; React consumers also need @runlane/react. Import a generated type with import type:
import { useRun, useRunStream } from '@runlane/react'
import type { AnswerWrite } from './runlane-types'
const { run } = useRun<AnswerWrite>(runId)
const { parts } = useRunStream<AnswerWrite>(runId, 'answer')This example assumes the backend registers answer.write with an answer stream. With several stream types, use useRunStream<AnswerWrite, 'answer'> for the exact part type. Wrap the component in a RunlaneProvider.
Regenerate and copy the file whenever the backend schemas change. The file contains types only; it does not bundle backend code or validate values in the browser. Output is byte-identical for the same catalog, and the destination is replaced atomically only after all tasks convert.
--out <file> selects the destination. Add --config <path> to select a config or --json for { "types": { "path": "<file>", "tasks": 3 } }. A missing catalog, unsupported converter, failed conversion, or type-name collision exits non-zero without replacing the file. Errors name the affected task and field or both sources of a name collision. See the CLI reference for all options and errors.
Run local development
Run one maintenance pass, drain currently due work, and exit:
npm exec -- runlane dev --onceFor a long-lived local process, run:
npm exec -- runlane devWith a local lane, keep that process running. Start your app in a second terminal with its usual command. App servers, scripts, and CLI commands create their normal runtimes; their local lanes share the dev process's in-memory store through an authenticated loopback storage bridge:
npm exec -- runlane trigger email.send-welcome '{"email":"ada@example.com"}'
npm exec -- runlane runs listDiscovery uses the nearest default runlane.config.*, searching upward from each process's working directory. The default order is .ts, .mts, .mjs, .js, then .cjs. The project key is the absolute config path, and the lane name must match. A CLI --config <path> keys by that exact path. App processes must find the same default config; an arbitrary custom filename cannot be discovered automatically. Without a config file, use the same working directory and the default runlane.config.ts path.
Lane creation performs no file or network I/O and starts no worker. Before connecting, each storage operation looks for dev. Without a live session, it fails with storage_unavailable, names the config path, and says to start runlane dev. A failed lookup is not cached: retrying after dev starts connects in the same app process. Tests use createTestLane() with drain() or executeNext() instead.
If dev stops, connected lanes fail with storage_unavailable and tell you to restart dev. After a restart, later operations reconnect to fresh memory; old runs are gone. Task edits reload automatically without clearing local runs. Only the dev host keeps its store in-process. Other local lanes always use the bridge. runlane work adds a worker against that same store; it cannot replace dev as the store owner.
The bridge binds only to 127.0.0.1. Config-keyed session files live under the OS temp directory in the env-paths folder for runlane-cli. On POSIX systems, discovery rejects symlinked or foreign-owned session folders and files, and requires folder mode 0700 and file mode 0600. Remove an untrusted path and restart dev as your user. Windows keeps its existing discovery behavior without POSIX ownership or mode checks. Its token and session file are user-private, and one dev owner holds the config lock until worker and runtime cleanup finish. Local mode is for Node.js development, not serverless or edge deployment.
For complete browser apps, see set up realtime and frontend types.
To create a run now but start it later, pass an ISO 8601 timestamp with --run-at. First set a future time, such as one hour from now:
export RUN_AT="$(node -p 'new Date(Date.now() + 60 * 60 * 1000).toISOString()')"
export START_BEFORE="$(node -p 'new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()')"npm exec -- runlane trigger email.send-welcome '{"email":"ada@example.com"}' \
--run-at "$RUN_AT"Choose a future time for your operation; a past time is immediately eligible. Keep the worker and maintenance running. Confirm the saved time with runlane runs get <run-id>. Repeating an idempotent trigger does not change the original run's time.
To reject a late first start, add --start-before "$START_BEFORE". The deadline is exclusive and absolute, independent of --run-at. Maintenance records expired if no attempt started in time; it does not stop a task that already started. runs get shows the saved deadline. Use --start-expiry-limit <count> with tick or dev to bound each expiry pass. See start expiry before deploying the coordinated storage upgrade.
After completing the priority upgrade and enabling priorityBoost on the selected queue, add --priority high or --priority low to a trigger. normal is also accepted. The default comes from contractDefaults.run.priority. runs get shows stored non-normal priority. The CLI uses your runtime's queue policy; the flag cannot enable priority by itself.
Submit a batch file
Create a JSON array in batch.json using registered task IDs:
[
{
"taskId": "email.send-welcome",
"payload": { "email": "ada@example.com" },
"options": { "idempotencyKey": "welcome.ada" }
}
]npm exec -- runlane trigger-batch --file batch.json --chunk-concurrency 2 --json
npm exec -- runlane runs list --batch <batch-id> --jsonThe response contains batchId and positional outcomes: { ok: true, run, outcome, deliveryError? } for an accepted position or { ok: false, error } for a rejected one. Per-item options use the scalar trigger command's camel-case names. The shared item bound is contractDefaults.trigger.maxBatchItems; --chunk-concurrency bounds concurrent backend chunks. Each chunk is atomic, and earlier chunks remain accepted if a later chunk fails. An empty file array still gets an identity. See batch submission before retrying a failed response.
Batch lists require creation order. Keep the same batch and filters while following cursors, including cursors returned with empty filtered pages.
Operate known runs
npm exec -- runlane runs get <run-id> --events
npm exec -- runlane cancel <run-id> --reason customer_request
npm exec -- runlane retry <failed-run-id>
npm exec -- runlane rerun <terminal-run-id>runs get shows stored debounce delay as debounce delay ms. It shows tags only when the run has labels.
Add the global --json option for machine-readable output. runlane work starts the configured lane's delivery worker: it polls storage with Local or Postgres polling, and consumes SQS messages with Postgres and SQS. Pass --maintenance to also run maintenance services in the same process. Use runlane tick for one maintenance pass. Run maintenance explains production ownership and scheduling.
A command that cannot load the config reports configuration_invalid with the attempted path. Verify the runtime module specifier and export name first. An unknown task means the runtime's named tasks catalog does not contain the requested task id.
Operate queues
npm exec -- runlane --json queues pause billing
npm exec -- runlane --json queues resume billing
npm exec -- runlane --json queues limit billing --total 10 --per-key 2
npm exec -- runlane --json queues limit billing --concurrency-key account.123 --per-key 1
npm exec -- runlane --json queues reset-limit billing --concurrency-key account.123
npm exec -- runlane --json queues get billinglimit replaces the entire queue override, including bounds and expiry. It does not merge: queues limit billing --total 4 removes a saved perKey override and expiry. With --concurrency-key, it replaces only that key's override, including expiry. Repeat every bound and expiry you want to keep.
limit accepts --expires-at <iso> for a future storage-time expiry. A keyed limit rejects --total and requires --per-key. Other queue operations reject --total, --per-key, and --expires-at; the error names the flag and the operation that accepts it. reset-limit without --concurrency-key clears only the queue override. get accepts --concurrency-key to include that key's override. All queue commands return { queue: QueueState } in JSON mode and use the same local storage bridge. See queue operations for exact precedence and admission behavior.
Override the worker lease
runlane work uses lease.duration from the runtime loaded by your CLI config. If the runtime omits it, Runlane uses contractDefaults.lease.duration. Override it for one command with --lease-duration:
runlane work --lease-duration 30s--heartbeat-interval must be shorter than the effective lease. Without that flag, the heartbeat defaults to one third of the effective lease. Refresh intervals are capped by contractDefaults.lease.maxRefreshIntervalMs. See recover from worker crashes.
When a worker takes over an expired lease, the CLI reports the abandoned attempt as interrupted. When an event's attempt start time is unavailable, the CLI omits the duration in text and the durationMs field in JSON.
Inspect deployment versions
runlane --version prints the CLI package version. The run filter uses your application's runtime version.
Use runlane runs list --version <version> to page visible started runs by baseline. This filter requires --sort-by created_at or the default sort. Follow cursors through empty filtered pages. Inspect unstarted scheduled and queued work separately.
runlane runs get <run-id> shows the baseline from the saved run. Add --events for a bounded timeline; started rows show the baseline and actual worker version, and patch rows show saved decisions. --limit and --cursor apply only to this timeline. JSON includes the events page and its nextCursor. Without --events, the command makes no event queries. See deploy task changes.
runlane runs get <run-id> shows current hook status, its update time, each callback's attempts, and bounded last failures. hooks: failed means callback delivery exhausted its retry budget; the run's terminal outcome remains unchanged.
Manage schedules
pnpm exec runlane schedules create --task emails.send --cron '0 9 * * 1-5' --time-zone America/New_York --payload '{"userId":"user-123"}' --deduplication-key user-123.weekday-mail
pnpm exec runlane schedules update runtime_schedule_ID --task emails.send --every 24h --payload '{"userId":"user-123"}'
pnpm exec runlane --json schedules get runtime_schedule_ID
pnpm exec runlane --json schedules list --task-id emails.send --limit 20
pnpm exec runlane schedules deactivate runtime_schedule_ID
pnpm exec runlane schedules activate runtime_schedule_ID
pnpm exec runlane schedules delete runtime_schedule_IDReplace task and schedule IDs with your registered task and returned schedule ID. Timing flags are --cron with optional --time-zone, --every with optional --starts-at/--ends-at, or --run-at. Dates use ISO format. Writes also accept --queue, --external-id, --deduplication-key, and --no-active. Update replaces the full definition.
All commands support the global --json option. Reads show source and effective active. Lists accept --task-id, --external-id, --limit, and --cursor; JSON includes schedules.data and optional schedules.nextCursor. Declarations come first by ID, then runtime definitions by creation time/ID. Continue through empty filtered pages while a cursor remains. Activate/deactivate also control locally declared schedules; update/delete require runtime schedules.
Read named output
npm exec -- runlane --json runs stream <run-id> answer
npm exec -- runlane --json runs stream <run-id> answer --after <cursor> --follow--after resumes the named reader checkpoint. --follow keeps polling until the terminal run and its retained stream tail drain, or the CLI signal aborts. Terminal task failure remains output data. Missing runs and invalid cursors fail the command. See streams.
Read logs and a causal timeline
runs logs shows captured task console output and context.logger entries. Console capture is on by default, still prints normally, and records the run's attempt number. Prefer context.logger for structured attributes. To disable capture, set logs: { captureConsole: false } in createRunlane(); the default comes from contractDefaults.logs.captureConsole. See task logs for formatting, limits, and failure behavior.
npm exec -- runlane runs logs <run-id> --limit 50 --json
npm exec -- runlane runs logs <run-id> --after <log-cursor> --follow
npm exec -- runlane runs timeline <run-id> --after <timeline-cursor> --limit 50 --jsonLogs and timeline return records, cursor, and hasMore. Each reader has its own cursor kind. Follow hasMore through empty pages. Log follow uses lane push hints when available and the contractDefaults.streams.pollInterval fallback otherwise, ending after terminal state and the drained attempt-log tail, or signal abort. Later hook logs need another read or follow. A failed task remains output data; missing runs and invalid cursors fail the command.
Timeline events stay in sequence order, with attempt-written records between their known events. Stream entries summarize consecutive positions without loading chunks. Read full records with runs stream. Hook state is captured current state, and partially pruned runs are labelled. See debug a run.
Reload task code
The dev parent owns the local store, bridge, session, watcher, signals, and output. Task code and maintenance run in a child worker. After the old child finishes its attempts and exits, the new child starts work. This also applies with --no-watch. dev --once runs its one pass in a child without watching. Embedded CLIs with a custom loadRuntime stay in-process without watch.
runlane dev watches the config and every local module it imports, including task helpers. It ignores node_modules. Files read at runtime with fs and .env files are not watched; restart dev after changing those files. Use --no-watch to disable reloads. runlane work and dev --once do not watch.
On a save, dev loads the new code in a child worker before stopping acquisition in the old worker. Invalid code prints an error and leaves the old worker running until the next valid save. Running attempts finish on the old code without a shutdown deadline or abort. Dev reports dev_reloading after the old worker acknowledges that acquisition has stopped. Runs triggered after that event wait for the replacement worker and use the new code. The store, bridge, and session stay alive, so app triggers remain accepted during the wait and saved runs remain readable. Changing the lane name requires a dev restart. Long waits list the running run IDs about every ten seconds.
JSON mode emits dev_reloading, dev_reload_waiting, dev_reloaded, and dev_reload_failed. An unexpected child exit emits dev_worker_crashed with its code and signal. Dev keeps its store and waits for a save to restart the worker; it does not restart in a loop.
Stop a worker
The first Ctrl+C or SIGTERM stops acquisition and waits for running attempts. A second Ctrl+C stops at once. Duplicate launcher signals within a short window count as one shutdown request. Configure grace per command:
runlane work --shutdown-grace 20s
runlane dev --shutdown-grace 20sThe default comes from contractDefaults.worker.shutdownGrace. The shutdown line reports the grace and running attempt count. JSON mode emits a structured worker_shutting_down record. An attempt that errors after the shutdown abort is shown as interrupted; it is queued again without spending retry budget. See shut down cleanly. Local dev's in-memory runs are lost when its process exits.