Chat API
The chat endpoint is Studio's primary interface for AI-powered content management. It uses Server-Sent Events (SSE) to stream the AI response and tool execution results in real time.
Internal SPA endpoint
This documents the internal chat endpoint that powers the Studio web app. It is authenticated with a session cookie and gated by workspace + project roles (owner / admin / member, combined with the project role editor / reviewer / viewer). For programmatic, API-key access, use the Conversation API instead — it has its own 3-role model.
Chat (SSE)
Start a conversation with the AI agent.
POST /api/workspaces/:workspaceId/projects/:projectId/chatRequest Body
interface ChatRequest {
message: string
conversationId?: string // Resume existing conversation
model?: string // AI model override
attachments?: ChatAttachment[] // From POST .../attachments
context?: {
activeModelId: string | null
activeLocale: string
activeEntryId: string | null
panelState: 'overview' | 'model' | 'branch' | 'vocabulary'
activeBranch: string | null
contextItems?: ContextItem[]
}
}
interface ChatAttachment {
blocks: AIContentBlock[] // As returned by the attachments endpoint
filename?: string
kind?: 'text' | 'document' | 'image'
}| Field | Type | Required | Description |
|---|---|---|---|
message | string | Yes | User message text |
conversationId | string | No | Existing conversation ID for multi-turn |
model | string | No | Chat model ID (see Model selection) |
attachments | ChatAttachment[] | No | Blocks produced by the attachments endpoint. They are re-validated on receipt and forged or invalid blocks are dropped |
context | ChatUIContext | No | Current UI state for context-aware responses. When omitted, an overview context with nothing selected is used |
Model selection
model takes one of the chat catalog IDs: claude-haiku-5-5, claude-sonnet-5-5, or claude-opus-5-5. Sonnet and Opus require a plan with the Advanced AI Models feature (ai.pro_models), and Opus is closed during a trial when Studio's key pays for the tokens. A retired ID from an older client is mapped to its family's current model. If the requested model is missing, unknown, or not available to the workspace, the request falls back to claude-sonnet-5-5 (or the first available model when Sonnet is not available).
Credit reservation
A Studio-funded turn reserves the plan's per-message credit ceiling before the model runs, and the turn spends against that reservation as a budget. When the turn ends (completed, errored, or the client disconnects) the credits it did not use are refunded, so concurrent turns can never take more than the month's pool holds. A turn on your own Anthropic key (BYOA) books 1 credit and is never refused for quota. If credits run out mid-turn, the stream ends with a done event that carries the notice (see Event Types). Quota and overage details: Billing & Plans.
Context Items
The contextItems array allows the client to pin specific content items to the conversation:
interface ContextItem {
type: 'model' | 'entry' | 'field' | 'asset'
modelId: string
modelName?: string
entryId?: string
fieldId?: string
assetId?: string
data?: unknown
}Response (SSE Stream)
The response is a stream of Server-Sent Events with data: lines containing JSON:
data: {"type":"conversation","id":"uuid"}
data: {"type":"text","content":"I'll create a new blog post"}
data: {"type":"tool_use","id":"tool_1","name":"save_content"}
data: {"type":"tool_input","id":"tool_1","input":{"model":"blog-post","locale":"en","data":{}}}
data: {"type":"tool_result","id":"tool_1","name":"save_content","input":{"model":"blog-post","locale":"en","data":{}},"result":{"branch":"cr/content/blog-post/en/...","merged":true}}
data: {"type":"text","content":"Done! I've created the blog post and it has been auto-merged."}
data: {"type":"done","usage":{"inputTokens":1234,"outputTokens":567},"affected":{"models":["blog-post"],"locales":["en"],"snapshotChanged":false,"branchesChanged":true}}Event Types
| Event Type | Description | Key Fields |
|---|---|---|
conversation | Conversation created/resumed. A conversationId you sent that does not belong to you starts a new conversation | id |
text | AI text chunk (streaming) | content |
tool_use | The model started a tool call | id, name |
tool_input | The tool call's full input is known; execution is about to start | id, input |
tool_result | Tool execution completed | id, name, input, result, affected |
done | Stream complete | usage, affected, and when the turn was cut short: stoppedBy |
error | Error occurred | message |
stoppedBy is credits or budget when the turn hit its spend ceiling. In the credits case (the month's credits ran out) the done event also carries code: "ai_credits_exhausted", resetsAt, and a message with the reset date.
Affected Resources
The done event includes an affected object that tells the client what to refresh:
interface AffectedResources {
models: string[] // Model IDs with content changes
locales: string[] // Locales that were modified
snapshotChanged: boolean // Model definitions changed (reload schema)
branchesChanged: boolean // Branch list changed (reload branches)
branch?: string // Specific branch created/merged/deleted
}Available Agent Tools
The agent can call these tools based on user permissions:
The tool set offered to the model is also narrowed by the project's current phase. Roles here are the internal agent's effective roles (workspace admin/owner, or the member's project role viewer/reviewer/editor). "Min Role" is the lowest role that may invoke the tool.
| Tool | Description | Min Role |
|---|---|---|
list_models | List all content models | viewer |
get_content | Read content entries | viewer |
save_content | Create/update content | editor |
replace_in_field | Find and replace text inside a text field | editor |
delete_content | Delete entries or dictionary keys | editor |
save_model | Create/update model definitions | admin |
validate | Validate content against schemas | viewer |
list_branches | List pending cr/* branches | viewer |
merge_branch | Merge a content branch | reviewer |
reject_branch | Reject/delete a branch | reviewer |
request_changes | Send a pending branch back to its author with a comment | reviewer |
init_project | Initialize .contentrain/ structure | admin |
copy_locale | Copy content between locales | editor |
brain_query | Read from brain cache | viewer |
brain_search | Full-text search across content | viewer |
brain_analyze | Content analysis (SEO, parity, stale, quality) | viewer |
validate_schema | Comprehensive schema validation | viewer |
search_media | Search media library | viewer |
upload_media | Upload media from URL | editor |
get_media | Get media asset metadata | viewer |
update_status | Publish/unpublish/archive entries | editor (published: admin) |
update_media | Update asset alt text, tags, focal point | editor |
delete_media | Delete an asset and its variants | editor |
branch_health | Check pending-branch warn/block thresholds | viewer |
relation_expand | Resolve forward/reverse relations for an entry | viewer |
vocabulary | Read or update the project glossary | editor |
add_locale | Register a new supported locale | admin |
delete_model | Permanently delete a model and its content | admin |
list_submissions | List form submissions | viewer |
approve_submission | Approve form submission | reviewer |
reject_submission | Reject form submission | reviewer |
list_comments | List comments by status | viewer |
approve_comment | Approve a comment for public display | reviewer |
reject_comment | Reject a comment or mark it as spam | reviewer |
reply_comment | Post a public moderator reply | reviewer |
Error Codes
| Status | Condition |
|---|---|
400 | Missing message, or attachments over the count/size limits (chat.no_api_key when no Anthropic key is configured) |
401 | No valid session |
403 | chat.no_permissions: the caller has no available tools in this project (not a member) |
429 | chat.rate_limited (per-user rate limit), or the month's AI credits are used up (chat.monthly_limit_reached, or chat.trial_credit_cap_reached during a capped trial). The credit case includes data.code: "ai_credits_exhausted" and data.resetsAt |
500 | chat.conversation_create_failed |
Example
curl -X POST http://localhost:3000/api/workspaces/{wsId}/projects/{projId}/chat \
-H "Content-Type: application/json" \
-H "Cookie: h3-session=..." \
-d '{
"message": "Create a blog post titled Hello World",
"context": {
"activeModelId": "blog-post",
"activeLocale": "en",
"activeEntryId": null,
"panelState": "model",
"activeBranch": null
}
}' \
--no-bufferAttachments
Pre-upload files or pasted links before sending a chat message. This endpoint converts each input into AI content blocks (AttachmentRef[]); the client then carries those blocks in the chat POST body, keeping the SSE handler JSON-only and letting the UI show per-attachment progress and errors.
POST /api/workspaces/:workspaceId/projects/:projectId/attachmentsThe channel is selected by Content-Type:
- Link paste (JSON):
{ "url": "https://..." }or{ "urls": ["https://...", ...] }. Remote fetches are SSRF-guarded. - File upload (
multipart/form-data): one or morefileparts, plus an optionalintentpart.intent=mediapersists images to the media library; any other value (or absent) treats them as ephemeralcontext.
Limits
| Limit | Value |
|---|---|
| Max items per request | 10 (URLs or files) |
| Max file size | 32 MB per file |
Response
{
"attachments": [
{
"id": "att_diagram.png",
"source": "upload",
"filename": "diagram.png",
"mime": "image/png",
"kind": "image",
"blocks": [ /* AIContentBlock[] */ ],
"error": null
}
]
}source is upload (multipart) or link (URL). Per-item failures (e.g. a file over the size limit) are reported inline via the error field rather than failing the whole request.
Plan gating
The endpoint itself is not feature-gated -- text, PDF, and link attachments ride the existing chat token metering. Only the image-to-CDN branch is plan-gated: in Community Edition it degrades to inline base64 instead of a CDN upload.
Auth
Requires workspace owner, admin, or member role. A member must also belong to the project.
Error Codes
| Status | Condition |
|---|---|
400 | No URL provided, more than 10 items, or no file part in the multipart body |
403 | Member is not a project member |
404 | Project not found in the workspace |
Conversations
These routes only see the signed-in user's own conversations.
List Conversations
GET /api/workspaces/:workspaceId/projects/:projectId/conversationsReturns the caller's conversations in this project, most recent first, with title and timestamps.
Delete Conversation
DELETE /api/workspaces/:workspaceId/projects/:projectId/conversations/:conversationIdDeletes the conversation and all its messages. Returns { "deleted": true }.
Get Conversation Messages
GET /api/workspaces/:workspaceId/projects/:projectId/conversations/:conversationId/messagesReturns up to 300 messages in chronological order, each with id, role, content, content_blocks, tool_calls, model, created_at, and turn_id. Thinking blocks are stripped from content_blocks. Returns 404 if the conversation does not exist or belongs to someone else.
Related Pages
- Agent System -- how the agent works internally
- Content API -- direct content operations
- Conversation API -- public conversation endpoint