Implementation of Distributed Actor Model for AI swarms using TypeScript/Node.js, Redis/Kafka, OpenTelemetry.
- One of the first open-source projects to combine Enterprise Messaging (Kafka/Redis), Distributed Actor-Model Isolation, AI Multi-Agent Orchestration, and Kanban Visualization into a single JavaScript-ecosystem runtime, for agents and humans.
Distributed horizontally-scalable Actor-Model Multi-Agent System Runtime, using Kanban style visualization for workflows.
Run multiple AI agents teams with independently deployed Node.js processes, real-time visibility and multi-agent orchestration via Redis/Kafka pub/sub, A2A, and MCP.
For running the examples see EXAMPLES.md. For technical documentation, check the files in docs/.
(For integrating KaibanJS system base, follow documents in docs/KAIBANJS_INTEGRATION.md).
Examples dedicated repository: kaiban-distributed-examples
Website: andreibesleaga.github.io/kaiban-distributed
Read next: users, Quick start (full demo); developers, Use as a library; operators, docs/deployment; security, SECURITY_FEATURES. The full index by reader is docs/README.md.
-
While most frameworks treat agents as scripts, Kaiban Distributed treats them as Stateful Actors. By using async Node.js, each agent operates in its own space, communicating via a pluggable Messaging Abstraction Layer (Kafka or BullMQ/Redis), horizontally scaling AI workforce. "Stateful" is meant in the actor-model sense: each agent has its own process, identity and mailbox, and per-process state (token tallies, circuit breaker). The task itself runs in a fresh
Team, so no conversation state survives between tasks. -
The system allows creation of Teams of Agents for various Tasks, Systems Integrations, and Data handling/analytics, with scalable AI workflows, from local usage to customizable Enterprise Grade Systems.
-
Integrates with existing KaibanJS system and agents, external agentic systems, or any service that can publish via A2A / MCP / Redis / Kafka — connecting them into actor-model team flows or peer-to-peer coordination.
-
Any Agentic AI Patterns (Loops & Harnesses), Team Archetypes, Workflows, and Human-in-The-Loop (BudgetCheckings) interruptions could be implemented programmatically at any point of the workflow/tasks, given the Actor-Model Isolation, Distributed Node Agents, Custom Orchestrators/Coreography, Messaging Layer - in JS/TS, or via other A2A/MCP comms and agents, or by any other programs and connectors into the messaging layer (visually connected kanban boards and any other display methods connecting directly to the published workflows messages on Redis/Kafka, such as CLI I/O, Enterprise Programs, etc.)
Published on npm as kaiban-distributed (canonical) and mirrored on GitHub Packages as @andreibesleaga/kaiban-distributed; the container image is ghcr.io/andreibesleaga/kaiban-distributed.
# 1. Clone and install git clone https://github.com/andreibesleaga/kaiban-distributed cd kaiban-distributed && npm ci # 2. Configure cp .env.example .env # Edit .env — add OPENROUTER_API_KEY or OPENAI_API_KEY + AGENT_IDS # 3. Start the full blog-team demo (Docker Compose, workers, gateway, orchestrator, monitor) ./scripts/blog-team.sh start # or the Global Research Distributed Team ./scripts/global-research.sh start # use flags for chaos (20% searcher crash rate) and number of parallel instances # ./scripts/global-research.sh start --chaos --searchers 6 # → Script prints board URLs when the gateway is ready. Open one in a separate terminal/tab. # 4. Open the board (choose one, in a separate terminal) cd board && npm ci && npm run dev # React board → http://localhost:5173 # — OR — # Open examples/blog-team/viewer/board.html in your browser (zero setup) # 5. Stop everything cleanly when done ./scripts/blog-team.sh stop # ./scripts/global-research.sh stop
To wire your own agent into a distributed worker node (the ./src/... paths below apply to a clone of this repository; see Use as a library for the package imports):
import { AgentActor } from './src/application/actor/AgentActor'; import { createKaibanTaskHandler } from './src/infrastructure/kaibanjs/kaiban-agent-bridge'; import { createDriver, createAgentStatePublisher } from './src/shared'; // BullMQ or Kafka from MESSAGING_DRIVER; REDIS_URL credentials and REDIS_TLS_* are applied. const driver = createDriver('my-agent'); // Applies MAX_TOKEN_BUDGET / MAX_TASK_TOKEN_BUDGET from the environment // (defaults 200000 / 50000; the literal 'unlimited' removes a cap). const statePublisher = createAgentStatePublisher(process.env.REDIS_URL ?? 'redis://localhost:6379', { agentId: 'my-agent', name: 'Ada', role: 'Analyst', }); const handler = statePublisher.wrapHandler( createKaibanTaskHandler({ name: 'Ada', role: 'Analyst', goal: 'Analyse datasets and produce structured summaries', background: 'Expert in data analysis and statistics', llmConfig: { provider: 'openai', model: 'gpt-4o-mini', apiKey: process.env.OPENAI_API_KEY }, }, driver) ); const actor = new AgentActor('my-agent', driver, 'kaiban-agents-my-agent', handler); await actor.start(); statePublisher.publishIdle(); // board shows agent as IDLE within 15s
npm install kaiban-distributed
import { AgentActor, BullMQDriver, createKaibanTaskHandler } from 'kaiban-distributed'; import { createDriver, createAgentStatePublisher, dispatchToAgent, CompletionRouter } from 'kaiban-distributed/shared';
The package has two entry points: kaiban-distributed (actor, drivers, bridges, security, governance, economics) and kaiban-distributed/shared (driver factory, state publisher factory, dispatch, completion router, orchestration helpers). createAgentStatePublisher and DistributedStateMiddleware are exported from the root too. Prefer createDriver() to a hand-built BullMQDriver: it applies the user, password, database and rediss:// of REDIS_URL and the REDIS_TLS_* files, which a connection built from host and port alone drops.
(Blog team of: researcher, writer, editor - nodes distributed locally over docker services with Redis/Kafka messaging between them and their processes tasks status and results)

flowchart TB
subgraph Clients
Board["Board UI<br/>(React/Vite or static HTML)"]
Ext["External orchestrator / agent<br/>(A2A JSON-RPC, MCP)"]
CLI["npm run stop-all<br/>(CLI)"]
end
subgraph Gateway["Edge Gateway :3000"]
GW["GatewayApp<br/>/health · /ready · /startup · /.well-known/agent-card.json<br/>/a2a/rpc · /mcp · /control/stop-all"]
A2A["A2A stack<br/>(buildA2AStack)"]
SG["SocketGateway<br/>(Socket.io)"]
CR["CompletionRouter"]
end
subgraph Redis["Redis 7 Pub/Sub (always)"]
SE["kaiban-state-events"]
HD["kaiban-hitl-decisions"]
CC["kaiban-control"]
end
Broker[("Durable broker: BullMQ (Redis) or Kafka<br/>kaiban-agents-* mailboxes · kaiban-events-completed · kaiban-events-failed")]
subgraph Workers["Agent worker nodes (1..N)"]
A1["AgentActor + KaibanJS bridge<br/>AgentStatePublisher · ControlSubscriber"]
end
Orch["Orchestrator (WorkflowOrchestrator)<br/>ControlSubscriber"]
Ext -- "message/send" --> GW
GW --> A2A
A2A -- "publish task" --> Broker
Broker -- "consume" --> A1
A1 -- "completed / failed" --> Broker
Broker -- "completed / failed" --> CR
Broker -- "completed / failed" --> Orch
A1 -- "state delta" --> SE
Orch -- "state delta" --> SE
SE --> SG
SG -- "state:update" --> Board
Board -- "hitl:decision" --> SG
SG --> HD
HD --> Orch
Board -- "control:stop-all" --> SG
Board -- "POST /control/stop-all" --> GW
CLI --> CC
SG --> CC
GW --> CC
CC --> A1
CC --> Orch
More views (ASCII layout, request topology, conceptual overview) are in docs/architecture/DIAGRAMS.md. The kaiban-control channel exists only when CONTROL_PLANE_ENABLED=true.
stateDiagram-v2
[*] --> TODO : message/send (A2A)
note right of TODO
API response: A2A task state 'submitted'
end note
TODO --> DOING : Worker Claims Task
DOING --> DONE : Inference Success
DOING --> TODO : Retry (max 3×, linear backoff)
DOING --> BLOCKED : Max Retries Exceeded (→ kaiban-events-failed)
DOING --> AWAITING_VALIDATION : HITL Required
AWAITING_VALIDATION --> DOING : Human approved, or asked for a revision (REVISE)
TODO --> STOPPED : Emergency STOP ALL (sent before the stop)
DOING --> STOPPED : Emergency STOP ALL (→ kaiban-events-failed)
note right of STOPPED
Workflow level: RUNNING to FINISHED, STOPPED or ERRORED.
A rejected draft ends the workflow STOPPED.
end note
DONE --> [*]
BLOCKED --> [*]
STOPPED --> [*]
| Component | Location | Purpose |
|---|---|---|
AgentActor |
src/application/actor/ |
Actor: subscribes to queue, processes tasks with retry (3×) + DLQ, optional firewall + circuit breaker; outbound message data capped at 64 KB |
KaibanAgentBridge |
src/infrastructure/kaibanjs/ |
Wraps KaibanJS agent in a per-task Team; calls team.start(); returns token-tracked KaibanHandlerResult; optional JIT token provider |
KaibanTeamBridge (deprecated) |
src/infrastructure/kaibanjs/ |
Wraps KaibanJS Team with distributed state sync, in one process. For single tasks use createKaibanTaskHandler; a model call in flight is not cancelled by STOP ALL on this path |
AgentStatePublisher |
src/adapters/state/ |
Publishes IDLE/THINKING/EXECUTING/ERROR agent status to Redis Pub/Sub; 15s heartbeat; enforces the per-agent and per-task token caps (build it with createAgentStatePublisher) |
BullMQDriver |
src/infrastructure/messaging/ |
Redis-backed job queue (default); optional TLS; no colon queue names |
KafkaDriver |
src/infrastructure/messaging/ |
Kafka-backed messaging; optional SSL/mTLS; unique consumer group per worker role |
DistributedStateMiddleware |
src/adapters/state/ |
Subscribes to the Zustand store and publishes each change as a signed board delta |
GatewayApp |
src/adapters/gateway/ |
Express HTTP: /health, /ready, /startup, /.well-known/agent-card.json, /a2a/rpc, /a2a/agents/:agentId/status, /mcp (when enabled), /control/stop-all (control plane only) |
SocketGateway |
src/adapters/gateway/ |
Socket.io server + Redis pub/sub subscriber; broadcasts state:update to board |
A2A stack (buildA2AStack: KaibanAgentExecutor + RedisTaskStore + AgentStatusTracker) |
src/infrastructure/federation/ |
Official @a2a-js/sdk v0.3 server; message/send validates + publishes to the agent mailbox (ADR-015) |
MCPFederationClient |
src/infrastructure/federation/ |
Connects to any MCP tool server via stdio transport |
HeuristicFirewall |
src/infrastructure/security/ |
Regex-based prompt injection detection (ASI01); opt-in via SEMANTIC_FIREWALL_ENABLED |
EnvTokenProvider |
src/infrastructure/security/ |
JIT token abstraction (ASI03); reads API keys from env vars; opt-in via JIT_TOKENS_ENABLED |
SlidingWindowBreaker |
src/infrastructure/security/ |
Sliding-window circuit breaker (ASI08); opt-in via CIRCUIT_BREAKER_ENABLED |
OrchestratorStatePublisher |
src/shared/orchestrator-state-publisher.ts |
Owns workflow lifecycle (RUNNING→FINISHED/STOPPED/AWAITING); each example extends it (examples/*/state-publisher.ts) |
CompletionRouter |
src/shared/completion-router.ts |
Single BullMQ/Kafka subscriber dispatching completion events by taskId |
- Node.js ≥ 22
- Docker + Docker Compose (for Redis, Kafka, and multi-node demo)
- LLM API key — OpenAI (
OPENAI_API_KEY), OpenRouter (OPENROUTER_API_KEY), other compatible APIs
git clone https://github.com/andreibesleaga/kaiban-distributed
cd kaiban-distributed
npm cicp .env.example .env
Edit .env — choose your LLM provider:
# Standard OpenAI OPENAI_API_KEY=sk-... LLM_MODEL=gpt-4o-mini # OpenRouter (https://openrouter.ai/keys) OPENROUTER_API_KEY=sk-or-v1-... LLM_MODEL=meta-llama/llama-3.1-8b-instruct:free # free tier # Required — which agents this node serves AGENT_IDS=researcher,writer,editor
docker compose up -d redis
npm run build AGENT_IDS=researcher,writer,editor PORT=3000 node dist/src/main/index.js
curl http://localhost:3000/health # → {"data":{"status":"ok","timestamp":"..."},"meta":{},"errors":[]} curl http://localhost:3000/.well-known/agent-card.json # → {"protocolVersion":"0.3.0","name":"kaiban-worker",...,"capabilities":{"streaming":true,...},"skills":[...]} (A2A v0.3) # name = SERVICE_NAME (kaiban-worker in .env.example); one skill per id in AGENT_IDS
This starts the gateway only. To run tasks, start a worker with ROLE=worker AGENT_IDS=researcher,writer,editor node dist/src/main/index.js, or use the full demo above.
The board/ subdirectory is a standalone React + Vite + TypeScript dashboard that visualises distributed agent activity in real time via Socket.io.
| Feature | Detail |
|---|---|
| Tech stack | React 19 · Vite · TypeScript · Tailwind CSS · Zustand · Socket.io client |
| Gateway URL | http://localhost:3000 (override with ?gateway=<url> query param or VITE_GATEWAY_URL) |
| State source | SocketGateway backend subscribes to Redis kaiban-state-events and fans out state:update events to all connected boards |
| Agent Grid | Live status badges per agent — IDLE / THINKING / EXECUTING (pulse) / ERROR |
| Kanban Board | 5-column task view: TODO · DOING · REVIEW · DONE · BLOCKED |
| HITL controls | Approve / Revise / Reject buttons when a task is AWAITING_VALIDATION; emits hitl:decision back through the socket |
| Economics panel | Aggregate token count, cost, and duration; reverse-chronological event log (capped at 200 entries) |
Start the board (dev):
cd board cp .env.example .env # optional: set VITE_GATEWAY_URL npm ci npm run dev # → http://localhost:5173
Production build outputs static files to board/dist/ — deploy anywhere (nginx, CDN, etc.). Set Content-Security-Policy: frame-ancestors 'none' and X-Content-Type-Options: nosniff as response headers on the host: browsers ignore them in <meta> tags (see board/README.md, "Production hosting").
The stop dialog and the board after a stop are shown in docs/images/board-stop-dialog.png and docs/images/board-stopped.png.
Mirrors the kaibanjs-node-demo pattern — each agent runs as an independent process:
// my-agent-node.ts import 'dotenv/config'; import { AgentActor } from './src/application/actor/AgentActor'; import { createKaibanTaskHandler } from './src/infrastructure/kaibanjs/kaiban-agent-bridge'; import { createDriver, createAgentStatePublisher } from './src/shared'; const REDIS_URL = process.env['REDIS_URL'] ?? 'redis://localhost:6379'; // BullMQ or Kafka from MESSAGING_DRIVER; REDIS_URL credentials and REDIS_TLS_* are applied. const driver = createDriver('researcher'); // Applies MAX_TOKEN_BUDGET / MAX_TASK_TOKEN_BUDGET (defaults 200000 / 50000). const statePublisher = createAgentStatePublisher(REDIS_URL, { agentId: 'researcher', name: 'Ava', role: 'News Researcher', }); const handler = statePublisher.wrapHandler( createKaibanTaskHandler({ name: 'Ava', role: 'News Researcher', goal: 'Find and summarize the latest news on a given topic', background: 'Expert data analyst with deep research experience', llmConfig: { provider: 'openai', model: process.env['LLM_MODEL'] ?? 'gpt-4o-mini', apiKey: process.env['OPENAI_API_KEY'], }, }, driver) ); const actor = new AgentActor('researcher', driver, 'kaiban-agents-researcher', handler); await actor.start(); statePublisher.publishIdle(); // board shows Ava as IDLE within 15s console.log('[Researcher] Ava started'); process.on('SIGTERM', async () => { await actor.stop(); await driver.disconnect(); await statePublisher.disconnect(); });
# Terminal 1 — researcher OPENAI_API_KEY=sk-... node dist/examples/blog-team/researcher-node.js # Terminal 2 — writer OPENAI_API_KEY=sk-... node dist/examples/blog-team/writer-node.js # Terminal 3 — send a task via A2A v0.3 (message/send; target agent in metadata.agentId) curl -X POST http://localhost:3000/a2a/rpc \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"message/send","params":{"message":{"kind":"message","role":"user","messageId":"m1","parts":[{"kind":"text","text":"Research the latest AI agent frameworks in 2025"}],"metadata":{"agentId":"researcher","expectedOutput":"A concise summary"}}}}'
kaiban-board is a React component that visualises KaibanJS team execution as a live Kanban board.
Worker nodes (each):
AgentStatePublisher.publishIdle() → Redis PUBLISH kaiban-state-events { agents: [IDLE] }
AgentStatePublisher.wrapHandler() → EXECUTING → THINKING → IDLE/ERROR → Redis PUBLISH
15-second heartbeat → re-publishes current agent status
(heartbeat NEVER sets teamWorkflowStatus — only the orchestrator does)
Orchestrator:
workflowStarted() → { teamWorkflowStatus: 'RUNNING', agents: all IDLE }
awaitingHITL(...) → { tasks: [AWAITING_VALIDATION] }
workflowFinished(...) → { teamWorkflowStatus: 'FINISHED', all tasks: DONE }
workflowStopped(...) → { teamWorkflowStatus: 'STOPPED', tasks: BLOCKED }
SocketGateway:
subscribes Redis kaiban-state-events → emits Socket.io 'state:update' to board
teamWorkflowStatus values (set by the orchestrator only). The banner texts below are those of the static viewer examples/blog-team/viewer/board.html; the React board shows "Workflow finished", "Workflow stopped" (amber) and "Workflow errored" (red) instead:
teamWorkflowStatus |
Board banner | Badge |
|---|---|---|
RUNNING |
none | 🔵 blue |
FINISHED |
✅ WORKFLOW COMPLETE (green glow) | 🟢 green |
STOPPED |
⏹ WORKFLOW ENDED (grey) | ⚫ grey |
ERRORED |
red banner (React board: "Workflow errored") | 🔴 red |
The ⏸ HUMAN DECISION REQUIRED (orange pulse) banner is shown when any task has status
AWAITING_VALIDATION— this is triggered by task state, not byteamWorkflowStatus.
Task card states:
TODO— 📋 pending (initial state)DOING— 🔵 blue left border + pulse dotDONE— 🟢 greenAWAITING_VALIDATION— 🟠 orange pulsing glow +⏸ HUMAN DECISIONbadge + HITL bannerBLOCKED— 🔴 red glow +⛔ ERRORbadge + red error banner with messageSTOPPED— shown in the Blocked column with aStoppedbadge after an emergency STOP ALL
The React board groups tasks into the columns To Do · In Progress · Review · Done · Blocked.
Open examples/blog-team/viewer/board.html directly in a browser.
Auto-connects to http://localhost:3000. All three agents (Ava, Kai, Morgan) appear as IDLE within 15 seconds.
Event stream shows typed, colour-coded entries:
WORKFLOWbadge — workflow status transitionsAGENTbadge — IDLE → EXECUTING → IDLE per agentTASKbadge — task status with result preview
import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); const agentMap = new Map(); const taskMap = new Map(); socket.on('state:update', (delta) => { // IMPORTANT: merge by ID — each worker publishes only its own slice if (delta.agents) { for (const a of delta.agents) agentMap.set(a.agentId, { ...agentMap.get(a.agentId), ...a }); } if (delta.tasks) { for (const t of delta.tasks) taskMap.set(t.taskId, { ...taskMap.get(t.taskId), ...t }); } });
The board/ directory is a standalone React + Vite + TypeScript app that connects
to the same Socket.io gateway and adds interactive Human-in-the-Loop controls:
cd board cp .env.example .env # optional: set VITE_GATEWAY_URL npm ci npm run dev # → http://localhost:5173
Or pass the gateway URL at runtime without rebuilding:
http://localhost:5173?gateway=http://my-gateway.example.com:3000
Gateway URL resolution (priority order):
?gateway=<url>query param (runtime, no rebuild needed)VITE_GATEWAY_URLbuild-time env var (.envfile)http://localhost:3000fallback
A board token is never sent to a gateway chosen by a link. When VITE_BOARD_TOKEN is built in, the React board honours ?gateway= only for the origin of VITE_GATEWAY_URL; any other value is ignored and the configured gateway is used. The static viewers ignore ?gateway= when the token comes from window.BOARD_TOKEN; a token given in the address fragment (#token=) is sent to the gateway named in that same address.
Layout (top → bottom):
- Header — logo, topic, gateway URL chip, workflow status pill, connection badge
- WorkflowBanner — conditional banner: HITL Approve/Revise/Reject buttons (when any task is
AWAITING_VALIDATION), FINISHED, STOPPED, or ERRORED states - AgentGrid — responsive 2–4 column grid with live status badges (IDLE / THINKING / EXECUTING + pulse / ERROR)
- KanbanBoard — 5-column board: TODO · DOING · REVIEW · DONE · BLOCKED
- EconomicsPanel + EventLog — tokens, cost, duration; reverse-chronological event stream (capped at 200)
HITL decision flow:
Board clicks [Approve]
→ socket.emit('hitl:decision', { taskId, decision: 'PUBLISH' })
→ SocketGateway: publishes to Redis kaiban-hitl-decisions
→ Orchestrator's waitForHITLDecision() races Redis vs terminal input
→ First to respond wins → workflow continues
Both the board and the terminal prompt remain functional simultaneously — first response wins.
Production build:
cd board && npm run build # → board/dist/ (static files, serve anywhere)
Deprecated: for single tasks use createKaibanTaskHandler. A model call in flight is not cancelled by STOP ALL on this path.
import { Agent, Task } from 'kaibanjs'; import { DistributedStateMiddleware } from './src/adapters/state/distributedMiddleware'; import { KaibanTeamBridge } from './src/infrastructure/kaibanjs/kaiban-team-bridge'; const ava = new Agent({ name: 'Ava', role: 'Researcher', goal: '...', background: '...' }); const kai = new Agent({ name: 'Kai', role: 'Writer', goal: '...', background: '...' }); // The bridge's second argument is the state middleware (publishes to kaiban-state-events) const middleware = new DistributedStateMiddleware('redis://localhost:6379'); const bridge = new KaibanTeamBridge({ name: 'Blog Team', agents: [ava, kai], tasks: [ new Task({ description: 'Research {topic}', expectedOutput: 'Summary', agent: ava }), new Task({ description: 'Write blog', expectedOutput: 'Blog post', agent: kai }), ], }, middleware); const result = await bridge.start({ topic: 'AI agents 2025' }); // State propagates: Redis Pub/Sub → SocketGateway → Socket.io → board
The Edge Gateway exposes a wire-conformant A2A v0.3 JSON-RPC surface (served by the official @a2a-js/sdk v0.3.x, ADR-015) for interoperability with other AI systems. It serves a v0.3 AgentCard at the spec path (/.well-known/agent-card.json) and implements the real v0.3 methods message/send, message/stream (SSE), tasks/get, tasks/cancel. A real @a2a-js/sdk client interoperates with it (proven by tests/e2e/a2a-protocol.test.ts).
History (superseded): v1.x exposed a custom, non-standard method set (
tasks.create/tasks.get/agent.status) and a flat{ capabilities: string[], endpoints }card. Those were removed in the v2.0 A2A migration (the customA2AConnectoris gone). SeeMIGRATION.md+docs/decisions/ADR-015.
curl http://localhost:3000/.well-known/agent-card.json
{
"protocolVersion": "0.3.0",
"name": "kaiban-gateway",
"description": "Kaiban distributed A2A gateway — bridges A2A tasks onto the actor messaging layer.",
"url": "http://localhost:3000/a2a/rpc",
"version": "2.1.4",
"preferredTransport": "JSONRPC",
"additionalInterfaces": [
{ "transport": "JSONRPC", "url": "http://localhost:3000/a2a/rpc" }
],
"capabilities": { "streaming": true, "pushNotifications": false, "stateTransitionHistory": false },
"defaultInputModes": ["text/plain", "application/json"],
"defaultOutputModes": ["text/plain", "application/json"],
"skills": [
{ "id": "researcher", "name": "Delegate to researcher", "tags": ["task", "agent", "researcher"] }
]
}
capabilitiesis an object in v0.3 (it was astring[]in the old card); an agent's discrete abilities live inskills[](one skill per agent id). The example above is the card of a gateway started withSERVICE_NAME=kaiban-gateway(the value the compose files set) andAGENT_IDS=researcher:nameisSERVICE_NAMEandskills[]has one entry per id in the gateway'sAGENT_IDS.
| Method | Purpose | Notes |
|---|---|---|
message/send |
Dispatch a task; await terminal result | Target agent in message.metadata.agentId; optional instruction/expectedOutput/context/inputs in metadata (or plain text parts). Input caps (A2A_INPUT_CAPS, 64 KB); oversized/wrong-typed → -32602. |
message/stream |
Same, streamed over SSE | submitted → working → completed/failed/canceled |
tasks/get |
Fetch a persisted task by id | Real data from RedisTaskStore |
tasks/cancel |
Cancel an in-flight task | Stops the gateway wait only; emits terminal canceled. The worker is not told and keeps running to its own timeout |
Live agent status is GET /a2a/agents/:agentId/status (not a JSON-RPC method).
# External A2A v0.3 caller: dispatch a task via message/send curl -X POST http://localhost:3000/a2a/rpc \ -H 'Content-Type: application/json' \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "message/send", "params": { "message": { "kind": "message", "role": "user", "messageId": "m1", "parts": [{ "kind": "text", "text": "Research quantum computing breakthroughs in 2025" }], "metadata": { "agentId": "researcher", "expectedOutput": "A 300-word technical summary", "inputs": { "topic": "quantum computing" } } } } }'
In-process dispatch (not A2A). When you orchestrate your own agent nodes in the same process, dispatch over the actor mailbox directly instead of the HTTP A2A surface:
import { createDriver, dispatchToAgent, CompletionRouter } from 'kaiban-distributed/shared'; const driver = createDriver('researcher'); const taskId = await dispatchToAgent(driver, 'researcher', { instruction: 'Research quantum computing breakthroughs in 2025', expectedOutput: 'A 300-word technical summary', inputs: { topic: 'quantum computing' }, }); // await the result by taskId via CompletionRouter.wait(...)
Attach any Model Context Protocol tool server to your agents:
import { MCPFederationClient } from './src/infrastructure/federation/mcp-client'; const mcp = new MCPFederationClient('npx', ['-y', '@brave/brave-search-mcp-server', '--transport', 'stdio']); await mcp.connect(); const tools = await mcp.listTools(); const result = await mcp.callTool('brave_web_search', { query: 'AI agents 2025' }); await mcp.disconnect();
MCP servers for Redis and Kafka enable AI agents to intercept and query live data streams:
| Server | Purpose |
|---|---|
mcp-redis |
Query kaiban-state-events pub/sub, streams (XREAD), vector search |
| Confluent MCP | Flink SQL queries over live Kafka topics (Confluent Cloud) |
tuannvm/kafka-mcp-server |
Consume Kafka messages at specific offsets (self-hosted) |
// claude_desktop_config.json { "redis": { "command": "uvx", "args": ["--from", "redis-mcp-server@latest", "redis-mcp-server", "--url", "redis://localhost:6379/0"] } }
Best for: development, small-to-medium scale, reliable delivery, job history.
MESSAGING_DRIVER=bullmq REDIS_URL=redis://localhost:6379
Important: BullMQ v5 rejects queue names containing colons. All internal channels use dashes:
kaiban-agents-researcher,kaiban-events-completed,kaiban-events-failed,kaiban-state-events
Best for: large scale, event streaming, message replay, multi-datacenter.
MESSAGING_DRIVER=kafka KAFKA_BROKERS=localhost:9092 KAFKA_CLIENT_ID=kaiban-worker KAFKA_GROUP_ID=kaiban-group
Kafka consumer group isolation — unique group suffix per component:
| Component | Consumer Group |
|---|---|
| researcher worker | kaiban-group-researcher |
| writer worker | kaiban-group-writer |
| editor worker | kaiban-group-editor |
| orchestrator (completed events) | kaiban-group-orchestrator-completed |
| orchestrator (failed/DLQ events) | kaiban-group-orchestrator-failed |
| gateway (completed events) | kaiban-group-gateway-completed |
| gateway (failed events) | kaiban-group-gateway-failed |
| searcher worker (global-research) | kaiban-group-searcher |
Long tasks and heartbeats — while a task handler runs, the Kafka worker sends a consumer-group heartbeat every 3 s (eachMessage heartbeat, cleared when the handler ends; heartbeat errors are logged, never thrown). A task running longer than the ~30 s session timeout therefore no longer gets its worker evicted and re-run elsewhere. The timeouts themselves are unchanged (KafkaJS defaults: session 30 s, rebalance 60 s). Known limit: if a real group rebalance happens while a task runs, the offset commit can still fail and the task may be delivered again to another worker; task-level de-duplication is planned (roadmap §7.2, item 5). BullMQ has its own lock renewal and is not affected.
A consumer group reads a topic from the beginning on a partition where it has no committed offset (first start, a new KAFKA_GROUP_ID, or offsets expired after the broker's offsets.retention.minutes), so a task mailbox's backlog is run and a result published before the orchestrator joined is not lost. Scaled replicas of one agent share work only when the task topic has at least that many partitions; the compose files set KAFKA_NUM_PARTITIONS=4. See MIGRATION.
Task queues use Kafka topics. State broadcast (
kaiban-state-events) always uses Redis Pub/Sub —SocketGatewayreads directly from Redis regardless ofMESSAGING_DRIVER.
// src/shared/driver-factory.ts (shared helpers; also re-exported from src/shared) import { createDriver, getDriverType } from './src/shared'; const driver = createDriver('researcher'); // BullMQ or Kafka based on MESSAGING_DRIVER env
The same shared barrel (kaiban-distributed/shared in the published package) exports startAgentNode and createAgentStatePublisher, the factory that builds an AgentStatePublisher with MAX_TOKEN_BUDGET / MAX_TASK_TOKEN_BUDGET applied; the root kaiban-distributed entry exports createAgentStatePublisher too.
Set MESSAGING_DRIVER=kafka (or bullmq) — the IMessagingDriver interface is the abstraction. Worker code is identical for both drivers.
| Method | Path | Description |
|---|---|---|
GET |
/health |
{ data: { status: 'ok', timestamp } } |
GET |
/ready |
Readiness probe: pings Redis; 200 when ready, 503 otherwise |
GET |
/startup |
Startup probe: 503 until the HTTP server is listening, then 200 |
GET |
/.well-known/agent-card.json |
A2A agent capabilities |
POST |
/a2a/rpc |
A2A v0.3 JSON-RPC: message/send, message/stream, tasks/get, tasks/cancel |
GET |
/a2a/agents/:agentId/status |
Real last-known agent status (AgentStatusTracker) |
POST / GET / DELETE |
/mcp |
MCP server (Streamable HTTP), mounted only when MCP_SERVER_ENABLED=true; path from MCP_SERVER_PATH (see docs/federation/MCP.md) |
POST |
/control/stop-all |
Emergency STOP ALL (2.1.0), mounted only when CONTROL_PLANE_ENABLED=true. Needs Authorization: Bearer <board token> (refused while BOARD_JWT_SECRET is unset); body { "reason"?: string }; 202 { commandId, issuedAt, saved }, 401, 400, 429 (5 per 10 s per token subject; refused attempts 30 per 10 s per address) |
The gateway's own routes (/health, /ready, /startup, /a2a/agents/:agentId/status and the 404 reply) answer in a { data, meta, errors } envelope. /a2a/rpc answers in JSON-RPC 2.0 and the agent card is the bare A2A AgentCard, both served by @a2a-js/sdk.
| Event | Direction | Payload |
|---|---|---|
state:update |
server → client | StateDelta (top-level PII keys stripped) |
state:request |
client → server | none; asks for a full snapshot replay (5 per 10 s per connection) |
hitl:decision |
client → server | { taskId: string, decision: 'PUBLISH' | 'REVISE' | 'REJECT' } |
control:stop-all |
client → server | { reason?: string }, acked with { ok, commandId, issuedAt, saved } or { ok: false, error } (2.1.0, only with CONTROL_PLANE_ENABLED=true; needs the handshake board token) |
| Channel | Driver | Purpose |
|---|---|---|
kaiban-agents-{agentId} |
BullMQ / Kafka | Task inbox per agent |
kaiban-events-completed |
BullMQ / Kafka | Successful task results |
kaiban-events-failed |
BullMQ / Kafka | DLQ after 3 retry failures, or after one non-retryable failure (budget breach, timeout, worker stopping); the record keeps the task inputs (up to 64 KB) so it can be replayed |
kaiban-state-events |
Redis Pub/Sub | Agent/workflow state → board |
kaiban-hitl-decisions |
Redis Pub/Sub | Board HITL decisions → orchestrator |
kaiban-control |
Redis Pub/Sub | Emergency STOP ALL → every worker and orchestrator (2.1.0, ADR-025); signed with CHANNEL_SIGNING_SECRET when set (with NODE_ENV=production a node refuses to attach the control channel without it, unless ALLOW_INSECURE_PRODUCTION=true); the latest stop is also kept in the Redis key kaiban-control:stopped-at |
| Variable | Default | Required | Description |
|---|---|---|---|
ROLE |
gateway |
No | node dist/src/main/index.js runs as gateway (HTTP, Socket.io, A2A; consumes no tasks) or worker (runs an agent for every id in AGENT_IDS; no HTTP). Worker processes must set ROLE=worker (ADR-013) |
AGENT_IDS |
— | Yes | Comma-separated agent IDs this node serves |
REDIS_URL |
redis://localhost:6379 |
No | Redis connection URL. User, password, database and rediss:// in it apply to every Redis client, the task queues too (since 2.1.2); REDIS_TLS_* add the client certificate. Example: rediss://:password@host:6379/0. REDIS_PASSWORD is read by the root docker-compose.yml only, not by this code |
MESSAGING_DRIVER |
bullmq |
No | bullmq or kafka (amqp is accepted by the parser and then refused at gateway boot: it is an unimplemented seam) |
KAFKA_BROKERS |
localhost:9092 |
Kafka only | Comma-separated broker addresses |
KAFKA_CLIENT_ID |
kaiban-worker |
No | Kafka client identifier |
KAFKA_GROUP_ID |
kaiban-group |
No | Kafka consumer group base ID |
PORT |
3000 |
No | HTTP + WebSocket port |
SERVICE_NAME |
kaiban-worker |
No | Name in telemetry and agent card |
OPENAI_API_KEY |
— | For agents | Standard OpenAI API key |
OPENROUTER_API_KEY |
— | For agents | OpenRouter key (auto-configures base URL) |
OPENAI_BASE_URL |
— | Optional | Custom OpenAI-compatible endpoint |
LLM_MODEL |
gpt-4o-mini |
No | Model (for OpenRouter: meta-llama/llama-3.1-8b-instruct:free) |
OTEL_EXPORTER_OTLP_ENDPOINT |
— | No | OpenTelemetry OTLP endpoint (else console) |
MAX_TOKEN_BUDGET |
200000 |
No | Token cap per agent (one AgentStatePublisher, in its worker process; resets on restart) |
MAX_TASK_TOKEN_BUDGET |
50000 |
No | Token cap per task, all attempts seen by the same agent process (attempts whose KaibanJS workflow ends BLOCKED included; an ERRORED workflow makes team.start() reject and is not counted) |
MAX_WORKFLOW_COST_USD |
0.50 |
No | Cost cap per workflow (orchestrator) |
MAX_WORKFLOW_TOKENS |
unlimited |
No | Token cap per workflow (orchestrator) |
AGENT_TIMEOUT_MS |
300000 |
No | Time limit for one task attempt, on the gateway's wait and (since 2.0.1) on every worker node; a timed-out task is not retried unless RETRY_ON_TIMEOUT is on |
RETRY_ON_TIMEOUT |
false |
No | true or 1: retry a timed-out task (3 attempts, linear back-off) instead of dead-lettering it at once; a hung provider call can then be paid for up to three times. The gateway's wait grows to 3 × AGENT_TIMEOUT_MS plus back-off plus 5 s, so set it identically on the gateway and every worker. A stop is never retried |
CONTROL_PLANE_ENABLED |
false |
No | true or 1 on every gateway, worker and orchestrator process: turns on the emergency STOP ALL (below). Unset: no subscription, route or socket event is added |
BOARD_JWT_SECRET |
— | Production | Signs board tokens (viewers, STOP ALL). How to mint one: SECURITY_FEATURES §1.1 |
A2A_JWT_SECRET |
— | Production | When set, /a2a/rpc needs a bearer token signed with it |
CHANNEL_SIGNING_SECRET |
— | Production | HMAC key for the Redis channels (state, human decisions, STOP ALL) |
SOCKET_CORS_ORIGINS |
— | Production | Comma-separated origins allowed to open the Socket.io connection; unset = any origin (development only); with NODE_ENV=production the gateway refuses to start without it |
TRUST_PROXY |
false |
No | true behind one reverse proxy: rate limits then use the client address from X-Forwarded-For instead of the proxy's |
A2A_PUBLIC_URL |
http://localhost:<PORT> |
No | Public base URL advertised in the agent card |
VALID_HITL_DECISIONS |
PUBLISH,REVISE,REJECT |
No | Decisions the gateway accepts from a board |
HITL_DECISION_TTL_SECONDS |
300 |
No | Seconds the gateway keeps a human decision in its Redis list; set the same value on the gateway and the orchestrator (1 to 604800). See Delivery guarantees and limits |
LOG_LEVEL |
info |
No | pino log level (LOG_PRETTY=true for readable output in development) |
MCP_SERVER_ENABLED |
false |
No | true mounts the MCP server; see docs/federation/MCP.md for MCP_* |
ALLOW_INSECURE_PRODUCTION |
— | No | With NODE_ENV=production, boot refuses unless BOARD_JWT_SECRET, A2A_JWT_SECRET and CHANNEL_SIGNING_SECRET are set, 32+ bytes and distinct; true lets a missing one through with a warning on every start (a weak or repeated secret is never allowed) |
Only the literal unlimited removes a spend cap; 0, a negative number or text gives the default and logs one warning.
The full list is .env.example; it also covers the variables not repeated here (the other MCP_*, ECONOMICS_* and GOVERNANCE_* groups).
Docker Compose passes only some of these variables to the containers. Which ones each compose file forwards, and how to add the rest, is in docs/deployment/DOCKER.md.
With CONTROL_PLANE_ENABLED=true on every process, one command kills every running model call on the OpenAI-compatible provider (the one the built-in worker handler uses; other providers stop at their next agent-loop step), every task and every workflow at once:
- From the board: the STOP ALL button in the header (shown only when the gateway has the control plane on), then confirm. The board needs
VITE_BOARD_TOKEN(local development only: a token built into a production bundle is public, and it can issue STOP ALL), and the gatewayBOARD_JWT_SECRET. - From the static HTML viewers (2.1.1): the same STOP ALL button, confirmation and banner in
examples/blog-team/viewer/board.htmlandexamples/global-research/viewer/board.html. When the gateway setsBOARD_JWT_SECRET, open the viewer with the token in the address fragment, for exampleboard.html#token=<board token>(orboard.html?gateway=http://localhost:3000#token=<board token>), or setwindow.BOARD_TOKEN. The fragment is removed from the address bar after it is read, and the token is never logged or stored. - Over HTTP:
curl -X POST http://localhost:3000/control/stop-all -H "Authorization: Bearer <board token>" -H "content-type: application/json" -d '{"reason":"runaway loop"}' - From a shell:
npm run buildonce, thennpm run stop-all -- --reason "runaway loop"(in the image:node dist/src/main/stop-all.js). It needs onlyREDIS_URL(andCHANNEL_SIGNING_SECRETwhen the deployment signs its channels; without it the command prints a warning, because signing nodes ignore an unsigned stop). A signed stop is accepted whatever the clock difference between the host that issues it and the node.
A board token is a JWT signed with BOARD_JWT_SECRET. Mint one with the command in SECURITY_FEATURES §1.1. It lasts 1 hour by default, so keep a fresh one ready before you need it; npm run stop-all needs no token.
The stop is a moment, not a mode. Every task sent before it ends: a running one has its model request cancelled mid-call and settles at once; a queued one is refused when it is delivered. Every workflow running then ends STOPPED (the examples exit with code 2). Anything started after the stop runs normally, so there is nothing to release. Stopped tasks show as STOPPED on the board, sit in the dead-letter channel as emergency_stop with their inputs, and can be replayed with replayDlq. Each node acknowledges on the state channel, and the board shows the last stop with its acknowledgement count. The moment is kept in Redis, so a node that missed the message or restarts still refuses the old tasks. Keep the hosts' clocks synchronised (NTP): a task sent within the clock skew of the stop can fall on either side. Pause, resume and stopping one task, agent or workflow are planned for a later version (roadmap §6.10).
There was no operator stop command before 2.1.0 (see Emergency STOP ALL above). Since 2.0.1, without the control plane:
- Stop a worker with SIGTERM or Ctrl-C (SIGINT). It takes no new task, aborts the call in flight, does not retry it, and drains within 25 s; a worker running several agents drains them all together and exits once, after flushing telemetry (at most 3 s more). The interrupted task goes to the dead-letter channel as
actor_stopped, with its inputs, so it can be replayed. - A task that times out (
AGENT_TIMEOUT_MS) is aborted and dead-lettered astask_timeout; it is not retried by default, so it is paid for once. WithRETRY_ON_TIMEOUT=trueit is retried up to 3 attempts in all (the last timeout is still dead-lettered astask_timeout). - The spend caps above are the safety net: a run or task that reaches its cap stops dispatching and is not retried.
tasks/cancel(A2A) stops the gateway waiting; the worker is not told (see the A2A table).
| Variable | Default | Description |
|---|---|---|
VITE_GATEWAY_URL |
http://localhost:3000 |
Gateway WebSocket URL (build-time; overridable via ?gateway= query param at runtime) |
VITE_BOARD_TOKEN |
— | Board token sent in the socket handshake; needed when the gateway sets BOARD_JWT_SECRET, and for the STOP ALL button. Local development only: the value is compiled into the bundle, so do not build a production bundle with a real token |
| Variable | Default | Description |
|---|---|---|
REDIS_TLS_CA / REDIS_TLS_CERT / REDIS_TLS_KEY |
— | Paths to Redis mTLS certificates |
KAFKA_SSL_CA / KAFKA_SSL_CERT / KAFKA_SSL_KEY |
— | Paths to Kafka mTLS certificates |
TLS_REJECT_UNAUTHORIZED |
true |
Only false or 0 turns verification off (self-signed certs in staging); any other value keeps it on |
SEMANTIC_FIREWALL_ENABLED |
false |
Enable heuristic prompt injection firewall |
SEMANTIC_FIREWALL_LLM_URL |
— | Reserved, not used yet: the firewall is always the built-in regex HeuristicFirewall |
JIT_TOKENS_ENABLED |
false |
Enable JIT token provider for LLM API keys |
CIRCUIT_BREAKER_ENABLED |
false |
Enable sliding-window circuit breaker |
CIRCUIT_BREAKER_THRESHOLD |
10 |
Failures before breaker trips |
CIRCUIT_BREAKER_WINDOW_MS |
60000 |
Sliding window duration (ms) |
Security audits have been performed against the OWASP Top 10 for Agentic AI (2026) and OWASP Top 10 for LLM Applications (2025).
For a complete reference of every security feature, configuration option, and deployment checklist see SECURITY_FEATURES.md.
| Feature | Component | OWASP | Activation |
|---|---|---|---|
| Board Viewer JWT | board-auth.ts + SocketGateway |
CRIT-01 | BOARD_JWT_SECRET |
| A2A Bearer Token Auth | a2a-auth.ts + GatewayApp |
CRIT-02 | A2A_JWT_SECRET |
| Redis Channel Signing | channel-signing.ts |
HIGH-01 | CHANNEL_SIGNING_SECRET |
| CORS Allowlist | SocketGateway |
HIGH-03 | SOCKET_CORS_ORIGINS (required in production) |
| Token Expiry Enforcement | SocketGateway |
LOW-01 | automatic when BOARD_JWT_SECRET set |
| Semantic Firewall | HeuristicFirewall |
ASI01 | SEMANTIC_FIREWALL_ENABLED=true |
| mTLS | KafkaDriver / BullMQDriver |
ASI07 | REDIS_TLS_* / KAFKA_SSL_* |
| JIT Token Provider | EnvTokenProvider |
ASI03 | JIT_TOKENS_ENABLED=true |
| Circuit Breaker | SlidingWindowBreaker |
ASI08 | CIRCUIT_BREAKER_ENABLED=true |
| W3C Traceparent Validation | BullMQDriver |
MED-06 | always-on |
| HTTP Hardening | GatewayApp (Helmet, rate limit, CSP, HSTS) |
MED-04/05 | always-on |
| WebSocket Hardening | SocketGateway (buffer limit, ping, HITL validation) |
— | always-on |
| A2A Task-Input Validation | validateTaskInput (a2a-input-validation.ts) |
HIGH-04 | always-on |
Authentication and signing features are env-var gated: when the relevant secret is not set, the system behaves exactly as before (backwards-compatible). When set, full enforcement is active.
kaiban-distributed is a library/runtime, not a certified product. The controls below can support a deploying organization's GDPR, SOC 2, or ISO/IEC 27001 program — they do not, by themselves, constitute compliance or certification, which remain the operator's responsibility.
| Capability | Implementation | Supports |
|---|---|---|
| PII minimisation in logs | Agent IDs SHA-256 hashed (8-char prefix) via sanitizeId() |
GDPR |
| PII stripping in state deltas | sanitizeDelta() strips the top-level delta keys email, name, phone, ip, password, token, secret, ssn, dob; nested keys are not inspected (applied on both the middleware and worker-publisher paths) |
GDPR |
| Data minimisation | result capped at 20,000 UTF-8 bytes (≈20 KB) in state events; outbound data capped at 64 KB in AgentActor |
GDPR |
| Least-privilege container | Dockerfile non-root USER kaiban |
SOC 2 (CC6) |
| Secret hygiene | Secrets via env vars only; .env gitignored; .env.example placeholders |
SOC 2 |
| Encryption in transit | mTLS for Redis/Kafka; HTTPS to LLM APIs; scripts/generate-dev-certs.sh for staging |
ISO/IEC 27001 (A.8.24) |
| Observability / audit trail | OpenTelemetry tracing; W3C traceparent across BullMQ/Kafka hops; run-logger decision trail |
SOC 2 / ISO 27001 |
| Supply chain | No high/critical advisory outside the dated exceptions in .trivyignore (CI-enforced); CycloneDX SBOM; SLSA provenance + Sigstore-signed releases; overrides pin patched @langchain/*, axios, protobufjs, etc. — see SECURITY.md |
— |
npm run build # tsc → dist/src/ and dist/examples/ npm run dev # node dist/src/main/index.js (build first) npm run test # 1804 unit tests (no external deps) npm run test:coverage # 100% coverage — all metrics npm run test:e2e # BullMQ E2E (Docker Redis auto-started) npm run test:e2e:kafka # Kafka E2E (Docker Kafka + Zookeeper required) # cd board && npm run test:visual # Playwright visual baselines (board + example viewers) npm run lint # ESLint + complexity ≤10 — 0 errors target npm run typecheck # tsc --noEmit — strict mode npm run format # prettier --write npm run lint:arch # madge --circular src/ — no circular imports
| Suite | Command | Count | Infrastructure |
|---|---|---|---|
| Unit | npm test |
1804 tests, 152 files | None (all mocked) |
| BullMQ E2E | npm run test:e2e |
73 tests, 12 files | Docker Redis (auto-managed by globalSetup) |
| Security E2E | npm run test:e2e:security |
41 tests, 1 file | Docker Redis (auto-managed by securitySetup) |
| Kafka E2E | npm run test:e2e:kafka |
4 tests, 3 files | Docker Kafka + Zookeeper |
| Chaos E2E | npm run test:e2e:chaos |
3 tests, 3 files (Redis paused mid-flight, zero tasks dropped; a storm of stops over 60 tasks; a worker killed in mid-task, its task redelivered and completed once for the caller) | Docker Redis |
| Board | cd board && npm test |
207 tests, 18 files: React component + Zustand store + a11y tests | happy-dom |
| Visual (Playwright) | cd board && npm run test:visual |
board screenshot baseline + structural checks of the two example viewers | board dev server + gateway + chromium |
Counts as of 18 Nov 2026 (release 2.1.4); the recorded run is in docs/VERIFICATION.md, the single home for these numbers. CI runs the unit suite with coverage and the board tests on every push and pull request to main and develop; the BullMQ, security, Kafka and chaos suites run nightly (see CONTRIBUTING.md). No workflow runs the Playwright visual tests.
| Metric | Result |
|---|---|
| Statements | 100% |
| Branches | 100% |
| Functions | 100% |
| Lines | 100% |
kaiban-distributed/
├── src/
│ ├── domain/
│ │ ├── entities/ # DistributedTask, DistributedAgentState (with type guards)
│ │ ├── errors/ # DomainError, TaskNotFoundError, MessagingError, ...
│ │ ├── result.ts # Result<T,E> — ok(), err(), isOk(), isErr()
│ │ └── security/ # Domain interfaces for security components
│ │ ├── semantic-firewall.ts # ISemanticFirewall — evaluates payloads for injection
│ │ ├── token-provider.ts # ITokenProvider — JIT token abstraction
│ │ ├── circuit-breaker.ts # ICircuitBreaker — success/failure tracking
│ │ └── admission-gate.ts # IAdmissionGate — pre-execution allow/block port (ADR-021)
│ ├── application/
│ │ └── actor/
│ │ ├── AgentActor.ts # Core: retry×3 + linear backoff, DLQ, firewall, circuit breaker
│ │ └── retry-policy.ts # Retry count, back-off and the gateway's wait under RETRY_ON_TIMEOUT
│ ├── adapters/
│ │ ├── gateway/
│ │ │ ├── GatewayApp.ts # Express: /health, /ready, /startup, agent-card, /a2a/rpc, /mcp, /control/stop-all, 404
│ │ │ ├── emergency-stop-ingress.ts # STOP ALL over HTTP and Socket.io (token checks, rate limits)
│ │ │ ├── rate-limiter.ts / request-timeouts.ts # per-address limits; socket and request time limits
│ │ │ └── SocketGateway.ts # Socket.io + Redis pub/sub → board
│ │ └── state/
│ │ ├── distributedMiddleware.ts # Zustand store subscription → board deltas
│ │ └── agent-state-publisher.ts # Direct Redis pub/sub; 15s heartbeat; lifecycle
│ ├── infrastructure/
│ │ ├── messaging/
│ │ │ ├── interfaces.ts # IMessagingDriver (publish, subscribe, unsubscribe, disconnect)
│ │ │ ├── channels.ts # Canonical channel names (STATE, COMPLETED, DLQ, HITL)
│ │ │ ├── bullmq-driver.ts # BullMQ Worker + Queue; optional TLS; no colons in queue names
│ │ │ ├── kafka-driver.ts # KafkaJS producer + consumer; optional SSL/mTLS
│ │ │ └── amqp-driver.ts # MESSAGING_DRIVER=amqp seam — unimplemented, throws on use (ADR-016)
│ │ ├── control/
│ │ │ └── control-channel.ts # kaiban-control: ControlSubscriber, signed STOP ALL command (ADR-025)
│ │ ├── federation/
│ │ │ ├── a2a-executor.ts # KaibanAgentExecutor: A2A v0.3 message/send → agent mailbox (ADR-015)
│ │ │ ├── a2a-agent-card.ts # buildAgentCard: v0.3 AgentCard (capabilities object + skills[])
│ │ │ ├── a2a-task-store.ts # RedisTaskStore: persisted tasks for tasks/get, tasks/cancel
│ │ │ ├── a2a-gateway-factory.ts # buildA2AStack: executor + task store + status tracker
│ │ │ ├── a2a-input-validation.ts # validateTaskInput + A2A_INPUT_CAPS (64 KB)
│ │ │ ├── agent-status-tracker.ts # last-known agent status for /a2a/agents/:agentId/status
│ │ │ ├── mcp-server.ts / mcp-http.ts # MCP server over Streamable HTTP (off by default, ADR-017)
│ │ │ └── mcp-client.ts # MCPFederationClient via stdio transport
│ │ ├── kaibanjs/
│ │ │ ├── kaiban-agent-bridge.ts # createKaibanTaskHandler; JIT tokens; error detection
│ │ │ ├── kaiban-team-bridge.ts # KaibanTeamBridge with DistributedStateMiddleware
│ │ │ └── owned-llm.ts # the bridge's own LangChain LLM instance: the abort seam for in-flight calls (ADR-014)
│ │ ├── security/ # Security infrastructure implementations
│ │ │ ├── heuristic-firewall.ts # Regex prompt injection detection (10 patterns)
│ │ │ ├── env-token-provider.ts # Env-var backed JIT token provider
│ │ │ ├── sliding-window-breaker.ts # Configurable sliding-window circuit breaker
│ │ │ ├── board-auth.ts / a2a-auth.ts # board and A2A JWTs (BOARD_JWT_SECRET / A2A_JWT_SECRET)
│ │ │ └── channel-signing.ts # HMAC signing of Redis pub/sub messages (CHANNEL_SIGNING_SECRET)
│ │ └── telemetry/
│ │ ├── telemetry.ts # initTelemetry(); recordAnomalyEvent(); OTLP or console
│ │ ├── telemetry-shutdown.ts # once-only, time-bounded flush on exit (internal)
│ │ └── TraceContext.ts # injectTraceContext / extractTraceContext (W3C)
│ ├── economics/ # Fleet cost control: RateCostLimiter, CostReservation, model routing (off by default, ADR-019)
│ ├── governance/ # Action Gate, PolicyEngine + policies.yml, AgentRegistry, hash-chained AuditLog (off by default, ADR-020)
│ ├── memory/ # SecureMemoryStore: tenant keyspaces, provenance tags, retrieval RBAC (ADR-020)
│ ├── resilience/ # dlq-replay, graceful-shutdown, readiness/startup probes (ADR-018)
│ ├── shared/ # Published as kaiban-distributed/shared: driver factory, CompletionRouter, HITL,
│ │ # WorkflowOrchestrator, dispatchToAgent, spend caps, startAgentNode (see src/shared/README.md)
│ ├── index.ts # Library barrel (the published `kaiban-distributed` entry)
│ └── main/
│ ├── index.ts # Entry point: picks the gateway or worker role from ROLE (ADR-013)
│ ├── stop-all.ts # `npm run stop-all`: publishes the emergency stop to Redis
│ ├── gateway.ts # Gateway role: HTTP + Socket.io + A2A (+ MCP when enabled); runs no task actors
│ ├── worker.ts # Worker role: one LLM-backed AgentActor per id in AGENT_IDS
│ ├── runtime.ts # Messaging driver + telemetry setup shared by both roles
│ └── config.ts # loadConfig(); TLS config; security feature flags
├── tests/
│ ├── unit/ # 1804 unit tests — mirrors src/ structure, 100% coverage
│ └── e2e/
│ ├── distributed-execution.test.ts # BullMQ: execution, fault tolerance, state sync
│ ├── fan-out-fan-in.test.ts # Parallel fan-out/fan-in workflow (7 scenarios)
│ ├── horizontal-scaling-bullmq.test.ts # Competing consumers, at-least-once delivery
│ ├── horizontal-scaling-kafka.test.ts # Kafka consumer groups scaling
│ ├── a2a-protocol.test.ts # HTTP gateway + A2A
│ ├── kafka-driver.test.ts # Kafka pub/sub round-trip
│ ├── … # blog-team / global-research flows, board HITL, event isolation,
│ │ # completion routing, security (security-*.test.ts), live LLM run
│ ├── chaos/broker-resilience.test.ts # Redis paused mid-flight, no task dropped (npm run test:e2e:chaos)
│ ├── chaos/worker-kill-redelivery.test.ts # a worker killed in mid-task, the task redelivered
│ └── setup/
│ ├── globalSetup.ts # Docker Redis auto-start; resilient to existing Redis
│ ├── kafkaSetup.ts # Docker Kafka + Zookeeper + Redis auto-start
│ ├── securitySetup.ts # Redis for the security suite
│ └── globalSetup.live.ts # global-research stack for the live (real LLM) suite
├── examples/
│ ├── global-research/ # Multi-agent distributed researchers pipeline example
│ └── blog-team/ # Three-agent editorial pipeline
│ ├── team-config.ts # Agent configs (Ava, Kai, Morgan) + LLM factory
│ ├── researcher-node.ts # Ava worker entry point
│ ├── writer-node.ts # Kai worker entry point
│ ├── editor-node.ts # Morgan worker entry point
│ ├── orchestrator.ts # Event-driven pipeline + HITL terminal
│ ├── phases.ts / state-publisher.ts # Pipeline phases; BlogStatePublisher (extends OrchestratorStatePublisher)
│ ├── run-logger.ts / agent-card.ts # Per-run JSON record (runs/); AgentCard skill parsing
│ ├── infra/ # kubernetes/ · helm/ · railway/ deployment files
│ ├── docker-compose.yml # BullMQ: redis + gateway + 3 workers
│ ├── docker-compose.kafka.yml # Kafka: zookeeper + kafka + redis + gateway + 3 workers
│ └── viewer/
│ ├── board.html # Live Kanban board — open in browser, no build
│ ├── board.js # Socket.io client + state rendering logic
│ └── board.css # Board styling
├── scripts/
│ ├── blog-team.sh # Start/stop orchestration wrapper (all modes)
│ ├── global-research.sh # Start/stop the global-research swarm (--chaos, --searchers N)
│ ├── run-example.sh # Generic start/stop for any examples/<name>
│ ├── monitor.sh # Real-time terminal dashboard (all streams)
│ ├── generate-dev-certs.sh # Self-signed CA + server/client certs for mTLS
│ ├── fix-lockfile.sh # npm run lockfile:check / lockfile:fix (npm 10 + 11)
│ ├── audit-gate.js # CI dependency audit: fails on HIGH+ except the dated .trivyignore entries
│ ├── pack-staging.sh # Apache-2.0 library tarball from a staging dir (used by the release workflows)
│ ├── smoke-consumer.sh # Packs the tarball and imports both entry points in a fresh consumer
│ ├── check-deploy-manifests.sh # Renders every compose file and both Helm charts (CI deploy-manifests job)
│ └── check-tag-version.sh # Release tag must equal the package.json version
├── board/ # React + Vite + TypeScript board app (standalone)
│ ├── src/
│ │ ├── main.tsx / App.tsx # Entry point + root layout
│ │ ├── types/board.ts # StateDelta, AgentDelta, TaskDelta, BoardState
│ │ ├── store/boardStore.ts # Zustand: applyDelta, setConnectionStatus, addLog
│ │ ├── socket/socketClient.ts # Socket.io singleton + sendHitlDecision()
│ │ └── components/ # layout/ · workflow/ · agents/ · kanban/ · economics/ · log/
│ ├── package.json # React 19, Vite 8, Tailwind, socket.io-client, zustand
│ └── .env.example # VITE_GATEWAY_URL=http://localhost:3000
├── docker-compose.yml # Full root stack (Redis + Zookeeper + Kafka + one gateway + one worker)
├── Dockerfile # Multi-stage: builder (npm ci + tsc) → runner (non-root)
└── .env.example # All env vars documented with examples
Distributed Actor Model documentation: see
docs/architecture/ACTOR_MODEL.mdfor a full explanation of how actor isolation, mailboxes, message-passing, fault containment, and horizontal scaling are implemented.
The full record is in docs/decisions/; the table lists the ones a reader meets first.
| Decision | Rationale |
|---|---|
| BullMQ as default | Lower ops overhead for dev; Kafka requires Zookeeper |
| No colons in BullMQ queue names | BullMQ v5 rejects colons; all internal names use dashes |
IMessagingDriver abstraction |
Swap BullMQ ↔ Kafka via MESSAGING_DRIVER; worker code unchanged |
Workers never set teamWorkflowStatus |
Only orchestrator owns workflow lifecycle; prevents heartbeats overriding FINISHED |
AgentStatePublisher uses ioredis directly |
SocketGateway reads Redis pub/sub; BullMQ queues are separate concerns |
15-second heartbeat in AgentStatePublisher |
Redis pub/sub is fire-and-forget; late-connecting boards see state within 15s |
Two KafkaDriver instances in CompletionRouter |
KafkaJS consumer.run() cannot subscribe to new topics after start |
Team per task in agent bridge |
Team.start() initializes LLM automatically from env; WorkflowResult.stats provides token counts without internal hacks |
| KaibanJS ERRORED status throws | team.start() rejects on ERRORED (no usage, not counted) and resolves { status: 'BLOCKED' } when an LLM/provider error blocks the task; on BLOCKED the bridge throws FailedAttemptError with the attempt's token usage, which the state publisher counts against the token caps; either way AgentActor retries (3×), then DLQs; once the counted usage reaches a cap, a non-retryable BudgetExceededError is dead-lettered without a further retry (and records no circuit-breaker failure) |
forceFinalAnswer: true on editor |
Free 8B models reach max iterations without structured output |
| SHA-256 hash prefix for agent IDs | 8-char prefix preserves debuggability while preventing PII leakage |
| 64 KB cap on published message data | AgentActor truncates result before publishing to prevent oversized frames from overloading messaging layer |
healthcheck: disable: true on workers |
Workers are not HTTP servers; Dockerfile HEALTHCHECK checks port 3000 which is gateway-only |
React board uses custom Socket.io client, not kaiban-board npm package |
[email protected] requires a KaibanJS Team instance; the distributed board consumes state:update events directly |
| Board HITL races readline vs Redis | waitForHITLDecision() in orchestrator resolves from whichever arrives first — terminal or board click; both remain usable simultaneously |
?gateway= query param for runtime URL override |
Allows the same static build to connect to any gateway without rebuilding |
The easiest way to run the full blog-team example is using the orchestration script. It handles Docker Compose, the API Gateway, worker nodes, the orchestrator, and the terminal monitor. When the gateway is ready it prints board URLs — open one in a separate terminal or browser tab.
# BullMQ/Redis — local orchestrator (default) ./scripts/blog-team.sh start ./scripts/blog-team.sh stop # Kafka — local orchestrator ./scripts/blog-team.sh start --kafka ./scripts/blog-team.sh stop --kafka # BullMQ/Redis — fully containerised (orchestrator runs in Docker, HITL via attached terminal) ./scripts/blog-team.sh start --docker ./scripts/blog-team.sh stop --docker # Kafka — fully containerised (flags are order-independent) ./scripts/blog-team.sh start --kafka --docker ./scripts/blog-team.sh stop --kafka --docker
--dockermode runs every component — including the orchestrator — as a Docker container. The orchestrator service (docker compose run --rm orchestrator) attaches your terminal for interactive HITL decisions [1/2/3/4]. Inside Docker it connects to gateway/Redis/Kafka via service-name hostnames. Without--docker, the orchestrator runs locally vianpx ts-node(requires Node.js + project deps installed).
The script prints board URLs when the gateway is ready. Open one or more in a separate terminal or browser tab — they are all synchronized from the backend stream at all times:
A) React Board — interactive HITL Approve / Revise / Reject, modern Kanban UI (requires Node.js):
# In a separate terminal, from the kaiban-distributed root: cd board && npm ci && npm run dev # → http://localhost:5173 # Point to a non-default gateway at runtime (no rebuild needed): # http://localhost:5173?gateway=http://my-gateway:3000
B) Static HTML viewer — zero setup, open directly in any browser:
examples/blog-team/viewer/board.html
# Auto-connects to http://localhost:3000
Multiple boards (React + HTML viewer + additional tabs) can all be open simultaneously and will all reflect the same live state. Each board receives a full state snapshot on connect and every incremental delta in real-time. HITL decisions can be sent from any connected board — the orchestrator accepts the first response.
If you started components manually, you can run the terminal monitor on its own. It automatically detects the MESSAGING_DRIVER (BullMQ/Redis or Kafka).
./scripts/monitor.sh
# With options:
REDIS_URL=redis://localhost:6379 \
COMPOSE_FILE=examples/blog-team/docker-compose.yml \
MESSAGING_DRIVER=bullmq \
LOG_TAIL=200 QUEUE_POLL_SEC=3 \
./scripts/monitor.sh| Stream | Description |
|---|---|
[workflow] |
Status transitions: RUNNING → FINISHED / STOPPED |
[agents] |
IDLE · EXECUTING (green) · THINKING (blue) · ERROR (red) |
[tasks] |
DOING · DONE (green) · BLOCKED (red) · AWAITING_VALIDATION (yellow) |
[logs] researcher/writer/editor/gateway |
Per-container process logs |
[queue] |
BullMQ queue depths polled every 5s |
[!ERR] |
All errors across all containers (red highlight) |
Fixes of earlier bugs are listed in CHANGELOG.md, not here.
| Error | Cause | Fix |
|---|---|---|
401 User not found |
Invalid OpenRouter API key | Get valid key at https://openrouter.ai/keys |
404 MODEL_NOT_FOUND / data policy |
Free model requires privacy opt-in | Enable https://openrouter.ai/settings/privacy or use paid model |
No endpoints found matching your data policy |
Free tier data-sharing required | Enable https://openrouter.ai/settings/privacy |
Agent failed: Max retries exceeded |
LLM API error | Check API key and model name |
network not found on docker compose up |
Stale network from previous compose stack | docker compose down --remove-orphans && docker network prune --force |
NOAUTH Authentication required from Redis |
The Redis password is not in REDIS_URL (dotenv does not expand ${...}) |
Put the real password into REDIS_URL, e.g. redis://:<password>@localhost:6379 |
401 Missing board token on STOP ALL |
No token, or one signed with another secret, or expired (1 hour by default) | Mint a fresh token with the same BOARD_JWT_SECRET the gateway runs with (SECURITY_FEATURES §1.1); npm run stop-all needs none |
A task ends with emergency_stop |
A STOP ALL was issued after the task was sent | Replay it from the dead-letter channel with replayDlq once the cause is fixed |
A2A or MCP answers -32602 for an agent id |
The id is not in the gateway's AGENT_IDS |
Add it to AGENT_IDS on the gateway |
Boot error X is required in production |
NODE_ENV=production needs BOARD_JWT_SECRET, A2A_JWT_SECRET and CHANNEL_SIGNING_SECRET (32+ bytes, all different) and, on the gateway, SOCKET_CORS_ORIGINS |
Set them; with Docker Compose also see which variables reach the containers |
No OTEL endpoint warning on startup |
OTEL_EXPORTER_OTLP_ENDPOINT not set — using verbose ConsoleSpanExporter |
Expected in dev; set OTEL_EXPORTER_OTLP_ENDPOINT for production |
Built with help from GABBE Agentic Engineering Kit, following the SDD/TDD lifecycle:
| Phase | Deliverable | Status |
|---|---|---|
| S01 | PRD.md — requirements | ✅ |
| S02 | PLAN.md — C4 architecture diagrams | ✅ |
| S03 | SPEC.md — domain models, API schemas | ✅ |
| S04 | Task decomposition | ✅ |
| S05 | Core implementation (6 modules) | ✅ |
| S06 | Unit test suite — 100% coverage | ✅ |
| S07 | KaibanJS integration, blog-team pipeline, Kafka, README | ✅ |
| S08 | Security remediation — mTLS, semantic firewall, JIT tokens, circuit breakers | ✅ |
Dual-licensed (see LICENSING.md, ADR-011):
- The published npm library (
kaiban-distributed— thedist/srcartifact) is Apache-2.0, usable in commercial / closed-source projects. - The full application (board, examples, tests, Docker images) is GPL-3.0.
Apache-2.0 (library) / GPL-3.0 (application) ©2026 Andrei Besleaga

