SDK
Use the Cohub TypeScript SDK for Spaces, Chats, Apps, Boards, rooms, realtime events and App runtime APIs.
This page is for writing code against Cohub instead of using the web app: creating Spaces and Chats, sending prompts, reading files, publishing Apps, subscribing to realtime events, and running inside a published App. It lists the real option names and client modules, says which authentication path applies where, and collects the errors that are easy to misread.
Package: @neta-art/cohub.
Install
npm install @neta-art/cohub
The package is ESM, ships TypeScript declarations, and works in browsers and Node.js 24 or newer. pixi.js, @pixi/3d and @napi-rs/canvas are optional peer dependencies, needed only by the Board rendering and export subpaths.
Create a client
import { createCohubClient } from "@neta-art/cohub";
const client = createCohubClient({
getAccessToken: async () => localStorage.getItem("token"),
});
createCohubClient(options?) returns a CohubClient with HTTP and realtime wired together.
| Option | Type | Purpose |
|---|---|---|
env |
"prod" | "dev" |
Environment; defaults to prod, or dev when ENV=dev is set |
baseUrl |
string |
API base URL; overrides COHUB_BASE_URL |
webBaseUrl |
string |
Web base URL used in links; overrides COHUB_WEB_URL |
getAccessToken |
(options?: { forceRefresh?: boolean; rejectedToken?: string | null }) => Promise<string | null> | string | null |
Supplies the bearer token for HTTP and realtime |
getAuthSessionVersion |
() => string | number | null |
Lets the transport tell a stale 401 from a fresh session |
onUnauthorized |
(context) => void | Promise<void> |
Called on a 401 that survives the refresh retry |
setStoredAuthToken / clearStoredAuthToken |
(token: string) => void / () => void |
Storage hooks used by the sign-in helpers |
fetch |
typeof fetch |
Custom fetch implementation |
websocket |
WebsocketClientOptions |
Realtime URL, auto-reconnect, timings, WebSocketImpl |
voice |
VoiceInputCreateOptions |
Voice input URL, timings, WebSocketImpl |
app |
AppRuntimeModeConfig |
App runtime mode (bridge or broker); work is the deprecated alias |
requestSource |
RequestSource | (() => RequestSource | null) |
X-Cohub-Source-* headers attached to requests |
localWorkspace |
LocalWorkspaceResolver |
Serves a Space this machine runs directly instead of through the API |
createHttpClient(options?) returns a CohubHttpClient with the same HTTP modules but no realtime transport, and new CohubClient / new CohubHttpClient are available if you prefer classes.
Default endpoints
| Env | API | Realtime | Voice input |
|---|---|---|---|
| production | https://api.cohub.live |
wss://gateway.cohub.live/ws |
wss://gateway.cohub.live/asr/ws |
| development | https://api-dev.cohub.live |
wss://gateway-dev.cohub.live/ws |
wss://gateway-dev.cohub.live/asr/ws |
Select development in code or from the environment:
const client = createCohubClient({ env: "dev", getAccessToken: async () => token });
ENV=dev node app.mjs
In Node.js you can override each endpoint without code:
| Variable | Endpoint |
|---|---|
COHUB_BASE_URL |
API base URL |
COHUB_WS_URL |
Realtime gateway (normalized to /ws) |
COHUB_WEB_URL |
Web base URL used in links |
COHUB_VOICE_WS_URL |
Voice input gateway (normalized to /asr/ws) |
Explicit options beat environment variables, and environment variables beat the selected environment's defaults. Voice input falls back to COHUB_WS_URL when COHUB_VOICE_WS_URL is unset, so one gateway URL configures both. API and gateway addresses are independent: changing baseUrl does not move realtime connections.
Spaces and Chats
const { space } = await client.spaces.create({ name: "Demo" });
const demo = client.space(space.id);
const { session } = await demo.sessions.create({ title: "Planning" });
const chat = demo.session(session.id);
await demo.prompt({
sessionId: session.id,
content: [{ type: "text", text: "Help me plan the next steps" }],
});
client.spaces lists, creates, reads and resolves Spaces (ensureHome() creates your Home Space on first use). client.space(id) returns a SpaceClient scoped to one Space.
Product mapping:
- Space →
client.spaces/client.space(id) - Chat →
space.sessionsandspace.session(id) - Save →
space.checkpoints - App →
client.apps
Client modules
Every module below is a property on the CohubClient object built in packages/sdk/src/client.ts.
| Module | Purpose |
|---|---|
spaces |
List, create, read, ensureHome() |
space(id) |
One Space: files, sessions, checkpoints, members, boards, displays and more |
channels |
Connected messaging channels |
user |
The signed-in user: profile, sessions, apps, cron jobs |
users |
Other users by UUID or username |
billing |
Credits, quotas, balance activity, catalog, subscriptions |
generations |
Generation tasks and their results |
models |
LLM and multimodal model catalog and pricing |
prompts |
Prompt templates |
skills |
Skills available to slash commands |
publicAssets |
Uploads for public assets, App sources, attachments and Board previews |
sessionAccess |
Per-Chat access policy |
search |
Search Spaces, Chats and label items |
references |
Forks, mentions, tool calls and file access |
inbox |
Notifications kept for later |
notifications |
Preferences, push targets, locale |
byok |
Your own model subscriptions and shares |
tasks |
Task runs |
boards |
Boards by id, plus Board clients |
cronJobs |
Scheduled jobs |
desktop |
Commands for the Cohub desktop (ui is the deprecated alias) |
invite |
Public invite links |
referrals |
Referral link and claims |
voice |
Voice input sessions |
apps |
Apps: publish, update, versions, domains, Actions, grants (works is the deprecated alias) |
appCommerce |
App products, entitlements, credits, orders |
rooms |
App rooms: create, join, events, members, RTC |
navigation |
Ask the host to open an App or route |
auth |
Sign-in helpers and authorize() for App runtime grants |
app |
App runtime surface: realtime, callable methods, window state, appearance, composer, commerce |
Inside a Space client:
| Module | Purpose |
|---|---|
files |
Read, write, upload, move, diff, copy |
publicFiles |
Public CDN files |
sessions / turns |
Chats and turn history |
checkpoints |
Saves: list, create, tree, diff |
members / presence / access / appAccess |
People, presence and policies |
labels |
Space labels and their items |
boards |
Boards bound to this Space |
displays |
Screens shared with the Space |
sandbox / env / usage / activity / overview |
Runtime, configuration and metrics |
webhooks / mods / invitations |
Inbound hooks, mods, invites |
wallet / commerce |
Balance and commerce |
A session client exposes messages, turns, realtime and generation, plus get(), stats(), files(), rename(), archive(), unarchive(), steerTurn(), cancelTurn(), abort() and turn(id).fork().
Session realtime
session.subscribe() attaches handlers to the Chat's room on the realtime socket:
const stop = session.subscribe({
turnUpdated(event) {
console.log("turn", event.payload);
},
turnFinalized(event) {
console.log("done", event.payload);
},
error(event) {
console.error("turn failed", event.payload);
},
});
stop();
Handlers are patch, turnUpdated, turnFinalized, error, persisted and event (every event for the Chat). session.on("turn.finalized", handler) subscribes to one event name. patchState still exists but is deprecated in favour of subscribeGeneration.
For streamed assistant output, session.subscribeGeneration(handlers, options) resolves patches into state, commit, finalized, turnUpdated, lifecycle, error and out_of_sync events. Pass { recover: true } to seed the reducer from the server's active stream snapshot, which is how you recover after a reconnect:
const stop = session.subscribeGeneration(
{
commit(event) {
process.stdout.write(event.commit.message.content.map((block) => ("text" in block ? block.text : "")).join(""));
},
},
{ recover: true },
);
The websocket reconnects on its own with backoff. Subscription state, however, is not a cache: after the connection drops, re-read the Chat (session.messages.list(), session.turns.list()) or use recover: true rather than assuming the stream continued.
Account-wide events and reconnect
client.onUserEvent() delivers events for the signed-in account without joining a Space: session.created and session.updated for every Chat you created or take part in (with participantUserUuids), and space.list.changed when a Space you belong to changes. Keep a cached list current from those events instead of polling, and re-fetch only after the connection was lost:
let wasOpen = client.connectionState === "open";
client.onConnection(({ state }) => {
if (state === "open" && !wasOpen) void refetchLists();
wasOpen = state === "open";
});
client.onUserEvent((event) => {
if (event.type === "session.updated") applySession(event.payload.session);
});
A session.created for a forked Chat also carries fork (RealtimeSessionFork: childSessionId, parentSessionId, depth, anchorSequence), so a list that already shows the parent can nest the new Chat immediately. It is omitted when the parent Chat has its own access policy, and it never includes titles; take the parent's title from your own list.
client.spaces.list() items include personalActivityAt, the viewer's own latest activity in the Space, which the list sorts by first.
client.connectionState is idle, connecting, reconnecting, open or closed. client.disconnect() closes the socket; client.dispose() also releases the App runtime and window listeners.
Subpath exports
Import only what you need:
| Subpath | Contents |
|---|---|
@neta-art/cohub |
Everything below plus the client |
@neta-art/cohub/http |
CohubHttpClient, createHttpClient, HttpError, HttpTransport |
@neta-art/cohub/websocket |
WebsocketClient, createWebsocketClient |
@neta-art/cohub/voice-input |
VoiceApi, VoiceInputClient, createVoiceInputClient |
@neta-art/cohub/debugger |
Console and network capture helpers |
@neta-art/cohub/space-picker |
Framework-free Space picker filtering and ordering |
@neta-art/cohub/app-ref |
parseAppRef, formatAppRef, isAppId |
@neta-art/cohub/host-bridge |
Host bridge for desktop hosts |
@neta-art/cohub/media |
Media probing, variants and previews |
@neta-art/cohub/board |
Board model, item types and JSON schema |
@neta-art/cohub/board/editor |
createBoardEditor |
@neta-art/cohub/board/replica |
createBoardReplica and storage adapters |
@neta-art/cohub/board/player |
createBoardPlayer, playback clock |
@neta-art/cohub/board/presence |
Presence and awareness helpers |
@neta-art/cohub/board/render |
PixiJS renderers, shaders and effects |
@neta-art/cohub/board/stage |
mountBoardStage |
@neta-art/cohub/board/export |
renderBoardExport, export planning |
@neta-art/cohub/board/export/node |
createNodeBoardRenderer for PNG/JPEG/WebP export in Node |
@neta-art/cohub/board/testing |
Script harness for Board tests |
Auth model
Outside App runtime, you supply the token: return it from getAccessToken. If you omit getAccessToken and COHUB_EXECUTION_TOKEN is set, the client uses that token; inside a published App it uses the runtime's short-lived credential. A 401 triggers one refresh retry through getAccessToken({ forceRefresh: true, rejectedToken }) before onUnauthorized runs.
Inside a published App, the Cohub shell provides short-lived runtime auth, so no API key ships in App code. client.context(), client.auth.authorize(), realtime rooms, the callable surface, composer context, commerce and App Actions are runtime-only. client.auth.authorize() asks the viewer for the scopes you actually need; client.auth.request, requestSpace and requestCreateSpace remain but are deprecated.
Which runtime is in use comes from the environment: COHUB_EXECUTION_TOKEN means a sandbox, a browser context is browser, and anything else is local. client.context() returns that runtime plus the execution details (Space, Chat, Turn, App, scopes) when they exist.
The complete capability model — permissions, the API-to-scope map, capability recipes and pitfalls — lives in App development.
Boundaries and common errors
| Symptom or error | Cause and fix |
|---|---|
realtime transport is not configured for this client |
You used CohubHttpClient (or createHttpClient) and called session.subscribe(). Use createCohubClient when you need events. |
| Every request is 401 | getAccessToken returned nothing or an expired token. Return a fresh token, or set COHUB_EXECUTION_TOKEN for an ephemeral run. Sessions are per API base URL, so a token from another server will not work. |
| Realtime connects but events never arrive | subscribe() keeps only the Chat's room. Check the Space and Chat IDs, and confirm the viewer can read both. |
| Events missing after a network drop | The socket reconnects, but state is not replayed forever. Re-fetch on onConnection when the state returns to open, or use subscribeGeneration({ recover: true }). |
App context is unavailable |
App runtime APIs were called outside a published App or App Action. Use user auth, or run inside the App. |
HttpError with a code but no message |
The API returned a structured error. Read error.status, error.body and error.code; billing and entitlement codes have helpers such as isBillingAccessBlockedError. |
| Board import fails with a missing canvas error | The Board render/export subpaths need the optional @napi-rs/canvas (and pixi.js) packages. Install them, or import only board/model. |
ENV=dev ignored in the browser |
process.env does not exist there. Pass env: "dev" or override baseUrl / websocket.url explicitly. |
Next steps
- App development — runtime permissions, scopes and App Actions
- CLI — the same surface from a terminal
- Apps — what a published App is and how it is hosted
- Spaces — Space roles and configuration
- Core concepts — Space, Chat, Save, Turn and App