openapi: 3.0.3
info:
  title: Tereno — verifiable evidence for autonomous agents on Base
  version: 6.0.0
  description: |
    Verifiable evidence for autonomous agents. Tereno answers six questions and no
    others, each one paid per call with x402 in USDC on Base and each one returning
    the evidence behind the answer, the point it stops being valid, and a receipt.
    Onchain evidence: token.launch.guard simulates DEX exit execution and verifies LP reserves;
    token.holders.guard audits top 10 holders concentration and cabal funding clusters;
    token.metadata reads a Base token's name, symbol, decimals and total supply;
    chain.snapshot returns the latest block, timestamp, base fee and suggested gas fees;
    contract.guard returns a bounded verdict over executable code, proxy signals and pause state.
    External evidence: prediction.evidence returns current sourced claims supporting
    or contradicting a prediction-market proposition, each with its source.
    Deterministic answers are computed once and reused: a later agent asking the same
    question inside the validity window is served the stored answer at a lower price,
    and the wallet that produced it earns a bounded, non-transferable credit. Agents
    can also publish deterministic work they computed themselves; publications are
    audited by recomputation before they can be reused. Unmet demand is exposed as
    open bounties.
    Capabilities Tereno has retired answer 410 with error capability_retired and
    cannot be bought; their historical receipts and artifacts remain readable.
    Prices shown below are indicative defaults; the authoritative price for any call is
    the one returned by GET /api/v1/quotes or the live x402 402 Payment Required challenge,
    since operators can retune prices by environment without a spec change.
  contact:
    name: Tereno
    email: ops@tereno.xyz
    url: https://www.tereno.xyz
  x-guidance: |
    Ask, verify, pay, reuse. Before acting, buy exactly the evidence the next action
    needs; every response is a decision contract with a verdict, the evidence behind
    it, explicit limitations, a validity window and a receipt. Start at GET
    /api/v1/capabilities for the live catalog and prices, then GET /api/v1/quotes for
    a wallet-bound quote, then call the invoke route and pay the x402 402 challenge.
    When verified work already exists, reusing it costs less than recomputing it, and
    the wallet that produced it earns a bounded credit. Quotes and the live 402
    challenge are authoritative over the prices here.
servers:
  - url: https://www.tereno.xyz
    description: Production
  - url: http://localhost:3000
    description: Local development
# Signed agent actions, published in full because a route nobody can call is
# indistinguishable from a route nobody wants. The free-but-signed routes have
# always required an EIP-712 signature, and the recipe for building one lived
# only in the server. Every zero recorded on them was therefore ambiguous: no
# demand, or no way in. This removes the second reading.
#
# The operation-level description limit does not apply here, so this is the one
# place the whole construction fits without being cut down to a hint.
x-agent-auth:
  summary: >-
    Free-but-signed routes authenticate with an EIP-712 typed-data signature
    over the action being taken, carried in four headers. No account, API key or
    registration exists; the wallet is the identity.
  headers:
    x-agent-wallet: The signing EVM address. Must equal the `wallet` in the body.
    x-agent-signature: The EIP-712 signature over the AgentAction message below.
    x-agent-timestamp: Unix milliseconds. Rejected outside a 5 minute window either side of server time.
    x-agent-nonce: Client-chosen, `^[a-zA-Z0-9_-]{8,128}$`, single-use for 10 minutes per wallet and action.
  domain:
    name: Tereno Agent API
    version: "1"
    chainId: 8453
    salt: "0x262c271b0d3c3d20c1aaa16174a0bd29f50e4d90bbe06804d086c23dc3ad9605"
    saltDerivation: >-
      keccak256(toHex(audience)) where audience is this origin without a
      trailing slash, i.e. keccak256(toHex("https://www.tereno.xyz")). The
      literal above is the production value; recompute it for any other server
      listed in this document.
  types:
    AgentAction:
      - { name: action, type: string }
      - { name: resource, type: string }
      - { name: timestamp, type: uint256 }
      - { name: nonce, type: string }
  primaryType: AgentAction
  actions:
    artifact_publish:
      endpoint: POST /api/v1/artifacts/publish
      resource: >-
        `JSON.stringify({address, registerIfMissing, bytecodeHash,
        bytecodeBytes, computedAtBlock, agentId})` with the keys in exactly that
        order, address lowercased, and agentId null when absent. The string
        binds the signature to the observation being published, so a signature
        captured for one reading cannot be replayed for another.
      keyOrderWarning: >-
        The server rebuilds this string with JSON.stringify over a literal in
        the stated order, so a different key order produces a different hash and
        a 401. The values must also be byte-identical to the ones in the request
        body.
    capability_quote:
      endpoint: GET /api/v1/quotes
      optional: >-
        Signing is not required to be quoted. It is what lets a quote apply the
        credits a wallet has earned, so an unsigned quote is simply the list
        price.
      resource: >-
        `JSON.stringify({capabilityId, inputHash, wallet})`, with the keys in
        exactly that order and the values the server returns for that quote.
    demand_pledge:
      endpoint: POST /api/v1/demand-pledges
      resource: The normalized capability id being pledged for.
paths:
  /api/v1/capabilities:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: List capability contracts, status, pricing and endpoints
      description: |
        Authoritative pricing. The prices declared per operation in this spec are indicative and are
        checked against this catalog on every build; the live 402 challenge remains the final word.
        The response also carries a `proposed` section: capabilities Tereno has declared but not built,
        with no price and no endpoint, which are free to name at POST /api/v1/demand-pledges. That is
        how Tereno decides what to build next, so a name that is absent from both sections is worth
        pledging rather than assuming.
      responses:
        "200":
          description: Capability catalog, including the `proposed` section of unbuilt capabilities
  /api/v1/capabilities/stats:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Public 30-day capability metrics
      description: |
        Aggregated, anonymized network metrics for the last 30 days: settled invocations,
        unique paying agents, retention (including the full-price second-day repeat rate),
        cache reuse, reuse-dividend credits and reliability percentiles. Simulated and
        excluded traffic is filtered out. Rate limited; cached for 30 seconds.
      responses:
        "200":
          description: Capability metrics window
        "429":
          description: Rate limit exceeded
  /api/v1/quotes:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Create a short-lived, wallet-bound capability quote
      parameters:
        - { name: capability, in: query, required: true, schema: { type: string, enum: [token.metadata, chain.snapshot, contract.guard, prediction.evidence] } }
        - { name: wallet, in: query, required: true, schema: { type: string } }
        - { name: address, in: query, required: false, schema: { type: string }, description: Required for token.metadata and contract.guard }
        - { name: question, in: query, required: false, schema: { type: string }, description: Required for prediction.evidence }
        - { name: market, in: query, required: false, schema: { type: string }, description: Optional venue for prediction.evidence; defaults to polymarket }
        - { name: marketUrl, in: query, required: false, schema: { type: string }, description: Optional market URL for prediction.evidence }
      responses:
        "200":
          description: Single-use quote with invokeUrl, invokeMethod and invokeBody
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Quote" }
  /api/v1/capabilities/contract.guard/invoke:
    get:
      summary: Paid reusable Base contract preflight
      description: |
        Combines a long-lived bytecode fingerprint with fresh EIP-1967 implementation and paused() checks. Eligible cross-wallet reuse returns a bounded credit dividend to the seeder.
        This is a bounded preflight, not a security audit.
      parameters:
        - { name: address, in: query, required: true, schema: { type: string } }
        - { name: quote, in: query, required: false, schema: { type: string } }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.03" }
        protocols:
          - { x402: {} }

      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
  /api/v1/capabilities/token.metadata/invoke:
    get:
      summary: Paid cache-shared Base token metadata read — $0.01–$0.03 USDC indicative (see /api/v1/quotes)
      description: |
        Reads a token's name, symbol, decimals and totalSupply (with bytes32-label
        fallback) in one typed call. Metadata is self-reported by the contract and
        can imitate other tokens; the response links contract.guard for a safety verdict.
      parameters:
        - { name: address, in: query, required: true, schema: { type: string } }
        - { name: quote, in: query, required: false, schema: { type: string } }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.03" }
        protocols:
          - { x402: {} }

      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
  /api/v1/capabilities/chain.snapshot/invoke:
    get:
      summary: Paid Base chain snapshot (latest block, timestamp, gas fees) — $0.01–$0.02 USDC indicative
      description: |
        No parameters. Latest block number, timestamp, base fee and suggested
        EIP-1559 fees, shared as a single global artifact within a short TTL.
        The fastest way to exercise an x402 payment loop end to end.
      parameters:
        - { name: quote, in: query, required: false, schema: { type: string } }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.02" }
        protocols:
          - { x402: {} }

      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
  /api/v1/capabilities/token.launch.guard/invoke:
    get:
      summary: Paid reusable DEX exit simulation and launch guard
      description: |
        Simulates sell/exit of a funded balance against a freshly launched Base token
        via eth_call, verifies DEX LP reserves and burn/lock status, checks holder
        concentration and cabal clusters, and inspects owner powers (mint, blacklist, fee traps).
      parameters:
        - { name: address, in: query, required: true, schema: { type: string } }
        - { name: quote, in: query, required: false, schema: { type: string } }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.02", max: "0.07" }
        protocols:
          - { x402: {} }
      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
  /api/v1/capabilities/token.holders.guard/invoke:
    get:
      summary: Paid Base ERC-20 holder concentration and cabal cluster preflight
      description: |
        Audits top 10 holders concentration (excluding LP and burn addresses) and traces
        ETH funding origins to identify cabal clusters funded by the same deployer or funder.
        Returns a bounded allow/review/block verdict with cluster evidence.
      parameters:
        - { name: address, in: query, required: true, schema: { type: string } }
        - { name: quote, in: query, required: false, schema: { type: string } }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.04" }
        protocols:
          - { x402: {} }
      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
  /api/v1/evidence/{artifactId}:
    get:
      security: []
      summary: Free portable evidence provenance and reproduction reference
      description: |
        Bazaar-independent public read for an artifactId received from another
        agent. It returns origin, declared validity and exact normalized input
        required to reproduce the work; it never returns payer identity or the
        original paid output. An optional opaque installation id is hashed and
        deduplicated per artifact/day as a measurement signal only: it never creates payment or credit.
      parameters:
        - { name: artifactId, in: path, required: true, schema: { type: string, pattern: "^sha256:[a-f0-9]{64}$" } }
        - { name: channel, in: query, required: false, schema: { type: string, maxLength: 64 } }
        - { name: X-Tereno-Evidence-Installation, in: header, required: false, schema: { type: string, minLength: 16, maxLength: 128 }, description: Stable opaque receiver-installation id; never send a wallet or secret. }
      responses:
        "200": { description: Portable evidence reference }
        "403": { description: Artifact is private and cannot be shared }
        "404": { description: Artifact not found }
  /api/v1/artifacts/publish:
    post:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Publish agent-computed work and claim the seeder slot
      description: |
        Phase-A publishing: submit a contract bytecode fingerprint you computed yourself
        (deterministic and verifiable). Publications are audited by recomputation against
        chain state; a mismatch burns the publication and is recorded in your audit history.
        On success you become the fingerprint's seeder and earn the reuse dividend, in
        non-transferable credits, on every settled cross-wallet reuse. Requires EIP-712
        AgentAction headers with action=artifact_publish and resource=address.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [capabilityId, wallet, address, bytecodeHash, bytecodeBytes, computedAtBlock]
              properties:
                capabilityId: { type: string, enum: [contract.guard] }
                wallet: { type: string }
                address: { type: string }
                bytecodeHash: { type: string, nullable: true, description: keccak256 of the bytecode, or null for empty accounts }
                bytecodeBytes: { type: integer, minimum: 0 }
                computedAtBlock: { type: integer, minimum: 0 }
      responses:
        "201": { description: Published; seeder slot claimed }
        "409": { description: A fresh fingerprint already exists }
        "422": { description: Audit failed; publication burned }
  /api/v1/capabilities/prediction.evidence/invoke:
    post:
      summary: Verifiable evidence for or against a prediction-market proposition
      description: |
        Finds current, sourced evidence that supports, contradicts or is neutral
        toward a prediction-market proposition. Each item carries its source,
        source URL, observation time and direction; a claim without provenance is
        not returned as evidence. Content-addressed, with a verifiable receipt.

        It does not price the market, output a probability, or advise or execute
        a trade. Prices here are indicative; the live 402 is authoritative.
      parameters:
        - { name: via, in: query, required: false, schema: { type: string, maxLength: 32 }, description: "Discovery channel marker carried by the listing that referred you (for example, via=circle). Attribution only; it never changes the price or the answer." }
        - { name: PAYMENT-SIGNATURE, in: header, required: false, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [question]
              properties:
                question:
                  type: string
                  minLength: 5
                  maxLength: 2000
                  description: The proposition to audit.
                market:
                  type: string
                  description: "Market platform identifier, for example polymarket, omen or kalshi. Any prediction market is accepted; none is required."
                marketUrl:
                  type: string
                  format: uri
                  description: Optional market page, used to extract resolution rules.
                context:
                  type: object
                  description: Optional contextual metadata from the calling agent.
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.05" }
        protocols:
          - { x402: {} }
      responses:
        "200": { $ref: "#/components/responses/CapabilityResult" }
        "402": { description: x402 payment required }
        "400": { description: Invalid or missing question }
        "409": { description: This payment authorization was already settled; the body carries the receipt of the execution it bought }
  /api/v1/demand-pledges:
    post:
      security: []
      summary: Declare a no-cost future paid intent
      description: Requires an EIP-712 AgentAction signed by the supplied wallet. No credit is paid for this declaration. A bounded non-transferable credit is released only if the same wallet later settles this exact capability. Any capability name is accepted, built or not; the `proposed` section of GET /api/v1/capabilities lists the unbuilt ones Tereno has declared and would build on named demand.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [wallet, capability]
              properties:
                wallet: { type: string, description: Base wallet that must later pay }
                capability: { type: string, description: Normalized 2-64 character capability id }
      responses:
        "201": { description: Pledge recorded }
        "401": { description: Signed AgentAction required for supplied wallet }
        "400": { description: Invalid wallet or capability id }
        "429": { description: Rate limited }
  /api/v1/opportunities:
    get:
      security: []
      summary: Aggregate unknown asks and conditional pledges
      description: Upstream market-signal data only. Wallets and prompts are never exposed.
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
      responses:
        "200": { description: Aggregate opportunities }
  /api/v1/bounties:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Open demand queue for publishers
      description: |
        Fresh cache misses nobody has seeded yet, ranked by demand, with the seeder
        economics (dividend per settled reuse, lifetime cap) for each entry. Each
        bounty states its fulfillment path: publish pre-computed work via
        /api/v1/artifacts/publish (contract.guard fingerprints) or be the first
        settled payer of the input. Either way the seeder earns on reuse.
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
      responses:
        "200": { description: Open bounties }
  /api/v1/publishers/{wallet}:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Publisher track record
      description: |
        Audit history (passed/failed/unaudited publications), settled reuse dividends
        and review credits for a publisher wallet. Reputation is computed from audits
        and settled economics, not self-reported claims.
      parameters:
        - { name: wallet, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: Publisher reputation }
  /api/v1/outcomes:
    post:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Attach signed outcome feedback to an invocation
      description: Requires EIP-712 AgentAction headers with action=capability_outcome and resource=invocationId.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [invocationId, wallet, outcome]
              properties:
                invocationId: { type: string }
                wallet: { type: string }
                outcome: { type: string, enum: [success, failure, avoided, unknown] }
                note: { type: string, maxLength: 500 }
      responses:
        "201":
          description: Outcome accepted; the first outcome on a settled invocation earns a bounded, non-transferable review credit (reviewCreditUsd in the response)
  /api/v1/receipts/{invocationId}:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Read a capability settlement receipt
      parameters:
        - { name: invocationId, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: Invocation and settlement state }
        "404": { description: Invocation not found }
  /api/mcp:
    post:
      summary: Model Context Protocol endpoint (Streamable HTTP, JSON-RPC 2.0)
      description: |
        Exposes the capabilities as MCP tools for agents that discover services through MCP.
        initialize, ping and tools/list are free; tools/call is forwarded to the same invoke
        route an HTTP agent would use, and the x402 challenge is relayed back unchanged, so
        the client signs against the real resource and the retry settles upstream. Same
        prices, same receipts, same ledger as the HTTP surface.
      x-payment-info:
        price: { mode: dynamic, currency: USD, min: "0.01", max: "0.05" }
        protocols:
          - { x402: {} }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [jsonrpc, method]
              properties:
                jsonrpc: { type: string, enum: ["2.0"] }
                id: { type: [string, integer, "null"] }
                method: { type: string, enum: [initialize, ping, tools/list, tools/call] }
                params: { type: object }
            example:
              jsonrpc: "2.0"
              id: 1
              method: tools/call
              params:
                name: chain_snapshot
                arguments: {}
      responses:
        "200": { description: JSON-RPC result }
        "402": { description: x402 payment required for this tool call }
  /api/v1/health:
    get:
      # Free route: no x402 paywall, so discovery probes must skip it.
      security: []
      summary: Runtime readiness for Base, persistence and x402
      responses:
        "200": { description: Ready }
        "503": { description: Missing production dependency }
components:
  responses:
    CapabilityResult:
      description: Decision result; PAYMENT-RESPONSE is attached after successful x402 settlement
      headers:
        PAYMENT-RESPONSE: { schema: { type: string } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/CapabilityResult" }
  schemas:
    Quote:
      type: object
      required: [capabilityId, quoteId, cacheStatus, listPriceUsd, creditAppliedUsd, priceUsd, expiresAt, invokeUrl, invokeMethod]
      properties:
        capabilityId: { type: string }
        quoteId: { type: string }
        cacheStatus: { type: string, enum: [hit, partial, miss] }
        listPriceUsd: { type: number }
        creditAppliedUsd: { type: number }
        priceUsd: { type: number }
        expiresAt: { type: string, format: date-time }
        invokeUrl: { type: string }
        invokeMethod: { type: string, enum: [GET, POST] }
        invokeBody: { type: object, nullable: true, additionalProperties: true }
    CapabilityResult:
      type: object
      required: [capabilityId, invocationId, verdict, result, receiptUrl]
      properties:
        capabilityId: { type: string }
        invocationId: { type: string }
        verdict: { type: string, enum: [allow, review, block] }
        result:
          type: object
          properties:
            reasonCodes: { type: array, items: { type: string } }
            summary: { type: string }
            evidence: { type: object, additionalProperties: true }
            computedAtBlock: { type: integer }
            validUntilBlock: { type: integer }
            limitations: { type: array, items: { type: string } }
        pricing:
          type: object
          properties:
            quotedCacheStatus: { type: string, enum: [hit, partial, miss] }
            actualCacheStatus: { type: string, enum: [hit, partial, miss] }
            listPriceUsd: { type: number }
            creditAppliedUsd: { type: number }
            pricePaidUsd: { type: number }
        receiptUrl: { type: string }
        nextCall:
          description: >-
            The validity boundary of this answer, as structure rather than prose. `recheck` is the request
            that recomputes it, with `notBeforeBlock` set to the first block at which recomputing can differ.
            `watch` names the capability that reports what changed between two observations of the same
            subject, and is null when this capability already is that. Null for answers with no block window.
            Descriptive only: nothing here is required, and the answer is complete for the window it states.
          type: object
          nullable: true
          additionalProperties: true
          properties:
            validUntilBlock: { type: integer }
            validForSeconds: { type: integer, nullable: true }
            recheck:
              type: object
              additionalProperties: true
              properties:
                capabilityId: { type: string }
                method: { type: string, enum: [GET, POST] }
                url: { type: string }
                body: { type: object, nullable: true, additionalProperties: true }
                notBeforeBlock: { type: integer }
                listPriceUsdCeiling: { type: number }
                payment: { type: string, enum: [x402] }
            watch:
              type: object
              nullable: true
              additionalProperties: true
        evidenceReference:
          description: Portable provenance/reproduction pointer. Present on every capability response; private artifacts explicitly state shareable=false.
          type: object
          additionalProperties: true
