docs/API.md

REST HTTP API Reference

Version 0.6.0 wire schemas for /api/v1/chat/completions, /api/generate SSE, /api/compile, /api/patch, /api/models, and 48 targets. Looking for JS/TS SDK functions? See SDK Reference.

This document specifies the HTTP endpoints, authentication headers, request/response JSON schemas, SSE wire contracts, error codes, and the 48 supported compilation targets exposed by Leveonas Server (https://leveonas.ainot.site or self-hosted npx leveonas serve).

For the TypeScript/JavaScript package functions (compile, parse, lower, inspect, createSession, DOMPatchApplier), see the SDK Reference.


Authentication

All POST endpoints require a valid Leveonas API key (lv_live_...) generated in Dashboard → API Keys (or via npx leveonas key create). Pass it in either header:

http
Authorization: Bearer lv_live_your_leveonas_api_key
# or
X-Leveonas-Key: lv_live_your_leveonas_api_key
EndpointLeveonas Key ScopeUpstream LLM Key Needed?
POST /api/v1/chat/completionswrite:streamYes (x-user-llm-key, x-<provider>-key, env, or Dashboard Vault)
POST /api/generatewrite:streamYes (x-user-llm-key, x-<provider>-key, env, or Dashboard Vault)
POST /api/compileread:compileNo (Deterministic compiler only)
POST /api/patchread:compileNo (Deterministic diff/patch engine only)
POST /api/validate & /api/verifyread:compileNo (Deterministic linter & security auditor)
GET /api/modelsOptionalNo (Returns verified model catalog + custom providers if authenticated)

Missing or revoked keys return 401 Unauthorized with { "code": "LM-AUTH-001", "error": "..." }.


Core Parameter Semantics (<BLOCK> vs framework vs target)

To avoid ambiguity across the REST API, CLI, and SDK, Leveonas separates three distinct concepts:

ConceptExampleWhere UsedMeaning
Source block tag<REACT>...</REACT>Inside source string / .lm fileDeclares the LM dialect of that embedded block
framework"react", "vue", "auto"POST /api/compile (framework), SDK compile(), CLI --frameworkOverrides which language/framework interpreter parses the block
target"code", "ui-ir", "ast", "document"CLI --target, CompileOptions.targetChooses which compiler artifact/representation to output
Compatibility Note: POST /api/compile treats framework as canonical. If a caller passes target to POST /api/compile, the server treats it as a backward-compatible alias for framework.

1. OpenAI-Compatible Proxy (POST /api/v1/chat/completions)

Drop-in OpenAI endpoint for server backends and AI builders (Lovable, Bolt.new, v0, Replit Agent, Cursor). Translates requests to OpenAI, Google Gemini, Anthropic, xAI, Meta Llama, or custom OpenAI-compatible gateways, injects LM directives, and compiles LM blocks (including write_file/edit_file tool calls and <boltAction> tags) back to native code.

Headers

  • Authorization: Bearer lv_live_... *(required)*
  • x-leveonas-provider: "openai" | "gemini" | "anthropic" | "xai" | "meta" (or custom slug)
  • x-user-llm-key or x-<provider>-key *(optional if saved in Dashboard Vault)*
  • x-leveonas-session-id *(optional session correlation ID)*

Request Body

json
{
  "model": "gpt-6.2-sol",
  "provider": "openai",
  "stream": false,
  "compileOutput": true,
  "temperature": 0.2,
  "max_tokens": 4096,
  "messages": [
    { "role": "system", "content": "Return clean, accessible React TypeScript code." },
    { "role": "user", "content": "Build a responsive React pricing card." }
  ]
}
FieldTypeDefaultDescription
modelstring"gpt-4o"Exact upstream model identifier (see GET /api/models)
providerstringAuto-inferredProvider keyword (openai, gemini, anthropic, xai, meta, or custom slug)
messagesMessage[]RequiredStandard OpenAI { role, content } message array (prompt string also accepted)
streambooleantruetrue streams OpenAI chat.completion.chunk SSE ending with data: [DONE]
compileOutputbooleantrueSet false to disable automatic LM-to-native code compilation
tools / tool_choicearray / anyOptionalForwarded & compiled across OpenAI, Anthropic (tool_use), and Gemini (functionDeclarations)
projectContext{ files?: Record<string, string> }OptionalExisting workspace files for stateful <PATCH> / edit_file resolution

Response (stream: false, 200 OK)

json
{
  "id": "chatcmpl_lev_m9k42a_9b1c",
  "object": "chat.completion",
  "created": 1796025600,
  "model": "gpt-6.2-sol",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "import React from 'react';\nexport function PricingCard() { ... }"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 180,
    "completion_tokens": 210,
    "total_tokens": 390
  },
  "leveonas": {
    "sessionId": "lev_sess_m9k42a",
    "workflow": "chat-completions",
    "compiledUnits": 1,
    "lmTokens": 114,
    "compiledTokens": 412,
    "tokensSavedPercentage": 72.3
  }
}

When stream: true, SSE frames emit standard OpenAI chat.completion.chunk payloads followed by data: [DONE].


2. Streaming Patch Pipeline (POST /api/generate)

Streams incremental DOM, CSS, and JS patch batches (PatchOperation[]) over Server-Sent Events as the upstream LLM emits canonical LM.

Request Body

json
{
  "provider": "gemini",
  "model": "gemini-4-carbon",
  "prompt": "Generate a React pricing card with Monthly and Annual billing toggle",
  "maxTokens": 4096,
  "emitDebugText": false,
  "telemetry": true
}

Official SSE Event Lifecycle & Exact JSON Payloads

text
HTTP 200 (text/event-stream)
  ├── 1. Session metadata:   data: {"session":{"id":"lev_sess_...","provider":"gemini","model":"gemini-4-carbon","timestamp":"..."}}
  ├── 2. Incremental patch:  data: {"patch":[PatchOperation, ...]}        (0..N times)
  ├── 3. Raw LM chunk:       data: {"text":"di(cs(p-6) ...)"}            (only if emitDebugText: true)
  ├── 4. Optional error:     data: {"error":"Sanitized error message"}
  ├── 5. Final telemetry:    data: {"telemetry":{"runId":"...","lmTokens":112,"compiledTokens":398,"tokensSavedPercentage":71.9}}
  └── 6. Stream terminator:  data: [DONE]

Exact JSON shape inside each data: {"patch":[...]} frame (PatchOperation[] matching DOMPatchApplier.apply() and validatePatches()):

json
{
  "patch": [
    {
      "operation": "CREATE_NODE",
      "nodeId": "node_1",
      "parentId": "leveonas-root",
      "index": 0,
      "payload": {
        "node": {
          "id": "node_1",
          "kind": "Container",
          "name": "div",
          "properties": [{ "name": "class", "value": "p-6 rounded-xl border" }],
          "children": []
        }
      }
    }
  ]
}
SSE vs SDK Mapping: When using createSession() from leveonas/sdk, the SDK reads these raw SSE lines and yields typed StreamingEvent objects (generation:start → generation:chunk / generation:patch / generation:diagnostic → generation:complete | generation:error), translating the raw data: [DONE] sentinel into generation:complete.

3. Deterministic Compiler (POST /api/compile)

Compiles canonical LM (tag(attr(value) child)) into native code, HTML5 documents, AST, and Common UI IR across all 48 targets with zero LLM token usage.

Request Body

json
{
  "source": "<REACT>\ncomponent(PricingCard)(di(cs(p-6 border rounded-xl) h2(Pro Plan) p($29/mo)))\n</REACT>",
  "framework": "react",
  "documentMode": true,
  "title": "Pricing Preview"
}

Response (200 OK)

json
{
  "success": true,
  "compiledBy": "leveonas-server",
  "version": "0.6.0",
  "detectedTarget": "react",
  "code": "// --- React (TSX) (tsx, mode: compiled) ---\n...",
  "html": "<div class=\"p-6 border rounded-xl\"><h2>Pro Plan</h2><p>$29/mo</p></div>",
  "document": "<!DOCTYPE html>\n<html lang=\"en\">...</html>",
  "sections": [
    { "title": "React (TSX)", "language": "tsx", "blockType": "react", "code": "...", "mode": "compiled" }
  ],
  "ast": { "kind": "ReactProgram", "components": [] },
  "uiIR": { "kind": "UIProgram", "components": [] },
  "diagnostics": [],
  "tokenStats": {
    "lmTokens": 19,
    "compiledTokens": 68,
    "savedTokens": 49,
    "savingsPercent": 72.1,
    "encoding": "o200k_base"
  }
}

Note: Syntax errors such as legacy Lisp (di cs:"x") (LM-DIALECT-001) return HTTP 200 with "success": false and structured entries in diagnostics + error, whereas missing/oversized payloads or auth failures return HTTP 400, 401, or 413.


4. Virtual File Patch Engine (POST /api/patch)

Applies or parses <PATCH file="..."> SEARCH/REPLACE blocks against a virtual in-memory files dictionary.

Request Body

json
{
  "patch": "<PATCH file=\"src/PricingCard.tsx\">\n<<<SEARCH\n<span>$19</span>\n===\n<span>$29</span>\n>>>\n</PATCH>",
  "files": {
    "src/PricingCard.tsx": "export function PricingCard() { return <span>$19</span>; }"
  }
}

Response (200 OK)

json
{
  "success": true,
  "version": "0.6.0",
  "files": {
    "src/PricingCard.tsx": "export function PricingCard() { return <span>$29</span>; }"
  },
  "applied": [{ "file": "src/PricingCard.tsx", "type": "search-replace", "line": 1 }],
  "failed": [],
  "diagnostics": []
}

5. Validation, Verification & Live Model Catalog

  • POST /api/validate: Accepts { source, framework?, streaming? } and returns { valid, version, streamStatus, diagnostics, securityAudit }.
  • POST /api/verify: Validates post-compile framework syntax (TypeScript/JSX, Vue SFC, Svelte, Angular, CSS, JSON, etc.).
  • GET /api/models: Dynamically returns the verified provider catalog (openai, gemini, anthropic, xai, meta), lastVerified timestamp, recommended vs legacy status per model ID, and (when authenticated) your custom providers registered in Dashboard Vault.

6. Supported Targets & Stability Classification (48 Targets)

Leveonas supports 48 LM block tags / compilation targets (SUPPORTED_TARGETS.length === 48):

CategoryCountStabilityTargetsCompilation Path
UI Frameworks5Stablereact, nextjs, vue, svelte, angularAST → Common UI IR → Codegen + DOM/JS Reconciler
Web Core & Styling9Stablehtml, tailwind, css, scss, js, ts, solid, astro, svgDedicated AST interpreters & emitters
Backend & Databases8Stablepython, node, sql, prisma, drizzle, mongo, graphql, rulesDedicated LM interpreters
Config, Infra & Diffs13Stablepatch, json, yaml, toml, env, dockerfile, shell, terraform, protobuf, makefile, xml, markdown, templateStructured emitters & SEARCH/REPLACE patch engine
Mobile & Polyglot13Betareact-native, dart, swift, kotlin, go, rust, java, php, csharp, ruby, cpp, elixir, luaDedicated LM interpreters

7. Standard Error Codes

HTTP StatusCode / FieldMeaning
400LM-DIALECT-001 / LM-REQ-001Invalid JSON, unsupported provider keyword, or deprecated Lisp (tag ...) syntax
401LM-AUTH-001Missing, expired, or revoked lv_live_... Leveonas API key
401missing_provider_api_keyNo upstream model provider key found in request headers, host env, or Vault
404model_not_foundUpstream provider rejected the model string (check GET /api/models for exact casing)
413LM-LIMIT-001Input exceeds 1,048,576 bytes (LEVEONAS_MAX_MESSAGE_BYTES)
502 / 4xxupstream_provider_errorUpstream LLM provider returned an HTTP error