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:
Authorization: Bearer lv_live_your_leveonas_api_key
# or
X-Leveonas-Key: lv_live_your_leveonas_api_key| Endpoint | Leveonas Key Scope | Upstream LLM Key Needed? |
|---|---|---|
POST /api/v1/chat/completions | write:stream | Yes (x-user-llm-key, x-<provider>-key, env, or Dashboard Vault) |
POST /api/generate | write:stream | Yes (x-user-llm-key, x-<provider>-key, env, or Dashboard Vault) |
POST /api/compile | read:compile | No (Deterministic compiler only) |
POST /api/patch | read:compile | No (Deterministic diff/patch engine only) |
POST /api/validate & /api/verify | read:compile | No (Deterministic linter & security auditor) |
GET /api/models | Optional | No (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:
| Concept | Example | Where Used | Meaning |
|---|---|---|---|
| Source block tag | <REACT>...</REACT> | Inside source string / .lm file | Declares the LM dialect of that embedded block |
framework | "react", "vue", "auto" | POST /api/compile (framework), SDK compile(), CLI --framework | Overrides which language/framework interpreter parses the block |
target | "code", "ui-ir", "ast", "document" | CLI --target, CompileOptions.target | Chooses which compiler artifact/representation to output |
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-keyorx-<provider>-key*(optional if saved in Dashboard Vault)*x-leveonas-session-id*(optional session correlation ID)*
Request Body
{
"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." }
]
}| Field | Type | Default | Description |
|---|---|---|---|
model | string | "gpt-4o" | Exact upstream model identifier (see GET /api/models) |
provider | string | Auto-inferred | Provider keyword (openai, gemini, anthropic, xai, meta, or custom slug) |
messages | Message[] | Required | Standard OpenAI { role, content } message array (prompt string also accepted) |
stream | boolean | true | true streams OpenAI chat.completion.chunk SSE ending with data: [DONE] |
compileOutput | boolean | true | Set false to disable automatic LM-to-native code compilation |
tools / tool_choice | array / any | Optional | Forwarded & compiled across OpenAI, Anthropic (tool_use), and Gemini (functionDeclarations) |
projectContext | { files?: Record<string, string> } | Optional | Existing workspace files for stateful <PATCH> / edit_file resolution |
Response (stream: false, 200 OK)
{
"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
{
"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
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()):
{
"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": []
}
}
}
]
}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
{
"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)
{
"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
{
"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)
{
"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),lastVerifiedtimestamp,recommendedvslegacystatus 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):
| Category | Count | Stability | Targets | Compilation Path |
|---|---|---|---|---|
| UI Frameworks | 5 | Stable | react, nextjs, vue, svelte, angular | AST → Common UI IR → Codegen + DOM/JS Reconciler |
| Web Core & Styling | 9 | Stable | html, tailwind, css, scss, js, ts, solid, astro, svg | Dedicated AST interpreters & emitters |
| Backend & Databases | 8 | Stable | python, node, sql, prisma, drizzle, mongo, graphql, rules | Dedicated LM interpreters |
| Config, Infra & Diffs | 13 | Stable | patch, json, yaml, toml, env, dockerfile, shell, terraform, protobuf, makefile, xml, markdown, template | Structured emitters & SEARCH/REPLACE patch engine |
| Mobile & Polyglot | 13 | Beta | react-native, dart, swift, kotlin, go, rust, java, php, csharp, ruby, cpp, elixir, lua | Dedicated LM interpreters |
7. Standard Error Codes
| HTTP Status | Code / Field | Meaning |
|---|---|---|
400 | LM-DIALECT-001 / LM-REQ-001 | Invalid JSON, unsupported provider keyword, or deprecated Lisp (tag ...) syntax |
401 | LM-AUTH-001 | Missing, expired, or revoked lv_live_... Leveonas API key |
401 | missing_provider_api_key | No upstream model provider key found in request headers, host env, or Vault |
404 | model_not_found | Upstream provider rejected the model string (check GET /api/models for exact casing) |
413 | LM-LIMIT-001 | Input exceeds 1,048,576 bytes (LEVEONAS_MAX_MESSAGE_BYTES) |
502 / 4xx | upstream_provider_error | Upstream LLM provider returned an HTTP error |