Docs

Route commands to a Worker and a Daemon

This example builds two services in one customer deployment that answer the same commands: named calls your backend makes into the deployment, with no admin port and no inbound connection. Each call names a target, which picks the service that answers.

Architecture diagram. Left: Your cloud, Your backend, CommandsClient. Right: Customer cloud containing Deployment containing api (Worker); indexer-daemon (Daemon); index (KV).

Commands name their target. Alien pushes them to the Worker; the Daemon leases them over outbound HTTPS.

You build:

  • An api Worker (serverless code) and an indexer-daemon Daemon (a long-lived process) that both expose status and search.
  • A shared KV index the Daemon fills and both services read.
  • A sender script, standing in for your backend, that calls each target by name.

Source: examples/command-routing-ts. See Commands for how delivery works.

Why route by target

An admin endpoint on each service needs a reachable port, authentication on every endpoint, and a firewall rule per service for the customer's security team to approve.

Commands avoid all three. Your backend names the deployment, the target resource, and the command; Alien delivers it and returns the result.

Command names only need to be unique within a target, so related services can each expose status. Once a deployment has more than one command-capable resource, every call must name its target. An untargeted call fails with COMMAND_TARGET_AMBIGUOUS, even for a command only one resource registers.

ResourceKindHow it receives commandsstatus returns
apiWorkerPushed to it. Handlers registered with command() from @alienplatform/sdkrole: "worker", model: "push"
indexer-daemonDaemonLeases them over outbound HTTPS with createCommandReceiver() from @alienplatform/commandsrole: "daemon", model: "pull"

Project layout

The stack declaration in alien.ts is next; the handlers live under services/.

command-routing-ts/
├── alien.ts                     # the stack: index KV, api Worker, indexer-daemon
├── shared/scan-all.ts           # KV helpers both services use
└── services/
    ├── api/src/index.ts         # Worker: push handlers + a Hono HTTP app
    ├── indexer/src/index.ts     # Daemon: seeds the index, pull receiver
    └── sender/src/index.ts      # client script, not deployed

services/sender stands in for your backend. It isn't part of the stack.

Stack

Start with the shared index. It's a frozen KV resource: the customer's admin creates it during initial setup (the one-time step they run with their own credentials), and a release can't replace or delete it. See Frozen and live.

alien.ts
// Shared index the daemon maintains and both resources report on.
const index = new alien.Kv("index").build()

The Worker serves an HTTP app and the commands. .commandsEnabled(true) makes it a command target:

alien.ts
// Worker: HTTP + the `status`/`search` commands via the SDK push registrar.
const api = new alien.Worker("api")
  .code({ type: "source", src: "./services/api", toolchain: { type: "typescript" } })
  .commandsEnabled(true)
  .publicEndpoint("api")
  .link(index)
  .permissions("execution")
  .build()

The Daemon is a resident process. It does the background indexing work and registers the same command names:

alien.ts
// Daemon: a resident process that leases the SAME command names through the
// pull receiver and serves them from its own view of the index.
const indexer = new alien.Daemon("indexer-daemon")
  .code({ type: "source", src: "./services/indexer", toolchain: { type: "typescript" } })
  .commandsEnabled(true)
  .link(index)
  .permissions("execution")
  .build()

The stack adds all three and grants both services read and write access to KV through one permission profile:

alien.ts
export default new alien.Stack("command-routing")
  .platforms(["local", "aws", "gcp", "azure", "kubernetes"])
  .add(index, "frozen")
  .add(api, "live")
  .add(indexer, "live")
  .permissions({
    profiles: {
      execution: {
        "*": ["kv/data-read", "kv/data-write"],
      },
    },
  })
  .build()

"*" applies the sets to every resource of their type in the stack. Here the only KV is index.

Both services are "live": Alien replaces them on every release, without the admin.

Worker handlers

A Worker registers commands with command() from @alienplatform/sdk. The Worker runtime receives each invocation and calls your handler, so there's no receive loop.

services/api/src/index.ts
import { command, kv } from "@alienplatform/sdk"
import { Hono } from "hono"
import { z } from "zod"
import { countDocs, searchIndex } from "../../../shared/scan-all"

const RESOURCE = "api"

// Overlapping command #1: `status`. The Worker answers from the request that
// was pushed to it, so `role` is "worker".
command("status", async () => ({
  resource: RESOURCE,
  role: "worker",
  model: "push",
  documents: await countDocs(kv("index")),
  at: new Date().toISOString(),
}))

// Overlapping command #2: `search`. Reads the shared index the daemon builds.
command("search", z.object({ term: z.string() }), async ({ term }) => ({
  resource: RESOURCE,
  term,
  hits: await searchIndex(kv("index"), term),
}))

search passes a zod schema. The runtime validates the input before your handler runs, so term is typed as a string inside it.

The same file exports a normal HTTP app next to the commands:

services/api/src/index.ts
const app = new Hono()
app.get("/health", c => c.json({ status: "ok", resource: RESOURCE }))
app.get("/status", async c =>
  c.json({ resource: RESOURCE, documents: await countDocs(kv("index")) }),
)

export default app

Daemon receiver

A Daemon has no Worker runtime in front of it, so nothing can push into it. It runs a receiver from @alienplatform/commands that leases its own commands over outbound HTTPS.

First, the background work that makes this a Daemon. It writes four documents into the shared index every 30 seconds:

services/indexer/src/index.ts
const SEED_DOCS: Record<string, string> = {
  "getting-started": "How to deploy your first Alien stack",
  commands: "Invoke commands on a deployment by target resource id",
  bindings: "Storage, kv, queue, and vault bindings run in-process",
  daemons: "A daemon is a resident process that leases commands",
}

// Background work that justifies this being a daemon: keep the shared index
// populated. In a real agent this would crawl a source; here it seeds a handful
// of documents the `search` command (on either resource) can read.
async function buildIndex(signal: AbortSignal): Promise<void> {
  while (!signal.aborted) {
    for (const [id, text] of Object.entries(SEED_DOCS)) {
      await index.set(`doc:${id}`, text)
    }
    await new Promise(resolve => setTimeout(resolve, 30_000))
  }
}

The Daemon reads KV through kv() from @alienplatform/bindings. The binding runs in-process and calls DynamoDB, Firestore, or Table Storage directly with the Daemon's own identity.

Then the receiver registers the same two names:

services/indexer/src/index.ts
const receiver = createCommandReceiver()

// Overlapping command #1: `status`. Answered by the daemon, so `role` is
// "daemon" and `model` is "pull".
receiver.command("status", async () => ({
  resource: RESOURCE,
  role: "daemon",
  model: "pull",
  documents: await countDocs(index),
  at: new Date().toISOString(),
}))

// Overlapping command #2: `search`, reading the index this daemon maintains.
receiver.command("search", async input => {
  if (
    typeof input !== "object" ||
    input === null ||
    !("term" in input) ||
    typeof input.term !== "string"
  ) {
    throw new TypeError("term must be a string")
  }
  const { term } = input
  return { resource: RESOURCE, term, hits: await searchIndex(index, term) }
})

receiver.command() takes no schema, so this handler checks its input by hand. A thrown error is returned to the caller as a failed command.

Finally, start the receiver from an async function:

services/indexer/src/index.ts
// A source-built daemon compiles to a single binary that embeds the bindings
// native addon, which requires a CommonJS bundle, and CommonJS forbids
// top-level await. Drive the receiver from an async entry point instead.
async function main(): Promise<void> {
  await receiver.run()
  controller.abort()
}

void main()

createCommandReceiver() reads its identity and credentials from the ALIEN_COMMANDS_* environment variables that .commandsEnabled(true) injects. Its defaults:

  • Polls for work every 5 seconds.
  • Holds one lease at a time, for 60 seconds.
  • On shutdown, stops polling, waits up to 30 seconds for running handlers, then returns, which stops the indexing loop.

Delivery is at least once. If a Daemon dies while holding a lease, the command is delivered again after the lease expires, so keep handlers safe to run twice.

Shared KV helpers

Both services count and search the index the same way, so the helpers live in shared/. scan() returns one page at a time; scanAll follows the cursor until the last page:

shared/scan-all.ts
/** Iterate every key under a prefix, following the scan cursor across pages. */
export async function* scanAll(store: KvScanStore, prefix: string) {
  let cursor: string | undefined
  do {
    const page = await store.scan(prefix, undefined, cursor)
    for (const item of page.items) yield item
    cursor = page.nextCursor
  } while (cursor)
}

searchIndex does a case-insensitive substring match and returns document IDs without the doc: prefix. Both services read the same index, so a search sent to the Worker sees the documents the Daemon wrote.

Calls from your backend

The sender creates one CommandsClient per deployment and calls status on each target:

services/sender/src/index.ts
const client = new CommandsClient({
  managerUrl: required("ALIEN_MANAGER_URL"),
  deploymentId: required("ALIEN_DEPLOYMENT_ID"),
  token: required("ALIEN_TOKEN"),
})

// Same command name, two targets, two senders.
const workerStatus = await client.target("api").invoke<Status>("status", {})
const daemonStatus = await client.target("indexer-daemon").invoke<Status>("status", {})

.target(name) returns a client that sets the target resource on every invoke. The script then checks that the two answers differ, and runs a search through the Worker:

services/sender/src/index.ts
// The routing is only meaningful if the two targets answered differently.
if (workerStatus.role === daemonStatus.role) {
  throw new Error(
    `expected the two targets to answer distinctly, but both returned role="${workerStatus.role}"`,
  )
}

// A search reads the shared index the daemon builds; either target can serve it.
const workerHits = await client.target("api").invoke("search", { term: "command" })

invoke creates the command, then polls for the result, starting at 500 ms and backing off to 5 seconds. It throws CommandTimeoutError after 60 seconds by default; pass { timeoutMs } to the client or to one call to change that.

Run it locally

This example isn't an alien init template. Clone the repository and install from the examples workspace, which links the Alien packages from the same checkout:

git clone https://github.com/alienplatform/alien.git
cd alien/examples
pnpm install
cd command-routing-ts

Start the local deployment and write its status to a file:

alien dev --status-file .alien/dev-status.json

alien dev starts a local manager on port 9090, builds both services, and runs them as local processes. The KV is a local SQLite file.

In a second terminal, point the sender at the local deployment. The local manager accepts any token:

ALIEN_MANAGER_URL=$(jq -r '.agents.default.commandsUrl' .alien/dev-status.json) \
ALIEN_DEPLOYMENT_ID=$(jq -r '.agents.default.id' .alien/dev-status.json) \
ALIEN_TOKEN=dev \
  bun services/sender/src/index.ts

The output shows the same command answered by two resources:

api            -> { resource: 'api', role: 'worker', model: 'push', documents: 4, at: '…' }
indexer-daemon -> { resource: 'indexer-daemon', role: 'daemon', model: 'pull', documents: 4, at: '…' }
search via api -> { resource: 'api', term: 'command', hits: [ 'commands', 'daemons' ] }
routing verified: overlapping `status` resolved by target

documents is 4 once the Daemon has seeded the index, a few seconds after startup. Earlier, the Worker may report 0.

From the CLI, name the resource with --target. Without it, the call fails with COMMAND_TARGET_AMBIGUOUS, because two resources handle status:

alien dev commands invoke --deployment local-dev/default --command status --target api
alien dev commands invoke --deployment local-dev/default --command status --target indexer-daemon

Test it

In a test with @alienplatform/testing, pass target to invokeCommand:

const worker = await deployment.invokeCommand("status", {}, { target: "api" })
const daemon = await deployment.invokeCommand("status", {}, { target: "indexer-daemon" })
expect(worker.role).toBe("worker")
expect(daemon.role).toBe("daemon")

Alien's own end-to-end suite runs this example and checks that:

  • Each target answers with its own role and model.
  • An untargeted status fails with COMMAND_TARGET_AMBIGUOUS.
  • A search for resident through the Worker returns exactly ["daemons"], a document the Daemon wrote.

Deploy to a customer

Release the stack and onboard a customer, as in the quickstart. The customer's admin runs the initial setup once; later releases arrive without them.

alien release
alien onboard customer-1 --allow admin@customer-1.com

In production, your backend doesn't hold a deployment token (the credential a deployment uses to reach Alien). Create the client from the deployment ID and a server-side API key; Alien finds the deployment's manager and issues short-lived, command-only access:

backend/status.ts
import { CommandsClient } from "@alienplatform/commands"

const commands = await CommandsClient.forDeployment({
  deploymentId: customer.deploymentId,
  apiKey: process.env.ALIEN_API_KEY!,
})

const status = await commands.target("indexer-daemon").invoke("status", {})

Create the key with alien api-keys create --for deployments. Reuse the client: it refreshes its access before it expires.

How it runs on each platform

How a command reaches its target depends on the resource kind, not on the command:

Platformapi Workerindexer-daemon Daemonindex KV
AWSLambda, invoked asynchronouslyOne process per EC2 machine in the ComputeClusterDynamoDB table
Google CloudCloud Run, through a Pub/Sub topicOne process per Compute Engine machineFirestore collection
AzureContainer Apps, through Service BusOne process per VMTable Storage table
KubernetesDeployment; the Operator (Alien's process in the cluster) leases the command and passes it to the WorkerDaemonSetExternal binding the customer supplies
LocalLocal process, called over HTTPLocal processSQLite file

The Daemon always leases, so it never needs an inbound route on any platform.

On AWS, Google Cloud, and Azure, a Daemon runs on every machine of its ComputeCluster. Each lease goes to one receiver, so a command still runs once per delivery. Each copy also runs the seeding loop; the writes are idempotent, so that's harmless here.

For Workers in pull deployments, the Operator in the customer's environment leases the command and hands it to the Worker. Your handler code is the same either way.

What to change for production

  • Remove the public endpoint. The api Worker has .publicEndpoint("api") for its HTTP routes. If your backend only needs commands, drop it.
  • Give each service its own profile. Both share execution with read and write on KV. The Worker only reads the index, so give it a profile with kv/data-read only. See Permissions.
  • Validate Daemon inputs with a schema. The receiver handler checks term by hand. Use zod or another validator there too, and return only the fields your backend needs.
  • Make handlers idempotent. Commands are delivered at least once. Pass an idempotencyKey when a retried create must not run twice.
  • Set timeouts. Pick a timeoutMs that fits each command instead of the 60-second default.

Adapt it

Prompt
Use the alien command-routing-ts example (github.com/alienplatform/alien/tree/main/examples/command-routing-ts) as a model. In my backend, add a small module that looks up a customer's deployment ID, creates a client with CommandsClient.forDeployment from @alienplatform/commands, and invokes the commands my deployment exposes with .target(resource).invoke(name, params). Keep the API key server-side and add timeouts and error handling. Read https://alien.dev/docs/guide/commands.md and https://alien.dev/docs/deployment-ux/deploy-button.md first.

Next

On this page