> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tybritelabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Read a shopper's message

> A shopper's message in, what kind of message it is (`intent`) out, and for a product request the exact constraint
object `POST /v1/agent/search` accepts, plus `unresolved` — the parts of the request it could not map to a
constraint.

**It works without the hosted helpers.** A greeting, a thank-you, a goodbye, a question about an order and a plain
question about the store (delivery with an optional place, returns, opening hours, payment, contact) are read by
fixed rules and cost nothing, whether or not the store has hosted helpers on; a message that asks several of those
is answered for each. Every other message is read by the hosted helper when the store has it on, and by the same
rules over the store's own vocabulary when it does not: a price limit ("under 50", "between 20 and 40"), `in stock`,
a colour that is one of the store's own colour values, and a category named as the store names it become
constraints; any other words stay in `query`; a word the rules cannot turn into a filter is listed in `unresolved`.
`classified_by` says which read the message. The call never answers `403 helpers_unavailable`.

| `intent` | The message | `constraints` | `reply` |
|---|---|---|---|
| `shop` | Asks for products, or changes an earlier product request | The search to run | Absent |
| `question` | Asks about the store: delivery, returns, opening hours, contact, payment | Empty | The store's published answer |
| `small_talk` | A greeting, a thank-you or a goodbye | Empty | A short answer |
| `order_help` | Asks about an existing order | Empty | How to check an order, with the store's contact |
| `unclear` | Cannot be read as any of these | Empty | A request for more detail |

Only a `shop` message carries constraints, so a greeting is never searched for. A `reply` is composed from what the
store has published: its shipping zones and distance tiers, its returns setting and window, its payment methods,
its profile (contact, support hours) and the opening of its published shipping or returns policy. A fact the store
has not published is never stated; the reply says the store has not published it and gives the contact the store
did publish. A greeting, a thank-you or a goodbye on its own is recognised without a model and debits nothing
(`usage.credits_debited: 0`).

`suggestions` holds two or three follow-up prompts drawn from the store's live collections and the categories its
online products are in. Each `text` can be sent back to `interpret` as it is.

A message read by the hosted helper debits the store's AI credits at the true cost of the call; `usage` reports what
was debited (`credits_debited: 0` for a message read by rules). A failed helper call keeps no credits and the
message is read by the rules instead. The call is limited per shopper at the store as described under the agent
fair-use budgets, in addition to the standard limits.

**A publishable key spends the store's credits too, when the helper reads the message.** A publishable key is
public, so anyone holding it can make these calls, and each one the helper reads debits the merchant's balance (and
can trigger the merchant's automatic top-up). The merchant sets a daily limit on that spend, counted over the last
24 hours; once it is reached, or when the helpers are off, paused or out of credits, the message is read by the
rules and nothing is debited.

**With a marketplace operator key** a message read by the helper is paid from the marketplace operator's own AI
credits, never a seller's; when the operator has not switched hosted helpers on or its credits are exhausted, the
rules read the message.

**A follow-up in a saved conversation.** With `conversation_id`, the request is read in the context of that
storefront conversation (`/v1/agent/me/conversations`): its last six turns, the prices of the results the storefront
last showed, and the constraints the previous `interpret` on it returned. "cheaper ones" or "in blue" then refine
the earlier request. The call names the conversation's owner the way the conversation endpoints do (a shopper
credential, or `x-session-id` for a guest), and is refused with the same codes when the store's assistant settings
do not allow it (`403 shopping_assistant_disabled`, `history_disabled`, `guests_not_allowed`) or when the
conversation is not the caller's (`404 not_found`). The constraints returned are kept on the conversation for the
next follow-up; no turn is added. Only a `shop` message updates them, so "cheaper ones" after "thanks" still refines
the last product request. A follow-up keeps the earlier request and applies the change: a new value replaces the old
one, a new attribute is added, "cheaper" sets `price_max` just below the lowest price last shown, and "more expensive"
sets `price_min` just above the highest.



## OpenAPI

````yaml /openapi.yaml post /v1/agent/interpret
openapi: 3.1.0
info:
  title: Galactic Core API
  version: 1.0.0
  description: >
    # Galactic Core — The Programmable Commerce Platform
      
    **By Tybrite Labs**
      
    Galactic Core is the programmable interface layer that transforms GalacticOS
    into a globally 

    accessible Backend-as-a-Service (BaaS) for commerce. Rather than rebuilding
    commerce logic 

    from scratch, Galactic Core re-exposes the operational depth of a
    production-grade retail 

    system through clean, versioned REST APIs and real-time webhooks.
      
    ## Why Galactic Core?
      
    **Commerce Infrastructure, Not Commerce Software**
      
    Galactic Core is not an application or a dashboard—it is **infrastructure**.
    The programmable 

    foundation upon which commerce applications are built. Developers inherit
    years of operational 

    hardening through simple API calls:
      
    - **Inventory management** with stock tracking and reorder logic

    - **Order processing** with payment reconciliation and fulfillment workflows

    - **Customer analytics** with RFM segmentation and purchase history

    - **Double-entry accounting** with automatic journal entries

    - **Multi-provider payments** (Stripe, PayPal, Paystack, M-Pesa)

    - **AI-powered recommendations** using semantic embeddings

    - **Dynamic pricing** with hierarchical discount rules
      
    ## Ship in Days, Not Months
      
    Stop rebuilding the same commerce infrastructure for every project. Galactic
    Core provides 

    production-ready primitives that eliminate months of development work:
      
    ✅ **No data silos** — All channels share the same operational reality  

    ✅ **No duplicated logic** — Business rules are centralized and consistent  

    ✅ **No fragile integrations** — Everything is part of one coherent system  

    ✅ **Complete auditability** — Every state change is tracked and traceable  
      
    ## Platform Capabilities
      
    **Core Commerce**

    - Products, Collections, Categories, Specifications

    - Orders with automatic inventory sync and accounting

    - Customers with RFM analytics and store metrics

    - Multi-provider payment processing with webhook automation
      
    **Advanced Features**

    - AI-powered semantic search and recommendations

    - Dynamic pricing engine with hierarchical rules

    - Cart & wishlist persistence with anonymous session support

    - Customer authentication with automatic record linking

    - Gift cards with full accounting integration

    - Promotions with usage tracking and discount attribution

    - Commerce-aware CMS with shoppable content
      
    **Global by Design**

    - Multi-currency support (135+ currencies via Stripe)

    - Regional payment methods (mobile money for Africa)

    - Multi-store architecture with complete data isolation

    - Edge-optimized delivery (10-50ms response times)
      
    ## Authentication
      
    All API requests require authentication using an API key in the
    `Authorization` header:
      
    ```

    Authorization: Bearer tybrite_sk_live_YOUR_API_KEY

    ```
      
    ### API Key Types
      
    **Secret Keys** (Server-Side Only)

    - Production: `tybrite_sk_live_*`

    - Sandbox: `tybrite_sk_test_*`

    - Full read/write access

    - ⚠️ Never expose in client-side code

    - **Required for:**
      - Write operations other than the shopper's own actions listed under publishable keys
      - Authentication endpoints (register, login, logout, etc.)
      - Payment verification (`POST /v1/payments/verify`)
      - AI recommendations (`POST /v1/recommendations`)
      - Order management
      - Customer management
      
    **Publishable Keys** (Client-Safe)

    - Production: `tybrite_pk_live_*`

    - Sandbox: `tybrite_pk_test_*`

    - Catalogue reads, plus the actions a shopper takes for themselves (cart,
    wishlist, reviews, storefront events, and the Agent API's quotes, cart
    drafts and checkout intents)

    - ✅ Safe for client-side use

    - **Allowed for:**
      - Product browsing
      - Search (both GET and POST semantic search)
      - Category/taxonomy browsing
      - CMS content retrieval
      - Pricing queries
      - Shipping calculations
      - Cart and wishlist
      - Reviews and storefront events
      - Agent API quotes, cart drafts and checkout intents
      
    ### Key Type Enforcement
      
    Attempting to use a publishable key for any other write operation or a
    restricted endpoint returns:

    ```json

    {
      "error": {
        "code": "forbidden",
        "message": "This operation requires a secret key. Publishable keys cover catalogue reads and the actions a shopper takes for themselves.",
        "hint": "Call this from your server with a secret key (tybrite_sk_*)"
      }
    }

    ```

    HTTP Status: 403 Forbidden
      
    ### Obtaining API Keys
      
    Generate API keys from your Tybrite dashboard under the Integrations page
    (Developer section).
      
    ## Money and currency


    **Every amount in this API is in major currency units.** A price of `369.99`
    is three hundred and

    sixty-nine dollars and ninety-nine cents. This holds everywhere without
    exception — catalog prices,

    cart and order totals, payment amounts, refunds, gift-card balances and
    store credit.


    Never send minor units. Payment processors have their own conventions
    (Stripe counts in cents,

    Paystack in kobo) and Galactic Core converts to and from those internally,
    so a `100.00` payment

    reaches Stripe as `10000` without you doing anything. Sending `10000`
    yourself for a `100.00` order

    is rejected with `amount_mismatch` rather than charging a hundred times the
    intended amount.


    **Currency codes are ISO 4217 and case-insensitive.** `usd` and `USD` are
    equivalent on the wire;

    each is normalised to whatever the chosen processor expects.


    ## Environments


    The API uses a single endpoint (`https://api.tybritelabs.com`) with the
    environment determined by your API key prefix:

    - Use `tybrite_*_live_*` keys for production data

    - Use `tybrite_*_test_*` keys for sandbox/testing data


    Sandbox and production data are fully isolated — orders, customers, carts,
    and wishlists created with a test key are only visible to other test keys.
    Payment providers are automatically switched to test mode when using a
    sandbox key, regardless of your store's payment settings.


    Every authenticated response includes a `Tybrite-Environment` header
    confirming which environment resolved.


    ## Technical Features
      
    - **Ultra-Low Latency**: 10-50ms response times via edge caching

    - **Multi-tier caching** for low-latency reads.

    - **Idempotency Protection**: Prevent duplicate orders on retry

    - **Field Filtering**: Request only the fields you need (50-90% bandwidth
    reduction)

    - **Automatic Accounting**: Double-entry journal entries for all
    transactions

    - **Webhook Automation**: Real-time payment status updates and order
    processing


    ## Rate Limiting & Usage Quota


    Two independent controls protect the API. They return **different `429`
    codes** — handle them

    differently:


    | `429` code | What it means | `Retry-After` behavior | Counts toward your
    monthly quota? |

    | --- | --- | --- | --- |

    | `rate_limited` | An **abuse throttle** tripped (too many requests, too
    fast, from one client or key). Responses carry an `X-RateLimit-Scope: abuse`
    header. | Transient — slow down and retry shortly | **No** — throttled
    requests never consume your plan's monthly allowance |

    | `quota_exceeded` | You've reached your plan's **monthly request
    allowance**. | Resolves on the next monthly cycle, or sooner if you upgrade
    | n/a (this *is* the monthly meter) |


    ### Abuse rate limits (`rate_limited`)


    These grow with the store's plan. The per-network limit applies to
    publishable keys and is counted

    separately for each store, so a busy office or mobile network shopping at
    another store never uses

    up this store's allowance:


    | Plan | Per API key, per hour | Per API key, per day | Per shopper network,
    per hour (publishable keys) |

    | --- | --- | --- | --- |

    | Free trial | 2,500 | 10,000 | 2,000 |

    | Starter | 10,000 | 50,000 | 2,000 |

    | Growth | 30,000 | 150,000 | 5,000 |

    | Premium | 150,000 | 750,000 | 25,000 |


    `Retry-After` on a `rate_limited` response is the end of the current hour
    (hourly and per-network

    limits) or UTC day (daily limit).


    ### Monthly usage quota (`quota_exceeded`)


    Your plan includes a monthly request allowance, reset on the 1st of each
    month (UTC):


    - **Starter:** 200,000 requests/month

    - **Growth:** 1,000,000 requests/month

    - **Premium:** 5,000,000 requests/month


    Dedicated infrastructure is arranged through sales and is not a plan; its
    limits are agreed individually.


    (During a free trial the allowance is a flat 40,000 requests/month on every
    plan.) Abuse-throttled requests are **not**

    counted against this allowance, so a traffic spike or scraping attempt can't
    quietly burn through

    your plan.


    ### Endpoint-Specific Limits


    **Payment Operations** (Additional limit on top of the above):

    - `POST /v1/payments/initialize`: 100 requests per hour per shopper address
    within a store (publishable keys). Secret-key calls are limited per key, at
    the plan's key limit.

    - Prevents payment spam and fraud attempts

    - Returns `429 rate_limited` if exceeded


    **Order Operations** (Enforced via idempotency):

    - `POST /v1/orders`: Requires `Idempotency-Key` header

    - `PATCH /v1/orders/:id`: Requires `Idempotency-Key` header

    - Duplicate keys return existing order/state (not counted against rate
    limits)

    - Prevents accidental duplicate orders and duplicate update processing


    **Authentication Operations**:

    - Publishable keys: 10 requests a minute per address and store. Secret keys:
    the per-account limits on each endpoint

    - Prevents brute force attacks

    - Applies to login, register, password reset, etc.


    Rate limit headers are included in responses:

    - `X-RateLimit-Limit`: Maximum requests allowed

    - `X-RateLimit-Remaining`: Requests remaining

    - `X-RateLimit-Reset`: Unix timestamp when the limit resets

    - `X-RateLimit-Scope: abuse`: present only on `rate_limited` responses
    (distinguishes an abuse
      throttle from the monthly quota)

    When an abuse limit is exceeded, the API returns HTTP 429 with error
    details:

    ```json

    {
      "error": {
        "code": "rate_limited",
        "message": "Too many requests for this API key. Please slow down and try again shortly.",
        "remaining": 0,
        "reset": 1739750400
      }
    }

    ```


    ## Special Headers


    ### Idempotency-Key (Required for Order Operations)


    **Endpoints:** `POST /v1/orders`, `PATCH /v1/orders/:id`


    Prevents duplicate order creation and duplicate update processing on network
    retries. If you retry a request with the same 

    idempotency key, the API returns the existing order/state instead of
    re-processing.


    ```

    POST /v1/orders

    Idempotency-Key: order-2026-02-16-abc123
      
    PATCH /v1/orders/922d235e-48c9-4933-abcd-88cb2a264f86

    Idempotency-Key: update-shipping-922d235e-1771524100

    ```


    **Requirements:**

    - Must be unique per operation (use different keys for create vs update)

    - Recommended formats:
      - Order creation: `order-{date}-{unique-id}`
      - Order updates: `update-{operation}-{order_id}-{timestamp}`
    - Stored for 24 hours

    - Returns existing order/state if key matches


    ### x-auth-token (Required for Customer Authentication)


    **Endpoints:**

    - `GET /v1/auth/me` - Get current authenticated customer

    - `POST /v1/auth/password/change` - Change or set the customer's password

    - Every customer-self endpoint (a customer's own orders, addresses, returns,
    wishlist, messages and so on)


    Contains the store's sign-in token: the `access_token` of the shopper's
    session.


    ```

    GET /v1/auth/me

    Authorization: Bearer tybrite_sk_live_YOUR_API_KEY

    x-auth-token: eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...

    ```


    **Flow:**

    1. Customer signs in via `POST /v1/auth/login`, or confirms a new account
    via `POST /v1/auth/register/verify`

    2. Response includes `session.access_token` and `session.refresh_token`

    3. Use `access_token` as `x-auth-token` header value

    4. The token expires after 15 minutes (`expires_at`); `POST
    /v1/auth/refresh` returns a new pair

    5. A token that is expired, revoked, issued by another store or environment,
    or malformed answers
       `401 invalid_token`; the storefront refreshes once and treats the shopper as signed out if that fails

    ### X-Session-Id (Optional for Anonymous Carts)


    **Endpoints:** All cart endpoints (`/v1/cart/*`)


    Enables anonymous cart functionality before customer authentication.
    Generate a unique 

    session ID on the client and include it in cart requests.


    ```

    POST /v1/cart/items

    Authorization: Bearer tybrite_pk_live_YOUR_API_KEY

    X-Session-Id: session-abc123-xyz789

    ```


    **Behavior:**

    - If `X-Session-Id` provided: Cart associated with session (anonymous)

    - If `customer_id` provided: Cart associated with customer account

    - If both provided: `customer_id` takes precedence

    - If neither provided: Returns 400 error


    **Session Management:**

    - Generate UUID or random string on client

    - Store in localStorage/sessionStorage

    - Persist across page reloads

    - When customer logs in, migrate cart using `customer_id`


    ### Tybrite-Environment (Response Header)


    Every authenticated response includes a `Tybrite-Environment` header that
    confirms which environment your API key resolved to. Use this to verify that
    test keys are hitting sandbox data and live keys are hitting production
    data.


    ```

    Tybrite-Environment: sandbox

    ```


    Possible values: `production`, `sandbox`.


    ## Caching & Performance


    ### ETag Support


    All GET endpoints support ETag caching for efficient revalidation:


    ```

    # First request

    GET /v1/products/abc-123

    Response: 200 OK, ETag: "a1b2c3d4"


    # Subsequent request

    GET /v1/products/abc-123

    If-None-Match: "a1b2c3d4"

    Response: 304 Not Modified (no body)

    ```


    ### Cache Headers


    - `ETag`: Resource version identifier

    - `Cache-Control`: Caching directives

    - `X-Cache`: Cache status (HIT, MISS, HIT-304, or STALE when a stored copy
    is served because the live read failed; `Warning: 110` and `Age` then
    accompany it)


    ## Field Filtering


    Request only specific fields to reduce bandwidth:


    ```

    GET /v1/products?fields=id,name,price,stock

    ```


    Supports nested fields with dot notation:


    ```

    GET /v1/products?fields=id,name,attributes.color,attributes.size

    ```


    ## Error Handling


    All errors follow a consistent format:


    ```json

    {
      "error": {
        "code": "error_code",
        "message": "Human-readable error message",
        "details": "Additional context (optional)"
      }
    }

    ```


    ### Common Error Codes


    - `unauthorized` (401): Invalid or missing API key

    - `forbidden` (403): The operation needs a secret key, and the key used is a
    publishable key

    - `insufficient_scope` (403): A GC Connect key was not granted the scope the
    operation needs; the message names the scope

    - `feature_not_available` (403): The store's plan does not include the
    feature the route belongs to. A key made for one extension also receives it
    on every endpoint while the store's plan does not include extension keys;
    the key works again, unchanged, when the plan includes them

    - `subscription_expired` (402): The store's subscription is not active

    - `store_suspended` (403): The store is suspended while a review is open

    - `invalid_token` (401): The `x-auth-token` sign-in token is not valid for
    this store and environment

    - `invalid_confirmation_token` (403): The confirmation token sent with an
    agent checkout intent does not match the intent

    - `endpoint_not_allowed` (403): The key is limited to an approved list of
    endpoints, or is a publishable key limited to part of the catalogue, and
    this request is not on that list

    - `out_of_scope` (403): The key is a publishable key limited to the products
    that carry one tag, and the request names a product, variant, promotion or
    review outside that slice. Nothing is written or reserved

    - `not_found` (404): Resource not found

    - `invalid_request` (400): Malformed request or missing fields

    - `method_not_allowed` (405): The route does not accept the HTTP method used

    - `rate_limited` (429): Abuse throttle tripped — too many requests too fast
    (carries `X-RateLimit-Scope: abuse`; not counted against your monthly quota)

    - `quota_exceeded` (429): Monthly plan request allowance reached

    - `server_error` (500): Internal server error

    - `config_error` (500): A setting the operation depends on is missing for
    this store, for example the store's request-signing secret

    - `provider_error` (502): A payment provider refused or failed a call made
    on the store's behalf; the message is a fixed sentence and the provider's
    own text is never returned

    - `provider_timeout` (504): A payment provider did not respond in time

    - `service_unavailable` (503): Service temporarily unavailable


    ## Idempotency


    Order creation supports idempotency to prevent duplicates on retry:


    ```

    POST /v1/orders

    Idempotency-Key: order-2026-02-03-abc123

    ```


    Retrying with the same key returns the existing order instead of creating a
    duplicate.


    ## Pagination


    List endpoints are **cursor-based**. Pass a `limit` (page size), and follow
    the

    `pagination.next_cursor` from each response to fetch the next page — there
    is no

    numeric `offset` or page number.


    ```

    GET /v1/products?limit=50

    GET
    /v1/products?limit=50&cursor=eyJwcm9kdWN0X2lkIjoiZDhjZWEyNzctOWJiNi00OTQyIn0=

    ```


    Each response carries a `pagination` object:


    ```json

    {
      "products": [...],
      "pagination": {
        "limit": 50,
        "has_more": true,
        "next_cursor": "eyJwcm9kdWN0X2lkIjoiZDhjZWEyNzctOWJiNi00OTQyIn0="
      }
    }

    ```


    When `has_more` is `false`, `next_cursor` is `null` and you've reached the
    last page.

    Cursors are opaque — pass them back verbatim; don't construct or parse them.
  contact:
    name: Galactic Core API Support - Tybrite Labs
    email: support@tybritelabs.com
    url: https://tybritelabs.com
  license:
    name: Proprietary
    url: https://tybritelabs.com/terms-of-service
servers:
  - url: https://api.tybritelabs.com
    description: Production API
security:
  - BearerAuth: []
tags:
  - name: System
    description: API information and health checks
  - name: Store
    description: >
      The store's public business profile and its published legal documents.


      The profile carries support contact details, addresses, legal identity,
      social profiles and the

      custom entries a merchant has made public. The policies are the documents
      a storefront renders

      at `/policies/{slug}` and links from its footer: privacy, terms, returns,
      shipping and cookies,

      plus an optional legal notice, an accessibility statement, and documents
      the merchant adds.

      Each document is versioned, and every published version stays readable.


      All three endpoints accept a publishable key. Drafts and private entries
      are never returned.
  - name: Authentication
    description: >
      Shopper accounts and sessions for a store (or, on a marketplace key, for
      the marketplace).


      **Secret key required for writes.** Every `POST` endpoint here requires a
      secret key (tybrite_sk_*);

      publishable keys answer 403 Forbidden. `GET /v1/auth/me` accepts either
      key.


      Sign-up is two steps: `POST /v1/auth/register` emails a code and link and
      returns no session, and

      `POST /v1/auth/register/verify` creates the account and returns the first
      session. A shopper then signs

      in with a password (`POST /v1/auth/login`) or an emailed code (`POST
      /v1/auth/magic-link`, then

      `POST /v1/auth/verify-otp`), resets a forgotten password with `POST
      /v1/auth/password/forgot` and

      `POST /v1/auth/password/reset`, and changes it with `POST
      /v1/auth/password/change`.


      A session is `{ access_token, refresh_token, expires_in, expires_at,
      token_type: "shopper" }`. The

      access token is the store's sign-in token: it lasts 15 minutes, is
      accepted only by the store and

      environment that issued it, and is sent as the `x-auth-token` header on
      customer-self endpoints. The

      refresh token lasts 30 days from its last use and works once; `POST
      /v1/auth/refresh` returns a

      replacement pair.


      **Special Headers:**

      - `x-auth-token`: required for `GET /v1/auth/me` and `POST
      /v1/auth/password/change`

      - a token that is not valid for the store answers `401 invalid_token`


      **Rate Limiting:**

      - With a publishable key: 10 requests per minute per IP address on these
      endpoints

      - Per-account attempt limits on every endpoint that takes an email address
      or a code
  - name: Products
    description: Product catalog management
  - name: Orders
    description: >
      Order lifecycle management with automatic inventory sync and accounting.
        
      **Special Headers:**

      - `Idempotency-Key`: **REQUIRED** for `POST /v1/orders` and `PATCH
      /v1/orders/:id`
        - Prevents duplicate order creation and duplicate update processing on network retries
        - Recommended formats:
          - Order creation: `order-{date}-{unique-id}`
          - Order updates: `update-{operation}-{order_id}-{timestamp}`
        - Stored for 24 hours
        - Retrying with same key returns existing order/state (not counted against rate limit)
      - `X-Timestamp`: **REQUIRED** for `POST /v1/orders` and `PATCH
      /v1/orders/:id`
        - Unix timestamp in seconds (current time)
        - Must be within 5 minutes of server time
        - Used to prevent replay attacks
      - `X-Signature`: **REQUIRED** for `POST /v1/orders` and `PATCH
      /v1/orders/:id`
        - HMAC-SHA256 signature of payload (timestamp + "." + request_body), base64-encoded
        - Sign using your HMAC secret from the Integrations page (Developer section)
        - Requests with invalid/missing signatures return 401 Unauthorized
        
      **Automatic Processing:**

      - Inventory automatically decremented when payment_status changes to
      'paid'

      - Double-entry accounting journal entries created automatically

      - Payment status tracked and updated via webhooks

      - Gift card redemptions and promotion usage tracked with idempotency
      protection
  - name: Customers
    description: Customer profile management
  - name: Cart & Wishlist
    description: |
      Shopping cart and wishlist operations with anonymous session support.
        
      **Special Headers:**
      - `X-Session-Id`: Optional header for anonymous cart functionality
      - Generate a unique session ID on the client (UUID or random string)
      - Store in localStorage/sessionStorage for persistence
      - When customer logs in, migrate cart by providing `customer_id` instead
        
      **Cart Association:**
      - If `X-Session-Id` provided: Cart associated with session (anonymous)
      - If `customer_id` provided: Cart associated with customer account
      - If both provided: `customer_id` takes precedence
      - If neither provided: Returns 400 error
        
      **Use Cases:**
      - Anonymous browsing: Use `X-Session-Id` before customer authentication
      - Logged-in customers: Use `customer_id` parameter
      - Cart migration: Switch from session to customer_id after login
  - name: Agent
    description: >
      Tools for an assistant shopping a store on a shopper's behalf: search by
      constraints, product

      dossiers, comparison, a landed-price quote, cart drafts, the shopper's own
      context behind their

      consent, and checkout intents that the shopper confirms before any order
      is placed.


      Every response carries `evidence` naming the operation each figure was
      read from, so an agent can

      cite its source rather than restate a number. Most tools are deterministic
      and cost what any

      storefront read costs. Two, `interpret` and `draftCartFromIntent`, run a
      model on the store's

      behalf and debit its AI credits; the rest never do.


      **Key type behavior:** a publishable key is enough for every tool except
      `GET /v1/agent/usage`,

      which needs a secret key. Tools that act on a shopper's own data also need
      exactly one shopper

      credential header (`x-auth-token`, `x-external-auth` or `x-idp-token`).


      Payment is never taken by an agent: a checkout intent becomes an order
      only when the shopper

      confirms it, and the payment itself is started with `POST
      /v1/payments/initialize`.


      **On a marketplace:** a marketplace operator key shops every seller of its
      own marketplace and no

      other. Search, compare and alternatives span the sellers and name each
      one; a quote is the

      marketplace checkout's own pricing, broken down per seller; and a
      confirmed checkout intent places

      one marketplace order with a single payment, after which each seller
      receives their own order. The

      The hosted helpers (`interpret`, `draftCartFromIntent`) are paid from the
      marketplace operator's own

      AI credits, never a seller's, and a helper's draft holds only that
      marketplace's items. The

      tools that act on one store's data (product details, fit, adding a draft
      to a live cart, cart

      insights, the shopper's own context, store policies, usage) need that
      store's key and answer `403` to

      a marketplace key.
  - name: Search
    description: >
      Semantic search with AI embeddings and simple text search.
        
      **Key Type Support:**

      - `GET /v1/search` (simple text search): Both secret and publishable keys
      allowed

      - `POST /v1/search` (semantic search): Both secret and publishable keys
      allowed
        
      Note: Despite using POST method, semantic search is a read-only operation
      and works

      with publishable keys. The POST method is used to support complex request
      bodies.
  - name: Recommendations
    description: >
      AI-powered product recommendations using semantic embeddings and
      collaborative filtering.
        
      **⚠️ SECRET KEY REQUIRED**: Recommendation generation requires a secret
      key (tybrite_sk_*).

      Publishable keys will return 403 Forbidden.
        
      This restriction protects the computational resources and AI model access
      used for

      generating personalized recommendations.
  - name: Discovery
    description: >
      Windowed storefront discovery lists derived from live shopper signals —
      most-viewed,

      most-added-to-cart, and best-converting products over a time window (1h /
      1d / 7d / 30d).

      Use them to power "Popular now" shelves, "Trending in carts" sections, and
      PDP "hot" badges.


      Publishable-key accessible (safe in a browser/app) and available on every
      plan. Distinct from

      Recommendations: these are simple, non-personalized signal rankings, not
      the ML engine.
  - name: Events
    description: >
      Storefront interaction events (product views, add-to-cart,
      add-to-wishlist). These power the

      `next` recommendation type — the products a shopper is most likely to view
      or add next based

      on their current session. Publishable keys are accepted so events can be
      sent from the browser.
  - name: Tax
    description: >
      Tax estimation for checkout. Preview the tax for a shipping destination
      and cart before placing

      an order, so the storefront can show and charge the final tax-inclusive
      total. Publishable keys

      are accepted so the estimate can be fetched from the browser during
      checkout.
  - name: Analytics
    description: >
      First-party storefront analytics capture. Fire a lightweight page-view /
      session-start event

      from the storefront on each route change; device, browser, and approximate
      location are derived

      automatically from the request. These events power the merchant's Store
      Analytics dashboard

      (traffic, audience, conversion funnel, and revenue-by-source). Publishable
      keys are accepted so

      events can be sent directly from the browser.
  - name: Taxonomy
    description: Categories and subcategories
  - name: CMS
    description: Content management (posts, lookbooks)
  - name: Payments
    description: >
      Multi-provider payment processing (Stripe, PayPal, Paystack, M-Pesa).
        
      **Special Headers:**

      - `Idempotency-Key`: **REQUIRED** for `POST /v1/payments/initialize`
        - Unique key to prevent duplicate payment initialization (e.g., payment-{timestamp}-{random})
        - If you retry with the same key, the original payment initialization is returned
        - Prevents duplicate charges on network retries
      - `X-Timestamp`: **REQUIRED** for `POST /v1/payments/initialize`
        - Unix timestamp in seconds (current time)
        - Must be within 5 minutes of server time
        - Used to prevent replay attacks
      - `X-Signature`: **REQUIRED** for `POST /v1/payments/initialize`
        - HMAC-SHA256 signature of payload (timestamp + "." + request_body), base64-encoded
        - Sign using your HMAC secret from the Integrations page (Developer section)
        - Requests with invalid/missing signatures return 401 Unauthorized
        
      **Key Type Requirements:**

      - `GET /v1/payments/methods`: Both secret and publishable keys allowed

      - `POST /v1/payments/initialize`: Secret key required

      - `POST /v1/payments/verify`: **SECRET KEY REQUIRED** (read operation but
      sensitive)
        
      Payment verification requires a secret key because it accesses sensitive
      payment status

      information that should not be exposed to client-side code.
        
      **Rate Limiting:**

      - Payment initialization has an additional rate limit of 100 requests/hour
      per API key

      - This is on top of the standard abuse limits (publishable: 1,000/hour per
      IP + 10,000/hour & 50,000/day per key; secret: 10,000/hour & 100,000/day
      per key)

      - Exceeding any of these returns `429 rate_limited` (carries
      `X-RateLimit-Scope: abuse`; not counted against your monthly quota)

      - Prevents payment spam and fraud attempts
  - name: Shipping
    description: Shipping zones and delivery cost calculation
  - name: Pricing
    description: Dynamic pricing engine
  - name: Promotions
    description: Marketing promotions and discounts
  - name: Campaigns
    description: Campaigns — a discount with a budget behind it
  - name: Gift Cards
    description: Gift card management
  - name: Messaging
    description: Real-time customer support messaging
  - name: GC Connect
    description: >
      Hosted authorization flow for connecting third-party tools to a merchant's
      store.


      **Connect your GC Store** lets developers build integrations where
      merchants

      authorize access with a single click — no API key copying required. The
      result

      is a permanent key pair scoped to the merchant's store and the permissions
      they

      granted.


      **Flow overview:**

      1. Redirect the merchant to the consent page with your `client_id`,
      `redirect_uri`,
         `scope`, and `state`.
      2. The merchant logs in (if not already) and approves the connection.

      3. Galactic Core redirects back to your `redirect_uri` with a short-lived
      `code`.

      4. Your **server** calls `POST /v1/connect/token` to exchange the code for
      `sk` + `pk`.

      5. Store the `sk` securely server-side. Use it for all subsequent API
      calls on behalf
         of the merchant.

      **Keys are permanent** — they remain active until the merchant disconnects
      your

      application from their Settings panel, or you call `POST
      /v1/connect/revoke`.


      **To integrate**, your application must be approved by Galactic Core.
      Apply via the

      [Developer Portal](https://gc.tybritelabs.com/developers).
  - name: Storefront Studio
    description: >
      What an application that builds a merchant's storefront reports back to
      the store, on the secret

      key of its own connection (see GC Connect). Each capability has its own
      scope the merchant sees on

      the consent screen:


      - `storefront_site:write` — the storefront's public address and page
      templates.

      - `ab_attribution:write` — the app's own A/B experiments and the paid
      orders and sales for each variant.

      - `support_tickets:write` — support requests the app opens for the
      merchant, and where each stands.

      - `storefront_template:write` — templates the app offers the merchant, and
      the merchant's answer.


      The key fixes the store, the environment and the app, so an app reaches
      only its own reports,

      experiments, requests and templates. A merchant who disconnects the app
      ends its access at once.
  - name: Reviews
    description: >
      Product reviews and ratings submitted by customers, moderated by
      merchants.


      **Key type behavior:**

      - Publishable keys (`tybrite_pk_*`) — list and get approved reviews,
      submit reviews
        (requires an additional customer session token), and mark reviews helpful.
      - Secret keys (`tybrite_sk_*`) — all of the above, plus view
      pending/rejected reviews,
        approve or reject submissions, and delete any review.

      **Review lifecycle:**

      1. A logged-in customer submits a review (`POST /v1/reviews`). It starts
      as `pending`.

      2. The merchant reviews pending submissions in their dashboard and calls
         `PATCH /v1/reviews/{id}` to approve or reject.
      3. Once approved, the review appears in public listing results.


      **Verified purchases:** Supply the `order_id` when submitting. If the
      order belongs to

      the authenticated customer, the review is automatically marked
      `verified_purchase: true`.


      **Duplicate prevention:** A customer may only have one non-rejected review
      per product.

      A second submission returns `409 Conflict`.


      **Special headers:**

      - `x-auth-token`: Customer session JWT — required for `POST /v1/reviews`
      (submit)
        and for `DELETE /v1/reviews/{id}` when using a publishable key to delete own review.
        Obtained from `POST /v1/auth/login` or `POST /v1/auth/verify-otp`.
  - name: Returns
    description: >
      Return requests a shopper lodges against their own online orders.


      **Key type behavior:**

      - The reason-code list (`GET /v1/returns/reasons`) needs only an API key —
      no
        customer session — so you can build the reason picker before sign-in.
      - Listing, getting, and creating returns require an API key **and** a
      customer
        session: either `x-auth-token` (a GC-native session token) or
        `x-external-auth` (a bring-your-own-auth assertion).

      A customer can only create, list, and track their OWN returns. Approving,

      processing refunds or store credit, restocking, and rejecting items are

      store-management tasks handled in the merchant admin, not through this
      API.


      **Special headers:**

      - `x-auth-token` **or** `x-external-auth`: identifies the signed-in
      customer on
        `GET /v1/returns`, `GET /v1/returns/{id}`, and `POST /v1/returns`.
  - name: Disputes
    description: >
      Disputes a shopper raises on their own marketplace orders when something
      goes

      wrong — the item never arrived, arrived damaged, or was not as described.


      Disputes are a marketplace capability: the operator sits between the
      shopper and

      the merchant, reviews an open dispute, and applies a resolution (a refund,
      store

      credit, or another remedy). This API is the shopper's side of that flow —
      open a

      dispute, list and track your own, add a message, and cancel one you
      opened.

      Reviewing and resolving disputes are operator and merchant tasks handled
      in the

      admin dashboards, not through this API.


      **Key type behavior:**

      - The reason-code list (`GET /v1/disputes/reasons`) needs only an API key
      — no
        customer session — so you can build the reason picker before sign-in.
      - Listing, getting, opening, messaging, and cancelling disputes require an
      API key
        **and** a customer session: either `x-auth-token` (a GC-native session token) or
        `x-external-auth` (a bring-your-own-auth assertion).

      A shopper can only open, list, track, message, and cancel their OWN
      disputes.


      **Special headers:**

      - `x-auth-token` **or** `x-external-auth`: identifies the signed-in
      customer on the
        per-shopper dispute endpoints.
  - name: Marketplace
    description: >
      Endpoints for building a multi-merchant marketplace storefront.


      These endpoints let a marketplace storefront read the marketplace's
      identity and

      branding (and a single merchant's store information within it), resolve
      commission,

      check out a cart spanning multiple merchants in a single payment, and read
      a

      shopper's unified profile across every merchant they have shopped with.


      To narrow aggregated marketplace catalog results to a single merchant's
      "shop page",

      pass `?store_id=<merchant>` to the products, categories, subcategories,
      and search

      endpoints (operator key only).


      **Key types:**

      - Marketplace information, unified checkout, and the unified customer
      profile use
        the marketplace operator key. Commission resolution accepts the marketplace operator
        key or a merchant secret key.

      Merchant payment onboarding and operator payout runs are merchant/operator
      back-office

      tasks handled in the admin interface, not through this API.
  - name: Ingestion
    description: >
      Sync an external product catalog INTO Galactic Core.


      **⚠️ SECRET KEY + SIGNATURE REQUIRED**: `POST /v1/ingest/products`
      requires a secret

      key (`tybrite_sk_*`) **and** a request signature. Publishable keys return
      403; a missing

      or invalid signature returns 401. This is the one write endpoint where
      both are mandatory.


      Use ingestion when a merchant's own system (an ERP, a PIM, another
      storefront, a

      spreadsheet export) is the source of truth for products and you want to
      push or sync

      that catalog into Galactic Core — rather than entering products by hand.


      **What it does:**

      - Accepts a batch of products as **JSON, XML, or CSV** (set the
      `Content-Type`, or
        `?format=`). One request can carry many products.
      - **Upserts by SKU**: a product whose SKU already exists is updated; a new
      SKU is created.
        Use `?strategy=create_only` to skip existing SKUs instead of updating them.
      - **Groups variants**: rows that share a `product_group` become variants
      of a single
        product (e.g. a shirt in S/M/L). Rows without a group are single-variant products.
      - **Reports per row**: the response carries a `summary` (created / updated
      / skipped /
        failed counts) and an `errors` array naming the row, SKU, field, and reason for every
        rejected row — so a partly-valid batch still imports the good rows and tells you exactly
        what to fix.

      **Signing:** sign each request the same way as orders/payments —
      `X-Timestamp` (unix

      seconds) + `X-Signature` (HMAC-SHA256 of `timestamp + "." + raw_body`,
      base64), within a

      5-minute window. An `Idempotency-Key` is required so a retried batch is
      processed once.


      **Test before you integrate (no key needed):**

      - `GET /v1/ingest/sample?format=json|xml|csv` returns a valid sample feed
      to copy.

      - `POST /v1/ingest/test` validates a feed and returns the same
      `summary`/`errors` you'd
        get from a real import — **without writing anything**. Both are rate-limited to 60/hour
        per IP.

      **Scheduled sync:** merchants can also register a feed URL in their
      dashboard for Galactic

      Core to pull and sync on a schedule; a `feed.sync.completed` webhook fires
      after each run.
  - name: Feeds
    description: >
      A store's public, read-only feeds, served **without an API key** so that
      search engines,

      marketplaces, other commerce systems and AI assistants can read them
      directly.


      - `products.json` / `products.xml` — the full catalogue, for catalogue
      sync. Published when
        the merchant turns on **Publish my catalog**; an optional feed token can be required.
      - `llms.txt` — a Markdown summary of the store for AI assistants: who it
      is, what it sells,
        its policies and where to go next.
      - `llms-full.txt` — the complete catalogue in the same Markdown format.


      `{store}` is the store's code (as in `GAL001`) or its id. Every feed
      carries only what the

      storefront already shows — never cost, margin or supplier data — and only
      production data.

      Feeds are cached at the edge and refresh when the catalogue changes.
  - name: Webhooks
    description: >
      Outbound webhook management for merchant integrators.


      **⚠️ SECRET KEY REQUIRED**: All webhook endpoints require the store's own
      secret key (`tybrite_sk_*`).

      Publishable keys return `403 forbidden`. A key held by a connected app (GC
      Connect) returns

      `403 insufficient_scope` on every webhook endpoint, whatever it was
      granted: the event log carries

      every subscriber's customer and order payloads. A connected app that
      receives events is given its

      endpoint when the merchant approves the connection.


      Webhooks allow your systems to receive real-time notifications when events
      occur in your

      store — eliminating the need to poll the API.


      **Delivery contract:**

      - **At-least-once** delivery — endpoints must be idempotent. Use
      `event.id` for dedup.

      - **HMAC-signed** — every request carries `X-Tybrite-Signature:
      t=<timestamp>,v1=<hmac_sha256>`.
        Verify with the `signing_secret` returned at endpoint creation.
      - **Payload size** — capped at 256 KB per delivery.

      - **Ordering** — best-effort, not guaranteed. Use event timestamps for
      sequencing.


      **Signature verification:**

      ```typescript

      const [tPart, v1Part] = req.headers['x-tybrite-signature'].split(',');

      const timestamp = tPart.replace('t=', '');

      const receivedSig = v1Part.replace('v1=', '');

      const payload = `${timestamp}.${rawBody}`;

      const expected = hmacSha256Hex(signingSecret, payload);

      if (receivedSig !== expected) throw new Error('Invalid signature');

      // Replay check: reject if |now - timestamp| > 300 seconds

      ```


      **Rate Limiting:** 500 requests/hour per secret key.
  - name: Sandbox
    description: >
      Developer tooling for the sandbox (test) environment — make your test runs
      fast and repeatable.


      **⚠️ SECRET TEST KEY REQUIRED**: every Sandbox endpoint requires the
      store's own `tybrite_sk_test_*` key

      holding the `write` scope, and only ever touches your sandbox data;
      publishable keys and live keys are

      rejected (`403 forbidden`), and a key held by a connected app (GC Connect)
      or one minted without `write`

      is rejected with `403 insufficient_scope`. Your live data and store
      configuration are never affected.


      - **Reset** (`POST /v1/sandbox/reset`, or `DELETE /v1/sandbox/data`) —
      wipe all your sandbox
        test data instantly instead of waiting for the automatic 30-day cleanup.
      - **Fast-forward time** (`POST /v1/sandbox/time`) — advance your sandbox
      by N days so abandoned
        carts, stock-reservation windows and analytics roll forward without waiting. (Subscription
        trials/renewals and promotion/gift-card expiry are not time-shifted — see the endpoint.)
      - **Replay a webhook** (`POST /v1/sandbox/webhooks/replay`) — re-send a
      recorded sandbox webhook
        event to your endpoints without recreating the underlying record.
  - name: B2B
    description: >
      GC B2B — the buyer-side wholesale flow: request a quote (RFQ), receive and
      accept

      a quote, track the resulting purchase order, and pay invoices on terms.


      Every endpoint acts on the buyer's own records and requires the buyer's
      session

      (`x-auth-token` or `x-external-auth`) alongside the API key. Supplier-side
      actions —

      pricing quotes, confirming purchase orders, fulfilling, and credit
      decisions — are

      handled in the supplier's admin, never through this API. Available only on

      deployments with B2B enabled.
  - name: Agency Signup
    description: Keyless reads and the signup flow an agency calls from its own pages
externalDocs:
  description: Galactic Core Documentation
  url: https://docs.tybritelabs.com/galactic-core
paths:
  /v1/agent/interpret:
    post:
      tags:
        - Agent
      summary: Read a shopper's message
      description: >-
        A shopper's message in, what kind of message it is (`intent`) out, and
        for a product request the exact constraint

        object `POST /v1/agent/search` accepts, plus `unresolved` — the parts of
        the request it could not map to a

        constraint.


        **It works without the hosted helpers.** A greeting, a thank-you, a
        goodbye, a question about an order and a plain

        question about the store (delivery with an optional place, returns,
        opening hours, payment, contact) are read by

        fixed rules and cost nothing, whether or not the store has hosted
        helpers on; a message that asks several of those

        is answered for each. Every other message is read by the hosted helper
        when the store has it on, and by the same

        rules over the store's own vocabulary when it does not: a price limit
        ("under 50", "between 20 and 40"), `in stock`,

        a colour that is one of the store's own colour values, and a category
        named as the store names it become

        constraints; any other words stay in `query`; a word the rules cannot
        turn into a filter is listed in `unresolved`.

        `classified_by` says which read the message. The call never answers `403
        helpers_unavailable`.


        | `intent` | The message | `constraints` | `reply` |

        |---|---|---|---|

        | `shop` | Asks for products, or changes an earlier product request |
        The search to run | Absent |

        | `question` | Asks about the store: delivery, returns, opening hours,
        contact, payment | Empty | The store's published answer |

        | `small_talk` | A greeting, a thank-you or a goodbye | Empty | A short
        answer |

        | `order_help` | Asks about an existing order | Empty | How to check an
        order, with the store's contact |

        | `unclear` | Cannot be read as any of these | Empty | A request for
        more detail |


        Only a `shop` message carries constraints, so a greeting is never
        searched for. A `reply` is composed from what the

        store has published: its shipping zones and distance tiers, its returns
        setting and window, its payment methods,

        its profile (contact, support hours) and the opening of its published
        shipping or returns policy. A fact the store

        has not published is never stated; the reply says the store has not
        published it and gives the contact the store

        did publish. A greeting, a thank-you or a goodbye on its own is
        recognised without a model and debits nothing

        (`usage.credits_debited: 0`).


        `suggestions` holds two or three follow-up prompts drawn from the
        store's live collections and the categories its

        online products are in. Each `text` can be sent back to `interpret` as
        it is.


        A message read by the hosted helper debits the store's AI credits at the
        true cost of the call; `usage` reports what

        was debited (`credits_debited: 0` for a message read by rules). A failed
        helper call keeps no credits and the

        message is read by the rules instead. The call is limited per shopper at
        the store as described under the agent

        fair-use budgets, in addition to the standard limits.


        **A publishable key spends the store's credits too, when the helper
        reads the message.** A publishable key is

        public, so anyone holding it can make these calls, and each one the
        helper reads debits the merchant's balance (and

        can trigger the merchant's automatic top-up). The merchant sets a daily
        limit on that spend, counted over the last

        24 hours; once it is reached, or when the helpers are off, paused or out
        of credits, the message is read by the

        rules and nothing is debited.


        **With a marketplace operator key** a message read by the helper is paid
        from the marketplace operator's own AI

        credits, never a seller's; when the operator has not switched hosted
        helpers on or its credits are exhausted, the

        rules read the message.


        **A follow-up in a saved conversation.** With `conversation_id`, the
        request is read in the context of that

        storefront conversation (`/v1/agent/me/conversations`): its last six
        turns, the prices of the results the storefront

        last showed, and the constraints the previous `interpret` on it
        returned. "cheaper ones" or "in blue" then refine

        the earlier request. The call names the conversation's owner the way the
        conversation endpoints do (a shopper

        credential, or `x-session-id` for a guest), and is refused with the same
        codes when the store's assistant settings

        do not allow it (`403 shopping_assistant_disabled`, `history_disabled`,
        `guests_not_allowed`) or when the

        conversation is not the caller's (`404 not_found`). The constraints
        returned are kept on the conversation for the

        next follow-up; no turn is added. Only a `shop` message updates them, so
        "cheaper ones" after "thanks" still refines

        the last product request. A follow-up keeps the earlier request and
        applies the change: a new value replaces the old

        one, a new attribute is added, "cheaper" sets `price_max` just below the
        lowest price last shown, and "more expensive"

        sets `price_min` just above the highest.
      operationId: interpret
      parameters:
        - name: x-auth-token
          in: header
          required: false
          schema:
            type: string
          description: >-
            With `conversation_id`, the signed-in shopper who owns it. Customer
            session token from `POST /v1/auth/login` or `POST
            /v1/auth/verify-otp`. At most one of `x-auth-token`,
            `x-external-auth`, or `x-idp-token`.
        - name: x-external-auth
          in: header
          required: false
          schema:
            type: string
          description: >-
            With `conversation_id`, a bring-your-own-auth assertion identifying
            the shopper who owns it. At most one of `x-auth-token`,
            `x-external-auth`, or `x-idp-token`.
        - name: x-idp-token
          in: header
          required: false
          schema:
            type: string
          description: >-
            With `conversation_id`, a raw token from the store's own identity
            provider for the shopper who owns it. At most one of `x-auth-token`,
            `x-external-auth`, or `x-idp-token`.
        - name: x-session-id
          in: header
          required: false
          schema:
            type: string
            pattern: ^[A-Za-z0-9._:-]{16,128}$
          description: >-
            With `conversation_id` and no shopper credential, the guest session
            that owns it.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
              properties:
                query:
                  type: string
                  maxLength: 500
                conversation_id:
                  type: string
                  format: uuid
                  description: >-
                    A saved storefront conversation whose context the request is
                    read in. Needs the conversation's owner (a shopper
                    credential or `x-session-id`).
            example:
              query: a black hoodie under 60 for my brother
      responses:
        '200':
          description: The constraints
          headers:
            Tybrite-Environment:
              $ref: '#/components/headers/TybriteEnvironment'
          content:
            application/json:
              schema:
                type: object
                required:
                  - data
                  - evidence
                  - computed_at
                  - environment
                properties:
                  data:
                    type: object
                    properties:
                      intent:
                        type: string
                        description: What kind of message it is (see the table above).
                        enum:
                          - shop
                          - question
                          - small_talk
                          - order_help
                          - unclear
                      reply:
                        type: string
                        description: >-
                          Present when `intent` is not `shop`. Composed only
                          from what the store has published.
                      suggestions:
                        type: array
                        description: >-
                          Two or three follow-up prompts from the store's live
                          collections and categories; empty when the store has
                          neither.
                        items:
                          type: object
                          required:
                            - text
                            - kind
                          properties:
                            text:
                              type: string
                              description: >-
                                A prompt the shopper can send back to
                                `interpret`, e.g. `Show me Summer Essentials`.
                            kind:
                              type: string
                              enum:
                                - collection
                                - category
                            collection_id:
                              type: string
                              format: uuid
                              description: With `kind` `collection`.
                            category:
                              type: string
                              description: With `kind` `category`.
                      constraints:
                        type: object
                        description: The search for a `shop` message; empty otherwise.
                        properties:
                          query:
                            type: string
                            maxLength: 300
                            description: >-
                              Free text. Matched by meaning where the store has
                              semantic search, and against name, brand,
                              category, SKU and tags.
                          price_min:
                            type: number
                            minimum: 0
                          price_max:
                            type: number
                            minimum: 0
                          category:
                            type: string
                            description: A category or subcategory name (case-insensitive).
                          attributes:
                            type: object
                            additionalProperties:
                              type: string
                            description: >-
                              Attribute name to wanted value, e.g. `{"color":
                              "black"}`.
                          in_stock_only:
                            type: boolean
                      unresolved:
                        type: array
                        items:
                          type: string
                      classified_by:
                        type: string
                        enum:
                          - rules
                          - helper
                        description: >-
                          `rules`: read by fixed rules over the store's own
                          vocabulary, at no cost. `helper`: read by the hosted
                          helper.
                      conversation_id:
                        type: string
                        format: uuid
                        description: >-
                          The conversation the request was read in, when
                          `conversation_id` was sent.
                      conversation_title:
                        type: string
                        description: >-
                          Present when this call named the conversation, which
                          had no title, with a short noun phrase from the first
                          shopping request, such as `Summer Essentials`, `Blue
                          lamps` or `Summer picks`. A title already set is never
                          changed.
                  evidence:
                    type: array
                    description: Where each figure in `data` was read from.
                    items:
                      type: object
                      properties:
                        source:
                          type: string
                        operation:
                          type: string
                        id:
                          type: string
                        field:
                          type: string
                        note:
                          type: string
                  computed_at:
                    type: string
                    format: date-time
                  currency:
                    type:
                      - string
                      - 'null'
                    description: ISO 4217 code every amount in `data` is expressed in.
                  environment:
                    type: string
                    enum:
                      - production
                      - sandbox
                  usage:
                    type: object
                    description: >-
                      What the call cost. Present on the hosted-helper tools
                      only.
                    properties:
                      credits_debited:
                        type: number
                        description: AI credits debited, in US dollars.
                      model_class:
                        type:
                          - string
                          - 'null'
                        enum:
                          - fast
                          - null
              examples:
                shop:
                  summary: A product request
                  value:
                    data:
                      intent: shop
                      suggestions:
                        - text: Show me Out and About
                          kind: collection
                          collection_id: 323d9dbc-1c9d-42a2-a069-ae4031750e3b
                        - text: Browse Men's Clothing
                          kind: category
                          category: Men's Clothing
                      constraints:
                        query: hoodie
                        price_max: 60
                        attributes:
                          color: black
                        in_stock_only: true
                      unresolved:
                        - for my brother
                    evidence:
                      - source: hosted_helper
                        operation: interpret
                        field: constraints, intent
                    computed_at: '2026-09-28T21:49:12.108Z'
                    currency: null
                    environment: sandbox
                    usage:
                      credits_debited: 0.000412
                      model_class: fast
                question:
                  summary: A question about delivery
                  value:
                    data:
                      intent: question
                      reply: >-
                        Delivery options: Local (within 10 km), $5.99 (free over
                        $75.00); Metro (10–50 km), $9.99 (free over $150.00).
                      suggestions:
                        - text: Show me Out and About
                          kind: collection
                          collection_id: 323d9dbc-1c9d-42a2-a069-ae4031750e3b
                        - text: Browse Men's Clothing
                          kind: category
                          category: Men's Clothing
                      constraints: {}
                      unresolved: []
                    evidence:
                      - source: hosted_helper
                        operation: interpret
                        field: constraints, intent
                      - source: store-info
                        operation: GET /v1/store/info
                        field: name
                      - source: shipping
                        operation: GET /v1/shipping/zones
                        field: delivery_zones, pricing_tiers
                    computed_at: '2026-11-08T10:12:40.000Z'
                    currency: null
                    environment: production
                    usage:
                      credits_debited: 0.000398
                      model_class: fast
                greeting:
                  summary: A greeting, recognised without a model
                  value:
                    data:
                      intent: small_talk
                      reply: >-
                        Hi! I can help you find something at Galactic Test
                        Store. What are you looking for?
                      suggestions:
                        - text: Show me Out and About
                          kind: collection
                          collection_id: 323d9dbc-1c9d-42a2-a069-ae4031750e3b
                        - text: Browse Men's Clothing
                          kind: category
                          category: Men's Clothing
                      constraints: {}
                      unresolved: []
                    evidence:
                      - source: agent
                        field: intent
                        note: recognised without a model
                      - source: store-info
                        operation: GET /v1/store/info
                        field: name
                    computed_at: '2026-11-08T10:12:41.000Z'
                    currency: null
                    environment: production
                    usage:
                      credits_debited: 0
                      model_class: null
        '400':
          description: The request is invalid
          headers:
            Tybrite-Environment:
              $ref: '#/components/headers/TybriteEnvironment'
          content:
            application/json:
              schema:
                type: object
                required:
                  - error
                properties:
                  error:
                    type: object
                    required:
                      - code
                      - message
                    properties:
                      code:
                        type: string
                      message:
                        type: string
                      details:
                        description: >-
                          Context for the error. On `quote_changed`,
                          `items_unavailable`, `shipping_not_deliverable` and
                          `quote_incomplete` it carries the current `quote`.
                        type:
                          - object
                          - string
                          - array
              example:
                error:
                  code: invalid_request
                  message: query must be a non-empty string of at most 500 characters
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '402':
          description: >-
            Not returned by this endpoint. A store without AI credits has its
            messages read by the rules at no cost.
          headers:
            Tybrite-Environment:
              $ref: '#/components/headers/TybriteEnvironment'
          content:
            application/json:
              schema:
                type: object
                required:
                  - error
                properties:
                  error:
                    type: object
                    required:
                      - code
                      - message
                    properties:
                      code:
                        type: string
                      message:
                        type: string
                      details:
                        description: >-
                          Context for the error. On `quote_changed`,
                          `items_unavailable`, `shipping_not_deliverable` and
                          `quote_incomplete` it carries the current `quote`.
                        type:
                          - object
                          - string
                          - array
              example:
                error:
                  code: insufficient_credits
                  message: >-
                    This store has no AI credits available. The deterministic
                    tools remain available.
        '403':
          description: >-
            With `conversation_id`, `shopping_assistant_disabled`,
            `history_disabled` or `guests_not_allowed` when the store's
            assistant settings do not allow the conversation to be read. Hosted
            helpers being off is never a refusal here.
          headers:
            Tybrite-Environment:
              $ref: '#/components/headers/TybriteEnvironment'
          content:
            application/json:
              schema:
                type: object
                required:
                  - error
                properties:
                  error:
                    type: object
                    required:
                      - code
                      - message
                    properties:
                      code:
                        type: string
                      message:
                        type: string
                      details:
                        description: >-
                          Context for the error. On `quote_changed`,
                          `items_unavailable`, `shipping_not_deliverable` and
                          `quote_incomplete` it carries the current `quote`.
                        type:
                          - object
                          - string
                          - array
              example:
                error:
                  code: helpers_unavailable
                  message: >-
                    Hosted helpers are not available for this store. The
                    deterministic tools remain available.
        '404':
          $ref: '#/components/responses/NotFoundError'
        '429':
          $ref: '#/components/responses/AgentRateLimitError'
        '500':
          $ref: '#/components/responses/ServerError'
        '502':
          description: The hosted helper did not complete
          headers:
            Tybrite-Environment:
              $ref: '#/components/headers/TybriteEnvironment'
          content:
            application/json:
              schema:
                type: object
                required:
                  - error
                properties:
                  error:
                    type: object
                    required:
                      - code
                      - message
                    properties:
                      code:
                        type: string
                      message:
                        type: string
                      details:
                        description: >-
                          Context for the error. On `quote_changed`,
                          `items_unavailable`, `shipping_not_deliverable` and
                          `quote_incomplete` it carries the current `quote`.
                        type:
                          - object
                          - string
                          - array
              example:
                error:
                  code: helper_failed
                  message: >-
                    The hosted helper did not complete. No credits are kept for
                    a failed call.
      security:
        - BearerAuth: []
components:
  headers:
    TybriteEnvironment:
      description: >
        Confirms which environment your API key resolved to. Use this to verify
        that test keys

        are hitting sandbox data and live keys are hitting production data.


        - `production` — requests are scoped to live data; real orders,
        customers, and payments

        - `sandbox` — requests are scoped to isolated test data; no real money
        is moved


        Present on every authenticated response, including error responses.
      schema:
        type: string
        enum:
          - production
          - sandbox
      example: sandbox
  responses:
    UnauthorizedError:
      description: Authentication failed - invalid or missing API key
      headers:
        Tybrite-Environment:
          $ref: '#/components/headers/TybriteEnvironment'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unauthorized
              message: Missing or invalid Authorization header
    NotFoundError:
      description: Resource not found
      headers:
        Tybrite-Environment:
          $ref: '#/components/headers/TybriteEnvironment'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: not_found
              message: Resource not found
    AgentRateLimitError:
      description: >-
        Too many requests. Besides the two codes every endpoint can answer
        (`rate_limited`, `quota_exceeded`), the shopping assistant endpoints
        answer `agent_rate_limited` when one shopper (their sign-in or guest
        session, with their network address, at this store) or one network
        address at this store passes the store's fair-use budget. There are two
        budgets: the tools (search, compare, product context, fit, alternatives,
        cart insights, quotes and drafts) and the AI helpers (`interpret`,
        `cart-drafts/from-intent`), which have a tighter one. Other shoppers at
        the store are unaffected. `details` names the budget, the window and
        when it resets; wait `Retry-After` seconds and retry. Not counted
        against the monthly quota.

        A guest (a session with no shopper credential) and a signed-in customer
        have separate budgets. When a guest reaches a guest budget that is lower
        than the signed-in budget, the code is `guest_limit_reached` instead:
        `details.scope` is `guest`, `details.signed_in_limit` is the signed-in
        shopper's budget for the same bucket and window, and
        `details.sign_in_raises_limit` is `true`. A storefront shows its sign-in
        prompt for this code and retries after sign-in, or after `Retry-After`
        seconds. A signed-in customer at their budget, and a guest stopped by a
        per-address or per-store ceiling, or whose budget is not lower than the
        signed-in one, still get `agent_rate_limited`. Both codes carry the same
        headers.
      headers:
        Tybrite-Environment:
          $ref: '#/components/headers/TybriteEnvironment'
        Retry-After:
          description: >-
            Seconds until the window that refused the request resets. Sent with
            `agent_rate_limited`, `guest_limit_reached` and `rate_limited`, and
            with `quota_exceeded` (the seconds until the monthly reset).
          schema:
            type: integer
          example: 23
        X-RateLimit-Limit:
          description: >-
            For `agent_rate_limited` and `guest_limit_reached`, the size of the
            budget that refused the request, in requests per window.
          schema:
            type: string
          example: '12'
        X-RateLimit-Remaining:
          description: Requests left in that window (0 on a refusal).
          schema:
            type: string
          example: '0'
        X-RateLimit-Reset:
          description: Unix time, in seconds, when that window resets.
          schema:
            type: string
          example: '1794139260'
        X-RateLimit-Scope:
          description: '`abuse` on every throttle refusal.'
          schema:
            type: string
          example: abuse
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            agent_rate_limited:
              summary: A signed-in customer reached their budget
              value:
                error:
                  code: agent_rate_limited
                  message: >-
                    Too many shopping assistant questions from this shopper.
                    Wait a moment and try again.
                  details:
                    bucket: helpers
                    scope: shopper
                    limit: 12
                    window_seconds: 60
                    remaining: 0
                    reset: 1794139260
                    retry_after: 23
            guest_limit_reached:
              summary: A guest reached a guest budget that signing in raises
              value:
                error:
                  code: guest_limit_reached
                  message: Sign in to keep going — signed-in shoppers get more.
                  details:
                    bucket: helpers
                    scope: guest
                    limit: 6
                    window_seconds: 60
                    remaining: 0
                    reset: 1794139260
                    retry_after: 23
                    signed_in_limit: 12
                    sign_in_raises_limit: true
    ServerError:
      description: Internal server error. A 5xx response never carries `details`.
      headers:
        Tybrite-Environment:
          $ref: '#/components/headers/TybriteEnvironment'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: server_error
              message: An unexpected error occurred
  schemas:
    Error:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              example: invalid_request
            message:
              type: string
              example: Missing required field
            details:
              description: >-
                Further detail about the error: a sentence, or for some errors
                an object (for example the `missing` list of
                `billing_location_required` or the `item_index` and `field_name`
                of `line_field_required`).
              oneOf:
                - type: string
                - type: object
                  additionalProperties: true
              example: The 'email' field is required
            hint:
              type: string
              description: Additional guidance on how to resolve the error.
            available_stock:
              type: integer
              description: Current stock level (present on insufficient_stock errors).
            current_cart_quantity:
              type: integer
              description: Quantity already in cart (present on insufficient_stock errors).
            limit:
              type: integer
              description: >-
                Rate limit ceiling (present on rate_limited / quota_exceeded
                errors).
            remaining:
              type: integer
              description: >-
                Requests remaining in the current window (present on
                rate_limited / quota_exceeded errors).
            reset:
              type: integer
              description: >-
                Unix timestamp when the rate limit / quota window resets
                (present on rate_limited / quota_exceeded errors).
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: >
        **API Key Authentication**
            
        Use your API key in the Authorization header:

        ```

        Authorization: Bearer tybrite_sk_live_YOUR_KEY

        ```
            
        **Key Types:**
            
        **Secret Keys (Server-Side Only):**

        - Format: `tybrite_sk_live_*` (production) or `tybrite_sk_test_*`
        (sandbox)

        - Full read/write access to all endpoints

        - ⚠️ NEVER expose in client-side code or public repositories

        - Required for: every write a shopper does not make for themselves,
        authentication, payment verification, AI recommendations
            
        **Publishable Keys (Client-Safe):**

        - Format: `tybrite_pk_live_*` (production) or `tybrite_pk_test_*`
        (sandbox)

        - Catalogue reads, plus the actions a shopper takes for themselves

        - ✅ Safe for client-side JavaScript, mobile apps, and public code

        - Allowed for: browsing products, search, CMS content, pricing queries,
        cart and wishlist,
          reviews, storefront events, and the Agent API's quotes, cart drafts and checkout intents
            
        **Endpoint-Specific Requirements:**

        - **Authentication endpoints** (`/v1/auth/*`): state-changing `POST`
        calls require a secret key, for store and marketplace keys alike; `GET
        /v1/auth/me` accepts either key

        - **Payment verification** (`POST /v1/payments/verify`): Secret key
        required

        - **AI Recommendations** (`POST /v1/recommendations`): Secret key
        required

        - **Semantic Search** (`POST /v1/search`): Both key types allowed
        (read-only operation)

        - **Shopper actions** (cart, wishlist, reviews, storefront events, Agent
        API quotes, cart drafts and checkout intents): Both key types allowed

        - **All other write operations**: Secret key required

        - **All read operations**: Both key types allowed
            
        Using a publishable key for restricted operations returns 403 Forbidden.


        **Limited publishable keys:**

        A publishable key can be limited to the products that carry one tag (for
        example `starter:jewellery`), created from

        the store's Developers page. The limit applies to the key, never to the
        shopper: shopper sign-up and sign-in stay store-wide.

        - Reads return only the slice: products (with their facets, filters,
        search, brands and specifications), categories and
          subcategories that hold in-slice products, collections, promotions, posts and lookbooks that carry the tag, reviews of
          in-slice products, prices, discovery lists and the store information summary, with every count computed on the slice.
          A product outside the slice answers `404`, as if it did not exist.
        - A write that names a product or variant outside the slice (adding to
        the cart or wishlist, reserving stock, an order line,
          a review, a promotion calculation, a storefront event) answers `403` with the error code `out_of_scope`, and nothing is
          written or reserved. An order is refused as a whole.
        - A route that carries no slice behaviour is not available to the key:
        it answers `403` with `endpoint_not_allowed`.

        - Orders placed through such a key record the tag on the order's
        attribution as `key_scope`.

        - Secret keys and connected-app keys cannot be limited.

        - Responses are cached per key limit: a limited key never receives a
        response cached for the whole store, and the reverse.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.