Skip to content

Build a custom participant runtime

The gambi participant join CLI covers the common case: pick a model, point at a hub, stay online. When you need more control, build your own runtime on top of createParticipantSession(). Examples: embedding the participant in a long-running service, adding custom shutdown logic, or running several participants in one process.

This guide shows the minimum runtime that behaves like the CLI, then the common extensions.

You need:

  • a Gambi hub you can reach (gambi hub serve), on the same minor version as the gambi-sdk you install
  • an existing room code (gambi room create --name "Demo")
  • a local OpenAI-compatible provider endpoint (Ollama, LM Studio, vLLM, or anything else that serves /v1/models and /v1/chat/completions)
  • Bun: the gambi-sdk/participant entry runs only in Bun
  • gambi-sdk installed
Terminal window
bun add gambi-sdk

createParticipantSession() does it all in one call: it probes your endpoint for the APIs it speaks, registers the participant, opens the tunnel, and resolves once the participant is online.

import { createParticipantSession } from "gambi-sdk/participant";
const session = await createParticipantSession({
hubUrl: "http://localhost:3000",
roomCode: "ABC123",
participantId: "worker-1",
nickname: "worker-1",
endpoint: "http://localhost:11434",
model: "llama3",
});
console.log("joined as", session.participant.id);

If the join fails, the call rejects with a ParticipantError and nothing is left running. Its code says why: ROOM_NOT_FOUND, INVALID_PASSWORD, VERSION_MISMATCH (the hub runs another minor version), HUB_UNREACHABLE, TUNNEL_OPEN_FAILED, and a few more. Treat it as a configuration error and exit.

The session does not check that your provider serves model. To check before you join, probe it:

import { probeProvider } from "gambi-sdk/participant";
const probe = await probeProvider("http://localhost:11434");
if (!probe.models.includes("llama3")) {
throw new Error("Pull the model first.");
}

After the join, the runtime takes care of itself. When the tunnel drops (Wi-Fi blinks, the hub is unreachable for a moment, the hub froze), it waits 1 second, then 2, 4, and so on up to 30, and registers again with the same participant ID. Apps that route to it by ID keep their target.

onLifecycle receives each step, in order:

const session = await createParticipantSession({
// ...
onLifecycle: (event) => {
if (event.type === "reconnecting") {
console.log(`tunnel lost (${event.reason}); retrying in ${event.delayMillis} ms`);
}
},
});
Event When
connected the tunnel is open; attempt is 0 for the join, then the attempt that brought it back
reconnecting the tunnel dropped and the runtime tries again in delayMillis
left the runtime ended and will not try again; always the last event

session.ended resolves with the reason of the left event. It never rejects:

const { reason, error } = await session.ended;
Reason Meaning Suggested action
"stopped" your code called leave() or stop() exit cleanly
"refused" the hub refused the way back; error has its name and message usually the room is gone, because the hub restarted. Create the room again and start a new session
"replaced" another runtime joined the room with the same participant ID, and the hub kept that one do not restart with the same ID; two runtimes cannot share it
"removed" someone removed the participant through the hub the session has ended. Start a new one if you want to rejoin
"tunnelDropped" the tunnel dropped and you passed reconnect: false start a new session if you want to come back

A participant that stays away for more than 60 seconds is removed from the room. The runtime does not give up after that: its next registration brings it back as a new participant with the same ID.

The SDK does not install signal handlers. Wire session.leave() to SIGINT and SIGTERM yourself. leave() takes the participant out of the room and stops the runtime. It never rejects, and gives up on a hub that does not answer within 3 seconds (leaveTimeoutMs).

for (const signal of ["SIGINT", "SIGTERM"] as const) {
process.on(signal, () => {
void session.leave();
});
}

session.stop() stops the runtime without telling the hub. The room shows the participant offline and removes it after 60 seconds, unless a runtime with the same ID joins before that. Use it when you are about to restart and want to come back as the same participant.

The session also works with await using, which calls leave().

authHeaders apply only when the runtime calls your provider endpoint. They never leave the participant runtime. Use them for API keys or bearer tokens your provider needs.

const session = await createParticipantSession({
hubUrl: "http://localhost:3000",
roomCode: "ABC123",
participantId: "worker-1",
nickname: "worker-1",
endpoint: "http://localhost:11434",
model: "llama3",
authHeaders: {
Authorization: `Bearer ${process.env.PROVIDER_TOKEN}`,
},
});

The hub never sees PROVIDER_TOKEN.

The TUI shows specs, and room events include them. Pass them when you know them. The fields are cpu, gpu, ram (GB), and vram (GB), all optional:

await createParticipantSession({
// ...
specs: {
cpu: "Apple M2 Pro",
ram: 32,
gpu: "Apple M2 Pro integrated",
},
});

Without capabilities, the session probes your endpoint to find which OpenAI-compatible APIs it supports. Pass them to skip the probe:

await createParticipantSession({
// ...
capabilities: {
openResponses: "supported",
chatCompletions: "supported",
},
});
await createParticipantSession({
// ...
password: process.env.ROOM_PASSWORD,
});

The runtime never writes to your stdout. Pass onLog to receive its log lines:

await createParticipantSession({
// ...
onLog: (entry) => console.error(entry.level, entry.message),
});

Running more than one participant in one process

Section titled “Running more than one participant in one process”

Call createParticipantSession() once per participant. Each call returns an independent session with its own tunnel and participant identity. Wait for their ended promises in parallel.

const sessions = await Promise.all([
createParticipantSession({ /* worker-1 */ }),
createParticipantSession({ /* worker-2 */ }),
]);
await Promise.all(sessions.map((session) => session.ended));

Putting it all together:

import { createParticipantSession } from "gambi-sdk/participant";
const session = await createParticipantSession({
hubUrl: process.env.GAMBI_HUB ?? "http://localhost:3000",
roomCode: "ABC123",
participantId: "worker-1",
nickname: "worker-1",
endpoint: "http://localhost:11434",
model: "llama3",
...(process.env.PROVIDER_TOKEN
? { authHeaders: { Authorization: `Bearer ${process.env.PROVIDER_TOKEN}` } }
: {}),
onLifecycle: (event) => console.log("[gambi]", event.type),
});
for (const signal of ["SIGINT", "SIGTERM"] as const) {
process.on(signal, () => {
void session.leave();
});
}
const { reason, error } = await session.ended;
console.log("[gambi] session ended:", reason);
if (error) {
console.error(error.name, error.message);
}
process.exit(reason === "stopped" ? 0 : 1);