# Accept a quarantined email Source: https://docs.hq.zone/api-reference/admin/accept-quarantine POST /v1/api/email/quarantine/{id}/accept Accepts a pending quarantined inbound email, marking it accepted, and returns an ok flag with an optional explanatory note. Admin only. Optionally binds the sender to a named workspace user (required to clear an unknown-sender quarantine) so their future mail routes; when the destination is now reachable the message is re-delivered so an agent acts on it immediately, otherwise it routes on the sender's next mail. Returns 404 if no pending quarantine with that id exists. # Add a user by email Source: https://docs.hq.zone/api-reference/admin/add-user POST /v1/api/users `POST /v1/api/users` - add a member by email (no Slack/Teams needed). Creates (or re-activates) a `workspace_users` row on the tenant's synthetic `direct` source with `origin='email'`, `signin_access='allowed'`, then mints a magic-link invite. Returns the link when no transactional email sender is wired (so an admin can hand it over). # Assign an unrouted email Source: https://docs.hq.zone/api-reference/admin/assign-email POST /v1/api/email/messages/{id}/assign Assign a handler to an `unrouted` item and re-drive it. Admin-only. Sets the message's agent (and, when the mail hit a handler-less mailbox endpoint, the endpoint's agent too, so future mail routes), then re-emits the routed event via the outbox so the worker drives a turn. The re-drive forces the agent/VM path (plane=NULL): a manually-assigned item is rare + deliberate, and the agent path avoids the light-plane's sender-bound disclosure ambiguity. # Assign a review-reply item to a user Source: https://docs.hq.zone/api-reference/admin/assign-email-owner POST /v1/api/email/messages/{id}/assign-owner Admin-only. Attributes a `review_reply` item (a reply to the team / default sender) to a workspace user, moving it into that user's review queue. Does NOT drive a turn or re-inject the reply into agent context - it only sets the reviewer. Use it to triage the Unassigned bucket. # Create email endpoint Source: https://docs.hq.zone/api-reference/admin/create-endpoint POST /v1/api/email/endpoints Creates a new inbound email endpoint (custom inbox) and returns it with its counters. Admin only. The localpart must be valid and not reserved or equal to the workspace mailbox; 'agent' (plane=agent) endpoints require a handler agent belonging to the workspace, while 'light' quick-reply endpoints must not name an agent. Returns 402 if the plan's email-inbox limit is reached and 409 if the address (or an agent's existing endpoint) already exists. # Delete email endpoint Source: https://docs.hq.zone/api-reference/admin/delete-endpoint DELETE /v1/api/email/endpoints/{id} Deletes an inbound email endpoint by id. Admin only and scoped to the caller's workspace. The HQ-managed workspace mailbox cannot be deleted (400), and an unknown or cross-workspace id returns 404. # Discard a reply draft Source: https://docs.hq.zone/api-reference/admin/discard-draft POST /v1/api/email/messages/{id}/discard Discard an `awaiting_review` draft without sending: settle to `handled`. # Download an email attachment Source: https://docs.hq.zone/api-reference/admin/download-attachment GET /v1/api/email/messages/{id}/attachments/{attachment_id}/download `GET /v1/api/email/messages/{id}/attachments/{attachment_id}/download` - the raw bytes of one attachment, for the admin viewer's inline preview + download (the read-half reuses the shared FilePreview renderer). Fetch-on-view from Sentio (never stored). The message is tenant-scoped here, and Sentio scopes the attachment to its message, so an attachment is reachable only through a message the caller's tenant owns. Admin-only. ## Binary response Returns the attachment's raw bytes with its stored `Content-Type` (not JSON). The bytes are fetched on demand and not stored by HQ. The interactive playground may not render binary — fetch it programmatically and stream the body to a file. # Erase another user (admin) Source: https://docs.hq.zone/api-reference/admin/erase-user POST /v1/admin/users/{id}/erase `POST /v1/admin/users/{id}/erase` - admin-erasure on behalf of another user. Requires `is_admin = TRUE` on the caller's row. Refuses self-erase via this route (use /v1/api/me/erase) so the audit trail consistently records `actor == subject` only for the explicit self path. # Get email badge count Source: https://docs.hq.zone/api-reference/admin/get-badge GET /v1/api/email/badge Returns the navigation badge count of email items needing a human, broken down into awaiting-review, unrouted and quarantined plus their sum. Scoped to the caller: a non-admin sees only their own awaiting-review items, while the unrouted and quarantined counts are admin-only and report zero for non-admins. # Get email endpoint Source: https://docs.hq.zone/api-reference/admin/get-endpoint GET /v1/api/email/endpoints/{id} Returns a single inbound email endpoint by id, with its full configuration and per-endpoint counters (message totals, attention items, disposition counts and reply-language distribution). Admin only and scoped to the caller's workspace; an unknown or cross-workspace id returns 404. # Get email message content Source: https://docs.hq.zone/api-reference/admin/get-message GET /v1/api/email/messages/{id}/content `GET /v1/api/email/messages/{id}/content` - the full inbound email for the detail view. Headers + decoded bodies are fetched on demand from Sentio (the raw EML is never stored); attachment metadata comes from the mirror, with a Trove `artifact_id` for download when the attachment was materialized. # Get business profile Source: https://docs.hq.zone/api-reference/admin/get-profile GET /v1/api/business-profile Returns the workspace's business profile, including its configured domain, the most recently crawled summary, brand palette, fonts, logo, crawl status and any last error, plus company enrichment (industry, segment, size hint) and detected technology signals ordered by confidence. The response also lists which fields have been manually overridden by an admin, with overrides taking precedence over auto-discovered values. Readable by any signed-in workspace member. # Get quarantined email content Source: https://docs.hq.zone/api-reference/admin/get-quarantine GET /v1/api/email/quarantine/{id}/content `GET /v1/api/email/quarantine/{id}/content` - view a quarantined message before accept/reject. Same fetch-on-view of the raw EML; attachments aren't materialized until accept, so the list is empty here. # Get workspace settings Source: https://docs.hq.zone/api-reference/admin/get-settings GET /v1/api/settings Returns the workspace-level settings an admin controls. Admin only. Includes the connected source's id, kind, and display name (read-only), the persona-distillation mode and per-user consent mode, the corpus history window in days, the sign-in mode and whether guest sign-in is allowed, and proactive-nudge settings (enabled flag, timezone, start/end hours, and fallback language). Returns 403 for non-admins. # Get a user Source: https://docs.hq.zone/api-reference/admin/get-user GET /v1/api/users/{id} `GET /v1/api/users/{id}` - one user (admin-only, tenant-scoped) for the detail page. Reuses USER_SELECT; bots/deleted are NOT excluded here (a deep link to an erased user must still resolve so the detail can show its state). # List email activity Source: https://docs.hq.zone/api-reference/admin/list-activity GET /v1/api/email/activity Returns a paginated feed of inbound and outbound email messages decorated with their endpoint, plane and a deep-link to the conversation thread, along with the total count for pagination. Admins see all workspace mail while a regular member sees only mail bound to them. Supports optional filtering by handling state (handled, awaiting_review, unrouted) and by endpoint, a limit (1-200, default 50), an offset, and a sort of recent (default, newest first) or oldest. # List audit log Source: https://docs.hq.zone/api-reference/admin/list-audit GET /v1/admin/audit Returns a paginated, recency-first list of audit-log events for the caller's own workspace, newest first. Admin only. Supports optional filtering by event kind, outcome, actor kind, agent id, and conversation id, a free-text query matched against the event target and intent, a lookback window in days (default 90; 0 or negative means all time), and page/page_size paging (page_size defaults to 50 and is clamped to 1-200). Each event includes its sequence number, hash-chain fields, and redacted details, alongside the unpaginated total. # List email endpoints Source: https://docs.hq.zone/api-reference/admin/list-endpoints GET /v1/api/email/endpoints Lists the workspace's inbound email endpoints (custom inboxes plus the HQ-managed workspace mailbox), each with its configuration and per-endpoint counters: total messages, items needing attention, inbound received, outbound replies, awaiting-review, unrouted and escalated counts, and a reply-language distribution. Also returns the workspace email slug, email domain and outbound mailbox localpart so a full address can be previewed without another call. Admin only and scoped to the caller's workspace. # List the caller's assigned email replies Source: https://docs.hq.zone/api-reference/admin/list-my-email-replies GET /v1/api/email/replies The member "Email replies" surface: replies attributed to the caller (review_owner_id), filtered by `reviewed` - false (default) = to-review, true = already reviewed. Owner-scoped to the caller's own items. # List emails awaiting review Source: https://docs.hq.zone/api-reference/admin/list-review GET /v1/api/email/review Returns the three actionable email triage queues - awaiting-review, unrouted and quarantined - each capped at 200 items, plus a count of each. The awaiting-review queue is scoped to the caller (or all workspace mail for admins), while the unrouted and quarantined queues are admin-only and come back empty with zero counts for a non-admin caller. # List users Source: https://docs.hq.zone/api-reference/admin/list-users GET /v1/api/users Returns the workspace's user directory as a paginated list, each entry including external id, source connector and workspace, display and real name, email, title, timezone, locale, admin/bot/guest/deleted flags, profile-consent state, last-seen time, sign-in access, admin-role override, and origin (slack, teams, or email). Supports a case-insensitive q search over name/handle/email/id, page and page_size pagination (page_size clamped 1-200, default 50), and a status filter of active (default), deleted, or all. Admin only; bots are excluded and results are scoped to the caller's own workspace. # Refresh business profile Source: https://docs.hq.zone/api-reference/admin/refresh-profile POST /v1/api/business-profile/refresh Queues an immediate re-crawl of the workspace's business profile and returns 202 with a queued status. Admin only. The refresh is skipped silently if the workspace has not yet confirmed its domain. # Reject a quarantined email Source: https://docs.hq.zone/api-reference/admin/reject-quarantine POST /v1/api/email/quarantine/{id}/reject Reject a quarantined mail: mark it `admin_reject` (terminal). Admin-only. # Reopen a reviewed email reply Source: https://docs.hq.zone/api-reference/admin/reopen-email-reply POST /v1/api/email/messages/{id}/reopen Flips a reviewed (`handled`) review-reply item back to the review queue - recovers a mis-clicked Done. Owner-or-admin, and only an item that was a review reply (`review_owner_id` set) and is currently `handled`. # Resend a user invite Source: https://docs.hq.zone/api-reference/admin/resend-invite POST /v1/api/users/{id}/resend `POST /v1/api/users/{id}/resend` - re-send the magic-link invite to a pending email member. Admin-only, tenant-scoped. # Mark a review-reply item reviewed Source: https://docs.hq.zone/api-reference/admin/review-reply-done POST /v1/api/email/messages/{id}/reviewed Clears a `review_reply` item from the review queue (sets it `handled`). The owner of the item (or an admin) may clear it, once a human has dealt with the reply. Does not touch agent context. # Revoke a pending invite Source: https://docs.hq.zone/api-reference/admin/revoke-invite DELETE /v1/api/users/{id} `DELETE /v1/api/users/{id}` - revoke a PENDING email invite (added by email, not yet signed in). Hard-deletes the row (no data to keep). Active members (signed in, or Slack/Teams) are NOT deletable here - that's the erasure flow. Admin-only, tenant-scoped. # Send an email reply Source: https://docs.hq.zone/api-reference/admin/send-reply POST /v1/api/email/messages/{id}/reply Approve (and optionally edit) the drafted reply on an `awaiting_review` item: send it through the same `email.reply` MCP path the agent uses, then settle the item to `handled`. The body comes from the request (the UI pre-fills it with the draft from the rendered transcript and lets a human edit before sending). # Set / rename the workspace handle (admin). Source: https://docs.hq.zone/api-reference/admin/set-workspace-slug POST /v1/api/admin/workspace/slug Renames `tenants.slug` (the URL handle) and realiases the email slug to match, keeping the old email address routing for a continuity window. The SPA reloads into `//`; stale `//` links self-heal via the email-keyed session. Re-validates atomically; the `tenants.slug` unique constraint is the final arbiter against a race. # Update email endpoint Source: https://docs.hq.zone/api-reference/admin/update-endpoint PATCH /v1/api/email/endpoints/{id} Updates the configurable behavior of an inbound email endpoint and returns the refreshed endpoint with counters. Admin only and scoped to the caller's workspace. Omitted fields keep their current values, supplying allow_patterns replaces the allowlist wholesale, and the localpart and kind cannot be changed. The system workspace mailbox cannot be edited here (400), and an unknown or cross-workspace id returns 404. # Update workspace mailbox Source: https://docs.hq.zone/api-reference/admin/update-mailbox PATCH /v1/api/email/workspace-mailbox Changes the localpart of the workspace outbound mailbox, the address all agents send from, renaming both the workspace setting and its system endpoint together. Admin only. The localpart must be lowercase alphanumerics with '.' or '-' separators (max 63 chars) and is rejected if it is reserved or already used by a custom inbox; the mailbox never auto-replies and that behavior is not configurable here. # Update business profile Source: https://docs.hq.zone/api-reference/admin/update-profile PUT /v1/api/business-profile Updates the workspace's business profile and returns the refreshed profile in the same shape as the GET endpoint. Admin only. Each field may be set, cleared (to re-expose the auto-discovered value), or left untouched; manual overrides persist across future automatic refreshes. Changing the domain to a new value normalizes it, rejects bare IP addresses with a 400, and triggers an immediate re-crawl. # Update workspace settings Source: https://docs.hq.zone/api-reference/admin/update-settings PATCH /v1/api/settings Updates the workspace-level settings an admin controls and returns the full updated settings. Admin only. Any subset of fields may be supplied; omitted fields are left unchanged, and for the nudge timezone and fallback language an empty string reverts to the default. Validates allowed values and ranges (for example profile_mode must be enabled or disabled, consent_mode admin_only or per_user, corpus_history_days 30-365, sign-in mode open or approval, and nudge start hour before end hour), returning 400 on an invalid value and 403 for non-admins. # Update a user's access Source: https://docs.hq.zone/api-reference/admin/update-user PATCH /v1/api/users/{id} `PATCH /v1/api/users/{id}` - set one user's sign-in access and/or tenant-admin role. Admin-only, tenant-scoped: the UPDATE is joined through the tenant slug so an admin can only ever touch a user in their OWN workspace. Either field may be omitted (only the supplied ones change). # Upload business logo Source: https://docs.hq.zone/api-reference/admin/upload-logo POST /v1/api/business-profile/logo Uploads a business logo supplied inline as base64 and returns the refreshed business profile. Admin only. Accepts PNG, JPEG, SVG, WebP and GIF up to 4 MiB; the stored logo becomes a manual override of the auto-discovered logo and is served from a stable HQ-hosted URL. # Verify audit chain Source: https://docs.hq.zone/api-reference/admin/verify-audit GET /v1/admin/audit/verify Re-walks the workspace's tamper-evident audit hash chain and reports whether it is intact. Admin only. Checks the most recent entries (the limit query parameter defaults to 10000 and is clamped to 1-100000), recomputing each entry's hash and verifying it links to its predecessor. Returns whether the chain is ok, how many entries were checked, the first and last sequence numbers covered, and, if broken, the sequence number where it first fails and whether the break is a content or linkage mismatch. # Check whether a workspace handle is free (admin). Source: https://docs.hq.zone/api-reference/admin/workspace-slug-available GET /v1/api/admin/workspace/slug/available Validates format + reserved words and checks global uniqueness across BOTH the URL registry (`tenants.slug`) and the email registry (`tenant_email_slug`), so the handle works for the URL and the email address alike. Advisory only - `set_slug` re-checks atomically. # Create an agent Source: https://docs.hq.zone/api-reference/agents/create-agent POST /v1/agents Creates a new agent in the caller's workspace from the supplied slug, display name, and optional description, instructions, personality settings, aliases, runtime profile, model, avatar URL, and initial enabled skill/MCP subsets, returning the created agent. The slug and aliases must be lowercase 2-32 character handles (letters, digits, hyphens), must not use reserved words, and must not collide with another agent in the workspace; if no avatar URL is given one is generated automatically. Admin only. # Disable an agent Source: https://docs.hq.zone/api-reference/agents/disable-agent DELETE /v1/agents/{id} Disables the named agent by setting its status to disabled so it no longer routes on any surface, and returns the now-disabled agent. The default agent cannot be disabled; promote another agent to default first (returns 400). Returns 404 if the agent is not in the caller's workspace. Admin only. # Enable an agent Source: https://docs.hq.zone/api-reference/agents/enable-agent POST /v1/agents/{id}/enable Re-enables a previously disabled agent by setting its status back to enabled, restoring routing on all surfaces, and returns the re-enabled agent. Idempotent: calling it on an already-enabled agent is a no-op. Returns 404 if the agent is not in the caller's workspace. Admin only. # Generate an agent avatar Source: https://docs.hq.zone/api-reference/agents/generate-avatar POST /v1/agents/{id}/avatar/generate `POST /v1/agents/{id}/avatar/generate` - admin-triggered xAI image generation. The optional `prompt` describes the desired look; it seeds the subject and is wrapped in the house illustration style + safety rails, then the image is stored in Trove and set as the agent's `avatar_url`. Synchronous (a few seconds). The cost is absorbed by the platform (`provider_usage.paid_by='platform'`). Admin only. # List agents Source: https://docs.hq.zone/api-reference/agents/list-agents GET /v1/agents Returns every agent configured in the caller's workspace, including each agent's slug, display name, description, system-prompt instructions, personality settings (tone, verbosity, cautions, languages), aliases, runtime profile, selected model, default flag, status, and avatar URL. Results are scoped to the caller's own workspace and ordered with the default agent first, then enabled agents, then by slug. Requires the agents:read scope. # List an agent's MCP servers Source: https://docs.hq.zone/api-reference/agents/list-mcp GET /v1/agents/{id}/mcp Returns the agent's enabled MCP-server subset as a list of server slugs. An empty list means the agent uses all MCP servers installed for the workspace. Returns 404 if the agent is not in the caller's workspace. Requires the agents:read scope. # List models Source: https://docs.hq.zone/api-reference/agents/list-models GET /v1/models Lists the models that can be selected in the agent editor, each with its slug, display name, family, runtime profile, vendor, and whether it is the runtime's default. Pass the optional runtime query parameter (claude-sdk, openai-agents, or opencode) to restrict the list to one runtime profile; otherwise all selectable models are returned. Requires the agents:read scope. # List an agent's skills Source: https://docs.hq.zone/api-reference/agents/list-skills GET /v1/agents/{id}/skills Returns the agent's enabled skill subset as a list of skill slugs. An empty list means the agent uses all skills installed for the workspace. Returns 404 if the agent is not in the caller's workspace. Requires the agents:read scope. # Replace an agent's MCP servers Source: https://docs.hq.zone/api-reference/agents/replace-mcp PUT /v1/agents/{id}/mcp Replaces the agent's enabled MCP-server subset with the supplied list of server slugs and returns the new subset; sending an empty list resets the agent to use all installed MCP servers. Every requested slug must be an MCP server currently installed for the workspace, otherwise the request is rejected (returns 400). Returns 404 if the agent is not in the caller's workspace. Admin only. # Replace an agent's skills Source: https://docs.hq.zone/api-reference/agents/replace-skills PUT /v1/agents/{id}/skills Replaces the agent's enabled skill subset with the supplied list of skill slugs and returns the new subset; sending an empty list resets the agent to use all installed skills. Every requested slug must be a skill currently installed for the workspace, otherwise the request is rejected (returns 400). Returns 404 if the agent is not in the caller's workspace. Admin only. # Set the default agent Source: https://docs.hq.zone/api-reference/agents/set-default POST /v1/agents/{id}/default Promotes the named agent to be the workspace's default agent, atomically clearing the default flag from whichever agent previously held it, and returns the now-default agent. The target must be enabled; a disabled agent cannot be made default (returns 400). Returns 404 if the agent is not in the caller's workspace. Admin only. # Suggest agent instructions Source: https://docs.hq.zone/api-reference/agents/suggest-instructions POST /v1/agents/{id}/suggest-instructions `POST /v1/agents/{id}/suggest-instructions` Reads the tenant's business profile + corpus signals + the agent's current role, asks Claude to draft a tailored system prompt with privacy guards in place. Returns the draft for the admin to review-and-save. Refuses with 503 when no Anthropic key is configured at boot (dev environment without ANTHROPIC_API_KEY). # Update an agent Source: https://docs.hq.zone/api-reference/agents/update-agent PATCH /v1/agents/{id} Updates the named agent's editable fields (slug, display name, description, instructions, tone, verbosity, cautions, languages, aliases, runtime profile, model, avatar URL) and returns the updated agent; only the fields you send are changed, and an explicit null clears nullable fields back to their default. Renaming the slug automatically preserves the old slug as an alias so existing references still route. Validation matches creation (slug/alias rules and collision checks); returns 404 if the agent is not in the caller's workspace. Admin only. # Upload an agent avatar Source: https://docs.hq.zone/api-reference/agents/upload-avatar POST /v1/agents/{id}/avatar `POST /v1/agents/{id}/avatar` - admin uploads an avatar image. Mirrors the business_profile_api logo upload: base64 in, decoded + validated locally, then handed to the internal artifacts publisher which writes Trove + the row. Resulting download URL is stored as the agent's `avatar_url`. # Delete an OAuth client Source: https://docs.hq.zone/api-reference/auth/delete-client DELETE /v1/oauth/register/{client_id} RFC 7592 deregistration of a dynamically registered OAuth client identified by client_id in the path, authenticated with the client's registration_access_token as a Bearer token. Soft-disables the client so it can no longer be used, returning 204 No Content on success. # Get an OAuth client Source: https://docs.hq.zone/api-reference/auth/get-client GET /v1/oauth/register/{client_id} RFC 7592 read of a dynamically registered OAuth client identified by client_id in the path. Authenticated with the client's registration_access_token as a Bearer token (not an HQ session). Returns the client's current metadata including redirect URIs, name, token_endpoint_auth_method, grant and response types, and scopes. The client_secret is never returned here. # OAuth authorization endpoint Source: https://docs.hq.zone/api-reference/auth/oauth-authorize GET /v1/oauth/authorize Starts an OAuth 2.1 authorization-code flow with PKCE, where HQ acts as the authorization server. Requires an active HQ browser session; if the caller is not signed in they are redirected to HQ sign-in and back. Validates the client_id against the client registry, checks that redirect_uri is on the client's allowlist, requires code_challenge_method=S256, and grants the requested scopes intersected with the client's allowed scopes (an empty scope param grants all allowed scopes; requesting only disallowed scopes returns invalid_scope). On success it issues a single-use authorization code and redirects to the client's redirect_uri with code and state query parameters; third-party (non-first-party) clients are first sent to a consent screen unless prior consent already covers the requested scopes. ## Browser redirect endpoint (OAuth 2.1) The start of the **authorization-code + PKCE** flow. This is a front-channel, browser-redirect endpoint — open it in the user's browser, don't call it from a server. HQ authenticates the user (via their `hq-session` cookie), then **302-redirects** back to your registered `redirect_uri` with a single-use `code`. Standard query parameters apply: `response_type=code`, `client_id`, `redirect_uri`, `scope`, `state`, `code_challenge`, and `code_challenge_method=S256`. The granted scope is what you request **intersected** with the client's allowed scopes, and never exceeds the user's own role. Exchange the returned `code` at [the token endpoint](/api-reference/auth/oauth-token). Register a client first via [Register an OAuth client](/api-reference/auth/register-client), or use a first-party client. # OAuth 2.0 Device Authorization Request (RFC 8628 §3.1-3.2) Source: https://docs.hq.zone/api-reference/auth/oauth-device-authorization POST /v1/oauth/device_authorization Starts a device-code flow with PKCE. Returns a `device_code` the client polls `/v1/oauth/token` with (grant_type=urn:ietf:params:oauth:grant-type:device_code) and a short `user_code` the user approves at `verification_uri`. No HQ session is required here - the user authenticates later, on the verification page. # Introspect a token Source: https://docs.hq.zone/api-reference/auth/oauth-introspect POST /v1/oauth/introspect RFC 7662 token introspection: the calling client authenticates (client_id, plus client_secret for confidential clients) and submits a token to check, as form or JSON. Returns active true only for a token that the authenticated client itself issued and that is neither revoked nor expired, along with its scope, client_id, username, token_type, exp, iat, and sub; for any other token (unknown, expired, revoked, or belonging to a different client) it returns active false without leaking details. ## Token introspection (RFC 7662) Reports whether a token is currently active and returns its metadata (scope, expiry, subject). Send the token as a form field `token` (**`application/x-www-form-urlencoded`**). Returns `{ "active": false }` for unknown, expired, or revoked tokens. # Revoke a token Source: https://docs.hq.zone/api-reference/auth/oauth-revoke POST /v1/oauth/revoke RFC 7009 token revocation: the calling client authenticates (client_id, plus client_secret for confidential clients) and submits a token to revoke, as form or JSON. If the token belongs to the authenticating client, it and its entire refresh family (the paired access and refresh tokens plus all rotations) are revoked. Always returns 200, including for unknown, already-revoked, or not-owned tokens, so it never reveals whether a token exists or who owns it. ## Token revocation (RFC 7009) Revokes an access or refresh token. Send the token as a form field `token` (**`application/x-www-form-urlencoded`**). Per the spec it returns success even if the token was already invalid or unknown. # OAuth token endpoint Source: https://docs.hq.zone/api-reference/auth/oauth-token POST /v1/oauth/token Exchanges an authorization code or a refresh token for tokens, accepting either application/x-www-form-urlencoded or application/json. For grant_type=authorization_code it verifies PKCE (S256 code_verifier against the stored challenge) and that client_id and redirect_uri match the original authorization; for grant_type=refresh_token it rotates the presented refresh token, carrying the original scopes forward, and detects reuse of an already-rotated token by revoking the entire token family. Confidential clients must authenticate with client_secret; public clients rely on PKCE. Returns an opaque short-lived Bearer access_token (expires_in seconds), a new rotating refresh_token, the token_type, and the space-delimited granted scope. ## Form-encoded token exchange (OAuth 2.1) Exchanges an authorization `code` for tokens, or rotates a refresh token. The request body is **`application/x-www-form-urlencoded`** (per RFC 6749), not JSON. * `grant_type=authorization_code` — send `code`, `redirect_uri`, `client_id`, and the PKCE `code_verifier` matching the `code_challenge` from the authorize step. * `grant_type=refresh_token` — send `refresh_token`. Refresh tokens **rotate**: each use returns a new one and invalidates the old (reuse is detected and revokes the chain). Returns a short-lived opaque **access token** (use it as `Authorization: Bearer ...`), a rotating **refresh token**, `token_type`, and `expires_in`. Access tokens last \~1 hour; refresh tokens \~30 days. # Register an OAuth client Source: https://docs.hq.zone/api-reference/auth/register-client POST /v1/oauth/register OAuth 2.1 Dynamic Client Registration (RFC 7591). Registration is authenticated: the caller must present a valid HQ session or token, and the resulting client is owned by that user. Validates the submitted JSON metadata (redirect URIs must be https or http loopback with no fragment; scopes must be known capability scopes; token_endpoint_auth_method none yields a public client, client_secret_post/basic a confidential one). Returns 201 with the new client_id, a registration_access_token, and, for confidential clients, a client_secret (the secret and registration token are shown only once), plus a registration_client_uri for managing the client. Registered clients are always treated as third-party and shown the consent screen, and each account is capped on how many it may register. ## Dynamic client registration (RFC 7591) Registers a new OAuth client and returns its `client_id` and registration metadata. Public clients (e.g. browser apps) use PKCE and have no secret. Provide your `redirect_uris` and the scopes the client may request. Afterwards, manage the registration with [Get](/api-reference/auth/get-client) / [Update](/api-reference/auth/update-client) / [Delete](/api-reference/auth/delete-client) using the returned credentials. # Update an OAuth client Source: https://docs.hq.zone/api-reference/auth/update-client PUT /v1/oauth/register/{client_id} RFC 7592 update of a dynamically registered OAuth client identified by client_id in the path, authenticated with the client's registration_access_token as a Bearer token. Re-validates and replaces the mutable metadata (name, redirect URIs, and requestable scopes); the client type and its secret lifecycle are fixed at registration and cannot be changed. Returns the updated client metadata. # Start a checkout session Source: https://docs.hq.zone/api-reference/billing/checkout POST /v1/api/billing/checkout Starts a subscription upgrade by creating a checkout session for the named plan and returns a hosted checkout URL to redirect the customer to. Workspace admin only. The plan_slug must reference an active plan that has a configured price (otherwise 400); the actual plan provisioning happens asynchronously once payment completes. Returns 503 if billing is not configured. ## Returns a Stripe redirect URL This doesn't change the subscription directly — it creates a Stripe Checkout session and returns `{ "url": "https://checkout.stripe.com/..." }`. **Redirect the customer to that URL** to complete payment. The new plan is provisioned asynchronously after Stripe confirms payment, so it appears shortly afterward, not in this response. Admin only; returns `503` if billing isn't configured. # Get my billing usage Source: https://docs.hq.zone/api-reference/billing/my-usage GET /v1/api/me/usage Billing usage for the caller's own tenant (billing B1). Session-scoped (resolved from the workspace + user headers) and admin-gated - credits and spend are workspace-admin information. Reuses the same projection as the operator route `/v1/admin/usage`; see `crate::usage_admin::summarize`. # Open the billing portal Source: https://docs.hq.zone/api-reference/billing/portal POST /v1/api/billing/portal Creates a hosted billing-portal session for the caller's workspace and returns its URL, where an admin can manage payment methods, view invoices, and change or cancel the subscription. Workspace admin only. Works even for workspaces that have never purchased (a billing customer is created on demand). Returns 503 if billing is not configured. ## Returns a Stripe redirect URL Returns `{ "url": "..." }` for Stripe's hosted billing portal (manage payment method, upgrade/downgrade, cancel). **Redirect the customer there.** Admin only. # Buy a credit pack Source: https://docs.hq.zone/api-reference/billing/topup POST /v1/api/billing/topup Buy a one-time credit pack (billing D). Available to ANY tier - a free-tier account gets a Stripe customer minted on demand, same as checkout. The `+topup` lands in credit_ledger when Stripe fires `checkout.session.completed` (mode=payment) at the webhook; the ledger stays authoritative. ## Returns a Stripe redirect URL Creates a one-time payment session for a credit pack and returns `{ "url": "..." }` — **redirect the customer there** to pay. Credits land on the workspace's balance asynchronously once Stripe confirms the payment. Available to any tier. # Create a conversation Source: https://docs.hq.zone/api-reference/conversations/create-conversation POST /v1/api/conversations Creates a new web conversation bound to a chosen agent and returns its identifiers so the client can navigate to the new thread and begin sending messages. Scoped to the caller's workspace; the agent_id must belong to the caller's workspace (otherwise 404). The caller is added as the conversation owner. Returns 402 if the workspace is out of credits, since the first turn would be refused. # Delete an artifact Source: https://docs.hq.zone/api-reference/conversations/delete-artifact DELETE /v1/api/artifacts/{id} Permanently deletes a delivered artifact and its stored bytes. Authorized like the artifact listing: the caller must participate in the artifact's conversation, or, once detached, be the artifact's original producer (otherwise 403). Deleting an attached artifact also removes it from the conversation transcript. Returns the artifact id and a deleted flag; returns 404 if the artifact is not found in the caller's workspace. # Delete a conversation Source: https://docs.hq.zone/api-reference/conversations/delete-conversation DELETE /v1/api/conversations/{id} Permanently deletes a conversation and cascades teardown of its backing app surfaces, sandbox resources, messages, and related records. Scoped to the caller's workspace and conversations they participate in. By default the conversation's delivered artifacts are detached and kept (still downloadable by their existing links); passing delete_artifacts=true permanently deletes those artifacts instead. Returns the conversation id along with counts of apps destroyed and artifacts deleted versus kept. Returns 404 if not found. # Delete a surface Source: https://docs.hq.zone/api-reference/conversations/delete-surface DELETE /v1/api/surfaces/{id} Deletes an app surface, stopping it and releasing its resources. Scoped to the caller's workspace; a workspace admin may delete any app in the workspace, while a non-admin must participate in the surface's backing conversation. Returns the surface id and the deletion outcome. Returns 404 if the surface is not found in the caller's workspace. # Deliver an artifact to a channel Source: https://docs.hq.zone/api-reference/conversations/deliver-artifact POST /v1/api/artifacts/{id}/deliver Pushes one of a conversation's delivered artifacts into a Slack channel the HQ bot belongs to. Used from the Studio when a file the agent produced in a web conversation needs to reach Slack (the automatic reply-to-source mirror only fires for Slack-born turns). The file is uploaded to Slack natively and posted as the conversation's agent with a "Shared from Studio by " note. Scoped to the caller's workspace and a conversation they can see; returns 400 when there is no live Slack install or HQ is not in the channel. # Download an artifact Source: https://docs.hq.zone/api-reference/conversations/download-artifact GET /v1/api/artifacts/{id}/download Downloads the bytes of the named artifact, streamed back with the artifact's original Content-Type and a Content-Disposition: attachment header carrying its filename. Scoped to the caller's own workspace: an artifact belonging to another workspace returns 404. ## Binary response Returns the raw file bytes with the artifact's stored `Content-Type` (not JSON), plus a `Content-Disposition` filename for download. The interactive playground may not render binary — fetch it programmatically and stream the body to a file. # Download conversation artifacts Source: https://docs.hq.zone/api-reference/conversations/download-conversation-artifacts GET /v1/api/conversations/{id}/artifacts/archive Streams a ZIP archive (application/zip) containing all of the conversation's delivered artifacts. Scoped to the caller's workspace and conversations they participate in. Colliding filenames are de-duplicated within the archive. Returns 404 when the conversation has no artifacts to download. ## Binary response (archive) Streams a single archive of all the conversation's artifacts as raw bytes, not JSON. The playground may not render it — fetch programmatically and save the response body to a file. # Get a conversation Source: https://docs.hq.zone/api-reference/conversations/get-conversation GET /v1/api/conversations/{id} Returns metadata for a single conversation the caller can access, including its title, mode (standard or fast), originating channel, surface type, whether it is read-only, the associated agent (id, slug, display name, avatar), and a directory of participants referenced in the thread. Scoped to the caller's own workspace and the conversations they participate in. Workspace admins may pass view=admin to read another member's conversation, which is reflected in the returned viewing_as field. Returns 404 if the conversation is not found. # Interrupt the active turn Source: https://docs.hq.zone/api-reference/conversations/interrupt POST /v1/api/conversations/{id}/interrupt `POST /v1/api/conversations/{id}/interrupt` - the user-facing "Stop". Fires the in-flight turn's abort token: the turn's stream loop breaks, the RunTurn gRPC drops, the vsock to the in-VM adapter tears down, and the adapter hits EOF and interrupts its SDK - the agent actually halts (Claude-CLI Esc). Idempotent: no active turn for this conv -> 200 with `stopped: false`. ## Stops the in-flight turn Signals the conversation's currently-running turn to abort — the user-facing "Stop". The agent halts as soon as it can, and the [event stream](/api-reference/conversations/stream) ends the turn with its terminal event. Idempotent: if nothing is running it returns `200` with `{ "stopped": false }`. # List apps Source: https://docs.hq.zone/api-reference/conversations/list-apps GET /v1/api/apps Returns the workspace's catalog of persistent app surfaces, visible to any member of the workspace, excluding destroyed apps and ordered by most recent activity. Each app includes its id, slug, state, visibility (public or private), run mode, declared port, originating conversation id (null if that conversation was deleted), a ready-to-open visitor URL, and creation/last-activity timestamps. Also returns the workspace's app quota and how many apps currently count against it. # List artifacts Source: https://docs.hq.zone/api-reference/conversations/list-artifacts GET /v1/api/artifacts Lists delivered artifacts (agent-produced deliverables) visible to the caller across their workspace, newest first and capped at 500. A caller sees artifacts from conversations they participate in, plus detached artifacts (whose conversation was deleted) that they originally produced; system assets such as avatars are excluded. Each entry includes name, content type, size, optional caption, a sensitive flag, creation time, originating conversation id and title (null once detached), and a download URL. # List conversation artifacts Source: https://docs.hq.zone/api-reference/conversations/list-conversation-artifacts GET /v1/api/conversations/{id}/artifacts Lists the delivered artifacts for a single conversation in chronological order. Scoped to the caller's workspace and accessible conversations; workspace admins may pass view=admin to view another member's conversation. Each entry includes the artifact id, name, content type, size, a sensitive flag, creation time, and a download URL. Returns only metadata; the bytes are fetched separately via each artifact's download URL. # List conversations Source: https://docs.hq.zone/api-reference/conversations/list-conversations GET /v1/api/conversations Returns a paginated list of the caller's conversations within their workspace, by default newest-activity first. Each row includes the conversation id, channel, mode, last-activity time, title, a short preview of the latest message, the associated agent, an optional attached app, a delivered-artifact count, and, for email threads, from/to/subject. Supports a free-text query over title/agent/preview, sort (recent, oldest, or title), a mode filter (fast vs standard, or all), and a channel filter (email is excluded by default unless explicitly requested). Workspace admins may pass view=admin to list every conversation in the workspace; the response echoes the viewing mode, total match count, and page window. # List conversation messages Source: https://docs.hq.zone/api-reference/conversations/list-messages GET /v1/api/conversations/{id}/messages Returns the conversation's transcript as a sequence-ordered list of journal rows, each carrying its direction, kind, JSON payload, sequence number, turn id, timestamp, and resolved author name/avatar; this is the cold-load companion to the live event stream. Optional query parameters filter the results: since_seq returns only events after a given sequence number (used to fill gaps on stream reconnect), turn_id restricts to a single turn, direction restricts to inbound or outbound, and view=admin lets a workspace admin read a conversation they do not participate in. The caller must have access to the conversation, otherwise 404 is returned. # List conversation surfaces Source: https://docs.hq.zone/api-reference/conversations/list-surfaces GET /v1/api/conversations/{id}/surfaces Lists the live application surfaces (apps) attached to a conversation, excluding destroyed ones, ordered by most recent activity. Scoped to the caller's workspace and accessible conversations; workspace admins may pass view=admin to inspect another member's conversation. Each surface includes its id, slug, state, declared port, run mode, and authentication mode, plus a shareable visitor-facing URL and a separate owner-only developer-embed URL (signed when required). # Start a fast ask Source: https://docs.hq.zone/api-reference/conversations/new-ask POST /v1/api/ask Create an empty `mode='fast'` conversation and return its id. The Studio "New ask" button calls this, then navigates to the thread; the first message runs on the fast lane because the conversation is fast. # Nudge a conversation Source: https://docs.hq.zone/api-reference/conversations/nudge POST /v1/api/conversations/{id}/nudge Buffers an extra text message to be delivered to an agent turn that is currently in progress on the conversation, returning whether it was buffered and how many nudges are now pending. The caller must be a participant of the conversation (404 otherwise), and there must be an active turn to nudge, otherwise the request returns 409. # Post a message to a conversation Source: https://docs.hq.zone/api-reference/conversations/post-message POST /v1/api/conversations/{id}/messages `POST /v1/api/conversations/{id}/messages` -- Phase A.4 (#726). Decoupled from the SSE stream: returns `202 Accepted` after idempotency check, spawns the turn driver in the background, caller observes events via `GET /v1/api/conversations/{id}/stream` (already attached or about to attach). Idempotency is decided IN THIS HANDLER, before spawning. The spawn passes `idempotency_key: None` so the inner pipeline's `prepare_turn` skips its own re-check -- avoids a double SETNX that would log a spurious "duplicate" on the fresh path. ## Asynchronous turn — read the reply from the event stream This endpoint does **not** return the agent's reply. It accepts the message, starts the turn server-side, and returns immediately with `202 Accepted`. You observe progress and read the final reply on the conversation's [event stream](/api-reference/conversations/stream). Typical flow: 1. Open `GET /v1/api/conversations/{id}/stream` (SSE). 2. `POST` the message here → `202 Accepted`. 3. Read this turn's `text_delta` … `final` events off the stream. Send an `Idempotency-Key` header to make retries safe — the same key on the same conversation returns the original turn instead of starting a duplicate (deduplicated for \~1 hour). To stop a turn that's already running, see [Interrupt the active turn](/api-reference/conversations/interrupt). # Promote a fast session Source: https://docs.hq.zone/api-reference/conversations/promote POST /v1/api/fast/{id}/promote Promotes a lightweight fast (quick-ask) conversation into a full standard conversation, binding it to the workspace's default agent so subsequent turns run in the full agent environment seeded with the existing transcript. The caller must be a participant of the conversation (returns 403 otherwise). The promotion is one-way and idempotent: it is a no-op if the conversation is already standard. Requires the conversations:write scope. Promote a fast session to a full hq: flip `mode` off `fast`, one-way. The conversation already holds its transcript, so the next turn in Studio cold-boots a VM seeded with that history via the normal path - no backfill. Idempotent: a no-op if it was already standard. # Rename a conversation Source: https://docs.hq.zone/api-reference/conversations/rename-conversation PATCH /v1/api/conversations/{id} PATCH /v1/api/conversations/{id} - participant renames the conversation. A non-empty title is pinned (title_is_custom = true) so the title.derive worker never overwrites it; an empty title clears both so the conv falls back to auto-derivation. Admin-view callers are intentionally NOT allowed to rename someone else's conv (this is a participant action), so we require default-view access. # Restore a surface Source: https://docs.hq.zone/api-reference/conversations/restore-surface POST /v1/api/surfaces/{id}/restore Initiates restoration of a previously paused or archived app surface so it can run again. Scoped to the caller's workspace, and the caller must be able to access the surface's backing conversation. Returns the surface id and the restore outcome. Returns 404 if the surface is not found in the caller's workspace. # Set surface visibility Source: https://docs.hq.zone/api-reference/conversations/set-visibility POST /v1/api/surfaces/{id}/visibility Sets an app surface's visibility to either private or public, controlling whether its bare URL works for anyone. Scoped to the caller's workspace, and the caller must be able to access the surface's backing conversation. Rejects values other than private or public with 400. Returns the surface id, the resulting visibility, and the underlying auth mode. Returns 404 if the surface is not found or is in a terminal state. # Share a surface Source: https://docs.hq.zone/api-reference/conversations/share-surface POST /v1/api/surfaces/{id}/share Mints a time-limited signed share URL for an app surface that the caller can hand out, without making the surface publicly visible. Scoped to the caller's workspace, and the caller must be able to access the surface's backing conversation. The optional ttl_secs sets the validity window, defaulting to 7 days and constrained to between 1 minute and 30 days (out-of-range values are rejected). Returns the surface id, the tokenized URL, and its expiry as a Unix timestamp. Returns 404 if the surface is not found. # Stream conversation events Source: https://docs.hq.zone/api-reference/conversations/stream GET /v1/api/conversations/{id}/stream Opens a Server-Sent Events stream of a conversation's live turn activity, emitting named events (agent token, tool, and final event kinds, plus stale when the client has lagged and done when the turn closes) each carrying a JSON data payload and an incrementing id sequence. Resume after a disconnect with the standard Last-Event-ID header or the since_seq query parameter; the optional scope parameter narrows the detail level (and is clamped to the caller's token scope), and view=admin lets an admin attach to a conversation they do not participate in. The caller must have access to the conversation, otherwise 404 is returned. ## Server-Sent Events This endpoint is a long-lived **Server-Sent Events (SSE)** stream, not a one-shot JSON response. Open it with an SSE client and keep it open — it emits one event per agent or platform update until you disconnect. ```http theme={null} GET /v1/api/conversations/{id}/stream Authorization: Bearer hq_pat_... Accept: text/event-stream ``` A comment line (`: ping` / `: idle`) is sent periodically as a keepalive so proxies don't drop the connection — ignore it. ### Event shape Each event has an `event:` name, a monotonic `id:` cursor, and a single-line JSON `data:` payload: ```text theme={null} event: text_delta id: 7Z9aQ2 data: {"text":"Looking up the financials"} ``` ### Common events | `event:` | `data` | Meaning | | -------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------- | | `text_delta` | `{ text }` | A chunk of the assistant's reply — append it. | | `status` | `{ message }` | Progress caption. | | `agent_active` | `{ hint }` | Drive a typing indicator. `hint` is diagnostic — don't render it as user-facing text. | | `tool_call` | `{ id, name, scope, args_summary, args_digest }` | The agent invoked a tool. | | `tool_result` | `{ id, is_error, summary }` | The matching tool call finished. | | `token_usage` | `{ model, input_tokens, output_tokens, cost_usd, … }` | Usage and cost for the turn. | | `final` | `{ text, duration_ms }` | **Terminal for the turn** — the reply is complete. | | `error` | `{ message, recoverable }` | **Terminal for the turn** — it failed. | `final`/`error` end a *turn*, not the stream — the next message produces the next batch. New `event:` names may be added over time; ignore ones you don't recognize (standard SSE behavior). ### Reconnecting `id:` is an opaque, incrementing sequence. On reconnect, send the last one you saw as the `Last-Event-ID` header and the server replays the events you missed from the conversation journal. (`EventSource` sets `Last-Event-ID` automatically on auto-reconnect; on a fresh attach where you can't set the header, pass `?since_seq=` instead.) An optional `?scope=` query parameter narrows which events you receive. To send a message and watch the reply, `POST` to [Post a message](/api-reference/conversations/post-message) (returns immediately) and read the result off this stream. # Create a folder Source: https://docs.hq.zone/api-reference/documents/create-folder POST /v1/api/folders Creates a folder in one of the caller's roots. `scope='channel'` requires a `channel_id` the caller belongs to; a `parent_id`, if given, must be a visible folder of the same scope. Names are unique within a parent + scope. Requires documents:write. # Delete a document Source: https://docs.hq.zone/api-reference/documents/delete-document DELETE /v1/api/documents/{id} Moves a document to Trash (soft-delete) by default - the bytes are kept and `POST /v1/api/documents/{id}/restore` brings it back. Pass `?purge=true` to delete it permanently; the stored file content is then removed only when no other document in the workspace references the same bytes, so deduplicated copies are preserved. Only the document's owner may delete it (others receive 403; an unknown document returns 404). Returns 204 No Content. Requires the documents:write scope. # Trash or permanently delete a folder Source: https://docs.hq.zone/api-reference/documents/delete-folder DELETE /v1/api/folders/{id} Soft-deletes a folder and everything under it (descendant folders + the documents they hold travel to Trash together, like Drive/Dropbox). Restore with `POST /v1/api/folders/{id}/restore`. Pass `?purge=true` to permanently delete an already-trashed folder: the subtree folders + their documents are hard-deleted and each document's bytes dropped from storage (dedup-guarded). Private folders are owner-only; team/channel folders are deletable by any member. Requires documents:write. # Download a document Source: https://docs.hq.zone/api-reference/documents/download-document GET /v1/api/documents/{id}/download Streams back the raw bytes of a document as a file attachment, setting the original filename, content type, and content length, with a short private cache lifetime. The document is only served if it is visible to the caller under the same private/channel/team visibility rules as the read endpoints; otherwise a 404 is returned. Requires the documents:read scope. ## Binary response Returns the raw file bytes with the document's stored `Content-Type` (not JSON), plus a `Content-Disposition` filename. The interactive playground may not render binary — fetch it programmatically and stream the body to a file. # Get a document Source: https://docs.hq.zone/api-reference/documents/get-document GET /v1/api/documents/{id} Returns the full metadata for a single document by id, including its filename, content type, size, SHA-256 hash, scope, owner, category, tags, caption, summary, classification status and confidence, detected language and document date, extracted reference numbers and entities, and a download URL. The document is only returned if it is visible to the caller under the private/channel/team visibility rules; otherwise a 404 is returned. Requires the documents:read scope. # List documents Source: https://docs.hq.zone/api-reference/documents/list-documents GET /v1/api/documents Returns the documents visible to the caller, newest first, along with the distinct categories and tags across that visible set for building filter sidebars. Visibility is enforced per request: team-scoped documents are seen by everyone in the workspace, private ones only by their owner, and channel-scoped ones only by members of that channel. Optional query parameters scope, category, channel, and tags (comma-separated, matching documents that carry all listed tags) narrow the results, and limit defaults to 50 and is capped at 200. Requires the documents:read scope. # List folders Source: https://docs.hq.zone/api-reference/documents/list-folders GET /v1/api/folders Returns every folder the caller can see (their private folders, all team folders, and the folders of channels they belong to), flat - the client builds the tree from `parent_id`. Each row carries a live `doc_count`. Requires documents:read. # Reclassify a document Source: https://docs.hq.zone/api-reference/documents/reclassify POST /v1/api/documents/{id}/reclassify Force the classifier worker to take another swing at this document. Owner-only. Resets `classification_status` to `queued`, zeros the rescue retry counter, and re-emits `hq..document.created` so a worker picks it up. Useful when the model returned a bad category, the upload arrived before the worker was up, or the doc terminal-failed and the user wants another go. # Restore a trashed document Source: https://docs.hq.zone/api-reference/documents/restore-document POST /v1/api/documents/{id}/restore Brings a soft-deleted document back from Trash (clears `deleted_at`). If the folder it lived in has since been trashed, it is restored to the root of its scope instead. Owner-only. Returns the restored document. Requires documents:write. # Restore a trashed folder Source: https://docs.hq.zone/api-reference/documents/restore-folder POST /v1/api/folders/{id}/restore Brings a folder and its trashed subtree (descendant folders + their documents) back from Trash. If the folder's own parent is still trashed, it is restored to the root of its scope. Requires documents:write. # Search documents Source: https://docs.hq.zone/api-reference/documents/search-documents GET /v1/api/documents/search Performs a case-insensitive substring search over the filename, caption, summary, and tags of documents the caller can see, returning matches newest first. Visibility rules are the same as the list endpoint (private, channel, and team scopes). Accepts a required q query parameter and an optional limit (default 50, max 200); the categories and tags rollup fields are returned empty for this endpoint. Requires the documents:read scope. # Update a document Source: https://docs.hq.zone/api-reference/documents/update-document PATCH /v1/api/documents/{id} Updates the editable metadata of a document: its scope, channel assignment, category, tags, and caption. Only fields present in the request body are changed; for channel_id, category, and caption, an explicit null clears the value while omitting the field leaves it untouched. Only the document's owner may modify it (others receive 403, and a missing or non-visible document returns 404). Returns the updated document. Requires the documents:write scope. # Rename or move a folder Source: https://docs.hq.zone/api-reference/documents/update-folder PATCH /v1/api/folders/{id} Renames and/or reparents a folder within its scope. A new parent must be a visible folder of the same scope and may not be the folder itself or one of its descendants (no cycles). Private folders are owner-only; team/channel folders are editable by any member. Requires documents:write. # Upload a document Source: https://docs.hq.zone/api-reference/documents/upload-document POST /v1/api/documents Uploads a document by sending its bytes inline as base64 in the JSON body (capped at roughly 12 MiB of file content), together with filename, content type, scope (private, channel, or team; defaults to private), and optional channel_id, category, tags, and caption. The operation is content-addressed and idempotent per owner and scope: re-uploading identical bytes returns the existing document rather than creating a duplicate, and any newly supplied tags, caption, or category are merged onto that existing row (reflected by deduplicated and enriched flags in the response). channel_id is required when scope is channel and rejected otherwise. Returns the document id, download URL, SHA-256, and size. Requires the documents:write scope. # Upload a document (multipart) Source: https://docs.hq.zone/api-reference/documents/upload-multipart POST /v1/api/documents/upload Uploads a single document as multipart/form-data, intended for browser drag-and-drop and accepting larger files than the inline JSON path (up to 64 MiB). The file bytes go in a part named file (or body), with optional text fields scope (private, channel, or team; defaults to private), channel_id, category, tags (comma-separated), and caption. Behavior otherwise matches the inline upload, including content-addressed deduplication and metadata enrichment of an existing identical document. Returns the document id, download URL, SHA-256, and size. Requires the documents:write scope. ## Multipart file upload Send the file as **`multipart/form-data`** (a real binary file part), not JSON. Use this variant for direct uploads from a browser file-picker or a form. The interactive playground's file control posts the part for you; from code, build a multipart body. # Get a help article Source: https://docs.hq.zone/api-reference/help/help-article GET /v1/help/articles/{slug} `GET /v1/help/articles/{slug}` - one article's full markdown body. # List help articles Source: https://docs.hq.zone/api-reference/help/help-articles GET /v1/help/articles `GET /v1/help/articles` - every article's metadata (slug, title, category, order, summary), for the Help & Docs browse view. Global corpus. # Create a help article (operator) Source: https://docs.hq.zone/api-reference/help/help-create-article POST /v1/help/articles `POST /v1/help/articles` - create a new article. Operator-only. The new row is chunked + embedded + indexed before this returns. # Delete a help article (operator) Source: https://docs.hq.zone/api-reference/help/help-delete-article DELETE /v1/help/articles/{slug} `DELETE /v1/help/articles/{slug}` - remove an article. Operator-only. Its chunks cascade-delete and the Torque index is reconciled before returning. # Search the help corpus Source: https://docs.hq.zone/api-reference/help/help-search GET /v1/help/search `GET /v1/help/search?q=...` - hybrid search: Torque BM25 (lexical) UNION pgvector ANN (dense), fused + ordered by a cross-encoder reranker, best chunk per article. The same recall stack workspace search uses. Degrades to dense-only, lexical-only, or a Postgres FTS fallback if a backend is down. # Update a help article (operator) Source: https://docs.hq.zone/api-reference/help/help-update-article PUT /v1/help/articles/{slug} `PUT /v1/help/articles/{slug}` - replace an article's fields. Operator-only. Re-chunked + re-embedded + re-indexed before returning. # Accept a recommendation Source: https://docs.hq.zone/api-reference/integrations/accept-recommendation POST /v1/api/recommendations/{id}/accept Marks the named recommendation as accepted and returns its new status. Scoped to the caller's workspace, so an id from another workspace returns 404. Accepting currently records intent only and does not yet perform the underlying integration connect or skill enable. Requires the agents:write scope. # Ask using the user's browser Source: https://docs.hq.zone/api-reference/integrations/browser-ask POST /v1/agent-browser/ask The dedicated browser path. The extension's "use my browser" button POSTs here, PAT-authed (the same token the WebSocket uses). This is the ONLY entry that runs an agent scoped to the local-browser tools (computer_*) + the browser prompt - normal chat (web / Slack) never sees them, because hq:computer is `default_enabled = FALSE` and the gateway only widens the scope when this turn's `browser_session` flag is set. Runs synchronously and returns the agent's reply. ## Requires a connected browser Runs an agent turn against the caller's **own local browser** using the `computer_*` tools — the only entry point where those tools are enabled. It runs **synchronously** and returns the reply directly (no event stream). The user's browser extension must already hold a live [WebSocket connection](/api-reference/integrations/browser-connect). With no connected browser this returns `403` instead of running a turn that couldn't do anything. Pass `conversation_id` to continue a thread; omit it on the first ask to create one. Store the returned `conversation_id` and send it back on the next ask — the same pattern as the normal turn endpoints. # Browser connect Source: https://docs.hq.zone/api-reference/integrations/browser-connect GET /v1/agent-browser/connect ## WebSocket endpoint This is **not** a plain HTTP `GET` — it's a **WebSocket upgrade**. It's the channel the HQ browser extension dials out on so a remote agent can drive the user's local browser; you don't normally call it yourself. * **Subprotocol:** `hq-agent-browser.v1`. * **Auth:** a browser can't set an `Authorization` header on a WebSocket, so the PAT rides in `Sec-WebSocket-Protocol` as `hq-pat.`, alongside the subprotocol. * **Heartbeat:** \~20 s application-level ping (also keeps idle proxies open). * **Presence:** one live connection per user. The server relays `computer.*` commands down this socket and awaits each result. ```text theme={null} GET /v1/agent-browser/connect Upgrade: websocket Sec-WebSocket-Protocol: hq-agent-browser.v1, hq-pat.hq_pat_xxx ``` Once connected, the agent reaches this browser via [Ask using the user's browser](/api-reference/integrations/browser-ask). # Connect Slack to the current workspace Source: https://docs.hq.zone/api-reference/integrations/connect-slack-install GET /v1/api/connect/slack/install Begins binding a Slack workspace to the caller's EXISTING tenant (the already-signed-in admin's workspace). Unlike the public, invite-gated `/get-started/slack` landing - which provisions a brand-new tenant from the install - this authenticated entry attaches the Slack workspace the admin authorizes to their current tenant. We mint a single-use, short-TTL bind ticket in Forge carrying this tenant's id, then 303-redirect the browser to slack-transport's install flow (same origin) with the ticket nonce; slack-transport owns the Slack authorize URL and threads the tenant into the OAuth `state` so the callback binds rather than creates. Admin only; this is a top-level browser navigation, not an XHR. # Get connection status Source: https://docs.hq.zone/api-reference/integrations/connect-status GET /v1/api/connect/status Returns the workspace's integration connection state and recommendations in one payload: whether Slack and Microsoft Teams are connected (with team/org name when available), the browser-extension download and web-store URLs (null until published), the list of suggested or accepted integration/skill recommendations enriched with catalog name, description, category, icon, confidence, priority, and rationale, and the technology signals detected about the organization's site and DNS. Scoped to the caller's workspace. Requires the agents:read scope. # Download the Teams app package Source: https://docs.hq.zone/api-reference/integrations/connect-teams-package GET /v1/api/connect/teams/package Streams the HQ Microsoft Teams app package (manifest zip) for an admin to upload to their Teams org catalog / sideload. The file path is configured by `HQ_TEAMS_APP_PACKAGE`; unconfigured or missing -> 404. Admin only. The package is the same for every org (the bind happens via the Microsoft sign-in claim, not a personalized package). See docs/teams-microsoft-signin.md. # Connect Microsoft Teams to the current workspace Source: https://docs.hq.zone/api-reference/integrations/connect-teams-start GET /v1/api/connect/teams/start Begins binding a Microsoft Teams org to the caller's EXISTING tenant. Teams has no install redirect HQ controls (unlike Slack), so this starts a verified "Sign in with Microsoft" (Entra OIDC): the callback records a `teams_bind_claims` row tying the admin's AAD org (`tid`) + user (`oid`) to this HQ tenant, and a later Teams app install in that org binds to this tenant when the installer matches. Admin only; top-level browser navigation, not an XHR. See docs/teams-microsoft-signin.md. # Register a private MCP behind a connector Source: https://docs.hq.zone/api-reference/integrations/connector-add-mcp POST /v1/mcp/connectors/{id}/mcp Registers a private MCP server reached through the given connector and installs it (enabled) for the caller's workspace. The MCP is exposed at the connector's local base path (defaulting to `/mcp`) and may carry an optional per-day call cap. Returns the generated catalog slug for the new integration. Admin only; scoped to the caller's own workspace. # Create a connector Source: https://docs.hq.zone/api-reference/integrations/connector-create POST /v1/mcp/connectors Registers a new connector for the caller's workspace and returns a one-time enrollment token (shown only here, never stored) along with the tunnel address and server name the connector agent dials out to. Admin only; scoped to the caller's own workspace. # Enroll a connector Source: https://docs.hq.zone/api-reference/integrations/connector-enroll POST /v1/mcp/connectors/enroll Completes connector enrollment: the connector agent presents its one-time enrollment token and a PEM-encoded certificate signing request, and receives a CA-signed client certificate, the CA certificate, and the tunnel address it should dial. This endpoint is public and authenticated only by the one-time token (the agent has no session); the token is single-use and time-limited. Returns 403 when the token is missing, invalid, expired, or already redeemed. # List connectors Source: https://docs.hq.zone/api-reference/integrations/connector-list GET /v1/mcp/connectors Returns every connector registered in the caller's workspace, newest first, with each connector's id, name, status, last-seen timestamp, and creation time. Admin only; scoped to the caller's own workspace. # Revoke a connector Source: https://docs.hq.zone/api-reference/integrations/connector-revoke DELETE /v1/mcp/connectors/{id} Revokes the given connector in the caller's workspace: its certificate fingerprint and any pending enrollment token are cleared so no new mTLS sessions can be established, and live sessions drop on their next reconnect. Admin only; scoped to the caller's own workspace. Returns 204 No Content. # Delete a skill Source: https://docs.hq.zone/api-reference/integrations/delete-skill DELETE /v1/skills/{slug} Permanently deletes a workspace-owned skill and its install records. Only the caller's own tenant skills (those whose slug carries the tenant prefix) and only workspace-authored (T3) skills may be deleted; attempting to delete a platform skill or another tenant's skill is forbidden. Returns the slug with deleted set to true. Admin only; scoped to the caller's own workspace. # Dismiss a recommendation Source: https://docs.hq.zone/api-reference/integrations/dismiss-recommendation POST /v1/api/recommendations/{id}/dismiss Marks the named recommendation as dismissed and returns its new status. Scoped to the caller's workspace, so an id from another workspace returns 404. Requires the agents:write scope. # Install an MCP server Source: https://docs.hq.zone/api-reference/integrations/install-mcp POST /v1/mcp/installs Installs or re-enables an MCP integration for the caller's workspace, marking it active and enabled. Servers using a tenant credential model (tenant_api_key or tenant_oauth) require a credential reference in the request, which must be provisioned beforehand. Accepts an optional per-tenant config blob. Idempotent: re-installing updates the existing entry and preserves the prior credential reference and config when they are omitted. Returns the slug and enabled flag. Admin only; scoped to the caller's own workspace. # Install a skill Source: https://docs.hq.zone/api-reference/integrations/install-skill POST /v1/skills/installs Installs or re-enables a skill for the caller's workspace, marking it active and enabled. Accepts an optional per-tenant config blob. System-locked skills cannot be installed this way (they are always on) and unknown or inactive slugs return 404. Idempotent: re-installing updates the existing entry and preserves the prior config when omitted. Returns the slug and enabled flag. Admin only; scoped to the caller's own workspace. # Join a Slack channel Source: https://docs.hq.zone/api-reference/integrations/join-channel POST /v1/api/slack/channels/{id}/join `POST /v1/api/slack/channels/{id}/join` (admin). Self-joins HQ to a public channel via `conversations.join`. Idempotent on Slack's side (joining a channel you're already in just succeeds). # List Slack channels Source: https://docs.hq.zone/api-reference/integrations/list-channels GET /v1/api/slack/channels Lists the Slack channels the HQ bot is a member of (each with id, name, and whether it is private), which is also the set of channels HQ can post to, for use in pickers such as the schedule editor. The response includes a connected flag that is false when the workspace has no active Slack installation, in which case the channel list is empty. Scoped to the caller's workspace; requires the agents:read scope. # List joinable Slack channels Source: https://docs.hq.zone/api-reference/integrations/list-joinable-channels GET /v1/api/slack/channels/joinable `GET /v1/api/slack/channels/joinable` (admin). Public channels HQ is NOT a member of - the ones the admin can self-join with one click. Private channels are intentionally excluded: Slack forbids a bot from self-joining them, so they need an `/invite @HQ` from a member. # List Microsoft Teams channels Source: https://docs.hq.zone/api-reference/integrations/list-teams-channels GET /v1/api/teams/channels Lists the standard Teams channels HQ can post to (each with team_id, channel_id, and name), sourced from the workspace corpus catalog the Teams crawl populates, for use in pickers such as the schedule editor. The response includes a connected flag that is false when the workspace has no active Teams installation, in which case the channel list is empty. Scoped to the caller's workspace; requires the agents:read scope. # Get the MCP catalog Source: https://docs.hq.zone/api-reference/integrations/mcp-catalog GET /v1/mcp/catalog Returns the full catalog of available MCP integration servers along with the calling workspace's install state for each. For every active server it reports static metadata (display name, description, category, publisher, transport, trust tier, version, credential model, and any featured ranking) plus per-tenant fields: whether the tenant explicitly enabled or disabled it, the effective enabled state, the install status (active, paused, failed, or reauth_required), the install scopes the operator allows, and an icon URL when one exists. Admin only; scoped to the caller's own workspace. # List an MCP server's tools Source: https://docs.hq.zone/api-reference/integrations/mcp-catalog-tools GET /v1/mcp/catalog/{slug}/tools Returns the captured tool list (name + one-line description) for one catalog server, scoped to the caller's workspace for custom (`t:`) backends. Empty until the backend's schema has been captured. Admin only. # Approve a custom MCP Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-approve POST /v1/mcp/custom/{slug}/approve Approves a custom integration that is held for review (either on first add under an approval-required policy, or after its tool set changed since the last approval). The currently-captured tool set is recorded as the approved baseline and the integration is re-activated so agents can use it again. Only integrations owned by the caller's own workspace can be approved. Admin only. Returns 204 No Content. # Add a custom MCP Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-create POST /v1/mcp/custom Provisions a private custom MCP integration for the caller's workspace from a pasted server URL. The server is re-probed and must be self-serve connectable; the workspace custom-integration policy is enforced first. A private catalog entry is created and, for open (no-auth) servers, enabled immediately (or held for review when the policy requires approval); OAuth and API-key servers return the next step the caller must take to finish connecting. Returns the new slug, display name, credential model, and that next step. Admin only; scoped to the caller's own workspace. # Remove a custom MCP Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-delete DELETE /v1/mcp/custom/{slug} Deletes a custom integration the caller's workspace previously added, along with its install rows, stored credentials, and per-agent enablement. Only integrations owned by the caller's own workspace (slug prefix `t:`) can be removed here; vetted platform/third-party integrations cannot. Admin only. Returns 204 No Content. # Set a custom MCP's daily call cap Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-limits PUT /v1/mcp/custom/{slug}/limits Sets or clears the per-day call cap for one of the caller's workspace's custom integrations; a null or zero value removes the cap (uncapped). Only integrations owned by the caller's own workspace can be limited here. Admin only. Returns 204 No Content. # Get the custom-MCP policy Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-policy-get GET /v1/mcp/custom/policy Returns the caller's workspace policy for self-serve custom MCP integrations: whether custom integrations are enabled, the allow-list and block-list of domains, and whether newly added integrations require admin approval before agents can use them. Admin only; scoped to the caller's own workspace. # Update the custom-MCP policy Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-policy-put PUT /v1/mcp/custom/policy Replaces the caller's workspace policy for self-serve custom MCP integrations: toggles whether custom integrations are allowed at all, sets the allow-list and block-list of domains (each normalized to a bare host), and sets whether newly added integrations must be approved by an admin before agents can use them. Returns the stored policy. Admin only; scoped to the caller's own workspace. # Probe a custom MCP URL Source: https://docs.hq.zone/api-reference/integrations/mcp-custom-probe POST /v1/mcp/custom/probe Dry-run discovery for a pasted MCP server URL: detects the server's authentication method (none, API key, or OAuth), reports whether the workspace can finish connecting it self-serve, and previews the server's tool list - without writing anything. The URL is checked against the workspace's custom-integration policy before any outbound call is made. Admin only; scoped to the caller's own workspace. # Search the public MCP ecosystem (Discover) Source: https://docs.hq.zone/api-reference/integrations/mcp-directory-search GET /v1/mcp/directory/search Read-only search over the wild MCP directory - public servers that exist in the open ecosystem, NOT the integrations this workspace runs. Each hit notes whether it is hostable (addable as a custom integration). Admin only; 503s when the directory database is not configured. # Public MCP directory size (Discover landing) Source: https://docs.hq.zone/api-reference/integrations/mcp-directory-stats GET /v1/mcp/directory/stats Read-only counts over the wild MCP directory for the Discover empty-state. Admin only; 503s when the directory database is not configured. # Get an MCP catalog icon Source: https://docs.hq.zone/api-reference/integrations/mcp-icon GET /v1/mcp/catalog/{slug}/icon Returns the SVG brand icon for the given MCP server as image/svg+xml. The response is public, immutable, and long-cached; a 404 is returned when the server has no icon or is not active. # Set an MCP server API key Source: https://docs.hq.zone/api-reference/integrations/set-mcp-key POST /v1/mcp/installs/{slug}/api_key Stores an API key credential for an MCP server and installs/enables it in one call, for servers whose credential model is tenant_api_key only. The scope may be team (shared across the workspace, the default) or user (private to the caller); the chosen scope must be among the server's allowed scopes, and user scope requires a resolvable calling user. The supplied key is securely sealed and, where the backend supports it, validated against the upstream before being saved; an invalid key is rejected. Idempotent: pasting a new key for an existing install rotates the credential in place. Returns the slug, enabled flag, the stored credential reference id, and the confirmed scope. Admin only; scoped to the caller's own workspace. # Get skill content Source: https://docs.hq.zone/api-reference/integrations/skill-content GET /v1/skills/catalog/{slug}/content Returns the full content of a skill pack, including its SKILL.md (listed first) and any additional files, with the skill's display name, description, runtime profile, and trust tier. Inline text files include their UTF-8 contents; large external assets are listed but returned with empty content. The editable flag is true only for the caller's own workspace-authored skills and false for platform skills. Requires agents read access; scoped to the caller's own workspace. # Get a skill icon Source: https://docs.hq.zone/api-reference/integrations/skill-icon GET /v1/skills/catalog/{slug}/icon Returns the SVG icon for the given skill as image/svg+xml. The response is public, immutable, and long-cached; a 404 is returned when the skill has no icon or is not active. # Get the skills catalog Source: https://docs.hq.zone/api-reference/integrations/skills-catalog GET /v1/skills/catalog Returns the full catalog of available skills along with the calling workspace's install state for each. For every active skill it reports metadata (display name, description, category, publisher, runtime profile, version, trust tier, and any featured ranking), whether it is system-locked (always on), its declared prerequisites, and its required integrations each annotated with whether that integration is currently met for this tenant. It also reports whether the tenant explicitly enabled or disabled the skill, the effective enabled state (always true when locked), the install status, and an icon URL when one exists. Requires agents read access; scoped to the caller's own workspace. # Uninstall an MCP server Source: https://docs.hq.zone/api-reference/integrations/uninstall-mcp DELETE /v1/mcp/installs/{slug} Disables an MCP integration for the caller's workspace, setting it to not enabled (this works even for servers enabled by default with no prior explicit install). Also clears any stored tenant credential for that server so a later re-install must supply a fresh one. Returns the slug with enabled set to false. Admin only; scoped to the caller's own workspace. # Uninstall a skill Source: https://docs.hq.zone/api-reference/integrations/uninstall-skill DELETE /v1/skills/installs/{slug} Disables a skill for the caller's workspace, opting it out even if it is enabled by default with no prior explicit install. System-locked skills cannot be disabled (they are always on). Returns the slug with enabled set to false. Admin only; scoped to the caller's own workspace. # Upload a skill Source: https://docs.hq.zone/api-reference/integrations/upload-skill POST /v1/skills/upload Creates a workspace-owned skill from caller-supplied content. The body may be either inline markdown (wrapped automatically as SKILL.md) or a multi-file pack of base64-encoded files that must include a SKILL.md at the root. The display name must be 3 to 60 characters of letters, digits, spaces, hyphens, or underscores and is used to derive the slug; an optional runtime profile (claude-sdk, hermes, or openai-agents; defaults to claude-sdk) and an optional capability slot may be set. Size limits apply (up to 50 files, 256 KiB total raw content, 64 KiB markdown, and a 1 MB request limit). Re-uploading with the same derived slug updates the existing skill in place. Returns the resulting slug and version with HTTP 201. Admin only; scoped to the caller's own workspace. # Create a new workspace Source: https://docs.hq.zone/api-reference/me/create-workspace POST /v1/api/me/workspaces Greenfield-creates a brand-new tenant owned by the caller and switches the session into it - the authenticated, in-product counterpart to the public magic-link `/v1/auth/signup` funnel. Shares the exact same atomic provisioning (`signup::provision_email_tenant`), so the new workspace gets the identical onboarding flow; the only differences are that the owner is taken from the caller's verified session email (no re-entry, no magic-link round-trip) and the session cookie is re-minted for the new tenant on the way out. Still invite-gated: an `invite_code` is required and consumed single-use, so an authenticated member can't mint workspaces freely. Web-session only - a PAT / OAuth token is pinned to one workspace and can't create another. Idempotency: the single-use invite row is the HARD guard (no double-create even under concurrency or a cache outage). An optional `Idempotency-Key` header adds soft lost-response replay - a retry with the same key returns the already-created workspace instead of a spurious "invite already used". # Erase my own data Source: https://docs.hq.zone/api-reference/me/erase-me POST /v1/api/me/erase `POST /v1/api/me/erase` - self-erasure. Any authenticated user can request this on their own data. No admin role required. # Get the signed-in user Source: https://docs.hq.zone/api-reference/me/get-me GET /v1/api/me The caller's own self-view, scoped to their identity: an identity block (display name, email, locale, timezone, admin/bot flags, connected-workspace source, profile-consent state, and clock/timezone display preferences), an optional persona block summarizing the user's distilled profile (`null` if not yet generated), quick counts such as the number of schedules owned, the workspace onboarding state, and an `out_of_credits` flag indicating whether the workspace has run out of credits. # List the workspaces the signed-in person can reach Source: https://docs.hq.zone/api-reference/me/my-workspaces GET /v1/api/me/workspaces Returns every workspace the caller's verified email can sign into (policy-passing - the same `signin_decision` gate as sign-in), with the active (current-session) one flagged. This is the read-only foundation of the cross-tenant workspace switcher (P1); re-scoping the session to another workspace (the active-tenant signed claim) is P2. When the session identity carries no email, only the current workspace is returned. # Switch the active workspace Source: https://docs.hq.zone/api-reference/me/switch-workspace POST /v1/api/me/workspaces/switch Re-scopes the session to another workspace the caller can reach (workspace switcher P2). Verifies the caller's verified email has a policy-passing membership in the target - the identical `signin_decision` gate as sign-in, so this never grants access a fresh sign-in wouldn't - then re-mints the vault-sealed session cookie for the target identity (Pattern 2: instant, no Slack re-auth). Returns 200 + a fresh `Set-Cookie`; the SPA reloads into the new workspace. 403 if the caller has no eligible membership in the target. # Update my profile Source: https://docs.hq.zone/api-reference/me/update-me PATCH /v1/api/me `PATCH /v1/api/me` - update the caller's own profile preferences (clock format + timezone). Self-scoped: the caller is resolved from the session headers (the same pair `me` reads), so it can only ever write its own row. Either field may be omitted; only the supplied ones change. # Upload my avatar Source: https://docs.hq.zone/api-reference/me/upload-my-avatar POST /v1/api/me/avatar `POST /v1/api/me/avatar` - the caller uploads their own profile image. Mirrors the agent-avatar upload: base64 in, decoded + validated locally, then handed to the internal artifacts publisher (Trove), and the resulting internal download URL is stored as the caller's `workspace_users.image_url`. Self-scoped (resolved from the session, never another user). EMAIL-ORIGIN only: connector (Slack/Teams) users get their avatar synced from upstream, so a local upload would be clobbered by the next sync - reject rather than mislead. Boundary enforced here, not just hidden in the UI. # Correct a fact about me Source: https://docs.hq.zone/api-reference/memory/correct-fact POST /v1/memory/about-me/{fact_id}/correct Corrects one of the assistant's remembered facts about the calling user by superseding it with a user-supplied replacement (1 to 4096 characters), preserving the original fact's type, confidence, agent, and source. The fact must currently be active and about the caller. Returns the id of the superseded fact and the id of the newly created corrected fact. Scoped to the caller's own account. # Forget a fact about me Source: https://docs.hq.zone/api-reference/memory/forget-fact DELETE /v1/memory/about-me/{fact_id} Forgets one of the assistant's remembered facts about the calling user, marking it superseded with no replacement so it is no longer surfaced. Idempotent: returns a status of "forgotten" when the fact was active, or "already_superseded_or_unknown" when it was already gone or never existed (no error in that case). Scoped to the caller's own account. # Freeze an agent's memory Source: https://docs.hq.zone/api-reference/memory/freeze POST /v1/memory/freeze/{agent_slug} Freezes the named agent out of the calling user's memory, revoking that agent's ability to read facts about the caller. Accepts an optional reason. Idempotent: re-freezing updates the stored reason and timestamp. Returns the agent slug with frozen set to true. Scoped to the caller's own account. # List facts about me Source: https://docs.hq.zone/api-reference/memory/list-facts GET /v1/memory/about-me Returns the facts the assistant currently remembers about the calling user, scoped to the caller's own account. Each fact includes its id, text, type, confidence, the agent that asserted it, when it was asserted, and the source conversation id. The response also includes a distilled one-paragraph persona summary (and when it was last generated, if available) and the distinct fact types present across the full set for use as filters. Supports filtering by agent slug and fact type, page sizing via limit (default 25, max 200), and forward pagination via an opaque cursor that returns null once the end is reached. # List freezable agents Source: https://docs.hq.zone/api-reference/memory/list-freezable-agents GET /v1/memory/agents Returns every enabled agent in the caller's workspace alongside the calling user's own freeze state for each: whether it is frozen, when it was frozen, and the reason. Intended to drive a per-user "agents that can read your memory" toggle list. Scoped to the caller's own account. # List memory freezes Source: https://docs.hq.zone/api-reference/memory/list-freezes GET /v1/memory/freeze Returns the list of agents the calling user has frozen out of their memory, each with the agent slug, the optional reason given, and when the freeze was created, ordered most recent first. Scoped to the caller's own account. # Unfreeze an agent's memory Source: https://docs.hq.zone/api-reference/memory/unfreeze DELETE /v1/memory/freeze/{agent_slug} Unfreezes the named agent for the calling user, re-granting that agent's ability to read facts about the caller. Idempotent. Returns the agent slug with frozen set to false. Scoped to the caller's own account. # Unregister a device token Source: https://docs.hq.zone/api-reference/notifications/delete-device-token DELETE /v1/api/device-tokens/{token} Removes the caller-tenant's registration for this device token (called on sign-out). Scoped to the caller's workspace; APNs feedback prunes the rest. # Delete an inbox message Source: https://docs.hq.zone/api-reference/notifications/delete-inbox DELETE /v1/api/inbox/{id} Permanently deletes one of the caller's inbox messages. Scoped to the caller's own inbox; returns 404 if the message does not exist or is not theirs. # Dismiss a notification Source: https://docs.hq.zone/api-reference/notifications/dismiss-notification POST /v1/api/notifications/{id}/dismiss Dismisses a single notification so it no longer appears in the notification list, recording the dismiss time. Scoped to the caller's workspace and to notifications addressed to the caller or workspace-wide; always returns ok. # List inbox messages Source: https://docs.hq.zone/api-reference/notifications/list-inbox GET /v1/api/inbox Returns a paginated page of the caller's personal in-app inbox messages (agent-delivered notifications such as scheduled-task digests), with each message's title, body, source and read state, plus the total matching count, the workspace-wide unread count for the nav badge, and the current page and page size. Scoped to the caller's own inbox; admins do not see other users' inboxes. Supports an unread-only filter, a case-insensitive free-text search over title, body and schedule name, paging (page and page_size 1-100, default 25), and a sort of recent (default) or oldest. # List notifications Source: https://docs.hq.zone/api-reference/notifications/list-notifications GET /v1/api/notifications Returns the caller's in-app notification center: up to 100 non-dismissed notifications (newest first), each with its kind, title, body, optional call-to-action, severity and status, plus a count of how many are still unread for the bell badge. Scoped to the caller's workspace and includes both notifications addressed to the caller and workspace-wide ones visible to any member. # Mark all inbox messages read Source: https://docs.hq.zone/api-reference/notifications/mark-all-inbox-read POST /v1/api/inbox/read_all Marks all of the caller's unread inbox messages as read. Scoped to the caller's own inbox and idempotent (returns ok even when nothing was unread). # Mark all notifications read Source: https://docs.hq.zone/api-reference/notifications/mark-all-notifications-read POST /v1/api/notifications/read-all Marks all of the caller's unread notifications as read and returns the number updated. Scoped to the caller's workspace and to notifications addressed to the caller or workspace-wide. # Mark an inbox message read Source: https://docs.hq.zone/api-reference/notifications/mark-inbox-read POST /v1/api/inbox/{id}/read Marks one of the caller's inbox messages as read, preserving the original read timestamp if it was already read. Scoped to the caller's own inbox; returns 404 if the message does not exist or is not theirs. # Mark an inbox message unread Source: https://docs.hq.zone/api-reference/notifications/mark-inbox-unread POST /v1/api/inbox/{id}/unread Marks one of the caller's inbox messages as unread by clearing its read timestamp. Scoped to the caller's own inbox; returns 404 if the message does not exist or is not theirs. # Mark a notification read Source: https://docs.hq.zone/api-reference/notifications/mark-notification-read POST /v1/api/notifications/{id}/read Marks a single notification as read and records the read time. Scoped to the caller's workspace and to notifications addressed to the caller or workspace-wide; only affects a notification currently in the unread state and always returns ok. # Register a device for push Source: https://docs.hq.zone/api-reference/notifications/register-device-token POST /v1/api/device-tokens Upserts the caller's APNs device token for the current workspace. Idempotent per `(token, tenant)`: a re-register from the same device updates the owning user, platform, bundle id, environment and refreshes `last_seen_at`. # Check a domain Source: https://docs.hq.zone/api-reference/onboarding/check-domain GET /v1/api/onboarding/domain/check `GET /v1/api/onboarding/domain/check?domain=` - live pre-check for the wizard so a typo is caught before submit. Returns the normalized host + whether it has a valid shape + whether it resolves. # Complete onboarding Source: https://docs.hq.zone/api-reference/onboarding/complete-onboarding POST /v1/api/onboarding/complete Marks the caller's workspace as having completed onboarding, which lifts the onboarding gate that otherwise blocks normal API access for a new workspace. The operation is idempotent: it only sets the completion timestamp if onboarding was not already complete. Admin only (returns 403 otherwise). Returns a simple ok acknowledgement. # Get onboarding status Source: https://docs.hq.zone/api-reference/onboarding/onboarding-status GET /v1/api/onboarding/status Returns the current onboarding state for the caller's workspace: whether onboarding has been completed, whether the business domain has been confirmed, the configured business domain if any, and a wizard track value (slack, teams, or web) indicating which onboarding flow applies. Scoped to the caller's own workspace. # Set onboarding domain Source: https://docs.hq.zone/api-reference/onboarding/set-domain POST /v1/api/onboarding/domain Sets and confirms the workspace's business domain during onboarding. The submitted value is normalized to a bare hostname and validated for shape and live DNS resolution, rejecting typos, unresolvable domains, and private or internal addresses with a 400; on success the domain is recorded as confirmed and a profile crawl of that website is started. Admin only (returns 403 otherwise). Returns a simple ok acknowledgement. # Cancel a run Source: https://docs.hq.zone/api-reference/runs/cancel-run POST /v1/api/runs/{id}/cancel Cancels a run still in flight (created/running/suspended) - sets it to cancelled, stamps finished_at, and drops its pending timers/awakeables. A no-op (ok=false) if the run already finished. The caller must own the run's schedule or be an admin (404 if the run isn't visible). Requires the schedules:write scope. # List runs Source: https://docs.hq.zone/api-reference/runs/list-runs GET /v1/api/runs Lists schedule runs (one row per executed fire) newest-first, with a total for pagination. scope=mine (default) returns only runs of the caller's own schedules; scope=workspace returns all runs in the workspace and is admin only (403 otherwise). status filters to all (default), active (created/running/suspended), or failed. Pass schedule_id for one schedule's history - it is gated owner-or-admin (404 otherwise). limit defaults to 50 (max 200). Requires the schedules:read scope. # Cancel a schedule Source: https://docs.hq.zone/api-reference/schedules/cancel-schedule DELETE /v1/api/schedules/{id} Cancels a schedule and archives it, stopping all future runs while retaining its history. Only the schedule's owner or an admin may cancel it (others receive 403). Returns an ok acknowledgement. Requires the schedules:write scope. # Create a schedule Source: https://docs.hq.zone/api-reference/schedules/create-schedule POST /v1/api/schedules Creates a new schedule that periodically runs an agent with a given prompt and delivery target, according to the supplied trigger. If agent_id is omitted the workspace's default enabled agent is used, and a non-existent agent_id returns 404. The new schedule is owned by the caller. Returns 201 with the created schedule; if the workspace plan's schedule limit has been reached the request fails with 402. Requires the schedules:write scope. # Erase an archived schedule Source: https://docs.hq.zone/api-reference/schedules/erase-schedule DELETE /v1/api/schedules/{id}/erase Permanently erase an archived schedule. Owner or admin only; engine refuses to erase non-archived rows so the operator must hit the Cancel button first. Past `hq_flow.instances` rows survive with `schedule_id = NULL` (ON DELETE SET NULL on the FK). Future hardening: emit an audit-log entry for the right-to- erasure trail, and gate workspace-wide schedules behind an extra admin-role check. For now, the same owner-or-admin gate as cancel applies - anyone who can cancel can also erase, but only after archive. # Fire a schedule now Source: https://docs.hq.zone/api-reference/schedules/fire-now POST /v1/api/schedules/{id}/fire_now Triggers an immediate run of the schedule without waiting for its next scheduled time, leaving the regular firing cadence unchanged. Only the schedule's owner or an admin may fire it (others receive 403). Returns an ok acknowledgement. Requires the schedules:write scope. # Get a schedule Source: https://docs.hq.zone/api-reference/schedules/get-schedule GET /v1/api/schedules/{id} Returns the full detail of a single schedule by id, including its name, description, trigger, run arguments, current lifecycle state, fire and failure counts, last and next fire times, and a link to the conversation from its most recent run. The schedule is only returned if the caller owns it or is an admin; otherwise a 404 is returned. Requires the schedules:read scope. # List schedule owners Source: https://docs.hq.zone/api-reference/schedules/list-owners GET /v1/api/schedules/owners `GET /v1/api/schedules/owners` (admin) - distinct schedule owners in the workspace with a count each. Powers the admin "filter by user" dropdown so it lists only users who actually have schedules (not every member), and stays bounded regardless of how many schedules exist. # List schedules Source: https://docs.hq.zone/api-reference/schedules/list-schedules GET /v1/api/schedules Lists scheduled automated runs along with a total count for pagination. By default (scope=mine) it returns only the caller's own schedules; scope=workspace returns all schedules in the workspace and is admin only (returns 403 otherwise), optionally narrowed to one owner via owner_user_id. Results can be filtered by lifecycle state, and archived schedules are excluded unless include_archived is set or an explicit state filter is given; limit defaults to 100 (max 500) and offset applies to the workspace view. Each schedule includes its trigger, name, current state, fire and failure counts, and last and next fire times. Requires the schedules:read scope. # Pause a schedule Source: https://docs.hq.zone/api-reference/schedules/pause-schedule POST /v1/api/schedules/{id}/pause Pauses an active schedule so it stops firing until resumed. Only the schedule's owner or an admin may pause it (others receive 403). Returns an ok acknowledgement. Requires the schedules:write scope. # Resume a schedule Source: https://docs.hq.zone/api-reference/schedules/resume-schedule POST /v1/api/schedules/{id}/resume Resumes a previously paused schedule so it begins firing again, returning the newly computed next fire time when the schedule was successfully resumed. Only the schedule's owner or an admin may resume it (others receive 403). Requires the schedules:write scope. # Update a schedule Source: https://docs.hq.zone/api-reference/schedules/update-schedule PATCH /v1/api/schedules/{id} Updates an existing schedule's name, description, trigger, or run arguments; only the fields supplied are changed, and an explicit null description clears it while omitting it keeps the current value. Only the schedule's owner or an admin may update it (others receive 403). Returns an acknowledgement that includes the recomputed next fire time when the trigger changed. Requires the schedules:write scope. # Search conversations Source: https://docs.hq.zone/api-reference/search/search-conversations GET /v1/api/search Full-transcript hybrid search (lexical BM25 + dense vector, reciprocal-rank fused, then cross-encoder reranked) over the caller's conversations within their workspace. Returns message-level hits - each carries the conversation, the matched message's sequence number (a jump-to-message deep link), a highlighted snippet, and a relevance score - newest-relevance first. Scoped to conversations the caller participates in. Cursor-paginated. # Add a field to a table Source: https://docs.hq.zone/api-reference/tables/add-field POST /v1/api/tables/{id}/fields # Create a table Source: https://docs.hq.zone/api-reference/tables/create-table POST /v1/api/tables # Delete a row Source: https://docs.hq.zone/api-reference/tables/delete-row DELETE /v1/api/tables/{id}/rows/{row_id} # Delete a table Source: https://docs.hq.zone/api-reference/tables/delete-table DELETE /v1/api/tables/{id} # Drop a field Source: https://docs.hq.zone/api-reference/tables/drop-field DELETE /v1/api/tables/{id}/fields/{field_id} # Export a table as CSV Source: https://docs.hq.zone/api-reference/tables/export-table-csv GET /v1/api/tables/{id}/export.csv Streams the table's live rows as a UTF-8 CSV attachment (RFC 4180, BOM for Excel, formula-injection defanged). Keyset-paged server-side so the response is constant-memory and never capped at the grid's page size. Full export (no filters) in v1. Requires the tables:read scope. # Get a table with its fields Source: https://docs.hq.zone/api-reference/tables/get-table GET /v1/api/tables/{id} # Insert rows Source: https://docs.hq.zone/api-reference/tables/insert-rows POST /v1/api/tables/{id}/rows # List tables Source: https://docs.hq.zone/api-reference/tables/list-tables GET /v1/api/tables # Query rows Source: https://docs.hq.zone/api-reference/tables/query-rows POST /v1/api/tables/{id}/rows/query # Update a row Source: https://docs.hq.zone/api-reference/tables/update-row PATCH /v1/api/tables/{id}/rows/{row_id} # Create an OAuth app Source: https://docs.hq.zone/api-reference/tokens/create-app POST /v1/api/oauth/apps Registers a new OAuth application owned by the authenticated caller, validating the supplied client metadata (redirect URIs must be https or http loopback with no fragment, scopes must be known capability scopes). Returns the created app including its client_id and, for confidential clients, a client_secret, plus a registration_access_token used for later RFC 7592 management; the secret and registration token are shown only once and cannot be retrieved again. Each account is limited in how many apps it may register. # Create an API token Source: https://docs.hq.zone/api-reference/tokens/create-token POST /v1/api/tokens Creates a new personal access token for the authenticated caller, returning the plaintext token exactly once (it cannot be retrieved again) along with its id, name, scopes, and optional expiry. Accepts a name, an optional list of capability scopes (resource:action, e.g. documents:read; omitting scopes defaults to full non-admin access), and an optional expires_in_days (omitted means non-expiring). Each scope must be a known capability or legacy tier, and requesting the admin scope requires the caller to have the admin role. The token's effective permissions are always clamped to the caller's role at request time. # Delete an OAuth app Source: https://docs.hq.zone/api-reference/tokens/delete-app DELETE /v1/api/oauth/apps/{client_id} Disables (deregisters) an OAuth app owned by the authenticated caller, identified by client_id in the path. Once disabled the client can no longer be used and its issued tokens stop working. Returns a deleted flag, or 404 if the caller does not own an active app with that client_id. # List OAuth authorizations Source: https://docs.hq.zone/api-reference/tokens/list-authorizations GET /v1/api/oauth/authorizations Lists the third-party OAuth applications the authenticated caller has authorized (consented to). Each entry includes the client_id, app name, client_type, an active flag indicating whether the app is still registered and enabled, the union of scopes the user has granted it, and timestamps for when it was first authorized and last updated. First-party apps such as the browser extension never appear here since they skip consent. # List OAuth apps Source: https://docs.hq.zone/api-reference/tokens/list-oauth-apps GET /v1/api/oauth/apps Lists the OAuth applications the authenticated caller has registered, scoped to the caller's own active (non-disabled) apps. Each entry includes the client_id, name, client_type (public for PKCE-only or confidential for clients with a secret), redirect_uris, requestable scopes, and creation timestamp, ordered newest first. # List token scopes Source: https://docs.hq.zone/api-reference/tokens/list-scopes GET /v1/api/tokens/scopes Returns the vocabulary of resource:action capability scopes a personal access token can be minted with. Each entry lists the scope string, a human-readable description of what it allows, and a requires_admin flag indicating whether granting it requires the admin role. Requires authentication. # List API tokens Source: https://docs.hq.zone/api-reference/tokens/list-tokens GET /v1/api/tokens Lists the authenticated caller's own live personal access tokens. Scoped to the caller's manually created tokens that are not revoked and not expired; OAuth-issued access and refresh tokens (those tied to a client) are deliberately excluded. Each entry includes the token id, name, kind, granted scopes, and creation, last-used, and expiry timestamps, ordered newest first. # Revoke an OAuth authorization Source: https://docs.hq.zone/api-reference/tokens/revoke-authorization DELETE /v1/api/oauth/authorizations/{client_id} Revokes the authenticated caller's authorization for a third-party OAuth app, identified by client_id in the path. This removes the consent and immediately revokes all of that app's live access and refresh tokens for this user, so the app's next API call fails and it must request authorization again. Returns a revoked flag and tokens_revoked count, or 404 if the caller has no authorization for that client_id. Scoped strictly to the caller's own grant; it never affects other users or apps. # Revoke an API token Source: https://docs.hq.zone/api-reference/tokens/revoke-token DELETE /v1/api/tokens/{id} Revokes one of the authenticated caller's own personal access tokens, identified by its id in the path. The revocation takes effect immediately. Scoped to the caller's own tokens, so it cannot revoke another user's token. Returns a revoked flag, or 404 if no matching live token belongs to the caller. # Update an OAuth app Source: https://docs.hq.zone/api-reference/tokens/update-app PUT /v1/api/oauth/apps/{client_id} Updates the mutable metadata (name, redirect URIs, and requestable scopes) of an OAuth app owned by the authenticated caller, identified by client_id in the path. The client type and secret lifecycle are fixed at registration and cannot be changed here. New metadata is validated with the same rules as on creation. Returns the updated app, or 404 if the caller does not own an active app with that client_id. # API conventions Source: https://docs.hq.zone/api/conventions Base URL, versioning, data formats, IDs, and the patterns shared across every HQ endpoint. ## Base URL & transport All requests go to `https://api.hq.zone` over HTTPS; plain HTTP is redirected to HTTPS. ## Versioning Every path carries a `/v1/` prefix (e.g. `/v1/api/conversations`). Backwards-incompatible changes ship under a new prefix; additive changes — new endpoints, new optional request fields, new response fields — can appear within `v1`, so write clients that **ignore unknown fields**. ## Authentication Send a bearer token on every request: `Authorization: Bearer hq_pat_...` (a [personal access token](/get-started/authentication)) or an OAuth 2.1 access token. Each endpoint's required permission is listed under its **Authorizations** and in [Scopes](/api/scopes). ## Content types * Most endpoints accept and return **`application/json`**. * The OAuth `token`/`introspect`/`revoke` endpoints accept **`application/x-www-form-urlencoded`** (or JSON) — see the [OAuth guide](/guides/oauth). * File uploads use **`multipart/form-data`** (e.g. [Upload a document](/api-reference/documents/upload-multipart)); some take base64 in a JSON field. * File downloads return **raw bytes** with the stored `Content-Type`, not JSON. ## Identifiers & timestamps * Resource IDs are **UUIDs**. * Timestamps are **RFC 3339 / ISO 8601** strings in UTC (e.g. `2026-06-10T09:14:00Z`). ## Idempotency Endpoints that start work accept an idempotency token so retries are safe. For turns, pass `idempotency_key` in the [message body](/api-reference/conversations/post-message); re-sending the same key on the same conversation returns the original turn instead of starting a duplicate (deduplicated for 24 hours). ## Pagination List endpoints that can grow are bounded. Where paging is supported (e.g. [List activity](/api-reference/admin/list-activity)) use `limit` (1–200, default 50), `offset`, and `sort` (`recent` default, or `oldest`). Other list endpoints return a capped, newest-first set (artifacts, for example, cap at 500). ## Errors Failures return the JSON body `{ "error": "" }` with a standard HTTP status — see [Errors](/api/errors). ## Realtime & binary Conversation turns stream over **Server-Sent Events**, and file endpoints return **binary** — neither maps onto a plain JSON client. Handle them as shown in [Stream a chat](/guides/streaming-chat) and [Work with artifacts](/guides/artifacts). # Errors Source: https://docs.hq.zone/api/errors How HQ reports failures: the error body shape and the status codes you'll see. Every failed request returns a standard HTTP status code and a JSON body with a single `error` field describing what went wrong: ```json theme={null} { "error": "message is handled, not awaiting_review" } ``` Branch on the **HTTP status**. Treat `error` as a human-readable message for logs and developers, not a stable machine code. ## Status codes | Status | Meaning | Typical cause | | --------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `400 Bad Request` | Malformed, or not valid for the resource's current state | Missing/invalid field, an unknown enum value, or a wrong-state action (e.g. replying to a message that isn't `awaiting_review`) | | `401 Unauthorized` | No valid credential | Missing, malformed, expired, or revoked token | | `402 Payment Required` | A plan or credit limit blocks the action | Out of credits; the plan's email-inbox limit reached | | `403 Forbidden` | Authenticated but not allowed | The token lacks the required [scope](/api/scopes); not an admin; not a participant of the resource | | `404 Not Found` | No such resource for this caller | Unknown id — or a resource in another workspace | | `409 Conflict` | Collides with existing state | e.g. an email address already in use | | `429 Too Many Requests` | Rate limit exceeded | See [Rate limits](/api/rate-limits) | | `503 Service Unavailable` | A dependency isn't configured or available | e.g. billing not configured | | `500 Internal Server Error` | Unexpected server error | Retry; if it persists, contact support | For resources outside your workspace HQ returns `404`, not `403`, so the API never reveals whether an id you can't access exists. # Generate a client (SDK) Source: https://docs.hq.zone/api/generate-a-client Generate a typed client for any language from HQ's OpenAPI spec. HQ publishes a complete **OpenAPI 3.1** spec: ``` https://api.hq.zone/openapi.json ``` Every operation has a clean, unique `operationId` (e.g. `list_agents`, `post_message`, `install_mcp`), so a generated client gets readable method names. Point any OpenAPI generator at the spec: ```bash openapi-generator theme={null} # TypeScript (fetch) npx @openapitools/openapi-generator-cli generate \ -i https://api.hq.zone/openapi.json \ -g typescript-fetch -o ./hq-client # Python npx @openapitools/openapi-generator-cli generate \ -i https://api.hq.zone/openapi.json \ -g python -o ./hq-client ``` ```bash Speakeasy theme={null} speakeasy generate sdk \ --schema https://api.hq.zone/openapi.json \ --lang typescript --out ./hq-client ``` ```bash Fern theme={null} # point fern.config.json at the spec, then: fern generate --group ts-sdk ``` Set the client's base URL to `https://api.hq.zone` and send your bearer token (see [Authentication](/get-started/authentication)) on every request. Re-generate whenever the spec changes. Because `operationId`s are stable and unique, method names stay consistent across regenerations. Streaming (SSE) and binary downloads don't map onto a generated JSON client. Handle the [event stream](/guides/streaming-chat) and [artifact downloads](/guides/artifacts) directly, as those guides show. # Rate limits Source: https://docs.hq.zone/api/rate-limits Where HQ throttles requests, and how to handle a 429. HQ rate-limits its most abuse-sensitive endpoints **per client IP**. Exceed a limit and you get `429 Too Many Requests`; back off and retry. ## OAuth endpoints The OAuth endpoints — `/v1/oauth/authorize`, `/v1/oauth/token`, `/v1/oauth/introspect`, `/v1/oauth/revoke` — allow a **burst of 30 requests**, then refill at **1 request per second**, keyed on the caller's IP. That's well above a normal sign-in or token-refresh cadence; it only bites credential-stuffing-style bursts. ## Handling a 429 * Treat `429` as transient: retry with **exponential backoff and jitter**. * Don't hammer the token endpoint — refresh an access token shortly **before** it expires (\~1 hour), not on every request. * The limiter is IP-keyed, so all of one backend's calls share a bucket; spread bursty traffic out. Most data endpoints aren't IP-rate-limited today, but treat any `429` as a signal to back off — limits can tighten as the API grows. # Scopes Source: https://docs.hq.zone/api/scopes The resource:action permission vocabulary that tokens and OAuth clients grant from. HQ uses a `resource:action` scope vocabulary. A [personal access token](/get-started/authentication) or [OAuth client](/guides/oauth) is granted a set of these, and each endpoint lists the scope it requires under its **Authorizations**. ## The vocabulary | Scope | Grants | | --------------------- | --------------------------------------------------------------- | | `conversations:read` | Read your conversations and their messages | | `conversations:write` | Start conversations and send messages on your behalf | | `documents:read` | Read your documents library | | `documents:write` | Upload and manage documents in your library | | `schedules:read` | View your scheduled tasks | | `schedules:write` | Create and manage scheduled tasks | | `agents:read` | View the agents in your workspace | | `agents:write` | Create and configure agents | | `memory:read` | Read what the assistant remembers about you | | `memory:write` | Correct or delete what the assistant remembers | | `billing:read` | View usage and billing information | | `admin` | Administer the workspace — users, settings, integrations, audit | ## How scopes resolve * **A token never exceeds its user's role.** The effective permissions are the user's role capabilities **intersected** with the token's granted scopes. A non-admin's token that asks for `admin` is silently clamped — never escalated. * **`admin` is role-gated.** Only a user with the admin role can hold it. An admin token can do everything a member token can, plus workspace administration. * **Request least privilege.** Ask only for the scopes you use. For OAuth, the granted set is your request **intersected** with the client's allowed scopes; requesting only scopes the client isn't allowed yields `invalid_scope`. * **Unknown scopes are ignored** (forward-compatible) — a scope added later won't break an existing token. Legacy coarse tiers still work: `user` (or `integrator`) grants every non-admin scope; `admin` grants everything. New integrations should use the explicit `resource:action` scopes above. # Web & browser control Source: https://docs.hq.zone/concepts/browser How HQ specialists research the live web and drive a real browser — including the user's own browser — to finish work on sites with no API. HQ specialists don't stop at static knowledge: they reach the **live web** and act on it. The browser is part of [qOS](/concepts/qos), and the broader picture lives in [How HQ works](/concepts/how-hq-works). ## Research on the live web A specialist opens real pages, clicks, fills forms, and pulls out what it finds, the way a person would — from the region you choose, reaching sources, regions, and sites behind a login that an ordinary assistant gets blocked from. Answers come back with their sources, not a confident guess. This matters because ordinary automation gets blocked on sight: most tools announce themselves, behave like a script, and render in ways a real machine never would. HQ's browser is built to look and behave like a real person on a real machine, so an agent can get legitimate work done on the sites your team already uses — including those with no API. A web browser built in Rust, driven from the platform — not a stripped-down automation shell. Natural mouse curves, reading-pace pauses, and varied scrolling, so a session reads as genuine use rather than a script. Renders on genuine hardware, so pages render exactly as they would on a real computer. A proxy pool with rotation, plus leak prevention, so locale, timezone, and geo are pinned to the egress. ## Full browser control An agent gets a full-featured browser it can read and act through: it sees the rendered page, fills forms, clicks, uploads files, and follows multi-step flows on sites with no API — all while looking like a genuine visitor. A clean command API covers navigation, clicking, typing, form-fill, file upload, screenshots, PDF export, cookies, and storage, so an agent can drive any website end to end. ## Driving the user's own browser Beyond research on its own egress, an agent can also drive **the user's own browser** — useful for sites and sessions that live in front of the person, not on a server. → Connect and drive it through the [Browser control API](/api-reference/integrations/browser-connect). Driving the machine itself — running turns and streaming the agent's work back — happens over [conversations and turns](/guides/streaming-chat). Web research and browser control are tools the agent reaches for inside that loop. # How HQ works Source: https://docs.hq.zone/concepts/how-hq-works The architecture behind HQ: a roster of specialists, a real isolated machine per conversation, and qOS — the agentic OS we built in Rust. Most AI tools stop at the conversation — they answer and hand the work back to you. HQ starts where they stop: you `@mention` a specialist and it **researches, decides, and does the work**, then reports back. This page explains the machinery behind that, and where each piece surfaces in the API. ## A roster of specialists You don't get one generic assistant — you assemble specialists, each with its own model, skills, integrations, and tone, reachable by an `@handle`. The right specialist picks up a thread and stays with it from request to done. → Configure them with the [Agents API](/api-reference/agents/list-agents) (`agents:read` / `agents:write`). ## A real machine behind every conversation The difference between *chatting* and *doing* is a computer. Every conversation runs on its own **private, hardware-isolated machine** — the same class of isolation behind modern serverless platforms. It boots in a fraction of a second and resumes exactly where it left off, even days later. Because it's a real machine, a specialist can run a script, crunch a file, drive a browser, build a small tool, and install what it needs — instead of only telling you how. → Drive that machine through [conversations and turns](/guides/streaming-chat); deliverables come back as [artifacts](/guides/artifacts) and live [surfaces](/api-reference/conversations/list-surfaces). ## qOS — the agentic operating system That machine runs **qOS**, the operating system we built for agents — in Rust, top to bottom. We didn't staple it together from other people's APIs; we built the data layer ourselves: Hybrid search across everything, microsecond shared memory, object storage for every artifact, and a queryable graph of connected data. A real inbox that sends and receives, a real web browser, PDF parsing, and structured extraction from any file. Frontier-model routing, plus memory that remembers and learns from work. Composable, per-agent skills and connectors to the tools you already use. ## The right model for each job Decision intelligence needs more than one model. HQ routes every call across the frontier — Anthropic, OpenAI, xAI, and Cerebras — and sends each task to the model that wins on quality, latency, or cost. The high-volume, data-sensitive work — the embeddings and reranking behind memory and search — runs on open models on **our own GPUs**, so your most sensitive text never leaves our infrastructure to be turned into numbers. → See what's available via [List models](/api-reference/agents/list-models), and select one per agent. ## Research you can act on HQ specialists browse the **live public web** the way a person does — from the region you choose, reaching sources and logged-in tools an ordinary assistant can't — and hand back answers with their sources, not a confident guess. Agents can also drive the user's own browser. → [Browser control API](/api-reference/integrations/browser-connect). ## Memory that compounds Specialists remember and consolidate between sessions, and arrive knowing your workspace's channels and people. You can always see what a specialist knows, and correct, delete, or freeze it. → [Memory API](/api-reference/memory/list-facts) (`memory:read` / `memory:write`). ## Trust is the foundation, not a setting Anything that can act needs a trust model that holds. Every action a specialist takes is **bound to the person who asked and the permission they were granted**, checked at each step, and written to a log that **cannot be edited after the fact**. You choose whether your data lives in the **EU or the US**, and HQ is built under GDPR and the EU AI Act from the first line. → Permissions are [scopes](/api/scopes); the record is the [Audit API](/api-reference/admin/list-audit). HQ is invite-only while we onboard teams. Slack and the browser extension are live today, with Microsoft Teams on the way. # Memory that compounds Source: https://docs.hq.zone/concepts/memory What HQ remembers between sessions, how specialists arrive knowing your workspace, and the controls you have to view, correct, delete, or freeze what they know. A specialist that forgets everything between sessions starts from zero every time. HQ specialists don't. They remember the work, arrive knowing your workspace, and get sharper the more your team relies on them — while leaving you in control of everything they know. For how this fits the rest of the architecture, see [How HQ works](/concepts/how-hq-works). ## Knows your workspace from day one From the first message, a specialist already knows your channels, people, and the documents you connect. It reads your team's past conversations — with consent — into a private index at install, so its very first reply fits how you already work, with no setup or re-explaining. Inviting the bot opts a channel in; removing it pauses. ## Remembers across sessions Memory persists between conversations and compounds over time: Preferences per person — like how you want briefs written — so replies stay in your style. Facts about the accounts you work, shared across the team, so context carries between people. The steps that worked for recurring tasks, so the work gets faster each time it runs. A specialist pulls the relevant background into each answer on its own, so you don't re-supply context. Memory consolidates while a specialist is idle, so it sharpens with use rather than just accumulating. ## Yours to govern You can always see what a specialist knows, then **correct, delete, or freeze** it. Memory is something you govern, not a black box — and that governance maps directly to the API. Edit, delete, and freeze controls over stored data support your data-protection obligations under GDPR. → Read and manage what a specialist knows through the [Memory API](/api-reference/memory/list-facts) (`memory:read` / `memory:write`). # Models & inference Source: https://docs.hq.zone/concepts/models How HQ routes every agent call across the frontier and serves the sensitive, high-volume work on its own GPUs — one model layer beneath qOS. Decision intelligence needs more than one model. **Agent Inference** is the model layer beneath HQ: every agent reaches frontier models through one interface, routed to whichever fits the task, alongside open models HQ serves on its own GPUs. This page is part of [qOS](/concepts/qos) and complements [How HQ works](/concepts/how-hq-works). ## Multi-model routing Every agent reaches frontier models from **Anthropic, OpenAI, xAI, and Cerebras** behind one interface. Each call goes to the model that fits the task — quality, latency, or cost — so the platform follows the frontier as it moves rather than being wired to whichever vendor was integrated first. Picking a model is part of defining an agent, not a buried platform setting. Give a research agent a frontier reasoning model and a triage agent a fast, small one, and run them side by side in the same workspace. Give each agent the model that fits its job, and run a fleet where every member is on a different model at once. If a provider errors or goes down, the call retries against a healthy one inside the same request. → See what's available via [List models](/api-reference/agents/list-models), and select one per agent. ## Own-GPU inference for sensitive work There is a quieter problem underneath model choice: most agent platforms ship your data to a third-party API just to embed or rerank it — the highest-volume calls they make. HQ answers this by serving the cheap, constant, and data-sensitive paths on hardware it runs itself. Open-weight models run on our own GPUs, so the high-volume and data-sensitive paths never have to leave our infrastructure. The vectors behind memory and search come from an embedding model we host, so indexed text is never sent to an outside API to be turned into numbers. A self-hosted reranking model does the final relevance pass on memory and corpus lookups, with no third-party round-trip. Large non-interactive jobs run through a batch lane for work that can wait rather than answer in the moment. The split is deliberate: frontier models for the hard, rare reasoning; owned open models for the cheap, constant, and sensitive work — not a degraded fallback. ## Independent of the runtime The model and the runtime are two separate dials. Each agent runs on a vendor's official agent loop — the Claude Agent SDK, the OpenAI Agents SDK, or the open OpenCode runtime — and any model can run under any of those runtimes, so each choice is made on its own merits. The model layer sits inside qOS next to search, cache, and storage, sharing the same hardware, isolation, and audit trail as everything else an agent touches. Adding or swapping a model is a config change, with nothing to alter in the agents on top. # qOS — the agentic operating system Source: https://docs.hq.zone/concepts/qos qOS is the operating system HQ built for agents, in Rust, top to bottom — a data layer of its own systems rather than a stack of stapled-together APIs. Every HQ conversation runs on a real, hardware-isolated machine, and that machine runs **qOS** — the operating system we built for agents. It is written in Rust, top to bottom. We didn't staple it together from other people's APIs; we built the data layer ourselves, so agents never wait on someone else's infrastructure. For where this fits in the wider picture — the roster of specialists and the machine behind each conversation — see [How HQ works](/concepts/how-hq-works). ## Why build the layer ourselves The systems below run in production for large-scale ingestion. Building them ourselves, in Rust, is a choice about performance and robustness: an agent reaches search, cache, storage, a graph, email, a browser, documents, and extraction without leaving the platform, and the model layer and memory sit right next to them, sharing the same hardware, isolation, and audit trail. ## The data layer Hybrid keyword and semantic search across everything, served from memory. Typesense-compatible, rebuilt in Rust. Microsecond-class shared memory — a multi-threaded, Redis-class in-memory store with a same-machine shared-memory path. Object storage for every artifact — an S3-compatible, masterless store with self-healing and erasure coding. Query connected data — an in-memory graph database speaking openCypher and ISO GQL over Neo4j-compatible Bolt. ## Content & I/O Send and receive real email — a two-way mail platform that authenticates and classifies inbound, with the full DKIM, SPF, DMARC, and ARC stack. Drive a real web browser — a custom browser built in Rust that behaves like a person on the live web. See [Web & browser control](/concepts/browser). Read and parse PDFs — a native-quality document engine with text extraction, forms, redaction, and signing. Pull data out of any file — one Rust library for image metadata and PDF text, images, and structure. ## Runtime Frontier models, and our own — multi-model routing across providers, plus open models on GPUs we run. See [Models & inference](/concepts/models). Remembers and learns from work — a layered memory system that consolidates between sessions, with user-facing governance. Composable, per-agent skills — enable, disable, or tailor them per agent; an agent can install what else it needs. Connect the tools you use — MCP-native, with local CLIs first-class, all in one safe environment. Each agent reaches a broad range of tools through MCP and locally installed CLIs and skills, all in one sandbox that behaves like a normal Linux server, fully the agent's. # Security, isolation & trust Source: https://docs.hq.zone/concepts/security How HQ keeps real work safe: a hardware-isolated machine per conversation, bound identity and a tamper-evident audit log, EU or US data residency, and independent certification. Agents that run shell, browse the web, and touch your SaaS need a security model that holds up. HQ isolates every conversation in its own machine, keeps your data in the region you choose, and writes an audit trail under every action. For how this fits the rest of the architecture, see [How HQ works](/concepts/how-hq-works). ## A machine per conversation Most platforms isolate customers with software boundaries on shared infrastructure. HQ goes a layer deeper: the boundary is a separate machine per conversation. Every conversation runs in its own microVM, isolated at the hardware level — not just a separate process on a shared kernel. It's the same isolation primitive behind serverless platforms at scale. Each thread gets its own microVM, memory, and identity. Nothing is shared between workspaces, and a sandbox is torn down when its work is done. Sandboxes snapshot and resume, so state persists for a conversation without persisting on shared infrastructure. Egress is controlled and country-pinned, so an agent reaches only what you allow, from where you expect. ## Bound identity and a tamper-evident audit log Identity and audit are the spine, built into every action rather than bolted on after. Every agent action carries an **identity chain** — who asked, which agent acted, on whose authority, and what it touched — and lands in an **immutable audit log** that cannot be edited after the fact. The result is a full, exportable history for your security and compliance teams. Every integration credential is encrypted at rest and scoped to a single tool. Authorize only what you want, revoke at any time, and toggle integrations per workspace. → Permissions are [scopes](/api/scopes); the record is the [Audit API](/api-reference/admin/list-audit). ## EU or US data residency You choose the region your data lives in. HQ runs two separated, isolated datacenters — one in the EU and one in the US — on hardware operated end to end, with no dependency on a hyperscaler in another jurisdiction. Your data stays in the region you choose. Data is encrypted in transit and at rest, and is never used to train models. ## Compliance * **EU AI Act** — an identity chain, immutable audit log, and human oversight give the traceability and accountability the Act expects from higher-risk AI. Built for it from the start, not bolted on. * **GDPR** — data residency, per-tool credential scoping, and edit, delete, and freeze controls support your data-protection obligations. * **Independently certified** — audited and certified to ISO 27001, ISO 14001, and ISO 9001 by an accredited registrar. # Authentication Source: https://docs.hq.zone/get-started/authentication Authenticate with a personal access token, or the OAuth 2.1 flow for apps acting on a user's behalf. All requests go to `https://api.hq.zone` over HTTPS. Every endpoint lists the scope it needs under **Authorizations**; HQ uses a `resource:action` scope vocabulary (e.g. `agents:read`, `documents:read`, `conversations:write`, `admin`). A token can never exceed the role of the user it belongs to. ## Personal access tokens (server-to-server) For backend integrations, authenticate with a **Personal Access Token (PAT)** sent as a bearer token: ```bash theme={null} curl https://api.hq.zone/v1/api/me \ -H "Authorization: Bearer hq_pat_..." ``` A workspace admin issues PATs with [Create an API token](/api-reference/tokens/create-token); the secret is shown once at creation. The token's scopes cap what it can do. Treat a PAT like a password — it carries your workspace access. Keep it in a secret manager; never put it in client-side code or version control. ## OAuth 2.1 (apps acting for a user) For apps that act on behalf of a signed-in user (a browser extension, a third-party integration), use the **authorization-code + PKCE** flow: Register once via [Dynamic Client Registration](/api-reference/auth/register-client) (RFC 7591), or use a first-party client. Public clients use PKCE and have no secret. Send the user's browser to [`/v1/oauth/authorize`](/api-reference/auth/oauth-authorize) with a `code_challenge` (method `S256`). HQ signs the user in and redirects back to your `redirect_uri` with a single-use `code`. POST the `code` and `code_verifier` to [`/v1/oauth/token`](/api-reference/auth/oauth-token) (form-encoded) to receive a short-lived access token and a rotating refresh token. Use the access token as `Authorization: Bearer ...`. Refresh it at the token endpoint before it expires (\~1 hour); refresh tokens rotate on every use. The granted scope is what you request intersected with the client's allowed scopes, capped by the user's role. Full details on the [Authentication endpoints](/api-reference/auth/oauth-authorize). ## Verify your token ```bash theme={null} curl https://api.hq.zone/v1/api/me -H "Authorization: Bearer $HQ_TOKEN" ``` A `200` with your identity confirms the token is valid; a `401`/`403` means it's missing, expired, or lacks the scope. # Quickstart Source: https://docs.hq.zone/get-started/quickstart Make your first authenticated calls and talk to an agent. This walks through your first few calls with a [personal access token](/get-started/authentication). Export it first: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` ```bash theme={null} curl https://api.hq.zone/v1/api/me -H "Authorization: Bearer $HQ_TOKEN" ``` Returns your identity, workspace, and onboarding state. ```bash theme={null} curl https://api.hq.zone/v1/agents -H "Authorization: Bearer $HQ_TOKEN" ``` Each agent has an `id`, `slug`, name, model, and status. Copy an `id` for the next step. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/conversations \ -H "Authorization: Bearer $HQ_TOKEN" \ -H "Content-Type: application/json" \ -d '{"agent_id":""}' ``` Returns the new conversation's `id`. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/conversations//messages \ -H "Authorization: Bearer $HQ_TOKEN" \ -H "Content-Type: application/json" \ -d '{"text":"Summarize our latest board deck."}' ``` This returns `202 Accepted` with a `stream_url` — the turn runs server-side on the agent's machine. The reply doesn't come back in that response — you read it live over the event stream. Open the conversation's event stream and render the agent's response as it happens. # Configure HQ agents Source: https://docs.hq.zone/guides/agents List, create, update, enable/disable, default, and equip agents with skills, MCP servers, and avatars over the HQ API. An **agent** is a configurable persona in your workspace: a routing slug, a display name, system-prompt instructions, personality settings, a runtime profile and model, and an enabled subset of skills and MCP servers. This guide walks the full lifecycle using the `/v1/agents` endpoints. All requests go to the base URL `https://api.hq.zone` and authenticate with a personal access token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." # Authorization: Bearer $HQ_TOKEN ``` Read operations require the `agents:read` scope. Every write operation (create, update, disable, enable, set default, replace skills/MCP, upload avatar, suggest instructions) requires the `admin` scope. Each endpoint is scoped to your own workspace; you can never see or modify another workspace's agents. ## Discover what's available Returns every agent in your workspace, ordered with the default agent first, then enabled agents, then by slug. See [List agents](/api-reference/agents/list-agents). ```bash theme={null} curl https://api.hq.zone/v1/agents \ -H "Authorization: Bearer $HQ_TOKEN" # → { "agents": [ { "id": "...", "slug": "...", "display_name": "...", # "is_default": true, "status": "enabled", ... } ] } ``` Each agent carries `id`, `slug`, `display_name`, `description`, `instructions`, `instructions_is_default`, `tone`, `verbosity`, `cautions`, `languages`, `aliases`, `runtime_profile`, `model`, `delivery_mode`, `is_default`, `status`, `avatar_url`, and `created_at`. The agent editor's model picker. Pass the optional `runtime` query parameter (`claude-sdk`, `openai-agents`, or `opencode`) to restrict to one runtime profile; otherwise all selectable models are returned. See [List models](/api-reference/agents/list-models). ```bash theme={null} curl "https://api.hq.zone/v1/models?runtime=claude-sdk" \ -H "Authorization: Bearer $HQ_TOKEN" # → { "models": [ { "slug": "...", "display_name": "...", "family": "...", # "runtime_profile": "claude-sdk", "vendor": "...", # "is_default": true } ] } ``` A model is only valid for an agent if its `runtime_profile` matches the agent's `runtime_profile`. Pick a `slug` from this list whose `runtime_profile` equals the runtime you plan to use. ## Create an agent Only `slug` and `display_name` are required. Everything else is optional. See [Create agent](/api-reference/agents/create-agent). ```bash theme={null} curl -X POST https://api.hq.zone/v1/agents \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{ "slug": "cfo", "display_name": "Anna the CFO", "description": "Finance questions for the leadership team.", "instructions": "You are Anna, the CFO assistant.", "tone": "formal", "verbosity": "concise", "cautions": ["Do not quote private legal opinions"], "languages": ["en", "sv"], "aliases": ["anna", "finance"], "runtime_profile": "claude-sdk", "model": "claude-opus-4-8" }' # → the created agent (same shape as a list entry) ``` The request accepts: `slug`, `display_name`, `description`, `instructions`, `tone`, `verbosity`, `cautions`, `languages`, `aliases`, `runtime_profile`, `model`, `avatar_url`, `enabled_skill_slugs`, and `enabled_mcp_slugs`. * **`slug`** and each entry of **`aliases`** must be 2-32 characters, lowercase ASCII letters/digits/hyphens, not starting or ending with a hyphen, with no `--`, and not a reserved token (`hq`, `me`, `help`, `default`, `none`, `agent`, `anyone`, `all`, `system`, `admin`, `bot`). An alias must differ from the slug and must not collide with any other agent's slug or alias in the workspace. * **`tone`** must be one of `formal`, `friendly`, `direct`, `casual` (or omitted). * **`verbosity`** must be one of `concise`, `balanced`, `detailed` (or omitted). * **`instructions`** is capped at 8 KiB; longer content should live in a skill. * **`languages`** are BCP-47 codes (e.g. `en`, `sv`, `pt-BR`), max 8. * **`cautions`** are short phrases, max 120 characters each, max 8 items. * **`runtime_profile`** defaults to `claude-sdk` if omitted. * **`model`** must be a selectable model belonging to `runtime_profile`; omit it to use the runtime's platform default. If you omit `avatar_url`, an avatar is generated automatically for the new agent (best-effort, asynchronous). To set one explicitly at create time, `avatar_url` must be an internal artifact path produced by the avatar upload flow — external URLs are rejected. See [Upload an avatar](#upload-an-avatar) below. A bad slug, an alias conflict, or an out-of-range field returns `400`. ## Update an agent `PATCH /v1/agents/{id}` changes only the fields you send; omitted fields are left unchanged. For nullable fields (`description`, `instructions`, `tone`, `verbosity`, `model`, `avatar_url`), sending an explicit `null` clears the value back to its default. See [Update agent](/api-reference/agents/update-agent). ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/agents/ \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{ "display_name": "Anna (Finance)", "verbosity": "balanced", "description": null }' # → the updated agent ``` The request accepts the same editable fields as create: `slug`, `display_name`, `description`, `instructions`, `tone`, `verbosity`, `cautions`, `languages`, `aliases`, `runtime_profile`, and `model`, `avatar_url`. Slug and alias rules match creation, including the collision check. Renaming the slug automatically preserves the old slug as an alias, so existing `@hq ` references keep routing. Writing any `instructions` value (including clearing it) sets `instructions_is_default` to `false`. A `400` is returned for an invalid slug, alias conflict, or bad field; `404` if the agent is not in your workspace. ## Enable, disable, and set the default Sets `status` to `disabled` so it stops routing on every surface. The default agent cannot be disabled. See [Disable agent](/api-reference/agents/disable-agent). ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/agents/ \ -H "Authorization: Bearer $HQ_TOKEN" # → the now-disabled agent ``` Disabling the default agent returns `400` — promote another agent to default first. Flips `status` back to `enabled`. It is idempotent — calling it on an already-enabled agent is a no-op. See [Enable agent](/api-reference/agents/enable-agent). ```bash theme={null} curl -X POST https://api.hq.zone/v1/agents//enable \ -H "Authorization: Bearer $HQ_TOKEN" # → the re-enabled agent ``` Atomically clears the default flag from whichever agent held it and sets this one. The target must be enabled. See [Set default](/api-reference/agents/set-default). ```bash theme={null} curl -X POST https://api.hq.zone/v1/agents//default \ -H "Authorization: Bearer $HQ_TOKEN" # → the now-default agent ``` A disabled agent cannot be made the default — that returns `400`. All three return `404` if the agent is not in your workspace. ## Attach skills and MCP servers Each agent has an enabled **subset** of skills and MCP servers. An **empty list means "use everything installed for the workspace."** The `PUT` endpoints **fully replace** the current subset — they do not merge with what's already there. See [List skills](/api-reference/agents/list-skills) and [List MCP](/api-reference/agents/list-mcp). ```bash theme={null} curl https://api.hq.zone/v1/agents//skills \ -H "Authorization: Bearer $HQ_TOKEN" # → { "enabled": ["..."] } (empty = all installed) curl https://api.hq.zone/v1/agents//mcp \ -H "Authorization: Bearer $HQ_TOKEN" # → { "enabled": ["..."] } (empty = all installed) ``` Send the complete `enabled` list. Each slug must be a skill currently installed for the workspace. See [Replace skills](/api-reference/agents/replace-skills). ```bash theme={null} curl -X PUT https://api.hq.zone/v1/agents//skills \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"enabled": ["web-search", "calendar"]}' # → { "enabled": ["calendar", "web-search"] } ``` Same contract for MCP servers. See [Replace MCP](/api-reference/agents/replace-mcp). ```bash theme={null} curl -X PUT https://api.hq.zone/v1/agents//mcp \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"enabled": ["github"]}' # → { "enabled": ["github"] } ``` These are **replace, not merge**. The request body is the new complete subset — any slug you leave out is removed. To reset an agent to "all installed," send `{"enabled": []}`. If any requested slug is not installed for your workspace, the whole request is rejected with `400`. A missing agent returns `404`. ## Upload an avatar `POST /v1/agents/{id}/avatar` uploads an avatar image. The image is sent as **base64 in a JSON body** (not multipart). The body has three fields: `filename`, `content_type`, and `body_b64`. See [Upload avatar](/api-reference/agents/upload-avatar). ```bash theme={null} curl -X POST https://api.hq.zone/v1/agents//avatar \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d "{ \"filename\": \"anna.png\", \"content_type\": \"image/png\", \"body_b64\": \"$(base64 -w0 anna.png)\" }" # → the agent, with its new avatar_url ``` * `content_type` must be one of `image/png`, `image/jpeg`, `image/svg+xml`, `image/webp`, or `image/gif`. * The decoded image must be non-empty and at most 2 MiB. * The handler stores the bytes and writes the resulting internal artifact path into the agent's `avatar_url`. An empty, oversized, or unsupported-type image returns `400`; a missing agent returns `404`. You generally do not set `avatar_url` directly on create/update — only an internal artifact path produced by this upload is accepted there. ## Suggest tailored instructions `POST /v1/agents/{id}/suggest-instructions` drafts a tailored system prompt for the agent based on your workspace's profile and the agent's current role, and returns it for review. See [Suggest instructions](/api-reference/agents/suggest-instructions). ```bash theme={null} curl -X POST https://api.hq.zone/v1/agents//suggest-instructions \ -H "Authorization: Bearer $HQ_TOKEN" # → { "instructions": "You are Anna, the CFO assistant for ..." } ``` The draft is **never auto-saved**. Review it, then persist it yourself with a follow-up update: ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/agents/ \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"instructions": ""}' ``` A `404` is returned if the agent is not in your workspace; a `500` is returned if the tailor feature is disabled (no Anthropic key configured on the control plane). # Work with artifacts Source: https://docs.hq.zone/guides/artifacts List, download, archive, and delete the files (artifacts) an agent produces. When an HQ agent produces a deliverable — a chart, a PDF, a report — it publishes an **artifact**: the bytes live in object storage and a row records the metadata. Each artifact has a stable id and a download URL of the shape `/v1/api/artifacts/{id}/download`. This guide covers listing artifacts (workspace-wide and per-conversation), downloading an artifact's raw bytes, downloading a whole conversation as a ZIP archive, and deleting an artifact. All requests go to `https://api.hq.zone` and authenticate with a personal access token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` The endpoints in this guide carry these scopes: listing and downloading require `conversations:read`; deleting requires `conversations:write`. The single-artifact byte download (`/v1/api/artifacts/{id}/download`) requires no specific scope — any authenticated caller in the artifact's workspace may use it. ## List artifacts There are two ways to list, depending on whether you want everything in the workspace or just one conversation's files. [List artifacts](/api-reference/conversations/list-artifacts) returns the delivered artifacts visible to you across the workspace, newest first and capped at 500. ```bash theme={null} curl https://api.hq.zone/v1/api/artifacts \ -H "Authorization: Bearer $HQ_TOKEN" ``` Each entry carries `id`, `name`, `content_type`, `size_bytes`, `caption` (nullable), `sensitive`, `created_at`, `conversation_id` (null once detached), `conversation_title` (null once detached), and `download_url`: ```js theme={null} // → 200 // { // "artifacts": [ // { // "id": "", // "name": "q3-revenue.pdf", // "content_type": "application/pdf", // "size_bytes": 81234, // "caption": null, // "sensitive": false, // "created_at": "2026-06-10T09:14:00Z", // "conversation_id": "", // "conversation_title": "Q3 numbers", // "download_url": "/v1/api/artifacts//download" // } // ] // } ``` [List conversation artifacts](/api-reference/conversations/list-conversation-artifacts) returns just the files for a single conversation, in chronological order (oldest first). ```bash theme={null} curl https://api.hq.zone/v1/api/conversations//artifacts \ -H "Authorization: Bearer $HQ_TOKEN" ``` Each entry is a trimmer shape — `id`, `name`, `content_type`, `size_bytes`, `sensitive`, `created_at`, and `download_url`: ```js theme={null} // → 200 // { // "artifacts": [ // { // "id": "", // "name": "chart.png", // "content_type": "image/png", // "size_bytes": 20481, // "sensitive": false, // "created_at": "2026-06-10T09:12:00Z", // "download_url": "/v1/api/artifacts//download" // } // ] // } ``` If you are a workspace admin inspecting another member's conversation, add `?view=admin` to the per-conversation listing to read their artifacts. This admin read is audited. ## Download an artifact's bytes Both list responses give you a `download_url`. Resolve it against the base URL and call [Download an artifact](/api-reference/conversations/download-artifact). The response is **raw binary** — the artifact bytes streamed back with the original `Content-Type` and a `Content-Disposition: attachment` header carrying the filename — not JSON. Save it to a file rather than printing it. Use `-o` to write the response body straight to a file: ```bash theme={null} curl https://api.hq.zone/v1/api/artifacts//download \ -H "Authorization: Bearer $HQ_TOKEN" \ -o q3-revenue.pdf ``` A 200 streams the bytes; a `404` means there is no such artifact in your workspace. Read the response as an `ArrayBuffer` (the body is binary, not JSON) and write it to disk: ```js theme={null} import { writeFile } from "node:fs/promises"; const base = "https://api.hq.zone"; const headers = { Authorization: `Bearer ${process.env.HQ_TOKEN}` }; const artifactId = ""; const res = await fetch(`${base}/v1/api/artifacts/${artifactId}/download`, { headers }); if (!res.ok) throw new Error(`download failed: ${res.status}`); const bytes = Buffer.from(await res.arrayBuffer()); await writeFile("q3-revenue.pdf", bytes); ``` The download is streamed, so large artifacts don't have to fit in memory on the server. The `Content-Type` you receive is whatever the artifact was published as (e.g. `application/pdf`, `image/png`). ## Download a conversation as a ZIP archive To grab every artifact in a conversation at once, call [Download conversation artifacts](/api-reference/conversations/download-conversation-artifacts). The response is a **raw `application/zip` stream**, not JSON — save it to a file. Filenames that would collide inside the archive are de-duplicated automatically. ```bash theme={null} curl https://api.hq.zone/v1/api/conversations//artifacts/archive \ -H "Authorization: Bearer $HQ_TOKEN" \ -o conversation-artifacts.zip ``` A 200 returns the ZIP; a `404` means the conversation has no artifacts to download. ```js theme={null} import { writeFile } from "node:fs/promises"; const base = "https://api.hq.zone"; const headers = { Authorization: `Bearer ${process.env.HQ_TOKEN}` }; const convId = ""; const res = await fetch(`${base}/v1/api/conversations/${convId}/artifacts/archive`, { headers }); if (res.status === 404) throw new Error("no artifacts to download"); if (!res.ok) throw new Error(`archive failed: ${res.status}`); await writeFile("conversation-artifacts.zip", Buffer.from(await res.arrayBuffer())); ``` The archive is a pure storage read — it works even when the conversation's workspace is asleep, since no agent VM has to be running. ## Delete an artifact [Delete an artifact](/api-reference/conversations/delete-artifact) permanently removes an artifact's row and its stored bytes. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/artifacts/ \ -H "Authorization: Bearer $HQ_TOKEN" ``` Note the path: deletion targets `/v1/api/artifacts/{id}` (DELETE), while the byte download targets `/v1/api/artifacts/{id}/download` (GET). The delete response is JSON with the artifact `id` and a `deleted` flag: ```js theme={null} // → 200 // { "id": "", "deleted": true } ``` You may delete an artifact if you participate in its backing conversation, or — once it has been detached from a deleted conversation — if you were its original producer. Otherwise the call returns `403`. A `404` means the artifact was not found in your workspace. Deleting an artifact that is still attached to a conversation also removes it from that conversation's transcript. The bytes are gone and the existing download link will then 404. # Connect your own MCP servers Source: https://docs.hq.zone/guides/connectors Bring MCP servers HQ doesn't ship in its catalog — a public URL via a custom integration, or a server inside your private network via an outbound mTLS connector. The [Integrations](/guides/integrations) catalog covers the MCP servers HQ ships. When you have your **own** MCP server, there are two ways to bring it in, both ending in a private entry in your workspace catalog that you attach to agents like any other: * **Custom MCP** — your server is reachable at a **public URL**. Probe it, then add it; HQ detects its auth and connects. * **Connector** — your server lives **inside a private network** with no public ingress. A small connector agent on your side dials out over an mTLS tunnel, and HQ routes tool calls back through it. Both are **admin-only** and scoped to your own workspace. All requests use the base URL `https://api.hq.zone` and a personal access token with the `admin` scope: `Authorization: Bearer hq_pat_...`. The servers you add are **private (T3)** catalog entries — visible only to your workspace. ## Custom integration policy Both paths are gated by a workspace-wide policy enforced **before any outbound call**. Read it with `GET /v1/mcp/custom/policy` and set it with `PUT`: ```bash theme={null} curl -X PUT https://api.hq.zone/v1/mcp/custom/policy \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "custom_mcp_enabled": true, "allowed_domains": ["mcp.acme.com"], "blocked_domains": [], "require_approval": true }' # → 200 (the updated policy) ``` * `custom_mcp_enabled` (required) — master switch; when `false`, every add/probe is refused. * `allowed_domains` — if non-empty, only these hosts may be connected (an allowlist). * `blocked_domains` — hosts that are always refused. * `require_approval` — when `true`, a newly added server is held for an admin to approve before agents can see it. References: [Get custom policy](/api-reference/integrations/mcp-custom-policy-get), [Update custom policy](/api-reference/integrations/mcp-custom-policy-put). ## Add a public MCP server (custom) `POST /v1/mcp/custom/probe` connects to the server, detects its authentication, and previews its tools — **without writing anything**. It's checked against your policy first. ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/custom/probe \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "url": "https://mcp.acme.com/mcp" }' # → 200 { # "endpoint": "https://mcp.acme.com/mcp", # "auth": "none", "auth_label": "No authentication", # "connectable": true, # "server_name": "Acme Tools", "tool_count": 7, # "tools": [ { "name": "lookup_order", "description": "..." } ], # "note": null # } ``` `auth` is one of `none`, `api_key`, `oauth`, or `oauth_unsupported`. `connectable` is `true` when you can finish setup self-serve (open servers, API-key servers, and OAuth servers that advertise dynamic client registration with a public client). When it's `false`, `note` explains why — typically an OAuth server that needs an operator to register a confidential client. A blocked/invalid URL or a failed discovery returns `400`. See [Probe a custom MCP](/api-reference/integrations/mcp-custom-probe). `POST /v1/mcp/custom` re-probes, enforces policy, and creates the private catalog entry. ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/custom \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "url": "https://mcp.acme.com/mcp", "display_name": "Acme Tools" }' # → 200 { "slug": "t::1", "display_name": "Acme Tools", # "credential_model": "none", "next": "connected" } ``` The body takes `url` (required), an optional `display_name`, and an optional `max_calls_per_day` cap. The `next` field tells you what's left: * `connected` — done; an open server is enabled immediately (or held for review if your policy requires approval). * `api_key` — finish by storing a key with the [Set MCP key](/api-reference/integrations/set-mcp-key) flow on the returned slug (see the [Integrations guide](/guides/integrations)). * `oauth_start` — finish the OAuth connect (see the [OAuth guide](/guides/oauth)). A non-connectable server, a policy block, or a failed discovery returns `400`. See [Add a custom MCP](/api-reference/integrations/mcp-custom-create). When your policy sets `require_approval`, a new server lands in `review_required` and stays hidden from agents until an admin approves it with `POST /v1/mcp/custom/{slug}/approve`. The same endpoint re-approves a server after its tool list changes (a tool-poisoning guard re-freezes it on schema drift). ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/custom/t::1/approve \ -H "Authorization: Bearer hq_pat_..." ``` See [Approve a custom MCP](/api-reference/integrations/mcp-custom-approve). Set or change a per-day call cap any time with `PUT /v1/mcp/custom/{slug}/limits` — body `{ "max_calls_per_day": 500 }` (`null` or `0` = uncapped). See [Set custom MCP limits](/api-reference/integrations/mcp-custom-limits). Remove a custom server with `DELETE /v1/mcp/custom/{slug}` — see [Delete a custom MCP](/api-reference/integrations/mcp-custom-delete). ## Connect a private-network server (connector) When the server has no public URL, register a **connector**: HQ mints a one-time enrollment token, your connector agent dials out and establishes a mutually-authenticated (mTLS) tunnel, and HQ routes tool calls to the private server through it. `POST /v1/mcp/connectors` registers a pending connector and returns a one-time enrollment token plus the tunnel address your agent dials. ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/connectors \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "name": "datacenter-1" }' # → 200 { # "connector_id": "", # "enrollment_token": "", # "tunnel_addr": "tunnel.hq.zone:8091", # "tunnel_server_name": "tunnel.hq.zone" # } ``` The `enrollment_token` is shown **once** and never stored — only its hash is kept. It is **single-use** and **expires in one hour**. If you lose it or it expires, create a new connector. See [Create a connector](/api-reference/integrations/connector-create). On your network, run the HQ connector agent with the token. It generates a keypair and a certificate signing request and calls `POST /v1/mcp/connectors/enroll` (public, authenticated by the one-time token — no session), receiving a CA-signed client certificate, the CA certificate, and the tunnel address. It then dials `tunnel_addr` over mTLS and stays connected. A missing, invalid, expired, or already-used token returns `403`. This call is made by the connector software, not by you directly. See [Enroll a connector](/api-reference/integrations/connector-enroll). Once the tunnel is up, expose the private MCP server reachable through it with `POST /v1/mcp/connectors/{id}/mcp`. This creates the catalog entry and installs it (enabled) for your workspace. ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/connectors//mcp \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "display_name": "Internal Tools", "path": "/mcp" }' # → 200 { "slug": "t::2" } ``` `display_name` is required; `path` is the MCP's path on the connector's local base (default `/mcp`); `max_calls_per_day` is an optional cap. A revoked connector returns `400`; an unknown one returns `404`. See [Register a private MCP behind a connector](/api-reference/integrations/connector-add-mcp). List your connectors with `GET /v1/mcp/connectors` — each reports `id`, `name`, `status` (`pending`, `enrolled`, `revoked`), `last_seen_at`, and `created_at` ([List connectors](/api-reference/integrations/connector-list)). Revoke one with `DELETE /v1/mcp/connectors/{id}` — it clears the certificate fingerprint and any pending token so no new tunnel sessions can be established, and live sessions drop on their next reconnect (returns `204`). See [Revoke a connector](/api-reference/integrations/connector-revoke). ## Attach it to an agent Adding a custom MCP or connector MCP makes it available to the **workspace**. To put it in front of a specific agent, add its slug to the agent's MCP subset: ```bash theme={null} curl -X PUT https://api.hq.zone/v1/agents//mcp \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{"enabled": ["t::1"]}' ``` See [Attach skills and MCP servers](/guides/agents). # Work with the documents library Source: https://docs.hq.zone/guides/documents Upload, classify, list, search, download, update, and delete the user-curated documents in your workspace. The HQ documents library is a curated, longer-lived file store: PDFs, CSVs, images, and other files your workspace keeps around and wants to find again. Each document has a stable id, a content-addressed hash, a download URL of the shape `/v1/api/documents/{id}/download`, and a set of classification fields that a worker fills in automatically after upload. This guide covers uploading (both the inline JSON and the multipart variants), how classification works and how to re-trigger it, listing and searching, reading and updating metadata, downloading the raw bytes, and deleting. All requests go to `https://api.hq.zone` and authenticate with a personal access token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` Read operations (list, search, get, download) require the `documents:read` scope. Write operations (upload, update, reclassify, delete) require `documents:write`. ## Visibility Every read enforces a visibility filter, so you only ever see documents you are allowed to see. There are three scopes: * `private` — only the owner sees it. * `channel` — members of the document's `channel_id` see it. * `team` — everyone in the workspace sees it. Scope is set at upload time (defaulting to `private`) and can be changed later with an update. ## Upload a document There are two upload paths. They share the same dedup, storage, and classification pipeline; they differ only in how the bytes reach the server. * **Inline JSON + base64** — `POST /v1/api/documents`. Bytes are base64-encoded in the JSON body. The JSON body is capped at 16 MiB, which lands the raw file ceiling at roughly 12 MiB after the base64 tax. * **Multipart form-data** — `POST /v1/api/documents/upload`. Bytes ride a `multipart/form-data` file part, so they don't pay the base64 tax. This path accepts larger files (up to 64 MiB) and is what browser drag-and-drop uses. Both require the `documents:write` scope and both return the same response shape. ### Variant A — inline JSON (base64) ```bash theme={null} B64=$(base64 -w0 report.pdf) ``` Send [Upload a document](/api-reference/documents/upload-document). The required fields are `filename`, `content_type`, and `body_b64`; `scope` defaults to `private`, and `channel_id`, `category`, `tags`, and `caption` are optional. `channel_id` is required when `scope` is `channel`, and rejected otherwise. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/documents \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d "{ \"filename\": \"report.pdf\", \"content_type\": \"application/pdf\", \"scope\": \"team\", \"tags\": [\"finance\", \"q3\"], \"caption\": \"Q3 board report\", \"body_b64\": \"$B64\" }" ``` A 200 returns the document id, download URL, hash, and size: ```js theme={null} // → 200 // { // "document_id": "", // "download_url": "/v1/api/documents//download", // "sha256": "", // "size_bytes": 81234, // "deduplicated": false, // "enriched": false // } ``` ### Variant B — multipart form-data Send [Upload a document (multipart)](/api-reference/documents/upload-multipart). The file bytes go in a part named `file` (the part name `body` is also accepted); the filename and content type are read from that part. Optional text fields are `scope`, `channel_id`, `category`, `tags` (comma-separated), and `caption`. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/documents/upload \ -H "Authorization: Bearer $HQ_TOKEN" \ -F "file=@report.pdf;type=application/pdf" \ -F "scope=team" \ -F "tags=finance,q3" \ -F "caption=Q3 board report" ``` The response shape is identical to the inline path: `document_id`, `download_url`, `sha256`, `size_bytes`, `deduplicated`, and `enriched`. The file part must carry a filename (via `Content-Disposition: filename=...`). If the part has no `Content-Type`, the server falls back to `application/octet-stream` rather than rejecting the upload. The `tags` field here is a single comma-separated string, whereas the inline JSON path takes a real JSON array. Uploads are content-addressed and idempotent per owner and scope. Re-uploading identical bytes under the same owner and scope returns the **existing** document instead of creating a duplicate — the response sets `deduplicated: true`. If you also supply new `tags`, `caption`, or `category` on that re-upload, they are merged onto the existing row (tags are unioned; caption and category fill in only when previously empty) and `enriched: true` is returned. ## How classification works When a document is saved, a background classifier worker analyzes it and writes back auto-derived metadata. You don't trigger it — it picks up newly created documents on its own. Its progress and output show up as fields on the document row: * `classification_status` — one of `pending`, `queued`, `processing`, `completed`, `failed`, or `skipped`. A UI typically shows a pill until this reaches `completed`. * `auto_categorized` — `true` once the worker has written back an auto-derived category, summary, and tags. (This is distinct from `category` being set, because users can also set a category manually.) * `category` — the document category (nullable; may be set by the worker or by you). * `summary` — an auto-generated summary (nullable). * `document_date` — the date the document *refers to* (issue / publication / statement date), not when it was ingested (nullable). * `language` — ISO 639-1 code such as `en` or `sv` (nullable). * `reference_numbers` — extracted document-specific IDs (invoice / case / order numbers). * `entities` — an LLM-extracted JSON blob of entities (e.g. person names, company names, identifiers, amounts, dates). * `analysis_strategy` — which classifier pipeline produced the row (nullable on older rows). * `profile_version` — the classifier schema version that wrote the row. * `classification_confidence` — the model's self-reported certainty in the range 0–1 (nullable). Confidence below `0.6` is typically flagged as "needs review". ### Re-trigger classification If the model returned a poor category, the document was uploaded before the worker was available, or it terminally failed, you can force another pass with [Reclassify a document](/api-reference/documents/reclassify). This resets `classification_status` to `queued` and re-queues the document for the worker. Owner-only. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/documents//reclassify \ -H "Authorization: Bearer $HQ_TOKEN" ``` ```js theme={null} // → 200 // { "status": "queued" } ``` A `403` means you are not the owner; a `404` means there is no such document in your workspace. ## List and search [List documents](/api-reference/documents/list-documents) returns the documents visible to you, newest first. Optional query parameters narrow the set: `scope`, `category`, `channel` (a channel id, useful with `scope=channel`), and `tags` (comma-separated, matching documents that carry **all** listed tags). `limit` defaults to 50 and is capped at 200. ```bash theme={null} curl "https://api.hq.zone/v1/api/documents?scope=team&category=finance&limit=20" \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response carries the `documents` array plus rollup `categories` and `tags` arrays — the distinct categories and tags across your whole visible set, for building filter sidebars: ```js theme={null} // → 200 // { // "documents": [ { "id": "", "filename": "report.pdf", ... } ], // "categories": ["finance", "legal"], // "tags": ["q3", "board"] // } ``` [Search documents](/api-reference/documents/search-documents) runs a case-insensitive substring search over filename, caption, summary, and tags. The `q` parameter is required; `limit` defaults to 50 and is capped at 200. ```bash theme={null} curl "https://api.hq.zone/v1/api/documents/search?q=revenue" \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response has the same shape as the list endpoint, but the `categories` and `tags` rollup arrays come back **empty** for search. ## Get and update metadata [Get a document](/api-reference/documents/get-document) returns the full metadata for a single document by id — `filename`, `content_type`, `size_bytes`, `sha256`, `scope`, owner fields, `category`, `tags`, `caption`, `summary`, the classification fields described above, `download_url`, and `is_owner` (whether you own it, which drives edit/delete affordances). A document not visible to you returns `404`. ```bash theme={null} curl https://api.hq.zone/v1/api/documents/ \ -H "Authorization: Bearer $HQ_TOKEN" ``` [Update a document](/api-reference/documents/update-document) edits the mutable metadata: `scope`, `channel_id`, `category`, `tags`, and `caption`. Only fields present in the body change. For `channel_id`, `category`, and `caption`, an explicit `null` **clears** the value while omitting the field leaves it untouched. Only the owner may update (others get `403`); a missing document returns `404`. ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/api/documents/ \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"category": "finance", "tags": ["q3", "board"], "caption": null}' ``` The response is the updated document row. To move a document into a channel, set both `scope` and `channel_id` in the same update. A valid `scope` is one of `private`, `channel`, or `team`. ## Download the bytes A document's metadata gives you `download_url`. Resolve it against the base URL and call [Download a document](/api-reference/documents/download-document). The response is **raw binary** — the document bytes streamed back as an attachment with the original `Content-Type`, the original filename in `Content-Disposition`, and the byte count in `Content-Length` — not JSON. Save it to a file rather than printing it. Visibility is enforced the same way as on the read endpoints; a document you can't see returns `404`. Use `-o` to write the response body straight to a file: ```bash theme={null} curl https://api.hq.zone/v1/api/documents//download \ -H "Authorization: Bearer $HQ_TOKEN" \ -o report.pdf ``` Read the response as an `ArrayBuffer` (the body is binary, not JSON) and write it to disk: ```js theme={null} import { writeFile } from "node:fs/promises"; const base = "https://api.hq.zone"; const headers = { Authorization: `Bearer ${process.env.HQ_TOKEN}` }; const documentId = ""; const res = await fetch(`${base}/v1/api/documents/${documentId}/download`, { headers }); if (!res.ok) throw new Error(`download failed: ${res.status}`); const bytes = Buffer.from(await res.arrayBuffer()); await writeFile("report.pdf", bytes); ``` The download is streamed, so large documents don't have to fit in memory on the server. The response carries `Cache-Control: private, max-age=300`. ## Delete a document [Delete a document](/api-reference/documents/delete-document) removes a document. Only the owner may delete it (others get `403`); an unknown document returns `404`. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/documents/ \ -H "Authorization: Bearer $HQ_TOKEN" ``` A successful delete returns `204 No Content` with an empty body. The stored bytes are removed only when no other document in the workspace still references the same content. Deduplicated copies are therefore preserved — deleting your copy of a shared file won't pull the bytes out from under someone else's row. # Agent email: inbox, drafts, and triage Source: https://docs.hq.zone/guides/email Give an agent an email address, then review, approve, send, or discard the replies it drafts — plus assign unrouted mail and clear quarantine. HQ lets an agent receive and reply to email. You mint an **email endpoint** (an inbound address), mail lands on it, and — depending on the endpoint's policy — the agent either replies on its own or **drafts a reply for a human to review**. This guide walks the operator/integrator flow: create an endpoint, watch the review queue, read a message, approve/edit and send (or discard) the draft, assign mail that couldn't be routed, and clear the quarantine. Two API surfaces are involved: * **Endpoint admin** (`/v1/api/email/endpoints`, `/v1/api/email/workspace-mailbox`) — manage the addresses. Every operation is **admin-scoped**. * **Triage** (`/v1/api/email/...`) — the read + action surface over inbound mail. Read/list operations require **`conversations:read`**, reply/discard require **`conversations:write`**, and the rest (`assign`, message/attachment content, quarantine) are **admin-scoped**. All requests use the base URL `https://api.hq.zone` and a PAT bearer token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` Most of this feature is **admin only**. The scope is stated per endpoint below; where it says "admin", a non-admin token is rejected. The triage list/badge endpoints (`list_review`, `list_activity`, `get_badge`) are scoped so a regular member sees only mail bound to them and the admin-only queues read empty. ## 1. Create an email endpoint (give an agent an address) `POST /v1/api/email/endpoints` (admin) creates a custom inbox. The required fields are `localpart` and `kind`; an agent-handled inbox sets `plane` to `agent` and names a handler `agent_id` (the agent must belong to your workspace). A "light" quick-reply inbox is agentless — do **not** pass `agent_id`. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/endpoints \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{ "localpart": "sales.eu", "kind": "agent", "agent_id": "", "plane": "agent", "reply_policy": "human_review", "sender_policy": "bound_users_only" }' ``` The response is the created endpoint (`EndpointJson`) with its `id`, the stored config, and per-endpoint counters. The endpoint object does not contain the full address by itself — it carries the `localpart`. To assemble the address, call `GET /v1/api/email/endpoints` (List endpoints, admin), which returns `tenant_email_slug`, `domain`, and `outbound_mailbox_localpart` alongside the endpoints: ```bash theme={null} curl https://api.hq.zone/v1/api/email/endpoints \ -H "Authorization: Bearer $HQ_TOKEN" # → { "tenant_email_slug": "...", "domain": "...", "outbound_mailbox_localpart": "team", "endpoints": [ ... ] } ``` The full address is `-@`. So the inbox above resolves to `sales.eu-@`. The `localpart` must be lowercase alphanumerics with `.` or `-` separators, start with an alphanumeric, and be at most 63 characters. Reserved localparts (such as `postmaster`, `noreply`) and the workspace mailbox localpart are rejected. ### Endpoint behavior fields `create_endpoint` and `update_endpoint` share the same config knobs. The validated enum fields: * `plane` — one of `light`, `agent`. `light` (the default) is the agentless quick-reply plane; `agent` hands the thread to the named agent. * `sender_policy` — one of `bound_users_only`, `anyone`, `domain_allowlist`, `addr_allowlist`. * `reply_policy` — one of `agent_decides`, `always_reply`, `never_reply`, `human_review`. Other fields include `instructions`, `allow_escalation`, `default_reply_lang`, `deliver_to`, `category_policy`, `spam_score_max`, `max_turns_per_sender_day`, `max_turns_per_day`, `enabled`, and `allow_patterns` (the allowlist; supplying it replaces the set wholesale). `create_endpoint` returns **402** if your plan's email-inbox limit is reached, and **409** if the address (or an agent's existing endpoint) already exists. The enum fields above are validated — an unknown value is a **400**. ### Manage existing endpoints | Operation | Method + path | Scope | Notes | | ------------------------------------------------------- | ------------------------------------- | ----- | ----------------------------------------------------------------- | | [List endpoints](/api-reference/admin/list-endpoints) | `GET /v1/api/email/endpoints` | admin | Endpoints + counters + slug/domain. | | [Get endpoint](/api-reference/admin/get-endpoint) | `GET /v1/api/email/endpoints/{id}` | admin | One endpoint; unknown id → 404. | | [Update endpoint](/api-reference/admin/update-endpoint) | `PATCH /v1/api/email/endpoints/{id}` | admin | Omitted fields keep current values; `localpart`/`kind` are fixed. | | [Delete endpoint](/api-reference/admin/delete-endpoint) | `DELETE /v1/api/email/endpoints/{id}` | admin | The system workspace mailbox can't be deleted (400). | ```bash theme={null} # Pause an inbox without deleting it curl -X PATCH https://api.hq.zone/v1/api/email/endpoints/ \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"enabled": false}' ``` ### The workspace outbound mailbox Every workspace has one HQ-managed outbound mailbox — the address all agents send from (`is_system: true`). It is **never** edited through the endpoint editor (that returns 400) and can't be deleted. The only knob is its localpart, changed via [Update mailbox](/api-reference/admin/update-mailbox): ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/api/email/workspace-mailbox \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"localpart": "hello"}' # → 200 { "ok": true } ``` The workspace mailbox never auto-replies, and that behavior is not configurable. An invalid or reserved localpart returns **400**. ## 2. Mail arrives and the agent drafts When mail lands on an endpoint, HQ mirrors it as an `email_message` and routes it. The message moves through a small handling-state machine. The exact state strings are: * `unrouted` — couldn't be routed to a handler (admin owns this queue). * `awaiting_review` — the agent drafted a reply; a human must approve, edit & send, or discard it. * `handled` — terminal: replied, discarded, or assigned. When the endpoint's `reply_policy` keeps a human in the loop, the drafted reply lands in `awaiting_review` for you to act on. The badge and review queues count exactly the items needing a human. ## 3. The review queue [List review](/api-reference/admin/list-review) (`GET /v1/api/email/review`, scope `conversations:read`) returns the three actionable queues plus counts: ```bash theme={null} curl https://api.hq.zone/v1/api/email/review \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response (`ReviewQueues`) has: * `awaiting_review` — rows of drafted replies (scoped to the caller; admins see all). Each is capped at 200 items. * `unrouted` — **admin-only**; empty for a non-admin. * `quarantined` — **admin-only**; empty for a non-admin. * `counts` — `{ awaiting_review, unrouted, quarantined }`. Each `awaiting_review` / `unrouted` row carries `email_message_id`, `direction`, `handling_state`, `from_addr`, `to_addrs`, `subject`, `llm_category`, `llm_summary`, `agent_id`, `endpoint_id`, `endpoint_localpart`, `endpoint_plane`, a `conversation_id` deep-link, and `occurred_at`. For a one-number nav badge, call [Get badge](/api-reference/admin/get-badge) (`GET /v1/api/email/badge`, scope `conversations:read`). It returns `count` (the sum the caller can see) broken down into `awaiting_review`, `unrouted`, and `quarantined`. For the full inbound + outbound feed with pagination and filtering, use [List activity](/api-reference/admin/list-activity) (`GET /v1/api/email/activity`, scope `conversations:read`) — it accepts `state` (`handled` / `awaiting_review` / `unrouted`), `endpoint_id`, `limit` (1–200, default 50), `offset`, and `sort` (`recent` default, or `oldest`). ## 4. Read a message Pick an `email_message_id` from the review queue and fetch the full message with [Get message](/api-reference/admin/get-message) (`GET /v1/api/email/messages/{id}/content`, **admin**): ```bash theme={null} curl https://api.hq.zone/v1/api/email/messages//content \ -H "Authorization: Bearer $HQ_TOKEN" ``` Headers, decoded bodies, and the attachment list are fetched on demand from the email store (the raw message is never kept on HQ's side). An unknown or cross-workspace id returns **404**. To pull one attachment's raw bytes, use [Download attachment](/api-reference/admin/download-attachment) (`GET /v1/api/email/messages/{id}/attachments/{attachment_id}/download`, **admin**). It streams the bytes with the upstream `Content-Type` and `Cache-Control: no-store`; an attachment that doesn't belong to the message returns **404**. ## 5. Approve & send — or discard [Send reply](/api-reference/admin/send-reply) (`POST /v1/api/email/messages/{id}/reply`, scope `conversations:write`) approves the drafted reply. The body (`ReplyReq`) is `{ "text": "...", "html": "..." }` — `text` is required and must be non-empty; `html` is optional. The UI pre-fills `text` with the draft so a human can edit before sending. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/messages//reply \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"text": "Thanks for reaching out — here is the quote you asked for..."}' # → 200 { "ok": true, "handling_state": "handled" } ``` The reply is sent as the handler agent on behalf of the bound user, and the item settles to `handling_state: "handled"`. [Discard draft](/api-reference/admin/discard-draft) (`POST /v1/api/email/messages/{id}/discard`, scope `conversations:write`) drops the draft without sending and settles the item to `handled`: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/messages//discard \ -H "Authorization: Bearer $HQ_TOKEN" # → 200 { "ok": true, "handling_state": "handled" } ``` Both actions require the item to be in `awaiting_review`. Acting on a message in any other state returns **400** (`message is , not awaiting_review`). A regular member can act only on mail bound to them — someone else's message returns **404** (so it can't be probed). `send_reply` also returns **400** if the message has no handler agent or no bound user. ## 6. Assign unrouted mail Mail that couldn't be routed sits in the `unrouted` queue (admin-only). [Assign email](/api-reference/admin/assign-email) (`POST /v1/api/email/messages/{id}/assign`, **admin**) attaches a handler and re-drives it: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/messages//assign \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"agent_id": ""}' # → 200 { "ok": true, "handling_state": "handled" } ``` The request body (`AssignReq`) is just `{ "agent_id": "..." }`. The agent must belong to your workspace. The handler sets the message's agent, re-emits the routed event so a turn runs, and — if the mail hit a handler-less mailbox endpoint — wires the chosen agent onto that endpoint so future mail routes without a human. The item settles to `handled`. The message must be in `unrouted` — anything else returns **400** (`message is , not unrouted`). An unknown agent, or a message with no bound user, also returns **400**. ## 7. The quarantine path Suspicious inbound mail (for example, `unknown_sender` or a spam-threshold hit) is held in quarantine instead of being routed. This is an **admin-only** surface; the pending items appear as the `quarantined` queue in `list_review`. [Get quarantine](/api-reference/admin/get-quarantine) (`GET /v1/api/email/quarantine/{id}/content`, **admin**) fetches the raw message for inspection before you decide. Attachments aren't materialized until accept, so the `attachments` list is empty here. ```bash theme={null} curl https://api.hq.zone/v1/api/email/quarantine//content \ -H "Authorization: Bearer $HQ_TOKEN" ``` Note the id here is the **quarantine id**, not an `email_message_id`. An unknown id returns **404**. [Accept quarantine](/api-reference/admin/accept-quarantine) (`POST /v1/api/email/quarantine/{id}/accept`, **admin**) marks the item accepted. The body (`AcceptReq`) optionally carries `bind_user_id` — binding the sender to a workspace user so their future mail routes. A `bind_user_id` is **required** to clear an `unknown_sender` quarantine. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/quarantine//accept \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"bind_user_id": ""}' # → 200 { "ok": true, "note": "Accepted and re-delivered to the agent." } ``` When the destination is now reachable (a freshly bound `unknown_sender`, or a `spam_threshold` item whose sender is already bound), HQ re-delivers this message so the agent acts on it immediately; otherwise it routes on the sender's next mail. The response (`ActionOk`) returns `ok: true` and an optional explanatory `note`. [Reject quarantine](/api-reference/admin/reject-quarantine) (`POST /v1/api/email/quarantine/{id}/reject`, **admin**) marks the item rejected — a terminal decision: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/email/quarantine//reject \ -H "Authorization: Bearer $HQ_TOKEN" # → 200 { "ok": true } ``` Accept and reject act only on a **pending** quarantine. If no pending item with that id exists, both return **404**. Accepting an `unknown_sender` without a `bind_user_id` only records the decision — the response `note` reminds you to pass `bind_user_id` to route the sender's future mail. ## Where it lands Once an item is `handled`, it drops out of the review queue and the badge. It stays visible in the [Activity feed](/api-reference/admin/list-activity), where you can filter by `state` or `endpoint_id` to audit what the agent and your reviewers did. # Extend agents with integrations Source: https://docs.hq.zone/guides/integrations Browse the catalog and install MCP servers, skills, and Slack channels for your workspace, then attach them to an agent. HQ agents gain new capabilities from three kinds of integration: **MCP servers** (tool backends), **skills** (instruction packs), and **Slack channels** (where the HQ bot can post). Each is installed once at the **workspace** level and then attached to individual agents. All requests use the base URL `https://api.hq.zone` and a personal access token: `Authorization: Bearer hq_pat_...`. Most install and uninstall operations require the `admin` scope; the catalog and status reads require `agents:read`. Installing an MCP server or skill makes it available to the *workspace*. To put it in front of a specific agent, attach it with the agent's MCP/skill subset — see [Attach skills and MCP servers](/guides/agents). ## Check connection status Before browsing the catalogs, you can fetch a single overview of what the workspace has connected. See [Connection status](/api-reference/integrations/connect-status). ```bash theme={null} curl https://api.hq.zone/v1/api/connect/status \ -H "Authorization: Bearer $HQ_TOKEN" # → { # "slack": { "connected": true, "team_name": "Acme" }, # "teams": { "connected": false, "org_name": null }, # "extension": { "web_store_url": null, "download_url": null }, # "recommendations": [ ... ], # "detected": [ ... ] # } ``` The `slack` and `teams` objects report whether each is connected (with the team or org name when available). `extension` carries the browser-extension URLs (null until published). `recommendations` lists suggested or accepted integrations/skills enriched with catalog `display_name`, `description`, `category`, `icon_url`, `confidence`, `priority`, and `rationale`; `detected` lists the technology signals the profiler found about your org's site and DNS. This read requires the `agents:read` scope. ## MCP servers MCP servers expose tools your agents can call. Some are one-click toggles; others need a credential before they will work. List every active MCP server together with your workspace's install state. See [MCP catalog](/api-reference/integrations/mcp-catalog). ```bash theme={null} curl https://api.hq.zone/v1/mcp/catalog \ -H "Authorization: Bearer $HQ_TOKEN" # → { "servers": [ { "slug": "github", "display_name": "GitHub", # "credential_model": "tenant_api_key", "effective_enabled": false, # "allowed_scopes": ["team","user"], ... } ] } ``` Each server reports `slug`, `display_name`, `description`, `category`, `publisher`, `transport`, `trust_tier`, `version`, `default_enabled`, `credential_model`, `tenant_enabled`, `effective_enabled`, `install_status`, `allowed_scopes`, `featured`, `featured_rank`, and `icon_url`. This read requires the `admin` scope. The **`credential_model`** drives how you install: * `none` / `platform` — a one-click toggle; no credential needed. * `tenant_api_key` — paste an API key (see *Install with an API key* below). * `tenant_oauth` — connect through OAuth, then install with the resulting credential reference. Fetch a server's brand icon (public, no auth) from [MCP icon](/api-reference/integrations/mcp-icon): ```bash theme={null} curl https://api.hq.zone/v1/mcp/catalog//icon # → image/svg+xml (404 when the server has no icon) ``` For `none` and `platform` servers, install by slug. See [Install MCP](/api-reference/integrations/install-mcp). ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/installs \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"slug": ""}' # → { "slug": "", "enabled": true } ``` The body accepts `slug`, an optional `credential_ref` (for `tenant_api_key` / `tenant_oauth` servers), and an optional `config` blob. Re-installing is idempotent and preserves the prior `credential_ref` and `config` when you omit them. Installing a `tenant_api_key` or `tenant_oauth` server without a `credential_ref` returns `400`. An unknown or inactive slug returns `404`. For servers whose `credential_model` is `tenant_api_key`, store the key and install in one call. See [Set MCP key](/api-reference/integrations/set-mcp-key). ```bash theme={null} curl -X POST https://api.hq.zone/v1/mcp/installs//api_key \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"api_key": "", "scope": "team"}' # → { "slug": "", "enabled": true, # "credential_ref": "", "scope": "team" } ``` The body takes `api_key` and an optional `scope`: `team` (shared across the workspace, the default) or `user` (private to you). The chosen scope must be in the server's `allowed_scopes`, and `user` scope requires a resolvable calling user. The key is sealed and, where the backend supports it, validated against the upstream before being saved. Pasting a new key for an existing install rotates the credential in place. An empty key, a server whose `credential_model` is not `tenant_api_key`, a disallowed scope, or a failed validation probe returns `400`. An unknown or inactive slug returns `404`. Installing only makes the server available to the workspace. To equip an agent, replace its MCP subset with the slugs you want — an empty list means "everything installed." See [Attach skills and MCP servers](/guides/agents). ```bash theme={null} curl -X PUT https://api.hq.zone/v1/agents//mcp \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"enabled": [""]}' ``` Disable the server for your workspace. See [Uninstall MCP](/api-reference/integrations/uninstall-mcp). ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/mcp/installs/ \ -H "Authorization: Bearer $HQ_TOKEN" # → { "slug": "", "enabled": false } ``` This works even for servers that are enabled by default with no prior install (it records an explicit opt-out). It also clears any stored tenant credential, so a later re-install of a credentialed server must supply a fresh one. For the OAuth dance that produces a `credential_ref` for `tenant_oauth` servers, see the [OAuth guide](/guides/oauth). ## Skills Skills are instruction packs that shape how agents work. The catalog mixes platform skills with any your workspace has authored. List every active skill with your workspace's install state. See [Skills catalog](/api-reference/integrations/skills-catalog). ```bash theme={null} curl https://api.hq.zone/v1/skills/catalog \ -H "Authorization: Bearer $HQ_TOKEN" # → { "skills": [ { "slug": "research", "display_name": "Research", # "profile": "claude-sdk", "locked": false, # "required_integrations": [ { "slug": "web", "display_name": "Web Search", "met": true } ], # "effective_enabled": true, ... } ] } ``` Each skill reports `slug`, `display_name`, `description`, `category`, `publisher`, `profile`, `version`, `default_enabled`, `trust_tier`, `locked`, `requires`, `required_integrations` (each with `slug`, `display_name`, and whether it is `met`), `tenant_enabled`, `effective_enabled`, `install_status`, `featured`, `featured_rank`, and `icon_url`. A `locked` skill is system-required and always on. This read requires the `agents:read` scope. Inspect a skill's full pack — its `SKILL.md` (listed first) and any other files — with [Skill content](/api-reference/integrations/skill-content): ```bash theme={null} curl https://api.hq.zone/v1/skills/catalog//content \ -H "Authorization: Bearer $HQ_TOKEN" # → { "slug": "", "display_name": "...", "profile": "claude-sdk", # "trust_tier": "...", "editable": false, # "files": [ { "path": "SKILL.md", "content": "...", "is_external": false } ] } ``` `editable` is `true` only for your own workspace-authored skills. Large external files are listed with empty `content`. Fetch a skill icon (public, no auth) from [Skill icon](/api-reference/integrations/skill-icon). Enable a skill for your workspace by slug. See [Install skill](/api-reference/integrations/install-skill). ```bash theme={null} curl -X POST https://api.hq.zone/v1/skills/installs \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"slug": ""}' # → { "slug": "", "enabled": true } ``` The body accepts `slug` and an optional `config` blob. Re-installing is idempotent and preserves the prior `config` when omitted. System-locked skills cannot be installed this way (they are always on) and return `400`; an unknown or inactive slug returns `404`. Requires the `admin` scope. Create a skill from your own content. See [Upload skill](/api-reference/integrations/upload-skill). The body is either inline markdown or a multi-file pack. ```bash theme={null} # Inline markdown — wrapped automatically as SKILL.md curl -X POST https://api.hq.zone/v1/skills/upload \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"kind": "markdown", "name": "Release Notes Style", "description": "How we write release notes", "body_markdown": "# Release Notes\n..."}' # → 201 { "slug": "t::release-notes-style", "version": "0.1.0" } ``` ```bash theme={null} # Multi-file pack — each file is base64-encoded; must include SKILL.md at the root curl -X POST https://api.hq.zone/v1/skills/upload \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"kind": "files", "name": "Release Notes Style", "files": [ { "path": "SKILL.md", "content_base64": "" } ]}' # → 201 { "slug": "t::release-notes-style", "version": "0.1.0" } ``` Fields: `name` (3–60 chars; letters, digits, spaces, hyphens, underscores — used to derive the slug), optional `description`, optional `profile` (`claude-sdk`, `hermes`, or `openai-agents`; defaults to `claude-sdk`), optional `provides` (a capability slot such as `app-design`), and the `body` discriminated by `kind` (`markdown` with `body_markdown`, or `files` with a list of `{ "path", "content_base64" }`). Re-uploading with the same derived slug updates the skill in place. Limits: up to 50 files, 256 KiB total raw content, 64 KiB markdown, and a 1 MB request body. Exceeding them — or a pack with no `SKILL.md` at the root — returns `400`. Requires the `admin` scope. Replace the agent's skill subset with the slugs you want — an empty list means "everything installed." See [Attach skills and MCP servers](/guides/agents). ```bash theme={null} curl -X PUT https://api.hq.zone/v1/agents//skills \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"enabled": [""]}' ``` Disable a skill for your workspace (opting out even of a default-enabled one). See [Uninstall skill](/api-reference/integrations/uninstall-skill). ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/skills/installs/ \ -H "Authorization: Bearer $HQ_TOKEN" # → { "slug": "", "enabled": false } ``` System-locked skills cannot be disabled (they return `400`). To remove a workspace-authored skill permanently — including its install records — use [Delete skill](/api-reference/integrations/delete-skill): ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/skills/t:: \ -H "Authorization: Bearer $HQ_TOKEN" # → { "slug": "t::", "deleted": true } ``` Only your own workspace-authored (T3) skills may be deleted; deleting a platform skill or another workspace's skill returns `403`, and an unknown slug returns `404`. Both operations require the `admin` scope. ## Slack channels Once Slack is connected, the HQ bot can post to channels it is a member of (for example, from a scheduled run). These endpoints let you see and grow that membership. List the channels the HQ bot already belongs to — the set it can deliver to. See [List Slack channels](/api-reference/integrations/list-channels). ```bash theme={null} curl https://api.hq.zone/v1/api/slack/channels \ -H "Authorization: Bearer $HQ_TOKEN" # → { "connected": true, # "channels": [ { "id": "C0123ABCD", "name": "general", "is_private": false } ] } ``` Each channel has `id`, `name`, and `is_private`. When `connected` is `false`, the workspace has no active Slack install and `channels` is empty — connect Slack first. This read requires the `agents:read` scope. List the public channels HQ is *not* yet in but can self-join. See [List joinable channels](/api-reference/integrations/list-joinable-channels). ```bash theme={null} curl https://api.hq.zone/v1/api/slack/channels/joinable \ -H "Authorization: Bearer $HQ_TOKEN" # → { "connected": true, # "channels": [ { "id": "C09XYZ", "name": "announcements", "is_private": false } ] } ``` Private channels are intentionally excluded — Slack forbids a bot from self-joining them, so a member must run `/invite @HQ` instead. Requires the `admin` scope. Self-join HQ to a public channel by id. See [Join Slack channel](/api-reference/integrations/join-channel). ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/slack/channels//join \ -H "Authorization: Bearer $HQ_TOKEN" # → { "joined": true, # "channel": { "id": "", "name": "announcements", "is_private": false } } ``` Joining is idempotent on Slack's side. If the workspace has no live Slack install, or Slack refuses the join, the call returns `400`. Requires the `admin` scope. To connect Slack in the first place, see the [Connection status](/api-reference/integrations/connect-status) read and the [OAuth guide](/guides/oauth). # Inbox and notifications Source: https://docs.hq.zone/guides/notifications Read and manage HQ's two in-app surfaces: your personal inbox and the workspace notification center. HQ has **two distinct in-app surfaces**, and they are easy to confuse: * **Inbox** — your *personal* feed of agent-delivered messages (for example, scheduled-task digests). It is scoped to you alone; admins never see another user's inbox. Inbox messages carry rich content and can be deleted. * **Notifications** — the *workspace* notification center: async results a tenant should see (recommendations, profile-ready, setup nudges, billing). Items can be addressed to you or be workspace-wide (visible to any member), and they are dismissed rather than deleted. Both are read with a `Bearer` token and live under `/v1/api`. Every request authenticates with `Authorization: Bearer hq_pat_...`. All nine endpoints below accept either a personal access token (`bearer_pat`) or an `oauth2` token. ## What each item carries The two list payloads are shaped differently because the surfaces solve different problems. An **inbox message** ([List inbox](/api-reference/notifications/list-inbox)) carries `id`, `source_kind`, `schedule_id`, `schedule_name`, `title`, `body_markdown`, `ui_strings`, `delivered_at`, and `read_at`. The body is Markdown, and when the message came from a schedule fire it includes the originating schedule's id and name so the UI can group and link. Read state is a **timestamp**: `read_at` is `null` while unread. A **notification** ([List notifications](/api-reference/notifications/list-notifications)) carries `id`, `kind`, `title`, `body` (optional), `cta` (optional), `severity`, `status`, and `created_at`. The body is optional plain text, there is an optional call-to-action (`cta`), and read state is an explicit `status` **string** (`unread`, `read`, or `dismissed`). Read state differs between surfaces. The inbox tracks a `read_at` timestamp (`null` = unread). Notifications track a `status` string. That is why the inbox supports re-marking a message *unread*, but notifications do not. ## The inbox `GET /v1/api/inbox` returns one page of your messages, newest delivery first. ```bash theme={null} curl https://api.hq.zone/v1/api/inbox \ -H "Authorization: Bearer hq_pat_..." # → { "messages": [ ... ], "unread_count": 3, "total": 42, "page": 1, "page_size": 25 } ``` The response is a `ListResp`: `messages` (the page), `unread_count` (unread across your *whole* inbox — drives the nav badge, independent of the current page/filter), `total` (rows matching the filter before paging), `page`, and `page_size`. Supported query params: * `unread=true` — only messages whose `read_at` is null. * `q=` — case-insensitive substring search over the title, body, and (for schedule digests) the schedule name. * `page=` — 1-based page index, clamped to `>= 1`. * `page_size=` — rows per page, clamped to `1..=100`, defaults to `25`. * `sort=recent` (default, newest first) or `sort=oldest`. ```bash theme={null} # Unread only, search "revenue", second page of 50, oldest first curl -G https://api.hq.zone/v1/api/inbox \ -H "Authorization: Bearer hq_pat_..." \ --data-urlencode "unread=true" \ --data-urlencode "q=revenue" \ --data-urlencode "page=2" \ --data-urlencode "page_size=50" \ --data-urlencode "sort=oldest" ``` A legacy `limit=` param is still honored as the `page_size` fallback for older clients. Prefer `page_size` in new code. Reading an inbox message just sets (or clears) its `read_at` timestamp. ```bash theme={null} # Mark read — preserves the original read_at if already read curl -X POST https://api.hq.zone/v1/api/inbox//read \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } # Mark unread — clears read_at back to null curl -X POST https://api.hq.zone/v1/api/inbox//unread \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } ``` Both return `{ "ok": true }` ([mark read](/api-reference/notifications/mark-inbox-read), [mark unread](/api-reference/notifications/mark-inbox-unread)). Because the lookup is scoped to your own inbox, a message that does not exist — or is not yours — returns `404`. `POST /v1/api/inbox/read_all` marks all of your unread messages read. It is idempotent — it returns ok even when nothing was unread. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/inbox/read_all \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } ``` See [Mark all inbox read](/api-reference/notifications/mark-all-inbox-read). The inbox is the only surface where items are **permanently deleted**. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/inbox/ \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } ``` Returns `{ "ok": true }`, or `404` if the message does not exist or is not yours. See [Delete inbox message](/api-reference/notifications/delete-inbox). ## The notification center `GET /v1/api/notifications` returns up to 100 non-dismissed notifications, newest first. There are **no query params** — no filters, no pagination. ```bash theme={null} curl https://api.hq.zone/v1/api/notifications \ -H "Authorization: Bearer hq_pat_..." # → { "items": [ ... ], "unread": 2 } ``` The response is a `NotificationsResp`: `items` and `unread` (how many of the returned-scope rows are still unread — drives the bell badge). The scope includes notifications addressed to you *and* workspace-wide ones visible to any member. Dismissed notifications are excluded. See [List notifications](/api-reference/notifications/list-notifications). `POST /v1/api/notifications/{id}/read` flips an `unread` notification to `read` and records the read time. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/notifications//read \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } ``` It only affects a notification currently in the `unread` state and always returns `{ "ok": true }`. See [Mark notification read](/api-reference/notifications/mark-notification-read). `POST /v1/api/notifications/read-all` marks all of your unread notifications read and returns the count. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/notifications/read-all \ -H "Authorization: Bearer hq_pat_..." # → { "updated": 2 } ``` Unlike the inbox's `read_all` (which returns `ok`), this returns `{ "updated": }` — the number of rows updated. See [Mark all notifications read](/api-reference/notifications/mark-all-notifications-read). Notifications are not deleted; they are **dismissed**. `POST /v1/api/notifications/{id}/dismiss` sets `status` to `dismissed`, records the dismiss time, and removes it from future list responses. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/notifications//dismiss \ -H "Authorization: Bearer hq_pat_..." # → { "ok": true } ``` Always returns `{ "ok": true }`. See [Dismiss notification](/api-reference/notifications/dismiss-notification). There is no "un-dismiss" and no inbox-style unread toggle for notifications. Dismissing is one-way: the item drops out of the list permanently. ## Key differences at a glance * **Scope.** Inbox is per-user (`owner_user_id`); notifications are per-workspace and may be addressed to you or visible to every member. * **Read state.** Inbox uses a `read_at` timestamp and supports re-marking *unread*; notifications use a `status` string and do not. * **Removal.** Inbox messages are `DELETE`d; notifications are dismissed (and disappear from the list, but are not re-markable). * **Listing.** The inbox supports unread filtering, search, pagination, and sort; the notification list takes no params and caps at 100 newest non-dismissed items. * **Badges.** Inbox `unread_count` is whole-inbox; notification `unread` is over the returned scope. * **Mark-all response.** Inbox `read_all` returns `{ "ok": true }`; notifications `read-all` returns `{ "updated": }`. # OAuth 2.1 with PKCE Source: https://docs.hq.zone/guides/oauth Register a client, run the authorization-code + PKCE flow, and manage access, refresh, introspection, and revocation against HQ as the authorization server. HQ is an **OAuth 2.1 authorization server**. A client (a browser extension, a CLI, a third-party integration) sends the user through HQ's `/v1/oauth/authorize` endpoint, gets a single-use authorization code back, then exchanges that code for an opaque **Bearer access token** plus a **rotating refresh token** at `/v1/oauth/token`. Every authorization-code flow uses **PKCE with `S256`** — `plain` is rejected. This guide walks the full lifecycle: register a client, build the authorize URL with PKCE, handle the redirect, exchange the code, call the API, refresh, then revoke and introspect. All endpoints live under the base URL `https://api.hq.zone`. The token, introspect, and revoke endpoints accept **either** `application/x-www-form-urlencoded` (the OAuth wire default) **or** `application/json`. Client registration ([Register a client](/api-reference/auth/register-client)) is JSON only. ## Before you start: pick a client type When you register, `token_endpoint_auth_method` decides the client type: * `none` → a **public** client. No secret. It proves itself at the token endpoint with PKCE alone. Use this for browser extensions, SPAs, mobile, and CLIs that can't keep a secret. * `client_secret_post` or `client_secret_basic` → a **confidential** client. It gets a `client_secret` and must send it on every token, introspect, and revoke call (in addition to PKCE). Registered clients are always third-party: `first_party` is forced to `false`, so the user is shown a **consent screen** the first time (and whenever the requested scopes grow). Only HQ's own first-party clients skip consent. ## The full walkthrough Registration is **authenticated** — you must present a valid HQ session or token, and the new client is owned by that account. POST your metadata as JSON to [Register a client](/api-reference/auth/register-client): ```bash theme={null} curl -X POST https://api.hq.zone/v1/oauth/register \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{ "redirect_uris": ["https://app.example.com/callback"], "client_name": "Acme Integration", "token_endpoint_auth_method": "none", "scope": "documents:read conversations:write" }' ``` Request fields (all but `redirect_uris` are optional): * `redirect_uris` — **required**, non-empty. Each must be `https://...` or an `http://` loopback (`localhost` / `127.0.0.1`), with no URL fragment. * `client_name` — display name; defaults to `Unnamed app` if omitted or blank. * `token_endpoint_auth_method` — `none` (public, default), `client_secret_post`, or `client_secret_basic`. * `grant_types` — defaults to `["authorization_code"]`; only `authorization_code` and `refresh_token` are accepted. * `response_types` — defaults to `["code"]`; only `code` is accepted. * `scope` — **required**, space-delimited capability scopes (e.g. `documents:read conversations:write`); every scope must be a known HQ capability. A `201` returns the client info: ```json theme={null} { "client_id": "hq_client_...", "client_secret": "hq_csec_...", "client_id_issued_at": 1733832000, "client_secret_expires_at": 0, "registration_access_token": "hq_ratk_...", "registration_client_uri": "https://api.hq.zone/v1/oauth/register/hq_client_...", "redirect_uris": ["https://app.example.com/callback"], "client_name": "Acme Integration", "token_endpoint_auth_method": "none", "grant_types": ["authorization_code"], "response_types": ["code"], "scope": "documents:read conversations:write" } ``` `client_secret` (confidential clients only) and `registration_access_token` are shown **once**, at registration. Store them now. The `registration_access_token` is what you'll use to read, update, or delete the client later — not your HQ session. For a `none` (public) client there is no `client_secret` / `client_secret_expires_at` in the response. PKCE is standard client-side crypto. Generate a high-entropy `code_verifier`, then derive `code_challenge = base64url(sha256(verifier))`. HQ requires the **`S256`** method. ```js theme={null} function base64url(bytes) { return btoa(String.fromCharCode(...new Uint8Array(bytes))) .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } // 32 random bytes → the verifier (kept secret on the client). const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); // challenge = base64url(SHA-256(verifier)). const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); const challenge = base64url(digest); ``` Keep `verifier` on the client; you'll send it at the token step. Only `challenge` goes in the authorize URL. HQ verifies PKCE by computing `base64url(sha256(code_verifier))` and comparing it to the stored challenge. It also rejects a `code_challenge` shorter than 32 characters — a real `S256` challenge is 43 characters. Redirect the user's browser to [Authorize](/api-reference/auth/oauth-authorize). The user must have an active HQ session; if they aren't signed in, HQ bounces them to sign-in and back. This is a browser redirect, not a fetch. ```text theme={null} https://api.hq.zone/v1/oauth/authorize ?client_id=hq_client_... &redirect_uri=https://app.example.com/callback &code_challenge= &code_challenge_method=S256 &scope=documents:read%20conversations:write &state= ``` Query parameters: * `client_id` — **required**. Must resolve to a known, active client. * `redirect_uri` — **required**. Must be on the client's registered allowlist. * `code_challenge` — **required**. The `S256` challenge from the previous step. * `code_challenge_method` — optional; defaults to `S256` and **must** be `S256` if sent (`plain` is rejected). * `scope` — optional, space-delimited. The granted scope is what you request **intersected** with the client's allowed scopes. An empty/omitted `scope` grants **all** of the client's allowed scopes. If you request only scopes the client isn't allowed, you get `invalid_scope`. * `state` — optional opaque value echoed back on the redirect. Use it to bind the response to your request (CSRF protection). On success HQ responds `302` and redirects to your `redirect_uri` with `code` and `state` appended: ```text theme={null} https://app.example.com/callback?code=&state= ``` A bad request (`invalid_request`, unknown `client_id`, disallowed `redirect_uri`, or `invalid_scope`) returns `400`. For a third-party (registered) client, HQ first redirects the browser to a consent screen; the `code` redirect only happens after the user approves. If the user denies, the redirect carries `error=access_denied&state=...` instead of a `code`. Your callback receives `code`. Verify `state` matches what you sent, then POST to [Token](/api-reference/auth/oauth-token) with `grant_type=authorization_code` and the `code_verifier` you stashed. The OAuth default is form-encoded: ```bash theme={null} curl -X POST https://api.hq.zone/v1/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d grant_type=authorization_code \ -d code= \ -d code_verifier= \ -d redirect_uri=https://app.example.com/callback \ -d client_id=hq_client_... # confidential clients also send: -d client_secret=hq_csec_... ``` Required form fields for this grant: * `grant_type` — `authorization_code`. * `code` — the single-use code from the redirect. * `code_verifier` — the PKCE verifier; HQ checks `base64url(sha256(code_verifier))` against the stored challenge. * `redirect_uri` — must match the one used at `/authorize`. * `client_id` — must match the client that started the flow. * `client_secret` — **confidential clients only**; public clients omit it. A `200` returns the token pair: ```json theme={null} { "access_token": "...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "...", "scope": "documents:read conversations:write" } ``` Response fields: `access_token` (opaque Bearer), `token_type` (always `Bearer`), `expires_in` (seconds — the access token lives **1 hour**), `refresh_token` (the rotating token, valid **30 days**), and `scope` (space-delimited granted scopes). Failure modes: `400` for `invalid_grant` (bad/expired code, PKCE mismatch, `redirect_uri` or `client_id` mismatch) or `invalid_request` (missing fields); `401` for `invalid_client` (a confidential client's secret didn't verify). The authorization code is single-use and short-lived (10-minute upper bound). Exchange it immediately. PKCE binds the exchange to the client that started the flow, so a leaked code is useless without the original `code_verifier`. Use the `access_token` as a Bearer on HQ API calls: ```bash theme={null} curl https://api.hq.zone/v1/api/conversations \ -H "Authorization: Bearer " ``` The token carries the granted scopes; the user's role remains the runtime ceiling, so a token never grants more than the user themselves has. The access token expires in an hour. Trade your `refresh_token` for a fresh pair at [Token](/api-reference/auth/oauth-token) with `grant_type=refresh_token`: ```bash theme={null} curl -X POST https://api.hq.zone/v1/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d grant_type=refresh_token \ -d refresh_token= \ -d client_id=hq_client_... # confidential clients also send: -d client_secret=hq_csec_... ``` Required form fields for this grant: * `grant_type` — `refresh_token`. * `refresh_token` — the current refresh token. It must belong to the same `client_id` that was issued it. * `client_id` — must match the client the refresh token was bound to. * `client_secret` — **confidential clients only**. The response is the same `TokenResp` shape as above, with a **new** `access_token` and a **new** `refresh_token`. The original scopes are carried forward unchanged. Refresh tokens **rotate**: every refresh revokes the one you just used and returns a new one. Always replace your stored refresh token with the new one. If a previously-rotated (already-revoked) refresh token is replayed, HQ treats it as a compromise signal and **revokes the entire token family** — both the access and refresh tokens and all their rotations. You'll then have to re-run the authorization flow. Errors are `400 invalid_grant` for an unknown, expired, reused, or mismatched-client refresh token; `401 invalid_client` for a bad confidential secret. POST to [Revoke](/api-reference/auth/oauth-revoke). The calling client authenticates with its `client_id` (plus `client_secret` for confidential clients): ```bash theme={null} curl -X POST https://api.hq.zone/v1/oauth/revoke \ -H "Content-Type: application/x-www-form-urlencoded" \ -d token= \ -d client_id=hq_client_... # confidential clients also send: -d client_secret=hq_csec_... ``` Request fields: `token` (**required** — the token to revoke), `token_type_hint` (optional, ignored), `client_id` (**required**), `client_secret` (confidential clients only). If the token belongs to the authenticating client, it **and its entire refresh family** (the paired access + refresh tokens and all rotations) are revoked. Revoke **always returns `200`** — including for unknown, already-revoked, or not-yours tokens — so it never reveals whether a token exists or who owns it. (A bad confidential `client_secret` is the one exception: `401 invalid_client`.) ## Inspecting a token (RFC 7662) To check whether a token is still valid, POST it to [Introspect](/api-reference/auth/oauth-introspect). The calling client authenticates the same way as revoke: ```bash theme={null} curl -X POST https://api.hq.zone/v1/oauth/introspect \ -H "Content-Type: application/x-www-form-urlencoded" \ -d token= \ -d client_id=hq_client_... # confidential clients also send: -d client_secret=hq_csec_... ``` Request fields: `token` (**required**), `token_type_hint` (optional, ignored), `client_id` (**required**), `client_secret` (confidential clients only). A `200` returns metadata **only** for a token the authenticating client itself issued and that is neither revoked nor expired: ```json theme={null} { "active": true, "scope": "documents:read conversations:write", "client_id": "hq_client_...", "username": "", "token_type": "Bearer", "exp": 1733835600, "iat": 1733832000, "sub": "" } ``` Response fields: `active` (always present), and when active also `scope`, `client_id`, `username`, `token_type` (`Bearer`), `exp` (Unix expiry), `iat` (Unix issued-at), and `sub` (the user id). For any other token — unknown, expired, revoked, or issued to a different client — the response is simply `{ "active": false }`, with no leaked detail. A bad confidential `client_secret` returns `401 invalid_client`. Otherwise introspect always returns `200` with `active` true or false. ## Managing a registered client (RFC 7592) The three management endpoints authenticate with the **`registration_access_token`** from registration as a Bearer token — **not** your HQ session. ```bash theme={null} curl https://api.hq.zone/v1/oauth/register/ \ -H "Authorization: Bearer " ``` [Get a client](/api-reference/auth/get-client) returns the current `ClientInfo` metadata (`redirect_uris`, `client_name`, `token_endpoint_auth_method`, `grant_types`, `response_types`, `scope`). The `client_secret` is never returned here. `200` on success, `401` for a bad registration token, `404` for an unknown client. ```bash theme={null} curl -X PUT https://api.hq.zone/v1/oauth/register/ \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "redirect_uris": ["https://app.example.com/callback", "https://app.example.com/cb2"], "client_name": "Acme Integration v2", "scope": "documents:read documents:write conversations:write" }' ``` [Update a client](/api-reference/auth/update-client) re-validates and replaces the **mutable** metadata: name, redirect URIs, and requestable scopes. The client type (and its secret lifecycle) is fixed at registration and can't change. Returns the updated `ClientInfo` (`200`); `400` for invalid metadata, `401` for a bad registration token. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/oauth/register/ \ -H "Authorization: Bearer " ``` [Delete a client](/api-reference/auth/delete-client) soft-disables the client so it can no longer be used. Returns `204 No Content`; `401` for a bad registration token. Each account is capped at 50 active registered clients. Deregister clients you no longer use to free up room. # Onboard a workspace Source: https://docs.hq.zone/guides/onboarding Walk a new workspace through the onboarding wizard: check status, validate a business domain, confirm it, and complete onboarding. A freshly created HQ workspace starts **not onboarded**. Until onboarding completes, the workspace can be blocked from normal API access — the onboarding wizard endpoints drive it the rest of the way. This guide walks the flow: read the current status, live-validate a business domain before submit, confirm the domain, and mark onboarding complete. All requests are authenticated with a personal access token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` Setting the domain and completing onboarding require the **admin** scope (`security(("bearer_pat" = ["admin"]))`); a non-admin caller gets a `403`. Reading status and checking a domain only require an authenticated caller. ## The flow Start by reading where the workspace stands. The response tells you what's left to do and which wizard track applies. ```bash theme={null} curl https://api.hq.zone/v1/api/onboarding/status \ -H "Authorization: Bearer $HQ_TOKEN" # → 200 # { # "completed": false, # "domain_confirmed": false, # "business_domain": null, # "track": "slack" # } ``` Fields: * `completed` (bool) — whether onboarding has finished. * `domain_confirmed` (bool) — whether the business domain has been confirmed. * `business_domain` (string or `null`) — the configured business domain, if any. * `track` (string) — the wizard track the SPA should render: `slack`, `teams`, or `web`. It is derived from the workspace's primary corpus source (a `slack` source wins, then `teams`, otherwise `web`). See [Get onboarding status](/api-reference/onboarding/onboarding-status). Before submitting, pre-check the value the user typed so a typo is caught early. Pass the candidate as the `domain` query parameter: ```bash theme={null} curl -G https://api.hq.zone/v1/api/onboarding/domain/check \ -H "Authorization: Bearer $HQ_TOKEN" \ --data-urlencode "domain=https://www.acme.com/about" # → 200 # { "valid_format": true, "normalized": "acme.com", "resolves": true } ``` The response reports: * `valid_format` (bool) — whether the input normalizes to a usable bare host. * `normalized` (string) — the normalized host (scheme, `www.`, path/query stripped, lowercased). Present only when the format is valid. * `resolves` (bool) — whether that host resolves to at least one usable public address. When the input doesn't look like a domain, the response is just `{ "valid_format": false, "resolves": false }` (no `normalized` field). The check normalizes before resolving, so `https://www.Acme.com/contact` and `acme.com` both collapse to `acme.com`. A host that resolves only into a private or internal range reports `resolves: false`. See [Check a domain](/api-reference/onboarding/check-domain). Once the candidate looks good, submit it. The request body is a single `domain` field: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/onboarding/domain \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"domain":"acme.com"}' # → 200 # { "ok": true } ``` The server re-normalizes and re-validates the value, then confirms it (this sets `domain_confirmed` in the status) and kicks off a profile crawl of that website. The API is the boundary, so it does not trust the live pre-check: * An invalid or unresolvable domain is rejected with `400`. * A non-admin caller is rejected with `403`. See [Set onboarding domain](/api-reference/onboarding/set-domain). Finally, mark the workspace complete. This lifts the onboarding gate that can otherwise block normal API access for a new workspace. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/onboarding/complete \ -H "Authorization: Bearer $HQ_TOKEN" # → 200 # { "ok": true } ``` The call is idempotent — it only stamps the completion time if onboarding wasn't already complete, so calling it twice is safe. A non-admin caller is rejected with `403`. See [Complete onboarding](/api-reference/onboarding/complete-onboarding). ## Putting it together Re-read status after completing to confirm the gate is lifted: ```bash theme={null} curl https://api.hq.zone/v1/api/onboarding/status \ -H "Authorization: Bearer $HQ_TOKEN" # → 200 # { "completed": true, "domain_confirmed": true, "business_domain": "acme.com", "track": "slack" } ``` `completed: true` is the signal that the workspace is fully onboarded; `domain_confirmed: true` with a non-null `business_domain` reflects a successful domain step. # Schedule a recurring agent run Source: https://docs.hq.zone/guides/schedules Create autonomous schedules that fire an agent on a cron or RRULE trigger, then list, pause, fire on demand, and tear them down. A **schedule** runs an agent automatically on a recurring trigger — no human in the loop. You give it a `prompt`, a `trigger` (when to fire), and a `deliver_to` (where the output lands), and HQ runs the agent on that cadence and delivers the result. This guide walks the full lifecycle: create, observe, pause/resume, fire once on demand, edit, and tear down. All routes live under `https://api.hq.zone/v1/api/schedules` and authenticate with a personal access token: `Authorization: Bearer hq_pat_...`. Read operations need the `schedules:read` scope; everything that mutates a schedule needs `schedules:write`. ## Create a recurring run The `trigger` field is a tagged object — a `kind` plus its parameters. For a recurring run you'll use one of: * `cron` — a **5-field cron expression** (`min hour dom month dow`) in a named timezone. `tz` is an **IANA name** like `"Europe/Stockholm"`; fixed offsets such as `"UTC+3"` are rejected. * `rrule` — an RFC 5545 RRULE for patterns cron can't express (e.g. "third Tuesday of the month"), also with an IANA `tz`. ```json theme={null} { "kind": "cron", "expr": "0 8 * * MON", "tz": "Europe/Stockholm" } { "kind": "rrule", "expr": "FREQ=WEEKLY;BYDAY=MO,WE,FR", "tz": "Europe/Stockholm" } ``` `tz` is required on the engine-side trigger. Pass an IANA zone name explicitly — a fixed UTC offset is refused because it can't track DST. `deliver_to` is also a tagged object. The supported destinations are: * `{ "kind": "web_inbox" }` — the user's web inbox (read via the `/v1/api/conversations` surface). * `{ "kind": "slack_dm", "user_id": "U0123..." }` — DM a Slack user. * `{ "kind": "slack_channel", "channel_id": "C0123..." }` — post in a Slack channel. * `{ "kind": "teams_dm", "conversation_id": "..." }` — a Microsoft Teams chat. * `{ "kind": "teams_channel", "team_id": "...", "channel_id": "..." }` — a Teams channel. `POST /v1/api/schedules` creates a schedule owned by the caller. The body is: * `name` (required) and optional `description`. * `trigger` (required) — the object from step 1. * `prompt` (required) — the instruction the agent runs on each fire. * `agent_id` (optional) — which agent runs the prompt. If omitted, the workspace's **default enabled agent** is used; a non-existent `agent_id` returns `404`. * `deliver_to` (required) — the destination from step 2. * `reset_each_fire` (optional, default `false`) — `false` reuses one persistent conversation thread across fires (so the agent can compare against prior runs); `true` starts a fresh conversation each fire. * `delivery_locale` (optional) — a BCP-47 locale override for this schedule's deliveries; falls back to the owner's workspace locale when absent. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/schedules \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "name": "Monday revenue digest", "description": "Weekly QoQ revenue summary", "trigger": { "kind": "cron", "expr": "0 8 * * MON", "tz": "Europe/Stockholm" }, "prompt": "Summarise revenue changes quarter over quarter and flag anomalies.", "deliver_to": { "kind": "web_inbox" }, "reset_each_fire": false }' # → 201 { "schedule": { "id": "", "state": "active", "next_fire_at": "...", ... } } ``` A successful create returns `201` with the full schedule object. If your plan's schedule limit is reached, the request fails with `402`. See the full request and response shapes on [Create a schedule](/api-reference/schedules/create-schedule). ## List and inspect `GET /v1/api/schedules` returns your schedules plus a `total` count for pagination. By default `scope=mine` returns only the caller's own schedules. ```bash theme={null} curl https://api.hq.zone/v1/api/schedules \ -H "Authorization: Bearer hq_pat_..." # → 200 { "schedules": [ ... ], "total": 3, "limit": 100, "offset": 0 } ``` Each entry carries observability fields: `state`, `last_fire_at`, `last_fire_status`, `next_fire_at`, `fire_count`, `failure_count`, `consecutive_failure_count`, `last_fire_lag_ms`, and `last_run_conversation_id` (a link to the conversation from the most recent run). By default the list **excludes archived** schedules so you see the working set. To change that: * `state=` filters by an explicit lifecycle state (passes through verbatim). * `include_archived=true` adds archived rows to the default view (the audit history view). * `limit` defaults to `100` (max `500`); `offset` paginates the workspace view. To fetch one schedule's full detail by id, use `GET /v1/api/schedules/{id}`. You can read a schedule only if you own it or are an admin; otherwise it returns `404`. ```bash theme={null} curl https://api.hq.zone/v1/api/schedules/ \ -H "Authorization: Bearer hq_pat_..." # → 200 { "id": "", "state": "active", ... } ``` Reference: [List schedules](/api-reference/schedules/list-schedules) and [Get a schedule](/api-reference/schedules/get-schedule). ### Lifecycle states A schedule's `state` is one of: * `active` — firing on its trigger. * `paused` — temporarily stopped; resumable. * `quarantined` — its stored trigger or args won't parse; the engine parked it. * `archived` — cancelled; will never fire again (history retained). ## Pause and resume Pause an active schedule to stop it firing until you resume it. `POST /v1/api/schedules/{id}/pause` moves it from `active` → `paused` and clears its next fire. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/schedules//pause \ -H "Authorization: Bearer hq_pat_..." # → 200 { "ok": true } ``` `POST /v1/api/schedules/{id}/resume` brings it back and returns the newly computed next fire time. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/schedules//resume \ -H "Authorization: Bearer hq_pat_..." # → 200 { "ok": true, "next_fire_at": "..." } ``` You can't resume an `archived` schedule. A `quarantined` schedule must have its trigger fixed via an update before it will resume — resuming it as-is would just re-quarantine on the next fire. Only the schedule's owner or an admin may pause or resume; others get `403`. ## Fire once now `POST /v1/api/schedules/{id}/fire_now` triggers an immediate run **without** changing the regular firing cadence. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/schedules//fire_now \ -H "Authorization: Bearer hq_pat_..." # → 200 { "ok": true } ``` Owner or admin only (`403` otherwise). See [Fire a schedule now](/api-reference/schedules/fire-now). ## Update a schedule `PATCH /v1/api/schedules/{id}` changes only the fields you supply: `name`, `description`, `trigger`, or `args`. When the `trigger` changes, the response includes the recomputed `next_fire_at`. ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/api/schedules/ \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "trigger": { "kind": "cron", "expr": "0 9 * * MON", "tz": "Europe/Stockholm" } }' # → 200 { "ok": true, "next_fire_at": "..." } ``` For `description` specifically, sending an explicit `null` clears it, while omitting the field keeps the current value. Owner or admin only (`403` otherwise). See [Update a schedule](/api-reference/schedules/update-schedule). ## Tear down: cancel, then erase Teardown is a deliberate two-step path so you can't destroy history by accident. `DELETE /v1/api/schedules/{id}` cancels the schedule and **archives** it: it flips `state` → `archived`, drops pending timers, and stops all future runs while retaining its history. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/schedules/ \ -H "Authorization: Bearer hq_pat_..." # → 200 { "ok": true } ``` `DELETE /v1/api/schedules/{id}/erase` permanently deletes the schedule row. The engine **refuses to erase a schedule that isn't already archived** — you must cancel it first. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/schedules//erase \ -H "Authorization: Bearer hq_pat_..." # → 200 { "ok": true } ``` Erase is destructive and irreversible. It only operates on archived rows; attempting to erase an active, paused, or quarantined schedule is rejected — cancel it first. Both cancel and erase are owner-or-admin only (`403` otherwise). References: [Cancel a schedule](/api-reference/schedules/cancel-schedule) and [Erase a schedule](/api-reference/schedules/erase-schedule). ## Admin: filter by owner Admins can list across the whole workspace with `scope=workspace` (non-admins get `403`), optionally narrowing to one owner via `owner_user_id`. To populate a "filter by user" dropdown with only users who actually have schedules, call `GET /v1/api/schedules/owners`. ```bash theme={null} curl https://api.hq.zone/v1/api/schedules/owners \ -H "Authorization: Bearer hq_pat_..." # → 200 { "owners": [ { "user_id": "...", "display_name": "...", "schedule_count": 4 }, ... ] } ``` This endpoint is admin-only (`403` otherwise) and returns each distinct owner with a `schedule_count`. See [List schedule owners](/api-reference/schedules/list-owners). # Stream a chat (SSE) Source: https://docs.hq.zone/guides/streaming-chat Send a message and read the agent's reply live over Server-Sent Events. HQ turns are **asynchronous**: you post a message, it runs server-side on the agent's machine, and you watch it unfold over a **Server-Sent Events (SSE)** stream. This is how you build a live chat UI or react to tool calls and artifacts as they happen. ## The flow Create one against an agent (`agent_id` from [List agents](/api-reference/agents/list-agents)): ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/conversations \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"agent_id":""}' # → { "id": "", ... } ``` Attach to the stream so you don't miss early events: ```bash theme={null} curl -N https://api.hq.zone/v1/api/conversations//stream \ -H "Authorization: Bearer $HQ_TOKEN" -H "Accept: text/event-stream" ``` `-N` disables buffering so events print as they arrive. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/conversations//messages \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"text":"What changed in revenue quarter over quarter?","idempotency_key":""}' # → 202 { "accepted": true, "stream_url": "/v1/api/conversations//stream", "idempotent": false } ``` The response is immediate; the reply arrives on the stream you opened. ## Reading the stream Each event has a name, an `id:` cursor, and a one-line JSON payload: ```text theme={null} event: text_delta id: 7Z9aQ2 data: {"text":"Revenue rose 12% "} event: text_delta id: 7Z9aQ3 data: {"text":"quarter over quarter."} event: final id: 7Z9aQ4 data: {"text":"Revenue rose 12% quarter over quarter.","duration_ms":4120} ``` Append `text_delta` chunks to the active reply; `final` (or `error`) ends the turn. The full event vocabulary and scope rules are on [Stream conversation events](/api-reference/conversations/stream). ## In JavaScript `EventSource` can't set an `Authorization` header, so read the stream with `fetch` and a streaming body reader (works in Node 18+ and modern browsers): ```js theme={null} const base = "https://api.hq.zone"; const headers = { Authorization: `Bearer ${process.env.HQ_TOKEN}` }; const convId = ""; // 1. Post the message (returns immediately). await fetch(`${base}/v1/api/conversations/${convId}/messages`, { method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify({ text: "What changed in revenue quarter over quarter?", idempotency_key: crypto.randomUUID() }), }); // 2. Read the reply off the SSE stream. const res = await fetch(`${base}/v1/api/conversations/${convId}/stream`, { headers: { ...headers, Accept: "text/event-stream" }, }); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ""; for (;;) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); const frames = buf.split("\n\n"); buf = frames.pop(); // keep the trailing partial frame for (const frame of frames) { const ev = {}; for (const line of frame.split("\n")) { if (line.startsWith("event:")) ev.event = line.slice(6).trim(); else if (line.startsWith("data:")) ev.data = line.slice(5).trim(); // lines starting with ":" are heartbeats — ignore } if (!ev.event) continue; const payload = ev.data ? JSON.parse(ev.data) : {}; if (ev.event === "text_delta") process.stdout.write(payload.text); if (ev.event === "final" || ev.event === "error") return; } } ``` Track the last `id:` you saw and send it as the `Last-Event-ID` header when reconnecting — the server replays what you missed from the journal (or pass `?since_seq=` on a fresh attach). Always include an `idempotency_key` in the message body so a network retry never starts a duplicate turn. ## Tips * **Open the stream early** — attach before or right after posting so you catch the first `text_delta`. * **One stream, many turns** — `result`/`error` ends a *turn*, not the stream. Keep it open and post again for the next turn. * **Stop a running turn** with [Interrupt the active turn](/api-reference/conversations/interrupt). # Publish and share surfaces (apps) Source: https://docs.hq.zone/guides/surfaces List a conversation's surfaces, list the workspace app catalog, mint a time-limited share link, change visibility, and delete or restore an app. When an HQ agent builds a live app, the platform records it as a **surface**: a persistent, browser-reachable application backed by the conversation's VM. Each surface has a stable id, a `slug`, a lifecycle `state`, a `declared_port` the in-VM server listens on, a `run_mode`, an `auth_mode`, and a ready-to-open `url`. This guide covers listing a conversation's surfaces, listing the whole workspace's app catalog, minting a time-limited share link, switching a surface between private and public, and the delete / restore lifecycle. All requests go to `https://api.hq.zone` and authenticate with a personal access token: ```bash theme={null} export HQ_TOKEN="hq_pat_..." ``` The endpoints in this guide carry these scopes: reads (listing a conversation's surfaces, listing apps) require `conversations:read`; every mutation (share, visibility, restore, delete) requires `conversations:write`. ## What a surface is A surface is the live app row attached to a conversation. The list endpoints return these fields per surface: * `id` — the surface id used by the share / visibility / restore / delete endpoints. * `slug` — the URL slug for the app. * `state` — the lifecycle state. Non-destroyed surfaces are listed; the states you will see include `booting`, `live`, `paused`, `archived`. A `destroyed` surface is filtered out of every listing. * `declared_port` — the port the app's server is bound to inside the VM. * `run_mode` — `dev` or `prod`. * `auth_mode` — `signed_url` (private) or `public`. This is the underlying column; the Apps list also exposes it as a derived `visibility` of `private` or `public`. * `url` — a ready-to-open, visitor-facing URL: the bare public URL when `auth_mode` is `public`, or a signed plain-host URL when it is `signed_url`. There is no `visibility` column on a surface. Visibility is derived from `auth_mode`: `public` maps to visibility `public`, and `signed_url` maps to visibility `private`. ## List a conversation's surfaces [List conversation surfaces](/api-reference/conversations/list-surfaces) returns the live application surfaces attached to one conversation, excluding destroyed ones, ordered by most recent activity. ```bash theme={null} curl https://api.hq.zone/v1/api/conversations//surfaces \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response wraps a `surfaces` array. Each entry carries `id`, `slug`, `state`, `declared_port`, `run_mode`, `auth_mode`, the visitor-facing `url`, and a separate owner-only `dev_url`: ```js theme={null} // → 200 // { // "surfaces": [ // { // "id": "", // "slug": "revenue-dashboard", // "state": "live", // "declared_port": 5173, // "run_mode": "dev", // "auth_mode": "signed_url", // "url": "https://...", // "dev_url": "https://..." // } // ] // } ``` The `url` is the visitor-facing view that the Share modal hands out and "open in new tab" points at. The `dev_url` is a separate owner-only developer-embed URL (always signed) that loads the in-browser devtools runtime; it is an empty string when no signing secret is configured. If you are a workspace admin inspecting another member's conversation, add `?view=admin` — this admin read is audited. ## List the workspace app catalog [List apps](/api-reference/conversations/list-apps) returns the workspace-wide catalog of persistent app surfaces, visible to any member of the workspace, excluding destroyed apps and ordered by most recent activity. ```bash theme={null} curl https://api.hq.zone/v1/api/apps \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response carries an `apps` array plus the workspace quota (`max_persistent`) and how many apps currently count against it (`used`). Each app includes `id`, `slug`, `state`, a derived `visibility` (`public` or `private`), `run_mode`, `declared_port`, `backing_conversation_id` (null if that conversation was deleted), a visitor-facing `url`, and `created_at` / `last_activity_at` as Unix-seconds timestamps: ```js theme={null} // → 200 // { // "apps": [ // { // "id": "", // "slug": "revenue-dashboard", // "state": "live", // "visibility": "private", // "run_mode": "dev", // "declared_port": 5173, // "backing_conversation_id": "", // "url": "https://...", // "created_at": 1749546840, // "last_activity_at": 1749550440 // } // ], // "max_persistent": 5, // "used": 1 // } ``` The conversation-surfaces list is conversation-scoped (one thread's apps); the Apps catalog is workspace-scoped (every member sees the same apps). Use the conversation list to embed the app a thread just built; use the catalog for a workspace-wide management view. ## Mint a time-limited share link [Share a surface](/api-reference/conversations/share-surface) mints a time-limited signed URL you can paste into chat, email, or a doc **without** making the surface publicly visible. The surface stays private; the URL carries the token that lets a recipient in. Omit the body (or send an empty one) to get the default validity window of **7 days**: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/surfaces//share \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{}' ``` The response is the surface `id`, the tokenized `url`, and `exp` (the expiry as a Unix-seconds timestamp): ```js theme={null} // → 200 // { // "surface_id": "", // "url": "https://...?token=...&exp=...", // "exp": 1750155640 // } ``` Set `ttl_secs` (seconds) to control the window. It is clamped to the inclusive range **60 seconds (1 minute) to 2,592,000 seconds (30 days)**; anything outside that range is rejected with a `400`: ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/surfaces//share \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"ttl_secs":86400}' ``` The share link keeps the surface private — it does not flip `auth_mode`. To open a surface to anyone with the bare URL, change its visibility instead (next section). A `404` from this endpoint means the surface was not found in your workspace. ## Change visibility [Set surface visibility](/api-reference/conversations/set-visibility) flips a surface between private and public. The only accepted values are `private` and `public`; anything else returns a `400`. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/surfaces//visibility \ -H "Authorization: Bearer $HQ_TOKEN" -H "Content-Type: application/json" \ -d '{"visibility":"public"}' ``` The response echoes the surface `id`, the resulting `visibility`, and the underlying `auth_mode` it maps to (`private` to `signed_url`, `public` to `public`): ```js theme={null} // → 200 // { // "surface_id": "", // "visibility": "public", // "auth_mode": "public" // } ``` Visibility can only be changed on a surface in a non-terminal state (`live`, `paused`, or `booting`). If the surface is not found or is in a terminal state, the call returns `404`. ## Delete and restore An app surface can be put to sleep and woken back up, or torn down for good. [Restore a surface](/api-reference/conversations/restore-surface) wakes a paused app back to `live`. Restore is **app-only**. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/surfaces//restore \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response carries the surface `id` and an `outcome` describing what happened — `already_live`, `restored`, or `in_progress`: ```js theme={null} // → 200 // { "surface_id": "", "outcome": "restored" } ``` A `404` means the surface was not found in your workspace. [Delete a surface](/api-reference/conversations/delete-surface) stops the app and releases its resources, flipping the surface to a destroyed state. ```bash theme={null} curl -X DELETE https://api.hq.zone/v1/api/surfaces/ \ -H "Authorization: Bearer $HQ_TOKEN" ``` The response carries the surface `id` and an `outcome` — `destroyed` (this call did the teardown) or `already_destroyed` (it was already gone, so the call is a no-op): ```js theme={null} // → 200 // { "surface_id": "", "outcome": "destroyed" } ``` A `404` means the surface was not found in your workspace. Delete is permanent: a destroyed surface is filtered out of every listing and cannot be restored — restore rejects surfaces in a terminal state (publish a fresh app instead). A non-admin caller must participate in the surface's backing conversation; a workspace admin may delete any app in the workspace. # Store structured data in tables Source: https://docs.hq.zone/guides/tables Create typed tables, write and query rows, evolve the schema, and export to CSV — a governed, multi-tenant data store your agents and your team share. A **table** is a durable, typed, multi-tenant store of structured data — the Airtable-class capability, built native so it composes with HQ's agents, identity chain, and audit. You define typed **fields**, then read and write **rows**; the data persists across conversations, and every write is stamped with who made it (human or agent) and recorded in the audit log. Tables serves two audiences over one store: * **Your team** — "save these leads", "track this pipeline" — edited through this API or the web-UI grid. Tables created here are **workspace-owned**. * **Your agents** — a durable relational scratchpad they read and write through the `hq:tables` MCP server. Agents can own their own tables and even evolve schema under governance. This guide covers the HTTP API. All routes live under `https://api.hq.zone/v1/api/tables` and authenticate with a personal access token: `Authorization: Bearer hq_pat_...`. Reads need the `tables:read` scope; writes need `tables:write`. The tables subsystem is provisioned per deployment. If it isn't configured for your workspace, these routes return `503` — enable the `hq:tables` integration (it ships opt-in/off) and ensure your workspace has the tables data plane provisioned. ## Field types Each field has a **logical type** that maps to real typed storage. Pass the type as the `type` string when you create a table or add a field: | Logical type | Notes | | --------------------------------- | ------------------------------------------------------------------- | | `text` / `long_text` | Short and multi-line strings. | | `number` / `currency` / `percent` | Numeric; format hints go in `options`. | | `date` / `datetime` | Calendar date / timestamp. | | `boolean` | True / false. | | `single_select` / `multi_select` | One or many values from a list; the choice list lives in `options`. | | `attachment` | File references (stored as artifact links, never inline bytes). | | `link_to_record` | A relation to another table — set `link_target` to that table's id. | | `autonumber` | Auto-incrementing integer. | | `json` | Escape hatch for sparse/nested data. | `formula`, `rollup`, and `lookup` (computed fields) are a planned fast-follow, not yet available. Every field accepts `required`, `is_unique`, and `indexed` booleans (all default `false`), plus a free-form `options` object the surfaces interpret per type (for example, a `link_to_record` field records its `target_table` there). ## Create a table `POST /v1/api/tables` creates a workspace-owned table with its fields in one call. Each field is `{ "name", "type", ... }`. Optional per-field flags: `required`, `is_unique`, `indexed`, `options`, and `link_target` (for `link_to_record`). The body takes `name` (required), an optional `slug` and `description`, and the `fields` array. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/tables \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "name": "Leads", "description": "Inbound sales leads", "fields": [ { "name": "Company", "type": "text", "required": true }, { "name": "Contact", "type": "text" }, { "name": "Value", "type": "currency" }, { "name": "Stage", "type": "single_select", "options": { "choices": ["New", "Contacted", "Won", "Lost"] } }, { "name": "Signed", "type": "boolean" } ] }' # → 200 { "id": "", "slug": "leads", "name": "Leads", "fields": [ ... ] } ``` Field names are slugified into stable **field slugs** (e.g. `Company` → `company`) — you reference rows by those slugs. An invalid spec (unknown type, a `link_to_record` with no `link_target`) returns `400`. See the full request and response shapes on [Create a table](/api-reference/tables/create-table). To list every table in the workspace, use [List tables](/api-reference/tables/list-tables) (`GET /v1/api/tables`); to read one table with its fields, [Get a table](/api-reference/tables/get-table) (`GET /v1/api/tables/{id}`). ## Write rows A row is a JSON object keyed by **field slug**. `POST /v1/api/tables/{id}/rows` inserts one or many. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/tables//rows \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "rows": [ { "company": "Acme", "contact": "Dana", "value": 12000, "stage": "New" }, { "company": "Globex", "contact": "Sam", "value": 48000, "stage": "Contacted" } ] }' # → 200 { "ids": ["", ""] } ``` Update one row's fields with `PATCH /v1/api/tables/{id}/rows/{row_id}` — only the slugs you include change: ```bash theme={null} curl -X PATCH https://api.hq.zone/v1/api/tables//rows/ \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "patch": { "stage": "Won", "signed": true } }' # → 200 { "updated": true } ``` Delete a row with `DELETE /v1/api/tables/{id}/rows/{row_id}` (`→ { "deleted": true }`). A missing row returns `404`. References: [Insert rows](/api-reference/tables/insert-rows), [Update a row](/api-reference/tables/update-row), [Delete a row](/api-reference/tables/delete-row). ## Query rows `POST /v1/api/tables/{id}/rows/query` reads rows with filters, sorting, projection, and pagination. An empty body returns the first page of all rows. ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/tables//rows/query \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "filters": [ { "field": "stage", "op": "eq", "value": "Won" }, { "field": "value", "op": "gte", "value": 10000 } ], "sorts": [ { "field": "value", "desc": true } ], "select": ["company", "value", "stage"], "limit": 50, "offset": 0 }' # → 200 { "rows": [ { "id": "", "company": "Globex", "value": 48000, "stage": "Won" } ] } ``` * **`filters`** — each `{ "field": "", "op": "", "value": }`. Operators: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `is_empty`, `is_not_empty`. Multiple filters combine with AND. * **`sorts`** — each `{ "field": "", "desc": }`. * **`select`** — field slugs to return; omit for all fields. * **`limit`** / **`offset`** — page the result set. Full shape on [Query rows](/api-reference/tables/query-rows). ## Evolve the schema Add a field at any time with `POST /v1/api/tables/{id}/fields` (the same field shape as create): ```bash theme={null} curl -X POST https://api.hq.zone/v1/api/tables//fields \ -H "Authorization: Bearer hq_pat_..." -H "Content-Type: application/json" \ -d '{ "name": "Owner", "type": "text", "indexed": true }' # → 200 { "id": "", "slug": "owner", ... } ``` Drop a field with `DELETE /v1/api/tables/{id}/fields/{field_id}`, and delete a whole table with `DELETE /v1/api/tables/{id}`. **Additive** changes (add a table, add a field) apply immediately. **Destructive** changes (drop a field, delete a table) are governed: a response of `{ "status": "applied" }` means it took effect, while `{ "status": "pending", "change_id": "..." }` means it was queued for a workspace admin to approve. Agent-initiated destructive changes on shared tables always queue; the typed confirmation in the web-UI grid is the human equivalent. References: [Add a field](/api-reference/tables/add-field), [Drop a field](/api-reference/tables/drop-field), [Delete a table](/api-reference/tables/delete-table). ## Export to CSV `GET /v1/api/tables/{id}/export.csv` streams the whole table as a UTF-8 CSV attachment (RFC 4180, with a BOM for Excel and formula-injection defanged). It's keyset-paged server-side, so the download is constant-memory and never capped at a page size. ```bash theme={null} curl -L https://api.hq.zone/v1/api/tables//export.csv \ -H "Authorization: Bearer hq_pat_..." -o leads.csv ``` Requires `tables:read`. See [Export a table as CSV](/api-reference/tables/export-table-csv). ## Provenance and audit Every table and row carries system columns — `created_by`, `updated_by`, timestamps — populated from the [identity chain](/concepts/security), so each row records whether a human or a specific agent (and which conversation) wrote it. Every mutation also emits an event to the always-on audit log. This per-row, tamper-evident provenance is what makes agent-written data accountable — see the [security concept](/concepts/security). Agents reach the same store through the `hq:tables` MCP server (`tables.*` / `rows.*` tools), governed by the same identity and audit. Install it from the [Integrations](/guides/integrations) page and attach it to an agent as you would any MCP server. # HQ API Source: https://docs.hq.zone/index Intelligence on a handle — the HTTP API for HQ's roster of @mentionable specialists. HQ brings **decision intelligence to Slack and Microsoft Teams**. You `@mention` a specialist and it researches, decides, and does real work — each conversation running on its own secure, hardware-isolated machine, with every action bound to who asked and written to a log that can't be edited after the fact. This is the reference for the **HQ HTTP API** (`https://api.hq.zone`): configure agents, drive conversations, stream a turn as it happens, work with documents and memory, and administer a workspace — the same capabilities the product runs on, exposed for your own integrations. Personal access tokens for servers, OAuth 2.1 + PKCE for browser apps. Make your first authenticated call in a couple of minutes. Send a message and read the agent's reply live over SSE. Every endpoint, generated from the live OpenAPI spec. ## How HQ works * **A roster of specialists, not one assistant.** Each agent has its own model, skills, integrations, and tone, reachable by an `@handle`. The API lets you list and configure them and converse with them directly. * **A real machine behind every conversation.** Each conversation runs on its own hardware-isolated sandbox (qOS) that boots in a fraction of a second and resumes where it left off — so a specialist can run code, drive a browser, parse files, and build tools, not just describe them. * **Bound identity and a tamper-evident record.** Every action is tied to the caller and the scope they were granted, checked at each step, and logged immutably. You choose whether your workspace's data lives in the EU or the US. HQ is invite-only while we onboard teams. The API and OAuth client registration are available to workspaces with access.