Cogitator
Server Adapters

Server Adapters

Expose your Cogitator agents, workflows, and swarms as REST APIs with built-in streaming, WebSocket, and OpenAPI support.

Cogitator ships five server adapters that turn your agent runtime into an HTTP API. They share the same routes, request bodies and SSE streaming protocol; they differ in how they are mounted, how OpenAPI is generated and what their WebSocket endpoint can do. Pick the one that matches your stack.

Available Adapters

PackageFrameworkMin VersionStyle
@cogitator-ai/expressExpress4.18+Class-based CogitatorServer
@cogitator-ai/fastifyFastify5.xPlugin cogitatorPlugin
@cogitator-ai/honoHono4.xFactory cogitatorApp
@cogitator-ai/koaKoa2.15+Factory cogitatorApp
@cogitator-ai/tetsuTetsu0.6+ (Bun)Controller cogitatorController

Common Endpoints

Every adapter registers these routes. Express (config.basePath) and Fastify (prefix) mount them under /cogitator by default; Hono, Koa and Tetsu serve them where you mount the app, router or controller.

MethodPathDescription
GET/healthHealth check: { status, uptime, timestamp }
GET/readyReadiness probe: { status, checks } (200 when ready, 503 on dependency failure)
GET/agentsList agents: name, description, tool names (never instructions)
POST/agents/:name/runRun an agent (JSON response)
POST/agents/:name/streamRun an agent (SSE stream)
POST/agents/:name/resumeResume a run paused for approvals
POST/agents/:name/resume/streamResume a paused run and stream the rest of it (SSE stream)
POST/agents/:name/aguiRun or resume an agent for an AG-UI client (AG-UI SSE)
GET/threads/:idGet thread messages, whole or a page at a time (limit, cursor)
POST/threads/:id/messagesAdd a message to a thread
DELETE/threads/:idDelete a thread
GET/toolsList the tools of all agents (parameters as JSON Schema)
GET/workflowsList workflows
POST/workflows/:name/runExecute a workflow
POST/workflows/:name/streamStream workflow execution
POST/workflows/:name/resumeResume a workflow from a checkpoint, see Workflow checkpoints
POST/workflows/:name/resume/streamResume a workflow and stream the rest of it (SSE stream)
GET/swarmsList swarms
POST/swarms/:name/runExecute a swarm
POST/swarms/:name/streamStream swarm execution
GET/swarms/:name/blackboardThe swarm's configured blackboard sections (only when it is enabled)
GET/openapi.json, /docsOpenAPI spec and Swagger UI, see OpenAPI

Fastify serves its spec at /docs/json instead of /openapi.json, and Tetsu's document comes from docs() of @tetsujs/openapi.

Request bodies:

  • Agent run and stream: { input, context?, threadId? }. input must contain more than whitespace ("" and " " are refused before the model is called), and so must threadId. Without a threadId the run opens a new thread and names it in the answer (and in the start event of a stream).
  • Resume: { threadId, decisions?, defaultDecision? }, where a decision is { approved: boolean, reason?: string, updatedArguments?: object, remember?: boolean | { rule?: string, layer?: string } } (see Permissions) keyed by tool call id.
  • Workflow: { input?, options? } with options limited to maxConcurrency, maxIterations and checkpoint. checkpoint: true is accepted only by a server with workflowCheckpoints and refused otherwise, since a checkpoint would be lost with the request.
  • Workflow resume: { checkpointId, options? }, checkpointId non-blank and options limited to maxConcurrency and maxIterations.
  • Swarm: { input, context?, threadId?, timeout? }, timeout in milliseconds and at most 2147483647.
  • Thread message: { role, content, metadata? }, role one of user and assistant unless the server accepts more (see below).
  • Thread page: GET /threads/:id?limit=50 answers the newest 50 messages and a nextCursor, and ?limit=50&cursor=<nextCursor> the 50 before them, until an answer has no nextCursor. limit is a whole number from 1 to 1000. Without limit the route answers the whole thread.

Every adapter reads these bodies with the same validators from @cogitator-ai/server-shared (parseRunRequest, parseResumeRequest, parseAddMessageRequest, parseWorkflowRunRequest, parseWorkflowResumeRequest), Fastify before its schema coerces types and Tetsu as refinements of its Zod schemas, so they refuse exactly the same bodies. A conformance suite in @cogitator-ai/server-shared (CONFORMANCE_CASES) runs the same requests against every adapter in its tests.

JSON endpoints read only JSON bodies: a POST whose body is not application/json (or another +json type) is answered 415 UNSUPPORTED_MEDIA_TYPE before it is parsed. Browsers send text/plain and form bodies across origins without a CORS preflight, so reading them as JSON would let any web page start a run on a server without auth, or with the visitor's cookies.

POST /agents/:name/run and /resume answer the same object on every adapter, built by toAgentRunResponse():

FieldWhen
output, threadIdalways
usagealways: inputTokens, outputTokens, totalTokens, and the reasoning and cache counts when reported
toolCallsalways: { id, name, arguments } of each call
statusalways: completed, or paused when tool calls wait for approval
pendingApprovalswhen paused
reasoningwhen the agent asks for a reasoning summary
structuredwhen the answer matches the agent's responseFormat
structuredErrorwhen it does not
truncatedwhen the answer stopped at the output token limit
blockedwhen the provider withheld the answer (content_filter or refusal)
iterationLimitReachedwhen tool calls used up maxIterations
traceIdalways: links the answer to the server's traces

The answer never carries the system prompt, the history, trace spans (with raw tool arguments and errors) or the checkpoint of a paused run, which stays on the server and is resumed by thread id. The WebSocket complete event carries the same object, and the finish event of an agent stream the same usage, threadId and outcome fields. None includes the run's cost or duration.

Workflow checkpoints

Give an adapter a CheckpointStore of @cogitator-ai/workflows as workflowCheckpoints (under config for Express) to run workflows with checkpoints over HTTP:

import { PostgresCheckpointStore } from '@cogitator-ai/workflows';

const api = cogitatorApp({
  cogitator,
  workflows: { shipping },
  auth,
  workflowCheckpoints: new PostgresCheckpointStore({ client: pool }),
});
  • A run or stream with options.checkpoint: true saves its checkpoints in the store as the caller's: each one gets the userId that auth returned as its owner, or none for an anonymous caller. The JSON answer and the workflow_completed stream event carry the last one as checkpointId.
  • POST /workflows/:name/resume with { checkpointId } passes over the nodes the checkpoint completed and runs the rest, answered like /run, and /resume/stream streams it like /stream. The run limits hold as on /run, and the resumed run keeps saving checkpoints, so it can be resumed again.
  • A checkpoint that is missing, belongs to another user or to another workflow answers 404 CHECKPOINT_NOT_FOUND before anything runs, on /resume/stream before the stream opens. An anonymous caller reaches only checkpoints saved without an owner. Without workflowCheckpoints the resume routes still exist and answer 404 CHECKPOINT_NOT_FOUND, and checkpoint: true is refused.
  • A run that fails answers its error with the last checkpoint it saved as checkpointId, next to code and message ({ error: { message, code, checkpointId } }, Tetsu { status, message, error, checkpointId }). Its stream sends a workflow_failed event with { checkpointId } right before the error event. That is how a client gets the checkpoint of a failed run and resumes it. A resume that fails again names the checkpoint to resume from, its own last one or, when it saved none, the one it started from.

ownedCheckpoints(store, userId) of @cogitator-ai/server-shared is the per-user view the adapters run the executor with, for routes of your own.

Triggers and inbox

Give an adapter the runtime's trigger manager as triggers (experimental) and it serves the routes of API triggers, webhooks and the inbox of their results, next to the routes above. Start the manager yourself:

const cog = new Cogitator({ experimental_triggers: { agents, routines } });
const triggers = cog.experimental_triggers!;
await triggers.start();

app.route('/cogitator', cogitatorApp({ cogitator: cog, agents, triggers, auth }));
MethodPathAuthBody
POST/triggers/:id/fireThe trigger's own bearer token{ "text": "..." }, read raw
POST/triggers/:id/webhookThe sender's signature (HMAC, GitHub, Mailgun, Postmark, SendGrid, Slack)Any content type, read raw
GET/inboxThe adapter's auth and anonymous?status=unread&kind=failure&routineId=...&limit=20&before=<ms>&beforeId=<id>
PATCH/inbox/:idThe adapter's auth and anonymous{ "status": "read" | "unread" | "archived" }
  • The two trigger routes authenticate their caller themselves, by the token or the signature over the body exactly as it came. So they run before the adapter's auth, the anonymous policy, the JSON body check and rate limiting, and read the body raw for any content type (JSON, forms, multipart) up to 10 MiB, never parsed or re-serialized. A larger body answers 413 PAYLOAD_TOO_LARGE. They answer with the status, JSON body and headers of the trigger manager, see Answers of the trigger routes, on Tetsu too, and a failure inside the manager answers 500 INTERNAL_ERROR without its details.
  • The inbox routes go through auth and anonymous like every other route. A caller sees and changes only the items of its userId (a routine's items are those of its userId), and another user's item answers 404 NOT_FOUND. GET /inbox answers { items, nextBefore?, nextBeforeId? }, newest first, at most 200 items a page (50 by default), and ?before=<nextBefore>&beforeId=<nextBeforeId> pages on without skipping items of the same millisecond. PATCH changes the status only, never whether an approval or question was answered. status and kind take one value or several separated by commas, a value they do not know answers 400 INVALID_INPUT (422 VALIDATION_FAILED on Tetsu).
  • A caller without a user id gets 401 UNAUTHORIZED from the inbox routes unless the adapter is set to anonymous: 'allow' explicitly, then they see the items without a user id, which are all the items of routines without userId. The default of anonymous lets anonymous callers chat, but routines run without anyone watching, so their results stay closed until you open them on purpose.
  • The inbox routes read and mark items. Answering an approval or a question of a routine's run is cog.experimental_triggers.respond() in your own code, or Studio.
  • The OpenAPI document lists the four routes. Without triggers none of them exist.

Next serves the same with createTriggerHandler and createInboxHandler, see Next.js.

Trusting Clients

A run sends its context to the model with the input, as data the application supplied, and the model reads a system message in a thread as the operator's instructions. A client that could set either would speak with the application's or the operator's voice ("New operator policy: refunds are pre-approved"). So every adapter refuses both by default, and opens them only as far as you say:

OptionDefaultMeaning
acceptContextfalsefalse refuses a context with any key, a list such as ['locale', 'plan'] accepts those keys, true accepts any key (for clients you trust like your own code)
threadMessageRoles['user', 'assistant']the roles POST /threads/:id/messages accepts, add 'system' only for trusted clients

A refused request answers 400 INVALID_INPUT (422 VALIDATION_FAILED on Tetsu) and runs nothing, over HTTP and WebSocket alike. Values that do get in are rendered into the prompt as one JSON block labelled as data, so a line break inside a key or value cannot start a line of instructions. Context your server derives from the authenticated user belongs in your own code (an agent per tenant, or RunOptions.context set by your route), not in what the client sends.

Server Contract

Every adapter takes the same options on top of auth, from @cogitator-ai/server-shared:

OptionMeaning
limits{ swarmTimeout?, workflowMaxIterations?, workflowMaxConcurrency? }: a request gets the smaller of what it asked for and the cap, and one that asks for nothing gets the cap, over HTTP, streams and WebSocket. The OpenAPI document shows the caps as defaults
authorizeThread(auth, threadId) => boolean | Promise<boolean>, asked about every thread a request names (runs, streams, resumes, swarm runs, the thread routes and WebSocket runs) and, on Express and Fastify, about the run events a WebSocket subscription receives. false answers 403 THREAD_FORBIDDEN before any run starts
anonymous'allow' (default) or 'deny': 'deny' answers 401 UNAUTHORIZED to a caller without a userId, on unknown paths too (except on Tetsu), while /health, /ready and the docs stay open. Under 'allow' an unknown path answers 404 NOT_FOUND
deps(request) => deps: the deps (context.deps of the tools) of agent runs, streams and resumes for the request, never read from the body. Over WebSocket, Express and Koa take a separate websocket.deps(req) that gets the raw upgrade request, and Tetsu builds them once per connection

Next takes anonymous, authorizeThread(req, threadId) and deps(req) on its route handlers, its caller being the userId beforeRun returns. The conformance suite runs the same requests for each option against every adapter.

Threads and Users

The thread routes use the runtime's memory (cogitator.getMemory()); without a memory adapter they answer 503. A thread belongs to the user who created it — through a run with a threadId or POST /threads/:id/messages — and another user's thread answers 403 THREAD_ACCESS_DENIED. The user is the userId your auth function returns, so set one whenever several people share a server (Multiple Users).

Errors

Errors are JSON: { "error": { "message": "...", "code": "..." } } on Express, Fastify, Hono, Koa and Next, and Tetsu's envelope { status, message, error } on Tetsu. Every adapter maps errors with describeHttpError of @cogitator-ai/server-shared.

  • A CogitatorError keeps its message, its code and its own status, or the one mapped to its code, for example 429 LLM_RATE_LIMITED or 403 THREAD_ACCESS_DENIED. When the provider said when to try again, the answer carries Retry-After in whole seconds.
  • A swarm that ran out of time answers 504 RUN_TIMEOUT.
  • Any other error is logged on the server and answered as 500 with the message Internal server error, so internals never reach the client.
  • Unknown agents, workflows and swarms answer 404, invalid bodies answer 400 INVALID_INPUT (422 VALIDATION_FAILED on Tetsu, or the validation status the Tetsu app sets), and a body that is not JSON answers 415 UNSUPPORTED_MEDIA_TYPE.
  • Workflow and swarm routes need @cogitator-ai/workflows and @cogitator-ai/swarms; without them they answer 501.

In a stream, the same errors end the stream with an error event instead of finish.

Streaming Protocol

Every adapter implements the same SSE protocol from @cogitator-ai/server-shared. The response is text/event-stream with one JSON event per data: line, ending with data: [DONE]:

data: {"type":"start","messageId":"msg_abc123","threadId":"thread_7f3c"}

data: {"type":"text-start","id":"txt_def456"}

data: {"type":"text-delta","id":"txt_def456","delta":"Let me check."}

data: {"type":"text-end","id":"txt_def456"}

data: {"type":"tool-call-start","id":"call_ghi789","toolName":"get_weather"}

data: {"type":"tool-call-delta","id":"call_ghi789","argsTextDelta":"{\"city\":\"Paris\"}"}

data: {"type":"tool-call-end","id":"call_ghi789"}

data: {"type":"tool-update","toolCallId":"call_ghi789","content":"Asking the weather service"}

data: {"type":"tool-result","id":"res_jkl012","toolCallId":"call_ghi789","result":"Sunny","presentation":{"label":"Weather","detail":"Paris"}}

data: {"type":"text-start","id":"txt_mno345"}

data: {"type":"text-delta","id":"txt_mno345","delta":"It is sunny in Paris."}

data: {"type":"text-end","id":"txt_mno345"}

data: {"type":"finish","messageId":"msg_abc123","usage":{"inputTokens":50,"outputTokens":120,"totalTokens":170,"reasoningTokens":64,"cachedInputTokens":32},"threadId":"thread_7f3c","status":"completed"}

data: [DONE]
EventFields
startmessageId, threadId? (agent streams)
text-start / text-delta / text-endid, delta
reasoning-start / reasoning-delta / reasoning-endid, delta
tool-call-start / tool-call-delta / tool-call-endid (the tool call id), toolName, argsTextDelta, dropped? on the end
tool-updatetoolCallId, content?, details?, presentation?
tool-resultid, toolCallId, result, details?, presentation?, or dropped and reason for a call that never runs
dataid, name, data, transient?, toolCallId?
state-snapshot / state-deltasnapshot, or delta (a JSON Patch, RFC 6902)
reset-steppartIds, toolCallIds
approval-requiredthreadId, approvals
interrupt-requiredthreadId, interrupts
errormessage, code?
finishmessageId, usage?, threadId? and the outcome fields of the JSON answer (agent streams)
workflow / swarmevent, data

The start event of an agent stream names the run's thread: the one the request sent, or the one the server opened for it, so a client that sent no threadId continues the conversation by sending this one with its next message, even when the stream breaks before finish. The finish event repeats threadId and carries status, pendingApprovals, truncated, blocked, iterationLimitReached, structured and structuredError as the JSON answer does. All adapters build these events with AgentStreamSession from @cogitator-ai/server-shared.

The finish event of an agent stream (and of a resumed one) carries the run's usage, the same object as in the JSON answer of POST /agents/:name/run: inputTokens, outputTokens, totalTokens, and reasoningTokens, cachedInputTokens and cacheWriteTokens when the model reported them. Workflow and swarm streams finish without usage. createFinishEvent builds it with toRunUsage, the converter of the JSON answer, so a run's RunResult.usage can be passed as is.

Text and reasoning blocks are closed before a tool call starts. The tool-call-* events follow the model as it writes the call: tool-call-start once its id and name are known, a tool-call-delta with each piece of its JSON arguments, tool-call-end as soon as it is complete, so the events of two calls do not interleave unless the provider mixes their pieces, and no piece is lost when it does (Streaming Tool Input). A run whose stream is held back (output guardrails) sends the three at once right before the call runs. A call that will never run, because the model never finished it or the run did not keep it, gets a tool-result with dropped: true and reason (incomplete or discarded) instead of a result, after a tool-call-end with dropped: true when its end had not gone out, and the stream drops every call it announced that never came to run before it ends. A dropped call that the run then gives another tool under the same id is announced again with a new tool-call-start. A client that does not know dropped sees such a call as a call with an empty result. tool-update carries what a running tool reported with context.update(), and tool-result its details and presentation next to the result the model read (Results and Progress). An answer the model gave in one piece, without tokens, arrives as one text part before finish. With the Constitutional AI output filter on, tokens are held back until the filter checked the turn, so each turn arrives as one text part (see Constitutional AI). Agents with reasoning: { summary: true } stream their reasoning as its own part before the text it leads to. A run that pauses for approval sends approval-required with the pending calls (toolCallId, toolName, arguments, description, sideEffects?) right before finish, resume it with POST /agents/:name/resume, or with POST /agents/:name/resume/stream to stream the rest of the run the same way. A run that pauses on questions its tools asked (context.interrupt()) sends interrupt-required with them instead (id, kind, reason, message, responseSchema?, expiresAt?, toolCallId?, toolName?), and the JSON answer and finish carry them in interrupts: resume with the answers by id in responses (see Interrupts).

Data parts, state and step resets

A tool sends its client structured data with context.data({ name, data, id?, transient? }), which returns the part's id: the stream carries it as a data event, and a later data with the same id replaces the part in place, so a chart or a status card updates as the tool goes on. A transient part is for the moment only (a "searching..." status): a client shows it while the stream lasts and never keeps it with the message. Nothing of a data part reaches the model or memory.

const forecast = tool({
  name: 'forecast',
  description: 'Weather forecast for a city',
  parameters: z.object({ city: z.string() }),
  execute: async ({ city }, context) => {
    const id = context.data?.({ name: 'weather', data: { city, loading: true } });
    const report = await fetchForecast(city);
    context.data?.({ id, name: 'weather', data: report });
    return report.summary;
  },
});

The run's state is shared with the client: RunOptions.state is the state the run starts from, context.state.get() reads it in a tool and context.state.set(next) replaces it. The stream sends it as state-snapshot the first time, then as state-delta, a JSON Patch (RFC 6902) on the state the client holds, so a large state that changes a little costs a few operations. createJsonPatch and applyJsonPatch of @cogitator-ai/server-shared/json-patch make and apply them. The state is not saved with the thread: a client that holds it sends it with every run.

When a step the model streamed starts over, the stream sends reset-step with the text and reasoning parts (partIds) and tool calls (toolCallIds) it streamed, for the client to take back: the step streams anew after it. It happens when a model fails mid-answer and the turn moves to the next of the agent's fallbackModels (before, a stream that reached the client could not change model and failed), or when a streamed answer came out empty and the model is asked again. The server sends it only to clients that handle it: AgentStreamSession sets onStepReset with resetSteps: true, which the handlers of @cogitator-ai/next (for useCogitatorChat) and the app-server turn on. The /stream routes of the HTTP adapters leave it off, so a model that fails mid-answer there fails the run as before. useCogitatorChat of @cogitator-ai/next handles all three: data parts land in the message's data (transient ones only reach onData), the state in state, a reset step is taken out of the message.

A run or stream request may name multitaskStrategy (enqueue, reject, interrupt or rollback), what the run does when its thread has a run going on (see Double-Texting). reject refuses the new run with THREAD_BUSY, and the run that interrupt or rollback stopped fails with RUN_INTERRUPTED. POST /agents/:name/run answers both with 409. A stream has already sent 200 and its start event when the run is seated on its thread, so it gets them as an error event instead, { type: 'error', message, code: 'THREAD_BUSY' }, and a WebSocket run gets an error frame. The same holds for a resume: POST /agents/:name/resume answers an answer after expiresAt with 410 INTERRUPT_EXPIRED, /agents/:name/resume/stream sends it as an error event with that code. Without it the multitaskStrategy of the Cogitator config applies. Swarm routes have no thread to queue on and ignore multitaskStrategy.

Every stream also writes a heartbeat comment, : keep-alive, every 5 seconds while it is open (sseHeartbeatMs on each adapter, on createChatHandler and createResumeHandler of @cogitator-ai/next, on A2AServer and on the openai-compat server, 0 turns it off). SSE clients skip comments, and the heartbeat keeps a stream that waits on a slow tool or model from being closed by an idle timeout: Bun.serve closes a connection silent for 10 seconds, nginx one silent for 60.

Swarm routes close the swarm they build once the run ends, succeeded, failed or aborted: a distributed swarm holds two Redis connections and keeps its state in Redis until it is closed, which also gives that state its expiry. GET /swarms lists every agent of a swarm, its router and pipeline stages included.

Workflow streams send workflow events named node_started, node_completed, node_error, node_progress and workflow_completed, or workflow_failed (with the checkpointId of a checkpointed run) right before the error event of a failed run. Swarm streams send swarm events named agent_start, agent_complete, agent_error, message, the swarm's own events, and swarm_completed. Disconnecting the client aborts the run.

Agent streams can outlive a dropped connection: with resumableStreams every event carries an SSE id, the run goes on without the client, and the same route with Last-Event-ID replays what the client missed and follows the run to its end. See Resumable Streams.

The event types (StreamEvent, TextDeltaEvent, …), their factories (createTextDeltaEvent, createFinishEvent, …) and the encodeSSE / encodeDone helpers are exported from @cogitator-ai/server-shared, and the adapters re-export the event types. So are Zod schemas of the same shapes, for a client that checks what it receives:

import { StreamEventSchema } from '@cogitator-ai/server-shared';

const event = StreamEventSchema.parse(JSON.parse(data));
if (event.type === 'text-delta') render(event.delta);

StreamEventSchema refuses an unknown event type and drops a field a newer server adds. The OpenAPI documents of the adapters have the same schemas as components, StreamEvent among them. Tetsu's gets them from documentStreamEvents (see OpenAPI).

Long-Running Runs

An agent waiting on a slow tool or a reasoning model can stay silent for tens of seconds. Anything between the client and the server that closes idle connections then cuts the answer: the client sees the connection close (terminated, other side closed, socket hang up and the like) and a stream ends without finish and data: [DONE].

  • SSE streams. Every adapter writes a : keep-alive comment every sseHeartbeatMs (5 seconds by default) while a stream is open, and SSE clients skip comments. Leave it on unless something else keeps the connection alive. 0 turns it off.
  • Bun. Bun.serve closes a connection that stays silent for idleTimeout seconds, 10 by default. The Hono adapter and the Tetsu controller handle it for you: streams send heartbeats and the JSON routes lift the idle timeout for their own request. If you set idleTimeout yourself, keep it at 5 seconds or more and above sseHeartbeatMs. Routes you add next to the adapter need the same care: call server.timeout(request, 0) in a long JSON route, or send heartbeats in your own streams.
  • Reverse proxies and load balancers. Heartbeats keep streams open through them, but a JSON run answers only when the run ends. Raise the read or idle timeout above your longest run, or use the stream route for long runs. Common defaults: nginx proxy_read_timeout 60 seconds, AWS Application Load Balancer idle timeout 60 seconds, Cloudflare 100 seconds. For SSE also turn off response buffering in the proxy (nginx: proxy_buffering off;), or events arrive in bursts.

WebSocket

All adapters offer a WebSocket endpoint, but not the same one:

AdapterHow to enableDefault pathClient messagesRuns over WebSocket
ExpressenableWebSocket: true, then attachWebSocket(httpServer)<basePath>/wsrun, resume, stop, ping, subscribe, unsubscribeagents
FastifyenableWebSocket: true with @fastify/websocket installed<prefix>/wsrun, resume, stop, ping, subscribe, unsubscribeagents
HonoenableWebSocket: true and websocket.upgradeWebSocket/ws under mountrun, resume, stop, pingagents, workflows, swarms
KoasetupWebSocket(httpServer, ctx, options)/wsrun, resume, stop, pingagents, workflows, swarms
Tetsuwebsocket: true/ws under grouprun, resume, stop, pingagents, workflows, swarms

The shared part of the protocol:

{ "type": "run", "id": "r1", "payload": { "type": "agent", "name": "assistant", "input": "Hello" } }
{ "type": "resume", "id": "r2", "payload": { "name": "assistant", "threadId": "thread_1", "decisions": { "call_1": { "approved": true } } } }
{ "type": "stop" }
{ "type": "ping", "id": "p1" }

The server answers with { "type": "event", "id": "r1", "payload": { ... } } frames whose payload type is token (delta), reasoning (delta), tool-call (id, name, arguments), tool-result, and finally complete or cancelled, with { "type": "error", "id", "error" } for failures (Tetsu adds a code) and with pong. The result of an agent's complete is the same object as the JSON answer of /run, never the full RunResult. Runs get the connection's userId, and closing the socket aborts its run.

Fastify, Hono and Koa run one at a time per connection and refuse a second run with A run is already in progress, while Express aborts the running one and starts the new one. Tetsu runs several side by side, told apart by id, up to websocket.maxRuns, and stop with an id cancels only that run (see Tetsu). subscribe / unsubscribe exist only on Express and Fastify, see their pages.

Authentication

Each adapter takes an auth function that receives the framework's request object and returns an AuthContext ({ userId?, roles?, permissions?, metadata? }). Throwing rejects the request with 401 UNAUTHORIZED. Returning undefined lets the request through anonymously on Express, Fastify, Hono and Koa; on Tetsu it answers 401. The userId reaches every agent and swarm run (tools see it as context.userId) and scopes the thread routes. Rate limiting is built into Express and Fastify; CORS into Express.

Choosing an Adapter

Use caseRecommended
Existing Express codebase@cogitator-ai/express
High-performance, schema validation@cogitator-ai/fastify
Edge / multi-runtime (Workers, Bun, Deno)@cogitator-ai/hono
Koa-based middleware stack@cogitator-ai/koa
Bun app built on Tetsu controllers@cogitator-ai/tetsu

Quick Install

# pick one
pnpm add @cogitator-ai/express express
pnpm add @cogitator-ai/fastify fastify
pnpm add @cogitator-ai/hono hono
pnpm add @cogitator-ai/koa koa @koa/router
bun add @cogitator-ai/tetsu @tetsujs/core @tetsujs/sse

Next Steps

On this page