Skip to content

Latest commit

 

History

History
737 lines (497 loc) · 85.7 KB

deployment.md

File metadata and controls

737 lines (497 loc) · 85.7 KB

Deploy the gateway

Start a PostgreSQL server and the connector services for the offers you intend to serve. Use an operator-controlled catalog, with a provider ID and binding for each offer. Keep vendor credentials in the respective connector process. The gateway receives only the credentials needed to authenticate to that connector.

Gateway configuration Value
DATABASE_URL PostgreSQL database used by the gateway and workers
FOUNDATION_ENV, API_GATEWAY_PORT Use development and 4000 for a manual local run
APP_BASE_URL, COOKIE_DOMAIN, COOKIE_SECURE For local Vite, use http://localhost:3000, localhost, and false
SESSION_SECRET, TOKENCRAFT_DEMO_PAYLOAD_KEY Independently generated secrets. For local use run openssl rand -hex 32 for each. Reuse the payload key for the same database.
TOKENCRAFT_CORE_CATALOG Path to version 1 catalog JSON
TOKENCRAFT_CONNECTORS Path to queue connector bindings if the catalog contains queue offers
TOKENCRAFT_LOCAL_CHAT_BINDINGS Path to chat bindings if the catalog contains compatible chat offers
TOKENCRAFT_DISABLE_BYOK_AND_WORKFLOWS Set to true to disable BYOK and the Workflows API and console. Restart each API replica to apply the setting. Defaults to enabled features in local gateway runs.
Binding token The environment variable named by each binding
TOKENCRAFT_DEMO_ARTIFACT_DIR Persistent local artifact directory for a single-host media setup

The queue protocol accepts a loopback HTTP origin for local development or a configured HTTPS origin. A local chat endpoint uses loopback HTTP and the path /v1/chat/completions. Run an OpenRouter plugin on the same host as its gateway worker or configure a supported private compute binding.

With those settings, apply migrations before compiling the gateway. SQLx checks queries against that schema.

cargo run --locked -p admin_cli --bin admin-cli -- migrate
cargo run --locked -p api_gateway --bin api-gateway

The default process runs the API and workers together. Set TOKENCRAFT_PROCESS_ROLE=api or TOKENCRAFT_PROCESS_ROLE=worker to run them separately. Both roles need the same database, persistent payload key, catalog, and bindings. Use shared artifact storage when those roles run on separate machines. Check /ready and the catalog model list after deploying. Configure event archives for verified filesystem or S3-compatible retention.

Workflows uses the existing persistent payload key by default. Each worker process advances up to two workflow runs at a time and processes deadlines and retention cleanup independently. PostgreSQL leases and admission limits continue to apply across all replicas. Workflow setup

A single deployment can use direct ingress and omit the cell ID. Chat compute pools then use dev-cell.

Roll out compatible database changes

Use the target build's migration CLI. Apply additive migrations during a rolling deployment only if every pending migration declares support for the deployed API and worker schema in public.gateway_schema_compatibility. Record migration_version and oldest_gateway_schema in the same transaction as the migration, after testing the oldest supported binaries against the changed schema. Review index builds and backfills for table locks and schedule a maintenance window when writes could be blocked. Use a coordinated cutover for incompatible changes.

A gateway needs a writable PostgreSQL primary and a compatible schema. If either check fails after startup, workers pause new background work while work already started can finish under its existing lease. Operational API requests return 503 with Retry-After: 5 until the checks pass again. Retry submissions with the same body and idempotency key. Health, readiness, and contract endpoints remain reachable for diagnosis.

Check the database before rollout

Run admin-cli schema-status from the target build using the gateway runtime role and the deployment's verified database connection. It reads the migration ledger and reports the binary schema, the database schema when present, and any pending versions. It exits successfully for compatible states. Recheck after applying migrations and runtime grants.

Status Meaning
current The applied migrations match the target build.
forward_compatible The build's migrations match and every later migration explicitly allows it.
upgrade_required The applied migrations match a prefix of the target build. Follow the cutover or rolling procedure before starting the new fleet.
diverged The ledger has a gap, a failed migration, or a checksum mismatch. Check the database and matching build before migrating.
incompatible_newer A later migration failed or lacks a compatibility declaration for this build. Use the matching image or restore the prior recovery point before rolling back.
empty The public schema has no ledger or application objects.
unmanaged The public schema has objects without a TokenCraft ledger. Verify the database connection before proceeding.

Cut over without schema overlap

  1. Pause submissions at ingress and use cell admission control while the old API still serves status and results. Drain active work and deliveries, then stop the API and workers before taking a backup.
  2. Retain the old image and deployment configuration. Back up PostgreSQL and record the corresponding recovery points for artifact storage, connector state, and retained keys. Verify that the backup can be restored to a separate database.
  3. With ingress paused and the fleet stopped, run admin-cli migrate --pause-admissions from the target image. Reapply runtime grants. Check admin-cli schema-status and admin-cli admissions status --expect paused as the runtime role before starting the new fleet.
  4. Run the public and read-only authenticated checks and verify that a saved receipt and its result are still readable. Resume cell admissions, then lift the ingress pause.
  5. For rollback, start the prior image against the separately restored database and verify the saved receipt and artifact before switching traffic. Preserve the upgraded database and reconcile any writes accepted after the backup before resuming admissions on the restored database.

Pause new admissions in a cell

The admission state is shared by every API replica in the cell. Run these commands with DATABASE_URL pointing to the cell's primary database. The migration owner can change the state. The runtime role can read it.

admin-cli admissions pause
admin-cli admissions status --expect paused
admin-cli admissions resume

The status command exits nonzero on a standby or when the observed state differs from --expect paused or --expect open. The pause waits for in-progress admission transactions to finish. New inference submissions, workflow invocations, and draft test runs then return 503 admissions_paused with Retry-After: 5. Matching receipt retries, scoped reads, quotes, provider polling, webhook delivery, and generation steps of admitted workflows remain available.

admin-cli migrate --pause-admissions applies migrations before setting the pause. If setting the pause fails, check the schema and set the pause before starting replicas. Plain admin-cli migrate preserves the recorded admission state.

Use the Operations console to check the pause state and whole-cell request, workflow, and webhook backlog. With API autoscaling enabled, the pause also waits for any scale-in already holding the database lock. Scale-in guard

Rehearse the cutover before release

The Release cutover workflow exercises upgrade and rollback on disposable PostgreSQL. It verifies readiness, receipt replay, recovery of an accepted provider job without resubmission, artifact reads, and signed webhook delivery.

To run the rehearsal locally, use matching binaries for each build, PostgreSQL 17, OpenSSL, and a free loopback port 4019. Set baseline_schema to the baseline build's binary schema from admin-cli schema-status. Add --expect-baseline-overlap when every pending migration declares support for the baseline schema.

python3 -B scripts/smoke_release_cutover.py \
  --baseline-schema "$baseline_schema" \
  --baseline-admin ./baseline/bin/admin-cli \
  --baseline-gateway ./baseline/bin/api-gateway \
  --baseline-connector ./baseline/bin/tokencraft \
  --candidate-admin ./target/debug/admin-cli \
  --candidate-gateway ./target/debug/api-gateway \
  --candidate-connector ./target/debug/tokencraft

Stage Cloudflare ingress and PlanetScale Postgres

Publish the placeholder console

Use a dedicated Workers Static Assets application while the gateway is being qualified. This profile publishes tokencraft-preview.<account-subdomain>.workers.dev with the public catalog and bundled API reference. It disables sign-in and live requests and asks search engines to skip the preview. Develop and verify it with Node.js 22.

Run the Cloudflare preview workflow manually on main for storytold/tokencraft when a static preview is needed. Set CLOUDFLARE_API_TOKEN in the repository's Actions secrets to a token with Editor access to the existing tokencraft-preview Worker in the Storyteller account. The workflow validates the static bundle before deployment and checks the public hostname for the expected revision, asset digests, and preview headers. Cloudflare preview workflow · Workers roles

npm --prefix frontend ci --ignore-scripts
export TOKENCRAFT_SOURCE_REVISION="$(git rev-parse HEAD)"
export TOKENCRAFT_REQUIRE_SOURCE_REVISION=1
VITE_TOKENCRAFT_STATIC_PREVIEW=true VITE_API_BASE_URL='' npm --prefix frontend run build
node scripts/console_security_headers.mjs --cloudflare --noindex > frontend/dist/_headers
npx --yes wrangler@4.170.0 deploy --config deploy/cloudflare/wrangler.preview.toml --dry-run

For a manual deployment, select the intended Cloudflare account with CLOUDFLARE_ACCOUNT_ID and remove --dry-run. Use the same checkout and build manifest for the public check. On the preview, /login displays a status message and takes no credentials. Workers Static Assets billing · workers.dev

bash scripts/smoke_hosted_console.sh --static-preview "$preview_origin" \
  "$TOKENCRAFT_SOURCE_REVISION" frontend/dist/release.json

Launch production before connecting providers

The gateway can serve sign-in, accounts, projects, and the public API contract with an explicit empty catalog. Use a current, migrated PlanetScale writer with restricted runtime grants and keep admissions paused. The gateway advertises no executable offers. Catalog import and review commands still require offers.

The Cloudflare production workflow publishes the normal console and its same-origin API to tokencraft-console.brandon-396.workers.dev. It uses one on-demand Cloudflare Container for the combined gateway and background tasks. Keep admissions paused until a reviewed catalog and connector configuration are installed and the background worker has been qualified for continuous processing.

Cloudflare production disables BYOK and Workflows by default. Clear Disable BYOK and Workflows in the workflow inputs, or set TOKENCRAFT_DISABLE_BYOK_AND_WORKFLOWS=false when generating a manual release, to enable both. Verify the setting with GET /v1/features. The gateway continues processing work admitted before the change.

Run Container smoke on the release commit and publish its checked Linux gateway image to the account's Cloudflare registry. For the first deployment, supply DATABASE_URL, SESSION_SECRET, and TOKENCRAFT_DEMO_PAYLOAD_KEY as Worker secrets via Wrangler's --secrets-file setting or the Worker dashboard. Keep those values in Cloudflare and use a separate migration login. For PlanetScale's public CA, use the direct URL with sslmode=verify-full and omit libpq's sslrootcert=system option in the SQLx connection string. Once configured, dispatch Cloudflare production from the same commit on main with the image's digest reference and a token authorized for that Worker and its Container deployment. Cloudflare Container deployments

The workflow defaults to the preserve inference profile. It reads the enabled modes from the single active Worker version and stops if that version changes before deployment. Select none, fal, artcraft, or both for an intentional change. Use an explicit profile for a first deployment or to replace a deliberate traffic split. Drain affected requests before disabling their connectors.

For a hosted release that can use the existing gateway binary, supply the active verified image as gateway_image and its full Git SHA as gateway_revision. For a manual release, pass that SHA as the third argument to deploy/cloudflare/production-config.mjs and set the active inference modes when generating the config. The generator limits revision differences to console, documentation, and specific Worker configuration and release verification files. The same gateway image, gateway revision, and container settings reuse the same instance, including when inference is enabled. Runtime changes such as credential rotation select a fresh instance. Allow database connection headroom for old and new instances during gateway updates, including the first release that uses this runtime identity. For a manual smoke check, export TOKENCRAFT_GATEWAY_SOURCE_REVISION with the active gateway's full SHA and pass the new console revision and build manifest to scripts/smoke_hosted_console.sh. This checks each component against its own revision.

Stage Stripe billing

The normal release keeps the current Stripe setting. Deploy the Stripe-capable gateway and compatible migration with checkout off to prepare the infrastructure without a merchant account. The optional paused profile connects a dedicated checkout role and Stripe credentials while keeping purchases closed. Stripe infrastructure setup

Connect Codex to production MCP

The production Worker registers tokencraft-codex as a public OAuth client with a fixed loopback callback. Add these settings to your Codex configuration.

[mcp_servers.tokencraft]
url = "https://tokencraft-console.brandon-396.workers.dev/mcp"

[mcp_servers.tokencraft.oauth]
client_id = "tokencraft-codex"
callback_url = "http://127.0.0.1:37653/callback"
callback_port = 37653

Run codex mcp login tokencraft, sign in to TokenCraft, and choose a project. To request optional permissions, pass --scopes with a comma-separated list that includes requests:read and the desired scopes from requests:submit, requests:cancel, and usage:read. Open Manage agent connections under /connect/agents to revoke access.

After a release, check that both OAuth discovery endpoints advertise the production origin, the authorization server supports S256 PKCE, and an unauthenticated JSON-RPC request to POST /mcp returns a 401 with a Bearer challenge pointing to /.well-known/oauth-protected-resource/mcp.

Enable the fal production pilot

Set the encrypted FAL_KEY in the production Worker. Select the fal or both inference profile in Cloudflare production, or set TOKENCRAFT_PROVIDER_PILOT=true when generating Wrangler config manually. The Worker starts separate fal image and chat connectors and gives the gateway an independent loopback token for each.

  • flux_schnell generates one 512×512 PNG per request at the reviewed list rate of $0.003 per image. Its Durable Object allowance covers 1,000 upstream attempts and existing receipts can still be polled after the allowance runs out. fal pricing
  • gpt_41_mini serves GPT‑4.1 mini through fal's Chat Completions endpoint. The pilot accepts text requests up to 16 KiB and 1,024 output tokens. Its separate Durable Object allowance covers 100 upstream attempts. The pilot uses the upstream model's published OpenRouter token rates for TokenCraft quotes. fal chat API · OpenRouter model pricing

The allowances persist across restarts and releases and reserve each attempt before upstream I/O. A minute-by-minute trigger keeps the gateway available for polling and queued work.

Verify the bindings with the catalog preflight. Send a limited request from a scoped project key. For chat, set model to gpt_41_mini, stream to true, and stream_options.include_usage to true on POST /v1/chat/completions. Check for incremental text, a final usage frame, and [DONE]. Drain accepted jobs before disabling the pilot.

Enable ArtCraft inference presets

The public ArtCraft models and pricing page ships with the hosted console. To also enable generation for the reviewed fal and Kinovi presets, set the encrypted Worker secret TOKENCRAFT_PROVIDER_CREDENTIAL_KEY to an independently generated 32-byte hex value and retain it for the life of the credential vault. Select artcraft or both when dispatching Cloudflare production or set TOKENCRAFT_ARTCRAFT_INFERENCE=true when generating a manual release. These presets use the customer's provider key and the provider bills that account. The both profile also enables the existing managed fal offer.

Start by checking the hosted inventory, readiness, and available offer IDs. In a test account, use Settings → Connected providers with a dedicated provider test key, then quote and submit a preset in Playground. Check the receipt, result and funding record. Keep the same bindings and credential key while draining outstanding requests. Use the consumer BYOK rollout to pause new provider-account work.

ArtCraft ID in production

Save the confidential Keycloak client secret for craft-tokencraft as the Worker secret TOKENCRAFT_ARTCRAFT_CLIENT_SECRET. The production config supplies the public issuer and client ID. Enable the authorization code flow with S256 PKCE, RS256 ID tokens, and the optional email scope. Register the exact redirect URI https://tokencraft-console.brandon-396.workers.dev/v1/auth/craft/callback for this client. The gateway connects to the public ArtCraft realm over HTTPS.

Apply migration 150 and the runtime grants before deploying this release. The previous gateway at schema 149 can still start after the migration. The new gateway reads and consumes temporary OIDC flows in PostgreSQL and issues the same locally revocable TokenCraft sessions as its other sign-in methods.

The hosted console opens the shared ArtCraft ID screen for sign-in and onboarding, then returns users to the TokenCraft page they requested. Keycloak can reuse an existing ArtCraft ID session and shows the available providers and Register when sign-in is required. Enable the intended identity providers and registration in Keycloak. After a failed or cancelled handoff, the console offers a fresh sign-in, registration, and the original TokenCraft sign-in.

TokenCraft creates a personal workspace for a new, verified ArtCraft identity. If the identity’s email matches an unlinked TokenCraft account, the console opens the sign-in form for that account. Existing TokenCraft users can also open /login?method=tokencraft directly. Sign in with the existing account credentials and choose User settings → Connected sign-in methods → ArtCraft ID. The gateway resolves the identity using the issuer and subject and checks the existing TokenCraft session before linking.

For a self-hosted same-origin deployment, set TOKENCRAFT_ARTCRAFT_ISSUER, TOKENCRAFT_ARTCRAFT_CLIENT_ID, and TOKENCRAFT_ARTCRAFT_CLIENT_SECRET on the gateway and register APP_BASE_URL plus /v1/auth/craft/callback in Keycloak. Leaving all three settings unset disables the option.

Start one cell and scale by tier

Start in one region with one API replica, one continuously running worker, one dedicated PlanetScale PostgreSQL 17 writer, and a private Standard R2 artifact bucket. Use the same immutable gateway image for the API and worker. PlanetScale Postgres keeps the existing SQLx queries, migration ledger, job leases, and idempotency state. Start with the direct writer over hostname-verified TLS. Leave runtime pooling changes until they pass transaction, reconnect, and lease tests. Keep the migration owner on the direct endpoint to preserve session-scoped migration locks. PlanetScale connection pooling · Hyperdrive connection pooling

For a Cloudflare-native pilot, route the same-origin API paths from the Worker to a private Container binding. Keep static assets on the free asset path. Forward API requests once, preserve streaming and the gateway cache policy, and restrict private probes and connector callbacks to their intended ingress. Use the Durable Object scheduling policy. Verify hostname-verified Postgres egress, placement and latency to the writer, streamed responses, and process restart and drain before this pilot handles live jobs. Use a supervised worker instance with health checks and a restart path that works during zero HTTP traffic. A health check that starts a sleeping instance consumes runtime, so reserve continuous runtime for the queue worker and test API cold starts separately. Cloudflare Containers currently require application-managed replica selection and scaling. The alternative below uses continuously running Linux services and Tunnel. Container scheduling · Container lifecycle · Container FAQ

Expand when Enable
API CPU or streaming concurrency is sustained, or there is eligible work and the provider has headroom Run the cell capacity controller in plan mode first. Start with a ceiling of two replicas per role, subject to the measured database connection budget, including rollout and admin reserve. Use one actuator, probe each replica, and apply scale-out only with fresh writer and provider signals. Qualify graceful API scale-in before enabling it. Retain an always-on worker and drain extra workers before removing them.
One origin no longer meets availability goals Spread replicas across failure domains against the same cell writer. Route only to ready API replicas using the cell's private HAProxy for Linux origins or a readiness-aware pool for Cloudflare Containers. Add Cloudflare Load Balancing with separate monitored Tunnel origins on a managed hostname once there are two independent ingress paths. Verify stream reconnect and outage behavior. Tunnel load balancing
The service takes production traffic with a regional availability requirement Upgrade the PlanetScale writer to HA and rehearse writer failover. Prove the remaining origins and workers can handle the intended load after losing a zone. PlanetScale single-node and HA
Tenant isolation, writer capacity, or data residency requires a second cell Give the second cell its own PlanetScale writer, artifact namespace, capacity controller, and provider bindings. Route organizations by durable home-cell placement. Fail over across ingress paths for the same cell. A different cell can serve a tenant only after its state and placement have been recovered and the previous writer has been fenced. Home-cell routing

Budget the pilot

Price estimates use a 30-day month and the PlanetScale AWS us-east-1 catalog. Select the actual region near the origin before buying. The static placeholder has no incremental compute cost. For the full pilot the PS-5 writer compute starts at $5/month single-node or $15/month HA, with separately metered database usage where applicable. Use single-node for staging and size from observed connections, query latency, and recovery goals. R2 Standard includes 10 GB-month, 1 million Class A operations, and 10 million Class B operations per month, with free egress. PlanetScale pricing catalog · R2 pricing

  • Cloudflare-native pilot. Workers Paid starts at $5/month. With two basic Containers (1 GiB RAM and 4 GB disk each) warm for 720 hours, budget about $24/month before Container CPU with a single-node PS-5. At 10% average use of the two allocated quarter vCPUs, the estimate is $26/month. These estimates include the Workers plan, database compute, and Container memory and disk after the included allotments. API sleeping reduces its billed time. Measure builds under uploads and streaming before choosing a smaller size. Containers pricing
  • Fixed-budget Linux pilot. One 2 GB Lightsail Linux VM with public IPv4 is $12/month. With the single-node PS-5, budget $17/month for origin and database compute. Run the separate API and worker roles on that node and use Cloudflare Tunnel and Workers Static Assets. Validate memory under uploads, streaming, and background work before committing to the size. A single VM is one failure domain. Lightsail pricing
  • Variable and optional costs. Price database storage, backups, transfer, provider inference, email, and any connector hosts separately. Stay on R2 Standard, monitor storage against the app's retention, sample routine logs, and set spend alerts before enabling traffic. Use TokenCraft's per-project limits and provider-side budgets. Start with a reviewed set of managed/on-demand endpoints and add dedicated GPU capacity only from measured utilization. Add the public Load Balancing subscription when multiple independently monitored origins are ready. Cloudflare budget alerts · Load Balancing

Qualify the Linux origin and ingress

Use a Cloudflare Workers Static Assets deployment for the console and a Cloudflare Tunnel for the API hostname. Run the native Linux gateway image as separate, continuously running API and worker services behind the tunnel. A worker must make progress when there are zero HTTP requests. Keep persistent queue connectors on their own services and volumes and run open-weight models on their reviewed serving hardware. Cloudflare static assets · Cloudflare Tunnel · Container lifecycle

Prepare the writer and object storage

  1. Create a dedicated PlanetScale Postgres staging branch in the region closest to the gateway processes. Start with PostgreSQL 17, the version used by the release rehearsal. Use the dashboard's direct writer connection on port 5432 with sslmode=verify-full for the migration owner and the restricted runtime login. Migrations use session-scoped locking. Consider a pooled endpoint for runtime traffic only after repeating the staging checks against that endpoint. Budget up to ten main database connections per gateway process, plus any separately enabled pools. PlanetScale Postgres quickstart · PlanetScale connection pooling
  2. Follow database role setup. The migration role must own the imported TokenCraft objects, including the existing migration ledger. For an existing deployment, restore an isolated copy first and preserve the ledger's contents and ownership. Reapply runtime grants after migration and run admin-cli schema-status and admin-cli admissions status --expect paused as the runtime login. Use the cutover procedure for the final copy, writer coordination and rollback.
  3. Use a private R2 bucket for shared artifacts. Set the S3 endpoint to the bucket's jurisdiction-specific endpoint and the signing region to auto. Issue bucket-scoped credentials. Keep any existing artifact root readable until the backed-up objects have been verified by request ID. Use a separately configured bucket and key for event archives if enabled. Leave S3 cold retrieval disabled with R2. Rehearse conditional writes, signed reads and deletes with synthetic objects in staging. R2 S3 compatibility

Publish the console and gateway from the same revision

Have a Workers administrator create the production tokencraft-console Worker and attach the approved hostname. Scope recurring console deployments to Editor on that Worker. Use a separate credential when administering the API Tunnel or changing DNS or routes. Workers roles · Workers Custom Domains

Choose same-site HTTPS hostnames for the console and API. Point the API's Tunnel hostname at the private cell balancer. Set TOKENCRAFT_LB_CLOUDFLARE_TUNNEL=true on that balancer and restrict its trusted-ingress file and listener access to the cloudflared connectors. The balancer then replaces any incoming forwarded chain with the single IP supplied by Cloudflare. Leave visitor IP forwarding enabled in Cloudflare, bypass edge caching on API routes and exclude private probes, including the balancer readiness route, from public ingress. Cloudflare client IP headers

Set the gateway's APP_BASE_URL to the console origin and follow the HTTPS ingress settings. Use the same source revision for both native gateway roles and the console. From a clean checkout of that revision, build the console with Node.js 22.

Before switching hostnames, verify email delivery with RESEND_API_KEY and a verified EMAIL_FROM_ADDRESS. If sign-in providers are enabled, register the new console origin with Google and the new /auth/github/callback URL with GitHub. Use the matching public console client IDs at build time. For existing avatars, retain their CDN path or verify the copied objects through the new CDN_BASE_URL. Use the avatar storage settings separately from private generated artifacts.

export TOKENCRAFT_SOURCE_REVISION="$(git rev-parse HEAD)"
export TOKENCRAFT_REQUIRE_SOURCE_REVISION=1
export VITE_API_BASE_URL=https://api.example.com
console_origin=https://console.example.com
npm --prefix frontend ci --ignore-scripts
npm --prefix frontend run build
node scripts/console_security_headers.mjs --cloudflare --api-origin "$VITE_API_BASE_URL" \
  > frontend/dist/_headers
npx --yes wrangler@4.170.0 deploy --config deploy/cloudflare/wrangler.toml --dry-run

Remove --dry-run to publish the reviewed console and attach its custom domain in Cloudflare. The profile disables workers.dev and preview URLs. Use the separate API check against the staged domains before promotion.

bash scripts/smoke_hosted_console.sh --separate-api "$console_origin" "$VITE_API_BASE_URL" \
  "$TOKENCRAFT_SOURCE_REVISION" frontend/dist/release.json

Connect providers and qualify the cutover

Start with a scoped catalog and one target for each intended route type. Run binding validation and live compute preflight from the worker network. Keep provider credentials in the connector service. Keep existing connector bindings, volumes and receipts available until accepted work drains. Exercise one buffered and one streaming chat request for each compute target. For each queued provider, submit a synthetic request, replay it with the same idempotency key, and verify the original receipt and stored artifact. Recheck the worker while the public API is idle and after a restart.

Use one release revision across console, API, worker, and migration CLI. Pin the gateway image by digest and keep the previous compatible digest and console deployment available. During the rehearsal, record database pool waits, queue age, provider headroom, stream reconnects, and restart behavior. Measure backup restore time and recovery point before accepting durable customer work. Use the cell fault checks before enabling automated scaling or decommissioning a surviving origin.

Before shifting traffic, verify a restored request and warm artifact, credentialed browser sign-in, the expected worker and API revisions, and the old and new recovery points. Keep admissions paused during the final database switch. Confirm the old writer is stopped before resuming on PlanetScale. After the new writer accepts requests, roll application versions back against that same writer if the schema supports it. Returning to the earlier database requires a separate paused restore or reconciliation to carry over the new receipts and usage. Database cutover procedure

Connect existing compute endpoints

Use the compute binding command to connect a deployed chat service or queue connector on AWS, Azure, Google Cloud, RunPod, or Render to an existing catalog offer. For an organization-owned chat target, use POST /v1/compute-providers/preview as an organization administrator. Supply the cell and binding IDs, the provider type, and the target. The preview validates the configuration and returns a review bundle without calling the endpoint.

Save the review bundle as compute-provider-patch.json. Use the deployed registry as the base and write the merged output to a new file.

api-gateway catalog apply-compute-patch --base bindings.json \
  --bundle compute-provider-patch.json > bindings.next.json

For the first registry, omit --base. Review the new placement and allowed locations before deploying the registry through TOKENCRAFT_LOCAL_CHAT_BINDINGS. Configure the named token in the worker environment. An openai_compatible_chat inference offer selects the pool through its local_binding. An organization can see its own pool before an offer uses it. Once an offer is linked, its projects can set fallback for that pool. Every endpoint in the pool should serve the same upstream model.

Use GET /v1/compute-providers to read the project's eligible targets and current policy revision. Use PUT /v1/compute-providers with the project scope and that revision to set the order. Put the primary target first, select a single target to pin the project, or clear the override to inherit pool priorities. See the console's /docs/api for the request fields and the compute placement guide for retry behavior.

Qualify each target with the live compute preflight before promoting a changed deployment. Enable the Operations preflight action for reviewed pools that need an interactive check.

Build the gateway runtime image

From the core repository, build the gateway target and tag it with the release version. The image includes the matching migration CLI and records the Git commit in VERSION.json when supplied at build time. The public catalog, OpenAPI contract, connector primitive registry, and PostgreSQL runtime grant script are in /opt/tokencraft.

docker build --file deploy/container/Dockerfile --target gateway \
  --build-arg "SOURCE_REVISION=$(git rev-parse HEAD)" --tag tokencraft-gateway:0.1.0 .

Run the image on your private ingress network. Supply the production configuration and mount the operator's catalog, binding files, and any private PostgreSQL CA read-only. The gateway runs as UID and GID 65532. Set TOKENCRAFT_LISTEN_IP to the private address or 0.0.0.0 inside its container so the ingress can reach it. A connector in another container uses a configured HTTPS origin.

Use the same image with --entrypoint admin-cli and the argument migrate as a one-off job. Set FOUNDATION_ENV to staging or production and use the migration owner's verified database connection. Then run the API and worker roles from that image. The Compose quickstart provides local synthetic inference with its own disposable state.

The Container smoke workflow builds both targets on pull requests, pushes to main, version tags, and manual runs. It verifies that the Docker context contains the native package inputs and checks the Linux image architecture, source revision, release profile, and matching package versions. A version tag must match the package version, for example v0.1.0. The workflow applies migrations with the gateway image and starts two API replicas and a separate worker using restricted PostgreSQL credentials. The private capacity probe verifies all three process identities and roles. The workflow checks that the replicas share the organization quota, accepted requests replay across replicas, and the worker completes the original request and records its usage once. It also exercises the demo's bundled connector and persistence across container recreation. The optional mount serves a launcher console built from the same revision. The smoke check verifies the API port, entry script, release manifest, public catalog, and OpenAPI document. Version tags and manual runs reload the archived gateway image and verify its image ID before upload. In the extracted CI artifact, run sha256sum -c SHA256SUMS, then load the tarball with docker load -i tokencraft-gateway-0.1.0-linux-amd64.tar.gz using the file's actual version.

Refresh reviewed rates

Set TOKENCRAFT_DEMO_RATE_FEED to a local JSON file on each API and worker replica. Use the base_revision from GET /v1/catalog/offers and the IDs of the offers you want the feed to manage.

For a new deployment, add a top-level "rate_feed_offers": ["my_video", "my_audio", "my_mesh"] alongside version and offers in the reviewed routing catalog. The gateway then requires those exact IDs on every load. Offers outside the list keep their configured prices. The field becomes part of the base revision. To introduce it on an existing deployment or change the managed IDs, prepare the revised catalog and its matching feed together.

For the first feed, use the planned catalog and the target's connector and chat binding environment to compute base_revision without starting the gateway.

api-gateway catalog check-rate-feed --catalog catalog.json
{
  "base_revision": "demo_REPLACE_WITH_BASE_REVISION",
  "observed_at": "2026-11-25T23:00:00Z",
  "valid_until": "2026-11-26T23:00:00Z",
  "rates": {
    "my_video": {
      "source_url": "https://vendor.example/video-pricing",
      "schedule": { "kind": "video", "usd_nanos_per_second": 32000000 }
    },
    "my_audio": {
      "source_url": "https://vendor.example/audio-pricing",
      "schedule": { "kind": "audio", "usd_nanos_per_second": 4000000 }
    },
    "my_mesh": {
      "source_url": "https://vendor.example/mesh-pricing",
      "schedule": { "kind": "mesh", "usd_nanos_per_mesh": 80000000 }
    }
  }
}

Image schedules use usd_nanos_per_image. Text schedules use usd_nanos_per_1000_input_tokens and usd_nanos_per_1000_output_tokens. Supply integer rates in USD nanodollars using the routing catalog's billing unit. Each rate must be between half and twice its reviewed base amount, subject to the catalog's limits. This range applies consistently after reloads and restarts. A change outside the range requires a new reviewed base catalog. Before upgrading a running gateway, check its accepted feed against the reviewed catalog so a previously accumulated rate change can be reviewed before restart. The gateway uses source URLs as provenance metadata and retains each offer's reviewed capabilities and binding.

Validate a proposed file before replacing the active feed. Use the same reviewed catalog and base revision as the target gateway. For an existing deployment, pass a copy of the last accepted file as --previous-feed to check freshness and offer coverage against it.

api-gateway catalog check-rate-feed --catalog catalog.json --base-revision "$BASE_REVISION" \
  --feed proposed-rates.json --previous-feed current-rates.json

Omit --previous-feed for a first publication. Omit --base-revision when running the check with the target's configured bindings. Use the explicit revision from GET /v1/catalog/offers to check from a machine that has only a copy of the catalog. The check reports the resulting revision, included offer IDs, and their deadlines. The report's valid_until is the next unexpired deadline. The check rejects a proposal whose rates have all expired and leaves the input files untouched.

Replace the file atomically with a complete snapshot. API and worker processes reload it independently every 15 seconds. Workers use their loaded rates to admit new workflow children. Connector retries use the original offer and estimate recorded at admission. A validity window can span up to seven days. A running process keeps its last accepted snapshot after a failed refresh. Once a rate expires, quotes omit its estimate and can select another eligible offer under the same spend cap.

Before committing a new admission, the process rechecks the quote deadline and the catalog revision it used. If its loaded revision changed or the deadline passed during a budget or quota wait, it returns 409 quote_stale and rolls back the request and its reservation. For a sealed submission, fetch a fresh quote and retry with the same idempotency key. Automatic submissions can retry directly with that key. Retrying an already accepted request still returns its original receipt. A workflow step can retry pricing within its existing execution deadline and spend cap. The offers API reports the effective revision and the rate_valid_until timestamps that the console uses to label expired prices.

Refresh offers on different schedules

For prices reviewed at different times, move observed_at and valid_until into every rate entry. Omit the top-level pair. Upgrade API and worker replicas before installing a feed with per-offer windows. Existing files with one top-level window remain valid.

{
  "base_revision": "demo_REPLACE_WITH_BASE_REVISION",
  "rates": {
    "my_video": {
      "source_url": "https://vendor.example/video-pricing",
      "observed_at": "2026-11-25T22:00:00Z",
      "valid_until": "2026-11-26T22:00:00Z",
      "schedule": { "kind": "video", "usd_nanos_per_second": 32000000 }
    },
    "my_audio": {
      "source_url": "https://vendor.example/audio-pricing",
      "observed_at": "2026-11-25T23:00:00Z",
      "valid_until": "2026-11-28T23:00:00Z",
      "schedule": { "kind": "audio", "usd_nanos_per_second": 4000000 }
    }
  }
}

When publishing one updated price, copy all other entries with their original observation times, deadlines, source URLs and rates. A live reload or a check with --previous-feed rejects older observations and changes at the same observation time. An expired entry stays in the reviewed set and remains ineligible until a new observation is approved. Requests retain the price evidence recorded at admission.

Prepare a feed from approved changes

Use catalog prepare-rate-feed to turn reviewed offers into a complete candidate. Use the catalog and binding revisions from the check-rate-feed report. When updating, include the SHA-256 of the last accepted rate file, which can be calculated even after its rates expire. Enter only offers with approved observations.

{
  "version": 1,
  "base_revision": "demo_REPLACE_WITH_BINDING_PINNED_REVISION",
  "catalog_file_revision": "demo_REPLACE_WITH_CATALOG_FILE_REVISION",
  "previous_feed_sha256": "REPLACE_WITH_LAST_ACCEPTED_FILE_SHA256",
  "rates": {
    "my_video": {
      "source_url": "https://vendor.example/video-pricing",
      "observed_at": "2026-11-25T23:00:00Z",
      "valid_until": "2026-11-26T23:00:00Z",
      "schedule": { "kind": "video", "usd_nanos_per_second": 32000000 }
    }
  }
}
api-gateway catalog prepare-rate-feed --catalog catalog.json --approved approved.json \\
  --previous-feed rates.json > rates.next.json
api-gateway catalog check-rate-feed --catalog catalog.json --feed rates.next.json --previous-feed rates.json

For an initial feed, omit both previous_feed_sha256 and --previous-feed. For an update, the command copies the other offers and preserves each observation and deadline. A legacy shared window is expanded into individual windows. Use the gateway's existing review and atomic replacement procedure to publish the candidate. Rerun preparation against the latest file if another operator publishes during review.

Carry reviewed rates into a preset update

After preparing a preset-only catalog update, use the deployment's binding configuration and a copy of its last accepted feed.

api-gateway catalog rebase-rate-feed --base catalog.json --candidate catalog.next.json \
  --feed current-rates.json > rates.next.json

The command checks the candidate against the base with the same preset-only rules as catalog review. It reads the configured bindings once, then validates the feed against both catalog revisions. The output carries the same rates, sources, observation times, and deadlines under the new base revision. Use newly reviewed observations if every rate has expired.

Deploy the two candidate files together on API and worker replicas. Keep the previous pair available for rollback until its feed expires.

Collect OpenRouter list prices

Collect OpenRouter pricing for the exact upstream model IDs in the operator catalog.

api-gateway catalog observe-openrouter --catalog catalog.json > openrouter-observations.json

The command uses the public models endpoint and writes a JSON report. Use --input snapshot.json to read a saved response. The report includes the source, response SHA-256, original pricing fields, and exact list rates in USD nanodollars per 1,000 tokens. A file observation leaves the fetch time unset. Record the supplier observation time when reviewing rates from a saved response. OpenRouter models API

Review list_rates and any populated additional_price_fields against the applicable billing terms. Extra prices, such as search or cached inputs, produce review_required. Missing models and rates stay explicit. The command reads the operator catalog and writes observations to stdout. Deploy approved rates through the reviewed feed using the base_revision from your running gateway. The report's catalog_file_revision identifies the input file.

Collect fal endpoint prices

Match configured fal queue offers to the pricing API's exact endpoint IDs.

api-gateway catalog observe-fal --catalog catalog.json --input fal-prices.json > fal-observations.json

Omit --input and supply TOKENCRAFT_FAL_PRICING_KEY in the command's environment to fetch prices directly. The command queries up to 50 distinct endpoints per request and reports a SHA-256 checksum for each response. Supply complete responses when using a saved file. File observations leave the fetch time unset. fal pricing API

Each observation includes the vendor's original billing unit and price, the exact usd_nanos_per_vendor_unit when available, and the active offer's configured schedule for comparison. Check the endpoint's billing terms against the offer's workload before approving a rate. For example, a price per megapixel needs a verified image size, and a price per video second may depend on resolution or audio. Apply approved schedules through the reviewed feed described above. fal model pricing

Review Kinovi credit estimates

Create a probe for a Kinovi queue offer in your operator catalog. Use synthetic text and the same media settings that the plugin sends for the workload you are reviewing. For the example kinovi_sample offer, a probe can look like this. Seedance 2.0 input contract

{
  "version": 1,
  "offer": "kinovi_sample",
  "inputs": {
    "prompt": "A blue square rotating on a plain white background",
    "duration": "5",
    "outputResolution": "720p",
    "aspectRatio": "16:9"
  }
}

Supply TOKENCRAFT_KINOVI_PRICING_KEY in the command's environment. The command sends the offer's upstream model ID and the probe inputs to Kinovi's estimate_cost tool. The tool estimates the task in credits without creating a generation request. Kinovi estimate tool · API key setup

api-gateway catalog observe-kinovi --catalog catalog.json --probe kinovi-probe.json > kinovi-observation.json

For an offline review, pass --input kinovi-estimate.json. Pair the result with the exact probe you used. The saved file records your association between the probe and the result. Replace the digest placeholder below with the SHA-256 of kinovi-probe.json and the illustrative numbers with the credits from that probe.

{
  "probe_sha256": "REPLACE_WITH_PROBE_SHA256",
  "estimate": { "modelId": "seedance-20", "credits": 180, "originalCredits": 200 }
}

To compare in USD, pass --usd-nanos-per-credit with an integer from your Kinovi billing terms. The report uses the estimated credits for the task and produces an exact total when the amount fits at nanodollar precision and the estimate has at most six fractional credit digits. Otherwise it flags the amount for review. Keep the original credit estimate, conversion terms, and probe as review evidence. Verify any per-second or per-generation schedule across its supported workload before applying an approved rate feed. Kinovi billing

Enable the instance Admin dashboard

Use the database operator's admin-cli on the instance to grant or revoke the existing staff role. Use the same database target as the gateway and set TOKENCRAFT_OPERATOR_ID to the desired user ID. A signed-in user can find their ID in user.id at GET /v1/auth/me.

admin-cli staff grant "$TOKENCRAFT_OPERATOR_ID"
admin-cli staff revoke "$TOKENCRAFT_OPERATOR_ID"

An operator can open /admin from the console and drill down from accounts to projects and credentials. The report includes request counts, estimates and supplier settlements for the selected UTC dates. Key inventory also shows revocation and expiry, the recorded creator when available, and last activity. It reflects accounts in the connected gateway database. Self-hosted instances retain their own reporting.

Run behind an HTTPS ingress

Set FOUNDATION_ENV=production or FOUNDATION_ENV=staging and set TOKENCRAFT_CORE_CATALOG to your operator-reviewed catalog. Both environments use the same production safeguards for any operator.

Production setting Value
DATABASE_URL PostgreSQL TCP URL with sslmode=verify-full. Use the hostname on the server certificate and set sslrootcert in the URL when the server uses a private CA.
APP_BASE_URL HTTPS console origin, for example https://console.example.com. Use the origin without a path.
COOKIE_SECURE true. The hosted session cookie is bound to the API host.
SESSION_SECRET, TOKENCRAFT_DEMO_PAYLOAD_KEY Generate a separate value for each with openssl rand -hex 32. Share the same values across replicas and preserve the payload key with the database backup.
TOKENCRAFT_CONTENT_ENCRYPTION_KEY, TOKENCRAFT_CONTENT_ENCRYPTION_READ_KEYS Optional settings for rotating request content encryption. Stage read keys on all API and worker replicas before promoting a new write key.
TOKENCRAFT_LISTEN_IP, API_GATEWAY_PORT Private HTTP listener. Defaults to 127.0.0.1:4000. Set a literal IP explicitly if an ingress or probe needs to reach it from another container.
TOKENCRAFT_CORE_CATALOG, binding registries Configure the real services that will execute the offers. The production profiles accept connector-backed offers.

Apply migrations and grant runtime access before starting the API or worker. The binaries check the migration history before opening a listener. Run api-gateway with TOKENCRAFT_PROCESS_ROLE=api or worker for independent scaling. If the roles run on the same machine, assign distinct ports. Database role setup

SIGTERM and SIGINT withdraw readiness and stop new worker claims. Each gateway allows up to 18 seconds for active HTTP responses and already-started background work to finish. If the window expires, the gateway exits with a failure status and the durable queues retain their lease and recovery state. Use the cell admission pause for a full deployment drain.

Each API replica bounds password hashing and verification to one to four concurrent operations based on its available CPUs. When those slots are busy, password login, signup, and password-protected account changes return 503 password_capacity with Retry-After: 2. Clients can retry the same action after that delay.

Each API replica shares four PostgreSQL report slots across project Usage, staff Usage, and MCP get_usage. Busy HTTP reports return 503 usage_capacity with Retry-After: 2. Report statements use an eight-second database deadline or the database's shorter configured timeout. A report that hits the deadline returns 503 usage_report_timeout. A disconnected caller's slot stays occupied until its PostgreSQL statement stops. PostgreSQL plans each report using its actual UTC window and filters. Shorter windows reduce the work for large projects. The existing private Operations probe exposes occupied report slots and per-process counts of rejections and timeouts.

Avatar, file, and workflow image uploads share two decode slots per replica. The decoder accepts PNG, JPEG, WebP, and GIF up to 8,192 pixels on either axis and 33,554,432 pixels in total, within a 64 MiB decode allocation budget. Image processing capacity returns 503 image_processing_capacity with Retry-After: 2. Workflow uploads verify the declared type against the image and retain the original file bytes and checksum.

Terminate public TLS at the ingress and keep the gateway's HTTP listener private. Forward streaming responses without buffering. Replace incoming X-Forwarded-For with one literal client IP verified by the ingress and restrict worker /ready probes to the private network.

Build the console with npm ci --ignore-scripts and npm run build in frontend/. The build uses its own origin. Forward /v1/, /ready, and /openapi.json to the running gateway so the console can check its supported filters. Serve the release contract at /docs/openapi.json and use the page fallback for application routes. Serve release assets such as /release.json before applying the fallback.

Set VITE_API_BASE_URL at build time to use a separate HTTPS gateway. Place both origins on the same site, such as console.example.com and api.example.com. Set APP_BASE_URL to the console origin so browser CORS and session writes are scoped to it. The session cookie is bound to the API host.

Run node scripts/console_security_headers.mjs for browser security headers, including the standalone design's content hashes. Pass --api-origin https://api.example.com when the console build targets a separate gateway. Apply the generated console headers to static content and the manifest headers to /release.json. Use the gateway's cache policy on proxied responses. Scoped API responses and errors use Cache-Control: private, no-store. The gateway OpenAPI and primitive schema allow a five-minute public TTL. Keep readiness responses fresh.

Use the same Git commit for console and gateway release builds. Set TOKENCRAFT_SOURCE_REVISION on the console and gateway build, or pass the revision through native_package.py --source-revision or the container's SOURCE_REVISION argument. Set TOKENCRAFT_REQUIRE_SOURCE_REVISION=1 to require the console build stamp. Preserve the gateway's TokenCraft-Source-Revision header at the ingress. The console manifest records the entry HTML and JavaScript and CSS hashes.

source_revision="$(git rev-parse HEAD)"
bash scripts/smoke_hosted_console.sh https://console.example.com https://api.example.com \
  "$source_revision" frontend/dist/release.json

Use the manifest from the build that produced the deployed files. The read-only check compares both console copies and the running gateway with the release contract, checks source revisions and cache headers, and verifies asset digests. The Container smoke workflow runs this same check with a loopback proxy and retains the tested manifest in its tokencraft-console-release-manifest-* artifact for main and release builds.

Before reopening submissions, pick an existing successful request with a gateway trace and a readable warm result. Inject a project key with requests:read and usage:read into TOKENCRAFT_SMOKE_API_KEY.

python3 -B scripts/smoke_authenticated_gateway.py \
  --api https://api.example.com --peer https://console.example.com \
  --revision "$source_revision" --request-id "$previous_request_id"

This mode uses GET requests to check the saved result, media digests, trace, scoped history, and usage for the UTC day of admission. With --peer, both origins must agree on the receipt identity and result. It repeats the scoped reads without a key and requires gateway denials. Scoped responses must be private and non-storable. If an ingress sets Age, it must send one value of zero. Omit --peer for a console that connects directly to the gateway rather than proxying API routes.

For deployments with the bundled example_image connector, run the authenticated check with a dedicated project key in TOKENCRAFT_SMOKE_API_KEY. Grant it requests:submit, requests:read, and usage:read. Supply --peer only if that trusted origin serves the same deployment.

python3 -B scripts/smoke_authenticated_gateway.py \
  --api https://api.example.com --peer https://console.example.com --revision "$source_revision"

With the revision set, both modes check a fresh, non-storable readiness response before sending the scoped key, then require the expected revision on each response they read. The synthetic mode submits one image with a zero-cost cap and replays its receipt. It verifies the PNG digest, connector trace, and one usage record scoped to the run. Inject the scoped project key into the process environment from your secret manager. For a private HTTPS ingress, supply its trusted CA bundle with --ca.

To deliver signed customer webhooks, set TOKENCRAFT_DEMO_WEBHOOK_CONFIG to an operator-maintained JSON registry such as {"destinations":{"customer_updates":"https://events.example.com/tokencraft"}}. Give the API and workers the same independent 32-byte hex TOKENCRAFT_DEMO_WEBHOOK_KEY. Hosts use the standard public certificate roots by default. Set TOKENCRAFT_WEBHOOK_CA_FILE to an operator-managed PEM bundle to use a private trust store for all webhook destinations. Tenants select a registry entry by ID. Register reviewed HTTPS destinations and set egress policy for the hosts you allow. TLS verifies the destination hostname and the client rejects redirects.

A worker can send only when its registry contains the subscription's saved destination ID and URL. During a registry rollout, a matching worker can pick up queued deliveries within their original retry window. A worker with a different registry can still close expired or revoked deliveries. Roll out this worker behavior across the cell before changing registry entries, then keep the original destinations available until their pending deliveries drain.

When the queue head is unavailable, the worker checks a bounded set of due deliveries. If that probe fills, it searches all active subscriptions so a large paused backlog cannot hide independent deliveries.

Each worker runs up to four delivery attempts at a time. When three attempts target the same origin and other origins are configured, the fourth slot stays available for a different origin. Destination aliases with the same scheme, host, and port share capacity. A deployment with one receiver origin can use all four slots per worker. Workers return to 250 ms claim polling when delivery work resumes. An idle worker backs off to one poll per second.

An acknowledgement can still settle the current attempt after its lease expires. When another worker takes over first, it records the old lease as expired and retries with the same event ID and body. Receivers should deduplicate by webhook-id because a successful delivery can be retried after a lost response or worker restart. Revocation prevents new attempts and redrives. An attempt already leased when revocation commits may finish.

To retry a failed delivery with a recoverable receipt, send POST /v1/projects/{project}/webhook-deliveries/{delivery}/redrives with the account scope, a fresh Idempotency-Key, and expected_version set to the delivery’s current redrive_version. The same administrator can repeat that key and version to confirm the latest retry after a lost response. Only a new retry advances the version, and each retry delivers the original event.

For retryable responses, the worker honors Retry-After in seconds or as an HTTP date, up to 60 seconds. It waits at least the normal backoff and retains the scheduled retry in PostgreSQL. HTTP 429 and 503 also pause new claims for the saved receiver URL across workers. The shared pause uses the positive Retry-After delay when supplied and lasts two seconds otherwise. Destination aliases sharing the exact URL observe the same pause. Workers skip the URL while a cooldown write is in progress. Work already leased can finish, and other URLs can keep receiving events. HTTP Retry-After

Separate migration and runtime roles

Use a dedicated PostgreSQL 17 database whose owner applies migrations and owns the TokenCraft objects in the public schema. Give the API and worker a separate login with an independent credential. The runtime login needs no database ownership, elevated role membership, or permission to create objects in public. In clusters upgraded from an older PostgreSQL release, check whether PUBLIC still has CREATE on that schema and revoke it in the dedicated database if needed.

With the migration owner's verified DATABASE_URL configured for admin-cli, apply migrations. In staging and production the CLI requires a TCP connection with sslmode=verify-full before it connects. Run the grant script against the same database as the migration owner. The example uses a PostgreSQL service definition called tokencraft_migration with sslmode=verify-full. Keep the password in your secret configuration. The grant script is included in the source checkout and native package. When deploying only the runtime image, extract its matching copy before running psql.

docker run --rm --network none --entrypoint cat tokencraft-gateway:0.1.0 \
  /opt/tokencraft/deploy/postgres/grant-runtime.sql > grant-runtime.sql

Use -f grant-runtime.sql below when using the extracted copy.

FOUNDATION_ENV=production admin-cli migrate
psql -X "service=tokencraft_migration" -v runtime_role=tokencraft_runtime \
  -f deploy/postgres/grant-runtime.sql

The grant script grants access to the owner's application tables, views, sequences, and invoker functions. It gives the runtime role read-only access to the migration ledger and any schema compatibility declarations. Reapply it after each migration before sending traffic to the new replicas. Configure the API and worker with the runtime login in DATABASE_URL. Keep the migration login in the one-off deployment job.

Shared artifact storage

Each API replica permits eight concurrent warm downloads of generated media, including generated workflow outputs. It reserves two additional slots for retained media and two for workflow tool outputs. The replica holds each slot until it releases the response buffer. When a limit is reached, retry the same download after the two-second Retry-After from the 503 artifact_download_capacity response.

Use a private S3-compatible bucket to serve generated media from multiple gateway and worker replicas. Apply migrations and upgrade both roles before enabling bucket writes. Configure these values on the API and workers. New artifacts use the bucket when configured. Keep the original TOKENCRAFT_DEMO_ARTIFACT_DIR mounted until existing filesystem results expire or archive. PostgreSQL continues to serve existing inline artifacts.

Gateway configuration Value
TOKENCRAFT_ARTIFACT_S3_ENDPOINT Region-specific HTTPS origin. Literal loopback HTTP is accepted for local fixtures.
TOKENCRAFT_ARTIFACT_S3_BUCKET Private unversioned bucket with Object Lock disabled.
TOKENCRAFT_ARTIFACT_S3_REGION Bucket signing region.
TOKENCRAFT_ARTIFACT_S3_ACCESS_KEY, TOKENCRAFT_ARTIFACT_S3_SECRET_KEY Credentials with s3:GetObject, s3:PutObject, and s3:DeleteObject for the artifact prefix.
TOKENCRAFT_ARTIFACT_S3_SESSION_TOKEN Optional temporary credentials. Restart with fresh credentials on rotation.
TOKENCRAFT_ARTIFACT_S3_PREFIX Defaults to tokencraft-artifacts/v1. Use a dedicated prefix for active media.

Replicas serving the same database need the same artifact target and persistent payload key. TokenCraft namespaces objects by its database identity, verifies encrypted uploads before committing the result, and serves bytes through the same scoped artifact endpoint. Workers reclaim abandoned uploads and delete live objects after expiry, early removal, or verified archival. The artifact storage probe reads a small marker in the configured prefix. The private Operations console collects the result through /internal/capacity.

An S3 outage keeps API-serving processes in rotation while their core readiness checks pass. Request status, catalog, and usage stay reachable. A download that needs the bucket returns HTTP 503, and pending media results await verified storage. The authenticated capacity probe reports the artifact failure. Worker-only /ready requires storage. Filesystem readiness can withdraw a replica whose local storage fails.

Keep the active prefix readable for the lifetime of the saved results. Use the separate request content archive for lifecycle transitions to cold storage. Bucket deletion must permanently remove the current object for cleanup to complete. S3 object deletion

Gravatar imports

Give the sweeper the same DATABASE_URL as the gateway. Set R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and R2_BUCKET_NAME on the sweeper for S3-compatible avatar storage. Set R2_REGION if your storage service requires a region other than auto. Set CDN_BASE_URL on the gateway to the public base URL that serves those avatar objects.

Run the sweeper alongside the gateway after the database migrations are applied.

cargo run --locked -p sweeper

The sweeper imports Gravatars after signup and email changes, and when a signed-in user selects Check or Refresh in Settings. The console loads the mirrored image from the configured CDN. Users can also choose initials or remove the mirror. The credential-free quickstart only displays initials until avatar storage and the sweeper are configured.

Successful result retention

By default, the gateway stores successful chat results for one hour and generated media for 24 hours. For newly admitted connected chat and media, operators can opt into 30-day warm history and archival through day 395 with a filesystem directory or an S3-compatible bucket. Result and artifact reads enforce the saved deadline. At expiry the worker clears the encrypted result, stream chunks, and artifact references and publishes a scoped request.content_removed event. This is the same removal path used for early project administrator deletion. Request state, trace timing, and accounting stay queryable. File cleanup removes unreferenced artifacts asynchronously.

Check a connector rollout

Run the drain check against the deployment database with the candidate catalog and the candidate binding environment. Include TOKENCRAFT_WORKFLOW_TOOL_BINDINGS and the referenced service token variables if the deployment uses workflow tools. Include TOKENCRAFT_DEMO_RATE_FEED when the candidate uses a reviewed rate feed. DATABASE_URL can use a role with read access to requests, provider runs, connector completion state, provider credential state, workflow runs, and routing policies. Use verified PostgreSQL TLS for a remote database. The command reads a point-in-time snapshot in a read-only transaction.

api-gateway catalog check-drain --catalog catalog.next.json

The JSON report gives the candidate base revision and counts by offer, request phase, and pinned binding digest. It also reports checked_workflow_tool_references and workflow_tool_blockers. One reference represents an active, unexpired run and one pinned tool operation revision. An active run can contribute more than one reference. The check uses the saved graph, including tool steps the run may already have completed. It reports counts without account, project, or run IDs, and checks configuration without contacting tool services. A blocker makes the command exit nonzero. Wait for outstanding work with the previous workers in place, then rerun the check close to cutover.

checked_workflow_generation_references and workflow_generation_blockers cover saved generation requirements in those same runs. One reference represents an active run and one distinct saved generation requirement. The checker uses the candidate bindings, first-frame support, fixed dimensions or token limits, current routing policy, and reviewed rates. For dynamic values it looks for a possible compatible workload and checks the minimum cost implied by the saved settings. For text, PostgreSQL returns the byte lengths of fixed messages. The checker receives no message content or workflow inputs. Provider credentials, temporary availability, and the resolved workload are evaluated again during execution.

Blocker What to preserve
queued_offer_changed Keep the original offer and its active binding until queued requests dispatch. The check uses the saved provider, upstream model, and binding identity. Rate-only changes preserve queued pins.
binding_unavailable Keep the original binding for in-flight work, submission recovery, and eligible rechecks. For queued media, a retained drain_only entry serves polling and recovery after the original offer stops accepting new work.
legacy_adapter Keep a worker that supports the original built-in adapter until its outstanding work finishes.
tool_binding_unavailable Keep the original workflow tool binding. Its name, revision, origin, and manifest determine its saved digest.
tool_scope_unavailable Retain the account and project authorization required by the active workflow run.
tool_operation_unavailable Retain the pinned tool operation and revision in the reviewed manifest.
generation_route_unavailable Retain a usable route for the saved model and workload in the affected projects. Check active bindings, connector capabilities, policy, and estimated cost against the step's cap.

When replacing a queue connector, provision a new binding name. Keep the old origin, revision, and completion settings available until the old work drains. A drain-only worker polls and recovers existing jobs on that binding. Workers with the active binding continue to claim submissions during cutover. Continue to coordinate admissions during cutover and review provider access and pricing for the candidate. Connector protocol

For a workflow tool, a drain_only binding remains eligible for admitted runs. Upgrade all workflow workers before rolling out different tool registries across the worker pool. Workers claim live runs only when their local configuration authorizes every pinned tool binding for that run's project. Any workflow worker can expire a due run at its deadline. Publish the revised workflow against the replacement binding before resuming new runs. Workflow tool bindings

Routing policy precedence

Provider preferences take the first configured value from the request, project, or organization. They apply to named models and to model: "auto". Eligible offers are ranked by provider preference first and then by the configured ranking within that group. Send preferred_providers: [] to rank by the lowest estimate. Automatic model selection also resolves minimum community quality and recent usage from the request, project, or organization. Hard budgets, provider allowlists, and data-handling requirements still apply.

Reliability and settled-cost ranking use up to 100 matching outcomes per offer from the previous seven days in the same project and client scope. They match the workload, accepted binding, upstream model, served offer, and saved output shape. Both strategies require 20 samples per eligible offer in the group. Settled-cost ranking uses completed UTC days and compares outcomes served on the originally quoted offer at the current estimate. It requires a settlement for each sample, comparable output shapes, and at least one completion in the group.

On scoped media endpoints, set model: "advise" to choose a concrete model using the gateway's catalog, eligibility policy, and scoped ranking. The project or organization can also enable this path when callers omit the model. To submit an advised preview, use the model returned in input.model and its quote_id.

Balance API replicas within a cell

Run the HAProxy 3.2+ configuration on a private network between trusted HTTPS ingress and the API replicas for one cell. It works with one replica and discovers additional replicas from a private DNS record. The optional organization router forwards to the selected cell’s proxy tier. Each proxy has one cell’s DNS target, so an unavailable API pool fails within that cell.

Client → HTTPS ingress → optional organization router → cell HAProxy → ready Axum replica
                                                                            ↓
                                                                     cell PostgreSQL

Configure the private proxy

The HTTPS ingress must replace incoming X-Forwarded-For with one client IP it verified, preserve the original Host and application headers, and stream responses without buffering. Configure any intermediate organization router to preserve that single verified address. Restrict the proxy listener to trusted ingress peers at the network boundary and restrict API listeners to the cell’s proxy peers. The proxy also checks the source allowlist. Use a private resolver that returns only API-role backends belonging to this cell. Keep every replica on the cell’s PostgreSQL database and shared artifact storage with matching session and payload keys.

Setting Example or meaning
TOKENCRAFT_LB_BIND Private listen address and port, such as 10.20.1.10:8080.
TOKENCRAFT_LB_TRUSTED_INGRESS_FILE Absolute path to a file with one trusted ingress IP or CIDR per line. Include only the ingress and probe sources the proxy will actually see.
TOKENCRAFT_LB_API_ADDRESS Use a cell-specific DNS name and common port, such as api.cell-a.internal:4000, or an SRV service name without an appended port, such as _tokencraft._tcp.cell-a.internal. Each SRV record supplies the target hostname and port for one API replica.
TOKENCRAFT_LB_API_SLOTS Maximum number of discovered replicas this instance can hold. Start with a ceiling that fits the cell and DNS response size, such as 32.
TOKENCRAFT_LB_MAX_CONNECTIONS Total incoming connection limit per proxy process.
TOKENCRAFT_LB_CONNECTIONS_PER_API Connection limit per API replica from this proxy. Size it across all proxy replicas, with headroom for PostgreSQL pools and long-lived streams.

Set the variables above in the service environment. Validate the configuration with haproxy -c -f deploy/haproxy/cell-api.cfg and run HAProxy in the foreground with haproxy -db -f deploy/haproxy/cell-api.cfg under the platform service manager.

HAProxy checks each replica’s GET /ready. Newly discovered replicas start down and become eligible after successful checks. The proxy uses least connections for a mix of short requests and longer streams, bounds how long a request waits for a connection, and gives streams a 120-second idle window. A protected GET /_tokencraft/ingress-ready returns 200 when the proxy has an eligible API replica and 503 otherwise. While all replicas are withdrawn, HAProxy adds Retry-After: 5 and Cache-Control: no-store to its 503 responses. The gateway still serves its regular /ready endpoint.

The proxy forwards requests once. Configure upstream ingress to avoid automatic submission retries as well. After a lost reply, callers can retry with the original idempotency key and intent. Stream reconnects recover retained chunks from cell state. The proxy logs replica selection, response status, queue time, connect time, and response timing.

Scale and verify the cell

The capacity guide describes the organization submission bucket, self-service quota tiers, and the opt-in, signal-driven API and worker controller.

Run redundant proxy instances across the cell’s failure domains and configure HTTPS ingress to check each instance’s private readiness endpoint. Keep an instance serving while replacing another. Drain API replicas before stopping them and give active streams time to finish. Load-test simultaneous streams, small reads, and submissions. Measure ready replica count, queue time, connection saturation, tail latency, stream disconnects, and PostgreSQL pool waits. Verify that the remaining replicas can handle peak traffic when a zone is removed. Add cells when database capacity or failure isolation calls for it.

Workers still share jobs through PostgreSQL lease claims. Self-hosted inference uses the cell’s configured compute binding, including its eligible targets and fallback rules. An internal replica service is optional for a group of interchangeable model servers in one placement and policy domain. Managed providers operate their own inference load balancing.

Each provider worker has four in-flight task slots shared by submissions, polling, and connector receipt lookup. Workers rotate the first choice among these queues when they claim work. A worker with multiple destinations limits each destination to three slots so another destination can keep serving during a stall. Direct connector and chat bindings with the same scheme, host, and port share that limit, including during a binding rollout. A compute stack counts as one destination. A worker with one destination can use all four slots. These limits apply per worker process.

Submission and poll claims skip a candidate while either its request row or provider run row is locked. The worker can claim other eligible work and revisit the candidate after the lock clears.

Provider deadline cleanup also skips locked requests and provider runs so independent expired jobs can be processed in the same cycle.

Scheduled result, retained-content, and interrupted-stream cleanup skip busy provider rows. Retained-content expiry also skips a locked history row before clearing its payload and scheduling archive deletion.

Request queue advancement and maintenance run independently on each worker. Each cleanup step uses its own transaction with a 500 ms lock wait and a three-second statement deadline, or a tighter PostgreSQL setting. The worker logs a failed step, continues with later cleanup, and retries on its next pass. A step has an eight-second total deadline.

With HAProxy 3.2+ available, run python3 deploy/haproxy/smoke.py in a disposable local environment. It checks configuration parsing, two fixture API replicas, readiness withdrawal and recovery, forwarding headers, SSE streaming, and a submission whose upstream disconnected after receiving the body. HAProxy configuration reference

The gateway CI rehearses live DNS discovery and chat streaming with HAProxy 3.2, two TokenCraft API processes, and a worker on shared PostgreSQL 17. The fixture publishes a new SRV record while a stream is open, then stops the replica carrying it. The surviving replica must replay the same request ID and retained chunk, then deliver the final chunk, usage, and [DONE]. The rehearsal also checks sibling-client isolation, one upstream inference call, and removal of the retired replica from discovery. Run the same check locally with HAProxy 3.2 or newer and PostgreSQL 17 on the path.

python3 -B scripts/smoke_stream_failover.py target/debug/api-gateway target/debug/admin-cli

Repeat in staging with the deployment's private resolver and HTTPS ingress, and exercise loss of a proxy or zone under load.

Route project API traffic to home cells

Use the organization router when independent cells share a project API hostname. Deploy each cell with its own Postgres writer and artifact namespace. Give each cell a stable ID and use it in its compute bindings and monitoring profile. Each cell can run its own organization-specific compute or use the same external providers as other cells.

The router runs on private ingress with HAProxy 3.2+ built with OpenSSL. The shared hostname routes requests authenticated with Authorization: Bearer <project-key>. Use cell-specific ingress for browser sessions, account API keys, credential issuance, and connector callbacks. The destination gateway authorizes the request, including checking key expiry, revocation, and scope.

Setting Value
TOKENCRAFT_ROUTER_BIND Private listener address and port
TOKENCRAFT_ROUTER_MAX_CONNECTIONS Total incoming connection limit
TOKENCRAFT_ROUTER_TRUSTED_INGRESS_FILE Absolute path to the trusted HTTPS ingress and probe IP allowlist
TOKENCRAFT_ROUTER_PROJECT_KEYS_MAP Absolute path to a space-separated map with one lowercase SHA-256 project key digest and account ID per line
TOKENCRAFT_ROUTER_PLACEMENTS_MAP Absolute path to a space-separated map with one account ID and home cell ID per line

Provision a new organization in its home cell and issue project keys there. Use the stored key_hash and account_id columns from that cell's gateway_project_keys table to populate the project key map. Keep raw keys out of the router configuration. Publish each key's route before clients start using it, and remove stale routes when rotating or revoking keys. The gateway enforces revocation even while the map is stale. Publish the maps and backends as one configuration revision, with a single home cell per organization.

In a separate backends.cfg, declare one backend per cell. Use the prefix cell- followed by the cell ID from the placement map. Point each backend at private cell ingress and include the organization router's source addresses in the cell ingress allowlist.

backend cell-studio from organization_router_http
    option httpchk GET /_tokencraft/ingress-ready
    server ingress studio-ingress.internal:8080 check

Validate with haproxy -c -f deploy/haproxy/organization-router.cfg -f backends.cfg and run with haproxy -db -f deploy/haproxy/organization-router.cfg -f backends.cfg under the platform service manager. Use the private router's GET /_tokencraft/router-ready to check its listener and the cell readiness endpoints to check each destination. Probe a scoped API read through each configured route before sending traffic. If a cell is unavailable, its requests return a retryable 503. Configure upstream ingress to preserve streams and avoid automatic submission retries. Clients retry against the same hostname with the same intent and idempotency key.

Placement maps are for assigning organizations to cells that already own their data. Moving an existing organization requires transferring its durable state and fencing the old writer and workers before updating the route.

From the checkout, run the disposable two-cell smoke check with HAProxy and PostgreSQL 17 on the path.

python3 -B scripts/smoke_organization_router.py target/debug/api-gateway target/debug/admin-cli