# Speech to Text
Source: https://docs.hitheo.ai/api-reference/audio/speech-to-text
POST /api/v1/audio/stt
Transcribe audio files to text.
Transcribe an audio file to text. Uses multipart form upload (not JSON). Maximum file size: 25 MB.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body (multipart/form-data)
Audio file to transcribe. Supported formats: MP3, MP4, MPEG, MPGA, M4A, WAV, WEBM.
Language hint (ISO 639-1 code, e.g., `"en"`, `"es"`, `"fr"`). If omitted, language is auto-detected.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/audio/stt \
-H "Authorization: Bearer $THEO_API_KEY" \
-F "file=@recording.mp3" \
-F "language=en"
```
```typescript SDK theme={null}
const file = new Blob([audioBytes], { type: "audio/mp3" });
const result = await theo.stt(file, "en");
console.log(result.text); // Transcribed text
console.log(result.language); // Detected language
console.log(result.duration_seconds); // Audio duration
```
## Response
Unique transcription ID (prefixed `stt_`).
ISO 8601 timestamp.
The transcribed text.
Detected or specified language.
Duration of the audio file in seconds.
Cost in cents.
### Example Response
```json theme={null}
{
"id": "stt_abc123",
"created": "2026-04-10T12:00:00Z",
"text": "Welcome to Theo. How can I help you today?",
"language": "en",
"duration_seconds": 3.2,
"usage": { "cost_cents": 0.01 }
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_file` | `file` is required (multipart form upload) |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 502 | `stt_provider_error` | Theo transcription engine returned an error — retry |
| 503 | `stt_unavailable` | STT is not configured on this instance |
# Text to Speech
Source: https://docs.hitheo.ai/api-reference/audio/text-to-speech
POST /api/v1/audio/tts
Convert text to spoken audio (returns MP3 binary).
Convert text to speech. Returns raw audio bytes (`audio/mpeg`) — not JSON.
The response is a binary MP3 file, not a JSON object. The `Content-Type` header is `audio/mpeg`.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Text to convert to speech. Maximum 4,096 characters.
Optional Theo voice identifier. Omit to use the default voice. Unknown values fall back to `theo-voice-classic`.
| Voice | Character |
| - | - |
| `theo-voice-classic` | Neutral, versatile — default |
| `theo-voice-bright` | Bright, clear, upbeat |
| `theo-voice-storyteller` | Narrative, expressive |
| `theo-voice-deep` | Deep, authoritative |
| `theo-voice-warm` | Warm, professional |
| `theo-voice-soft` | Soft, thoughtful |
Playback speed multiplier (0.25–4.0).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/audio/tts \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Welcome to Theo. How can I help you today?",
"voice": "theo-voice-warm",
"speed": 1.0
}' \
--output speech.mp3
```
```typescript SDK theme={null}
const audioBuffer = await theo.tts({
text: "Welcome to Theo. How can I help you today?",
voice: "theo-voice-warm",
speed: 1.0,
});
// audioBuffer is an ArrayBuffer — write to file or stream to client
import { writeFileSync } from "fs";
writeFileSync("output.mp3", Buffer.from(audioBuffer));
```
## Response
The response body is raw MP3 audio bytes.
| Header | Value |
| - | - |
| `Content-Type` | `audio/mpeg` |
| `Content-Length` | File size in bytes |
| `X-Request-Id` | Unique request ID (prefixed `tts_`) |
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_text` | `text` is required |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 502 | `tts_provider_error` | Theo voice engine returned an error — retry |
| 503 | `tts_unavailable` | TTS is not configured on this instance |
# Authentication
Source: https://docs.hitheo.ai/api-reference/authentication
API key authentication for all Theo API endpoints.
All API endpoints (except `GET /health`) require authentication via a Bearer token in the `Authorization` header.
## API Key Format
Keys are prefixed with `theo_sk_` for identification:
```
theo_sk_a1b2c3d4e5f6...
```
All keys are production keys — requests are billed against your credit balance.
## Making Authenticated Requests
Include the key in every request:
```bash theme={null}
curl https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer theo_sk_live_..." \
-H "Content-Type: application/json" \
-d '{"prompt": "Hello"}'
```
Always call the `www` host. The apex `hitheo.ai` 307-redirects to `www.hitheo.ai` and most HTTP clients strip the `Authorization` header on 3xx responses — the redirected request arrives unauthenticated and returns `401`. See [401 Troubleshooting](/troubleshooting/401-errors) for the full picture.
With the SDK, pass it during initialization:
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
```
## Key Management
Create and manage keys from the [API Dashboard](https://api.hitheo.ai) or via the API:
```bash theme={null}
# Create a key
curl -X POST https://www.hitheo.ai/api/v1/keys \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Production Server"}'
```
## First-Run Diagnostic
If anything doesn't work on the first call, run the SDK verifier before hunting through logs:
```bash theme={null}
# CLI — prints structured JSON + exit code 1 on failure
theo verify
```
```typescript theme={null}
// SDK — returns { healthy, authenticated, baseUrl, latencyMs, error?, hint? }
const result = await theo.verify();
if (!result.authenticated) console.error(result.hint);
```
Common failure modes and fixes live on the [401 Troubleshooting](/troubleshooting/401-errors) page.
## Security Best Practices
Never expose API keys in client-side code, public repositories, or logs.
* Store keys in environment variables or a secrets manager
* Use test keys (`theo_sk_test_`) for development
* Rotate keys regularly from the dashboard
* Set per-key rate limits and spending caps
## Error Responses
| Status | Error Code | Description |
| - | - | - |
| 401 | `invalid_api_key` | Key is missing, malformed, or revoked |
| 402 | `insufficient_credits` | Account has insufficient balance |
| 429 | `rate_limit_exceeded` | Too many requests — check `Retry-After` header |
# Generate Code
Source: https://docs.hitheo.ai/api-reference/code/generate
POST /api/v1/code
Generate production-quality code using the Theo Code engine.
Generate code from a natural language prompt. The Theo Code engine is optimized for production-quality code and long-form output.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Description of the code to generate.
Target programming language (e.g., `"typescript"`, `"python"`, `"go"`, `"rust"`). Appended as a hint to the engine.
Target framework (e.g., `"express"`, `"nextjs"`, `"fastapi"`, `"gin"`). Appended as a hint to the engine.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/code \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Write a TypeScript Express middleware for JWT authentication",
"language": "typescript",
"framework": "express"
}'
```
```typescript SDK theme={null}
const res = await theo.code({
prompt: "Write a TypeScript Express middleware for JWT authentication",
language: "typescript",
framework: "express",
});
console.log(res.content); // Generated code
console.log(res.artifacts); // Any files created
```
## Response
Unique code generation ID (prefixed `code_`).
ISO 8601 timestamp.
The generated code as text.
Any files created during generation (e.g., multi-file outputs).
Tools invoked during code generation.
Tool name.`"success"` or `"error"`.Cost in cents.
### Example Response
```json theme={null}
{
"id": "code_abc123",
"created": "2026-04-10T12:00:00Z",
"content": "import { Request, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\n\nexport function authMiddleware(req: Request, res: Response, next: NextFunction) {\n const token = req.headers.authorization?.split(' ')[1];\n if (!token) return res.status(401).json({ error: 'No token provided' });\n try {\n const decoded = jwt.verify(token, process.env.JWT_SECRET!);\n req.user = decoded;\n next();\n } catch {\n return res.status(401).json({ error: 'Invalid token' });\n }\n}",
"artifacts": [],
"tools_used": [],
"usage": { "cost_cents": 0.05 }
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_prompt` | `prompt` is required |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 429 | `rate_limit_exceeded` | Too many requests |
# Create Completion
Source: https://docs.hitheo.ai/api-reference/completions/create
POST /api/v1/completions
Send a prompt through the full orchestration pipeline — intent classification, skill loading, model routing, agent loop, and response.
The core endpoint of the Theo API. Sends a prompt through the full orchestration pipeline and returns the complete response.
For real-time token delivery, set `stream: true` or see [Streaming Completions](/api-reference/completions/streaming).
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
```bash theme={null}
Authorization: Bearer theo_sk_...
```
## Request Body
The prompt text. Must be a non-empty string.
Execution mode. When set to `auto`, Theo classifies the prompt and selects the optimal engine automatically.
Available modes:
* `auto` — Classify prompt and route to best engine (default)
* `fast` — Low-latency responses for simple queries
* `think` — Deep reasoning for complex analysis
* `code` — Code generation (Theo Code engine, extended output budget)
* `image` — Image generation (Theo Create)
* `video` — **Async.** Use [`POST /api/v1/video`](/api-reference/video/generate) + job polling, not this endpoint.
* `research` — **Async.** Use [`POST /api/v1/research`](/api-reference/research/create) + job polling, not this endpoint.
* `roast` — Humorous, irreverent tone
* `genui` — Generate interactive UI components (OpenUI Lang)
`research` and `video` are **asynchronous** and must not be sent to `/completions` (or `stream()`). They run as background jobs; invoking them here executes the work inline and the request hits the timeout before it finishes. Enqueue them via [`POST /api/v1/research`](/api-reference/research/create) / [`POST /api/v1/video`](/api-reference/video/generate) and poll with [Get Job Status](/api-reference/jobs/get). The `@hitheo/sdk` throws a `TheoUsageError` immediately if you pass these modes to `complete()` / `stream()`. See the [Async Jobs guide](/guides/async-jobs).
Enable SSE streaming. When `true`, returns a `text/event-stream` response instead of JSON. See [Streaming](/api-reference/completions/streaming).
Continue an existing conversation. Pass the conversation ID to maintain multi-turn context.
Skill slugs to activate for this request. These are merged with the user's installed skills.
Each slug activates a skill's prompt extension, tools, and model preferences for this completion. You can find slugs in the dashboard (copy icon on each skill card), via `GET /api/v1/skills`, or in the Skill Builder Input node.
See [Activating Skills via API](/guides/skills-api) for the full guide.
Inline tool definitions the model can call during the agent loop.
Tool name (e.g., `check_inventory`).
What the tool does — the model uses this to decide when to call it.
JSON Schema describing the tool's input parameters.
Override Theo's personality for this request.
* `"theo"` — Default Theo persona
* `"none"` — No persona (raw model output)
* `{ "system_prompt": "You are..." }` — Custom system prompt
Sampling temperature (0–2). Higher values produce more creative output.
Whether the model thinks before answering: `auto`, `on` or `off`. Thinking helps on hard problems but is slower and uses more output tokens. `auto` follows your orchestrator's Model node setting, otherwise the mode (on for `think` and `research`, off for quick modes like `fast`).
Maximum agent loop iterations (1–20). Each iteration is a think → act → observe cycle.
Override the engine used for specific modes. Keys are mode names (e.g., `"code"`, `"think"`), values are Theo engine IDs (e.g., `"theo-1-reason"`, `"theo-1-flash"`). See [List Models](/api-reference/models/list) for valid engine IDs.
Response format. `"theo"` for the default format, `"openai"` for OpenAI-compatible format.
Arbitrary key-value metadata attached to the completion. Returned in the response and logged in the audit trail.
Component library identifier for GenUI mode. Used by E.V.I. callers for custom UI rendering.
Set to `false` to skip long-term memory retrieval and injection for this request. Useful for stateless / privacy-sensitive calls where you don't want prior memories to influence the answer.
Inline conversation envelope for stateless callers — recent `messages` (max 20) the server uses when no `conversation_id` is supplied, so follow-ups like "make it longer" resolve against context.
Per-request response-style config (format, preciseness, intent) applied on top of the key's defaults.
Per-request personality/trait configuration overlay.
Master branding toggle. `false` strips the Theo persona/branding from the system prompt (superset control over `persona`).
When `true`, scopes the response to the key's brand catalog (Brand Soul) — recommends only your own products/content and redirects off-topic requests.
Image attachments for vision turns. Each item is either `{ type: "image_url", url }` or `{ type: "image_base64", data, mime_type }` (PNG / JPEG / WebP / GIF, ≤ 15MB base64).
Pin the image sub-engine for `image` mode (otherwise auto).
Pin the image quality tier for `image` mode.
Stealth-media model pin (`stealth_image` / `stealth_video`).
Stealth-media aspect ratio.
Stealth-video clip duration.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Explain microservices architecture",
"mode": "auto",
"temperature": 0.7
}'
```
```typescript SDK theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
const res = await theo.complete({
prompt: "Explain microservices architecture",
mode: "auto",
temperature: 0.7,
});
console.log(res.content);
console.log(res.model.label); // e.g. "Theo Flash"
console.log(res.usage.cost_cents); // e.g. 0.02
```
### With Skills and Tools
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Check current inventory levels for SKU-1234",
"mode": "auto",
"skills": ["inventory-check"],
"tools": [
{
"name": "check_stock",
"description": "Look up current stock levels by SKU",
"input_schema": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"warehouse": { "type": "string" }
},
"required": ["sku"]
}
}
],
"persona": { "system_prompt": "You are Atlas, an operations assistant." },
"max_iterations": 5
}'
```
```typescript SDK theme={null}
const res = await theo.complete({
prompt: "Check current inventory levels for SKU-1234",
skills: ["inventory-check"],
tools: [
{
name: "check_stock",
description: "Look up current stock levels by SKU",
input_schema: {
type: "object",
properties: {
sku: { type: "string" },
warehouse: { type: "string" },
},
required: ["sku"],
},
},
],
persona: { system_prompt: "You are Atlas, an operations assistant." },
max_iterations: 5,
});
```
## Response
Unique completion ID (prefixed `cmpl_`).
Always `"completion"`.
ISO 8601 timestamp.
The generated text content.
The mode you requested (e.g., `"auto"`).
The mode Theo actually used after intent classification (e.g., `"fast"`, `"think"`, `"code"`).
The Theo engine that handled the request.
Theo-branded model ID (e.g., `"theo-1-flash"`, `"theo-1-reason"`).
Human-readable name (e.g., `"Theo Flash"`, `"Theo Reason"`).
Engine subsystem (e.g., `"theo-core"`, `"theo-vision"`).
Tools called during the agent loop.
Tool name.`"success"` or `"error"`.Tool description.
Generated files (images, code, documents) produced during the completion.
Suggested next prompts.
Short label for the suggestion.Full prompt text.
Token counts and cost.
Cost in cents.Input tokens consumed. Always `0` for non-text modes (`image`, `video`, `tts`, `stt`).Output tokens generated. Always `0` for non-text modes.Total tokens.Present and `true` when the response was served from the semantic cache.
For non-text modes (`image`, `video`, `tts`, `stt`), `prompt_tokens` and `completion_tokens` are always `0` — tokens are not a meaningful billing unit there. Use `usage.cost_cents` as the sole usage metric for those modes.
The metadata you passed in the request, echoed back.
The server-side conversation id this turn resolved against. `null` when no conversation was created or attached. Echoed unchanged when you passed `conversation_id` in the request.
Server-assigned request identifier (also returned as the `X-Request-Id` header). Include this in support tickets so we can look up the request in logs.
### Example Response
```json theme={null}
{
"id": "cmpl_abc123",
"object": "completion",
"created": "2026-04-10T12:00:00Z",
"content": "Microservices architecture is a design pattern where an application is composed of small, independent services...",
"mode": "auto",
"resolved_mode": "fast",
"model": {
"id": "theo-1-flash",
"label": "Theo Flash",
"engine": "theo-core"
},
"tools_used": [],
"artifacts": [],
"follow_ups": [
{ "label": "Compare with monoliths", "prompt": "Compare microservices vs monolithic architecture" },
{ "label": "Service mesh", "prompt": "Explain service mesh in microservices" }
],
"usage": {
"cost_cents": 0.02,
"prompt_tokens": 12,
"completion_tokens": 156,
"total_tokens": 168
},
"metadata": null,
"conversation_id": null,
"request_id": "req_9f2e1a"
}
```
## OpenAI-Compatible Format
Pass `format: "openai"` to receive responses in OpenAI's `chat.completions` format. This allows drop-in replacement in existing OpenAI-based applications.
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Hello",
"format": "openai"
}'
```
The response follows the OpenAI `chat.completion` schema with `choices`, `usage`, and `model` fields.
## Semantic Caching
Non-conversation completions (no `conversation_id`) are automatically cached. Identical requests return cached results instantly at **zero cost**. See [Semantic Caching](/guides/semantic-caching).
Cached responses include `"_cached": true` in the response body.
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `validation_error` | Invalid request body (missing prompt, invalid mode, etc.) |
| 400 | `context_length_exceeded` | Request exceeds the largest context window on the key — add a larger-context model or shorten the request |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 402 | `insufficient_credits` | Account has insufficient balance |
| 403 | `model_not_allowed` | The request resolved to a model outside this key's model allowlist |
| 404 | `not_found` | Conversation ID not found |
| 422 | `guardrail_violation` | A Gateway Guardrails policy on this key denied the request |
| 422 | `orchestrator_no_path` | The key's orchestrator graph couldn't resolve a path for this request |
| 429 | `rate_limit_exceeded` | Too many requests — check `Retry-After` header |
| 500 | `server_error` | Internal server error |
# OpenAI-Compatible Chat Completions
Source: https://docs.hitheo.ai/api-reference/completions/openai-compat
POST /api/v1/chat/completions
Drop-in replacement for the OpenAI Chat Completions API. Point the OpenAI SDK at Theo and keep writing code the way you already do.
Theo implements the OpenAI Chat Completions wire protocol at `POST /api/v1/chat/completions`. Any application that uses the OpenAI SDK can point `baseURL` at `https://www.hitheo.ai/api/v1`, swap in a Theo API key, and keep working — the endpoint accepts the same `{ model, messages, stream, temperature, ... }` shape and returns the same `chat.completion` / `chat.completion.chunk` objects.
The **response shape** is identical to OpenAI. The **routing** underneath is Theo — intent classification, model selection, and automatic failover. Pass `model: "theo-1-auto"` to let Theo pick the best engine per request.
## Base URL
Use the canonical `www` host. The OpenAI SDK appends `/chat/completions`, so this base URL resolves to the real `POST /api/v1/chat/completions` route:
```
https://www.hitheo.ai/api/v1
```
Always use the `www` host. The apex `https://hitheo.ai` 307-redirects to `www`, and most HTTP clients strip the `Authorization` header across that redirect — the request arrives unauthenticated and returns `401`.
## Authentication
Uses the standard Bearer-token header. Your Theo API key replaces your OpenAI key.
```bash theme={null}
Authorization: Bearer theo_sk_...
```
## Drop-in Example (OpenAI SDK)
```typescript TypeScript theme={null}
import OpenAI from "openai";
const theo = new OpenAI({
apiKey: process.env.THEO_API_KEY,
baseURL: "https://www.hitheo.ai/api/v1",
});
const res = await theo.chat.completions.create({
model: "theo-1-auto",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Write me a haiku about Miami." },
],
});
console.log(res.choices[0].message.content);
```
```python Python theme={null}
from openai import OpenAI
theo = OpenAI(
api_key=os.environ["THEO_API_KEY"],
base_url="https://www.hitheo.ai/api/v1",
)
res = theo.chat.completions.create(
model="theo-1-auto",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Write me a haiku about Miami."},
],
)
print(res.choices[0].message.content)
```
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/chat/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "theo-1-auto",
"messages": [
{ "role": "user", "content": "Write me a haiku about Miami." }
]
}'
```
## Streaming
Set `stream: true` to receive an SSE stream of `chat.completion.chunk` objects terminated by `data: [DONE]`, exactly as OpenAI does.
```typescript theme={null}
const stream = await theo.chat.completions.create({
model: "theo-1-auto",
messages: [{ role: "user", content: "Stream me a short poem." }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
```
## Supported `model` Values
Pass any Theo-branded model ID. `theo-1-auto` is recommended so Theo's intent classifier picks the best engine per request; pass a specific engine if you want to pin the routing.
| Model ID | Theo Mode | Best For |
| - | - | - |
| `theo-1-auto` | auto | Let Theo pick the right engine per prompt |
| `theo-1-flash` | fast | Quick responses, short chats, classification |
| `theo-1-reason` | think | Deep reasoning, analysis, planning |
| `theo-1-code` | code | Code generation and review |
| `theo-1-create` | image | Image generation |
| `theo-1-motion` | video | Video generation |
| `theo-1-research` | research | Multi-step web research with citations |
| `theo-1-roast` | roast | Unfiltered humor and sharp critique |
| `theo-1-genui` | genui | Generative UI components |
| `theo-1-analyze` | domain\_analysis | Domain-specific analysis for business operations, finance, and compliance |
| `theo-1-extract` | data\_extraction | OCR and structured data extraction |
| `theo-1-vision` | vision | Multimodal image analysis |
Unknown model strings fall back to `auto` and Theo routes the request like any other prompt.
## Request Body
The body is the standard OpenAI Chat Completion shape. Fields not listed below are accepted but ignored (e.g. `top_p`, `n`, `max_tokens`, `user`).
A Theo model ID. See the table above for valid values.
The conversation so far. Each message has `{ role, content }`. Supported roles: `system`, `user`, `assistant`. `tool` messages are accepted but ignored (Theo owns tool-call state internally).
The **last user message** is treated as the prompt. All `system` messages are merged into a single system prompt that overrides Theo's default persona. Prior user/assistant turns are injected as conversation context.
When `true`, returns an SSE stream of `chat.completion.chunk` objects terminated by `data: [DONE]`.
Sampling temperature (0–2).
OpenAI-style thinking control. `none` or `minimal` = answer directly; `low`, `medium` or `high` = think before answering. Theo also accepts `reasoning`: `auto` (default), `on` or `off`, which wins when both are sent. Applies to tool calls too.
**Theo-specific.** Attach this completion to an existing Theo conversation so its memory persists across channels. Omit to send a stateless request.
**Theo-specific.** Activate skills by slug for this request. Merged with the user's installed skills.
**Theo-specific.** Arbitrary key-value data attached to the audit log.
## Response
A standard OpenAI `chat.completion` (or `chat.completion.chunk` for streaming). Theo-specific metadata is returned under a `theo_metadata` extension so it doesn't collide with existing OpenAI client expectations.
```json theme={null}
{
"id": "chatcmpl_...",
"object": "chat.completion",
"created": 1715872800,
"model": "theo-1-flash",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "Neon waves on sand..." },
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 24,
"completion_tokens": 38,
"total_tokens": 62
},
"theo_metadata": {
"mode": "auto",
"resolved_mode": "fast",
"tools_used": [],
"artifacts": [],
"engine": "theo-core"
}
}
```
## When to use `/v1/completions` instead
* You need a **single-turn prompt** string instead of a message array.
* You want the richer **native Theo response** (follow-ups, artifacts, tool traces) instead of the OpenAI shape.
* You want to control `persona` or `response_style` per request.
See [Create Completion](/api-reference/completions/create) for the native endpoint.
## Per-key orchestration applies
This endpoint runs the **same per-key orchestration** as the native endpoint: whatever you configured for the API key — the [Orchestrator graph](/dashboard/orchestrator), model pins, [Gateway Guardrails](/guides/guardrails), [Routing Studio](/core-concepts/model-routing) preferences, the model allowlist, and the [context-window guard](/api-reference/completions/openai-compat#errors) — governs requests here too. So a key you shaped in the dashboard or via the [MCP tools](/mcp/tools) behaves identically whether you call it through the OpenAI SDK or the native API. Guardrails can deny (`422`), a model outside the key's allowlist is rejected (`403`), and an oversize request returns `400 context_length_exceeded`. Keys with no such configuration are unaffected — they route on Theo's defaults exactly as before.
## Errors
Returns the same error envelope as every other v1 endpoint:
```json theme={null}
{
"error": {
"message": "Validation failed: messages must contain at least one message.",
"type": "invalid_request_error",
"code": "validation_error"
}
}
```
| Status | Code | Description |
| - | - | - |
| 400 | `validation_error` | `messages` is missing, empty, or malformed |
| 400 | `empty_prompt` | `messages` contained only system/tool messages |
| 400 | `context_length_exceeded` | Request is larger than any model on the key can hold — add a larger-context model to the orchestrator or shorten the request |
| 401 | `invalid_api_key` | Missing or invalid `Authorization: Bearer theo_sk_...` |
| 402 | `insufficient_credits` | Account balance is too low for the pre-flight reservation |
| 403 | `model_not_allowed` | The request resolved to a model outside this key's model allowlist |
| 422 | `guardrail_violation` | A Gateway Guardrails policy on this key denied the request |
| 422 | `orchestrator_no_path` | The key's orchestrator graph couldn't resolve a path for this request |
| 404 | `not_found` | `conversation_id` not found |
| 429 | `rate_limit_exceeded` | Check `Retry-After` |
| 500 | `server_error` | Internal error |
# Streaming Completions
Source: https://docs.hitheo.ai/api-reference/completions/streaming
Full SSE event schemas, wire format, and error semantics.
Set `stream: true` on any `POST /api/v1/completions` request to receive a Server-Sent Events (SSE) stream instead of a single JSON response.
## Request
```bash theme={null}
curl -N -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt": "Write a haiku about code", "stream": true}'
```
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
## Wire Format
Every event is two lines followed by a blank line:
```
event:
data:
```
Callers MUST buffer partial chunks and split on `\n\n` — token events can be tens of bytes each and the transport does not guarantee alignment with event boundaries.
## Event Types (in order of arrival)
The server emits events in a fixed order: `thinking` → `meta` → (`skills`? / `genui_meta`?) → `tool`\* → `artifact`\* → `token`\* → `done`. If anything fails mid-stream an `error` event is emitted and the stream closes.
| Event | Description |
| - | - |
| `thinking` | Heartbeat — a single byte so proxies flush the response immediately. No JSON payload |
| `meta` | Engine info, resolved mode, artifacts, routing, `conversation_id`, `request_id` |
| `skills` | Active skills for this turn (only when one or more skills were applied) |
| `genui_meta` | GenUI component library info (only when `resolved_mode === "genui"`) |
| `tool` | A tool was called (may fire multiple times) |
| `artifact` | A generated file (image, document, code, video) (may fire multiple times) |
| `token` | A text chunk (fires for each token) |
| `done` | Final payload: full content, follow-ups, usage, `conversation_id`, `request_id` |
| `error` | An error occurred — payload matches the REST error envelope |
## Payload Schemas
### `meta`
```typescript theme={null}
interface StreamMetaData {
id: string; // completion id (cmpl_...)
mode: ChatMode; // mode you requested
resolved_mode: ChatMode; // mode after intent classification
model: {
id: string; // theo-branded id (e.g. "theo-1-flash")
label: string; // human-friendly label
engine: string; // engine subsystem (e.g. "theo-core")
};
tools: Array<{ name: string; status: string; description?: string }>;
artifacts: unknown[]; // pre-populated artifacts (images, docs)
brand?: Record; // optional brand-soul overlay
routing?: Record;// routing-engine telemetry
conversation_id: string | null; // null for stateless callers
request_id: string; // mirror of X-Request-Id header
}
```
### `token`
```typescript theme={null}
interface StreamTokenData {
token: string; // text chunk; concatenate in order to reconstruct the full content
}
```
### `tool`
```typescript theme={null}
interface StreamToolData {
name: string; // tool name (e.g. "Intent classifier", "browser_navigate")
status: string; // "pending" | "running" | "complete" | "error"
description?: string;// short human-readable description
}
```
### `artifact`
The payload depends on `artifact.type`. Common fields: `id`, `type`, `title`, `providerId`, `modelId`. Image artifacts include `imageUrl`; video artifacts include `videoUrl`; document artifacts include `downloadUrl` and `sizeBytes`; code artifacts include `code` and `language`.
### `genui_meta`
```typescript theme={null}
interface GenUIMetaEvent {
library: string; // component library id (e.g. "theo")
tools: string[]; // tool names the Renderer's toolProvider should expose
}
```
### `skills`
```typescript theme={null}
interface StreamSkillsData {
active: Array<{
id: string;
slug: string;
name: string;
intensity?: number; // 0–100 when the skill supports intensity
}>;
}
```
### `done`
```typescript theme={null}
interface StreamDoneData {
id: string;
content: string; // full text output (same as concatenated tokens)
follow_ups: Array<{ label: string; prompt: string }>;
structured_output?: {
type: string;
data: unknown;
parse_error?: string;
};
skills_active?: Array<{ id: string; slug: string; name: string; intensity?: number }>;
routing?: Record;
usage: {
cost_cents: number;
prompt_tokens: number; // always 0 for non-text modes
completion_tokens: number;// always 0 for non-text modes
total_tokens: number;
cached?: boolean; // true when served from the semantic cache
};
conversation_id: string | null;
request_id: string;
}
```
### `error`
The `error` event payload matches the REST error envelope (see [Overview](/api-reference/overview)):
```typescript theme={null}
interface StreamErrorData {
error: {
message: string;
type: string; // e.g. "rate_limit_error", "server_error"
code: string; // e.g. "stream_interrupted", "orchestration_failed"
request_id: string | null;
};
}
```
## Example Stream
```
event: thinking
data: {"status":"processing"}
event: meta
data: {"id":"cmpl_abc123","mode":"auto","resolved_mode":"fast","model":{"id":"theo-1-flash","label":"Theo Flash","engine":"theo-core"},"tools":[],"artifacts":[],"conversation_id":null,"request_id":"req_9f2e1a"}
event: token
data: {"token":"Lines"}
event: token
data: {"token":" of"}
event: token
data: {"token":" code"}
event: done
data: {"id":"cmpl_abc123","content":"Lines of code","follow_ups":[],"usage":{"cost_cents":0.01,"prompt_tokens":8,"completion_tokens":3,"total_tokens":11},"conversation_id":null,"request_id":"req_9f2e1a"}
```
## Extracting `conversation_id`
`conversation_id` appears on both `meta` and `done`. For stateless callers (no `conversation_id` in the request) it is `null`. For callers that passed a `conversation_id` in the request, it is echoed back unchanged. The SDK exposes this as `stream.conversationId` after the stream completes.
```typescript theme={null}
const stream = theo.stream({ prompt: "..." });
for await (const event of stream) {
// consume events
}
console.log(stream.conversationId); // populated from meta / done
```
## Mid-Stream Errors
When orchestration fails after `meta` has already been emitted (e.g. the upstream LLM provider times out or a per-mode rate limit kicks in), the server emits an `error` event with the REST envelope and closes the stream:
```
event: meta
data: {"id":"cmpl_abc123","mode":"auto","resolved_mode":"fast","model":{"id":"theo-1-flash","label":"Theo Flash","engine":"theo-core"},"tools":[],"artifacts":[],"conversation_id":null,"request_id":"req_9f2e1a"}
event: token
data: {"token":"Lines"}
event: error
data: {"error":{"message":"Rate limit exceeded for fast mode (120 RPM on 'free' tier).","type":"rate_limit_error","code":"mode_rate_limit_exceeded","request_id":"req_9f2e1a"}}
```
Use the same code path as your REST error handler:
```typescript theme={null}
for await (const event of stream) {
if (event.type === "error") {
const { message, type, code, request_id } = event.data.error;
throw new Error(`[${type}/${code}] ${message} (request_id=${request_id})`);
}
// ...
}
```
## SDK Usage
The SDK returns a `TheoStream` — an async iterable with `cancel()` for mid-generation abort plus final-metadata properties.
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
const stream = theo.stream({ prompt: "Explain DNS" });
// Graceful cancel after 3s (e.g. user clicked "Stop generating")
setTimeout(() => stream.cancel(), 3000);
for await (const event of stream) {
switch (event.type) {
case "meta": console.log("Mode:", event.data.resolved_mode); break;
case "token": process.stdout.write(event.token); break;
case "tool": console.log("Tool:", event.data.name, event.data.status); break;
case "artifact": console.log("Artifact:", event.data); break;
case "error": console.error("Stream error:", event.data.error); break;
case "done": console.log("\nCost:", event.data.usage.cost_cents); break;
}
}
console.log("conversation_id:", stream.conversationId);
console.log("usage:", stream.usage);
console.log("request_id:", stream.requestId);
```
See [Streaming](/core-concepts/streaming) for the conceptual guide.
# Generate Document
Source: https://docs.hitheo.ai/api-reference/documents/generate
POST /api/v1/documents
Generate PDF, DOCX, PPTX, XLSX, or CSV documents from natural language.
Generate structured documents from a natural language prompt. Supports PDF, DOCX, PPTX, XLSX, and CSV formats.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Description of the document to generate.
Output format. One of: `pdf`, `docx`, `pptx`, `xlsx`, `csv`.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/documents \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Create a Q1 2026 sales report with executive summary and charts",
"format": "pdf"
}'
```
```typescript SDK theme={null}
const res = await theo.documents({
prompt: "Create a Q1 2026 sales report with executive summary and charts",
format: "pdf",
});
console.log(res.title); // "Q1 2026 Sales Report"
console.log(res.download_url); // Presigned download URL
console.log(res.content); // Document text content
```
## Response
Unique document ID (prefixed `doc_`).
ISO 8601 timestamp.
The output format (e.g., `"pdf"`).
Auto-generated document title.
Presigned URL to download the document file. May be `null` if file generation is still processing.
File size in bytes.
Text content of the generated document.
Cost in cents.
### Example Response
```json theme={null}
{
"id": "doc_abc123",
"created": "2026-04-10T12:00:00Z",
"format": "pdf",
"title": "Q1 2026 Sales Report",
"download_url": "https://artifacts.hitheo.ai/docs/abc123.pdf?token=...",
"size_bytes": 245760,
"content": "# Q1 2026 Sales Report\n\n## Executive Summary\n...",
"usage": { "cost_cents": 0.12 }
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_prompt` | `prompt` is required |
| 400 | `invalid_format` | Unsupported format. Supported: `pdf`, `docx`, `pptx`, `xlsx`, `csv` |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 429 | `rate_limit_exceeded` | Too many requests |
# Canvases
Source: https://docs.hitheo.ai/api-reference/evi/canvases
Create, list, update, and delete Skill Builderes.
## List Canvases
```http theme={null}
GET /api/v1/evi/canvases
Authorization: Bearer theo_sk_...
```
Returns up to 50 canvases for the authenticated user, ordered by last updated.
**Response**
```json theme={null}
{
"canvases": [
{
"id": "uuid",
"name": "My Agent",
"description": "A customer service agent",
"status": "draft",
"graphJson": { "nodes": [], "edges": [] },
"compiledManifest": null,
"isPublic": false,
"publishedSkillId": null,
"createdAt": "2026-04-15T00:00:00Z",
"updatedAt": "2026-04-15T00:00:00Z"
}
]
}
```
## Create Canvas
```http theme={null}
POST /api/v1/evi/canvases
Authorization: Bearer theo_sk_...
Content-Type: application/json
{
"name": "My Agent",
"description": "Optional description",
"graph_json": {
"nodes": [],
"edges": []
}
}
```
**Parameters**
* `name` (string, required) — Canvas name (max 128 chars).
* `description` (string, optional) — Short description (max 500 chars).
* `graph_json` (object, optional) — Initial graph with `nodes` and `edges` arrays. Defaults to empty.
## Get Canvas
```http theme={null}
GET /api/v1/evi/canvases/{id}
Authorization: Bearer theo_sk_...
```
Returns a single canvas by ID. Only the canvas owner can access it.
## Update Canvas
```http theme={null}
PATCH /api/v1/evi/canvases/{id}
Authorization: Bearer theo_sk_...
Content-Type: application/json
{
"name": "Updated Name",
"graph_json": { "nodes": [...], "edges": [...] }
}
```
All fields are optional. At least one must be provided.
**Parameters**
* `name` (string, optional)
* `description` (string, optional)
* `graph_json` (object, optional)
* `is_public` (boolean, optional)
## Delete Canvas
```http theme={null}
DELETE /api/v1/evi/canvases/{id}
Authorization: Bearer theo_sk_...
```
Permanently deletes the canvas. If a skill was published from it, the skill remains but is no longer linked.
# Compile Canvas
Source: https://docs.hitheo.ai/api-reference/evi/compile
Validate and compile an Skill Builder into a SkillManifest and WorkflowSteps.
```http theme={null}
POST /api/v1/evi/canvases/{id}/compile
Authorization: Bearer theo_sk_...
```
Validates the canvas graph and compiles it into two outputs:
1. **SkillManifest** — Used by the skill system for marketplace listing, install, and prompt injection.
2. **WorkflowSteps** — Used by the workflow engine for runtime execution.
The compiled output is saved on the canvas record. The canvas status transitions to `"testing"`.
## Validation Checks
* Exactly 1 Input node
* At least 1 reachable Output node
* No cycles in the execution path
* All nodes reachable from Input
* Model nodes must have an upstream Prompt node
* All node types must be valid (`input`, `prompt`, `model`, `tool`, `knowledge`, `condition`, `output`, `vision`)
## Response (success)
```json theme={null}
{
"compiled": true,
"manifest": { "name": "...", "slug": "...", "version": "1.0.0", "..." },
"steps": [{ "type": "ai_transform", "name": "...", "config": { "..." } }],
"errors": []
}
```
## Response (validation errors)
```json theme={null}
{
"compiled": false,
"errors": [
{ "code": "cycle_detected", "message": "Canvas graph contains a cycle." },
{ "code": "model_no_prompt", "message": "Model node has no Prompt node upstream.", "nodeId": "model-1" }
]
}
```
Status `422` is returned when validation fails.
# Publish Canvas
Source: https://docs.hitheo.ai/api-reference/evi/publish
Compile and publish an Skill Builder as a skill with configurable visibility.
```http theme={null}
POST /api/v1/evi/canvases/{id}/publish
Authorization: Bearer theo_sk_...
Content-Type: application/json
{
"slug": "my-support-agent",
"version": "1.0.0",
"author": { "name": "Your Name" },
"visibility": "public",
"readme": "# My Support Agent\nA customer service skill built with the Skill Builder.",
"license": "MIT",
"keywords": ["support", "customer-service"]
}
```
Compiles the canvas, runs automated review checks, and publishes it as a skill. The skill enters the same review pipeline as skills submitted via CLI or API.
## Parameters
* `slug` (string, required) — Skill slug. Lowercase alphanumeric with hyphens.
* `version` (string, required) — Semver version (e.g. `1.0.0`).
* `author` (object, required) — `{ name, email?, url? }`.
* `visibility` (string, optional) — Publishing visibility. Default: `"private"`.
* `"private"` — Only you can see and install the skill.
* `"org"` — Visible to all members of the target organization. Requires `target_org_id`.
* `"public"` — Listed in the public Skill Store.
* `target_org_id` (string, optional) — Required when `visibility` is `"org"`. The UUID of the org to scope the skill to.
* `readme` (string, optional) — Markdown README for the marketplace listing (max 50,000 chars).
* `license` (string, optional) — SPDX license identifier. Default: `"MIT"`.
* `keywords` (array, optional) — Up to 10 search keywords.
## Response (auto-approved)
```json theme={null}
{
"published": true,
"visibility": "public",
"submission": {
"id": "uuid",
"status": "approved",
"reviewTier": "auto",
"autoApproved": true
},
"skillId": "uuid"
}
```
## Response (pending review)
```json theme={null}
{
"published": true,
"visibility": "org",
"submission": {
"id": "uuid",
"status": "pending_review",
"reviewTier": "staff",
"autoApproved": false
},
"skillId": "uuid"
}
```
## Response (compilation or review failure)
Status `422` with `published: false` and an `errors` or `review` object describing what failed.
# Test Canvas
Source: https://docs.hitheo.ai/api-reference/evi/test
Send a test message through a compiled Skill Builder in sandbox mode.
```http theme={null}
POST /api/v1/evi/canvases/{id}/test
Authorization: Bearer theo_sk_...
Content-Type: application/json
{
"message": "Check stock for SKU-1234",
"history": [
{ "role": "user", "content": "Hello" },
{ "role": "assistant", "content": "Hi! How can I help?" }
]
}
```
Compiles the canvas (or uses cached compilation) and sends a test message through the sandbox. Tool calls are simulated with mock data — no real external requests are made.
## Parameters
* `message` (string, required) — The test message (max 4000 chars).
* `history` (array, optional) — Up to 10 previous messages for multi-turn testing. Each has `role` ("user" or "assistant") and `content`.
## Response
```json theme={null}
{
"response": "SKU-1234 currently has 47 units in stock...",
"cost_cents": 5
}
```
## Sandbox Constraints
* No real external HTTP requests
* Tool calls return simulated mock data
* Responses are concise for testing
* Credits are debited at the standard rate
Returns `422` if the canvas fails compilation.
# Create Hook
Source: https://docs.hitheo.ai/api-reference/hooks/create
POST /api/v1/hooks
Install an autonomous hook that triggers skill execution when matching events occur.
## Request
ID of a built-in hook preset (e.g., `share.accepted.welcome`, `task.overdue.summary`). Mutually exclusive with `event_pattern`.
Custom event pattern to match. Supports exact match (`share.accepted`), glob wildcards (`order.*.completed`), prefix match (`share`), or catch-all (`*`). Mutually exclusive with `hook_preset_id`.
Slug of the skill to execute when the hook fires.
Minimum time between firings in minutes (1–1440). A server-side default is applied when omitted.
## Response
The hook's unique UUID.
The resolved event pattern (from preset or custom).
The target skill slug.
Always `true` on creation.
Cooldown period between firings.
## Authentication
Requires an API key with `completions` scope.
## Example
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/hooks \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"event_pattern": "order.*.completed",
"skill_slug": "order-processor",
"cooldown_minutes": 5
}'
```
```typescript SDK theme={null}
const hook = await theo.createHook({
event_pattern: "order.*.completed",
skill_slug: "order-processor",
cooldown_minutes: 5,
});
```
## Guard Rails
* Pre-flight credit check before each autonomous execution
* Separate daily cap for autonomous actions
* Per-run caps on tool invocations and total spend
* Hooks auto-pause after repeated failures
* Cooldown enforced between firings
# Delete Hook
Source: https://docs.hitheo.ai/api-reference/hooks/delete
DELETE /api/v1/hooks/{id}
Permanently remove an installed hook.
## Path Parameters
The hook UUID.
## Response
```json theme={null}
{ "deleted": true }
```
## Authentication
Requires an API key with `completions` scope.
## Example
```bash curl theme={null}
curl -X DELETE https://www.hitheo.ai/api/v1/hooks/HOOK_ID \
-H "Authorization: Bearer $THEO_API_KEY"
```
```typescript SDK theme={null}
await theo.deleteHook("HOOK_ID");
```
# Get Hook Executions
Source: https://docs.hitheo.ai/api-reference/hooks/get
GET /api/v1/hooks/{id}
View recent execution history for an installed hook.
Returns the most recent execution records for a hook (up to 50), newest first.
## Path Parameters
The hook UUID.
## Response
Recent executions. Each entry includes `id`, `event_type`, `status`, `credits_used`, `execution_ms`, `skip_reason`, `error_message`, and `created_at`.
## Authentication
Requires an API key with `completions` scope.
## Example
```bash curl theme={null}
curl https://www.hitheo.ai/api/v1/hooks/HOOK_ID \
-H "Authorization: Bearer $THEO_API_KEY"
```
### Response
```json theme={null}
{
"executions": [
{
"id": "exec_a1b2c3",
"event_type": "order.shipped.completed",
"status": "success",
"credits_used": 12,
"execution_ms": 1840,
"skip_reason": null,
"error_message": null,
"created_at": "2026-05-20T14:03:00.000Z"
}
]
}
```
# List Hooks
Source: https://docs.hitheo.ai/api-reference/hooks/list
GET /api/v1/hooks
List all installed hooks and available hook presets.
## Response
Array of installed hooks. Each includes `id`, `event_pattern`, `skill_slug`, `enabled`, `cooldown_minutes`, `consecutive_failures`, `last_fired_at`, `created_at`.
Array of available hook presets. Each includes `id`, `event_pattern`, `default_skill`, `description`.
## Authentication
Requires an API key with `completions` scope.
## Example
```bash curl theme={null}
curl https://www.hitheo.ai/api/v1/hooks \
-H "Authorization: Bearer $THEO_API_KEY"
```
### Response
```json theme={null}
{
"hooks": [
{
"id": "a1b2c3d4-...",
"event_pattern": "order.*.completed",
"skill_slug": "order-processor",
"enabled": true,
"cooldown_minutes": 5,
"consecutive_failures": 0,
"last_fired_at": null,
"created_at": "2026-04-15T12:00:00.000Z"
}
],
"presets": [
{
"id": "share.accepted.welcome",
"event_pattern": "share.accepted",
"default_skill": "email-drafter",
"description": "Welcome on share accept"
}
]
}
```
## Management
* `PATCH /api/v1/hooks/{id}` — Update config, enable/disable
* `DELETE /api/v1/hooks/{id}` — Remove
* `GET /api/v1/hooks/{id}` — View execution history
# Update Hook
Source: https://docs.hitheo.ai/api-reference/hooks/update
PATCH /api/v1/hooks/{id}
Enable or disable a hook, or change its cooldown and configuration.
## Path Parameters
The hook UUID.
## Request
All fields are optional — include only what you want to change.
Enable or disable the hook. Disabled hooks never fire.
Minimum time between firings in minutes (1–1440).
Hook-specific configuration overrides.
## Response
```json theme={null}
{ "updated": true }
```
## Authentication
Requires an API key with `completions` scope.
## Example
```bash curl theme={null}
curl -X PATCH https://www.hitheo.ai/api/v1/hooks/HOOK_ID \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "enabled": false }'
```
```typescript SDK theme={null}
await theo.updateHook("HOOK_ID", { enabled: false });
```
# Generate Images
Source: https://docs.hitheo.ai/api-reference/images/generate
POST /api/v1/images
Generate images from text prompts using the Theo Create engine.
Generate one or more images from a text prompt. This is a synchronous endpoint — images are returned directly in the response.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Text description of the image(s) to generate.
Visual style hint (e.g., `"photorealistic"`, `"illustration"`, `"watercolor"`, `"3d-render"`). Appended to the prompt for the image engine.
Aspect ratio (e.g., `"1:1"`, `"16:9"`, `"9:16"`, `"4:3"`). Defaults to the engine's native ratio.
Number of images to generate (1–4).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/images \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A minimalist tech logo, blue and white",
"style": "photorealistic",
"aspect_ratio": "1:1",
"count": 2
}'
```
```typescript SDK theme={null}
const res = await theo.images({
prompt: "A minimalist tech logo, blue and white",
style: "photorealistic",
aspect_ratio: "1:1",
count: 2,
});
for (const img of res.images) {
console.log(img.url, img.engine);
}
```
## Response
Unique image generation ID (prefixed `img_`).
ISO 8601 timestamp.
Array of generated images.
Hosted image URL.Theo engine subsystem that produced the image (e.g. `"theo-vision"`).Theo model ID (e.g. `"theo-1-create"`).The prompt used (may include style/ratio enrichment).Cost in cents.
### Example Response
```json theme={null}
{
"id": "img_abc123",
"created": "2026-04-10T12:00:00Z",
"images": [
{
"url": "https://artifacts.hitheo.ai/img/abc123-1.png",
"engine": "theo-vision",
"model": "theo-1-create",
"prompt": "A minimalist tech logo, blue and white Style: photorealistic. Aspect ratio: 1:1."
},
{
"url": "https://artifacts.hitheo.ai/img/abc123-2.png",
"engine": "theo-vision",
"model": "theo-1-create",
"prompt": "A minimalist tech logo, blue and white Style: photorealistic. Aspect ratio: 1:1."
}
],
"usage": { "cost_cents": 0.08 }
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_prompt` | `prompt` is required |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 429 | `rate_limit_exceeded` | Too many requests |
# API Reference Overview
Source: https://docs.hitheo.ai/api-reference/overview
REST API for AI orchestration — completions, images, video, code, research, documents, skills, and more.
The Theo API is a RESTful JSON API served at `https://www.hitheo.ai/api/v1/`. All endpoints require authentication via Bearer token except `/health`.
## Base URL
```
https://www.hitheo.ai/api/v1/
```
Always call the `www` host directly. The apex `hitheo.ai` 307-redirects to `www.hitheo.ai`, and most HTTP clients strip the `Authorization` header on 3xx responses — the redirected request arrives unauthenticated and the server returns `401`. The SDK defaults to `https://www.hitheo.ai` as of `@hitheo/sdk@0.2.0`. If you hit an unexpected 401, see [401 Troubleshooting](/troubleshooting/401-errors).
## Authentication
All requests must include your API key in the `Authorization` header:
```
Authorization: Bearer theo_sk_...
```
See [Authentication](/api-reference/authentication) for details.
## OpenAPI Spec
The full OpenAPI 3.1 specification is available at:
```
https://www.hitheo.ai/api/v1/openapi.json
```
You can import this into Postman, Insomnia, or any OpenAPI-compatible tool.
## Endpoints at a Glance
| Category | Endpoints | Description |
| - | - | - |
| **Completions** | `POST /completions` | Core AI completions with the orchestration pipeline |
| **Chat Completions** | `POST /chat/completions` | Drop-in chat-completions wire format for existing tooling |
| **Images** | `POST /images` | Image generation (Theo Create) |
| **Video** | `POST /video` | Video generation (async) |
| **Code** | `POST /code` | Code generation (Theo Code) |
| **Research** | `POST /research` | Deep web research (async) |
| **Documents** | `POST /documents` | PDF, DOCX, PPTX, XLSX, CSV generation |
| **Audio** | `POST /audio/tts`, `POST /audio/stt` | Text-to-speech and speech-to-text |
| **Skills** | `GET/POST /skills`, `POST /skills/create`, `POST /skills/submit` | Marketplace and skill management |
| **Skill Builder** | `GET/POST /evi/canvases` | Build, compile, and publish E.V.I. personas |
| **Workflows** | `GET/POST /workflows`, `POST /workflows/{id}/run` | Automation workflows |
| **Hooks** | `GET/POST /hooks` | Autonomous event-triggered skill execution |
| **Events** | `POST /events` | Publish domain events |
| **Guardrails** | `GET/POST /guardrail-policies` | Input/output policy enforcement |
| **Routing Studio** | `GET/POST /routing-preferences` | Per-customer routing preferences |
| **Embed Widgets** | `GET/POST /iframes` | White-label chat widgets, analytics, and leads |
| **Theo Browser** | `POST /browser/sessions` | Managed headless browser sessions |
| **Webhooks** | `GET/POST /webhooks` | Outbound event delivery |
| **Conversations** | `GET /conversations` | Conversation history |
| **Models** | `GET /models` | Available engine registry |
| **Tools** | `GET /tools` | Available tool definitions |
| **Jobs** | `GET /jobs/{id}` | Async job status polling |
| **Usage** | `GET /usage`, `GET /usage/export` | Usage analytics and CSV export |
| **Billing** | `POST /billing/checkout`, `POST /billing/portal` | Credit top-ups and billing portal |
| **Settings** | `GET/PATCH /settings` | Account preferences |
| **Benchmarks** | `GET /benchmarks` | Aggregated latency and routing telemetry |
| **Organizations** | `GET/POST /orgs` | Team and membership management |
| **Audit** | `GET /audit`, `GET /audit/export` | Audit log listing and CSV export |
| **Keys** | `POST /keys` | API key management |
| **Key orchestration** | `GET/PUT /keys/{id}/models`, `/model-plan`, `/orchestrator-graph`, `/skills`, `/guardrails`, `/routing-preference` | Per-key model allowlist, model plan, executable graph, skills, guardrail + routing bindings |
| **Custom Providers** | `GET/POST /custom-providers`, `DELETE /custom-providers/{id}` | Bring-your-own OpenAI-compatible model endpoints |
| **Health** | `GET /health` | System status (public, no auth) |
## Response Format
All responses follow a consistent JSON structure:
```json theme={null}
{
"id": "resource_id",
"object": "resource_type",
"created": "2026-04-10T12:00:00Z",
"request_id": "req_9f2e1a",
...resource-specific fields
}
```
Every response also carries an `X-Request-Id` header; successful JSON responses surface the same value as a top-level `request_id` field. Include it in support tickets so the request can be looked up in logs.
## Idempotency Keys
POST requests to state-changing endpoints (create canvas, create workflow, run workflow, submit skill, create webhook, install hook, publish event, create iframe, duplicate iframe, start browser session, install skill) accept an `Idempotency-Key` header:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/workflows \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Idempotency-Key: c0ff33-2026-04-21-deploy-123" \
-H "Content-Type: application/json" \
-d '{...}'
```
* Responses are cached for 24 hours per (user, key). Retried requests with the same key return the original response body with `X-Idempotent-Replay: true`.
* The key is at most 256 characters and must match `[A-Za-z0-9\-_.:]+`. Use a UUID, ULID, or your own deterministic request id.
* Two concurrent requests with the same key resolve to `409 idempotency_conflict` on the second caller — retry shortly.
* Idempotency is scoped per user, so keys can't collide across tenants.
## Errors
Errors return a structured JSON body:
```json theme={null}
{
"error": {
"message": "Invalid API key",
"type": "authentication_error",
"code": "invalid_api_key",
"request_id": "req_abc123"
}
}
```
| Status | Meaning |
| - | - |
| 400 | Bad request — invalid parameters |
| 401 | Unauthorized — missing or invalid API key |
| 403 | Forbidden — insufficient permissions |
| 404 | Not found |
| 422 | Unprocessable — the request was rejected by a policy on the key |
| 429 | Rate limited — check `Retry-After` header |
| 500 | Internal server error |
| 503 | Service unavailable — check `Retry-After` header |
Some errors carry a semantic `code` that reflects the key's orchestration (both the native and OpenAI-compatible endpoints apply it):
| Status | Code | Meaning |
| - | - | - |
| 400 | `context_length_exceeded` | Request is larger than any model on the key can hold |
| 403 | `model_not_allowed` | The resolved model is outside the key's model allowlist |
| 422 | `guardrail_violation` | A Gateway Guardrails policy on the key denied the request |
| 422 | `orchestrator_no_path` | The key's orchestrator graph couldn't resolve a path |
# Create Research
Source: https://docs.hitheo.ai/api-reference/research/create
POST /api/v1/research
Run deep web research with source synthesis (asynchronous).
Run deep web research with multi-source synthesis and citations. This is an **asynchronous** endpoint — it returns a job ID immediately (HTTP 202) and research is conducted in the background.
Research is async. Poll the job status with [Get Job Status](/api-reference/jobs/get) or use `theo.waitForJob()` in the SDK.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
The research question or topic.
Research depth. `"basic"` for quick summaries, `"advanced"` for comprehensive multi-source analysis.
Maximum number of sources to consult (1–50).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/research \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Compare React, Vue, and Svelte for enterprise apps in 2026",
"depth": "advanced",
"max_sources": 10
}'
```
```typescript SDK theme={null}
const job = await theo.research({
prompt: "Compare React, Vue, and Svelte for enterprise apps in 2026",
depth: "advanced",
max_sources: 10,
});
// Poll until complete (check every 3s, timeout after 2min)
const result = await theo.waitForJob(job.job_id, 3000, 120_000);
console.log(result.result); // Full research report with citations
```
## Response (HTTP 202)
Unique research request ID (prefixed `res_`).
Job ID for polling status.
Always `"queued"` on creation.
ISO 8601 timestamp.
Relative URL to poll for job status.
### Example Response
```json theme={null}
{
"id": "res_abc123",
"job_id": "job_xyz789",
"status": "queued",
"created": "2026-04-10T12:00:00Z",
"poll_url": "/api/v1/jobs/job_xyz789"
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_prompt` | `prompt` is required |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 503 | `queue_unavailable` | Research queue is not available — retry later |
# Create Skill
Source: https://docs.hitheo.ai/api-reference/skills/create
POST /api/v1/skills/create
Author a new skill (private by default).
Create a new skill. Skills are private by default — use [Submit Skill](/api-reference/skills/submit) to publish to the marketplace.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Human-readable skill name.
Unique identifier. Must be lowercase alphanumeric with hyphens (e.g., `"inventory-check"`).
Skill category. One of: `productivity`, `domain`, `integration`, `automation`, `creative`.
System prompt extension injected into the LLM context when this skill is active.
Short description of what the skill does.
Tool definitions the skill provides.
Whether the skill is publicly listed. Use [Submit Skill](/api-reference/skills/submit) for marketplace publishing with review.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/skills/create \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Inventory Check",
"slug": "inventory-check",
"category": "automation",
"system_prompt_ext": "You are an inventory specialist. Use check_stock to look up levels.",
"description": "Real-time inventory lookup and reorder alerts",
"tool_definitions": [
{
"name": "check_stock",
"description": "Look up current stock levels for a SKU",
"inputSchema": {
"type": "object",
"properties": { "sku": { "type": "string" } },
"required": ["sku"]
}
}
]
}'
```
```typescript SDK theme={null}
const skill = await theo.createSkill({
name: "Inventory Check",
slug: "inventory-check",
category: "automation",
system_prompt_ext: "You are an inventory specialist. Use check_stock to look up levels.",
description: "Real-time inventory lookup and reorder alerts",
tool_definitions: [
{
name: "check_stock",
description: "Look up current stock levels for a SKU",
inputSchema: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
},
},
],
});
```
## Response (HTTP 201)
The created skill object with all fields including the generated `id`.
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `validation_error` | Missing required fields or invalid slug format |
| 409 | `conflict` | A skill with this slug already exists |
# Get Skill
Source: https://docs.hitheo.ai/api-reference/skills/get
GET /api/v1/skills/{id}
Get details for a specific skill.
Retrieve full details for a skill by ID, including its manifest, install count, and review status.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Path Parameters
The skill UUID.
## Request Example
```bash theme={null}
curl https://www.hitheo.ai/api/v1/skills/skill_abc123 \
-H "Authorization: Bearer $THEO_API_KEY"
```
## Response
Returns the full skill object including `id`, `name`, `slug`, `description`, `category`, `version`, `systemPromptExt`, `toolDefinitions`, `declaredPermissions`, `installCount`, `reviewStatus`, `authorUserId`, `readme`, `license`, `keywords`, `createdAt`, and `updatedAt`.
## Endpoint
`GET /api/v1/skills/{id}`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Install Skill
Source: https://docs.hitheo.ai/api-reference/skills/install
POST /api/v1/skills
Install a marketplace skill for the authenticated user.
Install a skill from the marketplace. Once installed, the skill is automatically loaded on every completion request.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
UUID of the skill to install.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/skills \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"skillId": "skill_abc123"}'
```
```typescript SDK theme={null}
await theo.installSkill("skill_abc123");
```
## Response (HTTP 201)
```json theme={null}
{ "installed": true }
```
## Uninstall
To uninstall a skill, send a `DELETE` request with the same body:
```bash theme={null}
curl -X DELETE https://www.hitheo.ai/api/v1/skills \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"skillId": "skill_abc123"}'
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `validation_error` | Invalid `skillId` format (must be UUID) |
| 404 | `not_found` | Skill not found |
# List Skills
Source: https://docs.hitheo.ai/api-reference/skills/list
GET /api/v1/skills
List marketplace or installed skills.
List available skills. Filter by installed skills or browse the full marketplace.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Query Parameters
Filter skills. Options:
* `"installed"` — Only skills installed by the authenticated user
* `"marketplace"` — All public marketplace skills (default when omitted)
## Request Examples
```bash curl theme={null}
# List installed skills
curl "https://www.hitheo.ai/api/v1/skills?filter=installed" \
-H "Authorization: Bearer $THEO_API_KEY"
# Browse marketplace
curl https://www.hitheo.ai/api/v1/skills \
-H "Authorization: Bearer $THEO_API_KEY"
```
```typescript SDK theme={null}
// Installed skills
const installed = await theo.skills("installed");
// Marketplace
const marketplace = await theo.skills("marketplace");
```
## Response
Array of skill objects. Each includes `id`, `name`, `slug`, `description`, `category`, `version`, `installCount`, `isPublic`, and more.
### Example Response
```json theme={null}
{
"skills": [
{
"id": "skill_abc123",
"name": "Deep Research",
"slug": "deep-research",
"description": "Multi-step web research with citations and structured reports",
"category": "productivity",
"version": "1.2.0",
"installCount": 342,
"isPublic": true,
"authorUserId": "user_xyz"
}
]
}
```
# Skill Reviews
Source: https://docs.hitheo.ai/api-reference/skills/reviews
GET /api/v1/skills/{id}/reviews
Get and submit user reviews for a marketplace skill.
Get user reviews for a skill, or submit your own rating.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Path Parameters
The skill UUID.
## List Reviews (GET)
```bash theme={null}
curl https://www.hitheo.ai/api/v1/skills/skill_abc123/reviews \
-H "Authorization: Bearer $THEO_API_KEY"
```
Returns an array of review objects with `rating` (1–5), `body`, `authorUserId`, and `createdAt`.
## Submit a Review (POST)
Rating from 1 to 5.
Review text (max 2,000 characters).
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/skills/skill_abc123/reviews \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"rating": 5, "body": "Great skill, saves hours of work!"}'
```
## Endpoint
`GET /api/v1/skills/{id}/reviews`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Submit Skill
Source: https://docs.hitheo.ai/api-reference/skills/submit
POST /api/v1/skills/submit
Submit a skill manifest for marketplace review and publishing.
Submit a skill manifest for marketplace review. Automated checks run immediately, and the skill is either auto-approved or queued for manual review based on its risk tier.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
The full skill manifest object. See [Manifest Reference](/skills/manifest-reference) for all fields.
Existing skill UUID if this is a version update (not a new submission).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/skills/submit \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"manifest": {
"name": "Inventory Check",
"slug": "inventory-check",
"version": "1.0.0",
"description": "Real-time inventory lookup and reorder alerts",
"category": "automation",
"author": { "name": "Acme Corp" },
"systemPromptExtension": "You are an inventory management specialist...",
"tools": [],
"permissions": ["execute:tools"]
}
}'
```
```typescript SDK theme={null}
import { defineSkill } from "@hitheo/sdk";
const manifest = defineSkill({
name: "Inventory Check",
slug: "inventory-check",
version: "1.0.0",
description: "Real-time inventory lookup and reorder alerts",
category: "automation",
author: { name: "Acme Corp" },
systemPromptExtension: "You are an inventory management specialist...",
permissions: ["execute:tools"],
});
const result = await theo.submitSkill(manifest);
console.log(result.status); // "approved" or "pending_review"
console.log(result.reviewTier); // "auto", "staff", or "security"
```
## Response (HTTP 201)
Submission ID.`"approved"` or `"pending_review"`.Risk tier: `"auto"`, `"staff"`, or `"security"`.Whether the skill was auto-approved.Whether automated checks passed.Assigned review tier.Detailed check results.
### Risk Tiers
| Tier | Description |
| - | - |
| `auto` | Low-risk manifests that pass all automated checks — approved without human review. |
| `staff` | Manifests that introduce tools, knowledge files, or write-scoped permissions — reviewed by the Theo marketplace team. |
| `security` | Manifests that combine external network access with write capability or other sensitive surfaces — reviewed by the security team before publish. |
### Example Response (Auto-Approved)
```json theme={null}
{
"submission": {
"id": "sub_abc123",
"status": "approved",
"reviewTier": "auto",
"autoApproved": true
},
"review": {
"passed": true,
"tier": "auto",
"checks": { "schema": "pass", "injection_scan": "pass", "tool_names": "pass" }
}
}
```
## Errors
| Status | Code | Description |
| - | - | - |
| 422 | `review_failed` | Automated checks failed — `review.checks` contains details |
| 429 | `rate_limit_exceeded` | Submission rate limit exceeded — try again later |
# Skill Versions
Source: https://docs.hitheo.ai/api-reference/skills/versions
GET /api/v1/skills/{id}/versions
Get version history for a published skill.
Retrieve the version history for a published skill, including manifest snapshots and changelogs.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Path Parameters
The skill UUID.
## Request Examples
```bash curl theme={null}
curl https://www.hitheo.ai/api/v1/skills/skill_abc123/versions \
-H "Authorization: Bearer $THEO_API_KEY"
```
```typescript SDK theme={null}
const versions = await theo.skillVersions("skill_abc123");
```
## Response
Array of version records.
Version record ID.Semver version string.`"active"`, `"superseded"`, or `"withdrawn"`.Markdown changelog for this version.Full manifest at time of publication.ISO 8601 timestamp.
## Endpoint
`GET /api/v1/skills/{id}/versions`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Generate Video
Source: https://docs.hitheo.ai/api-reference/video/generate
POST /api/v1/video
Generate video from text prompts (asynchronous).
Generate video from a text prompt. This is an **asynchronous** endpoint — it returns a job ID immediately (HTTP 202) and the video is generated in the background.
Video generation is async. Poll the job status with [Get Job Status](/api-reference/jobs/get) or use `theo.waitForJob()` in the SDK.
**AI-disclosure watermark.** Every video returned from Theo carries a small, semi-transparent Theo logo in the bottom-right corner. This is a provenance signal that identifies the clip as AI-generated and is always applied (regardless of any branding preference). Expect +2–15 seconds of re-encode latency per clip.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Text description of the video to generate.
Target video duration (e.g., `"5s"`, `"10s"`, `"15s"`).
Visual style (e.g., `"cinematic"`, `"animation"`, `"timelapse"`).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/video \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A 5-second animation of a rocket launch",
"duration": "5s",
"style": "cinematic"
}'
```
```typescript SDK theme={null}
const job = await theo.video({
prompt: "A 5-second animation of a rocket launch",
duration: "5s",
style: "cinematic",
});
// Poll until complete
const result = await theo.waitForJob(job.job_id);
console.log(result.result); // Video URL
```
## Response (HTTP 202)
Unique video request ID (prefixed `vid_`).
Job ID for polling status.
Always `"queued"` on creation.
ISO 8601 timestamp.
Relative URL to poll for job status (e.g., `/api/v1/jobs/{job_id}`).
### Example Response
```json theme={null}
{
"id": "vid_abc123",
"job_id": "job_xyz789",
"status": "queued",
"created": "2026-04-10T12:00:00Z",
"poll_url": "/api/v1/jobs/job_xyz789"
}
```
## Polling for Results
Use the [Get Job Status](/api-reference/jobs/get) endpoint to check progress. When `status` is `"completed"`, the `result` field contains the video URL.
```bash theme={null}
curl https://www.hitheo.ai/api/v1/jobs/job_xyz789 \
-H "Authorization: Bearer $THEO_API_KEY"
```
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_prompt` | `prompt` is required |
| 401 | `invalid_api_key` | Missing or invalid API key |
| 503 | `queue_unavailable` | Video generation queue is not available — retry later |
# Create Workflow
Source: https://docs.hitheo.ai/api-reference/workflows/create
POST /api/v1/workflows
Create a multi-step automation workflow.
Create a workflow that chains AI tasks together with scheduling, event triggers, and conditional logic.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Body
Human-readable workflow name.
How the workflow is triggered. One of: `schedule`, `event`, `manual`.
Trigger-specific configuration (e.g., `{ "cron": "0 9 * * 1" }` for schedule triggers).
Ordered array of workflow steps. At least one step is required.
Step type (e.g., `"ai_transform"`, `"notification"`, `"http"`).Step name.Step-specific configuration.Index of the next step on success.Index of the next step on failure.
Whether the workflow is active.
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/workflows \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Weekly Pipeline Report",
"triggerType": "schedule",
"triggerConfig": { "cron": "0 9 * * 1" },
"steps": [
{
"type": "ai_transform",
"name": "Generate report",
"config": { "prompt": "Analyze this week's pipeline changes", "skills": ["data-extraction"] }
},
{
"type": "notification",
"name": "Send to team",
"config": { "channel": "email", "to": "team@acme.com" }
}
]
}'
```
```typescript SDK theme={null}
const workflow = await theo.createWorkflow({
name: "Weekly Pipeline Report",
triggerType: "schedule",
triggerConfig: { cron: "0 9 * * 1" },
steps: [
{
type: "ai_transform",
name: "Generate report",
config: { prompt: "Analyze this week's pipeline changes", skills: ["data-extraction"] },
},
{
type: "notification",
name: "Send to team",
config: { channel: "email", to: "team@acme.com" },
},
],
});
```
## Response (HTTP 201)
The created workflow object with generated `id` and timestamps.
## Errors
| Status | Code | Description |
| - | - | - |
| 400 | `missing_fields` | `name`, `triggerType`, and `steps` are required |
## Endpoint
`POST /api/v1/workflows`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Delete Workflow
Source: https://docs.hitheo.ai/api-reference/workflows/delete
DELETE /api/v1/workflows/{id}
Permanently delete a workflow.
## Authentication
Requires a Bearer token with `tools` scope. See [Authentication](/api-reference/authentication).
## Path Parameters
The workflow UUID.
## Response
```json theme={null}
{ "deleted": true }
```
## Example
```bash curl theme={null}
curl -X DELETE https://www.hitheo.ai/api/v1/workflows/wf_abc123 \
-H "Authorization: Bearer $THEO_API_KEY"
```
# Get Workflow
Source: https://docs.hitheo.ai/api-reference/workflows/get
GET /api/v1/workflows/{id}
Fetch a workflow's definition along with its most recent runs.
Returns the workflow object plus up to 20 recent runs.
## Authentication
Requires a Bearer token with `tools` scope. See [Authentication](/api-reference/authentication).
## Path Parameters
The workflow UUID.
## Response
The workflow definition: `id`, `name`, `triggerType`, `triggerConfig`, `steps`, `enabled`, timestamps.
Up to 20 recent runs, each with `id`, `status`, `startedAt`, and step results.
## Example
```bash curl theme={null}
curl https://www.hitheo.ai/api/v1/workflows/wf_abc123 \
-H "Authorization: Bearer $THEO_API_KEY"
```
# List Workflows
Source: https://docs.hitheo.ai/api-reference/workflows/list
GET /api/v1/workflows
List all workflows for the authenticated user.
Returns all workflows owned by the authenticated user, ordered by creation date.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Examples
```bash curl theme={null}
curl https://www.hitheo.ai/api/v1/workflows \
-H "Authorization: Bearer $THEO_API_KEY"
```
```typescript SDK theme={null}
const workflows = await theo.workflows();
```
## Response
Array of workflow objects with `id`, `name`, `triggerType`, `triggerConfig`, `steps`, `enabled`, `createdAt`, and `updatedAt`.
## Endpoint
`GET /api/v1/workflows`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Run Workflow
Source: https://docs.hitheo.ai/api-reference/workflows/run
POST /api/v1/workflows/{id}/run
Trigger a manual workflow run.
Manually trigger a workflow run, optionally passing override data.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Path Parameters
The workflow UUID.
## Request Body
Optional override data passed to the workflow steps (e.g., `{ "overridePrompt": "Focus on enterprise deals" }`).
## Request Examples
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/workflows/wf_abc123/run \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"triggerData": {"overridePrompt": "Focus on enterprise deals this week"}}'
```
```typescript SDK theme={null}
const run = await theo.triggerWorkflow("wf_abc123", {
overridePrompt: "Focus on enterprise deals this week",
});
```
## Response
The workflow run object with `id`, `status`, `startedAt`, and step results.
## Endpoint
`POST /api/v1/workflows/{id}/run`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Update Workflow
Source: https://docs.hitheo.ai/api-reference/workflows/update
PATCH /api/v1/workflows/{id}
Update a workflow's name, trigger, steps, or enabled state.
## Authentication
Requires a Bearer token with `tools` scope. See [Authentication](/api-reference/authentication).
## Path Parameters
The workflow UUID.
## Request
All fields are optional — include only what you want to change.
Display name for the workflow.
How the workflow is triggered (e.g., `manual`, `schedule`, `event`).
Trigger configuration (schedule expression, event pattern, etc.).
Ordered list of workflow steps.
Enable or disable the workflow.
## Response
The updated workflow object.
## Example
```bash curl theme={null}
curl -X PATCH https://www.hitheo.ai/api/v1/workflows/wf_abc123 \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "enabled": false }'
```
# Changelog
Source: https://docs.hitheo.ai/changelog
What's new in the Theo API, SDK, and channel adapters.
What's new across the Theo API, `@hitheo/sdk`, `@hitheo/mcp`, `@hitheo/telegram`, and `@hitheo/whatsapp`. We publish here when we ship something developers can use.
## Versioning Policy
* Packages follow [semver](https://semver.org). Pre-`1.0.0`, the **minor** bump is the breaking-change signal (matches how npm's `^` operator resolves `0.x.y`) — `^0.1.6` does not auto-upgrade to `0.2.0`.
* Additive changes (new endpoints, optional fields, new SDK methods) ship as minor or patch and never break pinned callers.
* The API surface at `https://www.hitheo.ai/api/v1/*` is dated, not path-versioned. The current version is `2026-03-28`, returned in the `Theo-Api-Version` header.
***
## 2026-10-15 — October release
### Added
* **Pick models by what you need them for.** Everywhere you choose a model — Model nodes, the Classifier, per-key engine and single-model settings, Routing Studio engine pins — a model picker opens with categories (text & chat, reasoning, code, vision, fast & cheap, long context, open models, your models) and a card per model showing what it's good at, its context window and its price per 1M tokens.
* **Newest models, cheaper defaults.** The latest Claude generation (Opus 5.5, Sonnet 5.5, Haiku 5.5) is available on every Model node, and Theo's defaults moved to it: quick modes now run on Haiku 5.5 (about 10× cheaper than before), deep reasoning on Opus 5.5 and coding/vision on Sonnet 5.5 — newer models at a lower price, no code changes needed. A wider catalog of open models (Kimi, Qwen, DeepSeek and more) can be offered on Model nodes too.
* **One model can handle several Classifier categories.** Click a Model node connected to a Classifier and tick every category it should take. A category belongs to one model at a time, so routing is never ambiguous.
* **A clear default model.** Mark any model as the default with one click — anything the Classifier can't place (no match, low confidence, an unconnected category) goes there. A **Default** badge shows it on the canvas, and turns red when nothing actually routes to it.
* **A roomier Classifier editor.** Categories, descriptions, example prompts, extra instructions, the classifying model and the confidence threshold are edited in a full-size editor instead of the narrow side panel.
* **`/v1/models` describes every model.** Each `catalog` entry now carries the `mode` it runs as and its `capabilities` (`chat`, `streaming`, `tools`, `vision`, `image_generation`, `video_generation`, `voice`, `browser`), so integrations can classify every Theo model id, including image sub-engines.
* **Orchestrator and Classifier in Chinese.** The Orchestrator canvas, Classifier and model pickers are now fully available in Simplified and Traditional (Hong Kong) Chinese.
* **Control whether the model thinks before answering.** A new `reasoning` option (`auto`, `on`, `off`) on `/v1/completions`, plus OpenAI's `reasoning_effort` on `/v1/chat/completions`, decides whether the model reasons before replying. `auto` follows a new **Reasoning** setting on each Model node in the Orchestrator, and otherwise the mode: on for `think` and `research`, off for quick modes like `fast`, so a simple question never pays for slow, expensive thinking.
* **Custom Classifier categories in the orchestrator.** Click a Classifier node to route by **your own categories** instead of Theo's built-in modes: give each category a name, a short description and a few example prompts, then connect each one to a model. Add extra instructions, pick which model does the classifying (including your own models), and set a confidence threshold so unsure prompts take the default branch. Start from a template (Simple vs complex, Support tickets, Insurance, Language), chain several Classifiers to route on more than one dimension, and test a prompt right in the node. The decision is returned in `routing.graph_classifications`. Classification is never billed to you, and Classifiers without categories work exactly as before.
* **OpenAI drop-in now accepts array-style message content.** `/v1/chat/completions` accepts `message.content` as both a plain string and an array of content parts (`[{ "type": "text", "text": "…" }]`), matching the OpenAI spec. Coding tools like **Warp** and **Cursor** — which send the array form — now work with Theo as a drop-in backend: just point them at your Theo base URL and key.
* **Your key's orchestration now governs the OpenAI drop-in too.** `/v1/chat/completions` now applies the **full per-key orchestrator** — Orchestrator graph, model pins, Gateway Guardrails, Routing Studio rules, the model allowlist, and the context-window guard — exactly like the native `/v1/completions`. A key you shape in the dashboard or via the MCP tools now behaves identically whether it's called through the OpenAI SDK or the native API. Practically: guardrails can deny a request (`422 guardrail_violation`), a model outside the key's allowlist is rejected (`403 model_not_allowed`), and an oversize request returns `400 context_length_exceeded`. Keys with no orchestration configured are unaffected — they keep routing on Theo's defaults.
* **`fast` and `think` run on Claude while Theo's in-house engines are brought online.** Theo Arca is temporarily offline; quick replies and deep reasoning are served by Claude with automatic failover. Your `fast` / `think` calls don't change.
* **Build your own executable orchestrator.** The per-key Orchestrator canvas is now a real, runnable graph. Draw the flow — Entry → Router / Classifier → Model → Guardrail — wire a branch per mode, and every prompt to that key runs exactly the path you drew, with routing, skills, guardrails, and brand all applied. Fresh graphs seed strong default models per mode. A live **Test chat** runs the staged canvas (unsaved edits included) and lights up the path each prompt takes; attach images or documents (PDF / DOCX / XLSX / CSV / TXT) to try vision and document flows, and the preview never draws credits.
* **Bring your own models.** Register a custom model endpoint (any compatible chat-completions API) in Orchestrator settings, then pick it on any Model node or in the Skill Builder — that key runs on your own endpoint. Prompts to your own models are free and never draw credits. You can optionally declare each custom model's **context window** so oversize requests are caught before they reach your endpoint.
* **Large requests route to a large-context model — transparently.** When a prompt (plus history and injected context) is too big for the engine your orchestrator resolved, Theo reroutes it to the smallest model on that key that can actually hold it, and marks the reroute in the response's tool trace so it's visible. It only ever picks a model your key is already allowed to use — never a hidden failover on a different price — so a request is never silently promoted onto a costlier engine. If nothing on the key is large enough (for example a key pinned to a single small-context model), Theo returns an OpenAI-compatible `400 context_length_exceeded` up front, with the approximate token count and your largest available window, instead of an opaque downstream failure. Add a larger-context model to the orchestrator, or shorten the request.
* **Custom modes.** Create your own routing modes (for example `jokes` or `pets`) in Routing Studio and use them as routing-rule targets or as the mode a graph node handles, alongside the built-in modes.
* **Independent guardrails per checkpoint.** Each Guardrail node in a graph binds its own policy, so different points in the flow can enforce different rules — an injection check on the way in, a redactor on the way out.
* **Image and video in the orchestrator graph.** Add media branches and choose the generation engine per node, so one key can route text, image, and video prompts through a single graph.
* **Orchestrator goes fullscreen.** A new `⛶ Fullscreen` button on the Orchestrator toolbar promotes the entire surface — toolbar, test prompt, canvas, and the skills tray — into a viewport-spanning workspace. Esc or clicking the button again exits. Clicking any "↗ Open in Routing Studio / Guardrails / Skills" link inside a drawer drops fullscreen so you land cleanly on the linked page.
* **Test prompt lights up the whole path, not just the arrows.** Every node the prompt passes through (entry → rules or classifier → category → mode → model → guardrails) now glows cyan in lockstep with the animated edges, so the trail reads as one continuous signal you can follow at a glance.
* **Orchestrator — your own per-key control surface.** New dashboard page at `/dashboard/orchestrator` (and a sidebar entry under BUILD). Pick one of your API keys and shape its orchestration on a single canvas: add routing rules that route keywords to a specific Theo mode, attach the skills the key may call, bind a Guardrails policy, and overlay your brand identity. Saved changes show up on the canvas immediately — your rules render as arrows landing on the target mode pill, your skills appear as chips, your guardrails sit as a terminal node after the models. A **Test prompt** input above the canvas resolves any prompt against the current configuration (rules-only or full classifier) and highlights the path it would take. A **Quick start** banner offers three opinionated preset packs (Customer Support, Code Assistant, Research Assistant) to seed routing rules + brand identity in one click. Existing Routing Studio sets are pickable from the routing drawer, so a shared preference can drive multiple keys without copy/paste.
* **Embed widget voice mode is fully brand-aware.** Open voice in your widget and visitors see your logo and brand name in the header, an orb that glows in your primary color while it listens and speaks, transcripts that match your text-chat bubbles, and a clean controls bar in your theme — every surface a visitor touches in voice mode now matches the brand you set in the iframe builder. The previous shared playground UI has been retired from the embed surface.
* **Brand-scoped responses on embed widgets.** Turn on the new **Scope responses to this brand** toggle on any API key and Theo stays inside that brand's catalog — it recommends only your own products and content, never names or compares to competitors (not even as analogy or style reference), and politely redirects off-topic requests back to your support URL. The toggle flips on automatically when you use Fetch Brand in the iframe builder, so importing a brand is a single click to get an end-to-end brand-locked assistant.
* **Rich responses in embed widget chats.** Theo's replies inside iframe widgets now render formatting visually — inline brand-logo images, headings, lists, tables, code blocks, links — instead of leaking the underlying Markdown as raw text. Styling matches your widget theme (heading and link colors follow your primary color, code blocks pick up your bubble background).
### Improved
* **Redesigned dropdowns.** Every dropdown in the dashboard now matches the rest of the app — with descriptions, icons and grouped options, and full keyboard support.
* **Roast mode runs on a faster, cheaper engine** and is billed at that engine's real price.
* **Claude requests are billed at their real price.** Claude Opus 4.8, Sonnet 4.6 and Haiku 4.5 were missing from the price table and billed at a flat Opus-level rate; they now cost their own list price plus the standard margin, so Sonnet and Haiku turns are noticeably cheaper.
* **Top-up checkout shows the service fee up front.** When you add funds, the dashboard now shows a clear breakdown — deposit, 5% service fee, and the total you'll be charged — before you're sent to checkout, so the amount is never a surprise. Only the deposit is credited to your balance.
* **MCP `theo_code` and `theo_complete` finish app-sized generations.** Both tools now **stream** instead of making a single blocking call, so a large artifact (a full single-file web app, a multi-file module) is no longer cut off at \~30 seconds. Streaming falls back to the original call if a stream can't start, so behavior is never worse than before. The connect / time-to-first-byte budget is configurable via `THEO_TIMEOUT_MS` (default `120000`), and the server emits progress heartbeats every 5s so an MCP client that resets its request timeout on progress can run arbitrarily long generations past the \~60s JSON-RPC default. Requires `@hitheo/mcp@0.3.1`. See [MCP troubleshooting](/mcp/troubleshooting).
* **Engines that aren't live yet show as WIP.** In the Orchestrator graph and the per-key model pickers, an engine that's still being brought online (currently Theo Arca) appears with a `(WIP)` label and is disabled — so you always pick from engines that are ready to serve traffic. Keys already routing through it fall through to their configured fallback with no interruption.
* **Brand auto-fill in the iframe builder reaches more domains.** Paste a marketing subdomain like `os.example.com` and the importer retries against your root `example.com` if the precise subdomain has no indexed data, so the import succeeds where it used to silently return empty. The result card surfaces the canonical brand source so you can see exactly where the data came from.
* **Brand auto-fill tells you why an import didn't succeed.** When a fetch returns no brand data, an unconfigured provider, or an invalid URL, you see an inline message under the input with the specific reason. No more silent clicks.
* **Brand auto-fill shows your imported brand the moment it's ready** instead of waiting for the screenshot capture in parallel. A failed fetch surfaces its reason in under two seconds; a successful fetch populates the brand fields immediately and lets the screenshot land separately when it finishes.
* **Iframe builder Fetch Brand updates the API key's Brand Soul too.** A successful brand import now imports the brand identity onto the linked API key — name, tagline, logo, colors, ethos, industry, and support URL — so the visitor-facing assistant introduces itself as your brand from the very first message, not just the widget chrome.
* **Embed widget Brand Soul applies on every turn — including voice and pre-chat lead form flows.** The brand identity you configure on an API key (name, tagline, tone, ethos, CTA, support URL) drives how the widget greets visitors and answers "who are you?" on every channel, end to end.
* **Team API keys now work in the widget builder.** If your team shares an API key through an organization, you can now select it when creating a chat widget. Personal keys and team keys both appear in the same picker and both bind cleanly.
* **Clearer errors when a widget can't be created.** The Create Widget button now tells you why if the request fails — invalid key, validation issue, billing state — instead of a generic placeholder.
* **Embed chat input handles long content gracefully.** The chat textarea grows with the visitor's message, wraps very long URLs or unbroken text instead of pushing the send button off-screen, and never collapses to a single line on multi-line replies.
* **Ask Theo in the canvas editor** — small Theo icon next to every text field in the Skill Builder (Prompt, Tool, Vision, Output, Condition, Webhook, Web Knowledge nodes, plus the Publish dialog blurb). Click it and Theo reads your live canvas, then streams a context-aware suggestion into the field as you watch. The Prompt builder's Theo Assist menu now leads with **Write from Scratch** — generate a fresh, validator-compliant system prompt with the right role + constraints + runtime template variables, all inferred from your canvas. The five existing actions (Enhance, Rewrite, Simplify, Add Examples, Make Concise) follow underneath in the same menu so you have one Theo entry point per field.
* **Per-key skills picker** — new **Skills** pill on every API key in your dashboard. Click to choose exactly which of your installed skills that key may call. New skills you publish or install later won't auto-attach — you stay in control of every key's capability surface.
* **Per-skill keys picker** — inverse view inside any installed skill's detail panel (My Skills → click a skill). Tick which of your API keys can call this skill without leaving the skill view.
* **"Enable on which keys?" step at publish time** — the Publish dialog now ends with an explicit picker so you choose which keys see your new skill. Default is nothing checked — opt in per key, or skip entirely and add later from the Skills or Keys pages.
* **Gateway Guardrails** — opt-in input/output policies enforced on every completion bound to an API key. Five built-in protections (PII redactor, prompt-injection deny, JSON repair, max-length truncate, profanity flag) with five verdicts (flag, redact, truncate, repair, deny). Enforcement is unified across `/v1/completions` (streaming and non-streaming), `/v1/images`, `/v1/code`, `/v1/documents`, the playground, and embed widgets. SDK adds `theo.guardrails.policies`, `theo.guardrails.presets`, `theo.guardrails.executions`, and `theo.keys.{get,set}GuardrailPolicy()`. New error code `guardrail_violation` (HTTP 422) on deny verdicts. See the [Guardrails guide](/guides/guardrails).
* **Routing Studio** — per-customer routing preferences with a visual editor, preset gallery, keyword rules, few-shot examples, and per-mode confidence-floor overrides. API at `/api/v1/routing-preferences` with full CRUD plus a `/test` endpoint that replays a fixture prompt before and after the preference. Per-key binding at `/api/v1/keys/{id}/routing-preference`. Streaming `meta` and `done` events surface `routing.customer_preference` whenever a bound preference contributes. SDK adds `theo.routingPreferences.*` and `theo.keys.{get,set}RoutingPreference`. See the [Routing Studio guide](/guides/routing-studio).
* **Playground routing receipt** — every assistant turn renders an inline receipt below the model badge, surfacing the routing decision behind each response. Compact view shows requested → resolved mode and a Promoted chip when routing overrode the caller's choice. Expand for classification confidence, skill overrides, locked family, and the four-stage pipeline visual. A green **Studio** chip lights up when a Routing Studio preference contributed.
* **SDK `theo.verify()`** — first-run connectivity and auth diagnostic. Returns `{ healthy, authenticated, baseUrl, latencyMs }` with actionable hints for common setup states.
* **CLI `theo verify`** — machine-readable JSON output for the same diagnostic. Non-zero exit on failure so CI can gate on it.
* **SDK `TheoStream`** — `theo.stream(...)` returns an async-iterable with a `cancel()` method for graceful mid-generation abort, plus final-metadata properties (`conversationId`, `usage`, `model`, `requestId`) populated from the `meta` and `done` events.
* **Discriminated `StreamEvent` union** — `switch (event.type)` narrows `event.data` automatically. No `as any` needed.
* **Typed SDK list and get returns** — `conversations()`, `skills()`, `tools()`, `workflows()`, `submissions()`, `listWebhooks()`, `listHooks()`, `usage()`, and their mutation pairs now return named interfaces (`ConversationSummary`, `SkillSummary`, `WorkflowRecord`, etc.) instead of `unknown[]`.
* **`CompletionRequest` extensions** — `conversation` (inline envelope), `personality_config`, `response_style`, `theo_branding`, `brand_soul`, `attachments`, `image_model`, `image_quality`, `stealth_model`, `stealth_aspect`, `stealth_duration`.
* **Idempotency-Key support** — state-changing POSTs across `/workflows`, `/skills`, `/webhooks`, `/hooks`, `/events`, `/evi/canvases`, `/iframes`, `/browser/sessions` accept the `Idempotency-Key` header. Responses cached 24 hours per key.
* **`request_id` in JSON responses** — `/completions`, `/images`, `/video`, `/code`, `/research`, `/documents`, `/audio/stt` surface the request id as a top-level field in addition to the existing response header.
* **`conversation_id` in stream events** — the `meta` and `done` events on `/completions` include `conversation_id` so clients don't have to read it separately.
* **[Follow-ups documentation](/core-concepts/follow-ups)** — concept page covering when `follow_ups[]` is generated and chat-UI integration patterns.
* **Full SSE schemas published** — [Streaming Completions reference](/api-reference/completions/streaming) now publishes TypeScript interfaces for every event (`meta`, `token`, `tool`, `artifact`, `genui_meta`, `skills`, `done`, `error`).
* **Cross-session memory** — Theo now carries relevant context across conversations and channels automatically. New threads can open with a short, relevant recap of prior related work, and Theo tracks open loops so later follow-ups resume where you left off. Memory is scoped per owner and is never used to train models. See [Conversations & Memory](/core-concepts/conversations-memory).
* **Embed widget operator tools** — embedded chat widgets now support live human takeover, a full analytics view (sessions, leads, conversion, geo), and lead capture with CSV export. List sessions, read transcripts, take over or release a conversation, and post operator messages under `/api/v1/iframes/{id}/conversations`. See the [Embed Widget guide](/guides/embed-widget).
### Improved
* **API key skill bindings are explicit-only.** When you create a new API key, it starts with zero skills callable. You decide which skills it can use, when you want them on it. Existing keys' current capability sets are preserved during the migration — your apps keep working without any change on your side.
* **Prompt Builder writes validator-compliant prompts on the first try.** The new **Write from Scratch** action knows the canvas validator's requirements (role definition, explicit constraints) and the available runtime template variables (`{{user_name}}`, `{{user_input}}`, `{{current_date}}`, `{{language}}`, `{{skill_name}}`) so the generated prompt passes validation immediately, without a second round of editing.
* **Auto-resizing description fields on Tool and Output nodes.** Descriptions grow vertically as you type — or as Ask Theo streams in — so long capability summaries stay fully visible instead of clipping at one line.
* **Document generation reliability and chrome.** PDF / DOCX / CSV / PPTX / XLSX generation produces a properly rendered file in the playground, with a clean download card under the assistant reply (format badge, file size, click to download). Error messages on the rare retry path stay vendor-neutral and on-brand.
* **Toolbar tightened on the canvas editor.** The **▶ FULL** shortcut (open the published version in the main Playground) now only renders once the canvas has actually been published, so the toolbar reads as a clean `TEST → COMPILE → PUBLISH` pipeline until it has a destination to open.
* **SDK default `baseUrl` is now `https://www.hitheo.ai`.** Pin `baseUrl` explicitly if you target a different host.
* **MCP server default `THEO_BASE_URL` is now `https://www.hitheo.ai`.**
* **`CompletionResponse.usage` includes `prompt_tokens`, `completion_tokens`, `total_tokens`, and an optional `cached` flag.** `cached: true` is present on responses served from the semantic cache.
* **`theo status` CLI** probes both `hitheo.ai` and `www.hitheo.ai` and warns when the configured `baseUrl` is a redirect target.
* **SSE `error` event envelope matches the REST error envelope** — `{ error: { message, type, code, request_id } }`. One error-handling code path for REST and streaming.
* **Optional fields accept `null`** across `/completions`, `/chat/completions`, `/conversations`, `/playground/completions`, `/events`, `/images`, `/video`, `/code`, `/research`, `/documents`, `/audio/tts`. Matches the industry norm of treating `null` as "field omitted."
* **`EviInstance.stream()`** returns a `TheoStream`. `for await` continues to work unchanged; `.cancel()` and final metadata are now available.
### Fixed
* **Normal replies are no longer replaced by `{}`.** On keys whose guardrail policy includes **JSON repair** (for example the Enterprise default policy), a regular text reply could stream correctly and then be swapped for an empty `{}`. JSON repair now only touches responses that are actually meant to be JSON, and never replaces real content with an empty object.
* **Guardrails run only where your orchestrator has them.** With the Guardrails stage turned off, no guardrail runs. On a key with a custom graph, only the graph's own Guardrail nodes screen the prompt and the response — an output check runs only when a Guardrail node sits after the answering model.
* **Theo Reason and Theo Flash no longer pivot to PDF generation on text requests.** Calls to `/api/v1/chat/completions` and `/api/v1/completions` always return reasoning text now, even when your prompt happens to mention words like "report", "memo", "brief", "PDF", "docx", or "presentation". The previous behavior silently hijacked your request into document generation, then either timed out or returned a "couldn't generate your PDF" message — breaking OpenAI-SDK consumers that expect `choices[].message.content`. Document generation through the chat API is no longer inferred from prompt phrasing — if you want a document, use the dedicated `/api/v1/documents` endpoint.
* **Document generation produces real downloads again.** PDFs, DOCX files, PowerPoint decks, Excel sheets, and CSVs from `/api/v1/documents` and the playground now reliably render and surface a working `download_url`. The previous failure modes (a canned "Theo couldn't generate your PDF document" reply or a 504 timeout after \~90 seconds) are gone, and a slow upstream now falls through to a placeholder artifact instead of timing out the request.
### Migration
* **Keys with a custom orchestrator graph:** the key-wide guardrail policy no longer screens around a graph that has no Guardrail node. If you relied on it, add a Guardrail node to the graph (before the model to screen prompts, after it to screen responses).
Most callers need only `npm update @hitheo/sdk`. See the upgrade guide bundled with the SDK README.
***
## \[0.3.0] — 2026-06-01
### Added
* **SDK `streamIdleTimeoutMs` config** (default 120s) — streaming responses use an idle (between-chunks) timeout instead of a total-duration cap, so a long but actively-producing stream is never severed mid-flight.
* **New SDK error types** — `TheoTimeoutError` (carries `timeoutMs`) and `TheoCancelledError`, plus a `kind` discriminator (`"http" | "timeout" | "cancelled" | "network"`) on `TheoApiError`. `TheoUsageError` is thrown synchronously for SDK misuse. All subclasses remain `instanceof TheoApiError`.
* **Typed async job results** — `JobStatus` is generic with `ResearchJobResult`, `VideoJobResult`, `ImageJobResult`, `DocumentJobResult`; `job()` and `waitForJob()` are generic.
* **`waitForJob` options object** — `{ intervalMs, maxWaitMs, signal, onProgress }` adds a progress callback and `AbortSignal` cancellation. The legacy positional `(id, intervalMs?, maxWaitMs?)` signature still works.
* **SSE parser tolerance** — `event:` / `data:` lines are accepted with or without the trailing space.
* **New docs** — [Timeouts & Retries](/sdk-reference/timeouts-and-retries) and [Async Jobs](/guides/async-jobs).
### Improved
* **`GET /api/v1/jobs/{id}` result is sanitized** — completed video/image jobs expose Theo-branded `model` / `engine` instead of raw upstream `providerId` / `modelId`.
* **OpenAI-compatible base URL** is documented consistently as `https://www.hitheo.ai/api/v1`.
* **Timeouts are no longer retried on non-idempotent POSTs** (`complete`, `research`, `video`) — eliminates the double-run / double-bill risk on slow generations. A timeout now throws `TheoTimeoutError` instead of a generic `TheoApiError(0)`.
* **Async modes fail fast** — passing `mode: "research" | "video"` to `complete()` / `stream()` throws `TheoUsageError` immediately instead of hanging until the request timeout.
### Migration
* If you matched the `waitForJob` polling timeout via `err.status === 408`, switch to `err instanceof TheoTimeoutError` (`status` is now `0`, `kind: "timeout"`).
* If you ran `research` / `video` through `complete()` / `stream()`, move to `theo.research()` / `theo.video()` + `theo.waitForJob()`. See [Async Jobs](/guides/async-jobs).
***
## \[0.1.6] — 2026-04-17
### Added
* **Theo Browser SDK** — `@hitheo/sdk` exposes `theo.browser.*` wrapping the managed headless-browser API (`POST /api/v1/browser/sessions`, live-view refresh, snapshot, end). See [Theo Browser (API)](/api-reference/browser/sessions) and [Theo Browser (SDK)](/sdk-reference/browser).
* **Embed-ready Theo Browser iframe** — every new session includes an `embed_url` third-party apps can drop into an iframe without building UI. Short-lived signed token; auto-refresh on disconnect.
* **Branded TTS voice identifiers** — `POST /api/v1/audio/tts` now accepts `theo-voice-classic`, `theo-voice-bright`, `theo-voice-storyteller`, `theo-voice-deep`, `theo-voice-warm`, `theo-voice-soft`.
### Improved
* **`GET /api/v1/benchmarks` is now an authenticated endpoint.** Responses include `Cache-Control: private`.
***
## \[0.1.5] — 2026-04-17
### Improved
* Published READMEs across every `@hitheo` package on npm refreshed to reflect the current runtime surface, with upgrade guidance for older releases.
***
## \[0.1.4] — 2026-04-17
### Added
* **Signed GitHub provenance attestations** on every published npm tarball. Verify with `npm audit signatures @hitheo/sdk @hitheo/mcp @hitheo/telegram @hitheo/whatsapp`.
***
## \[0.1.3] — 2026-04-16
### Improved
* **Consistent Theo-branded surface** across documentation, SDK, and channel adapters.
***
## \[0.1.2] — 2026-04-15
### Added
* **API reference expansion** — new sections for Webhooks (create, list, update, delete, test, deliveries, retry, rotate-secret, stats), Hooks (create, list), Iframes (create, list), Settings (get, update), Benchmarks (get), and Skill Builder.
* **New guides** — [Skill Builder](/guides/evi-canvas), [Voice Integration](/guides/voice-integration), [Embed Widget](/guides/embed-widget), [Webhooks & Hooks](/guides/webhooks-and-hooks), [Skills API](/guides/skills-api).
* **SDK reference** — new [`sdk-reference/canvases`](/sdk-reference/canvases) page.
### Improved
* `@hitheo/mcp`, `@hitheo/telegram`, `@hitheo/whatsapp` now ship with full READMEs on npm.
* `@hitheo/sdk` README security guidance refreshed — points readers at per-key `allowed_origins` and the [Security docs](/security/authentication).
***
## \[0.1.1] — 2026-04-15
### Added
* **Skill Builder SDK methods** — `canvases`, `canvas`, `createCanvas`, `updateCanvas`, `deleteCanvas`, `compileCanvas`, `testCanvas`, `publishCanvas`.
* **Webhooks SDK methods** — `listWebhooks`, `createWebhook`, `updateWebhook`, `deleteWebhook`, `testWebhook`, `webhookDeliveries`.
* **Hooks SDK methods** — `listHooks`, `createHook`, `updateHook`, `deleteHook`, `hookExecutions`.
* **Events SDK** — `publishEvent`.
* **`@hitheo/telegram`** — attachment support (photo, voice, audio, document), pluggable conversation store, `X-Telegram-Bot-Api-Secret-Token` verification, chunked replies.
* **`@hitheo/whatsapp`** — media handling, HMAC `X-Hub-Signature-256` verification (`verifySignature`, `verifyWebhook` helpers), conversation store, chunked replies.
* **`@hitheo/mcp`** — tool catalog refresh, project-config loader (`theo.config.json|js|ts`).
***
## \[0.1.0] — 2026-04-15
### Added
* **First npm release** under the `@hitheo` scope: [`@hitheo/sdk`](https://www.npmjs.com/package/@hitheo/sdk), [`@hitheo/mcp`](https://www.npmjs.com/package/@hitheo/mcp), [`@hitheo/telegram`](https://www.npmjs.com/package/@hitheo/telegram), [`@hitheo/whatsapp`](https://www.npmjs.com/package/@hitheo/whatsapp).
* All packages are pure ESM with TypeScript declarations.
* CLI available globally via `npm install -g @hitheo/sdk` → `theo init`.
### Documentation
* Published comprehensive docs at [docs.hitheo.ai](https://docs.hitheo.ai).
* Full API reference with OpenAPI 3.1 spec.
* SDK, CLI, and MCP reference guides.
* Skills deep dive with marketplace authoring guide.
* 10+ guides covering E.V.I., IDE integration, workflows.
***
## \[API v1] — 2026-03-28
### Added
* Core completions API with multi-model routing.
* Skill marketplace with automated review pipeline.
* E.V.I. (Embedded Virtual Intelligence) support.
* SDK (`@hitheo/sdk`), CLI, and MCP server (`@hitheo/mcp`).
* Channel adapters for Telegram and WhatsApp.
* Workflow automation with schedules and event triggers.
* Image, video, code, research, and document generation.
* Audio TTS and STT.
* Per-token billing with credit system.
# Agent Loop & Tool Execution
Source: https://docs.hitheo.ai/core-concepts/agent-loop
How Theo executes multi-step tool calls in an iterative loop.
When tools are available (from skills, connectors, or inline definitions), Theo enters an iterative agent loop where the model can reason, call tools, observe results, and continue until the task is complete.
## How It Works
```
Iteration 0: LLM reads prompt + system prompt + tool definitions
→ Responds with text AND a tool call:
{"tool": "check_stock", "arguments": {"sku": "ABC123"}}
→ Theo executes the tool, gets result
Iteration 1: LLM reads the tool result + previous context
→ Responds with text (no more tool calls)
→ Final response returned
```
## Configuration
You can control how many iterations the agent loop runs per request via the `max_iterations` parameter:
```typescript theme={null}
const res = await theo.complete({
prompt: "Check stock and reorder if low",
tools: [/* ... */],
max_iterations: 4, // Limit to 4 tool calls
});
```
## Tool Sources
Tools can come from three sources, all merged into a single available set:
1. **Skill tools** — Defined in installed/per-request skill manifests
2. **Inline tools** — Passed directly on the completion request via `tools[]`
3. **Built-in tools** — Theo's system tools (web search, code execution, etc.)
## Inline Tool Example
```typescript theme={null}
const res = await theo.complete({
prompt: "Look up the customer and update their email",
tools: [
{
name: "lookup_customer",
description: "Search CRM for a customer by name or ID",
input_schema: {
type: "object",
properties: {
query: { type: "string" },
},
required: ["query"],
},
},
{
name: "update_customer",
description: "Update a customer field",
input_schema: {
type: "object",
properties: {
customer_id: { type: "string" },
field: { type: "string" },
value: { type: "string" },
},
required: ["customer_id", "field", "value"],
},
},
],
});
```
## Tool Execution in Response
The `tools_used` array in the response shows which tools were called:
```json theme={null}
{
"tools_used": [
{ "name": "lookup_customer", "status": "success" },
{ "name": "update_customer", "status": "success" }
]
}
```
## Guard Rails
* **Iteration limit** — prevents runaway loops (configurable per request)
* **Credit checkpoint** — verifies sufficient balance before each iteration
* **Timeout** — configurable per request via SDK `timeoutMs`
* If the engine hits the iteration limit, Theo forces a final synthesis response
# Conversations & Memory
Source: https://docs.hitheo.ai/core-concepts/conversations-memory
Multi-turn conversations with cross-session memory.
Theo maintains conversation history so the model has context from previous turns. Pass a `conversation_id` to continue an existing conversation.
## Starting a Conversation
The first request creates a new conversation automatically:
```typescript theme={null}
const res = await theo.complete({
prompt: "I'm building a SaaS for project management. Help me plan the tech stack.",
});
// Save the conversation ID for follow-ups
const conversationId = res.metadata?.conversation_id;
```
## Continuing a Conversation
Pass the `conversation_id` to maintain context:
```typescript theme={null}
const followUp = await theo.complete({
prompt: "What database should I use for this?",
conversation_id: conversationId,
});
// → Theo knows you're talking about a project management SaaS
```
## Conversation API
### List Conversations
```bash theme={null}
curl https://www.hitheo.ai/api/v1/conversations \
-H "Authorization: Bearer $THEO_API_KEY"
```
### Get a Conversation
```bash theme={null}
curl https://www.hitheo.ai/api/v1/conversations/{conversationId} \
-H "Authorization: Bearer $THEO_API_KEY"
```
Returns the full message history with metadata.
## How Theo Remembers
Beyond the verbatim turns in a single conversation, Theo runs a memory protocol (MCIR) that lets it carry relevant context across sessions — automatically, with no manual tagging.
* **Automatic capture.** Facts, preferences, decisions, and unresolved questions are captured as they come up in normal conversation.
* **Relevance-first recall.** Only memories relevant to your current request are surfaced — recall is scoped to what you're asking, not a plain keyword match.
* **Per-owner scoping.** Memory is isolated to the right owner (user, account, or organization). One tenant's memory is never visible to another.
* **Freshness & decay.** Stale or superseded memories lose weight over time and are revalidated before they influence a response, so old context doesn't linger forever.
* **Durable user facts.** Anything a user explicitly declares as a standing fact is preserved and exempt from decay.
* **Provenance.** Every memory the model uses is traceable to where it came from.
You don't call a separate API for this — it applies to every completion automatically. Pass `conversation_id` to keep turns linked within a thread; cross-thread recall happens on its own when prior context is relevant.
## Proactive Recall & Open Loops
When you start a new conversation, Theo can proactively surface a short, relevant summary of prior related threads instead of starting cold. It also tracks **open loops** — unresolved questions or tasks — so a later follow-up can pick up where you left off.
## Cross-Channel Memory
Theo's memory is **channel-agnostic**. Whether a user interacts via the API, the web playground, a voice session, an embedded widget, or a channel adapter, Theo carries context across all of them. Continuity follows the user, not the surface.
## Privacy
Theo does not train models on your memory. Memory is scoped per owner with tenant isolation, and user-declared facts can be marked durable. See [Data Privacy](/security/data-privacy) for retention details.
## Semantic Cache
Identical prompts (same text, same mode, same skills) hit the semantic cache and return instantly at zero cost. Cache hits are marked in the response metadata.
# Follow-Ups
Source: https://docs.hitheo.ai/core-concepts/follow-ups
How Theo generates suggested next prompts and how to render them in a chat UI.
Every Theo completion returns a `follow_ups: Array<{ label, prompt }>` field. These are AI-generated, mode-aware suggestions for the next turn — ready to drop into a chat UI as suggestion chips.
## When follow-ups are generated
* On **every text-mode completion** (`auto`, `fast`, `think`, `code`, `research`, `roast`, `genui`, `vision`, stealth text variants).
* On **image / video / document** turns — follow-ups tend to be edit/variation prompts ("Try a wider aspect ratio", "Make the background lighter").
* **Not** on `stt` (speech-to-text) or `tts` (text-to-speech) responses — there's no natural next turn.
The server returns between 0 and 3 follow-ups per response. Empty arrays are possible for terse answers, errors, or when Theo has nothing useful to suggest.
## Shape
```typescript theme={null}
interface FollowUp {
/** Short label suitable for a UI chip (max ~60 chars). */
label: string;
/** Full prompt to send on click — safe to use as-is in the next request. */
prompt: string;
}
```
`label` is the user-visible text on the chip. `prompt` is what you submit as the next `prompt` field when the user clicks it. The two are usually different — `label` is a short imperative, `prompt` is a fully-formed instruction that picks up where the last turn left off.
## How they're generated
Theo passes the turn's content, tools used, and any artifacts into a lightweight follow-up generator that runs after the main completion. The suggestions are AI-generated, not rules-based, so quality varies with the model tier — `think` mode produces better follow-ups than `fast`. There is no "follow-up cost" line item; the generator piggybacks on the same LLM call.
## Rendering in a chat UI
A minimal React pattern: chip row rendered below the last assistant bubble.
```tsx theme={null}
{assistantMessage.follow_ups?.length ? (
{assistantMessage.follow_ups.map((f) => (
))}
) : null}
```
* Render the chips **after** the full message is displayed. For streaming responses, `follow_ups` only appears on the `done` event, so wait for it before rendering.
* When the user clicks a chip, send `prompt` verbatim as the next `prompt`. Do NOT concatenate it with the user's own input — the prompts are self-contained.
* Hide the chip row once the user starts typing a new message, then re-show the next turn's chips on completion. This matches the pattern most production chat UIs use.
## Streaming
For streaming completions, follow-ups appear on the `done` event:
```typescript theme={null}
for await (const event of stream) {
if (event.type === "done") {
setFollowUps(event.data.follow_ups);
}
}
```
See [Streaming Completions](/api-reference/completions/streaming) for the full event schema.
## Opting out
If follow-ups clutter your UI, simply ignore the field. There is no per-request toggle \u2014 it is cheap enough to always generate, and some callers (voice, analytics) read it even when it isn't rendered.
# Intent Classification & Modes
Source: https://docs.hitheo.ai/core-concepts/intent-classification
How Theo determines the best execution mode for each request.
When you send `mode: "auto"` (the default), Theo classifies your prompt to determine the optimal execution mode. You can also set the mode explicitly to skip classification entirely.
## Available Modes
|| Mode | Description | Engine |
||------|-------------|--------|
|| `auto` | Theo classifies automatically | Varies by classification |
|| `fast` | Quick responses, simple tasks | `theo-1-flash` |
|| `think` | Deep reasoning, complex analysis | `theo-1-reason` |
|| `code` | Code generation and engineering | `theo-1-code` |
|| `image` | Image generation | `theo-1-create` |
|| `video` | Video generation (async) | `theo-1-motion` |
|| `research` | Web research with citations (async) | `theo-1-research` |
|| `roast` | Humorous, unfiltered responses | `theo-1-edge` |
|| `genui` | Generative UI components | `theo-1-genui` |
## Classification Process
### How Classification Works
Theo uses a multi-tier classification system. Obvious signals are caught instantly:
* `"Draw me a logo"` → `image`
* `"Write a React component"` → `code`
* `"Research the latest AI news"` → `research`
Ambiguous prompts are analyzed more deeply. The classifier returns:
```json theme={null}
{ "mode": "think", "confidence": 0.92, "reasoning": "Complex analytical question requiring deep reasoning" }
```
### Explicit Override
Pass `mode` directly to skip classification:
```typescript theme={null}
const res = await theo.complete({
prompt: "Write a REST API for user management",
mode: "code", // Skips classification entirely
});
```
## Mode Selection in the Response
Every response includes both the requested mode and the resolved mode:
```json theme={null}
{
"mode": "auto",
"resolved_mode": "code",
"model": { "id": "theo-1-reason", "label": "Theo Reason" }
}
```
# Engine Routing & Fallbacks
Source: https://docs.hitheo.ai/core-concepts/model-routing
How Theo selects the best engine and handles failures.
Theo doesn't use a single model. The engine router selects the optimal engine for each task based on the resolved mode, with automatic failover if the primary engine is unavailable.
## Engine Table
|| Mode | Engine ID | Description |
||------|-----------|-------------|
|| fast / auto | `theo-1-flash` | Fast, lightweight completions |
|| think | `theo-1-reason` | Deep reasoning and analysis |
|| code | `theo-1-code` | Production-quality code generation |
|| image | `theo-1-create` | Image generation |
|| video | `theo-1-motion` | Video generation |
|| research | `theo-1-research` | Multi-step web research and synthesis |
|| roast | `theo-1-edge` | Unfiltered humor |
|| genui | `theo-1-genui` | Generative UI components |
|| domain analysis | `theo-1-analyze` | Domain-specific analysis (business, operations, etc.) |
|| data extraction | `theo-1-extract` | Document OCR and structured data extraction |
Theo has access to 300+ models and automatically selects the best one for each engine.
## Automatic Failover
Every engine has a built-in failover mechanism. If the primary model is unavailable or performing below quality thresholds, Theo automatically routes to a backup — you never see a broken response. Failover is transparent and logged in the audit trail.
## Engine IDs in Responses
API responses always use Theo-branded engine identifiers:
```json theme={null}
{
"model": {
"id": "theo-1-reason",
"label": "Theo Reason",
"engine": "theo-core"
}
}
```
## Skill Engine Preferences
Skills can recommend a preferred engine via the `enginePreference` field in their manifest. When a skill's preferred engine differs from the mode default, Theo uses the skill's preference if available.
## Per-Customer Override Stage (Routing Studio)
Between the skill exclusive override and the global intent classifier, the routing engine consults the caller's bound **Routing Studio preference** — a customer-authored bundle of keyword rules, few-shot examples, and per-mode confidence-floor overrides. Preferences let your domain win on ambiguous prompts without retraining the global classifier.
The order, first match wins:
1. Agentic locks (`insurance_*`, `data_extraction`) — never promoted.
2. Attachments → vision.
3. Skill exclusive override (intensity-100 skill with a `modelPreference`).
4. **Routing Studio rule.** Customer-authored rule fast-path.
5. Intent classifier (with customer few-shot examples + per-mode confidence floor).
6. Stealth family preservation.
7. Conversation hint (for `auto` callers).
8. Requested mode.
Customer rules cannot escape stealth or agentic family locks. When a rule targets a stealth-incompatible mode for a stealth caller, the engine silently remaps to the stealth equivalent.
When a preference contributes to the resolution, the `routing` block carries a `customer_preference` field with the preference id, name, the rule id that matched (if any), and the count of few-shot examples injected into the classifier:
```json theme={null}
{
"routing": {
"reason": "customer_preference",
"customer_preference": {
"id": "",
"name": "ContractIQ Legal",
"rule_matched": "r_a4b8c01x9y",
"examples_injected": 2
}
}
}
```
See the [Routing Studio guide](/guides/routing-studio) for the full ContractIQ walkthrough and the [SDK reference](/sdk-reference/routing-studio) for `theo.routingPreferences.*` and `theo.keys.setRoutingPreference()`.
## Routing Receipts in the Playground
Every completion already includes a structured `routing` block on both the SSE `meta` and `done` events:
```json theme={null}
{
"routing": {
"requested_mode": "fast",
"resolved_mode": "image",
"promoted": true,
"reason": "intent_promotion",
"explanation": "Detected an image generation intent in a text-mode caller.",
"classification": {
"mode": "image",
"confidence": 0.93,
"used_fast_path": true,
"reasoning": "Keyword 'draw me' matched image-generation pattern."
},
"image_routing": {
"resolved_engine": "theo-1-rapid",
"auto_selected": true,
"quality": "standard"
}
}
}
```
The playground renders this as an inline **routing receipt** under every assistant turn: a compact `requested → resolved` line, a `Promoted` chip when the routing engine overrode the caller's mode, the engine's `explanation`, and a click-to-expand panel that surfaces classifier confidence, skill overrides, locked families, and the image sub-engine. A four-dot pipeline (CRL → Skill → Route → Dispatch) highlights the stage that drove the decision.
This is the same data your own apps receive over the wire — point your SDK at the `meta` event's `routing` field to render the same affordance in your product.
## Check Engine Availability
```bash theme={null}
curl https://www.hitheo.ai/api/v1/models \
-H "Authorization: Bearer $THEO_API_KEY"
```
Returns the full engine registry with status and availability.
# Orchestration Pipeline
Source: https://docs.hitheo.ai/core-concepts/orchestration-pipeline
How Theo processes every request through a 5-stage pipeline.
Theo is not a model proxy. Every API call passes through a multi-stage pipeline that handles classification, skill injection, model selection, tool execution, and response formatting.
## The Five Stages
```
Request → Classify → Load Skills → Route Model → Agent Loop → Response
```
### 1. Intent Classification
Determines the task type (`fast`, `think`, `code`, `image`, `research`, `roast`, etc.) using a multi-tier classification system. Skipped if you set `mode` explicitly.
### 2. Skill Loading
Loads domain expertise from two sources: the user's **installed skills** (persistent) and **per-request skills** (ephemeral `skills[]` array). Each skill injects system prompt extensions and tool definitions.
### 3. Engine Routing
Selects the optimal Theo engine based on the resolved mode. If the primary engine is unavailable, failover routes to the backup automatically.
### 4. Agent Loop
For requests with tools, Theo enters an iterative loop: the engine reasons, calls a tool, observes the result, and continues until done. For simple prompts with no tools, this collapses to a single call.
### 5. Response
The final output is formatted with content, engine metadata, tool execution log, artifacts, follow-up suggestions, and usage data. The request is billed, cached, and audited.
## Performance
| Scenario | Typical Latency |
| - | - |
| Fast mode, no tools | \~500ms |
| Think/code mode, no tools | 1-3s |
| Agentic with tool calls | 2-5s |
| Image generation | 5-15s |
| Research (async) | 30-120s |
## Pipeline Diagram
See [How Theo Thinks](/introduction/how-theo-thinks) for the complete stage-by-stage breakdown with examples.
# Personas & E.V.I.
Source: https://docs.hitheo.ai/core-concepts/personas-evi
Replace Theo's personality with your own branded AI assistant.
The `persona` parameter controls the base personality of every completion. An **E.V.I. (Embedded Virtual Intelligence)** is a pre-configured Theo client with a custom persona, skills, and tools baked in — your users interact with your brand, not Theo.
## Persona Options
| Value | Behavior |
| - | - |
| `"theo"` | Theo's default personality — a sarcastic, brilliant robot from Jupiter. Witty, confident, and genuinely helpful underneath the snark. |
| `"none"` | Neutral assistant with no personality |
| `{ system_prompt: "..." }` | Your custom persona — replaces Theo entirely |
```typescript theme={null}
// Custom persona
const res = await theo.complete({
prompt: "Draft a follow-up email",
persona: { system_prompt: "You are Eva, a professional CRM assistant for AcmeCorp." },
});
```
## E.V.I. — The SDK Shortcut
Instead of passing `persona`, `skills`, and `tools` on every request, create an E.V.I. instance:
```typescript theme={null}
const evi = theo.evi({
persona: "You are Nova, an operations assistant for WarehouseOS. Professional, concise, proactive.",
skills: ["inventory-check", "data-extraction"],
tools: [
{
name: "check_stock",
description: "Look up current stock levels for a SKU",
input_schema: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
},
},
],
defaultMode: "auto",
});
// Every call through the E.V.I. includes the persona, skills, and tools automatically
const res = await evi.complete({ prompt: "Check stock levels for SKU-1234" });
```
## Three Levels
1. **Persona only** — Replace Theo’s voice with your brand
2. **Persona + Skills** — Add domain expertise (inventory, compliance, etc.)
3. **Persona + Skills + Inline Tools** — Connect Theo to your product’s actions
See the full [E.V.I. Guide](/guides/build-an-evi) for detailed examples of each level.
## Skill Builder — The Visual Builder
Prefer a visual approach? The **Skill Builder** is a drag-and-drop skill builder in the dashboard. Design node graphs with prompts, models, tools, knowledge, vision, and conditions — then compile, test, and publish without writing a manifest.
See the [Canvas Guide](/guides/evi-canvas) and [Canvas SDK Reference](/sdk-reference/canvases).
# Streaming
Source: https://docs.hitheo.ai/core-concepts/streaming
How Theo streams responses over SSE, how to consume them, and how to cancel mid-generation.
Theo streams responses over **Server-Sent Events (SSE)**. Set `stream: true` on any completion request to receive events as they happen instead of waiting for the full response.
SSE is the same protocol OpenAI and Anthropic use — any HTTP client that can parse `text/event-stream` works. The SDK wraps it into an async iterable.
## Why streaming?
* **Time-to-first-token under 300ms** on fast modes — users see output immediately instead of staring at a spinner.
* **Agent-loop transparency** — `tool` and `artifact` events fire the moment Theo uses a tool or produces a file, so you can render a live "Theo is browsing…" or "Generated image" card.
* **Graceful cancellation** — close the HTTP connection (or call `stream.cancel()` in the SDK) to stop billing for tokens you don't want.
## Event flow
A normal turn emits events in this order:
1. `thinking` — a heartbeat so proxies flush the response.
2. `meta` — resolved mode, branded model, routing telemetry, `conversation_id`, `request_id`.
3. `skills` (optional) — which skills fired for this turn.
4. `genui_meta` (optional) — only when `resolved_mode === "genui"`.
5. `tool` / `artifact` — as they happen (may interleave).
6. `token` — one per text chunk.
7. `done` — full content, follow-ups, usage, `conversation_id`, `request_id`.
If anything fails, the server emits an `error` event whose payload **matches the REST error envelope** (`{ error: { message, type, code, request_id } }`) and closes the stream. No special handling required — reuse your HTTP error code path.
See [Streaming Completions (API reference)](/api-reference/completions/streaming) for the per-event JSON schemas, wire-format rules, and a mid-stream 429 example.
## SDK Streaming
The SDK returns a `TheoStream`. It is async-iterable, so `for await` works out of the box. After the stream completes, it exposes `conversationId`, `usage`, `model`, and `requestId` as properties.
```typescript theme={null}
const stream = theo.stream({
prompt: "Explain how TCP/IP works",
});
for await (const event of stream) {
switch (event.type) {
case "meta": console.log("Mode:", event.data.resolved_mode); break;
case "token": process.stdout.write(event.token); break;
case "tool": console.log("Tool:", event.data.name, event.data.status); break;
case "artifact": renderArtifact(event.data); break;
case "error": console.error("Stream error:", event.data.error); break;
case "done": console.log("\nCost:", event.data.usage.cost_cents); break;
}
}
// Final metadata — populated from meta + done events.
console.log("conversation_id:", stream.conversationId);
console.log("usage:", stream.usage);
console.log("request_id:", stream.requestId);
```
### Cancelling mid-generation
`TheoStream.cancel()` aborts the underlying HTTP connection, so the server stops generating and billing stops. The iterator ends after the next event boundary.
```typescript theme={null}
const stream = theo.stream({ prompt: "Write a 5000-word essay…" });
// Wire up your UI's "Stop generating" button:
cancelButton.onclick = () => stream.cancel();
for await (const event of stream) {
// ...
}
```
This is the cleanest way to implement a chat UI's "stop" button — no hacky HTTP connection teardown, no custom AbortController threading.
## Raw SSE (curl / fetch)
Use the canonical `www` host to avoid an apex-to-www redirect that some HTTP clients handle by stripping the `Authorization` header (see [401 Troubleshooting](/troubleshooting/401-errors)):
```bash theme={null}
curl -N -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt": "Write a haiku about code", "stream": true}'
```
The response body is a stream of SSE events:
```
event: meta
data: {"id":"cmpl_abc","resolved_mode":"fast","model":{"id":"theo-1-flash","label":"Theo Flash","engine":"theo-core"},"conversation_id":null,"request_id":"req_9f2e1a", ...}
event: token
data: {"token":"Lines"}
event: token
data: {"token":" of"}
event: done
data: {"id":"cmpl_abc","content":"Lines of code","usage":{"cost_cents":0.01,"prompt_tokens":8,"completion_tokens":2,"total_tokens":10}, ...}
```
## Multi-turn conversations
The `conversation_id` appears on both the `meta` and `done` events. When you pass one in the request, it is echoed back unchanged; when you don't, it is `null` (the server doesn't create a persistent conversation for API-key callers unless you explicitly call `POST /api/v1/conversations`).
The SDK captures the ID automatically — read `stream.conversationId` after the stream completes.
## E.V.I. Streaming
E.V.I. instances (`theo.evi(...)`) support streaming with the same `TheoStream` surface:
```typescript theme={null}
const evi = theo.evi({
persona: "You are Kai, a coding assistant...",
});
const stream = evi.stream({
prompt: "Debug this React hook",
});
for await (const event of stream) {
if (event.type === "token") process.stdout.write(event.token);
}
console.log("request_id:", stream.requestId);
```
# API Keys
Source: https://docs.hitheo.ai/dashboard/api-keys
Create and manage API keys from the dashboard.
Navigate to **API Keys** in the dashboard sidebar to manage your keys.
## Create a Key
1. Click **Create Key**
2. Enter a name (e.g., "Production", "Development")
3. Optionally set **scopes** to restrict what the key can access (e.g., completions only)
4. Optionally set **rate limits** and **spending caps** for this specific key
5. Copy the key — **it won't be shown again**
Store API keys securely. Use environment variables or a secrets manager. Never commit keys to source control.
## Key Formats
| Prefix | Environment | Billing |
| - | - | - |
| `theo_sk_live_` | Production | Billed per token |
| `theo_sk_test_` | Sandbox | No billing, lower rate limits |
## Key Management
* **Revoke** — instantly disable a key (takes effect within seconds)
* **Rename** — update the display name
* **View usage** — see per-key usage statistics, cost, and request counts
* **Edit limits** — adjust rate limits and spending caps per key
## Key Rotation
To rotate a key without downtime:
1. Create a new key
2. Update your environment variables
3. Verify traffic flows through the new key
4. Revoke the old key
Both keys work simultaneously during the transition.
## Programmatic Key Management
You can also create keys via the API: [Create API Key](/api-reference/keys/create).
# Billing & Credits
Source: https://docs.hitheo.ai/dashboard/billing-credits
Per-token billing, credit management, and spending caps.
Theo uses per-token billing with a credit system. 1 credit = 1 cent.
## How Credits Work
Every API call consumes credits based on the tokens processed. The cost depends on which Theo engine handles the request:
| Engine | Cost | Best For |
| - | - | - |
| Theo Flash (`fast`) | Lowest | Simple Q\&A, classification |
| Theo Reason (`think`) | Medium | Deep reasoning, analysis |
| Theo Code (`code`) | Medium-High | Code generation |
| Theo Create (`image`) | Per-image | Image generation |
| Theo Research (`research`) | Variable | Web research |
* **Cache hits cost 0 credits** — identical cached requests are free
* **Usage is tracked in real-time** in the dashboard
* Credits are deducted immediately after each completion
## Add Credits
1. Navigate to **Billing** in the dashboard sidebar
2. Click **Add Credits**
3. Choose an amount or set up auto-top-up
4. Complete payment via the secure billing portal
## Auto-Recharge
Keep your balance topped up automatically. Pick an amount and a cadence (weekly or monthly), and we'll add credits on that schedule using the card on file. Cancel anytime from the billing portal.
## Spending Caps
Protect against unexpected charges by setting spending limits:
* **Daily cap** — maximum credit spend per day
* **Monthly cap** — maximum credit spend per billing cycle
* **Per-key caps** — limit individual API keys independently
When a cap is reached, requests return `402 insufficient_credits` until the cap resets or is raised.
## Monitoring
* Real-time credit balance in the dashboard header
* Per-request cost visible in every API response (`usage.cost_cents`)
* Historical cost breakdown in [Usage & Analytics](/dashboard/usage-analytics)
* Alerts when balance drops below a configurable threshold
## Test vs. Production Keys
| Key Prefix | Billing | Rate Limits |
| - | - | - |
| `theo_sk_test_` | No billing | Lower limits |
| `theo_sk_live_` | Billed per token | Full limits |
# Settings
Source: https://docs.hitheo.ai/dashboard/settings
Account and organization settings.
Manage your account, organization, and preferences from the Settings page.
## Account Settings
* **Profile** — Update your display name and email address
* **Email preferences** — Configure notification preferences (usage alerts, billing, skill updates)
* **API keys** — Quick link to the [API Keys](/dashboard/api-keys) management page
* **Security** — Enable MFA, manage active sessions, view login history
## Organization Settings
If you belong to an organization:
* **Team members** — Invite members, assign roles (admin, member, viewer)
* **Billing** — Org-level credit pool and spending caps
* **Connectors** — Configure external system integrations (CRMs, APIs, data sources)
* **Webhooks** — Set up webhook URLs for event notifications (completions, skill installs, etc.)
* **SSO** — Configure single sign-on for your organization
## Danger Zone
* **Delete account** — Permanently delete your account and all associated data. Contact support to initiate.
# Skill Management
Source: https://docs.hitheo.ai/dashboard/skill-management
Install, configure, and manage skills from the dashboard.
The Skills page is your central hub for managing AI capabilities.
## Marketplace
Browse the skill marketplace to discover domain-specific AI capabilities:
* **Search** by name, category, or keyword
* **Filter** by category: Productivity, Domain, Integration, Automation, Creative
* **Sort** by install count, rating, or newest
* **Preview** skill details, permissions, and reviews before installing
## Installed Skills
Manage your installed skills:
* **Toggle on/off** — Disable a skill without uninstalling it
* **View details** — See the skill's system prompt, tools, and permissions
* **Uninstall** — Remove the skill entirely
* **Configure** — Adjust skill-specific settings (where available)
Installed skills are automatically loaded on every completion request. You can also activate skills per-request using the `skills` parameter.
## For Skill Authors
* **My Skills** — View skills you've authored
* **Publish** — Submit skills for marketplace review via CLI (`theo skill publish`) or API
* **Analytics** — Track install counts and usage
* **Earnings** — Monitor revenue from the [revenue sharing](/skills/revenue-sharing) program
See [Building a Skill](/skills/building-a-skill) to get started as an author.
# Usage & Analytics
Source: https://docs.hitheo.ai/dashboard/usage-analytics
Monitor API usage, costs, and model distribution.
The Usage page gives you full visibility into your API consumption, costs, and performance.
## Metrics Available
* **Total requests** — by day, week, month with trend graphs
* **Cost breakdown** — by mode, model, and active skill
* **Model distribution** — which Theo engines handle your requests (pie chart)
* **Latency percentiles** — p50, p95, p99 response times
* **Cache hit rate** — percentage of requests served from semantic cache
* **Token consumption** — prompt tokens vs. completion tokens
* **Error rates** — 4xx and 5xx response breakdown
## Filtering
Filter usage data by:
* **Date range** — custom start/end dates
* **API key** — see usage for a specific key
* **Mode** — filter by `fast`, `think`, `code`, etc.
* **Skill** — see which skills contribute to usage
## API Access
All dashboard metrics are also available via the REST API:
```bash theme={null}
curl "https://www.hitheo.ai/api/v1/usage?from=2026-04-01&to=2026-04-14" \
-H "Authorization: Bearer $THEO_API_KEY"
```
See [Get Usage](/api-reference/usage/get) for details.
# Async Jobs (Research & Video)
Source: https://docs.hitheo.ai/guides/async-jobs
Run long jobs the right way: enqueue with research()/video(), then poll the job with waitForJob().
Some Theo capabilities are **too slow to return inline**. `research` (plan → multi-source web search → synthesis) and `video` (model generation) run as background jobs: you enqueue them, get a `job_id` back immediately, then poll until they finish.
Do **not** send `mode: "research"` or `mode: "video"` to `/completions` or `theo.stream()`. Those run the work **inline**, which blows past the request timeout. The SDK throws a `TheoUsageError` immediately if you try. Use the dedicated methods below.
## Lifecycle
1. **Enqueue** — `POST /api/v1/research` or `/api/v1/video` returns `202` with `{ id, job_id, status: "queued", poll_url }`.
2. **Poll** — `GET /api/v1/jobs/{job_id}` returns the current `status`: `queued` → `active` → `completed` (or `failed`).
3. **Read the result** — when `status === "completed"`, `result` holds the typed payload.
## SDK usage
`waitForJob()` does the polling loop for you, with an optional `onProgress` callback and an `AbortSignal`.
```typescript theme={null}
import { Theo, type ResearchJobResult } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
const job = await theo.research({
prompt: "Compare React, Vue, and Svelte for enterprise apps in 2026",
depth: "advanced",
max_sources: 10,
});
const final = await theo.waitForJob(job.job_id, {
intervalMs: 3000, // poll cadence (default 2s)
maxWaitMs: 180_000, // give up after 3 min (default 5 min)
onProgress: (s) => console.log(`${s.status} ${s.progress}%`),
signal: AbortSignal.timeout(180_000), // optional hard cancel
});
if (final.status === "completed") {
console.log(final.result?.report);
console.log(`${final.result?.sourceCount} sources`);
}
```
Video works the same way with `theo.video()` + `waitForJob()`.
### Polling cadence & limits
* Default poll interval is **2s**; `waitForJob` gives up after **5 minutes** by default (`maxWaitMs`) and throws a `TheoTimeoutError`. Raise `maxWaitMs` for long video renders.
* Don't poll faster than \~1s — it wastes rate-limit budget without finishing the job any sooner.
### Cancellation
Pass an `AbortSignal`. When it fires, `waitForJob` stops polling and rejects with a `TheoCancelledError` (it does **not** cancel the server-side job — it just stops your client from waiting).
```typescript theme={null}
const controller = new AbortController();
// e.g. user navigates away
document.addEventListener("stop", () => controller.abort());
await theo.waitForJob(job.job_id, { signal: controller.signal });
```
## Result schemas
`result` is typed via the generic on `job()` / `waitForJob()`. The shapes mirror the REST payload ([Get Job Status](/api-reference/jobs/get)):
* **`ResearchJobResult`** — `{ report, sources: { title, url }[], queries, sourceCount }`
* **`VideoJobResult`** — `{ videoUrl, model, engine, durationMs }`
* **`ImageJobResult`** — `{ imageUrl, model, engine }`
* **`DocumentJobResult`** — `{ title, format, downloadUrl, sizeBytes }`
Any `model` / `engine` fields are Theo-branded — raw upstream identifiers never appear.
## Cost & usage
Job results do not yet carry a per-job `cost_cents` field. To attribute spend for research/video jobs, read the aggregated [Usage report](/api-reference/usage/get) (`theo.usage()`), which includes a `by_mode` breakdown covering `research` and `video`.
## Failures
When `status === "failed"`, `result` is `null` and `error` holds the reason string. The enqueue call itself can also return `503 queue_unavailable` if the job queue is temporarily down — retry shortly.
# Build an E.V.I.
Source: https://docs.hitheo.ai/guides/build-an-evi
Embed Theo into your product with a custom persona, skills, and tools.
An E.V.I. (Embedded Virtual Intelligence) is Theo embedded in your product. Your users interact with your branded AI, powered by Theo's orchestration engine.
## What You're Building
```
Your Application (CRM, dashboard, app)
└── Your UI (chat, sidebar, actions)
└── @hitheo/sdk (evi instance)
└── Theo API (api.hitheo.ai)
└── Classify → Skills → Route → Agent Loop → Response
```
## Level 1: Custom Persona Only
```typescript theme={null}
const evi = theo.evi({
persona: "You are Kai, a friendly coding assistant for DevHub.",
});
const res = await evi.complete({
prompt: "Why is my useEffect running twice?",
});
```
## Level 2: Persona + Skills
```typescript theme={null}
const evi = theo.evi({
persona: "You are Atlas, an operations assistant for AcmeCorp.",
skills: ["inventory-check", "data-extraction"],
});
```
## Level 3: Persona + Skills + Inline Tools
```typescript theme={null}
const evi = theo.evi({
persona: "You are Nova, the AI assistant for WarehouseOS.",
skills: ["data-extraction"],
tools: [
{
name: "check_inventory",
description: "Look up stock levels for a SKU",
input_schema: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
},
},
],
});
```
## Streaming
```typescript theme={null}
const stream = evi.stream({ prompt: "Generate inventory report" });
for await (const event of stream) {
if (event.type === "token") process.stdout.write(event.token!);
}
```
## Best Practices
* **Persona**: Be specific about what the E.V.I. should NOT do ("Never mention Theo")
* **Skills**: Install only what your use case needs
* **Tools**: Keep descriptions clear — the model reads them to decide when to call
* **Cost**: Use `mode: "fast"` for simple queries
# Cost Optimization
Source: https://docs.hitheo.ai/guides/cost-optimization
Tips for reducing API costs while maintaining quality.
## Use the Right Mode
| Mode | Cost | Use When |
| - | - | - |
| `fast` | Lowest | Simple Q\&A, classification, short responses |
| `auto` | Variable | Let Theo decide — usually picks the cheapest adequate model |
| `think` | Higher | Complex reasoning, multi-step analysis |
| `code` | Higher | Code generation, architecture design |
## Tips
1. **Set `mode: "fast"` for simple tasks** — routes to Theo Flash (cheapest)
2. **Use semantic caching** — identical requests are free after the first call
3. **Monitor usage** — `GET /api/v1/usage` shows cost breakdown by mode and model
4. **Set daily caps** — configure spending limits in the billing dashboard
5. **Use per-request skills** instead of installing everything — fewer skills = less prompt tokens
6. **Lower `max_iterations`** — if you know the task needs only 1-2 tool calls, set `max_iterations: 3`
# Custom Tool Execution
Source: https://docs.hitheo.ai/guides/custom-tool-execution
Connect Theo to your product's actions via inline tools.
Pass tool definitions on any completion request to let Theo call your product's actions:
```typescript theme={null}
const res = await theo.complete({
prompt: "Check if we're low on SKU-A1234 and reorder if needed",
tools: [
{
name: "check_inventory",
description: "Look up current stock levels for a SKU",
input_schema: {
type: "object",
properties: { sku: { type: "string" } },
required: ["sku"],
},
},
{
name: "create_reorder",
description: "Create a purchase order to restock",
input_schema: {
type: "object",
properties: {
sku: { type: "string" },
quantity: { type: "number" },
},
required: ["sku", "quantity"],
},
},
],
});
console.log(res.tools_used);
// [{ name: "check_inventory", status: "success" }, { name: "create_reorder", status: "success" }]
```
The model decides when to call each tool based on the descriptions you provide.
# Embed a Chat Widget
Source: https://docs.hitheo.ai/guides/embed-widget
Add a white-label Theo chat widget to your website with a single script tag.
Theo's embed widgets let you add an AI chat interface to any website. Each widget is linked to an API key and inherits its Brand Soul, credits, and permissions.
## Quick Start
1. **Create an API key** in the Dashboard → Keys page.
2. **Create a widget** in Dashboard → Widgets, or via the API:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/iframes \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"api_key_id": "your-key-id",
"name": "Support Widget",
"appearance": { "primaryColor": "#715eac" },
"behavior": { "welcomeMessage": "Hi! How can I help?" }
}'
```
3. **Embed the snippet** on your site:
```html theme={null}
```
## Customization
### Appearance
Control the look of the widget via the `appearance` object:
* `primaryColor` — Accent color for the widget header and buttons
* `position` — `"bottom-right"` (default) or `"bottom-left"`
* `borderRadius` — Corner radius in pixels
* `fontFamily` — Custom font (loaded from Google Fonts)
### Behavior
* `welcomeMessage` — Greeting shown when the widget opens
* `placeholder` — Input field placeholder text
* `maxPromptLength` — Maximum characters per message
* `enableFileUpload` — Allow users to upload images/documents
* `enableVoice` — Enable voice input (speech-to-text)
* `strictAbuse` — Enable abuse detection heuristics (rapid-fire, content repetition, prompt-length)
### Brand Soul
If the linked API key has a Brand Soul configured (via Dashboard → Keys → Brand Soul), the widget automatically inherits it. The Brand Soul defines the persona, tone, knowledge base, and behavior constraints — making the widget sound like your brand, not like a generic chatbot.
## Security
### Domain Allowlist
Configure `allowedOrigins` on the API key to restrict which domains can embed the widget. Requests from unauthorized origins are rejected via CORS.
### Bot Protection
Enable `requireTurnstile: true` in the widget's security config to add a bot-protection challenge before the first message.
### Abuse Detection
When `strictAbuse` is enabled, Theo applies server-side heuristics that flag and throttle abusive traffic patterns — including rapid-fire requests from a single IP, repetitive or duplicate content, and excessively long prompts. Exact thresholds are not published so attackers can’t calibrate around them.
### Human Escalation
The widget automatically detects when users request a human agent ("talk to a real person", "get me an agent"). You can configure custom keyword triggers and actions (redirect to URL, show message, fire webhook) in the widget's intent config.
## Preview
Generate a preview token to test unpublished widgets in the Dashboard:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/iframes/{id}/preview-token \
-H "Authorization: Bearer $THEO_API_KEY"
```
Preview tokens are short-lived and bypass the domain allowlist for testing.
## Live Conversations & Human Takeover
Every visitor session is recorded. You can list sessions, read a full transcript, and — when a visitor needs a person — jump in:
* **List sessions** with `GET /api/v1/iframes/{id}/conversations` (filter by `status`, `has_lead`, date range).
* **Read a transcript** with `GET /api/v1/iframes/{id}/conversations/{sessionId}`.
* **Take over** a live chat with `POST .../takeover` to suppress AI replies, then **post operator messages** with `POST .../messages`.
* **Release** the chat back to the AI with `POST .../release`.
The transcript marks human turns with the `operator` role so AI and human messages stay distinguishable.
## Analytics
`GET /api/v1/iframes/{id}/analytics?window=30d` returns KPIs (sessions, leads, messages, conversion rate, average session duration), a previous-period comparison, daily time series, and top referrers/countries for building a dashboard.
## Lead Capture
When a widget collects contact details, each lead is stored against its session. Retrieve them with `GET /api/v1/iframes/{id}/leads` (paginated, searchable) or download everything as CSV with `GET /api/v1/iframes/{id}/leads/export`.
## API Reference
* [Create Widget](/api-reference/iframes/create)
* [List Widgets](/api-reference/iframes/list)
* [Get](/api-reference/iframes/get) · [Update](/api-reference/iframes/update) · [Delete](/api-reference/iframes/delete) · [Duplicate](/api-reference/iframes/duplicate) · [Bulk Delete](/api-reference/iframes/bulk-delete)
* [Analytics](/api-reference/iframes/analytics)
* [Leads](/api-reference/iframes/leads) · [Leads Export](/api-reference/iframes/leads-export)
* [Conversations](/api-reference/iframes/conversations) · [Conversation Transcript](/api-reference/iframes/conversation)
* [Take Over](/api-reference/iframes/takeover) · [Release](/api-reference/iframes/release) · [Operator Message](/api-reference/iframes/operator-message)
* [Verify Installation](/api-reference/iframes/verify)
# Build with the Skill Builder
Source: https://docs.hitheo.ai/guides/evi-canvas
Design AI skills visually with the drag-and-drop canvas editor.
The Skill Builder is a visual skill builder in the Theo dashboard. Instead of writing a manifest by hand, you drag nodes onto a canvas, connect them, and publish — Theo compiles the graph into a skill automatically.
## Open the Canvas
Navigate to **Dashboard → Skills → Canvas** or go directly to `api.hitheo.ai/dashboard/skills/canvas`. You can start from a blank canvas or pick a quick-start template (Customer Service Agent, Research Pipeline, Content Generator, Data Extractor).
## Node Types
Every canvas is a directed acyclic graph (DAG) of nodes:
* **Input** — Entry point. Configures the trigger type (manual, keyword, event, schedule). Every canvas needs exactly one.
* **Prompt** — System instructions injected into the skill's prompt extension.
* **Model** — Selects a Theo model (`theo-1-flash`, `theo-1-reason`, `theo-1-code`, etc.) and temperature.
* **Tool** — Declares a custom tool the skill can call. Includes name, description, and optional JSON schema.
* **Knowledge** — Attaches reference documents (file keys) for RAG-style retrieval.
* **Vision** — Enables multimodal image analysis. Configure the image source (upload, URL, or upstream step output) and analysis instructions.
* **Condition** — Branch logic with a boolean expression. Outputs to "true" and "false" handles.
* **Output** — Response format node. At least one must be reachable from Input.
## Workflow
1. **Design** — Drag nodes from the toolbar, connect edges, configure each node's settings inline.
2. **Save** — Click **Save** (or Ctrl+S). The graph is persisted to your account.
3. **Compile** — Click **Compile**. Theo validates the graph (checks for cycles, unreachable nodes, missing prompts) and transforms it into a `SkillManifest` + `WorkflowSteps`.
4. **Test** — Click **Test** to open the sandbox playground. Send messages to your compiled skill in a safe environment — no real tool calls, mock data only.
5. **Publish** — Click **Publish**, choose a slug, version, and visibility tier, then submit. The skill enters the same review pipeline as CLI/API-submitted skills.
## Publishing Visibility
When publishing, you choose one of three tiers:
* **Private** — Only you can see and install the skill.
* **My Organization** — All members of your organization can see and install the skill, but it's not listed publicly.
* **Public Marketplace** — The skill is listed in the Skill Store for all Theo users.
## Via SDK
You can also manage canvases programmatically:
```typescript theme={null}
const canvas = await theo.createCanvas({ name: "My Agent" });
await theo.updateCanvas(canvas.id, {
graph_json: { nodes: [...], edges: [...] },
});
const compiled = await theo.compileCanvas(canvas.id);
const test = await theo.testCanvas(canvas.id, "Hello, test message");
const published = await theo.publishCanvas(canvas.id, {
slug: "my-agent",
version: "1.0.0",
author: { name: "Your Name" },
visibility: "public",
});
```
## Via API
All canvas operations are available under `POST/GET/PATCH/DELETE /api/v1/evi/canvases`. See the [Canvas API Reference](/api-reference/evi/canvases) for full details.
# Gateway Guardrails
Source: https://docs.hitheo.ai/guides/guardrails
Opt-in input/output policies that the Theo gateway enforces on every completion bound to an API key.
Gateway Guardrails let you attach policy-driven safety, privacy, and reliability checks to any API key. Bound policies fire on every completion — including `/v1/completions` (streaming + non-streaming), `/v1/images`, `/v1/code`, `/v1/documents`, the playground, and embed widgets.
## Strict opt-in contract
**Nothing is live until you bind a policy to an API key.** New keys, all existing keys, and every Clerk-session caller bypass guardrails entirely. There is no automatic org or user default — guardrails are an enforcement boundary, not a routing preference, so the gateway never enforces something you didn't explicitly opt into.
This means:
* **Existing API keys are unaffected** until you explicitly bind a policy. Roll-out is risk-free.
* **No fallback chain.** Clearing a binding (`policy_id: null`) drops the key back to no enforcement.
* **Per-key, 1:1.** A key can be bound to at most one policy; the policy can be bound to any number of keys.
## The five built-in protections
Each protection is a pure evaluator: identical inputs always produce identical outputs. They are vendor-neutral and never name an upstream provider in customer-facing strings.
Scrubs emails, phone numbers, US Social Security numbers, Luhn-valid credit cards, and driver-license-shaped IDs from the prompt **before** any model call.
Allowed verdicts: `redact` (default), `flag` (logged only, prompt untouched).
Phase: `input` only.
```json theme={null}
{ "guardrail_id": "pii_redactor", "phase": "input", "verdict": "redact" }
```
Catches the canonical OWASP-LLM01 patterns: "ignore previous instructions", role takeovers, fake system messages, prompt exfiltration probes.
Allowed verdicts: `deny` (default — surfaces a vendor-neutral 422 to the caller), `flag`.
Phase: `input` only.
```json theme={null}
{ "guardrail_id": "prompt_injection", "phase": "input", "verdict": "deny" }
```
Detects malformed JSON in model output. On a `repair` verdict the runner makes a single repair attempt and falls back to the original buffer if it can't produce valid JSON.
Allowed verdicts: `repair` (default), `flag`.
Phase: `output` only.
Config: `{ "fenced": true }` (default `true`) — when set, the evaluator first strips a fenced `json` block before parsing, mirroring the most common LLM output shape.
```json theme={null}
{ "guardrail_id": "json_repair", "phase": "output", "verdict": "repair", "config": { "fenced": true } }
```
Truncates the buffer to a configured cap and appends a small `…[truncated]` marker.
Allowed verdicts: `truncate` (default), `flag`.
Phase: `input` and/or `output`.
Config (one of):
* `{ "maxChars": 16000 }` — hard character cap.
* `{ "maxTokens": 4000, "charsPerToken": 4 }` — token cap (default 4 chars/token).
```json theme={null}
{ "guardrail_id": "max_length", "phase": "output", "verdict": "truncate", "config": { "maxTokens": 4000 } }
```
Detects common profanity in either direction. Defaults to `flag` (visibility only) so you can review activity before deciding to block.
Allowed verdicts: `flag` (default), `deny`.
Phase: `input` and/or `output`.
```json theme={null}
{ "guardrail_id": "profanity", "phase": "output", "verdict": "flag" }
```
## The five verdicts
A rule's verdict tells the runner what to do when the protection fires. The runner aggregates the worst verdict across all matched rules for the phase and applies it once:
* **flag** — Pass-through. The match is recorded in the execution log; nothing else changes.
* **redact** — Replace the matched text with `[REDACTED:]` before forwarding.
* **truncate** — Trim to the configured limit and append `…[truncated]`.
* **repair** — Run a single repair pass on the buffer. Used by `json_repair` only.
* **deny** — Block the request. On `input` the gateway returns a `422 invalid_request_error` with `code: "guardrail_violation"` before any model call. On `output` the response content is replaced with the deny reason and artifacts are dropped.
Customer-facing messages never name an upstream provider — the SDK surfaces a stable `guardrail_violation` code so your application can branch on policy enforcement without knowing which detector fired.
## Quick start — dashboard
1. Open **Dashboard → Guardrails** and pick a preset (or click **New policy** for a blank policy).
2. Add protections from the picker; each card lets you choose the phase and verdict.
3. Use the **Test bench** in the right rail to replay a fixture prompt + optional model output through the policy. You'll see the verdict trail per rule.
4. In the **Bindings** panel below the editor, toggle the policy on each API key you want to enforce against.
That's it. The policy is live for every bound key.
## Quick start — SDK
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
// 1. (Optional) Start from a preset
const presets = await theo.guardrails.presets.list();
const enterprise = presets.find((p) => p.id === "enterprise-default")!;
// 2. Create a policy
const policy = await theo.guardrails.policies.create({
name: "Production defaults",
description: "PII redaction + jailbreak deny + JSON repair on output.",
rules: enterprise.rules,
});
// 3. Bind it to an API key
await theo.keys.setGuardrailPolicy("", policy.id);
// 4. Verify the binding
const bindings = await theo.guardrails.policies.bindings(policy.id);
console.log(`Policy is enforcing on ${bindings.count} key(s).`);
// 5. Tail the audit log
const recent = await theo.guardrails.executions.list({ policyId: policy.id, limit: 20 });
```
The management endpoints (`/api/v1/guardrail-policies/*`, `/api/v1/keys/{id}/guardrails`) require the `billing` API key scope — matching the routing-preferences convention. Mint a key with this scope explicitly if you plan to manage policies programmatically; the default `completions` scope is sufficient for normal traffic.
## Error envelope
When an input-phase `deny` fires, the API returns:
```json theme={null}
{
"error": {
"type": "invalid_request_error",
"code": "guardrail_violation",
"message": "Request blocked by your active guardrail policy.",
"request_id": "req_..."
}
}
```
HTTP status is `422`. For streaming completions the same envelope is emitted as an `error` SSE event:
```
event: error
data: { "error": { "type": "invalid_request_error", "code": "guardrail_violation", ... } }
```
The deny reason is the customer-facing copy the protection surfaced; the matched-pattern id (e.g. `ignore_previous`) is intentionally **not** included so attackers can't probe which detector fired.
## Streaming behavior
Output guardrails run after the full token stream has been collected on the server. This means:
* **Tokens stream live as the model produces them.** The client sees the raw, pre-guard text in real time.
* **The `done` event carries the guarded buffer.** Any client that re-renders the message body from the `done` event (the official SDK, the playground, the embed widget) ends up displaying the policy-compliant version.
* **On `deny`, an additional `error` SSE event is emitted** before `done`. The `done.content` is replaced with the deny reason and any artifacts produced during the turn are dropped.
If your client renders tokens live and doesn't re-read `done.content`, plan on switching to non-streaming mode (`stream: false`) when you need byte-exact policy enforcement on every visible character.
## Team policies
`scope: "team"` policies are visible to every member of the owning organization and require the `manageWebhooks` permission to create/update (re-used as the generic team-config gate; there is no dedicated `manageGuardrails` bit today).
Personal policies are only visible to their author. Team keys can only be bound to team policies in the same org — the binding endpoint enforces this with `guardrail_policy_not_bindable` when the scopes don't match.
## Audit & telemetry
Every evaluation writes an immutable row to `guardrail_executions` (90-day retention, enforced by the BullMQ retention worker). Each row captures:
* `policy_id`, `key_id`, `user_id` — who/what triggered the evaluation.
* `guardrail_id`, `phase`, `verdict` — the rule and outcome.
* `matched_pattern`, `redacted_count` — bounded forensic context (no raw prompts).
* `latency_ms` — per-rule overhead, surfaced in the dashboard's activity feed.
Tail the log via `theo.guardrails.executions.list({ keyId, policyId, since })` or `GET /api/v1/guardrail-executions`. The dashboard's **Recent activity** panel renders the same rows in plain language.
## What guardrails do not change
* **Model allowlists, routing rules, skills, brand soul, response style, and personality** all keep working independently. Guardrails layer around the request/response path; they don't override other key-level features.
* **Existing keys without a binding stay unchanged.** You opt in per key.
* **Cost is unaffected.** Builtins are pure evaluators (sub-millisecond); `json_repair`'s repair pass adds a single small call only when malformed JSON is detected.
## API reference
* [List policies](/api-reference/guardrails/list-policies)
* [Create policy](/api-reference/guardrails/create-policy)
* [Get / update / delete policy](/api-reference/guardrails/get-policy)
* [Test policy](/api-reference/guardrails/test-policy)
* [List bindings for a policy](/api-reference/guardrails/policy-bindings)
* [List presets](/api-reference/guardrails/presets)
* [Get / set key binding](/api-reference/guardrails/key-binding)
* [List executions](/api-reference/guardrails/executions)
# IDE Integration
Source: https://docs.hitheo.ai/guides/ide-integration
Use Theo in Cursor, Claude Code, Warp, Windsurf, and VS Code via MCP.
Theo works inside every major agentic IDE through the **Model Context Protocol (MCP)**. This guide is a one-screen orientation — the canonical reference lives in the dedicated [MCP Server](/mcp/overview) section.
## Quick Start
```bash theme={null}
npm install -g @hitheo/sdk
export THEO_API_KEY=theo_sk_...
theo init
```
`theo init` automatically detects your IDEs and writes the correct MCP config. For hand-written config or per-IDE paths, see [MCP / Install](/mcp/install).
## Available Tools
Once configured, your IDE agent has access to:
| Tool | Description |
| - | - |
| `theo_complete` | General AI completion — auto-routes to best engine |
| `theo_code` | Code generation — Theo Code engine, long-form output |
| `theo_research` | Deep research with citations |
| `theo_image` | Image generation — Theo Create engine |
| `theo_document` | Document generation (PDF, DOCX, PPTX, XLSX, CSV) |
| `theo_skill_list` | Browse the skill marketplace |
| `theo_skill_install` | Install domain-specific skills |
| `theo_status` | Check health and engine availability |
Full schemas and examples for each tool live in [MCP / Tools](/mcp/tools); the three `theo://` read-only resources are documented in [MCP / Resources](/mcp/resources).
## Next steps
* **[MCP Overview](/mcp/overview)** — what MCP is, how the request flow works.
* **[Install](/mcp/install)** — per-IDE setup walkthroughs.
* **[Project Config](/mcp/project-config)** — pin a persona, skills, or inline tools per repo.
* **[Troubleshooting](/mcp/troubleshooting)** — fix the most common setup failures.
# Routing rules
Source: https://docs.hitheo.ai/guides/routing-studio
Tune Theo's routing engine for your domain with per-key rules, few-shot examples, and confidence overrides.
Routing Studio is Theo's per-customer routing layer. You describe how your users phrase requests, and Theo's routing engine biases the classifier toward the right mode — without you ever having to manage a separate "preference" object. Rules live directly on each API key: open the key, add the words that should fire a rule, pick the destination, and save.
A **routing rule** maps a list of keywords (or, for power users, a raw regex) to a Theo engine. Rules run BEFORE Theo's global intent classifier so your domain wins on ambiguity. The routing engine layers them on top of its global cascade and never lets them escape Theo's safety locks (stealth, agentic) or leak upstream vendor names into your customers' surfaces.
Alongside rules you can also configure:
* **Few-shot examples** — prompt / expected-mode pairs injected into the classifier's system prompt (up to 8 per request).
* **Confidence-floor overrides** — per-mode replacements for Theo's global `0.85` promotion floor. Lower a floor to make intent promotion easier; raise it to be conservative.
Most teams will only ever edit rules on the keys page. Shared rule sets are a power-user feature for one rule list that needs to span many keys or act as a team default.
## Edit rules on a key
Open [`api.hitheo.ai/dashboard/keys`](https://api.hitheo.ai/dashboard/keys), find the API key you want to tune, and click the **Routing** pill. The panel inlines everything you need:
* **Inherited context** — if no per-key rules are set, the panel tells you whether the key currently inherits the team default, your personal default, or nothing.
* **Rules** — one row per rule. Each row has a keyword chip input, a destination combobox, and a Gentle / Balanced / Strict toggle. The empty state offers a few one-click starter templates (Pricing questions, Customer complaints, Legal review, Photo & image requests) and a Blank rule chip for power users.
* **More options** — a small caret on each row reveals a note field, a raw regex textarea, an optional Theo engine pin, and a raw confidence slider for fine-grained control.
* **Try a prompt** — a compact input appears once you've started editing. Type a sample customer prompt and the panel renders a one-line diff (`baseline mode → with-rules mode`) so you can see exactly what would change before saving.
Click **Save changes** to write the rules to the key. Click **Clear per-key rules** to drop them entirely and fall back to inherited defaults.
### Advanced: hand-written regex
The chip editor projects keywords down to the same `pattern` string the API uses internally. To author a rule with a raw ECMAScript regex (lookaheads, anchors, capturing groups), expand the row's **More options** caret and edit the pattern textarea. Pasting a regex switches the row to Advanced mode automatically so we never silently rewrite your pattern; loading a key whose pattern doesn't round-trip through the chip editor opens that row in Advanced mode by default.
## ContractIQ — a complete walkthrough
ContractIQ is a fictional legal-tech tool. Their users paste contract clauses and ask Theo to analyze them. Without any rules, "look at this clause" routes to `fast` (a short reply); with one rule on the key, it routes to `think` (deep analysis).
### 1. Set rules on the API key
```bash curl theme={null}
curl -X PUT https://www.hitheo.ai/api/v1/keys/$KEY_ID/routing-rules \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"rules": [
{
"pattern": "\\\\b(clause|provision|indemnity|warranty)\\\\b",
"target_mode": "think",
"confidence": 0.92,
"description": "Contract terms get the analytical engine."
}
],
"examples": [
{ "prompt": "Look at this clause", "expected_mode": "think" },
{ "prompt": "Compare these two indemnity sections", "expected_mode": "think" }
]
}'
```
```typescript SDK theme={null}
await theo.routingRules.set(keyId, {
rules: [
{
pattern: "\\\\b(clause|provision|indemnity|warranty)\\\\b",
target_mode: "think",
confidence: 0.92,
description: "Contract terms get the analytical engine.",
},
],
examples: [
{ prompt: "Look at this clause", expected_mode: "think" },
{ prompt: "Compare these two indemnity sections", expected_mode: "think" },
],
});
```
The response confirms the rules are active on the key:
```json theme={null}
{
"key_id": "22222222-2222-4222-8222-222222222222",
"rules": [
{
"id": "r_a4b8c01x9y",
"pattern": "\\\\b(clause|provision|indemnity|warranty)\\\\b",
"target_mode": "think",
"confidence": 0.92,
"description": "Contract terms get the analytical engine."
}
],
"examples": [...],
"active": true,
"shared_binding": null
}
```
The `active: true` field confirms the rules are driving completions on this key right now. To drop the rules and fall back to inherited defaults, send a `DELETE` to the same endpoint (or call `theo.routingRules.clear(keyId)` from the SDK).
### 2. Send a completion
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "prompt": "Look at this indemnity clause", "mode": "auto", "stream": true }'
```
The SSE `meta` event now carries a `customer_preference` field that confirms a rule fired:
```json theme={null}
{
"routing": {
"requested_mode": "auto",
"resolved_mode": "think",
"promoted": true,
"reason": "customer_preference",
"explanation": "Routing Studio rule matched: \"indemnity clause\".",
"customer_preference": {
"rule_matched": "r_a4b8c01x9y",
"examples_injected": 2
}
}
}
```
The playground renders a green chip next to the routing receipt's promotion reason whenever your rules drove the decision.
### 3. Test changes before they ship
Use the test endpoint to replay a fixture prompt with vs. without the preference:
```bash curl theme={null}
curl -X POST "https://www.hitheo.ai/api/v1/routing-preferences/$PREF_ID/test" \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "prompt": "Compare these two warranty sections", "mode": "auto" }'
```
```typescript SDK theme={null}
const diff = await theo.routingPreferences.test(pref.id, {
prompt: "Compare these two warranty sections",
mode: "auto",
});
console.log(diff.baseline.resolved_mode); // "fast"
console.log(diff.with_preference.resolved_mode); // "think"
```
Both blobs match the same `routing` telemetry shape your production callers receive — the diff is a precise, deterministic preview of what your tuning does.
#### Testing an unsaved draft
The dashboard test bench replays the draft you're currently editing — it never makes you save first. If you're building your own UI on top of the API, hit the no-id `POST /api/v1/routing-preferences/test` route with the full draft body. Same response shape as the by-id route; nothing is persisted.
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/routing-preferences/test \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Look at this clause",
"mode": "auto",
"draft": {
"name": "ContractIQ Legal (draft)",
"rules": [
{ "pattern": "\\b(clause|provision)\\b", "target_mode": "think", "confidence": 0.92 }
],
"examples": []
}
}'
```
## Order of precedence
Routing Studio sits inside Theo's broader routing engine. The full cascade, first match wins:
1. **Agentic locks** (`insurance_*`, `data_extraction`) — never promoted.
2. **Attachments → vision** — image attachments on a non-media caller route to `vision`.
3. **Skill exclusive override** — a skill with `intensity: 100` and a `modelPreference` wins.
4. **Routing Studio rule** — your rules fire here.
5. **Intent classifier** — runs with your few-shot examples injected and uses your per-mode confidence-floor overrides.
6. **Stealth family preservation** — promotions from a `stealth_*` caller stay inside the stealth family.
7. **Conversation hint** — falls back to the prior-turn artifact type when the caller used `auto`.
8. **Requested mode** — default.
Your rules **cannot** escape agentic family locks (legal/healthcare/data-extraction modes) and **cannot** escape stealth-family isolation. A rule that targets a stealth-incompatible mode for a stealth caller is silently remapped to the stealth equivalent.
## Confidence-floor overrides
The classifier won't promote a caller's mode unless its confidence is ≥ `0.85` (`PROMOTION_CONFIDENCE_FLOOR`). For specialist domains where the classifier is often correct at lower confidence, lower the floor:
```json theme={null}
{
"name": "Legal Default",
"confidence_floor_overrides": {
"think": 0.65
}
}
```
For domains where false promotions are expensive, raise it:
```json theme={null}
{
"name": "Cost-Sensitive",
"confidence_floor_overrides": {
"image": 0.95,
"video": 0.95
}
}
```
All values are clamped server-side to `[0.5, 0.99]` — neither end of the range can disable the floor entirely.
## Brand-safety contract
Every customer-authored field — name, description, rule pattern, rule description, example prompt — is scanned for upstream vendor names (Claude, OpenAI, Anthropic, Gemini, fal.ai, etc.) and rejected at validation time. Theo's surfaces always read as Theo. Your customers never see the underlying model providers.
The same scan runs on Routing Studio's outputs — the `customer_preference` block your callers receive is guaranteed to be free of vendor names.
## Limits
| Limit | Value |
| - | - |
| Rules per preference | 50 |
| Examples per preference | 30 |
| Examples injected into classifier | 8 (highest-priority first) |
| Pattern length | 512 chars |
| Example prompt length | 1024 chars |
| Confidence range | `[0.5, 0.99]` (clamped) |
| Test prompt length | 4096 chars |
| Cache TTL | 5 minutes (Redis) |
## Team vs. personal scope
Pass `scope: "team"` on create to scope the preference to your active org. Team preferences become candidates for org defaults; team admins (with the team config permission) can manage them. Without a team binding, a key inherits its scope's default → the user's personal default → no preference.
```typescript theme={null}
await theo.routingPreferences.create({
name: "ACME Legal Default",
scope: "team",
is_default: true,
rules: [...],
});
```
Setting `is_default: true` on a second team preference returns `409 conflict` — at most one default per scope.
## Common patterns
* **Domain vocabulary biasing.** Use rules for hard keywords ("policy", "claim", "rune"), use examples for phrasings ("draft me a response to this complaint" → `think`).
* **Cost containment.** Raise floors on `image`/`video` for personal keys; let team keys keep the defaults.
* **Speed bias.** Lower the `fast` floor and add examples like `{ prompt: "thanks!", expected_mode: "fast" }` so short replies don't escalate to `think`.
## Per-key vs. shared sets — when to use which
If you're tuning one or two keys, edit rules directly on the keys page. The dashboard hides everything but the rule editor itself — no "preference" to create, no binding to wire up.
Reach for shared sets when:
* You want one rule list to span many API keys (e.g. every key on your team uses the same legal vocabulary).
* You want a team default that new keys inherit automatically.
* You're scripting bulk changes and would rather author rules in source control once than mirror them across keys.
Under the hood the per-key endpoint and the shared-set endpoints write to the same `routing_preferences` table; the only thing that differs is whether the row is named for a specific key (hidden from the shared list) or carries a customer-chosen name.
## Next steps
* [`/api/v1/routing-preferences` reference](/api-reference/routing-preferences/list-preferences) — full request/response schemas for every endpoint.
* [Routing Studio SDK reference](/sdk-reference/routing-studio) — `theo.routingPreferences.*`, `theo.routingRules.*`, and the per-key binding helpers.
* [Engine Routing & Fallbacks](/core-concepts/model-routing) — where Routing Studio fits inside Theo's broader routing engine.
# Semantic Caching
Source: https://docs.hitheo.ai/guides/semantic-caching
How Theo caches responses to reduce cost and latency.
Theo caches completion responses semantically. Identical requests (same prompt, mode, skills, and tools) return cached results instantly at zero cost.
## How It Works
1. Theo generates a deterministic cache key from the request parameters (prompt, mode, skills, tools)
2. Checks the server-side cache for a matching entry
3. **On hit**: returns the cached response immediately — zero cost, sub-10ms latency
4. **On miss**: runs the full orchestration pipeline, caches the result, and returns it
Cached responses include `"_cached": true` in the response body so you can detect cache hits.
## Cache Key Computation
The cache key is a deterministic hash of:
* **Prompt text** (exact match)
* **Mode** (`auto`, `fast`, `think`, etc.)
* Active **skill slugs**
* Inline **tool definitions**
Requests with a `conversation_id` are never cached, since they depend on conversation history that changes between calls.
## TTL Behavior
Cache entries expire automatically based on the content type:
| Mode | Typical TTL |
| - | - |
| `fast` / `auto` | Minutes |
| `think` / `code` | Minutes to hours |
| `research` | Not cached (async job) |
| `image` / `video` | Not cached (generative) |
TTLs are managed server-side and optimized for freshness vs. cost savings.
## Cache Scope
* Cache is **per-user** — your cached responses are not shared with other accounts
* Cache is **per-key** scoped when org-level keys are used
## Detecting Cache Hits
```typescript theme={null}
const res = await theo.complete({ prompt: "What is DNS?" });
if ((res as any)._cached) {
console.log("Cache hit! Cost: 0");
} else {
console.log(`Cache miss. Cost: ${res.usage.cost_cents}¢`);
}
```
## Cost Impact
For applications with repetitive queries (chatbots, dashboards, classification), semantic caching can reduce costs by 30–60%. Monitor your cache hit rate in the [Usage Dashboard](/dashboard/usage-analytics).
# Activating Skills via API
Source: https://docs.hitheo.ai/guides/skills-api
How to find skill slugs, pass them in API calls, and use them from the SDK.
Skills extend Theo with specialized capabilities — domain knowledge, custom tools, prompt extensions, and model preferences. You can activate skills on any completion request by passing their **slug**.
## Finding a Skill Slug
Every skill has a unique slug (e.g., `customer-support`, `code-review`, `deep-research`).
**In the Dashboard:**
1. Go to **Skills → Marketplace** or **My Skills**.
2. Each skill card displays its slug — click the copy icon to copy it.
**Via API:**
```bash theme={null}
# List all marketplace skills
curl -H "Authorization: Bearer $THEO_API_KEY" \
https://www.hitheo.ai/api/v1/skills
# List your installed skills
curl -H "Authorization: Bearer $THEO_API_KEY" \
"https://www.hitheo.ai/api/v1/skills?filter=installed"
```
Both return a `skills` array. Each object includes `slug`, `name`, `description`, and `category`.
**In the Skill Builder:**
When you open the Input node with **API Call** trigger, the canvas shows the skill's slug with a **Copy** button. If the canvas hasn't been published yet, it shows the draft slug preview.
## Using Skills in a Completion
Pass one or more slugs in the `skills` array:
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Summarize recent support tickets for this customer",
"skills": ["customer-support"]
}'
```
```typescript SDK theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
const res = await theo.complete({
prompt: "Summarize recent support tickets for this customer",
skills: ["customer-support"],
});
```
```python Python (requests) theme={null}
import requests
res = requests.post(
"https://www.hitheo.ai/api/v1/completions",
headers={"Authorization": f"Bearer {THEO_API_KEY}"},
json={
"prompt": "Summarize recent support tickets for this customer",
"skills": ["customer-support"],
},
)
```
## How It Works
When you pass `skills`:
1. **Slug resolution** — Theo looks up each slug and loads the skill's manifest (prompt extension, tools, model preference).
2. **Merge with installed skills** — The requested skills are merged with any skills you already have installed and enabled.
3. **Prompt injection** — Each active skill's system prompt extension is injected into the request context, ordered by priority and intensity.
4. **Tool aggregation** — Tools declared by active skills become available to the agent loop.
5. **Model preference** — If a skill specifies a preferred model (e.g., `theo-1-reason` for deep analysis), Theo may route to that model.
## Multiple Skills
You can activate multiple skills simultaneously:
```json theme={null}
{
"prompt": "Extract data from the attached ACORD 125 form and run a compliance check",
"skills": ["data-extraction", "insurance-compliance"]
}
```
Skills are applied in the order listed. If skills have conflicting model preferences, the first skill's preference takes precedence.
## Skills You Don't Have Installed
You can pass the slug of **any public skill** in the `skills` array — you don't need to install it first. Installing a skill means it's automatically included in every request; passing it in `skills` activates it for a single request.
## Building Your Own Skill
See [Build with the Skill Builder](/guides/evi-canvas) to create skills visually, or use the SDK:
```typescript theme={null}
import { defineSkill } from "@hitheo/sdk";
export default defineSkill({
name: "my-custom-skill",
tools: [myTool],
knowledge: ["./docs/*.md"],
});
// Publish: npx theo publish
```
After publishing, your skill's slug is available for use in `skills` arrays immediately.
# Telegram Bot Setup
Source: https://docs.hitheo.ai/guides/telegram-bot
Connect Theo to Telegram using the @hitheo/telegram adapter.
The `@hitheo/telegram` package connects Theo to Telegram as a bot. Users message your bot, Theo handles the response with the full orchestration pipeline, and the adapter replies through the Bot API.
Theo never hosts your bot. You create the bot with [@BotFather](https://t.me/BotFather), hold the token, and deploy this adapter on **your** infrastructure; Theo only processes the completion traffic the adapter forwards. That keeps every message, webhook URL, and credential under your control.
## Prerequisites
1. A Telegram bot token from [@BotFather](https://t.me/BotFather)
2. A Theo API key (`theo_sk_...`)
## Install
```bash npm theme={null}
npm install @hitheo/telegram
```
```bash yarn theme={null}
yarn add @hitheo/telegram
```
```bash pnpm theme={null}
pnpm add @hitheo/telegram
```
## Quick Setup
`createTelegramHandler` returns an async function that processes a single Telegram webhook update. Wire it into any HTTP framework — Express, Next.js route handlers, Cloudflare Workers, AWS Lambda, etc.
```typescript theme={null}
import express from "express";
import { createTelegramHandler } from "@hitheo/telegram";
const app = express();
app.use(express.json());
const handle = createTelegramHandler({
theoApiKey: process.env.THEO_API_KEY!,
telegramToken: process.env.TELEGRAM_BOT_TOKEN!,
secretToken: process.env.TELEGRAM_WEBHOOK_SECRET, // optional but recommended
mode: "auto",
skills: ["customer-support"],
persona: "You are a helpful assistant for Acme Corp.",
});
app.post("/webhook", async (req, res) => {
try {
await handle(req.body, {
secretToken: req.header("X-Telegram-Bot-Api-Secret-Token"),
});
res.sendStatus(200);
} catch (err) {
// TelegramSignatureError indicates an unauthorized POST.
res.sendStatus(401);
}
});
app.listen(3000, () => console.log("Telegram bot listening on :3000"));
```
## How It Works
1. User sends a message to your Telegram bot
2. Telegram POSTs the update to your webhook URL
3. The adapter verifies the `X-Telegram-Bot-Api-Secret-Token` header (when `secretToken` is configured)
4. The adapter forwards the text (and any photo/document attachments) to `POST /api/v1/completions`, reusing the `conversation_id` associated with that chat
5. Theo processes the request through the full pipeline (classification, skills, agent loop)
6. The response is sent back to the Telegram chat, split into multiple messages if needed
## Handler Config
| Option | Type | Required | Description |
| - | - | - | - |
| `theoApiKey` | `string` | ✅ | Your `theo_sk_...` API key |
| `telegramToken` | `string` | ✅ | Bot token from BotFather |
| `secretToken` | `string` | | Shared secret passed to `setWebhook`. When set, updates with a missing or mismatched header throw `TelegramSignatureError`. |
| `theoBaseUrl` | `string` | | API base URL (default: `https://www.hitheo.ai`) |
| `mode` | `ChatMode` | | Default mode — `auto`, `fast`, `think`, `code`, etc. |
| `persona` | `PersonaInput` | | Custom persona or `"theo"` / `"none"` |
| `skills` | `string[]` | | Skill slugs to activate on every message |
| `conversationStore` | `ConversationStore` | | Map chat IDs → Theo conversation IDs. Defaults to an in-process `Map`; swap for Redis/DB across instances. |
| `enableVoice` | `boolean` | | Transcribe voice/audio with Theo speech-to-text and append the transcript to the prompt. Off by default (STT adds cost). |
| `maxChunkChars` | `number` | | Max chars per outbound message. Default 4000. |
## Built-in Commands
The adapter handles three commands itself (no Theo call):
| Command | Behavior |
| - | - |
| `/start` | Sends an intro message |
| `/help` | Lists commands |
| `/reset` | Clears the stored `conversation_id` for this chat so the next message starts a fresh context |
Any other `/foo` command returns a short "Unknown command" reply.
## Attachments
Photos attached to messages (and image documents) are downloaded inside the adapter and forwarded to Theo as **base64 image data** — the adapter never passes a Telegram file URL to Theo. This keeps the bot token inside your deployment.
Always run the latest `@hitheo/telegram` release. If you are still on a `≤0.1.3` version, upgrade to `^0.1.4` and rotate the bot token via `@BotFather` as part of the upgrade.
Voice and audio messages are ignored unless you set `enableVoice: true`. When enabled, the adapter downloads the voice clip, runs it through Theo speech-to-text, and appends the transcript to the prompt as text. Voice is **not** sent as an attachment — Theo's completion endpoint only accepts image attachments.
## Setting Up the Webhook
Register your webhook URL with Telegram and include the `secret_token`:
```bash theme={null}
curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-domain.com/webhook",
"secret_token": "'"$TELEGRAM_WEBHOOK_SECRET"'"
}'
```
## Conversation Persistence Across Instances
The default `ConversationStore` is an in-process `Map` — fine for a single long-running server, wrong for serverless (each invocation is a fresh process). Provide your own store:
```typescript theme={null}
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
const handle = createTelegramHandler({
theoApiKey: process.env.THEO_API_KEY!,
telegramToken: process.env.TELEGRAM_BOT_TOKEN!,
conversationStore: {
get: (chatId) => redis.get(`tg:conv:${chatId}`),
set: async (chatId, id) => {
await redis.set(`tg:conv:${chatId}`, id, "EX", 60 * 60 * 24 * 30);
},
clear: async (chatId) => {
await redis.del(`tg:conv:${chatId}`);
},
},
});
```
## Deploying
Deploy as any Node.js HTTP server. For production:
* **Railway / Render / Fly.io** — easiest for webhook-based bots
* **Vercel / Cloudflare Workers** — serverless (one invocation per message); pair with a remote `conversationStore`
* **Docker + PM2** — self-hosted
Use `theo_sk_test_` keys during development to avoid billing.
# Voice Integration
Source: https://docs.hitheo.ai/guides/voice-integration
Add real-time voice conversations to your app using Theo's voice API.
Theo's voice system enables real-time conversational AI with speech-to-text,
text-to-speech, and live tool calling. Voice sessions share the same
persona, skills, and tools that power text completions, so a single
API key can drive both surfaces.
## How it works
A voice session is a streaming connection between your client and the
Theo voice runtime. Your app:
1. Captures microphone audio in the browser (or on device).
2. Requests a short-lived session token from Theo.
3. Opens the streaming voice connection using that token and plays back
Theo's audio response as it arrives.
Theo handles transcription, orchestration (persona, skills, tools,
memory), and text-to-speech behind the token. The client never talks to
any upstream model — every call is mediated by the Theo voice runtime.
## Getting a Voice Token
Before starting a voice session, request a session token:
```bash theme={null}
curl -X POST https://api.hitheo.ai/api/v1/voice/token \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
The response includes:
```json theme={null}
{
"token": "theo_voice_...",
"expiresAt": "2026-04-16T22:00:00Z",
"systemInstruction": "…Theo voice persona…",
"tools": [ { "functionDeclarations": [] } ]
}
```
The token endpoint returns `systemInstruction` and `tools` alongside the
token as a Theo platform contract. Your client MUST attach both when it
opens the live voice connection — otherwise the session starts without
the Theo persona and with no tool access.
The `systemInstruction` carries the Theo voice persona, platform context,
runtime protocol, and tool-usage guidance (plus memory and skill context
when present). The `tools` array includes every declared voice tool
(`generate_image`, `generate_video`, `deep_research`, `generate_code`,
`generate_document`, `save_memory`) and any installed skill tools
namespaced as `skill_{slug}_{toolName}`.
Voice selection is optional. Available voice identifiers are listed in
the dashboard under **Settings → Voice**.
## Transcription (STT)
Send audio for transcription via the STT endpoint:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/audio/stt \
-H "Authorization: Bearer $THEO_API_KEY" \
-F "file=@recording.webm" \
-F "language=en"
```
Returns `{ "text": "transcribed text" }`.
Supported formats: WebM, MP3, WAV, M4A, OGG. Max file size: 25MB.
## Text-to-Speech (TTS)
Convert text to audio:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/audio/tts \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "text": "Hello!", "voice": "theo-voice-warm" }' \
--output response.mp3
```
Voice selection is optional. See the [TTS reference](/api-reference/audio/text-to-speech) for the full list of Theo voice identifiers.
## Skill Tools in Voice
E.V.I. skills with tool definitions are automatically available in voice
sessions. The skill bridge exposes each skill's tools to the voice
runtime as function declarations:
* Tool names are namespaced as `skill_{slug}_{toolName}` to avoid collisions.
* Input schemas declared in the skill manifest are forwarded to the voice runtime.
* When the voice session calls a skill tool, Theo routes it to your skill's tool executor and feeds the result back into the live session.
## Voice Actions
During a live session, tools may fire mid-turn. Theo routes those calls
to:
```
POST /api/v1/voice/action
```
This endpoint executes the tool call (skill tool, web search, memory
lookup, code generation) and returns the result to the live session so
Theo can incorporate it into its response.
## Example Flow
```
User speaks → WebM audio blob
→ POST /api/v1/audio/stt → "What's the status of my latest order?"
→ Theo voice session (with customer-support skill tools)
→ Voice session calls skill_customer-support_lookup_order tool
→ POST /api/v1/voice/action → tool result
→ Voice session generates response with order status
→ POST /api/v1/audio/tts → audio response
→ Play audio to user
```
## API Reference
* [Speech to Text](/api-reference/audio/speech-to-text)
* [Text to Speech](/api-reference/audio/text-to-speech)
# Webhooks & Hook Events
Source: https://docs.hitheo.ai/guides/webhooks-and-hooks
Receive real-time notifications and trigger autonomous skill execution via webhooks and hooks.
Theo supports two complementary event systems for the Skill Builder Input node's **Webhook Event** and **Hook Event** trigger types.
## Webhooks — Outbound HTTP Notifications
Webhooks deliver events to your HTTP endpoints. When something happens in Theo (completion, job finish, skill install, etc.), a signed POST is sent to every matching endpoint.
### Register a Webhook
```bash curl theme={null}
curl -X POST https://www.hitheo.ai/api/v1/webhooks \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-server.com/webhooks/theo",
"event_types": ["completion.created", "job.completed"]
}'
```
```typescript SDK theme={null}
const webhook = await theo.createWebhook({
url: "https://your-server.com/webhooks/theo",
event_types: ["completion.created", "job.completed"],
});
// Save webhook.signing_secret — shown once only
```
The response includes a `signing_secret` — save it securely. It's shown once and used to verify payloads.
### Event Catalog
| Event | Description |
| - | - |
| `completion.created` | A completion was generated |
| `job.completed` / `job.failed` | Background job finished |
| `workflow.completed` / `workflow.failed` | Workflow run finished |
| `skill.installed` / `skill.uninstalled` | Skill install/uninstall |
| `skill.submitted` / `skill.approved` / `skill.rejected` | Skill review |
| `connector.created` / `connector.status_changed` | Connector events |
| `credits.low` | Credit balance low |
| `key.created` / `key.revoked` | API key events |
Use `"*"` as an event type to receive all events.
### Verify Signatures
Every delivery includes HMAC-SHA256 signatures:
```
Theo-Webhook-Signature: v1=
Theo-Webhook-Timestamp:
Theo-Webhook-Id:
```
Verify by computing `HMAC-SHA256(signing_secret, timestamp + "." + raw_body)` and comparing. Reject if the timestamp drifts more than 5 minutes.
### Retry Behavior
* Automatic retries with exponential backoff on transient failures
* Per-attempt timeout enforced server-side
* 4xx errors are not retried (client errors)
* Webhooks are auto-disabled after a sustained run of failed deliveries
* Every attempt — successful or failed — is recorded in the delivery log
### Manage Webhooks
* `GET /api/v1/webhooks` — List all webhooks
* `PATCH /api/v1/webhooks/{id}` — Update URL, event types, enable/disable
* `DELETE /api/v1/webhooks/{id}` — Remove
* `POST /api/v1/webhooks/{id}/test` — Send a test event
* `GET /api/v1/webhooks/{id}/deliveries` — View delivery log
***
## Hook Events — Autonomous Skill Triggers
Hooks are internal event triggers that automatically execute skills when events occur — no HTTP endpoint needed. The skill runs headless via the autonomous executor with credit guards.
### How Hooks Work
1. An event is published (via `POST /api/v1/events` or internal platform events)
2. The hook evaluator checks all enabled hooks for pattern matches
3. Matching hooks load the associated skill and execute it autonomously
4. Results are recorded in the execution log
### Hook Presets
| Preset | Event Pattern | Default Skill | Description |
| - | - | - | - |
| `share.accepted.welcome` | `share.accepted` | `email-drafter` | Welcome on share accept |
| `task.overdue.summary` | `task.overdue` | `todo-manager` | Summarize overdue tasks |
| `project.created.suggestions` | `project.created` | `document-analyzer` | Suggest project next steps |
| `team.member_joined.onboarding` | `team.member_joined` | `email-drafter` | Onboarding guidance |
| `document.analyzed.followup` | `document.analyzed` | `document-analyzer` | Follow-up action items |
### Install a Hook
```bash curl theme={null}
# Using a preset
curl -X POST https://www.hitheo.ai/api/v1/hooks \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"hook_preset_id": "share.accepted.welcome",
"skill_slug": "email-drafter"
}'
# Using a custom event pattern
curl -X POST https://www.hitheo.ai/api/v1/hooks \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"event_pattern": "order.*.completed",
"skill_slug": "my-order-processor",
"cooldown_minutes": 5
}'
```
```typescript SDK theme={null}
// Preset
await theo.createHook({
hook_preset_id: "share.accepted.welcome",
skill_slug: "email-drafter",
});
// Custom pattern
await theo.createHook({
event_pattern: "order.*.completed",
skill_slug: "my-order-processor",
cooldown_minutes: 5,
});
```
### Custom Event Patterns
Patterns support:
* **Exact match**: `share.accepted` matches only `share.accepted`
* **Glob wildcard**: `order.*.completed` matches `order.purchase.completed`, `order.return.completed`
* **Prefix match**: `share` matches `share.accepted`, `share.declined`, etc.
* **Catch-all**: `*` matches everything
### Publishing Events
Use `POST /api/v1/events` to publish domain events that trigger hooks and webhooks:
```typescript theme={null}
await theo.publishEvent({
orgId: "your-org-id",
eventType: "order.purchase.completed",
payload: { orderId: "ORD-123", total: 299.99 },
});
```
### Guard Rails
Autonomous execution runs under strict safety limits:
* Pre-flight credit check before each run
* Separate daily cap for autonomous actions
* Per-run caps on tool invocations and total spend
* Credit checkpoint between steps
* Hooks auto-pause after repeated failures
* Configurable cooldown between firings to prevent runaway execution
### Manage Hooks
* `GET /api/v1/hooks` — List hooks (includes available presets)
* `PATCH /api/v1/hooks/{id}` — Update config, enable/disable
* `DELETE /api/v1/hooks/{id}` — Remove
* `GET /api/v1/hooks/{id}` — View execution history
# WhatsApp Integration
Source: https://docs.hitheo.ai/guides/whatsapp-integration
Connect Theo to WhatsApp using the @hitheo/whatsapp adapter.
The `@hitheo/whatsapp` package connects Theo to the WhatsApp Cloud API. Customers message your WhatsApp number and the adapter forwards each message to `POST /api/v1/completions`, then replies via the Cloud API.
Theo never hosts your WhatsApp number or tokens. You own the WhatsApp Business Account in Meta Business Suite, hold the access token, and deploy this adapter on **your** infrastructure; Theo only processes the completion traffic the adapter forwards. Your customers message your brand, not ours.
## Prerequisites
1. A WhatsApp Business API account (via Meta Business Suite)
2. A Theo API key (`theo_sk_...`)
3. A webhook URL for receiving incoming messages
4. The Meta App Secret (used to verify webhook signatures)
## Install
```bash npm theme={null}
npm install @hitheo/whatsapp
```
```bash yarn theme={null}
yarn add @hitheo/whatsapp
```
```bash pnpm theme={null}
pnpm add @hitheo/whatsapp
```
## Quick Setup
The package exports three functions:
* `createWhatsAppHandler(config)` — returns an async function that processes a WhatsApp webhook payload.
* `verifyWebhook(params)` — validates the Meta GET challenge during webhook registration.
* `verifySignature(rawBody, headerSig, appSecret)` — HMAC-SHA256 signature check for the inbound POST. You MUST pass the **raw** request body (bytes), not a re-parsed JSON object.
```typescript theme={null}
import express from "express";
import {
createWhatsAppHandler,
verifyWebhook,
verifySignature,
} from "@hitheo/whatsapp";
const app = express();
const handle = createWhatsAppHandler({
theoApiKey: process.env.THEO_API_KEY!,
whatsappToken: process.env.WHATSAPP_TOKEN!,
phoneNumberId: process.env.WHATSAPP_PHONE_ID!,
appSecret: process.env.WHATSAPP_APP_SECRET!,
mode: "auto",
skills: ["customer-support"],
});
// GET webhook verification
app.get("/webhook", (req, res) => {
const challenge = verifyWebhook({
mode: req.query["hub.mode"] as string,
token: req.query["hub.verify_token"] as string,
challenge: req.query["hub.challenge"] as string,
verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!,
});
if (challenge) return res.send(challenge);
res.sendStatus(403);
});
// POST webhook — signature-verified, then handed off to the adapter
app.post(
"/webhook",
express.raw({ type: "application/json" }),
async (req, res) => {
const ok = verifySignature(
req.body, // Buffer because of express.raw
req.header("x-hub-signature-256"),
process.env.WHATSAPP_APP_SECRET!,
);
if (!ok) return res.sendStatus(401);
const payload = JSON.parse(req.body.toString("utf8"));
await handle(payload);
res.sendStatus(200);
},
);
app.listen(3000, () => console.log("WhatsApp bot listening on :3000"));
```
## How It Works
1. Customer sends a WhatsApp message
2. Meta POSTs the webhook payload with an `X-Hub-Signature-256` header
3. Your HTTP layer verifies the signature via `verifySignature`
4. The adapter iterates over messages, forwards text and media to Theo (with a per-sender `conversation_id`), and sends Theo's response back via the Cloud API
5. Status events (`delivered`, `read`) are acknowledged silently — no duplicate replies
## Handler Config
| Option | Type | Required | Description |
| - | - | - | - |
| `theoApiKey` | `string` | ✅ | Your `theo_sk_...` API key |
| `whatsappToken` | `string` | ✅ | WhatsApp Cloud API access token |
| `phoneNumberId` | `string` | ✅ | Your WhatsApp phone number ID |
| `appSecret` | `string` | | Meta App Secret. Store it in your environment and pass it to `verifySignature`; the adapter itself never reads network traffic. |
| `theoBaseUrl` | `string` | | API base URL (default: `https://www.hitheo.ai`) |
| `mode` | `ChatMode` | | Default mode |
| `persona` | `PersonaInput` | | Custom persona or `"theo"` / `"none"` |
| `skills` | `string[]` | | Skill slugs to activate on every message |
| `conversationStore` | `ConversationStore` | | Map sender numbers → Theo conversation IDs. Defaults to an in-process `Map`. |
| `enableVoice` | `boolean` | | Transcribe voice/audio with Theo speech-to-text and append the transcript to the prompt. Off by default (STT adds cost). |
| `maxChunkChars` | `number` | | Max chars per outbound message. Default 4000. |
## Attachments
Image messages (and `image/*` documents) are downloaded inside the adapter and forwarded to Theo as **base64 image data**. The adapter presents the Meta access token to the Graph API to fetch the bytes, but never passes the tokenized Graph CDN URL onwards — so no credentials leave your deployment. Captions become the prompt text.
Voice and audio messages are ignored unless you set `enableVoice: true`. When enabled, the adapter downloads the clip, transcribes it with Theo speech-to-text, and appends the transcript to the prompt as text.
## Conversation Persistence Across Instances
The default `ConversationStore` is in-process. For serverless or multi-instance deployments, plug in Redis or your database:
```typescript theme={null}
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL!);
const handle = createWhatsAppHandler({
theoApiKey: process.env.THEO_API_KEY!,
whatsappToken: process.env.WHATSAPP_TOKEN!,
phoneNumberId: process.env.WHATSAPP_PHONE_ID!,
conversationStore: {
get: (from) => redis.get(`wa:conv:${from}`),
set: async (from, id) => {
await redis.set(`wa:conv:${from}`, id, "EX", 60 * 60 * 24 * 30);
},
clear: async (from) => {
await redis.del(`wa:conv:${from}`);
},
},
});
```
Use `theo_sk_test_` keys during development to avoid billing.
# Workflow Automation
Source: https://docs.hitheo.ai/guides/workflow-automation
Build multi-step automated workflows with schedules and event triggers.
Workflows chain AI tasks together with scheduling, conditional logic, and notifications.
## Create a Workflow
```typescript theme={null}
const workflow = await theo.createWorkflow({
name: "Weekly Newsletter Draft",
triggerType: "schedule",
triggerConfig: { cron: "0 9 * * 1" },
steps: [
{
type: "ai_transform",
name: "Research trends",
config: { prompt: "Research top AI trends this week", skills: ["deep-research"] },
},
{
type: "ai_transform",
name: "Draft newsletter",
config: { prompt: "Draft a newsletter from the research above", skills: ["content-writer"] },
},
{
type: "notification",
name: "Send draft",
config: { channel: "email", to: "editor@acme.com" },
},
],
});
```
## Trigger Types
| Type | Description |
| - | - |
| `schedule` | Cron-based schedule |
| `event` | Triggered by system events |
| `manual` | Triggered via API call |
# Theo Documentation
Source: https://docs.hitheo.ai/index
AI orchestration API — one call, every model, full pipeline.
Meet Theo — the AI orchestration engine with a personality. Intent classification, multi-engine routing, skills, and tool execution, all in one API call. Born on Jupiter, built for developers.
## Get Started
Sign up and create a key in 30 seconds.
Make your first API call with curl.
Set up @hitheo/sdk for TypeScript.
Build a working example in 5 minutes.
## Explore
REST API docs for all endpoints.
TypeScript SDK methods and types.
Build and publish domain expertise packages.
Embed Theo in your product with a custom persona.
Use Theo in Cursor, Claude Code, Warp, and more.
The @hitheo/mcp server, its 8 tools, and 3 resources.
theo init, status, complete, skill publish.
## Set Up in Your IDE
First, set your API key as an environment variable:
```bash theme={null}
export THEO_API_KEY=theo_sk_...
```
Then pick your IDE:
Add to `.cursor/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide cursor
```
Run this in your terminal:
```bash theme={null}
claude mcp add theo npx -y @hitheo/mcp
```
Or run:
```bash theme={null}
theo mcp install --ide claude-code
```
Add to `.warp/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide warp
```
Add to `~/.codeium/windsurf/mcp_config.json`:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide windsurf
```
Add to `.vscode/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide vscode
```
Auto-detect and configure all installed IDEs at once:
```bash theme={null}
npm install -g @hitheo/sdk
theo init
```
This detects Cursor, Claude Code, Warp, Windsurf, and VS Code, writes the correct config for each, and creates a `theo.config.json` for project-level settings.
Restart your IDE after adding the config.
# How Theo Thinks
Source: https://docs.hitheo.ai/introduction/how-theo-thinks
The multi-stage orchestration pipeline behind every API call.
Every time you call `POST /api/v1/completions`, Theo runs a multi-stage orchestration pipeline — not a single model call. You send one request, and Theo handles classification, routing, skill injection, tool execution, fallback, and billing automatically.
## The Pipeline
```
Your prompt
│
▼
┌─────────────────────┐
│ Intent Classifier │ ← Determines the best execution mode
│ Determines: mode, │
│ confidence, tools │
└────────┬────────────┘
│
▼
┌─────────────────────┐
│ Skill Loader │ ← Loads installed skills + per-request skill slugs
│ Merges: prompts, │
│ tools, engine prefs │
└────────┬────────────┘
│
▼
┌─────────────────────┐
│ Engine Router │ ← Selects the optimal Theo engine
│ Checks: availability│ Falls back automatically if primary is down
│ + failover │
└────────┬────────────┘
│
▼
┌─────────────────────┐
│ Agent Loop │ ← Think → act → observe, iterates until done
│ Calls tools, feeds │
│ results back in │
└────────┬────────────┘
│
▼
┌─────────────────────┐
│ Response │ ← Formatted, billed, cached, audited
└─────────────────────┘
```
## Stage 1: Intent Classification
When you send `mode: "auto"` (the default), Theo classifies your prompt to determine the best execution mode.
Theo uses a multi-tier classification system that combines fast heuristics with AI-powered analysis to accurately route your request. Obvious signals (e.g., "Draw me a logo" → `image`) are detected instantly. Ambiguous prompts are analyzed more deeply.
**Override:**
If you pass `mode: "code"` explicitly, classification is skipped entirely.
The resolved mode determines which Theo engine handles the request, what system prompt is used, and which follow-up suggestions are offered.
## Stage 2: Skill Loading
Skills are loaded from two sources:
1. **Installed skills** — persistent skills loaded on every request
2. **Per-request skills** — skill slugs passed in the `skills[]` array, loaded on-demand
Each loaded skill contributes:
* **System prompt extension** — domain-specific instructions injected into the context
* **Tool definitions** — callable actions the engine can invoke
* **Engine preference** — the skill can recommend which Theo engine handles its tasks best
All skill prompts are aggregated and sandboxed so they don't interfere with each other.
## Stage 3: Engine Routing
Theo selects the optimal engine based on the resolved mode:
|| Mode | Engine | Description |
||------|--------|-------------|
|| fast / auto | `theo-1-flash` | Fast, lightweight completions |
|| think | `theo-1-reason` | Deep reasoning and analysis |
|| code | `theo-1-code` | Production-quality code generation |
|| image | `theo-1-create` | Image generation |
|| video | `theo-1-motion` | Video generation |
|| research | `theo-1-research` | Multi-step web research |
|| roast | `theo-1-edge` | Unfiltered humor |
|| genui | `theo-1-genui` | Generative UI components |
If the primary engine is unavailable, Theo automatically fails over to a backup — you never see a broken response.
## Stage 4: Agent Loop
For requests with available tools, Theo enters an iterative agent loop:
```
Iteration 0: Engine reads prompt + system prompt + tool definitions
→ Responds with text AND a tool call
→ Theo executes the tool, gets result
Iteration 1: Engine reads the tool result + previous context
→ Responds with text (no more tool calls)
→ Final response returned to caller
```
The loop continues until the task is complete or the iteration limit is reached. For simple prompts with no tools, the loop collapses to a single call — no overhead.
## Stage 5: Response
The final response includes:
* `content` — the generated text
* `model` — which Theo engine handled it (e.g., `theo-1-reason`)
* `tools_used` — which tools were called and their status
* `artifacts` — any generated files (images, code, documents)
* `follow_ups` — suggested next prompts
* `usage` — token counts and cost in cents
The response is also **billed**, **cached** (identical requests return instantly at zero cost), and **audited** (logged to the immutable audit trail).
# Theo vs. Alternatives
Source: https://docs.hitheo.ai/introduction/theo-vs-alternatives
How Theo compares to model proxies, LangChain, and direct model APIs.
## The Developer's Choice
You want AI in your product. You have options:
1. **Direct model APIs** — Call a single provider directly
2. **Model proxy** — Use a unified gateway for multi-model access
3. **Framework** — Build your own pipeline with LangChain / LangGraph
4. **Orchestration API** — Use Theo for classification, routing, skills, tools, and billing in one call
## Comparison
| Capability | Direct API | Model Proxy | LangChain | **Theo** |
| - | - | - | - | - |
| Model access | 1 provider | 300+ models | Any (you configure) | 300+ models |
| Intent classification | ❌ | ❌ | Build it | ✅ Built-in |
| Model routing | ❌ | Manual | Build it | ✅ Automatic |
| Automatic failover | ❌ | ✅ | Build it | ✅ Built-in |
| Tool execution | Provider-specific | ❌ | Build it | ✅ Agent loop |
| Skills / domain expertise | ❌ | ❌ | ❌ | ✅ Marketplace |
| Custom persona (E.V.I.) | Build it | ❌ | Build it | ✅ One parameter |
| Memory | ❌ | ❌ | Build it | ✅ Cross-session |
| Streaming | ✅ | ✅ | Build it | ✅ SSE |
| Billing / credits | Provider billing | ✅ | ❌ | ✅ Per-token |
| Semantic cache | ❌ | ❌ | Build it | ✅ Built-in |
| Audit trail | ❌ | ❌ | Build it | ✅ Immutable |
| Time to production | Weeks | Days | Months | **Hours** |
## Code Comparison
### DIY Approach — You handle everything
```typescript theme={null}
const model = pickModelForTask(prompt); // you build this
const skills = loadDomainKnowledge(userContext); // you build this
const tools = resolveToolDefinitions(skills); // you build this
const systemPrompt = buildPrompt(persona, skills, tools); // you build this
const response = await llmProvider.complete({ model, messages, tools });
const toolResults = await executeTools(response.tool_calls); // you build this
const finalResponse = await llmProvider.complete({ model, messages: [..., toolResults] });
await debitCredits(user, response.usage); // you build this
await logAudit(user, response); // you build this
```
### Theo — One call
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: "theo_sk_..." });
const response = await theo.complete({
prompt: "Check inventory across all warehouses",
skills: ["inventory-check"],
persona: { system_prompt: "You are Nova..." },
});
```
## When to Use What
**Use Theo when:**
* You want AI features without building orchestration infrastructure
* You need multi-model routing with automatic failover
* You want domain expertise via installable skills
* You're building an E.V.I. (embedded AI with custom persona)
* You need built-in billing, caching, and audit
**Use a model proxy when:**
* You just need model access with unified billing
* You're building your own orchestration layer
**Use LangChain when:**
* You need total control over every pipeline decision
* Your use case requires custom agent architectures
* You have the engineering team to build and maintain the infrastructure
**Use direct APIs when:**
* You only need one model from one provider
* You have specific provider requirements (SLA, data residency)
# What is Theo?
Source: https://docs.hitheo.ai/introduction/what-is-theo
AI orchestration API — one call, every model, full pipeline.
Theo is an **AI orchestration engine** exposed as a developer API. Instead of calling individual model providers and building your own classification, routing, tool execution, and billing infrastructure, you call `POST /api/v1/completions` and Theo handles everything.
## What Theo Does
When you send a prompt to Theo, a multi-stage pipeline runs automatically:
1. **Intent Classification** — Determines what kind of task the prompt is (code, research, image, etc.)
2. **Skill Loading** — Loads domain expertise packages (installed + per-request) that inject system prompt extensions and tool definitions
3. **Model Routing** — Selects the optimal Theo engine for the task, with automatic failover
4. **Agent Loop** — Iteratively reasons, calls tools, and feeds results back until the task is complete
5. **Response** — Returns formatted content with engine info, tool execution log, artifacts, follow-up suggestions, and usage data
All of this happens in one API call.
## Key Capabilities
Multi-model AI completions with automatic intent classification and routing.
Installable packages of domain knowledge and tools — like apps for AI.
Embed Theo into your product with a custom persona. Your users see your brand, not Theo.
Theo Code engine with an extended output budget for long-form, best-in-class code.
Theo Create engine for photorealistic images with automatic fallback.
Deep web research with source synthesis and citations.
Generate PDFs, DOCX, PPTX, XLSX, and CSV files.
Multi-step automations with schedules, event triggers, and conditional logic.
## Architecture at a Glance
```
Your App → @hitheo/sdk → Theo API (api.hitheo.ai)
│
┌─────────┼─────────┐
▼ ▼ ▼
Classifier Skill Model
Loader Router
│
▼
Agent Loop
(think → act → observe)
│
▼
Response + Billing + Audit
```
## Who It's For
* **Product developers** embedding AI into their apps via the SDK or REST API
* **Agencies and SaaS companies** building branded AI assistants (E.V.I.) for their customers
* **Skill authors** creating and monetizing domain-specific AI capabilities on the marketplace
## How to Get Started
Sign up at [api.hitheo.ai](https://api.hitheo.ai) and create a key from the dashboard. Keys are prefixed `theo_sk_`.
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer theo_sk_..." \
-H "Content-Type: application/json" \
-d '{"prompt": "Explain quantum computing in one paragraph", "mode": "auto"}'
```
```bash theme={null}
npm install @hitheo/sdk
```
# Let an agent set up your key
Source: https://docs.hitheo.ai/mcp/agent-setup
Have Claude / Cursor / Warp configure a Theo API key for you via the MCP server — one call, no manual orchestrator building.
You don't have to open the dashboard and wire an orchestrator by hand. From any MCP-connected IDE (Claude Code, Cursor, Warp, Windsurf), the agent can create and configure a Theo key for a specific use case in a single tool call — and the result shows up in your hitheo dashboard immediately, ready to review or extend.
## The fast path: "just coding"
Ask the agent, in plain language:
```text theme={null}
Set up a Theo key I can use as my coding model in this IDE.
```
The agent calls [`theo_setup_key`](/mcp/tools#theo_setup_key) with `use_case="coding"`. Theo:
1. Creates a new API key.
2. Pins it to a single strong code engine as a **deterministic passthrough** — no intent classification, skills, or guardrail routing, so every request goes straight to the coding model with no surprises.
3. Returns the raw key (shown once) and a dashboard link.
You copy the key into your IDE's Theo/OpenAI-compatible endpoint setting and you're done. No canvas, no nodes.
## Use cases
| `use_case` | What it does |
| - | - |
| `coding` | Pins a code engine (deterministic passthrough). Best for IDE backends. |
| `chat` | Pins a fast chat engine. |
| `raw` | Pins whatever engine you name (`model` argument required). |
Pass a `model` to override the default for any use case, e.g. `use_case="raw", model="anthropic/claude-opus-4.8"`.
## Route by load (or any per-mode split)
Want light requests on a fast engine and heavy ones on a reasoning engine? Describe it, and the agent passes a `routing` array — Theo's classifier splits each request into a mode and the binding pins that mode's engine. No graph to build.
```text theme={null}
Set up a Theo coding key where light requests use Arca Velox and heavy ones use Arca Magnus.
```
The agent calls [`theo_setup_key`](/mcp/tools#theo_setup_key) with:
```json theme={null}
{
"routing": [
{ "mode": "fast", "model": "arca-velox-5.1" },
{ "mode": "think", "model": "arca-magnus-5.1" }
]
}
```
Modes: `fast`, `think`, `code`, `research`, `roast`, `genui`, `data_extraction`. Engine ids include `arca-velox-5.1`, `arca-magnus-5.1`, `anthropic/claude-sonnet-4.6`, `anthropic/claude-opus-4.8`, `anthropic/claude-haiku-4.5`, `google/gemini-2.5-pro`, `openai/gpt-4.1`.
## Custom logic → a full graph
For arbitrary branching/guardrail logic the user describes in prose, the agent can pass a `graph` (`{ enabled, nodes, edges }`) — a full orchestrator graph, applied as-is. See the [Canvas graph schema](/guides/evi-canvas) for node/edge shapes. `graph` takes precedence over `routing` and `use_case`.
## Configure a key you already have
```text theme={null}
Configure my existing key for coding.
```
The agent calls [`theo_configure_key`](/mcp/tools#theo_configure_key). Same presets, applied to the key you name.
## It round-trips to the dashboard
Both tools return a link like:
```text theme={null}
https://www.hitheo.ai/dashboard/orchestrator?key=
```
Open it and the Orchestrator lands directly on that key, showing exactly what the agent set up. From there you can layer on routing rules, skills, guardrails, or brand — the visual builder and the agent edit the same underlying config.
## Requirements
* The MCP server must be authenticated with a key that has the **`billing`** scope (needed to create keys). See [Install](/mcp/install).
* The created key ships with `completions`, `skills`, and `tools` scopes.
## See also
* [MCP tools reference](/mcp/tools) — full input schemas for `theo_setup_key` / `theo_configure_key`.
* [Orchestrator guide](/guides/orchestrator) — the dashboard surface the link opens.
# Install MCP
Source: https://docs.hitheo.ai/mcp/install
Set up @hitheo/mcp in Cursor, Claude Code, Warp, Windsurf, VS Code, or any other MCP-compatible IDE.
You have three ways to install Theo's MCP server, in increasing order of manual effort:
1. **`theo init`** — recommended. Detects every supported IDE on your machine and writes the right config for each in one shot.
2. **`theo mcp install --ide `** — targets a single IDE.
3. **Hand-written `mcp.json`** — for unusual setups or IDEs we haven't bundled detection for.
All three install the same package (`@hitheo/mcp`) and point each IDE at it via `npx -y @hitheo/mcp`. They differ only in which config files they touch.
Every method requires the `THEO_API_KEY` environment variable to be set in the shell that launches your IDE. [Get a key](https://api.hitheo.ai) if you don't have one, or run `theo login` to walk through it.
## Prerequisites
* **Node.js 18+** with `npx` on `$PATH` (any LTS install will do).
* **A Theo API key** of the form `theo_sk_…` exported as `THEO_API_KEY` in your shell.
* *(optional)* The `@hitheo/sdk` package installed globally for the `theo` CLI:
```bash theme={null}
npm install -g @hitheo/sdk
```
## Method 1 — `theo init` (recommended)
`theo init` does the full project bootstrap in one command:
```bash theme={null}
cd your-project
theo init
```
It will:
1. Create `theo.config.json` (project-level [config](/mcp/project-config)).
2. Detect installed IDEs (Cursor, Claude Code, Warp, Windsurf, VS Code).
3. Write the matching `mcp.json` for each detected IDE.
4. Generate `.theo/RULES.md` so your IDE agent knows the tools exist.
Example output:
```text theme={null}
[theo] Initializing Theo in this project...
[theo] ✓ Created theo.config.json
[theo] Detecting IDEs...
[theo] Found: Cursor, Warp
[theo] Writing MCP configurations...
[theo] ✓ Cursor: .cursor/mcp.json
[theo] ✓ Warp: .warp/mcp.json
[theo] Generating agent context...
[theo] ✓ Created .theo/RULES.md
[theo] ✅ Theo initialized!
```
Restart each IDE after the command finishes.
## Method 2 — `theo mcp install --ide `
Use this when you want MCP set up for a single IDE without touching the others, or to re-run after installing a new IDE:
```bash theme={null}
theo mcp install --ide cursor # one IDE
theo mcp install --ide all # every supported IDE
theo mcp install # auto-detect installed IDEs
```
Supported `--ide` values: `cursor`, `claude-code`, `warp`, `windsurf`, `vscode`, `all`.
See the [`theo mcp install`](/cli-reference/mcp-install) CLI reference for the full flag list.
## Method 3 — Hand-written config
Every IDE we support reads a JSON file with an `mcpServers.` entry. The block is identical across IDEs:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": { "THEO_API_KEY": "${env:THEO_API_KEY}" }
}
}
}
```
The IDE expands `${env:THEO_API_KEY}` to the value from the shell that launched it, so you never commit a key into the repo. Drop the block at the IDE-specific path below.
**Path**: `/.cursor/mcp.json`
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": { "THEO_API_KEY": "${env:THEO_API_KEY}" }
}
}
}
```
Cursor picks up the file when you reopen the project. The Theo tools appear under the agent's tool menu as `theo_complete`, `theo_image`, and so on.
**Path**: `/.mcp.json`, or use the CLI helper:
```bash theme={null}
claude mcp add theo npx -y @hitheo/mcp
```
Either approach is fine. The CLI helper writes to the same `.mcp.json` plus an entry in Claude Code's per-user store, so it survives across projects.
**Path**: `/.warp/mcp.json`
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": { "THEO_API_KEY": "${env:THEO_API_KEY}" }
}
}
}
```
Warp's agent will list Theo's tools the next time the project is opened.
**Path**: `~/.codeium/windsurf/mcp_config.json` (user-level, not per-project).
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": { "THEO_API_KEY": "${env:THEO_API_KEY}" }
}
}
}
```
Restart Windsurf — the config is read once at boot.
**Path**: `/.vscode/mcp.json`
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": { "THEO_API_KEY": "${env:THEO_API_KEY}" }
}
}
}
```
Requires a VS Code build with MCP support enabled (Insiders or a recent stable release). Reload the window after writing the file.
Any IDE that follows the MCP `command` / `args` / `env` config shape (most do) works with the same block. Drop it wherever that IDE expects MCP server config, set `THEO_API_KEY`, and restart.
If you have to invoke `node` directly instead of `npx`, install the package globally and point at the binary:
```bash theme={null}
npm install -g @hitheo/mcp
which theo-mcp # absolute path; e.g. /usr/local/bin/theo-mcp
```
Then use `"command": "theo-mcp"` with an empty `args` array.
## Verify the install
After restarting your IDE, ask the agent something only Theo can answer to confirm the tools are loaded:
> "Use the Theo MCP server to run a status check."
If the agent doesn't see the tools, see [Troubleshooting](/mcp/troubleshooting). The most common cause is a missed restart; the second most common is `THEO_API_KEY` set in a different shell than the one that launched the IDE.
## What gets written where
| File | Purpose | Source of truth |
| - | - | - |
| `theo.config.json` | Persona, skills, default mode, inline tools | [Project Config](/mcp/project-config) |
| `.theo/RULES.md` | Agent-facing description of Theo's tools | Auto-generated; safe to edit |
| `.cursor/mcp.json` | Cursor MCP config | Standard MCP block above |
| `.mcp.json` | Claude Code MCP config | Standard MCP block above |
| `.warp/mcp.json` | Warp MCP config | Standard MCP block above |
| `~/.codeium/windsurf/mcp_config.json` | Windsurf user-level MCP config | Standard MCP block above |
| `.vscode/mcp.json` | VS Code MCP config | Standard MCP block above |
`theo init` is idempotent — re-running it merges into existing files rather than overwriting them.
# MCP Server Overview
Source: https://docs.hitheo.ai/mcp/overview
How Theo plugs into Cursor, Claude Code, Warp, Windsurf, VS Code, and any other MCP-compatible IDE via @hitheo/mcp.
Theo exposes its full orchestration engine as a local **Model Context Protocol (MCP)** server, published as the [`@hitheo/mcp`](https://www.npmjs.com/package/@hitheo/mcp) npm package. Any MCP-compatible IDE — Cursor, Claude Code, Warp, Windsurf, VS Code, and others — can launch it on demand and call Theo as a set of tools and resources.
## What is MCP
The [Model Context Protocol](https://modelcontextprotocol.io) is an open standard for letting an LLM-powered agent invoke tools and read resources hosted by a separate process. The host (your IDE's agent) speaks JSON-RPC over stdio to a server (`@hitheo/mcp`) and receives back a typed catalog of tools, resources, and prompts.
Concretely, MCP gives your IDE three primitives:
| Primitive | What it is | Theo example |
| - | - | - |
| **Tool** | A callable function with a JSON-Schema input | `theo_complete`, `theo_image` |
| **Resource** | A read-only URL the agent can fetch for context | `theo://models`, `theo://health` |
| **Prompt** | A reusable prompt template | *(not exposed by `@hitheo/mcp` today)* |
## What `@hitheo/mcp` does
`@hitheo/mcp` is a **stdio MCP server** that wraps the official `@hitheo/sdk` and forwards calls to the Theo REST API (`https://www.hitheo.ai/api/v1/*`). It is not a separate Theo backend — it is a thin local adapter that converts MCP tool calls into authenticated API calls using your `THEO_API_KEY`.
This means every tool you invoke from an IDE agent runs through the exact same orchestration pipeline (intent classification → model routing → skills → tool execution) as a direct API call. Skills you have installed, custom personas, project tools — all of it applies inside the IDE.
## Surface area
The server currently exposes:
* **8 tools**: [`theo_complete`](/mcp/tools#theo_complete), [`theo_code`](/mcp/tools#theo_code), [`theo_research`](/mcp/tools#theo_research), [`theo_image`](/mcp/tools#theo_image), [`theo_document`](/mcp/tools#theo_document), [`theo_skill_list`](/mcp/tools#theo_skill_list), [`theo_skill_install`](/mcp/tools#theo_skill_install), [`theo_status`](/mcp/tools#theo_status).
* **3 resources**: [`theo://models`](/mcp/resources#theo-models), [`theo://skills/installed`](/mcp/resources#theo-skills-installed), [`theo://health`](/mcp/resources#theo-health).
* **Project config**: an optional [`theo.config.json`](/mcp/project-config) in the repo root that injects `persona`, `skills`, `tools`, `defaultMode`, `temperature`, and `metadata` into every tool call.
## Request flow
```mermaid theme={null}
sequenceDiagram
participant IDE as IDE Agent
participant MCP as @hitheo/mcp (stdio)
participant SDK as @hitheo/sdk
participant API as api.hitheo.ai
IDE->>MCP: tools/call theo_complete { prompt }
MCP->>MCP: load theo.config.json (cwd)
MCP->>SDK: client.complete({ prompt, persona, skills, ... })
SDK->>API: POST /api/v1/completions
API-->>SDK: { content, model, usage, ... }
SDK-->>MCP: typed response
MCP-->>IDE: text content (Theo's reply)
```
A few invariants worth knowing:
1. **The IDE launches the server**, not you. IDEs spawn `npx -y @hitheo/mcp` on demand and tear it down when the workspace closes.
2. **Transport is stdio**. There is no inbound network port; the server only makes outbound HTTPS calls to `https://www.hitheo.ai`.
3. **Auth is your normal API key**. `THEO_API_KEY` is read once at startup and reused for every request. The key never leaves the server process; the IDE never sees it.
4. **`theo.config.json` is loaded from the current working directory** (the IDE workspace root) at startup. JS/TS variants are ignored by default — see [Security](/mcp/security).
## How it compares to the SDK and REST API
| Use case | Best surface |
| - | - |
| Inside an IDE agent, no code to write | **MCP** (`@hitheo/mcp`) |
| Your own TypeScript/Node app or worker | **SDK** ([`@hitheo/sdk`](/sdk-reference/installation)) |
| Any other language, CI, curl, webhooks | **REST** ([`/api/v1/*`](/api-reference/overview)) |
All three end up calling the same backend. MCP is just the local adapter that gives an IDE agent typed tools.
## Smoke test: confirm it works
You can launch the server by hand to verify the install pipeline and your API key:
```bash theme={null}
export THEO_API_KEY=theo_sk_...
npx -y @hitheo/mcp
```
The process reads `THEO_API_KEY` from the environment, opens a stdio MCP transport, and waits silently for JSON-RPC messages. Press `Ctrl+C` to exit — silence is the expected behavior, because IDEs (not humans) talk to it.
For a richer end-to-end check that also exercises the network path, use the [CLI](/cli-reference/overview):
```bash theme={null}
theo verify # machine-readable JSON, exits non-zero on failure
theo status # human-readable; probes both apex and www
```
If both pass, MCP will work inside any IDE configured with the same key.
## Versioning
`@hitheo/mcp` follows the [pre-1.0 semver policy](/changelog) used by the rest of the Theo packages: **minor** bumps are the breaking-change signal (not major), matching how npm's `^` operator resolves `0.x.y`. The MCP server (currently `0.3.0`) pins `@hitheo/sdk` with `^0.4.0`, so a `0.4.x` SDK release is picked up automatically; a `0.5.0` SDK release requires bumping the MCP server.
Every published tarball ships with [signed npm provenance](/security/authentication#supply-chain-verifying-npm-packages) starting at `0.1.4`. Verify before installing:
```bash theme={null}
npm audit signatures @hitheo/mcp
```
## Next steps
* **[Install](/mcp/install)** — set up MCP in your IDE (auto-detect or per-IDE).
* **[Tools](/mcp/tools)** — what each tool does, schemas, examples.
* **[Resources](/mcp/resources)** — the three `theo://` URIs your agent can read.
* **[Project Config](/mcp/project-config)** — pin a persona, default skills, or inline tools per repo.
* **[Troubleshooting](/mcp/troubleshooting)** — common setup failures and fixes.
* **[Security](/mcp/security)** — threat model and sandbox semantics.
# Project Config
Source: https://docs.hitheo.ai/mcp/project-config
Use theo.config.json to pin a persona, default skills, and inline tools for every MCP call in a repo.
When `@hitheo/mcp` starts, it looks for a `theo.config.json` in the working directory (the IDE workspace root). If it finds one, every relevant tool call is enriched with the values you defined — your IDE agent doesn't have to remember to pass them.
This is how you give a repo its own persona ("you are a backend engineer for this Express API"), pre-activate the skills that matter for the project, and expose custom tools that only make sense in this codebase.
Most people generate this file with `theo init`, then tune `persona` and `skills` by hand. You rarely need to write it from scratch.
## Quick example
```json theme={null}
{
"persona": "You are a backend engineer assistant for this Express API.",
"skills": ["deep-research", "content-writer"],
"defaultMode": "code",
"temperature": 0.3,
"tools": [
{
"name": "check_stock",
"description": "Look up current stock levels for a SKU",
"input_schema": {
"type": "object",
"properties": { "sku": { "type": "string" } },
"required": ["sku"]
}
}
],
"metadata": { "team": "warehouse-ops" }
}
```
Drop that at the repo root. The next time any MCP tool fires, those fields are merged into the request.
## Schema
| Field | Type | Used by | Description |
| - | - | - | - |
| `persona` | `string` | `theo_complete` | Custom system prompt injected as `persona.system_prompt`. |
| `skills` | `string[]` | `theo_complete` | Skill slugs to activate on every completion. |
| `defaultMode` | [`ChatMode`](/sdk-reference/types) | `theo_complete` | Fallback mode when the caller didn't pass one. |
| `tools` | `ToolDef[]` | `theo_complete` | Inline tool definitions Theo can call during the agent loop. |
| `temperature` | `number` | reserved | Default temperature. *(Plumbed in the config loader but not yet forwarded by `theo_complete`.)* |
| `metadata` | `Record` | reserved | Metadata attached to every request for tracking. *(Loaded today; passthrough planned.)* |
`ToolDef` shape (used in `tools`):
```ts theme={null}
interface ToolDef {
name: string;
description: string;
input_schema?: Record; // JSON-Schema
}
```
## File precedence and sandbox
`@hitheo/mcp` loads config in this order, by design:
1. **`theo.config.json`** — always loaded if present. Parsed with `JSON.parse`; no code runs.
2. **`theo.config.js` / `theo.config.ts`** — **ignored** unless you opt in. Loading them would `import()` arbitrary code from the workspace root, which is unsafe when an IDE spawns the MCP server inside a project you haven't audited.
To opt back in:
```bash theme={null}
export THEO_ALLOW_JS_CONFIG=1
```
With that flag set, the loader tries `theo.config.js` first, then `theo.config.ts`, before falling back to JSON. If a JS/TS config is present without the flag, the server logs a warning to stderr and skips it.
Only set `THEO_ALLOW_JS_CONFIG=1` in directories you authored or trust. A malicious `theo.config.js` in any repo you open will execute as your user the moment the IDE launches the MCP server.
Even with the flag set, `theo.config.json` remains the recommended format. The TypeScript helper `defineConfig` from [`@hitheo/sdk`](/sdk-reference/project-config) can emit a typed object you then `JSON.stringify` into the JSON file if you want autocompletion in your editor.
## Merge semantics
When the MCP server handles a tool call, the project config is *merged* with the arguments the IDE agent passes in. The rules:
| Field | Merge rule |
| - | - |
| `persona` | If config has `persona`, it becomes `persona.system_prompt`. Caller arg overrides if present. |
| `skills` | Concatenated: `[...config.skills, ...args.skills]`. Empty result → field omitted. |
| `defaultMode` | Only used if the caller didn't pass `mode`. Caller args win. |
| `tools` | Forwarded as-is when no caller args; not currently overridden by per-call tool lists. |
| `temperature`, `metadata` | Loaded by the config parser; not yet forwarded by `theo_complete`. |
In practice this means:
* A repo persona is always applied.
* Skills are **additive** — the agent can request more skills on top of the repo's defaults, but cannot subtract from them in a single call.
* Modes follow "explicit wins": if the agent passes `mode: "research"`, that beats `defaultMode: "code"`.
## Where `theo init` puts it
When you run `theo init`, the CLI writes a starter config based on your folder name:
```json theme={null}
{
"persona": "You are an AI assistant for the project.",
"skills": [],
"defaultMode": "auto"
}
```
You can edit it freely afterward; the MCP server will pick up changes the next time it starts (i.e. the next IDE restart).
## Updating without restarts
The config is read **once at server startup**, so changes take effect on the next MCP server boot (which usually means the next time your IDE reopens the workspace). If you need to iterate on a persona quickly, edit `.theo/RULES.md` instead — it influences how the IDE's agent thinks about the tools, and most agents reload it automatically.
## Related
* **[Install](/mcp/install)** — how `theo init` writes the config file in the first place.
* **[SDK `defineConfig`](/sdk-reference/project-config)** — typed helper for projects that prefer TS authoring.
* **[Skills overview](/skills/overview)** — what to put in `skills`.
* **[Security](/mcp/security)** — full rationale for the JSON-only default.
# Resources
Source: https://docs.hitheo.ai/mcp/resources
The three read-only theo:// URIs your IDE agent can fetch via @hitheo/mcp.
In MCP, **resources** are read-only URIs an agent can pull for context without invoking a tool. `@hitheo/mcp` exposes three:
| URI | Mime type | Description |
| - | - | - |
| [`theo://models`](#theo-models) | `application/json` | Available Theo models and their routing config |
| [`theo://skills/installed`](#theo-skills-installed) | `application/json` | Skills active on the current API key |
| [`theo://health`](#theo-health) | `application/json` | Live provider/engine health and version |
All three are derived live from the API — no caching, no transformation. The MCP server simply forwards them with `application/json`. If the underlying call fails, the resource returns a `text/plain` body of the form `Error reading : ` so the agent can still surface something useful.
Resources are a **read-only context channel**. They are not state-changing — the agent can pull them whenever it needs grounding without spending a tool turn or burning extra credits. (Reading a resource still hits the underlying API, but no AI inference happens.)
## `theo://models`
Returns the array your account can route to, with the same shape as `GET /api/v1/models`.
**When to use it:** before asking Theo to use a specific model, or when the agent wants to explain to the user *what* engine handled a request.
```json theme={null}
[
{
"mode": "auto",
"model_id": "theo-1-flash",
"label": "Theo Flash",
"engine": "theo-core",
"description": "Fast general-purpose model"
},
{
"mode": "code",
"model_id": "theo-1-code",
"label": "Theo Code",
"engine": "theo-core",
"description": "Long-form code generation"
}
]
```
Backed by [`theo.models()`](/sdk-reference/client) → [`GET /api/v1/models`](/api-reference/models/list).
## `theo://skills/installed`
Returns the list of skills currently installed for the API key the MCP server is using. Same shape as `theo_skill_list` with `filter="installed"`.
**When to use it:** before the agent suggests installing a skill (so it doesn't recommend something the user already has), or before invoking `theo_complete` with a `skills` array (to validate slugs).
```json theme={null}
[
{
"id": "skill_a1b2c3",
"slug": "deep-research",
"name": "Deep Research",
"description": "Multi-step research with citations",
"version": "1.4.0"
}
]
```
Backed by [`theo.skills("installed")`](/sdk-reference/skills) → [`GET /api/v1/skills?filter=installed`](/api-reference/skills/list).
## `theo://health`
Live system health — engine availability, latency, infrastructure status, and API version. Identical to `GET /api/v1/health` (the only public endpoint that does not require authentication).
**When to use it:** at the start of a long task, or when a tool starts returning errors and the agent wants to differentiate "Theo is down" from "my prompt was bad".
```json theme={null}
{
"status": "healthy",
"version": "2026-03-28",
"providers": {
"theo-core": { "status": "healthy", "latencyMs": 42 },
"theo-vision": { "status": "healthy", "latencyMs": 88 },
"theo-search": { "status": "healthy", "latencyMs": 130 }
},
"infrastructure": {
"database": { "status": "healthy", "latencyMs": 3 },
"redis": { "status": "healthy", "latencyMs": 1 }
}
}
```
Backed by [`theo.health()`](/sdk-reference/client) → [`GET /api/v1/health`](/api-reference/health/check).
## Error responses
If the underlying API call fails (network drop, expired key, etc.), the resource returns:
```text theme={null}
Error reading theo://models:
```
with `mimeType: "text/plain"` instead of JSON. The agent can either retry or fall back to the matching tool (e.g. `theo_status` instead of `theo://health`).
## How an IDE agent uses these
A typical Theo-aware agent prompt loop:
1. On boot, pull `theo://health` to confirm engines are up.
2. Pull `theo://skills/installed` to learn what domain knowledge is already loaded.
3. Optionally pull `theo://models` so it knows the names of the engines it can ask for.
4. Then start invoking tools (`theo_complete`, `theo_code`, …) for real work.
You can encode that loop in `.theo/RULES.md` (generated by `theo init`) so every agent in the workspace follows it.
# Security
Source: https://docs.hitheo.ai/mcp/security
Threat model for @hitheo/mcp — what runs where, how the JSON-only sandbox protects you, and how to verify the supply chain.
`@hitheo/mcp` is intentionally a small, predictable piece of software. This page covers exactly what it does, what it doesn't do, and what you can do to harden the install further.
## Where the server runs
| Property | Value |
| - | - |
| Process owner | The same user that launched the IDE |
| Transport | Stdio (no inbound network port) |
| Outbound traffic | HTTPS only, to `https://www.hitheo.ai` |
| Lifetime | Per-workspace; the IDE spawns and kills it |
| Persistent state | None — the server is stateless across runs |
The server is a Node.js process running as your local user. There is no daemon, no shared socket, no inter-IDE coordination. If you close the workspace, the process exits.
Because the transport is stdio rather than HTTP, **nothing on your network can talk to it**. The only entity that can call tools is the IDE process that spawned it as a child. Outbound, it speaks TLS 1.2+ to the same Theo API that any SDK or curl call uses.
## Where the API key lives
```text theme={null}
shell environment → IDE process → @hitheo/mcp child process → outbound HTTPS
```
The key flow:
1. You export `THEO_API_KEY` in your shell (or persist it for GUI app launches).
2. The IDE reads the value and forwards it as an environment variable when it spawns `@hitheo/mcp`.
3. The server reads it once at startup and stores it in process memory.
4. Every outbound call signs `Authorization: Bearer theo_sk_...`.
5. The IDE's agent itself **never sees the key** — it only sees the tool outputs.
This means:
* The key is never written to disk by `@hitheo/mcp`. (Your shell config or the optional `~/.theo/credentials` file may persist it, but those are CLI artifacts, not MCP ones.)
* The key is not transmitted to the IDE vendor, the model provider, or any third party. It goes straight to `api.hitheo.ai`.
* The key is not embedded in the tool descriptions, schemas, or resource bodies the agent can read.
If you ever leak a key into a chat log, [rotate it immediately](/security/authentication#key-rotation).
## The JSON-only config sandbox
`@hitheo/mcp` reads `theo.config.json` from the current working directory at startup. It deliberately **does not** read `theo.config.js` or `theo.config.ts` by default.
The reason is the threat model: an IDE will happily launch the MCP server inside any project you open, including ones you cloned from the internet. If JS/TS config were loaded automatically, a malicious `theo.config.js` could `import()` arbitrary code the moment the workspace opens — full arbitrary-code-execution as your user, before you've read a single file.
JSON config covers every documented use case (`persona`, `skills`, `defaultMode`, `tools`, `temperature`, `metadata`) without that risk.
If you genuinely need JS/TS config in a directory you trust:
```bash theme={null}
export THEO_ALLOW_JS_CONFIG=1
```
The server then loads `theo.config.js` first, then `theo.config.ts`, with the same JSON fallback.
Only set `THEO_ALLOW_JS_CONFIG=1` in directories you authored or trust. Treat it the same way you'd treat `--allow-scripts` — a knob you turn on per-project, not globally.
## Supply chain
Every official `@hitheo/*` tarball on npm — including `@hitheo/mcp` — ships with [signed npm provenance](/security/authentication#supply-chain-verifying-npm-packages) starting at version `0.1.4`. Each attestation links the tarball back to the exact public CI workflow + git commit that produced it.
Verify before installing or pinning a new version:
```bash theme={null}
npm audit signatures @hitheo/mcp
```
You can also inspect the attestation URL for a specific release:
```bash theme={null}
npm view @hitheo/mcp@latest dist.attestations
```
If the attestation check ever fails for an official Theo package, **do not install it**. Report the issue to `security@opencharts.com` (see [Disclosure Policy](/security/disclosure-policy)).
## Pinning a known-good version
`npx -y @hitheo/mcp` resolves the latest published release on each install. If you want to lock to a specific version in CI or a shared dev environment, pin it in your IDE config:
```json theme={null}
"args": ["-y", "@hitheo/mcp@0.3.0"]
```
This makes upgrades explicit. Re-run `theo init` (or hand-edit) to move to a new release.
## What the agent can and can't do
The 8 [tools](/mcp/tools) and 3 [resources](/mcp/resources) are the **entire** surface the IDE agent sees. The MCP server does not expose:
* Your file system
* Your shell
* Your local processes or environment variables
* Any Theo internals beyond the documented HTTP endpoints
Any code the agent ends up running locally (`theo_code` returns code, not a runtime) is something *the IDE* offers to execute. That decision sits with you and the IDE's own permission model — `@hitheo/mcp` itself is read-only with respect to your machine.
## Key rotation, scopes, and revocation
`@hitheo/mcp` inherits the full key model documented in [Authentication](/security/authentication):
* **Hashed at rest** — Theo only stores SHA-256 hashes of `theo_sk_*` keys.
* **Scoped permissions** — each key can be limited to specific capabilities (completions, skills, tools, connectors, billing). A key without the `completions` scope cannot run `theo_complete`; the tool will return a `403 missing_scope` error to the agent.
* **Per-key rate limits** — limits apply per key, so a runaway IDE agent can't starve your other integrations.
* **Instant revocation** — revoke from the [dashboard](https://api.hitheo.ai/dashboard/api-keys) and the MCP server stops working within seconds (the next call returns `401 key_revoked`).
When rotating:
1. Create the new key in the dashboard.
2. Update the environment / shell where your IDE launches.
3. Restart the IDE.
4. Confirm with `theo verify` from the same shell.
5. Revoke the old key.
The grace window during rotation means there is no downtime for the IDE between steps 1 and 5.
## Reporting vulnerabilities
Found a security issue in `@hitheo/mcp` or related infrastructure? See the [Disclosure Policy](/security/disclosure-policy). Email `security@opencharts.com` rather than filing a public GitHub issue.
## Related
* **[Authentication](/security/authentication)** — full key model, scopes, rotation.
* **[Data Privacy](/security/data-privacy)** — how Theo handles your prompts and artifacts.
* **[Disclosure Policy](/security/disclosure-policy)** — how to report a vulnerability.
# Tools
Source: https://docs.hitheo.ai/mcp/tools
Every MCP tool @hitheo/mcp exposes — schemas, examples, and the SDK/REST endpoint behind each one.
`@hitheo/mcp` exposes fourteen tools to your IDE agent. Each one wraps a method on [`@hitheo/sdk`](/sdk-reference/installation) and ultimately hits a REST endpoint on `https://www.hitheo.ai/api/v1/*`. The schemas below are reproduced from `packages/mcp/src/tools.ts`, so what your IDE sees in its tool catalog is what's documented here.
The tools fall into two groups: **execution** tools that run work (`theo_complete`, `theo_code`, …) and **configuration** tools that build and shape a key's orchestrator from natural language (`theo_setup_key`, `theo_set_guardrail`, …). Every configuration change is saved immediately and rendered on the dashboard canvas at `/dashboard/orchestrator?key=…`.
Tools never see your API key — `@hitheo/mcp` loads it once at startup from `THEO_API_KEY` and signs the underlying HTTP request on the agent's behalf. The agent only sees the text/JSON the tool returns.
Every **configuration** tool (`theo_setup_key`, `theo_configure_key`, `theo_add_skill`, `theo_assign_skill_to_node`, `theo_set_guardrail`, `theo_set_routing`) requires the MCP server's own key to carry the **`billing`** scope. Without it those calls return a permission error.
**Scope inheritance.** Configuration tools inherit the scope of the key the MCP
server authenticates with. Point the server at a **team key** and everything it
creates — new keys (`theo_setup_key`), routing preferences and guardrail
policies (`theo_set_routing` / `theo_set_guardrail`) — is created under that
**team**, billed to the team, and visible to every member. Point it at a
personal key and the same tools stay personal. You never pass a scope
explicitly; it follows the key.
## Tool catalog
### Execution
| Tool | Purpose | SDK | REST |
| - | - | - | - |
| [`theo_complete`](#theo_complete) | General-purpose orchestrated completion | [`theo.complete()`](/sdk-reference/completions) | [`POST /api/v1/completions`](/api-reference/completions/create) |
| [`theo_code`](#theo_code) | Code generation with long output budget | [`theo.code()`](/sdk-reference/completions) | [`POST /api/v1/code`](/api-reference/code/generate) |
| [`theo_research`](#theo_research) | Deep research with citations (async) | [`theo.research()`](/sdk-reference/completions) | [`POST /api/v1/research`](/api-reference/research/create) |
| [`theo_image`](#theo_image) | Image generation | [`theo.images()`](/sdk-reference/media) | [`POST /api/v1/images`](/api-reference/images/generate) |
| [`theo_document`](#theo_document) | Generate PDF / DOCX / PPTX / XLSX / CSV | [`theo.documents()`](/sdk-reference/media) | [`POST /api/v1/documents`](/api-reference/documents/generate) |
| [`theo_skill_list`](#theo_skill_list) | List installed or marketplace skills | [`theo.skills()`](/sdk-reference/skills) | [`GET /api/v1/skills`](/api-reference/skills/list) |
| [`theo_skill_install`](#theo_skill_install) | Install a skill from the marketplace | [`theo.installSkill()`](/sdk-reference/skills) | [`POST /api/v1/skills`](/api-reference/skills/install) |
| [`theo_status`](#theo_status) | Engine health + latency | [`theo.health()`](/sdk-reference/client) | [`GET /api/v1/health`](/api-reference/health/check) |
### Configuration (requires `billing` scope)
| Tool | Purpose | REST |
| - | - | - |
| [`theo_setup_key`](#theo_setup_key) | Create a new key + a saved, visible orchestrator (preset / per-mode routing / full graph) | `POST /api/v1/keys` + `PUT …/orchestrator-graph` |
| [`theo_configure_key`](#theo_configure_key) | Re-plan an existing key (same options as setup) | `PUT …/orchestrator-graph` |
| [`theo_add_skill`](#theo_add_skill) | Install + attach a skill to a key (optionally scoped to one mode) | `PUT …/keys/{id}/skills` |
| [`theo_assign_skill_to_node`](#theo_assign_skill_to_node) | Attach a skill to graph node(s), matched by id / label / mode / engine | `PUT …/orchestrator-graph` |
| [`theo_set_guardrail`](#theo_set_guardrail) | Add a guardrail as an input/output node (or key-level) | `PUT …/keys/{id}/guardrails` |
| [`theo_set_routing`](#theo_set_routing) | Append routing rules + insert a Router node | `PUT …/keys/{id}/routing-preference` |
***
## `theo_complete`
Run an AI completion through Theo's orchestration engine. Theo automatically classifies intent, selects the best engine across 300+ AI models, injects domain skills, executes tools, and returns the response. Use this for any general AI task: writing, analysis, planning, Q\&A.
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `prompt` | `string` | ✅ | The prompt or question to send to Theo. |
| `mode` | `"auto" \| "fast" \| "think" \| "code" \| "research" \| "roast"` | — | Execution mode. `auto` lets Theo classify. `fast` uses a lightweight model. `think` uses deep reasoning. `code` optimizes for code. Default: `auto`. |
| `skills` | `string[]` | — | Skill slugs to activate (e.g. `["deep-research", "content-writer"]`). |
| `conversation_id` | `string` | — | Continue an existing conversation by ID. |
When `theo.config.json` defines `persona`, `skills`, `defaultMode`, or `tools`, those values are merged into the request — see [Project Config](/mcp/project-config#merge-semantics).
### Example agent invocation
```text theme={null}
Use theo_complete to draft a release-note summary for the diff in HEAD~3..HEAD.
```
### Example response (truncated)
```text theme={null}
Here's a release-note summary for the last three commits:
- ...
---
Tools used: web_search (ok), summarize_diff (ok)
Model: Theo Reason | Mode: think | Cost: 3¢
```
### Notes
* Output includes a one-line tail with the resolved model, mode, and cost so the agent sees how the request was routed.
* Costs are reconciled after execution and reflect what your account was billed.
***
## `theo_code`
Generate code using Theo. Routes to the Theo Code engine for best-in-class code generation with an extended output budget. Returns generated code and any artifacts (full files, project scaffolds). Use this when the task is primarily about writing, generating, or scaffolding code.
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `prompt` | `string` | ✅ | Describe the code you want generated. |
| `language` | `string` | — | Target programming language (e.g. `typescript`, `python`, `go`). |
| `framework` | `string` | — | Target framework (e.g. `nextjs`, `express`, `fastapi`, `react`). |
### Example agent invocation
```text theme={null}
Use theo_code to scaffold a FastAPI service with a /health route and a /chat
SSE route. language=python, framework=fastapi.
```
The tool returns the generated content plus an `Artifacts:` block with JSON describing any files created.
***
## `theo_research`
Run deep research on a topic. Theo plans 3–6 focused search queries, runs them in parallel, deduplicates sources, and synthesizes a structured report with citations. **This is an async operation** — the MCP server polls until the underlying job completes (default budget: 120 seconds at a 3-second interval) and returns the final report.
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `prompt` | `string` | ✅ | The research question or topic. |
| `depth` | `"basic" \| "advanced"` | — | `basic` is faster; `advanced` is more thorough. Default: `basic`. |
### Example agent invocation
```text theme={null}
Use theo_research with depth="advanced" to compare PostgreSQL native partitioning
vs Citus for a write-heavy time-series workload.
```
### Failure handling
If the research job fails or times out, the tool returns a single text payload starting with `Research failed:` so the agent can decide whether to retry with a narrower prompt.
***
## `theo_image`
Generate images using Theo. Routes to the Theo Create engine with automatic provider fallback. Returns image URLs. Use for logos, illustrations, mockups, concept art, or any visual content.
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `prompt` | `string` | ✅ | Describe the image to generate. |
| `style` | `string` | — | Visual style (e.g. `photorealistic`, `illustration`, `3d`, `pixel`). |
| `aspect_ratio` | `"1:1" \| "16:9" \| "9:16" \| "4:3" \| "3:4"` | — | Aspect ratio. Default: `1:1`. |
### Example response
```text theme={null}
Image 1: https://artifacts.hitheo.ai/img/.png [theo-vision]
Cost: 5¢
```
Each line corresponds to one image; if the request asked for multiple, you get one URL per image plus a final cost line.
***
## `theo_document`
Generate a formatted document. Theo creates the document and returns a download URL on `artifacts.hitheo.ai`. Use for reports, presentations, spreadsheets, and data exports.
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `prompt` | `string` | ✅ | Describe the document to generate. |
| `format` | `"pdf" \| "docx" \| "pptx" \| "xlsx" \| "csv"` | — | Output format. Default: `pdf`. |
### Example agent invocation
```text theme={null}
Use theo_document with format="pptx" to build a 7-slide pitch deck for an
AI-native EHR called SentryOS.
```
### Example response
```text theme={null}
Document: SentryOS Pitch Deck
Format: pptx
Download: https://artifacts.hitheo.ai/doc/.pptx
Cost: 3¢
```
***
## `theo_skill_list`
List available Theo skills. Skills are packages of domain knowledge and tools that extend Theo's capabilities (like apps for AI). Filter to either `installed` (active on this account) or `marketplace` (available to install).
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `filter` | `"installed" \| "marketplace"` | — | Filter to installed skills or marketplace catalog. Default: all visible. |
The tool returns a pretty-printed JSON array of skill records (`id`, `slug`, `name`, `description`, `version`, …). Agents typically pair this with [`theo_skill_install`](#theo_skill_install).
***
## `theo_skill_install`
Install a skill from the Theo marketplace. Once installed, the skill's domain knowledge and tools are available on every completion (and inside every subsequent `theo_complete` MCP call).
### Input schema
| Field | Type | Required | Description |
| - | - | - | - |
| `skill_id` | `string` | ✅ | The skill ID to install. |
### Example response
```text theme={null}
Skill skill_a1b2c3 installed successfully.
```
***
## `theo_status`
Check Theo's health and engine availability. Returns engine status, latency, and infrastructure health. Use to verify the connection works or diagnose issues from inside the IDE.
### Input schema
No parameters.
### Example response
```text theme={null}
Status: healthy
Version: 2026-03-28
Engines:
theo-core: healthy
theo-vision: healthy
theo-search: healthy
```
If the tool returns anything other than `Status: healthy`, run [`theo verify`](/cli-reference/overview#commands) on the host to dig in.
***
## `theo_setup_key`
Create a **new** Theo API key and build a **saved, visible orchestrator** in one call — no hand-drawing on the canvas. Specify the plan one of three ways (precedence: **`graph` > `routing` > `use_case`**):
* **`use_case`** — a single-engine preset. `coding` pins a code engine as a deterministic passthrough (a clean drop-in backend for Warp / Cursor); `chat` a fast engine; `raw` an engine you choose.
* **`routing`** — per-mode engine bindings. Theo's classifier splits each request into a mode and you pin an engine per mode.
* **`graph`** — a full custom orchestrator graph `{ enabled, nodes, edges }`, applied as-is.
Returns the raw key (**shown once**) plus a dashboard link. The orchestrator is enabled immediately.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `use_case` | `"coding" \| "chat" \| "raw"` | Single-engine preset. `coding` is the default. |
| `model` | `string` | Engine id to pin for the preset (e.g. `anthropic/claude-opus-4.8`). **Required** for `raw`. |
| `routing` | `Array<{ mode, model }>` | Per-mode engine bindings, e.g. `[{ "mode": "fast", "model": "arca-velox-5.1" }, { "mode": "think", "model": "arca-magnus-5.1" }]`. |
| `graph` | `{ enabled, nodes[], edges[] }` | Advanced: a full graph. Overrides `use_case` / `routing`. |
| `name` | `string` | Optional name for the new key. |
### Example agent invocation
```text theme={null}
Use theo_setup_key to make a key where light requests go to Arca Velox and heavy
ones to Arca Magnus.
```
```json theme={null}
theo_setup_key { "routing": [
{ "mode": "fast", "model": "arca-velox-5.1" },
{ "mode": "think", "model": "arca-magnus-5.1" }
] }
```
### Example response (truncated)
```text theme={null}
✅ Created key "orchestrator (via MCP)".
API key (shown once — store it now):
theo_sk_…
Built & saved an orchestrator graph (classifier → one engine per mode):
fast → arca-velox-5.1
think → arca-magnus-5.1
Review or extend this setup in the dashboard:
https://www.hitheo.ai/dashboard/orchestrator?key=…
```
***
## `theo_configure_key`
Re-plan an **existing** key — the same three options as `theo_setup_key` (`use_case` / `routing` / `graph`, same precedence). Changes reflect on the dashboard canvas immediately. Returns a dashboard link.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `key_id` | `string` | **Required.** The API key UUID to configure. |
| `use_case` | `"coding" \| "chat" \| "raw"` | Single-engine preset. |
| `model` | `string` | Engine id override; **required** for `raw`. |
| `routing` | `Array<{ mode, model }>` | Per-mode engine bindings. |
| `graph` | `{ enabled, nodes[], edges[] }` | Full graph; overrides the others. |
### Example agent invocation
```text theme={null}
Use theo_configure_key on key to send everything to Claude Opus.
```
```json theme={null}
theo_configure_key { "key_id": "", "use_case": "raw", "model": "anthropic/claude-opus-4.8" }
```
***
## `theo_add_skill`
Install a skill (from the marketplace, if needed) and attach it to a key's allowlist so that key can call it. Optionally scope it to a single **mode**. Idempotent — re-adding the same (skill, mode) is a no-op.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `key_id` | `string` | **Required.** The API key UUID. |
| `skill` | `string` | **Required.** Skill slug, name, or id (e.g. `deep-research`). |
| `mode` | `string` | Optional: scope to one mode (`fast` / `think` / `code` / `research` / `roast` / `genui` / `data_extraction` / `vision`). Omit = all modes. |
### Example agent invocation
```text theme={null}
Add the deep-research skill to key , but only for the think mode.
```
```json theme={null}
theo_add_skill { "key_id": "", "skill": "deep-research", "mode": "think" }
```
If the skill can't be resolved, the tool returns `No skill matches "…"` so the agent can call [`theo_skill_list`](#theo_skill_list) and retry.
***
## `theo_assign_skill_to_node`
Attach a skill to one or more **model nodes** in a key's orchestrator graph, so the skill applies only there. The target is matched by node **id**, **label**, the **mode** it handles, or the **engine** it runs — and the skill is attached to **every** match. So a query naming an engine or mode shared by two or more nodes hits all of them (e.g. `sonnet` attaches to every node running `anthropic/claude-sonnet-4.6`).
Requires the key to already have a graph. If nothing matches, the tool returns the list of available nodes.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `key_id` | `string` | **Required.** The API key UUID. |
| `node` | `string` | **Required.** Node id, label, the mode it handles (`code`), or the engine it runs (`sonnet`, `arca-magnus-5.1`). Matches every node with that mode/engine. |
| `skill` | `string` | **Required.** Skill slug, name, or id. |
### Example agent invocation
```text theme={null}
Put the deep-research skill on every node running sonnet on key .
```
```json theme={null}
theo_assign_skill_to_node { "key_id": "", "node": "sonnet", "skill": "deep-research" }
```
```text theme={null}
✅ Skill "deep research" (deep-research) attached to 2 nodes (think, code) on key .
```
***
## `theo_set_guardrail`
Bind a [Gateway Guardrails](/guides/guardrails) policy to a key. Pass an existing policy **name/id**, or a **preset** name (e.g. `PII-safe`, `Injection guard`) to create a policy from that template and bind it. On a key with an orchestrator graph the policy is added as a **Guardrail node** on the canvas:
* an **input** node (after Entry, or after the classifier when scoped) screens the **prompt**;
* an **output** node (after the model) screens the **reply**.
The **phase** is inferred from the policy's own rule phases (`input` / `output` / `both`) unless you pass `phase` explicitly. Pass **`mode`** (a mode or engine name) to scope the guardrail to just that branch — it attaches to every node with that mode/engine. On a key **without** a graph, the policy is bound key-level (screens both phases per its rules). `remove: true` clears guardrails; add `phase` to remove only the input or output checkpoint.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `key_id` | `string` | **Required.** The API key UUID. |
| `policy` | `string` | An existing policy name/id, or a preset name. |
| `phase` | `"input" \| "output" \| "both"` | Where it runs. Omit to infer from the policy. Also filters `remove`. |
| `mode` | `string` | Optional: scope to one branch — a mode (`think`) or engine (`sonnet`, `anthropic/claude-opus-4.8`). Hits every matching node. |
| `remove` | `boolean` | Unbind guardrails. Combine with `phase` to remove only input or output. |
### Example agent invocations
```text theme={null}
Add PII-safe on the output of key .
```
```json theme={null}
theo_set_guardrail { "key_id": "", "policy": "PII-safe", "phase": "output" }
```
```text theme={null}
Add an injection guard on the input of just the think branch of key .
```
```json theme={null}
theo_set_guardrail { "key_id": "", "policy": "Injection guard", "phase": "input", "mode": "think" }
```
```text theme={null}
Remove only the output guardrail from key .
```
```json theme={null}
theo_set_guardrail { "key_id": "", "remove": true, "phase": "output" }
```
***
## `theo_set_routing`
Bind a Routing Studio preference to a key — either an existing **preference** by name/id, or create rules inline (`pattern` keyword/regex → `mode`). Rules are **additive** by default: new rules are appended to the key's current routing (deduped), so asking for a second rule keeps the first. Pass `replace: true` to reset instead. On a graph key a single **Router node** is inserted (`Entry → … → Router → Classifier`) so the rules actually apply in-path and show on the canvas; a rule whose target mode has no engine node triggers a warning. `remove: true` clears routing.
### Input schema
| Field | Type | Notes |
| - | - | - |
| `key_id` | `string` | **Required.** The API key UUID. |
| `preference` | `string` | An existing routing-preference name or id to bind. |
| `rules` | `Array<{ pattern, mode, engine? }>` | Rules to add: keyword/regex → mode (optional pinned engine). |
| `name` | `string` | Optional name for a preference created from `rules`. |
| `replace` | `boolean` | Replace the key's rules instead of appending (default: append). |
| `remove` | `boolean` | Unbind the routing preference from the key. |
### Example agent invocation
```text theme={null}
On key , route anything mentioning "invoice" to code.
```
```json theme={null}
theo_set_routing { "key_id": "", "rules": [ { "pattern": "invoice", "mode": "code" } ] }
```
A second call adds to the first:
```text theme={null}
✅ Added 1 routing rule to key (2 total):
/contract/i → think
```
***
## Reference
**Engines** (config surface — real engine names are intentional here): `arca-velox-5.1` (fast), `arca-magnus-5.1` (deep reasoning), `anthropic/claude-sonnet-4.6`, `anthropic/claude-opus-4.8`, `anthropic/claude-haiku-4.5`, `google/gemini-2.5-pro`, `openai/gpt-4.1`, plus your own `custom::`.
**Modes:** `fast`, `think`, `code`, `research`, `roast`, `genui`, `data_extraction`, `vision`, `image`, `video`.
**Guardrail presets:** e.g. `PII-safe`, `Injection guard`. On a mismatch the tool lists the available policies and presets.
***
## Errors
When any tool throws (network error, API error envelope, polling timeout), the MCP server formats it as:
```text theme={null}
Theo error:
```
The agent sees the text as a normal tool result, not a JSON-RPC error, so it can read and react instead of bailing. The full structured error is also visible in your MCP server logs if your IDE surfaces them.
See [Troubleshooting](/mcp/troubleshooting) for the most common failure modes.
# Troubleshooting
Source: https://docs.hitheo.ai/mcp/troubleshooting
Common failures when running @hitheo/mcp inside an IDE, with log signatures and fixes.
Most MCP setup failures fall into one of the categories below. Each section has the log signature you'll see (in the IDE's MCP panel or stderr) plus the fix.
Before digging in, run `theo verify` on the same shell you launch your IDE from. If it fails, the MCP server will fail with the same error — fix the host first.
## `THEO_API_KEY` not set
**Signature:**
```text theme={null}
[theo-mcp] ERROR: THEO_API_KEY environment variable is required.
Get one at https://api.hitheo.ai → API Keys.
Then set it: export THEO_API_KEY=theo_sk_...
```
The server exits with code 1 immediately and the IDE shows "Theo MCP server failed to start" or equivalent.
**Fix:** export the key in the shell that launches your IDE, *not* a different terminal:
```bash theme={null}
export THEO_API_KEY=theo_sk_live_a1b2c3...
```
On macOS, GUI apps started from Finder/Spotlight don't pick up `export` lines in `~/.zshrc`. Either:
1. Launch the IDE from the same terminal where you exported the key, or
2. Persist the variable somewhere the GUI session sees it (e.g. `launchctl setenv THEO_API_KEY ...` for macOS app launches), or
3. Inline it in the MCP config's `env` block instead of using `${env:THEO_API_KEY}`:
```json theme={null}
"env": { "THEO_API_KEY": "theo_sk_live_a1b2c3..." }
```
This commits the key into the file — fine for personal projects, not for shared repos.
## IDE didn't restart after writing config
**Signature:** the agent doesn't see `theo_*` tools at all, and there is no MCP log line for Theo.
IDEs read MCP config at boot. Editing `.cursor/mcp.json` (or any other path) while the IDE is open is a no-op until you fully quit and relaunch.
**Fix:** quit the IDE completely (not just close the window) and reopen the project.
## `npx` cache stuck on an old version
**Signature:** the server boots, tools appear, but a feature documented for a newer release behaves like it isn't there.
`npx -y @hitheo/mcp` resolves the latest version, but only on the first run for that account; subsequent boots may reuse the cached copy until `npm` decides to re-check.
**Fix:** clear the npx cache once:
```bash theme={null}
rm -rf ~/.npm/_npx
```
Or pin a specific version in your MCP config:
```json theme={null}
"args": ["-y", "@hitheo/mcp@0.3.0"]
```
You can confirm what got launched by running `theo status` — its output includes the API version the server saw, and `npx -y @hitheo/mcp` shipped with that release.
## Redirect-induced 401 from `THEO_BASE_URL`
**Signature:**
```text theme={null}
[theo-mcp] Theo error: TheoApiError: 401 invalid_api_key
```
…even though `theo verify` from the same shell succeeds.
The most common cause: `THEO_BASE_URL` is set to `https://hitheo.ai` (apex) somewhere in the environment. The apex 307-redirects to `https://www.hitheo.ai`, and Node 18's `fetch` strips the `Authorization` header on 3xx responses, so the redirected request arrives unauthenticated.
**Fix:** point at the canonical host. Either:
* Unset the variable so the SDK default (`https://www.hitheo.ai`) wins:
```bash theme={null}
unset THEO_BASE_URL
```
* Or set it explicitly:
```bash theme={null}
export THEO_BASE_URL=https://www.hitheo.ai
```
See [401 Troubleshooting](/troubleshooting/401-errors) for the full story.
## `claude mcp add` failed silently
**Signature:** `theo mcp install --ide claude-code` reports success but Claude Code doesn't list the server.
The CLI helper first tries `claude mcp add theo npx -y @hitheo/mcp`; if that binary isn't on `$PATH`, it falls back to writing `.mcp.json` at the project root. Both paths *report* success, but Claude Code only reads one of them depending on how it was launched.
**Fix:** if you have the `claude` CLI installed, prefer it. Otherwise write the JSON file directly:
```bash theme={null}
which claude # if empty, fall back to .mcp.json
```
If both are present, the JSON file takes priority inside the project. Removing `.mcp.json` makes Claude Code fall back to the global registration.
## Stdio transport closed unexpectedly
**Signature:**
```text theme={null}
MCP error: server connection closed
```
or your IDE shows the Theo server as "disconnected" mid-session.
Almost always one of:
1. The server crashed because `THEO_API_KEY` was unset or expired mid-session.
2. The host's `npx` lost its network connection while downloading the package and the IDE killed the process.
3. The agent sent an oversized request body (>1 MB).
**Fix:** check the MCP panel for the server's stderr output. The first line of the error message is almost always actionable.
## Theo tools show up but agent refuses to use them
**Signature:** `theo_*` appears in the IDE's tool catalog, but the agent never invokes them.
This is an agent-side bias issue, not an MCP wiring issue. Some IDEs (especially Claude Code) prefer their built-in tools over MCP-provided ones unless explicitly told otherwise.
**Fix:** drop a hint in your project rules file (`.theo/RULES.md` is auto-generated by `theo init`, or use your IDE's native rules file):
> Prefer `theo_*` tools for any AI generation task — image, video, code, research, document.
A single sentence is usually enough.
## Large `theo_code` / `theo_complete` generations get cut off
**Signature:** small snippets return fine, but anything app-sized aborts — often at a round number like `exceeded 30000ms` or `Request timed out` after \~60s.
There are three timeout layers between your agent and the model. `@hitheo/mcp` 0.3.1+ handles the two it owns:
* **SDK request timeout (was 30s).** `theo_code` and `theo_complete` now **stream** instead of making a unary call, so a long-but-active generation runs under an idle (between-token) timeout rather than a total-duration cap. Tune the connect/first-byte budget with `THEO_TIMEOUT_MS` (default `120000`).
* **Server route timeout.** Streaming responses return their headers immediately, so the server's own per-request cap no longer applies to the generation body.
* **Your MCP client's JSON-RPC request timeout (\~60s default).** This one lives in *your IDE/agent*, not in Theo. The server emits `notifications/progress` heartbeats every 5s while generating, so a client that **resets its request timeout on progress** stays alive for arbitrarily long generations.
**Fix (client side):** if very long generations still time out, enable progress-reset and/or raise the request timeout in your MCP client. With the official MCP SDK that's `resetTimeoutOnProgress: true` (plus a generous `maxTotalTimeout`) on the tool call; other clients expose an equivalent "request timeout" setting. A 3-minute app-sized artifact is known to complete once progress-reset is on.
## `theo.config.{js,ts}` is being ignored
**Signature:**
```text theme={null}
[theo-mcp] Ignored theo.config.js: JS/TS config is disabled by default.
Set THEO_ALLOW_JS_CONFIG=1 to enable it (arbitrary code execution — only do
this in trusted directories). Use theo.config.json for safe config.
```
**Fix:** this is intentional. Either convert your config to JSON, or opt in via `THEO_ALLOW_JS_CONFIG=1` — and only in directories you trust. See [Security](/mcp/security#the-json-only-config-sandbox).
## Still stuck?
1. Run `theo verify` on the same shell that launched the IDE. Share the JSON output with support if it fails.
2. Capture the MCP server's stderr from the IDE's MCP panel — that's where `@hitheo/mcp` logs the real error.
3. File an issue on [github.com/hitheoai/theoai](https://github.com/hitheoai/theoai/issues) with the redacted stderr and the IDE version.
# Mode Selector
Source: https://docs.hitheo.ai/playground/mode-selector
Choose execution modes in the Playground.
The mode selector lets you control which Theo engine handles your request:
| Mode | What Happens |
| - | - |
| Auto | Theo classifies your prompt and picks the best engine |
| Fast | Routes to Theo Flash — quick, cheap |
| Think | Routes to Theo Reason — deep reasoning |
| Code | Routes to Theo Code — optimized for code |
| Research | Runs async web research with citations |
| Image | Routes to Theo Create — image generation |
| Roast | Routes to Theo Edge — unfiltered humor |
# Playground Overview
Source: https://docs.hitheo.ai/playground/overview
Interactive testing environment for the Theo API.
The Playground at [hitheo.ai/playground](https://hitheo.ai/playground) is an interactive environment for testing Theo's capabilities.
## Features
* **Mode selector** — switch between auto, fast, think, code, research, image, roast
* **Skill activation** — enable/disable installed skills
* **Real-time streaming** — see tokens as they're generated
* **Tool execution** — watch tools being called in real-time
* **Artifact viewer** — preview generated images, code, and documents
* **Cost tracking** — see per-request cost in real-time
* **Model info** — see which model was selected and why
# Skill Activation
Source: https://docs.hitheo.ai/playground/skill-activation
Enable skills in the Playground.
Toggle installed skills on/off in the Playground sidebar. Active skills inject their system prompt extensions and tool definitions into the pipeline.
## How It Works
1. Open the **Skills** panel in the Playground sidebar
2. Your installed skills are listed with toggle switches
3. **Enable** a skill to include it in the next completion
4. **Disable** a skill to exclude it (without uninstalling)
Active skills are visible in the `meta` event during streaming, so you can see exactly which skills contributed to each response.
## Installing New Skills
You can browse and install new skills from the marketplace directly within the Playground:
1. Click **Browse Marketplace** in the Skills panel
2. Search or filter by category
3. Click **Install** to add a skill
4. The skill becomes immediately available for activation
## Per-Request vs. Installed
* **Installed skills** (toggled on) are active on every request from the Playground
* Use the `skills` parameter in the API to activate skills on a per-request basis without installing them
# Streaming & Artifacts
Source: https://docs.hitheo.ai/playground/streaming-artifacts
Real-time streaming and artifact preview in the Playground.
## Streaming
The Playground streams responses token-by-token using Server-Sent Events (SSE). As the response is generated:
* **Tokens** appear in real-time as they're produced
* **Tool calls** are displayed inline with their name and status (`success` / `error`)
* **Model info** shows which Theo engine was selected and the resolved mode
* **Cost** updates in real-time as tokens are consumed
### Event Types
The streaming display corresponds to the SSE event types from the API:
| Event | What You See |
| - | - |
| `meta` | Model name, resolved mode, active skills |
| `token` | Text appearing character by character |
| `tool` | Tool call badge with status |
| `artifact` | Preview card for generated files |
| `done` | Final cost, token count, follow-up suggestions |
## Artifacts
Generated files (images, code, documents) are displayed as interactive preview cards:
* **Images** — inline preview with full-resolution download link
* **Code** — syntax-highlighted with copy button and language detection
* **Documents** — download link with format badge (PDF, DOCX, PPTX, XLSX, CSV)
Artifacts are hosted on `artifacts.hitheo.ai` and the download URLs are presigned for secure access.
# First Completion
Source: https://docs.hitheo.ai/quickstart/first-completion
Make your first API call with curl and see the full response.
## Send a Request
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "What are the three laws of thermodynamics? Explain each in one sentence.",
"mode": "auto"
}'
```
## Response
```json theme={null}
{
"id": "comp_abc123",
"object": "completion",
"created": "2026-04-10T12:00:00Z",
"content": "1. **Zeroth Law**: If two systems are each in thermal equilibrium with a third, they are in equilibrium with each other...",
"mode": "auto",
"resolved_mode": "fast",
"model": {
"id": "theo-1-flash",
"label": "Theo Flash",
"engine": "theo-core"
},
"tools_used": [],
"artifacts": [],
"follow_ups": [
{ "label": "Explain entropy", "prompt": "Explain entropy in simple terms" },
{ "label": "Real-world examples", "prompt": "Give real-world examples of each law" }
],
"usage": {
"cost_cents": 0.02
}
}
```
## What Just Happened
1. Theo classified your prompt as a simple Q\&A task (`resolved_mode: "fast"`)
2. Routed to `theo-1-flash` for speed
3. No tools were needed, so the agent loop was skipped
4. Response was cached, billed (0.02¢), and audited
## Try Different Modes
```bash theme={null}
# Code generation — routes to Theo Code
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt": "Write a TypeScript function that debounces any callback", "mode": "code"}'
# Deep reasoning — routes to Theo Reason
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt": "Compare microservices vs monolith architecture for a 10-person startup", "mode": "think"}'
```
## With Skills
Activate domain expertise by passing skill slugs:
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/completions \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Check current inventory for SKU-1234 across all warehouses",
"skills": ["inventory-check"]
}'
```
The skill's system prompt extension and tool definitions are injected into the pipeline automatically.
# Get Your API Key
Source: https://docs.hitheo.ai/quickstart/get-api-key
Create a Theo API key to start making requests.
## Create an Account
1. Go to [api.hitheo.ai](https://api.hitheo.ai)
2. Sign up with your email or social login
3. You'll land on the API dashboard
## Generate a Key
1. Navigate to **API Keys** in the sidebar
2. Click **Create Key**
3. Give your key a descriptive name (e.g., "Production", "Development")
4. Copy the key immediately — it won't be shown again
Your key will look like:
```
theo_sk_a1b2c3d4e5f6...
```
Store your API key securely. Never commit it to source control or expose it in client-side code. Use environment variables instead.
## Set the Environment Variable
```bash theme={null}
export THEO_API_KEY=theo_sk_a1b2c3d4e5f6...
```
Or add it to your `.env` file:
```env theme={null}
THEO_API_KEY=theo_sk_a1b2c3d4e5f6...
```
## Verify It Works
```bash theme={null}
curl https://www.hitheo.ai/api/v1/health
```
This endpoint is public (no auth required) and returns system status. To verify your key specifically:
```bash theme={null}
curl https://www.hitheo.ai/api/v1/models \
-H "Authorization: Bearer $THEO_API_KEY"
```
You should get back a list of available Theo engine models.
## Key Format
All API keys use the `theo_sk_` prefix. Keys are production keys — all usage is billed against your credit balance.
## Next Steps
Send your first completion request with curl.
Set up the TypeScript SDK for a better developer experience.
# Hello World
Source: https://docs.hitheo.ai/quickstart/hello-world
Build a working example in under 5 minutes.
## Node.js / TypeScript
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({ apiKey: process.env.THEO_API_KEY! });
async function main() {
// Simple completion
const response = await theo.complete({
prompt: "Write a haiku about debugging code",
mode: "auto",
});
console.log(response.content);
console.log(`Model: ${response.model.label} | Cost: ${response.usage.cost_cents}¢`);
}
main();
```
**Run it:**
```bash theme={null}
export THEO_API_KEY=theo_sk_...
npx tsx hello.ts
```
## Streaming
```typescript theme={null}
const stream = theo.stream({
prompt: "Explain how DNS works step by step",
});
for await (const event of stream) {
if (event.type === "token") {
process.stdout.write(event.token!);
}
if (event.type === "done") {
const done = event.data as { usage: { cost_cents: number } };
console.log(`\n\nCost: ${done.usage.cost_cents}¢`);
}
}
```
## Python (REST API)
No SDK needed — the REST API works with any HTTP client:
```python theme={null}
import requests
import os
response = requests.post(
"https://www.hitheo.ai/api/v1/completions",
headers={
"Authorization": f"Bearer {os.environ['THEO_API_KEY']}",
"Content-Type": "application/json",
},
json={
"prompt": "Write a Python function to flatten nested lists",
"mode": "code",
},
)
data = response.json()
print(data["content"])
print(f"Model: {data['model']['label']} | Cost: {data['usage']['cost_cents']}¢")
```
## With an E.V.I.
Embed Theo in your product with a custom persona:
```typescript theme={null}
const evi = theo.evi({
persona: "You are Kai, a friendly coding assistant for DevHub. Help developers debug issues and write tests.",
skills: ["deep-research"],
});
const res = await evi.complete({
prompt: "Why is my useEffect running twice in dev mode?",
});
console.log(res.content);
// → Kai explains React strict mode with code examples
```
Your user talks to "Kai" — they never see Theo. See the [E.V.I. Guide](/guides/build-an-evi) for the full walkthrough.
# Install the SDK
Source: https://docs.hitheo.ai/quickstart/install-sdk
Set up @hitheo/sdk for TypeScript and Node.js projects.
## Installation
```bash npm theme={null}
npm install @hitheo/sdk
```
```bash yarn theme={null}
yarn add @hitheo/sdk
```
```bash pnpm theme={null}
pnpm add @hitheo/sdk
```
**Requirements:** Node.js 18+ with native `fetch` support.
## Initialize the Client
```typescript theme={null}
import { Theo } from "@hitheo/sdk";
const theo = new Theo({
apiKey: process.env.THEO_API_KEY!,
// Optional:
// baseUrl: "https://www.hitheo.ai", // default (canonical `www` host)
// timeoutMs: 30_000, // default
// maxRetries: 2, // default — retries on 429/5xx
});
```
## Configuration Options
| Option | Type | Default | Description |
| - | - | - | - |
| `apiKey` | `string` | **required** | Your `theo_sk_...` API key |
| `baseUrl` | `string` | `https://www.hitheo.ai` | API base URL (always target `www` — the apex redirects and some HTTP clients strip the `Authorization` header on 3xx) |
| `timeoutMs` | `number` | `30000` | Request timeout in milliseconds |
| `maxRetries` | `number` | `2` | Max retry attempts on 429/5xx errors |
## Retry Behavior
The SDK automatically retries on:
* **429 Too Many Requests** — respects the `Retry-After` header
* **5xx Server Errors** — exponential backoff (1s, 2s, 4s, max 8s)
Client errors (400, 401, 403, 404) are not retried.
## Also Available
### CLI
The SDK includes a CLI for terminal usage:
```bash theme={null}
npm install -g @hitheo/sdk
theo init # Set up Theo in a project
theo status # Check connection + health (probes both apex and www)
theo verify # Machine-readable JSON diagnostic (CI-friendly)
theo complete "What is quantum computing?"
```
See the [CLI Reference](/cli-reference/overview) for all commands.
### MCP Server — IDE Integration
Use Theo inside Cursor, Claude Code, Warp, Windsurf, and VS Code via MCP:
First, set your API key as an environment variable:
```bash theme={null}
export THEO_API_KEY=theo_sk_...
```
Then pick your IDE:
Add to `.cursor/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide cursor
```
Run this in your terminal:
```bash theme={null}
claude mcp add theo npx -y @hitheo/mcp
```
Or run:
```bash theme={null}
theo mcp install --ide claude-code
```
Add to `.warp/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide warp
```
Add to `~/.codeium/windsurf/mcp_config.json`:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide windsurf
```
Add to `.vscode/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"theo": {
"command": "npx",
"args": ["-y", "@hitheo/mcp"],
"env": {
"THEO_API_KEY": "${env:THEO_API_KEY}"
}
}
}
}
```
Or run:
```bash theme={null}
theo mcp install --ide vscode
```
Auto-detect and configure all installed IDEs at once:
```bash theme={null}
npm install -g @hitheo/sdk
theo init
```
This detects Cursor, Claude Code, Warp, Windsurf, and VS Code, writes the correct config for each, and creates a `theo.config.json` for project-level settings.
Restart your IDE after adding the config.
# Audit Trail
Source: https://docs.hitheo.ai/security/audit-trail
Immutable logging of all API activity.
Every API request is logged to an immutable audit trail. Audit records cannot be modified or deleted.
## What's Logged
| Field | Description |
| - | - |
| **Endpoint** | API route and method |
| **Identity** | API key ID (not the key itself) and user ID |
| **Timestamp** | ISO 8601 UTC timestamp |
| **Result** | HTTP status code, engine used, cost in credits |
| **Context** | SHA-256 prompt hash (not the raw prompt), active skill IDs, tool calls made |
| **Request ID** | Unique identifier for cross-referencing |
Raw prompts are never stored in the audit trail. Only a SHA-256 hash of the prompt is recorded, along with the prompt length and mode. This ensures auditability without exposing sensitive content.
## Access
```bash theme={null}
curl https://www.hitheo.ai/api/v1/audit \
-H "Authorization: Bearer $THEO_API_KEY"
```
Returns paginated audit events. Supports filtering by date range, API key, mode, and status code.
## Use Cases
* **Cost tracking** — see exactly which requests consumed credits
* **Debugging** — trace a request through the pipeline using the request ID
* **Compliance** — demonstrate access controls and data handling to auditors
* **Anomaly detection** — identify unusual usage patterns or unauthorized access attempts
# Authentication
Source: https://docs.hitheo.ai/security/authentication
API key security, dashboard auth, and best practices.
All API requests are authenticated via Bearer tokens (`theo_sk_...` keys).
## API Key Security
* **Hashed at rest** — keys are SHA-256 hashed before storage. We cannot recover a lost key; you must generate a new one.
* **Prefixed for identification** — all keys use the `theo_sk_` prefix.
* **Scoped permissions** — each key can be scoped to specific API capabilities (completions, skills, tools, connectors, billing).
* **Per-key rate limits** — rate limits are enforced per key based on your plan tier.
* **Instant revocation** — revoke any key immediately from the dashboard or API. Revoked keys are rejected within seconds.
* **Key rotation** — roll keys with a configurable grace period where both old and new keys work simultaneously.
## Key Rotation
We recommend rotating API keys regularly:
1. Create a new key in the dashboard
2. Update your environment variables / secrets manager
3. Verify traffic is flowing through the new key
4. Revoke the old key
Both keys work simultaneously during the transition — there is no downtime.
## Dashboard Authentication
The web dashboard supports email/password, social login, and optional multi-factor authentication (MFA). Session tokens are short-lived and scoped to the authenticated session.
## Transport Security
* All API traffic is encrypted via **TLS 1.2+**
* HSTS is enforced on all Theo domains
* Certificate transparency logs are monitored
## Supply Chain: Verifying npm Packages
Every official Theo npm package (`@hitheo/sdk`, `@hitheo/mcp`, `@hitheo/telegram`, `@hitheo/whatsapp`) is published with **npm provenance** starting with version `0.1.4`. Each tarball carries a cryptographically signed attestation linking the release back to the exact public CI workflow + git commit that produced it.
To verify before installing:
```bash theme={null}
npm audit signatures @hitheo/sdk @hitheo/mcp @hitheo/telegram @hitheo/whatsapp
```
You can also inspect an individual release's attestation URL:
```bash theme={null}
npm view @hitheo/sdk@latest dist.attestations
```
The attestation confirms that each tarball was built by the official Theo publish pipeline and was not substituted at any point before reaching the npm registry.
# Data Privacy
Source: https://docs.hitheo.ai/security/data-privacy
How Theo handles, stores, and protects your data.
## Data Handling Principles
* **No training on your data** — Prompts and responses are never used to train or fine-tune models. Your data is processed in real-time and used only to fulfill your request.
* **Encrypted at rest** — Sensitive credentials (e.g. connector auth) are encrypted at the application layer using AES-256-GCM. All other data is encrypted at rest via the database provider's storage-level encryption.
* **Encrypted in transit** — All communication uses TLS 1.2+ encryption.
* **Tenant isolation** — Your data is logically isolated from other accounts. API keys, conversations, and artifacts are scoped to your account.
* **API keys are hashed** — We store only a one-way hash of your key. Lost keys cannot be recovered.
## Data Retention
| Data Type | Retention |
| - | - |
| Conversations | Retained until you delete them via the API or dashboard |
| Audit logs | Retained for compliance period (minimum 90 days) |
| Cache entries | TTL-based automatic expiration (minutes to hours depending on mode) |
| Generated artifacts | Retained per your account settings; deletable at any time |
| Account data | Retained while your account is active; deleted on account closure |
## Data Deletion
You can delete your data at any time:
* **Conversations**: `DELETE /api/v1/conversations/{id}` or via the dashboard
* **Artifacts**: deletable from the dashboard or via API
* **Account**: contact support for full account and data deletion
## Third-Party Model Providers
When Theo routes your request to a model, the prompt is sent to the upstream provider for processing. We select providers with strong data handling commitments:
* Prompts are not used for provider model training
* Prompts are not stored by providers beyond the request lifecycle
* We do not send your API key or account information to providers
# Disclosure Policy
Source: https://docs.hitheo.ai/security/disclosure-policy
How to report a security vulnerability and what happens next. All reports go to security@opencharts.com.
Thanks for helping us keep Theo safe. OpenCharts is the parent company behind
Theo, and `security@opencharts.com` is the single inbox that covers every
product we operate. Every message lands with the security team — not a
general support queue.
## Reporting a vulnerability
Email **[security@opencharts.com](mailto:security@opencharts.com)** with as
much detail as possible. We prefer:
1. A short description of the issue.
2. Reproduction steps — a minimal request, command, or script works best.
3. The impact you believe the issue has.
4. Your contact info if you want credit.
Please **do not** open a public GitHub issue, social-media post, or blog
for suspected vulnerabilities.
### What happens next
* **Within 2 business days**: you receive an acknowledgement that a human
has read your report.
* **Within 7 business days**: we share a triage decision (accepted,
duplicate, out of scope, needs more info).
* **Throughout the fix**: we keep you updated and coordinate a
disclosure date if one is warranted.
This page is the canonical disclosure pointer. Our machine-readable
equivalent is at
[`hitheo.ai/.well-known/security.txt`](https://hitheo.ai/.well-known/security.txt).
## Scope
### In scope
* `hitheo.ai`, `api.hitheo.ai`, `docs.hitheo.ai`, `artifacts.hitheo.ai`
* The Theo dashboard, API routes, and the embed widget runtime
* The four public npm packages: `@hitheo/sdk`, `@hitheo/mcp`,
`@hitheo/telegram`, `@hitheo/whatsapp`
* Our GitHub Actions workflows (`.github/workflows/**`)
### Out of scope
* Denial-of-service testing against our production endpoints
* Social-engineering of our team or customers
* Physical access to our infrastructure
* Issues that require an attacker to already control the victim's
browser, operating system, email account, npm account, or GitHub
account
## Safe harbor
We will not pursue legal action against researchers who:
1. Follow this policy in good faith.
2. Do not deliberately access or modify other users' data beyond what's
necessary to demonstrate the issue.
3. Avoid techniques that degrade service for other customers.
4. Give us reasonable time to fix the issue before public disclosure.
## Supply chain: verifying npm provenance
Every official `@hitheo/*` package ships with an npm provenance
attestation signed by GitHub's OIDC token. You can verify the tarballs
you install with:
```bash theme={null}
npm audit signatures
```
See the [Authentication](/security/authentication) page for a deeper
walkthrough of how supply-chain provenance works on Theo.
## Secrets hygiene
If you find leaked credentials — API keys, database URLs, Clerk
secrets, Cloudflare tokens, and so on — in our code, logs, or any
public surface, please email `security@opencharts.com`. We will rotate
the affected secret and notify customers whose data might have been
exposed.
We maintain a list of secret-shaped patterns in our logger so leaked
values are redacted before they leave the process. A report of a leak
that slipped past our scrubber is especially welcome.
# Rate Limiting
Source: https://docs.hitheo.ai/security/rate-limiting
Request rate limits, tiers, spending caps, and how to handle 429 responses.
## Rate Limit Tiers
Rate limits are enforced per API key using a 60-second sliding window. Each key has a tier that determines its limits:
| Tier | Requests/min (RPM) | Tokens/min (TPM) |
| - | - | - |
| Free (default) | 60 | 100,000 |
| Starter | 300 | 500,000 |
| Pro | 1,000 | 2,000,000 |
| Enterprise | 5,000 | 10,000,000 |
All new API keys start on the **Free** tier.
## Per-Mode Limits
Expensive modes have lower RPM caps, scaled proportionally to your tier's base RPM:
| Mode | Free RPM | Starter RPM | Pro RPM | Enterprise RPM |
| - | - | - | - | - |
| Text / Code / Auto | 60 | 300 | 1,000 | 5,000 |
| Stealth | 30 | 150 | 500 | 2,500 |
| Image | 20 | 100 | 333 | 1,666 |
| Research | 15 | 75 | 250 | 1,250 |
| Video | 10 | 50 | 166 | 833 |
Dashboard sessions have a fixed 120 RPM limit.
## How to Increase Your Limits
### Check your current limits
```bash theme={null}
curl https://www.hitheo.ai/api/v1/rate-limits \
-H "Authorization: Bearer theo_sk_..."
```
### Request a tier upgrade
```bash theme={null}
curl -X POST https://www.hitheo.ai/api/v1/rate-limits/request-increase \
-H "Authorization: Bearer theo_sk_..." \
-H "Content-Type: application/json" \
-d '{
"requested_tier": "starter",
"use_case": "Production chatbot serving 10K daily active users",
"expected_volume": "~200 RPM peak, 50K requests/day"
}'
```
Requests are reviewed by the Theo platform team. You'll receive a `rate_limit.upgraded` webhook when approved.
## Credit Balance
In addition to request rate limits, each account has a credit balance. When your balance reaches zero, subsequent requests return `402 insufficient_credits` until you top up.
## Handling 429 Responses
When rate limited, the API returns:
* **Status 429** with one of three codes:
* `rate_limit_exceeded` — universal RPM exceeded
* `mode_rate_limit_exceeded` — per-mode RPM exceeded
* `token_limit_exceeded` — TPM exceeded
* **`Retry-After` header** — seconds to wait before retrying
The SDK handles this automatically with exponential backoff (configurable via `maxRetries`).
## Response Headers
Every response includes rate limit headers reflecting your tier's actual limits:
```
X-Ratelimit-Limit-Requests: 60
X-Ratelimit-Remaining-Requests: 47
X-Ratelimit-Reset-Requests: 58s
X-Ratelimit-Limit-Tokens: 100000
X-Ratelimit-Remaining-Tokens: 85000
X-Ratelimit-Reset-Tokens: 42s
```
# Building a Skill
Source: https://docs.hitheo.ai/skills/building-a-skill
Step-by-step guide to creating a Theo skill with defineSkill().
## 1. Scaffold
```bash theme={null}
mkdir my-skill && cd my-skill
theo skill init
```
This creates `theo-skill.json` and `README.md`.
## 2. Define the Manifest
Edit `theo-skill.json` or use `defineSkill()` in TypeScript:
```typescript theme={null}
import { defineSkill } from "@hitheo/sdk";
export default defineSkill({
name: "Inventory Check",
slug: "inventory-check",
version: "1.0.0",
description: "Real-time inventory lookup and reorder alerts",
category: "automation",
author: { name: "Acme Corp" },
systemPromptExtension: `
You are an inventory management specialist. When the user asks about
stock levels, use the check_stock tool. Flag items below reorder threshold.
`,
tools: [
{
name: "check_stock",
description: "Look up current stock levels for a SKU",
inputSchema: {
type: "object",
properties: {
sku: { type: "string", description: "Product SKU" },
},
required: ["sku"],
},
},
],
permissions: ["read:artifacts", "execute:tools"],
trigger: { type: "keyword", config: { keywords: ["stock", "inventory", "reorder"] } },
});
```
## 3. Validate
```bash theme={null}
theo skill validate
```
## 4. Publish
```bash theme={null}
theo skill publish
```
See [Publishing](/skills/publishing) and [Review Pipeline](/skills/review-pipeline) for details.
# Skill Manifest Reference
Source: https://docs.hitheo.ai/skills/manifest-reference
Complete reference for theo-skill.json fields.
See the [SDK defineSkill() reference](/sdk-reference/skills) for the full typed interface.
## Required Fields
| Field | Type | Description |
| - | - | - |
| `name` | `string` | Human-readable skill name |
| `slug` | `string` | Unique ID (lowercase, hyphens, no leading/trailing hyphens) |
| `version` | `string` | Semver (e.g., `1.0.0`) |
| `description` | `string` | Short description |
| `category` | `SkillCategory` | One of: `productivity`, `domain`, `integration`, `automation`, `creative` |
| `author` | `object` | `{ name: string, email?: string, url?: string }` |
| `systemPromptExtension` | `string` | Domain instructions injected into the LLM |
## Optional Fields
| Field | Type | Default | Description |
| - | - | - | - |
| `tools` | `SkillToolInput[]` | `[]` | Tool definitions |
| `permissions` | `SkillPermission[]` | `[]` | Required permissions |
| `knowledge` | `string[]` | `[]` | Bundled knowledge file paths |
| `modelPreference` | `string` | — | Preferred model ID |
| `trigger` | `SkillTriggerInput` | — | Activation trigger |
| `hooks` | `object` | — | `{ onInstall?, onUninstall? }` |
| `readme` | `string` | — | Markdown README |
| `changelog` | `string` | — | Markdown changelog |
| `license` | `string` | `"MIT"` | License identifier |
| `repository` | `string` | — | Source repo URL |
| `keywords` | `string[]` | `[]` | Search keywords |
# What Are Skills?
Source: https://docs.hitheo.ai/skills/overview
Installable packages of domain knowledge and capabilities — like apps for AI.
A skill is a package of domain knowledge and capabilities that extends what Theo can do. Think of it like an app for an AI — it gives Theo specialized expertise in a specific area.
## What's Inside a Skill
Every skill contains:
1. **System Prompt Extension** — domain instructions injected into the LLM context
2. **Tool Definitions** — callable actions the model can invoke
3. **Permissions** — what the skill needs access to
4. **Model Preference** — which model works best for this skill
5. **Trigger** — how the skill activates (keyword, event, schedule, manual)
6. **Knowledge Files** — bundled reference data
## Two Ways to Use Skills
### Installed Skills (Persistent)
Install a skill once, and it's active on every completion:
```typescript theme={null}
await theo.installSkill("skill-uuid-here");
const res = await theo.complete({ prompt: "Research the latest AI agent frameworks" });
// → Installed skill is automatically loaded
```
### Per-Request Skills (Ephemeral)
Activate skills for a single request:
```typescript theme={null}
const res = await theo.complete({
prompt: "Check stock levels for SKU-1234",
skills: ["inventory-check", "data-extraction"],
});
```
Both methods stack — installed skills + per-request skills are all active together.
## The Marketplace
Skills are published to the Theo marketplace. Other developers can browse, install, and rate them. Skill authors earn revenue when their skills are used.
See [Building a Skill](/skills/building-a-skill) to create your own.
# Permissions
Source: https://docs.hitheo.ai/skills/permissions
What skills can access and how permissions are enforced.
Skills declare what they need access to. Permissions are shown to users before install.
| Permission | What It Allows |
| - | - |
| `read:conversations` | Access conversation history |
| `read:artifacts` | Read generated files and images |
| `write:artifacts` | Create and store files |
| `write:notes` | Create user-visible notes |
| `external:http` | Make outbound HTTP requests |
| `execute:tools` | Call the skill's declared tools |
| `autonomous:run` | Execute without user in the loop |
## Enforcement
* Skills without `execute:tools` have their tools stripped at load time
* Skills without declared permissions operate in legacy mode (all tools allowed)
* Permission combinations that grant broad write or external-network access are promoted to a higher review tier during submission
# Publishing to the Marketplace
Source: https://docs.hitheo.ai/skills/publishing
Submit skills for review and distribution.
## Submission Flow
1. **Author** — Use `defineSkill()` or `theo skill init`
2. **Validate** — `theo skill validate`
3. **Submit** — `theo skill publish` or `POST /api/v1/skills/submit`
4. **Review** — Automated checks + risk-based manual review
5. **Publish** — Approved skills appear in the marketplace
## Via CLI
```bash theme={null}
theo skill publish
```
## Via API
```typescript theme={null}
const result = await theo.submitSkill(manifest);
console.log(result.status); // "approved" | "pending_review"
console.log(result.reviewTier); // "auto" | "staff" | "security"
```
## Via Skill Builder
Build skills visually in the dashboard canvas editor, then publish directly:
1. Open **Dashboard → Skills → Canvas**
2. Design your skill graph (prompts, models, tools, knowledge, vision nodes)
3. Click **Compile** to validate
4. Click **Test** to try it in the sandbox
5. Click **Publish** and choose visibility: **Private**, **My Organization**, or **Public Marketplace**
See the [Canvas Guide](/guides/evi-canvas) for the full walkthrough.
## Visibility Tiers
When publishing (via Canvas, CLI, or API), skills support three visibility levels:
* **Private** — Only the author can see and install the skill.
* **Organization** — Scoped to a specific org. All org members can discover and install it, but it’s not listed publicly.
* **Public** — Listed in the Skill Store marketplace for all Theo users.
# Revenue Sharing
Source: https://docs.hitheo.ai/skills/revenue-sharing
Earn credits when other developers use your skills.
Skills earn revenue. When another developer's API call activates your skill, you earn credits.
## How It Works
1. Developer installs your skill
2. Their API calls activate it
3. Theo tracks which skill contributed to each request
4. Your earnings are aggregated per billing period
5. Payouts are processed automatically to your connected account
## Tracking
View your earnings in the [Dashboard](https://api.hitheo.ai/dashboard/skills) or via the API.
# Review Pipeline & Risk Tiers
Source: https://docs.hitheo.ai/skills/review-pipeline
Automated and manual review for marketplace skills.
## Automated Checks
Every submission is scanned before it reaches a reviewer. Checks include manifest schema validation, prompt-injection heuristics, tool and permission audits, slug uniqueness, and version integrity. Per-author submission rate limits also apply. Specific detection rules and thresholds are not published.
## Risk Tiers
| Tier | Description |
| - | - |
| **Auto** | Low-risk manifests that pass all automated checks — approved without human review. |
| **Staff** | Manifests that introduce tools, knowledge files, or write-scoped permissions — reviewed by the Theo marketplace team. |
| **Security** | Manifests that combine external network access with write capability or other sensitive surfaces — reviewed by the security team before publish. |
Submissions that don’t clearly fall into a higher tier are promoted to the next tier up rather than auto-approved.
# Skill Sandbox & Testing
Source: https://docs.hitheo.ai/skills/sandbox-testing
Test skills in isolation before publishing.
Use the sandbox API to test a skill without publishing it:
```bash theme={null}
POST /api/v1/skills/sandbox
```
The sandbox executes the skill's system prompt extension and tools against a test prompt, returning the result without billing or persisting anything.
## Local Testing
1. Create your skill with `defineSkill()`
2. Run `theo skill validate` to check the manifest
3. Use per-request skills to test without installing:
```typescript theme={null}
const res = await theo.complete({
prompt: "Test: check stock for SKU-123",
skills: ["my-skill-slug"],
});
```
# Tool Definitions
Source: https://docs.hitheo.ai/skills/tool-definitions
Define callable actions within a skill.
Tools give skills the ability to take actions. Each tool has a name, description, and JSON Schema for inputs.
```typescript theme={null}
tools: [
{
name: "check_stock",
description: "Look up current stock levels by SKU and warehouse",
inputSchema: {
type: "object",
properties: {
sku: { type: "string" },
warehouse: { type: "string" },
},
required: ["sku"],
},
requiresApproval: false,
permissionLevel: "user",
},
]
```
## SkillToolInput Fields
| Field | Type | Description |
| - | - | - |
| `name` | `string` | Lowercase alphanumeric with underscores |
| `description` | `string` | What the tool does (the model reads this) |
| `inputSchema` | `object` | JSON Schema for arguments |
| `outputSchema` | `object` | Optional JSON Schema for results |
| `permissionLevel` | `string` | `"user"`, `"org_member"`, `"org_admin"`, `"system"` |
| `requiresApproval` | `boolean` | If true, user must approve before execution |
## Validation
Tool names must match `/^[a-z0-9_]+$/`. Names that imply code-execution, shell access, or other sensitive operations are rejected during review.
# Triggers & Autonomous Execution
Source: https://docs.hitheo.ai/skills/triggers-autonomous
How skills activate automatically.
## Trigger Types
| Type | Description |
| - | - |
| `manual` | User explicitly activates |
| `keyword` | Activates when prompt contains specific keywords |
| `event` | Activates on system events (e.g., new claim, new message) |
| `schedule` | Runs on a cron schedule |
## Autonomous Execution
Skills with `autonomous:run` permission can execute without a user sending a prompt:
* **Scheduled tasks** — "Every Monday, run the compliance checker"
* **Event triggers** — "When a new claim comes in, run triage"
* **Heartbeat** — a background worker checks for due tasks at a regular cadence
## Guard Rails
* Pre-flight credit check before each autonomous run
* Separate daily cap for autonomous actions
* Per-run caps on steps and total spend
* Credit checkpoint between steps
* Skills auto-pause after repeated failures
# 401 Unauthorized
Source: https://docs.hitheo.ai/troubleshooting/401-errors
Common causes of first-time 401 errors on the Theo API and how to fix them.
If your first request to the Theo API returns `401 Unauthorized`, it is almost always one of the causes below. Work through them in order.
## 1. The apex → www redirect (most common)
`https://hitheo.ai` 307-redirects to `https://www.hitheo.ai`. Most HTTP clients — including Node 18's built-in `fetch`, curl without `--location-trusted`, and several language runtimes — strip the `Authorization` header on 3xx responses as a security precaution. That leaves the redirected request unauthenticated and the server correctly returns `401 invalid_api_key`.
**Fix:** use the canonical `www` host directly. The SDK defaults to `https://www.hitheo.ai` as of `@hitheo/sdk@0.2.0`; if you pinned `baseUrl` manually, update it:
```typescript theme={null}
// Before
new Theo({ apiKey, baseUrl: "https://hitheo.ai" })
// After
new Theo({ apiKey, baseUrl: "https://www.hitheo.ai" })
// or: omit baseUrl entirely to pick up the default.
```
For raw curl:
```bash theme={null}
# Use www directly
curl -H "Authorization: Bearer $THEO_API_KEY" https://www.hitheo.ai/api/v1/models
```
The CLI diagnostic command catches this automatically:
```bash theme={null}
theo status # probes both apex and www, warns when your baseUrl is a redirect target
theo verify # machine-readable JSON diagnostic you can pipe into CI
```
## 2. Missing or malformed API key
Every request (except `GET /api/v1/health`) needs an `Authorization: Bearer theo_sk_...` header. Check:
* The header name is exactly `Authorization`, not `authorization:` with a stray colon or `X-API-Key`.
* The token is prefixed with `theo_sk_` (there is no `theo_sk_test_` variant — all keys are live).
* No leading/trailing whitespace in the token — a trailing newline from a `.env` file is a common cause.
* The key has not been revoked. Check the [API Keys dashboard](https://api.hitheo.ai/dashboard/api-keys).
## 3. Wrong scope on the key
API keys carry scopes (`completions`, `skills`, `tools`, `connectors`, `billing`). A key without the `completions` scope returns `403 missing_scope`, not `401`. If you see a `403` specifically: re-issue the key with the scopes you need, or ask the key's creator to update it.
## 4. Key expired (grace period ended)
When you rotate a key, the old one enters a grace window (configurable, default 60 min) then gets revoked. Requests against an expired key return `401 key_expired`. Rotate on the dashboard or via `POST /api/v1/keys/rotate` and swap the new token into your secret store.
## 5. Clock skew breaking HMAC on webhooks
Unrelated to API key auth, but sometimes reported as "401 on webhooks": webhook signature verification uses the `Theo-Signature` header which is HMAC-SHA256 over the request body. If your server's clock is more than 5 minutes out of sync, the signature won't match. Run `ntpdate -q pool.ntp.org` to check.
## Still stuck?
* Call `theo verify` (or `await theo.verify()` in the SDK) and share the output with support.
* Include the `X-Request-Id` response header in your ticket — every v1 response carries one, and successful responses also expose it as `request_id` in the JSON body. Support can look the request up in logs.
* Check [status.hitheo.ai](https://status.hitheo.ai) for active incidents.
# Export Audit Log (CSV)
Source: https://docs.hitheo.ai/api-reference/audit/export
GET /api/v1/audit/export
Download the audit log as a streamed CSV file.
Streams matching audit entries as a CSV attachment. Without `orgId`, the export is scoped to your own entries.
## Authentication
Requires an API key with `billing` scope. Org-scoped exports additionally require the **View audit log** permission for that organization.
## Query Parameters
Export entries for this organization instead of your personal entries.
Filter to a single action (e.g., `completion.created`).
ISO timestamp lower bound (inclusive).
ISO timestamp upper bound (inclusive).
## Response
`Content-Type: text/csv` attachment. Columns:
```
timestamp,action,entity_type,entity_id,model_id,ip_address,user_agent,route,input_summary,output_summary
```
## Example
```bash curl theme={null}
curl -L "https://www.hitheo.ai/api/v1/audit/export?from=2026-05-01&to=2026-06-01" \
-H "Authorization: Bearer $THEO_API_KEY" \
-o theo-audit-log.csv
```
# List Audit Events
Source: https://docs.hitheo.ai/api-reference/audit/list
GET /api/v1/audit
Query the immutable audit trail.
Query the immutable audit trail. Every API action (completions, skill installs, key operations, etc.) is logged with full context.
## Authentication
Requires a Bearer token. See [Authentication](/api-reference/authentication).
## Request Example
```bash theme={null}
curl https://www.hitheo.ai/api/v1/audit \
-H "Authorization: Bearer $THEO_API_KEY"
```
## Response
Returns an array of audit event objects. Each event includes:
Event ID.
Action performed (e.g., `"completion.created"`, `"skill.installed"`, `"key.created"`).
Type of entity affected (e.g., `"completion"`, `"skill"`, `"api_key"`).
ID of the affected entity.
User who performed the action.
ISO 8601 timestamp.
Summary of the request input.
Summary of the response output.
Audit events are stored in a tamper-evident, append-only log. They cannot be modified or deleted.
## Endpoint
`GET /api/v1/audit`
Requires authentication via Bearer token. See [Authentication](/api-reference/authentication).
# Get Benchmarks
Source: https://docs.hitheo.ai/api-reference/benchmarks/get
GET /api/v1/benchmarks
Retrieve aggregated platform performance benchmarks for a given time window.
## Query Parameters
Time window for aggregation. One of: `24h`, `7d`, `30d`. Default: `24h`.
## Response
The requested time window.
Per-mode latency statistics: `{ [mode]: { p50, p95, p99, count } }`.
Per-mode time-to-first-token statistics (streaming only): `{ [mode]: { p50, p95, count } }`.
Intent classification latency: `{ p50, p95, count }`. Null if no auto-mode requests in the window.
Aggregate counters: `total`, `failover_count`, `routing_accuracy`, `total_tokens`, `total_cost_cents`, `by_mode`.
## Authentication
Requires an API key or a dashboard session.
## Example
```bash curl theme={null}
curl "https://www.hitheo.ai/api/v1/benchmarks?window=24h" \
-H "Authorization: Bearer $THEO_API_KEY"
```
### Response
```json theme={null}
{
"window": "24h",
"latency_by_mode": {
"fast": { "p50": 450, "p95": 1200, "p99": 2100, "count": 1543 },
"code": { "p50": 890, "p95": 2400, "p99": 4100, "count": 312 }
},
"ttft_by_mode": {
"fast": { "p50": 180, "p95": 450, "count": 1200 }
},
"classification": { "p50": 12, "p95": 310, "count": 890 },
"counters": {
"total": 2847,
"failover_count": 3,
"routing_accuracy": 0.94,
"total_tokens": 4520000,
"total_cost_cents": 1250,
"by_mode": { "fast": 1543, "code": 312, "image": 201 }
},
"bucket": "2026-04-16T05"
}
```
# Create a top-up checkout
Source: https://docs.hitheo.ai/api-reference/billing/checkout
POST /api/v1/billing/checkout
Generate a hosted checkout URL to add credits to your personal balance or your team's shared credit pool.
Top up credits against the caller's personal balance or an organization's
shared team billing pool. Returns a hosted checkout URL your application
opens in a new tab or redirects the user to.
## Authentication
Requires a Bearer token with the `billing` scope. See
[Authentication](/api-reference/authentication).
## Body
Amount to add, in cents. Minimum `500` ($5.00), maximum `100000` ($1,000.00).
`"user"` (default when personal) or `"org"` (default when the caller is
inside a team and holds `manageBilling`). When `"org"`, the top-up
lands on the team's shared credit pool at
`organizations.polar_customer_id` and all subsequent team-scoped API
usage draws from that pool until it's depleted.
Optional. URL to redirect the user to after successful checkout.
Defaults to `/dashboard/billing?topup=success` (or
`/dashboard/billing?topup=success&scope=team` when `scope: "org"`).
## Example: personal top-up
```bash curl theme={null}
curl -X POST "https://api.hitheo.ai/api/v1/billing/checkout" \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount_cents": 2500 }'
```
## Example: team top-up
```bash curl theme={null}
curl -X POST "https://api.hitheo.ai/api/v1/billing/checkout" \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount_cents": 10000, "scope": "org" }'
```
```typescript SDK theme={null}
// Fund the team pool. Admins with `manageBilling` can call this; any
// other scope returns 403.
const { checkout_url } = await theo.billingCheckout({
amount_cents: 10_000,
scope: "org",
});
window.open(checkout_url, "_blank");
```
## Response
```json theme={null}
{
"checkout_url": "https://checkout.hitheo.ai/...",
"scope": "org"
}
```
## Errors
| Status | Code | Meaning |
| - | - | - |
| 400 | `missing_amount` | `amount_cents` missing or not an integer. |
| 400 | `amount_too_low` | Below the \$5.00 minimum. |
| 400 | `amount_too_high` | Above the \$1,000.00 maximum. |
| 400 | `org_context_required` | Requested `scope: "org"` without an active team. |
| 402 | `team_payment_method_required` | Team key creation blocked until the team funds billing. Retry after a checkout. |
| 403 | `permission_denied` | Caller lacks `manageBilling` in the active team. |
| 503 | `billing_unavailable` | Billing isn't configured on this deployment. |
## Lifecycle
1. Client calls this endpoint with `amount_cents` and optional `scope`.
2. The billing service reserves the right customer (personal or team),
creates a checkout session, and returns `checkout_url`.
3. The user completes checkout.
4. A background webhook routes the top-up to the correct credit pool
(user vs team) and marks the customer as having a payment method on
file.
5. Subsequent API usage drafts from the funded pool.
# Open the billing portal
Source: https://docs.hitheo.ai/api-reference/billing/portal
POST /api/v1/billing/portal
Generate a short-lived customer portal URL for a user's personal billing or an organization's team billing.
Open the hosted billing portal so a user can update a saved card, view
invoices, or download receipts. Scope the portal to a personal billing
customer or to a team (organization) billing customer.
## Authentication
Requires a Bearer token with the `billing` scope. See
[Authentication](/api-reference/authentication).
## Body
`"user"` (default when personal) or `"org"` (default when the caller is
inside a team and holds `manageBilling`). Team scope additionally
requires the team to have a payment method already on file — callers
who try the team portal before funding billing get a 409
`team_billing_setup_required` error instead.
## Example
```bash curl theme={null}
curl -X POST "https://api.hitheo.ai/api/v1/billing/portal" \
-H "Authorization: Bearer $THEO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "scope": "org" }'
```
```typescript SDK theme={null}
const { portal_url } = await theo.billingPortal({ scope: "org" });
window.open(portal_url, "_blank");
```
## Response
```json theme={null}
{
"portal_url": "https://portal.hitheo.ai/session/...",
"scope": "org"
}
```
## Errors
| Status | Code | Meaning |
| - | - | - |
| 400 | `org_context_required` | Requested `scope: "org"` without an active team. |
| 403 | `permission_denied` | Caller lacks `manageBilling` in the active team. |
| 409 | `team_billing_setup_required` | Team has no payment method on file — run a checkout first. |
| 503 | `billing_unavailable` | Billing isn't configured on this deployment. |
# Embed the Theo Browser
Source: https://docs.hitheo.ai/api-reference/browser/embed
Drop a live Theo Browser session into your own product with a single iframe.
Every Theo Browser session response includes an `embed_url` that renders the full Theo-branded browser chrome (URL bar, live indicator, auto-reconnect UI) in a third-party iframe. No SDK wiring, no manual CDP handling — point an `