# TLAY Machine Commerce Platform API (published copy of specs/PLATFORM_API.yaml; examples use a local chain id)
openapi: 3.1.0
info:
  title: TLAY MCE Platform API
  version: 1.0.0
  summary: Identity, capabilities, authorization, invocations, events, evidence, agreements and settlement for third-party devices.
  description: |
    The formal integration contract for third-party business platforms, applications and agents (PRD §8).
    Everything the developer console can do is available here — the console is just a client.

    **Conventions**
    - All writes that create or change business state require an `Idempotency-Key` (scope: organization + application + operation type).
      Same key + same body → the same resource; same key + different body → `409 idempotency_conflict`.
    - `201`/`202` mean *durably accepted*, never "device executed" or "funds settled". Follow `status_url`, webhooks or `GET /events`.
    - Times are UTC RFC 3339. Amounts, 64-bit counters and cumulative quantities are **decimal integer strings**, always with unit / asset / scale.
    - `external_ref` is echoed for correlation with your own records and is never used for authorization.
    - `X-MCE-Client` (optional, `a-z0-9.-`, up to 32) names the software placing an order (`shop`, `mcp`, your own). It
      is recorded on the order only for the seller's view of who buys (`sales.buyers`); nothing is decided by it.
    - Read models report `observed_at`, `received_at`, `freshness` and a monotonic `resource_version`; cached values are never presented as live.
    - There is no endpoint that sets an arbitrary device result to success. Platform-submitted evidence is always `source=platform_application`.
    - Request bodies are limited to 256 KiB; larger material is referenced by authorized object references.
  license:
    name: Apache-2.0
    identifier: Apache-2.0
servers:
  - url: "{base}/v1/tlay"
    variables:
      base:
        default: https://api.example.invalid
        description: Deployment-specific; provided by configuration.
security:
  - bearer: []
tags:
  - { name: auth, description: "Access tokens" }
  - { name: accounts, description: "People: sign-in, organisation members and roles, invitations, password resets (docs/design/ACCOUNTS.md)" }
  - { name: disputes, description: "What the seller, the buyer and the resolver see and say in a dispute; the resolver's decision (docs/design/DISPUTES.md)" }
  - { name: notifications, description: "What people and buyer wallets are told, in the apps and by email (docs/design/NOTIFICATIONS.md)" }
  - { name: applications, description: "Platform applications and credential scopes" }
  - { name: products, description: "Products and immutable capability manifests" }
  - { name: firmware, description: "Signed firmware releases and rollouts (devices verify and apply them under their own policy)" }
  - { name: manufacturing, description: "Factory provisioning keys and imported production manifests (FACTORY_PROVISIONING.md)" }
  - { name: devices, description: "Device identity, claim, registry, modules and keys" }
  - { name: invocations, description: "Authorised device action requests" }
  - { name: data, description: "Properties, device events and meters" }
  - { name: grants, description: "Delegated access and funds scopes" }
  - { name: commerce, description: "Service offerings, quotes and agreements" }
  - { name: payments, description: "Funding intents, payments and settlements" }
  - { name: evidence, description: "Evidence records, anchoring and bundles" }
  - { name: events, description: "Webhooks and event recovery" }
  - { name: operations, description: "Asynchronous operations" }

paths:
  /oauth/token:
    post:
      tags: [auth]
      operationId: issueToken
      summary: Exchange application credentials for a short-lived access token (client credentials)
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type, client_id, client_secret]
              properties:
                grant_type: { const: client_credentials }
                client_id: { type: string }
                client_secret: { type: string, writeOnly: true }
                scope: { type: string, description: Space-separated subset of the application's scopes }
      responses:
        "200":
          description: Token issued
          content:
            application/json:
              schema:
                type: object
                required: [access_token, token_type, expires_in, scope]
                properties:
                  access_token: { type: string }
                  token_type: { const: Bearer }
                  expires_in: { type: integer, maximum: 3600 }
                  scope: { type: string }
        "401": { $ref: "#/components/responses/Error" }

  /auth/login:
    post:
      tags: [accounts]
      operationId: login
      summary: Sign a person in with email and password
      description: >-
        Returns a short-lived access token for one of the person's organisations (`organization_id`, default
        the first) and a refresh token. A wrong password, an unknown address and a locked account get the same
        401. Five wrong passwords or codes lock the account for a while (longer each time). With two-factor
        sign-in on, the right password alone answers `{two_factor_required: true}` (no token): send the request
        again with `code` (the authenticator's 6 digits, each usable once, or a recovery code). No Idempotency-Key.
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [email, password], properties: { email: { type: string }, password: { type: string, writeOnly: true }, organization_id: { type: string },
          code: { type: string, writeOnly: true, description: The second factor, when the account has it on } } } } }
      responses:
        "200": { description: Signed in, or a code is needed, content: { application/json: { schema: { oneOf: [{ $ref: "#/components/schemas/Session" }, { $ref: "#/components/schemas/TwoFactorRequired" }] } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/passkey-options:
    post:
      tags: [accounts]
      operationId: passkeyLoginOptions
      summary: Options for navigator.credentials.get, to sign in with a passkey (no email, no password)
      description: The relying party is the operator app (MCE_OPERATOR_URL); the challenge is single use and expires in 5 minutes. No Idempotency-Key.
      security: []
      responses:
        "200": { description: Options, content: { application/json: { schema: { type: object, properties: { challenge_id: { type: string }, options: { type: object, description: PublicKeyCredentialRequestOptionsJSON } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/passkey-login:
    post:
      tags: [accounts]
      operationId: passkeyLogin
      summary: Sign in with a passkey; the session counts as signed in with two factors
      description: >-
        The browser's answer to navigator.credentials.get (user verification required). The signature counter must move
        forward. The session meets an organisation's two-factor requirement. No Idempotency-Key.
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [challenge_id, response], properties: { challenge_id: { type: string }, response: { type: object, description: AuthenticationResponseJSON }, organization_id: { type: string } } } } }
      responses:
        "200": { description: Signed in, content: { application/json: { schema: { $ref: "#/components/schemas/Session" } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/refresh:
    post:
      tags: [accounts]
      operationId: refreshSession
      summary: A new access token for a refresh token, which is replaced
      description: Refresh tokens rotate. One presented a second time ends every session it led to. `organization_id` switches organisation.
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [refresh_token], properties: { refresh_token: { type: string, writeOnly: true }, organization_id: { type: string } } } } }
      responses:
        "200": { description: Signed in, content: { application/json: { schema: { $ref: "#/components/schemas/Session" } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/logout:
    post:
      tags: [accounts]
      operationId: logout
      summary: End the session a refresh token belongs to
      security: []
      requestBody:
        content: { application/json: { schema: { type: object, properties: { refresh_token: { type: string, writeOnly: true } } } } }
      responses:
        "200": { description: Signed out, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/invitations/{token}:
    parameters: [{ name: token, in: path, required: true, schema: { type: string } }]
    get:
      tags: [accounts]
      operationId: getInvitation
      summary: What an invitation is for (address, organisation, role, whether the address has an account)
      security: []
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/invitations/{token}/accept:
    parameters: [{ name: token, in: path, required: true, schema: { type: string } }]
    post:
      tags: [accounts]
      operationId: acceptInvitation
      summary: Join the organisation and sign in
      description: >-
        A new account needs `name` and `password` (10 to 200 characters). An address that already has an account
        proves its `password` instead, and its `code` when it has two-factor sign-in on (answered
        `{two_factor_required: true}` without it). Single use.
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [password], properties: { name: { type: string, maxLength: 80 }, password: { type: string, writeOnly: true }, code: { type: string, writeOnly: true } } } } }
      responses:
        "200": { description: Signed in, or a code is needed, content: { application/json: { schema: { oneOf: [{ $ref: "#/components/schemas/Session" }, { $ref: "#/components/schemas/TwoFactorRequired" }] } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/password-resets:
    post:
      tags: [accounts]
      operationId: requestPasswordReset
      summary: Email a password reset link to whoever has an account at this address
      description: >-
        For a person who forgot their password. The answer is `202` whether or not the address has an account; one
        link per address is mailed per two minutes at most; the link (to the operator app's reset page) works for an
        hour, once. `unsupported_capability` when the platform sends no email (an owner or admin then makes a link).
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [email], properties: { email: { type: string, format: email } } } } }
      responses:
        "202": { description: Requested, content: { application/json: { schema: { type: object, properties: { requested: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/password-resets/{token}:
    parameters: [{ name: token, in: path, required: true, schema: { type: string } }]
    post:
      tags: [accounts]
      operationId: resetPassword
      summary: Set a new password with a reset link (single use; every session of the account ends)
      security: []
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [password], properties: { password: { type: string, writeOnly: true } } } } }
      responses:
        "200": { description: Password changed, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /auth/unlocks/{token}:
    parameters: [{ name: token, in: path, required: true, schema: { type: string } }]
    post:
      tags: [accounts]
      operationId: unlockAccount
      summary: Unlock an account with the link from the email sent when it locked (single use, 24 hours; nothing else changes)
      security: []
      responses:
        "200": { description: Unlocked, content: { application/json: { schema: { type: object, properties: { unlocked: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /organization:
    get:
      tags: [accounts]
      operationId: getOrganization
      summary: This organisation's name and public profile
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Organization" } } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [accounts]
      operationId: updateOrganization
      summary: Change the name or the public profile (owners and admins, tenant:admin); an empty string clears a profile field
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { name: { type: string, minLength: 2, maxLength: 80 }, profile: { $ref: "#/components/schemas/OrganizationProfile" },
          require_two_factor: { type: boolean, description: "Turning it on: a person doing so must have two-factor sign-in themself (409 otherwise)" } } } } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Organization" } } } }
        default: { $ref: "#/components/responses/Error" }
  /me:
    get:
      tags: [accounts]
      operationId: getMe
      summary: The person behind this token, their organisation, role and scopes (`403` for an application's token)
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [accounts]
      operationId: updateMe
      summary: Change one's own name or password (the current password is required; other sessions end)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { name: { type: string, maxLength: 80 }, current_password: { type: string, writeOnly: true }, new_password: { type: string, writeOnly: true } } } } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/passkeys:
    get:
      tags: [accounts]
      operationId: listPasskeys
      summary: This person's passkeys
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { type: object, properties: {
          id: { type: string }, name: { type: string }, created_at: { $ref: "#/components/schemas/Time" }, last_used_at: { type: [string, "null"] }, synced: { type: boolean } } } } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [accounts]
      operationId: addPasskey
      summary: Add a passkey from the browser's answer to navigator.credentials.create
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [challenge_id, response], properties: { challenge_id: { type: string }, response: { type: object, description: RegistrationResponseJSON }, name: { type: string, maxLength: 60 } } } } }
      responses:
        "201": { description: Added, content: { application/json: { schema: { type: object } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/passkeys/options:
    post:
      tags: [accounts]
      operationId: passkeyRegistrationOptions
      summary: Options for navigator.credentials.create (a resident key with user verification; at most 10 passkeys)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Options, content: { application/json: { schema: { type: object, properties: { challenge_id: { type: string }, options: { type: object, description: PublicKeyCredentialCreationOptionsJSON } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/passkeys/{passkey_id}:
    parameters: [{ name: passkey_id, in: path, required: true, schema: { type: string } }]
    delete:
      tags: [accounts]
      operationId: removePasskey
      summary: Remove a passkey; it no longer signs in
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Removed, content: { application/json: { schema: { type: object, properties: { removed: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/two-factor:
    post:
      tags: [accounts]
      operationId: startTwoFactor
      summary: Start turning on two-factor sign-in (a secret and an otpauth URI for an authenticator app)
      description: Idempotency-Key required; the answer (a secret) is never kept. 409 when it is already on.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "201": { description: Started, content: { application/json: { schema: { type: object, properties: { secret: { type: string, description: Base32 }, otpauth_uri: { type: string } } } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [accounts]
      operationId: disableTwoFactor
      summary: Turn it off, with the current password and a code
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [current_password, code], properties: { current_password: { type: string, writeOnly: true }, code: { type: string, writeOnly: true } } } } }
      responses:
        "200": { description: "Off", content: { application/json: { schema: { type: object, properties: { enabled: { const: false } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/two-factor/confirmation:
    post:
      tags: [accounts]
      operationId: confirmTwoFactor
      summary: "On, once a code from the app matches: ten single-use recovery codes, shown once"
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [code], properties: { code: { type: string } } } } }
      responses:
        "200": { description: "On", content: { application/json: { schema: { type: object, properties: { enabled: { const: true }, recovery_codes: { type: array, items: { type: string } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /me/two-factor/recovery-codes:
    post:
      tags: [accounts]
      operationId: newRecoveryCodes
      summary: Ten new recovery codes (the old ones stop working), with a current code
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [code], properties: { code: { type: string } } } } }
      responses:
        "200": { description: New codes, content: { application/json: { schema: { type: object, properties: { recovery_codes: { type: array, items: { type: string } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /members/{user_id}/two-factor:
    parameters: [{ name: user_id, in: path, required: true, schema: { type: string } }]
    delete:
      tags: [accounts]
      operationId: resetMemberTwoFactor
      summary: Turn off a member's two-factor sign-in (lost authenticator and recovery codes); their sessions end
      description: >-
        Owners and admins (an owner for owners and admins), never for oneself, and not for a person who belongs to
        other organisations too (they use a recovery code). In the audit log.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: "Off", content: { application/json: { schema: { type: object, properties: { user_id: { type: string }, two_factor: { type: object } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /members:
    get:
      tags: [accounts]
      operationId: listMembers
      summary: The organisation's members and their roles
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /members/{user_id}:
    parameters: [{ name: user_id, in: path, required: true, schema: { type: string } }]
    patch:
      tags: [accounts]
      operationId: setMemberRole
      summary: Change a member's role
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      description: >-
        Roles: `owner` and `admin` (everything, members included), `operator` (devices, invocations, commerce,
        firmware), `viewer` (read only). Admins manage operators and viewers; only an owner makes or unmakes
        owners and admins; an organisation keeps at least one owner. A role taken away applies at once.
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [role], properties: { role: { enum: [owner, admin, operator, viewer] } } } } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [accounts]
      operationId: removeMember
      summary: Remove a member (their tokens stop working at once; the account itself stays)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Removed, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /members/{user_id}/password-resets:
    parameters: [{ name: user_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [accounts]
      operationId: createPasswordReset
      summary: A password reset link for a member (valid one hour)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      description: The token is returned once and is not kept in the idempotency log, so a repeated call makes a new link. No mail is sent; the manager passes the link on.
      responses:
        "201": { description: Created, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /member-invitations:
    get:
      tags: [accounts]
      operationId: listInvitations
      summary: Open invitations (without their tokens)
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [accounts]
      operationId: inviteMember
      summary: Invite someone into the organisation (valid seven days)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      description: >-
        The token is returned once and is not kept in the idempotency log, so a repeated call makes a new invitation, which
        replaces the previous one for that address. When the platform sends email and knows the operator app's address
        (MCE_OPERATOR_URL), the invitee is emailed the link too (`emailed: true`); otherwise the inviter passes it on.
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [email, role], properties: { email: { type: string }, role: { enum: [owner, admin, operator, viewer] } } } } }
      responses:
        "201": { description: Created, content: { application/json: { schema: { type: object, additionalProperties: true, properties: { id: { type: string }, email: { type: string }, role: { type: string }, token: { type: string }, expires_at: { $ref: "#/components/schemas/Time" }, emailed: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /member-invitations/{invitation_id}:
    parameters: [{ name: invitation_id, in: path, required: true, schema: { type: string } }]
    delete:
      tags: [accounts]
      operationId: revokeInvitation
      summary: Revoke an open invitation
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }

  /applications:
    post:
      tags: [applications]
      summary: Register a platform application and its credential scope
      description: >-
        Requires tenant-admin. The client secret is returned once. An agent can be given its limits here, so it is never
        without them (a person who is an owner or an administrator only).
      operationId: createApplication
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationCreate" } } }
      responses:
        "201":
          description: Created
          content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationWithSecret" } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [applications]
      summary: The organisation's applications (backends, agents, storefronts), not its people's sign-ins
      description: Requires tenant-admin. Revoked applications are listed after the active ones; secrets are never returned.
      operationId: listApplications
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/Application" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /audit-log:
    get:
      tags: [applications]
      operationId: listAuditLog
      summary: Who changed what in the organisation's configuration, newest first
      description: >-
        Requires tenant-admin. People and roles, applications and webhooks, products and security policies, services
        and prices, devices' keys and registry, firmware, payouts, dispute decisions. Orders and runs have their own
        history and are not listed. Details keep the request's plain fields, never secrets, signatures or keys.
      parameters:
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
        - { name: action, in: query, schema: { type: string }, description: "An action or its prefix (members., firmware.)" }
        - { name: resource_id, in: query, schema: { type: string } }
        - { name: actor, in: query, schema: { type: string }, description: A user id or an application id }
      responses:
        "200":
          description: Page
          content: { application/json: { schema: { type: object, properties: {
            data: { type: array, items: { $ref: "#/components/schemas/AuditEntry" } }, next_cursor: { type: [string, "null"] } } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/{application_id}:
    parameters: [{ name: application_id, in: path, required: true, schema: { type: string } }]
    delete:
      tags: [applications]
      summary: Revoke an application (at once; its tokens stop working with their next request)
      description: >-
        Requires tenant-admin; an application holding tenant:admin is revoked by an owner only. An application cannot
        revoke itself. The application is kept, revoked, with the history and webhooks it owns.
      operationId: revokeApplication
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { $ref: "#/components/schemas/Application" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/self:
    get:
      tags: [applications]
      summary: The application behind the token, with what it may do on its own
      description: >-
        For an application's token only (a person's gets 403). An agent reads its limits here to know which changes it
        makes directly and which it proposes or drafts for a person to decide.
      operationId: getSelfApplication
      responses:
        "200": { description: The application, content: { application/json: { schema: { $ref: "#/components/schemas/Application" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/self/record:
    get:
      tags: [applications]
      summary: The application's own record (see getApplicationRecord)
      description: For an application's token only (a person's gets 403).
      operationId: getSelfApplicationRecord
      responses:
        "200": { description: Its record, content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationRecord" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/{application_id}/record:
    parameters: [{ name: application_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [applications]
      summary: How people decided on what the application held back for them, and the freedom it has earned
      description: >-
        Requires commerce:read for a person of the organisation (those who decide for an agent see how it did), or
        tenant-admin for an application. Counts over the last 30 days: price proposals approved, declined, lapsed and open; drafts
        sent as written, sent edited, discarded, lapsed and open. in_a_row counts the newest decisions in a row that a
        person took as the agent made them (approved; sent unedited). After trust_run of them, while its limits still
        hold that back, suggestions carries the whole limits set that lets it act on its own (for prices, with the
        largest step it was approved for); a person applies it with setApplicationLimits, the platform never does.
      operationId: getApplicationRecord
      responses:
        "200": { description: Its record, content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationRecord" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/self/limits:
    post:
      tags: [applications]
      summary: The application holds itself back (stricter only)
      description: >-
        For an application's token only (a person's gets 403). Each limit given is kept when stricter than the one it
        has (propose, draft, a smaller step or band); the others stay as they are. An application never loosens its
        own limits: only a person does, with setApplicationLimits. The MCP server run with MCE_SELLER=propose asks
        for prices propose and answers and dispute messages draft at start, so its promise binds its credentials.
        Refused (409, details.reason tenant_admin) for an application holding tenant:admin.
      operationId: holdSelf
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationLimits" } } }
      responses:
        "200": { description: The application, with its limits now, content: { application/json: { schema: { $ref: "#/components/schemas/Application" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/{application_id}/limits:
    parameters: [{ name: application_id, in: path, required: true, schema: { type: string } }]
    put:
      tags: [applications]
      summary: What the application may do on its own (the whole set, replaced)
      description: >-
        Requires a person who is an owner or an administrator (an owner for an application holding tenant:admin); no
        application sets limits. Refused (409, details.reason tenant_admin) for an application holding tenant:admin,
        which could create another one without them. An application whose prices are held (propose, a step or a band)
        changes a largest order only by a proposal, and publishes no versions, creates no services or pools, changes no
        pool's machines and sets no price rule (403, needs_approval). Checked by the platform: a held-back change is refused with 403 forbidden, details.reason needs_approval (or
        price_step, or price_band with lowest_atomic, highest_atomic and the anchor_atomic a person last set) and details.instead naming the proposal or draft to make. Proposals and drafts are decided by a person.
      operationId: setApplicationLimits
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ApplicationLimits" } } }
      responses:
        "200": { description: The application, content: { application/json: { schema: { $ref: "#/components/schemas/Application" } } } }
        default: { $ref: "#/components/responses/Error" }
  /applications/{application_id}/secret-rotations:
    parameters: [{ name: application_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [applications]
      summary: A new client secret; the previous one is still accepted for previous_valid_s (default a day)
      description: >-
        Requires tenant-admin (an owner for an application holding tenant:admin). Tokens already issued run until they
        expire; previous_valid_s 0 stops the previous secret at once.
      operationId: rotateApplicationSecret
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { previous_valid_s: { type: integer, minimum: 0, maximum: 604800, default: 86400 } } } } }
      responses:
        "201":
          description: Rotated (the secret is shown once)
          content: { application/json: { schema: { type: object, required: [id, client_id, client_secret], properties: {
            id: { type: string }, client_id: { type: string }, client_secret: { type: string },
            previous_secret_valid_until: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }] } } } } }
        default: { $ref: "#/components/responses/Error" }

  /products:
    post:
      tags: [products]
      operationId: createProduct
      summary: Create a product model (a class of devices, not a device)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ProductCreate" } } }
      responses:
        "201": { description: Created, content: { application/json: { schema: { $ref: "#/components/schemas/Product" } } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [products]
      operationId: listProducts
      summary: List products
      parameters: [{ $ref: "#/components/parameters/Cursor" }, { $ref: "#/components/parameters/Limit" }]
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/ProductPage" } } } }
        default: { $ref: "#/components/responses/Error" }

  /products/{product_id}/versions:
    parameters: [{ $ref: "#/components/parameters/ProductId" }]
    post:
      tags: [products]
      operationId: publishProductVersion
      summary: Publish an immutable manifest version
      description: |
        Validates against the Capability Manifest schema and semantic rules, computes the canonical digest and
        stores the version immutably. Re-publishing an existing version with different content → `409 conflict`.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ProductManifest" }
      responses:
        "201": { description: Published, content: { application/json: { schema: { $ref: "#/components/schemas/ProductVersion" } } } }
        default: { $ref: "#/components/responses/Error" }
  /products/{product_id}/versions/{version}:
    parameters: [{ $ref: "#/components/parameters/ProductId" }, { name: version, in: path, required: true, schema: { type: string } }]
    get:
      tags: [products]
      operationId: getProductVersion
      summary: Get the manifest and its digest
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/ProductVersion" } } } }
        default: { $ref: "#/components/responses/Error" }
  /products/{product_id}/versions/{version}/firmware-tables:
    parameters: [{ $ref: "#/components/parameters/ProductId" }, { name: version, in: path, required: true, schema: { type: string } }]
    get:
      tags: [products]
      operationId: getFirmwareTables
      summary: The version compiled into the firmware's const C tables (the same as `mce manifest compile`)
      description: >-
        Requires `products:read`. A header and a source file declaring `const tlay_product_desc_t <symbol>`, with
        parameter bounds narrowed by the manifest's policy limits and the manifest digest the device reports.
      parameters: [{ name: symbol, in: query, schema: { type: string, pattern: "^[a-z][a-z0-9_]{0,39}$", default: app_product } }]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  product_id: { type: string }
                  version: { type: string }
                  digest: { type: string }
                  symbol: { type: string }
                  files: { type: array, items: { type: object, properties: { name: { type: string }, content: { type: string } } } }
        default: { $ref: "#/components/responses/Error" }

  /products/{product_id}/security-policy:
    parameters: [{ $ref: "#/components/parameters/ProductId" }]
    get:
      tags: [products]
      operationId: getProductSecurityPolicy
      summary: The security state this product's devices must report
      description: Requires `products:read`. 404 when the product has no policy (devices then show verdict `no_policy`).
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/SecurityPolicyView" } } } }
        default: { $ref: "#/components/responses/Error" }
    put:
      tags: [products]
      operationId: putProductSecurityPolicy
      summary: Set the security state this product's devices must report
      description: >-
        Requires `products:write`. Replaces the policy; it applies at once to every device of the product (the verdict
        is computed when read). With `enforcement: refuse_commerce`, a device failing it can neither buy nor be sold:
        quotes and agreements naming it are refused. See docs/design/DEVICE_SECURITY.md: the reported state is a
        self-report of the running firmware, as trustworthy as secure boot.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody: { required: true, content: { application/json: { schema: { $ref: "#/components/schemas/SecurityPolicy" } } } }
      responses:
        "200": { description: Stored, content: { application/json: { schema: { $ref: "#/components/schemas/SecurityPolicyView" } } } }
        default: { $ref: "#/components/responses/Error" }

  /installation-credentials:
    get:
      tags: [devices]
      operationId: listInstallationCredentials
      summary: The organisation's installation credentials (never the secret), newest first
      description: Requires `devices:provision`. State open, used (with the device it claimed), expired or revoked.
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/InstallationCredential" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [devices]
      operationId: createInstallationCredential
      summary: Issue a single-use installer/manufacturing credential required to claim a device
      description: Requires `devices:provision`. The secret is returned once; only its hash is stored. A claim needs BOTH this credential and the device's key-possession proof (GEN-09).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                product_id: { type: string, description: Restrict the credential to one product }
                ttl_days: { type: integer, minimum: 1, maximum: 365, default: 30 }
      responses:
        "201":
          description: Credential (secret shown once)
          content:
            application/json:
              schema:
                type: object
                required: [id, installation_credential, expires_at, single_use]
                properties:
                  id: { type: string }
                  installation_credential: { type: string }
                  product_id: { type: ["string", "null"] }
                  expires_at: { $ref: "#/components/schemas/Time" }
                  single_use: { const: true }
        default: { $ref: "#/components/responses/Error" }

  /device-claims/challenges:
    post:
      tags: [devices]
      operationId: createClaimChallenge
      summary: Start a one-time claim (installer / registry controller)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: >-
                Name the module by module_id, or by the serial on the unit's label when the organization
                imported its production manifest (the serial then names the module and the product;
                product_id may be omitted). Not both.
              required: [product_version]
              properties:
                module_id: { type: string }
                serial: { type: string, description: Serial of an imported manufactured unit (/manufactured-units) }
                product_id: { type: string }
                product_version: { type: string }
                external_ref: { $ref: "#/components/schemas/ExternalRef" }
      responses:
        "201":
          description: Challenge (relay to the device, which signs it with tlay_claim_begin)
          content:
            application/json:
              schema:
                type: object
                required: [challenge_id, challenge, expires_at]
                properties:
                  challenge_id: { type: string }
                  challenge: { type: string, contentEncoding: base64 }
                  module_id: { type: string, description: The module the challenge is for (resolved from the serial when one was given) }
                  product_id: { type: string }
                  expires_at: { $ref: "#/components/schemas/Time" }
        default: { $ref: "#/components/responses/Error" }
  /device-claims:
    post:
      tags: [devices]
      operationId: submitClaim
      summary: Submit the device's key-possession proof plus the installation credential
      description: Both the device proof and the installation/manufacturing credential must be valid (GEN-09). Returns an Operation.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [challenge_id, device_proof, installation_credential]
              properties:
                challenge_id: { type: string }
                device_proof: { $ref: "#/components/schemas/SignedStructure" }
                installation_credential: { type: string, writeOnly: true, description: One-time installer/manufacturing credential }
                external_ref: { $ref: "#/components/schemas/ExternalRef" }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }

  /devices:
    get:
      tags: [devices]
      operationId: listDevices
      summary: List devices in scope
      parameters:
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
        - { name: product_id, in: query, schema: { type: string } }
        - { name: external_ref, in: query, schema: { type: string } }
        - { name: serial, in: query, schema: { type: string }, description: "Unit serial: from an imported production manifest or reported by the device (firmware.factory.serial)" }
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/DevicePage" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [devices]
      operationId: getDevice
      summary: Get device identity, capability binding and connection
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Device" } } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [devices]
      operationId: updateDevice
      summary: The team's name, location and reference for the device, and where buyers find it ("" clears one)
      description: Requires `devices:write`. `place` is public (shown with its listed services, matched by the catalog's text search); the rest is the team's own.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, properties: {
          name: { type: string, maxLength: 80 }, location: { type: string, maxLength: 120 }, external_ref: { type: string, maxLength: 128 }, place: { type: string, maxLength: 80 } } } } }
      responses:
        "200": { description: Changed, content: { application/json: { schema: { $ref: "#/components/schemas/Device" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/retirement:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: retireDevice
      summary: Retire the device (it no longer connects, sells, buys or runs; its services are unlisted)
      description: >-
        Requires `devices:write`. Refused (409, details.open_agreements) while an order on the device is open. Its live
        connection is closed and the gateway refuses it ("retired"). Restoring undoes it, except the listings.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { reason: { type: string, maxLength: 300 } } } } }
      responses:
        "200":
          description: Retired
          content: { application/json: { schema: { allOf: [{ $ref: "#/components/schemas/Device" }, { type: object, properties: { unlisted_offerings: { type: array, items: { type: string } } } }] } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [devices]
      operationId: restoreDevice
      summary: Restore a retired device (it may connect and trade again; list its services again yourself)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Restored, content: { application/json: { schema: { $ref: "#/components/schemas/Device" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/pause:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: pauseDevice
      summary: Pause the machine for maintenance (other organisations cannot order its services until it is resumed or the pause ends)
      description: >-
        Requires `devices:write`. Its services stay listed and show the pause; quotes for other organisations are refused
        (409, details.reason device_paused, details.until, details.opens_at), and so is accepting a quote made before the
        pause (POST /agreements). Orders already placed run as agreed, and the
        seller's own organisation is not limited. Pausing a paused machine keeps when the pause began and replaces its
        end and note. Wallets waiting for a service to open are told once it is resumed or the pause ends.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                until: { $ref: "#/components/schemas/Time", description: "When the pause ends by itself: in the future, at most 90 days ahead, with its offset (Z or ±hh:mm). Absent: until resumed" }
                note: { type: string, maxLength: 200, description: Shown to buyers with the pause }
      responses:
        "200": { description: Paused, content: { application/json: { schema: { $ref: "#/components/schemas/Device" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [devices]
      operationId: resumeDevice
      summary: End the pause (its services can be ordered again, within their hours)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Resumed, content: { application/json: { schema: { $ref: "#/components/schemas/Device" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/registry-operations:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: requestRegistryOperation
      summary: Register or update the on-chain registry binding (registry controller)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kind, network]
              properties:
                kind: { enum: [register, update_binding, suspend, reactivate, revoke, set_operator] }
                network: { $ref: "#/components/schemas/Caip2" }
                controller: { $ref: "#/components/schemas/EvmAddress", description: "register: the controller address (default: the platform's custodial controller in the sandbox)" }
                operator: { $ref: "#/components/schemas/EvmAddress", description: "set_operator: address allowed to grant leases for this device" }
                allowed: { type: boolean, default: true }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/module-bindings:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: replaceModule
      summary: Controlled module replacement — device_id and history are kept (GEN-10)
      description: Requires no active sessions or unreconciled payments on the old module, or an explicit risk disposition.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [challenge_id, new_module_claim, installation_credential]
              properties:
                challenge_id: { type: string, description: Claim challenge created for the NEW module }
                new_module_claim: { $ref: "#/components/schemas/SignedStructure" }
                installation_credential: { type: string, writeOnly: true }
                reason: { type: string, maxLength: 200 }
      responses:
        "202":
          description: >-
            Module replaced. The old module's payment key leaves with the old hardware: it becomes `abandoned`, and
            `payment_keys_abandoned` reports what still refers to its address (open agreements, unsettled payments,
            escrow credit, token balance) — docs/design/PAYMENT_KEY_ROTATION.md §5.6.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Operation" }
                  - type: object
                    properties:
                      payment_keys_abandoned: { type: array, items: { type: object, properties: { key_id: { type: string }, address: { $ref: "#/components/schemas/EvmAddress" }, obligations: { $ref: "#/components/schemas/PaymentKeyObligations" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/virtual:
    post:
      tags: [devices]
      operationId: createVirtualDevice
      summary: A virtual device of a product, run by the platform (development and test deployments only)
      description: >-
        Requires `devices:claim`. The platform claims a new device of the product (it answers the claim challenge with
        its own key), connects it to the gateway and runs it: it acknowledges each invocation, runs for the time asked,
        reports the action's meters and completes. Its records are development_only and the device is shown as virtual
        everywhere, the catalog included. At most 20 per organisation. Refused (unsupported_capability) where the
        deployment does not run virtual devices.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [product_id], properties: {
          product_id: { type: string }, product_version: { type: string, description: "Default: the latest version" }, name: { type: string, maxLength: 80 } } } } }
      responses:
        "201": { description: Claimed and started, content: { application/json: { schema: { type: object, properties: {
          device_id: { type: string }, product_id: { type: string }, product_version: { type: string }, virtual: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/record:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [devices]
      operationId: getMachineRecord
      summary: The machine's record, as buyers see it where a listing shows it (show_record, on unless the seller turns it off)
      description: Requires `devices:read`. Counted by the platform from the contracts' settlements of other organisations' orders and from the device's connections.
      responses:
        "200": { description: OK, content: { application/json: { schema: { allOf: [{ type: object, properties: { device_id: { type: string } } }, { $ref: "#/components/schemas/MachineRecord" }] } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/connections:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [devices]
      operationId: listDeviceConnections
      summary: When the device was connected over the last days (spans merged and clipped to the window)
      description: Requires `devices:read`. Connections are kept for 30 days after they end (RETENTION.md).
      parameters: [{ name: days, in: query, schema: { type: integer, minimum: 1, maximum: 30, default: 7 } }]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  device_id: { type: string }
                  from: { $ref: "#/components/schemas/Time" }
                  to: { $ref: "#/components/schemas/Time" }
                  recorded_from: { $ref: "#/components/schemas/Time", description: "From when connections are recorded in the window (absent: none yet)" }
                  online_share: { type: number, minimum: 0, maximum: 1, description: "Of the recorded part of the window; absent before a minute of it" }
                  data: { type: array, items: { type: object, properties: { from: { $ref: "#/components/schemas/Time" }, to: { $ref: "#/components/schemas/Time" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/payment-keys:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [devices]
      operationId: listPaymentKeys
      summary: The device's payment keys and, for keys that are not active, what still refers to their address
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { device_id: { type: string }, data: { type: array, items: { $ref: "#/components/schemas/PaymentKey" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/payment-keys/{key_id}/approvals:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }, { name: key_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [devices]
      operationId: approvePaymentKey
      summary: Approve an unconfirmed payment address (a device whose payment key was lost or reset)
      description: >-
        A module that reports a different payment address than before has lost or reset its payment key. Its commerce
        is refused (`forbidden`, payment_key_unconfirmed) until a registry controller approves the new address; the
        previous one then becomes `abandoned`. Approving an active key changes nothing.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: The keys after approval, content: { application/json: { schema: { type: object, properties: { device_id: { type: string }, operation_id: { type: string }, data: { type: array, items: { $ref: "#/components/schemas/PaymentKey" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/payment-handovers:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: handOverPaymentBalance
      summary: Before replacing a working module, move its payment balance to the owner address provisioned on the device
      description: >-
        The module's active payment key signs one transferWithAuthorization to the owner sweep address
        provisioned on the device (tlay_payment_config_t.owner_sweep_address, reported in its signed auth
        body; capability owner_handover). The payee is fixed on the device: the platform cannot redirect
        it. Refunds still due to the address are withdrawn first, and agreements whose refund would land
        on it keep the handover open. Follow the operation (result.phase: withdrawing, sweeping,
        waiting_for_agreements, completed); then replace the module. One handover at a time (409).
        docs/design/PAYMENT_KEY_ROTATION.md D6.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }

  /devices/{device_id}/key-rotations:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [devices]
      operationId: rotateKey
      summary: Request key rotation; old keys remain verifiable for historic evidence (GEN-11)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [purpose]
              properties:
                purpose:
                  enum: [evidence, transport, payment]
                  description: >-
                    payment: the device proves the new key with the old one (EIP-712 PaymentKeyRotation); the new key
                    is active at once and the old key RETIRES: it finishes only its own agreements and authorisations,
                    its balance and refunds are swept to the device's own new address, and it is erased when nothing
                    is left (docs/design/PAYMENT_KEY_ROTATION.md). Needs device capability payment_key_rotation
                    (422 otherwise) and no retiring key (409). Follow the operation: result.phase, result.obligations.
                mode:
                  enum: [planned, compromised]
                  default: planned
                  description: >-
                    payment only. compromised: the old key's unsubmitted authorisations are not submitted and are
                    cancelled on-chain (cancelAuthorization, signed by the old key on the device), actions signed by
                    the old key are no longer relayed, and result.residual_risk states what cannot be prevented, in numbers.
                revoke_previous: { type: boolean, default: false, description: "true = compromise; historic evidence stays verifiable but flagged" }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }

  /devices/{device_id}/properties:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [data]
      operationId: getProperties
      summary: Latest REPORTED state with freshness, plus pending desired values (kept separate)
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/PropertyState" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/desired-properties:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    patch:
      tags: [data]
      operationId: setDesiredProperties
      summary: Request a change of writable properties
      description: |
        Properties with `side_effect: physical` are converted into an Invocation of their `set_via_action` and go
        through the same permit, limits and recovery path (GEN-13); the response then contains `invocation_id`.
        Reported state changes only when the device reports it.
        Non-physical writable properties become a desired change (`kind: desired_change`) with an `operation_id`.
        It is delivered to the device with a permit (action "$desired"), again after every reconnect until the
        device application answers. The operation then succeeds (applied) or fails with the application's reason.
        A newer value for the same property supersedes an unfinished older change (its operation fails as a conflict).
        Every property is validated first: an invalid one refuses the whole request, and nothing is changed.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [properties]
              properties:
                properties: { $ref: "#/components/schemas/Fields" }
                if_resource_version: { type: integer, description: Optimistic concurrency on the property state }
                authorization_ref: { type: string }
                external_ref: { $ref: "#/components/schemas/ExternalRef" }
      responses:
        "202":
          description: Accepted
          content:
            application/json:
              schema:
                type: object
                required: [changes]
                properties:
                  changes:
                    type: array
                    items:
                      type: object
                      required: [property, kind, state]
                      properties:
                        property: { type: string }
                        kind: { enum: [desired_change, invocation] }
                        change_id: { type: string }
                        invocation_id: { type: string }
                        state: { type: string }
        default: { $ref: "#/components/responses/Error" }

  /devices/{device_id}/invocations:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    post:
      tags: [invocations]
      operationId: createInvocation
      summary: Create one scoped action request
      description: |
        Checks authentication, product version, schema, grant/agreement, parameter limits, concurrency and rate limits,
        then durably accepts. `202` means accepted — not executed. If the action `requires_agreement`, an active agreement
        is mandatory; no client flag (e.g. `paid=true`) can replace it. Cancelling and re-creating cannot bypass
        concurrency or budget limits.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/InvocationCreate" } } }
      responses:
        "202":
          description: Accepted
          headers: { Location: { schema: { type: string } } }
          content: { application/json: { schema: { $ref: "#/components/schemas/Invocation" } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [invocations]
      operationId: listInvocations
      summary: List invocations of a device
      parameters: [{ $ref: "#/components/parameters/Cursor" }, { $ref: "#/components/parameters/Limit" }, { name: state, in: query, schema: { $ref: "#/components/schemas/InvocationState" } },
                   { name: order, in: query, schema: { enum: [asc, desc], default: asc }, description: "asc: oldest first; desc: newest first" }]
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/InvocationPage" } } } }
        default: { $ref: "#/components/responses/Error" }
  /invocations/{invocation_id}:
    parameters: [{ $ref: "#/components/parameters/InvocationId" }]
    get:
      tags: [invocations]
      operationId: getInvocation
      summary: Acceptance, execution, result, device receipt source, evidence and enforcement points
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Invocation" } } } }
        default: { $ref: "#/components/responses/Error" }
  /invocations/{invocation_id}/cancellations:
    parameters: [{ $ref: "#/components/parameters/InvocationId" }]
    post:
      tags: [invocations]
      operationId: cancelInvocation
      summary: Request cancellation (never forges a terminal state)
      description: The invocation moves to `cancel_requested`; only the device application confirming it stopped makes it `cancelled`. On an `unknown` invocation the request is recorded and the state stays `unknown` until the device answers. A device that never received the invoke reports it `cancelled` (reason `not_received`) and refuses it from then on. Pending cancellations are sent again at each device connection. Non-cancellable → `422 unsupported_capability`.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { reason: { type: string, maxLength: 200 } } } } }
      responses:
        "202": { description: Cancellation requested, content: { application/json: { schema: { $ref: "#/components/schemas/Invocation" } } } }
        default: { $ref: "#/components/responses/Error" }

  /devices/{device_id}/events:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }]
    get:
      tags: [data]
      operationId: listDeviceEvents
      summary: List authorised device events
      parameters:
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
        - { name: order, in: query, schema: { enum: [asc, desc], default: asc }, description: "asc: oldest first; desc: newest first" }
        - { name: name, in: query, schema: { type: string } }
        - { name: since, in: query, schema: { $ref: "#/components/schemas/Time" } }
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/DeviceEventPage" } } } }
        default: { $ref: "#/components/responses/Error" }
  /devices/{device_id}/meters/{meter}:
    parameters: [{ $ref: "#/components/parameters/DeviceId" }, { name: meter, in: path, required: true, schema: { type: string } }]
    get:
      tags: [data]
      operationId: getMeter
      summary: Normalised totals with quality flags and references to raw signed samples
      parameters:
        - { name: from, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: to, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: session_id, in: query, schema: { type: string } }
        - { name: agreement_id, in: query, schema: { type: string }, description: "Only this agreement's runs, each summed on its own (as for settlement)" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/MeterReading" } } } }
        default: { $ref: "#/components/responses/Error" }

  /grants:
    get:
      tags: [grants]
      operationId: listGrants
      summary: Grants this application gave or received (tenant admins see all)
      parameters:
        - { name: role, in: query, schema: { enum: [grantor, grantee] } }
        - { name: kind, in: query, schema: { enum: [access, funds] } }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/Grant" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [grants]
      operationId: createGrant
      summary: Delegate device scope, actions and (separately) funds to an application or agent
      description: Access and funds are distinct scopes; viewing a device never implies invoking it, and invoking never implies paying.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/GrantCreate" } } }
      responses:
        "201": { description: Created, content: { application/json: { schema: { $ref: "#/components/schemas/Grant" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}:
    parameters: [{ name: grant_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [grants]
      operationId: getGrant
      summary: Get a grant
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Grant" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}/buyer-signatures:
    parameters: [{ name: grant_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [grants]
      operationId: signFundsGrant
      summary: The payer's EIP-712 FundsGrant signature (EOA or ERC-1271 wallet) activates an application funds grant
      description: Until then the grant is `requires_buyer_signature` and authorises nothing. The typed data to sign is in the grant (`typed_data`).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [signature], properties: { signature: { type: string, description: 0x-hex signature } } } } }
      responses:
        "200": { description: Active, content: { application/json: { schema: { $ref: "#/components/schemas/Grant" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}/renewals:
    parameters: [{ name: grant_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [grants]
      operationId: renewGrant
      summary: The same funds grant for as long again (or `days`), from now
      description: >-
        grants:write. An application's renewal waits for the payer's signature like any funds grant and, once signed,
        replaces the grant it renews (that one is revoked, `replaced_by` names the renewal; what it bought stays). A
        device's renewal is in force at once. A recurring budget's renewal keeps its periods (same period_start) and
        counts what the renewed grant spent in the period they share; its max_total is max_per_period times the periods
        it touches. One renewal waits at a time: asking again returns it. 409 for a revoked grant, one that waits for
        its own signature, or one already replaced.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { days: { type: integer, minimum: 1, maximum: 365, description: "Default: as long as the renewed grant was" } } } } }
      responses:
        "201": { description: The renewal, content: { application/json: { schema: { $ref: "#/components/schemas/Grant" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}/asks:
    parameters: [{ name: grant_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [grants]
      operationId: askForMoreBudget
      summary: The application a funds grant belongs to (an AI agent) asks its organisation for a larger budget, and says why
      description: >-
        commerce:buy, by the grant's own grantee application only. One open ask a grant: asking again replaces it. The
        organisation's people are told (notification budget.asked, at most once a day per grant); they answer with a new
        grant for the payer to sign (POST /grants with `answers_ask`) or decline it. The grant's `ask` says which.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [max_total, reason]
              properties:
                max_total: { $ref: "#/components/schemas/Uint", description: The budget in all it asks for (atomic units of the grant's asset) }
                max_per_tx: { $ref: "#/components/schemas/Uint", description: "The most per purchase it asks for; default: the grant's, or max_total if that is less" }
                days: { type: integer, minimum: 1, maximum: 365, default: 30 }
                reason: { type: string, minLength: 1, maxLength: 500, description: What the budget is for, in a sentence or two }
      responses:
        "201": { description: Asked, content: { application/json: { schema: { $ref: "#/components/schemas/BudgetAsk" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}/asks/{ask_id}/declines:
    parameters:
      - { name: grant_id, in: path, required: true, schema: { type: string } }
      - { name: ask_id, in: path, required: true, schema: { type: string } }
    post:
      tags: [grants]
      operationId: declineBudgetAsk
      summary: The organisation declines what its agent asked for (grants:write)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Declined, content: { application/json: { schema: { $ref: "#/components/schemas/BudgetAsk" } } } }
        default: { $ref: "#/components/responses/Error" }
  /grants/{grant_id}/revocations:
    parameters: [{ name: grant_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [grants]
      operationId: revokeGrant
      summary: Revoke future use; past deliveries and funding obligations are unaffected
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { $ref: "#/components/schemas/Grant" } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-offerings:
    post:
      tags: [commerce]
      operationId: createServiceOffering
      summary: Map device capabilities to a purchasable service
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOfferingCreate" } } }
      responses:
        "201": { description: Created, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [commerce]
      operationId: listServiceOfferings
      summary: Offerings the caller may purchase
      parameters:
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
        - { name: device_id, in: query, schema: { type: string } }
        - { name: archived, in: query, schema: { enum: ["false", "true", all], default: "false" }, description: Archived services are left out unless asked for }
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOfferingPage" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-offerings/{offering_id}:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [commerce]
      operationId: getServiceOffering
      summary: One of the organisation's services, with its versions and sales
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [commerce]
      operationId: updateServiceOffering
      summary: The name and what buyers read (summary, description, tags, image), listed or not; never the terms
      description: Requires `commerce:operate`. The terms (price, limits, payees) change by publishing a version. "" clears a text field.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, properties: {
          name: { type: string, minLength: 2, maxLength: 80 }, summary: { type: string, maxLength: 280 }, description: { type: string, maxLength: 4000 },
          tags: { type: array, maxItems: 8, items: { type: string, pattern: "^[a-z0-9][a-z0-9-]{0,31}$" } }, image_url: { type: string, maxLength: 500, description: An https address },
          availability: { oneOf: [{ $ref: "#/components/schemas/Availability" }, { type: "null" }], description: "When other organisations can order it; null: at any time" },
          show_record: { type: boolean, description: "Show buyers the machine's record (GET /devices/{device_id}/record); shown unless set to false" } } } } }
      responses:
        "200": { description: Changed, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-offerings/{offering_id}/archive:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: archiveServiceOffering
      summary: No longer offered (unlisted, no new quote); its orders and history stay
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Archived, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [commerce]
      operationId: restoreServiceOffering
      summary: Offer it again (it stays unlisted until listed)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Restored, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-offerings/{offering_id}/versions:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: publishServiceOfferingVersion
      summary: Publish new terms; they apply to new agreements only (GEN-31)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/ServiceTerms" } } }
      responses:
        "201": { description: Published, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceOffering" } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-offerings/{offering_id}/price-changes:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: changeServiceOfferingPrice
      summary: A new price or largest quantity per order, on the service or every machine of its pool
      description: >-
        Publishes new terms with the regular price (per unit, or fixed) and/or the largest quantity per order changed,
        and nothing else; an off-peak price moves by the same share. On a machine of a pool, every machine still on the
        pool's terms changes alike in one transaction, and the pool keeps them. Recorded in `price_changes` with the
        facts the seller gives (a suggestion's, when it applies one). Orders already placed keep their terms.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                price_atomic: { $ref: "#/components/schemas/Uint" }
                max_quantity: { $ref: "#/components/schemas/Uint" }
                facts: { type: array, maxItems: 5, items: { type: string, maxLength: 200 } }
      responses:
        "201": { description: Published, content: { application/json: { schema: { $ref: "#/components/schemas/PriceChange" } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-offerings/{offering_id}/price-rule:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    put:
      tags: [commerce]
      operationId: setServiceOfferingPriceRule
      summary: Let the price follow demand, within a floor and a ceiling
      description: >-
        At most once a week, when the facts call for it (its machines ran 60% of the last week or more and three orders
        were paid since the last change, or buyers found every machine of its pool busy; or, a week or more after the
        last change, the machines ran under 20% and fewer than a quarter of five or more buyer wallets of two or more
        organisations that asked for a price paid), the platform publishes new terms one step up or down, never past
        the floor or the ceiling, and tells the seller's people (price.changed). On a machine of a pool the rule is the
        pool's. Only for a price per unit or a fixed price; the price now must be within the bounds. Setting it again
        replaces it.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [floor_atomic, ceiling_atomic]
              properties:
                floor_atomic: { $ref: "#/components/schemas/Uint" }
                ceiling_atomic: { $ref: "#/components/schemas/Uint" }
                step_percent: { type: integer, minimum: 2, maximum: 25, default: 10 }
      responses:
        "200": { description: The rule, content: { application/json: { schema: { $ref: "#/components/schemas/PriceRule" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [commerce]
      operationId: deleteServiceOfferingPriceRule
      summary: Stop the price following demand (the price stays where it is)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Deleted, content: { application/json: { schema: { type: object, properties: { deleted: { const: true } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-offerings/{offering_id}/price-proposals:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: proposeServiceOfferingPrice
      summary: An application proposes a new price or largest order, for a person to approve
      description: >-
        For an application of the seller (an agent running without a person at hand): nothing is published until a
        person of the organisation approves it (POST /price-proposals/{id}/approve); the people are told
        (price.proposed). A newer proposal for the same service or pool replaces an open one; it lapses after 7 days or
        when the price changes another way. A person changes the price directly instead (400 here).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                price_atomic: { $ref: "#/components/schemas/Uint" }
                max_quantity: { $ref: "#/components/schemas/Uint" }
                reason: { type: string, maxLength: 500 }
                facts: { type: array, maxItems: 5, items: { type: string, maxLength: 200 } }
      responses:
        "201": { description: Proposed, content: { application/json: { schema: { $ref: "#/components/schemas/PriceProposal" } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-requests/{request_id}/answer-drafts:
    parameters: [{ name: request_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: draftServiceRequestAnswer
      summary: An application drafts an answer to a buyer's request, for a person to send
      description: >-
        For an application of the seller: nothing is sent to the buyer until a person sends it (POST
        /drafts/{id}/send); the people are told (draft.ready). A person answers directly instead (400 here). An
        offer in it (a lower price for the wallet that asked) is the person's to make when they send it: no limit of
        the application bounds it here, only the list price.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [offering_id]
              properties:
                offering_id: { type: string }
                note: { type: string, maxLength: 280 }
                offer: { $ref: "#/components/schemas/OfferCreate" }
                reason: { type: string, maxLength: 500 }
      responses:
        "201": { description: Drafted, content: { application/json: { schema: { $ref: "#/components/schemas/Draft" } } } }
        default: { $ref: "#/components/responses/Error" }

  /disputes/{agreement_id}/message-drafts:
    parameters: [{ name: agreement_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: draftDisputeMessage
      summary: An application drafts a message in a dispute on the seller's order, for a person to send
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              properties:
                body: { type: string, minLength: 1, maxLength: 2000 }
                reason: { type: string, maxLength: 500 }
      responses:
        "201": { description: Drafted, content: { application/json: { schema: { $ref: "#/components/schemas/Draft" } } } }
        default: { $ref: "#/components/responses/Error" }

  /drafts:
    get:
      tags: [commerce]
      operationId: listDrafts
      summary: The organisation's drafts, newest first
      parameters:
        - { name: state, in: query, schema: { enum: [open, sent, discarded, replaced, lapsed] } }
        - { name: kind, in: query, schema: { enum: [request_answer, dispute_message] } }
        - { name: target_id, in: query, description: The request or the disputed order, schema: { type: string } }
        - { name: decided_since, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        "200": { description: Drafts, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/Draft" } } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /drafts/{draft_id}/send:
    parameters: [{ name: draft_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: sendDraft
      summary: A person sends a draft, as written or with their own text
      description: >-
        A person of the organisation with commerce:operate (not an application). It is then the person's answer or
        dispute message, exactly as if written in the operator app. 409 when it is no longer open, or when its request
        or dispute is over (it lapses).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { body: { type: string, maxLength: 2000, description: The text to send instead of the draft's } } } } }
      responses:
        "200": { description: Sent, content: { application/json: { schema: { type: object, properties: { draft: { $ref: "#/components/schemas/Draft" }, sent: { type: object } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /drafts/{draft_id}/discard:
    parameters: [{ name: draft_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: discardDraft
      summary: A person discards a draft, with a note the application reads
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { note: { type: string, maxLength: 500 } } } } }
      responses:
        "200": { description: Discarded, content: { application/json: { schema: { $ref: "#/components/schemas/Draft" } } } }
        default: { $ref: "#/components/responses/Error" }

  /price-proposals:
    get:
      tags: [commerce]
      operationId: listPriceProposals
      summary: The organisation's price proposals, newest first
      parameters:
        - { name: state, in: query, schema: { enum: [open, approved, declined, replaced, lapsed] } }
        - { name: decided_since, in: query, description: Only those decided after this time (an agent reading its answers), schema: { $ref: "#/components/schemas/Time" } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        "200": { description: Proposals, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/PriceProposal" } } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /price-proposals/{proposal_id}/approve:
    parameters: [{ name: proposal_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: approvePriceProposal
      summary: A person approves a proposal; it is published exactly as proposed
      description: >-
        A person of the organisation with commerce:operate (not an application). Recorded as the application's price
        change, approved by that person. 409 when it is no longer open (reason proposal_<state>) or the price changed
        since it was proposed (price_moved; it lapses).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Approved and published, content: { application/json: { schema: { type: object, properties: { proposal: { $ref: "#/components/schemas/PriceProposal" }, change: { $ref: "#/components/schemas/PriceChange" } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /price-proposals/{proposal_id}/decline:
    parameters: [{ name: proposal_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: declinePriceProposal
      summary: A person declines a proposal, with a note the application reads
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { note: { type: string, maxLength: 500 } } } } }
      responses:
        "200": { description: Declined, content: { application/json: { schema: { $ref: "#/components/schemas/PriceProposal" } } } }
        default: { $ref: "#/components/responses/Error" }

  /price-changes/{change_id}/put-back:
    parameters: [{ name: change_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [commerce]
      operationId: putBackPriceChange
      summary: A person puts back a price an application changed on its own
      description: >-
        Requires `commerce:operate` and a person's sign-in (an application cannot). Only a change an application made
        on its own (not an approved proposal), while it is still the newest change of the service or pool and its
        version still stands: the price and largest order of the version before it are published again, as the
        seller's change. The application's change records who put it back, when and the note; its record counts it
        (GET /applications/self/record), and when a person put back some of its last ten changes the record suggests
        holding its prices back. 409 with details.reason not_application, put_back or changed_since.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { note: { type: string, maxLength: 500, description: Why; the application reads it } } } } }
      responses:
        "200":
          description: Put back
          content:
            application/json:
              schema:
                type: object
                properties:
                  put_back: { $ref: "#/components/schemas/PriceChange" }
                  change: { $ref: "#/components/schemas/PriceChange" }
        default: { $ref: "#/components/responses/Error" }

  /service-offerings/{offering_id}/listing:
    parameters: [{ name: offering_id, in: path, required: true, schema: { type: string } }]
    put:
      tags: [commerce]
      operationId: setServiceOfferingListing
      summary: List an offering in the marketplace catalog (or take it out)
      description: >-
        Requires `commerce:operate` in the seller's organisation. A public offering can be found and quoted by any
        organisation's applications (docs/design/MARKETPLACE.md); a purchase then belongs to both organisations.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [visibility]
              properties:
                visibility: { enum: [public, private] }
                summary: { type: string, maxLength: 280 }
                description: { type: string, maxLength: 4000 }
                tags: { type: array, maxItems: 8, items: { type: string, pattern: "^[a-z0-9][a-z0-9-]{0,31}$" } }
                image_url: { type: string, maxLength: 500 }
                availability: { oneOf: [{ $ref: "#/components/schemas/Availability" }, { type: "null" }], description: "When other organisations can order it; null: at any time" }
                show_record: { type: boolean, description: "Show buyers the machine's record (GET /devices/{device_id}/record); shown unless set to false" }
      responses:
        "200": { description: Stored, content: { application/json: { schema: { type: object, properties: { offering_id: { type: string }, listing: { $ref: "#/components/schemas/Listing" } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /marketplace/offerings:
    get:
      tags: [commerce]
      operationId: listMarketplaceOfferings
      summary: The catalog of every organisation's publicly listed offerings, cheapest first
      description: >-
        Requires `commerce:read`. Shows the current terms and, of the device, only its product, whether it is online,
        its security verdict and its registry status.
      parameters:
        - { name: offering_id, in: query, schema: { type: string }, description: Only this offering (empty when it is not listed) }
        - { name: device_id, in: query, schema: { type: string }, description: "Only what this device sells: everything a machine offers, e.g. for a label on it" }
        - { name: organization_id, in: query, schema: { type: string }, description: "Only what this seller lists: its page in a shop" }
        - { name: action, in: query, schema: { type: string } }
        - { name: template, in: query, schema: { type: string } }
        - { name: asset, in: query, schema: { $ref: "#/components/schemas/Caip19" } }
        - { name: tag, in: query, schema: { type: string } }
        - { name: text, in: query, schema: { type: string }, description: "Case-insensitive match in the name, summary, description, tags and the machine's place" }
        - { name: max_unit_price_atomic, in: query, schema: { $ref: "#/components/schemas/Uint" } }
        - { name: online, in: query, schema: { enum: ["true"] } }
        - { name: available, in: query, schema: { enum: ["now"] }, description: "Only what can be ordered now (inside its seller's hours, its machine not paused)" }
        - { name: security, in: query, schema: { enum: [meets, fails, not_reported, no_policy] } }
        - { name: pool_id, in: query, schema: { type: string }, description: "Each machine of this pool. Without it (and without offering_id or device_id) a pool is one entry, shown by one of its machines (a free one when there is one), with `pool`" }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/CatalogEntry" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /marketplace/watches:
    get:
      tags: [commerce]
      operationId: listOpeningWatches
      summary: Every service this storefront's wallet waits to be told about, newest first
      description: >-
        Requires `commerce:buy`. What each watch waits for, since when and until when it lasts (30 days from when it was
        last put), and the price
        an order placed now pays (the off-peak one in its hours), so a price watch shows how far it is.
      parameters:
        - { name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        offering_id: { type: string }
                        name: { type: string }
                        listed: { type: boolean }
                        when: { enum: [open, online, off_peak, price] }
                        at_most_atomic: { type: string, description: "when: price: the price it waits for" }
                        asset: { type: string }
                        price_now_atomic: { type: string, description: "The price an order placed now pays; absent for a price quoted per order" }
                        unit: { type: string, description: "Pay-for-what-you-use: what the price is per" }
                        template: { type: string }
                        created_at: { type: string, format: date-time }
                        ends_at: { type: string, format: date-time }
        default: { $ref: "#/components/responses/Error" }
  /marketplace/offerings/{offering_id}/watches/{address}:
    parameters:
      - { name: offering_id, in: path, required: true, schema: { type: string } }
      - { name: address, in: path, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
    get:
      tags: [commerce]
      operationId: getOpeningWatch
      summary: Whether this storefront's wallet waits to be told when a listed service opens for orders
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/OpeningWatch" } } } }
        default: { $ref: "#/components/responses/Error" }
    put:
      tags: [commerce]
      operationId: watchOpening
      summary: Tell this wallet (a notification, emailed at a confirmed address) when the service can be ordered again; once
      description: >-
        Requires `commerce:buy`. At most 20 services per wallet at a time. The watch ends when it was told, 30 days after
        it was put (putting it again starts the 30 days again), or when the service is taken down or its new terms leave
        nothing to wait for; a watch that ends untold tells the wallet so, once (`service.watch_ended`). `when: online` waits also for the machine to be connected (a buyer at a machine that is
        offline); `when: off_peak` waits for the service's off-peak price to be in force while it can be ordered (refused
        with `conflict` when its terms have no off-peak price; the watch ends if new terms drop it); `when: price`
        waits for the price an order placed now pays (the off-peak one in its hours) to be at or below `at_most_atomic`
        while it can be ordered, told as `service.price` (refused with `conflict`, reason `no_price`, for a price quoted
        per order, and reason `already` when it can be ordered at that price now; the watch ends if new terms are in
        another asset). A new version of the service looks at its price watches at once. Putting it again changes
        what it waits for.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                when: { enum: [open, online, off_peak, price], default: open }
                at_most_atomic: { type: string, pattern: "^[0-9]{1,78}$", description: "With when: price only: the price to wait for, in the service's asset's smallest unit (per unit, per order or per period, as the service is priced)" }
      responses:
        "200": { description: Watching, content: { application/json: { schema: { $ref: "#/components/schemas/OpeningWatch" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [commerce]
      operationId: unwatchOpening
      summary: Stop waiting
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Not watching, content: { application/json: { schema: { $ref: "#/components/schemas/OpeningWatch" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-requests:
    post:
      tags: [commerce]
      operationId: createServiceRequest
      summary: Ask for a machine no service offers yet, for one of this storefront's wallets
      description: >-
        Requires `commerce:buy`. One line of text (3..280 characters), optionally where and which kind of order. Every
        seller sees it (GET without address), never which wallet or storefront asked, and can answer with a service of
        its own listed in the market; the wallet is then told (notification `request.answered`). A request ends after
        30 days or when its wallet closes it. A wallet has at most 5 open requests and asks at most 3 times a day
        (`conflict`, details.reason `too_many_open` / `too_many_today`).

        With `offering_id`, the request is about that service: the buyer asks its seller for a lower price (the text may
        be left out: "Could you offer me a lower price?"). Only that seller sees it, and its people are told at once
        (notification `request.asked`); it answers with that service, with an offer or without. The service is listed
        and priced per unit or at a fixed price (else `invalid_argument`); one open request per wallet and service
        (`conflict`, details.reason `already_asked`). While it is open, a new version of the service at a lower price
        tells the wallet (notification `request.lowered`, once a version); an offer made on it ends with that version.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [address, text]
              properties:
                address: { $ref: "#/components/schemas/EvmAddress" }
                text: { type: string, minLength: 3, maxLength: 280, description: Required unless offering_id is given }
                place: { type: string, maxLength: 80 }
                kind: { enum: [metered_service_escrow, access_lease, access_subscription] }
                offering_id: { type: string, description: The service the request is about, asked of its seller alone }
      responses:
        "201": { description: Asked, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceRequest" } } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [commerce]
      operationId: listServiceRequests
      summary: With address, that wallet's requests and their answers; without, every open request in the market
      description: >-
        With `address` (requires `commerce:buy`): this storefront's wallet's requests of the last 90 days, newest first,
        each with the answers sellers gave. Without (requires `commerce:read`): every storefront's open requests, newest
        first, with how many answers each has and the service this organisation answered with; never who asked. A
        request about one service (`about`) is listed to that service's seller alone.
      parameters:
        - { name: address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { name: q, in: query, description: Text or place contains this, schema: { type: string, maxLength: 100 } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        "200":
          description: OK
          content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/ServiceRequest" } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-requests/{request_id}:
    delete:
      tags: [commerce]
      operationId: closeServiceRequest
      summary: Close a wallet's request (it found what it wanted); sellers no longer see it
      parameters:
        - { name: request_id, in: path, required: true, schema: { type: string } }
        - { name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { $ref: "#/components/parameters/IdempotencyKey" }
      responses:
        "200": { description: Closed, content: { application/json: { schema: { $ref: "#/components/schemas/ServiceRequest" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-requests/{request_id}/answers:
    post:
      tags: [commerce]
      operationId: answerServiceRequest
      summary: Answer an open request with one of this organisation's services listed in the market
      description: >-
        Requires `commerce:operate`. Once per organisation and request (`conflict`, details.reason `already`); a
        request takes at most 10 answers (`full`), an organisation gives at most 50 a day (`too_many_today`). The
        wallet that asked is told at once, with the note. A request about one service (`about`) is answered by that
        service's seller alone (`not_found` for others), with that service (`invalid_argument`, details.offering_id).


        `offer`: a price for the wallet that asked only, below the service's list price (400 otherwise, details
        list_price_atomic), on a service with a price per unit or a fixed price, until valid_days from now (default
        7). That wallet orders at it from the storefront it asked from (POST /quotes with request_id), one order at a
        time; a new version of the service ends it. An application whose prices are held (prices: propose) drafts
        the offer instead (403, details.reason needs_approval); one held to a step or a band offers at most that share
        below the list price (the step) or the price a person last set (the band): 403, details.reason price_step or
        price_band, with lowest_atomic.
      parameters:
        - { name: request_id, in: path, required: true, schema: { type: string } }
        - { $ref: "#/components/parameters/IdempotencyKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [offering_id], properties: { offering_id: { type: string }, note: { type: string, maxLength: 280 }, offer: { $ref: "#/components/schemas/OfferCreate" } } }
      responses:
        "201":
          description: Answered
          content:
            application/json:
              schema:
                type: object
                properties:
                  request_id: { type: string }
                  offering_id: { type: string }
                  note: { type: string }
                  offer: { type: object, properties: { price_atomic: { $ref: "#/components/schemas/Uint" }, list_price_atomic: { $ref: "#/components/schemas/Uint" }, expires_at: { $ref: "#/components/schemas/Time" } } }
                  answered_at: { type: string, format: date-time }
        default: { $ref: "#/components/responses/Error" }
  /quote-bundles:
    post:
      tags: [commerce]
      operationId: createQuoteBundle
      summary: Quote several escrowed offerings (of any organisations) as one purchase that starts all-or-nothing
      description: >-
        Requires `commerce:buy`. 2..8 parts, all `metered_service_escrow`, one network and asset. Accept with
        POST /agreements {bundle_id}; fund each part. No part starts until every part is funded; a part never funded
        keeps the others from starting and every funded part refunds itself in full at its start deadline.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [parts, buyer]
              properties:
                parts:
                  type: array
                  minItems: 2
                  maxItems: 8
                  items: { type: object, required: [offering_id, quantity], properties: { offering_id: { type: string }, quantity: { $ref: "#/components/schemas/Uint" }, max_amount_atomic: { $ref: "#/components/schemas/Uint" } } }
                buyer: { type: object, required: [address], properties: { address: { $ref: "#/components/schemas/EvmAddress" } } }
                grant_id: { type: string }
                max_total_atomic: { $ref: "#/components/schemas/Uint" }
      responses:
        "201": { description: Quoted, content: { application/json: { schema: { $ref: "#/components/schemas/Bundle" } } } }
        default: { $ref: "#/components/responses/Error" }
  /bundles/{bundle_id}:
    parameters: [{ name: bundle_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [commerce]
      operationId: getBundle
      summary: Where a bundle stands (buyer's organisation)
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Bundle" } } } }
        default: { $ref: "#/components/responses/Error" }

  /service-pools:
    get:
      tags: [commerce]
      operationId: listPools
      summary: The organisation's machine pools, each machine and what it can take now
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/Pool" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [commerce]
      operationId: createPool
      summary: Sell one service from several identical machines
      description: >-
        Requires `commerce:operate`. 2..100 of the organisation's services, one per machine, each in one pool at most,
        alike in product and terms (all but the machine and its payees; 400 reason terms_differ names the one that is
        not). Not for services priced by their operator per quote. Buyers then quote the pool (POST /quotes {pool_id})
        and the platform assigns a free machine; the catalog shows the pool once.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, offering_ids]
              properties:
                name: { type: string, minLength: 2, maxLength: 80 }
                summary: { type: string, maxLength: 280 }
                offering_ids: { type: array, minItems: 2, maxItems: 100, items: { type: string } }
      responses:
        "201": { description: Created, content: { application/json: { schema: { $ref: "#/components/schemas/Pool" } } } }
        default: { $ref: "#/components/responses/Error" }
  /service-pools/{pool_id}:
    parameters: [{ name: pool_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [commerce]
      operationId: getPool
      summary: A machine pool, each machine and what it can take now
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Pool" } } } }
        default: { $ref: "#/components/responses/Error" }
    patch:
      tags: [commerce]
      operationId: updatePool
      summary: Rename a pool, or replace its machines (offering_ids is the whole new set)
      description: Requires `commerce:operate`. The same rules as creating one.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, minLength: 2, maxLength: 80 }
                summary: { type: [string, "null"], maxLength: 280 }
                offering_ids: { type: array, minItems: 2, maxItems: 100, items: { type: string } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Pool" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [commerce]
      operationId: deletePool
      summary: Dissolve a pool; each machine's service stays, sold on its own
      description: Requires `commerce:operate`. Orders already placed are not touched.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Deleted, content: { application/json: { schema: { type: object, properties: { id: { type: string }, deleted: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /quotes:
    post:
      tags: [commerce]
      operationId: createQuote
      summary: A binding quote (price may be computed by the operator's own platform and submitted signed), or an estimate
      description: >-
        A machine that is retired, suspended or revoked (403, details.reason device_suspended / device_revoked), or
        that fails its product's security policy where that refuses commerce, is not quoted; the order (POST
        /agreements) checks it again.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/QuoteCreate" } } }
      responses:
        "201": { description: Quote, content: { application/json: { schema: { $ref: "#/components/schemas/Quote" } } } }
        "200": { description: "Estimate (estimate: true): the Quote's fields without id and expires_at, plus unit_price_atomic for a metered service", content: { application/json: { schema: { $ref: "#/components/schemas/Quote" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements:
    get:
      tags: [commerce]
      operationId: listAgreements
      summary: Agreement summaries from the platform's records (no chain reads; GET /agreements/{id} for funds and chain state)
      parameters:
        - { name: device_id, in: query, schema: { type: string } }
        - { name: state, in: query, schema: { type: string }, description: "One state, or several separated by commas (ready,active)" }
        - { name: grant_id, in: query, schema: { type: string } }
        - { name: offering_id, in: query, schema: { type: string }, description: Only orders of this service }
        - { name: external_ref, in: query, schema: { type: string }, description: The customer reference given when the agreement was created }
        - { name: created_after, in: query, schema: { $ref: "#/components/schemas/Time" }, description: Created at or after this time }
        - { name: created_before, in: query, schema: { $ref: "#/components/schemas/Time" }, description: Created before this time }
        - { name: q, in: query, schema: { type: string, maxLength: 100 }, description: "Words found in the order id, the buyer's address, the customer reference or the service's name (case-insensitive)" }
        - { name: order, in: query, schema: { enum: [asc, desc], default: asc }, description: "asc: oldest first; desc: newest first. A cursor continues in the order it was made with" }
        - { name: buyer_address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" }, description: Only the agreements this address pays for }
        - { name: side, in: query, schema: { enum: [sold, bought] }, description: "Only this organisation's sales (it is the seller), or only its purchases (it is the buyer); both by default" }
        - { name: needs_provider_signature, in: query, schema: { enum: ["true"] }, description: "Only this organisation's orders waiting for its service provider's signature over the terms (a provider key the platform does not hold); GET /agreements/{id} has the typed data to sign" }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/AgreementSummary" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [commerce]
      operationId: createAgreement
      summary: Accept a quote → agreement / order (buyer or legitimate delegate); or a bundle → one agreement per part
      description: >-
        With `bundle_id` (POST /quote-bundles) instead of `quote_id`, one agreement is created per part and the Bundle
        is returned. A quote of another organisation's listed offering gives an agreement both organisations see.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                quote_id: { type: string }
                bundle_id: { type: string }
                buyer: { $ref: "#/components/schemas/Party" }
                grant_ref: { type: string, description: Delegation under which a delegate/agent accepts }
                external_ref: { $ref: "#/components/schemas/ExternalRef" }
                acceptance_rule: { $ref: "#/components/schemas/AcceptanceRule" }
      responses:
        "201": { description: Created, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    get:
      tags: [commerce]
      operationId: getAgreement
      summary: Rights, execution, evidence and funds status (separate dimensions)
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/evidence:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    get:
      tags: [evidence]
      operationId: listAgreementEvidence
      summary: The order's signed device records, each as a bundle for independent verification
      description: >-
        For the order's seller and its buyer alike (a buyer sees only its own orders' records, without
        owning the device). Each item is the same EvidenceBundle as `GET /evidence/{evidence_id}/bundle`,
        so `mce evidence verify` and the shop's in-browser check read it unchanged. Oldest first.
      parameters:
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { type: object, required: [data], properties: { data: { type: array, items: { $ref: "#/components/schemas/EvidenceBundle" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/funding-intents:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [payments]
      operationId: createFundingIntent
      summary: A constrained funding intent (structured EIP-712 payload to sign; payee is the agreement contract)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                payer: { $ref: "#/components/schemas/EvmAddress" }
                signed_authorization: { $ref: "#/components/schemas/Eip712Authorization", description: "Optional: submit the buyer's signature in the same call" }
      responses:
        "201": { description: Intent, content: { application/json: { schema: { $ref: "#/components/schemas/FundingIntent" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/verifier-signatures:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: addVerifierSignature
      summary: A verifier-committee member co-signs the pending start or delivery proposal (verification template "committee")
      description: >-
        For an escrow whose verifier is a VerifierCommittee (acceptance.verifier_committee), the platform
        verifier signs its part of the start and of the delivery proposal and waits for the other members;
        `verification.pending` on the agreement carries the kind, digest and EIP-712 typed data to sign
        (members should check the evidence bundle first). Once the members' signatures reach the threshold the
        platform submits the transaction. A signature by a non-member is refused (403). If the committee never
        reaches the threshold, the escrow's deadlines refund the buyer.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [kind, signature], properties: {
          kind: { enum: [start, delivery] }, digest: { type: string, description: The pending digest the member checked (refused if it changed) },
          signature: { type: string, pattern: "^0x[0-9a-fA-F]{130}$" } } } } }
      responses:
        "201": { description: The agreement with its verification state, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/provider-signatures:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: addProviderSignature
      summary: The service provider's EIP-712 signature over the agreement's on-chain terms (when the platform does not hold a provider signer)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [signature], properties: { signature: { type: string, pattern: "^0x[0-9a-fA-F]{130}$" } } } } }
      responses:
        "201": { description: Signature recorded, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/acceptances:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: acceptDelivery
      summary: Explicitly accept (or propose, if verifier) a submitted delivery
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [delivered_quantity, evidence_refs]
              properties:
                delivered_quantity: { $ref: "#/components/schemas/Uint" }
                evidence_refs: { type: array, items: { type: string } }
                role: { enum: [buyer, verifier] }
                signature: { $ref: "#/components/schemas/Eip712Authorization", description: "The buyer's EIP-712 BuyerAction (action 1) returned as typed_data by a first call without signature; relayed, checked by the contract" }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/finish:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: finishAgreement
      summary: The buyer finishes a metered order now, with what was delivered so far (0 when nothing ran)
      description: >-
        For a paid metered order (ready or active) with no run still going. No run starts afterwards. The platform
        proposes the delivery so far at its next pass (state awaiting_acceptance); the buyer accepts it at once or
        lets the challenge period run, and the rest is refunded. Without it, an unused order is refunded only after
        its delivery deadline. execution.finish_requested_at records it.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Finishing, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/acceptance-rule:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    put:
      tags: [commerce]
      operationId: setAcceptanceRule
      summary: The buyer says what counts as a good delivery of a metered order (an empty rule removes it)
      description: >-
        By the application that bought it (commerce:buy), before the order settles. When the delivery is proposed
        the platform checks it against the rule: the order's `acceptance` says whether it meets the rule and, if
        not, a dispute reason; the delivery notice says the same. The buyer's own client then accepts or disputes
        with the payer's key: a rule never signs anything by itself. Also settable at POST /agreements.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/AcceptanceRule" } } }
      responses:
        "200": { description: Set, content: { application/json: { schema: { $ref: "#/components/schemas/Agreement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/proofs:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    get:
      tags: [commerce]
      operationId: listProofs
      summary: The public proof links the caller's side of the order made (a storefront, with address, one wallet's)
      parameters:
        - { name: address, in: query, required: false, schema: { type: string, pattern: "^0x[0-9a-fA-F]{40}$" }, description: "A storefront's buyer wallet: only the links it asked for" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, required: [data], properties: { data: { type: array, items: { $ref: "#/components/schemas/ProofLink" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [commerce]
      operationId: createProof
      summary: Make a link anyone can open to this settled order's receipt and its device's signed records
      description: >-
        By either side of the order, with commerce:buy or commerce:operate: its buyer (a storefront names the
        wallet that paid with `address`; the link then also ends when that wallet signs out of the storefront on
        every device) or its seller (the link does not show the buyer's wallet). The link is the shop's
        `/proofs/{token}` page, or GET /proofs/{token} for a program. Never the run's inputs or results. Only a
        settled order (`not_settled` otherwise); at most 20 open links per side of an order (`too_many_links`).
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: {
          days: { type: integer, minimum: 1, maximum: 365, default: 90, description: How long the link opens },
          address: { type: string, pattern: "^0x[0-9a-fA-F]{40}$", description: "A storefront's buyer wallet: the order's payer" } } } } }
      responses:
        "201": { description: Made, content: { application/json: { schema: { $ref: "#/components/schemas/ProofLink" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/proofs/{proof_id}:
    parameters:
      - { $ref: "#/components/parameters/AgreementId" }
      - { name: proof_id, in: path, required: true, schema: { type: string, pattern: "^prf_[a-z0-9]+$" } }
    delete:
      tags: [commerce]
      operationId: revokeProof
      summary: Withdraw a public proof link (it stops opening at once)
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
        - { name: address, in: query, required: false, schema: { type: string, pattern: "^0x[0-9a-fA-F]{40}$" }, description: "A storefront's buyer wallet that made it" }
      responses:
        "200": { description: Withdrawn, content: { application/json: { schema: { $ref: "#/components/schemas/ProofLink" } } } }
        default: { $ref: "#/components/responses/Error" }
  /proofs/{token}:
    parameters: [{ name: token, in: path, required: true, schema: { type: string, pattern: "^[A-Za-z0-9_-]{43}$" } }]
    get:
      tags: [commerce]
      operationId: readProof
      summary: A public proof link's order, without credentials
      description: >-
        What one side of a settled order made public (POST /agreements/{id}/proofs): its receipt, the contract's
        transactions and the device's signed records as evidence bundles, each checkable offline (`mce evidence
        verify`) or in a browser. The buyer's wallet only where the buyer made the link. An unknown, ended or
        withdrawn link is `not_found`.
      security: []
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/PublicProof" } } } }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/cancellations:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: cancelAgreement
      summary: Cancel (buyer only) — escrow before start (full refund); lease ends early; subscription refunds the periods not started
      description: >-
        Without a signature, returns the typed data the buyer must sign: BuyerAction (action 3) for an escrow,
        LesseeAction (action 2) for a lease, SubscriberAction (action 2) for a subscription. With it, the platform relays.
        A cancelled subscription stays usable until its current (paid) period ends. An order not paid yet
        (`awaiting_funding`) is withdrawn at once without a signature: it becomes `cancelled` (operation `succeeded`);
        409 when its payment is already on its way.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content: { application/json: { schema: { type: object, properties: { signature: { $ref: "#/components/schemas/Eip712Authorization", description: "The buyer's EIP-712 BuyerAction / LesseeAction / SubscriberAction; relayed" } } } } }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }
  /agreements/{agreement_id}/disputes:
    parameters: [{ $ref: "#/components/parameters/AgreementId" }]
    post:
      tags: [commerce]
      operationId: openDispute
      summary: Open a dispute with evidence references
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, maxLength: 500 }
                evidence_refs: { type: array, items: { type: string } }
                signature: { $ref: "#/components/schemas/Eip712Authorization", description: "The buyer's EIP-712 BuyerAction (action 2, reasonHash = keccak256(reason)); relayed" }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }

  /provisioning-keys:
    get:
      tags: [manufacturing]
      operationId: listProvisioningKeys
      summary: The factory provisioning keys registered for this organization
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/ProvisioningKey" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [manufacturing]
      operationId: addProvisioningKey
      summary: Register a factory provisioning key for one product (docs/design/FACTORY_PROVISIONING.md §9)
      description: >-
        The public half of `mce factory keygen`, the same key compiled into the product's production
        images. Production manifests are imported only when both the unit's factory record and the
        station's unit attestation are signed by a key registered for the record's product.
        With require_for_claims (default true), claims and module replacements for the product accept
        only imported units.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [key_id, product_id, public_key], properties: {
          key_id: { type: string, pattern: "^[a-z0-9_-]{1,40}$" }, product_id: { type: string }, public_key: { type: string, pattern: "^[0-9a-f]{64}$" },
          require_for_claims: { type: boolean, default: true } } } } }
      responses:
        "201": { description: Registered (the same registration again returns it), content: { application/json: { schema: { $ref: "#/components/schemas/ProvisioningKey" } } } }
        default: { $ref: "#/components/responses/Error" }
  /provisioning-keys/{key_id}/revocations:
    parameters: [{ name: key_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [manufacturing]
      operationId: revokeProvisioningKey
      summary: Stop importing units signed by this key (units already imported stay)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { $ref: "#/components/schemas/ProvisioningKey" } } } }
        default: { $ref: "#/components/responses/Error" }
  /manufactured-units:
    get:
      tags: [manufacturing]
      operationId: listManufacturedUnits
      summary: Imported units of the production manifests
      parameters:
        - { name: product_id, in: query, schema: { type: string } }
        - { name: serial, in: query, schema: { type: string } }
        - { name: module_id, in: query, schema: { type: string } }
        - { name: state, in: query, schema: { enum: [claimed, unclaimed] } }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200": { description: Page, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/ManufacturedUnit" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [manufacturing]
      operationId: importManufacturedUnits
      summary: Import lines of a factory station manifest (tools/factory/station.py)
      description: >-
        Each line must carry the unit's factory record and the station's unit attestation, both signed
        by a provisioning key registered (and not revoked) for the record's product; the attestation
        must name the same serial, chip, product and record digest, and the plain manifest fields must
        agree with it. Lines are checked one by one: valid ones are imported, the same line again is
        reported unchanged, and every other line is refused with its reason (nothing partial per unit).
        A module already claimed before its line arrived is linked to its device.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [units], properties: { units: { type: array, minItems: 1, maxItems: 1000, items: { $ref: "#/components/schemas/ManifestUnit" } } } } } }
      responses:
        "200":
          description: Per-line result
          content:
            application/json:
              schema:
                type: object
                required: [imported, unchanged, refused]
                properties:
                  imported: { type: array, items: { type: string }, description: Serials }
                  unchanged: { type: array, items: { type: string } }
                  refused:
                    type: array
                    items:
                      type: object
                      required: [index, reason, detail]
                      properties:
                        index: { type: integer }
                        serial: { type: [string, "null"] }
                        reason:
                          type: string
                          description: >-
                            malformed, record_bad_signature, record_malformed, record_unsupported, record_absent, key_not_for_product,
                            attestation_bad_signature, attestation_malformed, attestation_mismatch, manifest_mismatch, serial_conflict, module_conflict
                        detail: { type: string }
        default: { $ref: "#/components/responses/Error" }
  /manufactured-units/{serial}:
    parameters: [{ name: serial, in: path, required: true, schema: { type: string } }]
    get:
      tags: [manufacturing]
      operationId: getManufacturedUnit
      summary: One imported unit, with its deployment configuration and the device that claimed it
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/ManufacturedUnit" } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-publishers:
    get:
      tags: [firmware]
      operationId: listFirmwarePublishers
      summary: The publisher keys releases are checked against, active first, with how many releases each signed
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { type: object, properties: {
          target: { type: string }, key_id: { type: string }, public_key: { type: string }, state: { enum: [active, revoked] },
          created_at: { $ref: "#/components/schemas/Time" }, revoked_at: { type: [string, "null"] }, releases: { type: integer } } } } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [firmware]
      operationId: addFirmwarePublisher
      summary: Register a publisher key allowed to sign releases for one target (PRD 14.1)
      description: Devices trust only the publisher keys compiled into their current image; this registration is the platform's own gate.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [target, key_id, public_key], properties: {
          target: { type: string, pattern: "^(mcu|module):[a-z0-9_.-]{1,40}$" }, key_id: { type: string }, public_key: { type: string, pattern: "^[0-9a-f]{64}$" } } } } }
      responses:
        "201": { description: Registered, content: { application/json: { schema: { type: object } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-publishers/{target}/{key_id}:
    parameters:
      - { name: target, in: path, required: true, schema: { type: string } }
      - { name: key_id, in: path, required: true, schema: { type: string } }
    delete:
      tags: [firmware]
      operationId: revokeFirmwarePublisher
      summary: Revoke a publisher key; no new release signed with it is accepted (releases already registered stay)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { type: object } } } }
        default: { $ref: "#/components/responses/Error" }
  /installation-credentials/{credential_id}:
    parameters: [{ name: credential_id, in: path, required: true, schema: { type: string } }]
    delete:
      tags: [devices]
      operationId: revokeInstallationCredential
      summary: Withdraw an unused installation credential (409 when it already claimed a device)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Revoked, content: { application/json: { schema: { $ref: "#/components/schemas/InstallationCredential" } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-releases:
    get:
      tags: [firmware]
      operationId: listFirmwareReleases
      summary: Releases with rollout counts per state
      parameters:
        - { name: target, in: query, schema: { type: string } }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/FirmwareReleaseSummary" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [firmware]
      operationId: createFirmwareRelease
      summary: Register a release signed offline by a registered publisher (`mce firmware sign`)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [release], properties: { release: { type: object, required: [body, sig, key_id], properties: {
          body: { type: string, contentEncoding: base64, description: "Canonical CBOR {v, release_id, target, hardware, version, security_version, image_sha256, image_size, issued_at_ms}" },
          sig: { type: string, contentEncoding: base64 }, key_id: { type: string } } } } } } }
      responses:
        "201": { description: Registered (image still to upload), content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareRelease" } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-releases/{release_id}:
    parameters: [{ name: release_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [firmware]
      operationId: getFirmwareRelease
      summary: Release and per-device rollout state as reported by the devices
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareRelease" } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-releases/{release_id}/image:
    parameters: [{ name: release_id, in: path, required: true, schema: { type: string } }]
    put:
      tags: [firmware]
      operationId: uploadFirmwareImage
      summary: Upload the image once; it must match the signed SHA-256 and size (max 4 MiB)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/octet-stream: { schema: { type: string, format: binary } } }
      responses:
        "200": { description: Stored, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareRelease" } } } }
        default: { $ref: "#/components/responses/Error" }
  /firmware-releases/{release_id}/rollouts:
    parameters: [{ name: release_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [firmware]
      operationId: createFirmwareRollout
      summary: Offer the release to devices; each device verifies it again and applies it under its own policy
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [device_ids], properties: { device_ids: { type: array, maxItems: 1000, items: { type: string } } } } } }
      responses:
        "202": { description: Offered, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareRelease" } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-releases/{release_id}/campaigns:
    parameters: [{ name: release_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [firmware]
      operationId: createFirmwareCampaign
      summary: Bulk update in waves, with automatic pause on failures
      description: >-
        Targets the organisation's claimed devices of the release's target (mcu:<product> -> that product,
        module:<name> -> Module Mode devices), optionally narrowed by `selector`, in a stable pseudo-random
        order so each wave is a fair sample. Wave k offers the first `waves[k]` percent (cumulative).
        Devices already running the version (the image version after the last "/" of their firmware string)
        are recorded as installed without an offer. A wave advances when `min_completion_percent` of it
        finished and `soak_s` passed since; if failures (failed or rolled back) exceed `max_failure_percent`
        of the finished ones, after `min_reports`, the campaign pauses and withdraws the offers not yet
        started. One running or paused campaign per release (409). Devices verify every release themselves.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                selector:
                  type: object
                  properties:
                    device_ids: { type: array, items: { type: string } }
                    running_versions: { type: array, items: { type: string }, description: Only devices running one of these image versions }
                    max_devices: { type: integer, minimum: 1, maximum: 100000 }
                waves: { type: array, minItems: 1, maxItems: 10, items: { type: integer, minimum: 1, maximum: 100 }, default: [1, 10, 50, 100], description: Increasing cumulative percentages ending at 100 }
                max_failure_percent: { type: number, minimum: 0, maximum: 100, default: 5 }
                min_completion_percent: { type: number, minimum: 1, maximum: 100, default: 90 }
                min_reports: { type: integer, minimum: 1, default: 3 }
                soak_s: { type: integer, minimum: 0, maximum: 604800, default: 600 }
      responses:
        "202": { description: Started (the first wave is offered), content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareCampaign" } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-campaigns:
    get:
      tags: [firmware]
      operationId: listFirmwareCampaigns
      parameters: [{ name: release_id, in: query, schema: { type: string } }]
      responses:
        "200": { description: Campaigns (newest first), content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/FirmwareCampaign" } }, next_cursor: { type: string, nullable: true } } } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-campaigns/{campaign_id}:
    parameters: [{ name: campaign_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [firmware]
      operationId: getFirmwareCampaign
      responses:
        "200": { description: Campaign, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareCampaign" } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-campaigns/{campaign_id}/pauses:
    parameters: [{ name: campaign_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [firmware]
      operationId: pauseFirmwareCampaign
      summary: Stop further waves and withdraw offers not yet started (held)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Paused, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareCampaign" } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-campaigns/{campaign_id}/resumptions:
    parameters: [{ name: campaign_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [firmware]
      operationId: resumeFirmwareCampaign
      summary: Re-offer held devices and continue; failures seen before the resumption no longer count against the threshold
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Running, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareCampaign" } } } }
        default: { $ref: "#/components/responses/Error" }

  /firmware-campaigns/{campaign_id}/cancellations:
    parameters: [{ name: campaign_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [firmware]
      operationId: cancelFirmwareCampaign
      summary: End the campaign; offers not yet started are withdrawn for good (updates already under way finish)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Cancelled, content: { application/json: { schema: { $ref: "#/components/schemas/FirmwareCampaign" } } } }
        default: { $ref: "#/components/responses/Error" }

  /payments/{payment_id}:
    parameters: [{ name: payment_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [payments]
      operationId: getPayment
      summary: Payment authorisation, submission and reconciliation status
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Payment" } } } }
        default: { $ref: "#/components/responses/Error" }
  /earnings:
    get:
      tags: [commerce]
      operationId: listEarnings
      summary: What this organisation's agreements credited to their payees, and what of it is still in the contracts
      description: >-
        Requires `commerce:read`. One entry per network, payee address and asset: the service provider and further
        payees of settled agreements (not the platform fee, not refunds). `available_atomic` is read from the
        contracts now.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Earning" } }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
  /dispute-resolvers:
    get:
      tags: [disputes]
      operationId: listDisputeResolvers
      summary: The addresses this organisation decides disputes as
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { type: object, properties: { address: { $ref: "#/components/schemas/EvmAddress" }, created_at: { type: string, format: date-time } } } }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
    post:
      tags: [disputes]
      operationId: addDisputeResolver
      summary: Register an address this organisation decides disputes as (proved by the address's signature)
      description: >-
        Requires `commerce:operate`. `signature` is the address's EIP-191 personal signature of the message from
        GET /dispute-resolvers/message (it names this organisation). The organisation then sees and may decide every
        dispute whose terms name this address as `dispute_resolver`. Ordinary (EOA) addresses only.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [address, signature]
              properties:
                address: { $ref: "#/components/schemas/EvmAddress" }
                signature: { type: string }
      responses:
        "201": { description: Registered, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /dispute-resolvers/message:
    get:
      tags: [disputes]
      operationId: disputeResolverMessage
      summary: The message an address signs to register as this organisation's resolver
      parameters: [{ name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }]
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { message: { type: string } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /dispute-resolvers/{address}:
    parameters: [{ name: address, in: path, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }]
    delete:
      tags: [disputes]
      operationId: removeDisputeResolver
      summary: Stop deciding disputes as this address
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /disputes:
    get:
      tags: [disputes]
      operationId: listDisputes
      summary: Disputes this organisation decides (as a registered resolver address), open ones first
      parameters: [{ name: state, in: query, schema: { enum: [open] } }]
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { type: object, additionalProperties: true } }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
  /disputes/{agreement_id}:
    parameters: [{ name: agreement_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [disputes]
      operationId: getDispute
      summary: A dispute as its seller, buyer (a storefront, with buyer_address) or resolver sees it
      description: >-
        The buyer's reason (kept only when its hash is the one the buyer signed), when it was opened, until when the
        resolver may decide (`decide_by`, the contract's window; without a decision the buyer is refunded in full),
        the resolver, the messages, and the device's runs for the order with their signed measurements.
      parameters: [{ name: buyer_address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" } }]
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Dispute" } } } }
        default: { $ref: "#/components/responses/Error" }
  /disputes/{agreement_id}/messages:
    parameters: [{ name: agreement_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [disputes]
      operationId: postDisputeMessage
      summary: Write in an open dispute, as its seller, its buyer (with buyer_address) or its resolver
      description: The other parties are notified. Up to 2,000 characters; 100 messages per dispute; read-only once it is over.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              properties:
                body: { type: string, maxLength: 2000 }
                buyer_address: { $ref: "#/components/schemas/EvmAddress" }
                as: { enum: [seller, buyer, resolver], description: "When the organisation has more than one role in this dispute" }
      responses:
        "201": { description: Posted, content: { application/json: { schema: { $ref: "#/components/schemas/Dispute" } } } }
        default: { $ref: "#/components/responses/Error" }
  /disputes/{agreement_id}/resolutions:
    parameters: [{ name: agreement_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [disputes]
      operationId: disputeResolutionCall
      summary: The call the resolver sends from its own address to decide the delivered quantity
      description: >-
        Requires `commerce:operate` and a registered resolver address named by the terms. Nothing is sent: the
        resolver sends `transaction` from its address (paying the network fee) before `decide_by`; the platform
        settles the order when it confirms.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [quantity], properties: { quantity: { type: string, pattern: "^[0-9]+$" } } } } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, additionalProperties: true } } } }
        default: { $ref: "#/components/responses/Error" }
  /notifications:
    get:
      tags: [notifications]
      operationId: listNotifications
      summary: A person's notifications in this organisation, or a storefront's for one of its buyer wallets
      description: >-
        With a person's token: their own (docs/design/NOTIFICATIONS.md lists the kinds). With an application's token
        (`commerce:read`): those of the wallet in `buyer_address` that bought through this organisation's storefront
        applications; without `buyer_address` an application gets `invalid_argument`. Newest first.
      parameters:
        - { name: buyer_address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { name: unread, in: query, schema: { enum: ["true"] } }
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Notification" } }
                  unread_count: { type: integer }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
  /notifications/read:
    post:
      tags: [notifications]
      operationId: markNotificationsRead
      summary: Mark notifications read (some by id, or all)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                ids: { type: array, maxItems: 100, items: { type: string } }
                all: { type: boolean }
                buyer_address: { $ref: "#/components/schemas/EvmAddress" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { marked_read: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /notification-settings:
    get:
      tags: [notifications]
      operationId: getNotificationSettings
      summary: Which kinds this person is emailed about in this organisation (a person's token only)
      description: Urgent kinds are emailed by default to every role but viewers; the others are in the app only by default.
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/NotificationSettings" } } } }
        default: { $ref: "#/components/responses/Error" }
    put:
      tags: [notifications]
      operationId: putNotificationSettings
      summary: Choose which kinds this person is emailed about
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kinds]
              properties:
                kinds: { type: object, additionalProperties: { type: boolean }, description: "kind -> email it or not" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/NotificationSettings" } } } }
        default: { $ref: "#/components/responses/Error" }
  /wallet-sessions/{address}:
    parameters: [{ name: address, in: path, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }]
    get:
      tags: [notifications]
      operationId: getWalletSession
      summary: The time before which every sign-in of this buyer wallet at this storefront counts as signed out
      description: Requires `commerce:buy`. A storefront keeps its wallets' sign-ins itself (sealed cookies); it reads this when it reads one, and treats a sign-in made before `signed_out_before` as signed out.
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletSession" } } } }
        default: { $ref: "#/components/responses/Error" }
  /wallet-sessions/{address}/sign-outs:
    parameters: [{ name: address, in: path, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }]
    post:
      tags: [notifications]
      operationId: signOutWallet
      summary: Sign a buyer wallet out of this storefront on every device (every sign-in made before now ends)
      description: Requires `commerce:buy`. The storefront calls it for the wallet signed in with it.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletSession" } } } }
        default: { $ref: "#/components/responses/Error" }
  /wallet-contacts/{address}:
    parameters: [{ name: address, in: path, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }]
    get:
      tags: [notifications]
      operationId: getWalletContact
      summary: The email address a buyer wallet gave this storefront, and whether it is confirmed
      description: Requires `commerce:buy`.
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletContact" } } } }
        default: { $ref: "#/components/responses/Error" }
    put:
      tags: [notifications]
      operationId: putWalletContact
      summary: Record a buyer wallet's email address and mail it a confirmation link
      description: >-
        Requires `commerce:buy`. The storefront calls this for the wallet signed in to it. Nothing is emailed to the
        address until it is confirmed through the link, which goes to `verify_url` with a `token` query parameter and
        works for 24 hours; the storefront's page then calls POST /wallet-contact-verifications. One confirmation
        per minute at most (`rate_limited`); `unsupported_capability` when the platform sends no email.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, verify_url]
              properties:
                email: { type: string, format: email }
                verify_url: { type: string, format: uri, description: "The storefront's confirmation page; its origin is also where notification emails link to" }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletContact" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [notifications]
      operationId: deleteWalletContact
      summary: Forget a buyer wallet's email address (no more emails to it)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletContact" } } } }
        default: { $ref: "#/components/responses/Error" }
  /wallet-contact-verifications:
    post:
      tags: [notifications]
      operationId: verifyWalletContact
      summary: Confirm a buyer wallet's email address with the token from its confirmation link
      description: Requires `commerce:buy` of the same organisation. Single use.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [token], properties: { token: { type: string } } } } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/WalletContact" } } } }
        default: { $ref: "#/components/responses/Error" }
  /earnings/withdrawals:
    post:
      tags: [commerce]
      operationId: withdrawEarnings
      summary: Send every credit of one payee to it (withdrawFor; the platform's relayer pays the gas)
      description: >-
        Requires `commerce:operate`. Only for an address that is a payee of this organisation's settled agreements.
        withdrawFor pays only the credit's owner: the money goes to `address` and nowhere else.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [network, address]
              properties:
                network: { type: string }
                address: { $ref: "#/components/schemas/EvmAddress" }
                asset: { $ref: "#/components/schemas/Caip19" }
      responses:
        "202":
          description: Withdrawals sent (one per contract holding a credit)
          content:
            application/json:
              schema:
                type: object
                properties:
                  address: { $ref: "#/components/schemas/EvmAddress" }
                  network: { type: string }
                  transactions: { type: array, items: { type: object, properties: { contract: { type: string }, asset: { type: string }, amount_atomic: { $ref: "#/components/schemas/Uint" }, tx: { type: string } } } }
        default: { $ref: "#/components/responses/Error" }

  /payee-earnings:
    get:
      tags: [commerce]
      operationId: getPayeeEarnings
      summary: A payee's own share across every seller, for a wallet a storefront signed in
      description: >-
        Requires `commerce:buy`. What settled orders of any seller credited to `address` as a payee (a site owner,
        an installer, the service provider itself), per network and asset, which sellers and services it came from,
        and what of it is still credited in the contracts. Buyers are never shown. Needs the wallet's own proof
        (X-MCE-Wallet-Proof); without it, 403 with `details.reason` `wallet_proof`.
      parameters:
        - { name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { $ref: "#/components/parameters/WalletProof" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  address: { $ref: "#/components/schemas/EvmAddress" }
                  data: { type: array, items: { $ref: "#/components/schemas/PayeeShare" } }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
  /payee-earnings/lines:
    get:
      tags: [commerce]
      operationId: listPayeeLines
      summary: Every share a payee address was credited, oldest first (the payee's statement and CSV)
      description: >-
        Requires `commerce:buy`. One line per allocation to `address` in a settled order of any seller (not refunds,
        not fees), settled in `[from, to)`, oldest first, keyset paging. Failed settlements are left out; a running
        subscription counts with what it has released so far. Buyers are never shown. Needs the wallet's own proof.
      parameters:
        - { name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { $ref: "#/components/parameters/WalletProof" }
        - { name: from, in: query, schema: { type: string, format: date-time } }
        - { name: to, in: query, schema: { type: string, format: date-time } }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 500, default: 100 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  address: { $ref: "#/components/schemas/EvmAddress" }
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        settlement_id: { type: string }
                        settled_at: { type: string, format: date-time }
                        network: { type: string }
                        asset: { $ref: "#/components/schemas/Caip19" }
                        template: { type: string }
                        offering_id: { type: string }
                        offering_name: { type: string }
                        seller: { type: object, properties: { organization_id: { type: string }, name: { type: string } } }
                        role: { type: string }
                        amount_atomic: { $ref: "#/components/schemas/Uint" }
                        withdrawn: { type: boolean, description: "Sent on to the payee already" }
                        tx: { type: string, description: "The settlement transaction" }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }
  /payee-earnings/withdrawals:
    post:
      tags: [commerce]
      operationId: withdrawPayeeEarnings
      summary: Send everything credited to a payee address on one network to it (withdrawFor; the platform pays the gas)
      description: >-
        Requires `commerce:buy`. For an address that is a payee of any seller's settled order. withdrawFor pays only
        the credit's owner: the money goes to `address` and nowhere else. A few sends per address a day (conflict,
        `details.reason` `too_many_today`); nothing is sent while one is pending or when nothing is credited. Needs the
        wallet's own proof.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }, { $ref: "#/components/parameters/WalletProof" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [network, address]
              properties:
                network: { type: string }
                address: { $ref: "#/components/schemas/EvmAddress" }
                asset: { $ref: "#/components/schemas/Caip19" }
      responses:
        "202":
          description: Withdrawals sent (one per contract holding a credit; none when nothing is credited)
          content:
            application/json:
              schema:
                type: object
                properties:
                  address: { $ref: "#/components/schemas/EvmAddress" }
                  network: { type: string }
                  transactions: { type: array, items: { type: object, properties: { contract: { type: string }, asset: { type: string }, amount_atomic: { $ref: "#/components/schemas/Uint" }, tx: { type: string } } } }
        default: { $ref: "#/components/responses/Error" }

  /networks:
    get:
      tags: [commerce]
      operationId: listNetworks
      summary: The networks an offering can be priced on, their assets and the templates each can settle
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: "#/components/schemas/Network" } }
                  next_cursor: { type: string, nullable: true }
        default: { $ref: "#/components/responses/Error" }

  /statements:
    get:
      tags: [commerce]
      operationId: getStatement
      summary: Totals of what was settled in a period, per asset (and per service for the seller)
      description: >-
        Requires `commerce:read` (docs/design/ACCOUNTING.md). role=seller (default): this organisation's sales settled in
        [from, to): orders, charged to buyers, platform fees, earned by its payees, refunded; and the same per service.
        role=buyer: this organisation's purchases (a storefront narrows them to one wallet with buyer_address): orders,
        charged, fees within the charge, refunded, paid in, and what its open orders still hold. Amounts are atomic units
        of each asset, never summed across assets. A settlement counts at the time the platform recorded it.
      parameters:
        - { name: role, in: query, schema: { enum: [seller, buyer], default: seller } }
        - { name: buyer_address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { name: from, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: to, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: interval, in: query, description: "day: also the totals per UTC day and asset (days without a settlement left out)", schema: { enum: [day] } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Statement" } } } }
        default: { $ref: "#/components/responses/Error" }
  /settlements:
    get:
      tags: [commerce]
      operationId: listSettlements
      summary: The settlement lines behind a statement (for exports), oldest first
      description: Requires `payments:read`. Same role, buyer_address and period as GET /statements; up to 500 a page.
      parameters:
        - { name: role, in: query, schema: { enum: [seller, buyer], default: seller } }
        - { name: buyer_address, in: query, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { name: from, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: to, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { $ref: "#/components/parameters/Cursor" }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 500, default: 100 } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/SettlementLine" } }, next_cursor: { type: [string, "null"] } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /payouts:
    get:
      tags: [commerce]
      operationId: listPayouts
      summary: This organisation's payees' withdrawals (POST /earnings/withdrawals), newest first
      description: Requires `commerce:read`.
      parameters:
        - { name: from, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: to, in: query, schema: { $ref: "#/components/schemas/Time" } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 500, default: 100 } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        network: { $ref: "#/components/schemas/Caip2" }
                        address: { $ref: "#/components/schemas/EvmAddress" }
                        asset: { $ref: "#/components/schemas/Caip19" }
                        amount_atomic: { $ref: "#/components/schemas/Uint" }
                        contract: { $ref: "#/components/schemas/EvmAddress" }
                        tx: { type: string }
                        state: { enum: [pending, confirmed, failed] }
                        created_at: { $ref: "#/components/schemas/Time" }
                        confirmed_at: { $ref: "#/components/schemas/Time" }
        default: { $ref: "#/components/responses/Error" }
  /balances:
    get:
      tags: [commerce]
      operationId: getBalances
      summary: What a wallet holds of each asset the platform knows (e.g. before paying)
      description: Requires `commerce:read`. Read from the chain now.
      parameters:
        - { name: address, in: query, required: true, schema: { $ref: "#/components/schemas/EvmAddress" } }
        - { name: network, in: query, schema: { $ref: "#/components/schemas/Caip2" } }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  address: { $ref: "#/components/schemas/EvmAddress" }
                  data: { type: array, items: { type: object, properties: { network: { $ref: "#/components/schemas/Caip2" }, asset: { $ref: "#/components/schemas/Caip19" }, token: { $ref: "#/components/schemas/EvmAddress" }, name: { type: string }, balance_atomic: { $ref: "#/components/schemas/Uint" } } } }
        default: { $ref: "#/components/responses/Error" }
  /settlements/{settlement_id}:
    parameters: [{ name: settlement_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [payments]
      operationId: getSettlement
      summary: Settlement allocations and chain confirmation
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Settlement" } } } }
        default: { $ref: "#/components/responses/Error" }

  /evidence-submissions:
    post:
      tags: [evidence]
      operationId: submitPlatformEvidence
      summary: Submit platform business material (always source=platform_application)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [kind, content_digest]
              properties:
                kind: { type: string, maxLength: 64 }
                content_digest: { type: string, pattern: "^sha256:[0-9a-f]{64}$" }
                media_type: { type: string }
                object_ref: { type: string, description: Authorized object reference for the content }
                links: { $ref: "#/components/schemas/Links" }
                level: { enum: [signed, signed_anchored], default: signed_anchored }
      responses:
        "202": { description: Accepted, content: { application/json: { schema: { $ref: "#/components/schemas/Evidence" } } } }
        default: { $ref: "#/components/responses/Error" }
  /evidence/{evidence_id}:
    parameters: [{ name: evidence_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [evidence]
      operationId: getEvidence
      summary: Signed records, identity history, links and anchor status
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Evidence" } } } }
        default: { $ref: "#/components/responses/Error" }
  /evidence/{evidence_id}/bundle:
    parameters: [{ name: evidence_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [evidence]
      operationId: exportEvidenceBundle
      summary: Self-contained bundle for independent verification (`mce evidence verify`)
      responses:
        "200": { description: Bundle, content: { application/json: { schema: { $ref: "#/components/schemas/EvidenceBundle" } } } }
        default: { $ref: "#/components/responses/Error" }

  /webhook-subscriptions:
    post:
      tags: [events]
      operationId: createWebhookSubscription
      summary: Subscribe to events with a signing secret
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: "#/components/schemas/WebhookSubscriptionCreate" } } }
      responses:
        "201": { description: Created (secret returned once), content: { application/json: { schema: { $ref: "#/components/schemas/WebhookSubscription" } } } }
        default: { $ref: "#/components/responses/Error" }
    get:
      tags: [events]
      operationId: listWebhookSubscriptions
      summary: List webhook subscriptions
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/WebhookSubscription" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /webhook-subscriptions/{subscription_id}:
    parameters: [{ name: subscription_id, in: path, required: true, schema: { type: string } }]
    patch:
      tags: [events]
      operationId: updateWebhookSubscription
      summary: Change the address, the event types or the filter; pause or resume
      description: A paused subscription keeps its place in the event log; when it is resumed, the events since are sent.
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, properties: {
          url: { type: string }, event_types: { type: array, items: { type: string } },
          filter: { type: object, properties: { device_ids: { type: array, items: { type: string } }, product_ids: { type: array, items: { type: string } } } },
          state: { enum: [active, paused] } } } } }
      responses:
        "200": { description: Changed, content: { application/json: { schema: { $ref: "#/components/schemas/WebhookSubscription" } } } }
        default: { $ref: "#/components/responses/Error" }
    delete:
      tags: [events]
      operationId: deleteWebhookSubscription
      summary: Delete (nothing more is sent; deliveries still waiting are dropped)
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "200": { description: Deleted, content: { application/json: { schema: { type: object, properties: { id: { type: string }, deleted: { type: boolean } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /webhook-subscriptions/{subscription_id}/deliveries:
    parameters: [{ name: subscription_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [events]
      operationId: listWebhookDeliveries
      summary: The most recent deliveries, newest first, with what the endpoint answered
      parameters:
        - { name: state, in: query, schema: { enum: [pending, delivered, dead] } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
      responses:
        "200": { description: OK, content: { application/json: { schema: { type: object, properties: { data: { type: array, items: { $ref: "#/components/schemas/WebhookDelivery" } } } } } } }
        default: { $ref: "#/components/responses/Error" }
  /webhook-subscriptions/{subscription_id}/secret-rotations:
    parameters: [{ name: subscription_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [events]
      operationId: rotateWebhookSecret
      summary: New secret; both old and new signatures are sent during the overlap window
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      responses:
        "201": { description: Rotated, content: { application/json: { schema: { $ref: "#/components/schemas/WebhookSubscription" } } } }
        default: { $ref: "#/components/responses/Error" }
  /webhook-subscriptions/{subscription_id}/replays:
    parameters: [{ name: subscription_id, in: path, required: true, schema: { type: string } }]
    post:
      tags: [events]
      operationId: replayWebhooks
      summary: Explicitly re-deliver events (including dead-lettered ones) from a cursor
      parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, required: [from_cursor], properties: { from_cursor: { type: string }, only_dead_lettered: { type: boolean } } } } }
      responses:
        "202": { $ref: "#/components/responses/OperationAccepted" }
        default: { $ref: "#/components/responses/Error" }
  /events:
    get:
      tags: [events]
      operationId: listEvents
      summary: Recover missed events (same envelopes as webhooks), ordered by the platform's event sequence
      parameters:
        - { $ref: "#/components/parameters/Cursor" }
        - { $ref: "#/components/parameters/Limit" }
        - { name: type, in: query, schema: { type: string } }
        - { name: resource_id, in: query, schema: { type: string } }
        - { name: order, in: query, schema: { enum: [asc, desc], default: asc }, description: "desc: the newest first, next_cursor pages back in time (no resume cursor)" }
      responses:
        "200": { description: Page, content: { application/json: { schema: { $ref: "#/components/schemas/EventPage" } } } }
        default: { $ref: "#/components/responses/Error" }
  /operations/{operation_id}:
    parameters: [{ name: operation_id, in: path, required: true, schema: { type: string } }]
    get:
      tags: [operations]
      operationId: getOperation
      summary: Status of an asynchronous configuration / claim / registry / payment operation
      responses:
        "200": { description: OK, content: { application/json: { schema: { $ref: "#/components/schemas/Operation" } } } }
        default: { $ref: "#/components/responses/Error" }

webhooks:
  mceEvent:
    post:
      operationId: mceEventDelivery
      summary: Event delivery (at-least-once)
      description: |
        Headers: `MCE-Event-Id`, `MCE-Timestamp` (unix seconds), `MCE-Signature: v1=<hex>[,v1=<hex>]`.
        `v1 = HMAC-SHA256(secret, timestamp + "." + event_id + "." + raw_body)`. During secret rotation both
        signatures are present. Reject if |now - timestamp| > 300 s. Deliveries retry with exponential backoff
        for 24 h, then dead-letter (replayable). Order is not guaranteed: use `resource_version` and GET the resource.
        Never infer the real order of fund movements from delivery order.
      requestBody:
        content: { application/json: { schema: { $ref: "#/components/schemas/EventEnvelope" } } }
      responses:
        "2XX": { description: Acknowledged (any 2xx) }

components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      description: Short-lived token from /oauth/token. Browsers must never hold tenant master credentials.

  parameters:
    WalletProof:
      name: X-MCE-Wallet-Proof
      in: header
      required: true
      schema: { type: string, maxLength: 4000 }
      description: >-
        The wallet's own proof for routes that read or move what other organisations' orders gave it: base64url of
        {"message", "signature"}, the EIP-4361 sign-in the wallet signed at this storefront (an ordinary account's
        personal_sign). The message names the wallet, has an Issued At no later than now and an Expiration Time not
        passed (at most 7 days after it was issued); a sign-in made before the wallet signed out of this storefront
        everywhere is refused (SDKs: walletProof / wallet_proof / WalletProof).
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      schema: { type: string, minLength: 8, maxLength: 128, pattern: "^[A-Za-z0-9_.:-]+$" }
      description: "The same key with the same body returns the first answer for 7 days (docs/design/RETENTION.md); with another body, 409 idempotency_conflict. After 7 days the key is new again: retry within the week."
    Cursor: { name: cursor, in: query, schema: { type: string } }
    Limit: { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
    ProductId: { name: product_id, in: path, required: true, schema: { type: string } }
    DeviceId: { name: device_id, in: path, required: true, schema: { type: string } }
    InvocationId: { name: invocation_id, in: path, required: true, schema: { type: string } }
    AgreementId: { name: agreement_id, in: path, required: true, schema: { type: string } }

  responses:
    Error:
      description: Error
      headers:
        Retry-After: { schema: { type: integer }, description: Present when retryable (e.g. rate_limited) }
      content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
    OperationAccepted:
      description: Durably accepted; follow the operation
      content: { application/json: { schema: { $ref: "#/components/schemas/Operation" } } }

  schemas:
    ProductManifest: {"title": "TLAY MCE Capability Manifest", "description": "Immutable, versioned capability description of a Product (PRD \u00a75.3). Registered via POST /v1/tlay/products/{id}/versions. Digest = SHA-256('TLAY-MCE/manifest/v1' || 0x00 || deterministic-CBOR(manifest)). Floats are not allowed anywhere; decimals and 64-bit values use strings.", "type": "object", "additionalProperties": false, "required": ["schema_version", "product_id", "product_version", "firmware_compatibility"], "properties": {"schema_version": {"const": "1.0"}, "product_id": {"$ref": "#/components/schemas/Manifest_id", "description": "Stable product id, e.g. prd_generic_actuator"}, "product_version": {"$ref": "#/components/schemas/Manifest_semver"}, "display": {"type": "object", "additionalProperties": false, "description": "Human-readable text. Treated strictly as data (PRD \u00a716.1); never interpreted as instructions or permissions.", "properties": {"name": {"type": "string", "maxLength": 80}, "description": {"type": "string", "maxLength": 1000}, "vendor": {"type": "string", "maxLength": 80}}}, "properties": {"type": "array", "maxItems": 64, "items": {"$ref": "#/components/schemas/Manifest_property"}}, "actions": {"type": "array", "maxItems": 32, "items": {"$ref": "#/components/schemas/Manifest_action"}}, "events": {"type": "array", "maxItems": 64, "items": {"$ref": "#/components/schemas/Manifest_event"}}, "meters": {"type": "array", "maxItems": 16, "items": {"$ref": "#/components/schemas/Manifest_meter"}}, "resources": {"type": "array", "maxItems": 8, "description": "Exclusive resources used for lease / fencing (PRD \u00a710.4). Actions and sessions reference them.", "items": {"type": "object", "additionalProperties": false, "required": ["name", "max_concurrent"], "properties": {"name": {"$ref": "#/components/schemas/Manifest_name"}, "max_concurrent": {"type": "integer", "minimum": 1, "maximum": 16}}}}, "policy_constraints": {"$ref": "#/components/schemas/Manifest_policy_constraints"}, "firmware_compatibility": {"type": "object", "additionalProperties": false, "required": ["device_api", "modes"], "properties": {"device_api": {"type": "string", "description": "Semver range of the Device API, e.g. '>=1.0.0 <2.0.0'", "maxLength": 64}, "host_protocol": {"type": "string", "description": "Required for module mode. Major.minor range, e.g. '>=1.0 <2.0'", "maxLength": 64}, "modes": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"enum": ["mcu", "module"]}}, "profiles": {"type": "array", "uniqueItems": true, "items": {"$ref": "#/components/schemas/Manifest_name"}, "description": "Runtime build profiles known to satisfy this manifest"}}}}}
    Manifest_id: {"type": "string", "pattern": "^[a-z][a-z0-9_]{2,39}$"}
    Manifest_name: {"type": "string", "pattern": "^[a-z][a-z0-9_]{0,31}$"}
    Manifest_semver: {"type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$"}
    Manifest_int_string: {"type": "string", "pattern": "^-?(0|[1-9][0-9]{0,19})$"}
    Manifest_uint_string: {"type": "string", "pattern": "^(0|[1-9][0-9]{0,19})$"}
    Manifest_unit: {"type": "string", "pattern": "^[A-Za-z0-9_%/.\\-]{1,16}$", "description": "UCUM-like unit symbol, e.g. ms, Wh, mA, %, count"}
    Manifest_value_type: {"description": "Value types usable on device. 64-bit and decimal values are strings in JSON and integers in CBOR.", "oneOf": [{"type": "object", "additionalProperties": false, "required": ["type"], "properties": {"type": {"const": "bool"}, "required": {"type": "boolean"}}}, {"type": "object", "additionalProperties": false, "required": ["type"], "properties": {"type": {"enum": ["int32", "uint32"]}, "minimum": {"type": "integer"}, "maximum": {"type": "integer"}, "unit": {"$ref": "#/components/schemas/Manifest_unit"}, "required": {"type": "boolean"}}}, {"type": "object", "additionalProperties": false, "required": ["type"], "properties": {"type": {"enum": ["int64_string", "uint64_string"]}, "minimum": {"$ref": "#/components/schemas/Manifest_int_string"}, "maximum": {"$ref": "#/components/schemas/Manifest_int_string"}, "scale": {"type": "integer", "minimum": -18, "maximum": 18, "description": "value = integer \u00d7 10^scale unit"}, "unit": {"$ref": "#/components/schemas/Manifest_unit"}, "required": {"type": "boolean"}}}, {"type": "object", "additionalProperties": false, "required": ["type", "values"], "properties": {"type": {"const": "enum"}, "values": {"type": "array", "minItems": 1, "maxItems": 32, "uniqueItems": true, "items": {"$ref": "#/components/schemas/Manifest_name"}}, "required": {"type": "boolean"}}}, {"type": "object", "additionalProperties": false, "required": ["type", "max_length"], "properties": {"type": {"enum": ["string", "bytes"]}, "max_length": {"type": "integer", "minimum": 1, "maximum": 512}, "required": {"type": "boolean"}}}]}
    Manifest_fields: {"type": "object", "maxProperties": 16, "propertyNames": {"$ref": "#/components/schemas/Manifest_name"}, "additionalProperties": {"$ref": "#/components/schemas/Manifest_value_type"}}
    Manifest_property: {"type": "object", "additionalProperties": false, "required": ["name", "value", "access"], "properties": {"name": {"$ref": "#/components/schemas/Manifest_name"}, "value": {"$ref": "#/components/schemas/Manifest_value_type"}, "access": {"enum": ["read", "read_write"]}, "side_effect": {"enum": ["none", "physical"], "default": "none", "description": "physical: writing this property changes the physical world. The cloud turns PATCH desired-properties into an Invocation of `set_via_action` (PRD \u00a78.4, GEN-13)."}, "set_via_action": {"$ref": "#/components/schemas/Manifest_name", "description": "Required when access=read_write and side_effect=physical."}, "report": {"type": "object", "additionalProperties": false, "properties": {"mode": {"enum": ["on_change", "periodic", "on_request"]}, "min_interval_ms": {"type": "integer", "minimum": 0, "maximum": 86400000}, "stale_after_ms": {"type": "integer", "minimum": 1000, "maximum": 604800000, "description": "freshness threshold reported by GET properties"}}}}, "if": {"properties": {"access": {"const": "read_write"}, "side_effect": {"const": "physical"}}, "required": ["access", "side_effect"]}, "then": {"required": ["set_via_action"]}}
    Manifest_action: {"type": "object", "additionalProperties": false, "required": ["name", "execution_mode", "max_duration_ms", "cancellable", "offline_start_allowed", "idempotency", "recovery"], "properties": {"name": {"$ref": "#/components/schemas/Manifest_name"}, "input": {"$ref": "#/components/schemas/Manifest_fields"}, "output": {"$ref": "#/components/schemas/Manifest_fields"}, "execution_mode": {"enum": ["sync", "async"], "description": "sync: app completes within the callback window (still reports complete/fail). async: ack, then started/progress/complete."}, "max_duration_ms": {"type": "integer", "minimum": 1, "maximum": 86400000}, "ack_timeout_ms": {"type": "integer", "minimum": 100, "maximum": 60000, "default": 5000}, "cancellable": {"type": "boolean"}, "offline_start_allowed": {"type": "boolean", "description": "May start from a cached permit while offline (PRD \u00a710.3). Requires offline_limits in policy_constraints."}, "risk": {"enum": ["low", "medium", "high"], "default": "medium"}, "idempotency": {"enum": ["idempotent", "at_most_once"], "description": "idempotent: repeating with same inputs is harmless. at_most_once: a second physical execution must never happen for one invocation_id."}, "recovery": {"enum": ["query_device", "assume_not_started", "manual_reconcile"], "description": "What the runtime does when a crash leaves the outcome unknown (PRD \u00a713.3). manual_reconcile pauses new invocations of this action until reconciled."}, "resource": {"$ref": "#/components/schemas/Manifest_name", "description": "Exclusive resource (see resources) this action holds while running."}, "requires_agreement": {"type": "boolean", "default": false, "description": "Only invocable under an active on-chain AccessLease / Agreement (PRD \u00a78.5). Enforced by cloud AND runtime."}, "evidence_level": {"enum": ["transport_only", "signed", "signed_anchored"], "default": "signed"}, "meters": {"type": "array", "maxItems": 16, "uniqueItems": true, "items": {"$ref": "#/components/schemas/Manifest_name"}, "description": "Meters expected to be appended during execution (each once)."}}}
    Manifest_event: {"type": "object", "additionalProperties": false, "required": ["name"], "properties": {"name": {"$ref": "#/components/schemas/Manifest_name"}, "payload": {"$ref": "#/components/schemas/Manifest_fields"}, "severity": {"enum": ["info", "warning", "critical"], "default": "info"}, "evidence_level": {"enum": ["transport_only", "signed", "signed_anchored"], "default": "signed"}, "priority": {"enum": ["telemetry", "normal", "critical"], "default": "normal"}}}
    Manifest_meter: {"type": "object", "additionalProperties": false, "required": ["name", "unit", "mode", "value_type", "source"], "properties": {"name": {"$ref": "#/components/schemas/Manifest_name"}, "unit": {"$ref": "#/components/schemas/Manifest_unit"}, "dimension": {"enum": ["time", "energy", "power", "count", "volume", "mass", "data", "other"]}, "mode": {"enum": ["cumulative", "delta", "sample"]}, "value_type": {"enum": ["uint64_string", "int64_string"]}, "scale": {"type": "integer", "minimum": -18, "maximum": 18, "default": 0}, "source": {"enum": ["device_application", "host_reported", "module_observed"]}, "max_rate_per_s": {"type": "integer", "minimum": 1, "maximum": 100, "default": 1}, "max_step": {"$ref": "#/components/schemas/Manifest_uint_string", "description": "Largest plausible increase between consecutive samples; larger jumps get quality flag drift"}, "reset_rule": {"enum": ["epoch", "never"], "default": "epoch", "description": "epoch: counter may restart at 0 with a new meter_epoch after reboot"}, "billing_eligible": {"type": "boolean", "default": false, "description": "May be referenced by MeteredServiceEscrow terms. Estimated values never are."}}}
    Manifest_policy_constraints: {"type": "object", "additionalProperties": false, "description": "Layer-1/2 limits (PRD \u00a710.1). Compiled into firmware; no commercial term, grant or config.set may widen them.", "properties": {"parameter_limits": {"type": "array", "items": {"type": "object", "additionalProperties": false, "required": ["action", "parameter"], "properties": {"action": {"$ref": "#/components/schemas/Manifest_name"}, "parameter": {"$ref": "#/components/schemas/Manifest_name"}, "minimum": {"type": ["integer", "string"]}, "maximum": {"type": ["integer", "string"]}}}}, "rate_limits": {"type": "array", "items": {"type": "object", "additionalProperties": false, "required": ["action", "max_per_window", "window_s"], "properties": {"action": {"$ref": "#/components/schemas/Manifest_name"}, "max_per_window": {"type": "integer", "minimum": 1}, "window_s": {"type": "integer", "minimum": 1, "maximum": 86400}}}}, "offline_limits": {"type": "object", "additionalProperties": false, "properties": {"max_offline_invocations": {"type": "integer", "minimum": 0, "maximum": 1000}, "max_permit_age_s": {"type": "integer", "minimum": 0, "maximum": 86400}}}, "purchase": {"type": "object", "additionalProperties": false, "description": "Hard ceiling for device-initiated purchases; owner budgets must be \u2264 these.", "properties": {"enabled": {"type": "boolean"}, "max_amount_atomic_per_tx": {"$ref": "#/components/schemas/Manifest_uint_string"}, "max_amount_atomic_per_day": {"$ref": "#/components/schemas/Manifest_uint_string"}, "allowed_assets": {"type": "array", "items": {"type": "string", "maxLength": 128, "description": "CAIP-19 asset id"}}}}}}
    Session:
      type: object
      required: [access_token, token_type, expires_in, refresh_token, user, organization, role, organizations]
      properties:
        access_token: { type: string }
        token_type: { const: Bearer }
        expires_in: { type: integer }
        refresh_token: { type: string, description: Opaque; replaced at every refresh }
        user: { type: object, properties: { id: { type: string }, email: { type: string }, name: { type: string } } }
        organization: { type: object, properties: { id: { type: string }, name: { type: string } } }
        role: { enum: [owner, admin, operator, viewer] }
        organizations: { type: array, items: { type: object, properties: { id: { type: string }, name: { type: string }, role: { type: string } } } }
    Time: { type: string, format: date-time, description: UTC RFC 3339 }
    Uint: { type: string, pattern: "^(0|[1-9][0-9]{0,77})$", description: Decimal integer string }
    ExternalRef: { type: string, maxLength: 128, description: "Customer's own reference; echoed, never used for authorization" }
    Caip2: { type: string, pattern: "^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$", examples: ["eip155:31337"] }
    Caip19: { type: string, maxLength: 128, examples: ["eip155:31337/erc20:0x3600000000000000000000000000000000000000"] }
    EvmAddress: { type: string, pattern: "^0x[0-9a-fA-F]{40}$" }
    Digest: { type: string, pattern: "^sha256:[0-9a-f]{64}$" }
    Source: { enum: [device_application, host_reported, module_observed, platform_application, external_verifier] }
    EnforcementPoint: { enum: [runtime, module, cloud_gateway, contract] }
    Fields:
      type: object
      maxProperties: 16
      propertyNames: { pattern: "^[a-z][a-z0-9_]{0,31}$" }
      additionalProperties:
        description: bool, integer (int32/uint32), decimal string (64-bit), enum value name, string, or base64 bytes — per the manifest type
        oneOf: [{ type: boolean }, { type: integer }, { type: string }]
    Links:
      type: object
      properties:
        device_id: { type: string }
        invocation_id: { type: string }
        session_id: { type: string }
        agreement_id: { type: string }
        payment_id: { type: string }

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message, request_id, retryable]
          properties:
            code:
              enum: [unauthorized, forbidden, not_found, conflict, idempotency_conflict, invalid_argument, unsupported_capability, schema_mismatch, device_unavailable, stale_state, device_busy, grant_expired, grant_revoked, budget_exceeded, quote_expired, funding_unconfirmed, execution_unknown, payment_reconciling, buffer_full, rate_limited, internal]
            message: { type: string }
            request_id: { type: string }
            resource_id: { type: string }
            retryable: { type: boolean }
            details: { type: object, description: "Safe, non-sensitive details" }

    PaymentHandoverResult:
      type: object
      properties:
        handover_id: { type: string }
        module_id: { type: string }
        from_address: { $ref: "#/components/schemas/EvmAddress" }
        owner_address: { $ref: "#/components/schemas/EvmAddress" }
        network: { $ref: "#/components/schemas/Caip2" }
        phase: { enum: [withdrawing, sweeping, waiting_for_agreements, completed] }
        obligations:
          type: object
          properties:
            agreements: { type: array, items: { type: string }, description: Open agreements whose refund would still land on the address }
            payments: { type: array, items: { type: string } }
            asset: { $ref: "#/components/schemas/Caip19", description: The device's (primary) payment asset (the amounts below) }
            balance_atomic: { $ref: "#/components/schemas/Uint" }
            escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }
            by_asset:
              type: array
              description: A device paying in several assets (payment_tokens) - each one's figures, never added up; the process ends when every one is 0
              items: { type: object, properties: { asset: { $ref: "#/components/schemas/Caip19" }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" } } }
            unsweepable_other_assets:
              type: array
              description: >-
                Holdings of the address in the network's OTHER assets. The device signs only for its own tokens (payment_tokens),
                so it cannot move these; they do not hold the process (anyone could otherwise block it with a transfer) and are reported
              items: { type: object, properties: { asset: { $ref: "#/components/schemas/Caip19" }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" } } }
    PaymentKeyRotationResult:
      type: object
      description: "kind=key_rotation, purpose=payment: where the rotation stands"
      properties:
        rotation_id: { type: string }
        purpose: { type: string }
        mode: { enum: [planned, compromised] }
        phase: { enum: [proving, draining, sweeping, retiring, retired] }
        old_key_id: { type: string }
        new_key_id: { type: string }
        old_address: { $ref: "#/components/schemas/EvmAddress" }
        new_address: { $ref: "#/components/schemas/EvmAddress" }
        network: { $ref: "#/components/schemas/Caip2" }
        obligations:
          type: object
          description: What keeps the old key alive (§5.4); the key is retired when all are empty and both amounts are 0 in every asset the device pays in
          properties:
            agreements: { type: array, items: { type: string } }
            payments: { type: array, items: { type: string } }
            asset: { $ref: "#/components/schemas/Caip19" }
            balance_atomic: { $ref: "#/components/schemas/Uint" }
            escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }
            by_asset:
              type: array
              description: A device paying in several assets (payment_tokens) - each one's figures, never added up; the process ends when every one is 0
              items: { type: object, properties: { asset: { $ref: "#/components/schemas/Caip19" }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" } } }
            unsweepable_other_assets:
              type: array
              description: >-
                Holdings of the address in the network's OTHER assets. The device signs only for its own tokens (payment_tokens),
                so it cannot move these; they do not hold the process (anyone could otherwise block it with a transfer) and are reported
              items: { type: object, properties: { asset: { $ref: "#/components/schemas/Caip19" }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" } } }
        residual_risk:
          type: object
          description: "mode=compromised: what a holder of the old key could still do, and the most it could take"
          properties:
            open_agreements: { type: array, items: { type: string } }
            refunds_to_old_address_atomic: { $ref: "#/components/schemas/Uint" }
            balance_atomic: { $ref: "#/components/schemas/Uint" }
            escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }
            max_loss_atomic: { $ref: "#/components/schemas/Uint" }
            asset: { $ref: "#/components/schemas/Caip19", description: The asset of the top-level figures (the device's payment asset) }
            by_asset:
              type: array
              description: The same figures per asset (amounts of different assets are never added up)
              items: { type: object, properties: { network: { $ref: "#/components/schemas/Caip2" }, asset: { $ref: "#/components/schemas/Caip19" },
                       refunds_to_old_address_atomic: { $ref: "#/components/schemas/Uint" }, balance_atomic: { $ref: "#/components/schemas/Uint" },
                       escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }, max_loss_atomic: { $ref: "#/components/schemas/Uint" } } }
            cannot_prevent: { type: array, items: { type: string } }
    Operation:
      type: object
      required: [id, kind, state, created_at, updated_at]
      properties:
        id: { type: string }
        kind: { type: string, description: "claim, registry, module_binding, key_rotation, acceptance, cancellation, dispute, webhook_replay, configuration, or a device-initiated operation kind (quote_request, purchase_request, payment_submit, agreement_response)" }
        state: { enum: [accepted, running, succeeded, failed, unknown, requires_buyer_transaction, requires_controller_transaction] }
        resource_id: { type: string }
        error: { $ref: "#/components/schemas/Error/properties/error" }
        tx: { type: string, description: Transaction the platform relayed for this operation (e.g. a buyer-signed escrow action) }
        result:
          description: "kind=key_rotation (payment) or kind=payment_handover: phase and what is still open"
          oneOf: [{ $ref: "#/components/schemas/PaymentKeyRotationResult" }, { $ref: "#/components/schemas/PaymentHandoverResult" }]
        typed_data: { type: object, description: "state=requires_buyer_transaction: the exact EIP-712 BuyerAction to sign; POST it back as `signature` to have it relayed (escrow v2)" }
        transaction:
          type: object
          description: "state=requires_buyer_transaction: the exact contract call the buyer address must send itself (the platform never acts for the buyer)"
          properties:
            network: { $ref: "#/components/schemas/Caip2" }
            to: { $ref: "#/components/schemas/EvmAddress" }
            from: { $ref: "#/components/schemas/EvmAddress" }
            data: { type: string, pattern: "^0x[0-9a-fA-F]*$" }
            note: { type: string }
        status_url: { type: string }
        created_at: { $ref: "#/components/schemas/Time" }
        updated_at: { $ref: "#/components/schemas/Time" }

    ApplicationCreate:
      type: object
      required: [name, scopes]
      properties:
        name: { type: string, maxLength: 80 }
        kind: { enum: [backend, agent, device_installer], default: backend }
        scopes:
          type: array
          items: { enum: [tenant:admin, devices:provision, products:read, products:write, devices:read, devices:claim, devices:registry, devices:write, properties:read, properties:write, invocations:create, invocations:read, events:read, meters:read, grants:write, commerce:read, commerce:operate, commerce:buy, commerce:verify, payments:read, evidence:read, evidence:write, webhooks:admin, firmware:admin, firmware:read] }
        device_scope:
          type: object
          properties:
            product_ids: { type: array, items: { type: string } }
            device_ids: { type: array, items: { type: string } }
        limits:
          allOf: [{ $ref: "#/components/schemas/ApplicationLimits" }]
          description: >-
            What it may do on its own from its first token, as PUT /applications/{application_id}/limits sets it: only a
            person who is an owner or an administrator gives it (403 otherwise), and not with tenant:admin (409, tenant_admin).
    AuditEntry:
      type: object
      required: [id, at, actor, action, summary]
      properties:
        id: { type: string }
        at: { $ref: "#/components/schemas/Time" }
        actor: { type: object, properties: { label: { type: string, description: "The person (name and email then) or the application" }, user_id: { type: [string, "null"] }, application_id: { type: [string, "null"] } } }
        action: { type: string, description: "e.g. member.role_changed, offerings.publish, firmware.campaign_pause" }
        summary: { type: string }
        resource_id: { type: [string, "null"] }
        details: { type: object }
    TwoFactorRequired:
      type: object
      required: [two_factor_required]
      description: The password was right; the account has two-factor sign-in on. Send the request again with code.
      properties: { two_factor_required: { const: true } }
    Application:
      type: object
      required: [id, name, kind, client_id, scopes, state, created_at]
      properties:
        id: { type: string }
        name: { type: string }
        kind: { enum: [backend, agent] }
        client_id: { type: string }
        scopes: { type: array, items: { type: string } }
        device_scope: { type: object }
        state: { enum: [active, revoked] }
        created_at: { $ref: "#/components/schemas/Time" }
        last_used_at: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }], description: When it last obtained a token }
        revoked_at: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }] }
        previous_secret_valid_until: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }], description: Until when the secret replaced by the last rotation is still accepted }
        self: { type: boolean, description: The application making this request }
        limits: { $ref: "#/components/schemas/ApplicationLimits" }
    ApplicationLimits:
      type: object
      description: What the application may do on its own; "direct" (and a null step and band) is the default
      properties:
        prices: { enum: [direct, propose], description: "propose: a price change becomes a proposal a person approves" }
        price_step_percent: { oneOf: [{ type: integer, minimum: 1, maximum: 100 }, { type: "null" }], description: A direct change moves the price by at most this share of the current price }
        price_band_percent: { oneOf: [{ type: integer, minimum: 1, maximum: 100 }, { type: "null" }], description: "The application's own changes keep the price within this share of the one a person last set (a person's edit, a price rule, an approved proposal), however many steps" }
        answers: { enum: [direct, draft], description: "draft: an answer to a buyer's request becomes a draft a person sends" }
        dispute_messages: { enum: [direct, draft], description: "draft: a message as the seller in a dispute becomes a draft a person sends" }
    ApplicationRecord:
      type: object
      required: [application_id, name, since, days, trust_run, limits, prices, answers, dispute_messages, suggestions]
      properties:
        application_id: { type: string }
        name: { type: string }
        since: { $ref: "#/components/schemas/Time" }
        days: { type: integer }
        trust_run: { type: integer, description: Decisions in a row after which a suggestion is made }
        limits: { $ref: "#/components/schemas/ApplicationLimits" }
        prices:
          type: object
          properties:
            approved: { type: integer }
            declined: { type: integer }
            lapsed: { type: integer }
            open: { type: integer }
            in_a_row: { type: integer, description: Newest decided proposals approved in a row }
            largest_step_percent: { oneOf: [{ type: integer }, { type: "null" }], description: The largest price move among those approved in a row }
            held: { type: boolean }
            changed: { type: integer, description: Price changes it made on its own (not proposed) }
            put_back: { type: integer, description: Of those, how many a person put back }
            recent_put_back:
              type: array
              description: The last five put back, newest first
              items:
                type: object
                properties:
                  change_id: { type: string }
                  offering_id: { type: string }
                  pool_id: { type: string }
                  service: { type: string }
                  from_atomic: { $ref: "#/components/schemas/Uint" }
                  to_atomic: { $ref: "#/components/schemas/Uint" }
                  max_quantity: { $ref: "#/components/schemas/Uint" }
                  changed_at: { $ref: "#/components/schemas/Time" }
                  at: { $ref: "#/components/schemas/Time" }
                  by: { type: object, properties: { name: { type: string } } }
                  note: { type: string }
        answers: { $ref: "#/components/schemas/DraftRecord" }
        dispute_messages: { $ref: "#/components/schemas/DraftRecord" }
        suggestions:
          type: array
          items:
            type: object
            required: [what, kind, why, limits]
            properties:
              what: { enum: [prices, answers, dispute_messages] }
              kind: { enum: [let_go, hold_back], description: "let_go: it earned acting on its own; hold_back: a person put back some of its last ten price changes" }
              why: { type: string }
              limits: { $ref: "#/components/schemas/ApplicationLimits" }
    DraftRecord:
      type: object
      properties:
        sent: { type: integer, description: Sent as written }
        sent_edited: { type: integer }
        discarded: { type: integer }
        lapsed: { type: integer }
        open: { type: integer }
        in_a_row: { type: integer, description: Newest decided drafts sent as written in a row }
        held: { type: boolean }
    ApplicationWithSecret:
      allOf:
        - { $ref: "#/components/schemas/ApplicationCreate" }
        - type: object
          required: [id, client_id, client_secret, created_at]
          properties:
            id: { type: string }
            client_id: { type: string }
            client_secret: { type: string, description: Shown once }
            created_at: { $ref: "#/components/schemas/Time" }

    ProductCreate:
      type: object
      required: [product_id, name]
      properties:
        product_id: { type: string, pattern: "^[a-z][a-z0-9_]{2,39}$" }
        name: { type: string, maxLength: 80 }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
    Product:
      allOf:
        - { $ref: "#/components/schemas/ProductCreate" }
        - type: object
          required: [versions, created_at]
          properties:
            versions: { type: array, items: { type: string } }
            created_at: { $ref: "#/components/schemas/Time" }
    ProductPage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/Product" } } } }
    ProductVersion:
      type: object
      required: [product_id, version, digest, manifest, published_at]
      properties:
        product_id: { type: string }
        version: { type: string }
        digest: { $ref: "#/components/schemas/Digest" }
        manifest: { type: object, description: The manifest exactly as published }
        published_at: { $ref: "#/components/schemas/Time" }

    ProvisioningKey:
      type: object
      required: [key_id, product_id, public_key, require_for_claims, created_at]
      properties:
        key_id: { type: string }
        product_id: { type: string }
        public_key: { type: string, pattern: "^[0-9a-f]{64}$" }
        require_for_claims: { type: boolean }
        created_at: { $ref: "#/components/schemas/Time" }
        revoked_at: { type: [string, "null"], format: date-time }
    ManifestUnit:
      type: object
      description: One line of the station's manifest (JSON lines); other fields of the line are ignored.
      required: [record, attestation]
      properties:
        serial: { type: string }
        module_id: { type: string }
        evidence_pubkey: { type: string, pattern: "^[0-9a-f]{64}$" }
        record: { type: string, contentEncoding: base64, description: "The flashed record: header, CBOR body, signature" }
        attestation:
          type: object
          required: [body, sig]
          properties:
            body: { type: string, contentEncoding: base64, description: "Canonical CBOR {v, serial, hw_id, product_id, module_id, evidence_pubkey, record_digest, provisioned_at_ms}" }
            sig: { type: string, contentEncoding: base64, description: "Ed25519 over TLAY-MCE/factory-unit/v1 || 0x00 || body" }
            key_id: { type: string }
    ManufacturedUnit:
      type: object
      required: [serial, product_id, hw_id, module_id, evidence_public_key, record_digest, key_id, provisioned_at, imported_at, state, config]
      properties:
        serial: { type: string }
        product_id: { type: string }
        hw_id: { type: string, description: "Chip id the record is bound to (ESP32: base MAC)" }
        module_id: { type: string }
        evidence_public_key: { type: string, pattern: "^[0-9a-f]{64}$", description: The evidence key the module reported at the factory; a claim must prove possession of it }
        record_digest: { type: string, pattern: "^sha256:[0-9a-f]{64}$" }
        key_id: { type: string, description: The provisioning key that signed record and attestation }
        provisioned_at: { $ref: "#/components/schemas/Time" }
        imported_at: { $ref: "#/components/schemas/Time" }
        device_id: { type: [string, "null"] }
        state: { enum: [claimed, unclaimed] }
        config:
          type: object
          description: >-
            The deployment configuration in the record (gateway_url, issuer_keys, ota, payment incl. owner and allow-lists)
            and wifi_provisioning (whether the unit has installer Wi-Fi provisioning; its SRP verifier is not returned)
    InstallationCredential:
      type: object
      required: [id, state, created_at, expires_at]
      properties:
        id: { type: string }
        product_id: { type: [string, "null"] }
        state: { enum: [open, used, expired, revoked] }
        created_at: { $ref: "#/components/schemas/Time" }
        expires_at: { $ref: "#/components/schemas/Time" }
        used_at: { type: [string, "null"] }
        device_id: { type: [string, "null"], description: The device it claimed }
        revoked_at: { type: [string, "null"] }
    Device:
      type: object
      required: [device_id, identity_state, connection, product, keys, modules, resource_version]
      properties:
        device_id: { type: string }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        name: { type: string, description: What the team calls it }
        location: { type: string, description: The team's own note of where it is (not shown to buyers) }
        place: { type: string, description: "Where buyers find it: shown with its listed services" }
        virtual: { type: boolean, description: "Run by the platform for its product (POST /devices/virtual), not hardware" }
        retired: { type: object, properties: { at: { $ref: "#/components/schemas/Time" }, reason: { type: string } }, description: Present while the device is retired }
        paused: { $ref: "#/components/schemas/Pause" }
        running_7d:
          type: object
          description: >-
            How much of the last week (or since the device was added) it spent running: overlapping runs once, a run still
            going up to now; runs started in that time. Absent before an hour.
          properties:
            share: { type: number, minimum: 0, maximum: 1 }
            runs: { type: integer, minimum: 0 }
        last_connection_error:
          type: object
          description: The last connection the gateway refused for it (retired, revoked, module_not_bound, device_mismatch), while newer than its last good one
          properties: { at: { $ref: "#/components/schemas/Time" }, reason: { type: string }, module_id: { type: string } }
        identity_state: { enum: [unclaimed, claimed, registry_pending, active, suspended, revoked] }
        connection:
          type: object
          required: [state, freshness]
          properties:
            state: { enum: [offline, connecting, online, degraded] }
            last_seen_at: { $ref: "#/components/schemas/Time" }
            freshness: { enum: [live, recent, stale, unknown] }
            online_share_7d: { type: number, minimum: 0, maximum: 1, description: "Share of the last week connected (or since its connections were first recorded); absent before an hour of history" }
        product:
          type: object
          required: [product_id, version, digest, device_confirmed]
          properties:
            product_id: { type: string }
            version: { type: string }
            digest: { $ref: "#/components/schemas/Digest" }
            device_confirmed: { type: boolean, description: The device bound the same digest }
        mode: { enum: [mcu, module] }
        firmware:
          type: object
          description: What the device reported in its last transport-signed auth (DEVICE_TRANSPORT §2).
          properties:
            version: { type: string, description: "<image name>/<image version>" }
            device_api: { type: array, items: { type: integer }, description: "[major, minor, patch]" }
            mode: { enum: [mcu, module] }
            development: { type: boolean }
            capabilities: { type: integer, description: Capability bitmask (specs/generated/TABLES.md) }
            owner_sweep_address: { $ref: "#/components/schemas/EvmAddress" }
            payment_token: { $ref: "#/components/schemas/EvmAddress", description: "The primary token the device's payment key signs for" }
            payment_tokens:
              type: array
              items: { $ref: "#/components/schemas/EvmAddress" }
              description: "A device paying in several assets: every token it signs for, primary first. Quotes priced in another asset are refused for this device"
            payment_policy:
              type: object
              properties:
                providers: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
                verifiers: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
                max_fee_bps: { type: integer }
            factory:
              type: object
              description: >-
                The factory record the device runs on (docs/design/FACTORY_PROVISIONING.md): the unit's serial
                and the digest of the signed record, checked at every connect against the imported production
                manifest line of its module. Absent when the device reports no record and no unit is imported
                for its module.
              required: [verification]
              properties:
                serial: { type: string }
                record_digest: { type: string, pattern: "^sha256:[0-9a-f]{64}$" }
                verification:
                  enum: [matched, mismatch, not_reported, not_imported]
                  description: >-
                    matched = serial, record digest, owner sweep address and allow-lists as imported; mismatch = something
                    differs (see mismatches; webhook device.factory_mismatch); not_reported = an imported unit runs without
                    its record (build-time configuration); not_imported = no manifest line for this module.
                mismatches: { type: array, items: { enum: [serial, record_digest, owner_sweep_address, payment_policy.providers, payment_policy.verifiers, payment_policy.max_fee_bps] } }
        keys:
          type: array
          items:
            type: object
            required: [key_id, purpose, algorithm, public_key, valid_from]
            properties:
              key_id: { type: string }
              purpose: { enum: [evidence, transport, payment] }
              algorithm: { enum: [ed25519, secp256k1] }
              public_key: { type: string }
              address: { $ref: "#/components/schemas/EvmAddress" }
              valid_from: { $ref: "#/components/schemas/Time" }
              valid_to: { $ref: "#/components/schemas/Time" }
              revoked_at: { $ref: "#/components/schemas/Time" }
        modules:
          type: array
          items: { type: object, required: [module_id, bound_at], properties: { module_id: { type: string }, bound_at: { $ref: "#/components/schemas/Time" }, unbound_at: { $ref: "#/components/schemas/Time" } } }
        registry:
          type: object
          properties:
            network: { $ref: "#/components/schemas/Caip2" }
            registry_contract: { $ref: "#/components/schemas/EvmAddress" }
            registry_device_key: { type: string, pattern: "^0x[0-9a-f]{64}$" }
            state: { enum: [none, pending, confirmed, failed] }
            status: { enum: [none, active, suspended, revoked], description: "On-chain status, re-read from the registry" }
            controller: { $ref: "#/components/schemas/EvmAddress" }
            binding_version: { type: integer }
            key_commitment: { type: string, description: "keccak256(module_id || 0x00 || evidence_key_id || 0x00 || evidence_public_key)" }
            product_digest: { type: string }
            binding_current: { type: boolean, description: Whether the on-chain commitments equal the device's current module key and product version }
            tx: { type: string }
        security: { $ref: "#/components/schemas/DeviceSecurity" }
        resource_version: { type: integer }
    DevicePage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/Device" } } } }

    Listing:
      type: object
      properties:
        visibility: { enum: [public, private] }
        summary: { type: string }
        description: { type: string }
        tags: { type: array, items: { type: string } }
        image_url: { type: string }
        availability: { $ref: "#/components/schemas/Availability" }
        show_record: { type: boolean }
        hours_changed_at: { $ref: "#/components/schemas/Time", description: "When the hours were last set (the seller's view): a suggestion of wider hours counts from here" }
        listed_at: { $ref: "#/components/schemas/Time" }
    MachineRecord:
      type: object
      description: >-
        What happened to the orders other organisations placed on a machine, and how much of the last week it was
        connected. Counted by the platform from the contracts' settlements and the gateway's connections; not a rating.
      required: [orders, buyers, delivered, not_delivered, disputes]
      properties:
        since: { $ref: "#/components/schemas/Time" }
        orders: { type: integer, description: "Ended orders of other organisations (a buyer's cancellation before the start is not counted)" }
        buyers: { type: integer, description: Distinct buyer wallets among them }
        delivered: { type: integer, description: "Something delivered and accepted (or the challenge period passed); timed access and subscription periods served" }
        not_delivered: { type: integer, description: "Refunded in full: the device did not start, or delivered nothing" }
        disputes:
          type: object
          properties:
            opened: { type: integer }
            open: { type: integer, description: Not decided yet }
            upheld: { type: integer, description: The resolver settled what the device measured }
            reduced: { type: integer, description: The resolver settled less than the device measured }
            refunded: { type: integer, description: "Refunded in full: by the resolver, or because no decision came in time" }
        online_share_7d: { type: number, minimum: 0, maximum: 1, description: "Share of the last week connected (or since connections were first recorded); absent before an hour of history" }
    Pause:
      type: object
      description: Present while the machine is paused for maintenance (POST /devices/{device_id}/pause)
      properties:
        since: { $ref: "#/components/schemas/Time" }
        until: { $ref: "#/components/schemas/Time", description: When it ends by itself; absent until resumed }
        note: { type: string }
    ServiceRequest:
      type: object
      description: >-
        A buyer's "ask for a machine". `answers` is the list of answers for the wallet that asked, and a count in the
        market-wide list (with `answered_with`, the service this organisation answered with, and `my_offer`, the
        price it offered).
      properties:
        id: { type: string }
        text: { type: string }
        place: { type: string }
        kind: { enum: [metered_service_escrow, access_lease, access_subscription] }
        state: { enum: [open, closed, expired] }
        created_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time }
        about:
          type: object
          description: The service the request is about, when the buyer asked its seller for a lower price
          properties: { offering_id: { type: string }, name: { type: string } }
        answered_with: { type: string }
        my_offer: { type: object, properties: { price_atomic: { $ref: "#/components/schemas/Uint" }, expires_at: { $ref: "#/components/schemas/Time" } } }
        answers:
          oneOf:
            - type: integer
            - type: array
              items:
                type: object
                properties:
                  offering_id: { type: string }
                  name: { type: string }
                  listed: { type: boolean, description: Still listed in the market }
                  note: { type: string }
                  answered_at: { type: string, format: date-time }
                  seller: { type: object, properties: { organization_id: { type: string }, name: { type: string } } }
                  offer:
                    type: object
                    description: >-
                      A price for this wallet only. state: open (it can be ordered at it: POST /quotes with
                      request_id), ordered (an order at it that was not withdrawn), expired, or ended (the service's
                      terms changed since).
                    properties:
                      price_atomic: { $ref: "#/components/schemas/Uint" }
                      list_price_atomic: { $ref: "#/components/schemas/Uint" }
                      asset: { $ref: "#/components/schemas/Caip19" }
                      unit: { type: string }
                      template: { type: string }
                      expires_at: { $ref: "#/components/schemas/Time" }
                      state: { enum: [open, ordered, expired, ended] }
    OfferCreate:
      type: object
      required: [price_atomic]
      description: A price for the wallet that asked only, below the list price (unit price, or price per period)
      properties:
        price_atomic: { $ref: "#/components/schemas/Uint" }
        valid_days: { type: integer, minimum: 1, maximum: 30, default: 7 }
    OpeningWatch:
      type: object
      properties:
        offering_id: { type: string }
        address: { type: string }
        watching: { type: boolean }
        when: { enum: [open, online, off_peak, price] }
        at_most_atomic: { type: string, description: "when: price: the price it waits for" }
        asset: { type: string, description: "when: price: the asset that price is in" }
    Availability:
      type: object
      description: >-
        Weekly windows in the seller's time zone when other organisations can order the service (quotes outside them
        are refused: conflict, details.reason outside_availability, details.opens_at). It limits ordering, not how an
        order already placed runs; the seller's own organisation is not limited. Not part of the signed terms.
      required: [time_zone, windows]
      properties:
        time_zone: { type: string, description: "An IANA time zone, e.g. Europe/Berlin or UTC" }
        windows:
          type: array
          maxItems: 14
          items:
            type: object
            required: [days, from, to]
            properties:
              days: { type: array, items: { type: integer, minimum: 1, maximum: 7 }, description: ISO weekdays, 1 Monday to 7 Sunday }
              from: { type: string, pattern: "^([01][0-9]|2[0-3]):[0-5][0-9]$" }
              to: { type: string, pattern: "^([01][0-9]|2[0-3]):[0-5][0-9]$", description: Earlier than from runs past midnight }
        open: { type: boolean, description: "Catalog only: orderable now" }
        opens_at: { $ref: "#/components/schemas/Time" }
        closes_at: { $ref: "#/components/schemas/Time" }
    CatalogEntry:
      type: object
      required: [offering_id, name, seller, version, terms_hash, terms, device, price_atomic]
      properties:
        offering_id: { type: string }
        name: { type: string }
        seller: { $ref: "#/components/schemas/SellerFacts" }
        summary: { type: string }
        description: { type: string }
        image_url: { type: string, description: An https image the seller gives }
        availability: { $ref: "#/components/schemas/Availability" }
        orderable:
          type: object
          description: >-
            Whether another organisation can order it now: inside the seller's hours and its machine not paused for
            maintenance; when not, the time it can again (absent while paused with no end)
          properties: { now: { type: boolean }, opens_at: { $ref: "#/components/schemas/Time" } }
        off_peak:
          type: object
          description: "Terms with an off-peak price: whether an order placed now pays it, and until when; or when it begins next"
          properties: { now: { type: boolean }, ends_at: { $ref: "#/components/schemas/Time" }, starts_at: { $ref: "#/components/schemas/Time" } }
        tags: { type: array, items: { type: string } }
        listed_at: { $ref: "#/components/schemas/Time" }
        version: { type: integer }
        terms_hash: { type: string }
        terms: { $ref: "#/components/schemas/ServiceTerms" }
        actions:
          type: array
          description: How each sold action is invoked (its input fields from the device's product version)
          items: { type: object, properties: { name: { type: string }, input: { type: object }, max_duration_ms: { type: integer } } }
        device:
          type: object
          properties:
            device_id: { type: string }
            product_id: { type: string }
            online: { type: boolean }
            virtual: { type: boolean, description: "A virtual device run by the platform (test deployments), not hardware" }
            security_reasons: { type: array, items: { type: string }, description: "When the device does not meet its seller's security policy (or does not report): what is missing" }
            security_enforcement: { enum: [report, refuse_commerce], description: "What the seller's policy does when a device fails it" }
            security: { enum: [meets, fails, not_reported, no_policy] }
            registry: { type: object, properties: { network: { $ref: "#/components/schemas/Caip2" }, status: { type: string } } }
            record: { $ref: "#/components/schemas/MachineRecord", description: Where the seller shows it }
            paused: { $ref: "#/components/schemas/Pause" }
            place: { type: string, description: Where buyers find the machine (its seller's words) }
            in_use:
              type: object
              description: >-
                Present while the machine runs an order on what this service uses: a start now is refused with device_busy
                (whose details carry free_by exactly, same_order when the run holding it is under the same order, and the
                holder and since only for the device's own organisation). free_by is when it should be free again (the
                run's length, at most its action's longest), rounded up to the quarter minute; absent when that is not
                known or has passed.
              properties:
                free_by: { $ref: "#/components/schemas/Time" }
        price_atomic: { $ref: "#/components/schemas/Uint", description: "Unit price (metered) or price (lease, subscription period) of an order placed now: the off-peak one in its hours" }
        resolver: { $ref: "#/components/schemas/ResolverRecord" }
        pool: { $ref: "#/components/schemas/PoolSummary", description: "One of a pool of identical machines: quote the pool (POST /quotes {pool_id}) and the platform assigns a free one" }
    ResolverRecord:
      type: object
      description: >-
        The dispute resolver the terms name, and what happened to the disputes of every order on the platform whose
        terms name it (the decisions are on chain; this counts them). Present when the terms name a resolver.
      properties:
        address: { $ref: "#/components/schemas/EvmAddress" }
        organization: { type: string, description: The organisation that proved by signature that it decides as this address }
        decided: { type: integer }
        for_seller: { type: integer, description: Decided for what the device measured (or more) }
        for_buyer: { type: integer, description: Decided for less than measured }
        timed_out: { type: integer, description: "No decision in time: the buyer got everything back" }
        open: { type: integer }
        median_decision_s: { type: integer, description: From the dispute to the resolver's settlement, over decided disputes }
    Bundle:
      type: object
      required: [id, state, network, asset, total_atomic, parts]
      properties:
        id: { type: string }
        state:
          enum: [quoted, awaiting_funding, starting, started, failed]
          description: failed = not every part was funded before the start deadline; funded parts are refunded in full
        network: { $ref: "#/components/schemas/Caip2" }
        asset: { $ref: "#/components/schemas/Caip19" }
        total_atomic: { $ref: "#/components/schemas/Uint" }
        expires_at: { $ref: "#/components/schemas/Time" }
        start_deadline: { $ref: "#/components/schemas/Time" }
        parts:
          type: array
          items: { type: object, properties: { quote_id: { type: string }, offering_id: { type: string }, amount_atomic: { $ref: "#/components/schemas/Uint" }, agreement_id: { type: string }, state: { type: string } } }
        created_at: { $ref: "#/components/schemas/Time" }
    SecurityPolicy:
      type: object
      additionalProperties: false
      properties:
        require_secure_boot: { type: boolean }
        min_flash_encryption: { enum: [off, development, release] }
        min_key_protection: { enum: [none, nvs_encrypted, secure_element] }
        require_jtag_disabled: { type: boolean }
        require_download_mode_restricted: { type: boolean }
        min_secure_version: { type: integer, minimum: 0, maximum: 4294967295, description: Anti-rollback counter (ESP eFuse secure_version) }
        require_known_firmware: { type: boolean, description: The running image's digest must identify an uploaded firmware release of this organisation }
        enforcement: { enum: [report, refuse_commerce], default: report }
    SecurityPolicyView:
      type: object
      required: [product_id, policy, updated_at]
      properties:
        product_id: { type: string }
        policy: { $ref: "#/components/schemas/SecurityPolicy" }
        updated_at: { $ref: "#/components/schemas/Time" }
    DeviceSecurity:
      type: object
      description: >-
        The security state the running firmware reports in its transport-signed auth, and the verdict under the
        product's policy. A self-report: as trustworthy as secure boot, not hardware-rooted attestation.
      properties:
        reported:
          type: object
          properties:
            key_protection: { enum: [none, nvs_encrypted, secure_element] }
            secure_boot: { type: boolean }
            flash_encryption: { enum: [off, development, release] }
            jtag_disabled: { type: boolean }
            download_mode_restricted: { type: boolean }
            secure_version: { type: integer }
            app_digest_kind: { enum: [esp_app_digest, image_sha256] }
            app_digest: { type: string, pattern: "^[0-9a-f]{64}$" }
        verdict:
          type: object
          required: [state, reasons]
          properties:
            state: { enum: [meets, fails, not_reported, no_policy], description: "webhook device.security_mismatch when a device connects failing (or not reporting)" }
            reasons: { type: array, items: { type: string } }
            enforcement: { enum: [report, refuse_commerce] }
            firmware_release: { type: string, description: The registered release the running image is }
    PropertyState:
      type: object
      required: [device_id, reported, desired, resource_version]
      properties:
        device_id: { type: string }
        reported:
          type: object
          additionalProperties:
            type: object
            required: [value, observed_at, received_at, freshness, clock_trusted]
            properties:
              value: {}
              observed_at: { $ref: "#/components/schemas/Time" }
              received_at: { $ref: "#/components/schemas/Time" }
              freshness: { enum: [live, recent, stale] }
              clock_trusted: { type: boolean }
              source: { $ref: "#/components/schemas/Source" }
        desired:
          type: object
          additionalProperties:
            type: object
            properties:
              value: {}
              change_id: { type: string }
              invocation_id: { type: string }
              state: { enum: [pending, applied, rejected, superseded] }
        resource_version: { type: integer }

    InvocationState: { enum: [accepted, dispatched, acknowledged, running, cancel_requested, completed, failed, cancelled, expired, unknown] }
    InvocationCreate:
      type: object
      required: [action, product_version, parameters, expires_at]
      properties:
        action: { type: string }
        product_version: { type: string }
        parameters: { $ref: "#/components/schemas/Fields" }
        authorization_ref: { type: string, description: Grant id (enterprise / free authorisation) }
        agreement_id: { type: ["string", "null"], description: Required when the action requires an on-chain right }
        expires_at: { $ref: "#/components/schemas/Time" }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
    Invocation:
      type: object
      required: [invocation_id, device_id, action, state, status_url, accepted_at, resource_version]
      properties:
        invocation_id: { type: string }
        device_id: { type: string }
        action: { type: string }
        product_version: { type: string }
        parameters: { $ref: "#/components/schemas/Fields" }
        state: { $ref: "#/components/schemas/InvocationState" }
        status_url: { type: string }
        accepted_at: { $ref: "#/components/schemas/Time" }
        dispatched_at: { $ref: "#/components/schemas/Time" }
        acknowledged_at: { $ref: "#/components/schemas/Time" }
        started_at: { $ref: "#/components/schemas/Time", description: From the application's real start report }
        finished_at: { $ref: "#/components/schemas/Time" }
        result: { $ref: "#/components/schemas/Fields" }
        failure: { type: object, properties: { reason: { type: string }, stage: { enum: [cloud, gateway, runtime, module, application] } } }
        receipt_source: { $ref: "#/components/schemas/Source" }
        enforcement_points: { type: array, items: { $ref: "#/components/schemas/EnforcementPoint" } }
        evidence_refs: { type: array, items: { type: string } }
        meters: { type: array, items: { type: object, properties: { meter: { type: string }, quantity: { $ref: "#/components/schemas/Uint" }, unit: { type: string }, scale: { type: integer } } } }
        authorization_ref: { type: string }
        agreement_id: { type: ["string", "null"] }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        resource_version: { type: integer }
    InvocationPage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/Invocation" } } } }

    DeviceEvent:
      type: object
      required: [id, device_id, name, payload, source, origin, observed_at, received_at, evidence_id]
      properties:
        id: { type: string }
        device_id: { type: string }
        name: { type: string }
        payload: { $ref: "#/components/schemas/Fields" }
        source: { $ref: "#/components/schemas/Source" }
        origin: { enum: [remote_invocation, local_application] }
        observed_at: { $ref: "#/components/schemas/Time" }
        received_at: { $ref: "#/components/schemas/Time" }
        clock_trusted: { type: boolean }
        links: { $ref: "#/components/schemas/Links" }
        evidence_id: { type: string }
        development_only: { type: boolean }
    DeviceEventPage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/DeviceEvent" } } } }
    MeterReading:
      type: object
      required: [meter, unit, scale, total, quality_flags, samples_ref]
      properties:
        meter: { type: string }
        unit: { type: string }
        scale: { type: integer }
        total: { $ref: "#/components/schemas/Uint", description: Measured total (estimates excluded) }
        estimated_total: { $ref: "#/components/schemas/Uint" }
        epochs: { type: array, description: "One counter segment per module, boot and epoch (a replacement module counts from its own start)", items: { type: object, properties: { epoch: { type: string, description: "boot_id:epoch" }, module_id: { type: string }, baseline: { $ref: "#/components/schemas/Uint" }, last: { $ref: "#/components/schemas/Uint" } } } }
        quality_flags: { type: array, items: { enum: [gap, overflow, unit_mismatch, regression, drift, estimated, epoch_reset] } }
        gaps: { type: array, items: { type: object, properties: { from: { $ref: "#/components/schemas/Time" }, to: { $ref: "#/components/schemas/Time" } } } }
        samples_ref: { type: string, description: Cursor/URL to raw signed samples }

    GrantCreate:
      type: object
      required: [expires_at]
      description: >-
        Access grants (devices, products, actions, limits) and funds grants are separate grants.
        A funds grant names exactly one grantee: an application / agent (spending from `buyer_address`,
        active only after that address signs it) or a device (buying with its own payment key; the
        platform refuses a device's quotes without one).
      properties:
        grantee_application_id: { type: string }
        grantee_device_id: { type: string, description: "Funds grants only: a device allowed to buy" }
        buyer_address: { $ref: "#/components/schemas/EvmAddress", description: "Application funds grants: the payer, who must sign the grant" }
        on_behalf_of: { type: string, description: Verified end-user mapping id (not a free-form claim) }
        devices: { type: array, items: { type: string } }
        products: { type: array, items: { type: string } }
        actions: { type: array, items: { type: string } }
        parameter_limits: { type: object, description: "{action: {param: {minimum, maximum}}} — must be within product policy" }
        read_scopes: { type: array, items: { enum: [properties, events, meters, evidence] } }
        funds:
          type: object
          description: >-
            Separate from access. Absent = no spending right. Each agreement reserves the most it can cost
            until it ends (a closed escrow counts what was settled; one that expires or is cancelled unfunded
            counts nothing); settled + open + new must fit max_total. A recurring budget (period_days with
            max_per_period) also caps what the agreements made in each period may cost, the periods counted
            from period_start; an agreement counts in the period it was made in. The payer signs the period
            with the rest (FundsGrant version 2). max_total is required unless the budget is recurring.
          required: [asset, max_per_tx]
          properties:
            asset: { $ref: "#/components/schemas/Caip19" }
            max_per_tx: { $ref: "#/components/schemas/Uint", description: Per agreement (one funding authorisation each) }
            max_total: { $ref: "#/components/schemas/Uint", description: "In all, while it lasts. A recurring budget's default: max_per_period times the periods it touches" }
            period_days: { type: integer, minimum: 1, maximum: 365, description: "Recurring: the length of a period, in days (with max_per_period)" }
            max_per_period: { $ref: "#/components/schemas/Uint", description: "Recurring: the most each period may spend; max_per_tx <= max_per_period <= max_total" }
            period_start: { $ref: "#/components/schemas/Time", readOnly: true, description: "Recurring: when the first period began (set by the platform: creation, or the start of the budget a renewal renews)" }
            allowed_payees: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
            allowed_offerings: { type: array, items: { type: string } }
            refund_to:
              $ref: "#/components/schemas/EvmAddress"
              description: >-
                Device grants only: the owner's address that receives escrow refunds of agreements the
                device buys (escrow v3 `Terms.refundTo`, fixed in the provider-signed terms and the funding
                nonce). It must be the owner sweep address provisioned on the device (400 otherwise): the
                device checks the terms it funds and refuses any other refund recipient. Absent = refunds go
                to the device's payment address. An application buyer's refunds always go to the buyer.
        max_invocations: { type: integer }
        expires_at: { $ref: "#/components/schemas/Time" }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        answers_ask: { type: string, description: "Application funds grants: the open ask (BudgetAsk id) of the same application this grant answers; the ask becomes answered with this grant's id" }
    BudgetAsk:
      type: object
      description: What an agent asked of its budget (POST /grants/{id}/asks), and how its organisation answered.
      required: [id, state, asked_at, max_total, max_per_tx, days, reason]
      properties:
        id: { type: string }
        state: { enum: [open, answered, declined] }
        asked_at: { $ref: "#/components/schemas/Time" }
        max_total: { $ref: "#/components/schemas/Uint" }
        max_per_tx: { $ref: "#/components/schemas/Uint" }
        days: { type: integer }
        reason: { type: string }
        answered_at: { $ref: "#/components/schemas/Time" }
        new_grant_id: { type: string, description: "answered: the new grant (it waits for the payer's signature until signed)" }
    Grant:
      allOf:
        - { $ref: "#/components/schemas/GrantCreate" }
        - type: object
          required: [id, state, created_at]
          properties:
            id: { type: string }
            state: { enum: [requires_buyer_signature, active, expired, revoked] }
            typed_data: { type: object, description: "requires_buyer_signature: the EIP-712 FundsGrant the payer signs (POST /grants/{id}/buyer-signatures)" }
            funds_used:
              type: object
              properties:
                settled: { $ref: "#/components/schemas/Uint" }
                signed_unsettled: { $ref: "#/components/schemas/Uint" }
                available: { $ref: "#/components/schemas/Uint", description: "What can be spent now: in all, and for a recurring budget in this period too" }
                period:
                  type: object
                  description: Recurring budgets, the period it is in
                  properties:
                    start: { $ref: "#/components/schemas/Time" }
                    resets_at: { $ref: "#/components/schemas/Time" }
                    settled: { $ref: "#/components/schemas/Uint" }
                    signed_unsettled: { $ref: "#/components/schemas/Uint" }
                    available: { $ref: "#/components/schemas/Uint" }
            renews: { type: string, description: "The budget this one renews (POST /grants/{id}/renewals)" }
            replaced_by: { type: string, description: "The renewal that replaced this budget once in force (this one is then revoked)" }
            ask: { $ref: "#/components/schemas/BudgetAsk", description: "Application funds grants: the latest ask its application made of it, answered or not" }
            activity:
              type: object
              description: >-
                Funds grants, on GET /grants/{id} only: what the grantee bought under it, by service (the 20 largest;
                spent = settled, held = still reserved by orders under way), and the purchases the grant refused in the
                last 30 days with why. Refusals are kept from quotes and orders (not estimates), at most 100 a grant
                and day, and each day's first tells the organisation's people (notification budget.refused).
              properties:
                by_service:
                  type: array
                  items:
                    type: object
                    properties:
                      offering_id: { type: string }
                      offering_name: { type: string }
                      seller_organization_id: { type: string }
                      orders: { type: integer }
                      spent_atomic: { $ref: "#/components/schemas/Uint" }
                      held_atomic: { $ref: "#/components/schemas/Uint" }
                refused:
                  type: object
                  properties:
                    days: { type: integer }
                    total: { type: integer }
                    by_reason:
                      type: array
                      items:
                        type: object
                        properties:
                          reason: { $ref: "#/components/schemas/BudgetRefusal" }
                          count: { type: integer }
                          last_at: { $ref: "#/components/schemas/Time" }
                    recent:
                      type: array
                      description: The 10 latest.
                      items:
                        type: object
                        properties:
                          at: { $ref: "#/components/schemas/Time" }
                          reason: { $ref: "#/components/schemas/BudgetRefusal" }
                          offering_id: { type: string }
                          offering_name: { type: string }
                          amount_atomic: { $ref: "#/components/schemas/Uint" }
            created_at: { $ref: "#/components/schemas/Time" }
            revoked_at: { $ref: "#/components/schemas/Time" }
    BudgetRefusal:
      description: >-
        Why a funds grant refused a purchase. per_purchase: over max_per_tx; total: settled + held + this over
        max_total; period: over what a recurring budget has left this period; service: not in allowed_offerings; payee: a payee not in allowed_payees; asset: another token;
        payer: paid from another address; revoked; expired; unsigned: the payer has not signed it yet.
      enum: [per_purchase, total, period, service, payee, asset, payer, revoked, expired, unsigned]

    Party:
      type: object
      properties:
        application_id: { type: string }
        device_id: { type: string }
        address: { $ref: "#/components/schemas/EvmAddress" }
    ServiceTerms:
      type: object
      required: [template, device_id, action, unit, pricing, acceptance, payees]
      properties:
        template:
          enum: [access_lease, access_subscription, metered_service_escrow]
          description: >-
            metered_service_escrow: metered service, prepaid up to a cap, settled on the verified quantity, the rest refunded.
            access_lease: a time/use-bounded right, one payee. access_subscription: `subscription.periods` prepaid periods
            (each earned when it starts), 1..4 payees splitting the price, uses counted per period, the subscriber can
            cancel at any time and the periods not started are refunded to the terms' refundTo (contract SubscriptionLease).
        template_version: { type: string, default: "1" }
        device_id: { type: string }
        product_version: { type: string }
        action: { type: string, description: Capability action delivering the service }
        actions: { type: array, items: { type: string }, description: "access_lease / access_subscription: the covered actions (each must be a requires_agreement action)" }
        subscription:
          type: object
          description: access_subscription periods and use bound (uses are counted per period by the gateway)
          required: [period_s, periods]
          properties:
            period_s: { type: integer, minimum: 60, maximum: 31622400 }
            periods: { type: integer, minimum: 1, maximum: 1000 }
            max_uses_per_period: { type: integer, minimum: 0, description: 0 = unlimited within a period }
            grantor: { $ref: "#/components/schemas/EvmAddress", description: "Registry controller/operator that signs the subscription terms (default: payees[0])" }
        lease:
          type: object
          description: access_lease window and use bound (uses are counted by the gateway; the contract fixes the bound)
          properties:
            duration_s: { type: integer, minimum: 60 }
            max_uses: { type: integer, minimum: 0, description: 0 = unlimited within the window }
            grantor: { $ref: "#/components/schemas/EvmAddress", description: "Registry controller/operator that signs the lease terms (default: the payee)" }
        meter: { type: string, description: Billing-eligible meter (metered_service_escrow) }
        unit: { type: string }
        pricing:
          type: object
          required: [asset, mode]
          properties:
            asset: { $ref: "#/components/schemas/Caip19" }
            mode:
              enum: [free, fixed, per_unit, operator_quoted]
              description: >-
                operator_quoted: the operator's own platform prices each quote and signs it (EIP-712 OperatorQuote)
                with one of quote_signers, never above the maximum; applications and agents buy it, devices cannot.
            unit_price_atomic: { $ref: "#/components/schemas/Uint" }
            price_atomic: { $ref: "#/components/schemas/Uint", description: "access_lease fixed price; access_subscription price per period (the quote amount is price x periods)" }
            max_quantity: { $ref: "#/components/schemas/Uint" }
            quote_signers: { type: array, minItems: 1, maxItems: 5, items: { $ref: "#/components/schemas/EvmAddress" }, description: "operator_quoted: the operator's quoting keys (EOA or ERC-1271)" }
            max_unit_price_atomic: { $ref: "#/components/schemas/Uint", description: "operator_quoted escrow: the highest unit price a signed quote may carry" }
            max_price_atomic: { $ref: "#/components/schemas/Uint", description: "operator_quoted access_lease: the highest price a signed quote may carry" }
            off_peak:
              type: object
              description: >-
                A lower price in weekly hours of the seller's time zone (the windows as in Availability), for per_unit
                (unit_price_atomic) and fixed-price access_lease (price_atomic) terms. A quote placed in those hours locks
                the lower price (its terms say price_applied: off_peak), whenever the order is then placed and run.
                Above 0 and below the regular price; the largest order at it must still reach the network's smallest
                order.
              required: [time_zone, windows]
              properties:
                time_zone: { type: string }
                windows: { type: array, items: { type: object, properties: { days: { type: array, items: { type: integer } }, from: { type: string }, to: { type: string } } } }
                unit_price_atomic: { $ref: "#/components/schemas/Uint" }
                price_atomic: { $ref: "#/components/schemas/Uint" }
            price_applied: { enum: [off_peak], description: "In a quote's or order's locked terms only: the price is the off-peak one" }
        acceptance:
          type: object
          required: [method]
          properties:
            method: { enum: [buyer_explicit, verifier_with_challenge] }
            verifier: { $ref: "#/components/schemas/EvmAddress", description: "The escrow's verifier: the platform verifier, or the committee below" }
            verifier_committee:
              $ref: "#/components/schemas/EvmAddress"
              description: >-
                Verification template "committee": a VerifierCommittee contract (M-of-N, fixed members) that
                must include the platform verifier. Starts and deliveries then need M members' signatures
                (POST /agreements/{id}/verifier-signatures). A buying device must list the committee address as an allowed verifier.
            committee:
              type: object
              description: Read from the chain when the offering is published (members, threshold)
              properties: { address: { $ref: "#/components/schemas/EvmAddress" }, threshold: { type: integer }, members: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } } }
            challenge_period_s: { type: integer, minimum: 0 }
            start_deadline_s: { type: integer }
            delivery_deadline_s: { type: integer }
            dispute_resolver: { $ref: "#/components/schemas/EvmAddress" }
            dispute_timeout_s: { type: integer }
        payees:
          type: array
          description: >-
            metered_service_escrow: the service_provider receives the pool remainder, other payees their bps.
            access_lease: exactly one service_provider. access_subscription: 1..4 payees, payees[0] the service_provider,
            bps summing to 10000 (payee 0 receives the rounding remainder).
          items: { type: object, required: [address, bps], properties: { address: { $ref: "#/components/schemas/EvmAddress" }, bps: { type: integer, minimum: 0, maximum: 10000 },
                   role: { type: string, description: "service_provider, or a label such as operator, installer, partner" } } }
        partial_delivery: { enum: [pro_rata, all_or_nothing], default: pro_rata }
        cancellation: { type: object }
        platform_fee_disclosed: { type: boolean, description: Whether this service incurs a platform fee }
    ServiceOfferingCreate:
      type: object
      required: [name, terms]
      properties:
        name: { type: string, maxLength: 80 }
        terms: { $ref: "#/components/schemas/ServiceTerms" }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
    ServiceOffering:
      type: object
      required: [id, name, current_version, versions]
      properties:
        id: { type: string }
        name: { type: string }
        current_version: { type: integer }
        versions: { type: array, items: { type: object, properties: { version: { type: integer }, terms: { $ref: "#/components/schemas/ServiceTerms" }, terms_hash: { type: string }, published_at: { $ref: "#/components/schemas/Time" } } } }
        platform_fee_for_new_quotes: { type: object, properties: { bps: { type: integer }, recipient: { $ref: "#/components/schemas/EvmAddress" }, paid_from: { type: string } } }
        listing: { $ref: "#/components/schemas/Listing" }
        archived_at: { type: [string, "null"], description: Set while the service is archived (no longer offered) }
        sales:
          type: object
          description: Orders by state, and what settled orders charged and earned the payees, per asset
          properties:
            orders: { type: integer }
            open: { type: integer }
            settled: { type: integer }
            disputed: { type: integer }
            waiting_for_opening: { type: integer, description: "Buyer wallets waiting to be told when it opens (outside its hours); a count only" }
            waiting_for_off_peak: { type: integer, description: "Buyer wallets waiting to be told when its off-peak price starts; a count only" }
            waiting_for_price:
              type: object
              description: >-
                Buyer wallets waiting to be told when its price is at or below one they chose (in its asset now), and the
                highest of those prices: at it, one of them is told. Never who. In the detail view only; absent when none.
              properties: { wallets: { type: integer }, highest_atomic: { type: string } }
            asks:
              type: object
              description: >-
                Buyers who asked the seller alone for a lower price on it (a service request with offering_id) over the
                last `days` days: how many it answered, how many with an offer, how many of those paid an order at the
                offer, and how many open ones wait for an answer. On GET /service-offerings/{id} only; absent when no one
                asked.
              properties:
                days: { type: integer }
                asked: { type: integer }
                answered: { type: integer }
                offered: { type: integer }
                ordered: { type: integer, description: "Requests whose offer was ordered and paid on the chain" }
                waiting: { type: integer }
            run_hours:
              type: object
              description: >-
                When its machine ran: the minutes in each hour of the week over the last `days` days, summed (all its runs,
                overlapping ones once, the seller's own included). UTC, Monday 00:00 first. On a single service only.
              properties:
                days: { type: integer }
                minutes: { type: array, minItems: 168, maxItems: 168, items: { type: number } }
            usage:
              type: object
              description: >-
                Pay-for-what-you-use services with settled orders: of the orders the device started (not refunded for
                not starting, not cancelled before the start), the quantity ordered against the quantity charged, and how
                many ordered the most their version allowed. Absent before the first. In the unit of the service's meter.
              properties:
                orders: { type: integer }
                ordered: { $ref: "#/components/schemas/Uint" }
                settled: { $ref: "#/components/schemas/Uint" }
                at_limit: { type: integer, description: Orders of the most the terms allowed (max_quantity) }
                median_ordered: { $ref: "#/components/schemas/Uint" }
                median_settled: { $ref: "#/components/schemas/Uint" }
            missed:
              type: object
              description: >-
                Orders it could not take in the last 30 days, while listed: quotes other organisations' buyers asked for and
                were refused outside the seller's hours, while the machine was paused, or for more than one order allows
                (details.reason over_limit); estimates are not counted. Buyer wallets per day, counts only, at most 20 a
                day from any one asking organisation. Only on GET /service-offerings/{id}, as is `usage`. Absent when
                there were none.
              properties:
                days: { type: integer }
                outside_availability: { type: integer }
                device_paused: { type: integer }
                over_limit: { type: integer }
                pool_busy: { type: integer, description: "Every machine of its pool was busy (counted on the pool's first machine)" }
            advice:
              type: array
              description: >-
                What the facts suggest changing, most useful first; only on GET /service-offerings/{id}, for a listed
                service. raise_price and lower_price follow the same facts as a price rule (a step of the rule's size
                within its bounds, or 10%), shown three days after the terms last changed; lower_price also follows
                buyers who asked the seller for a lower price on it (`asks`) and did not order while it stood idle,
                through one storefront here and two for a rule; with no other price suggestion, lower_price also
                proposes the price that tells two wallets which paid before and wait for a lower price
                (`waiting_for_price`) while it stood idle, at most 30% below the price and not below a rule's floor
                (never followed by a rule); off_peak: busy at some hours
                of the day and nearly idle at others over four weeks, with no off-peak price yet (the hours are the
                seller's to choose); larger_limit: many orders at the most one allows; wider_hours: buyers came when it
                was closed. `change` is what POST /service-offerings/{id}/price-changes applies.
              items:
                type: object
                required: [kind, text, facts]
                properties:
                  kind: { enum: [raise_price, lower_price, off_peak, larger_limit, wider_hours] }
                  text: { type: string }
                  facts: { type: array, items: { type: string } }
                  change:
                    type: object
                    properties:
                      price_atomic: { $ref: "#/components/schemas/Uint" }
                      max_quantity: { $ref: "#/components/schemas/Uint" }
                      off_peak_price_atomic: { $ref: "#/components/schemas/Uint" }
            funnel:
              type: object
              description: >-
                Where buyers stop: the orders other organisations placed in the last 30 days (the seller's own are
                left out), how many were paid, started (the device began a run for it) and settled after a run, and
                why the others stopped. unsigned: the buyer signed the payment and it waited for the seller's signature
                (orders on the seller's own key); waiting_payment: not paid yet and may still be; left_unpaid: never
                paid; not_started: pay-for-what-you-use, paid, no run asked for before its start deadline, nothing
                charged; not_run: pay-for-what-you-use, paid, a run asked for that the device never began, nothing
                charged; cancelled_before_start: paid, then cancelled or finished by the buyer before any run. Counts
                only, only on GET /service-offerings/{id}. Absent when there were none.
              properties:
                days: { type: integer }
                placed: { type: integer }
                paid: { type: integer }
                started: { type: integer }
                settled: { type: integer }
                disputed: { type: integer }
                unsigned: { type: integer }
                waiting_payment: { type: integer }
                left_unpaid: { type: integer }
                not_started: { type: integer }
                not_run: { type: integer }
                cancelled_before_start: { type: integer }
            buyers:
              type: object
              description: >-
                Who buys: the paid orders other organisations placed in the last 30 days by kind of buyer. machine: a
                device paying with its own key; agent: on a funds grant or through the MCP server; person: in a shop;
                app: any other application. Shop and MCP are what the buyer's software says of itself (X-MCE-Client).
                buyers: different paying wallets or devices; returning: those with more than one paid order of this
                service, ever. Counts only, no buyer is named; only on GET /service-offerings/{id}. Absent when there
                were none.
              properties:
                days: { type: integer }
                buyers: { type: integer }
                returning: { type: integer }
                by_kind:
                  type: array
                  items:
                    type: object
                    properties:
                      kind: { type: string, enum: [person, agent, machine, app] }
                      orders: { type: integer }
                      settled: { type: integer }
                      buyers: { type: integer }
                      returning: { type: integer }
            by_asset: { type: array, items: { type: object, properties: { asset: { type: string }, earned_atomic: { type: string }, charged_atomic: { type: string } } } }
        price_rule: { $ref: "#/components/schemas/PriceRule" }
        price_proposal: { $ref: "#/components/schemas/PriceProposal" }
        price_changes:
          type: array
          description: The last ten price changes made through the platform (a rule's or the seller's), newest first; on a machine of a pool, the pool's
          items: { $ref: "#/components/schemas/PriceChange" }
        operator_quote_signing:
          type: object
          description: >-
            operator_quoted offerings: the fixed part of the EIP-712 OperatorQuote for the current version. The operator
            adds buyer, quantity, unitPrice, validUntil (unix s) and a fresh 32-byte nonce, signs, and gives the buyer
            the fields as `operator_quote` (TS SDK: operatorQuoteTypedData / operatorQuoteBody).
          properties:
            domain: { type: object, properties: { name: { type: string }, version: { type: string }, chainId: { type: integer }, verifyingContract: { $ref: "#/components/schemas/EvmAddress" } } }
            types: { type: object }
            primaryType: { const: OperatorQuote }
            message: { type: object, properties: { offering: { type: string }, offeringVersion: { type: integer }, termsHash: { type: string } } }
            signers: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
            max_price_atomic: { $ref: "#/components/schemas/Uint" }
    PriceRule:
      type: object
      properties:
        id: { type: string }
        applies_to: { type: object, description: "The service, or the pool its machine is in", properties: { offering_id: { type: string }, pool_id: { type: string } } }
        floor_atomic: { $ref: "#/components/schemas/Uint" }
        ceiling_atomic: { $ref: "#/components/schemas/Uint" }
        step_percent: { type: number }
        created_at: { $ref: "#/components/schemas/Time" }
        updated_at: { $ref: "#/components/schemas/Time" }
        checked_at: { $ref: "#/components/schemas/Time" }
    PriceChange:
      type: object
      properties:
        id: { type: string }
        source: { enum: [rule, seller, application], description: "application: an application of the seller's (e.g. an agent with the MCP server's seller tools) made it; its people were told" }
        application: { type: object, description: The application that made it (source application), properties: { id: { type: string }, name: { type: string } } }
        from_atomic: { $ref: "#/components/schemas/Uint" }
        to_atomic: { $ref: "#/components/schemas/Uint" }
        max_quantity: { $ref: "#/components/schemas/Uint" }
        facts: { type: array, items: { type: string } }
        versions: { type: array, description: The versions published, one per machine, items: { type: object, properties: { offering_id: { type: string }, version: { type: integer } } } }
        pool_id: { type: string }
        approved_by: { type: object, description: "The person who approved it, when an application proposed it (POST /price-proposals/{id}/approve)", properties: { user_id: { type: string }, name: { type: string } } }
        put_back:
          type: object
          description: A person put back this change of an application's (POST /price-changes/{id}/put-back)
          properties:
            at: { $ref: "#/components/schemas/Time" }
            by: { type: object, properties: { user_id: { type: string }, name: { type: string } } }
            note: { type: string }
            change_id: { type: string, description: The change that put it back }
        created_at: { $ref: "#/components/schemas/Time" }
    PriceProposal:
      type: object
      description: >-
        A new price and/or largest order an application proposed, with why, for a person of the seller to approve or
        decline. One open proposal per service or pool; it lapses after 7 days or when the price changes another way.
      properties:
        id: { type: string }
        applies_to: { type: object, properties: { offering_id: { type: string }, pool_id: { type: string } } }
        offering_id: { type: string, description: The service (on a pool, its first machine's) whose page shows it }
        service_name: { type: string }
        application: { type: object, properties: { id: { type: string }, name: { type: string } } }
        from_atomic: { $ref: "#/components/schemas/Uint" }
        price_atomic: { $ref: "#/components/schemas/Uint" }
        max_quantity: { $ref: "#/components/schemas/Uint" }
        reason: { type: string }
        facts: { type: array, items: { type: string } }
        state: { enum: [open, approved, declined, replaced, lapsed] }
        created_at: { $ref: "#/components/schemas/Time" }
        expires_at: { $ref: "#/components/schemas/Time" }
        decided_at: { $ref: "#/components/schemas/Time" }
        decided_by: { type: object, properties: { user_id: { type: string }, name: { type: string } } }
        note: { type: string, description: "The person's note when declined; why it lapsed or was replaced" }
        change_id: { type: string, description: The price change it became, when approved }
    Draft:
      type: object
      description: >-
        What an application drafted for a person of the seller to send: an answer to a buyer's request (a listed
        service and a note) or a message in a dispute on the seller's order. One open draft per request or dispute; it
        lapses after 7 days or when its request or dispute is over.
      properties:
        id: { type: string }
        kind: { enum: [request_answer, dispute_message] }
        request_id: { type: string }
        request_text: { type: string, description: What the buyer asked for (the buyer's text) }
        order_id: { type: string }
        offering: { type: object, properties: { id: { type: string }, name: { type: string } } }
        offer: { type: object, description: "An answer's offer: the price for the wallet that asked, made when a person sends it", properties: { price_atomic: { $ref: "#/components/schemas/Uint" }, valid_days: { type: integer } } }
        body: { type: string, description: The note to the buyer, or the dispute message (as sent, when sent) }
        reason: { type: string, description: Why, for the person who sends it }
        application: { type: object, properties: { id: { type: string }, name: { type: string } } }
        state: { enum: [open, sent, discarded, replaced, lapsed] }
        edited: { type: boolean, description: The person changed the text before sending it }
        created_at: { $ref: "#/components/schemas/Time" }
        expires_at: { $ref: "#/components/schemas/Time" }
        decided_at: { $ref: "#/components/schemas/Time" }
        decided_by: { type: object, properties: { user_id: { type: string }, name: { type: string } } }
        note: { type: string, description: "The person's note when discarded; why it lapsed or was replaced" }
    PaymentKey:
      type: object
      properties:
        key_id: { type: string }
        module_id: { type: string }
        address: { $ref: "#/components/schemas/EvmAddress" }
        state: { enum: [active, unconfirmed, abandoned, retiring, retired] }
        valid_from: { $ref: "#/components/schemas/Time" }
        valid_to: { $ref: "#/components/schemas/Time" }
        obligations: { $ref: "#/components/schemas/PaymentKeyObligations" }
        funds:
          description: The active key only, what its address holds to buy with (read from the chain, never estimated)
          type: array
          items: { type: object, properties: { network: { type: string }, asset: { type: string }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }, error: { type: string } } }
    PaymentKeyObligations:
      type: object
      description: What still refers to an address whose key is not active. Chain amounts are read, never estimated.
      properties:
        agreements: { type: array, items: { type: object, properties: { id: { type: string }, state: { type: string }, network: { type: string }, template: { type: string } } } }
        payments: { type: array, items: { type: object, properties: { id: { type: string }, state: { type: string }, amount_atomic: { $ref: "#/components/schemas/Uint" } } } }
        funds: { type: array, items: { type: object, properties: { network: { type: string }, asset: { type: string }, balance_atomic: { $ref: "#/components/schemas/Uint" }, escrow_credit_atomic: { $ref: "#/components/schemas/Uint" }, error: { type: string } } } }
    Notification:
      type: object
      properties:
        id: { type: string }
        kind:
          enum: [order.needs_signature, order.missed, order.disputed, order.paid, order.settled, device.offline, device.security, device.budget_low,
                 rollout.paused, rollout.completed, dispute.message, dispute.to_decide, delivery.ready, order.closed, order.expired, access.ending, dispute.reply,
                 service.open, service.off_peak, service.price, service.watch_ended, order.start_soon, request.answered, request.asked, request.lowered, share.credited, budget.refused, budget.low, budget.asked, budget.answered, budget.ready, budget.ending, price.changed, price.proposed, draft.ready, agent.earned]
        severity: { enum: [urgent, info] }
        title: { type: string }
        body: { type: string }
        path: { type: string, description: "Where it points in the recipient's app (operator app for people, the storefront for wallets), e.g. /orders/agr_…" }
        resource_id: { type: string }
        created_at: { type: string, format: date-time }
        read: { type: boolean }
        emailed: { type: boolean }
    Dispute:
      type: object
      properties:
        agreement_id: { type: string }
        state: { enum: [open, closed] }
        your_roles: { type: array, items: { enum: [buyer, seller, resolver] } }
        reason: { type: string }
        opened_at: { type: string, format: date-time }
        decide_by: { type: string, format: date-time }
        resolver: { type: string, nullable: true }
        without_decision: { enum: [refund_in_full] }
        can_decide: { type: boolean }
        can_write: { type: boolean }
        ordered_quantity: { type: string }
        delivered_quantity: { type: string }
        unit: { type: string }
        messages:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              author: { enum: [buyer, seller, resolver] }
              name: { type: string }
              reason: { type: boolean }
              body: { type: string }
              created_at: { type: string, format: date-time }
        runs: { type: array, items: { type: object, additionalProperties: true } }
        settlement: { type: object, properties: { quantity: { type: string }, reason: { type: string } } }
    NotificationSettings:
      type: object
      properties:
        email_address: { type: string }
        email_available: { type: boolean, description: Whether this platform sends email at all }
        kinds:
          type: array
          items:
            type: object
            properties:
              kind: { type: string }
              label: { type: string }
              severity: { enum: [urgent, info] }
              email: { type: boolean }
              default_email: { type: boolean }
    WalletSession:
      type: object
      properties:
        address: { type: string, description: The wallet, lower case }
        signed_out_before: { type: [string, "null"], format: date-time, description: Sign-ins made before this time count as signed out; null when the wallet was never signed out everywhere }
    WalletContact:
      type: object
      properties:
        wallet: { $ref: "#/components/schemas/EvmAddress" }
        email: { type: string, nullable: true }
        verified: { type: boolean }
        verified_at: { type: string, format: date-time }
    AgreementSummary:
      type: object
      properties:
        id: { type: string }
        state: { type: string }
        template: { type: string }
        device_id: { type: string }
        offering_id: { type: string }
        offering_name: { type: string, description: The service's name }
        amount_atomic: { $ref: "#/components/schemas/Uint" }
        asset: { $ref: "#/components/schemas/Caip19" }
        network: { $ref: "#/components/schemas/Caip2" }
        buyer: { $ref: "#/components/schemas/Party" }
        funded: { $ref: "#/components/schemas/Uint" }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        grant_id: { type: string }
        priced_by: { $ref: "#/components/schemas/EvmAddress", description: operator quoting key for operator_quoted prices }
        bundle_id: { type: string, description: The bundle this agreement is a part of }
        settlement_reason: { type: string, description: "Once anything is settled: why (e.g. resolved, dispute_timeout_refund, subscriber_cancelled: a cancelled subscription stays usable until its running period ends)" }
        used: { type: boolean, description: "A device has run under it (a paid metered order is ready to start until then)" }
        seller_organization_id: { type: string, description: "A marketplace purchase: the seller's organisation (when it is not the caller's)" }
        buyer_organization_id: { type: string, description: "A marketplace sale: the buyer's organisation (when it is not the caller's)" }
        created_at: { $ref: "#/components/schemas/Time" }
        updated_at: { $ref: "#/components/schemas/Time" }
    FirmwareReleaseSummary:
      type: object
      properties:
        id: { type: string }
        target: { type: string }
        hardware: { type: string }
        version: { type: string }
        security_version: { type: integer }
        image_size: { type: integer }
        key_id: { type: string }
        image_uploaded: { type: boolean }
        created_at: { $ref: "#/components/schemas/Time" }
        rollout: { type: object, additionalProperties: { type: integer }, description: devices per rollout state }
    OperatorQuote:
      type: object
      description: >-
        An operator-signed price. Accepted once (per nonce), only if signed by one of the offering's quote_signers for
        this offering version's terms_hash, this buyer and this quantity, within the maximum and before valid_until;
        the price is then locked into the quote's terms (terms_hash), the agreement and the on-chain terms.
      required: [offering_version, terms_hash, quantity, unit_price, valid_until, nonce, signature]
      properties:
        offering_version: { type: integer }
        terms_hash: { type: string }
        quantity: { $ref: "#/components/schemas/Uint", description: access_lease 1 }
        unit_price: { $ref: "#/components/schemas/Uint", description: access_lease the lease price }
        valid_until: { $ref: "#/components/schemas/Uint", description: unix seconds }
        nonce: { type: string, pattern: "^0x[0-9a-fA-F]{64}$" }
        signature: { type: string }
    ServiceOfferingPage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/ServiceOffering" } } } }
    QuoteCreate:
      type: object
      required: [quantity]
      description: "offering_id, or pool_id: a machine pool's service, quoted on a machine the platform assigns"
      properties:
        offering_id: { type: string }
        pool_id: { type: string, description: "Quote a machine pool (docs/design/MARKETPLACE.md \"Machine pools\"): the platform assigns a machine that is online and free and quotes its service (the answer's `pool` says which). 409 reason pool_busy when none is free. Not with offering_id, offering_version or operator_quote" }
        offering_version: { type: integer }
        quantity: { $ref: "#/components/schemas/Uint" }
        buyer: { $ref: "#/components/schemas/Party" }
        max_amount_atomic: { $ref: "#/components/schemas/Uint" }
        grant_id: { type: string, description: "Spend as the payer's delegate under this funds grant. Left out, the caller's funds grant in force from this payer (and asset) applies all the same: it binds; with several in force, name one (400 lists them). Without any, the caller is the payer itself" }
        estimate: { type: boolean, description: "true: every check and the price, nothing kept (no quote, nothing reserved against a grant, no operator nonce used); answered 200 with estimate: true" }
        operator_quote: { $ref: "#/components/schemas/OperatorQuote", description: "Required for operator_quoted offerings: the price computed and signed by the operator's own platform" }
        request_id: { type: string, description: "The seller's offer in answer to this wallet's request (POST /service-requests/{id}/answers offer): its price, unless the price now is lower. Only for the wallet that asked, from the storefront it asked from (403), on that service (404), while it is open: 409 reason offer_used (an order at it stands), offer_quoted (a quote at it is still open), offer_expired or offer_ended (new terms). Not with pool_id. The quote lasts no longer than the offer" }
    Quote:
      type: object
      required: [id, offering_id, offering_version, quantity, amount_atomic, asset, expires_at, terms_hash]
      properties:
        id: { type: string }
        offering_id: { type: string }
        offering_version: { type: integer }
        quantity: { $ref: "#/components/schemas/Uint" }
        amount_atomic: { $ref: "#/components/schemas/Uint" }
        platform_fee_atomic: { $ref: "#/components/schemas/Uint", description: "The most the platform fee can be for this quote (fee bps x amount); 0 when no fee applies" }
        platform_fee:
          type: object
          description: >-
            Locked in the terms (terms_hash) and enforced by the contract: taken from the provider's charge at
            settlement, once; the buyer pays amount_atomic. A later fee change never affects this quote or its agreement.
          properties:
            bps: { type: integer, minimum: 0, maximum: 2000 }
            recipient: { $ref: "#/components/schemas/EvmAddress" }
            paid_from: { enum: [provider_charge] }
        asset: { $ref: "#/components/schemas/Caip19" }
        expires_at: { $ref: "#/components/schemas/Time" }
        terms_hash: { type: string, description: keccak256 of the locked terms snapshot }
        grant_id: { type: string, description: The funds grant the purchase runs under (devices always; applications when they named one) }
        priced_by: { type: object, description: "operator_quoted: which quoting key signed the price", properties: { operator_signer: { $ref: "#/components/schemas/EvmAddress" }, nonce: { type: string } } }
        unit_price_atomic: { $ref: "#/components/schemas/Uint", description: "Metered: the unit price the quote locked" }
        off_peak: { type: boolean, description: "true when the quote locked the off-peak price (absent otherwise)" }
        offer: { type: object, description: "Quoted with request_id: applied is false when the price now was lower than the offer (the offer stays for later)", properties: { request_id: { type: string }, applied: { type: boolean } } }
        pool:
          type: object
          description: "Quoted from a machine pool (pool_id): the machine the platform assigned. Until the quote expires or becomes an order, no other quote of the pool gets it"
          properties: { pool_id: { type: string }, offering_id: { type: string }, device_id: { type: string } }
    ProofLink:
      type: object
      required: [id, agreement_id, made_by, state, token, path, created_at, expires_at, opened]
      properties:
        id: { type: string, pattern: "^prf_[a-z0-9]+$" }
        agreement_id: { type: string }
        made_by: { type: string, enum: [buyer, seller] }
        wallet: { type: string, description: "The storefront wallet that asked for it" }
        state: { type: string, enum: [active, expired, withdrawn] }
        token: { type: string, description: The link's secret part }
        path: { type: string, description: "The shop's page for it: /proofs/{token}" }
        created_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time }
        revoked_at: { type: string, format: date-time }
        opened: { type: integer, description: How many times it was opened }
        last_opened_at: { type: string, format: date-time }
    PublicProof:
      type: object
      required: [proof, order, evidence]
      properties:
        proof: { type: object, required: [id, made_by, created_at, expires_at], properties: { id: { type: string }, made_by: { type: string, enum: [buyer, seller] }, created_at: { type: string, format: date-time }, expires_at: { type: string, format: date-time } } }
        order:
          type: object
          required: [id, template, terms_snapshot, terms_hash, created_at, seller, funds, chain]
          properties:
            id: { type: string }
            template: { type: string }
            state: { type: string }
            offering: { type: object, properties: { id: { type: string }, name: { type: string } } }
            terms_snapshot: { type: object, additionalProperties: true }
            terms_hash: { type: string }
            created_at: { type: string, format: date-time }
            seller: { type: object, properties: { organization_id: { type: string }, name: { type: string }, website: { type: string }, support_email: { type: string } } }
            buyer: { type: object, description: "Only where the buyer made the link", properties: { address: { type: string } } }
            funds: { type: object, properties: { funded: { type: string }, provider: { type: string }, fees: { type: string }, refunded: { type: string } } }
            chain: { type: object, properties: { network: { type: string }, contract: { type: string }, tx: { type: string } } }
            execution: { type: object, properties: { delivered_quantity: { type: string }, measured_by_runs: { type: string, description: "What the last runs measured in the order's unit" } } }
        settlement:
          type: object
          properties:
            quantity: { type: string }
            reason: { type: string }
            tx: { type: string }
            refund_tx: { type: string }
            settled_at: { type: string, format: date-time }
            allocations: { type: array, items: { type: object, properties: { role: { type: string }, amount_atomic: { type: string }, address: { type: string, description: "Not the refund's where the seller made the link" } } } }
        evidence: { type: array, description: "The device's signed records as evidence bundles, without the run's inputs and results", items: { type: object, additionalProperties: true } }
    PoolSummary:
      type: object
      required: [pool_id, name, machines, online, free_now]
      properties:
        pool_id: { type: string }
        name: { type: string }
        summary: { type: string }
        machines: { type: integer, description: "Its machines other organisations can order: listed, in use, on the pool's terms" }
        online: { type: integer }
        free_now: { type: integer, description: "Online, not running an order, no order or quote of the pool holding it, open for orders" }
        next_free_by: { $ref: "#/components/schemas/Time", description: "None free: when the first running one should be done, when that is known" }
    PoolMember:
      type: object
      properties:
        offering_id: { type: string }
        device_id: { type: string }
        name: { type: string }
        listed: { type: boolean }
        matches: { type: boolean, description: "Its current terms are the pool's. false after they were changed: the pool does not assign it" }
        usable: { type: boolean, description: "false: the service is archived or its machine retired or suspended" }
        online: { type: boolean }
        paused: { type: boolean }
        open: { type: boolean, description: "Inside its seller's hours (always, without hours)" }
        running: { type: boolean }
        free_by: { $ref: "#/components/schemas/Time" }
        held: { type: integer, description: "Orders on it that have not run yet, and the pool's quotes that still hold it" }
        free: { type: boolean }
    Pool:
      type: object
      required: [id, name, machines, online, free_now, members]
      properties:
        id: { type: string }
        name: { type: string }
        summary: { type: string }
        machines: { type: integer }
        online: { type: integer }
        free_now: { type: integer }
        next_free_by: { $ref: "#/components/schemas/Time" }
        members: { type: array, items: { $ref: "#/components/schemas/PoolMember" } }
        created_at: { $ref: "#/components/schemas/Time" }
        updated_at: { $ref: "#/components/schemas/Time" }
    AcceptanceRule:
      type: object
      additionalProperties: false
      description: >-
        What the buyer counts as a good delivery of a metered order (docs/design/AGENTS.md "Accepting by rule"). Every
        field given must hold; a delivery that fails one is to be disputed before its challenge period ends.
      properties:
        min_delivered_share: { type: number, exclusiveMinimum: 0, maximum: 1, description: "At least this share of the quantity ordered is delivered (0.9: 90%)" }
        require_records: { type: boolean, description: The device signed records for the run }
        require_security: { type: boolean, description: The selling device meets its product's security policy }
        result:
          type: array
          maxItems: 10
          description: Conditions on the result the device reported for the run (its latest finished run)
          items:
            type: object
            required: [field, op, value]
            properties:
              field: { type: string, description: "A field of the result, dotted for nested ones: ok, pick.grams" }
              op: { enum: [eq, ne, gt, gte, lt, lte] }
              value: { oneOf: [{ type: string, maxLength: 200 }, { type: number }, { type: boolean }] }
    Agreement:
      type: object
      required: [id, template, state, terms_snapshot, terms_hash, funds, resource_version]
      properties:
        offering_id: { type: string, description: The offering this agreement was quoted from }
        pool_id: { type: string, description: "The machine pool it was quoted from (POST /quotes {pool_id}), when it was" }
        history:
          type: array
          description: What happened to it and when, oldest first ("ordered", then each state it entered)
          items: { type: object, properties: { state: { type: string }, at: { $ref: "#/components/schemas/Time" } } }
        awaiting_provider_signature:
          type: object
          description: >-
            The contract needs the service provider's (escrow) or grantor's (lease, subscription) EIP-712 signature
            over the terms and the platform does not hold that key: funding waits (the buyer's authorisation is kept)
            until the seller posts it to POST /agreements/{agreement_id}/provider-signatures before the offer expires.
            `mce seller sign-orders` signs them automatically under the seller's own rules.
          properties:
            signer: { $ref: "#/components/schemas/EvmAddress" }
            digest: { type: string }
            typed_data: { type: object, description: EIP-712 typed data to sign (uint256 fields as decimal strings) }
            payees:
              type: array
              description: Who is paid and their basis points (what typed_data's payeesHash commits to; a lease pays its one payee)
              items: { type: object, properties: { address: { $ref: "#/components/schemas/EvmAddress" }, bps: { type: integer } } }
            submit: { type: string }
        funding_status:
          type: object
          description: The buyer has signed the payment and the order is not funded yet; what it waits for
          properties:
            payment_id: { type: string }
            payment_state: { enum: [authorized, submitted, pending, reconciling] }
            waiting_for: { enum: [provider_signature, chain_confirmation] }
        bundle_id: { type: string, description: The bundle this agreement is a part of (it starts only when every part is funded) }
        seller_organization_id: { type: string }
        seller: { $ref: "#/components/schemas/SellerFacts" }
        buyer_organization_id: { type: string, description: Differs from the seller's for a marketplace purchase }
        id: { type: string }
        template: { enum: [access_lease, access_subscription, metered_service_escrow] }
        template_version: { type: string }
        state: { enum: [awaiting_funding, ready, active, awaiting_acceptance, disputed, closed, cancelled, expired] }
        terms_snapshot: { $ref: "#/components/schemas/ServiceTerms", description: Immutable once accepted and funded (GEN-31) }
        terms_hash: { type: string }
        chain:
          type: object
          properties:
            network: { $ref: "#/components/schemas/Caip2" }
            contract: { $ref: "#/components/schemas/EvmAddress" }
            agreement_key: { type: string }
            state: { enum: [not_created, pending, confirmed, reorged] }
            tx: { type: string }
        execution:
          type: object
          properties:
            invocations: { type: array, items: { type: string } }
            sessions: { type: array, items: { type: string } }
            delivered_quantity: { $ref: "#/components/schemas/Uint" }
            evidence_root: { type: string, description: "metered_service_escrow: keccak256 of the agreement's record digests, committed with the delivery proposal" }
            period: { type: integer, description: "access_subscription: the current period (0-based)" }
            periods: { type: integer }
            periods_released: { type: integer, description: "access_subscription: periods credited to the payees so far" }
            uses_this_period: { type: integer }
            max_uses_per_period: { type: integer }
        evidence_refs: { type: array, items: { type: string }, description: "The device-signed records of the agreement's runs (ids for GET /evidence/{id}), at most 1,000" }
        funds:
          type: object
          description: "Conservation: funded = provider + fees + refunded + unallocated"
          properties:
            funded: { $ref: "#/components/schemas/Uint" }
            provider: { $ref: "#/components/schemas/Uint" }
            fees: { $ref: "#/components/schemas/Uint" }
            refunded: { $ref: "#/components/schemas/Uint" }
            unallocated: { $ref: "#/components/schemas/Uint" }
            refund_to: { $ref: "#/components/schemas/EvmAddress", description: "Escrow and subscription: the terms' refund recipient" }
            withdrawable: { type: object, additionalProperties: { $ref: "#/components/schemas/Uint" } }
        deadlines: { type: object, additionalProperties: { $ref: "#/components/schemas/Time" } }
        acceptance:
          type: object
          description: "metered_service_escrow with an acceptance rule: the rule and, once a delivery is proposed, what it shows against it"
          required: [rule, state, checks]
          properties:
            rule: { $ref: "#/components/schemas/AcceptanceRule" }
            state: { enum: [pending, meets, fails], description: "pending: no delivery proposed yet" }
            checks:
              type: array
              items:
                type: object
                required: [check, ok, detail]
                properties:
                  check: { enum: [delivered, records, security, result] }
                  ok: { type: boolean }
                  detail: { type: string }
            action: { enum: [accept, dispute], description: What the buyer's client is to do }
            dispute_reason: { type: string, description: "fails: a reason to dispute with, naming what failed" }
        verification:
          type: object
          description: "metered_service_escrow: who verifies (platform_verifier or committee) and what awaits co-signatures"
          properties:
            template: { enum: [platform_verifier, committee] }
            verifier: { $ref: "#/components/schemas/EvmAddress" }
            committee: { $ref: "#/components/schemas/EvmAddress" }
            threshold: { type: integer }
            members: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
            pending:
              type: object
              properties:
                kind: { enum: [start, delivery] }
                digest: { type: string }
                quantity: { $ref: "#/components/schemas/Uint" }
                evidence_root: { type: string }
                signed_by: { type: array, items: { $ref: "#/components/schemas/EvmAddress" } }
                typed_data: { type: object }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        resource_version: { type: integer }
    Eip712Authorization:
      type: object
      required: [domain, primary_type, message, signature]
      properties:
        domain: { type: object, required: [name, version, chainId, verifyingContract], properties: { name: { type: string }, version: { type: string }, chainId: { type: integer }, verifyingContract: { $ref: "#/components/schemas/EvmAddress" } } }
        primary_type: { type: string }
        message: { type: object }
        signature: { type: string, pattern: "^0x[0-9a-fA-F]{130}$" }
    FundingIntent:
      type: object
      required: [id, agreement_id, scheme, typed_data, amount_atomic, asset, state]
      properties:
        id: { type: string }
        agreement_id: { type: string }
        scheme: { enum: ["eip3009.receive_with_authorization", "erc20.approve_transfer_from", "lease.accept_free"], description: "lease.accept_free: typed_data is the lessee's LesseeAction; submit it as signed_authorization" }
        typed_data: { type: object, description: Exact EIP-712 structure to sign (payee = agreement contract) }
        amount_atomic: { $ref: "#/components/schemas/Uint" }
        asset: { $ref: "#/components/schemas/Caip19" }
        payment_id: { type: string }
        state: { enum: [awaiting_signature, submitted, confirmed, failed, expired] }
    Payment:
      type: object
      required: [id, state, amount_atomic, asset, network, payer, payee]
      properties:
        id: { type: string }
        state: { enum: [requested, authorized, submitted, pending, settled, rejected, reconciling] }
        amount_atomic: { $ref: "#/components/schemas/Uint" }
        asset: { $ref: "#/components/schemas/Caip19" }
        network: { $ref: "#/components/schemas/Caip2" }
        payer: { $ref: "#/components/schemas/EvmAddress" }
        payee: { $ref: "#/components/schemas/EvmAddress" }
        nonce: { type: string }
        valid_before: { $ref: "#/components/schemas/Time" }
        agreement_id: { type: string }
        settlement_id: { type: string }
        tx: { type: string }
        reconciliation: { type: object, description: Present while state=reconciling (what is being matched and why) }
    PayeeShare:
      type: object
      required: [network, asset, earned_atomic, sending, sellers, recent]
      properties:
        network: { type: string }
        asset: { $ref: "#/components/schemas/Caip19" }
        earned_atomic: { $ref: "#/components/schemas/Uint" }
        available_atomic: { $ref: "#/components/schemas/Uint", description: "Still credited in the contracts now; absent when a contract could not be read" }
        sending: { type: boolean, description: "A withdrawal for this address is pending" }
        sellers:
          type: array
          items:
            type: object
            properties:
              organization_id: { type: string }
              name: { type: string }
              earned_atomic: { $ref: "#/components/schemas/Uint" }
              roles: { type: array, items: { type: string } }
              services: { type: array, items: { type: string } }
        recent:
          type: array
          description: The newest settled orders that credited this address (at most 20)
          items:
            type: object
            properties:
              settled_at: { type: string, format: date-time }
              offering_id: { type: string }
              offering_name: { type: string }
              seller: { type: object, properties: { organization_id: { type: string }, name: { type: string } } }
              role: { type: string }
              amount_atomic: { $ref: "#/components/schemas/Uint" }
    Earning:
      type: object
      properties:
        network: { type: string }
        address: { $ref: "#/components/schemas/EvmAddress" }
        roles: { type: array, items: { type: string } }
        asset: { $ref: "#/components/schemas/Caip19" }
        earned_atomic: { $ref: "#/components/schemas/Uint" }
        available_atomic: { $ref: "#/components/schemas/Uint" }
        managed: { type: boolean, description: The platform holds this payee's key (sandbox only) }
        contracts: { type: array, items: { type: object, properties: { contract: { type: string }, template: { type: string }, earned_atomic: { $ref: "#/components/schemas/Uint" }, available_atomic: { $ref: "#/components/schemas/Uint" } } } }
    Network:
      type: object
      properties:
        network: { type: string, description: "CAIP-2, e.g. eip155:31337" }
        chain_id: { type: integer }
        assets:
          type: array
          items:
            type: object
            properties:
              asset: { type: string, description: CAIP-19 id used in pricing.asset }
              token: { $ref: "#/components/schemas/EvmAddress" }
              name: { type: string, description: The token's EIP-712 domain name }
              decimals: { type: integer }
        templates: { type: array, items: { enum: [metered_service_escrow, access_lease, access_subscription] } }
        verifier: { $ref: "#/components/schemas/EvmAddress" }
        platform_fee_bps: { type: integer }
        min_order_atomic: { type: string, description: "The smallest paid order on this network, in atomic units of any of its assets (\"0\": none). A quote below it, and terms whose largest order is below it, are refused (invalid_argument with details.min_order_atomic); free services are exempt" }
        explorer_url: { type: string, description: "A block explorer for this network, when configured: transactions at <explorer_url>/tx/<hash>" }
        managed_providers: { type: array, items: { $ref: "#/components/schemas/EvmAddress" }, description: "Payee addresses the platform signs agreements for (custodial keys: sandbox only)" }
        contracts:
          type: object
          description: The contracts whose EIP-712 domains a provider signs for (a signer pins these)
          properties:
            escrow: { $ref: "#/components/schemas/EvmAddress" }
            lease: { $ref: "#/components/schemas/EvmAddress" }
            subscription: { $ref: "#/components/schemas/EvmAddress" }
    Settlement:
      type: object
      required: [id, agreement_id, state, allocations]
      properties:
        id: { type: string }
        agreement_id: { type: string }
        state: { enum: [pending, confirmed, reorged, failed] }
        allocations: { type: array, items: { type: object, properties: { address: { $ref: "#/components/schemas/EvmAddress" }, role: { type: string }, amount_atomic: { $ref: "#/components/schemas/Uint" }, withdrawn: { type: boolean } } } }
        tx: { type: string }
        block: { type: integer }
        refund_tx: { type: string, description: "The refund sent on from the contract to the buyer's wallet, once confirmed" }
        settled_at: { $ref: "#/components/schemas/Time" }
    OrganizationProfile:
      type: object
      description: What buyers see about a seller in the shop and on receipts
      properties:
        summary: { type: string, maxLength: 500 }
        website: { type: string, description: An https address }
        support_email: { type: string }
    Organization:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        profile: { $ref: "#/components/schemas/OrganizationProfile" }
        require_two_factor: { type: boolean, description: "Its people must use two-factor sign-in: a person without it reaches only /me and /me/two-factor (403, details.two_factor_setup_required) until they turn it on" }
        created_at: { $ref: "#/components/schemas/Time" }
    SellerFacts:
      type: object
      description: A seller as buyers see it
      properties:
        organization_id: { type: string }
        name: { type: string }
        summary: { type: string }
        website: { type: string }
        support_email: { type: string }
        since: { $ref: "#/components/schemas/Time" }
        orders_settled: { type: integer }
        orders_disputed: { type: integer }
        asks:
          type: object
          description: >-
            How the seller answers buyers who ask it alone for a lower price (a service request with offering_id) over
            the last `days` days: the asks it had two days to answer or answered sooner, how many it answered, and the
            median seconds to its answer. Absent below three asks.
          properties:
            days: { type: integer }
            asked: { type: integer }
            answered: { type: integer }
            median_answer_s: { type: integer }
    SettlementLine:
      type: object
      properties:
        settlement_id: { type: string }
        agreement_id: { type: string }
        settled_at: { $ref: "#/components/schemas/Time" }
        template: { type: string }
        offering_id: { type: string }
        offering_name: { type: string }
        external_ref: { $ref: "#/components/schemas/ExternalRef" }
        buyer_address: { $ref: "#/components/schemas/EvmAddress" }
        network: { $ref: "#/components/schemas/Caip2" }
        asset: { $ref: "#/components/schemas/Caip19" }
        quantity: { $ref: "#/components/schemas/Uint" }
        reason: { type: string }
        charged_atomic: { $ref: "#/components/schemas/Uint", description: "What the buyer was charged: to the payees and the platform fee" }
        fees_atomic: { $ref: "#/components/schemas/Uint", description: The platform fee within the charge }
        earned_atomic: { $ref: "#/components/schemas/Uint", description: "role=seller only: what this organisation's payees received" }
        refunded_atomic: { $ref: "#/components/schemas/Uint" }
        tx: { type: string }
        refund_tx: { type: string }
    Statement:
      type: object
      properties:
        role: { enum: [seller, buyer] }
        from: { $ref: "#/components/schemas/Time" }
        to: { $ref: "#/components/schemas/Time" }
        buyer_address: { $ref: "#/components/schemas/EvmAddress" }
        assets:
          type: array
          items:
            type: object
            properties:
              asset: { $ref: "#/components/schemas/Caip19" }
              orders: { type: integer }
              charged_atomic: { $ref: "#/components/schemas/Uint" }
              fees_atomic: { $ref: "#/components/schemas/Uint" }
              earned_atomic: { $ref: "#/components/schemas/Uint", description: role=seller }
              refunded_atomic: { $ref: "#/components/schemas/Uint" }
              paid_in_atomic: { $ref: "#/components/schemas/Uint", description: "role=buyer: funded into its orders" }
              held_atomic: { $ref: "#/components/schemas/Uint", description: "role=buyer: still held by its open orders" }
        services:
          type: array
          description: role=seller
          items: { type: object, properties: { offering_id: { type: string }, name: { type: string }, asset: { $ref: "#/components/schemas/Caip19" }, orders: { type: integer }, charged_atomic: { $ref: "#/components/schemas/Uint" }, fees_atomic: { $ref: "#/components/schemas/Uint" }, earned_atomic: { $ref: "#/components/schemas/Uint" }, refunded_atomic: { $ref: "#/components/schemas/Uint" } } }
        days:
          type: array
          description: interval=day, oldest first
          items: { type: object, properties: { day: { type: string, format: date }, asset: { $ref: "#/components/schemas/Caip19" }, orders: { type: integer }, charged_atomic: { $ref: "#/components/schemas/Uint" }, fees_atomic: { $ref: "#/components/schemas/Uint" }, earned_atomic: { $ref: "#/components/schemas/Uint" }, refunded_atomic: { $ref: "#/components/schemas/Uint" } } }

    FirmwareCampaign:
      type: object
      properties:
        id: { type: string }
        release_id: { type: string }
        state: { enum: [running, paused, completed, cancelled] }
        pause_reason: { type: string, description: "Automatic pauses say which failure rate crossed the threshold" }
        plan: { type: object }
        selector: { type: object }
        targets: { type: integer }
        wave:
          type: object
          properties:
            index: { type: integer }
            percent: { type: integer }
            devices: { type: integer }
            finished: { type: integer }
            installed: { type: integer }
            failed: { type: integer }
            started_at: { $ref: "#/components/schemas/Time" }
            soaking_since: { $ref: "#/components/schemas/Time" }
        waves: { type: array, items: { type: object, properties: { index: { type: integer }, percent: { type: integer }, devices: { type: integer } } } }
        rollout: { type: object, additionalProperties: { type: integer }, description: "Devices of this campaign by state (offered, held, downloading, ..., installed, failed, rolled_back, cancelled)" }
        devices:
          type: array
          description: Each target device, in wave order (retired devices are never targets)
          items:
            type: object
            properties:
              device_id: { type: string }
              name: { type: string }
              wave: { type: integer }
              running: { type: string, description: The firmware version it reports now }
              state: { type: string, description: "Its update's state, or waiting (a later wave) / not_offered (not sent yet)" }
              detail: { type: string, description: "Why it failed or rolled back, as the device reported; or already running this version" }
              updated_at: { $ref: "#/components/schemas/Time" }
        created_at: { $ref: "#/components/schemas/Time" }
        updated_at: { $ref: "#/components/schemas/Time" }
    FirmwareRelease:
      type: object
      required: [id, target, hardware, version, security_version, image_sha256, image_size, image_uploaded, rollout]
      properties:
        id: { type: string }
        target: { type: string }
        hardware: { type: string }
        version: { type: string }
        security_version: { type: integer }
        image_sha256: { type: string }
        image_size: { type: integer }
        key_id: { type: string }
        image_uploaded: { type: boolean }
        app_digest: { type: string, description: "For an ESP-IDF app image: the SHA-256 appended to it (what a device reports as esp_app_digest)" }
        rollout:
          type: array
          items: { type: object, properties: { device_id: { type: string },
            state: { enum: [offered, downloading, ready, deferred, activating, confirming, installed, failed, rolled_back] },
            detail: { type: string, description: "Refusal or failure reason reported by the device (e.g. not_newer, below_security_floor, image_hash_mismatch)" },
            running_version: { type: string }, updated_at: { $ref: "#/components/schemas/Time" } } }
        created_at: { $ref: "#/components/schemas/Time" }

    SignedStructure:
      type: object
      required: [domain, body, alg, key_id, sig]
      description: An MCE signed structure (EVIDENCE_AND_SIGNING.md) with the canonical CBOR body kept verbatim
      properties:
        domain: { type: string }
        body: { type: string, contentEncoding: base64 }
        alg: { const: ed25519 }
        key_id: { type: string }
        sig: { type: string, contentEncoding: base64 }
    Evidence:
      type: object
      required: [id, state, level, source, records]
      properties:
        id: { type: string }
        state: { enum: [queued_local, uploaded, verified, anchor_pending, anchored, rejected, retrying] }
        level: { enum: [transport_only, signed, signed_anchored] }
        source: { $ref: "#/components/schemas/Source" }
        records: { type: array, items: { $ref: "#/components/schemas/SignedStructure" } }
        links: { $ref: "#/components/schemas/Links" }
        received_at: { $ref: "#/components/schemas/Time" }
        anchor:
          type: object
          properties:
            batch_root: { type: string }
            receipt:
              type: object
              description: >-
                The anchoring service's receipt (HashAnchor receipt v1): {hash = batch_root, merkleRoot, proof
                (keccak256, sorted pairs), anchor {chainId, contractAddress, txHash, blockNumber, blockTimestamp}, signature}.
                The batch is reported anchored only once this receipt exists and its proof leads from batch_root to merkleRoot.
            network: { $ref: "#/components/schemas/Caip2" }
            tx: { type: string }
            confirmed: { type: boolean }
    EvidenceBundle:
      type: object
      required: [bundle_version, evidence, manifest, identity]
      properties:
        bundle_version: { const: "1" }
        evidence: { $ref: "#/components/schemas/Evidence" }
        manifest: { type: object }
        identity: { type: object, description: Key history and registry binding at the relevant times }
        merkle_proof: { type: array, items: { type: object, properties: { side: { enum: [L, R] }, hash: { type: string } } } }
        business: { type: object, description: Invocation / agreement snapshots referenced by the records }

    WebhookSubscriptionCreate:
      type: object
      required: [url, event_types]
      properties:
        url: { type: string, format: uri, pattern: "^https://" }
        event_types:
          type: array
          items: { enum: [device.bound, device.connection_changed, identity.updated, property.reported, device.event, meter.updated, invocation.started, invocation.completed, invocation.failed, invocation.unknown, invocation.updated, agreement.updated, payment.updated, evidence.anchored, evidence.updated, operation.updated, firmware.updated, firmware.campaign_updated, device.factory_mismatch, device.security_mismatch, grant.updated] }
        filter: { type: object, properties: { device_ids: { type: array, items: { type: string } }, product_ids: { type: array, items: { type: string } } } }
    WebhookSubscription:
      allOf:
        - { $ref: "#/components/schemas/WebhookSubscriptionCreate" }
        - type: object
          required: [id, state]
          properties:
            id: { type: string }
            state: { enum: [active, paused] }
            secret: { type: string, description: Returned only on create/rotation }
            created_at: { $ref: "#/components/schemas/Time" }
            dead_letter_count: { type: integer }
            pending_count: { type: integer }
            last_delivered_at: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }] }
            last_failure:
              oneOf:
                - { type: "null" }
                - { type: object, properties: { at: { $ref: "#/components/schemas/Time" }, status: { type: [integer, "null"] }, error: { type: [string, "null"] } } }
    WebhookDelivery:
      type: object
      required: [event_id, event_type, state, attempts]
      properties:
        event_id: { type: string }
        event_type: { type: string }
        resource_id: { type: string }
        occurred_at: { $ref: "#/components/schemas/Time" }
        state: { enum: [pending, delivered, dead] }
        attempts: { type: integer }
        last_status: { type: [integer, "null"], description: The HTTP status the endpoint answered }
        last_error: { type: [string, "null"], description: Why no answer came (timeout, connection refused) }
        updated_at: { $ref: "#/components/schemas/Time" }
        next_attempt_at: { oneOf: [{ $ref: "#/components/schemas/Time" }, { type: "null" }] }
    EventEnvelope:
      type: object
      required: [event_id, schema_version, event_type, resource_id, resource_version, occurred_at, received_at, correlation_id, payload, cursor]
      properties:
        event_id: { type: string }
        schema_version: { const: "1" }
        event_type: { type: string }
        resource_id: { type: string }
        resource_version: { type: integer }
        occurred_at: { $ref: "#/components/schemas/Time" }
        received_at: { $ref: "#/components/schemas/Time" }
        correlation_id: { type: string, description: "Links application, device, invocation, session, agreement and payment" }
        cursor: { type: string }
        payload: { type: object, description: "Per event type: docs/EVENTS.md lists every field, when it is present and its values" }
    EventPage: { $ref: "#/components/schemas/Page", properties: { data: { type: array, items: { $ref: "#/components/schemas/EventEnvelope" } } } }

    Page:
      type: object
      required: [data]
      properties:
        data: { type: array }
        next_cursor: { type: ["string", "null"] }
