REST API Reference

REST API Reference

The Huitzo REST API provides programmatic access to all platform capabilities.

Base URL

Production: https://huitzo.ai/v1
Self-hosted: http://your-server:8080/api/v1

Authentication

All API requests require authentication via Bearer token.

curl -H "Authorization: Bearer sk_xxxxx" \
     https://huitzo.ai/v1/commands

Getting a Token

Via API:

POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "your-password"
}

Response:

{
  "data": {
    "tokens": {
      "accessToken": "eyJhbG...",
      "refreshToken": "eyJhbG...",
      "expiresAt": 1740000000000
    },
    "user": {
      "id": "usr_abc123",
      "email": "[email protected]",
      "name": "user",
      "role": "owner",
      "developerMode": false,
      "createdAt": "2026-02-15T10:00:00Z"
    }
  }
}

Response Format

Success Response

All successful API responses wrap the payload in a data envelope. SDK clients must unwrap this envelope to access the actual response data.

{
  "data": { ... },
  "meta": {
    "request_id": "req_abc123",
    "timestamp": "2025-01-22T10:30:00Z"
  }
}

The data field always contains the response payload. The meta field is optional and omitted by most endpoints; it is included only when the server has additional context to convey. The Dashboard SDK handles this unwrapping automatically.

Error Response

All error responses share one envelope. error.message is always present; the other fields appear when the endpoint has them. A command that raised SecretsError, for example:

{
  "success": false,
  "error": {
    "message": "Add PLAID_KEY on the Integrations page.",
    "type": "SecretsError",
    "code": "SECRET_MISSING",
    "details": {
      "correlation_id": "req_abc123",
      "retryable": false
    }
  }
}
Field Type Description
success boolean Always false for errors
error.message string Human-readable error description
error.type string Error class, when the endpoint sets one (for a command, the nearest huitzo_sdk.errors class: see Errors a command raises)
error.code string Machine-readable error code, when the endpoint sets one (see table below)
error.details object Additional context. An endpoint that mints a correlation id for support lookup returns it here, as details.correlation_id

There is no top-level error.correlation_id and no timestamp.

Error Codes

Code HTTP Status Description
VALIDATION_FAILED 400 Invalid input data
AUTHENTICATION_FAILED 401 Invalid or missing token
INSUFFICIENT_CREDITS 402 Preflight reservation refused — insufficient wallet balance
tenant_read_only 402 The acting tenant's Team plan is 45 days past due (read_only, Billing: Team lifecycle): a write outside billing, payment, auth and staff routes is refused; reads work
PERMISSION_DENIED 403 Insufficient permissions
NOT_FOUND 404 Resource not found
TIMEOUT 504 A command exceeded its timeout (CommandTimeoutError)
RATE_LIMITED 429 Too many requests in a window (Rate Limiting)
INLINE_CAPACITY_EXCEEDED 429 Too many inline commands running for the tenant or the server (details)
INTERNAL_ERROR 500 Unexpected server error
INTEGRATION_ERROR 502 External service failure
SERVICE_UNAVAILABLE 503 Service temporarily unavailable

Billing error codes

Every error code of the D-024 billing surfaces, with its HTTP status (ADR-041 error codes, billing.md). The code is error.code, or error.details.code on the staff routes. The linked section says when each is raised.

Code Status Surface
INSUFFICIENT_CREDITS 402 The chokepoint: no allowance and no balance, no tenant account, or a frozen or closed account (details)
RESERVATION_UNAVAILABLE 503 The chokepoint reached no decision (details)
tenant_read_only 402 A write on a read_only Team tenant (billing: Team lifecycle)
team_managed_billing 409 Wallet money writes on a team_* tenant (tenant wallet)
house_plan_no_topup 409 Wallet money writes on a house tenant (tenant wallet)
paid_balance_cap_exceeded 400 A top-up over the $1,900 paid-balance cap (PAYG top-up)
auto_recharge_unavailable_region 403 Enabling auto-recharge for a Mexican consumer or an unknown country. error.details.reason is mx_consumer or unknown_country: the second clears with a first top-up that records a billing address (auto-reload policy)
wallet_account_frozen, wallet_account_closed 409 A top-up or auto-recharge on a wallet a chargeback froze or closed; wallet_account_closed also refuses a staff unfreeze (unfreeze)
billing_address_required 409 Arming auto-recharge with lot owner capture on and no country on file (auto-reload policy)
payg_refunds_disabled 404 The refund route with HUITZO_PAYG_REFUNDS_ENABLED off (paid-lot refund)
lot_not_refundable 409 A refund of a lot that is not an untouched paid lot inside 30 days (paid-lot refund)
billing_profile_required 409 Team provisioning or a usage block without a complete business profile (billing profile)
billing_profile_not_found 404 Reading a profile the tenant does not have (billing profile)
team_stripe_invoice_out_of_scope 409 stripe_invoice provisioning with the invoice rail off (Team subscription)
team_subscription_exists 409 Provisioning a tenant that already has a live row (Team subscription)
team_subscription_changed 409 A concurrent change; re-read and retry (Team subscription)
team_subscription_canceled 409 Changing a canceled row (Team subscription)
team_subscription_already_canceled 409 Canceling a canceled row (Team subscription)
team_subscription_illegal_transition 409 A reactivation or plan change from a status that does not allow it (Team subscription)
team_subscription_incompatible_billing_mode 409 A stripe_invoice row PATCHed with the invoice rail off (Team subscription)
team_subscription_off_catalog_plan 409 An invoice-row plan change on a row that is not on a Team plan (Team subscription)
team_subscription_missing_stripe_id, team_subscription_missing_version 409 A malformed legacy row (Team subscription)
team_downgrade_requires_period_end 409 An invoice-row downgrade with the lifecycle v2 off (Team subscription)
team_pending_change_exists 409 A second scheduled change (Team subscription)
team_lifecycle_v2_disabled 400 cancel_at_period_end with the lifecycle v2 off (Team subscription)
team_usage_blocks_disabled 404 Any usage-block route with its flag off (usage blocks)
usage_block_below_minimum, usage_block_above_maximum 400 A block under 5,000 or over 1,000,000 credits (usage blocks)
billing_contact_email_required 400 A block for a tenant with no Stripe customer and no recipient (usage blocks)
usage_block_requires_team_plan 409 A block for a tenant without a live team_* plan (usage blocks)
usage_block_idempotency_key_reused 409 An Idempotency-Key replayed with a different body (usage blocks)
usage_block_voided_during_issue 409 The block was voided while its invoice was issued (usage blocks)
usage_block_already_paid 409 Voiding a paid block (usage blocks)
usage_block_not_found 404 No such block in the tenant (usage blocks)
usage_block_invoice_failed, usage_block_void_failed 502 Stripe could not issue or void the invoice (usage blocks)
promo_grant_not_found 404 Approving or rejecting an unknown promotional-grant request (promo grants)
promo_grant_already_decided 409 Approving or rejecting a request that is not pending (promo grants)
pack_pricing_version_not_found 404 Approving or rejecting an unknown pack pricing version (pack pricing review)
pack_pricing_version_already_decided 409 Approving or rejecting a version that is not pending_review (pack pricing review)
pack_pricing_nothing_to_submit 409 Submitting a pack pricing version with nothing to submit (pack pricing versions)
pack_pricing_conflict 409 A concurrent pack pricing submission or decision won; retry (pack pricing versions)
invalid_pack_ref 422 A Hub price read names a pack that is not @scope/name (catalog pack prices)
too_many_pack_refs 422 A Hub price read names more than 100 packs (catalog pack prices)
house_plan_disabled 404 Any house-plan route with its flag off (house plan)
house_billing_mode_invalid 400 House provisioning in a mode other than internal (house plan)
house_tenant_has_non_staff, house_plan_exists, tenant_has_plan, house_budget_below_usage 409 House provisioning and budget writes (house plan)
house_plan_missing 404 A budget PATCH on a tenant not on house (house plan)
house_tenant_staff_only 409 Admitting a non-staff member to a house tenant (house plan)
membership_admission_unavailable 503 The house admission check could not run (house plan)
home_tenant_has_plan, home_seat_limit_fixed 409 Staff tenant edits (tenant kind)
invalid_seat_limit 422 A hosted staff tenant create or edit whose quotas.max_seats is not an integer of at least 1 (tenant kind)
tenant_has_ledger_rows 409 A tenant or account delete refused because ledger rows must be kept (ledger retention)
tenant_has_live_plan 409 A tenant or account delete refused while the tenant has a live Team subscription; cancel it first (SaaS retention hook)
account_has_ledger_rows 409 An account delete in a shared home refused because the caller's own credit account holds ledger rows (account delete)
tenant_tombstoned 409 Editing a tenant kept only for ledger retention (ledger retention)
tenant_retention_unavailable 503 The ledger-retention check could not run, or the delete lost a lock conflict; retry. Nothing was deleted (ledger retention)
tenant_quota_exceeded 409 An admission or write past a tenant quota, seats included
license_limit_exceeded 409 A Core edition licence limit is reached; details {key, limit, current, attempted_delta, scope} (Core editions)
license_count_unavailable 503 A licence limit applies and its usage count could not be read; nothing ran. Retry

Insufficient Credits Error (402)

Two chokepoint families can produce this error. They share the same code, http_status and error.details fields: required, available, wallet_id and auto_reload_state are filled the same way for both. wallet_id is null (absent) and auto_reload_state is forced to "disabled" when the tenant has no account or is read_only; on every other refusal auto_reload_state is the wallet's real state, which is also "disabled" when auto-reload was never configured. units_remaining is added only on a reservation refusal and on a managed no-account refusal, and only when the tenant has a drawable allowance period (see Tenant wallet below); it is omitted on read_only, frozen or closed-account and pack-price refusals:

  • TTS, compute, and command/pipeline execution (T-031) perform an atomic ADR-035 §4 preflight reservation before any provider work starts, gated behind HUITZO_SAAS_BILLING_ENABLED (dark by default — docs/architecture/adrs/035-usage-ledger-contract.md#self-hosted-mode).
  • LLM (T-220) reserves through the same ADR-035 §4 seam, but only when HUITZO_LLM_PRICING_ENABLED is on (dark by default — ADR-038 §7.1). With the flag off no 402 of this shape originates from an LLM call at all. With it on, one reservation is made per physical provider attempt (LLM Chokepoint Metering §5), so a wallet that runs dry between attempts refuses mid-sequence; attempts that already completed stay settled and billed. Only a platform-funded (HUITZO_MANAGED) LLM call can produce this error — a BYOK or self-hosted call reserves zero and is never gated (ADR-038 §8.2).

With HUITZO_DISPUTE_CLAWBACK_ENABLED on, a wallet frozen or closed after a chargeback is refused the same way, with available: 0, before availability is read, for every platform-funded (HUITZO_MANAGED) product (dispute clawback).

When the wallet cannot cover the estimate, the reservation is refused before the provider is ever called — no ledger entry is written and no provider work occurred (docs/architecture/adrs/035-usage-ledger-contract.md#failure-matrix). The five fields below (code/required/available/wallet_id/auto_reload_state) are the same on every surface this error can reach, but the ENVELOPE differs per surface:

# pseudocode — error.details for code == "INSUFFICIENT_CREDITS"
{
  "code": "INSUFFICIENT_CREDITS",
  "required": <int>,                    # credits the reservation needed
  "available": <int>,                   # credits available at refusal time
  "wallet_id": <string | null>,         # the CreditAccount id; null when the tenant has no account or is read_only
  "auto_reload_state": <string | null>  # armed | pending | capped | failed | disabled; forced "disabled" when the tenant has no account or is read_only
}
  • SSE (stream_response=true) and MCP (tools/call) have no HTTP status line to carry 402, so both spread the same five fields FLAT into their own error envelope instead of nesting them under details — see the SSE framing note in Execute Pipeline and the insufficient_credits entry in the MCP error envelope.
  • Async task polling (GET /api/v1/tasks/{task_id}, reached when a command or medium/long-queue pipeline dispatches to Celery and the refusal happens inside the worker) does not carry this shape. The worker's generic failure handler records error: str(exc) with no code/required/available/wallet_id/auto_reload_state fields — a client polling task status sees only a plain message, not the structured 402 contract. Prefer the inline/SSE/MCP surfaces above when the caller needs to branch on INSUFFICIENT_CREDITS programmatically; this gap is tracked, not yet closed.

auto_reload_state mirrors WalletPolicy.reload_state (docs/architecture/adrs/036-payg-wallet-state-machine.md#reload-states) — disabled when auto-reload was never configured for this wallet.

Tenant wallet. Every chokepoint charges the acting tenant's account, whoever the actor is, and a platform-funded call is never run unreserved (ADR-041 D3). Three things follow for this error:

  • A tenant with no account, or a read_only tenant, is refused with available: 0, wallet_id absent (null) and auto_reload_state: "disabled", on every chokepoint including scheduled (cron) work, which has no actor. Every other refusal, including a frozen or closed account, carries the account id as wallet_id and the wallet's real auto_reload_state.
  • available stays credits only: live lot credits minus live holds.
  • When the tenant has a drawable allowance period, details also carries units_remaining, the units left this period (ADR-041 D4). It is never added to available. Only a reservation refusal and a managed no-account refusal carry it; the read_only, frozen or closed-account and pack-price refusals never do, and it is absent when there is no such period.

A reservation that reaches no decision (a ledger outage, an uncomposable idempotency key) is refused with RESERVATION_UNAVAILABLE (503) on every chokepoint, not only LLM calls, and on the first failure.

LLM authorization refusals (403 / 503)

An LLM call can be refused before any provider request is made, for reasons that are not payment problems. These are deliberately not 402: the caller's wallet is not in question and adding credits cannot fix any of them. Every one of them is raised at authorization time (ADR-038 §1), so no COGS was incurred and no charge exists.

They share status codes with each other, so error.details.code — not the HTTP status — is what a client branches on:

code Status Retryable Meaning
MODEL_NOT_REGISTERED 403 no A platform-funded call named a model the LLM registry does not serve (absent, disabled, or its provider disabled). Refused rather than priced at a guessed rate (ADR-038 §1.2). An administrator must register or enable it. details: provider, model, reason
MODEL_NOT_ALLOWED 403 no The model is outside the BYOK integration's model_allowlist (ADR-038 §8.3). Never falls through to a platform credential. details: provider, model, integration_id
CREDENTIAL_PROVENANCE_UNKNOWN 403 no The credential's provenance could not be resolved, so the call is refused rather than run un-gated against platform-funded capacity (ADR-038 §1.2). details: product
RESERVATION_UNAVAILABLE 503 yes The reservation circuit breaker is open — consecutive ledger/database failures (ADR-038 §9). Platform-funded LLM calls only; BYOK and self-hosted are never broken by it. Also returned by compute, TTS and pipeline execution, on the first reservation that reaches no decision (ADR-041 D3). details: product
REGISTRY_SNAPSHOT_EXPIRED 503 yes The LLM model registry is temporarily unavailable, so the platform stops spending its own money against a catalog it can no longer vouch for (ADR-038 §3.3). Platform-funded calls only. details: provider

Neither 503 reports how degraded the platform is — no failure counts, no snapshot ages, no validity bounds. Those are operator-facing and stay in the logs and metrics: returning them would tell an authenticated tenant exactly when the platform's spend controls are weakened.

The two 503s are honest and temporary: retry shortly. The three 403s are permanent until an operator changes configuration — retrying cannot help.

Isolated command capacity (429)

Every call of a pack command runs in its own isolated child process (ADR-039). One API or worker process runs at most 64 such children at once, and one tenant at most 33 of them; past its first 8, a tenant may start another only while more than 16 stay free for other tenants (limits). A command that starts while there is no room waits up to 30 seconds for one, then is refused before it runs; while the process's cleanup backlog is full it is refused at once, because no child ending would clear it. The same answer comes back, at once, when the process is already describing as many builds in the background as it allows (32) and a call needs another one described. The first calls of a build published moments ago, whose describe did start, are not a capacity condition: they are the retryable 503 PACK_BUILD_NOT_READY of Execute Command.

code Status Retryable Meaning
ISOLATION_CAPACITY_EXCEEDED 429 yes The process serving the request, or this tenant's share of it, is at capacity (its live children, or its backlog of cleanup after children: fork safety and bounded cleanup). Temporary, and nothing about the request is wrong. The response carries Retry-After: 5; details: code, namespace, correlation_id. The execution row closes as failure with that fixed text. The MCP surface returns the same fact as type: "isolation_capacity_exceeded" error content with retryable: true and retry_after.

The refusal keeps this answer wherever it happens:

  • A nested ctx.commands call refused for capacity reaches the calling pack as the SDK's RateLimitError (retry_after set). It can handle it; left unhandled, the request gets this 429.
  • A pipeline stage, branch or joiner refused for capacity ends the run with this 429 and code on the pipeline execute and resume routes, never the 422 of a stage failure; execute also records the run as failed with that code, and the streaming route sends it as an error event. Their details carry code and correlation_id (no namespace). A run on a worker records the same code with retryable: true; the worker does not retry it, because earlier stages may already have had effects.

A command waits for room before any credit is reserved, so a refused request never touches the wallet.

Pack load busy (503)

No longer produced. Registration reads stored metadata and a pack's code runs only in an isolated child, so nothing loads a pack build into the API process and this refusal cannot occur. The route handlers and this section are removed with the follow-up that deletes the old in-process import machinery. It is described here as it was.

Command execution can also be refused before the command body runs when the API process must load the pack build the request was routed for and a different build of that same pack is still executing in this process. Two builds of one distribution cannot share one interpreter, so the loader waits for the live executions to drain (HUITZO_PACK_LOAD_WAIT_SECONDS, default 30) and refuses rather than mixing them (resource-lifecycle).

code Status Retryable Meaning
PACK_LOAD_BUSY 503 yes Another build of this pack is executing on the replica that served the request. Bounded by those executions — never a 400: nothing about the request is wrong. The response carries Retry-After: 5; details: code, namespace, correlation_id. The MCP surface has no status line and returns the same fact as type: "pack_load_busy" error content.

The same refusal is returned by pack publish for the same reason and with the same Retry-After.

An inline command's registration or reload counts against its own timeout (inline command capacity): when that runs out first, the answer is the 504 with code: TIMEOUT. The command did not run; retry it.

Inline command capacity (429)

A command that runs inline (the fast queue) is refused at once, before an execution row is written, the pack is loaded or any credit is held, when the calling tenant already has as many inline commands running as it may, across every API process (HUITZO_INLINE_SPAWN_MAX_PER_TENANT, default 2), or when this API process already runs as many as it allows in total (HUITZO_INLINE_SPAWN_MAX_GLOBAL, default 6). Nothing is queued: the caller retries after Retry-After (configuration, ADR-039: inline admission).

code Status Retryable Meaning
INLINE_CAPACITY_EXCEEDED 429 yes Too many commands are running right now. details.scope is tenant (your workspace's own commands fill its share) or global (the server is busy with other work). The response carries Retry-After: 10; details: code, scope, namespace, correlation_id. The MCP surface has no status line and returns the same fact as type: "inline_capacity_exceeded" error content with retryable: true, scope and retry_after.

The tenant limit is counted in Redis, so it holds across API processes; the total is counted per API process (shared limits). A refusal writes no execution row, so it counts against no quota or licence limit; it is recorded as a command_executed audit event with status inline_capacity_exceeded.

An inline command's timeout is also capped (HUITZO_INLINE_COMMAND_TIMEOUT_SECONDS, default 40), so it is answered with this API's own 504 (code: TIMEOUT) before a reverse proxy's read timeout would cut the connection. The budget starts when the request is admitted: writing the execution row, building the context, loading the pack and holding credits all count against it, so a stall there is answered with that 504 too, and a load that leaves no time is answered without running the command.

Errors a command raises

A huitzo_sdk.errors exception raised while a command runs is answered by one caller-facing policy on every surface: synchronous REST execute, the MCP endpoint, and the task record behind Get Task Status and huitzo_task_poll. It is never flattened to 500 "Command execution failed" (#1274). Implementation: apps/backend/src/backend/commands/caller_errors.py.

Status, code and type come from the SDK class, never the instance. The platform walks the exception's class hierarchy to the nearest class that huitzo_sdk.errors itself exports, the same rule the process-isolation boundary uses to relay a pack's error, and reads http_status, code, retryable and the class name from that class. A pack-defined subclass therefore answers with its SDK base's values, whatever http_status or code it declares: a subclass of ExternalAPIError is a 502 EXTERNAL_API_ERROR whose type is ExternalAPIError, and a class derived directly from HuitzoError is a 500 HUITZO_ERROR. A status outside 400-599, or 401 or 407, is sent as 500: 401 and 407 would tell the client that its own credentials failed. CommandTimeoutError declares 408 and is sent as 504, because clients resend a request that got a 408 on a reused connection, which would run the command again.

Body. The general error shape, with details limited to two fields:

# pseudocode: the REST answer when a command raises SecretsError
HTTP 400
{
  "success": false,
  "error": {
    "message": "<the caller-facing text, see the table>",
    "type": "SecretsError",      # the nearest SDK class
    "code": "SECRET_MISSING",    # that class's code
    "details": { "correlation_id": "<uuid>", "retryable": false }
  }
}

The exception's own details are never returned, because platform raisers put upstream response bodies and request inputs there.

retryable says whether the failure's class is transient, so the same request may succeed later. Retrying runs the command again from the start, including any side effects it performed before it failed. An HTTPError or LLMError that carries an upstream status is retryable only for 429 and 5xx; a 401 or a 404 fails the same way on every retry. Without an upstream status it keeps its class's value.

Retry-After. A RateLimitError sets the header from its retry_after: an integer, or a finite float rounded up, clamped to 1 to 3600 seconds. A bool, NaN or infinity sends none. A pack command always runs in an isolated child (ADR-039), and only a pack error's type and message cross that boundary, so a RateLimitError the pack raises arrives without its retry_after and sends no header.

Message. A class whose text is written for the caller (by the pack author, or by platform code from values the caller or the pack already knows: a secret's name, an extension name, a timeout) keeps its own message. One exception is known, pre-existing and tracked in #1743: ctx.commands wraps a sub-command's exception that is not a huitzo_sdk.errors one as a CommandError whose message quotes that exception's text, cut to 200 characters, so a CommandError can carry text nobody wrote for the caller. The policy cleans the text: control characters become spaces, runs of whitespace collapse, and it is cut to 1024 characters ending in ...; the dedicated branches (¹ below) return their text as raised. When it has no usable text the caller gets The command failed.. Every other class gets a fixed text, because platform code raises those families with text the caller must not see: HTTPError carries the request URL with its query string (an ?apikey=), StorageError wraps the database driver's text ([SQL: INSERT ...]), PipelineError wraps an arbitrary stage exception, and the model, database, email, file and object-storage integrations carry upstream response bodies, driver errors, paths and endpoints. HTTPSecurityError gets one text for SSRF and allowlist refusals alike, so its message no longer says whether a host resolves to an internal address. The status and code still can: for a pack whose services.http.allowed_domains is ["*"] and that forwards a caller-supplied URL, a host that resolves to an internal address is refused before any request (403 HTTP_SECURITY_ERROR), while a public host that fails is a 502 HTTP_ERROR. That residual is the pack's to close, by not forwarding arbitrary URLs under a wildcard allowlist. To give the caller your own words, raise or subclass ExternalAPIError, CommandError or ValidationError (SDK error handling).

Exception Status code retryable message
ValidationError ¹ 400 ¹ ¹ its own
PackPermissionError ¹ 403 ¹ ¹ its own
CommandError and its subclasses (CommandNotFoundError, CircularCommandError, MaxCallDepthError) ¹ 422 ¹ ¹ its own
InsufficientCreditsError ² 402 ² ² its own
LLM authorization refusals ² 403 / 503 ² ² its own
SecretsError 400 SECRET_MISSING no its own
HTTPSecurityError 403 HTTP_SECURITY_ERROR no Requests to '<host>' are not permitted. when the refused host is a plain name or IP address (letters, digits, ., :, -, [, ]; at most 253 characters), else This request is not permitted. The same text for SSRF and allowlist refusals, though the status can still tell a refused internal host from a failed public one (see above)
ExtensionNotAvailable 404 EXTENSION_NOT_AVAILABLE no its own
CommandTimeoutError 504 (declares 408) TIMEOUT yes its own
PipelineError 422 PIPELINE_FAILED no A pipeline stage failed.
RateLimitError 429 RATE_LIMITED yes its own
ExternalAPIError 502 EXTERNAL_API_ERROR no its own
CronError 502 CRON_ERROR yes its own
HTTPError 502 HTTP_ERROR yes without an upstream status; with one, only for 429 and 5xx The outbound HTTP request failed with status N., with with status N only when the upstream status is an integer from 100 to 599
LLMError 502 LLM_ERROR same rule as HTTPError The model provider request failed with status N., same rule
DatabaseError 502 DATABASE_ERROR yes The database integration query failed.
EmailError 502 EMAIL_ERROR yes Sending the email failed.
MCPError and its subclasses 502 the class's, e.g. MCP_TOOL_ERROR yes The MCP tool call failed.
SSHError 502 SSH_ERROR yes The SSH command failed.
IntegrationError, any other subclass 502 INTEGRATION_ERROR yes An integration call failed.
IntegrationLifecycleError 500 INTEGRATION_LIFECYCLE_ERROR no its own
StorageError 500 STORAGE_ERROR no The storage operation failed.
ConfigurationError 500 CONFIGURATION_ERROR no The platform could not run this command.
PackExecutionError 500 PACK_EXECUTION_ERROR no The pack failed to run.
HuitzoError, including a class derived directly from it 500 HUITZO_ERROR no The command failed.

¹ A dedicated branch answers first, with the status shown and a body of only error.message (the exception's text as raised) and error.details.correlation_id: no type, code or retryable. A subclass keeps the branch's status even when its class declares another (CommandNotFoundError declares 404 and is answered with 422).

² A dedicated branch with its own documented shape: Insufficient Credits Error and LLM authorization refusals.

Exceptions outside the SDK family keep their own handling: a ValueError is a 400 with its text, the executor's own TimeoutError is a 504 Command execution timed out with code TIMEOUT (the status and code CommandTimeoutError gets), a SQLAlchemyError is a 500 Database error occurred, and anything else is a 500 Command execution failed with only correlation_id, because its text can carry paths, secrets or third-party internals. Under process isolation, the default, only exceptions of the huitzo_sdk.errors family come back to the API process as themselves: any other exception the command raises arrives as a plain error and is that 500, including a pydantic.ValidationError raised in the command's body (a pack validating a third-party response, say).

A failing args model is answered as a ValidationError under process isolation. Before the child calls the command, it validates the arguments with the command's args model, the model its input_schema is derived from, and raises a failure as the SDK's ValidationError. REST answers it through the dedicated 400 branch (¹), MCP returns it as validation, and a task closes as failure. A pydantic.ValidationError that a default_factory or model_post_init raises while the model validates is answered the same way. The command receives the validated model, so its validators run once. A pack decorator stacked over @command with functools.wraps copies the args model too, so it receives the model.

The message lists the failures as <path>: <reason> pairs joined by ;. The execution row stores it in plaintext, so it carries neither the rejected value nor a key the caller chose, outside the residuals below:

  • Path. List indices print as numbers. A string segment shows only at the top level, where it names a field, and only when it is shaped like one (a letter or _, then letters, digits, _ or -, at most 64 characters) and the failure is not about a key the caller added (extra_forbidden, unexpected_keyword_argument) or an attribute the code assigned (no_such_attribute). Every other segment reads <key>, so a string mapping key never shows: m.<key>, items.3.<key>. An empty path reads <root>. Two residuals: a model whose top level is itself a mapping (a RootModel over a dict, or extra="allow" with typed extras) has the caller's keys at the top level, where an identifier-shaped one shows; and an integer mapping key (dict[int, ...]) that Python code supplied prints as a number, like a list index (a JSON body's keys are strings, so below the top level they read <key>).
  • Reason. pydantic's own message where pydantic writes it from the schema and at most the input's length, such as String should have at least 3 characters or List should have at least 2 items after validation, not 1. The error type instead where pydantic's message can carry the input or a validator's text (value_error, assertion_error, union_tag_invalid, uuid_parsing, bytes_invalid_encoding, timezone_offset, no_such_attribute, and the errors that quote an input object's own exception), and for a PydanticCustomError, unless it is raised under a standard type's name with that type's own message template, which shows the context values its validator passed. A custom type that is not shaped like a field name reads invalid. A validator that wants the caller to read its own words raises the SDK's ValidationError, which passes through with its message.
  • Length. At most 20 failures, then ; and N more. Under isolation the message then crosses the process boundary cut to its first 512 characters, with ...(truncated) appended. A long list ends at whichever limit it reaches first, and the 512-character cut can drop the ; and N more count.

MCP. tools/call returns the same text as error, the lowercased code as type (for example secret_missing, http_error or timeout), the class name as error_type, and retryable, in the error envelope. MCP has no headers, so a RateLimitError that carries a retry_after adds it to the envelope as retry_after, in the header's seconds. The dedicated branches keep their own type (validation, permission, command, insufficient_credits, the lowercased refusal code).

Async tasks. GET /api/v1/tasks/{task_id} and huitzo_task_poll return the stored text (next paragraph) as error.message. error.type is the class name of the exception the task caught: under process isolation the nearest huitzo_sdk.errors class for an SDK error and RuntimeError for any other exception (the child's own class name leads the stored message, not error.type). A platform-written failure (the last case below) reports the builtin it is, ValueError, RuntimeError or LookupError: the classes the platform uses to mark its own text are internal and never appear here. A CommandTimeoutError closes the task as timeout, as on the synchronous surfaces; every other SDK error closes it as failure.

The stored text. An execution row keeps a command's failure in error_message, a plaintext column cut to 2048 characters. One rendering (apps/backend/src/backend/commands/persisted_errors.py) writes it: the worker for async tasks, and synchronous REST execute and MCP tools/call for the commands they run inline. One failure is therefore stored the same way on every path, apart from the two branches listed after these cases:

  • A huitzo_sdk.errors exception stores the caller-facing text above, with pydantic's input echo removed (a CommandError from ctx.commands quotes a sub-command's pydantic failure, #1743). The echo is recognized by its markers (input_value=, input_type=, a quoted input key): when one follows a bracket or brace, the message is withheld from the first bracket or brace to its end (<details withheld>), which ordinary text carrying a marker also triggers. The text is read to at most its first 8192 characters. A message that itself contains pydantic's header shape (2 validation errors for ...) is summarized as one. The ¹ classes are cleaned like the rest, though REST and MCP return theirs as raised, and the ² refusals keep their own text.
  • A pydantic.ValidationError raised in the API or worker process stores the <path>: <reason> text described above. A pack's args failure already arrives as the SDK's ValidationError with that text (after the 512-character cut above), and a failure in a pack's body takes the next case.
  • Any other exception stores its class name and a fixed sentence, <ClassName>: the command failed; its message is not stored, never its text (#1822). Libraries quote their input (float("sk_live_x") and int() echo the argument), the column is plaintext, and the monitor and task endpoints return it, so text the platform did not write is not persisted. Under process isolation a body failure arrives as a RelayedPackError (a RuntimeError) that records the child's class name; that name is used only when it is identifier shaped (^[A-Za-z_][A-Za-z0-9_.]{0,99}$). A plain RuntimeError raised in the API process is never parsed: its text is not a class name, so it stores RuntimeError: .... A pydantic failure that crossed the boundary as plain text keeps its summary of the error count and rule names only (ValidationError: Data validation failed in the command (1 error(s)): int_parsing), because its path lines can carry a key the caller chose. The label does not say "arguments": an args-model failure is raised as the SDK ValidationError (a 400) and never takes this path, so what does is a model the command body validated, such as a stored record the current model no longer accepts. Platform-written texts are allowed by exception type, never by their words: the registry miss (Command not found in registry: @scope/pack/cmd, a ValueError subclass), the pack build mismatch, the busy pack loader (PackLoadBusyError, "Retry shortly"), Pack storage is unavailable, pack-load refusals (Refusing pack load: ...), pip and extraction failures (... failed, ... timed out) and ctx.pipeline misuse (nesting depth, no live database session, a run or checkpoint that is not found: Pipeline run not found (or not visible to this tenant)., which never quotes the run id); their messages are fixed sentences or metadata. This text is kept only when the error is raised in the API or worker process outside an isolated child, as the registry miss is. Process isolation is on by default for inline runs and every queue, and there neither kind of platform error keeps its text. One raised in the parent while it serves a child's nested call (ctx.pipeline, ctx.commands) is replaced before it crosses the boundary: unless it is an SDK error, the parent logs it and sends RuntimeError with the fixed text pipeline operation failed (or commands operation failed). Pack code therefore reads a relayed error whose error_type is always RuntimeError, whatever was raised: a ctx.pipeline.get() miss is not a LookupError under isolation, and its sentence does not arrive. (The handler's own argument and nesting-limit checks are not redacted; they cross under their own class name with their text and are stored class-only too.) One raised inside the child crosses as class name and text, and the name is the builtin's (ValueError, RuntimeError, LookupError), never the internal marker class. Either failure is then stored like any other relayed failure, class only: RPCError: the command failed; its message is not stored for a parent-side error the command let propagate, and ValueError: ... or RuntimeError: ... for one raised inside the child. That fails safe; carrying the original across is #1962. One residual is open (#1743): ctx.commands wraps a sub-command's non-SDK failure in a CommandError that quotes its text, and that SDK error is stored as written, with or without isolation. Pack authors who want a failure's text to reach the caller or the task record should raise an SDK error (CommandError, ExternalAPIError, ...) with their own words. The monitor below and, for an async task, the task endpoint return this text, which the 500 under "Exceptions outside the SDK family" withholds from a synchronous response. The user who ran the command gets the failure detail in its place.

Two branches store less. The executor's own TimeoutError closes the row as timeout with no error type or text, on every path. REST's 500 Database error occurred makes no update, so the stale-execution reaper closes that row.

The owner's failure detail

error_message is read by the tenant's admins and owners too (the monitor), so it keeps the class-only rule above. The same terminal write also stores a failure detail for the user who ran the command. It goes in the row's result_full, the field that already holds the command's return value and that only that user can read: the task endpoint, the MCP task poll, and the monitor's run detail when the caller is that user. No other viewer, and no platform log, receives it. Platform logs keep their current redaction.

Field Content
type The exception's class name. For a failure relayed from an isolated child, the child's class name when it is identifier-shaped (where error_type says RuntimeError). Readers return this type with the detail
origin sdk: a huitzo_sdk.errors error, whose message is written for users. validation: a pydantic failure. unexpected: anything else
message sdk: the stored text above. validation: its <path>: <reason> text. unexpected: the exception's own message only when pack code raised it in the isolated child, after the pydantic echo scrub above; before relaying it, the child replaces every secret value it read through ctx.secrets (6 characters or longer; the first 256 distinct values) with [REDACTED]. A platform-written failure keeps its fixed text. Any other exception raised in the API or worker process itself (a driver, broker, filesystem or HTTP client error) stores An internal error occurred; the details are in the platform logs., because its text can name hosts, paths, SQL and bound parameters. Every message, whatever its origin, then has control characters escaped, token shapes redacted ([REDACTED] for bearer and Basic credentials, sk-/sk_live_ keys, GitHub, Slack, AWS, Google and webhook-secret shapes, JWTs, URL userinfo, and the value of a credential-named parameter in query, form, DSN, header or JSON form, such as api_key=, session_token=, X-Api-Key: or "password":; a newline or other separator before a token does not hide it), and is cut to 1024 characters. Never a traceback or the exception's cause chain

A failure from a runtime gap names the unsupported call. For example, NotImplementedError with ctx.db.transaction() is not supported in the hosted runtime; run the statements without a transaction.

Readers use the detail only for a row whose status is not success, so a command whose own result contains the same key is unaffected. A row written before the detail existed has none, and readers fall back to error_message.

GET /api/v1/monitor/executions returns the stored text with token-shaped strings replaced by [REDACTED], cut to 500 characters. The scrub knows only common credential formats, so it is a backstop for this rendering, not a substitute for it.

GET /api/v1/monitor/runs lists command executions and pipeline runs together, one row per correlation id, and GET /api/v1/monitor/runs/{correlation_id} returns one run's steps, their status and timing, and the model calls each step made. Both follow the monitor's visibility rule (a member sees only runs they started; an unknown or hidden correlation id is 404), and every error text they return passes through the same scrub. Parameters, response fields and error statuses are in Run Flow View.

The list accepts pack=@scope/name and, with it, version=<version> to return one pack's command runs (pack and version filters). Each row carries executed_version, and the envelope of a 200 carries meta.scope: own for a member and tenant for an admin or owner. A pack that is not @scope/name, a version without pack, and a version that is not 1 to 20 characters are each 422 with {"success": false, "error": {"message": "…"}}: a message, no error.code and no meta.


Endpoints

Authentication

Register

Create a new user account and its own kind='home' tenant. All accounts start in Consumer mode.

While HUITZO_REQUIRE_SIGNUP_COUPON is on (the default), registration needs a coupon_code carrying account.create, the only admission credential (ADR-042 D14, D15). A body without one is 400 A signup coupon is required. While the setting is off (dev and test only) no credential is required, but a coupon_code that is sent is still redeemed.

The endpoint is public and IP-limited (D9): 5 calls per client IP per minute (429) and an hourly platform breaker (503 register_at_capacity), both failing closed on a Redis outage (503 rate_limiter_unavailable). The limits cover the coupon path too.

POST /api/v1/auth/register

Request:

{
  "email": "[email protected]",
  "password": "securepassword",
  "slug": "jane-acme",
  "coupon_code": "K7Q2-M4XA-…"
}
Field Type Required Description
email string Yes User email address
password string Yes Password (min 8 characters)
slug string Yes Personal namespace slug (2-39 chars, lowercase, no reserved prefixes)
coupon_code string While HUITZO_REQUIRE_SIGNUP_COUPON is on A coupon carrying account.create (Coupon registration)

Response:

{
  "data": {
    "tokens": {
      "accessToken": "eyJhbG...",
      "refreshToken": "eyJhbG...",
      "expiresAt": 1740000000000
    },
    "user": {
      "id": "usr_abc123",
      "email": "[email protected]",
      "name": "jane",
      "role": "owner",
      "developerMode": false,
      "createdAt": "2026-02-15T10:00:00Z"
    }
  }
}

An email that already has an account is 409 on this (plain) path. A taken slug is 409.

Register with a coupon

D-024 CR70 (ADR-042 D6, D8). Always on: the access-code fold (D-024 CR78) made coupons the only admission path. It needs no email server: a staff-minted account.create coupon is the whole invite-only flow on a Core-only deployment.

{
  "email": "[email protected]",
  "password": "securepassword",
  "slug": "jane-acme",
  "coupon_code": "K7Q2-M4XA-…"
}

Registration and redemption are one database transaction. The coupon is locked and checked first (state, bindings, a registered handler for every capability, and account.create present); then the identity is written: the home tenant, the user homed in it, the home membership, the session and the tokens. Only then do the bundled capabilities apply, in order: tenant.create (a kind='team' tenant), tenant.join in the landing tenant (seat gate, membership admission check), then extension handlers. A pilot coupon (account.create + tenant.create + tenant.join{role: owner}) therefore yields a home tenant plus an owner membership of the new team tenant. The landing tenant is the created tenant, else the coupon's target_tenant_id, else the new home tenant; the register body has no landing_tenant_id. Any refusal or error after the lock rolls everything back: no account, and redemption_count unchanged.

Response (201): the register body above plus a coupon object. Joining is never switching: the tokens are for the home tenant, and the client offers an explicit switch to joined_tenant_id.

{
  "data": {
    "tokens": {"accessToken": "eyJhbG...", "refreshToken": "eyJhbG...", "expiresAt": 1740000000000},
    "user": {"id": "…", "email": "[email protected]", "role": "owner", "…": "…"},
    "coupon": {
      "redemption_id": "…",
      "landing_tenant_id": "…",
      "landing_tenant_name": "Acme",
      "joined_tenant_id": "…",
      "created_tenant_id": "…",
      "outcomes": {"tenant.create": "applied", "tenant.join": "applied"}
    }
  }
}

Uniform refusal (400). Every coupon refusal returns the redeem body (details.code = "coupon_invalid"): an unknown, expired, exhausted, revoked or unapproved code, a wrong email or domain, a coupon without account.create, a full seat budget, a refused admission, a handler refusal, an unregistered handler, the flag being off, and an email that already has an account (the holder signs in and redeems at POST /api/v1/coupons/redeem instead). Registration never answers coupon_already_redeemed. The reason goes to the coupon_register_refused log event (reason, and coupon_id when a coupon was resolved; never the code or the email). A taken slug is 409; a seat or admission count that cannot run is 503; any other error is 500.


Login

POST /api/v1/auth/login

Request:

{
  "email": "[email protected]",
  "password": "your-password"
}

Response:

{
  "data": {
    "tokens": {
      "accessToken": "eyJhbG...",
      "refreshToken": "eyJhbG...",
      "expiresAt": 1740000000000
    },
    "user": {
      "id": "usr_abc123",
      "email": "[email protected]",
      "name": "user",
      "role": "owner",
      "developerMode": false,
      "createdAt": "2026-01-01T00:00:00Z"
    }
  }
}

Login is limited per client IP (HUITZO_LOGIN_IP_RATE_LIMIT_PER_MINUTE, 429). change-password/login also checks an email and password, so it spends from the same per-IP budget as login. The other credential routes (change-password, forgot-password, reset-password and reauth) are limited at 5 calls per client IP per minute each. All six fail closed: while Redis is down they answer 503 with code: rate_limiter_unavailable, and the request is refused before any credential is checked (shared limits).


Refresh Token

POST /api/v1/auth/refresh

Request:

{
  "refreshToken": "eyJhbG..."
}

Response:

{
  "data": {
    "accessToken": "eyJhbG...",
    "refreshToken": "eyJhbG...",
    "expiresAt": 1740000000000
  }
}

Used by the Hub dashboard for XSS-safe token refresh. Reads the refresh token from the huitzo_refresh HttpOnly cookie instead of the request body. CLI/SDK should use the body-based POST /auth/refresh endpoint above.

POST /api/v1/auth/refresh-cookie
Cookie: huitzo_refresh=<refresh-token>

No request body required. The refresh token is read from the HttpOnly cookie set during login or previous refresh.

Response:

{
  "data": {
    "accessToken": "eyJhbG...",
    "expiresAt": 1740000000000
  }
}

The response also sets a new huitzo_refresh HttpOnly cookie with a rotated refresh token.

This endpoint is public (no Bearer token required) since its purpose is to obtain a new access token when the previous one has expired. The cookie is scoped to the /api/v1/auth path prefix, so the browser does not send it on other API requests.

Rotation is idempotent for a short window after the latest rotation: a replay of the just-superseded refresh-token value (second-tab race, transport-level retry, visibility-listener fire while a reactive refresh is in flight) still resolves to the active session and re-issues fresh tokens. See Refresh Rotation Grace Window for the server-side semantics.


Logout

POST /api/v1/auth/logout
Authorization: Bearer {token}

Response:

{
  "data": {
    "message": "Successfully logged out"
  }
}

Change Password (Authenticated)

Change password from an active session (Hub Settings page).

POST /api/v1/auth/change-password
Authorization: Bearer {token}

Request:

{
  "current_password": "old-password",
  "new_password": "new-password"
}

Response:

{
  "data": {
    "message": "Password updated successfully"
  }
}

On success, all existing refresh sessions are revoked and a password-change notification email is sent (best effort) through SendGrid.


Change Password (Login Screen)

Change password from the login screen using email plus the current password.

POST /api/v1/auth/change-password/login

Request:

{
  "email": "[email protected]",
  "current_password": "old-password",
  "new_password": "new-password"
}

Response:

{
  "data": {
    "message": "Password updated successfully"
  }
}

This endpoint is public because it is designed for the login page flow. It still requires valid current credentials and sends the same account-change email notification.

Email verification

Prove that the signed-in user controls their email address (ADR-042 D11, D-024 CR74). Verification is SaaS state (the email_verifications table), so these routes exist only where the SaaS extension is mounted, and every one of them returns 404 while HUITZO_EMAIL_VERIFICATION_ENABLED is off (the default). Core users carries no verification column.

Status (authenticated):

GET /api/v1/auth/verify-email/status
Authorization: Bearer {token}
{ "data": { "verified": false } }

verified is true once any verification of the user has succeeded. The dashboard banner reads this route and hides itself on verified: true or on any error, including the flag-off 404.

Send (authenticated; API keys are refused with 403):

POST /api/v1/auth/verify-email/send
Authorization: Bearer {token}

Mints a single-use token (token_urlsafe(32), stored only as its SHA-256 hex, valid for 24 hours) and queues the email huitzo.send_verification_email to the user's address with a link to the dashboard's /verify-email?token=… page (on frontend_url). The row is written in the user's home tenant, derived from users.tenant_id of the signed-in identity, never from the acting tenant, so the route works the same while the user is acting in a team tenant. Earlier unexpired tokens stay valid.

Status Body When
202 {"data": {"message": "Verification email sent."}} The token was written and the email queued
409 email_already_verified The user is already verified; nothing is written
429 — More than 3 sends per hour from the client IP, or more than 3 per hour for the user (D9; HUITZO_VERIFY_EMAIL_SEND_IP_RATE_LIMIT_PER_HOUR, HUITZO_VERIFY_EMAIL_SEND_USER_RATE_LIMIT_PER_HOUR)
503 rate_limiter_unavailable Redis is down: both limits fail closed
503 email_enqueue_failed The broker refused the email after the token was written; the token stays valid but nothing was sent, and the dashboard shows its generic failure text

Delivery runs in the worker under the shared retry and dead-letter contract (email_retry.py: retries after 30 s, 5 m and 1 h, then an email_dead_letter row). With no SendGrid key the send fails into that path; the deployment still boots and the routes still answer.

Verify (public; the token is the credential):

POST /api/v1/auth/verify-email
{ "token": "<the token from the link>" }
{ "data": { "verified": true } }

The token is resolved under auth_bootstrap by token_hash equality only. Unknown, expired and already-used tokens, a token whose user is inactive or has moved home, and a token for a user who is already verified all return the same 400:

{ "success": false, "error": { "message": "This verification link is invalid or has expired.", "code": "verification_invalid" } }

Verification is one transaction in two phases (ADR-042 D12): phase A locks the row and stamps verified_at; phase B switches the transaction's RLS context to the user's home tenant for the verified-event work: the signup seed while HUITZO_SEED_ON_VERIFICATION is on (default false; CR75). Any failure rolls back the stamp too, so the token stays usable. A token verifies exactly once. The route is limited to 5 calls per client IP per minute (429, failing open on a Redis outage).


Account

Get Account Mode

Check the current account mode and organization membership.

GET /api/v1/account/mode
Authorization: Bearer {token}

Response (Consumer Mode):

{
  "data": {
    "account_mode": "consumer",
    "developer_mode_available": true
  }
}

Response (Developer Mode):

{
  "data": {
    "account_mode": "developer",
    "organization": {
      "id": "org_xyz789",
      "name": "Acme Corp",
      "slug": "acme",
      "scope": "@acme",
      "role": "owner"
    }
  }
}

Enable Developer Mode

Enable Developer Mode for the current user. Creates a new organization: from the request body, or auto-generated from the caller's email when the body is empty ({}).

Slug uniqueness: organization slugs are unique globally across every tenant, not just within the caller's own tenant — a slug doubles as the org's public @scope namespace (see Check Namespace), and the organizations.slug column carries a global unique constraint to match. An auto-generated slug (empty request body, derived from the caller's email) that collides with another tenant's organization is retried automatically with a fresh suffix — invisible to the caller. A collision on an explicitly-chosen organization.slug is returned as a clean conflict response so the caller can pick a different one.

POST /api/v1/account/developer-mode
Authorization: Bearer {token}
Content-Type: application/json

Request (Create New Organization):

{
  "organization": {
    "name": "Acme Corp",
    "slug": "acme"
  }
}

Response:

{
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "[email protected]",
      "mode": "developer"
    },
    "organization": {
      "id": "org_xyz789",
      "name": "Acme Corp",
      "slug": "acme",
      "scope": "@acme"
    },
    "message": "Developer Mode enabled. You can now use the SDK and CLI."
  }
}

Error Responses:

Code Error Description
400 SLUG_TAKEN Organization slug already in use
400 SLUG_INVALID Slug doesn't meet validation rules
400 SLUG_RESERVED Slug is a reserved scope

Slug Validation Rules:

  • 2-39 characters
  • Lowercase letters, numbers, hyphens only
  • Cannot start or end with hyphen
  • Cannot be reserved (huitzo, system, admin)

Wallet

The PAYG credit wallet (ADR-035 usage ledger + ADR-036 wallet state machine; see the credits reference). Dark behind HUITZO_PAYG_ENABLED — every route below returns 404 while it is off, so a disabled surface is indistinguishable from an absent one.

Removed: GET /api/v1/credits, GET /api/v1/credits/transactions, GET /api/v1/credits/topup/packs, and POST /api/v1/credits/topup/checkout — ADR-019/ADR-021 Ledger A, deleted by migration saas_0014 (owner directive, 2026-08-24). GET /api/v1/wallet below is the replacement balance read.

Tenant wallet

Every route in this section acts on the acting tenant's account, the credit_accounts row with user_id NULL, never on a personal one (ADR-041 C3). Every member resolves the same wallet, so what a caller may do depends on their tenant role (ADR-041 D7):

Route Owner / admin Member
GET /wallet, GET /wallet/topup/catalog, GET /wallet/reload/policy The tenant wallet The tenant wallet
GET /wallet/topup/history, GET /wallet/lots, GET /wallet/usage/summary The tenant wallet's totals 403
GET /wallet/usage/charges, /by-dimension, /daily Tenant-wide, or one account Only the charges the member caused (actor_user_id)
POST /wallet/auto-reload/disable, /enable, PATCH /wallet/reload/policy Allowed 403
POST /wallet/topup/checkout Allowed on payg; on team_* with HUITZO_TEAM_CARD_OVERFLOW_ENABLED on 403 on payg, 409 team_managed_billing on team_*
POST /wallet/topup/card-setup With HUITZO_TEAM_CARD_OVERFLOW_ENABLED on: allowed on payg and team_* As for checkout

Also:

  • A settled top-up is granted to the tenant account.
  • The signup seed lands at most once per tenant, and only in a home tenant on payg (no plan row). A team or house tenant never receives it.
  • Auto-reload runs on a payg or team_* tenant's account, never on a house tenant's, and charges the tenant's Stripe customer from its billing profile (ADR-041 D8, credits: tenant auto-recharge). A tenant whose profile has no customer gets a failed attempt with no_stripe_customer; a personal card never pays for a tenant.

The billing boundary is the acting tenant (D-024 CR19):

  • There is no home-tenant boundary: GET /billing/status and POST /billing/portal answer for the acting tenant, and a member working in another tenant reads that tenant's wallet under the role rules above. The home-tenant 409 and the contract-tenant 409 of the personal-wallet model were removed on 2026-10-09 (billing: retired).
  • Top-up checkout, PATCH /wallet/reload/policy and /auto-reload/enable pass the plan-based gate (ADR-041 D7). The gate reads the plan row and the caller's membership role from the database:
Acting tenant's plan Owner / admin Member
payg (no plan row) Allowed 403
team_* 409 team_managed_billing; with HUITZO_TEAM_CARD_OVERFLOW_ENABLED on, allowed for top-up checkout, card setup, reload policy and auto-reload enable 409 team_managed_billing
house 409 house_plan_no_topup 409 house_plan_no_topup
  • The tenant card (HUITZO_TEAM_CARD_OVERFLOW_ENABLED, D-024 CR41) opens the two card writes to a Team owner or admin, and (D-024 CR42) the two auto-recharge arming writes, PATCH /wallet/reload/policy and /auto-reload/enable, because a Team auto-recharge charges the tenant card (ADR-041 D12). With that flag off, all four stay 409 team_managed_billing for every Team caller. A row on an unknown plan id refuses every one of them.
  • /auto-reload/disable takes no plan gate: stopping charges is never refused because of the plan.
  • Every money write (checkout, reload policy, disable, enable) refuses an API key (403), needs a token issued in the last 15 minutes (401 admin_reauth_required), and writes one admin_audit_log row: wallet_topup_checkout_created, wallet_reload_policy_updated, wallet_auto_reload_disabled or wallet_auto_reload_enabled. A disable in a workspace with no wallet yet still writes its row, with account_id null.
  • The checkout's session metadata carries the acting tenant's tenant_id and account: "tenant", and the settlement grants the lot to that tenant's account. The marker is honoured at settlement whatever the flag reads then, so a session opened before a flag-off revert (ADR-041 D5) still settles on the tenant account instead of failing.
# pseudocode — the plan gate's 409 (team shown; house uses HousePlanNoTopup / house_plan_no_topup)
{
  "success": false,
  "error": {
    "type": "TeamManagedBilling",
    "message": "<customer-facing sentence>",
    "code": "team_managed_billing",
    "details": { "status": "active|past_due|suspended" }
  }
}

Get Wallet Balance

The acting tenant's wallet: spendable balance, outstanding holds, top-up ladder rung, and auto-reload budget state.

GET /api/v1/wallet
Authorization: Bearer {jwt_token}
# pseudocode — response (200)
{
  "account_id": "<uuid>",
  "wallet": {
    "available_credits": <int>,   # live lot pool MINUS outstanding holds
    "held_credits": <int>,        # sum of unexpired `reserved` charges
    "current_rung": <int>,        # ADR-036 §6 top-up ladder rung
    "accrued": "<credits string>" # ADR-038 §5.2/§10 (M-10) — e.g. "0.340"; "0.000" if never accrued
  },
  "budget": null                  # or the wallet's auto-reload budget/cap state
}

available_credits is computed in one statement as the live credit_lots pool minus outstanding holds — byte-identical to what the reservation path computes (ADR-035 §3.3), so this read can never advertise credits a reservation would refuse. It is not a stored balance; there is no balance column.

accrued rides along automatically (this endpoint returns the same get_wallet_state projection /wallet/usage/summary uses, below) — the account's current sub-credit remainder, pre-rendered in credits, never a millicredit-denominated value on this surface. See PAYG Wallet Usage & Cost Projection for the full ADR-038 §10 field contract.

This read is also where the ADR-036 D-3 signup grant self-heals: if the account was stamped eligible at registration and has not been granted yet, the grant is written in the same transaction as the read, so the caller sees it immediately.

Status Meaning
200 The acting tenant's wallet
404 PAYG disabled (HUITZO_PAYG_ENABLED off), or the tenant has no tenant account (this read never creates one; every tenant gets its account when it is created, so this is data residue, not an empty wallet, which reads 200 with available_credits: 0)
402 Not returned by this read — see Insufficient Credits Error, raised by metered operations

List Wallet Lots

The live credit lots behind the balance, in the order settlement draws them, each with its expiry (D-024 CR49, lot expiry disclosure). Read-only.

GET /api/v1/wallet/lots?limit=50&offset=0
Authorization: Bearer {jwt_token}
# pseudocode — response (200)
{
  "draw_order": "promotional_first",
  "items": [
    { "position": <int>,              # 1-based draw position
      "kind": "promotional" | "paid",
      "label": "Promotional, no purchase necessary" | null,  # coupon lots only
      "credits_granted": <int>,
      "credits_remaining": <int>,
      "granted_at": <iso8601>,
      "expires_at": <iso8601> }
  ],
  "limit": <int>,
  "offset": <int>,
  "total": <int>
}
Status Meaning
200 Page returned; an account with no live lots, or no account, returns an empty page
403 The caller is a member (tenant wallet)
404 PAYG wallet disabled (HUITZO_PAYG_ENABLED off), or the caller's user row is not visible (User not found)

PAYG Wallet Top-up

Money-in for the ADR-035/036 wallet (Ledger B) — distinct from the Ledger A pack top-up above. See credits reference and ADR-035. Dark behind HUITZO_PAYG_ENABLED.

GET /api/v1/wallet/topup/catalog
Authorization: Bearer {jwt_token}

Filtered to the amounts purchasable at the caller's current ADR-036 §6 tier-ladder rung (ceilings 200/500/1,000/1,500/2,500 credits, see credits.md#payg-topup-catalog). A new wallet starts at rung 1 and sees only the $20 minimum:

# pseudocode — response (200), a rung-1 wallet
{
  "topups": [
    { "id": "payg_20", "price_cents": 2000, "credits": 200, "label": <str> }
  ],
  "current_rung": 1
}

A rung-3 wallet sees every amount up to 1,000 credits:

# pseudocode — response (200), a rung-3 wallet
{
  "topups": [
    { "id": "payg_20",  "price_cents": 2000,  "credits": 200,  "label": <str> },
    { "id": "payg_50",  "price_cents": 5000,  "credits": 500,  "label": <str> },
    { "id": "payg_100", "price_cents": 10000, "credits": 1000, "label": <str> }
  ],
  "current_rung": 3
}

The retired payg_10 is never listed, and POST /checkout refuses it with 400 like any other unknown id.

Create a Stripe Checkout session (mode=payment, one-time, addressed by the catalog's Stripe Price lookup_key — a real, provisioned Price, never inline price_data) for one of the PAYG amounts affordable at the caller's rung. Does not grant credits — credits are granted only on the settlement webhook, as a 1-year CreditLot (ADR-035 §3, D-3) through the merged ledger, sized from the amount Stripe actually collected (ADR-035 §2.1), not merely the catalog price. Bearer-token auth required (not the ambient session cookie) — a money-moving route, mirroring the billing router's /checkout.

POST /api/v1/wallet/topup/checkout
Authorization: Bearer {jwt_token}
Content-Type: application/json
# pseudocode — request
{
  "topup_id": "payg_50",
  "success_url": "{frontend_url}/wallet?topup=success",
  "cancel_url": "{frontend_url}/wallet?topup=cancelled"
}
# pseudocode — response (200)
{
  "checkout_url": "https://checkout.stripe.com/c/pay/cs_test_...",
  "account_email": "[email protected]",
  "topup_id": "payg_50",
  "credits": 500,
  "expires_at": "<iso8601>"   # when the lot expires if it settles now (12 months, NYC calendar)
}
Status Meaning
200 Checkout session created; redirect the user to checkout_url
400 Unknown topup_id, or a topup_id above the caller's current tier-ladder ceiling (ADR-036 §6); with HUITZO_PAID_BALANCE_CAP_ENABLED on, paid_balance_cap_exceeded — the top-up would take the tenant's paid balance past the cap. details carry cap_credits, paid_balance_credits, headroom_credits and requested_credits (paid balance cap)
404 PAYG wallet disabled (HUITZO_PAYG_ENABLED off), or the caller's user row is not visible (User not found)
401 admin_reauth_required — the token is older than 15 minutes
403 The caller is an API key, or a member of a payg tenant (tenant wallet)
409 team_managed_billing (every Team caller, or only a Team member with HUITZO_TEAM_CARD_OVERFLOW_ENABLED on) or house_plan_no_topup. With HUITZO_DISPUTE_CLAWBACK_ENABLED on: wallet_account_frozen or wallet_account_closed when the wallet the top-up would settle into is frozen or closed after a chargeback, before any Stripe call (dispute clawback)
422 Invalid success_url/cancel_url — see billing.md's redirect rules
503 Billing not configured (no Stripe key), or the top-up's Price is not provisioned in this Stripe mode

With HUITZO_TEAM_CARD_OVERFLOW_ENABLED on, a Team tenant's owner or admin may top up. The session always opens on the tenant's Stripe customer from its billing profile (created there when absent) and offers the cards saved on it, including one saved through card setup. A member's personal customer is never used, so a personal card never pays for a Team tenant. The tier-ladder ceiling and the paid-balance cap apply as for any top-up, and the settled lot lands on the tenant account.

With HUITZO_LOT_OWNER_CAPTURE_ENABLED on, the session requires a billing address, offers the optional tax ID field and is always opened on the tenant's Stripe customer, which the first such checkout creates and stores on the tenant billing profile. The settled lot records the owner and payment facts (lot owner capture).

GET /api/v1/wallet/topup/history
Authorization: Bearer {jwt_token}

Paginated, newest-first, tenant-scoped (RLS) list of the caller's settled wallet top-up receipts — customer-facing fields only, no COGS/internal fields (ADR-035 §7's allowlist discipline).

# pseudocode — response (200)
{
  "items": [
    { "id": <uuid>, "credits": <int>, "occurred_at": <iso8601>, "purchase_id": <uuid>,
      "expires_at": <iso8601> }   # the purchased lot's expiry
  ],
  "limit": <int>,
  "offset": <int>,
  "total": <int>
}
Status Meaning
200 Page returned for the acting tenant's wallet
403 The caller is a member (tenant wallet)
404 PAYG wallet disabled (HUITZO_PAYG_ENABLED off), or the caller's user row is not visible (User not found)

Tenant card setup

Save a card on the acting tenant's Stripe customer, the tenant card on file (ADR-041 D12). Opens a Stripe Checkout session in mode=setup on the customer from the tenant's billing profile, created there when absent. Nothing is charged. Bearer-token auth required. Dark behind HUITZO_TEAM_CARD_OVERFLOW_ENABLED, which requires HUITZO_SAAS_BILLING_ENABLED.

POST /api/v1/wallet/topup/card-setup
Authorization: Bearer {jwt_token}
Content-Type: application/json
# pseudocode — request
{
  "success_url": "{frontend_url}/billing?card=saved",
  "cancel_url": "{frontend_url}/billing?card=cancelled"
}
# pseudocode — response (200)
{
  "checkout_url": "https://checkout.stripe.com/c/pay/cs_test_...",
  "account_email": "[email protected]"
}
Status Meaning
200 Setup session created; redirect the user to checkout_url. One admin_audit_log row, wallet_card_setup_checkout_created, is written first
401 admin_reauth_required — the token is older than 15 minutes
403 The caller is an API key, or a member of a payg tenant
404 HUITZO_PAYG_ENABLED or HUITZO_TEAM_CARD_OVERFLOW_ENABLED off, or the caller's user row is not visible
409 team_managed_billing (a Team member, or a row on an unknown plan id) or house_plan_no_topup
422 Invalid success_url/cancel_url, as for checkout
503 Billing not configured (no Stripe key)

When the session completes, the billing webhook (checkout.session.completed, mode=setup, metadata.purpose = tenant_card_setup) makes the saved card the customer's default, the card an off-session charge uses. It does so only when the session's customer is the tenant's billing-profile customer; any other customer is logged and left unchanged. With the flag off the event is acknowledged and ignored.

PAYG Wallet Auto-reload Opt-out

Atomic opt-out/opt-in for auto-reload (ADR-036 §3.3). See credits reference. Both endpoints act ONLY on the acting tenant's wallet — neither takes an account identifier.

POST /api/v1/wallet/auto-reload/disable
Authorization: Bearer {jwt_token}

Always available — no reload_state precondition, no enterprise-billing gate. Idempotent: a repeat call returns the same state with changed: false and performs no write.

# pseudocode — response (200)
{
  "enabled": false,
  "reload_state": "disabled",
  "disabled_at": "2026-08-19T00:00:00+00:00",
  "disabled_by": <uuid>,
  "changed": true
}
Status Meaning
200 Disable applied (or already disabled — check changed)
401 admin_reauth_required — the token is older than 15 minutes
403 The caller is an API key, or is not the tenant's owner or an admin (tenant wallet)
404 PAYG disabled AND auto-reload dark (both HUITZO_PAYG_ENABLED and HUITZO_PAYG_AUTO_RELOAD_ENABLED off)
POST /api/v1/wallet/auto-reload/enable
Authorization: Bearer {jwt_token}

Explicit user action only. reload_state is recomputed from the append-only attempt log — pending while an attempt is non-terminal, failed behind an engaged decline latch, armed otherwise, never assumed. Refuses an API-key principal (re-arming grants standing off-session charging authority with no further human confirmation step); disable above carries no such restriction.

# pseudocode — response (200), shape identical to /disable
{ "enabled": true, "reload_state": "armed", "disabled_at": null, "disabled_by": null, "changed": true }
Status Meaning
200 Enable applied (or already enabled — check changed)
401 admin_reauth_required — the token is older than 15 minutes
403 Caller is an API-key principal, or is not the tenant's owner or an admin; auto_recharge_unavailable_region when the wallet's owner is a Mexican consumer or has no country on file, whatever the flags, with error.details.reason mx_consumer or unknown_country (tenant auto-recharge)
404 PAYG disabled (HUITZO_PAYG_ENABLED off), or the tenant has no wallet account
409 team_managed_billing or house_plan_no_topup. With HUITZO_LOT_OWNER_CAPTURE_ENABLED on: billing_address_required when a disabled wallet has no billing address on file (lot owner capture). With HUITZO_DISPUTE_CLAWBACK_ENABLED on: wallet_account_frozen or wallet_account_closed for a wallet frozen or closed after a chargeback (dispute clawback)

PAYG Wallet Auto-reload Policy

The auto-reload configuration surface (ADR-036 §3.1/§3.2). See credits reference. Acts ONLY on the acting tenant's wallet — neither endpoint takes an account identifier — and every write is limited to the tenant's owner and admins, verified under the account row lock.

GET /api/v1/wallet/reload/policy
Authorization: Bearer {jwt_token}

presets is filtered to the wallet's current tier-ladder rung (invariant R2), so a client can only ever offer a preset the ladder would honour. A wallet that has never configured auto-reload returns the truthful not-configured shape (enabled: false, preset_id: null, reload_target: null, the server default trigger_balance) — never a 404.

# pseudocode — response (200)
{
  "enabled": <bool>,
  "preset_id": <str|null>,
  "trigger_balance": <int>,
  "reload_target": <int|null>,
  "reload_cap_credits": <int|null>,        # null ⇒ no limit (D-7)
  "reload_state": "armed|pending|capped|failed|disabled",
  "alert_baseline": <int>,                 # last funding high-water mark; 0 if never funded
  "reload_cap_consumed_credits": <int>,    # auto-reload credits settled this NYC month
  "reload_cap_rearm_at": <iso8601>,        # first instant of the next NYC month
  "presets": [ { "id": <str>, "trigger_balance": <int>, "reload_target": <int>, "label": <str> } ]
}
Status Meaning
200 The tenant wallet's policy (configured or not)
404 PAYG disabled (HUITZO_PAYG_ENABLED off), or the tenant has no wallet account
PATCH /api/v1/wallet/reload/policy
Authorization: Bearer {jwt_token}
# pseudocode — request body; every field optional, omitted ⇒ unchanged
{ "preset_id": <str|null>, "enabled": <bool>, "reload_cap_credits": <int|null> }

A client-supplied trigger_balance or reload_target is rejected (422), never clamped — both are server-resolved from the preset. preset_id: null clears the preset (and is refused while enabled stays true, since an armed wallet with no target can never size a purchase). reload_cap_credits: null means unlimited, never zero. Money-adjacent and Bearer-only; refuses an API-key principal. Responds with the same shape as GET.

Status Meaning
200 Applied; body is the re-read policy
400 Unknown preset; preset above the wallet's rung ceiling (R2); cap below reload_target or below the smallest preset; enabled: true with no resolved preset. Carries a closed-vocabulary details.reason: unknown_preset, preset_above_rung, cap_below_reload_target, cap_below_minimum_reload, enable_without_preset
401 admin_reauth_required — the caller's JWT is older than the step-up window (ADR-036 §1.2: reload-policy writes are fresh-auth actions). Checked after the 404 dark gate and the API-key 403
403 Caller is an API-key principal, or is not the tenant's owner or an admin; auto_recharge_unavailable_region when the wallet's owner is a Mexican consumer or has no country on file, whatever the flags, with error.details.reason mx_consumer or unknown_country (tenant auto-recharge), sent only with enabled: true; nothing in the request is written
404 PAYG disabled (HUITZO_PAYG_ENABLED off), or the tenant has no wallet account
409 team_managed_billing or house_plan_no_topup (a member of a payg tenant gets 403). With HUITZO_LOT_OWNER_CAPTURE_ENABLED on: billing_address_required when enabled: true arms a wallet with no billing address on file; nothing in the request is written (lot owner capture). With HUITZO_DISPUTE_CLAWBACK_ENABLED on: wallet_account_frozen or wallet_account_closed when enabled: true targets a wallet frozen or closed after a chargeback; nothing in the request is written (dispute clawback)
422 Body contained a server-owned field (trigger_balance, reload_target) or a malformed value

PAYG Wallet Usage & Cost Projection

Read-only summary and paginated detail endpoints over the ADR-035 usage ledger and the ADR-036 wallet policy (T-070, D-13). See credits reference. Dark behind HUITZO_PAYG_ENABLED. A member sees only the charges they caused; an admin/owner may pass account_id to inspect a specific account of the tenant or omit it for a tenant-wide aggregate (/charges, /by-dimension only — /summary reads the tenant account).

GET /api/v1/wallet/usage/summary?account_id={uuid}&period={YYYY-MM}
Authorization: Bearer {jwt_token}
# pseudocode — response (200)
{
  "data": {
    "account_id": <uuid>,
    "wallet": {
      "available_credits": <int>, "held_credits": <int>, "current_rung": <int>,
      "accrued": "<credits string>"  # ADR-038 §5.2/§10 (M-10) — e.g. "0.340"
    },
    "period": {
      "period": "2026-08",
      "opening_balance_credits": <int>,
      "closing_balance_credits": <int>,
      "totals_by_entry_kind": { <entry_kind>: <int> }  # sparse — only kinds that occurred; keys drawn from purchase/grant/charge/expiration/adjustment
    },
    "budget": {
      "enabled": <bool>, "trigger_balance": <int>, "reload_target": <int|null>,
      "reload_cap_credits": <int|null>, "reload_state": <str>
    } | null,
    "recent_accrual_drawdowns": [  # ADR-038 §5.3/§10 (M-10) — newest first, [] if none
      {
        "id": <uuid>, "credits_drawn": <int>,
        "accumulator_before": <int>, "accumulator_after": <int>,  # millicredits — the ONE raw-millicredit surface, an audit field, never the `accrued` denomination
        "contributing_period_start": <iso8601>, "contributing_period_end": <iso8601>,
        "occurred_at": <iso8601>
      }
    ]
  }
}
GET /api/v1/wallet/usage/charges?account_id={uuid}&limit={int}&offset={int}
Authorization: Bearer {jwt_token}

Newest-first, paginated. A charge that has not reached state='settled' carries settled_credits: null — never a fabricated/inferred cost.

# pseudocode — response (200)
{
  "data": [
    {
      "id": <uuid>, "correlation_id": <str|null>, "state": "settled",
      "reserved_credits": <int>, "settled_credits": <int|null>,
      "uncollected_credits": <int>, "estimated": <bool>,
      "reserved_at": <iso8601|null>, "settled_at": <iso8601|null>,
      "allowance_units": <int>,                         # ADR-041 D4 — units, never credits
      "billing": "billable" | "report_only" | null,   # ADR-038 §10 (M-10)
      "accrued": "<credits string>" | null              # ADR-038 §10 (M-10)
    }
  ],
  "meta": { "limit": <int>, "offset": <int>, "total": <int> }
}

billing/accrued are null whenever there is no linked usage_events row — true for a charge that has not yet settled, and ALSO true for an estimated=true lost-provider-response settlement (ADR-035 §4.2: real money moved, but no UsageEvent is ever written for that settlement shape). settled_credits == 0 MUST NOT be read as proof of report-only — a billable sub-credit charge under accrual settles 0 too; billing is the field that answers that question. accrued is set for a report-only charge too (its cost is real even though it never reaches the account accumulator) — it answers "what did this cost," never "what does the customer owe."

allowance_units is the part of the charge the tenant's plan allowance paid (ADR-041 D4), in units. It is 0 for a charge the allowance did not touch. It is never a credit figure and never has a dollar value: settled_credits and uncollected_credits are the credit part only.

GET /api/v1/wallet/usage/by-dimension?account_id={uuid}&period={YYYY-MM}&limit={int}&offset={int}
Authorization: Bearer {jwt_token}

Per-product usage totals for one NYC calendar month, settled charges only.

# pseudocode — response (200)
{
  "data": [
    {
      "product": <str>, "charge_count": <int>, "settled_credits": <int>,
      "billable_charge_count": <int>, "report_only_charge_count": <int>,  # ADR-038 §10 (M-10) — always sum to charge_count
      "accrued": "<credits string>" | null  # ADR-038 §10 (M-10) — null if even ONE contributing charge lacks a figure, never a partial sum shown as a total
    }
  ],
  "meta": { "period": "2026-08", "limit": <int>, "offset": <int>, "total": <int> }
}
GET /api/v1/wallet/usage/daily?account_id={uuid}&period={YYYY-MM}&limit={int}&offset={int}
Authorization: Bearer {jwt_token}

Per-NYC-calendar-day exact-cost buckets for one period (settled charges only), feeding the Usage/cost tab's trend graph (T-232). Same join and null-honesty rule as /by-dimension, applied per billing split.

# pseudocode — response (200)
{
  "data": [
    {
      "day": "2026-08-01",
      "billable_charge_count": <int>, "report_only_charge_count": <int>,
      "billable_accrued": "<credits string>" | null,      # null if any billable charge that day lacks a figure, or none exist
      "report_only_accrued": "<credits string>" | null    # same rule, report-only split
    }
  ],
  "meta": { "period": "2026-08", "limit": <int>, "offset": <int>, "total": <int> }
}
GET /api/v1/wallet/usage/price-versions/{price_version_id}
Authorization: Bearer {jwt_token}

The rate-card explanation for one PUBLISHED price version whose effective_from has arrived — platform-global, no tenant scoping. A draft or future-dated version answers 404 (not a customer-facing fact yet); a version superseded by a later one is still served (it explains a historical charge priced under it).

# pseudocode — response (200)
{
  "data": {
    "id": <uuid>, "version": <int>, "product": <str>,
    "usd_minor_per_credit": 10, "rates": <object|null>,
    "effective_from": <iso8601>, "effective_to": <iso8601|null>
  }
}
Status Meaning
200 Data returned
400 period present but not a valid YYYY-MM key
403 account_id names an account other than the tenant account (member only); a member on /summary (tenant wallet)
404 PAYG disabled (HUITZO_PAYG_ENABLED off); the tenant has no wallet account (a member on any of the four endpoints, or an admin/owner on /summary — /charges//by-dimension fall back to a tenant-wide aggregate instead for those two roles); an admin/owner-supplied account_id that names no account in the caller's tenant, including one that belongs to a different tenant entirely; or, for /price-versions/{id}, no published/effective version with that id

API Keys

Machine-to-machine authentication for CI/CD pipelines and scripts. Keys use the format sk-huitzo-<64 hex chars> (256-bit entropy), hashed with argon2id at rest.

Role: An API key always acts as member, whatever the role of the user who created it, so it never confers owner or admin powers. Routes that need either role refuse it, among them Uninstall Pack, Grant Pack Access, Delete Dashboard and Grant Dashboard Access.

Auth: All endpoints require JWT. API keys cannot manage other API keys.

Create API Key

POST /api/v1/account/api-keys
Authorization: Bearer {jwt_token}
Content-Type: application/json
# pseudocode — request
{ "name": "descriptive-name", "scopes": ["commands:execute"] }
# pseudocode — response (201, plaintext key returned exactly once)
{
  "data": {
    "id": "uuid",
    "name": "descriptive-name",
    "key": "sk-huitzo-<64 hex chars>",
    "key_prefix": "sk-huitzo-abcd12",
    "scopes": ["commands:execute"],
    "created_at": "ISO8601"
  }
}

Allowed scopes: commands:execute (command execution and MCP), files:read (file downloads via Download a File).

List API Keys

GET /api/v1/account/api-keys
Authorization: Bearer {jwt_token}

Returns metadata only — never returns the hashed secret.

# pseudocode — response fields per key
{ "id", "name", "key_prefix", "scopes", "last_used_at", "revoked_at", "created_at" }

Revoke API Key

Soft-delete — sets revoked_at, does not hard-delete the row.

DELETE /api/v1/account/api-keys/{key_id}
Authorization: Bearer {jwt_token}
Code Condition
200 Key revoked
403 Request came via API key (keys cannot revoke keys)
404 Key not found or belongs to another user

Organizations

Create Organization

Create a new organization (requires Developer Mode).

POST /api/v1/organizations
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "name": "New Organization",
  "slug": "new-org"
}

Response:

{
  "data": {
    "organization": {
      "id": "org_new123",
      "name": "New Organization",
      "slug": "new-org",
      "scope": "@new-org",
      "createdAt": "2026-01-24T10:30:00Z"
    }
  }
}

Get Organization

GET /api/v1/organizations/{org_id}
Authorization: Bearer {token}

Response:

{
  "data": {
    "organization": {
      "id": "org_xyz789",
      "name": "Acme Corp",
      "slug": "acme",
      "scope": "@acme",
      "createdAt": "2026-01-01T00:00:00Z",
      "members_count": 3,
      "packs_count": 5
    }
  }
}

Invite Member

Invite a user to join the organization.

POST /api/v1/organizations/{org_id}/invite
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "email": "[email protected]",
  "role": "member"
}

Response:

{
  "data": {
    "invite": {
      "id": "inv_abc123xyz",
      "email": "[email protected]",
      "role": "member",
      "expiresAt": "2026-02-07T10:30:00Z"
    },
    "message": "Invitation sent to [email protected]"
  }
}

Available Roles:

Role Permissions
owner Full control, billing, delete org
admin Manage members, publish packs
member Publish packs under org scope

List Members

GET /api/v1/organizations/{org_id}/members
Authorization: Bearer {token}

Response:

{
    "data": [
    {
      "id": "usr_abc123",
      "user_id": "usr_user123",
      "email": "[email protected]",
      "role": "owner",
      "joined_at": "2026-01-01T00:00:00Z"
    },
    {
      "id": "usr_def456",
      "user_id": "usr_user456",
      "email": "[email protected]",
      "role": "admin",
      "joined_at": "2026-01-15T00:00:00Z"
    }
  ]
}

Remove Member

DELETE /api/v1/organizations/{org_id}/members/{user_id}
Authorization: Bearer {token}

Response:

{
  "data": {
    "message": "Member removed from organization"
  }
}

Commands

List Commands

List every command the caller can discover: the commands of each pack's active version, for packs the caller owns, public packs, and organization-visibility packs the caller's tenant holds a grant for. unlisted packs are never listed (they stay reachable by exact namespace). Ordered by namespace. The endpoint takes no query parameters and returns every row.

input_schema is always a JSON Schema object and never {}. A bare {"type": "object"} means no argument shape was stored for that command — see Command Input Schema for the cases that produce it.

summary is the one line a listing shows (from the manifest's commands[].description); description is the full text (from the decorator or docstring). Both are strings, never null — see Command description.

GET /api/v1/commands
Authorization: Bearer {token}

Response (200):

data is an array; each entry has exactly these fields.

Field Type Description
id string (UUID) The command row
namespace string @scope/pack/command — the address to get and execute; its last segment is the command's name
name string The decorator's command name
summary string First non-empty line of the manifest description, falling back to the first non-empty line of description; "" when neither exists
description string Full normalized description; "" when none was given
version string The pack version that published this row (the active version)
timeout integer Seconds, as stored at publish
input_schema object JSON Schema of the args model
{
  "data": [
    {
      "id": "0b8f3c52-6a1e-4d2b-9f47-3c1a8e5d7b20",
      "namespace": "@acme/finance/analyze",
      "name": "analyze",
      "summary": "Analyze portfolio performance",
      "description": "Compute returns, volatility and drawdown for a symbol.\n\nPrices come from the configured market-data integration.",
      "version": "2.0.0",
      "timeout": 60,
      "input_schema": {
        "type": "object",
        "properties": {
          "symbol": { "type": "string" },
          "period": { "type": "string", "enum": ["1d", "1w", "1m", "1y"] }
        },
        "required": ["symbol"]
      }
    }
  ]
}

Error Responses:

Status Condition
500 Database or unexpected error

Get Command

Get one command by its full namespace. Same visibility as List Commands, except that an unlisted pack's command is returned when addressed exactly.

input_schema, summary and description follow the same rules as List Commands.

GET /api/v1/commands/@{scope}/{pack}/{command}
Authorization: Bearer {token}

Response (200): data is one object with the same eight fields as a List Commands entry.

{
  "data": {
    "id": "0b8f3c52-6a1e-4d2b-9f47-3c1a8e5d7b20",
    "namespace": "@acme/finance/analyze",
    "name": "analyze",
    "summary": "Analyze portfolio performance",
    "description": "Compute returns, volatility and drawdown for a symbol.\n\nPrices come from the configured market-data integration.",
    "version": "2.0.0",
    "timeout": 60,
    "input_schema": { "type": "object", "properties": { "...": "..." } }
  }
}

Error Responses:

Status Condition
400 The namespace is not @scope/pack/command (three non-empty segments), or its scope is reserved
404 Command not found or not visible to the caller
500 Database error

Execute Command

Run one command by its full namespace. The command resolves under the same visibility as Get Command, so an unlisted pack's command runs when addressed exactly. A pack that a platform operator has disabled is refused. Handler: apps/backend/src/backend/api/v1/commands.py::execute_command.

POST /api/v1/commands/@{scope}/{pack}/{command}
Authorization: Bearer {token}
Content-Type: application/json

{token} is a session JWT or an sk-huitzo- API key.

Request:

Field Type Description
args object The command's arguments, shaped by its input_schema (see Get Command). Optional; defaults to {}
{ "args": { "symbol": "AAPL", "period": "1m" } }

The body itself is required: send {} for a command that takes no arguments. Top-level fields other than args are ignored, so an argument sent outside args never reaches the command. The endpoint does not check args against input_schema; the command's own args model validates them when it runs, and its failure is a 400 (see the 400 rows under Error Responses and a failing args model).

Sync or async. The command's declared queue, resolved as described in Queue Resolution, decides how it runs. fast runs inline in this request and answers 200 with the result. medium and long are dispatched to a Celery worker and answer 202 with a task to poll.

Response (200, fast queue):

Field Type Description
result any The command's return value, JSON-encoded
correlation_id string (UUID) Minted for this request and recorded on the execution row
{
  "data": {
    "result": {
      "symbol": "AAPL",
      "performance": { "return": 0.0842, "volatility": 0.23 },
      "recommendation": "Hold"
    },
    "correlation_id": "4e9b2f61-0c7d-4a3e-9f15-8d2c6b7a1e03"
  }
}

Response (202, medium or long queue): a dispatch receipt, never the command's output. The execution row is committed as queued with this task_id before the task is enqueued, so Get Task Status resolves it as soon as this response arrives. Poll it for the outcome. The arguments are validated on the worker, after the 202: a failing args model closes the task as failure.

Field Type Description
task_id string (UUID) The id to poll with Get Task Status
queue string medium or long
correlation_id string (UUID) Minted for this request and recorded on the execution row
status string Always queued
{
  "data": {
    "task_id": "b7d5e0c4-2a19-4f6e-8c3b-91a0d4f2e7c8",
    "queue": "medium",
    "correlation_id": "4e9b2f61-0c7d-4a3e-9f15-8d2c6b7a1e03",
    "status": "queued"
  }
}

If the broker rejects the enqueue, the row moves to failure (an update that never overwrites a terminal state the worker already wrote) and the endpoint answers 503.

Execution-status lifecycle (command_executions.status):

queued → started → success | failure | timeout

queued is set at dispatch for async commands; started and the terminal state are written by the worker (which may put a started row back to queued while it retries a command whose pack build is not ready on it yet, ending failure with PACK_BUILD_UNAVAILABLE past the retry window: pack build permission repair), except that the API closes a queued row as failure when the broker rejects the enqueue or the command is missing from its registry. Inline (fast) commands never enter queued: they open at started and close at the terminal state in the same request, except after a Database error occurred 500, which leaves the row for the stale-execution reaper. Cancel Task closes an unfinished task as revoked.

Error Responses:

Every row except the second 422 uses the error envelope.

Status Condition error.details
400 The namespace is not @scope/pack/command (three non-empty segments), or its scope is reserved none
400 The command raised the SDK's ValidationError. This includes a failing args model: the message gives each failing field and the reason, never the rejected value (bar the residuals under a failing args model) correlation_id
400 Any other ValueError raised in the API process. The execution row, if one exists, closes as failure, rendered like every other failure (pydantic's text, the registry miss's text, the class alone for any other ValueError) none
402 INSUFFICIENT_CREDITS: see Insufficient Credits Error correlation_id plus the fields that section lists
403 The pack is disabled by a platform operator correlation_id
403 The command raised PackPermissionError correlation_id
403 or 503 An LLM authorization refusal correlation_id, code and the refusal's fields
404 Command not found: no such command, or not visible to the caller none
404 Command not available in this deployment: …: the command is in the database but this API process cannot register it: its pack is not visible to the caller, or the build provides no such command. A build that has not reached this server is never this 404: it is the 503 PACK_BUILD_NOT_READY below, however long it lasts. A build that cannot be described is never this 404 either: it is the 503 PACK_BUILD_UNAVAILABLE below. This process remembers this answer for 30 seconds per tenant, namespace and version, so a pack newly shared with the tenant can still answer 404 for up to 30 seconds. A published build this process has not registered yet is loaded first, or answered with the 503 PACK_BUILD_NOT_READY below while it is described; it gets this 404 only in the cases listed above (inline miss path) none
409 error.code license_limit_exceeded: the deployment reached its licence monthly_executions limit (Core editions) key, limit, current, attempted_delta, scope
409 error.code tenant_quota_exceeded: the tenant reached its trailing-30-day monthly_command_cap (tenant quotas) key, limit, current, attempted_delta
409 The installed build of this command does not match its published declaration: the build registered here routes the command to a different queue than its published queue/timeout, even after this process reloaded the promised build. A build that has not reached this server yet is the 503 PACK_BUILD_NOT_READY below instead, and a build that cannot be described is the 503 PACK_BUILD_UNAVAILABLE below. MCP tools/call answers the same refusal as error content (static registration). Nothing ran none
422 The command raised CommandError or a subclass correlation_id
422 The body is missing or not JSON, or args is not an object. FastAPI's own {"detail": [...]} body n/a
429 INLINE_CAPACITY_EXCEEDED, with Retry-After: 10: too many inline commands are running for this tenant or this server code, scope, namespace, correlation_id
500 Database error occurred none
500 Command execution failed: any other exception. Because a pack command runs in an isolated child (ADR-039), this includes a pydantic.ValidationError the command's body raises, which reaches the API process as a non-SDK error correlation_id
503 error.code license_count_unavailable: a licence monthly_executions limit applies and the usage count could not be read. No execution was recorded counter
503 Failed to queue command for execution: the broker rejected the enqueue correlation_id, task_id
503 error.code PACK_BUILD_NOT_READY, with Retry-After: 5: the command is published but its build is not ready on this server yet: it has not reached this server (or this server still holds only an earlier release), or it is being described in the background (a fresh publish: its describe started with this call or an earlier one), or this server's startup permission repair has not reached it yet. Not a capacity condition: when the server is already describing as many builds as it allows (32) and this one needs describing too, the answer is the capacity 429 ISOLATION_CAPACITY_EXCEEDED instead. Temporary, however long it lasts: never a 404. Nothing ran and no execution row exists. A build still missing 2 minutes after this server first answered so is logged once at ERROR (pack_build_not_ready_overdue) for operators, and keeps this answer. MCP tools/call answers retryable error content with type: "pack_build_not_ready" and retry_after (inline miss path) code, namespace, correlation_id
503 error.code PACK_BUILD_UNAVAILABLE, with no Retry-After: the command is published and its build is on this server, but the build cannot be described, so none of its commands can start here. Its description recently hung or crashed (staff see inspection_failed; it is tried again after 15 minutes), or failed in this process within the last minute (its isolated child did not start or crashed, or the build still did not have the build permission rule when this server's startup permission repair finished). One entry point that fails to import is not this: that command alone is not registered, the 404 above. Message: "This pack version can't start on this server right now; Huitzo has been alerted." The server logs one ERROR (pack_build_unavailable, with the namespace and the build's owner tenant, pack id and version) per build at most once a minute. Not a capacity condition: never the 429, never a 404, and a client retrying sooner gets the same answer. Nothing ran and no execution row exists. MCP tools/call answers error content with type: "pack_build_unavailable" and retryable: false (inline miss path) code, namespace, correlation_id
429 ISOLATION_CAPACITY_EXCEEDED, with Retry-After: 5 code, namespace, correlation_id
504 The executor's own timeout fired: Command execution timed out, error.code TIMEOUT. An inline command's timeout is capped at HUITZO_INLINE_COMMAND_TIMEOUT_SECONDS (details) correlation_id

Any other huitzo_sdk.errors exception the command raises is answered with the status, code and type of its nearest SDK class, with details correlation_id and retryable: see Errors a command raises.


Tasks

Task polling endpoints allow clients to check the status of async command executions and cancel running tasks. These are the primary integration surface for CI/CD pipelines via the GitHub Action (run-pack-action@v1).

Auth: JWT or sk-huitzo-* API key. Caller must own the task (matched on user_id AND tenant_id).

State resolution: the DB row is authoritative. It is committed with status: "queued" at dispatch, so the task is resolvable immediately (no more 404 races on a freshly-dispatched task). Terminal states (success, failure, timeout, revoked) are authoritative from the DB, including the persisted result. For a still-running task the Celery AsyncResult is consulted only to advance the reported state (e.g. queued → started when the worker has begun but its DB write has not yet landed); it is never used to downgrade a specific queued/started to Celery's ambiguous PENDING, nor to synthesize a terminal state — the worker's DB write is the source of truth for terminal status and result.

Get Task Status

GET /api/v1/tasks/{task_id}
Authorization: Bearer {token_or_api_key}

Status values: queued | pending | started | success | failure | timeout | revoked

Response (success):

# pseudocode — illustrative shape, not copy-paste
{
  "success": true,
  "data": {
    "task_id": "uuid",
    "status": "success",
    "result": { "...pack output..." },
    "error": null,
    "started_at": "ISO8601",
    "completed_at": "ISO8601",
    "correlation_id": "uuid",
    "executed_version": "1.2.0",
    "worker_pid": 41,
    "worker_hostname": "worker-fast-2"
  }
}

Response (failure):

# pseudocode
{
  "success": true,
  "data": {
    "task_id": "uuid",
    "status": "failure",
    "result": null,
    "error": { "message": "human-readable", "type": "ExceptionClassName", "origin": "unexpected" },
    "started_at": "ISO8601",
    "completed_at": "ISO8601",
    "correlation_id": "uuid",
    "executed_version": "1.2.0",
    "worker_pid": 41,
    "worker_hostname": "worker-fast-2"
  }
}

The caller is always the task's own user, so error is the failure detail when the row stores one: error.message is its message, error.origin its origin (sdk, validation, unexpected). result is null for any row whose status is not success. A row without a failure detail returns error_message and no origin. For an exception from huitzo_sdk.errors, error.message is the caller-facing text Errors a command raises assigns, the same text a synchronous execute returns, apart from two differences described under The stored text there: pydantic's input echo is removed, and ValidationError, PackPermissionError and CommandError text is cleaned.

Executed build identity. executed_version, worker_pid and worker_hostname report which build actually ran, not which one was dispatched. The worker writes them the moment it has resolved the pack build and before it calls the command, so a task that timed out or was closed by the stale-execution reaper still names the build that was running. All three are null for a row no worker has picked up yet, and executed_version is also null for a platform command that comes from no pack venv. When executed_version is present it is the version recorded in the installed distribution's own metadata, which the worker has already proven to be the same release as the dispatched version — a disagreement it cannot resolve is refused instead, as a terminal failure whose error.type is PackVersionMismatchError (see compute-pool.md §1.4).

Error responses:

Code Condition
401 Missing or invalid auth
403 Task belongs to a different user or tenant
404 Task ID not found
410 Task completed but result expired (never persisted to result_full)

Cancel Task

Cancel a running task. Returns 409 Conflict if the task is already in a terminal state (success, failure, timeout, revoked).

POST /api/v1/tasks/{task_id}/cancel
Authorization: Bearer {token_or_api_key}

Response (200):

# pseudocode
{
  "success": true,
  "data": {
    "task_id": "uuid",
    "revoked": true
  }
}

Error responses:

Code Condition
403 Not your task
404 Task not found
409 Task already in terminal state

Studio

Studio is the pack-creation journey: Intent → Spec → Plan → Build. Every route below is session-authenticated (Authorization: Bearer {token}) and RLS-scoped to the caller's tenant — a tenant-A user can never read or act on a tenant-B row; the row is simply invisible (404), never a 403 that would confirm it exists. Responses use the standard {"data": ...} / {"error": ...} envelope except where a route's own frozen contract predates it and is noted inline (GET /studio/runners, GET /studio/plans).

For the wire-level job envelope, lease, and event schemas the runner side of these builds speaks, see Studio Channel Contracts and Runner Channel. For the derived sessions read-model's full latest.* rollup shape, see Studio Sessions.

Intents — Clarify & Specify

Method Path Description
POST /api/v1/studio/intents Create an Intent from the user's own prose, then immediately run CLARIFY scoring against it.
GET /api/v1/studio/intents/change-targets List the packs a published dashboard uses that the caller may start a change from, each at the version it would start from.
GET /api/v1/studio/intents/{intent_id} Inspect one of the caller's own intents.
POST /api/v1/studio/intents/{intent_id}/answers Record answers to the CLARIFY questions and re-score.
POST /api/v1/studio/intents/{intent_id}/rescore Re-run CLARIFY scoring on a draft Intent with no open question (the retry for a refused POST /intents, and the revival of a draft left with nothing to ask).
POST /api/v1/studio/intents/{intent_id}/specify Dispatch an async SPECIFY draft job from a clarified Intent; with the optional body {"skip_clarify": true}, first advance a draft Intent to clarified (the owner's "skip to drafting").
Change missions

A change mission starts from a published version (artifact model §3.1). POST /intents takes an optional change object, sent with "source": "evolve":

POST /api/v1/studio/intents
Content-Type: application/json

{
  "prose": "Add a column for the delivery date.",
  "source": "evolve",
  "change": {
    "namespace": "acme",
    "name": "orders",
    "base_version": "0.4.0",
    "dashboard": {"namespace": "acme", "name": "orders"}
  }
}

namespace may carry its leading @; dashboard is optional. The created Intent returns change_target (the stored shape, or null on a new mission), and every intent read returns it too. The CLARIFY pass runs exactly as on a new mission.

GET /intents/change-targets?dashboard_namespace=acme&dashboard_name=orders writes nothing. It answers 200 with {"change_targets": [...]}: for each pack the dashboard's active version depends on (in declared order, each once) that the caller's team owns and has an active published version of, the change_target a create would store, starting from that active version and naming this dashboard. Packs the team may not change are left out, so the list may be empty. The server reads the stored dependency list itself and does a fixed number of queries whatever its length, so the caller sends one request per listing. The Hub calls it to decide whether to show Change this on a listing.

The create answers the refusals of §3.1, each with its code in error.code and error.details.reason: 403 not_owner_or_admin (also for any API-key caller: keys are member-scoped) or not_publisher; 404 pack_not_found, version_not_found or dashboard_not_found; 409 dashboard_not_published or pack_not_a_dependency (the named dashboard does not use that pack). The list answers only those about the caller and the dashboard: 403 not_owner_or_admin or not_publisher, 404 dashboard_not_found, 409 dashboard_not_published.

Who may act on it. Every later mutation of a change mission (answers, rescore, specify, every Spec and plan action, decisions, build approvals, abort, interrupt, a managed checkout's cancel, finding dispositions, publish and its cancel, archive) needs the same caller as the create: an owner or admin signed in as a person. Anyone else who can see the mission gets 403 not_owner_or_admin ("Only an owner or admin can change a published pack") before anything is written; reads stay open. The full list is in artifact model §3.1. Session reads carry change_locked: true for a reader who may only follow the mission (sessions).

A 422 carries no closed code. It answers a change sent without "source": "evolve", an evolve create with no change, a value that is not a valid name, namespace or version, and, on the list, a missing dashboard_namespace or dashboard_name.

POST /intents and /answers insert or update the Intent row in one transaction, then run CLARIFY (a two-call LLM pass) as a separate step — a scoring refusal (503, router/budget; 502, the provider rejected the call or the model answered without a result) or an LLM-input-too-large refusal (422) leaves the Intent durably created but unscored; it is never rolled back. A refused POST /intents records the refusal on the Intent (clarify_failure, returned by every intent read), which the session rollup names as a clarify-leg failure, and POST /rescore re-runs the same pass: it takes no body, invents no answers (any already recorded feed the prompt and are kept), and returns the same Intent shape and refusals as POST /intents. It also admits a draft that WAS read but has no open question (a pass from before CLARIFY's never-nothing-pending rule), so a mission left stranded there can be read again. It answers 409 when the Intent is no longer a draft, and 409 with error.details.reason (checked before any model call and again under the persist step's row lock) when the draft still has open questions (pending_questions: answer them through /answers; a re-score would replace them), was judged out of scope (out_of_scope: the same words get the same verdict, so the way on is a new mission), or has had three persisted re-reads (round_cap; clarification.rescore_rounds, which answer rounds never move).

Every pass that persists ends in one of three states: an open question, a recorded failure, or clarified (artifact model §4). An idea Studio cannot build as a pack (a one-off deck or document, a human service) stays draft with clarify_failure = {"kind": "out_of_scope", "headline", "reason", "at"}, where reason is the model's explanation in the user's language; the session rollup names it as a clarify-leg failure with retry.kind: none and adds kind/reason to the block (sessions §2.1). A buildable draft below the threshold with nothing to ask is given a question, or advanced to clarified with clarification.low_confidence_advance: true. A pass whose independent reviewer answers revise and leaves open questions stays draft with those questions to answer, at most three times (clarification.review_holds); an Intent that advances with questions still open records them in clarification.unanswered_open_questions, and SPECIFY states its assumption for each (artifact model §4). The reviewer sees the recorded answers, an answer wins over the intent text, and a point an answer settles is not asked again. /answers stops asking on the fifth answer round: the pass that brings clarification.answer_rounds to 5 answers 200 with the Intent clarified (clarification.round_cap_advance: true when only the cap advanced it), carrying its open questions in unanswered_open_questions. An out-of-scope verdict never advances. A retried /answers whose answers are all already recorded (the same question, ignoring case and punctuation, and the same answer, ignoring surrounding whitespace) is not a new round: it makes no model call and returns 200 with the Intent unchanged, whatever its status, so the retry of a batch whose pass advanced the Intent answers like the original. A batch with a new answer on an Intent that is no longer a draft is still 409. The 64-answer cap (422) remains as a backstop. POST /specify is asynchronous (SD11): it returns 202 with a new spec_jobs row immediately, and the draft itself runs later in the worker. It takes an optional body {"skip_clarify": bool} (default false; no body or {} is accepted). With skip_clarify: true on a draft Intent, the Hub first advances the Intent to clarified in the same transaction that inserts the job, recording clarification.owner_skipped: true and the draft's open questions in unanswered_open_questions. On an Intent that is already clarified, the flag behaves like a plain call, so a retry after a lost response is idempotent. Every 409 from /specify sets error.code and error.details.reason to the same code:

Code When
not_clarified The Intent is a draft and skip_clarify is not set, or it is in any status other than draft or clarified (including a concurrent pass moving the draft anywhere but clarified while the skip ran; one that clarified it gets a plain specify).
already_drafting A job is already pending/running for this Intent. details.spec_job_id names it when the Hub can look it up.
out_of_scope skip_clarify on a draft Studio judged out of scope. No job is created.

A second /specify while a job is already pending/running for the same Intent returns 409 already_drafting; /specs/{id}/revise (below) answers its own 409 naming the in-flight spec_job_id.

POST /api/v1/studio/intents
Authorization: Bearer {token}
Content-Type: application/json

{
  "prose": "Build a dashboard that shows weekly signups by plan tier.",
  "source": "dashboard"
}
{
  "data": {
    "id": "8f2b...intent",
    "prose": "Build a dashboard that shows weekly signups by plan tier.",
    "source": "dashboard",
    "status": "clarified",
    "clarification": { "questions": [], "confidence": 0.86 },
    "clarified_by": null,
    "supersedes_id": null,
    "created_at": "2026-09-10T10:00:00Z",
    "updated_at": "2026-09-10T10:00:02Z"
  }
}

Error responses: 404 intent not found; 409 intent not in a clarifiable/clarified state, or a spec job already in flight ({spec_job_id} in details), where every /specify 409 names not_clarified, already_drafting or out_of_scope in error.code and error.details.reason; 422 too many recorded answers, or the intent's content is too large for CLARIFY to process; 502 a model route did resolve and the provider or the model gave nothing usable; 503 CLARIFY/SPECIFY has no usable model route, or exceeded its time budget. The same 502/503 split applies to the plan-scoped DECIDE and DECOMPOSE calls.

A 502 is one of three cases, told apart by its message:

Case Message Will a retry help?
The provider answered the request with a client error (other than 408/429) "The model provider rejected this stage's request (HTTP N); a model route did resolve, so this is not a routing problem" Not until the cause is fixed on Huitzo's side
The model declined the request (stop_reason: refusal) "The model declined to produce a result for this request; a model route did resolve, so this is not a routing problem. Sending the same content again will most likely be declined again; rewording it may help" Most likely not with the same content; reword it
The model reached its output-token ceiling before finishing (stop_reason: max_tokens) "The model ran out of its output budget before finishing this stage; a model route did resolve, so this is not a routing problem. This is a Studio configuration problem, not something in your request" No: an operator-side setting, not the request

The last two carry no HTTP status: the provider's call succeeded and the model's own answer was unusable. They are never reported as 503 "no usable model route".


Specs — Approve & Revise

Method Path Description
GET /api/v1/studio/specs/{spec_id} Inspect one of the caller's own specs.
GET /api/v1/studio/specs/{spec_id}/export.pdf Export a spec as a share-before-approve PDF.
POST /api/v1/studio/specs/{spec_id}/approve Approve a draft Spec, minting its section anchors.
POST /api/v1/studio/specs/{spec_id}/revise Dispatch an async SPEC REVISION job (SD13) with the caller's answers/guidance folded in.
POST /api/v1/studio/specs/{spec_id}/autonomy Set a draft Spec's policy autonomy (the owner's opt-out from the autonomous default).
POST /api/v1/studio/specs/{spec_id}/data-scope Set who sees a draft Spec's data, as the owner's own choice for the mission (below).

revise sends {"responses": [{"question", "answer"}], "guidance": ""} — at least one of responses/guidance is required. It reuses the exact same spec_jobs async job SPECIFY dispatches (same 202 shape, same in-flight guard) and only a draft Spec may be revised (422 on approved / superseded). A revised draft lands as a new Spec version, linked via supersedes_id; the superseded version stays readable.

Who sees the data {#studio-spec-data-scope}. data-scope sends {"data_scope": "user" | "tenant"} and answers 200 with the Spec. It sets the draft's policy data_scope and its generated policy section, removes the Spec's data_scope_suggestion Hub note, and records the choice on the mission (intents.clarification.owner_data_scope), so every later version stores it whatever the drafter reports. A value outside the two is 422; a Spec that is not a draft, has no readable policy, or has a revision in flight is 409 spec_data_scope_locked (error.code and details.reason); another tenant's Spec is 404. On a change mission the caller must be an owner or admin (403 not_owner_or_admin, who may act). The data scope is never set from model output (studio-artifact-model).

autonomy sends {"autonomy": "act_with_approval"} (any value of the Policy Card vocabulary) and answers the updated Spec. Only a draft Spec that has a readable structured policy, and whose intent has no revision in flight, may be changed (409 otherwise; 404 for a Spec the caller cannot see; 422 for a value outside the vocabulary or any other key in the body). A later revision keeps the value. See the opt-out.

read_only on a Spec whose permissions list has a write is refused by both autonomy and approve with 422, error.code = autonomy_conflicts_with_permissions, error.details.reason = the same code and error.details.writes = the write tokens (sorted); nothing is written and the Spec stays a draft. A Spec with permissions: null is never refused this way.

POST /api/v1/studio/specs/8f2b.../approve
Authorization: Bearer {token}
Content-Type: application/json

{ "note": "Looks good, ship it." }
{
  "data": {
    "id": "8f2b...spec",
    "intent_id": "8f2b...intent",
    "version": 1,
    "sections": { "...": "..." },
    "confidence": 0.86,
    "open_questions": [],
    "status": "approved",
    "supersedes_id": null,
    "policy": { "autonomy": "suggest", "data_scope": "tenant" },
    "permissions": ["llm:complete", "storage:read", "storage:write"],
    "reviewed_by": "usr_abc123",
    "review_note": "Looks good, ship it.",
    "created_at": "2026-09-10T10:00:02Z",
    "updated_at": "2026-09-10T10:05:00Z"
  }
}

policy is the structured policy the owner approves with the Spec: autonomy (read_only / suggest / act_with_approval / autonomous) and data_scope (user / tenant), drafted by SPECIFY and re-derived by a revision. It is null on Specs drafted before the field existed, and on a Spec whose stored value does not read as a valid policy (plans from such a Spec are refused with 409, never run unpinned). A plan that contradicts it is refused (studio-artifact-model §11.2).

open_questions is a list whose items are string | object. A string is a question the Spec left open. An object is a Hub note, Studio's own message to the owner (today only {"hub_note": "autonomy_conflict", "writes": [<write tokens>]}); tell it apart by its hub_note field, never by its words, and render it with fixed client copy keyed by that code (studio-artifact-model, the autonomy default).

permissions is the list of SDK permission tokens SPECIFY reported the pack's commands need (sorted, unknown tokens dropped); null means unknown (a Spec drafted before the list existed), never "no writes".

Error responses: 404 spec not found; 409 spec already reviewed/changed (approve), or a spec job already in flight (revise); 413 spec too large to export as a PDF; 422 only a draft spec can be revised, revision content exceeds its char budget, or revision has neither responses nor guidance; 422 autonomy_conflicts_with_permissions (approve, autonomy) read only on a Spec that lists a write.


Plans — Review, Execute, Decide, Decompose

Method Path Description
POST /api/v1/studio/plans Create + dispatch a PLAN job against an approved spec_id (required: missing or other-tenant ⇒ 404, not approved ⇒ 409, a Spec whose stored policy cannot be read ⇒ 409). The Hub composes the plan prompt from the Spec (studio-artifact-model §11.1).
GET /api/v1/studio/plans?build_job_id= The reviewable plan row(s) for a plan job.
GET /api/v1/studio/plans/{plan_id} Inspect one plan.
GET /api/v1/studio/plans/{plan_id}/export.pdf Export a plan (+ its Decisions/Tasks) as a PDF.
POST /api/v1/studio/plans/{plan_id}/approve Atomic approve-and-execute: claim the plan and dispatch the build in one act. A plan whose setup_required lists outputs needs acknowledge_setup_required: true (else 422 setup_required_unacknowledged); one whose core output needs setup is refused 409 setup_required_core (runner-channel). A change plan whose Spec changes the base data scope needs acknowledge_scope_change: true (else 422 scope_change_unacknowledged, studio-artifact-model).
POST /api/v1/studio/plans/{plan_id}/execute Plan-scoped re-execution of an already-approved plan (T17/T24).
POST /api/v1/studio/plans/{plan_id}/reject Decline the plan; no build.
POST /api/v1/studio/plans/{plan_id}/request-changes Mark changes_requested and dispatch a new plan job.
POST /api/v1/studio/plans/{plan_id}/revise-spec Ask Studio to revise the plan's approved Spec (W3-23); 202 with the spec job.
POST /api/v1/studio/plans/{plan_id}/decide Run DECIDE: capability-diff trigger against the plan's approved Spec.
GET /api/v1/studio/plans/{plan_id}/decisions List Decisions recorded against the plan.
POST /api/v1/studio/plans/{plan_id}/decompose Run DECOMPOSE: task-sizing trigger over the plan's scope manifest.
GET /api/v1/studio/plans/{plan_id}/tasks List Tasks recorded against the plan.

Create body. POST /api/v1/studio/plans takes prompt (1–8192 characters, kept only as an owner note when it is not the request prose), spec_id, an optional runner_id, and an optional stopped_publish_request_id (W8-4, W9-1): the publish request Mission Control's Plan again comes from when that publish was stopped for stored fields or refused for a command contract. The Hub loads that request in the caller's tenant and requires it to be either needs_confirmation with error_class stored_fields_unread, or failed with error_class publish_rejected and a stored command_contract rejection, for a build job of this Spec's mission (the Spec's Intent). It reads the finding from the row, re-checked like every read of stored_fields or rejection, never from the client, and adds the stopped-fields sentence or the command-contract sentence to the plan prompt. A caller who may not read that finding gets a plan with no sentence and no error: an API key, or a reader the stored-fields rules do not admit (for a rejection, the rejection reading rule), whether or not the request was superseded, as long as it names a stopped publish of this mission. Without the field the plan still gets the sentence for the mission's newest stopped or contract-rejected publish that no later version superseded (as a re-plan, a build and a Fix do), so retrying a failed plan keeps it.

Status error.code = details.reason Condition
422 stopped_publish_not_found stopped_publish_request_id names no request of this tenant that is needs_confirmation with stored_fields_unread, or failed with publish_rejected and a stored command_contract rejection, for a build of this Spec's mission, or (for a caller who may read its finding) one a later version of its pack superseded

GET /plans returns the frozen {"data": {"plans": [...]}} shape (a bare array under data is not accepted by the dashboard's row extractor) — distinct from every other list route on this surface.

Every plan read (GET /plans, GET /plans/{plan_id}) carries policy_check: null when the plan's Spec has no structured policy, else {"result", "spec", "plan"} where result is match, policy_unverified (the plan's manifest states no policy; plan is null) or policy_mismatch (the plan contradicts the approved Spec; the plan is rejected with no reviewer, and approve / execute answer 409 like for any reviewed plan). spec and plan are {"autonomy", "data_scope"} (studio-artifact-model §11.2).

Every plan read also carries scope_check: the verdict approve would reach on the plan's scope_manifest, computed without approving, while the plan is reviewable (proposed or changes_requested, the states approve claims from); null once it is no longer reviewable. result is ok or invalid; an invalid verdict names a class: dashboard_scope_incoherent (the dashboard folder and its tools do not travel together) with missing or stray, whose members come only from the closed set npm, node, registry.npmjs.org and dashboard/** (today only the three tools are ever named; the glob is reserved); or scope_invalid for any other manifest refusal, with the closed rule it broke (manifest_not_object, unknown_key, schema_version, list_shape, too_many_entries, entry_too_long, host_not_exact, path_glob_unsafe, policy_malformed, setup_required_malformed, broad_credential) and nothing else (runner-channel §7.10).

{
  "scope_check": {
    "result": "invalid",
    "class": "dashboard_scope_incoherent",
    "missing": ["node"]
  }
}

Every plan read also carries declined and requested_changes (W3-23). declined is the list of reviewer requests the planner left out, or null when the runner did not report ([] means nothing was declined); each item is {"request", "reason", "spec_change"} with reason spec or policy (runner-channel §4.6). requested_changes is every reviewer note this plan was asked to address, oldest first, and [] for an original plan or a plan with no linked Spec. Both are text to show, never instructions.

Every plan read also carries setup_required (huitzo #2297): the outputs the plan says will not work until the Huitzo team sets them up, each {"output", "core"} (at most 16; output non-blank plain text of at most 200 characters; core true for the main thing the owner asked for). It is [] when the manifest lists none, and also [] when the list is malformed, in which case scope_check is invalid with rule setup_required_malformed. Approve then needs "acknowledge_setup_required": true (a JSON boolean) in its body, or refuses 422 setup_required_unacknowledged; a plan with a core entry is refused 409 setup_required_core either way. Both refusals carry error.code and details.reason = the code (runner-channel).

Every plan read also carries pack_target (W3-29): while the plan is reviewable and the tenant has a publish namespace, the pack name (display form @scope/name), the version a publish would assign now, whether the tenant already owns that pack and its active version; null otherwise. It is a preview: it holds no number. draft is always true here: a version number is assigned only when a publish succeeds, the next contiguous one at that moment, so a failed or abandoned build never skips one (studio-channel-contracts §4.2.3, version at publish). current_commands lists that active version's command names (shape-checked, at most 20; [] with no active version). holds_data says whether the pack holds an unexpired stored record; other users' user-scope records count only when the caller is an owner or admin and not an API key; a read that fails answers false. For a change mission pack_target names the target pack and its next version (studio-artifact-model).

Every plan read also carries base_changes: for a change mission, the base pack and version, whether the brief has its "Changes to existing commands and data" section (declared), the removals and renames in it that name something the base version has (changes, at most 20), and how many lines did not pass (unmatched, including passing lines after the 20th) with those lines as written (unchecked, at most 20), whether the section says - none (none_declared), and whether the change list is known (confirmed); null for a new mission (studio-artifact-model). scope_change is {"from", "to"} (each user or tenant) when the mission's Spec changes the base version's data scope, else null. When the base version's scope does not read and the Spec stores tenant, it is {"from": null, "to": "tenant"}. A plan with a scope change needs "acknowledge_scope_change": true (a JSON boolean) in the approve body, or approve refuses 422 scope_change_unacknowledged with error.code and details.reason = the code (studio-artifact-model).

{
  "base_changes": {
    "base": {"name": "@acme/customer-follow-up-reminders", "version": "0.3.0"},
    "declared": true,
    "none_declared": false,
    "confirmed": true,
    "changes": [
      {"kind": "argument", "action": "rename", "scope": "add-reminder",
       "name": "customer", "to": "customer_name"}
    ],
    "unmatched": 0,
    "unchecked": [],
    "scope_change": null
  }
}
{
  "pack_target": {
    "name": "@acme/customer-follow-up-reminders",
    "version": "0.2.0",
    "draft": true,
    "existing": true,
    "current_version": "0.1.0",
    "current_commands": ["complete-reminder", "list-reminders"],
    "holds_data": true
  }
}
{
  "requested_changes": ["Store results per user.", "Also email the team."],
  "declined": [
    { "request": "Store results per user", "reason": "spec",
      "spec_change": "Results are kept for each person separately." }
  ]
}

POST /plans/{plan_id}/revise-spec {"guidance": "..."} (at most 8192 characters as sent; blank after trimming is a 422 validation error) enqueues a revision of the plan's approved Spec and answers 202 with the same spec-job body as POST /specs/{spec_id}/revise. The plan row is not changed (studio-artifact-model §10.1). Refusals, in order: 404 plan_not_found; 409 plan_not_reviewable (the plan is not proposed/changes_requested); 422 no_linked_spec; 409 spec_not_latest; 409 replan_in_progress (a plan job is still running for the Spec); 409 already_drafting (a spec job is already active for the intent; details.spec_job_id names it); 503 the job could not be queued (the job is marked failed).

While a revision is running, or once a newer Spec version exists, the plan is not actionable: approve, execute, request-changes and POST /plans answer 409 spec_revision_in_progress or 409 spec_not_latest. reject is not gated. Every refusal named in this section has one shape:

{
  "success": false,
  "error": {
    "message": "A newer version of the spec exists",
    "code": "spec_not_latest",
    "details": { "reason": "spec_not_latest" }
  }
}

When a plan's linked Spec has a stored policy that cannot be read, approve, execute and request-changes answer 409 ("The Spec this plan was made from cannot be read") and dispatch nothing.

{
  "policy_check": {
    "result": "policy_mismatch",
    "spec": { "autonomy": "suggest", "data_scope": "tenant" },
    "plan": { "autonomy": "autonomous", "data_scope": "user" }
  }
}

POST /plans/{plan_id}/execute re-dispatches an approved plan as a fresh build with no second human review, guarded by a compare-and-set (execute_attempts) and a deterministic idempotency key, so two concurrent calls dispatch exactly one build. Body:

{ "mode": "build" }

mode is "build" (default — a fresh workspace, re-derived scope) or "fix" (T24 — re-enters the failed prior build's own workspace at REPAIR, on the runner that still holds it). Response:

{
  "data": {
    "build_job_id": "b1c2...",
    "attempt_no": 2,
    "retry_of_id": "a0b1...",
    "idempotent": false,
    "resume_stage": null
  }
}

Error responses (execute): 404 plan not found; 409 plan not approved (not_approved), the recorded build already succeeded (build_succeeded; except, for mode: "build", a done build that made no dashboard its plan grants, which is built again in full and counts against the attempt cap, runner-channel) or is still running (build_in_flight), on that same done-build path the resolved runner cannot run the dashboard step (dashboard_unavailable; no attempt is spent), the compare- and-set lost the race (execute_raced), the plan's recorded build can't be read (prior_build_unreadable), or — mode: "fix" only — the prior build isn't a fix candidate (fix_no_prior_build, workspace_not_resumable, fix_not_applicable, runner_unavailable, runner_outdated); 422 mode outside {"build", "fix"} (mode_unsupported), or the plan/scope manifest is invalid; 429 the plan has used all of its execution attempts (attempt_cap). approve shares the same refusal classes via the same shared execution path: scope_invalid (422/403) and session_archived (409). A change mission's build adds four, each with error.code and error.details.reason = the class (studio-artifact-model): change_target_refused (404; the target no longer passes its re-check), change_target_moved (409; the target is not in the tenant's publish namespace), base_source_missing (409; Huitzo keeps no source for the base version) and base_source_unsupported (409; the resolved runner's CLI or SDK is older than the change build needs, or the deployment serves no snapshot downloads; the runner gate). A scope_invalid refusal on either route keeps the message "Plan scope manifest is invalid" and carries error.code: "scope_invalid" and error.details.reason: "scope_invalid"; details also carries what scope_check reports: the class, plus missing | stray for the dashboard pairing rule or rule for any other:

{
  "success": false,
  "error": {
    "message": "Plan scope manifest is invalid",
    "code": "scope_invalid",
    "details": {
      "reason": "scope_invalid",
      "class": "dashboard_scope_incoherent",
      "missing": ["node"]
    }
  }
}

Here details.class is the scope vocabulary (dashboard_scope_incoherent or scope_invalid), disjoint from the runner-resolution classes below; a client discriminates on error.code first.

See Plan-scoped re-execution (T17) and Guided fix re-execution (T24).

Choosing a runner. POST /plans, POST /plans/{plan_id}/approve, POST /plans/{plan_id}/execute, POST /plans/{plan_id}/request-changes and POST /builds accept an optional "runner_id" in the body. Omitted, the Hub resolves the caller's one online runner (control-plane §3.6). When no runner can be used, every one of these routes refuses with error.details.class:

Status class Meaning
409 none_registered The caller has no enabled runner.
409 none_online The caller has runners, but none is online.
409 runner_ambiguous More than one runner is online at the winning tier; error.details.candidates lists {id, name}. Retry with runner_id.
404 runner_not_found runner_id is not a runner this caller may use (another tenant's, a teammate's personal one, disabled, or deleted).
409 runner_offline runner_id names a usable runner that is not online.
409 runner_pinned execute with mode: "fix" and a runner_id other than the runner holding the workspace, or with hosting when the workspace is on the caller's own runner.

Choosing a Huitzo runner. The same five routes accept an optional "hosting": "huitzo_managed": this job runs on a Huitzo-managed runner even when the caller has a runner online (managed-runners.md, Explicit choice). Omitted, the rule above applies. The Hub keeps no per-mission choice: send the field on every dispatch of the mission. A Fix (execute with mode: "fix") needs no field: it runs where the build it fixes ran. The refusals are a closed set, carry error.code equal to error.details.class and a closed error.details.reason, and record nothing:

Status code details.reason Meaning
400 hosting_conflict runner_named hosting together with runner_id or runner_name.
400 hosting_conflict key_not_managed A replay: the idempotency key (or, on execute, this attempt) already started a job that is not on a Huitzo runner. Without hosting the same replay returns that job.
409 managed_runners_unavailable disabled, runner_channel_disabled, no_pool, no_image, kill_switch This deployment does not offer Huitzo runners now, or the global runner kill switch is engaged.
409 managed_not_opted_in not_opted_in The workspace has not turned Huitzo runners on (POST /api/v1/studio/runners/managed, owner or admin).
402 managed_not_eligible no_credits, billing_unavailable The workspace may not spend.
{
  "success": false,
  "error": {
    "message": "More than one of your runners is online; choose one",
    "details": {
      "class": "runner_ambiguous",
      "candidates": [{"id": "r_1...", "name": "laptop"}, {"id": "r_2...", "name": "desktop"}]
    }
  }
}

decide and decompose are always 200/201 respectively — the not-fired case is a normal response ({"decision": null, "capability_diff": []} / {"tasks": [], "fired": false}), never a different status code. Both refuse 409 against a rejected/superseded plan (nothing worth spending an LLM call on); decide additionally refuses 422 when the plan has no linked (or no approved) Spec.


Builds — Control, Approvals, Events

Method Path Description
POST /api/v1/studio/builds Create + (if a runner resolves) enqueue a build.
GET /api/v1/studio/builds List the caller's own builds (keyset-paginated).
GET /api/v1/studio/builds/{id} Inspect one build (metadata only).
GET /api/v1/studio/builds/{id}/events SSE: bounded replay of persisted events, then a live tail.
GET /api/v1/studio/builds/{id}/approvals List PENDING approve-each-write checkpoints for the build.
POST /api/v1/studio/builds/approvals/{approval_id}/approve Grant a pending checkpoint — resumes the build.
POST /api/v1/studio/builds/approvals/{approval_id}/reject Deny a pending checkpoint — stops the build (killed).
POST /api/v1/studio/builds/{id}/interrupt Soft, resumable pause of an in-flight build.
POST /api/v1/studio/builds/{id}/abort Hard-stop the build (→ killed); the user's kill switch.

POST /builds accepts either an intent-only body ({"prompt": "..."}, the dashboard's create-from-intent surface — the endpoint fills repo_url / idempotency_key / command_allowlist from deployment defaults) or an explicit body naming least-privilege grants directly; every omitted scope list defaults to deny, and an explicit empty command_allowlist: [] is honored verbatim, never widened. An idempotency_key starting with auto-fix: is reserved for the Hub's automatic Fix and is refused with 422 (runner-channel §7.10.2). The body takes no permission mode: every Studio build is stored with approve_each_write (an old client that still sends permission_mode has it ignored), and the build summary reports the stored value. The summary's hosting is "huitzo_managed" when the job runs on a Huitzo-managed runner and "self_hosted" otherwise (Managed runners). GET /builds/{id}/events is a metadata- only SSE stream — only events the Hub's PrivacyIngestGuard already admitted cross the wire, never raw code/secret bytes:

GET /api/v1/studio/builds/b1c2.../events?after_seq=-1
Authorization: Bearer {token}
Accept: text/event-stream
event: agent
data: {"seq":1,"event_kind":"tool_use","ts":"2026-09-10T10:10:00Z","payload":{"...":"..."}}

event: agent
data: {"seq":2,"event_kind":"gate_result","ts":"2026-09-10T10:12:00Z","payload":{"...":"..."}}

event: end
data: {"status":"done"}

Error responses: 404 build/approval not found; 403 approval resolution denied (missing/already-resolved/cross-tenant — indistinguishable by design); 409 approval_expired (the approval window closed), or the build is terminal/raced for abort/interrupt; 503 DB error.


Builds — Publish

Method Path Description
POST /api/v1/studio/builds/{id}/publish Ask for a finished build to be published privately. 202 with the publish request.
DELETE /api/v1/studio/builds/{id}/publish Cancel the request while the runner has not received it.
GET /api/v1/studio/builds/{id}/publish The publish state: gates, runner availability, the latest request, the publications.

The caller must be the build's owner or a tenant admin or owner. Anyone else gets 404, on all three routes. A change build (its Spec's mission has a change_target) has no build-owner path: a caller who is not an admin or owner gets 403 not_owner_or_admin on POST and DELETE (who may act).

Publishing is limited per tenant and per user (publish limits): past either budget the answer is 429 with code: publish_rate_limited and Retry-After; while Redis is down it is 503 with code: rate_limiter_unavailable.

POST takes an optional body {"confirm_unverified": false, "confirm_stored_fields": false}; each value must be a JSON boolean. The Hub records a request; the build's own runner then uploads the artifacts the build already produced and the Hub publishes them as the caller, under the build's publish_namespace, with private visibility. The request waits up to 2 hours for the runner and has 15 minutes to finish once the runner receives it. While a request is active, a second POST returns the same request with 202, and does so before the publish gates are checked: the 403 and 409 refusals below apply only when a new request would be created.

If the workspace or the wheel changed after the build finished, nothing is uploaded and the request stops at needs_confirmation. Sending the POST again with "confirm_unverified": true publishes it, marked as unverified.

If the stored-data check answers a stored_fields_unread notice with stops: true (a stored field the new version erases, or hides while the active version reads it), nothing is published and the request stops at needs_confirmation with error_class stored_fields_unread; the request's stored_fields carries the finding (the first 20 collections, the same bodies as the 422 stored_fields_unread refusal's details.unread). A new POST with "confirm_stored_fields": true (and confirm_unverified again when the stopped request had it) publishes it. The two confirmations are independent and stack (Unread stored fields).

{
  "data": {
    "gates": {"quality": "passed", "security": "not_available", "can_publish": false, "blockers": ["already_published"]},
    "runner": {"state": "online", "last_heartbeat_at": "2026-10-09T15:04:05Z", "busy": false},
    "request": {"id": "…", "status": "succeeded", "legs": ["pack", "dashboard"], "unverified_confirmed": false, "error_class": null},
    "dashboard_owed": false,
    "will_publish": null,
    "policy": {"autonomy": "autonomous", "data_scope": "tenant"},
    "publications": [
      {"kind": "pack", "scope": "@acme", "name": "claims", "version": "1.2.0", "tree_match": true, "artifact_match": true, "security_verdict": "not_available", "attached_to_existing": false, "removed": false}
    ]
  }
}

The example is abridged. Request statuses: requested, delivered, publishing, needs_confirmation, succeeded, partial, failed, expired, cancelled.

In the GET, gates.blockers lists every POST refusal code that would apply to a new request, in gate order, whether or not a request is already active. runner is null when the build has no assigned runner (runner_unassigned is a blocker) or the runner has no registry row (runner_too_old is). runner.busy is true while the runner holds any job, a build or a plan. dashboard_owed is true when the pack is published and a dashboard the build declared is not, whatever the latest request's status; a new POST then publishes the dashboard only. will_publish is what a new POST would publish now: ["pack", "dashboard"] when the build built a dashboard, ["pack"] when it did not, ["dashboard"] for the owed dashboard alone, or null when nothing is left; a request's legs uses the same three lists (Legs). A publication's attached_to_existing is true when the pack or dashboard already existed before this publish, and false only when this publish created it. policy is the policy of the Spec the build was made from (null when there is none, or it cannot be read); the publish screen shows it read-only. A pack leg whose built manifest's autonomy or data scope differs from it ends the request with error_class policy_mismatch; a pack whose Spec says read_only and whose manifest declares a write ends it with read_only_pack_writes (the publish check). A build with a stored pack_identity whose built pack name or version differs from it ends the request with error_class build_identity_mismatch, and nothing is published (studio-channel-contracts §4.2.3). A build whose built pack name is another app's pack ends it with error_class pack_name_taken, and nothing is published (gate 10). A publication's active says whether that version is the target's active version now (null once removed); a pack publication's newer_than_active says whether its version was created after the pack's active version, which only going back can leave behind, and its checkable whether that version stored the collections it declares, so going back to it runs a stored-data check. policy_conflict is the read-time re-check of the build's live pack version against policy: null, or {"code", "details": {"reason", "writes"?}} with code published_pack_can_write, published_policy_differs or published_policy_unknown; it never changes gates. pack_identity is the pack this build publishes into, with the pack's active version and that version's current_commands, or null. draft is true until this build has a live pack publication of a request that ended; version is then the number it was published at. While this build's own publish is in flight, draft stays true and version is the number that publish was assigned; otherwise a draft's version is the number a publish would assign now (computed on each read, never stored as the build's version). Two builds published one after the other get the next two numbers, whatever they were built with (version at publish); the full field tables are in studio-channel-contracts §4.6.3.

{
  "pack_identity": {
    "name": "@acme/customer-follow-up-reminders",
    "version": "0.2.0",
    "draft": true,
    "existing": true,
    "current_version": "0.1.0",
    "current_commands": ["complete-reminder", "list-reminders"]
  },
  "policy_conflict": {
    "code": "published_pack_can_write",
    "details": { "reason": "published_pack_can_write", "writes": ["storage:write"] }
  }
}

Error responses (error.code in parentheses): 403 (session_required on a POST made with an API key, developer_mode_required, publisher_terms_required); 404 build not found or not the caller's to publish; 409 on POST (build_not_done, publish_namespace_missing, runner_unassigned, quality_not_passed, runner_too_old, already_published, pack_name_taken: the build's pack is another app's, see gate 10); 409 on DELETE (publish_not_cancellable); 422 {id} is not a UUID or the body is not valid (the framework's {"detail": [...]} body); 500 database error. The 404 carries no error.code.

A build that ran on a Huitzo runner is published by the Hub inside the POST (managed-runners.md, Publish), and that publish is bounded. 409 (publish_in_progress): another publish holds the build's stored snapshot; the request keeps waiting and the next POST takes it. 503 (publish_timed_out): the publish passed its 10 minute limit before the pack was published and was stopped; the request is ended and nothing of the unfinished step is kept. When the limit passes after the pack was published, the answer is 202 with the request in status partial: the pack version stands and the dashboard was not published. When the Hub cannot tell which of the two happened, it answers 202 with the request as it stands; read the publish state until the request ends.

The full contract, with every field, status and code, is Publish from Mission Control. The security verdict is recorded as not_available on every publication; sharing, grants and Marketplace listing are not reachable from these routes.


Sessions — Journey Rollup

Method Path Description
GET /api/v1/studio/sessions List the caller's sessions, newest-derived-activity first.
GET /api/v1/studio/sessions/{intent_id} One session's full rollup + ordered artifact timeline.
DELETE /api/v1/studio/sessions/{intent_id} Archive a session (delete-as-archive; never a purge/cascade).

A session is a derived read-model over the Intent/Spec/BuildJob/ BuildPlan/ApprovalRecord lineage — one row per pack-creation journey, with no new tables and no writes on the GET paths. include_archived=true re-includes archived sessions in the list. DELETE is an atomic conditional archive: 409 when the session has a non-terminal build in flight, or is already archived; 404 missing/cross-tenant. See Studio Sessions for the full latest.* rollup field reference (spec/plan/build sub-status, publish_namespace, the failure block, the T25b resume provenance fields, and context_file_count) rather than duplicating it here. A row whose current plan or build job is leased and working also carries a top-level liveness object (progress_at, stale), omitted otherwise; see Session liveness.


Runners

Method Path Description
GET /api/v1/studio/runners List the caller tenant's registered runners + last-known liveness.
POST /api/v1/studio/runners Mint a runner integration row + its one-time pairing secret.

GET /studio/runners deliberately returns the bare {"runners": [...]} shape (a purpose-specific runner-surface contract), not the generic {data} envelope POST uses. POST mints the pairing secret the CLI's huitzo runner up consumes right after huitzo login — the tenant is always the caller's session tenant (never body-supplied), bounded by a per-tenant quota (default 25), and the plaintext registration_secret is returned exactly once and never re-readable. The deployment licence max_runners ceiling is checked first, under the license:max_runners advisory lock (409 license_limit_exceeded, details.scope = "deployment"; 503 license_count_unavailable when the count fails; Core editions). Disabled runners are not counted.

POST accepts an optional scope: "personal" (the default, dispatchable only by the minting member) or "tenant" (dispatchable by every member of the tenant; owner/admin only; it stays usable only while the minting admin keeps an owner/admin role). Each GET entry carries scope, owned_by_caller, dispatchable (the caller can dispatch builds to it), default_target (an unnamed build from the caller lands on it now) and name (hidden from members for a teammate's personal runner) alongside the liveness fields (state, last_heartbeat_at, and stale: true when the last heartbeat is older than the 120 s dispatch window, runner-channel §5.3). A runner that died holding a lease can still read state: "online" with stale: true until the reaper reaps that lease; no dispatch resolves to a stale runner (control-plane §3.6). Only runners whose integration still exists are listed: a deleted runner disappears at once.

The top-level resolution object is computed by the same function every dispatch uses, so it says what an unnamed build from the caller would do right now: runner_id is the runner it would use (or null), reason is null or one of none_registered / none_online / runner_ambiguous, and candidates lists {id, name} when the caller must choose.

{
  "runners": [{"id": "r_1...", "state": "online", "default_target": false, "...": "..."}],
  "resolution": {
    "runner_id": null,
    "reason": "runner_ambiguous",
    "candidates": [{"id": "r_1...", "name": "laptop"}, {"id": "r_2...", "name": "desktop"}]
  }
}
{
  "data": {
    "runner_id": "r_abc123",
    "tenant_id": "t_def456",
    "registration_secret": "AbCdEf...one-time-only",
    "api_url": "https://huitzo.ai",
    "scope": "personal"
  }
}

Error responses: 400 invalid runner config; 403 scope="tenant" requested by a non-owner/admin; 409 tenant_quota_exceeded, or a runner name collision within the same scope; 503 integrations encryption is not configured.

For the runner-side pairing/announce/pull protocol these routes feed, see Pairing mint (Track A) and Resume claims.

A runner's secret is set only by this mint. The generic integration routes never take one for a runner row, whoever calls them (a tenant admin included):

Route On a runner row
POST /api/v1/integrations with type=runner 409 (mint through POST /api/v1/studio/runners)
PATCH /api/v1/integrations/{id} with secrets (including {}) 409 once the caller passes the usual visibility and ownership checks (404 / 403 come first); nothing on the row changes, including a name in the same body
PATCH /api/v1/integrations/{id}/secrets with any set or remove 409 once the caller passes the usual visibility and ownership checks (404 / 403 come first), before the optimistic-concurrency check
PATCH /api/v1/integrations/{id} with only name / config unchanged (200 under the usual ownership rules)
DELETE /api/v1/integrations/{id} unchanged (204 under the usual ownership rules)

The 409 body is the standard error envelope; its message names the re-mint path. To rotate a runner's secret, delete the runner and mint a new one. See A runner's secret is Hub-generated only.


Evaluations — GateReports & ReviewFindings

Method Path Description
POST /api/v1/studio/evaluations/fold Idempotent Tier-1 deterministic fold from a build run's own gate results.
POST /api/v1/studio/evaluations CLI-submit self-attestation — write a reviewer or deterministic GateReport directly.
GET /api/v1/studio/evaluations/{report_id} Inspect one of the caller's own GateReports, with its ReviewFindings.
GET /api/v1/studio/evaluations?build_run_id=&spec_id=&limit= List the caller's own GateReports, newest first.
POST /api/v1/studio/evaluations/{report_id}/findings/{finding_id}/disposition Record a human open -> fixed\|waived disposition on a ReviewFinding.

All five routes are session-authenticated and RLS-scoped like every other Studio route on this page; a missing/cross-tenant build_run_id / GateReport / ReviewFinding is a 404 (RLS makes "missing" and "someone else's tenant" indistinguishable by construction).

POST /evaluations/fold takes only {"build_run_id"} — there is no free-form verdict input on this endpoint by design. It is terminal-immutable: re-folding an already-folded build run no-ops and returns the existing report.

A report anchored on a build run carries the Spec that build was made from in spec_id, resolved by the Hub from the build itself (null for a build with no Spec). See studio-evaluation.md §7.

POST /api/v1/studio/evaluations/fold
Authorization: Bearer {token}
Content-Type: application/json

{ "build_run_id": "8f2b...build" }
{
  "data": {
    "id": "8f2b...report",
    "build_run_id": "8f2b...build",
    "spec_id": "8f2b...spec",
    "gate_kind": "deterministic",
    "verdicts": { "manifest": true, "traceability": true, "pytest": true, "ruff": true, "mypy": true },
    "intent_acceptance": "unknown",
    "intent_acceptance_rationale": null,
    "findings": [],
    "created_at": "2026-09-10T10:20:00Z",
    "updated_at": "2026-09-10T10:20:00Z"
  }
}

On a change mission, POST /evaluations, POST /evaluations/fold and the finding disposition need an owner or admin signed in as a person: 403 not_owner_or_admin, checked on each anchor the body names (who may act).

POST /evaluations is the CLI-submit self-attestation path. verdicts keys are the closed five-gate vocabulary (manifest, traceability, pytest, ruff, mypy) with strict boolean values (no truthy 1/0/"true" coercion); gate_kind is "reviewer" or "deterministic". Either build_run_id or spec_id is required (never neither). Four cross-field rules are enforced by request validation (a 422 before the handler runs, never a silent drop):

  • a gate_kind="reviewer" submission must carry verdicts: {} (reviewer rows never carry the deterministic vocabulary);
  • a gate_kind="deterministic" submission may never carry a build_run_id — a build-run-anchored deterministic GateReport is written exclusively by POST /evaluations/fold;
  • a gate_kind="deterministic" submission must carry intent_acceptance="unknown" and no rationale — Tier-3's verdict lives on a gate_kind="reviewer" row only;
  • at least one anchor (build_run_id or spec_id) is required.

On a submission anchored on a build run, the Hub sets spec_id to that build's own Spec. A body may leave spec_id out; one that names a different Spec is refused with 409 and nothing is written.

POST /api/v1/studio/evaluations
Authorization: Bearer {token}
Content-Type: application/json

{
  "spec_id": "8f2b...spec",
  "gate_kind": "reviewer",
  "verdicts": {},
  "intent_acceptance": "accepted",
  "intent_acceptance_rationale": "Matches the approved spec's scope."
}

Error responses: 404 build run not found (fold), or GateReport/ ReviewFinding/build_run_id+spec_id not found (submit, get, disposition); 422 anchorless submission, fold-exclusivity violation, or deterministic-intent-acceptance violation (submit, request-validation-level where possible); 409 a build-anchored submission whose spec_id is not that build's Spec (submit).


Decisions — Inspect & Accept

Method Path Description
GET /api/v1/studio/decisions/{decision_id} Inspect one of the caller's own Decisions.
POST /api/v1/studio/decisions/{decision_id}/accept The atomic conditional proposed -> accepted human review gate.

Decision creation is a separate surface (POST /plans/{plan_id}/decide and GET /plans/{plan_id}/decisions, above) — this router owns review/accept only, the same two-router split specs/intents already establish.

accept takes an optional reviewer note (becomes the accepted ruling verbatim; empty defaults ruling to the drafted choice, never left NULL). It is an atomic conditional UPDATE ... WHERE status='proposed' RETURNING — a raced or already-accepted Decision is 409, never a read-then-write. A founder_gate=true Decision requires the caller to hold the owner/admin role.

POST /api/v1/studio/decisions/8f2b.../accept
Authorization: Bearer {token}
Content-Type: application/json

{ "note": "Approved — matches the capability diff." }
{
  "data": {
    "id": "8f2b...decision",
    "plan_id": "8f2b...plan",
    "status": "accepted",
    "choice": "extend_capability_x",
    "ruling": "Approved — matches the capability diff.",
    "founder_gate": false,
    "created_at": "2026-09-10T10:15:00Z",
    "updated_at": "2026-09-10T10:16:00Z"
  }
}

Error responses: 404 Decision not found; 403 a founder_gate Decision accepted by a caller who is not owner/admin; 409 the Decision is not proposed (already accepted/raced).


Runner Install Manifest

Method Path Description
GET /api/v1/studio/runner/install-manifest The Hub-signed, integrity-checked runner install manifest.

Public and unauthenticated — the consumer is the runner CLI / onboarding rail, a machine, before any login, so this route is in both auth.middleware.PUBLIC_PATHS and licensing.middleware.PUBLIC_PATHS (reachable pre-license), exactly like GET /capabilities. Studio renders runner install commands from this signed manifest only — never free text. The manifest is root-signed with the same deployment-root Ed25519 key the capability document and channel index use (one trust anchor); the runner CLI verifies it against its TOFU-pinned root before trusting any install command or the hub_cert_spki_sha256 pin set it carries. The service re-verifies its own signature before serving (verify-on-render); a self-check failure or malformed configured pin is a fail-closed 500, never a silent unsigned/free-text fallback.

{
  "schema": "huitzo-runner-install-manifest/1",
  "deployment": "huitzo.ai",
  "issued_at": "2026-09-10T00:00:00Z",
  "public_key": "base64...",
  "feed_channel": "stable",
  "runner_component": "huitzo-cli",
  "min_secure_version": "1.4.0",
  "hub_cert_spki_sha256": ["sha256:...", "sha256:..."],
  "install": [
    { "os": "macos", "shell": "bash", "command": "curl -fsSL ... | bash", "supported": true },
    { "os": "linux", "shell": "bash", "command": "curl -fsSL ... | bash", "supported": true },
    { "os": "windows", "shell": "powershell", "command": "iwr ... | iex", "supported": false }
  ]
}

This response is a bare signed document, not the {"data": ...} envelope — the runner CLI verifies manifest_sig against the raw wire shape, the same convention GET /capabilities and the channel feed use.

Error responses: 500 INSTALL_MANIFEST_UNAVAILABLE — the signed manifest could not be produced (a signing/config defect); the route refuses to serve an unverifiable manifest rather than fall back to unsigned free text.


Pipelines

Pipeline endpoints expose the inline-pipeline executor that lands in Phase E.1b (PR-59). See docs/architecture/piping-protocol.md for the full protocol contract and docs/architecture/piping-internals.md for executor internals.

Execute Pipeline

Execute a pipeline declared in a pack's manifest. Fast-queue pipelines run inline and return the full PipelineResult envelope; medium/long pipelines dispatch to Celery and return a task_id for polling via GET /api/v1/tasks/{task_id}.

POST /api/v1/pipelines/{pack_scope}/{pack_name}/{pipeline_name}/execute
Authorization: Bearer {token_or_api_key}
Content-Type: application/json

Request:

# pseudocode — illustrative shape, not copy-paste
{
  "initial_args": { "...first-stage input dict..." },
  "override_config": {
    "stage-name": { "...per-stage config overlay..." }
  }
}

Response (inline, 200):

# pseudocode
{
  "data": {
    "pipeline_run": {
      "id": "uuid",
      "correlation_id": "uuid",
      "status": "SUCCESS",
      "stage_results": [ { "stage_index": 0, "status": "success", "...": "..." } ],
      "final_output": [ { "data": { "...": "..." }, "index": 0, "is_last": true } ],
      "started_at": "ISO8601",
      "ended_at": "ISO8601"
    },
    "correlation_id": "uuid"
  }
}

Response (async dispatch, 202):

# pseudocode
{
  "data": {
    "task_id": "uuid",
    "queue": "medium",
    "status": "queued",
    "correlation_id": "uuid"
  }
}

Streaming (SSE): with "stream_response": true in the request body and a streaming-capable pipeline, the response is text/event-stream instead of one of the JSON envelopes above: one event: chunk per PipeChunk the pipeline emits, followed by a terminal event: result carrying the full PipelineResult. There is no HTTP status line to carry an error code mid-stream, so any failure (including a 402 preflight refusal) instead closes the stream with event: error whose data is the same JSON an equivalent non-streaming failure would put in error.details — flattened to the top level rather than nested (see §Insufficient Credits Error for the INSUFFICIENT_CREDITS shape). SSE-served runs are not persisted to pipeline_runs; clients that need the run queryable via GET /api/v1/pipelines/runs/{id} should omit stream_response (default false).

Error responses:

Code Condition
401 Missing or invalid auth
402 ADR-035 preflight reservation refused — INSUFFICIENT_CREDITS (see §Insufficient Credits Error); an SSE-streamed run instead closes with event: error carrying the same fields flattened
404 Pack not visible to caller, or pipeline not declared in manifest
409 license_limit_exceeded (the deployment licence monthly_executions limit) or tenant_quota_exceeded (the tenant monthly_command_cap), checked before the run starts, so no pipeline_runs row is written. Same body as Execute Command's 409
422 Stage failed (PipelineError) — body carries failed_stage_index, failed_stage_name, scrubbed partial_results
500 Database error
503 license_count_unavailable: a licence monthly_executions limit applies and its usage count could not be read; nothing ran

Get Pipeline Run

Fetch a persisted pipeline run by id. RLS scopes reads to the caller's tenant; foreign rows surface as 404 (not 403) so the API does not leak cross-tenant existence. In Phase E.1b only inline (fast-queue) runs are persisted to pipeline_runs; worker-side persistence for async runs lands with the streaming executor in PR-61.

GET /api/v1/pipelines/runs/{pipeline_run_id}
Authorization: Bearer {token_or_api_key}

Response (200):

# pseudocode
{
  "data": {
    "id": "uuid",
    "correlation_id": "uuid",
    "pack": "@scope/pack",
    "pipeline_name": "string",
    "status": "SUCCESS",
    "stage_results": [ "..." ],
    "final_output": [ "..." ],
    "error": null,
    "started_at": "ISO8601",
    "ended_at": "ISO8601"
  }
}

Error responses:

Code Condition
401 Missing or invalid auth
404 Run not found, not visible under RLS, or async-dispatched (not yet persisted in E.1b)
500 Database error

Packs

Every pack entry below shares one command shape: commands[] carries name, summary and description for each command of the pack's active version, with the same meaning as in List Commands (both strings, never null). A pack with no active version has version: null, commands: [] and listing: null.

Create Pack

Create an empty pack the caller's tenant owns; publish builds to it with Upload Pack Version. Requires developer mode and the current developer terms (T-051).

Publishing is limited per tenant and per user (publish limits): past either budget the answer is 429 with code: publish_rate_limited and Retry-After; while Redis is down it is 503 with code: rate_limiter_unavailable.

POST /api/v1/packs
Authorization: Bearer {token}
Content-Type: application/json

Request:

Field Type Description
scope string Without @. 2–39 chars, lowercase letter first, then lowercase letters, digits, hyphens. Must be the caller's tenant slug or an organization the caller belongs to. huitzo is publishable only by the first-party tenant; the reserved scopes (system, admin, api, …) are refused for every tenant (ADR 025)
name string Same slug rule, 2–39 chars, no reserved prefix
visibility string private (default), organization, unlisted or public
{ "scope": "acme", "name": "finance", "visibility": "private" }

Response (201):

{
  "data": {
    "id": "5f0c2d7e-8b41-4a9c-b3e6-1d2f7a9c4e10",
    "scope": "acme",
    "name": "finance",
    "visibility": "private"
  }
}

Error Responses:

Status Condition
403 Developer mode required, developer terms not accepted, a reserved scope (or huitzo from a non-first-party tenant), or scope not owned by the caller
403 publish_public_required: a public, unlisted or organization visibility on a deployment whose licence lacks publish_public (Core editions)
403 The pack name is not on the licence's licensed_packs allowlist
409 A pack with this scope and name already exists, or the tenant is at its max_packs quota (tenant_quota_exceeded)
409 license_limit_exceeded: the deployment is at the licence max_packs ceiling (details.scope = "deployment")
422 Request body fails validation (slug rules, unknown visibility)
500 Database error
503 license_count_unavailable: a licence ceiling applies and the deployment pack count could not be read

List Installed Packs

Every pack visible to the caller — owned, public, or organization-visibility with a grant to the caller's tenant — newest first. unlisted packs are excluded; their owner still reaches them through Get Pack.

GET /api/v1/packs
Authorization: Bearer {token}

Response (200):

{
  "data": [
    {
      "id": "5f0c2d7e-8b41-4a9c-b3e6-1d2f7a9c4e10",
      "scope": "acme",
      "name": "finance",
      "visibility": "public",
      "namespace": "@acme/finance",
      "version": "2.0.0",
      "commands": [
        {
          "name": "analyze",
          "summary": "Analyze portfolio performance",
          "description": "Compute returns, volatility and drawdown for a symbol.\n\nPrices come from the configured market-data integration."
        }
      ],
      "listing": { "publisher": { "name": "Acme Inc." }, "...": "..." },
      "created_at": "2026-08-01T10:00:00+00:00"
    }
  ]
}

scope is returned without @; namespace is @scope/name, the prefix of every command namespace in the pack. listing is the active version's marketplace-listing snapshot (listing-snapshot-persistence), or null.

Error Responses:

Status Condition
500 Database error

Get Pack

One pack by id, under the same visibility as List Installed Packs plus the caller's own unlisted packs.

GET /api/v1/packs/{pack_id}
Authorization: Bearer {token}

Response (200): the List Installed Packs entry plus policy, the active version's Policy Card (ADR-005), or null when the stored manifest carries none.

{
  "data": {
    "id": "5f0c2d7e-8b41-4a9c-b3e6-1d2f7a9c4e10",
    "scope": "acme",
    "name": "finance",
    "visibility": "public",
    "namespace": "@acme/finance",
    "version": "2.0.0",
    "commands": [
      { "name": "analyze", "summary": "Analyze portfolio performance", "description": "..." }
    ],
    "policy": { "autonomy": "...", "audit": { "level": "..." }, "...": "..." },
    "listing": null,
    "created_at": "2026-08-01T10:00:00+00:00"
  }
}

Error Responses:

Status Condition
404 Pack not found or not visible to the caller
422 pack_id is not a UUID
500 Database error

Grant Pack Access

Grant another tenant access to an organization-visibility pack. Only an owner or admin of the owning tenant may grant. An API key always acts as member, so it cannot grant.

POST /api/v1/packs/{pack_id}/grant
Authorization: Bearer {token}
Content-Type: application/json

Request:

{ "grantee_tenant_id": "9d3e6b1a-2c4f-4e8d-a7b5-0f1c3e5a7d92" }

Response (201):

{
  "data": {
    "id": "c2a7e4f1-5b3d-4c9e-8a61-7f0d2b4e6a18",
    "pack_id": "5f0c2d7e-8b41-4a9c-b3e6-1d2f7a9c4e10",
    "grantee_tenant_id": "9d3e6b1a-2c4f-4e8d-a7b5-0f1c3e5a7d92"
  }
}

Error Responses:

Status Condition
400 The pack's visibility is not organization
403 Caller's tenant does not own the pack
403 Caller's role in the owning tenant is not owner or admin (an API key always counts as member)
404 Pack or grantee tenant not found
409 Access already granted to this tenant
422 pack_id or grantee_tenant_id is not a UUID
500 Database error

There is no revoke endpoint.


Pack Versions

Upload Pack Version

Publish a new version of a pack the caller's tenant owns: accepts a wheel file, installs it into a private per-version venv, extracts its commands, creates the PackVersion + Command rows, and only then points the pack's venv at the new build. Only the pack owner's developer-mode users may upload.

Publishing is limited per tenant and per user (publish limits): past either budget the answer is 429 with code: publish_rate_limited and Retry-After; while Redis is down it is 503 with code: rate_limiter_unavailable.

POST /api/v1/packs/{pack_id}/versions
Authorization: Bearer {token}
Content-Type: multipart/form-data

Request (multipart fields):

Field Type Description
wheel file The .whl build artifact (PEP 427 filename required)
version string The version being published. Must equal the wheel's dist-info Version byte for byte — see Artifact Integrity
manifest string (required) JSON-encoded huitzo.yaml manifest (schema v2). Its pack.version must equal version

Response (201):

{
  "data": {
    "version_id": "7c4a9e1b-3d2f-4a6b-8c1d-2e5f9a0b6c3d",
    "version": "1.2.0",
    "commands": [
      {
        "name": "analyze",
        "namespace": "@scope/pack/analyze",
        "timeout": 60,
        "queue": "fast",
        "schedule": null
      }
    ],
    "artifact": {
      "wheel_sha256": "3b1f…",
      "dist_name": "my-pack",
      "dist_version": "1.2.0"
    }
  }
}

A 201 means every huitzo.commands entry point in the wheel loaded as a command in the isolated extraction child and every command the manifest declares was extracted; the API process never imports the pack at publish. A partial wheel is refused with 400 command_contract_violation (see Command Runtime Contract), so data.commands holds one entry per command the manifest declares.

data.pricing_notices is present only when the manifest's pricing produced an informational code — PRICING_LEGACY_MAPPED (a legacy pack.pricing mapped to a declaration, with the before/after figures) or PRICING_LOW_PRICE_SHARE_NOTICE — as [{code, path, message}]. Neither fails the publish.

Execution pricing (400). listing.commercial.execution_pricing and the other pricing surfaces are validated before the schema-v2 parse (Execution-Pricing Schema → Diagnostics). A violation returns 400 with error.details.code set to the first diagnostic's PRICING_* code and error.details.diagnostics listing every violation as {code, path, message}. A server-owned or unknown key is named by path only; its value is never echoed. An accepted declaration is stored inert in the version's manifest and charges nothing.

data.degraded is present only when the version IS published but a post-commit step did not complete — promote_failed (the venv pointer still names the previous build; every runtime reader addresses the version the database gave it) or broker_notification_failed (no worker got the warm-up push; workers self-heal on their next registry miss).

data.stored_data reports the stored-data check as {outcome, cause, capped, collections, notices}. outcome is checked (every stored record of every declared collection validated), capped (the check stopped at its bound and every record it read validated) or not_checked (the manifest declares no state.collections). not_checked never means the data passed. notices lists what the pack holds that the new version does not list or does not read (stored_data_unlisted, stored_collections_dropped, stored_fields_unread and stored_fields_not_checked against the version being replaced; see Stored-data notices); a notice never refuses this publish, and a notice whose read fails (the count, or the version being replaced) is omitted. Only Studio's own publish leg may stop on stored_fields_unread, as a needs_confirmation answer (Unread stored fields).

commands[].schedule is null unless the manifest declares one for that command (see Scheduled Commands in the pack manifest reference) — echoed exactly as stored, not merely as declared.

Licence schedule ceiling (409). Manifest crons count toward the deployment licence max_schedules claim while the pack is enabled. A publish that adds crons (the new version's scheduled commands minus the active version's) past the ceiling is refused whole with 409 license_limit_exceeded (details.key = "max_schedules", details.attempted_delta the net increase); nothing is published. A count failure is 503 license_count_unavailable (Core editions).

Artifact Integrity

The Hub opens the uploaded wheel server-side before anything is written to disk. The declared version is not a label the publisher attaches to an opaque blob: it becomes PackVersion.version and Command.version, which is the identity a worker compares against the build it actually imported. The upload is refused unless all four spellings agree:

  1. the wheel filename's {name}-{version} fields (PEP 427),
  2. the wheel's single *.dist-info/METADATA Name and Version,
  3. the multipart version field,
  4. manifest.pack.version.

Names are compared after PEP 503 canonicalization (my_pack ≡ my-pack), and the dist-info Name must also canonicalize to the Pack.name the row carries. Versions are compared as exact strings. This is deliberately stricter than the runtime rule: the worker-side guard uses backend.packs.installer.same_release (PEP 440 equality, falling back to exact string), so 1.0 and 1.0.0 are the same release at execution time — but publish refuses to record two spellings of one release, because one canonical spelling at the source beats normalizing in every consumer. A v1.2.3 or 1.0.0-beta1 declaration is therefore rejected against a wheel whose dist-info says 1.2.3 / 1.0.0b1; the error names both spellings and, when the two are the same release, says which one to declare in huitzo.yaml.

The wheel container is bounded before it is parsed. The Hub reads the End-of-Central-Directory record (including the Zip64 record) from the tail of the upload and refuses with 400 wheel_unreadable when the archive declares more than 10,000 entries or a zip directory larger than 2 MiB, without reading the directory (the Zip64 locator is read from the real file offset, so a maximum-length archive comment cannot hide it); it then enforces the real parsed entry count against the same 10,000 cap, not only the count the publisher declares, and refuses a wheel whose members declare more than 512 MiB uncompressed in total. A truncated archive with no EOCD record is the same 400. Member names are never echoed in these errors.

The sha256 of the uploaded bytes is recorded with the row. pack_versions.manifest carries a reserved, Hub-written key that no manifest may supply:

"artifact": {
  "wheel_sha256": "3b1f…",
  "wheel_filename": "my_pack-1.2.0-py3-none-any.whl",
  "wheel_size": 20481,
  "dist_name": "my-pack",
  "dist_version": "1.2.0"
}

It is storage-only: GET /api/v1/packs/{id} and the catalog listing projection are allow-lists and never echo it. Forensics compares it against the kept wheel archive:

sha256sum "$HUITZO_PACKS_DIR/<pack_id>/<wheel_filename>"

Rows published before this check exists have no artifact key.

The dist-info/METADATA entry is read with a hard cap of 64 KiB uncompressed. The zip entry's declared size is checked first and the read is bounded as well, so a small, highly compressed entry cannot inflate in the API process. An entry past the cap is refused as 400 wheel_unreadable, before any ownership check. The Name and Version a wheel_filename_mismatch message echoes are clipped to 200 characters.

Publish Atomicity

A (pack_id, version) row exists iff the wheel whose dist-info Version equals that version string is installed at versions/<version>/venv (docs/architecture/resource-lifecycle.md#pack-venv-layout-and-promotion). The install never targets the build that is live, and the pointer only moves after the database has accepted the row:

# pseudocode — apps/backend/src/backend/api/v1/packs.py::upload_version
inspect the wheel (zip + dist-info) and compare all four version spellings
    layout: plain member names, no duplicate, no second distribution's metadata,
        no .pth, sitecustomize or byte-code, .data/ only purelib, platlib   # wheel_layout_refused
    every Requires-Dist parses and names no URL             # wheel_dependency_refused
validate the manifest: required, size, JSON, schema v2, listing security,
    manifest.pack.version == version, LLM capability floor
#   ^ everything above is pure: no session, no disk write, no install
open the session
    developer mode + publisher-terms gate
    SELECT ... FROM packs WHERE id = :id FOR UPDATE   # serializes this pack
    dist-info Name canonicalizes to Pack.name
    from dist-info/entry_points.txt, before anything is written or run:
        at least one huitzo.commands entry point
        every entry point name starts with "{scope}/{name}/"
    409 pre-check on (pack_id, version)
    write the wheel to the pack's archive directory
    with _install_lock:
        install_wheel(...)            -> .publish/<owner>.<pack>.<version>.installing-<uuid>/venv
            # first: publish + execution sandbox identities usable, else 503 publish_sandbox_unavailable
            # every step as the publish UID, binary-only, then copied to the service UID
        venv shows exactly the archive's dist-info + entry_points.txt   # read back, no import
        extract_commands_from_package(..., venv_dir=<staging>)  # isolated child; commands, failed (<= 50), failed_total
        at least one extracted command or failed entry point   # backstop
        every extracted namespace starts with "{scope}/{name}/"   # backstop
        one command_contract_violation response (<= 100 listed, details.total counts all):
            _check_entry_point_loads(...)            # every entry point loaded as a command
            _check_command_names(...)                # unique names, kebab-case command segment
            _check_command_contract(...)             # manifest mirrors the decorator
            _check_declared_commands_extracted(...)  # every declared command extracted
        stored-data check              # every declared collection, see Stored-Data Check
        licence max_schedules gate     # net cron increase, license:max_schedules lock
        _create_version_records(..., artifact=...) + flush   # the DB decides
        finalize_pack_version(...)    -> versions/<version>/venv
        commit                        # the row is durable from here on
    promote_pack_version(...)         # venv -> versions/<version>/venv
    # nothing of the pack is imported here; this replica registers the build
    # in the background, the others on their first call
    register_published_build(...)
    send_task("huitzo.reload_pack_commands", {tenant_id, pack_id, version})

Ordering facts this protocol depends on, in the order they matter:

  • Nothing runs before every static check has passed. The wheel's entry points are read from its dist-info/entry_points.txt as bytes, so an upload refused for its namespace, for a missing entry point or for any earlier reason is refused before the wheel is written, installed or imported. Install and extraction then follow the environment rule in Untrusted code at publish.

  • The flush is the arbiter, and it runs before the directory is published. The 409 pre-check is advisory — two replicas can both pass it — so the unique index on (pack_id, version) decides, and it decides before finalize_pack_version renames a directory into place. The loser never replaces a directory that is serving traffic.

  • The API process never imports the pack at publish. The command metadata comes only from the isolated extraction child, which runs as the publish UID. Once the commit lands, the publishing replica registers the build in the background; every other replica registers it on its first call through the inline miss path. Without a usable publish or execution sandbox identity the publish is refused with 503 publish_sandbox_unavailable before anything is installed.
  • The promote runs after the commit. A failure there is loud but not a correctness failure — every runtime reader addresses the version the database gave it — so the response is 201 with degraded: promote_failed rather than a rollback of a committed row. The opposite order would leave a committed row with no directory and no API to retract it.
  • The pure gates answer before authorization does. A structurally invalid upload is 400 even when the caller has not accepted the current developer terms, is not in developer mode, or does not own the pack: the wheel and the manifest are inspected before the session opens, so 403 and 404 are only reached by an upload that is already well formed. Nothing is disclosed by that ordering — the 400 describes only the bytes the caller sent.
  • Any failure before the commit publishes nothing. Rollback + discard the version directory + unlink the wheel, on every refusal and database error, and when the request is cancelled before the commit (a dropped connection, shutdown, an outer timeout): the cleanup is shielded from that cancellation, and a pip install still running in its thread is discarded the moment it ends. A cancellation that arrives while the commit is in flight waits for the commit's outcome first: files are removed only when the row did not become durable, never for a committed version.
  • The row lock serializes publishes of one pack, in-process and across replicas sharing a database. It is held across pip and across the loader's bounded drain wait, so PATCH /packs/{id}/listing and DELETE /packs/{id} on the same pack block behind an in-flight publish; other packs are unaffected. This transaction already spanned the install before the lock was added, so the idle-in-transaction exposure is pre-existing, not new.
  • The stored-data check runs before anything is flushed. It reads rows and runs the new build's models in a child, but writes nothing, so a refusal is undone like every other pre-commit refusal and the previous version stays active. It is not a snapshot: the active version keeps serving, and a record written between the check and the commit is not covered. Studio closes that window by checking the new active version again once after the publish (Check Stored Data).
Stored-Data Check

Every version of a pack reads the same stored data: storage is partitioned by the pack, not by the version. A publish therefore validates the records the publisher's tenant already holds against the new version's own record models before the version can become active.

  • What is read. For each state.collections entry of the uploaded manifest, the records under <key_prefix>/<one segment> in its declared scope, read on the Hub through the same storage client the runtime uses, in key order. Only the publisher's tenant is read; other tenants of a granted pack are not.
  • Whose user-scope records. They follow the publisher of the version being checked. On a publish that is the caller, and the decision is stored with the version (state.read_scope, stored manifest). On an installed version (Check Stored Data, Studio's automatic check after a publish) it is the version's recorded publisher (published_by_user_id), whoever asks, and every user's records are read only when the stored read_scope is every_user and that publisher is still an active owner or admin. When the publisher is an owner or admin of the tenant (on a publish: not through an API key, which acts as member), every user's records of the tenant: the users holding unexpired records are listed by one query filtered on tenant, pack and key prefix (row-level security is the second layer), at most 50 users, in user-id order. Any other publisher's version is checked against that publisher's own user-scope records only, and the collection is capped when other users hold records: the values are handed to code the publisher wrote, so a member's version must not reach another user's data. A version with no recorded publisher reads no user-scope records. Going back (Activate) is the exception: it reads every user's records whoever published the target (after the owner or admin confirms, when the target's publish scope was narrower), since the version then serves every user anyway (whose records the go-back check reads).
  • Where it is validated. In one isolation child spawned on the new build's staging venv with no RPC handlers, so the child can reach no storage, secrets or model: driver method validate_records (ADR-039). It imports each collection's model (module.path:Class), accepts it only when it is a pydantic model class whose module file lives in the build's own site-packages (a platform or standard-library class is model_not_loadable), and calls model_validate on each value. Stored values are never sent to a runner. The child shares the Hub's network namespace (the documented sandbox limitation), so a hostile model could send the values it is given elsewhere; that is why a member's version is checked against that member's own records only. At most two check children run at once per replica, and at most one per tenant; a check that finds its tenant already holding a slot, or waits 5 s for one, answers the retryable 503 stored_data_check_unavailable. A runner's publish leg gets that 503 back and retries once; a managed-runner publish from the project store (studio/publish_from_store.py) does not retry it, and its request waits out its window.
  • Bounds. 2,000 records and 6 MiB of encoded values per check, totalled across collections and users, at most 50 users per user-scope collection, and 8,000 listed keys (a prefix full of keys deeper than one segment ends the scan); 15 s for the child once it has answered the handshake, 5 s for the handshake. Over a bound (or when more than 50 users hold records) the records already read are validated and the outcome is capped.
  • What comes back. Per collection: name, total (records validated), failing, capped and rules, pydantic error-type names only, filtered through pydantic's own vocabulary (a pack's custom rule and any other exception a validator raises read as invalid). No value or record id is ever returned or logged. Top-level field names are returned only inside the stored_fields_unread notice, under the guards listed there, and never logged: the log line carries the number of unread fields only.
  • What the version does with each stored field (W8-1, W8-2). After every collection has been validated, the child probes the records that validated and are JSON objects, under one 2 s deadline shared by all collections and never past 12 s after the call began; the deadline is checked before every validation, so an overrun marks the collections not finished partial and never fails the check. The probe first collects donors: per top-level key, up to 8 distinct values from the validated records (compared by type and equality, so unhashable values count). Then, per record, it validates a fresh copy and takes the JSON dump (model_dump(mode="json"), what Collection.save writes) twice; a field whose two dumps differ is unstable and ignored in every comparison. A record whose dump raises or is not an object with string keys is skipped (still counted as probed). Each key is then one of:
  • Used: it is in the dump and not one of the model's extras, or it names a computed field. Never reported. The version's used keys, plus every key whose perturbation below changed the stable dump or raised in at least one record, are its reads (only the baseline's are used, and they never leave the Hub).
  • Certain: any other key is perturbed: deleted, set to one fixed synthetic string, then set to each donor from other records; a key that is no field name or alias (the first AliasPath element included) and has no donor is also set to fixed variants of the record's own value (a number plus one, a string with the synthetic suffix, a list or object with one synthetic element, the other boolean; any other value, such as null, is tried as true and 1). It is invariant when nothing raises and the stable dump without that key never changes. It is certain when invariant and either a donor value different from the record's own exists, the key is no field name or alias, or the model is blind: the key is no field name or alias and the model has no model validator of any mode, no model or field serializer, no computed field, and no custom __init__, model_post_init (the one pydantic installs for private attributes does not count), model_validate or __get_pydantic_core_schema__ (any introspection error means not blind). For a blind model and a key that is no name or alias the probe deletes only.
  • Its fate. Certain and absent from the dump is erased: the next save of that record removes it (kept: false). Certain and present is hidden: it stays saved and the version has no field for it (kept: true). Anything else is silent. A key erased in some records and hidden in others is erased. An erased key's count is the records the probe proved erase it; when more probed records' saves drop the key (a shim reads it there, so its value may live on under another name), the child marks the entry at_least and the notice sets records_at_least. A hidden key's count is the records that keep it.
  • Which records. Each reported key also lists the records behind it: erased and hidden, the ordinals of the records whose save erases or hides it, and null, those of them whose stored value is null. An ordinal is the record's position in the list the Hub sent the child (a record that failed validation keeps its place); it is never an id or a value. Both children are handed the same list, so an ordinal names the same record in both answers. The child also answers reached, the first ordinal its probe did not finish: every record before it was looked at (or failed validation), none from it on; all of them when the probe finished. It also answers unreadable, the ordinals below reached of the records its model could not read: they failed validation or are not JSON objects (a record that validates but whose dump raises is not one: the version can still show it). One child answer lists at most 400,000 ordinals across all its collections (two per record and listed key for 2,000 records and 100 names, about 2.4 MB, under the 8 MiB frame). The Hub sends one check at most 2,000 records in all, so a real answer stays within it. Every collection's key lists are bounded first, in answer order: the first key whose lists would pass it, and every later one that lists any record, comes without its three lists. The unreadable lists then share what is left, so one never displaces a key's lists; one that does not fit is left out and reads as empty. The Hub then compares such a key against nothing: a checked-build key counts every record and stops, and a baseline key is compared as no usable baseline (every record the checked build erases, or hides holding a value, stops; baseline: false). The Hub re-checks every list (integers below the records sent, strictly ascending, erased and hidden disjoint, null within them, the reported fate's list as long as count, no erased record on a hidden key; for the baseline, no listed record at or past its reached); a key whose lists fail reads as one without them. Only the baseline's unreadable is used; it must be strictly ascending, below its reached, and share no record with any of its keys' lists, or it reads as empty.
  • A null (W9-7). A record whose value is null never makes a hidden key stop (unless the checked build's key comes without usable lists, above, when every record counts): the version keeps the key, so nothing that showed stops showing. On a whole sample (the collection's sample is not capped and the probe finished, not partial), the notice also leaves those records out of the key's count, and a hidden key whose only new records are null is not reported. On a capped sample, or after a partial probe, the count keeps them, because records beyond the sample, or not reached, may hold values; such a key is listed without a stop. An erased key counts its null records and stops on them: dropping a stored null is not always lossless (an older version may read a missing key as a non-null default). "", 0, false, [] and {} are values, never null.

The probe costs at most rows × (2 + unread keys × 10) validations; a wide model that would exceed the deadline answers partial. The baseline's probe is sent through = the checked build's reached, so it has up to 12 s to reach every record the checked build's probe reached; it is partial only when that is not enough. Records a partial baseline never reached are then listed, never a stop, where the checked build hides the key (its records listed); where it erases the key they stop (see the baseline below). A baseline that probed no record (probed: 0, partial: true) is partial, not unusable, whenever its reached is valid: a key the checked build erases stops; a key it hides is listed without a stop. A declared field no validated record sets is unfilled. A rename the model handles (AliasChoices, a mode="before" validator, a custom __init__) changes the dump when the old key is perturbed, so it is read and not reported. Synthetic and donor values exist only inside the child and never appear in its reply. A batch the Hub sends with through (the baseline's, below) has no 2 s deadline: it is probed up to 12 s after the call began, and stops at the first validated record whose ordinal is through or more (then partial, reached = through; when every record from through on failed validation, the probe finishes and lists them in unreadable). A through that is not an integer from 0 to the number of records sent is ignored. With through, a keys list of strings limits the probe to those keys: it probes, reports and reads only them (anything else in keys is ignored).

A collection with no stored records has nothing to check: it is never sent to the child and is never refused, for any cause (total: 0; on a timeout or a failed child, details.collections lists only the collections the child was given). A first publish of a new pack is therefore never refused with a 422 by this check; only a failed read defers it with the retryable 503. With no stored records at all, no child runs.

Result Answer
No state.collections declared Publish proceeds; stored_data.outcome = not_checked
No stored records in a collection Nothing to check there; with none anywhere, checked (or capped) and no child
Every record read validates Publish proceeds; checked (or capped past a bound)
A stored record was validated and failed 422, error.code = details.reason = stored_data_unreadable, with details.collections — the only result that means the data cannot be read
Records exist and the model does not import, is not a pydantic model, or is not the build's own 422, error.code = details.reason = stored_data_check_failed, details.cause = "model_not_loadable"
Records exist and the child exceeds 15 s 422 stored_data_check_failed, details.cause = "timeout"
Records exist and the child dies after the handshake 422 stored_data_check_failed, details.cause = "check_failed"
The child cannot be spawned, the tenant already holds a check slot, no slot frees within 5 s, or the stored records could not be read (a transient failure, whether or not any exist) 503, error.code = details.reason = stored_data_check_unavailable, Retry-After: 5

stored_data_check_failed is never a verdict on the data: it says the check could not finish, and the publish is refused because a later check could not run either.

A refused publish publishes nothing (see Publish Atomicity). There is no override. The check result is not stored; it is in the response and one log line (stored-data check pack=… version=… outcome=…).

Stored-data notices. The outcome carries notices: [{code, …}], keyed by a fixed code; a client shows fixed copy per code and ignores a code it does not know. A notice never changes the outcome or the status code of a REST publish or a check, and never appears in a 422's details except as details.unread of a stored_fields_unread stop. Studio's publish leg and Activate stop on a stored_fields_unread notice whose stops is true: the publish leg answers needs_confirmation with nothing published (Unread stored fields), Activate answers 422 stored_fields_unread with nothing changed.

code Fields Meaning
stored_data_unlisted count, capped The tenant holds count unexpired records of this pack whose key is under no <key_prefix>/ the checked version declares (all of them when it declares none). Counted up to 2,001; capped is count > 2000; no notice when the count is 0
stored_collections_dropped collections (names, at most 20), more (how many more there were) Collections the version being replaced declared in its stored state that the checked version does not declare, without repeats, in declaration order
stored_fields_not_checked collection, looked The probe ran out of time on validated records of collection and found no key to report: looked is false when it looked at none of them, true when it looked at some. Studio cannot say which stored fields the checked version reads there. Informational like every notice; it never stops a publish
stored_fields_unread collection, records, records_at_least, fields ([{name, count, kept, change}], at most 20), more, unfilled (names, at most 20), partial, baseline, stops Top-level keys of validated records in collection whose fate under the checked version is worse than, or unknown against, the baseline's (Unread fields: the baseline below). One notice per collection, only when at least one key is reported. count is the number of records the change is about: for erased the records this version newly erases, for hidden the records it newly hides (or that a partial baseline never reached), less their null records on a whole sample, neither capped nor partial (W9-7), and for already_erased every record it erases (a lower bound when the child marks it at_least); kept is true exactly for hidden. A key erased in some records, all of them erased by the baseline too, and newly hidden in others holding a value has two entries with the same name: hidden, counting the records it newly hides (where it stays saved), and already_erased, counting the records both versions erase (where it is removed on the next save); fields may therefore repeat a name, never with the same change. change is erased, hidden or already_erased; stops is true when any reported key, listed or not, is erased (always), or hidden in a record that holds a value, which the baseline reached and could read, for a key the baseline reads, or in a record that could not be compared record by record (Unread fields: the baseline below). records is the busiest reported entry's count (at least 1; a key listed twice has two entries), and records_at_least is true whenever that or any count is a lower bound: the probe is partial, the collection's sample is capped, a reported key is not listed (more > 0), a key's count is marked at_least, or a hidden count leaves out records the key is hidden in that the baseline cannot read (in U, the baseline's unreadable records, below), whatever the notice's baseline. unfilled lists declared fields no validated record sets. Notices are ordered stopping ones first, then by their worst change (erased, hidden, already_erased); fields within one notice by change; a stored finding keeps the first 20 notices in this order
  • The count. One count(*), its result bounded at 2,001, over pack_data rows filtered on tenant, pack and expiry, with one arm per scope: user-scope rows (the two sentinel users excluded) whose key matches no tenant:{tid}:user:%:pack:{pid}:{prefix}/%, tenant-scope rows (the tenant sentinel user) matching no tenant:{tid}:{prefix}/%, and pack-scope rows (the pack sentinel user) matching no tenant:{tid}:pack:{pid}:{prefix}/%, each prefix of that scope LIKE-escaped. Rows never leave the Hub and never reach a check child; no key, id or value is returned or logged, only the count.
  • Its time bound. The count runs in a savepoint under a 5 s statement timeout, the check's own wait for a free check slot: a notice must never hold the install lock longer than a check may wait to start. The caller's own timeout is restored before the savepoint ends. A count that times out or fails is logged in one line (no key, no SQL) and the notice is omitted.
  • Whose rows. On a publish, other users' user-scope rows count only when the caller reads every user (an owner or admin, not through an API key); otherwise only the caller's own. Tenant and pack scope always. On Check Stored Data and Activate every user's, since both already require an owner or admin of the owning tenant.
  • Failure. The count runs in a savepoint; when it fails the notice is omitted and one log line is written. It never adds a refusal or a 503.
  • Unread fields: the baseline. The baseline is the active version at publish, the version being left on Activate, and previous on Check Stored Data when previous.newer is false. When the checked build reports any key, the same probe code runs once more, in a second child inside the same check slot, with the baseline version's models (its stored collections, matched by name, scope and key prefix, from its own version directory) over the same records, each batch with through = the checked build's reached for that collection (sent only when it is an integer from 0 to the records sent) and keys = the names the checked build reported there (sent only when they are at most 100 strings of at most 128 characters), the only keys compared; that child also answers the baseline's reads among those keys (at most 100 names). The baseline is unusable when there is none, it is not installed here, its collection is not declared, its model does not load, its child fails or does not answer within its 15 s (see below), or it listed more keys than it could name, or its reached is missing, past the records sent, or short of them on a probe that finished. More reads than it could name leave it usable: every key it does not name then counts as one it reads (only a hidden record needs the reads; an erased one never does), and no line cites the baseline as reading a key it did not name. Each key the checked build reports is compared with the baseline record by record, never by count. For the checked build let E be the records it erases the key in and H those it hides it in; for the baseline Eb and Hb, R the records its probe reached, and U its unreadable records:
Records Result
some of E is not in Eb (the baseline hides or reads the key there, did not reach the record, cannot read it (it is in U), or is unusable) stop, change: "erased", count = those records, null ones included
else some of H lies in R, in none of Hb, Eb and U, the baseline reads the key, and the record holds a value stop, change: "hidden", count = those records (on a sample that is not whole, their null ones too); when E is not empty too (E ⊆ Eb: both versions erase it there), a second entry for the same name, change: "already_erased", count = E, so each line is true of the records it counts: the key stays saved in the first, and is removed on the next save in the second, by either version
else E is not empty (E ⊆ Eb) notice only, change: "already_erased", count = E; it cites the baseline only when the baseline does not read the key (otherwise baseline is false, so no line says neither version has a field for it)
else some of H lies outside R, or the newly hidden records of H hold null listed, change: "hidden", never sets stops (on a whole sample null records are left out, and a key with none left is silent)
else (H ⊆ Hb ∪ Eb ∪ U, or the baseline does not read the key) silent: nothing changed

An unusable baseline is compared as one that erases and hides nothing, reached every record and reads every key: every erased record stops, and every hidden record holding a value stops (baseline: false). "The baseline reads the key" is per key, not per record: its probe found the key used, or its perturbation changed the dump, in at least one record. A key the baseline erases in some records and hides in others counts each record by its own fate. A record in U is one the baseline cannot read at all, so nothing in it shows today: hiding a key there hides nothing that showed.

So a build identical to the baseline never stops on the same records when both probes finish: the same records erase and hide the same keys, its erased keys are already_erased, its hidden keys silent. The same holds when the checked build's probe is cut short and the baseline's reaches its through: both then compare exactly the records the checked build reached. Only when the baseline's probe runs out of its 12 s before through (its validation pass left it too little of them) are the records past its reached compared against nothing it did: an identical build lists the hidden ones without a stop, and stops, with true copy, on the erased ones (data safety wins over that false stop). With an injected clock over many cut points this happened for 1 unchanged build in 1,230, against 85 in 1,230 when both probes had the 2 s deadline. Giving the baseline its through adds at most 10 s to a check (its probe ran at most 2 s, now at most 12 s after its call began). The 12 s are checked before each validation, never during one, and the child's timeout is 15 s, so a validation call still running at the 12 s mark has about 2.7 s (less the reply's encoding) before the child is killed. A baseline child killed at its timeout is not run again (a second call could take the check past the 60 s proxy timeout): it is unusable, every reported key is classified against no baseline, so every erased record and every hidden one holding a value stops, and the notice has partial: true (the comparison did not finish) and baseline: false. When the checked build's own probe is partial, only the records it reached are compared, and the notice has partial: true and baseline: false. A key past the checked child's 100 listed names cannot be classified: it is counted in more and sets stops. baseline is true only when the baseline was usable, neither probe was partial, no reported key was past the checked child's listed names, every reported key was compared record by record (its own lists and, where the baseline reported the key, the baseline's lists were usable), and for every key reported erased the baseline names the key among its reads or hides it in every newly erased record, and none of them is a record the baseline cannot read (in U), so no line claims the current version keeps a key it does not. A key reported hidden (stopping or listed) cites the baseline only when the baseline names it among its reads; otherwise baseline is false. A key's already_erased entry beside its hidden one cites the baseline whenever the baseline is usable, so it never changes baseline for the other keys (Studio says that line without naming the baseline, which may read the key in the records of the hidden entry). A key reported already_erased alone cites the baseline only when the baseline does not read the key. stops is computed from every collection's notice, not only the first 20 a stored finding keeps. A notice never stops a REST publish or a check: they show the same classification. Studio's publish leg and Activate stop on it (above). The reads list never leaves the Hub. - Unread fields: names. A name is listed only when it matches [A-Za-z_][A-Za-z0-9_]{0,63} (whole string), the collection's model declares at least one field, and the collection has at most 20 distinct reported keys in at most 20 entries (a key listed twice, hidden and already_erased, is two entries); otherwise fields is [] and more counts the distinct reported keys. With names listed, more counts the distinct keys not listed, and a key listed twice is counted once. A name that fails the pattern is counted in more, and still sets stops by its own change. An undeclared key is row content, not schema: with extra="allow" or "ignore" a user-chosen, identifier-shaped key can be listed. unfilled names come from the model and pass the same pattern. The finding comes from the records the check may read (see Whose user-scope records), so it is never wider than the check itself. Every number the child returns is bounded on the Hub before it is logged, stored or returned (count and records by the records sent, more by 10,000 distinct keys, and a reply listing more than 100 names per collection is dropped), so a count cannot carry a stored value. The probe reads each record as stored (copied before validation). The log line carries counts only: the number of reported fields, never a name. - Unread fields: what is not covered. Nested models (only top-level keys are probed), records past the bounds, other tenants' records, a pack with no records, and loss in command code (a command that rebuilds a record by hand). A key read only by a validator whose donors, synthetic value and fixed variants of its own value all collapse to the same result (a shim key whose every value maps to the default) reads as unread and is reported. A key the model inspects and then drops is not reported when a trial raises or matches one exact value. - Dropped collections. At publish, against the active version; on Check Stored Data, against previous only when previous.newer is false; never on activate. Each name must be a valid collection name (huitzo_sdk.identifiers.COLLECTION_NAME); others are dropped. A version published before collections were stored has no state, so it never yields this notice; the count still applies.

Command Runtime Contract

commands[].timeout and commands[].queue in the manifest are declarations that must match the @command decorator, not a second source of truth. Publish rejects any divergence with 400 command_contract_violation and lists the violations, so a manifest edit can never silently fail to take effect. See manifest.md#command-runtime-contract for the comparison rules (queue is compared after resolution) and the rationale.

The same response refuses a partial wheel. An entry point that did not load as a command is listed first (field load: ImportError, AttributeError, BadZipFile or OSError while it loads, or a target not decorated with @command), and a declared command the wheel does not export is listed last (field missing). A declared command whose own entry point (the pack's {scope}/{name}/ followed by the command's name) failed is reported once, as load.

It also refuses two command-name defects in the wheel itself, listed after any load entries and ahead of the comparison violations: a command name exported by more than one entry point (field duplicate), and a namespace whose command segment is not the command's name as one SDK kebab-case identifier (field namespace). Every check runs before any row is written. See manifest.md#command-name-checks.

Every entry in details.violations carries message, the line publish writes for it, so a client can print each one without knowing every field. At most 100 entries are listed, and at most 50 failed entry points among them; details.total counts every violation, listed or not. error.message is the first entry's message, followed by (and N more; see details.violations) when there are more, where N is details.total minus one. When more than 50 entry points fail, missing is not checked: an unlisted failure could account for any declared command. Every string an entry echoes from the wheel or the manifest is cut to 200 characters, in the entry and in its message, and a duplicate entry lists at most 10 namespaces, with decorator_total counting them all (see manifest.md#command-runtime-contract).

Error Responses:

Status error.details.code Condition
400 — Invalid version format, non-.whl upload, or path-traversal filename
400 wheel_unreadable The upload is not a readable zip, or it does not contain exactly one *.dist-info/METADATA, or that METADATA or its entry_points.txt is over 64 KiB uncompressed, or that entry_points.txt is malformed
400 wheel_layout_refused A member name is not a plain relative path or appears twice, the archive ships distribution metadata (*.dist-info, *.egg-info, *.egg-link) besides its own dist-info, a .pth file, a sitecustomize/usercustomize module or compiled byte-code (__pycache__, .pyc, .pyo), or <name>.data/ holds a scheme other than purelib, platlib (checked before anything is written or installed); or, after install and before anything is imported, the venv has unreadable distribution metadata, a dependency declaring huitzo.commands entry points, other metadata for the pack, or entry points that differ from the archive's
400 wheel_dependency_refused A Requires-Dist does not parse, or names a URL (a direct reference); dependencies must come from the package index; checked before anything is written or installed
400 wheel_filename_mismatch The wheel filename is not PEP 427, or its name/version disagree with dist-info
400 wheel_version_mismatch dist-info Version ≠ the declared version (exact string)
400 wheel_name_mismatch dist-info Name does not canonicalize to Pack.name
400 manifest_required The manifest field is absent
400 manifest_version_mismatch manifest.pack.version ≠ the declared version
400 — Manifest is not JSON / not an object / not schema v2, or the LLM capability floor is unsatisfiable
400 — Wheel installation or command extraction failed (including an entry point that raises anything other than ImportError, AttributeError, BadZipFile or OSError while it loads), or the wheel registers no huitzo.commands entry point
400 namespace_mismatch A huitzo.commands entry point in the wheel's entry_points.txt (checked before install), or an extracted command's namespace, is outside the pack's {scope}/{name}/ prefix (details.namespaces lists up to 100, each cut to 200 characters, and details.total counts them; error.message names up to 10)
400 command_contract_violation An entry point did not load as a command, a declared command was not extracted, a command's decorator timeout/queue differs from the manifest declaration, a declared timeout above the resolved queue's ceiling (fast 570 s, medium 1170 s, long 32370 s), an extracted command is undeclared, two entry points export the same command name, or a namespace's command segment is not the command's kebab-case name — up to 100 violations listed, each with its message, and details.total counting them all
403 — Developer mode required
403 listing_publisher_mismatch Caller's tenant does not own the pack
404 — Pack not found
409 — Version already published for this pack — bump the version in huitzo.yaml
413 — Wheel or manifest exceeds the size limit
422 stored_data_unreadable (error.code too) A record the tenant already stored was validated with the new version's model and failed (Stored-Data Check); nothing was published
422 stored_data_check_failed (error.code too) Records exist and the check could not finish them; details.cause is model_not_loadable, timeout or check_failed; nothing was published
503 publish_sandbox_unavailable The publish or execution sandbox identity is not usable on this server (see Untrusted code at publish); nothing was installed or run
503 publish_cleanup_failed A process of the publish UID survived the kill that ends every publish step, or the kill could not finish; nothing was published, and no further publish step runs on this server until the kill succeeds
503 stored_data_check_unavailable (error.code too) The stored-data check could not start (no child, or no free check slot) or could not read the stored records; retry after the Retry-After interval
500 — Database error unrelated to the duplicate-version constraint
Check Stored Data

Run the stored-data check against an installed version of a pack, without changing anything. Studio calls it once after a publish succeeds, so a record written between the publish-time check and the commit is seen.

POST /api/v1/packs/{pack_id}/versions/{version}/stored-data-check
Authorization: Bearer {token}

Only an owner or admin of the owning tenant may call it (an API key acts as member and is refused). A caller who cannot see the pack (another tenant's pack that is not publicly listed) gets 404 version_not_found, as for a pack that does not exist; another tenant's publicly listed pack answers 403 not_permitted. The collections are the ones stored with the version (manifest.state, Stored manifest); a version published before they were stored answers not_checked. A per-pack non-blocking lock bounds it: a second call for the same pack while one runs answers 409 check_in_progress. It is a POST because it runs pack code; a page load or a cross-site GET cannot start it.

Response (200):

{
  "data": {
    "pack_id": "a6ed4f8d-…",
    "version": "0.2.0",
    "active": true,
    "outcome": "unreadable",
    "cause": null,
    "capped": false,
    "collections": [
      {"name": "reminders", "total": 3, "failing": 1, "capped": false, "rules": ["string_too_long"]}
    ],
    "notices": [{"code": "stored_data_unlisted", "count": 12, "capped": false}],
    "previous": {
      "version": "0.1.0",
      "dashboard": {"scope": "@acme", "name": "reminders-board", "version": "0.1.0"},
      "checkable": true,
      "newer": false
    },
    "command_changes": {
      "removed": ["complete-reminder"],
      "added": ["mark-done"],
      "arguments": [
        {"command": "list-reminders", "removed": ["status"], "added": ["include_done"], "required_added": []}
      ]
    }
  }
}

outcome is checked, capped, not_checked, unreadable (a stored record was validated and failed) or check_failed (the check could not finish, never a verdict); cause is set only with check_failed (timeout, check_failed, model_not_loadable, read_failed). previous is the most recently active other version still installed here, by the mtime of its version directory (which an install and every go-back set), among those created no later than the checked version (pack_versions.created_at). Only when no such version is installed is previous the most recently active newer one in the same order, with previous.newer true, so an installed older version is never hidden behind a newer one. A Studio release whose cleanup is pending is never previous. It comes with the dashboard version published by the same Studio build as {scope, name, version}; null when there is none. Studio offers it as the version to go back to unless previous.newer is true (going back after a publish), so it only names a version still installed here.

previous.checkable is true when previous has stored collections, so going back to it runs a check; false when it declares none or was published before they were stored. previous.newer is true when previous was created after the checked version (pack_versions.created_at): a publish always makes its new version the active one, so a newer version that is not active was left by going back, and Studio does not offer it as "Go back". notices are the stored-data notices, counted before the not_checked answer too. command_changes compares the checked version's command names (its commands rows) with previous's, as {removed, added, arguments}, removed and added each sorted and at most 20; every list is empty when previous is null or newer. arguments (W8-6) compares, for each command both versions have, the top-level properties and required of the input schema each version stored at its publish (commands.input_schema): {command, removed, added, required_added} lists the argument names the checked version no longer takes, the ones it newly takes, and the ones it newly requires (an added required argument is in both added and required_added). Nothing is said about what a call that still passes a removed argument meets: the args model's own validators decide it (a rename shim maps the old name), and the stored schema does not show them. Only commands with a change are listed, sorted, at most 20; each name must match [A-Za-z_][A-Za-z0-9_]{0,63} (others are dropped) and each list holds at most 20. A version holding the minimal fallback schema ({"type": "object"}, no properties) for a command makes no claim about it. A changed argument is only known once both versions are on the Hub: there is no notice before a publish.

Status error.code = details.reason Condition
403 not_permitted The caller is a member of the owning tenant but not an owner or admin, or the pack is another tenant's publicly listed pack
404 version_not_found No such pack, no such version of it, or a pack the caller cannot see (another tenant's, not publicly listed)
409 check_in_progress A check of this pack is already running
409 version_not_installed The version has no directory of its own on this Hub (no longer retained, or a pack installed before per-version directories)
503 pack_build_not_ready The target build does not have the build permission rule yet (its tree root is not in the sandbox group with mode 0750): this server's startup permission repair is running and has not reached it. Retry after Retry-After (5 s); nothing changed and no check ran
503 pack_build_unavailable The target build does not have the build permission rule (its tree root is not in the sandbox group with mode 0750), and no startup permission repair is running (it finished without fixing the build, or could not run): "This pack version can't start on this server right now; Huitzo has been alerted." Logged at ERROR; nothing changed and no check ran
503 stored_data_check_unavailable The check could not start: no child, the tenant already holds a check slot, or no free slot within 5 s
Activate Pack Version

Make an earlier version of a pack the active one again ("Go back to 0.3.0"), with the dashboard version published together with it. The version is an existing one: going back never assigns or consumes a version number. A version whose directory retention has collected is restored first from what was published (restoring a version).

POST /api/v1/packs/{pack_id}/versions/{version}/activate
Authorization: Bearer {token}
Content-Type: application/json

{"expected_active_version": "0.2.0"}

Same authorization as Check Stored Data. The body is optional; expected_active_version (1 to 20 characters, else a 422 validation error) is the version the caller saw active; expected_dashboard_version (same bounds) is the paired dashboard's active version the caller saw (Activate Dashboard Version sends it). confirm_stored_fields (boolean, default false) goes on past the unread-field stop and the unlisted-data stop below; confirm_every_user_check (boolean, default false) lets the check read every user's records for a target published by someone who could not (whose records). The Studio client sends the pack's live active version from the publish state (active_version, Publication) whenever one is active. Under the pack row lock (the one a publish takes), in one transaction:

# pseudocode — apps/backend/src/backend/packs/activation_service.py::activate_pack_version
lock the pack row; the target version must exist and not be active
the target must not be a Studio release whose cleanup is pending, else 409 version_not_installed
the active version must be expected_active_version when sent, else 409 active_version_changed
no Studio publish of this pack may be between its pack and dashboard legs, else 409 publish_in_progress
the target must not itself be a version still awaiting its Studio publish's dashboard leg (its request still publishing, whether or not its window has lapsed), else 409 publish_in_progress
take the per-pack check lock, else 409 check_in_progress
when sent, the paired dashboard's active version must be expected_dashboard_version, else 409 active_version_changed
a target whose code was published by someone who could not read every user's records, and that
    declares a user-scope collection: 422 every_user_check_unconfirmed unless confirm_every_user_check
no versions/<version> directory: restore it from the published wheel, else 409 version_not_restorable
count the rows under no prefix the target declares (stored_data_unlisted)
run the stored-data check against the target's stored collections over EVERY user's records,
    the version being left as baseline
stop as a publish does: 422 stored_data_unreadable, 422 stored_data_check_failed,
    503 stored_data_check_unavailable (a restored directory is removed)
when the count could not be read: 503 stored_data_check_unavailable, with or without confirm_stored_fields
unless confirm_stored_fields, stop on 422 stored_fields_unread, and when the target lists none of the
    saved data, or not a collection the version being left lists, while records sit outside what the
    target lists: 422 stored_collections_unread; both data stops are evaluated first and answered
    together (stored_fields_unread carries details.unlisted)
with this replica's install lock (publish's order: row, install lock, licence lock):
    licence max_schedules gate on the net cron increase
    flip PackVersion.is_active to the target
    flip the paired dashboard version (same Studio build) the same way
    load the target's commands in this process (503 pack_busy when it is executing)
    commit
register the loaded commands; touch the version directory; promote the venv pointer
send_task("huitzo.reload_pack_commands", {tenant_id, pack_id, version})

The paired dashboard is the dashboard version a Studio build published together with the target pack version (build_publications). A version published outside Studio has none, and the pack goes back alone (data.dashboard = null). The version directory's mtime is set to now before the promote, so the retention of the two newest directories keeps it.

Data safety: the publish guards run. A target is checked against the data the pack holds exactly as a new build is at publish, with the version being left as the baseline of the unread-field comparison, and stops the same way: a target whose models reject a stored record (422 stored_data_unreadable), whose check could not finish over stored records (422 stored_data_check_failed), or that does not read a field the records hold that the version being left reads or keeps (422 stored_fields_unread, the fields named in details.unread exactly as on the publish leg, unread stored fields) is not activated and nothing changes. A stored record the version being left saved can carry a field an older version never had; going back to it would drop that field on the next save, so the owner is told which fields first. As on a publish, the unread-field stop asks and never blocks: the same request with confirm_stored_fields: true goes on past it (and the response's stored_data.notices still name the fields). The other two stops have no override, as a publish has none: the owner plans a fix instead. A check whose records could not be read is the retryable 503 stored_data_check_unavailable.

Saved data the target does not list. A target that declares no stored collections answers not_checked, and one that drops a collection the version being left declares never looks at that collection's records. Neither may go back silently over saved data: when the target declares no collection, or does not declare one the version being left declares, and the pack holds records under no key prefix the target declares (the stored_data_unlisted count, over every user), the answer is 422 stored_collections_unread and nothing changes. details carries records and capped (that count) and collections: the collections the version being left declares that the target does not, each {name, fields} (its stored top-level field names, [] when none are stored), shape-checked, at most 20. collections is [] when the version being left declares none either. unconfirmed is true when neither the target nor the version being left declares any stored collection (read from both manifests before any shape check): the Hub then had nothing to check, so the stop means only that it could not confirm the target reads the saved data, never that the target cannot read it (huitzo #2350; the owner's line is Studio's unconfirmed-data line). It is false whenever either version declares one. Like the unread-field stop it asks and never blocks: the same request with confirm_stored_fields: true goes on (the records stay saved; when unconfirmed is false, the target does not list data the version being left lists, so it cannot read it). A count that could not be read is the retryable 503 stored_data_check_unavailable, never a silent go-back: the count is read on every go-back, confirmed or not, and confirm_stored_fields covers only the stops an answer named, never a check that could not finish.

One answer names everything that one confirmation covers. Both data stops are evaluated before the go-back answers, so confirm_stored_fields is only ever sent for what was shown: when the target also leaves stored fields unread, the answer is 422 stored_fields_unread with details.unread and, beside it, details.unlisted = {records, capped, collections, unconfirmed} (the same shape as the stored_collections_unread details); 422 stored_collections_unread alone means no field is left unread. The count behind both the stop and the stored_data_unlisted notice is read once.

Whose records the go-back check reads. Every user's, whoever published the target and whatever their role now: the check runs with the Hub's own read scope over all of the pack's records in the tenant (user, tenant and pack scope), not the publisher's recorded scope, so incompatible data another user saved is never missed. (The check route keeps the publisher's scope.)

That hands every user's records to the target's own record models, in the check's isolation child, before anything is activated, and also when the go-back is then refused. That child shares the Hub's network namespace (sandbox limitation). So when the target's code was published by someone who could not read every user's records (its stored read_scope is not every_user, or its publisher is no longer an active owner or admin, or none is recorded) and it declares a user-scope collection, the go-back first answers 422 every_user_check_unconfirmed and reads nothing: the owner or admin confirms that showing every user's saved records to that version's code is acceptable by sending confirm_every_user_check: true, and only then does the check run. A target published by a current owner or admin with every_user scope, or one that declares no user-scope collection, is checked without asking.

Restoring a version that is no longer installed. The Hub keeps the directories of the two most recently active versions. Any other version is restored from the wheel it was published with, under the pack row lock and this replica's install lock, before the check:

  1. the project-store snapshot of the Studio build that published the version (found through its build_publications row), when that snapshot's wheel sha256 equals the artifact.wheel_sha256 recorded with the version;
  2. else the wheel the Hub archived at publish (artifact.wheel_filename in the pack's archive directory), under the same sha256 comparison.

Either is read whole (at most the 50 MB wheel cap), hashed, and installed into a private staging directory exactly as a publish installs a wheel (the publish UID, --only-binary, the SDK pin); the installed distribution must match the wheel's own entry points, and the directory is then moved to versions/<version>. The commands are not extracted again: the version's commands rows already exist. A version with no matching source answers 409 version_not_restorable and nothing changes. When the activation does not commit (a stop, a refusal, a load failure), the restored directory is removed again before the transaction rolls back, so the pack row lock is held until it is gone; once the commit has been sent the directory stays (an unknown commit outcome leaves it to retention).

A restore is a publish-grade install, so it counts against the publish limits first: past them the answer is the publish's own 429 publish_rate_limited (or its 503 while the limiter is down, code: rate_limiter_unavailable) and nothing is read or installed. Activating a version that is still installed is not counted. Only the wheel is checked against what was published: the install resolves its dependencies again, as a publish does, under the backend's current huitzo-sdk pin, so a restored build runs the dependency versions the index serves at restore time.

expected_active_version closes a race: an activate that waited on the pack row behind a publish would otherwise deactivate the version that publish just made active. A Studio publish between its pack leg and its dashboard leg is refused too: going back then would leave the pack and the dashboard, once its leg lands, on different builds.

Response (200):

{
  "data": {
    "pack_id": "a6ed4f8d-…",
    "version": "0.1.0",
    "from_version": "0.2.0",
    "dashboard": {"scope": "@acme", "name": "reminders-board", "version": "0.1.0"},
    "restored": "snapshot",
    "stored_data": {
      "outcome": "not_checked", "cause": null, "capped": false, "collections": [],
      "notices": [{"code": "stored_data_unlisted", "count": 3, "capped": false}]
    }
  }
}

stored_data.outcome is checked, capped or not_checked (the stops above answer every other outcome). stored_data.notices carries stored_data_unlisted (never stored_collections_dropped), counted over every user's rows, and stored_fields_unread (the confirmed stopping ones too) and stored_fields_not_checked, against the version being left (from_version). restored is "snapshot" or "archive" when the version was restored first, else null.

Status error.code Condition
403 not_permitted The caller is a member of the owning tenant but not an owner or admin, or the pack is another tenant's publicly listed pack
404 version_not_found No such pack, no such version of it, or a pack the caller cannot see (another tenant's, not publicly listed)
409 version_already_active The version is already the active one
409 active_version_changed expected_active_version was sent and another version is active now
409 publish_in_progress A Studio publish of this pack is between its pack and dashboard legs; for up to 15 minutes (its execution window) after a publish that stopped between them. Always when the target itself is the version such a publish wrote and has not finished (its request still publishing, even past its window, until expiry releases it)
409 check_in_progress A stored-data check of this pack is already running
409 version_not_restorable The version is not installed here and neither its snapshot nor its archived wheel matches what was published
409 version_not_installed The version is a Studio release whose cleanup is pending (cleanup pending), or its directory went away between the restore (or the installed check) and the stored-data check; retry
409 license_limit_exceeded The target's crons would pass the licence max_schedules ceiling (the licence refusal body: details.key, details.attempted_delta)
422 stored_data_unreadable The target's models reject a stored record (details: capped, collections, as on a publish)
422 stored_data_check_failed Stored records exist and the check could not finish (details.cause)
422 stored_fields_unread The target does not read a stored field the version being left reads or keeps (details.unread; details.unlisted too when saved data the target does not list is also found), and confirm_stored_fields was not sent
422 every_user_check_unconfirmed The target's code was published by someone who could not read every user's records, it declares a user-scope collection, and confirm_every_user_check was not sent; nothing was read (whose records)
422 stored_collections_unread The target lists none of the saved data, or not a collection the version being left lists, while records sit outside what the target lists (details.records, capped, collections, unconfirmed), and confirm_stored_fields was not sent (saved data the target does not list)
429 publish_rate_limited A restore was needed and the tenant or user is past the publish limits (the publish's own body)
503 license_count_unavailable The licence count failed (the licence body, no details.reason)
503 pack_busy Another build of this pack is executing on this replica; retry after Retry-After
503 pack_build_not_ready The target build does not have the build permission rule yet (its tree root is not in the sandbox group with mode 0750): this server's startup permission repair is running and has not reached it. Retry after Retry-After (5 s); nothing changed and the version was not activated
503 pack_build_unavailable The target build does not have the build permission rule (its tree root is not in the sandbox group with mode 0750), and no startup permission repair is running (it finished without fixing the build, or could not run): "This pack version can't start on this server right now; Huitzo has been alerted." Logged at ERROR; nothing changed and the version was not activated
500 pack_load_failed The target build's commands could not be registered (its isolated introspection failed, or nothing serves the version, its directory included), or a restore's install failed; nothing changed
503 stored_data_check_unavailable The check could not start (no child, the tenant already holds a check slot, or no free slot within 5 s), the stored records could not be read, or the count of records the target does not list could not be read (also when confirm_stored_fields was sent)
503 rate_limiter_unavailable A restore was needed and the publish limiter is down (the publish's own body)

Every code this endpoint writes itself also carries details.reason with the same value; the two licence codes keep the licence refusal's own details. The pack row lock is held through the stored-data check, which is bounded by the slot wait (5 s), and for each of its two children (the checked build's, and the baseline's when a key is reported) the handshake (5 s) and the child's 15 s, plus the read, so a publish of the same pack waits behind an activation, as behind another publish. A restore adds the install of the wheel (the publish install's own bounds: 120 s per pip step).

There is no tenant-plane audit table, and a publish writes no audit record either: an activation writes one structured log line (pack version activated tenant=… actor=… pack=… from=… to=… dashboard=… stored_data=… restored=…). After the commit, a failed touch, promote or worker notification is logged only; unlike a publish, the response has no degraded field.

List Pack Versions

The pack's version history: every version the Hub keeps, newest first, what changed in each, who published it and when, and which one is active. The Studio history view reads it (version history UI).

GET /api/v1/packs/{pack_id}/versions?limit=50&offset=0
Authorization: Bearer {token}

Every member of the owning tenant may read it (an API key too); any other caller gets 404 as for a pack it cannot see. can_manage is true for an owner or admin of the owning tenant: only they may go back. limit is 1 to 200 (default 50), offset at least 0.

Response (200):

{
  "data": {
    "pack_id": "a6ed4f8d-…",
    "scope": "@acme",
    "name": "reminders",
    "active_version": "0.3.0",
    "can_manage": true,
    "versions": [
      {
        "version": "0.3.0",
        "active": true,
        "published_at": "2026-11-20T15:04:05Z",
        "published_by": "[email protected]",
        "dashboard": {"scope": "@acme", "name": "reminders-board", "version": "0.3.0"},
        "available": "installed",
        "changes": {
          "previous": "0.2.0",
          "commands": {"removed": [], "added": ["snooze-reminder"], "arguments": []},
          "stored": {
            "collections_added": [], "collections_removed": [],
            "fields": [{"collection": "reminders", "added": ["snoozed_until"], "removed": []}]
          }
        }
      }
    ]
  },
  "meta": {"limit": 50, "offset": 0, "has_more": false}
}
  • Order. pack_versions.created_at newest first, then id.
  • Only publications. A version that is not a publication is never listed, never counted for has_more, and never another version's changes.previous: one a Studio publish wrote and whose dashboard leg has not finished (its request still publishing), or a release whose cleanup is pending (release_pending_at set). Going back refuses both (Activate: 409 publish_in_progress, 409 version_not_installed).
  • published_by. The email of the version's recorded publisher (published_by_user_id), null when none is recorded or the user is gone.
  • dashboard. The dashboard version a Studio build published together with the version (build_publications), as on Activate; null when the pack was published alone.
  • available. How going back would reach the version: installed (its directory is on this Hub), snapshot (its project-store snapshot carries a wheel whose sha256 is the one recorded with the version), archive (the Hub's archived wheel file exists; its sha256 is compared when it is restored), or null (it cannot be restored; going back answers version_not_restorable). See restoring a version.
  • changes. Against the next older version (previous, null for the first one, which carries empty lists):
  • commands: the command changes (removed, added, arguments), from the commands rows and their stored input schemas;
  • stored: the collections the version stores that the older one did not and the reverse, and per collection both declare, the top-level field names added and removed, from each version's stored state.collections[].fields (a collection without a valid field list is left out of fields). Names are shape-checked and each list holds at most 20. A rename shows as one field removed and one added: the stored manifest cannot tell a rename apart.

Every name in the answer passes the same shape checks as the stored-data notices; no record key or value is ever read.

Status Condition
404 No such pack, or the caller's tenant does not own it
422 limit or offset out of range

Uninstall Pack

Remove a pack and all its versions, commands, and access grants. Only an owner or admin of the owning tenant, in developer mode, can delete a pack. An API key always acts as member, so it cannot delete.

DELETE /api/v1/packs/{pack_id}
Authorization: Bearer {token}

Response (200):

{
  "data": {
    "message": "Pack uninstalled successfully"
  }
}

Error Responses:

Status Condition
403 User is not in developer mode
403 Pack is not owned by user's tenant
403 User's role in the owning tenant is not owner or admin (an API key always counts as member)
404 Pack not found
500 Database error

Side Effects:

  • All pack versions, commands, and access grants are cascade-deleted
  • Pack virtual environment and wheel files are removed from disk
  • A Celery task is dispatched to deregister the pack's commands. It is a unicast message, so it reaches one worker process, not the fleet
  • Remaining processes keep a stale registry entry until they exit. Those entries are unreachable: dispatch resolves against the database first and the rows are gone, and the venv has been removed so nothing can re-load the pack. See resource-lifecycle.md#pack-deletion-flow

Pack Listing History

Returns every published version's marketplace-listing snapshot (docs/architecture/database-schema.md#listing-snapshot-persistence), newest first, up to limit. Applies the same visibility/access-grant filter as GET /api/v1/packs/{pack_id} (owner, public, or org-grant) — never exposes a pack more broadly than the detail endpoint already does.

GET /api/v1/packs/{pack_id}/listing-history?limit=50
Authorization: Bearer {token}

Query parameters:

Parameter Type Default Description
limit int 50 Max rows returned (1-200)

Response (200):

{
  "data": [
    {
      "version": "1.2.0",
      "is_active": true,
      "published_at": "2026-08-01T00:00:00Z",
      "listing_updated_at": null,
      "listing": { "publisher": { "name": "Acme Inc." }, "...": "..." },
      "published_by_user_id": "u-abc123"
    }
  ],
  "meta": { "has_more": false, "limit": 50 }
}

published_by_user_id / listing_updated_by_user_id are included only when the caller is the pack's owning tenant — every other permitted viewer (public, org-grant) sees the version/timestamp/listing fields with those two omitted.

Error Responses:

Status Condition
404 Pack not found or not accessible
500 Database error

Update Pack Listing

Replaces the active version's listing snapshot in place — no bundle re-upload, no new version row. Owner-only; requires developer mode and the T-051 publisher-terms gate, same as Upload Pack Version. Dark by default (HUITZO_LISTING_METADATA_UPDATE_ENABLED=false): 404s exactly like a nonexistent route until an operator turns the flag on.

PATCH /api/v1/packs/{pack_id}/listing
Authorization: Bearer {token}
Content-Type: application/json

{ "listing": { "publisher": { "name": "Acme Inc." } } }

Response (200):

{
  "data": {
    "id": "p-abc123",
    "version": "1.2.0",
    "listing": { "publisher": { "name": "Acme Inc." } },
    "listingUpdatedAt": "2026-08-20T10:00:00Z"
  }
}

Error Responses:

Status Condition
403 User is not in developer mode
403 Pack is not owned by user's tenant
404 Flag is off, or pack not found
400 listing fails ListingSection validation
400 listing carries a server-owned key, an unknown commercial key or the removed reserved bag — the PRICING_* body of Upload Pack Version
400 listing.commercial.execution_pricing is present (details.code: PRICING_REQUIRES_PUBLISH) — a price changes only through a version publish
409 Pack has no active version, or a concurrent publish deactivated the targeted version between resolve and write (retry against the new active version)
413 listing payload exceeds 64 KB
500 Database error

Side Effects: Stamps listing_updated_by_user_id / listing_updated_at on the active version row (never published_by_user_id, which stays the original publisher). Emits a pack_listing_updated tracked event. A stored listing.commercial.execution_pricing declaration is carried over unchanged: a metadata edit never withdraws a price (spec §3.4).


Pack Pricing Versions (SaaS)

The owner's view of a pack's server-owned pricing versions (D-024 CR82, execution pricing §3). A published listing.commercial.execution_pricing declaration is inert until it is submitted here and a staff member approves it (staff review); only an approved version prices an execution, and nothing charges it yet. Mounted with the SaaS extension; every route returns 404 while HUITZO_PACK_PRICING_ENABLED is off.

Method Path Purpose
GET /api/v1/packs/{pack_id}/pricing-versions Every version of the pack, newest first. 200 {items}
POST /api/v1/packs/{pack_id}/pricing-versions Submits the active pack version's stored declaration as a new pending_review version. A pack with an approved price and no declaration submits {"mode": "free"} (spec §3.4). A newer submission withdraws an older pending one (superseded). 201 with the new version; 200 with the existing one when the declaration is already pending, or already approved (an older pending one is then withdrawn)

Only the pack's owner tenant sees or submits its versions: another tenant gets the same 404 as an unknown pack. No request field is a price: the server reads the declaration from the published manifest.

# pseudocode — one version in items[] or a submit/decision response
{
  "id": "uuid", "pack_id": "uuid", "owner_tenant_id": "uuid", "version": 2,
  "mode": "free" | "fixed_credits", "credits_per_execution": 5, "rate_bps": 1500,
  "declaration": {"mode": "fixed_credits", "credits_per_execution": 5},
  "checksum": "64 hex", "status": "pending_review" | "approved" | "rejected" | "superseded",
  "effective_from": "…" | null, "effective_to": "…" | null,
  "submitted_by": "uuid" | null, "submitted_at": "…",
  "approved_by": "uuid" | null, "approved_at": "…" | null,
  "rejected_by": "uuid" | null, "rejected_at": "…" | null
}
Status Code When
404 pack_not_found The pack is unknown or not owned by the caller's tenant
409 pack_pricing_nothing_to_submit The active version carries no declaration and the pack has no approved price to withdraw, or the pack has no active version
409 pack_pricing_conflict A concurrent submission or decision won; retry

Developer Earnings (SaaS)

A developer tenant's records of the pack platform fee on its own packs (D-024 CR84, settlement spec §0.4.2). Read only; payouts are not yet available, and a share is a record, not a balance owed. Returns 404 while HUITZO_PACK_PRICING_ENABLED is off.

Method Path Purpose
GET /api/v1/developer/earnings?months=12 The caller's tenant's settled fee records, summed per pack it developed and per UTC calendar month, newest month first, over the last months UTC calendar months including the current one (default 12, 1–36; 422 outside). Totals cover the window only. 200

Access: role owner or admin of the developer tenant (403 otherwise). The read goes through pack_developer_earnings(), which reads the caller's own tenant and takes no tenant argument, so only the caller's own packs are ever returned. No paying tenant, user or instant finer than a month appears (execution pricing §8.3). A free listing books no fee record and never appears; a pack the tenant no longer owns keeps its pack_id with scope and name null.

# pseudocode — the response data
{
  "months": 12,
  "payouts_available": false,
  "payouts_notice": "Payouts are not yet available. …",
  "platform_fee_rate_bps": 1500,
  "totals": {"settled_executions": 12, "price_credits": 60,
             "fee_credits": 12, "developer_share_credits": 48},
  "packs": [
    {"pack_id": "uuid", "scope": "acme", "name": "claims",
     "settled_executions": 12, "price_credits": 60, "fee_credits": 12,
     "developer_share_credits": 48,
     "months": [{"month": "2026-10", "settled_executions": 12, "price_credits": 60,
                 "fee_credits": 12, "developer_share_credits": 48}]}
  ]
}

Catalog Pack Prices (SaaS)

The Hub's read of the approved per-execution price in force (D-024 CR84, execution pricing §8.2), for the priced listing copy. Returns 404 while HUITZO_PACK_PRICING_ENABLED is off, which the Hub renders as free execution.

Method Path Purpose
GET /api/v1/catalog/pack-prices?pack=@scope/name&pack=… The approved credits_per_execution in force now of each named pack. At most 100 pack values. 200 {items: [{pack, credits_per_execution}]}

Any authenticated caller. A pack is listed only when the caller can see it (packs RLS: public, unlisted, its own or granted), the caller's tenant does not own it (the owner pays no P) and an approved fixed_credits version is in force; every other pack is simply absent. Only the price is returned: never the pricing version, the owner or the fee split.

Status Code When
422 invalid_pack_ref A pack value is not @scope/name (details.pack)
422 too_many_pack_refs More than 100 pack values

Dashboards

Dashboard identity is scope-qualified. A dashboard is identified by the composite (scope, slug), unique together — never by slug alone. Two scopes may hold the same slug (@huitzo/field-service and @acme/field-service are distinct dashboards). Every resolve/serve route therefore carries the scope explicitly: GET /api/v1/dashboards/{scope}/{slug} and GET /api/v1/dashboards/{scope}/{slug}/bundle/..., where {scope} is the bare scope (no leading @, matching the scope field the list/get responses return). A publish under a new scope creates (or updates) that scope's own row and can never mutate a foreign scope's dashboard (ADR-025 Phase 1b, fixes #1135).

Register Dashboard

Create a new dashboard in the registry. Only users in developer mode can create dashboards.

POST /api/v1/dashboards
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "scope": "@acme",
  "name": "claims-dashboard",
  "description": "Claims management dashboard",
  "category": "business",
  "visibility": "organization"
}
Field Type Required Description
scope string Yes Organization scope with @ prefix (e.g., @acme). Stored with @; responses return scope without the prefix.
name string Yes Dashboard name (kebab-case, 3-50 chars)
description string No Short description (max 200 chars; see manifest spec)
category string No Category: business, analytics, productivity, etc.
visibility string No public, unlisted, organization, private (default: private)

Response:

{
  "data": {
    "id": "d-abc123",
    "scope": "acme",
    "name": "claims-dashboard",
    "slug": "claims-dashboard",
    "visibility": "organization",
    "created_at": "2026-03-13T10:00:00Z"
  }
}

Error Responses:

Code Error Description
403 Developer mode required Caller is not in developer mode
403 Scope mismatch Scope doesn't match caller's tenant or organization
403 publish_public_required visibility is public, unlisted or organization and the deployment licence lacks publish_public (Core editions). private is always allowed.
404 Dashboard not found Registering the first-party @credits/credits dashboard is refused unconditionally — the ADR-022 Ledger-A plugin it named was deleted by migration saas_0014, so the slug is reserved with no bundle behind it (see credits reference). Keyed on the scope-qualified identity, so a tenant that owns a credits scope is unaffected.
409 A dashboard with this slug already exists in scope '@{scope}' The (scope, slug) pair is already registered. The same slug under a different scope is not a conflict.

List Dashboards

Returns dashboards visible to the current user, pinned first, keyset-paginated. Filters by visibility and access grants. Excludes unlisted dashboards from list results — they are accessible only via direct slug lookup.

GET /api/v1/dashboards?limit=50&include_hidden=false&cursor={opaque}
Authorization: Bearer {token}
Query param Default Description
limit 50 (max 200) Page size
include_hidden false false = Home's view (hidden rows excluded); true = Explore's "All dashboards" view (includes the caller's own hidden rows)
cursor none Opaque composite cursor from a previous page's meta.next_cursor

Response:

{
  "data": [
    {
      "id": "d-abc123",
      "slug": "claims-dashboard",
      "name": "Claims Dashboard",
      "description": "Claims management dashboard",
      "version": "1.2.0",
      "entryPoint": "/api/v1/dashboards/acme/claims-dashboard/bundle/1.2.0/main.js",
      "minSdkVersion": "1.0.0",
      "scope": "acme",
      "category": "business",
      "visibility": "organization",
      "packDependencies": [
        { "scope": "@acme", "name": "claims-processor", "version": ">=2.0.0" }
      ],
      "listing": { "publisher": { "name": "Acme Inc." }, "...": "..." },
      "isPinned": false,
      "isHidden": false
    }
  ],
  "meta": {
    "next_cursor": "eyJiIjowLCJrIjoiMjAyNi0wMS0wMVQwMDowMDowMFoiLCJpIjoiLi4uIn0",
    "has_next": true,
    "limit": 50
  }
}

Each item carries its scope (bare, no @); build the scope-qualified resolve URL as /api/v1/dashboards/{scope}/{slug}. The entryPoint is already scope-qualified server-side, so clients import it verbatim. isPinned/isHidden are the calling user's own preference state, bulk-loaded for the page — never a per-row lookup. listing is the allow-listed Listing Snapshot Persistence projection, or null.

Visibility filtering: A dashboard is visible if it is public, owned by the caller's tenant, or has a DashboardAccessGrant for the caller's tenant (for organization visibility). Preference state (pin/hide) never widens or narrows this set — see Hub Personalization. A dashboard an operator has disabled (disabled_at IS NOT NULL, admin-console §5.5) is excluded platform-wide, including from the owning tenant's own listing.

Pagination: cursor is opaque (base64url-encoded, strictly validated) and orders pinned dashboards first, then everything else by recency, id as the final tie-break. Full cursor format and the ordering invariant: Hub Personalization § Pagination. A malformed cursor returns 400.


Get Dashboard by Scope and Slug

Returns a single dashboard's metadata and the active version's entry point URL. This is the primary endpoint Hub calls when a user navigates to /d/{scope}/{slug}.

{scope} is the bare scope (no leading @). Returns 404 (not 403) for dashboards the caller cannot access — and, because identity is scope-qualified, also 404 when the slug exists only under a different scope — to prevent information leakage about the existence of private dashboards. A dashboard an operator has disabled (admin-console §5.5) 404s the same way, for every tenant including the owner's.

GET /api/v1/dashboards/{scope}/{slug}
Authorization: Bearer {token}

Response:

{
  "data": {
    "id": "d-abc123",
    "slug": "claims-dashboard",
    "name": "Claims Dashboard",
    "description": "Claims management dashboard",
    "version": "1.2.0",
    "entryPoint": "/api/v1/dashboards/acme/claims-dashboard/bundle/1.2.0/main.js",
    "minSdkVersion": "1.0.0",
    "scope": "acme",
    "category": "business",
    "visibility": "organization",
    "packDependencies": [
      { "scope": "@acme", "name": "claims-processor", "version": ">=2.0.0" }
    ],
    "listing": { "publisher": { "name": "Acme Inc." }, "...": "..." }
  }
}

The entryPoint is a fully-qualified, scope-qualified URL path that Hub passes directly to import(). listing is the allow-listed Listing Snapshot Persistence projection of the active version's manifest.listing, or null when the manifest declared none.


Set Dashboard Preference

Sets the caller's own pin/hide state for one dashboard. {scope} is the bare scope (no leading @) — the same resolve shape as GET /{scope}/{slug}. PUT replaces the full preference state (idempotent — the same body sent twice converges to the same row and response), not a partial patch: an omitted field is false. The body accepts only is_pinned/is_hidden — an unrecognized field (including the response's own camelCase isPinned/isHidden sent back verbatim) returns 422, never a silently-applied default.

PUT /api/v1/dashboards/{scope}/{slug}/preference
Authorization: Bearer {token}
Content-Type: application/json

{ "is_pinned": true, "is_hidden": false }

Response:

{
  "data": {
    "dashboardId": "d-abc123",
    "isPinned": true,
    "isHidden": false,
    "pinnedAt": "2026-01-01T00:00:00Z"
  }
}

Access invariant: applies the exact same gate GET /{scope}/{slug} does (extension gating, then visibility/grants) before touching any preference row — a caller who cannot reach the dashboard gets the same 404 the read path gives, never a 403, never an existence leak, and no row is written. Preference state never confers access. Full invariant and rationale: Hub Personalization § Core Model.


Upload Dashboard Version

Uploads a new dashboard version as a gzipped tarball. Uses multipart form data. Only the dashboard owner can upload versions.

The target is resolved scope-explicitly by (scope, slug) — the caller names the exact scope, so a version can never be attached to another scope's dashboard even if a same-slug dashboard exists elsewhere (the #1135 cross-scope-corruption class). The owner check (owner_tenant_id == caller tenant) still applies on top.

POST /api/v1/dashboards/{scope}/{slug}/versions
Authorization: Bearer {token}
Content-Type: multipart/form-data

Form fields:

Field Type Description
bundle file Gzipped tarball (.tar.gz) containing main.js and optional assets
version string Semver version string (e.g., 1.2.0)

Response:

{
  "data": {
    "id": "dv-xyz789",
    "dashboard_id": "d-abc123",
    "version": "1.2.0",
    "entry_point": "main.js",
    "min_sdk_version": "1.0.0",
    "bundle_size_bytes": 867492,
    "is_active": true,
    "created_at": "2026-03-13T10:05:00Z"
  }
}

Error Responses:

Code Error Description
400 Entry point not found main.js missing from bundle
400 Invalid tarball format Cannot extract the uploaded file
400 Malformed huitzo-dashboard.json manifest huitzo-dashboard.json is present but is not valid JSON or is not a JSON object. An absent manifest remains valid for compatibility.
403 Not owner Only dashboard owner can upload
404 Dashboard not found (scope, slug) doesn't resolve — including a slug that exists only under a different scope (the #1135 case: a wrong/typo'd scope resolves to nothing, never a foreign row). Also returned unconditionally for the first-party @credits/credits dashboard, so no bundle can be published for it — the ADR-022 plugin was deleted by migration saas_0014 (see credits reference).
409 Version already exists The database version or permanent bundle path already exists. Existing content is never replaced or removed by an upload. A path with no matching row can remain after process termination between promotion and commit; operators must reconcile that exact path and database state before retrying.
413 Size limit exceeded Bundle exceeds 50 MB

Processing: The backend extracts and validates the tarball in a request-unique staging directory. A missing huitzo-dashboard.json keeps the current compatibility defaults; a present malformed or non-object manifest is rejected. After validation, the backend locks the resolved dashboard row, repeats owner and duplicate checks, deactivates prior versions, creates and flushes the new version row, atomically promotes the staged directory to the previously absent {HUITZO_DASHBOARDS_DIR}/{dashboard_id}/{version}/ path, and commits. The row lock serializes activation per dashboard, so a successful request leaves exactly one active version.

A confirmed extraction, database flush, promotion, or commit failure rolls back the database transaction and preserves the prior active row and bundle. Failure cleanup is confined to the unique staging directory and, only after this request successfully created it and rollback is confirmed, the promoted version directory; an existing database row or filesystem path is never overwritten or recursively removed. If a database connection fails while the commit result is unknown and rollback cannot be confirmed, the promoted path is retained for operator reconciliation because the database may have committed. Publication events remain best-effort after commit and cannot roll back or delete a committed version.


Dashboard Version History

The dashboard's version history, newest first, each with the pack version published together with it. The Hub listing page reads it (catalog listing).

GET /api/v1/dashboards/{scope}/{slug}/versions?limit=50&offset=0
Authorization: Bearer {token}

Every member of the owning tenant may read it; any other caller gets 404, as for a dashboard it cannot see. can_manage, limit and offset are as on List Pack Versions.

Response (200):

{
  "data": {
    "scope": "@acme",
    "slug": "reminders-board",
    "active_version": "0.3.0",
    "can_manage": true,
    "versions": [
      {
        "version": "0.3.0",
        "active": true,
        "published_at": "2026-11-20T15:04:05Z",
        "published_by": "[email protected]",
        "pack": {"pack_id": "a6ed4f8d-…", "scope": "@acme", "name": "reminders", "version": "0.3.0", "active": true},
        "changes": {"previous": "0.2.0", "commands": {"…": "…"}, "stored": {"…": "…"}}
      }
    ]
  },
  "meta": {"limit": 50, "offset": 0, "has_more": false}
}

pack is the pack version a Studio build published together with this dashboard version (build_publications), null for a dashboard version published alone, or when that pack version is not a publication (see List Pack Versions). changes is that pack version's changes from List Pack Versions (null without a pack): what an owner reads as "what changed" lives in the pack.

Activate Dashboard Version

Make an earlier version of a dashboard the active one again (#1607): the way back from a bad bundle without publishing forward.

POST /api/v1/dashboards/{scope}/{slug}/versions/{version}/activate
Authorization: Bearer {token}
Content-Type: application/json

{"expected_active_version": "0.3.0"}

Only an owner or admin of the owning tenant (an API key acts as member and is refused). A caller who cannot see the dashboard (another tenant's, not publicly listed) gets 404; another tenant's publicly listed dashboard answers 403. expected_active_version (optional, 1 to 20 characters) is the dashboard version the caller saw active; confirm_stored_fields and confirm_every_user_check (booleans, default false) are passed to the pack activation below.

  • The decision is taken under the row locks. When a pack version is paired with the target, the pack row and then the dashboard row are locked (the order every go-back and publish takes them in) before whether that pack version is active is read again (the pairing itself is fixed when the dashboard version is published); only then is the request routed below. A publish of the pack that lands first is waited for and seen, so the dashboard never goes back alone beside a pack it was not published with. The pairing here counts every pack version, publications or not: a target paired with a pack version that is not a publication (awaiting its dashboard leg, or a release whose cleanup is pending) goes through the pack go-back and is refused there (409 publish_in_progress, 409 version_not_installed), never flipped alone.
  • Published with a pack. When a Studio build published the target together with a pack version (and that pack version's own paired dashboard version is the target), the two go back as one: the request is Activate Pack Version for that pack version, with expected_dashboard_version = expected_active_version, and answers as it does (its restore, its data-safety stops, its refusals). When that pack version is already the active one, only the dashboard is flipped, as below.
  • Published alone. Under the dashboard row lock, in one transaction: the target must exist and not be active, the active version must be expected_active_version when sent, and the target's bundle directory must still exist; then the target becomes the only active version.

Response (200): {"data": {"scope", "slug", "version", "from_version", "pack"}}, pack being the pack activation's answer (data of Activate Pack Version) or null when the dashboard went back alone. from_version is the dashboard version active under the row locks.

Status error.code = details.reason Condition
403 not_permitted The caller is a member of the owning tenant but not an owner or admin, or the dashboard is another tenant's publicly listed one
404 version_not_found No such dashboard, no such version of it, or one the caller cannot see (another tenant's, not publicly listed; an extension dashboard whose extension is off answers 404 with no code, as the other dashboard routes do)
409 version_already_active The version is already the active one
409 active_version_changed expected_active_version was sent and another version is active now
409 bundle_missing The version's bundle is no longer on this Hub
any (pack codes) Published with a pack: every code of Activate Pack Version

The activation writes one structured log line (dashboard version activated tenant=… actor=… dashboard=… from=… to=… pack=…).

Dashboard Listing History

Returns every published version's marketplace-listing snapshot (docs/architecture/database-schema.md#listing-snapshot-persistence), newest first, up to limit. Applies Get Dashboard by Scope and Slug's exact two-part access gate (extension gating, then the grant-aware access check) — never exposes a dashboard more broadly than the detail endpoint already does.

GET /api/v1/dashboards/{scope}/{slug}/listing-history?limit=50
Authorization: Bearer {token}

Query parameters:

Parameter Type Default Description
limit int 50 Max rows returned (1-200)

Response (200): same shape as Pack Listing History — an array of {version, is_active, published_at, listing_updated_at, listing, published_by_user_id?, listing_updated_by_user_id?}, with the two provenance fields present only for the owning tenant.

Error Responses:

Status Condition
404 Dashboard not found, not accessible, or extension-gated out
500 Database error

Update Dashboard Listing

Replaces the active version's listing snapshot in place — no bundle re-upload, no new version row. Owner-only; requires developer mode and the T-051 publisher-terms gate, same as Upload Dashboard Version. Dark by default (HUITZO_LISTING_METADATA_UPDATE_ENABLED=false): 404s exactly like a nonexistent route until an operator turns the flag on.

PATCH /api/v1/dashboards/{scope}/{slug}/listing
Authorization: Bearer {token}
Content-Type: application/json

{ "listing": { "publisher": { "name": "Acme Inc." } } }

Response (200):

{
  "data": {
    "id": "d-abc123",
    "version": "1.2.0",
    "listing": { "publisher": { "name": "Acme Inc." } },
    "listingUpdatedAt": "2026-08-20T10:00:00Z"
  }
}

Error Responses:

Status Condition
403 User is not in developer mode
403 Dashboard is not owned by user's tenant
404 Flag is off, dashboard not found, or extension-gated out
400 listing fails ListingSection validation
409 Dashboard has no active version, or a concurrent version upload deactivated the targeted version between resolve and write (retry against the new active version)
413 listing payload exceeds 64 KB
500 Database error

Side Effects: Stamps listing_updated_by_user_id / listing_updated_at on the active version row (never published_by_user_id, which stays the original publisher). Emits a dashboard_listing_updated tracked event.


Serve Bundle Files

Serves individual files from a dashboard bundle. Called by the browser when Hub executes import(entryPointUrl).

GET /api/v1/dashboards/{scope}/{slug}/bundle/{version}/{path:path}
Authorization: Bearer <jwt>

{scope} is the bare scope (no @), matching the scope-qualified entryPoint the list/get responses return. Hub's service worker matches this two-segment {scope}/{slug} shape to inject the JWT.

Response headers:

Header Value Why
Content-Type MIME type based on extension Browser needs correct type for import()
Cache-Control private, max-age=31536000, immutable Bundle files are immutable per version

Error Responses:

Code Error Description
401 Missing authorization No JWT provided
404 Dashboard not found (scope, slug) doesn't exist, caller lacks access, or an operator has disabled the dashboard (admin-console §5.5)
404 File not found Requested path doesn't exist in bundle

Authentication: This endpoint uses standard JWT auth. The browser's native import() cannot send custom headers, so Hub's service worker intercepts bundle requests and injects the JWT. See Dashboard Loading Architecture for details.

Security: Path traversal is prevented by resolving the path within the bundle directory and rejecting paths that escape it.


Grant Dashboard Access

Grants organization-visibility dashboard access to specific tenants. Only an owner or admin of the owning tenant can grant access. An API key always acts as member, so it cannot grant.

POST /api/v1/dashboards/{dashboard_id}/grant
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "tenant_ids": ["tenant-abc", "tenant-def"]
}

Response:

{
  "data": {
    "granted": 2,
    "dashboard_id": "d-abc123"
  }
}

Error Responses:

Code Error Description
400 Wrong visibility Can only grant access to organization-visibility dashboards
403 Not owner Only dashboard owner can grant access
403 Only a tenant owner or admin can grant access Caller's role in the owning tenant is not owner or admin (an API key always counts as member)
404 Not found Dashboard doesn't exist

Delete Dashboard

Remove a dashboard and all its versions and access grants. Only an owner or admin of the owning tenant, in developer mode, can delete a dashboard. An API key always acts as member, so it cannot delete.

DELETE /api/v1/dashboards/{dashboard_id}
Authorization: Bearer {token}

Response (200):

{
  "data": {
    "message": "Dashboard deleted successfully"
  }
}

Error Responses:

Code Error Description
403 Developer mode required User is not in developer mode
403 Only a tenant owner or admin can delete dashboards User's role in the owning tenant is not owner or admin (an API key always counts as member)
404 Not found Dashboard does not exist or is not owned by user's tenant
500 Database error Internal database failure

Side Effects:

  • All dashboard versions and access grants are cascade-deleted
  • Dashboard bundle files are removed from disk
  • A dashboard_deleted event is emitted with dashboard_id, scope, name, and versions_removed

Dashboard Visibility Levels

Dashboard access control mirrors the Pack access control model with four visibility levels:

Level Discovery Access Use Case
public Listed in Explore, searchable No grant required Open source, community dashboards
unlisted Hidden from search and browse Accessible via direct slug Beta testing, invitation-only
organization Visible to granted tenants Requires DashboardAccessGrant Agency distribution, enterprise
private Owner only Owner tenant only Internal tools, development

Access control is enforced at every layer:

Level Enforcement
Discovery GET /api/v1/dashboards filters by visibility + grants
Metadata GET /api/v1/dashboards/{scope}/{slug} returns 404 if caller lacks access
Bundle serving GET /api/v1/dashboards/{scope}/{slug}/bundle/... requires JWT and checks the same access rules

Storage

Save Data

Save data to pack storage.

PUT /api/v1/storage/{key}
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "data": {
    "title": "My Note",
    "content": "Hello world"
  },
  "ttl": 86400
}

Response:

{
  "data": {
    "key": "notes:note_123",
    "created": true,
    "expires_at": "2025-01-23T10:30:00Z"
  }
}

Get Data

GET /api/v1/storage/{key}
Authorization: Bearer {token}

Response:

{
  "data": {
    "key": "notes:note_123",
    "value": {
      "title": "My Note",
      "content": "Hello world"
    },
    "created_at": "2025-01-22T10:30:00Z",
    "expires_at": "2025-01-23T10:30:00Z"
  }
}

Delete Data

DELETE /api/v1/storage/{key}
Authorization: Bearer {token}

Response:

{
  "data": {
    "deleted": true
  }
}

List Keys

GET /api/v1/storage
Authorization: Bearer {token}

Query Parameters:

Parameter Type Default Description
prefix string - Filter by key prefix
limit integer 100 Max keys to return

Response:

{
  "data": {
    "keys": [
      "notes:note_123",
      "notes:note_456",
      "settings:preferences"
    ],
    "total": 3
  }
}

Files

Download a File

Streams a file written through ctx.files. This is the only route that serves platform file storage — see File Storage for the pack and dashboard developer guide.

GET /api/v1/files/{path:path}
Authorization: Bearer {token}

Authentication: Session or API key — the same auth as every other /api/v1 route. API-key principals must additionally carry the files:read scope (403 without it); session principals need no scope. This endpoint serves no unauthenticated downloads.

Tenant resolution: The storage backend is resolved via get_file_backend(tenant_id) from the authenticated caller's tenant only. The {path} segment is the relative path pack code passed to ctx.files; the tenant prefix is applied server-side from the caller's identity, so a URL can never name another tenant's files, no matter what path it carries.

Response: The file body is streamed with the correct Content-Type for the file, plus Content-Disposition: attachment and X-Content-Type-Options: nosniff on every download. Tenant/pack-written bytes are never rendered inline in the app origin (an attacker-planted .html/.svg downloads instead of executing as stored XSS). fetch() → blob consumers are unaffected — Content-Disposition applies only to browser navigations.

Caching: Every download carries Cache-Control: private, no-store. The URL deliberately names no tenant (tenant resolution comes from the auth principal), so the same path serves different bytes to different tenants — a shared cache (CDN, reverse proxy) that stored a response would serve one tenant's bytes to another. no-store forbids any cache, shared or private, from storing the response. Error responses (the 404 and the 403) carry the same header — 404s are heuristically cacheable by default (RFC 9111), so a cached one could be replayed to a different tenant whose file exists at that path, or mask a freshly written file.

Error Responses:

Code Error Description
401 Missing or invalid credentials No session or API key provided (emitted by the auth middleware)
403 API key is missing the 'files:read' scope required to download files. Create a new key with this scope in Settings → API Keys. API key authenticated but lacks the files:read scope
404 File not found Missing file or path-traversal attempt — indistinguishable by design (no existence oracle)
### Command Schedules

Per-user recurring command execution (ADR-030). A schedule binds a pack command to a cron expression evaluated in the caller's IANA timezone; the platform beat fires it under the caller's own identity, tenant, secrets, and quota.

Session auth only. All four endpoints refuse API-key principals with 403 — a schedule is a durable recurring execution grant that must not outlive a revocable key. user_id is always the authenticated principal (never taken from the body); another user's schedule id is invisible and returns a uniform 404 (no existence leak).

Create Schedule

Subscribe the caller to a recurring command run.

POST /api/v1/schedules
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "namespace": "@acme/audio-briefings",
  "command": "generate-briefing",
  "args": { "voice": "kai" },
  "cron": "0 7 * * *",
  "timezone": "America/New_York"
}

Response: 201 Created

{
  "data": {
    "id": "b3d9f0e2-7c4a-4e1b-9f2a-1c6d8e0a5b47",
    "namespace": "@acme/audio-briefings",
    "command": "generate-briefing",
    "args": { "voice": "kai" },
    "cron": "0 7 * * *",
    "timezone": "America/New_York",
    "enabled": true,
    "last_dispatched_minute": null,
    "created_at": "2026-07-20T10:00:00Z"
  }
}

Validation (all failures return 422):

Rule Detail
Cron format Exactly 5 fields, croniter-valid
Minimum interval Consecutive fire times must be ≥ 15 minutes apart (sampled with croniter)
Timezone Valid IANA zone (e.g. America/New_York)
Args size JSON-serializable, ≤ 16 KB encoded
Per-user cap ≤ 20 schedules per user (counted under a per-user advisory lock)
Target command {namespace}/{command} must exist and be executable by the caller (ADR-025 visibility/grant + pack kill-switch)

Errors:

Code Error Description
403 API keys cannot manage command schedules API-key principal; session auth required
422 invalid cron expression: ... (expected 5 fields) Cron is not exactly 5 croniter-valid fields
422 invalid cron expression: ... Cron parses as 5 fields but cannot be iterated (e.g. can never fire)
422 cron fires more often than every 15 minutes Cron violates the 15-minute floor
422 invalid IANA timezone: ... Unknown or malformed timezone
422 args exceed the 16384-byte limit Args payload larger than 16 KB
422 schedule limit reached (20 per user) Per-user cap reached
422 invalid command namespace: ... Namespace is malformed (not @scope/pack)
422 Command's pack is disabled Target pack has been kill-switched (disabled_at set)
422 Command not found or not accessible Target command invisible or not executable for the caller
409 license_limit_exceeded The deployment is at the licence max_schedules ceiling (details.scope = "deployment"; counted under the license:max_schedules advisory lock)
503 license_count_unavailable A licence ceiling applies and the deployment schedule count could not be read

List Schedules

List the caller's own schedules, newest first.

GET /api/v1/schedules
Authorization: Bearer {token}

Response:

{
  "data": [
    {
      "id": "b3d9f0e2-7c4a-4e1b-9f2a-1c6d8e0a5b47",
      "namespace": "@acme/audio-briefings",
      "command": "generate-briefing",
      "args": { "voice": "kai" },
      "cron": "0 7 * * *",
      "timezone": "America/New_York",
      "enabled": true,
      "last_dispatched_minute": "20260720T0700",
      "created_at": "2026-07-20T10:00:00Z"
    }
  ]
}

Errors:

Code Error Description
401 — Missing or invalid session token
403 API keys cannot manage command schedules API-key principal; session auth required

Update Schedule

Update cron, args, and/or enabled on one of the caller's own schedules. Only these three fields are mutable — the binding (namespace, command, timezone) is immutable, so changing a schedule's target or wall clock is a delete-and-recreate, not an edit. A new cron re-runs the full validation (15-minute floor included).

PATCH /api/v1/schedules/{id}
Authorization: Bearer {token}
Content-Type: application/json

Request: (any subset of the mutable fields)

{
  "cron": "30 8 * * 1-5",
  "args": { "voice": "ana" },
  "enabled": false
}

Response:

{
  "data": {
    "id": "b3d9f0e2-7c4a-4e1b-9f2a-1c6d8e0a5b47",
    "namespace": "@acme/audio-briefings",
    "command": "generate-briefing",
    "args": { "voice": "ana" },
    "cron": "30 8 * * 1-5",
    "timezone": "America/New_York",
    "enabled": false,
    "last_dispatched_minute": "20260720T0700",
    "created_at": "2026-07-20T10:00:00Z"
  }
}

Errors:

Code Error Description
403 API keys cannot manage command schedules API-key principal; session auth required
404 Schedule not found Missing, or owned by another user/tenant (uniform — no existence leak)
422 invalid cron expression: ... (expected 5 fields) New cron is not exactly 5 croniter-valid fields
422 invalid cron expression: ... New cron parses as 5 fields but cannot be iterated
422 cron fires more often than every 15 minutes New cron violates the 15-minute floor
422 args exceed the 16384-byte limit New args payload larger than 16 KB
409 license_limit_exceeded enabled: true on a disabled schedule would pass the licence max_schedules ceiling
503 license_count_unavailable A licence ceiling applies and the deployment schedule count could not be read

Delete Schedule

Delete one of the caller's own schedules.

DELETE /api/v1/schedules/{id}
Authorization: Bearer {token}

Response:

{
  "data": {
    "id": "b3d9f0e2-7c4a-4e1b-9f2a-1c6d8e0a5b47",
    "deleted": true
  }
}

Errors:

Code Error Description
403 API keys cannot manage command schedules API-key principal; session auth required
404 Schedule not found Missing, or owned by another user/tenant (uniform — no existence leak)

Users

Get Current User

GET /api/v1/auth/me
Authorization: Bearer {token}

Response:

{
  "data": {
    "id": "usr_abc123",
    "email": "[email protected]",
    "name": "John Doe",
    "role": "admin",
    "developerMode": true,
    "tenantSlug": "john-doe",
    "createdAt": "2025-01-01T00:00:00Z"
  }
}

Check Namespace

GET /api/v1/namespaces/{namespace}/check
Authorization: Bearer {token}

Checks whether a namespace is available for the current user. A namespace is "available" if the user owns it (either as their personal tenant slug or as a member of an organization with that slug).

Response (owned — personal):

{
  "data": {
    "available": true,
    "owner": "personal"
  }
}

Response (owned — organization):

{
  "data": {
    "available": true,
    "owner": "organization"
  }
}

Response (taken by someone else):

{
  "data": {
    "available": false,
    "error": "This namespace is already in use"
  }
}

Response (unclaimed — no tenant or org exists with this slug):

{
  "data": {
    "available": false,
    "error": "Namespace not found. Create an organization with this slug first, or use your personal namespace."
  }
}

Update Current User

PATCH /api/v1/users/me
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "name": "Jane Doe"
}

Setup (First-Run)

The setup endpoints power the first-run experience of a freshly-installed, self-hosted deployment whose database is still empty. Both are reachable before any user or license exists — a completed install must be inspectable and bootstrappable precisely when nobody can log in yet. They are exempt from the user-session auth check and from the license 402 hard-gate. Once the first admin exists, the bootstrap path is permanently closed (fail-closed).

Scope is intentionally minimal: admin bootstrap + readiness only. There is no integration-setup wizard and no pack install in first-run.

Get Setup Status

GET /api/v1/setup/status

Unauthenticated, side-effect-free. Reports whether the deployment still needs its first admin, the deployment's license state, its deployment ID, whether it is in setup mode, and a per-component readiness checklist. Reveals only deployment-level posture — no tenant, user, or secret data. The deployment ID is an identifier, not a secret: the operator reads it here to request a license (ADR-008 setup mode).

Response (conceptual shape):

// pseudocode — illustrative shape, not copy-paste
{
  "data": {
    "needs_bootstrap": true,        // true while no users exist
    "ready": false,                  // true only when every check below passed
    "deployment_id": "hzd_01JA…",    // generated at first boot; null if not resolved
    "setup_mode": true,              // no usable license for this ID: only setup routes serve
    "license": {                     // null if the license service is unavailable
      "state": "valid",              // valid | grace | invalid (ADR-008)
      "tier": "preview",             // the edition: preview | licensed | enterprise
      "purpose": "demo_poc",         // ADR-008 D8: demo_poc | pilot | nfr | paid; null on enterprise, in setup mode, or when invalid
      "valid_until": "…",
      "grace_expires": null,
      "detail": "…"                  // in setup mode: the reason only, never a license field
    },
    "checks": [                      // per-component readiness rows
      { "name": "database",   "ok": true,  "detail": "reachable" },
      { "name": "migrations", "ok": true,  "detail": "at head …" },
      { "name": "redis",      "ok": true,  "detail": "reachable" },
      { "name": "beat",       "ok": true,  "detail": "last tick 12 s ago" },
      { "name": "license",    "ok": true,  "detail": "…" },
      { "name": "storage",    "ok": true,  "detail": "writable: …" }
    ]
  }
}

The migrations row compares the applied Alembic revision against the schema head shipped in the image; an ok: false here means alembic upgrade head has not run. The beat row is ok while Celery beat's heartbeat in Redis is no older than 120 s (Celery beat); a deployment without a beat process reports ready: false. The license row is ok for valid or grace, reusing the same license layer as GET /api/v1/license/status (no re-validation). See Checking license status.

Bootstrap First Admin

POST /api/v1/setup/bootstrap-admin
Content-Type: application/json

Creates the very first admin user (and its workspace) — and only when the users table is empty. This is the classic first-run pattern and is security-critical: it mints an admin with no prior authentication, so it MUST be impossible to use as a backdoor on a running system.

Request (conceptual):

// pseudocode
{
  "email": "[email protected]",
  "password": "…",        // 8–72 chars (bcrypt-bounded), same policy as change-password
  "slug": "workspace",     // optional; valid non-reserved slug; renameable later
  "setup_token": "…"       // the one-time setup token from the license-data volume
}

Setup token. The backend writes a one-time token at first boot to setup-token on the huitzo-license-data volume, readable only from the host (docker compose exec backend cat /app/license-data/setup-token). No API returns it, and it is deleted once the first admin exists. A missing, short or wrong token gets 403 setup_token_invalid; wrong tokens are counted per client and across the deployment, and past the limit get 429 setup_token_rate_limited. The correct token always succeeds, even past the limit (ADR-008 D3).

Fail-closed contract: the "zero users" check and the create are made atomic by a transaction-scoped Postgres advisory lock — concurrent callers serialize, the first wins, and every subsequent caller (or any call once any user exists) returns 409 with error code setup_already_completed. The users.email unique constraint is the database-level backstop. On success the response is 201 with the new admin and an initial session (access + refresh tokens), mirroring the register flow.

Status Meaning
201 First admin created; tokens issued.
403 setup_token_invalid: the setup token is missing or wrong.
409 Setup already completed (a user exists) or workspace name taken.
422 Invalid email / password policy / slug.
429 setup_token_rate_limited: too many wrong setup tokens; retry later or use the correct token.

Response on 201 (conceptual shape):

// pseudocode — illustrative shape, not copy-paste
{
  "data": {
    "user": {
      "id": "…",
      "email": "[email protected]",
      "role": "admin",             // the first user is the deployment admin
      "tenantId": "…",             // the workspace just created for them
      "createdAt": "…"
    },
    "tokens": {
      "accessToken": "…",          // use immediately as a Bearer token
      "refreshToken": "…"          // exchange at /api/v1/auth/refresh
    }
  }
}

Field names in this body are camelCase (the authenticated-session convention), matching the register flow. A scripted installer can read data.tokens.accessToken to continue setup without a separate login.


Platform

Toolchain

The toolchain versions this Hub tells clients to build against. The CLI reads it to choose the @huitzo/dashboard-sdk-react range it scaffolds and checks. Any authenticated principal (session JWT or API key of any scope); the answer is the same for every tenant. Platform admins change the values from Admin Settings, "Platform Settings" in the admin navigation (admin console §5.10).

GET /api/v1/platform/toolchain
Authorization: Bearer {token}

Response (200): the bare object, not the {data} envelope.

{
  "dashboard_sdk_react": "^7.0.0",
  "source": "default",
  "updated_at": null
}
Field Meaning
dashboard_sdk_react An npm semver range
source "default" (the value this Hub release ships) or "admin" (set by a platform admin)
updated_at ISO-8601 time the admin value was set, or null while source is "default"

Additive-only: new keys may appear; clients ignore keys they do not know. 401 without credentials. Clients must check dashboard_sdk_react against the range grammar before using it. The CLI uses its bundled default and prints a notice when the value fails that check, on any non-200 answer (including 404 from a Hub older than this endpoint and 402 when the licence stops the Hub), and on a timeout.


Health

Health Check

GET /health

Response:

{
  "status": "healthy",
  "version": "2.0.0",
  "services": {
    "database": "healthy",
    "redis": "healthy",
    "worker": "healthy"
  },
  "timestamp": "2025-01-22T10:30:00Z"
}

Coupons

Core coupons (ADR-042). The routes are unconditional: since the access-code fold (D-024 CR78) coupons are the only admission and invite primitive (D14, D15). A coupon carries one or more capabilities (D5): Core's account.create, tenant.join{role} and tenant.create{name?}, plus any capability a mounted extension registers through coupon_handlers(). The raw code is 26 base32 characters shown once, in the mint response, in groups of four; only its SHA-256 hash and a four-character prefix are stored. No response, audit row or log line carries the raw code after mint.

Mint a coupon (staff)

POST /api/v1/admin/coupons
Authorization: Bearer {token}
Content-Type: application/json

Platform staff with role admin or owner, a token issued in the last 15 minutes (401 admin_reauth_required otherwise). Runs under the coupon_admin RLS context and writes one admin_audit_log row (coupon_minted, actor = the staff user).

{
  "capabilities": [
    {"capability": "tenant.join", "params": {"role": "member"}}
  ],
  "target_tenant_id": "6f1c…",
  "max_redemptions": 1,
  "expires_in_days": 14,
  "per_user_limit": null,
  "per_tenant_limit": null,
  "bound_email": "[email protected]",
  "bound_email_domain": null
}
Rule Refusal
A capability that is neither Core nor registered by a mounted extension 422 coupon_capability_unavailable
An extension handler's validate refuses the params 422 coupon_capability_invalid
Bad Core params: tenant.join without a landing tenant (target_tenant_id or a bundled tenant.create), tenant.create without tenant.join{role: owner}, with max_redemptions above 1 or with a target_tenant_id 422 coupon_capability_invalid

max_total_credits is the sum of each handler's reported per-redemption credit exposure times max_redemptions. A product above 2,147,483,647 is 422 coupon_capability_invalid. A coupon with any credit exposure and no per_user_limit gets per_user_limit: 1, so a retried redeem cannot apply it twice; staff may set a higher limit, for example to let one person redeem the code once per workspace they administer. A coupon with no credit exposure and no per_user_limit keeps null (no per-user limit). The response and the list carry the stored value. Above 5,000 the coupon is minted unredeemable (status: pending_approval) until a different staff user approves it.

Response (201):

{
  "data": {
    "code": "K7Q2-M4XA-…",
    "coupon": {"id": "…", "code_prefix": "K7Q2", "status": "active", "needs_approval": false, "…": "…"}
  }
}

List, approve and revoke (staff)

GET  /api/v1/admin/coupons?cursor=&limit=
POST /api/v1/admin/coupons/{coupon_id}/approve
POST /api/v1/admin/coupons/{coupon_id}/revoke
GET  /api/v1/admin/coupons/{coupon_id}/redemptions?cursor=&limit=

Same staff gates as mint. The lists are newest first; cursor is the opaque meta.next_cursor of the previous page (keyset on timestamp then id, so rows sharing a timestamp are never skipped; a malformed cursor is 400). The lists read through the '__admin__' sentinel and include tenant-issued coupons. Approve runs under coupon_admin: 403 coupon_approver_is_creator when the caller minted the coupon, 409 coupon_approval_not_required at or below 5,000 credits, 409 coupon_already_approved, 409 coupon_revoked. Revoke is idempotent. A platform coupon is revoked under coupon_admin; a tenant-issued coupon under its issuing tenant's own scope, so the tenant's owner sees it revoked. Approve and revoke each write one admin_audit_log row (coupon_approved, coupon_revoked).

Tenant invites as coupons

POST /api/v1/tenant/coupons
GET  /api/v1/tenant/coupons?cursor=&limit=
POST /api/v1/tenant/coupons/{coupon_id}/revoke

Owner or admin of the acting tenant, with step-up auth; API keys get 403. The request body is the staff body without target_tenant_id and bound_email_domain: the coupon always lands on the acting tenant. A tenant coupon carries tenant.join and must set bound_email; it may add account.create beside it when max_redemptions is 1. Owners mint any role, admins member only. Any other capability (credits.*, plan.*, tenant.create) is 403 coupon_capability_forbidden. The seat budget and the membership admission check run at mint as advisory checks (409). A tenant mint or revoke is recorded on the coupons row (created_by, revoked_by, revoked_at), never in admin_audit_log.

Redeem a coupon

POST /api/v1/coupons/redeem
Authorization: Bearer {token}
Content-Type: application/json

{"code": "K7Q2-M4XA-…", "landing_tenant_id": "…"}
Field Required Meaning
code yes The coupon code
landing_tenant_id no The workspace to apply the coupon to. Omitted or null, it is the workspace the caller is acting in. Used only when the coupon neither creates a workspace nor carries a target_tenant_id; the caller must be an owner or admin of it. A malformed id is 422

Any signed-in user; API keys get 403. The code is case- and separator-insensitive. Limits (D9): 5 calls per client IP per minute and 10 per user per hour (429), and an hourly platform breaker (503 coupon_redeem_at_capacity). They fail closed: a Redis outage is 503 rate_limiter_unavailable.

The redemption is one database transaction (D6): it locks the coupon, checks its state, bindings and limits, records the redemption, then applies each capability in the landing tenant: tenant.create, then tenant.join (tenant row lock, seat gate, membership admission check), then extension handlers. Any refusal or error rolls everything back. account.create is inert here (it is the registration credential, redeemed at /auth/register); a coupon with nothing else to apply is refused.

With HUITZO_COUPON_CREDITS_ENABLED on (default false), the SaaS extension registers credits.grant{amount, expiry_days} (staff mint only): the redemption writes one promotional source='coupon' lot and one ledger grant entry on the landing tenant's wallet, and outcomes carries "credits.grant": "applied" (Credits: coupon credits).

With the same flag on, it also registers plan.assign{plan_id, months} (staff mint only, with a target_tenant_id or a bundled tenant.create): the redemption gives the team landing tenant a Team-plan trial with no invoice, opens its first allowance period and schedules the return to payg at the trial end; outcomes carries "plan.assign": "applied" (billing: Team trials).

Response (200):

{
  "data": {
    "redemption_id": "…",
    "landing_tenant_id": "…",
    "landing_tenant_name": "Acme",
    "joined_tenant_id": "…",
    "created_tenant_id": null,
    "outcomes": {"tenant.join": "applied"}
  }
}

Joining is never switching: the caller's acting tenant is unchanged, and the client offers an explicit switch to joined_tenant_id.

landing_tenant_id and landing_tenant_name are the workspace every capability applied to: the tenant the coupon created, else its target_tenant_id, else the requested workspace (the request's landing_tenant_id, or the acting workspace). A credits.grant coupon with no target therefore funds the workspace the caller is acting in, or the one they named. There is no fallback to the home workspace: a caller who is not an owner or admin of the requested workspace gets the uniform refusal. A coupon's own target or created workspace wins over the request, so the client names the landing workspace and says when it is not the acting one.

Uniform refusal (400). Unknown, expired, exhausted, revoked or unapproved codes, a wrong email or domain, a requested workspace the caller does not own or administer, a per-tenant limit, a full seat budget, an existing membership, a refused admission, a handler refusal and a capability whose handler is no longer registered all return the same body:

{"success": false, "error": {"message": "This coupon code is not valid", "details": {"code": "coupon_invalid"}}}

Already redeemed (400). The one refusal with its own code (D6): the caller has already redeemed this coupon as many times as its per_user_limit allows.

{"success": false, "error": {"message": "You have already used this coupon code as many times as one person can", "details": {"code": "coupon_already_redeemed"}}}

It is answered only when the coupon is still redeemable, the caller matches its bindings and the requested workspace is one they may land in; a revoked, expired or exhausted coupon is coupon_invalid for a caller who redeemed it too. Nothing is written, and the call counts against the same limits as any other attempt.

The reason goes to the coupon_redeem_refused log event (reason, coupon_id when a coupon was resolved, user_id, requested_landing_tenant_id; never the code). A seat or admission count that cannot run is 503; any other error is 500. A successful redemption is recorded as its coupon_redemptions row plus a structured log, never in admin_audit_log, so a redeemer can always delete their account.

Coupon delivery email

A coupon minted with bound_email (staff or tenant) is also emailed to that address after the mint commits. The email replaces the two invite emails retired by the invite fold (D-024 CR77).

Coupon Link in the email
Carries account.create /register?coupon=<code>: the recipient registers with it
No account.create /redeem?code=<code>: the recipient signs in and redeems it

When the coupon lands on a tenant (target_tenant_id), the email names that tenant. Delivery is best effort: the mint response is unchanged, a broker outage is logged and swallowed, and the minter can still share the code from the response. The worker task (huitzo.send_coupon_email) retries, then dead-letters to the admin Email Queue; the raw code is never logged or stored in the dead-letter row. With no email server configured the mint still succeeds. HUITZO_SENDGRID_TEMPLATE_COUPON selects a SendGrid dynamic template; unset, the worker sends a plain text and HTML body.

Folded invites

Core migration 0052 folded every outstanding staff invite (pending_invite) and tenant invite (tenant_invites) into a coupon whose hash is the invite token's hash (ADR-042 D3). The token in an invite email sent before the fold is therefore a valid code: it registers through coupon_code at /auth/register or redeems at /coupons/redeem. The dashboard forwards /register?invite=<token> to /register?coupon=<token>; /invite/accept is no longer a route (removed after the D-024 cutover, 2026-10-08). POST /auth/register/invite, POST /auth/invites/accept, /api/v1/admin/invites, /api/v1/tenant/invites and POST /api/v1/admin/tenants/{tenant_id}/invites no longer exist.

Invite Coupon
Staff invite, no tenant Platform coupon: account.create
Staff invite bound to a tenant Platform coupon: account.create + tenant.join{role}, target_tenant_id = the invite tenant
Tenant invite Tenant-issued coupon: account.create + tenant.join{role}

Every folded coupon has code_prefix invite, bound_email set to the invitee, max_redemptions 1 and the invite's own expires_at. Redeemed, revoked and expired invites were not copied.


Access codes and paid registration (removed)

The access-code fold (D-024 CR78, ADR-042 D15) voided every legacy access code and deleted the surface with it. /api/v1/access-codes (generate, validate, list, deactivate), /api/v1/admin/access-codes, POST /api/v1/admin/users/{id}/access-codes, the paid-registration Checkout (/api/v1/registration/checkout, its session-status poll and POST /api/v1/registration/webhook) and HUITZO_STRIPE_WEBHOOK_SECRET_REGISTRATION no longer exist. The access_codes and founding_member_slots tables and saas_subscriptions.access_code_id are dropped (SaaS migration saas_0035). A staff-minted coupon carrying account.create (Coupons) is the only admission credential; see Register.


Billing

Get Billing Status

The caller's personal billing facts: it reports the caller's subscription row in the acting tenant (tenant wallet). There is no tier: D-024 CR27 deleted the personal membership tier (ADR-041 C7). The tenant's plan is in GET /api/v1/billing/usage.

GET /api/v1/billing/status
Authorization: Bearer {token}

Response:

{
  "data": {
    "has_billing_account": true
  }
}

has_billing_account is true when the caller's row carries a Stripe customer, the precondition of POST /api/v1/billing/portal.


Create Checkout Session / Change Plan (removed)

POST /api/v1/billing/checkout and POST /api/v1/billing/change-plan were removed by migration saas_0014 (owner directive, 2026-08-24) with the rest of the paid-tier lifecycle. There is no self-serve tier purchase or switch. The public GET /api/v1/billing/plans tier ladder was deleted with the tiers themselves by D-024 CR27 (ADR-041 C7). A member with an existing subscription manages or cancels it through Create Portal Session; to buy credits, use the wallet top-up.


Get Usage

Current-period usage vs plan allowance for the authenticated member. Read-only and credits-dark-safe. Each metric reports current and limit (null ⇒ no cap).

GET /api/v1/billing/usage
Authorization: Bearer {token}

Response:

{
  "data": {
    "tier": "payg",
    "usage": {
      "commands_last_30d": { "current": 142, "limit": null },
      "seats": { "current": 3, "limit": 5, "source": "plan", "staff_limit": 4, "plan_limit": 5 },
      "packs": { "current": 7, "limit": null }
    }
  }
}

usage.seats is the seat limit in force (ADR-041 D14, billing: seat limits):

Field Meaning
current Active members of the tenant
limit The limit in force: the live plan's seats_licensed while a plan is live, else the staff-set tenants.quotas.max_seats; the licence ceiling max_seats_per_tenant caps both. null is no limit
source The bound that set limit: license, plan, tenant_quota (the staff-set limit), default, or null when there is no limit
staff_limit The stored tenants.quotas.max_seats, or null
plan_limit The live plan's seats_licensed, or null when no plan is live

tier is the acting tenant's resolved plan: the plan id while the plan row governs (active or past_due; with HUITZO_TEAM_LIFECYCLE_V2_ENABLED on, also suspended and read_only), else payg (D-024 CR27 deleted the personal tier).

When the tenant has a tenant_subscriptions row in any status, the response also carries the plan block (ADR-027 B5, ADR-041 D1). It has no price and no allowance; the allowance is GET /api/v1/billing/allowance.

Field Meaning
plan id, name (null for an id outside the catalog), billing_mode, and the rate budget: pooled_requests_per_minute, commands_per_hour (-1 unlimited), per_member_rpm_ceiling
status, grace_expires_at The plan row's status and grace deadline
current_period_start, current_period_end, contract_term_end The anchors and the contract term (null when month-to-month)
seats_licensed, seat_drift The plan row's licensed seats, and whether the limit in force (usage.seats.limit) differs from them: the plan row is canceled, so the staff-set limit applies, or a licence ceiling binds
members[] Owner and admin callers only: user_id, email, commands_last_30d for each homed member

monthly_credit_allowance and the enterprise plan.monthly_pooled_credits keys were removed by migration saas_0014, not merely hidden — they described ADR-019/ADR-024's Ledger-A allowances, which no longer exist. A member's spendable credit balance is GET /api/v1/wallet.


Get Allowance

The acting tenant's plan allowance this period, in units (ADR-041 HTTP surfaces). Any member of the acting tenant may read it.

GET /api/v1/billing/allowance
Authorization: Bearer {token}

Response:

{
  "data": {
    "units_included": 2500,
    "units_used": 740,
    "units_remaining": 1760,
    "period_end": "2026-10-15T00:00:00+00:00"
  }
}

The period is the one settlement draws: the plan is active or past_due and the period covers now. Periods follow the subscription anchor, not the calendar month. Without such a period (a payg tenant, or a suspended or canceled plan) the response is still 200 and all four values are null; clients treat that body as "no current period", not as an error. A 404 means only that the route is absent (the SaaS extension is not mounted). The allowance is never credits and never money, so the body has no credit field and no price field (Team allowance).

Status Meaning
401 Not authenticated
500 Database error

Request a Team Change

A Team tenant's owner or admin asks platform staff for a change. The call writes one admin_audit_log row (team_change_request), emails the platform staff addresses after the response, and changes no billing state; staff act on it through Team subscription.

POST /api/v1/billing/team/request
Authorization: Bearer {token}

{"request_type": "add_seats", "desired_seats": 12, "note": "Two new technicians"}
Field Rule
request_type change_plan, add_seats, renew, cancel or other
desired_plan_id Optional; an assignable team_* plan id, else 422
desired_seats Optional; at least 1
note Optional; at most 2,000 characters
Status Meaning
201 {request_id, request_type, status: "submitted"}
401 Not authenticated, or the token is older than the recent-auth window
403 The caller is not an owner or admin, or the tenant has no governing plan row (one uniform message for both)
422 Malformed body or unknown plan id
429 More than 20 requests for the tenant in 24 hours
500 Database error

Create Portal Session

Create a Stripe Customer Portal session for managing billing. It uses the caller's subscription row in the acting tenant, and answers 400 No billing account found when there is none.

POST /api/v1/billing/portal
Authorization: Bearer {token}
Content-Type: application/json

Request:

{
  "return_url": "https://hub.huitzo.com/billing"
}

Response:

{
  "data": {
    "portal_url": "https://billing.stripe.com/p/session/..."
  }
}

Stripe Webhook

Handle Stripe webhook events. Uses Stripe signature verification (no JWT auth).

POST /api/v1/billing/webhook
Stripe-Signature: t=...,v1=...

Handles events: checkout.session.completed, checkout.session.expired, checkout.session.async_payment_succeeded, customer.subscription.updated, customer.subscription.deleted, invoice.payment_succeeded, invoice.payment_failed, payment_intent.succeeded, payment_intent.payment_failed, charge.dispute.created, charge.dispute.closed.

A checkout.session.completed/checkout.session.async_payment_succeeded with mode == "payment" and payment_status == "paid" is a credit top-up settlement — it grants the pending purchase's credits exactly once (see credits.md#top-ups and ADR-021). A same-shaped event whose metadata carries purpose == "wallet_topup" is instead a PAYG wallet top-up settlement (see credits.md#payg-wallet-topup and ADR-035) — it grants a 1-year CreditLot through the merged ledger, exactly once, deduplicated by the checkout-time purchase_id rather than the top-level webhook claim. A payment_intent.succeeded/payment_intent.payment_failed event whose metadata carries purpose == "wallet_auto_reload" is the PAYG auto-reload settlement (see ADR-036 §4.1/§8) — it grants or records a decline for the off-session charge exactly once, deduplicated by the WalletReloadAttempt.id the charge was created against. All other handled events are subscription/membership state.

charge.dispute.created, and charge.dispute.closed with status == "lost", run the chargeback clawback while HUITZO_DISPUTE_CLAWBACK_ENABLED is on (D-024 CR43, credits.md#dispute-clawback, ADR-041 disputes and refunds): the disputed paid lot is found by the HMAC of the dispute's PaymentIntent id (else by the PaymentIntent's purchase_id/attempt_id metadata), its remaining credits are clawed back with one negative adjustment, one credit_writeoffs row is recorded, and the account is frozen (closed at the second dispute) with auto-reload and seed eligibility off. The write-off's UNIQUE (dispute_ref_hash) makes a redelivery a no-op. A dispute closed with any other status is logged only. With the flag off, both events are acknowledged (200), claimed and ignored: a later resend of one answers duplicate: true, so subscribe the endpoint to charge.dispute.created and charge.dispute.closed when the flag is turned on and reconcile any earlier dispute by hand. A Stripe inquiry (warning_needs_response) is handled like a chargeback.

Response:

{
  "data": {
    "received": true
  }
}

The publisher legal-acceptance enrollment API (T-051). See the legal registry reference and ADR-034 / ADR-037. Contributed by the SaaS extension — absent on a self-hosted OS, matching the publish gate's no-op there.

Get Developer Terms

GET /api/v1/legal/developer-terms?product={optional-product-key}
Authorization: Bearer {jwt_token}
# pseudocode — response (200), no servable version registered yet
{
  "document_key": "developer-terms",
  "available": false,
  "accepted": false,
  "product_terms": null
}
# pseudocode — response (200), a current version exists
{
  "id": <str>,               # echo verbatim as document_version_id on accept (ADR-037 D10)
  "document_key": "developer-terms",
  "available": true,
  "version": <str>,
  "status": "interim" | "published",
  "interim_label": "Preliminary terms — subject to counsel revision" | null,
  "canonical_url": <str>,
  "effective_date": <ISO8601>,
  "accepted": <bool>,
  "accepted_at": <ISO8601> | null,
  "typed_name": <str> | null,
  "product_terms": { "document_key": <str>, "version": <str>, "canonical_url": <str>, "status": "interim" | "published" } | null
}
Status Meaning
200 Always — available: false is an honest non-error state, not a 404

Accept Developer Terms

POST /api/v1/legal/developer-terms/accept
Authorization: Bearer {jwt_token}
Content-Type: application/json
# pseudocode — request
{
  "typed_name": <str>,            # D-6: the accepter's typed full name, non-blank, max 255 chars
  "document_version_id": <str>    # the `id` from GET above — pins the accept to the reviewed version (ADR-037 D10)
}
# pseudocode — response (201)
{
  "document_key": "developer-terms",
  "document_version": <str>,
  "typed_name": <str>,
  "accepted_at": <ISO8601> | null   # null only on the rare post-commit read-miss fallback; the acceptance itself still recorded
}
Status Meaning
201 Recorded (or replayed idempotently — ADR-034 D5)
401 Identity resolved from the ambient session cookie rather than an explicit bearer token (require_bearer_identity, H1)
403 Caller is an API-key principal (ADR-037 D11 — this write requires an interactive, explicitly-authenticated human session)
409 No current servable (interim/published) version exists yet, or document_version_id no longer matches the current version (reload and re-review — ADR-037 D10)
422 typed_name blank, missing, or over 255 chars; document_version_id missing or not a valid UUID — standard FastAPI/Pydantic request-body validation

Metrics

All metrics endpoints require admin role (owner or admin).

Onboarding Funnel

GET /api/v1/metrics/onboarding?since=2026-02-15T00:00:00
Authorization: Bearer {token}

Response:

{
  "data": {
    "funnel": [
      { "step": "signup", "count": 200, "conversion_pct": 100.0 },
      { "step": "invite_redeemed", "count": 195, "conversion_pct": 97.5 },
      { "step": "developer_activated", "count": 150, "conversion_pct": 76.9 },
      { "step": "pack_created", "count": 80, "conversion_pct": 53.3 },
      { "step": "command_executed", "count": 60, "conversion_pct": 75.0 }
    ]
  }
}

The invite_redeemed step counts the pre-fold invite_redeemed billing events only; a coupon redemption writes coupon_redeemed, which this funnel does not yet count.


Revenue Metrics

GET /api/v1/metrics/revenue
Authorization: Bearer {token}

Response:

mrr_cents and active_subscribers are derived from real Stripe subscription aggregates and served from a periodically-refreshed snapshot (as_of is the snapshot timestamp). When no snapshot is available (Stripe unconfigured or unreachable with no prior snapshot) all three are null and the UI renders "—" rather than a fabricated figure. See admin-console.md#revenue-and-navigation.

{
  "data": {
    "mrr_cents": 250000,
    "active_subscribers": 50,
    "as_of": "2026-02-20T09:00:00Z",
    "recent_events": [
      {
        "type": "payment_succeeded",
        "data": { "amount": 5000 },
        "created_at": "2026-02-20T10:00:00Z"
      }
    ]
  }
}

Usage Metrics

GET /api/v1/metrics/usage?since=2026-02-15T00:00:00
Authorization: Bearer {token}

Core telemetry, mounted on every deployment. Every figure comes from Core's command_executions table, filtered on created_at >= since when since is given (ADR-043 DR-24j, spec §7.5). Before D-024 CR8 it read the SaaS billing_events table, so it returned zeros on a Core-only deployment and different numbers on SaaS.

Key Source
commands_executed every command execution
active_users distinct non-null user_id (cron runs carry none)
error_count executions with status failure or timeout
avg_command_duration_ms mean of completed_at − started_at where both are set; null when none are

The statement is aggregate-only: it never reads a result or error payload column.

Response:

{
  "data": {
    "commands_executed": 1500,
    "active_users": 120,
    "error_count": 15,
    "avg_command_duration_ms": 342.5
  }
}

User Journeys

Per-user event timelines for the admin dashboard.

GET /api/v1/metrics/user-journeys
Authorization: Bearer {token}

Response:

{
  "data": [
    {
      "user_id": "uuid-abc",
      "email": "[email protected]",
      "created_at": "2026-02-15T10:00:00Z",
      "events_count": 25,
      "time_to_first_command_ms": 180000,
      "last_active": "2026-02-20T15:30:00Z",
      "events": [
        { "type": "signup", "created_at": "2026-02-15T10:00:00Z", "duration_ms": null },
        { "type": "command_executed", "created_at": "2026-02-15T10:03:00Z", "duration_ms": 450 }
      ]
    }
  ]
}

Export Metrics

Bulk export billing events for analysis.

GET /api/v1/metrics/export?format=csv&since=2026-02-15T00:00:00
Authorization: Bearer {token}

Formats: csv (default), json

CSV response returns a downloadable file with columns: id, tenant_id, user_id, event_type, event_data, duration_ms, created_at.


Admin

All admin endpoints require an admin or owner JWT and write one row to admin_audit_log per request. Read paths use the app.tenant_id='__admin__' RLS sentinel; cross-tenant writes (revoke sessions, reset passwords) re-open a per-target-tenant session so standard tenant isolation policies apply.

Self-hosted password recovery (#675). A forgotten password must never be a permanent lockout, even with no SMTP configured. Two email-independent paths exist: (1) the admin-assisted POST /api/v1/admin/users/{id}/password-reset below, when a second admin is logged in; and (2) the host break-glass CLI python -m backend.manage set-password --email <email> (run via docker exec), which works with zero email transport and no second admin — see operations-runbook.md#break-glass-password-reset.

Method Path Purpose
GET /api/v1/admin/users List users; filters: referral, created_after. Rows carry no tier: the membership tier is retired and a user's commercial state is the acting tenant's plan. Cursor or offset pagination, limit 1-200 (default 50).
GET /api/v1/admin/users/{id} Detail view: user record, recent billing events, live Stripe subscription status (60s cached).
POST /api/v1/admin/users/{id}/sessions/revoke Delete every refresh-session row for the target user.
POST /api/v1/admin/users/{id}/password-reset Admin-assisted reset (no email required). Mints a single-use reset token (delete-on-mint) and returns it in the response (reset_token, expires_in_minutes, tenant_id) for out-of-band delivery; the user completes the reset via POST /api/v1/auth/reset-password. Requires recent authentication (require_recent_auth) — a stale admin session must re-authenticate first. The admin never sets or learns the password; the raw token is never logged.
GET /api/v1/admin/metrics/funnel Daily/weekly aggregate of checkout_started → checkout_completed → registered → first_command. Single GROUP BY query; p95 < 500 ms with 10K user fixtures.

Non-admin requests (role NOT IN ('admin','owner')) receive 403 before any audit row is written. Unauthenticated requests receive 401.

LLM Registry

Platform-staff (admin/owner, recent authentication) management of the LLM registry — the only source of platform LLM configuration (ADR-038 §3.2). Prefix /api/v1/admin/llm; {data} / {error} envelope; every request audited. Full contract: admin console §5.8.

Method Path Purpose
GET / POST /providers List / register providers. Projection includes has_api_key, api_key_last4, api_key_updated_at — never the key
POST /providers/{id}/enable, /providers/{id}/disable The provider kill switch
PUT / DELETE /providers/{id}/api-key Set ({api_key}, 20–512 printable ASCII) or clear the platform key; 404 unknown provider, 422 for local_ai or an invalid key, 503 on set when the server encryption key is not configured (§5.8.1)
GET /providers/{id}/available-models Models the stored key can reach; 409 without a key (or an undecryptable one), 422 for a provider kind with no model listing, 502 on provider error, 503 when the server encryption key is not configured (§5.8.3)
GET / POST /models; PATCH /models/{id}; POST /models/{id}/enable, /disable Model catalog
GET /settings Default model, every profile's mapping and resolved model, warnings (§5.8.2)
PUT / DELETE /settings/default-model Set ({model_id}, enabled model, else 422) or clear the default model
PUT / DELETE /profiles/{profile} Map a profile to a model ({model_id}) or remove the mapping
GET /provider-types Supported provider kinds and whether each is registered

Platform Toolchain Settings

Platform-staff (admin/owner, recent authentication) management of the platform-wide toolchain settings that GET /api/v1/platform/toolchain serves. {data} envelope; every request audited. Full contract: admin console §5.10.

Method Path Purpose
GET /api/v1/admin/platform/toolchain Stored values with source, updated_at, updated_by, the release default, and valid (false for a stored value that is not a valid range, which clients never receive)
PUT /api/v1/admin/platform/toolchain/dashboard-sdk-react Body { "value": "^7.1.0" }. Sets the dashboard SDK range; 422 unless value is a well-formed npm semver range of at most 64 characters (validation)
DELETE /api/v1/admin/platform/toolchain/dashboard-sdk-react Reset to the release default (idempotent)

Each returns the GET body. Non-staff callers and API-key principals (even a staff user's key) get 403; unauthenticated callers get 401; a session older than 15 minutes gets 401 admin_reauth_required.

Usage by Tenant

Staff-only, cross-tenant measured usage from Core's execution_usage table (D-024 CR8). Core measures and SaaS prices, so these routes carry no dollars, no prices and no credits: every figure is a quantity (executions, tokens, milliseconds, characters) or metering_units_milli. Contract: Core execution usage spec §7 and ADR-043.

Method Path Purpose
GET /api/v1/admin/usage/tenants?period=YYYY-MM[&format=json\|csv] One row per tenant for one month, including tenants with no usage (zeros). Ordered by metering_units_milli descending, then name.
GET /api/v1/admin/usage/tenants/{tenant_id}?period=YYYY-MM[&format=json\|csv] One tenant: tenant, totals (its list row), executions_by_source (api, mcp, cron, user_schedule, pipeline), breakdown (grouped by product, provenance, provider, model and source) and daily (per NYC calendar day and product).

Access. Platform staff only (users.is_platform_staff), with role admin or owner and a token issued in the last 15 minutes. API keys are refused. Each successful call writes exactly one admin_audit_log row (admin_usage_list_tenants or admin_usage_tenant_detail, payload {period, tenant_id?, format}).

Periods. period is an America/New_York calendar month; it defaults to the current NYC month. The bounds are half-open and returned in UTC as period_start and period_end, beside timezone. Usage rows bucket by event_time; executions bucket by created_at. last_event_at is the tenant's latest measured event for all time, or null if it has never been measured.

Executions. executions counts distinct correlation ids across command executions and pipeline runs, so a pipeline that a command dispatched counts once. In the detail view a pipeline run that no command owns counts as pipeline, so the five sources add up to executions.

CSV. format=csv returns text/csv; charset=utf-8 as an attachment named usage-tenants-<period>.csv (the list rows) or usage-tenant-<slug>-<period>.csv (the detail breakdown rows). The columns are exactly the JSON keys in response order. A string cell that starts with =, +, -, @, a tab or a carriage return gets a leading ', so a spreadsheet shows it as text.

Status When
400 invalid_period (error.details.code) period is not YYYY-MM
400 Invalid tenant id the detail path is not a UUID
401 {"error": "admin_reauth_required"} the token is older than 15 minutes
403 not platform staff, or role is not admin/owner
404 Tenant not found unknown tenant (detail)
503 usage_query_timeout (error.details.code) an aggregate exceeded the 15-second statement bound
# pseudocode — response (200) for GET /api/v1/admin/usage/tenants?period=2026-09, one row shown
{
  "data": {
    "period": "2026-09",
    "period_start": "2026-09-01T04:00:00+00:00",
    "period_end": "2026-10-01T04:00:00+00:00",
    "timezone": "America/New_York",
    "tenants": [
      {
        "tenant_id": "uuid", "name": "Acme", "slug": "acme",
        "is_first_party": false, "is_active": true,
        "executions": 42, "llm_calls": 30,
        "llm_input_tokens": 120000, "llm_output_tokens": 18000,
        "llm_cache_read_tokens": 0, "llm_cache_creation_tokens": 0,
        "compute_ms": 912000, "tts_characters": 0, "feedback_submissions": 1,
        "metering_units_milli": 5100000, "metering_units_milli_managed": 5100000,
        "estimated_rows": 0, "last_event_at": "2026-09-22T18:04:11+00:00"
      }
    ]
  }
}

The priced view of the same tenants is a separate SaaS route, /api/v1/admin/usage/billing/tenants, present only when the SaaS extension is mounted (spec §7.6).

Dashboard. The admin console reads these routes in the Usage by tenant tab of /admin/metrics (both modes; in SaaS mode the overlay adds a credits column group headed "Settled in period") and in the Metered usage section of /admin/tenants/:id. Both load on demand rather than polling, since every call writes an audit row, and both download CSV through the authenticated client (spec §8).

Usage Billing Overlay (SaaS)

The priced view of the same tenants and months, in credits, from the SaaS ledger (D-024 CR9). It is mounted only with the SaaS extension: without it both paths return 404 and the Core routes above are unaffected. Core neither imports nor proxies it. Contract: spec §7.6 and ADR-043 DR-24i.

Method Path Purpose
GET /api/v1/admin/usage/billing/tenants?period=YYYY-MM One row per tenant, including idle tenants (zeros). Ordered by credits_debited descending, then tenant_id.
GET /api/v1/admin/usage/billing/tenants/{tenant_id}?period=YYYY-MM One tenant: totals (its list row), ledger (tenant-wide opening_balance_credits, closing_balance_credits and totals_by_entry_kind), products (settled usage per product: charge_count, settled_credits, billable_charge_count, report_only_charge_count, accrued) and daily (per NYC day of settlement).

The path is /usage/billing/tenants, not /usage/tenants/billing: Core's /usage/tenants/{tenant_id} mounts first and would read billing as a tenant id.

Each row carries tenant_id (the join key to the Core row) and:

Key Meaning
credits_debited credits the ledger debited for usage in the period: the negated sum of ledger_entries.delta_credits over charge entries, bucketed by occurred_at
credits_debited_by_lot_source the same debit split by the debited lot's source: purchase, grant, adjustment, coupon
credits_uncollected the shortfall forgiven on charges settled in the period
billable_charge_count, report_only_charge_count charges settled in the period, split by the linked usage event's stored billable flag
internal_cost_usd_micros present only when non-zero

Buckets. The overlay buckets by settlement (settled_at, occurred_at); the Core view buckets by event_time. An event settled after an NYC month boundary lands in different months on the two sides, so they are not expected to tie per period. There is no allowance field.

Access, periods and errors are the Core view's: platform staff with role admin or owner and a token issued in the last 15 minutes; period defaults to the current NYC month; 400 invalid_period, 400 Invalid tenant id, 401 admin_reauth_required, 403, 404 Tenant not found and 503 usage_query_timeout as above. Each successful call writes one admin_audit_log row (admin_usage_billing_list_tenants or admin_usage_billing_tenant_detail, payload {period, tenant_id?}). JSON only.

# pseudocode — response (200) for GET /api/v1/admin/usage/billing/tenants?period=2026-09, one row shown
{
  "data": {
    "period": "2026-09",
    "period_start": "2026-09-01T04:00:00+00:00",
    "period_end": "2026-10-01T04:00:00+00:00",
    "timezone": "America/New_York",
    "tenants": [
      {
        "tenant_id": "uuid",
        "credits_debited": 812,
        "credits_debited_by_lot_source": {"purchase": 600, "grant": 212, "adjustment": 0, "coupon": 0},
        "credits_uncollected": 0,
        "billable_charge_count": 40,
        "report_only_charge_count": 3
      }
    ]
  }
}

House Cost (SaaS)

The staff view of what the house tenants (the Huitzo first-party and demo tenants on the internal house plan) cost, per NYC month (D-024 CR39, ADR-041 D11). House usage is internal cost, never revenue: it appears here and nowhere in the revenue figures (GET /api/v1/metrics/revenue excludes house tenants, and a house charge never writes the ledger entry credits_debited sums). It is served by the SaaS overlay, never by Core: Core's usage responses carry no dollars (DR-1). Returns 404 house_plan_disabled while HUITZO_HOUSE_PLAN_ENABLED is off.

Method Path Purpose
GET /api/v1/admin/usage/billing/house?period=YYYY-MM One row per house tenant: a tenant with a non-canceled house plan row, or with a house budget period overlapping the month. Ordered by internal_cost_usd_micros descending, then tenant_id.
Key Meaning
cost_label Always "internal cost": how every dollar figure in this response is labelled
internal_cost_peg_usd_micros_per_unit 20000: the raw metering peg, 1 unit = $0.02 of provider cost. It is not a loaded cost; the loaded-cost factor is a CFO item
units_consumed Units of house usage settled in the month (bucketed by settled_at) inside a house budget period: the budget draws (usage_charges.allowance_units) plus units_over_budget
units_over_budget The part settled past the budget as uncollected_credits (only under the FQ-2 alert-only sub-switch, or a settlement larger than its hold)
internal_cost_usd_micros units_consumed × the peg
budget The tenant's latest house budget period, or null: period_start, period_end, budget_units, units_used, units_remaining and percent_used (one decimal)
totals units_consumed, units_over_budget and internal_cost_usd_micros summed over the rows

Access, periods and errors are the overlay's: platform staff with role admin or owner and a token issued in the last 15 minutes; period defaults to the current NYC month; 400 invalid_period, 401 admin_reauth_required, 403 and 503 usage_query_timeout. Each successful call writes one admin_audit_log row (admin_usage_billing_house, payload {period}). The Metrics page's House cost tab shows it.

Staff alerts. With HUITZO_WALLET_ALERTS_ENABLED also on, a house settlement that takes the budget period to 80% used, and one that uses all of it, writes a house_80 or house_100 wallet alert that the alert dispatcher emails to the house tenant's platform-staff owners and admins, once per budget period each (wallet alerts).

# pseudocode — response (200) for GET /api/v1/admin/usage/billing/house?period=2026-09
{
  "data": {
    "period": "2026-09",
    "period_start": "2026-09-01T04:00:00+00:00",
    "period_end": "2026-10-01T04:00:00+00:00",
    "timezone": "America/New_York",
    "cost_label": "internal cost",
    "internal_cost_peg_usd_micros_per_unit": 20000,
    "totals": {"units_consumed": 10000, "units_over_budget": 0, "internal_cost_usd_micros": 200000000},
    "tenants": [
      {
        "tenant_id": "uuid", "name": "Huitzo", "slug": "huitzo", "plan_status": "active",
        "units_consumed": 10000, "units_over_budget": 0, "internal_cost_usd_micros": 200000000,
        "budget": {
          "period_start": "2026-09-25T12:00:00+00:00", "period_end": "2026-10-25T12:00:00+00:00",
          "budget_units": 12500, "units_used": 10000, "units_remaining": 2500, "percent_used": 80.0
        }
      }
    ]
  }
}

Team Subscription (SaaS)

Staff provisioning and lifecycle of a tenant's Team plan (D-024 CR21, CR35, CR45; ADR-041 D1, D9, D10). tenant_subscriptions holds one row per tenant; no row means payg. The procedure is the Team onboarding runbook and the customer contract is billing: Team plans. Mounted only with the SaaS extension. The /enterprise-subscription and /enterprise-plans routes are gone, with no alias.

Method Path Purpose
GET /api/v1/admin/team-plans The assignable team_* plans. 200 with a list of {id, name, allowance_units, pooled_requests_per_minute, per_member_rpm_ceiling, commands_per_hour, billing_modes}. billing_modes is ["contract"], plus "stripe_invoice" while HUITZO_TEAM_INVOICE_RAIL_ENABLED is on. No price
POST /api/v1/admin/tenants/{tenant_id}/team-subscription Provision a Team plan, or resurrect a canceled row. 201
GET /api/v1/admin/tenants/{tenant_id}/team-subscription The row and its derived state. 200
PATCH /api/v1/admin/tenants/{tenant_id}/team-subscription Change the plan, seats, contact or term, reactivate, or schedule a change. 200
DELETE /api/v1/admin/tenants/{tenant_id}/team-subscription Cancel now: the row moves to canceled and is kept; the seat limit falls back to the staff-set quotas.max_seats, which the cancel raises to the active member count if it was lower (never lowers it); no member or data is removed. 200

POST body. {plan_id, billing_mode?, seats_licensed, billing_contact_email?, period_start?, contract_term_end?, days_until_due?, reason?}.

  • plan_id is team_s, team_m or team_l. An unknown id, payg, partner_managed and house are 400 (house has its own route).
  • billing_mode is contract (the default) or stripe_invoice.
  • seats_licensed is required, at least 1. It is the seat limit until the row is canceled. No Team subscription write changes tenants.quotas.max_seats, the staff-set limit (seat limit).
  • Contract mode: contract_term_end is required while HUITZO_TEAM_LIFECYCLE_V2_ENABLED is off and optional (month-to-month) with it on; it must be after period_start, which defaults to now. days_until_due is 400.
  • stripe_invoice mode: billing_contact_email is required (the invoice recipient); days_until_due is 1–365, default 30; contract_term_end and period_start are 400. The Stripe customer is the tenant billing profile's, created and written back when absent. If the write fails after Stripe objects exist, the subscription is canceled and a customer this request created is deleted.
  • Provisioning opens the first allowance period at the row's anchors.

PATCH body. {plan_id?, seats_licensed?, billing_contact_email?, contract_term_end?, cancel_at_period_end?, reactivate?, reason?}. At least one field, or reactivate: true, is required.

Row What a PATCH does
contract Applies plan, seats, contact and term in one transaction. reactivate: true returns a past_due, suspended or read_only row to active; a set term must then be in the future. With the lifecycle v2 on, a larger plan_id applies at once and adds the prorated units to the current period; a smaller one is recorded as pending_plan_id for the period roll; the current plan_id clears it; cancel_at_period_end schedules or clears a cancel at the roll
stripe_invoice, invoice rail on active or past_due rows accept plan_id and seats_licensed only. An upgrade reprices Stripe once with a proration and adds floor((new − old) × remaining / period) units. A downgrade is scheduled with the lifecycle v2 on, else 409. cancel_at_period_end sets Stripe's own flag (lifecycle v2)
stripe_invoice, invoice rail off 409 team_subscription_incompatible_billing_mode

Response (POST, GET, PATCH, DELETE):

# pseudocode — response (200) for GET /api/v1/admin/tenants/{id}/team-subscription
{
  "data": {
    "tenant_id": "uuid", "plan_id": "team_m", "plan_name": "Team M", "allowance_units": 5500,
    "status": "active", "billing_mode": "contract", "stripe_subscription_id": null,
    "current_period_start": "2026-10-01T00:00:00+00:00", "current_period_end": "2026-11-01T00:00:00+00:00",
    "grace_expires_at": null, "contract_term_end": null,
    "seats_licensed": 10, "billing_contact_email": "[email protected]",
    "pending_plan_id": null, "cancel_at_period_end": false,
    "created_at": "2026-10-01T00:00:00+00:00", "updated_at": "2026-10-01T00:00:00+00:00",
    "derived": { "governs": true, "grace_days_remaining": null, "read_only_days_remaining": null,
                 "contract_term_days_remaining": null, "plan_sets_seats": true,
                 "staff_max_seats": 4 }
  }
}

derived.staff_max_seats is the stored staff-set seat limit (tenants.quotas.max_seats), or null. derived.plan_sets_seats is true while seats_licensed is the seat limit: in every status but canceled, and never for a house row. It is not derived.governs, which follows the budgets through dunning. The staff-set limit applies otherwise (ADR-041 D14).

plan_name and allowance_units are null for an id outside the catalog. The allowance is units only: no field carries credit or a price.

Errors. Every route answers 400 Invalid tenant id for a malformed id and 500 on a database error.

Status Code When
400 — plan_id is not an assignable team_* plan; a field forbidden in the mode (contract_term_end, period_start, days_until_due); a missing billing_contact_email in stripe_invoice mode; a missing or earlier-than-start contract_term_end; null for plan_id, seats_licensed or cancel_at_period_end; an empty PATCH; clearing the term where it is required; a reactivation with a past term; contract fields or reactivate on a stripe_invoice row; a plan change and a cancel in one request
400 team_lifecycle_v2_disabled cancel_at_period_end while HUITZO_TEAM_LIFECYCLE_V2_ENABLED is off
404 — Tenant not found, or Tenant has no Team subscription (GET, PATCH, DELETE)
409 billing_profile_required POST: the billing profile lacks is_business, legal_name, tax_id or billing_country; details.missing_for_team lists them (billing profile)
409 team_stripe_invoice_out_of_scope POST with stripe_invoice while HUITZO_TEAM_INVOICE_RAIL_ENABLED is off, before any read or Stripe call
409 team_subscription_exists POST on a tenant with a non-canceled row (details.status), or a concurrent provision
409 team_subscription_changed A concurrent write or a changed Stripe customer; re-read and retry
409 team_subscription_canceled PATCH on a canceled row; re-provision with POST
409 team_subscription_illegal_transition reactivate on a row that is not past_due, suspended or read_only, or an invoice-row change outside active and past_due
409 team_subscription_incompatible_billing_mode PATCH on a stripe_invoice row while the invoice rail is off
409 team_subscription_off_catalog_plan An invoice-row plan change on a row that is not on a Team plan
409 team_downgrade_requires_period_end An invoice-row downgrade while the lifecycle v2 is off; nothing changes
409 team_pending_change_exists The row already schedules the other change (a downgrade or a cancel)
409 team_subscription_missing_stripe_id, team_subscription_missing_version A malformed legacy row; repair it before changing it
409 team_subscription_already_canceled DELETE on a canceled row
409 — contract_term_end is required in contract mode on a legacy row with no term
502 — Stripe failed: provisioning, the price lookup, the reprice, the schedule, or the DELETE's Stripe cancel (the row is left untouched; retry)
503 — Billing is not configured, or the plan's hz_team_*_monthly Price is not provisioned (provision_catalog.py --team)

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes. Every call writes one admin_audit_log row, and every write re-primes the plan cache. The DELETE's cancel_team_subscription row records staff_max_seats, the staff-set seat limit in force after the cancel. The hourly Team sweep (team_billing_sweep, :15) rolls contract anchors, opens the next allowance period, and moves rows through past_due, suspended and read_only (billing: Team lifecycle).

Enterprise plan cutover (removed)

The one-time re-plan of every row on a retired enterprise plan onto a Team plan (D-024 CR24, ADR-041 D5) ran on production on 2026-10-08. The /api/v1/admin/ent-cutover routes and their CLI were removed afterwards, and the enterprise plan ids with them: tenant_subscriptions.plan_id accepts the plan catalog ids only (saas_0043).

Tenant Kind Correction

PATCH /api/v1/admin/tenants/{tenant_id} accepts kind (home or team), the staff-only correction of Core's tenant kind (D-024 CR13, ADR-041 D2). Kind is otherwise fixed at creation: /auth/register and first-boot setup create home, staff tenant create creates team.

Status Code When
409 home_tenant_has_plan kind: "home" on a tenant with a tenant_subscriptions row, checked under the row lock

The change is recorded in the tenant's admin_audit_log row with old and new values. On a hosted deployment a correction to home also resets the stored quotas.max_seats to 1.

Seat limit. On a hosted deployment the same PATCH, and POST /api/v1/admin/tenants, write quotas.max_seats, the staff-set seat limit (ADR-041 D14). A team workspace takes any integer of at least 1; create defaults to 1 when the key is omitted. A home workspace is fixed at 1. A PATCH whose quotas map omits max_seats, or whose quotas is JSON null, edits the other keys and carries the stored limit forward. The limit is stored whether or not a Team plan is live; while one is live, its seats_licensed is the limit in force and the stored value applies again when it is canceled. The change is audited as the quotas old and new pair of update_tenant. The limit in force and its source are read from GET /api/v1/admin/tenants/{tenant_id}/usage (tenant quotas).

Status Code When
422 invalid_seat_limit Hosted create or PATCH with a quotas.max_seats that is not an integer of at least 1
409 home_seat_limit_fixed Hosted PATCH of a home workspace with a quotas.max_seats other than 1

House Plan (SaaS)

Staff provisioning of the internal house plan for the Huitzo first-party and demo tenants (D-024 CR28, ADR-041 D11). A house tenant's usage is metered and priced at the rate card like any other, but it is paid from a monthly budget in units, never from credit lots or the ledger, and it is internal cost, never revenue. Mounted only with the SaaS extension. Both routes return 404 house_plan_disabled while HUITZO_HOUSE_PLAN_ENABLED is off.

Method Path Purpose
POST /api/v1/admin/tenants/{tenant_id}/house-plan Put the tenant on house: a tenant_subscriptions row with billing_mode = 'internal' (no Stripe ids, no contract term, zero seats) and the first budget period, [now, now + 1 month). Body: {monthly_budget_units?, billing_mode?, reason?}; the budget defaults to the catalog's house budget. A canceled plan row is resurrected as house. 201
PATCH /api/v1/admin/tenants/{tenant_id}/house-plan Set the monthly budget. Body: {monthly_budget_units, reason?}. Rewrites the latest budget period's units_included; later periods carry it forward. 200

Both answer with the plan row and the current budget period, in units only:

# pseudocode — response (201) for POST /api/v1/admin/tenants/{id}/house-plan
{
  "data": {
    "tenant_id": "uuid", "plan_id": "house", "status": "active", "billing_mode": "internal",
    "current_period_start": "2026-09-25T12:00:00+00:00", "current_period_end": "2026-10-25T12:00:00+00:00",
    "monthly_budget_units": 12500, "units_used": 0, "units_remaining": 12500,
    "period_end": "2026-10-25T12:00:00+00:00"
  }
}
Status Code When
400 house_billing_mode_invalid billing_mode is anything but internal (contract and stripe_invoice included)
409 house_tenant_has_non_staff The tenant has members, by membership or home, who are not platform staff. details.users lists them (user_id, email, at most 50) and details.count is exact
409 house_plan_exists POST on a tenant already on house; use PATCH
409 tenant_has_plan POST on a tenant with a live plan row on another plan; cancel it first
404 house_plan_missing PATCH on a tenant not on house
409 house_budget_below_usage PATCH below the units already used this period

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes. Each write records one admin_audit_log row (provision_house_plan or update_house_budget). Every budget write takes the tenant's credit_accounts lock before the period row (ADR-041 lock order); the hourly Team sweep rolls house anchors monthly like contract rows.

At the chokepoint (with HUITZO_SAAS_BILLING_ENABLED and HUITZO_HOUSE_PLAN_ENABLED both on), a house execution reserves against the budget's remaining units minus live holds and settles into a priced usage_charges row whose allowance_units moved the budget counter; no lot or ledger entry is written. At 100% of budget the execution gets 402 INSUFFICIENT_CREDITS (available 0, units_remaining beside it) until staff raise the budget. With the FQ-2 sub-switch HUITZO_HOUSE_BUDGET_ALERT_ONLY_ENABLED it runs instead, the overflow settles as uncollected_credits, and a house_budget_exhausted warning is logged. House tenants are excluded from GET /api/v1/metrics/revenue.

Members are platform staff only (D-024 CR29, ADR-041 membership admission hook). While HUITZO_HOUSE_PLAN_ENABLED is on, every route that would create a membership in a house tenant refuses a user who is not platform staff and writes nothing. A tenant.join coupon redemption (POST /api/v1/coupons/redeem, or POST /api/v1/auth/register with a coupon_code: a new identity is never staff) answers the uniform coupon refusal (ADR-042 D6). The tenant coupon mint (POST /api/v1/tenant/coupons) refuses an existing non-staff invitee up front with 409 house_tenant_staff_only. If the check cannot run, the same routes answer 503 membership_admission_unavailable. Revoking a user's platform-staff bit never removes a membership; the hourly Team sweep logs a house_tenant_non_staff_member alert for each house tenant that still has one. Flag off, admission is unchanged.

Tenant Billing Profile (SaaS)

Staff read and write of a tenant's business identity (D-024 CR31, ADR-041 D8). tenant_billing_profiles is the single source of the legal name, tax ID and billing country for PAYG and Team alike, and of the tenant's Stripe customer. Mounted only with the SaaS extension; no flag.

Method Path Purpose
GET /api/v1/admin/tenants/{tenant_id}/billing-profile The profile. 200; 404 billing_profile_not_found when the tenant has none
PUT /api/v1/admin/tenants/{tenant_id}/billing-profile Create or replace the profile. 201 when created, 200 when replaced

The PUT body is {is_business, legal_name?, tax_id?, tax_id_type?, billing_country?, billing_region?, reason?}. Every field it omits is cleared, except the tax ID pair: the stored tax ID is encrypted and never returned, so omitting both tax_id and tax_id_type keeps them, and sending tax_id: null clears them. The Stripe customer is never set here; the rows that create it write it (CR33, CR35).

Field Rule
legal_name 1–255 characters after trimming
tax_id_type ein, rfc or other; required with tax_id
tax_id ein: nine digits, stored as NN-NNNNNNN. rfc: the 12-character company or 13-character personal RFC, uppercase. other: 1–64 characters. Spaces are stripped
billing_country ISO 3166-1 alpha-2, uppercased
billing_region The ISO 3166-2 subdivision code without the country prefix (CA, JAL); needs billing_country

A malformed field is 422. Both routes answer with the same projection. The tax ID appears only as its last four characters, and the Stripe customer only as a boolean:

# pseudocode — response (201) for PUT /api/v1/admin/tenants/{id}/billing-profile
{
  "data": {
    "tenant_id": "uuid", "is_business": true, "legal_name": "Acme Robotics, S.A. de C.V.",
    "tax_id_type": "rfc", "tax_id_last4": "48A1", "billing_country": "MX", "billing_region": "JAL",
    "stripe_customer_id_present": false,
    "team_ready": true, "missing_for_team": [],
    "created_at": "2026-09-25T12:00:00+00:00", "updated_at": "2026-09-25T12:00:00+00:00"
  }
}

team_ready is true when the tenant may be provisioned a Team plan; otherwise missing_for_team lists the unmet fields, in the order is_business, legal_name, tax_id, billing_country. POST /api/v1/admin/tenants/{tenant_id}/team-subscription refuses with 409 billing_profile_required, with the same missing_for_team list in error.details, before any Stripe call and again under the tenant row lock the PUT also takes.

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes; 400 Invalid tenant id; 404 Tenant not found. Each successful call records one admin_audit_log row (get_tenant_billing_profile or put_tenant_billing_profile); the PUT's payload names the changed fields and never carries the tax ID.

PII handling (D11 / #G15): raw coupon codes, full stripe_*_id, and full emails are never persisted in admin_audit_log — the writer applies HMAC-SHA256 sidecars or last-4-of-localpart redaction before INSERT. The stripe_customer_id field is replaced by a stripe_customer_id_present boolean in every response body.

Escheat Report (SaaS)

The per-lot unclaimed-property report of unused paid value (D-024 CR50, ADR-041 escheat inputs). Read-only: the report runs in one SET TRANSACTION READ ONLY transaction on the '__admin__' sentinel session. Mounted only with the SaaS extension; no flag. The valuation, owner-state and dormancy rules are in Escheat and dormancy report. It files nothing; using it for a filing waits on counsel (ADR-041 E2).

Method Path Purpose
GET /api/v1/admin/compliance/escheat?as_of=YYYY-MM-DD&format=json\|csv Every purchase lot with reportable value at the end of as_of (UTC). as_of defaults to today (UTC); format defaults to json

format=csv returns text/csv (Content-Disposition: attachment; filename="escheat-<as_of>.csv"): a header row, then one row per lot with the lot keys below in that order. A text cell that starts with =, +, -, @, a tab or a carriage return is prefixed with '. The JSON body carries the lots plus the summaries:

# pseudocode — response (200) for GET /api/v1/admin/compliance/escheat?as_of=2026-12-31
{
  "data": {
    "as_of": "2026-12-31", "cutoff": "2027-01-01T00:00:00+00:00",
    "dormancy_years": 5, "report_due": "2027-03-01",
    "notice_threshold_usd_micros": 50000000, "delaware_de_minimis_usd_micros": 5000000000,
    "valuation_bases": {"lot_cost_basis": "…", "price_version_peg": "…"},
    "totals": {"lot_count": 3, "credits_reportable": 900, "value_usd_micros": 90000000,
               "dormant_lot_count": 1, "dormant_value_usd_micros": 60000000},
    "by_state": [{"owner_state": "DE", "lot_count": 2, "credits_reportable": 700,
                  "value_usd_micros": 70000000, "dormant_lot_count": 1,
                  "dormant_value_usd_micros": 60000000, "dormant_face_value_usd_micros": 60000000}],
    "notice_list": [{"tenant_id": "uuid", "owner_state": "DE", "owner_legal_name": "Acme S.A. de C.V.",
                     "dormant_lot_count": 1, "dormant_value_usd_micros": 60000000}],
    "delaware": {"dormant_face_value_usd_micros": 60000000, "report_required": false},
    "lots": [{
      "lot_id": "uuid", "origin_lot_id": null, "tenant_id": "uuid", "account_id": "uuid",
      "granted_at": "2021-06-01T12:00:00+00:00", "expires_at": "2022-06-01T12:00:00+00:00",
      "owner_legal_name": "Acme S.A. de C.V.", "owner_entity_type": "business",
      "billing_country": "MX", "billing_region": "JAL", "billing_postal_code": "44100",
      "owner_state": "DE", "owner_state_reason": "foreign_address",
      "credits_remaining": 0, "credits_expired_unused": 600, "credits_reportable": 600,
      "valuation_basis": "lot_cost_basis", "value_usd_micros": 60000000, "face_value_usd_micros": 60000000,
      "last_activity_at": "2021-06-01T12:00:00+00:00", "presumed_abandoned_at": "2026-06-01T12:00:00+00:00",
      "dormant": true
    }]
  }
}

Lots are ordered by tenant_id, granted_at, lot_id; by_state by owner_state; notice_list by tenant_id, owner_state.

Unpaginated by design. The response is the whole filing extract in one body, with no page, limit or cursor: totals, by_state, notice_list and delaware are computed over every reportable lot, so a page of lots would carry wrong summaries. This is a deliberate exemption from the pagination rule for unbounded result sets. The report is bounded by its statement timeout (503 escheat_query_timeout), the staff gate and the number of paid lots; if it outgrows the timeout, the fix is a streamed CSV, not pages.

Status Code When
400 invalid_as_of as_of is not a YYYY-MM-DD date between 1970 and 9998
422 format is not json or csv (request validation)
503 escheat_query_timeout The report query ran past its statement timeout

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes; anyone else gets 403 (401 admin_reauth_required for a stale token). Each successful call records one admin_audit_log row (admin_compliance_escheat_report, payload {as_of, format, lot_count}), written after the read-only transaction ends.

Wallet Account Unfreeze (SaaS)

Clears a chargeback freeze on one credit account (D-024 CR43, ADR-041 disputes and refunds). The freeze itself is written by the dispute webhook; the rules are in Dispute clawback. Mounted only with the SaaS extension; no flag.

Method Path Purpose
POST /api/v1/admin/wallet/accounts/{account_id}/unfreeze Clear frozen_at and frozen_reason. Body: {"reason": "<1–500 characters>"}
# pseudocode — response (200)
{
  "data": {
    "account_id": "uuid", "tenant_id": "uuid",
    "frozen_at": null, "frozen_reason": null,
    "dispute_count": 1, "closed_at": null,
    "changed": true
  }
}

changed is false when the account was not frozen; nothing is written then except the audit row. Unfreezing does not re-enable auto-reload, does not restore seed eligibility and keeps dispute_count, so a later dispute still closes the account.

Status Code When
404 No credit account with that id
409 wallet_account_closed The account is closed (two disputes): closure is permanent
422 account_id is not a UUID, or reason is missing or blank (request validation)

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes; anyone else gets 403 (401 admin_reauth_required for a stale token). Each successful call records one admin_audit_log row (wallet_account_unfrozen, payload {tenant_id, account_id, changed, previous_frozen_reason, dispute_count, reason}) in the same transaction as the write.

Paid-Lot Refund (SaaS)

Refunds one untouched paid lot within 30 days of purchase (D-024 CR44, ADR-041 disputes and refunds). The eligibility rules, the amount and the webhook mirror are in Paid-lot refunds. Mounted only with the SaaS extension; answers 404 payg_refunds_disabled while HUITZO_PAYG_REFUNDS_ENABLED is off.

Method Path Purpose
POST /api/v1/admin/wallet/lots/{lot_id}/refund Refund the lot through Stripe (idempotency key: the lot id) and retire it with a negative adjustment. Body: {"reason": "<1–500 characters>"}
# pseudocode — response (200)
{
  "data": {
    "lot_id": "uuid", "tenant_id": "uuid", "account_id": "uuid",
    "credits_refunded": 500,
    "amount_minor": 5367, "currency": "usd", "tax_minor": 400,
    "fee_deducted_minor": 33, "full_refund_jurisdiction": false,
    "refund_status": "succeeded", "tax_reversal": "reversed", "replay": false
  }
}

amount_minor is amount_paid_minor + tax_minor less fee_deducted_minor, which is 0 for a Mexico or California consumer (full_refund_jurisdiction: true). A lot already refunded answers 200 with replay: true, its credits_refunded, and null Stripe amounts; Stripe is not called again. tax_reversal (D-024 CR47) is null for an untaxed lot or a replay; for a taxed charge it is reversed (the auto-reload's Stripe Tax Transaction was reversed in full), stripe_managed (a Checkout top-up, whose refund Stripe Tax records itself), transaction_missing or failed (the refund stands; both are logged at ERROR for staff to reverse by hand). See Stripe Tax.

Status Code When
404 payg_refunds_disabled HUITZO_PAYG_REFUNDS_ENABLED is off
404 No credit lot with that id
409 lot_not_refundable details.reason: not_purchase (a promotional lot), lot_expired, lot_touched (credits drawn, from the lot or its cutover source), refund_window_closed (granted more than 30 days ago), unsupported_payment (not a top-up or auto-reload), snapshot_incomplete, payment_not_found, charge_disputed, charge_already_refunded, charge_mismatch (the charge is not amount_paid_minor + tax_minor), fee_unavailable (the charge has no balance transaction yet) or nothing_to_refund
422 lot_id is not a UUID, or reason is missing or blank (request validation)
500 The lot and its ledger disagree (a reconciliation incident; nothing is written)
502 Stripe failed; nothing is written. A retry reuses the same Stripe idempotency key; if Stripe did create the refund, the webhook mirror retires the lot and a retry answers 409 charge_already_refunded
503 Stripe is not configured

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes; anyone else gets 403 (401 admin_reauth_required for a stale token). Each 200 records one admin_audit_log row (wallet_lot_refunded, payload: the response fields, a 12-character prefix of the refund id's HMAC, and reason) in the same transaction as the write.

Team Usage Blocks (SaaS)

Staff-issued, invoiced usage blocks: Team overflow option (a) (D-024 CR36, ADR-041 D12). A block is a one-off Stripe invoice for at least 5,000 credits ($500) at $0.10 per credit. Once paid it becomes one paid purchase lot on the tenant account with a 12-month expiry, exempt from the paid-balance cap. Mounted only with the SaaS extension; every route answers 404 team_usage_blocks_disabled while HUITZO_TEAM_USAGE_BLOCKS_ENABLED is off.

Method Path Purpose
POST /api/v1/admin/tenants/{tenant_id}/usage-blocks Issue a block and send its invoice. 201
GET /api/v1/admin/tenants/{tenant_id}/usage-blocks?limit=&offset= The tenant's blocks, newest first (limit 1–200, default 50). 200 {items, limit, offset, total}
DELETE /api/v1/admin/tenants/{tenant_id}/usage-blocks/{block_id} Void an issued block: the Stripe invoice is voided (a draft is deleted), then the block. A block with no recorded invoice is looked up at Stripe by metadata.block_id, so an invoice Stripe issued without the id reaching Huitzo is voided too. 200; a block already void answers 200 unchanged

The POST body is {credits, days_until_due?, billing_contact_email?, reason?}. days_until_due is the invoice's net terms (1–90, default 30). The invoice goes to the tenant's Stripe customer on its billing profile; when the profile has none yet, one is created for billing_contact_email, or for the Team plan row's billing contact when the body omits it, and stored on the profile. The invoice carries its own custom fields (the credits bought at $0.10 per credit, and their 12-month expiry) and footer, which replace the Team customer's plan-allowance disclosures (Team invoice rail): a block buys prepaid credits, not allowance. The DELETE body is optional: {reason?}.

Double-submit guard. Send an Idempotency-Key header (1–255 characters) on the POST. The key names the block: a repeat with the same key and credits answers 200 with the block it already issued, and sends no second invoice (a repeat after a 502 re-drives the same invoice under the same Stripe idempotency keys); a repeat with other credits is 409 usage_block_idempotency_key_reused. Without the header every POST issues a new block.

# pseudocode — response (201) for POST /api/v1/admin/tenants/{id}/usage-blocks {"credits": 5000}
{
  "data": {
    "id": "uuid", "tenant_id": "uuid", "credits": 5000, "amount_cents": 50000, "currency": "usd",
    "state": "issued", "stripe_invoice_present": true, "lot_id": null,
    "issued_by": "uuid", "voided_by": null, "reason": null,
    "issued_at": "2026-09-25T12:00:00+00:00", "paid_at": null, "voided_at": null
  }
}
Status Code When
400 usage_block_below_minimum credits below 5,000, checked before any read
400 usage_block_above_maximum credits above 1,000,000 (a typo guard)
400 billing_contact_email_required The tenant has no Stripe customer and no invoice recipient is known
409 usage_block_requires_team_plan The tenant has no live team_* plan row (none, canceled, or a row on another plan)
409 billing_profile_required The tenant's billing profile is not a complete business profile (missing_for_team lists the gaps). A US profile also needs billing_region, which the paid lot's owner snapshot requires
409 usage_block_idempotency_key_reused The Idempotency-Key already issued a block with other credits
409 usage_block_voided_during_issue Staff voided the block while its invoice was being issued; the new invoice is voided at Stripe (details.invoice_voided) and never attached to the block
502 usage_block_invoice_failed Stripe could not create the customer or issue the invoice. The block (named in details.block_id) stays issued without an invoice; void it and issue a new one
404 usage_block_not_found DELETE on a block this tenant does not have
409 usage_block_already_paid DELETE on a paid block, or one whose invoice Stripe reports paid
502 usage_block_void_failed Stripe could not void the invoice; the block stays issued

Payment. The block row is written issued before the invoice exists, so every invoice Stripe can collect on names a block. invoice.paid and invoice.payment_succeeded whose metadata.purpose is team_usage_block are routed by POST /api/v1/billing/webhook before the tenant-subscription branch, so a block payment never moves a Team plan row: a past_due tenant stays past_due (ADR-041 D9). The settlement takes the tenant account lock, then the block row, and writes one purchase lot (source_ref team_usage_block:{block_id}, expires_at 12 months out, the owner snapshot from the billing profile) with its purchase ledger entry, and marks the block paid. Both events and every redelivery converge on that one lot. The invoice's subtotal must equal the block's amount_cents; any other amount grants nothing and answers 500. Every other invoice.* event on a block invoice, invoice.payment_failed on a declined card above all, is a logged no-op 200 that never reaches the tenant-subscription branch, so a failed block payment never puts the Team plan into dunning. With the flag off the settlement branch is a logged no-op too, and the webhook answers 200. The Stripe webhook endpoint must be subscribed to invoice.paid.

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes; 400 Invalid tenant id; 404 Tenant not found. A successful POST, a GET, and a DELETE that voids each record one admin_audit_log row (issue_team_usage_block, list_team_usage_blocks, void_team_usage_block); no audit payload carries a Stripe id, and the invoice appears in responses only as stripe_invoice_present.

Promotional Grants (SaaS)

The staff queue of the monthly promotional budget (D-024 CR73, ADR-042 D13; Credits: promotional budget). While HUITZO_PROMO_BUDGET_ENFORCED is on (default false), a coupon-credit grant that does not fit under the 25,000-credit monthly cap is not written: the redemption succeeds with the outcome queued, and the grant waits here as a pending request. Mounted with the SaaS extension and never flag-gated, so a queue stays drainable after the flag is turned off.

Method Path Purpose
GET /api/v1/admin/promo-grants?status=&limit=&offset= Requests across tenants, oldest first. status is pending (default), approved, rejected or all; limit 1–200, default 50. 200 {items, limit, offset, total}
GET /api/v1/admin/promo-grants/budget The current New York month: period_start, cap_credits, reserved_credits, queued_credits, override_credits, alert_threshold_percent (80), alert_80_at, enforced, pending_requests. 200
POST /api/v1/admin/promo-grants/{request_id}/approve The cap override: writes the coupon lot and its grant entry, keyed on the request's redemption_id (a lot that already exists is reused), and counts the credits in the approving month's override_credits for reporting only, with no second reservation. The lot expires expiry_days after approval. 200 with the request, status = approved and its lot_id
POST /api/v1/admin/promo-grants/{request_id}/reject Marks the request rejected. No lot, entry or budget count is written, and the redemption stays consumed. 200 with the request
# pseudocode — one request in items[] or a decision response
{
  "id": "uuid", "tenant_id": "uuid", "account_id": "uuid", "redemption_id": "uuid",
  "coupon_id": "uuid", "user_id": "uuid" | null, "credits": 4000, "expiry_days": 30,
  "period_start": "2026-10-01", "status": "pending" | "approved" | "rejected",
  "lot_id": "uuid" | null, "decided_by": "uuid" | null, "decided_at": "…" | null,
  "created_at": "…"
}
Status Code When
404 promo_grant_not_found No request has this id
409 promo_grant_already_decided The request was already approved or rejected (details.status)

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes. The list and budget read through the admin sentinel; a decision runs in the request's own tenant session and records one admin_audit_log row (approve_promo_grant, reject_promo_grant).

Pack Pricing Review (SaaS)

The staff review of submitted pack pricing versions (D-024 CR82, execution pricing §3.2). Every route returns 404 while HUITZO_PACK_PRICING_ENABLED is off.

Method Path Purpose
GET /api/v1/admin/pack-pricing?status=&limit=&offset= Versions across tenants, oldest submission first. status is pending_review (default), approved, rejected, superseded or all; limit 1–200, default 50. 200 {items, limit, offset, total}
POST /api/v1/admin/pack-pricing/{version_id}/approve Approves a pending_review version prospectively: its effective_from is the approval instant, never earlier, and the pack's previously approved version is closed (superseded, effective_to = the same instant) in the same transaction. No prior version's price or declaration is rewritten. 200 with the version
POST /api/v1/admin/pack-pricing/{version_id}/reject Marks a pending_review version rejected. The approved version in force, if any, keeps pricing. 200 with the version
Status Code When
404 pack_pricing_version_not_found No version has this id
409 pack_pricing_version_already_decided The version is not pending_review (details.status)
409 pack_pricing_conflict A concurrent decision won; retry

Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes. The list reads through the admin sentinel; a decision runs in the pack owner's tenant session and records one admin_audit_log row (approve_pack_pricing, reject_pack_pricing).


Pack Fee Revenue (SaaS)

Platform staff's view of the records-only pack platform fee (D-024 CR84, settlement spec §0.4.2). Read only. Returns 404 while HUITZO_PACK_PRICING_ENABLED is off.

Method Path Purpose
GET /api/v1/admin/pack-fees/monthly?months= Fee revenue per UTC calendar month across every pack, newest first, one entry per month (zeros when nothing settled). months 1–36, default 12, counting the current month. 200 {platform_fee_rate_bps, months: [...]}
# pseudocode — one entry of months[]
{"month": "2026-10", "settled_executions": 40, "price_credits": 200,
 "fee_credits": 40, "developer_share_credits": 160,
 "collected_credits": 198, "uncollected_credits": 2,
 "funded_paid_credits": 150, "funded_promotional_credits": 48,
 "packs": 3, "developers": 2}

fee_credits is the platform fee booked on P as priced; uncollected_credits is the part of P the settle could not draw (settlement spec §0.4.5). Access is the other staff routes': platform staff with role admin or owner and a token issued in the last 15 minutes, read through the admin sentinel.

Ledger Invariant Runs (SaaS)

The run record of the nightly ledger invariant check (issue #1892 H4, Credits: invariant runs). Read only. Platform staff with the admin or owner role; no recent-auth step-up, because the response carries counts, check names and one-line error texts and never a tenant id or a row id. Mounted with the SaaS extension and never flag-gated; a deployment without the extension answers 404.

Method Path Purpose
GET /api/v1/admin/ledger/invariant-runs?limit= The health verdict, the latest run and the most recent runs, newest first. limit 1–90, default 14. 200
# pseudocode — the response data
{
  "health": "ok" | "violations" | "failed" | "skipped" | "stale" | "never_ran",
  "checked_at": "…", "stale_after_hours": 26,
  "latest": <run> | null,
  "items": [<run>, …]
}
# pseudocode — one run
{
  "id": "uuid", "started_at": "…", "finished_at": "…",
  "status": "ok" | "violations" | "failed" | "skipped",
  "violations": 3, "failed_checks": 0,
  "passes": {
    "compliance_invariants": {
      "label": "Compliance invariant check", "status": "ok" | "skipped" | "failed",
      "error": "…" | null,
      "checks": {"c5": {"state": "violated", "count": 3},
                 "c2": {"state": "not_evaluated", "count": null},
                 "c3": {"state": "failed", "count": null, "error": "…"}}
    }
  }
}

health is never_ran when no run is recorded, stale when the latest run finished more than stale_after_hours ago (a nightly run is missing), and otherwise the latest run's status. A check's state is ok, violated, failed (its query failed), not_evaluated (its flag is off, or its pass did not run) or reported (a count that is never a violation). What to do with each: Ledger invariants runbook.


MCP Endpoint

A Streamable-HTTP Model Context Protocol server that exposes the caller's tenant-visible pack commands as MCP tools. Designed for Claude Code, Cursor, VS Code and any other Streamable-HTTP MCP client that can send an Authorization header. The full user-facing setup walkthrough is in guides/connect-claude-mcp.md.

Endpoint

POST /mcp
Authorization: Bearer sk-huitzo-...
Content-Type: application/json

The path is /mcp (not /api/v1/mcp) so the URL pasted into a client config stays short. /mcp and /mcp/ are served identically; neither answers with a redirect.

Authentication

API key only. The sk-huitzo-* key must carry the commands:execute scope. JWT and cookie credentials are rejected by design — connector configs sit in client UIs for months and need long-lived, scoped, revocable credentials.

Status Cause
401 — Authentication required Missing Authorization header
401 — requires API-key authentication Sent a JWT or cookie instead of an API key
401 — Invalid or revoked API key Key revoked or never existed
403 — missing commands:execute scope API key authenticated but lacks the required scope. Generate a new key with the commands:execute scope.

A request body over 4 MiB is refused with a plain-text 413 (Request body too large), after authentication and before it is parsed. That is the MCP SDK's default max_request_body_size, which backend/api/v1/mcp.py does not override.

Supported MCP methods

JSON-RPC method Behavior
initialize Standard MCP handshake — declares server capabilities (tools only)
tools/list Returns every command visible to the authenticated tenant
tools/call Invokes a command via the same ExecutionRouter used by POST /api/v1/commands/{namespace}. No internal HTTP round-trip — the MCP handler resolves the command, builds the Context, and calls the executor directly under the same RLS tenant scope. Counted against the per-tier command_execution rate-limit bucket, and gated by the tenant's monthly_command_cap quota exactly as the REST endpoint is (see architecture/admin-console.md#tenant-quotas) — a refused call mints no tracking row. Before that gate, the arguments are validated against the input schema of the command version resolved for the caller at call time, the schema tools/list would return now; no cached copy is used, so a republish or another tenant's listing cannot change the verdict. A mismatch is refused as validation (Input validation error: …, quoting at most 1,024 characters) and mints no tracking row. References resolve only inside the stored schema, never over the network. If the validator itself fails, on the stored schema or on an extreme argument, the check is skipped and logged with the command's namespace, and the command's own args model still validates the call.
ping Health probe

Tool naming

Huitzo namespaces (@scope/pack/command) are mapped deterministically to MCP-legal tool names:

@scope/pack/command  ↔  scope__pack__command

Round-trip: split on __, prepend @. Pack names are validated at publish time against [a-z0-9-]+, so the mapping is lossless by construction.

One tool name is reserved outside the namespace-derived space: huitzo_task_poll, always present in tools/list alongside the tenant's commands. It polls the status of an asynchronously-dispatched command (see Result shape below) and takes a single task_id string argument.

Visibility & isolation

tools/list returns the same set of commands as GET /api/v1/commands — public packs, the caller's private packs, and packs shared with the caller's tenant via organization grants. Unlisted packs are excluded. Tenant isolation is enforced by PostgreSQL RLS exactly as on the REST endpoint; a client cannot see another tenant's private commands.

Result shape

tools/call always returns a single text content block whose body is JSON, serialized compactly (no space after , or :) with non-ASCII characters written as UTF-8 rather than \uXXXX escapes (a payload containing an unpaired surrogate keeps \uXXXX escapes for that content, since it cannot be encoded as UTF-8). For a command invocation, three shapes are possible; huitzo_task_poll reuses shape 3 for its own errors but returns a fourth, distinct shape for a found task (below).

The MCP protocol's own isError flag is set on the result alongside the JSON body: isError: true on every shape-3 error envelope (including pre-execution refusals, quota refusals, huitzo_task_poll errors, and the generic internal catch-all), and isError: false on shapes 1, 2 and 4. For tools/call responses (shapes 1-3) a client may branch on the protocol flag or on the universal error key; both agree there. huitzo_task_poll's shape-4 response is the exception: its error field mirrors the polled task's own terminal outcome (null on success, a populated object on failure/timeout/revoked) even though the poll call itself succeeded, so isError stays false for any found task. A client that polls async tasks must therefore read shape 4's error field, not isError, to learn whether the task failed. Note that the pending envelope (shape 2) is a successful dispatch, and an expired poll result is an error even though the task itself once succeeded.

1. Synchronous success (fast-queue commands — the common case):

{ "result": <command_result>, "correlation_id": "..." }

2. Asynchronous dispatch (medium- or long-queue commands):

{
  "pending": true,
  "task_id": "celery-...",
  "queue": "medium",
  "namespace": "@scope/pack/command",
  "correlation_id": "...",
  "message": "Command queued on the medium pool. Call the 'huitzo_task_poll' tool with task_id='celery-...' for the result."
}

The MCP handler does not block on async commands — the client (or the conversational model in front of it) is responsible for calling the huitzo_task_poll tool (see Tool naming above) with the returned task_id to retrieve the eventual result. An MCP client cannot make raw HTTP calls, so this tool — not GET /api/v1/tasks/{task_id} — is the only way to poll from within an MCP session. Most pack commands run on the fast queue; this branch is rare.

3. Error (typed envelope; type, when present, is one of validation, command, timeout, internal, permission, not_found, expired, QuotaExceeded, insufficient_credits, pack_load_busy, the lowercased code of an LLM authorization refusal, or, for any other SDK error the command raised, the lowercased code of its nearest huitzo_sdk.errors class, such as secret_missing, http_error or external_api_error (Errors a command raises) — several pre-execution refusals, e.g. invalid tool name, command not found, pack disabled, command not loaded in this deployment, and a resolve-time database error, carry no type at all, which is why error is the universal discriminator):

{ "error": "<user-facing message or generic label>", "type": "internal", "correlation_id": "..." }

The MCP server intentionally never surfaces str(exc) for unknown exception types — only the huitzo_sdk.errors family reaches the client: ValidationError, PackPermissionError and CommandError through their own branches with their own text, and every other SDK error as the caller-facing text Errors a command raises assigns it (its own message for a class written for the caller, a fixed text for a platform family such as HTTPError or StorageError, whose message can carry a URL key or SQL). Its envelope adds error_type (the nearest SDK class's name), retryable, namespace and, for a RateLimitError that carries one, retry_after to error, type (that class's lowercased code) and correlation_id. validation covers three cases: the call-time schema check in the tools/call row above (Input validation error: …, refused before the quota gate, so no tracking row is minted); the SDK's own ValidationError, whose message is returned verbatim; and a pack's declared args model rejecting the tools/call arguments, which reads as <path>: <reason> pairs (a failing args model gives the exact rule) — the field and the constraint an agent needs in order to retry, never the rejected value. The isolated child raises that failure as the SDK's ValidationError, already rendered this way, and REST answers with the same text. A pydantic.ValidationError raised inside a pack's command body reaches the API as a non-SDK error and is the generic internal envelope. Scoping is otherwise unchanged: an internal ValueError is not user-facing and still collapses into the generic internal envelope. Every error envelope on this surface carries error, so a client can branch on payload.get("error") uniformly rather than special-casing any one type.

A QuotaExceeded refusal carries extra keys beyond the base {error, type, correlation_id}: its message/code/details mirror REST's 409 error object verbatim (error and message are the identical string) — {"error": "...", "type": "QuotaExceeded", "message": "...", "code": "tenant_quota_exceeded", "details": {"key", "limit", "current", "attempted_delta"}, "correlation_id": "..."} — so a client hitting the cap over MCP gets the identical refusal vocabulary REST returns, plus a correlation id. A Core edition licence limit refuses the same way, with "type": "LicenseLimitExceeded", "code": "license_limit_exceeded" and details.scope added; a licence usage count that could not be read returns {"error": "...", "type": "LicenseCountUnavailable", "message": "...", "code": "license_count_unavailable", "details": {"counter"}, "correlation_id": "..."} (REST's 503). Both are checked before the tracking row, so neither mints one. Unlike other refusals on this surface, a quota refusal is also logged server-side (logger.warning, tagged with the same correlation_id) precisely so that id is useful for support lookup — no command_executions row is minted, so the log line is the only server-side record. correlation_id in this section is otherwise always freshly minted per tools/call invocation — huitzo_task_poll mints no correlation_id of its own, so its own errors (validation, not_found, expired, internal) omit the field. Operators correlate command-execution errors via correlation_id. The expired error additionally echoes the polled task_id (the caller already supplied it, but polling errors have no namespace field to anchor the response to, so it's included for symmetry with the other huitzo_task_poll-specific errors).

An insufficient_credits refusal (T-031, ADR-035 §4) similarly carries extra keys beyond the base three: {"error": "...", "type": "insufficient_credits", "namespace": "...", "correlation_id": "...", "code": "INSUFFICIENT_CREDITS", "required": <int>, "available": <int>, "wallet_id": <string | null>, "auto_reload_state": <string | null>} — the same code/required/available/wallet_id/auto_reload_state fields §Insufficient Credits Error documents, spread flat into this envelope rather than nested under a details key. The SSE pipeline stream (stream_response=true) follows the identical flattened shape inside its event: error frame's data payload.

4. Task status (huitzo_task_poll only — not one of the three tools/call shapes above; a found task returns the same object REST nests under data in its GET /api/v1/tasks/{task_id} response, unwrapped — MCP content blocks carry no success/data envelope):

{
  "task_id": "celery-...",
  "status": "success",
  "result": <command_result_or_null>,
  "error": null,
  "started_at": "2026-08-11T12:00:00+00:00",
  "completed_at": "2026-08-11T12:05:00+00:00",
  "correlation_id": "..."
}

status is one of queued, pending, started, success, failure, timeout, revoked — Celery's live state can only advance a non-terminal DB status; a terminal DB status is always authoritative. started_at/completed_at are UTC-normalized ISO 8601 timestamps (naive stored datetimes are stamped +00:00), matching REST. correlation_id here is the original command invocation's id (read back off the stored row) — not a new one minted for the poll call. A success row with no stored result (result_full IS NULL — either the result was purged, or the command legitimately returned nothing; the two are indistinguishable in storage, matching REST) comes back as an expired-typed error (shape 3 above) instead of this shape with result: null. MCP carries no HTTP status, so this is surfaced as a distinct error type rather than a bare null — mirroring REST's 410 Task result has expired. Polling a task_id that doesn't exist, or that belongs to another user, both return not_found — MCP does not distinguish "doesn't exist" from "not yours" the way REST's 404/403 split does, so a client can't use the poll tool to probe which task IDs exist for other tenant members.


Telemetry

Submit CLI Telemetry

Lightweight telemetry ingestion for CLI usage data. Public endpoint (opt-in, anonymous).

POST /api/v1/telemetry
Content-Type: application/json

Request:

{
  "command": "build",
  "duration_ms": 1200,
  "success": true,
  "python_version": "3.14.0",
  "os": "linux",
  "cli_version": "0.1.0"
}

Response:

{
  "data": {
    "received": true
  }
}

Rate Limiting

Rate limiting is a SaaS-extension concern (present only on a saas-entitled deployment). Requests are budgeted per endpoint class from the acting tenant's plan, not one shared bucket. See Plan-based rate budgets for the budgets and architecture/security.md#rate-limiting for the full model.

Class Window Examples
auth_session 60s /auth/me, /auth/validate (high floor — never blocks hydration)
dashboard_read 60s catalog/status GETs, monitor/dev-session reads
interactive_write 60s settings, key create/revoke, checkout
command_execution 3600s POST /commands/{ns}, MCP tools/call, pipeline execute/resume

There are no membership tiers. A tenant with no plan row is payg: 60 requests a minute per member and no command cap (the wallet is the spend control). A Team plan (team_*) carries a pooled per-tenant budget from PLAN_CATALOG. Unlimited is represented as -1.

Rate Limit Headers:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1708000060
Retry-After: 42
Header Description
X-RateLimit-Limit Budget for this endpoint class / window
X-RateLimit-Remaining Requests remaining in the current window
X-RateLimit-Reset Epoch second the window resets
Retry-After Seconds until reset — window-correct (≈60s reads, up to 3600s commands); 429 only

Rate Limit Response (429):

{
  "success": false,
  "error": {
    "code": "rate_limited",
    "message": "Rate limit exceeded for dashboard_read; retry after 42s.",
    "endpoint_class": "dashboard_read",
    "limit": 60,
    "remaining": 0,
    "reset": 1708000060,
    "retry_after": 42
  }
}

Pagination

There is no platform-wide pagination envelope. An endpoint that pages documents its own query parameters and paging fields in its section, and that section is authoritative. Most report paging state in the top-level meta object next to data (for example Pack Listing History returns meta: { "has_more", "limit" }); some carry it inside data instead.

List Commands and List Installed Packs are not paginated: each returns every visible row in one data array.


Webhooks

Configure webhooks to receive notifications.

Supported Events

Event Description
command.executed Command execution completed
task.completed Async task completed
task.failed Async task failed
pack.installed Pack installed
pack.uninstalled Pack uninstalled

Webhook Payload

{
  "id": "evt_abc123",
  "type": "command.executed",
  "timestamp": "2025-01-22T10:30:00Z",
  "data": {
    "command": "financial.analyze",
    "tenant_id": "ten_xyz789",
    "user_id": "usr_abc123",
    "duration_ms": 1234
  }
}

SDKs

Official SDKs are available:

  • Python: pip install huitzo-sdk
  • JavaScript: npm install @huitzo/sdk

See SDK Documentation for usage.


OpenAPI Specification

Full OpenAPI 3.0 specification available at:

https://huitzo.ai/openapi.json

Interactive documentation:

https://huitzo.ai/docs