cli

module
v0.2.37 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT

README

altengine CLI (local emulator)

A local emulator for the altengine services — datastore, search, channels, auth, functions, blob and containers — plus a built-in admin console and the MCP endpoint. It lets you develop against the altengine APIs on your machine without connecting to the hosted service. Static sites are served from a directory (dev --static) rather than deployed; automation has no local stand-in — its commands below talk to the hosted service. One static Go binary, no external dependencies (containers need a local Docker daemon).

alt install altlimit/altengine   # via https://github.com/altlimit/alt
altengine dev
# → http://127.0.0.1:9191  (admin console + every emulated data plane)

# or from source:
cd cli && go build -o altengine ./cmd/altengine

Point your SDK/base URL at http://127.0.0.1:9191 and use any Authorization: Bearer <token>.

Deploying functions

deploy talks to the hosted service, not the emulator. It bundles your entry file and everything it imports into a single ES module (the server resolves no imports) and uploads it.

altengine login                      # paste an org API key ('full' access to the instance)
export ALTENGINE_INSTANCE=prod

altengine deploy --name hello ./hello.js       # bundle + deploy + activate
altengine deploy --dry-run ./hello.js          # bundle only, report the size
altengine deploy --minify --no-activate ./hello.js

altengine functions list
altengine functions versions hello
altengine functions rollback --version 3 hello   # `activate` is the same command
altengine functions pull --out hello.js hello
altengine functions delete --version 2 hello     # one stored version; without --version, the function

delete asks first on a terminal; in a script it needs --yes.

altengine login reads the key from stdin (without echo) and saves it, with the service URL, to altengine/credentials.json in your user config directory (0600; ALTENGINE_CREDENTIALS overrides the path). altengine logout removes it. The hosted commands take the key from --key, then ALTENGINE_API_KEY, then the saved file; the URL from --url, then ALTENGINE_URL, then the saved file, then https://api.altengine.net. A URL must be https://; plain http:// is accepted only for localhost, so the key is never sent unencrypted.

Every stored version has its own address, printed by functions versions: {slug}--v{n}-fn hosted, /fn/{instance}--v{n}/{function} against altengine dev. It runs that version's code with the function's current grants, limits and secrets. The instance setting keepVersions (1–50, default 10) is how many versions are kept per function; the active one is always kept, and lowering the setting deletes the excess immediately.

Access is granted per function, in the same service[:instance]=level form an API key uses:

altengine deploy --grants "datastore:appdb=full,search=read" --name hello ./hello.js

Omit --grants and the function keeps the access it already had — a routine redeploy of source never silently strips it. Deploying itself needs full on the functions instance: it replaces the code that runs with that instance's capabilities, so it is more powerful than writing data through them.

Schedules

A function can run on a timer as well as on request. Expressions are five-field cron, in UTC, and you can give more than one:

altengine deploy --schedule "0 3 * * *" --name nightly ./nightly.js
altengine deploy --schedule "0 9 * * 1-5" --schedule "0 12 * * 6" --name digest ./digest.js
altengine deploy --unschedule --name nightly ./nightly.js     # back to HTTP-only

Several expressions are not a convenience — within one expression the hour and day-of-week fields are ANDed, and cron's only OR is the fixed day-of-month/day-of-week rule, so "09:00 on weekdays and 12:00 on Saturday" genuinely cannot be written as one.

Like --grants, omitting --schedule keeps the existing schedules, so deploying code never silently unschedules a job. --unschedule is how you remove them.

A scheduled run arrives as a POST with x-ae-trigger: cron and a body of {"crons": [...], "scheduled_for": <epoch ms>} — crons is always a list, so a function that later gains a second schedule does not see its own payload change shape.

altengine dev runs the same scheduler locally, ticking on the minute. Three behaviours match the hosted service exactly, because getting them wrong locally would be worse than having no local scheduler:

  • One at a time. A run still in flight when the next is due is skipped, not queued — a job never overlaps itself, and one that is permanently slower than its interval does not build a backlog it can never drain.
  • Not on startup. A function runs because its expression came due while the scheduler was watching, not because the process restarted.
  • No retries. A failed run is logged and not retried.

Deploying a site

static hosts your built front end. Point it at your build output DIRECTORY, not a file.

altengine login                             # once; or export ALTENGINE_API_KEY=ae_...
export ALTENGINE_INSTANCE=marketing

npm run build
altengine static deploy ./dist

altengine static info                       # where it lives, which build is live
altengine static list                       # deploy history, * marks the live one
altengine static rollback <deployment-id>   # switch back to an earlier one

Files are hashed locally and only the ones the site does not already have are uploaded, so redeploying a site where one page changed uploads one page.

A deployment is not live until it is activated, which deploy does for you. --no-activate uploads one to publish later — and that publish and a rollback are the same operation. Neither uploads anything, so switching between builds is immediate.

altengine static deploy --message "release 2.1" ./dist
altengine static deploy --dry-run ./dist       # hash and report, upload nothing
altengine static deploy --no-activate ./dist

The label defaults to the current commit, so altengine static list is readable without one.

Each deployment is numbered (v1, v2, …; a number is never reused) and a ready one is served at its own address, {slug}--v{n}-web, with x-robots-tag: noindex. static list prints it. The instance setting keepDeployments (1–50, default 10) is how many are kept; the live one is always kept.

Everything in the directory is deployed, dotfiles included — .well-known/ has to survive, or certificate renewal and app-association files break. A symlink pointing outside the directory is refused rather than followed, since publishing whatever it points at is rarely what was meant.

Serving a site locally

altengine dev --static serves a build output directory the way the hosted service serves a deployment. There is no local deploy step — the directory is read on every request, so a rebuild shows up on the next reload.

altengine dev --static ./dist
# → http://127.0.0.1:9191   API + admin console
# → http://127.0.0.1:9192   the site

The site gets its own port because a generator emits root-absolute URLs (/assets/app.js), which resolve only when the site owns the whole path space — the local stand-in for the hostname it gets when deployed. That also makes the site and the API different origins here, exactly as they are in production, so the app calls the API by its full URL.

  --static ./dist        build output directory to serve
  --static-port 9192     port for the site (default: --port + 1)
  --spa                  serve index.html for unmatched paths

--spa is detected from the directory when you do not pass it, and the startup banner says what was decided and why: one page and no 404.html reads as a client-routed build, anything else as a generated site. Pass --spa or --spa=false to settle it yourself.

Resolution matches the hosted service — directory indexes, /docs → /docs/, clean URLs (/about → /about.html), the SPA shell, then /404.html with a 404 status. Content types come from the same table, and ETags are content hashes, so a reload is a 304.

Two things differ on purpose, both because a developer's browser is the wrong place to get stuck with them: every response is no-cache rather than the year a fingerprinted asset gets when deployed, and the trailing-slash redirect is a 302 rather than a 301. The banner still counts how many assets will be cached for a year once deployed — that number is a build setting, and it is easier to fix before the deploy than after.

The directory need not exist yet: the site answers 404 saying so, and serves the build as soon as it lands.

Deploying a manifest locally

The emulator takes the same Deploy to AltEngine manifest (altengine.json) as the hosted deploy page, with the same rules: instance names from the app name (N, N-<key>, N-<suffix>), ${key} references, {{vars}}, initialConfig only on creation, the one-level config merge that adds to auth settings.allowedOrigins and functions corsOrigins, hash-checked modules and site files, and create / update / adopt / conflict per instance.

altengine dev                                     # in one terminal
altengine dev deploy ./deploy/altengine.json \
  --var board=acme --secret functions/RESEND_KEY=re_123

Or apply it at startup, for npm run setup and smoke tests (exits non-zero on problems):

altengine dev --deploy ./deploy/altengine.json --var board=acme
Flag
--name app App name. Default: the manifest's name. Deploying the same name again is an update.
--var k=v A var value; repeat. Precedence: --var, the manifest URL's query string, the values the install was last deployed with, the default.
--secret key/NAME=value A secret for the functions instance key; repeat. Stored values are kept when left out.
--bind key=instance The existing instance a uses entry means. Default: the previous binding, else suggest.
--adopt Take over existing instances with the app's names that no deployed app manages.
--confirm-escalation, --confirm-source Allow an update that asks for more access, or that comes from another host.
--dry-run Print the plan; change nothing.
--url, --json The emulator (default http://127.0.0.1:9191); print the response as JSON.

The manifest is a file path or an http(s) URL; plain http only to this machine. Relative URLs resolve against the file's directory or the URL. The CLI calls POST /__deploy, which answers loopback callers only and takes { manifest, name?, vars?, secrets?: {key: {NAME: value}}, bindings?, adopt?, confirmEscalation?, confirmSource?, dryRun? }. It returns { plan, result?, error? }.

Install records are in <data>/deploys.json: owned instance ids, bindings, vars, the applied manifest's sha256, its source and each site's port.

Static instances. The emulator has no static service, so each one is a site served on a port of its own, assigned once and kept: the first takes --port + 1 (or --static-port; the next port up when --static uses it), and every site opens on its port again at startup. ${key:url} is http://127.0.0.1:<port>/; for functions it is http://127.0.0.1:9191/fn/<name>/. A file manifest's site is served live from its base directory, so a rebuild shows on reload and files the manifest does not list are served too; a URL manifest's files are downloaded to <data>/sites/. The runtimeConfig file is served from memory, never written into your build; its api is the emulator's URL, so keep the same --port or deploy again after changing it.

Differences from hosted: there are no roles, quotas or custom domains; a config value is checked by the step that writes it rather than in the plan; functions are activated one after another after all are stored, not in one switch; vars.*.pattern uses Go regular expressions (no lookaround); and auth allowedOrigins is stored but not enforced, as every loopback origin is allowed locally.

Automation

automation deploys scripts to an automation instance's enrolled machines, starts runs and reads what they produced. It talks to the hosted service; the emulator has no automation plane. Enrolling machines and minting enrollment tokens happen in the console.

altengine login
export ALTENGINE_AUTOMATION_INSTANCE=fleet      # or --instance; falls back to ALTENGINE_INSTANCE

altengine automation deploy --name nightly ./nightly.js   # bundle + upload + make live
altengine automation deploy --parallel ./scrape.js        # browsers/HTTP only: may share a machine
altengine automation scripts                              # every script, live version, mode
altengine automation scripts nightly                      # one script's versions, * = live
altengine automation activate --version 3 nightly         # `rollback` is the same command
altengine automation delete nightly

altengine automation agents [--q text]          # enrolled machines: online/offline/never/unchecked
altengine automation run --param day=mon --label office nightly   # prints the run id
altengine automation run --wait nightly         # follow the log; exit 1 if the run fails
altengine automation runs [--status s] [--script n] [--cursor c]
altengine automation logs <run-id>
altengine automation get <run-id>               # run + artifacts with short-lived download links
altengine automation cancel <run-id>

echo 123456 | altengine automation send otp      # job.waitForData("otp"); exit 1 if no job got it
altengine automation env                         # credential names (values are write-only)
altengine automation env --set PORTAL_PASSWORD   # value from stdin
altengine automation env --unset PORTAL_PASSWORD

Scripts are bundled like functions, so what altengine-worker run ran locally is what the machine runs. --parallel/--exclusive change the script's mode; a deploy with neither keeps it. run reports queued when no matching machine is connected — the run starts when one is.

Why

This emulator re-implements the data-plane HTTP/WebSocket contracts the hosted services expose, backed by local SQLite (pure-Go modernc.org/sqlite, so search/datastore inherit real FTS5 + json_extract + keyset-cursor semantics) and an in-memory pub/sub hub for channels. Feature parity is high where it's cheap and clearly documented where it isn't (see Not emulated).

Install / run

altengine dev [flags]

  --port 9191            port to listen on
  --host 127.0.0.1       host to bind
  --data ./.altengine     data directory (SQLite files + control.json)
  --memory               keep everything in RAM (nothing persisted)
  --reset                wipe the data directory before starting (asks on a terminal; --yes skips)
  --static ./dist        serve a built site on its own port (see above)
  --static-port 9192     port for that site (default: --port + 1)
  --spa                  serve index.html for unmatched paths (default: detected)

Data persists to --data by default and survives restarts. Instances auto-create on first use, so no setup is needed — just start issuing requests. --reset deletes only a directory that holds the emulator's control.json (or is empty); pointed at anything else it refuses.

Local data

The data directory is owner-only (0700, files 0600): control.json holds every channel and auth instance's signing secret. A data directory the emulator creates, or one named .altengine*, gets a .gitignore that ignores everything in it.

Each datastore and search namespace has its own database file. Older emulators stored namespaces containing characters other than A-Z a-z 0-9 _ . - under one shared name (org:1, org/1 and org 1 all in org_1.db). Such a namespace now starts empty; its old data is still on disk and is listed as the namespace org_1. The emulator logs the file on that namespace's first use; copy the data across if you need it.

Keep it on localhost. The emulator has no authentication by design: any bearer token gets full access, /mcp is served unauthenticated, functions run whatever JavaScript you deploy to them, and containers start jobs on your local Docker daemon. --host 0.0.0.0 therefore puts a JavaScript runtime and your Docker daemon on the network for anyone who can reach the port. It is a development tool, not a sandbox — run only code you trust in it. See SECURITY.md.

Credentials

There are two kinds of data-plane credential, and the emulator accepts both.

Org API keys (dev-open). The emulator accepts any Authorization: Bearer <token> and grants full access on a single local dev org, so you can start issuing requests with no setup. You can still mint grant-scoped keys in the console (API keys tab) to exercise read < write < full grant enforcement locally.

End-user identity tokens. An auth instance (/v1/auth/{instance}) signs up and signs in your app's end users and hands each one a short-lived id_token. Sending that token to the datastore or channel plane makes the caller an end user rather than a trusted backend: grants come from the auth instance's access config, and datastore reads/writes are additionally row-scoped by its rules. This is the "no backend of your own" path — see Auth.

Admin console

Open http://127.0.0.1:9191/. Vanilla SPA (embedded in the binary, no build step):

  • Overview — instances per service and base URLs.
  • Datastore — namespace/collection browser, query & aggregate consoles, insert, index editor.
  • Search — index browser, query box (full query language), put/delete documents.
  • Channels — live WebSocket playground: subscribe, publish (HTTP + WS), see delivered frames.
  • API keys — mint scoped keys (shown once) and revoke.

Auth instances are managed through the admin API (/admin/auth) — create them, edit their signup/access config, and rotate the signing secret (which invalidates every outstanding identity token).

PUT /admin/{service}/{id}/config replaces the whole config, as it does hosted — send every field you want to keep. MCP's patch_instance_config merges top-level fields instead.

Services & endpoints

All data-plane routes require Authorization: Bearer <token> (except the public auth endpoints, which are browser-facing). {instance} auto-creates.

Datastore — /v1/datastore/{instance}
Method & path Purpose
GET /ns list namespaces
DELETE /ns/{ns} drop a namespace
POST /ns/{ns}/col/{c}/documents put/upsert {documents:[{key?,data}]} → {keys}
POST /ns/{ns}/col/{c}/documents/get {keys:[]} → {documents} (the only point-read)
POST /ns/{ns}/col/{c}/documents/delete {keys:[]} → {deleted}
POST /ns/{ns}/col/{c}/query {where,order,limit,cursor,keys_only,join}
POST /ns/{ns}/col/{c}/aggregate {where,group,metrics,order,limit}
POST /ns/{ns}/transaction {operations:[put/delete/mutate/check]}
GET/POST /ns/{ns}/col/{c}/indexes · DELETE …/indexes/{id} index CRUD

{ns} is the namespace segment; the default (empty) namespace is spelled _default. There is no single-document GET — SDKs implement it as a one-key batch against documents/get.

Query DSL: where = [{field,op,value}] with ops = != < <= > >= in; dot-paths + meta selectors __key__ __created__ __updated__; keyset cursor; join by foreign key. Queries must be index-served or (with autoIndex on, the default) the suggested index is auto-created and the response carries auto_indexed. Transactions are atomic within a namespace, with field-level mutate (set/increment/remove) and optimistic check.

Search — /v1/search/{instance}
Method & path Purpose
GET /ns list namespaces
POST /ns/{ns}/idx/{index}/documents batch put (lazy index create) → {ids}
POST /ns/{ns}/idx/{index}/documents/get {ids:[]} → {documents}
GET /ns/{ns}/idx/{index}/documents list/range
POST /ns/{ns}/idx/{index}/documents/delete {ids:[]} → {deleted}
POST /ns/{ns}/idx/{index}/search search
GET /ns/{ns}/idx/{index}/schema union field schema
GET /ns/{ns}/idx · DELETE /ns/{ns}/idx/{index} list / drop

{ns} is the namespace segment (_default for the default one), the same as datastore. There is no single-document GET — use the documents/get batch.

Field types: text html atom number date geo tokenprefix untokenprefix. Query language: bare/global terms, field scope (title:up, genre = "sci fi"), numeric/date compares (rating > 3), AND/OR/NOT/-, grouping (genre:(comedy OR drama)), phrases, stemming (~running), and geo (distance(loc, geopoint(37.7,-122.4)) < 1000). Supports limit/offset/cursor, sort, ids_only, returned_fields, facet discovery + refinements, and bounded total_hits with total_hits_accuracy. There is no * wildcard: a tokenprefix field matches its query as a word prefix (title:wond finds "wonderful") and an untokenprefix field as a prefix of the whole value; a * in a query is an ordinary character.

Result shaping matches production too: snippets (snippet block → per-result highlighted, HTML-escaped excerpts via FTS5) and field collapsing (collapse: {field, limit} — top-N per distinct atom/number value; total_hits/facets stay uncollapsed). Instance config applies the same way as production: synonyms (equivalents/oneWay + the computed numeral toggles numberRoman/numberWords, so godfather 2 can find Part II) and query rules (pin/hide/rule_data) — set them via the instance's admin config. One fidelity gap: multi-word synonym keys ("laptop computer" as a source) aren't matched against word runs here; single-word keys and multi-word targets work.

Channels — /v1/channel/{instance}
Method & path Purpose
POST /tokens mint a subscriber JWT {channels,ttl_seconds,publish,presence_id}
POST /publish {channel,data} → {delivered} (API key or publish-JWT)
GET /subscribe WebSocket upgrade (?token= or Sec-WebSocket-Protocol: bearer,<jwt>)
GET /presence server-side roster (requires presence config on)

Delivered wire frame: {"channel","data","ts"} (ts ms). Over the socket: {type:subscribe|unsubscribe|publish} in, {type:subscribed|published|error} and {type:presence,event} control frames out. HS256 tokens signed with the instance secret; publish may be true/"http"/"ws"/"all".

Minting with an end-user identity token instead of an API key is scoped: the requested channels must match the auth instance's channels patterns (a trailing * is a prefix wildcard, and $auth.uid / $auth.identifier / $auth.email / $auth.claims.X interpolate inside the string from the verified token), the minted token is always subscribe-only, and presence_id is forced to the end user's uid. End users publish by writing to the datastore, whose live bridge broadcasts the change (see below).

Auth — /v1/auth/{instance}

The end-user identity provider. These endpoints are public (browser-facing) — no API key.

Method & path Purpose
GET /config client-safe config: allow_signup, identity_field, fields, captcha, methods
POST /signup the configured form + password → {id_token,refresh_token,expires_at,refresh_expires_at,user} (201)
POST /signin {identifier,password} → the same token bundle
POST /token/refresh {refresh_token} → a fresh id_token + a rotated refresh_token
POST /signout {refresh_token} → {ok:true} (revokes it)
GET /me Authorization: Bearer <id_token> → {user}
POST /passwordless/start · /passwordless/verify one-time emailed code sign-in
POST /password/reset/start · /password/reset/verify one-time emailed code reset

The signup form is configurable per instance (signup config): which fields to collect and which one (identityField) is the unique login handle. That field's value becomes the user's identifier; every other collected field becomes a custom claim, which is what row rules read as $auth.claims.X. Passwords are hashed with PBKDF2-HMAC-SHA256; refresh tokens and one-time codes are stored only as hashes.

Sign-in is deliberately non-enumerating: an unknown handle and a wrong password return the exact same error, and /passwordless/start always answers 200 whether or not the account exists.

One-time codes are printed, not emailed. The emulator has no mailer, so a passwordless or reset code is written to the server log:

[auth] sign-in code for alice@example.com: 481920

…and, because the emulator runs dev-open, also echoed in the /start response as dev_code so tests and local clients can complete the flow without a mailbox. The hosted service never returns a code — do not build on that field.

Row-level access for end users

An auth instance's access config decides what a token it issued may reach:

{
  "datastore:appdb": {
    "level": "write",
    "rules": {
      "posts": {
        "read": "authenticated",                                  // or "public", or a filter list
        "create": { "stamp": { "author_uid": "$auth.uid" } },     // server-set, forge-proof
        "update": {
          "match": [{ "field": "author_uid", "op": "=", "value": "$auth.uid" }],
          "immutable": ["author_uid"]
        },
        "delete": { "match": [{ "field": "author_uid", "op": "=", "value": "$auth.uid" }] }
      }
    }
  },
  "channel:appfeed": { "level": "read", "channels": ["posts.*", "dm.$auth.uid"] }
}

Enforcement matches the hosted service:

  • read — the rule's filters are ANDed into query/aggregate before the index-served guard, and applied server-side to documents/get (a row you may not read is omitted, never leaked).
  • create — stamp overwrites those fields from the verified token, so authorship can't be forged; an optional match then validates the resulting document.
  • update / delete — the existing row must satisfy match, and immutable fields may not change. A put replaces the whole document, so an omitted immutable field counts as a change. On update, a field match compares to an $auth.* placeholder is immutable too, unless the update stamps it or it has its own fields.<name>.write gate.
  • $auth.* resolves only from the verified token. A placeholder that can't be resolved is a hard 403 — a rule never silently degrades into an unconstrained match.
  • Default-deny: once rules is present, a collection or mode that isn't listed is refused.
  • Namespace administration, transactions, and index management stay backend-only (org API key).

An org API key bypasses rules entirely: it is a trusted backend credential.

Datastore → channel live bridge

A datastore instance's live config turns committed writes into channel events:

{ "live": { "channelInstance": "appfeed", "collections": { "posts": { "keyBy": "board" } } } }

After a committed put or delete the emulator publishes {op, keys, ns, collection} to appfeed on channel posts.<board-value> (or bare posts with no keyBy). Keys only — never a document body — so subscribers re-fetch through the access-controlled read path and a live event can't leak a row they couldn't read. It is best-effort: a publish failure never fails the write.

Tasks — /v1/tasks/{instance}

Queues of work. Every instance has a default queue. Org API keys only.

Method & path Purpose
GET / · GET /queues the instance's queues, with settings and counts by state
POST /queues · PATCH /queues/{q} · DELETE /queues/{q} create / change (only the fields sent) / delete — full
POST /queues/{q}/pause · /resume · /purge full
POST /queues/{q}/tasks a task, an array, or {tasks} (≤100) → {tasks:[{ok,id,…}]}; 409 when none was added
GET /queues/{q}/tasks ?state&cursor&limit&name → {tasks,cursor}
POST /queues/{q}/lease pull queues: {count,leaseSeconds} → tasks with a leaseId
GET /tasks/{id} · DELETE /tasks/{id} · POST /tasks/cancel read / cancel one / cancel {ids}
POST /tasks/{id}/run run now; retry a failed one; re-run a finished one as a new task
POST /tasks/{id}/ack · /extend · /release finish, hold longer, or give back a leased task ({leaseId,…})

A push queue's target is {function: "<instance>/<fn>"} (called in process with x-ae-trigger: task and the body {task, payload}), {channel: "<instance>/<channel>"} or {webhook: "https://…"} (signed with the instance's key). The engine checks for due work about once a second and logs every attempt; a 2xx is done, a timeout/408/429/5xx is retried with the queue's backoff, and any other 4xx fails the task. An attempt is waited for the queue's deadlineSeconds (15–840, default 600) or the task's own; past it, it counts as a timeout and the target is not stopped. The task a target receives carries that moment as deadlineAt. A late call keeps its task's slot until it returns, so maxConcurrent is never exceeded and the retry never runs beside it; the timed-out attempt then records what the target answered. The hold lasts at most 14.5 minutes from the attempt's start; then the slot is freed (a webhook request is cancelled) and the attempt records that the target was still running.

Triggers. A datastore or blob instance's triggers config, and a mailbox route's {"queue": "<tasks-instance>/<queue>"} action, add a task for each matching write, upload, delete or message:

{ "triggers": [ { "match": { "collection": "orders", "ops": ["create"] }, "queue": "jobs/billing" } ] }

The queue must exist when the rule is saved. Events are best effort — a write never waits for or fails because of one — and a chain more than 8 deep (a function writing what triggers it) is cut.

Quick examples

BASE=http://127.0.0.1:9191
AUTH='Authorization: Bearer devkey'

# datastore
curl -H "$AUTH" -XPOST $BASE/v1/datastore/shop/ns/main/col/orders/documents \
  -d '{"documents":[{"key":"o1","data":{"total":150,"user_id":"u1"}}]}'
curl -H "$AUTH" -XPOST $BASE/v1/datastore/shop/ns/main/col/orders/query \
  -d '{"where":[{"field":"total","op":">","value":100}]}'

# search
curl -H "$AUTH" -XPOST $BASE/v1/search/app/ns/_default/idx/movies/documents \
  -d '{"documents":[{"id":"m1","fields":[{"name":"title","type":"text","value":"Up in the Air"},{"name":"rating","type":"number","value":4}]}]}'
curl -H "$AUTH" -XPOST $BASE/v1/search/app/ns/_default/idx/movies/search -d '{"query":"title:air rating > 3"}'

# auth: sign up an end user, then use the id_token as the datastore credential
curl -XPOST $BASE/v1/auth/appauth/signup -d '{"email":"alice@example.com","password":"hunter2hunter"}'
ID_TOKEN=...   # the id_token from the response
curl -H "Authorization: Bearer $ID_TOKEN" -XPOST $BASE/v1/datastore/shop/ns/main/col/posts/query -d '{}'

# channels: mint token, then open a WebSocket on ws_endpoint offering the returned protocols
curl -H "$AUTH" -XPOST $BASE/v1/channel/chat/tokens -d '{"channels":["room1"],"publish":true}'
curl -H "$AUTH" -XPOST $BASE/v1/channel/chat/publish -d '{"channel":"room1","data":{"hi":"there"}}'

Development

go build ./...    # build
go test ./...     # unit + integration tests (in-process, no network)
go vet ./...

Layout:

cmd/altengine/              CLI: dev, deploy, functions, static, automation, login
internal/common/            error envelope, JSON helpers, ids, config checks
internal/auth/              dev-open bearer API keys + grants
internal/control/           instance & key registry (JSON-persisted)
internal/datastore/         store + query/aggregate/transaction engine (SQLite json_extract)
internal/search/            store + query lexer/parser/compiler + search (SQLite FTS5 + EAV)
internal/channel/           in-memory rooms/connections + JWT + WebSocket
internal/identity/          auth data plane: end-user store, identity tokens, row rules
internal/functions/         function runtime, bindings, egress rules, scheduler
internal/blob/              objects, signed URLs, multipart, public host
internal/container/         jobs on the local Docker daemon
internal/devsite/           `dev --static` site server
internal/manifest/          Deploy to AltEngine manifests: parse, plan, apply, local sites
internal/mcp/               the MCP endpoint
internal/admin/             control-plane REST + embedded console (web/*)
internal/server/            HTTP wiring, rate limits
internal/hosted/            the hosted-service client the deploy commands share
internal/deploy|static|automation/   hosted-command clients

Not emulated

Intentionally out of scope for a local dev tool (documented so the parity gap is explicit): metering/billing, the hosted console's own admin sessions & OAuth (the emulator's /admin is open on localhost), CSRF, the plan-level rate-limit ceilings (an instance's own rateLimit, publishRateLimit and connectRateLimit are enforced, with a 429 RATE_LIMITED), usage archival, datastore PITR/backups, and multi-node channel fan-out (single-process hub). The index-served guard matches the hosted service on field coverage but is lenient on sort direction.

Tasks run in the emulator process: a task is delivered within about a second of falling due, a delivery a restart interrupts is retried once its lease runs out, and a trigger that cannot be enqueued is logged to the terminal rather than raised as a console notice.

Static deployments are not stored locally — altengine dev --static ./dist serves a directory instead, which is what a dev loop wants. /v1/static answers 501 UNIMPLEMENTED naming that, so altengine static deploy pointed at the emulator says what to do rather than failing obscurely.

On the auth plane specifically:

  • TOTP 2FA and passkeys / WebAuthn are not emulated — both need a real authenticator, which a local tool can't stand in for. Their endpoints answer 501 UNIMPLEMENTED rather than pretending to succeed, so a client that requires them fails loudly. Sign-in therefore never returns an mfa_required challenge here.
  • No email is sent. Passwordless and password-reset codes are printed to the server log and echoed as dev_code in the /start response (dev-open only).
  • CAPTCHA is configurable and reported by GET /config, but no token is verified.
  • Origin allowlists and per-IP rate limits are not enforced.

Directories

Path Synopsis
cmd
altengine command
Command altengine runs a local emulator for the altengine services plus an admin console, so applications can develop against the altengine APIs without the hosted service, and deploys functions, static sites and automation scripts to the hosted service.
Command altengine runs a local emulator for the altengine services plus an admin console, so applications can develop against the altengine APIs without the hosted service, and deploys functions, static sites and automation scripts to the hosted service.
internal
admin
Package admin is the emulator's control plane and embedded admin console.
Package admin is the emulator's control plane and embedded admin console.
auth
Package auth emulates altengine's data-plane authentication: a Bearer API key resolves to an org + a grants map.
Package auth emulates altengine's data-plane authentication: a Bearer API key resolves to an org + a grants map.
automation
Package automation talks to a hosted automation instance: deploying scripts, starting runs, and reading what they produced.
Package automation talks to a hosted automation instance: deploying scripts, starting runs, and reading what they produced.
blob
Package blob emulates altengine's blob service: a place to put a file, an upload that does not travel through the API, and a public URL for the ones you publish.
Package blob emulates altengine's blob service: a place to put a file, an upload that does not travel through the API, and a public URL for the ones you publish.
common
Package common holds cross-service primitives: the API error envelope, JSON request/response helpers, and small id/crypto utilities.
Package common holds cross-service primitives: the API error envelope, JSON request/response helpers, and small id/crypto utilities.
container
Package container emulates the altengine container service: a Docker image run as a background job for as long as the work takes.
Package container emulates the altengine container service: a Docker image run as a background job for as long as the work takes.
control
Package control is the emulator's control plane: the registry of service instances (search / channel / datastore / auth) and minted API keys for the single local dev org.
Package control is the emulator's control plane: the registry of service instances (search / channel / datastore / auth) and minted API keys for the single local dev org.
datastore
Package datastore emulates the altengine datastore data plane: a per-namespace JSON document store with a bounded, index-served query/aggregate/transaction engine.
Package datastore emulates the altengine datastore data plane: a per-namespace JSON document store with a bounded, index-served query/aggregate/transaction engine.
deploy
Package deploy pushes a function to a hosted altengine functions instance.
Package deploy pushes a function to a hosted altengine functions instance.
devsite
Package devsite serves a built site directory the way the hosted static service serves a deployment, so the local dev loop is the deployed behavior.
Package devsite serves a built site directory the way the hosted static service serves a deployment, so the local dev loop is the deployed behavior.
functions
Package functions emulates the altengine functions service: sandboxed JavaScript, deployed as one bundled ES module and invoked over HTTP, with capability-scoped access to the other services and nothing else.
Package functions emulates the altengine functions service: sandboxed JavaScript, deployed as one bundled ES module and invoked over HTTP, with capability-scoped access to the other services and nothing else.
hosted
Package hosted is the one HTTP client the CLI's hosted-service commands (deploy, functions, static, automation) share: the URL check, the bearer header, the error envelope and retries.
Package hosted is the one HTTP client the CLI's hosted-service commands (deploy, functions, static, automation) share: the URL check, the bearer header, the error envelope and retries.
identity
Package identity emulates the altengine auth data plane: per-tenant end-user accounts (`/v1/auth/{instance}`) that issue identity tokens the browser presents to the datastore and channel data planes instead of an org API key.
Package identity emulates the altengine auth data plane: per-tenant end-user accounts (`/v1/auth/{instance}`) that issue identity tokens the browser presents to the datastore and channel data planes instead of an org API key.
mailbox
Package mailbox emulates the altengine mailbox service: email addresses an app or an agent owns.
Package mailbox emulates the altengine mailbox service: email addresses an app or an agent owns.
manifest
Package manifest deploys a "Deploy to AltEngine" manifest into the emulator: the same JSON file the hosted deploy page reads, parsed with the same rules, planned with the same create / update / adopt / conflict classification, and applied in the same step order — through the emulator's own MCP tools and REST routes, so a config the emulator refuses anywhere is refused here too.
Package manifest deploys a "Deploy to AltEngine" manifest into the emulator: the same JSON file the hosted deploy page reads, parsed with the same rules, planned with the same create / update / adopt / conflict classification, and applied in the same step order — through the emulator's own MCP tools and REST routes, so a config the emulator refuses anywhere is refused here too.
mcp
Package mcp serves the emulator's MCP endpoint: POST /mcp, JSON-RPC 2.0, stateless.
Package mcp serves the emulator's MCP endpoint: POST /mcp, JSON-RPC 2.0, stateless.
search
Package search emulates the altengine search data plane — an App Engine Search API feature-parity service.
Package search emulates the altengine search data plane — an App Engine Search API feature-parity service.
server
Package server wires the emulator's HTTP surface: the data planes (/v1/search, /v1/datastore, /v1/channel, /v1/auth, /v1/functions, /v1/blob, /v1/container, /v1/mailbox, /v1/tasks and the public /fn and /blob paths), the control-plane admin API (/admin), MCP, and the embedded admin console — mounted in the same order as the hosted platform (data plane, then admin, then static assets).
Package server wires the emulator's HTTP surface: the data planes (/v1/search, /v1/datastore, /v1/channel, /v1/auth, /v1/functions, /v1/blob, /v1/container, /v1/mailbox, /v1/tasks and the public /fn and /blob paths), the control-plane admin API (/admin), MCP, and the embedded admin console — mounted in the same order as the hosted platform (data plane, then admin, then static assets).
static
Package static deploys a built site to a hosted altengine static instance.
Package static deploys a built site to a hosted altengine static instance.
tasks
Package tasks emulates the tasks service: queues of work delivered to a function, a channel or a signed webhook (push queues), or leased by workers (pull queues), with retries, backoff, dead-letter queues and triggers from datastore writes, blob uploads and mailbox routes.
Package tasks emulates the tasks service: queues of work delivered to a function, a channel or a signed webhook (push queues), or leased by workers (pull queues), with retries, backoff, dead-letter queues and triggers from datastore writes, blob uploads and mailbox routes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL