Skip to main content
Trinity
Updated Nov 17, 2026main@87e21ff
API Reference

Chat API

API endpoints for agent chat, voice, streaming, and public chat access. All endpoints require JWT Bearer token unless noted. See Authentication for details.

Full interactive API docs are available at http://localhost:8000/docs when running locally.

Authenticated Chat

POST

/api/agents/:name/chat

Send a message to an agent. Returns stream-json output for real-time responses. Accepts files attachments (see File attachments).

curl -X POST -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize the latest research findings"}' \
  http://localhost:8000/api/agents/research-agent/chat
GET

/api/agents/:name/chat/sessions

List all chat sessions for an agent.

GET

/api/agents/:name/chat/sessions/:id

Get a specific session with all its messages.

POST

/api/agents/:name/chat/sessions/:id/close

Close a chat session.

GET

/api/agents/:name/chat/history/persistent

Get persistent chat history across sessions.

GET

/api/agents/:name/chat/history

The agent's current /chat conversation.

DELETE

/api/agents/:name/chat/history

Reset the /chat conversation so the next turn starts fresh (owner or admin).

GET

/api/agents/:name/chat/session

Current /chat session info, including context usage.

GET

/api/agents/:name/model

Read the model the agent uses for subsequent messages. PUT sets it. On a Claude Code agent, PUTalso saves the value as the agent's own model, which turns the platform starts run on; if the save fails after the agent accepted it, the answer is 500 model_not_saved. GET adds default_model, backend_turn_model, default_model_source and default_model_refused (see Model Selection). An agent's own refusal (for example 400 for an invalid model, naming the valid ones) reaches you with its status and detail; an unreachable agent or an agent error answers 503.

GET

/api/agents/:name/activity

Session activity summary for the agent. DELETE clears it.

GET

/api/agents/:name/activity/:tool_id

Full detail of one tool call.

POST /chat runs one turn at a time per agent. While the agent is busy, further requests queue (up to 3 waiting); beyond that the route answers 429 with retry_after: 30. A stopped agent answers 503.

Failed turns

A turn whose run ends in an error is a failed execution, recorded with the run's real error — even when the agent had already written part of an answer, and on a resumed turn as well as a fresh one. POST /chat then answers with an error status rather than a 200 whose reply text is the error message. If the agent actually finished the turn and only the final result event was lost, Trinity recovers the reply instead of failing it.

Pull-mode pilot agents

Pull mode is an experimental, operator-only setting: agents named in PULL_MODE_PILOT_AGENTStake their work from Trinity's durable queue instead of having it pushed to them. On those agents only:

  • POST /chat, the Workspace, the session API, public links, Slack/Telegram/WhatsApp, rooms and paid chat all enqueue the turn and wait for a worker to claim it. A turn no worker claims within the agent's timeout fails as a capacity error (the session API answers 429). A caller that disconnects while its turn is still queued cancels it.
  • An async /task always answers queued, idle or not; its messagesays the task is queued for the agent's worker pool.
  • /chat memory is per caller: each person (or key owner) gets their own conversation with the agent, resumed turn to turn, instead of the one conversation every caller shares. A second turn on the same conversation waits up to 30 seconds, then gets 429; other callers' turns run in parallel.
  • GET /chat/history returns your conversation from the database. DELETE /chat/historymakes every caller's next turn start fresh and closes the conversations /chat was using.

Agents not in the pilot are unchanged.

Voice Chat

POST

/api/enterprise/client-portal/agents/:name/voice/start

Start a Workspace voice call bound to a chat (portal_session_id); returns a single-use websocket_ticket; 409 while a reply is in flight.

POST

/api/agents/:name/voice/start

Start a per-agent voice session (retained for API clients; the UI starts calls in the Workspace). Signed-in sessions only; returns a single-use websocket_ticket.

POST

/api/agents/:name/voice/stop

Stop a voice chat session.

GET

/api/agents/:name/voice/status

Get the current voice session status.

WS

/ws/voice/:session_id

WebSocket endpoint for bidirectional audio streaming. Used as the audio bridge for voice chat — the URL is returned by voice/start. Send {"type":"auth","ticket":...} as the first frame and wait for auth_ok; no credential goes in the URL — see Connecting the voice socket.

The per-agent voice prompt, voice name and canvas panel routes are listed in Voice Chat.

Public Chat (No Auth)

Public chat endpoints do not require authentication. They use a unique token to identify the public chat session.

POST

/api/public/chat/:token

Send a message via public chat using a share token.

GET

/api/public/history/:token

Get chat history for a public chat session.

GET

/api/public/executions/:token/:execution_id/status

Status of a turn started from this link.

GET

/api/public/executions/:token/:execution_id/stream

Live activity for that turn (SSE).

POST

/api/public/executions/:token/:execution_id/terminate

Stop a turn started from this link. Scoped per link and per trigger: it stops only turns this public link started — never a scheduled run, an operator chat, or a Workspace turn on the same agent. A link with email verification requires the same session_token that started the turn.

GET

/api/public/canvas/:token

Resolve a canvas share link (the page at /canvas/s/:token). A public share renders with no credential; an authorized share answers 401 until the viewer signs in and is re-checked against the agent's access list. Unknown, revoked and expired tokens are told apart only where the holder already knew the canvas existed. See Agent Canvas.

Paid Chat (x402)

Paid chat endpoints use the x402 payment protocol. Clients receive a 402 response with payment requirements, then resubmit with a payment proof header.

POST

/api/paid/:agent_name/chat

Send a paid chat message. Returns 402 with payment requirements or 200 with the response.

GET

/api/paid/:agent_name/info

Get payment requirements and pricing info for an agent.

Task Execution

POST

/api/agents/:name/task

Submit a stateless task. async_mode: true returns at once with status: "accepted" and an execution_id; otherwise the call holds until the task finishes (see below). Accepts files attachments.

curl -X POST -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"message": "Generate a report on Q1 sales data"}' \
  http://localhost:8000/api/agents/research-agent/task
GET

/api/agents/:name/executions

List all executions (tasks and schedule runs) for an agent.

GET

/api/agents/:name/executions/:id

Execution details (status, response, cost) — the polling target for async_mode and for a receipt.

GET

/api/agents/:name/executions/:id/log

Full execution transcript (tool calls and results).

GET

/api/agents/:name/executions/:id/stream

Live execution log (SSE) while it runs.

GET

/api/agents/:name/executions/running

Executions currently running on the agent.

POST

/api/agents/:name/executions/:id/terminate

Stop a running or queued execution. Answers terminated, cancelled_while_queued, cancelled_while_parked, or already_finished; a stopped run ends as cancelled, not failed.

POST

/api/agents/:name/fan-out

Dispatch N tasks in parallel — see Fan-Out.

GET

/api/agents/:name/fan-out/:fan_out_id

Poll a fan-out batch while it runs — see Fan-Out → Polling a batch.

Sync task calls and the execution_id receipt

A synchronous /task call (the default, async_mode: false) holds the HTTP connection for the whole run — at capacity it queues on the same connection and long-polls until the execution reaches a terminal state. The MCP chat_with_agent(parallel=true) tool wraps this route and gives up before the MCP gateway does, answering with {status: "queued_timeout", execution_id} so the caller reads the outcome with get_execution_result (over REST, GET /api/agents/{name}/executions/{id}) instead of re-sending — see MCP Integration. If you know the task will run long, send async_mode: true from the start.

A sync /task that fails, times out, or is cancelled releases its Idempotency-Key claim, so a legitimate retry with the same key goes through instead of answering 409 for the rest of the day; a call whose long-poll timed out while the execution was still queued or running completes the claim with the same queued_timeout receipt, so a replay answers 200 with the execution to poll.

File attachments

POST /chat and POST /task accept a files array of {name, mimetype, size, data_base64} (raw base64 or a data: URI). Images are passed to the agent as vision content; other files land in /home/developer/uploads/ inside the container. Accepted: images, plain text, CSV, JSON, and ZIP (stored unextracted — the agent unpacks it itself). Rejected: PDF, tar/gzip/rar, audio, video. Web limits: 3 files per message, 5 MB per file, 10 MB of images in total.

Model override

POST /chat, POST /task, and POST /api/agents/{name}/sessions/{id}/message (see Agent Sessions) accept an optional model. The value is checked before anything is dispatched:

  • Empty, whitespace, or omitted means the agent's own model, else the platform default; the model the run used is recorded as model_used.
  • Otherwise it must start with a known model family, ignoring case: a short alias (sonnet, opus, haiku, fable) or a full id (claude-…, gemini-…, gpt-…, codex…). Suffixes such as [1m] are kept.
  • Anything else is refused with 422, and the error names the value: '<value>' is not a model id. Use a short alias (sonnet, opus, haiku, fable) or a full id such as '…'.

A refused request starts no execution. It does not use up its Idempotency-Key, and a refused session turn leaves no unanswered message in the session. The check is on the shape only: an id with a valid prefix that the provider does not serve still fails when the run starts.

Per-task max_turns

POST /task accepts an optional max_turns (1–500). It can only tighten the agent's max_turns_task guardrail, never raise it: the agent runs on the lower of the two, and a missing value leaves the guardrail in force. It applies to sync and async tasks, a queued task, and a task released by a skill approval. A task that stops at the cap fails with 422 and X-Trinity-Error-Code: max_turns (see Agent Guardrails). That failure is final for its Idempotency-Key: the same key replays the same 422 with X-Idempotent-Replay: true instead of running the task again. Claude Code agents only; Gemini and Codex log the value and rely on the timeout.

Deprecated: per-task timeout_seconds

The timeout_seconds field on the task request body is deprecatedand will be removed in a future release. The agent's execution timeout (GET/PUT /api/agents/{name}/timeout) is authoritative.

Current behavior: the field is still honored, but values above the agent's timeout cap are clamped down to the cap (the server logs a deprecation warning). Omit the field — the task then uses the agent's configured timeout. To run longer tasks, raise the agent's timeout cap instead.

Idempotency

Endpoints that trigger an execution accept an optional Idempotency-Key header so you can retry safely without creating duplicate executions. Pick any unique string per logical request (e.g., a UUID) and resend it on retry:

curl -X POST http://localhost:8000/api/agents/my-agent/task \
  -H "Authorization: Bearer <token>" \
  -H "Idempotency-Key: 7f3a2c1e-..." \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize the latest reports"}'
  • The same key within 24 hours returns the original result with the header X-Idempotent-Replay: true — no second execution is created. The one exception is a receipt whose run has ended without success (see Retrying after a failed run): then the same key starts a new run.
  • A duplicate sent while the first request is still running returns 409 with the original execution_id to poll (for /fan-out, that field carries the batch's fan_out_id).
  • If the first attempt was rejected before dispatch (e.g., at capacity), the key is released so the retry goes through.
  • The header is optional and fail-open: omitting it preserves normal behavior, and a dedup-layer error never blocks a real request.

Retrying after a failed run (/chat and /task)

An async /task answers with a receipt — {"status": "accepted" | "queued" | "queued_timeout", "execution_id": ..., "async_mode": true}. A sync /task, or a /chat turn on a pull-mode agent, that outlives its wait answers 504 but stores the same kind of receipt (queued_timeout). That stored receipt is what an identical request replays, as a 200 with X-Idempotent-Replay: true. Whether it is replayed depends on how its run is doing:

The receipt's run is…An identical request with the same key gets
queued, running or pending_retrythe original receipt (X-Idempotent-Replay: true)
successthe original receipt — read the result from the execution
failed, cancelled or skipped, or the execution no longer existsa new run with a new execution_id, no replay header
failed with an error starting lease_expired: (no result arrived before the slot expired, so the run may still report back)the original receipt until the agent's timeout + 5 minutes after the failure; after that, a new run

A non-receipt result (a completed sync reply) always replays. Scheduler-issued keys (sched:…) are never reclaimed, and a request for an approval-gated skill is answered by its approval record first.

# 1. Dispatch async with a key
curl -s -X POST http://localhost:8000/api/agents/my-agent/task \
  -H "Authorization: Bearer <token>" -H "Idempotency-Key: report-2026-10-06" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize the latest reports", "async_mode": true}'
# -> 200 {"status": "accepted", "execution_id": "<first-id>", "async_mode": true, ...}

# 2. Check the outcome
curl -s -H "Authorization: Bearer <token>" \
  http://localhost:8000/api/agents/my-agent/executions/<first-id>
# -> {"status": "failed", ...}

# 3. Re-send the identical request: a new run, no X-Idempotent-Replay header
curl -s -X POST http://localhost:8000/api/agents/my-agent/task \
  -H "Authorization: Bearer <token>" -H "Idempotency-Key: report-2026-10-06" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize the latest reports", "async_mode": true}'
# -> 200 {"status": "accepted", "execution_id": "<second-id>", ...}

Checking the status tells you whether to retry; it cannot make a retry safe. Anything the failed run already did (a message sent, a file written) may happen again in the new run — effect de-duplication is per execution, and the new run has a new execution_id. Two identical retries that arrive together start one new run.

Wired boundaries: /api/agents/{name}/chat, /api/agents/{name}/task, /api/agents/{name}/fan-out, /api/agents/{name}/voip/call, /api/agents/{name}/data/import, /api/paid/{agent_name}/chat (always keyed on the payment signature plus message, so a different client key never forks the execution), webhook triggers (key auto-derived from token + body when the header is absent), and the MCP chat_with_agent / fan_out tools (deterministic key derived from the call arguments).

Endpoint Summary

EndpointMethodDescription
/api/agents/{name}/chatPOSTSend message (stream-json output); accepts files attachments
/api/agents/{name}/chat/sessionsGETList sessions
/api/agents/{name}/chat/sessions/{id}GETSession with messages
/api/agents/{name}/chat/sessions/{id}/closePOSTClose session
/api/agents/{name}/chat/history/persistentGETPersistent history
/api/agents/{name}/chat/historyGETThe agent's current /chat conversation
/api/agents/{name}/chat/historyDELETEReset the /chat conversation so the next turn starts fresh (owner or admin)
/api/agents/{name}/chat/sessionGETCurrent /chat session info, including context usage
/api/agents/{name}/modelGETRead the model the agent uses for subsequent messages; adds default_model, backend_turn_model, default_model_source and default_model_refused
/api/agents/{name}/modelPUTSet the model the agent uses for subsequent messages. On a Claude Code agent, also saves it as the agent's own model (500 model_not_saved if that save fails after the agent accepted it). An agent's own refusal (e.g. 400 for an invalid model) is passed through; an unreachable agent or agent error answers 503
/api/agents/{name}/activityGETSession activity summary
/api/agents/{name}/activityDELETEClear the session activity summary
/api/agents/{name}/activity/{tool_id}GETFull detail of one tool call
/api/enterprise/client-portal/agents/{name}/voice/startPOSTStart a Workspace voice call bound to a chat; returns a single-use websocket_ticket
/api/agents/{name}/voice/startPOSTStart a per-agent voice session (signed-in sessions only); returns a single-use websocket_ticket
/api/agents/{name}/voice/stopPOSTStop session
/api/agents/{name}/voice/statusGETSession status
/ws/voice/{session_id}WSAudio WebSocket bridge (URL returned by voice/start); authenticate with a first-frame ticket, never in the URL
/api/public/chat/{token}POSTPublic chat
/api/public/history/{token}GETPublic history
/api/public/executions/{token}/{execution_id}/statusGETStatus of a turn started from this link
/api/public/executions/{token}/{execution_id}/streamGETLive activity for that turn (SSE)
/api/public/executions/{token}/{execution_id}/terminatePOSTStop a turn started from this link (scoped per link and per trigger)
/api/public/canvas/{token}GETResolve a canvas share link
/api/paid/{agent_name}/chatPOSTPaid chat (402/200)
/api/paid/{agent_name}/infoGETPayment requirements
/api/agents/{name}/taskPOSTSubmit a stateless task (async_mode: true returns an execution_id at once; otherwise holds until done); accepts files
/api/agents/{name}/executionsGETList executions
/api/agents/{name}/executions/{id}GETExecution details (status, response, cost) — polling target for async_mode and receipts
/api/agents/{name}/executions/{id}/logGETFull execution transcript (tool calls and results)
/api/agents/{name}/executions/{id}/streamGETLive execution log (SSE) while it runs
/api/agents/{name}/executions/runningGETExecutions currently running on the agent
/api/agents/{name}/executions/{id}/terminatePOSTStop a running or queued execution (ends as cancelled, not failed)
/api/agents/{name}/fan-outPOSTDispatch N tasks in parallel
/api/agents/{name}/fan-out/{fan_out_id}GETPoll a fan-out batch while it runs