API Reference
Eluvix provides a unified, production-grade REST API. In addition to being a drop-in replacement for the OpenAI Chat Completions specification, Eluvix exposes programmatic control over dynamic routing configurations, active local hardware discovery, Docker engine containers, canvas topology presets, GPU compute worker serving, and telemetry.
Base URL & Same-Port TLS Auto-Upgrade
Eluvix features same-port dual-protocol demuxing on port 3588:
- HTTPS (Canonical):
https://127.0.0.1:3588/api/v1(Encrypted TLS via localmkcertcertificate) - HTTP on 3588 (NOT upgraded for API traffic):
http://127.0.0.1:3588/api/v1is served directly over plain HTTP by design (apps/nextjs/server.mjs: the same-port HTTP handler serves/api/before the 308 branch). Only browser navigation to port 3588 gets theHTTP/1.1 308upgrade to HTTPS. Never send anAuthorizationBearer token to thehttp://API URL β it will work, unencrypted. API clients must use thehttps://URL above. - HTTP Fallback Port:
http://127.0.0.1:3580/api/v1(Secondary loopback port; same rule β browser navigation is upgraded,/api/*is served directly over HTTP, as documented on the configurator page.)
Authentication: Master Password & Named API Keys
Eluvix supports two authentication mechanisms:
-
Master Admin Password: Pass your master admin password (from
~/.config/eluvix/auth.json) in the standard HTTPAuthorizationheader:Authorization: Bearer <ADMIN_PASSWORD> -
Named API Keys (
keys.json): Eluvix supports user- and role-scoped Named API Keys stored in~/.config/eluvix/keys.json. Each key is tagged with auserId, anorigin(client,harness, orplayground), rate limits, and model access whitelists:{ "keys": [ { "id": "key_dev_alice", "key": "elx_live_a1b2c3d4e5f6g7h8", "name": "Alice Dev Key", "userId": "alice", "origin": "client", "rateLimit": 120, "createdAt": "2026-10-21T00:00:00.000Z" }, { "id": "key_harness_trueforge", "key": "elx_live_harness_trueforge_01", "name": "TrueForge Agent Runner", "userId": "agent_system", "origin": "harness", "rateLimit": 600, "createdAt": "2026-10-21T00:00:00.000Z" } ] }Provide the key in the request header (both OpenAI
Authorization: Bearerand Anthropicx-api-keyheaders are supported across all/api/v1/*routes):Authorization: Bearer elx_live_a1b2c3d4e5f6g7h8 x-api-key: elx_live_a1b2c3d4e5f6g7h8When a Named API Key is used, its
userIdautomatically scopes the Memory & Context Engine (viking://user/{userId}/memories) and stateful/api/v1/responsesrecords, and itsoriginactivates the Loop Guard if tagged asorigin: "harness".
1. Chat Completions
POST /api/v1/chat/completions
Executes an intelligent chat completion through the Switchyard pipeline. Supports both non-streaming JSON responses and Server-Sent Events (SSE) streaming.
Headers
Content-Type: application/json
Authorization: Bearer <ADMIN_PASSWORD_OR_NAMED_KEY>
Optional Context, Silicon & Fabric Policy Headers
X-Eluvix-User: Override user identifier for memory recall (if not using a named key).X-Eluvix-Session: Session identifier for multi-turn conversational memory tracking.X-Eluvix-Hops: Current hop count when chained through agent harnesses (used by Loop Guard).X-Eluvix-Confidential: Per-request confidential silicon policy override (prefer-tee,require-tee,require-dual-attestation).X-Eluvix-Quantization: Per-request quantization policy override (prefer-nvfp4-hadamard,lossless-reasoning).X-Eluvix-Fabric: Per-request Clos fabric policy override (prefer-rail-optimized,require-collision-free-fabric).X-Eluvix-PD-Role: Per-request disaggregation role preference (prefill,decode,disaggregated-conductor).X-Eluvix-Effort: Reasoning effort hint (low,medium,high).
Request Parameters
| Parameter | Type | Required | Default | Description |
| :--- | :--- | :--- | :--- | :--- |
| model | string | Yes | "auto" | Target model name or "auto" to trigger dynamic complexity, code escalation, and multimodal vision routing. |
| messages | array | Yes | β | Array of message objects (role, content). Content can be string or structured multimodal blocks (image_url). |
| stream | boolean | No | false | When true, streams completion tokens as standard SSE data: {...}\n\n chunks. |
| temperature | number | No | 0.7 | Sampling temperature between 0.0 and 2.0. |
| max_tokens | number | No | β | Maximum token limit for generated output. |
Response Headers
X-Eluvix-Upstream: The upstream ID that executed the request (e.g.ollama-local,vllm-dlb-oooddp-moe,openai-cloud).X-Eluvix-Complexity: Numeric complexity score assigned by Switchyard (1β4).X-Eluvix-Cache: ReturnsHITif served from the semantic response cache, orMISSif executed upstream.X-Eluvix-Memory: Active context memory provider (e.g.openviking,graphiti,lightrag,mem0,sqlite, ornone).X-Eluvix-Memory-Tokens: Number of memory context tokens prepended to the prompt.X-Eluvix-Knowledge: Active static knowledge base RAG status (injected,empty,disabled).X-Eluvix-TTFT-Ms: Time to First Token (Prefill latency in milliseconds).X-Eluvix-ITL-Ms: Inter-Token Latency (Decode step duration in milliseconds per token).X-Eluvix-KV-Cache-KB: Estimated KV-cache footprint in kilobytes (GQA-8vsDeepSeek MLA).X-Eluvix-PD-Role: Disaggregated serving role (prefill,decode,disaggregated-conductor,colocated).X-Eluvix-TEE-Posture: Confidential computing posture (ATTESTED_DUAL_ENCLAVE,ATTESTED_CPU_ONLY,PLAINTEXT).X-Eluvix-Quantization-Format: Upstream weight/activation precision (nvfp4,mxfp4,fp8_e4m3,int4_awq,bf16).X-Eluvix-Outlier-Rotation: Active outlier mitigation (quarot_hadamard,spinquant_hadamard,svdquant_hadamard_lora,none).X-Eluvix-Tensor-Core-PTX: Executed Tensor Core instruction (tcgen05.mma.kind::mxf4nvf4,tcgen05.mma.kind::mxf4,wgmma.mma_async).X-Eluvix-Fabric-Topology: Active GPU cluster fabric (rail-dlb-oooddp,rail-srv6-usid,rail-pxn-ecmp,tor-static-ecmp).X-Eluvix-RDMA-Transport: Active RoCEv2 transport mode (rocev2-dlb-oooddp,rocev2-srv6-usid,rocev2-pxn-4qp,rocev2-static-ecmp).X-Eluvix-SRv6-uSID-Carrier: 128-bit SRv6 Micro-SID carrier address (e.g.fcbb:bb00:0202:0104:0040::).X-Eluvix-Cost-USD: Estimated USD cost recorded in SQLite telemetry for the request.X-Eluvix-Rolling-24h-Spend-USD: Rolling 24-hour cumulative cloud spend in USD whenmaxDailySpendUsdis active.X-Eluvix-Budget-Fallback: Set tolocal-sovereignwhen Switchyard soft-fails over to\$0local hardware due to the 24-hour spend ceiling.X-Eluvix-Model-Alias: Emitted when Switchyard translates a vendor-pinned model string (e.g.claude-3-5-haiku-20241022βsimple,claude-3-7-sonnet-20250219βheavy,o3-miniβfrontier) into a sovereign capability tier unlessstrictModelMatch: true.X-Eluvix-Cascade: Speculative cascade decision (draft-acceptedorverifier-escalated) whenspeculativeCascadeis enabled.X-Eluvix-Cascade-Confidence: Measured speculative draft confidence score (0.00β1.00).X-Eluvix-Embedding-Dimensions: Vector dimensionality returned by/api/v1/embeddingsafter Matryoshka L2-normalized truncation/padding.X-Eluvix-Cache-Read-Tokens: Prompt cache read input tokens (discounted bycacheReadMultiplier, default 90% discount).X-Eluvix-Cache-Write-Tokens: Prompt cache creation/write input tokens on Anthropiccache_controlor prefix-cached upstreams.X-Eluvix-Schema-Validation: Structured Output JSON Schema validation outcome (passed,repaired,escalated, orfailed).X-Eluvix-Output-Guard: Output Guardrail & streaming SSE DLP inspection result (clean,redacted, orblocked).X-Eluvix-Output-Redactions: Number of secrets, PII tokens, or policy regex matches redacted from the model response.X-Eluvix-Trace-Id: 128-bit OpenTelemetry trace ID exported via OTLP/HTTP JSON (gen_ai.*&eluvix.*semantic conventions) or Langfuse.X-Eluvix-Engine-Load: Live local engine load telemetry (engine,waiting,running,kv,warm,delta).X-Eluvix-Rerank-Model: Model identifier that scored a/api/v1/rerankrequest.X-Eluvix-Prompt: Resolved versioned Prompt Registry template (<id>@v<version>) whenX-Eluvix-Promptormetadata.promptRefis supplied.X-Eluvix-Audit-Chain-Valid: Cryptographic SHA-256 hash-chain verification status (true/false) onGET /api/v1/audit?verify=1.X-Eluvix-Hops: Incremented hop count returned to the caller.
Request Example (cURL)
curl -k -X POST https://127.0.0.1:3588/api/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(jq -r .adminPassword ~/.config/eluvix/auth.json)" \
-d '{
"model": "auto",
"messages": [
{ "role": "system", "content": "You are a coding assistant." },
{ "role": "user", "content": "Write a fast matrix multiplication function in C++." }
],
"temperature": 0.2
}'
1b. Universal Wire-Protocol Gateway (/v1/messages, /v1/responses, /v1/embeddings)
Eluvix speaks the native wire protocols of Claude Code, Anthropic SDKs, OpenAI Codex CLI, and RAG/vector pipelines directlyβapplying PrivacyGuard, SemanticGuard, Switchyard complexity routing, and \$0.00 sovereign tier aliasing across every endpoint.
POST /api/v1/messages (Anthropic Messages Wire Protocol)
Drop-in ANTHROPIC_BASE_URL=https://127.0.0.1:3588/api endpoint supporting x-api-key and Authorization: Bearer headers, top-level system blocks, thinking (budget_tokens β <think> conversion), tool_use / tool_result blocks, image (base64 / URL) vision blocks, and spec-compliant SSE streaming (message_start, content_block_start, content_block_delta with thinking_delta / text_delta / input_json_delta, message_delta, message_stop).
POST /api/v1/responses, GET /api/v1/responses/:id, DELETE /api/v1/responses/:id (OpenAI Stateful Responses API)
Stateful multi-turn orchestration endpoint for Codex CLI and OpenAI Agents SDK:
- Chains multi-turn server-side conversation state via
previous_response_idpersisted in SQLiteresponse_store(strictly scoped byuserId). - Honors
store: falsefor zero-retention confidential turns (never written toresponse_store). - Streams typed
response.created,response.output_text.delta,response.function_call_arguments.delta, andresponse.completedSSE events.
POST /api/v1/embeddings (Matryoshka Dimension-Pinned Embeddings)
OpenAI-compatible vector embedding endpoint routing to local Ollama (nomic-embed-text, bge-m3), RamaLama, vLLM, or cloud providers:
- Scrubs PII via
PrivacyGuardprior to embedding generation. - Requires the
embeddingsscope β readonly or wrongly-scoped keys get403. - Enforces Matryoshka L2-normalized dimension pinning (
dimensions) so switching between local and cloud embedding models never breaks downstream pgvector, Qdrant, or SQLite vector table schemas.
1c. Headless Sovereign Audio (/v1/audio/transcriptions & /v1/audio/speech)
POST /api/v1/audio/transcriptions
OpenAI Whisper-compatible multipart/form-data Speech-to-Text (STT) endpoint routing file, model, language, and response_format to local Speaches Faster-Whisper (:8005), whisper.cpp, or cloud fallback, applying PrivacyGuard redaction to transcribed text. Requires the audio scope β readonly or wrongly-scoped keys get 403.
POST /api/v1/audio/speech
OpenAI TTS-compatible Text-to-Speech synthesis endpoint routing { model, input, voice, response_format, speed } to local Kokoro-FastAPI (:8880), Piper TTS, or cloud TTS, streaming audio/mpeg, audio/wav, or audio/opus bytes after PrivacyGuard input scrubbing. Requires the audio scope β readonly or wrongly-scoped keys get 403.
2. Chat History & Traces
GET /api/v1/chat/history
Retrieves conversation sessions and persisted chat history recorded by the Trace Playground.
Query Parameters
session_id(optional): When supplied, returns all messages associated with the specified conversation session. When omitted, returns a list of all known unique session IDs.
Response Example
{
"success": true,
"data": [
{
"id": 42,
"session_id": "sess_default_1710000000",
"timestamp": "2026-10-13T10:00:00Z",
"role": "user",
"content": "Explain latency spillover."
}
]
}
3. Upstream Models & Dynamic Discovery
GET /api/v1/models
Returns an OpenAI-compatible list of all models currently registered across active upstreams, including capability tags (text, code, vision).
GET /api/v1/detect-models
Actively probes local network interfaces (Ollama on 11434, vLLM on 8000, Lemonade on 13305) and CLI agents. Returns newly discovered engines and automatically populates candidate models in the Routing Editor.
4. Observability & Telemetry
GET /api/v1/analytics
Returns aggregate summary statistics: total request volume, average latency per upstream, error rates, and local $0 cost savings.
GET / POST / DELETE /api/v1/observability
GET: Returns detailed real-time telemetry including live request feeds, SLA breaches, upstream node health check results, activePaperclipruns, and long-horizondailyRollupsaggregated in SQLitetelemetry_daily_rollups.POST: Executes operational maintenance tasks ({"action": "ping"}synthetic completion or{"action": "purge"}full raw-log reset).DELETE ?olderThanDays=<days>(Admin required): Prunes expired rows fromrequest_logsandpaperclip_assignment_outcomesolder than<days>while keepingtelemetry_daily_rollupsand the SHA-256audit_eventshash chain intact.
GET /api/v1/metrics
Returns Prometheus 0.0.4 text exposition metrics (text/plain; version=0.0.4; charset=utf-8), including request counters, token counters, TTFT/ITL gauges, rolling 24-hour cloud spend (eluvix_rolling_24h_spend_usd), daily spend cap (eluvix_daily_spend_cap_usd), and circuit breaker states. Supports Authorization: Bearer elx_... Named API Keys. Aggregates and rolling spend are scoped to the caller's userId; only admin callers see global aggregates.
POST /api/v1/route-explain
Executes a non-destructive Switchyard dry-run trace and returns modality classification, complexity tier, intra-heartbeat trajectory step tier (agentStepTier), Paperclip org routing bias & per-key ceiling enforcement, budget guardrail evaluation, candidate scores, and the winning upstream without invoking any model. Supports Paperclip context headers (X-Paperclip-* with HMAC verification) and optional body paperclip simulator fields.
4b. ComfyUI Media Synthesis & Status
POST /api/v1/images/generations
OpenAI-compatible local image, video, and 3D mesh generation endpoint backed by ComfyUI (:8188). Supports model workflow presets (flux-txt2img, sdxl-txt2img, wan21-txt2vid, hunyuan3d-mesh), prompt, negative_prompt, size (e.g. "1024x1024"), seed, and response_format ("url" or "b64_json"). Requires the images scope β readonly or wrongly-scoped keys get 403.
GET /api/v1/images/view
SSRF-guarded HTTPS media proxy that streams generated PNG, WEBP, MP4, or GLB files from the configured ComfyUI /view endpoint without mixed-content warnings.
GET /api/v1/comfyui/status
Probes the active ComfyUI server (:8188/system_stats and /queue) and returns GPU device name, free/total VRAM in GiB, and running/pending queue counts.
5. Dataset Fine-Tuning & SFT/DPO Distillation Export
GET /api/v1/export
Exports curated training datasets in JSONL format ready for direct ingestion into Unsloth, Axolotl, TRL, or LLaMA-Factory:
?format=chat(default): Exports multi-turn conversations fromchat_historyin OpenAI Fine-Tuning format.?format=sft&minScore=0.8: Exports high-confidence teacher completions from SQLitedistillation_pairs(with PII scrubbed viaPrivacyGuardprior to storage).?format=dpo&minScore=0.8: Exports Direct Preference Optimization ({ prompt, chosen, rejected }) triples pairing frontier teacher or Arena-voted winners (chosen) against#shadow-studentor Arena-rejected completions (rejected).
curl -k "https://127.0.0.1:3588/api/v1/export?format=dpo&minScore=0.8" \
-H "Authorization: Bearer <ADMIN_PASSWORD>" \
-o dpo_preferences.jsonl
POST /api/v1/distillation/vote
Records human preference votes from Playground 2.0 A/B Arena ({ prompt, chosen, rejected, teacherModel, studentModel }), scrubbing PII through PrivacyGuard before writing a score: 1.0 preference pair to distillation_pairs.
5b. Sovereign MCP Server & Golden Eval Suites
GET / POST /api/v1/mcp
Native Model Context Protocol (2025-06-18) Streamable-HTTP JSON-RPC 2.0 endpoint (mirrored over stdio via npx eluvix-mcp). Exposes 7 sovereign tools (eluvix_route_explain, eluvix_list_models, eluvix_smart_complete, eluvix_memory_query, eluvix_memory_store, eluvix_privacy_scrub, eluvix_generate_image) and eluvix:// resources while enforcing x-eluvix-hops loop protection (>= 2 rejected). POST requires the mcp scope and refuses readonly keys.
POST /api/v1/evals/run
Executes Golden Routing & Security Regression Eval Suites (including the built-in paperclip-org-governance suite; mode: "dry-run" for \$0.00 deterministic routing/DLP/injection/Paperclip bias & expectedStepTier assertions, or mode: "live" for full upstream regex/judge verification; readonly keys are restricted to dry-run and configOverride upstreams are validated via ssrf-guard). Invalid configOverride values are rejected with 400 in both live and dry-run modes. Also runnable in CI/CD via npx eluvix-eval run evals.json.
6. Dynamic Router Configuration
GET /api/v1/config
Retrieves the active @eluvix/router-core configuration JSON (upstreams, routing strategies, latency thresholds, security guard settings). Admins see the raw config; everyone else gets upstream/memory API keys as configured flags and observability secrets (Langfuse secret key, Authorization headers) as *Configured flags.
POST /api/v1/config
Updates and immediately hot-reloads the active router configuration without service restart. Validates upstream definitions and threshold numbers before saving. Default requests merge partial JSON payloads over the live config (preserving omitted egressPolicy / memory sections); pass ?authoritative=1 (or X-Eluvix-Authoritative-Apply: 1, used by the Eluvix Visual Node Routing Editor after diff confirmation) for an authoritative full-graph replace that removes deleted optional modules while still preserving an omitted egressPolicy. Persistence failures throw instead of being swallowed, so memory and disk cannot silently diverge.
POST /api/orchestrator/deploy
Deploys compiled routing topologies across all four orchestration tiers (local, docker, compose, k3d; read-only callers receive 403). Validates upstreams before mutating state, writes secret-redacted container runtime bundles (eluvix.json, bifrost.yaml, routing.json, gateway.json) mounted read-only at /config for Docker/Compose services, auto-starts or provisions k3d clusters with :latest local images and ConfigMap rollout checksums, and reloads the active Next.js router. Bifrost upstream keys are emitted as ${ELUVIX_UPSTREAM_API_KEY_<NODE_ID>} environment references (never raw values) and bifrost.yaml is written 0600; OpenCode is provisioned with a scoped configurator:opencode key (reused when still valid, otherwise freshly minted) instead of the master admin password.
7. Client Configurator Apply
POST /api/v1/configurator/apply
Applies Eluvix model definitions directly into local developer tooling configurations:
Request Body
{
"client": "opencode",
"protocol": "https",
"selectedModels": ["llama3:8b", "qwen2.5-coder:7b"]
}
Supported client targets: "opencode", "continue". Safely creates automatic timestamped configuration backups before applying changes.
8. Docker Container Lifecycle
Eluvix provides container control endpoints to orchestrate local backend runtimes:
GET /api/v1/docker/status: Returns container running state, CPU, and memory stats.POST /api/v1/docker/up: Spins up specified Compose services ({"services": ["vllm", "agent-router"]}).POST /api/v1/docker/down: Gracefully halts containers to free up GPU VRAM.GET /api/v1/docker/logs?service=vllm: Streams recent stdout/stderr container logs.
9. Canvas Layouts Management
Enables programmatic CRUD for visual routing graph topologies (lib/layouts):
| Endpoint | Method | Description |
| :--- | :--- | :--- |
| /api/v1/layouts | GET | Lists all saved layouts and the active slug (no longer returns the layouts directory path). Caller identity is enforced (401 unauthenticated). |
| /api/v1/layouts | POST | Saves a new layout topology (slug, name, nodes, edges, viewport). Caller identity is enforced (401 unauthenticated, 403 readonly mutations); imports validate node types against the shared KNOWN_NODE_TYPES registry and node data (cliPath must be a bare or absolute agy path with no shell characters, endpoints must use an allowed scheme with no embedded credentials, edges must reference existing nodes). |
| /api/v1/layouts/[slug] | GET | Fetches a specific layout by its slug. |
| /api/v1/layouts/[slug] | PUT | Updates an existing layout definition. |
| /api/v1/layouts/[slug] | DELETE | Deletes a custom layout (protects built-in examples). |
| /api/v1/layouts/active | GET / POST | Gets or sets the currently active layout slug. |
| /api/v1/layouts/restore-examples | POST | Restores the 22 bundled example templates (the route returns EXAMPLE_LAYOUTS.length). |
10. GPU Compute Provider
Manage the background Billama worker node daemon:
GET /api/v1/provider/status: Returns worker status (ONLINE,SERVING,PAUSED,OFFLINE), GPU specs, temperature, active jobs, and earnings.POST /api/v1/provider/config: Updates server URL, worker token, floor pricing, thermal ceilings, and user pause toggles.POST /api/v1/provider/toggle: Starts or stops the background worker daemon ({"enabled": true}).POST /api/v1/provider/benchmark: Executes an inference speed benchmark against local models.
11. Native Tools API
POST /api/v1/tools
Inspects and executes built-in server-side native tools:
List Tools (action: "list")
{
"action": "list"
}
Execute Tool (action: "execute")
{
"action": "execute",
"tool": "calculator",
"params": {
"expression": "42 * (100 / 4)"
}
}
Available native tools:
calculator: Evaluates mathematical expressions using AST parsing withouteval().web_scraper: Fetches external URLs with SSRF protection (private IP / localhost blocked) and extracts clean text.
12. Secrets Discovery (OpenBao / Vault)
GET /api/secrets/discover
Discovers available API keys and credential paths stored in OpenBao or HashiCorp Vault. Used by the Agent Gateway to securely bind credentials into external tool runtime environments.
13. Memory Management API
Memory is always scoped to the authenticated caller (named elx_ key,
admin bearer, or NextAuth session β see apps/nextjs/src/lib/caller-identity).
A userId supplied via query string or request body is deliberately
ignored: it can never widen access beyond the caller's own store, and the
response echoes the caller's own userId. Readonly callers get 403 on
POST and DELETE.
GET /api/v1/memory
Retrieves semantically relevant memories or search results for the caller:
Query Parameters
qorquery(optional): Natural language search string. When empty or absent, the call lists stored items instead of searching.limit(optional): Maximum number of memory items to return (default:50, clamped to1β200).
With a query and a healthy context provider, the provider's recall runs first (falling back to local SQLite search when the provider is unreachable); without a query, stored items are listed.
POST /api/v1/memory
Adds a memory item, or commits a session transcript, in the active memory backend:
Add Memory Record (no action field)
{
"content": "Prefers TypeScript strict mode with no implicit any in all repositories.",
"sessionId": "sess_frontend_123",
"uri": "memory://user/alice/preferences/1",
"level": "L1",
"metadata": { "source": "client" }
}
content(required string): anything else returns400"'content' string is required". There is notextfield and nocategoryfield β both are ignored if sent.sessionId,uri,metadata(optional).level(optional):L0,L1(default), orL2.- There is no
action: "add": any POST body withoutaction: "commit"is treated as an add, and the item is also synced to the active external provider (OpenViking / Mem0) when one is configured.
Commit Session Transcript (action: "commit")
{
"action": "commit",
"sessionId": "sess_frontend_123"
}
Only action: "commit" is special-cased. The provider commits its own
server-side transcript for the session; no messages array is read from
the request.
DELETE /api/v1/memory
There is no POST "clear" action β clearing is a DELETE:
DELETE /api/v1/memory?clearAll=trueβ deletes all of the caller's memories (returns{ success: true, deletedCount, userId }).DELETE /api/v1/memory?id=<number>β deletes a single item, but only if it belongs to the caller (returns{ success: true|false }).- Omitting both parameters returns
400"Provide '?id=<number>' or '?clearAll=true'"; a non-positive or non-numericidreturns400"Invalid '?id=<number>' parameter".
14. Security Audit Chain, Batch API, Reranker, Prompt Registry & Alerting Webhooks (v1.2)
GET /api/v1/audit
Returns tamper-evident security audit events (api_key.create, api_key.revoke, config.update, prompt.register, prompt.promote). Pass ?verify=1 to walk the entire SHA-256 hash chain (prev_hash β entry_hash) from genesis and emit X-Eluvix-Audit-Chain-Valid: true|false.
POST /api/v1/files, GET /api/v1/files, GET /api/v1/files/:id/content
OpenAI-compatible JSONL batch file storage backed by SQLite batch_files.
POST /api/v1/batches, GET /api/v1/batches, GET /api/v1/batches/:id, POST /api/v1/batches/:id
OpenAI-compatible asynchronous Batch API executing queued JSONL /v1/chat/completions and /v1/embeddings items while cooperatively yielding to interactive foreground GPU requests via CooperativeVramArbiter.
POST /api/v1/rerank
Cohere / Jina / vLLM compatible cross-encoder and sovereign BM25/overlap reranking endpoint ({ model, query, documents, top_n, return_documents }) with PrivacyGuard PII scrubbing and X-Eluvix-Rerank-Model telemetry.
GET /api/v1/prompts, POST /api/v1/prompts
Versioned Prompt Registry storing immutable system templates (v1, v2, v3...), aliases (@staging, @production), and minEvalScore promotion gates. Reference prompts in chat requests via X-Eluvix-Prompt: <id>@production or metadata.promptRef.
GET / POST / DELETE /api/v1/keys (Admin RBAC)
Scoped API Key & Paperclip Policy Manager backed by ~/.config/eluvix/keys.json:
GET: Lists all named API keys with key hashes omitted, tokens truncated toelx_..., and literalpaperclip.hmacSecretvalues masked (while keepingSecretRefpointers such asenv:,file:,bao:,vault:, orkeychain:legible).POST: Mints a newelx_...key ({ label, role, origin, scopes, rpm, maxDailySpendUsd, paperclip: { companyIds, maxTier, maxCostPer1kUsd, hmacSecret, allowUnsignedContext } }) and returns the plaintext token once alongsideaudit_eventslogging.DELETE ?id=<id>: Revokes a named API key by ID and appends a tamper-evident entry toaudit_events.
GET /api/v1/webhooks, POST /api/v1/webhooks, DELETE /api/v1/webhooks
Manage and test SSRF-guarded outbound alerting webhooks (slack, discord, ntfy, json) signed with X-Eluvix-Signature: sha256=<hmac_hex>. Supports Paperclip governance events paperclip.budget_forecast, paperclip.tier_escalated, paperclip.hmac_rejected, and paperclip.safety_fuse.
15. Paperclip Integration & Correlation API (v1.3)
All /api/v1/paperclip/* endpoints require a named API key with the paperclip (or *) scope (or an authenticated dashboard session for /api/v1/paperclip/health). Only admin or admin:config-scoped callers may probe an arbitrary Paperclip base URL via the health endpoint; the target's response body is never echoed (status + latency only). Multi-endpoint parity across /api/v1/chat/completions, /api/v1/messages, /api/v1/responses, /api/v1/route-explain, and DesktopRouterServer enforces per-key companyIds isolation (403 on cross-company access), maxTier / maxCostPer1kUsd ceilings, x-eluvix-hops loop checks, company/issue episodic memory partitioning (`${userId}::pc:${companyId}`), and SecretRef (env:, file:, bao:, vault:, keychain:) HMAC secret resolution.
GET /api/v1/paperclip/whoami
Returns caller identity (userId), paperclipIntegrationEnabled, trustHeadersFrom, per-key paperclip policy (companyIds, maxTier, maxCostPer1kUsd, masked hmacSecret), egressPolicy, and rolling24hSpendUsd.
GET /api/v1/paperclip/capabilities
Returns Switchyard strategy, virtualModels (eluvix/auto, eluvix/fast-local, eluvix/code-specialist, eluvix/heavy-reasoning, eluvix/frontier-verified), sanitized paperclipPolicy (masking literal hmacSecret while preserving SecretRef pointers and hmacSigningConfigured), and upstream fleet telemetry.
POST /api/v1/paperclip/classify
Classifies a Paperclip issue ({ title, description, priority, labels, sensitivity }) into complexity, modalities, piiDetected, sensitivity, suggestedTier, and taskClass.
POST /api/v1/paperclip/recommend-assignee
Scores and ranks candidate Paperclip employees ({ task, candidates, parentAssigneeAgentId, weights, topN, explore, useEmbeddings }) using /v1/embeddings semantic fit cached in SQLite paperclip_embedding_cache (SHA-256 keyed with automatic keyword fallback), decayed cost-weighted Beta posteriors, 7-day budget exhaustion forecasts (triggering paperclip.budget_forecast webhooks when runway < 3 days), live openIssueCount load, and reportsTo/parent affinity.
POST /api/v1/paperclip/feedback
Records completed/reassigned assignment outcomes ({ issueId, agentId, companyId, taskClass, success, costUsd, durationMs }) into paperclip_assignment_outcomes.
GET /api/v1/paperclip/usage/:runId
Returns company-scoped aggregated inputTokens, outputTokens, cachedInputTokens, costUsd, dominantModel, and byModel breakdown for correlation_id = runId.
GET / POST /api/v1/paperclip/health
SSRF-guarded live health probe validating paperclipBaseUrl against cloud IMDS rules and probing <paperclipBaseUrl>/api/health for PaperclipBridgeNode (mirrored on /v1/paperclip/health in DesktopRouterServer).
Paperclip Security & Telemetry Headers
X-Paperclip-Context-Ts: Epoch millisecond timestamp paired withX-Paperclip-Context-Sig(300sreplay window).X-Paperclip-Context-Sig: HMAC-SHA256 signature (v1.<ts>.<hex>) authenticating canonicalx-paperclip-*context headers (resolved viaSecretRefwith fail-closed behavior if unresolved).X-Eluvix-Correlation-Id: Correlated Paperclip run ID (x-paperclip-run-id).X-Eluvix-Paperclip-Priority: Resolved issue priority (critical,high,medium,low).X-Eluvix-Paperclip-Bias: Applied Switchyard routing bias tags (tier-floor,tier-ceiling,prefer-local,local-only,budget-cascade,key-tier-ceiling,key-cost-ceiling,step:*).X-Eluvix-Step-Tier: Resolved intra-heartbeat trajectory step tier (fast-local,code-specialist,heavy-reasoning,frontier-verified) for agent tool-call loops.
HTTP Status Codes & Error Handling
| Status Code | Description | Typical Cause |
| :--- | :--- | :--- |
| 200 OK | Request succeeded. | Successful completion, query, or operation. |
| 400 Bad Request | Request rejected by Semantic Guard or invalid parameters. | Prompt injection attempt, malformed JSON, or missing required fields. |
| 401 Unauthorized | Authentication failed. | Missing or invalid master password or named API key Bearer token. |
| 402 Payment Required | Financial budget cap exceeded. | Request estimated cost exceeds maxCostPerRequest. |
| 429 Too Many Requests | Rate limit or Agent Loop detected. | Sliding-window RPM exceeded, or x-eluvix-hops exceeded max threshold (Agent loop detected). |
| 502 Bad Gateway | Upstream failure. | All candidate engines in the routing queue failed or returned errors. |
| 504 Gateway Timeout | Execution timeout. | Upstream engine exceeded timeoutMs (default 15,000ms). |