Providers, aliases & sandboxes.
Route approved text models, run isolated sandboxes, and manage project access from your private dashboard.
Call a public alias
Enable the ai scope on both the project and key, then grant the project access to an alias under Providers → Project service access. Existing AI projects receive the Alextra alias during migration. New projects require an explicit grant.
const answer = await hq.ai.generate("Write a short greeting", {alias: "Alextra"});
console.log(answer.response);
// HTTP: POST /v1/ai/generate
// {"alias":"Alextra","prompt":"Write a short greeting","stream":false}
The response model field now contains the public alias. This additive routing release changes the meaning of that field from backend model ID to public model name. Treat it as an opaque name. Operational logs retain actual providers and models privately. Aliases do not imply that HQ trained the backend model; provider licensing and disclosure requirements still apply.
Abilities and streaming
The normalized API accepts text prompts (4,000 characters), optional alias, and optional stream. Output is capped at 256 completion tokens. Tools, images, structured-output parameters and reasoning controls are rejected on this public text endpoint even when a provider advertises them. During Fetch and verify models, HQ reads provider metadata and sends each compatible model a small real request. Only models that work and return a mainly English response are saved and connected to Alextra. Verification requests can use provider quota or incur charges.
for await (const event of hq.ai.stream("Hello", {alias:"Alextra"})) {
if (event.delta) process.stdout.write(event.delta);
}
// SSE: data: {"alias":"Alextra","delta":"Hello"}
// Final: data: {"alias":"Alextra","done":true}
Streaming requires an eligible model with both chat and stream declarations. SSE output exposes normalized text only. An interruption emits stream_interrupted and closes the stream. No retry or fallback happens after stream headers are committed. Cancel the iterator to cancel the reader. HQ never executes model-produced tool calls.
Routing, health and accounting
Routes must belong to an enabled public alias granted to the project. API keys and models must be enabled and approved, support the requested operation, and be outside cooldown. Eligible provider-model routes share traffic automatically. There is no per-key routing order, traffic weight, request cap, or spending cap to configure. Fallback is off by default. When enabled, at most three candidates are considered. An API key and model pair is attempted once; authentication failures are not repeatedly retried. Authentication failures open a 24-hour circuit, rate limits cool down for 60 seconds, and three failures open a five-minute circuit. An administrator may replace API keys or explicitly reset health.
External calls time out after seven seconds. Workers AI binding calls are bounded by an 18-second response timeout; the binding may finish remotely after that timeout and no automatic fallback follows it. Retries before output can produce duplicate inference charges after ambiguous network failures; this text-only path performs no external tool actions. If no compatible candidate remains, HQ returns no_compatible_provider (503). Existing queues remain at-least-once, so a consumer crash can repeat text inference; use the job’s idempotency key to avoid duplicate submissions.
Usage is attributable only to HQ requests, including explicit admin tests. Each private attempt records project, credential, provider, model, operation, latency, status, and provider-measured tokens when returned. Missing tokens or costs remain null. Prices are entered by the administrator in USD per million tokens; costs calculated from those prices are estimates, not provider-reported charges. Provider-account totals and balances are unavailable in this version.
Projects share the available AI provider capacity. HQ records attempts and measured token details for visibility, while provider account limits and shared ecosystem safeguards still apply. Sandbox concurrency and lifetime controls remain in place to protect running resources.
Provider API key setup and security
Add multiple named Workers AI, OpenAI, Groq, or custom OpenAI-compatible API keys. Saved API keys are encrypted and never returned by list endpoints. Use Test API key to verify access without generating AI output. Replace or delete an API key from the provider form. New providers start turned off and can be turned on directly from the provider list. Fetch and verify models automatically detects abilities, tests English responses, removes failed models, and connects accepted models to Alextra. Groq uses https://api.groq.com/openai/v1, and its API keys begin with gsk_.
OpenAI uses https://api.openai.com/v1; Groq uses https://api.groq.com/openai/v1. Custom AI adapters require GET /models with a data array of IDs and POST /chat/completions accepting messages, model, max_completion_tokens and optional streaming with stream_options.include_usage. The supported response is choices[0].message.content and usage, or SSE text deltas ending in [DONE]. Responses-only APIs, arbitrary tools, audio, images and provider-specific extensions are not compatible. If discovery is unsupported, add model IDs manually.
Custom endpoints require an exact server-configured PROVIDER_ENDPOINTS allowlist on both gateway and AI Workers. Only trusted public HTTPS provider hosts may be allowlisted. Redirects and arbitrary client-selected endpoints are rejected. Do not allowlist user-controlled hosts or private network services.
Create and operate a sandbox
Daytona setup: Add a Daytona provider API key, open Snapshots, fetch the active snapshot catalog, choose one approved snapshot, and then turn the provider on. Run Connection test only after choosing the snapshot; it creates a real temporary sandbox and requests cleanup, so provider usage or charges may apply. Grant the Daytona API key to each project under Project service access.
Enable sandbox on the project and key and grant one or more sandbox credentials. The administrator configures the provider’s approved template/snapshot, concurrency (1–5), and lifetime (60–1,800 seconds). Projects cannot request arbitrary images, environment variables, resource sizes or control-plane secrets. At most two nonterminal sandboxes are allowed per project. Daytona resource sizes come from the selected snapshot, and HQ supplies the hard lifetime. E2B templates must be configured by the owner with an appropriate resource allocation.
const box = await hq.sandboxes.create({idempotencyKey: "build-unique-1"});
let status = await hq.sandboxes.status(box.id);
// If starting, poll status with bounded backoff before file or command operations.
await hq.sandboxes.write(box.id, "/tmp/hello.txt", "Hello");
const file = await hq.sandboxes.read(box.id, "/tmp/hello.txt");
const run = await hq.sandboxes.command(box.id, "cat /tmp/hello.txt", {timeoutSeconds:5});
await hq.sandboxes.destroy(box.id);
HTTP: POST /v1/sandboxes with Idempotency-Key and optional credentialId; GET /v1/sandboxes/{id}; DELETE /v1/sandboxes/{id}; POST /v1/sandboxes/{id}/files with path and optional content; POST /commands with command and timeoutSeconds; POST /preview with port. Daytona additionally supports POST /start and /stop. Stopping its ephemeral sandbox triggers deletion; do not assume it can be restarted. E2B uses create/destroy and does not expose pause/resume here.
Sandbox provisioning returns 202 with a stable HQ ID. Poll status; never assume that a successful create request means startup is complete. Commands are deliberately short (1–5 seconds), with 16 KiB output. File operations support UTF-8 text up to 16 KiB. Long commands and persistent background jobs are outside this initial subset. Execution occurs only at the external sandbox provider. Provider timeouts do not prove that a command did not execute; commands are never replayed.
Running sandboxes stay pinned to their original credential, endpoint and provider ID. New provisions select an available permitted API key automatically; this version does not automatically replay failed provisioning on another credential. Unknown create outcomes remain visible for administrator reconciliation. An explicit later new provision may choose another available credential, but it does not migrate files or processes.
Daytona previews use 60-second signed provider URLs. E2B previews return a private provider URL and a sandbox-specific traffic header; keep that header on your backend. Preview credentials can remain valid until their own expiry after project access changes. Untrusted previews are never served from the admin origin. Do not render arbitrary sandbox HTML on your application’s authenticated origin.
Important work must be saved separately using project files/records or your own durable storage. Sandbox files are temporary and are not a backup. Provider-enforced expiry is the primary lifetime bound; scheduled cleanup also retries known expired resources. Test sandboxes are immediately cleaned up where possible, with complete, pending, failed or unknown cleanup shown honestly. An unknown provider ID requires provider-side reconciliation using the HQ ID metadata.
Custom sandbox adapter v1
A custom sandbox service must explicitly implement this contract; an arbitrary sandbox API is not assumed compatible. Bearer authentication and HTTPS are required. All JSON responses are bounded to 64 KiB and must contain version:1. POST /sandboxes accepts requestId, template, ttlSeconds, resources, privatePreview:true and returns id/status. It must enforce the resource limits, hard TTL, private previews, isolation and idempotency of requestId. GET /sandboxes/{id} returns status (starting, running, stopped, destroyed, failed); DELETE destroys it, and GET subsequently returns 404 or destroyed. POST /sandboxes/{id}/files reads {path} and returns {content}; PUT writes {path,content} and returns {written:true}. POST /commands accepts command, timeoutSeconds, maxOutputBytes and returns stdout, stderr, exitCode. POST /preview accepts port and expiresInSeconds:60, returning a private signed HTTPS url. No HQ credential may be injected into workload environments. Qualify custom adapters with contract tests before enabling them.
Scopes, key reveal and isolation
Each API request rechecks key revocation, project status and scopes in D1; no authorization cache is used. Service access also gates aliases and sandbox credentials. Projects cannot select another project ID or edit their own permissions. Reductions affect subsequent requests immediately; operations already dispatched may finish. Existing queued work may already be in flight, and provider preview credentials have their own lifetime.
New keys keep a SHA-256 verification hash plus a separately AES-256-GCM-encrypted copy. Legacy hash-only keys remain valid and cannot be recovered: rotate once to enable secure reveal. Rotating preserves the project and its domains but invalidates the old key value. Reveal requires an explicit action and an administrator password verification within five minutes, tied to the current login session. Values are cleared from the dashboard after 30 seconds and are never included in lists or audit logs.
Administrator encryption and DNS setup
Configure a dedicated VAULT_KEYS secret on gateway and AI Workers: a JSON object mapping key IDs to independently generated 32-byte keys encoded as 64 lowercase hex characters. Set VAULT_KEY_ID to the active ID. Never reuse SESSION_SECRET. Missing or invalid encryption configuration fails closed. For rotation, add a new key to the ring on both Workers, switch the active ID, re-encrypt stored envelopes using the repository rotation procedure, verify reads, then remove the old key. Preserve encrypted database backups and old keys for their retention period.
To enable DNS application, configure DNS_API_TOKEN on the gateway with only DNS Edit and the required read permissions scoped to the alexstudiohq.com zone, and set DNS_ZONE_ID to that zone. This token is separate from deployment credentials. Without it the admin shows a setup requirement and saves proposals without claiming DNS works.
The hosted site does not need an HQ API key or any HQ API integration. An HQ project is only an inventory label here and can have no enabled services or keys. Add the subdomain to your hosting project manually. Copy its exact required A, AAAA, CNAME or TXT records into Project domains. Only direct, unreserved subdomains of alexstudiohq.com and supported verification labels are allowed. Admin, apex, infrastructure names, MX, NS and zone settings are protected. Existing unrelated records cause a conflict, even if they have similar values. Record names accept short labels (html, _vercel) or full names; short labels expand under alexstudiohq.com and the saved review shows full names. Vercel ownership TXT at _vercel.alexstudiohq.com is supported only when its vc-domain-verify value names this exact project subdomain. Existing unrelated TXT values at that shared verification label are preserved. Proposals are immutable; review before explicitly applying. A partial apply retains created records and reports failure; no unrelated records are overwritten or deleted.
Checks distinguish DNS record saved, public resolution observed, hosting verification (confirmed manually by the administrator), and HTTPS route readiness. A Cloudflare API success is not proof of propagation or a valid hosting certificate. DNS and TLS may take time. The integration does not edit Vercel projects or assume remembered hosting IPs.
Runtime constraints
Cloudflare Free Workers have a small CPU allowance and bounded subrequests. Network waiting is not CPU time, but a disconnected client can end work. This implementation uses short bounded calls and status polling for sandbox startup, not indefinitely open command requests. External AI and sandboxes may be billable. No paid Cloudflare plan is automatically activated.