Cogitator
Server Adapters

Tetsu Adapter

Serve Cogitator agents, threads, workflows and swarms from a Tetsu application on Bun — one controller with validated requests, SSE, WebSocket and an OpenAPI document.

The @cogitator-ai/tetsu package provides cogitatorController, a Tetsu controller with every Cogitator route. Requests and responses are Zod schemas, so Tetsu validates them, types the handlers and describes them in the OpenAPI document. Tetsu runs on Bun 1.4 or later.

Installation

bun add @cogitator-ai/tetsu @cogitator-ai/core @tetsujs/core @tetsujs/sse

Add @cogitator-ai/workflows and @cogitator-ai/swarms to serve the workflow and swarm endpoints, and @tetsujs/openapi for the document.

Basic Setup

import { Agent, Cogitator } from '@cogitator-ai/core';
import { cogitatorController } from '@cogitator-ai/tetsu';
import { createApp, group } from '@tetsujs/core';
import { docs } from '@tetsujs/openapi';

const cogitator = new Cogitator({
  llm: { defaultModel: 'google/gemini-3.5-flash-lite' },
  memory: { adapter: 'memory' },
});

const chat = new Agent({
  name: 'chat',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a helpful assistant.',
});

const app = createApp({
  routes: [
    group('/cogitator', { children: [cogitatorController({ cogitator, agents: { chat } })] }),
    docs({ info: { title: 'Agents', version: '1.0.0' } }),
  ],
});

Bun.serve({ ...app, port: 3000 });

Long runs on Bun

Bun.serve closes a connection that stays silent for idleTimeout seconds, 10 by default, so without help a run that waits on a slow tool or model for longer ends with the connection closed. The controller keeps both kinds of answer open without any setting: the JSON routes (run, resume, workflow run and resume, swarm run) lift the idle timeout for their own request once its body is validated, and SSE streams write a heartbeat comment every sseHeartbeatMs (5 s by default). If you set idleTimeout, keep it above sseHeartbeatMs and at 5 seconds or more, since Bun cuts connections at once below that whatever is written. See Long-Running Runs for proxies and load balancers.

The routes are the common endpoints under the group's prefix. The document is at /openapi.json and the page at /docs.

Options

interface CogitatorDeps {
  cogitator: Cogitator;
  agents?: Record<string, Agent>;
  workflows?: Record<string, Workflow>;
  swarms?: Record<string, SwarmConfig>;
  auth?: Authenticate | CallerHook;
  anonymous?: 'allow' | 'deny'; // 'deny' answers 401 to a caller without userId, default 'allow'
  authorizeThread?: (auth: AuthContext | undefined, threadId: string) => boolean | Promise<boolean>;
  limits?: RunLimits; // { swarmTimeout?, workflowMaxIterations?, workflowMaxConcurrency? }
  deps?: (ctx: BaseCtx) => unknown | Promise<unknown>; // the deps of agent runs, never from the body
  websocket?: boolean | { path?: `/${string}`; maxRuns?: number; maxBufferedBytes?: number };
  until?: AbortSignal | (() => AbortSignal | undefined);
  sseHeartbeatMs?: number; // SSE heartbeat interval in ms, default 5000, 0 turns it off
  acceptContext?: boolean | string[]; // context keys clients may send: none by default, a list, or true for any
  threadMessageRoles?: ('user' | 'assistant' | 'system')[]; // roles of POST /threads/:id/messages, default user and assistant
  workflowCheckpoints?: CheckpointStore; // workflow checkpoints and /workflows/:name/resume, none by default
  triggers?: TriggersHost; // experimental: the trigger manager, serves /triggers/:id/fire, /webhook and /inbox
}

With triggers the controller serves the trigger and inbox routes. The two trigger routes run neither auth, nor the anonymous policy, nor the JSON body check, read the body Tetsu keeps as rawBody, and answer with the trigger manager's status and body rather than the Tetsu envelope. The inbox routes answer refusals in the envelope, 422 VALIDATION_FAILED for a query or body that breaks their schemas.

Errors

Every error is answered in Tetsu's envelope { status, message, error }. A request that fails its schema gets 422 VALIDATION_FAILED with every issue, a context key the controller does not accept (acceptContext) and a thread message role it does not take (threadMessageRoles, user and assistant by default) included. Statuses, codes and Retry-After come from the taxonomy every adapter shares (describeHttpError() of @cogitator-ai/server-shared), in Tetsu's own envelope: a CogitatorError keeps its status and code, for example 429 LLM_RATE_LIMITED with Retry-After in whole seconds, and a swarm that ran out of time answers 504 RUN_TIMEOUT. Any other error answers 500 INTERNAL_SERVER_ERROR and goes to the application's reportError, never to the client. Streams and the WebSocket send it as Internal server error with code INTERNAL_ERROR, the stream protocol every Cogitator adapter shares.

StatuserrorWhen
400MALFORMED_JSONThe body is not valid JSON
401UNAUTHORIZEDauth returned undefined or threw (an expired token), or anonymous: 'deny' met a caller without userId
403THREAD_ACCESS_DENIEDThe thread belongs to another user
403THREAD_FORBIDDENauthorizeThread refused the thread
404AGENT_NOT_FOUND, …No agent, workflow or swarm with that name
404CHECKPOINT_NOT_FOUNDA workflow resume named a checkpoint that is missing, of another user or of another workflow
409BLACKBOARD_DISABLEDThe swarm has no blackboard
409RUN_NOT_PAUSEDA resume named a thread without a paused run
413BODY_TOO_LARGEThe body is over the application's limit
415UNSUPPORTED_MEDIA_TYPEThe body is not JSON (text/plain, a form)
501PACKAGE_NOT_INSTALLED@cogitator-ai/workflows or @cogitator-ai/swarms missing
503MEMORY_NOT_CONFIGUREDA thread endpoint on a runtime without memory
504RUN_TIMEOUTA swarm ran past its timeout

cogitatorErrors() returns the onError hook the controller uses. Mount one on the application to map CogitatorErrors and swarm timeouts from your own routes too.

Authentication

auth runs as a beforeParse hook, before the body is read. Return the caller, or undefined for 401. Any other error it throws or rejects with answers 401 too, and an HttpError answers with its own status. /health and /ready stay open.

cogitatorController({
  cogitator,
  agents: { chat },
  auth: (ctx) => {
    const token = ctx.req.headers.get('authorization')?.replace(/^Bearer /, '');
    const user = token ? sessions.find(token) : undefined;
    return user && { userId: user.id };
  },
});

The caller's userId reaches every run, so tools see it as context.userId, and scopes runs and thread endpoints to the caller.

To document the scheme, build the hook with callerHook(), wrap it in secured(), and reuse it on your own routes, where the caller is ctx.cogitatorAuth:

import { callerHook } from '@cogitator-ai/tetsu';
import { secured } from '@tetsujs/openapi';

const signedIn = secured(callerHook(authenticate), {
  name: 'bearerAuth',
  scheme: { type: 'http', scheme: 'bearer' },
  error: 'UNAUTHORIZED',
});

cogitatorController({ cogitator, agents, auth: signedIn });

Anonymous callers

By default a caller without a userId (no auth, or auth returned {}) uses the API as an anonymous user. With anonymous: 'deny' such a caller gets 401 UNAUTHORIZED on every route and on the WebSocket handshake, while /health, /ready and your docs() routes stay open. auth returning undefined answers 401 under either policy, and a secured() caller hook documents that 401. A path the application does not serve, and a method a path does not take, are answered by the application before any route runs, with Tetsu's own 404 and 405, so the controller cannot put auth in front of them.

cogitatorController({ cogitator, agents, auth, anonymous: 'deny' });

Users and Threads

Multiple users

A thread belongs to the user who created it, through a run or POST /threads/:id/messages. Runs and the thread endpoints let only that user in: another user's thread answers 403 THREAD_ACCESS_DENIED and stays untouched, and a stream on it ends with an error event carrying that code. Callers without a userId share the threads that have no owner. When several people share a server, have auth return a userId.

authorizeThread

On top of ownership, authorizeThread guards the thread endpoints and every run that names a threadId, before the model is called:

cogitatorController({
  cogitator,
  agents,
  auth,
  authorizeThread: (auth, threadId) => threadId.startsWith(`${auth?.userId}:`),
});

Use it for rules ownership does not express, such as thread ids your server hands out. It is checked on GET, DELETE and POST /threads/:id/messages, agent runs, streams and resumes, swarm runs and streams, and WebSocket runs and resumes, and false answers 403 THREAD_FORBIDDEN without starting a run.

Thread pages

GET /threads/:id answers the whole thread, or one page with ?limit=50: the newest 50 messages, oldest first within the page, and a nextCursor. Pass it back as ?limit=50&cursor=<nextCursor> for the 50 before them, until an answer has no nextCursor. Messages written in the same millisecond are neither skipped nor repeated. A limit outside 1 to 1000 or a cursor the server did not give answers 422 VALIDATION_FAILED, and the OpenAPI document describes both query parameters.

Run Deps

deps builds what an agent's tools get as context.deps, such as a database handle or the tenant. The model never sees them, and they never come from the request body.

cogitatorController({
  cogitator,
  agents,
  auth,
  deps: async (ctx) => ({ db: await pool.connect(), tenant: ctx.req.headers.get('x-tenant') }),
});

Agent runs, streams and resumes call it once per request, after auth and authorizeThread. A WebSocket connection calls it once, with its handshake, never for each run: all its agent runs and resumes get what it built, which lives as long as the connection, since a Tetsu context belongs to its request and not to the connection. An error it throws refuses the handshake, as 500 unless it is an HttpError, and no socket opens.

Run Limits

limits caps what a request may ask a run for: swarmTimeout (ms) for swarm runs, workflowMaxIterations and workflowMaxConcurrency for workflow runs, over HTTP, SSE and WebSocket alike. A request that asks for more is held to the cap, one that asks for nothing gets it, and each limit must be a positive integer or building the controller throws.

cogitatorController({
  cogitator,
  swarms: { research },
  limits: { swarmTimeout: 120_000, workflowMaxIterations: 50, workflowMaxConcurrency: 4 },
});

The request schemas show each limit as the default of the field it caps, with a description, and not as a maximum, since a larger value is held to the limit rather than refused.

Workflow Checkpoints

With workflowCheckpoints, a workflow run with options.checkpoint: true saves its checkpoints as the caller's and answers the last one as checkpointId. A run that fails answers its error envelope with that checkpointId ({ status, message, error, checkpointId }), and its stream sends workflow_failed with { checkpointId } right before the error event. Then POST /workflows/:name/resume (or /resume/stream) with { checkpointId, options? } runs the nodes the checkpoint left. A checkpoint that is missing, of another user or of another workflow answers 404 CHECKPOINT_NOT_FOUND before anything runs. Without it checkpoint: true fails validation with 422 VALIDATION_FAILED and every resume answers 404 CHECKPOINT_NOT_FOUND, see Workflow checkpoints.

Approvals

A tool with requiresApproval pauses the run before it executes. POST /agents/:name/run answers with status: 'paused' and pendingApprovals (toolCallId, toolName, arguments, description, sideEffects); the checkpoint stays on the server, stored by the runtime per thread. A paused stream sends approval-required with the same calls right before finish.

curl -X POST localhost:3000/cogitator/agents/support/resume \
  -H 'content-type: application/json' \
  -d '{ "threadId": "thread_…", "decisions": { "call_1": { "approved": true } } }'

POST /agents/:name/resume takes { threadId, decisions?, defaultDecision? }, where a decision is { approved, reason? } by tool call id. Approved calls run, declined ones answer the model with the reason, and calls left undecided pause the run again. /agents/:name/resume/stream streams the rest of the run, and the WebSocket accepts { type: 'resume', id, payload: { name, threadId, decisions? } }. Only the user the run belongs to may resume it (403 THREAD_ACCESS_DENIED; authorizeThread is checked too), and a thread with nothing paused answers 409 RUN_NOT_PAUSED.

Streaming

/stream routes use @tetsujs/sse: keep-alive comments every sseHeartbeatMs, backpressure, and the run is aborted when the client leaves (with resumableStreams an agent run goes on and the client reconnects with Last-Event-ID, see Resumable Streams). Events follow the shared protocol, an agent with reasoning: { summary: true } also streams reasoning-start, reasoning-delta and reasoning-end, closed before text, tool calls and finish, and POST /agents/:name/run returns the summary as reasoning. start names the run's thread (the one the request sent, or a new one) and finish repeats it with the run's outcome, and text after a tool call starts a new text part. Validation (415, 422), 401, 404 and the 403 THREAD_FORBIDDEN of authorizeThread are answered as JSON before the stream opens. Another user's thread is found by the run itself and ends the open stream with an error event, code: 'THREAD_ACCESS_DENIED'. Swarm streams also forward every event the swarm emits under its own name, and GET /swarms lists every agent, router and pipeline stages included. The OpenAPI document declares the 200 of each stream route.

WebSocket

cogitatorController({ cogitator, agents, auth, websocket: true });

The handshake runs auth and the anonymous policy and builds the connection's deps once, for every run on the socket, and workflow and swarm runs are held to limits. Send { type: 'run', id, payload: { type: 'agent', name, input, threadId? } } and receive event frames (token, reasoning, tool-call, tool-result, then complete or cancelled). { type: 'resume', id, payload: { name, threadId, decisions? } } continues a run paused for approvals. Runs with different ids go on side by side, up to websocket.maxRuns (8 by default, one more gets TOO_MANY_RUNS, and a second run with the id of one still going gets RUN_IN_PROGRESS). { type: 'stop', id } cancels that run at once, { type: 'stop' } every run of the socket. { type: 'ping' } is answered with pong, and errors arrive as { type: 'error', id, error, code } without closing the socket, for example THREAD_FORBIDDEN or RUN_TIMEOUT.

A slow reader gets every frame in order: frames wait on the server while the socket pushes back. Past websocket.maxBufferedBytes waiting (4 MiB by default) the socket is closed with 1008 and its runs are cancelled, so no frame is lost in silence.

Shutdown

Pass draining from @tetsujs/lifecycle as until, so a stopping server ends open streams and sockets and clients reconnect elsewhere:

let shutdown: ReturnType<typeof onShutdownSignals> | undefined;

const app = createApp({
  routes: cogitatorController({ cogitator, agents, until: () => shutdown?.draining }),
});
shutdown = onShutdownSignals(Bun.serve({ ...app }));

Example

examples/integrations/08-tetsu-server.ts is an app with its own users and its own MCP server: the agent reaches the app's tasks through MCP tools and acts for the signed-in user.

bun examples/integrations/08-tetsu-server.ts

On this page