openapi: 3.1.0
info:
  title: Chartnaut API
  version: 1.0.0-draft
  summary: Author and run indicators, definitions and studies on Chartnaut compute
  description: |
    The public contract behind the Chartnaut CLI and the Chartnaut MCP server.
    Every CLI command and every MCP tool is a call to an operation in this file;
    neither has operations of its own.

    Design rules (see README.md for the reasoning):
    - Public names only. `definition` (never "flow"), `run`, `script`, `version`.
      No internal type is ever serialised directly; every response is a DTO here.
    - Versions are immutable. `slug@3` means the same code and the same
      dependency pins forever. A bare `slug` resolves to the latest version at
      run time and the run records which version it used.
    - Every run is async. `wait` lets short runs return finished in one call.
    - No raw market data. Runs return what the script produced (series, events,
      study results), never candles or tape.
    - A save that is not runnable fails (422). There is no "saved but not
      promoted" success.
  contact:
    email: help@chartnaut.com

servers:
  - url: https://api.chartnaut.com/v1
    description: |
      The public API, called with a personal API key (the CLI's `chartnaut login`, or
      **Developers → CLI and API keys**). A key works in the region where it was made.

security:
  - bearerToken: []

tags:
  - name: Scripts
    description: Your indicators, definitions and studies, and their versions.
  - name: Runs
    description: Execute a saved version or inline source on an instrument and window.
  - name: Forward Insights
    description: |
      A study on the chart: click one of a definition's events and a card shows what happened
      after events like it. Made from a succeeded run of a study that publishes `pin_cell`.
  - name: Library
    description: |
      Every script the caller can use: their own, Chartnaut's built-ins, other people's public
      scripts and the ones they added to their library. Described by ref; source is never
      returned. Another author's script runs only once it is added to the caller's library,
      which also adds the scripts it needs after an explicit `confirm`.
  - name: Catalog
    description: Instruments, timeframes and coverage. Metadata only.
  - name: Account
    description: Usage, limits and webhooks.
  - name: Docs
    description: The scripting reference, served in slices sized for an agent's context.
  - name: Projects
    description: |
      Your developer projects (once called apps): the Chartnaut side of what you build with the SDK.
      Test keys and Test sites only; Live keys and Live sites are made on the Developers page.

paths:
  # ───────────────────────────── CLI sign-in ─────────────────────────────
  /auth/device:
    post:
      tags: [Account]
      operationId: startDeviceLogin
      summary: Start a browser sign-in
      description: |
        No key needed. Show `user_code` and open `verification_uri_complete`; the person approves it
        in Chartnaut while signed in, then poll `pollDeviceLogin` every `interval` seconds.
        30 starts a minute per IP.
      security: []
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                client_name: { type: string, description: Shown on the approval page and in the key's name. }
                expires_in_days:
                  type: integer
                  enum: [7, 30, 90]
                  default: 90
                  description: How long the key works once approved. The person approving can shorten it, never lengthen it. Any other value is 400 `invalid_request` with `details.allowed`.
                scopes:
                  type: array
                  items: { type: string, enum: ['apps:write'] }
                  description: Opt-in scopes the key should carry on top of the defaults (`apps:write` lets it create and manage your developer projects and their Test keys). The approval page names them. Any other value, a default scope included, is 400 `invalid_request` with `details.allowed`.
      responses:
        '200':
          description: Grant started.
          content:
            application/json:
              schema:
                type: object
                properties:
                  device_code: { type: string, description: Secret; keep it and poll with it. }
                  user_code: { type: string, example: BCDF-GHJK }
                  verification_uri: { type: string, format: uri }
                  verification_uri_complete: { type: string, format: uri }
                  expires_in: { type: integer, example: 600 }
                  interval: { type: integer, example: 3 }
                  expires_in_days: { type: integer, enum: [7, 30, 90], description: The key lifetime asked for. The approver may shorten it. }
                  scopes: { type: array, items: { type: string }, description: 'Every scope the key will carry once approved, the defaults plus any opt-in asked for.' }
        default: { $ref: '#/components/responses/Error' }

  /auth/token:
    post:
      tags: [Account]
      operationId: pollDeviceLogin
      summary: Finish a browser sign-in
      description: |
        Until approved: 400 with `authorization_pending` (keep polling), `slow_down` (add 2 s to
        the interval), `access_denied` or `expired_token` (stop). Approved: 200 with a key named
        "CLI on <client_name>", created at this moment and returned once. The key expires at
        `expires_at`: the `expires_in_days` asked for, or less if the approver shortened it.
        After that every call answers 401 `unauthorized` ("API token expired.").
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [device_code]
              properties:
                device_code: { type: string }
      responses:
        '200':
          description: Approved.
          content:
            application/json:
              schema:
                type: object
                properties:
                  token: { type: string }
                  name: { type: string }
                  expires_at: { type: string, format: date-time, description: When the key stops working (RFC 3339). }
                  expires_in_days: { type: integer, enum: [7, 30, 90], description: The key's lifetime in days. }
        default: { $ref: '#/components/responses/Error' }

  /auth/revoke:
    post:
      tags: [Account]
      operationId: revokeCurrentKey
      summary: Revoke the key making this request (sign out)
      responses:
        '204': { description: Revoked. }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Scripts ─────────────────────────────
  /scripts:
    get:
      tags: [Scripts]
      operationId: listScripts
      summary: List your scripts
      parameters:
        - $ref: '#/components/parameters/Kind'
        - name: q
          in: query
          description: Substring match on slug, name and description.
          schema: { type: string }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of scripts (no source).
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/ScriptSummary' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Scripts]
      operationId: createScript
      summary: Create a script and its first version
      description: |
        Validates, resolves and pins dependencies, then saves the first version.
        Counts against the plan's custom-indicator, definition or study cap.
        Nothing is created when validation fails (422). A study's first version
        can be numbered 2: the app seeds a starter version when a study is created.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateScriptRequest' }
      responses:
        '201':
          description: Created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Script' }
        '409': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/ScriptInvalid' }
        default: { $ref: '#/components/responses/Error' }

  /scripts/validate:
    post:
      tags: [Scripts]
      operationId: validateScript
      summary: Lint and resolve a script without saving or running it
      description: |
        Returns diagnostics, the derived settings and outputs, and the
        dependency versions it would pin. Free (no compute units).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ScriptSource' }
      responses:
        '200':
          description: Validation result. `ok:false` is still a 200; the request itself succeeded.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ValidationResult' }
        default: { $ref: '#/components/responses/Error' }

  /scripts/{slug}:
    parameters:
      - $ref: '#/components/parameters/Slug'
    get:
      tags: [Scripts]
      operationId: getScript
      summary: Get a script (latest version, or `slug@N`)
      parameters:
        - name: include
          in: query
          description: Comma list. `source` returns files (own scripts only).
          schema: { type: string, example: source }
      responses:
        '200':
          description: The script.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Script' }
        default: { $ref: '#/components/responses/Error' }
    put:
      tags: [Scripts]
      operationId: updateScript
      summary: Save a new version
      description: |
        `base_version` is required. If the latest version is not
        `base_version` the save is refused with `version_conflict` (409),
        so an agent never overwrites an edit made in the app. A save always
        adds a new version; it never rewrites the one you based it on.
        An unchanged file set adds nothing and returns the current version.
      parameters:
        - name: kind
          in: query
          description: Only needed when a study shares its slug with an indicator or definition.
          schema: { $ref: '#/components/schemas/ScriptKind' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/UpdateScriptRequest' }
      responses:
        '200':
          description: New version saved.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Script' }
        '409': { $ref: '#/components/responses/Error' }
        '422': { $ref: '#/components/responses/ScriptInvalid' }
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Scripts]
      operationId: updateScriptMetadata
      summary: Rename or describe a script
      description: >-
        Making a public script private while other people use it is refused with 409 `in_use`
        and changes nothing: `details.usage` counts who would lose it (`people`, `installs`,
        `apps`, `insights`, `studies`, `scripts`, and for definitions `alerts`, `collectors`,
        `events`). Send the same request with `confirm_users: true` to go ahead; they lose access
        at once. With nobody else using it, no confirmation is needed.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string }
                visibility: { $ref: '#/components/schemas/Visibility' }
                confirm_users:
                  type: boolean
                  description: Go ahead with making it private although other people use it. Only read with `visibility`.
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Script' }
        '409':
          description: >-
            `in_use`: other people use this script, so making it private needs `confirm_users: true`.
            `details.usage` has the counts.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                error:
                  code: in_use
                  message: 4 people use this. Making it private removes it for them. Send confirm_users to go ahead.
                  details:
                    usage: { people: 4, installs: 3, apps: 1, insights: 5, studies: 0, scripts: 0, alerts: 0, collectors: 2, events: 1830, used_by_others: true }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Scripts]
      operationId: deleteScript
      summary: Delete a script
      description: Refused with `in_use` if another of your scripts pins it.
      responses:
        '204': { description: Deleted. }
        default: { $ref: '#/components/responses/Error' }

  /scripts/{slug}/versions:
    parameters:
      - $ref: '#/components/parameters/Slug'
    get:
      tags: [Scripts]
      operationId: listScriptVersions
      summary: List versions, newest first
      parameters:
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of versions.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/VersionSummary' }
        default: { $ref: '#/components/responses/Error' }

  /scripts/{slug}/events:
    parameters:
      - $ref: '#/components/parameters/Slug'
    get:
      tags: [Scripts]
      operationId: listDefinitionEvents
      summary: List a definition's events
      description: |
        Every event this definition has collected in Chartnaut — from the app or through
        `collectDefinition` — across instruments, timeframes and windows. Studies read these.
        Runs return only their own events; this is the stored history. Own definitions only.
      parameters:
        - { name: instrument, in: query, schema: { type: string } }
        - { name: timeframe, in: query, schema: { $ref: '#/components/schemas/Timeframe' } }
        - { name: event, in: query, description: Declared event id., schema: { type: string } }
        - { name: from, in: query, description: Events starting at or after (RFC 3339)., schema: { type: string, format: date-time } }
        - { name: to, in: query, description: Events ending at or before (RFC 3339)., schema: { type: string, format: date-time } }
        - { name: version, in: query, description: Only events collected by this version., schema: { type: integer } }
        - name: where
          in: query
          description: 'Payload filters as JSON: [{"key":"range","op":"gt","value":10}]. Ops: eq neq contains gt gte lt lte between (valueTo) is_empty is_not_empty.'
          schema: { type: string }
        - { name: format, in: query, schema: { type: string, enum: [json, csv], default: json } }
        - $ref: '#/components/parameters/Cursor'
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 1000, default: 100 }
      responses:
        '200':
          description: A page of events, oldest first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items: { $ref: '#/components/schemas/Event' }
                  total: { type: integer }
                  next_cursor: { type: [string, 'null'] }
            text/csv:
              schema: { type: string }
        default: { $ref: '#/components/responses/Error' }

  /scripts/{slug}/events/summary:
    parameters:
      - $ref: '#/components/parameters/Slug'
    get:
      tags: [Scripts]
      operationId: definitionEventsSummary
      summary: Summarise a definition's events
      parameters:
        - { name: version, in: query, schema: { type: integer } }
      responses:
        '200':
          description: Summary.
          content:
            application/json:
              schema:
                type: object
                properties:
                  definition: { type: string }
                  events: { type: integer }
                  days: { type: integer }
                  events_per_day: { type: number }
                  datasets:
                    type: array
                    items:
                      type: object
                      properties:
                        instrument: { type: string }
                        timeframe: { type: string }
                        events: { type: integer }
                        days: { type: integer }
                        from: { type: string, format: date-time }
                        to: { type: string, format: date-time }
                  collecting:
                    type: array
                    description: Collections queued or running. Poll until empty.
                    items: { type: object, additionalProperties: true }
                  failed:
                    type: array
                    description: Collections that failed, with failure_kind.
                    items: { type: object, additionalProperties: true }
        default: { $ref: '#/components/responses/Error' }

  /scripts/{slug}/collect:
    parameters:
      - $ref: '#/components/parameters/Slug'
    post:
      tags: [Scripts]
      operationId: collectDefinition
      summary: Run a definition over history
      description: |
        Only the part of the window not already collected runs. Uses the plan's research gate
        and Events budget, like collecting in the app. Needs `runs:write`. Studies run through
        the API collect what they declare automatically.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [instrument, timeframe, window]
              properties:
                instrument: { type: string }
                timeframe: { $ref: '#/components/schemas/Timeframe' }
                window: { $ref: '#/components/schemas/Window' }
                version: { type: integer, description: Default latest. }
      responses:
        '200':
          description: 'The window was already collected (covered: true).'
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '202':
          description: Collection queued; poll the events summary.
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Runs ─────────────────────────────
  /runs:
    post:
      tags: [Runs]
      operationId: createRun
      summary: Run a script on one instrument and window
      description: |
        One verb for all three kinds. Pass `script` (a saved ref) or `source`
        (inline, saves nothing). A study over several instruments is several
        runs; the CLI fans out.

        Limits:
        - Inline `source` supports indicators and definitions. Save a study
          first, then run it by ref.
        - Studies run only from your own scripts. Indicators and definitions can
          also run by `author/slug`, without their source, once they are in your
          library (`addToLibrary`). Otherwise 409 `not_in_library`, with `details`
          `{ref, add, needs, cannot_add, confirm}`. Your own scripts and `chartnaut/`
          built-ins never need adding.
        - A study whose declared definitions are not all yours, built-in or in your
          library is refused before anything runs: 409 `not_in_library` with
          `details.definitions` (one entry per definition to add), or 409
          `not_shared` with `details.cannot_add` when one is not shared with you.
        - One run's window holds at most 50,000 bars at the run's timeframe.
        - Runs execute in the account's run slots (plan: Free 1, Pro 3, plus
          1 per compute concurrency add-on), shared with the account's own app sessions.
          Queued+running API runs are capped at slots + 4 (429 `busy`).
        - Indicator and definition results are kept for 7 days.
        - A definition run keeps at most 10,000 events; `summary.events_total`
          counts all of them.
        - The window is clamped to your plan's history and ends on a closed bar.

        With `wait` > 0 the call blocks until the run finishes or `wait`
        elapses, then returns the run in whatever state it is in. 202 means
        still running: poll `getRun` or use a webhook.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateRunRequest' }
            example:
              script: chartnaut/rsi
              instrument: NAS100
              timeframe: 15m
              window: { last: 90d }
              wait: 30
      responses:
        '200':
          description: Finished within `wait` (succeeded, failed or cancelled).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Run' }
        '202':
          description: Accepted, still queued or running.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Run' }
        '409':
          description: |
            `not_in_library`: another author's script, or a definition your study declares, is not in
            your library. `not_shared`: your study declares a definition that is not shared with you.
            `conflict`: one of your studies shares the slug with an indicator or definition.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422': { $ref: '#/components/responses/ScriptInvalid' }
        default: { $ref: '#/components/responses/Error' }
    get:
      tags: [Runs]
      operationId: listRuns
      summary: List your runs, newest first
      parameters:
        - name: source
          in: query
          description: |
            `api` (default): runs started through the API. `app`: study runs made in the app, as
            `srun_<id>` — get, results and cancel work on them like any run. `all`: both.
          schema: { type: string, enum: [api, app, all], default: api }
        - name: script
          in: query
          description: Filter by script slug.
          schema: { type: string }
        - name: status
          in: query
          schema: { $ref: '#/components/schemas/RunStatus' }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of runs.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/Run' }
        default: { $ref: '#/components/responses/Error' }

  /runs/{run_id}:
    parameters:
      - $ref: '#/components/parameters/RunId'
    get:
      tags: [Runs]
      operationId: getRun
      summary: Get a run's status, progress and summary
      parameters:
        - name: wait
          in: query
          description: Block up to this many seconds for the run to finish.
          schema: { type: integer, minimum: 0, maximum: 30, default: 0 }
      responses:
        '200':
          description: The run has finished (succeeded, failed or cancelled).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Run' }
        '202':
          description: The run is still queued or running (after `wait`, if given). Poll again.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Run' }
        default: { $ref: '#/components/responses/Error' }

  /runs/{run_id}/cancel:
    parameters:
      - $ref: '#/components/parameters/RunId'
    post:
      tags: [Runs]
      operationId: cancelRun
      summary: Cancel a queued or running run
      responses:
        '200':
          description: The run, now `cancelled` (or already terminal).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Run' }
        default: { $ref: '#/components/responses/Error' }

  /runs/{run_id}/results:
    parameters:
      - $ref: '#/components/parameters/RunId'
    get:
      tags: [Runs]
      operationId: getRunResults
      summary: Get what the run produced
      description: |
        Shape depends on the run's kind:
        - indicator → output series (time, value) per declared output
        - definition → emitted events
        - study → result blocks (metric, table, distribution, …)

        Paginated. Large study blocks are omitted by default and fetched by
        `keys`. `format=csv` returns one flat table (indicator: one column per
        output; definition: one row per event; study: requires one `keys`).
      parameters:
        - name: outputs
          in: query
          description: Indicator only. Comma list of output ids. Default all.
          schema: { type: string }
        - name: event
          in: query
          description: Definition only. Filter by declared event id.
          schema: { type: string }
        - name: keys
          in: query
          description: Study only. Comma list of result keys to return in full.
          schema: { type: string }
        - name: full
          in: query
          description: Study only. Return every block's data. Subject to the size cap.
          schema: { type: boolean, default: false }
        - name: from
          in: query
          schema: { type: string, format: date-time }
        - name: to
          in: query
          schema: { type: string, format: date-time }
        - name: format
          in: query
          schema: { type: string, enum: [json, csv], default: json }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: Results.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/IndicatorResults'
                  - $ref: '#/components/schemas/DefinitionResults'
                  - $ref: '#/components/schemas/StudyResults'
                discriminator:
                  propertyName: kind
                  mapping:
                    indicator: '#/components/schemas/IndicatorResults'
                    definition: '#/components/schemas/DefinitionResults'
                    study: '#/components/schemas/StudyResults'
            text/csv:
              schema: { type: string }
        '409':
          description: The run is not finished, or it failed or was cancelled (`run_not_finished`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410':
          description: The run's results expired (7 days).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Forward Insights ─────────────────────────────
  /insights:
    get:
      tags: [Forward Insights]
      operationId: listInsights
      summary: List your Forward Insights, newest change first
      description: |
        Your own insights. When sharing is on for your account, the list also includes other people's
        shared insights you added in the app, read-only: `is_owner` is `false`, `author` names them,
        and `study`, `study_version` and `app_url` are empty. Updating or removing one answers `not_found`.
      parameters:
        - name: definition
          in: query
          description: Only insights on this definition slug.
          schema: { type: string }
        - name: study
          in: query
          description: Only insights made from this study slug.
          schema: { type: string }
        - name: instrument
          in: query
          description: Only insights on this instrument.
          schema: { type: string, example: BTC }
        - name: timeframe
          in: query
          schema: { $ref: '#/components/schemas/Timeframe' }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of insights.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data: { type: array, items: { $ref: '#/components/schemas/Insight' } }
        '404':
          description: '`unknown_instrument`: the instrument filter names no instrument.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Forward Insights]
      operationId: createInsight
      summary: Put a study run on the chart as a Forward Insight
      description: |
        The run must have succeeded, and its study version must declare `pin_cell` as
        `popover_layout` and publish exactly one cell per combination of its `indexedBy`
        dimensions. The insight shows on the caller's charts of the definition, and of the run's
        instrument and timeframe. Never spends AI credits: the study is used as written. With
        `dry_run` nothing is saved and the response is the preview. Counts as a heavy request.

        A new insight is saved to your library, and shows on charts only once it is active
        (`POST /insights/{insight_id}/activate`); `message` says which. The library holds the
        plan's Forward Insights (Free 5, Pro 25): only your own live
        insights count, not ones you added. Re-saving one (`replaces`, or `replace` by name) keeps
        its place and never needs a slot; it also keeps its active state.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateInsightRequest' }
      responses:
        '200':
          description: '`dry_run`: every check passed. Nothing was saved.'
          content:
            application/json:
              schema:
                type: object
                required: [dry_run, definition, scope_dimensions, preview]
                properties:
                  dry_run: { type: boolean, enum: [true] }
                  definition: { type: string }
                  scope_dimensions: { type: array, items: { type: string } }
                  preview: { $ref: '#/components/schemas/InsightPreview' }
        '201':
          description: Created. Also carries the preview card.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Insight'
                  - type: object
                    required: [preview, message]
                    properties:
                      preview: { $ref: '#/components/schemas/InsightPreview' }
                      message: { type: string, description: 'Where it shows: saved to your library, and on charts once it is active (a re-save of an active insight already shows).', example: 'Saved to your library. To see it, make it active on a BTC 1h chart.' }
                      projection: { type: boolean, description: 'Present when `projection` was asked: whether the click now draws the projection too.' }
                      projection_error: { type: string, description: Why the projection could not be set. The insight was created with its card only. }
        '400':
          description: '`invalid_request`: missing `run` or `name`, not a study run, or `definition` is needed (the error lists the choices) or was not read by the run.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: '`forbidden`: the definition is someone else''s. Insights go on your own definitions (when sharing is on for your account: on definitions in your library). `plan_limit`: your library is full (the plan''s Forward Insights); delete one, re-save one with `replaces`, or upgrade.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no such run, or `replaces` is not one of your live insights on the definition.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`run_not_finished`: the run has not succeeded (`details.status`). `conflict`: `replace` is false and an insight with that name exists on the definition.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422':
          description: '`script_invalid`: the study does not meet the `pin_cell` contract. `details.fix` says what to change when it can; `details.docs_topic` is the reference page.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  /insights/{insight_id}:
    parameters:
      - name: insight_id
        in: path
        required: true
        schema: { type: string, pattern: '^ins_[0-9]+$', example: ins_61 }
    get:
      tags: [Forward Insights]
      operationId: getInsight
      summary: Get one Forward Insight
      responses:
        '200':
          description: The insight.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Insight' }
        '404':
          description: '`not_found`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Forward Insights]
      operationId: updateInsight
      summary: Rename an insight, change its description, or choose what a click on its events opens
      description: >-
        To change its numbers, run the study again and `POST /insights` with the same name.
        `show` is what a click on one of its events opens on the chart: `card` (its numbers),
        `outlook` (the study's outlook.js draws the projection) or `both`. `outlook` and `both`
        need the study to have an outlook, and a horizon no longer than the bars the chart keeps
        ahead and the bars the study measured after its events; a refusal says which.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              minProperties: 1
              properties:
                name: { type: string, minLength: 1, maxLength: 120 }
                description: { type: string, maxLength: 2000 }
                show: { type: string, enum: [card, outlook, both] }
                outlook_max_bars: { type: integer, minimum: 0, maximum: 1000, description: 'Bars ahead the outlook draws on this insight; 0 goes back to the outlook''s maxBars.' }
                outlook_label: { type: string, maxLength: 80, description: 'The outlook''s name on the charts; empty goes back to the outlook''s label.' }
      responses:
        '200':
          description: The updated insight.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Insight' }
        '400':
          description: '`invalid_request`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Forward Insights]
      operationId: deleteInsight
      summary: Take an insight off your charts. The study and its runs are kept
      responses:
        '204': { description: Removed. }
        '404':
          description: '`not_found`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  /insights/{insight_id}/activate:
    parameters:
      - name: insight_id
        in: path
        required: true
        schema: { type: string, pattern: '^ins_[0-9]+$', example: ins_61 }
    post:
      tags: [Forward Insights]
      operationId: activateInsight
      summary: Make an insight active, so it shows on your charts of its definition, instrument and timeframe
      description: |
        Works for your own insights and ones you added. One insight is active per definition,
        instrument and timeframe: activating where another is active replaces it (`replaced`), and
        never needs a slot. Otherwise it takes one of the plan's Forward Insights on charts
        (Free 1, Pro 5); when they are full the refusal names the
        active ones, so you can deactivate one first. Activating one that is already active
        changes nothing.
      responses:
        '200':
          description: Active.
          content:
            application/json:
              schema:
                type: object
                required: [insight, active, state, in_use, limit]
                properties:
                  insight: { type: string, example: ins_61 }
                  active: { type: boolean, enum: [true] }
                  state: { type: string, enum: [live, paused], description: '`paused` when the account is over its plan''s limit (after a downgrade): active but not shown until it fits.' }
                  replaced: { type: array, items: { type: string }, description: 'The insights it took the place of on the same definition, instrument and timeframe. Absent when none.' }
                  in_use: { type: integer, description: 'Active insights now, live and paused.' }
                  limit: { $ref: '#/components/schemas/ActiveInsightsLimit' }
        '400':
          description: '`invalid_request`: the insight cannot be made active (for example its series no longer resolves).'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: '`plan_limit`: your charts hold the plan''s Forward Insights on charts. `details.limit` is the limit and `details.active` the active insights (`ActiveInsight`); deactivate one and try again.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no such insight in your list.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  /insights/{insight_id}/deactivate:
    parameters:
      - name: insight_id
        in: path
        required: true
        schema: { type: string, pattern: '^ins_[0-9]+$', example: ins_61 }
    post:
      tags: [Forward Insights]
      operationId: deactivateInsight
      summary: Stop an insight showing on your charts. It stays in your library
      description: Frees its slot in the plan's Forward Insights on charts. Deactivating one that is not active changes nothing.
      responses:
        '200':
          description: Not active.
          content:
            application/json:
              schema:
                type: object
                required: [insight, active, in_use, limit]
                properties:
                  insight: { type: string, example: ins_61 }
                  active: { type: boolean, enum: [false] }
                  in_use: { type: integer, description: 'Active insights now, live and paused.' }
                  limit: { $ref: '#/components/schemas/ActiveInsightsLimit' }
        '400':
          description: '`invalid_request`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no such insight in your list.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Library ─────────────────────────────
  /library:
    get:
      tags: [Library]
      operationId: searchLibrary
      summary: Search the scripts the caller can use. No source
      description: |
        Searches the caller's own scripts, Chartnaut's built-ins, other people's public scripts
        and other people's public or unlisted scripts the caller added to their library.
        Studies have no community layer: only the caller's own and built-in studies appear.
        Archived and deleted scripts never appear, nor do other people's scripts whose owner
        has no username. Each item's `ref` is usable as `script` in
        `POST /runs`. Not a heavy call.
      parameters:
        - name: q
          in: query
          description: |
            Search words. Every word (the first 8 filter) must appear, in any letter case, in the
            name, slug, description, tags, category or author's username. Built-ins match
            `chartnaut` as their author.
          schema: { type: string, maxLength: 200 }
        - name: kind
          in: query
          description: An unknown kind is `400 invalid_request`.
          schema: { $ref: '#/components/schemas/ScriptKind' }
        - name: scope
          in: query
          description: |
            `mine`: own scripts, any visibility. `published`: own public scripts.
            `chartnaut`: built-ins. `community`: other people's public scripts.
            `installed`: other people's public or unlisted scripts the caller added to their
            library. `library`: mine + chartnaut + installed (what the app's library shows).
            `all`: library + community.
          schema:
            type: string
            enum: [all, library, mine, published, chartnaut, community, installed]
            default: all
        - name: author
          in: query
          description: One author, within `scope`. A username, `chartnaut` for built-ins, or `me`.
          schema: { type: string }
        - name: sort
          in: query
          description: |
            Defaults to `relevance` when `q` is set, else `updated`. `relevance`: exact slug or
            name, then prefix, then substring match on the whole query, ties by adoptions then
            updated. `updated`/`created`: newest first. `adoptions`: most first. `name`: A to Z.
          schema:
            type: string
            enum: [relevance, updated, created, adoptions, name]
        - name: include
          in: query
          description: '`interface` adds each item''s interface at its latest version.'
          schema: { type: string, enum: [interface] }
        - $ref: '#/components/parameters/Cursor'
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
      responses:
        '200':
          description: A page of library scripts.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/LibraryScript' }
        '400':
          description: '`invalid_request`: bad `scope`, `kind` or `sort`, or `q` over 200 characters.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  /library/{author}/{slug}:
    get:
      tags: [Library]
      operationId: getLibraryScript
      summary: Describe one library script, with its interface and dependencies. No source
      description: |
        `author` is a username, `chartnaut` for built-ins, or `me` for the caller's own.
        Someone else's script is found when it is public, or unlisted and added to the
        caller's library. It runs (`POST /runs`) only once it is in the caller's library
        (`installed: true`). Other people's studies are never found. Describes the latest saved version, or
        version N with `slug@N`. Never returns files or code, whatever the script's
        show-source setting in the app.
      parameters:
        - name: author
          in: path
          required: true
          description: A username, `chartnaut` or `me`, in any letter case.
          schema: { type: string, example: chartnaut }
        - name: slug
          in: path
          required: true
          description: The script's slug, optionally pinned as `slug@N`.
          schema: { type: string, example: rsi@6 }
        - name: kind
          in: query
          description: Required when one of the caller's studies shares the slug with an indicator or definition.
          schema: { $ref: '#/components/schemas/ScriptKind' }
      responses:
        '200':
          description: The script at the version asked for.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LibraryScriptDetail' }
        '400':
          description: '`invalid_request`: the slug or version in the path, or `kind`, is not valid.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no script by that author and slug the caller can see, or no version N.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`conflict`: a study shares the slug. Pass `kind`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Library]
      operationId: addToLibrary
      summary: Add another author's script to your library, with the scripts it needs
      description: |
        Another author's indicator or definition runs only once it is in your library, as in the
        app. Adding it also adds the scripts it reads that you have not added, all or nothing.
        Adding never copies anything: each script stays its author's, tracks their edits, and can
        be removed at any time.

        The agreement step: call `getLibraryRequirements`, show the person what will be added, and
        only if they agree send `confirm` listing every ref in its `confirm`. A `confirm` that leaves
        any out adds nothing and answers 409 `confirmation_required` with `details.needs`,
        `details.confirm` and `details.missing`.

        Already usable (your own, a built-in, or already added): 200 with `added: false` and
        `reason`; nothing changes. A dependency not shared with you: 409 `not_shared` with
        `details.cannot_add`. A study: 409 `not_installable`. `@N` in the path is refused (400): a
        library entry is the live script.
      parameters:
        - $ref: '#/components/parameters/LibraryAuthor'
        - $ref: '#/components/parameters/LibrarySlug'
        - name: kind
          in: query
          description: When the author has an indicator and a definition with that slug.
          schema: { type: string, enum: [indicator, definition] }
      requestBody:
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LibraryAddRequest' }
      responses:
        '201':
          description: Added, with everything in `added_with`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LibraryAddResult' }
        '200':
          description: Already usable. Nothing changed; `added` is false and `reason` says why.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LibraryAddResult' }
        '400':
          description: '`invalid_request`: the body is not JSON, the path has `@N`, or `kind` is not valid.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no script by that author and slug the caller can see.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `confirmation_required`: `confirm` does not list every script that would be added
            (details: `needs`, `confirm`, `missing`). `not_shared`: something it needs is not shared
            with you (details: `cannot_add`). `not_installable`: studies cannot be added. `conflict`:
            pass `kind`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Library]
      operationId: removeFromLibrary
      summary: Remove a script you added from your library
      description: |
        Removes the library entry only; the scripts added with it stay. Works after the author made
        the script private or archived it. Your own scripts and `chartnaut/` built-ins cannot be
        removed (400).
      parameters:
        - $ref: '#/components/parameters/LibraryAuthor'
        - $ref: '#/components/parameters/LibrarySlug'
        - name: kind
          in: query
          description: Required when you added an indicator and a definition with that slug.
          schema: { type: string, enum: [indicator, definition] }
      responses:
        '200':
          description: Removed.
          content:
            application/json:
              schema:
                type: object
                required: [removed, ref, kind]
                properties:
                  removed: { type: boolean, const: true }
                  ref: { type: string, example: bob/vwap-bands }
                  kind: { type: string, enum: [indicator, definition] }
        '400':
          description: '`invalid_request`: your own script or a built-in, `@N` in the path, or a bad `kind`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: it is not in your library.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`conflict`: you added an indicator and a definition with that slug. Pass `kind`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  /library/{author}/{slug}/requirements:
    get:
      tags: [Library]
      operationId: getLibraryRequirements
      summary: What adding a script to your library would add, and anything that stops it
      description: |
        The app's "Add to library" dialog as data. Changes nothing. `confirm` is exactly what to send
        to `addToLibrary` once the person agrees. A study's `root.status` is `not_installable`.
        `@N` in the path is refused (400).
      parameters:
        - $ref: '#/components/parameters/LibraryAuthor'
        - $ref: '#/components/parameters/LibrarySlug'
        - name: kind
          in: query
          description: When the author has more than one script with that slug.
          schema: { $ref: '#/components/schemas/ScriptKind' }
      responses:
        '200':
          description: The requirements.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LibraryRequirements' }
        '400':
          description: '`invalid_request`: the path is not `/library/{author}/{slug}`, has `@N`, or `kind` is not valid.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`not_found`: no script by that author and slug the caller can see.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`conflict`: more than one script with that slug. Pass `kind`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Catalog ─────────────────────────────
  /instruments:
    get:
      tags: [Catalog]
      operationId: searchInstruments
      summary: Search instruments you can run on
      parameters:
        - name: q
          in: query
          description: Matches symbol, short symbol and name.
          schema: { type: string, example: bitcoin }
        - name: category
          in: query
          schema: { $ref: '#/components/schemas/InstrumentCategory' }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of instruments.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/Instrument' }
        default: { $ref: '#/components/responses/Error' }

  /datasets:
    get:
      tags: [Catalog]
      operationId: listDatasets
      summary: List the reference datasets scripts can read
      description: >-
        What `dataset(name, { where })` reads: the economic calendar (schedule, forecast and previous
        figure; the released figure is not available to scripts) and daily rates and yields. Each entry
        lists its fields, the fields `where` can filter on and with which operators, the plan it needs
        and how far back and ahead reads may reach.
      responses:
        '200':
          description: The catalogue.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        name: { type: string, example: econ.calendar }
                        doc: { type: string }
                        time_field: { type: string, example: scheduledAt }
                        main_field: { type: string, example: value }
                        fields:
                          type: array
                          items:
                            type: object
                            properties:
                              name: { type: string }
                              type: { type: string, enum: [string, number, boolean, time] }
                              optional: { type: boolean }
                              doc: { type: string }
                        filters:
                          type: object
                          additionalProperties: { type: array, items: { type: string, enum: [eq, in, gte, lte, fromInstrument] } }
                        require_filter_one_of: { type: array, items: { type: string } }
                        min_plan: { type: string, enum: [free, starter, pro, ultra] }
                        max_lookback: { type: string, example: 400d }
                        max_lookahead: { type: string, example: 7d }
        default: { $ref: '#/components/responses/Error' }

  /datasets/econ.calendar/codes:
    get:
      tags: [Catalog]
      operationId: searchCalendarCodes
      summary: Search economic calendar indicator codes
      description: >-
        Codes to filter `dataset("econ.calendar", { where: { code } })` on. Every word of `q` must
        match the release name or code.
      parameters:
        - name: q
          in: query
          required: true
          schema: { type: string, example: nonfarm payrolls }
        - name: country
          in: query
          description: One economy, two letters (EU = euro area).
          schema: { type: string, example: US }
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: Matching codes, most important first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        code: { type: string, example: US.NFP }
                        name: { type: string, example: Non Farm Payrolls }
                        country: { type: string, example: US }
                        category: { type: string, example: labour }
                        importance: { type: integer, minimum: 1, maximum: 3 }
                        expects_actual: { type: boolean }
        default: { $ref: '#/components/responses/Error' }

  /instruments/{symbol}:
    get:
      tags: [Catalog]
      operationId: getInstrument
      summary: Get one instrument, including the coverage your plan can reach
      parameters:
        - name: symbol
          in: path
          required: true
          description: Canonical (`HYPERLIQUID:BTC`) or short (`BTC`). URL-encode it.
          schema: { type: string }
      responses:
        '200':
          description: The instrument.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Instrument' }
        default: { $ref: '#/components/responses/Error' }

  /timeframes:
    get:
      tags: [Catalog]
      operationId: listTimeframes
      summary: List supported timeframes
      responses:
        '200':
          description: Supported timeframes.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Timeframe' }

  # ───────────────────────────── Account ─────────────────────────────
  /me:
    get:
      tags: [Account]
      operationId: whoami
      summary: Who this token belongs to, its scopes and the plan
      responses:
        '200':
          description: The caller.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Me' }
        default: { $ref: '#/components/responses/Error' }

  /usage:
    get:
      tags: [Account]
      operationId: getUsage
      summary: Compute used this period, and every plan cap with its current count
      responses:
        '200':
          description: Usage.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Usage' }
        default: { $ref: '#/components/responses/Error' }

  /webhooks:
    get:
      tags: [Account]
      operationId: listWebhooks
      summary: List webhooks (not available yet, 501)
      responses:
        '200':
          description: Webhooks.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Webhook' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Account]
      operationId: createWebhook
      summary: Register a webhook (not available yet, 501)
      description: |
        Deliveries are POSTs signed with `Chartnaut-Signature: t=<unix>,v1=<hex>`,
        HMAC-SHA256 of `<t>.<body>` with the webhook's secret. Retried with
        backoff for 24h on non-2xx.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri }
                events:
                  type: array
                  items: { $ref: '#/components/schemas/WebhookEvent' }
      responses:
        '201':
          description: Created. `secret` is shown once.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Webhook'
                  - type: object
                    properties:
                      secret: { type: string }
        default: { $ref: '#/components/responses/Error' }

  /webhooks/{webhook_id}:
    delete:
      tags: [Account]
      operationId: deleteWebhook
      summary: Delete a webhook (not available yet, 501)
      parameters:
        - name: webhook_id
          in: path
          required: true
          schema: { type: string }
      responses:
        '204': { description: Deleted. }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Docs ─────────────────────────────
  /docs:
    get:
      tags: [Docs]
      operationId: listDocs
      summary: List scripting reference topics
      responses:
        '200':
          description: Topics.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        topic: { type: string, example: definitions/events }
                        title: { type: string }
                        summary: { type: string }
                        kind: { $ref: '#/components/schemas/ScriptKind' }
                        tokens: { type: integer, description: Approximate size. }

  /docs/{topic}:
    get:
      tags: [Docs]
      operationId: getDoc
      summary: Get one reference topic as markdown
      parameters:
        - name: topic
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Markdown.
          content:
            text/markdown:
              schema: { type: string }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Developer projects ─────────────────────────────
  # Needs a token with the opt-in apps:write scope (the scope keeps its name). Refusals: invalid_request,
  # name_reserved, app_limit (details {limit: "apps", owner: "developer", used, cap}; the code and limit
  # keep their old names), rate_limited, site_refused, key_limit, not_found, forbidden, owner_only,
  # live_keys_browser_only, test_only. See developer-apps.md.
  /projects:
    get:
      tags: [Projects]
      operationId: listProjects
      summary: List your developer projects
      responses:
        '200':
          description: Your projects and your developer plan.
          content:
            application/json:
              schema: { type: object, properties: { data: { type: array, items: { $ref: '#/components/schemas/Project' } }, plan: { type: object, properties: { max: { type: integer }, plan: { type: string } } } } }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Projects]
      operationId: createProject
      summary: Create a developer project and its first Test key (the secret is shown once)
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [name], properties: { name: { type: string, maxLength: 60, description: "What the project's users see on the Connect screen." } } }
      responses:
        '201':
          description: The project and its Test key.
          content:
            application/json:
              schema: { type: object, properties: { app: { $ref: '#/components/schemas/Project' }, test_key: { $ref: '#/components/schemas/ProjectKeyCreated' } } }
        default: { $ref: '#/components/responses/Error' }

  /projects/{slug}:
    get:
      tags: [Projects]
      operationId: getProject
      summary: Get one project
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: The project.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Project' }
        default: { $ref: '#/components/responses/Error' }

  /projects/{slug}/keys:
    post:
      tags: [Projects]
      operationId: createProjectKey
      summary: 'Mint a Test key (Live keys are only made in the browser: env "live" is 403 live_keys_browser_only)'
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { name: { type: string }, env: { type: string, enum: [test, live], default: test } } }
      responses:
        '201':
          description: The key; the secret is shown once.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectKeyCreated' }
        default: { $ref: '#/components/responses/Error' }

  /projects/{slug}/sites:
    get:
      tags: [Projects]
      operationId: listProjectSites
      summary: List Test sites
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: Test sites.
          content:
            application/json:
              schema: { type: object, properties: { data: { type: array, items: { type: object, additionalProperties: true } }, automatic_test_sites: { type: array, items: { type: string } } } }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Projects]
      operationId: addProjectSite
      summary: 'Add a Test site (Live sites are only added in the browser: 403 test_only)'
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [origin], properties: { origin: { type: string, example: 'https://*.vercel.app' }, env: { type: string, enum: [test, live], default: test } } }
      responses:
        '200':
          description: The site. localhost answers `automatic` true and stores nothing.
          content:
            application/json:
              schema: { type: object, properties: { origin: { type: string }, wildcard: { type: boolean }, automatic: { type: boolean } } }
        default: { $ref: '#/components/responses/Error' }

  /projects/{slug}/quickstart:
    get:
      tags: [Projects]
      operationId: getProjectQuickstart
      summary: What Test and Live still need, and the one CLI command
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: The quickstart.
          content:
            application/json:
              schema: { type: object, properties: { test: { type: array, items: { $ref: '#/components/schemas/ProjectStep' } }, live: { type: array, items: { $ref: '#/components/schemas/ProjectStep' } }, command: { type: string }, env_key: { type: string } } }
        default: { $ref: '#/components/responses/Error' }

  # The old paths: projects were called apps until November 2026. Kept permanently, deprecated.
  /apps:
    get:
      tags: [Projects]
      operationId: listApps
      summary: Old path of listProjects
      deprecated: true
      description: The same operation as `/projects`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects`.
      responses:
        '200':
          description: Your projects and your developer plan.
          content:
            application/json:
              schema: { type: object, properties: { data: { type: array, items: { $ref: '#/components/schemas/Project' } }, plan: { type: object, properties: { max: { type: integer }, plan: { type: string } } } } }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Projects]
      operationId: createApp
      summary: Old path of createProject
      deprecated: true
      description: The same operation as `/projects`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [name], properties: { name: { type: string, maxLength: 60, description: "What the project's users see on the Connect screen." } } }
      responses:
        '201':
          description: The project and its Test key.
          content:
            application/json:
              schema: { type: object, properties: { app: { $ref: '#/components/schemas/Project' }, test_key: { $ref: '#/components/schemas/ProjectKeyCreated' } } }
        default: { $ref: '#/components/responses/Error' }

  /apps/{slug}:
    get:
      tags: [Projects]
      operationId: getApp
      summary: Old path of getProject
      deprecated: true
      description: The same operation as `/projects/{slug}`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects/{slug}`.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: The project.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Project' }
        default: { $ref: '#/components/responses/Error' }

  /apps/{slug}/keys:
    post:
      tags: [Projects]
      operationId: createAppKey
      summary: Old path of createProjectKey
      deprecated: true
      description: The same operation as `/projects/{slug}/keys`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects/{slug}/keys`.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { name: { type: string }, env: { type: string, enum: [test, live], default: test } } }
      responses:
        '201':
          description: The key; the secret is shown once.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectKeyCreated' }
        default: { $ref: '#/components/responses/Error' }

  /apps/{slug}/sites:
    get:
      tags: [Projects]
      operationId: listAppSites
      summary: Old path of listProjectSites
      deprecated: true
      description: The same operation as `/projects/{slug}/sites`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects/{slug}/sites`.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: Test sites.
          content:
            application/json:
              schema: { type: object, properties: { data: { type: array, items: { type: object, additionalProperties: true } }, automatic_test_sites: { type: array, items: { type: string } } } }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Projects]
      operationId: addAppSite
      summary: Old path of addProjectSite
      deprecated: true
      description: The same operation as `/projects/{slug}/sites`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects/{slug}/sites`.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, required: [origin], properties: { origin: { type: string, example: 'https://*.vercel.app' }, env: { type: string, enum: [test, live], default: test } } }
      responses:
        '200':
          description: The site. localhost answers `automatic` true and stores nothing.
          content:
            application/json:
              schema: { type: object, properties: { origin: { type: string }, wildcard: { type: boolean }, automatic: { type: boolean } } }
        default: { $ref: '#/components/responses/Error' }

  /apps/{slug}/quickstart:
    get:
      tags: [Projects]
      operationId: getAppQuickstart
      summary: Old path of getProjectQuickstart
      deprecated: true
      description: The same operation as `/projects/{slug}/quickstart`, kept working permanently for clients built before the rename (the CLI through 0.5.0 and `@chartnaut/create-app` still call it). Use `/projects/{slug}/quickstart`.
      parameters:
        - { name: slug, in: path, required: true, schema: { type: string, example: acme-desk-k3p9 } }
      responses:
        '200':
          description: The quickstart.
          content:
            application/json:
              schema: { type: object, properties: { test: { type: array, items: { $ref: '#/components/schemas/ProjectStep' } }, live: { type: array, items: { $ref: '#/components/schemas/ProjectStep' } }, command: { type: string }, env_key: { type: string } } }
        default: { $ref: '#/components/responses/Error' }

components:
  securitySchemes:
    bearerToken:
      type: http
      scheme: bearer
      description: |
        A personal API token (`cn_live_…`) minted in Settings → Developers
        (terminal.chartnaut.com/morpheus/settings/developers). Stored hashed; shown
        once. Scopes: `scripts:read` (every GET, and validate),
        `scripts:write` (create, save, patch, delete), `runs:write` (start and
        cancel runs). 300 requests a minute per token. The same token works for
        the CLI and the MCP server.

  parameters:
    LibraryAuthor:
      name: author
      in: path
      required: true
      description: The author's username (or `me` / `chartnaut` where allowed), in any letter case.
      schema: { type: string, example: bob }
    LibrarySlug:
      name: slug
      in: path
      required: true
      description: The script's slug. No `@N`; a library entry is the live script.
      schema: { type: string, example: vwap-bands }
    Slug:
      name: slug
      in: path
      required: true
      description: Your script's slug, optionally pinned as `slug@N`.
      schema: { type: string, pattern: '^[a-z0-9][a-z0-9-]{1,62}(@[0-9]+)?$', example: vwap-reclaim@3 }
    RunId:
      name: run_id
      in: path
      required: true
      schema: { type: string, example: run_01J9ZK3Q8C4 }
    Kind:
      name: kind
      in: query
      schema: { $ref: '#/components/schemas/ScriptKind' }
    Cursor:
      name: cursor
      in: query
      description: Opaque cursor from a previous page's `next_cursor`.
      schema: { type: string }
    Limit:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 500, default: 50 }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      description: |
        Any unique string. A retry with the same key within 24h returns the
        first response instead of creating a second script, version or run.
      schema: { type: string, maxLength: 128 }

  responses:
    Error:
      description: Error.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ScriptInvalid:
      description: The script does not lint, link or derive. Nothing was saved or run.
      content:
        application/json:
          schema:
            allOf:
              - $ref: '#/components/schemas/Error'
              - type: object
                properties:
                  diagnostics:
                    type: array
                    items: { $ref: '#/components/schemas/Diagnostic' }

  schemas:
    # ── primitives ──
    ScriptKind:
      type: string
      enum: [indicator, definition, study]
    Visibility:
      type: string
      enum: [private, public]
      description: Studies are always private; setting visibility on a study is refused with 400.
    Timeframe:
      type: string
      enum: ['1m', '5m', '15m', '30m', '1h', '2h', '4h', '1d', '1w', '1mo']
    ScriptRef:
      type: string
      description: |
        `slug` or `slug@N` for your own scripts; `author/slug` or
        `author/slug@N` for library scripts; `chartnaut/slug` for built-ins
        (which always run their latest version).
      examples: [vwap-reclaim, vwap-reclaim@3, jane/orb-breakout@7, chartnaut/rsi]
    Window:
      type: object
      description: |
        Exactly one of `{from,to}`, `last` or `bars`. Warmup is fetched before
        the window automatically and never counted in results. Clamped to the
        plan's historical depth.
      properties:
        from: { type: string, format: date-time }
        to: { type: string, format: date-time, description: Defaults to now. }
        last: { type: string, pattern: '^[0-9]+[dwmy]$', example: 90d }
        bars: { type: integer, minimum: 1, example: 2000 }
    Page:
      type: object
      properties:
        next_cursor: { type: [string, 'null'] }

    # ── scripts ──
    ScriptFile:
      type: object
      required: [path, code]
      properties:
        path: { type: string, example: main.ts }
        code: { type: string }
        entry:
          type: boolean
          description: Exactly one file is the entry. Indicators have one file, always the entry.
    ScriptSource:
      type: object
      required: [kind, files]
      properties:
        kind: { $ref: '#/components/schemas/ScriptKind' }
        files:
          type: array
          minItems: 1
          items: { $ref: '#/components/schemas/ScriptFile' }
    CreateScriptRequest:
      allOf:
        - $ref: '#/components/schemas/ScriptSource'
        - type: object
          required: [slug]
          properties:
            slug: { type: string, pattern: '^[a-z0-9][a-z0-9-]{1,62}$' }
            name: { type: string }
            description: { type: string }
            visibility: { $ref: '#/components/schemas/Visibility' }
            change_summary: { type: string }
    UpdateScriptRequest:
      type: object
      required: [files, base_version]
      properties:
        files:
          type: array
          minItems: 1
          description: The full file set for the new version. Missing files are deleted.
          items: { $ref: '#/components/schemas/ScriptFile' }
        base_version: { type: integer, minimum: 1 }
        change_summary: { type: string }
    ScriptSummary:
      type: object
      properties:
        id:
          type: string
          description: "The script's id for the Terminal SDK and partner API: `ind_<n>` for an indicator, `flw_<n>` for a definition. Pass it to `cn.scripts.publish({ script })` or `chart.scripts.add`. Absent for a study."
          example: ind_1298
        slug: { type: string }
        kind: { $ref: '#/components/schemas/ScriptKind' }
        name: { type: string }
        description: { type: string }
        visibility: { $ref: '#/components/schemas/Visibility' }
        latest_version: { type: integer }
        updated_at: { type: string, format: date-time }
        app_url: { type: string, format: uri, description: Opens this script in the Chartnaut app. }
    Script:
      allOf:
        - $ref: '#/components/schemas/ScriptSummary'
        - type: object
          properties:
            version: { type: integer, description: The version this response describes. }
            interface: { $ref: '#/components/schemas/ScriptInterface' }
            dependencies:
              type: array
              items: { $ref: '#/components/schemas/PinnedDependency' }
            files:
              type: array
              description: Present with `include=source` on your own scripts.
              items: { $ref: '#/components/schemas/ScriptFile' }
    VersionSummary:
      type: object
      properties:
        version: { type: integer }
        change_summary: { type: string }
        author: { type: string, description: '`you`, `app-agent`, `api` or a model id.' }
        created_at: { type: string, format: date-time }
    PinnedDependency:
      type: object
      properties:
        ref: { $ref: '#/components/schemas/ScriptRef' }
        as: { type: string, description: The alias the script uses. }
        version: { type: integer }
    ScriptInterface:
      type: object
      description: What a caller needs to run the script and read its results. Derived from the code.
      properties:
        settings:
          type: object
          additionalProperties: { $ref: '#/components/schemas/SettingDef' }
        outputs:
          type: array
          description: Indicator only.
          items: { $ref: '#/components/schemas/OutputDef' }
        events:
          type: array
          description: Definition only. The events it can emit.
          items: { $ref: '#/components/schemas/EventDef' }
        results:
          type: array
          description: Study only. The result blocks it produces.
          items:
            type: object
            properties:
              key: { type: string }
              kind: { $ref: '#/components/schemas/StudyResultKind' }
              title: { type: string }
        timeframes:
          type: array
          description: Extra timeframes the script reads besides the run's own.
          items: { $ref: '#/components/schemas/Timeframe' }
        warmup_bars: { type: integer }
    SettingDef:
      type: object
      properties:
        type:
          type: string
          enum: [number, string, boolean, color, select, multi_select, timeframe, range, array]
          description: An indicator's settings take their type, bounds and options from its settings dialog.
        default: {}
        min: { type: number }
        max: { type: number }
        step: { type: number }
        options:
          type: array
          description: Choices for a select. From an indicator's settings dialog each is `{label, value}`.
          items: {}
    OutputDef:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        kind:
          type: string
          description: The output's declared kind (line, area, baseline, histogram, fill, markers, labels, hline, range, …).
        pane: { type: string, enum: [price, own] }
    EventDef:
      type: object
      properties:
        id: { type: string, example: reclaim_long }
        intent: { type: string }
        payload_keys:
          type: array
          items: { type: string }
    Diagnostic:
      type: object
      required: [severity, message]
      properties:
        severity: { type: string, enum: [error, warning] }
        code: { type: string, example: link.unresolved_import }
        message: { type: string }
        path: { type: string }
        line: { type: integer }
        setting: { type: string, description: 'The setting a finding is about, if any.' }
    ValidationResult:
      type: object
      properties:
        ok: { type: boolean }
        diagnostics:
          type: array
          items: { $ref: '#/components/schemas/Diagnostic' }
        interface: { $ref: '#/components/schemas/ScriptInterface' }
        dependencies:
          type: array
          description: The versions a save would pin now.
          items: { $ref: '#/components/schemas/PinnedDependency' }

    # ── runs ──
    RunStatus:
      type: string
      enum: [queued, running, succeeded, failed, cancelled]
    CreateRunRequest:
      type: object
      required: [instrument, timeframe, window]
      properties:
        script: { $ref: '#/components/schemas/ScriptRef' }
        source:
          $ref: '#/components/schemas/ScriptSource'
        instrument:
          type: string
          description: Canonical or short symbol.
          example: BTC
        timeframe: { $ref: '#/components/schemas/Timeframe' }
        window: { $ref: '#/components/schemas/Window' }
        settings:
          type: object
          description: Overrides; anything omitted uses the script's default.
          additionalProperties: true
        study:
          type: object
          description: Study only.
          properties:
            event_filter:
              type: object
              description: Restrict to events matching these payload values.
              additionalProperties: true
        wait:
          type: integer
          minimum: 0
          maximum: 30
          default: 0
          description: Seconds to block for completion.
        label: { type: string, description: 'Free text, shown in the app.' }
      oneOf:
        - required: [script]
        - required: [source]
    FailureKind:
      type: string
      description: Why a run failed. `retryable` on the run says whether trying again can help.
      enum: [script, plan_limit, out_of_coverage, data_not_ready, timeout, cancelled, internal]
    Run:
      type: object
      properties:
        id: { type: string }
        kind: { $ref: '#/components/schemas/ScriptKind' }
        script:
          type: string
          description: The resolved ref that ran (`vwap-reclaim@3`), or `inline`.
        instrument: { type: string, example: NAS100, description: "The instrument's display symbol (`short` in /instruments). " }
        timeframe: { $ref: '#/components/schemas/Timeframe' }
        window:
          type: object
          description: The resolved window after clamping.
          properties:
            from: { type: string, format: date-time }
            to: { type: string, format: date-time }
        settings: { type: object, additionalProperties: true }
        status: { $ref: '#/components/schemas/RunStatus' }
        progress:
          type: object
          properties:
            pct: { type: number, minimum: 0, maximum: 100 }
            phase: { type: string, example: collecting }
        failure:
          type: [object, 'null']
          properties:
            kind: { $ref: '#/components/schemas/FailureKind' }
            message: { type: string }
            retryable: { type: boolean }
            diagnostics:
              type: array
              items: { $ref: '#/components/schemas/Diagnostic' }
        summary:
          type: [object, 'null']
          description: |
            Small, always inline once finished.
            indicator: `{bars, outputs:{id:{last, min, max, count}}, warnings?, errors?}`
            definition: `{bars, events_total, events_kept?, by_event:{id:count}, warnings?, errors?}`
            study: `{events_processed}`
            `errors` are runtime errors on some bars; the run still produced results.
          additionalProperties: true
        console:
          type: [array, 'null']
          description: The first 50 console lines the script printed. `null` until the run has finished, or when it printed nothing.
          items:
            type: object
            properties:
              level: { type: string }
              message: { type: string }
              time: { type: string, format: date-time }
        usage:
          type: object
          properties:
            bars: { type: integer, description: 'Bars evaluated, warmup and dependencies included.' }
            compute_units: { type: number }
        app_url:
          type: [string, 'null']
          format: uri
          description: Study runs only; indicator and definition runs are not stored in the app.
        results_expire_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
        started_at: { type: [string, 'null'], format: date-time }
        finished_at: { type: [string, 'null'], format: date-time }

    # ── results ──
    IndicatorResults:
      type: object
      required: [kind, run_id]
      properties:
        kind: { type: string, const: indicator }
        run_id: { type: string }
        outputs:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              kind: { type: string, enum: [line, area, baseline, histogram, fill, markers, labels, hlines, ranges, trendlines] }
              points:
                type: array
                description: |
                  Unix seconds. `line|area|baseline`: `{t, v}` (v is null where
                  the script produced no finite value). `histogram`:
                  `{t, v, color?}`. `fill`: `{t, top, bottom}`.
                  `markers|labels|hlines|ranges|trendlines`: `{t, data}`; the
                  last three are returned as one output each, id = kind.
                items:
                  type: object
                  properties:
                    t: { type: integer }
                    v: { type: number }
                  additionalProperties: true
        next_cursor: { type: [string, 'null'] }
    DefinitionResults:
      type: object
      required: [kind, run_id]
      properties:
        kind: { type: string, const: definition }
        run_id: { type: string }
        events:
          type: array
          items: { $ref: '#/components/schemas/Event' }
        next_cursor: { type: [string, 'null'] }
    Event:
      type: object
      properties:
        event: { type: string, description: The declared event id. }
        intent: { type: string }
        instrument: { type: string }
        timeframe: { $ref: '#/components/schemas/Timeframe' }
        start: { type: string, format: date-time }
        end: { type: string, format: date-time }
        bar_index: { type: integer }
        payload:
          type: object
          additionalProperties: true
    StudyResultKind:
      type: string
      enum: [metric, series, distribution, boxplot, heatmap, scatter, bar, table, vega, annotation, prose, popover_layout]
    StudyResults:
      type: object
      required: [kind, run_id]
      properties:
        kind: { type: string, const: study }
        run_id: { type: string }
        results:
          type: array
          items:
            type: object
            properties:
              key: { type: string }
              kind: { $ref: '#/components/schemas/StudyResultKind' }
              title: { type: string }
              data:
                description: |
                  Present for `metric` always, and for other kinds when named in
                  `keys` or with `full=true`. Shapes: metric `{value}`,
                  series `[{x,y,series?}]`, distribution `[{lo,hi,mid,count}]`,
                  boxplot `[{group,values[]}]`, heatmap `[{x,y,value}]`,
                  scatter `[{x,y,group?}]`, bar `[{cat,value,series?}]`,
                  table `[object]`, vega `object`.
              omitted:
                type: boolean
                description: True when `data` was left out. Fetch with `keys=<key>`.
              size: { type: integer, description: Rows in the full data. }
        caveats:
          type: array
          description: Interpretation warnings (small sample, overlapping events, …).
          items: { type: string }
        truncated: { type: boolean, description: True if the 1 MB response cap cut data. }

    # ── forward insights ──
    Insight:
      type: object
      properties:
        id: { type: string, example: ins_61 }
        name: { type: string }
        description: { type: string }
        definition: { type: string, description: The definition slug whose events show the card. }
        study: { type: string, description: The study slug. }
        study_version: { type: [integer, 'null'] }
        instrument: { type: string, example: BTC }
        timeframe: { $ref: '#/components/schemas/Timeframe' }
        profile: { type: [string, 'null'], description: 'The definition profile of the run. The card shows on charts using this profile.' }
        window: { $ref: '#/components/schemas/Window' }
        scope_dimensions: { type: array, items: { type: string }, description: '`pin_cell`''s `indexedBy`. Empty for one global card.' }
        is_owner: { type: boolean, description: '`false` for someone else''s shared insight you added in the app (read-only).' }
        author: { type: string, description: 'The username of whoever shared it. Only when `is_owner` is `false`.' }
        app_url: { type: string, description: 'Opens the insight''s study run in the app. Empty when `is_owner` is `false`.' }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        problems:
          type: array
          description: 'What stops this insight working for you: a dependency of its study that is not in your library, or no longer shared with you. Empty when it works.'
          items:
            type: object
            required: [code, kind, name]
            properties:
              code: { type: string }
              kind: { type: string }
              name: { type: string }
              add: { type: string }
              reason: { type: string }
        active: { type: boolean, description: 'It shows on your charts of its definition, instrument and timeframe (`POST /insights/{insight_id}/activate`).' }
        active_state: { type: [string, 'null'], enum: [live, paused, null], description: 'Only when `active`: `live`, or `paused` when the account is over its plan''s Forward Insights on charts (after a downgrade).' }
        valid_from: { type: [string, 'null'], format: date-time, description: 'The first moment its numbers know nothing about (the run''s end, plus how far the study read past an event, to the next bar). Setups from then on are out of sample. Null when unknown.' }
        headline:
          type: [object, 'null']
          description: 'The one number its label shows, across every setup. Null when it has none, or an older insight''s is not worked out yet.'
          required: [value, label, basis]
          properties:
            value: { type: string }
            label: { type: string }
            basis: { type: string, enum: [this_setup, all_setups] }
      required: [id, name, description, definition, study, study_version, instrument, timeframe, profile, window, scope_dimensions, is_owner, app_url, created_at, updated_at, active, valid_from, headline]
    CreateInsightRequest:
      type: object
      required: [run, name]
      properties:
        run: { type: string, description: 'A succeeded study run: `run_…` from `POST /runs`, or `srun_…` for a run made in the app.' }
        name: { type: string, minLength: 1, maxLength: 120, description: What the chart shows as the card's title. }
        definition: { type: string, description: 'Your definition slug. Needed only when the study reads more than one of yours.' }
        description: { type: string, maxLength: 2000 }
        replace: { type: boolean, default: true, description: 'Replace an insight with the same name on the same definition. `false` refuses with `conflict` instead.' }
        replaces: { type: string, pattern: '^ins_[0-9]+$', example: ins_61, description: 'Re-save this insight of yours (on the same definition) whatever its name is now: it keeps its place in the library, its active state and who added it, and never needs a library slot. Takes precedence over `replace`.' }
        dry_run: { type: boolean, default: false, description: Run every check and return the preview without saving. }
        projection: { type: boolean, default: false, description: 'A click on one of its events also draws the study''s projection (`outlook.js`) on the chart (`show: both`). Needs the study to have one. If it cannot be set, the insight is still created and `projection_error` says why.' }
    ActiveInsightsLimit:
      description: 'The plan''s Forward Insights on charts: a number, or `unlimited`.'
      oneOf:
        - { type: integer, minimum: 0 }
        - { type: string, enum: [unlimited] }
    ActiveInsight:
      type: object
      description: 'An active insight, as a `plan_limit` refusal from activate names it in `details.active`.'
      required: [timeframe, state]
      properties:
        insight: { type: string, example: ins_61 }
        name: { type: string }
        instrument: { type: string, example: BTC }
        timeframe: { type: string }
        state: { type: string, enum: [live, paused] }
    InsightPreview:
      type: object
      description: The card compiled for one sample event of the run.
      properties:
        card: { type: object, additionalProperties: true }
        sample_event: { type: [object, 'null'], additionalProperties: true, description: The scope values of the event the card was compiled for. }

    # ── library ──
    LibraryScript:
      type: object
      description: A script as the library describes it. Never carries source.
      properties:
        ref:
          $ref: '#/components/schemas/ScriptRef'
          description: Bare slug for the caller's own, `chartnaut/slug` for built-ins, `author/slug` for others. Usable as `script` in `POST /runs`.
        kind: { $ref: '#/components/schemas/ScriptKind' }
        slug: { type: string }
        name: { type: string }
        description: { type: string, description: 'Plain text; a rich-text description is converted. `""` when empty.' }
        author: { type: string, description: 'The author''s username in lowercase, or `chartnaut` for built-ins.' }
        official: { type: boolean, description: True for Chartnaut's built-ins. }
        owned: { type: boolean, description: True when the caller wrote it. }
        installed: { type: boolean, description: True when it is someone else's script the caller added to their library. }
        visibility: { type: string, enum: [private, unlisted, public], description: Built-ins are `public`. }
        latest_version: { type: integer, description: '`0` when no version has been saved.' }
        adoptions: { type: [integer, 'null'], description: 'Install count. `null` for studies.' }
        tags: { type: array, items: { type: string } }
        category: { type: string }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        app_url: { type: string, format: uri }
        interface:
          $ref: '#/components/schemas/ScriptInterface'
          description: On `GET /library` only with `include=interface`.
      required: [ref, kind, slug, name, description, author, official, owned, installed, visibility, latest_version, adoptions, tags, category, created_at, updated_at, app_url]
    LibraryScriptDetail:
      allOf:
        - $ref: '#/components/schemas/LibraryScript'
        - type: object
          required: [interface, version, dependencies]
          properties:
            version: { type: integer, description: 'The version this response describes. `0` when none has been saved.' }
            dependencies:
              type: array
              items: { $ref: '#/components/schemas/PinnedDependency' }

    LibraryItemStatus:
      type: string
      enum: [installable, installed, owned, builtin, unavailable, not_installable]
      description: |
        `installable`: adding the root adds it. `installed`: already in your library. `owned`: yours.
        `builtin`: Chartnaut's. `unavailable`: not shared with you. `not_installable`: a study root.
    LibraryItem:
      type: object
      required: [ref, kind, name, status]
      properties:
        ref: { type: string, example: bob/session-vwap }
        kind: { $ref: '#/components/schemas/ScriptKind' }
        name: { type: string }
        author: { type: string, description: 'Lowercase username, or `chartnaut`. Omitted on a requirements root.' }
        status: { $ref: '#/components/schemas/LibraryItemStatus' }
    LibraryCannotAdd:
      type: object
      required: [kind, name]
      description: A dependency not shared with the caller. Only its kind and name, never its author.
      properties:
        kind: { type: string }
        name: { type: string }
    LibraryRequirements:
      type: object
      required: [root, needs, cannot_add, truncated, confirm, message]
      properties:
        root: { $ref: '#/components/schemas/LibraryItem' }
        needs:
          type: array
          description: Every dependency the caller can have, at its status. Only `installable` ones are added.
          items: { $ref: '#/components/schemas/LibraryItem' }
        cannot_add:
          type: array
          description: Dependencies not shared with the caller. Any one refuses the add.
          items: { $ref: '#/components/schemas/LibraryCannotAdd' }
        truncated: { type: boolean, description: The walk stopped at 200 scripts; `needs` is a prefix. }
        confirm:
          type: array
          description: The refs to send as `confirm` to `addToLibrary`.
          items: { type: string }
        message: { type: string, description: 'The app''s wording for the situation, to show the person.' }
    LibraryAddRequest:
      type: object
      properties:
        confirm:
          type: array
          description: The refs the person agreed to add. Must include every ref in the requirements' `confirm`. `@N` is dropped.
          items: { type: string }
          example: [bob/session-vwap]
    LibraryAddResult:
      type: object
      required: [added, root, added_with, skipped]
      properties:
        added: { type: boolean, description: True when this call added it. }
        root: { $ref: '#/components/schemas/LibraryItem' }
        added_with:
          type: array
          description: Refs added along with it.
          items: { type: string }
        skipped:
          type: array
          description: '`confirm` entries not added, with `not_a_dependency` or the status that made them unnecessary.'
          items:
            type: object
            properties:
              ref: { type: string }
              reason: { type: string }
        reason: { type: string, description: 'Only when `added` is false: why nothing changed.' }

    # ── catalog ──
    InstrumentCategory:
      type: string
      description: The instrument's market category, such as `crypto`, `fx`, `index` or `commodities`.
      example: crypto
    Instrument:
      type: object
      properties:
        symbol: { type: string, example: 'HYPERLIQUID:BTC' }
        short: { type: string, example: 'NAS100', description: 'The name to show and to pass. Every place that takes an instrument accepts it, and also `symbol` and any of `aliases`.' }
        aliases:
          type: array
          items: { type: string }
          example: ['XYZ100', 'US100']
          description: Other names that resolve to exactly this instrument. Each names one instrument only.
        name: { type: string, example: Bitcoin }
        category: { $ref: '#/components/schemas/InstrumentCategory' }
        tick_size: { type: number }
        contract_multiplier: { type: number }
        order_flow: { type: boolean, description: 'Volume-tape scripts (footprint, delta) can run on it.' }
        coverage:
          type: object
          description: The range your plan can run on.
          properties:
            start: { type: string, format: date-time }
            end: { type: string, format: date-time }
        sessions: { type: object, additionalProperties: true }

    # ── account ──
    Me:
      type: object
      properties:
        user: { type: string, description: Display name. }
        plan: { type: string, enum: [free, starter, pro, ultra], description: "`free` or `pro`. `starter` and `ultra` are retired plans, reported only for accounts still on one." }
        token:
          type: object
          properties:
            name: { type: string }
            scopes:
              type: array
              items: { type: string }
            expires_at:
              type: [string, 'null']
              format: date-time
              description: When the key stops working. `null` only for a key made in the app with Never. CLI sign-in keys last 7, 30 or 90 days.
    Usage:
      type: object
      properties:
        plan: { type: string, enum: [free, starter, pro, ultra], description: "The account's plan: `free` or `pro`. `starter` and `ultra` are retired plans, reported only for accounts still on one." }
        period:
          type: object
          properties:
            start: { type: string, format: date-time }
            end: { type: string, format: date-time }
        compute_units:
          type: object
          description: 1 unit = 1,000 bars evaluated, dependencies included. Pricing is not set; included is null.
          properties:
            used: { type: number }
            included: { type: [number, 'null'] }
        caps:
          type: object
          description: >-
            Each plan cap with its current count. `limit` null means unlimited. Limits already
            include the account's add-ons (Pro): `events_250k`, `studies_100`, `definitions_25`
            raise their cap, `compute_concurrency` raises `concurrent_runs`.
          additionalProperties:
            type: object
            properties:
              used: { type: integer }
              limit: { type: [integer, 'null'] }
          example:
            indicators: { used: 4, limit: null }
            definitions: { used: 12, limit: 50 }
            studies: { used: 31, limit: 1000 }
            events: { used: 18220, limit: 150000 }
            concurrent_runs: { used: 1, limit: 3 }
        history_start: { type: string, format: date-time }
        memory_bars: { type: integer }
        addons:
          description: >-
            The add-ons the account holds on Pro, with their quantities (empty on Free). `caps` and
            `api_limits` already count them.
          type: array
          items:
            type: object
            properties:
              key:
                type: string
                enum: [metatrader_account, login_broker_account, events_250k, studies_100, definitions_25, compute_concurrency, alerts_5, multistream_100h, private_seats_250]
              quantity: { type: integer, minimum: 1, maximum: 99 }
          example: [{ key: events_250k, quantity: 2 }]
        api_limits:
          description: >-
            Per account, shared by all of its keys, set by plan (each `compute_concurrency`
            add-on adds 1 to concurrent_heavy). Past requests_per_minute
            (429 rate_limited) or concurrent_heavy (validate, save, collect, run start; 429 busy).
            Past concurrent_waits a `wait` poll answers at once instead of holding.
          type: object
          properties:
            requests_per_minute: { type: integer }
            concurrent_heavy: { type: integer }
            concurrent_waits: { type: integer }
          example: { requests_per_minute: 300, concurrent_heavy: 3, concurrent_waits: 6 }
    WebhookEvent:
      type: string
      enum: [run.succeeded, run.failed, run.cancelled]
    Webhook:
      type: object
      properties:
        id: { type: string }
        url: { type: string, format: uri }
        events:
          type: array
          items: { $ref: '#/components/schemas/WebhookEvent' }
        created_at: { type: string, format: date-time }

    # ── errors ──
    Project:
      type: object
      description: A developer project, the Chartnaut side of an app that embeds the terminal (keys, sites, webhooks, profile, permissions).
      properties:
        slug: { type: string, example: acme-desk-k3p9 }
        name: { type: string, example: Acme Desk }
        role: { type: string, enum: [owner, admin, developer, billing, viewer] }
        created_at: { type: string, format: date-time }
        frame_url: { type: string, format: uri }
        readiness: { type: object, additionalProperties: true, description: What Live still needs. }
        test_sites: { type: array, items: { type: string } }
        command: { type: string, example: chartnaut init --app acme-desk-k3p9 }
        env_key: { type: string, example: CHARTNAUT_SECRET_KEY }
        manage_url: { type: string, format: uri, example: 'https://terminal.chartnaut.com/morpheus/developers/projects/acme-desk-k3p9' }
        test_view_as: { type: string }
    ProjectKeyCreated:
      type: object
      properties:
        key: { type: object, properties: { id: { type: string }, env: { type: string, enum: [test, live] }, name: { type: string } } }
        secret: { type: string, description: Shown once. Store it as CHARTNAUT_SECRET_KEY. }
    ProjectStep:
      type: object
      properties:
        key: { type: string }
        label: { type: string }
        done: { type: boolean }
        at: { type: string, format: date-time }
        hint: { type: string }
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              description: Stable. Branch on this, never on `message`.
              enum:
                - unauthorized
                - forbidden_scope
                - plan_limit
                - not_found
                - version_conflict
                - script_invalid
                - in_use
                - out_of_coverage
                - unknown_instrument
                - ambiguous_instrument
                - unsupported_timeframe
                - run_not_finished
                - rate_limited
                - busy
                - invalid_request
                - forbidden
                - conflict
                - not_in_library
                - confirmation_required
                - not_shared
                - not_installable
                - not_implemented
                - authorization_pending
                - slow_down
                - access_denied
                - expired_token
                - internal
            message: { type: string }
            details: { type: object, additionalProperties: true }
            docs_url: { type: string, format: uri }
            request_id: { type: string }
