convez.ai
PluginDevOps & InfraestruturaAvançado
RonenMars

Threadbase Streamer

RonenMars/threadbase-streamer

Streaming de sessões Claude Code com PTY, WebSocket e REST API

Ver no GitHub
InicialPluginScore · de 0 a 100

Gerenciador de sessões PTY, streaming WebSocket e servidor REST API para conversas Claude Code. Mantém sessões Claude ao vivo via node-pty, transmite saída de terminal em tempo real e oferece API para histórico de conversas, busca e controle de sessões.

Instalação

$npx convez-ai RonenMars/threadbase-streamer

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 1 dia
Versão
v1.143.7
Issues abertas
51
Contribuidores
4

Casos de uso

  • Integrar Claude Code em aplicações externas com streaming em tempo real
  • Persistir e retomar sessões de terminal do Claude
  • Monitorar e buscar histórico de conversas via API REST

Veredito

Solução robusta para orquestração de sessões Claude em produção, com persistência em SQLite/PostgreSQL e suporte a resumo. Recomendado para quem precisa integrar fluxos de código Claude em pipelines DevOps complexos, mas exige familiaridade com arquitetura de microserviços e management de PTY.

README

A tradução para o português deste README ainda está na fila.

@threadbase/streamer

PTY session management, WebSocket streaming, and REST API server for Claude Code conversations. Manages live Claude sessions via node-pty, broadcasts terminal output over WebSocket, and serves a REST API for conversation history, search, and session control.

Quick Start

Install via Homebrew (recommended, macOS + Linux)

brew tap RonenMars/threadbase
brew install tb-streamer

# One-time setup:
tb-streamer set-key <YOUR_API_KEY>

# Start the service (also starts on login):
brew services start tb-streamer

To stop or restart: brew services stop tb-streamer / brew services restart tb-streamer. Optional automatic updates: see docs/guides/auto-update.md.

Note: the Homebrew install is mutually exclusive with the manual scripts/deploy.sh install. If you previously installed via that path, run launchctl bootout gui/$UID/com.threadbase.streamer before starting the Homebrew service.

Run from source

npm install
npm run build
node dist/cli.cjs serve --verbose --local-no-auth

The server starts on http://localhost:8766 by default with WebSocket at ws://localhost:8766/ws.

Persistence

Conversation metadata lives in a SQLite cache at ~/.threadbase/cache/cache.db — created and migrated automatically on startup, no configuration needed. Managed sessions are in-memory: a restart drops the live PTYs, but conversation history is on disk and every session can be resumed via POST /api/sessions/resume.

PostgreSQL is optional and currently dormant (it stores upload records only — not session state). Enable it by setting THREADBASE_DATABASE_URL (e.g. docker compose up -d postgres and export THREADBASE_DATABASE_URL="postgresql://threadbase:threadbase@localhost:5432/threadbase"); migrations run automatically. Related knobs: THREADBASE_DATABASE_SSL, THREADBASE_DATABASE_POOL_MAX, THREADBASE_DATABASE_STATEMENT_TIMEOUT_MS.

Architecture

Three layers: core engine (src/*.ts) → API layer (src/api/ + src/index.ts exports) → CLI wrapper (cli/).

The short version:

  • POST /api/sessions/start / resume spawns a claude process in a PTY; output streams to all WebSocket clients as terminal_output, with a terminal_replay snapshot on subscribe.
  • SessionStore registers managed (PTY) sessions plus externally-running claude processes found by process discovery.
  • A chokidar-backed watcher tails conversation JSONL files into the SQLite cache, which backs the conversation/list endpoints without filesystem scans.
  • When the last WebSocket subscriber disconnects, a grace timer (default 4.5 minutes) puts the PTY on hold — history intact, resumable any time.

Full runtime flow and module reference: docs/how-it-works.md. Dated design documents: docs/architecture/.

Relationship to Claude Code dynamic workflows

Claude Code dynamic workflows live inside a Claude Code session — the kind of session PTY mode hosts. The meaningful comparison is with --multi-agent-flow mode, where the streamer hands each turn off to a Temporal pipeline in tb-multi-agent instead of a node-pty Claude session: developer-triggered in-session orchestration vs. durable per-turn orchestration with webhook → WebSocket result delivery.

Details: docs/comparisons/claude-code-dynamic-workflows.md; multi-agent mode itself: docs/multi-agent-mode.md.

REST API

MethodEndpointDescription
GET/healthzHealth check (version)
GET/api/infoServer info (version, platform, active sessions)
GET/api/sessionsList managed + discovered sessions
GET/api/sessions/countCount of active managed sessions
GET/api/sessions/:idGet single session
POST/api/sessions/startStart a new Claude session in a given directory
POST/api/sessions/resumeResume a conversation (creates managed session)
POST/api/sessions/:id/inputSend input to a managed session
POST/api/sessions/:id/cancelCancel a managed session
GET/api/sessions/:id/outputGet terminal output buffer
POST/api/sessions/:id/filesUpload a file attachment to a session
GET/api/conversationsPaginated conversation history
GET/api/conversations/countCount conversations matching optional filters
GET/api/conversations/:idFull conversation with messages
GET/project-chatsUnified active-sessions + historical-conversations list (discriminated union); accepts ?refreshConversations=1
GET/api/search?q=...Full-text search across conversations
GET/api/browseBrowse the file system
POST/api/browse/mkdirCreate a directory
GET/api/profilesList scan profiles
POST/api/push/registerRegister a push notification token
POST/api/pair/startMint a short-lived pair token (authenticated)
POST/api/pair/exchangeTrade a pair token + client public key for a sealed API key (unauthenticated)

Remote Access (tunnels, funnels, proxies)

By default the streamer binds to 127.0.0.1:8766 and isn't reachable from the network. For the mobile app to pair from outside your LAN you need something forwarding HTTPS traffic to that local port. The fastest path is a Cloudflare quick-tunnel — no account, no domain, ~30 seconds:

# macOS / Linux / WSL / Git Bash
bash scripts/remote-access/cloudflare.sh

# Anywhere `pwsh` is installed (Windows native, or macOS/Linux via Homebrew)
pwsh scripts/remote-access/cloudflare.ps1

The Claude Code skill setup-cloudflare-tunnel runs the same script with prereq checks and named-tunnel guidance.

Mobile Pairing (QR)

Mobile clients pair by scanning a QR that encodes a threadbase://pair?url=…&token=…&exp=… URL. The token is single-use and expires after 180 seconds; the client then trades it (with its X25519 public key) at /api/pair/exchange for a sealed-box-encrypted API key, so the key never appears in the QR.

A QR is printed automatically when the server starts (skip with --no-pair-qr). To re-print a fresh QR while a server is already running:

tb-streamer pair          # uses default port 8766
tb-streamer pair -p 4000

If the mobile device can't reach localhost, point clients at a reachable address so the QR encodes it. In order of precedence:

  1. --public-url <https-url> flag on serve
  2. THREADBASE_PUBLIC_URL environment variable
  3. public_url: in ~/.threadbase/server.yaml

https:// is required (except for localhost).

Global commands (tb-streamer / threadbase-streamer)

npm run deploy automatically installs two global commands that wrap the deployed CLI at ~/.threadbase/cli.js: tb-streamer (short name) and threadbase-streamer (long name, used by the auto-update docs and scheduled-job scripts). Both work for every subcommand: tb-streamer pair, threadbase-streamer update, etc. The deploy prompts for the install dir on first run and persists the choice to ~/.threadbase/shim.conf.

Install dirs, non-interactive flags, PATH handling, and the legacy tb shim: docs/guides/deploy-internals.md.

Lazy-nvm note: if your shell wraps node/npm in a lazy nvm function, node is not on PATH in fresh shells until you invoke it once, and the shims fail with "node not found". Cheapest fix: run node -v once per session, or eager-load nvm.

Development

npm test                  # Run all tests
npm run lint              # Type-check + Biome lint
npm run format            # Auto-format
npm run build             # Build ESM/CJS + copy SQLite + Postgres migrations
npm run dev               # Watch mode
npm run migrate           # Apply SQLite migrations to ~/.threadbase/cache/cache.db (override --db <path>)
npm run migrate:projects  # Backfill projects + conversation.project_id from existing cache (idempotent)
npm run db:validate       # Report conversations missing project_id, duplicate project paths, orphans

Dependencies

  • @threadbase/scanner + @threadbase/agent-types — git submodules at vendor/ (run git submodule update --init before npm install)
  • node-pty — native PTY management
  • ws — WebSocket server
  • better-sqlite3 — SQLite driver for the conversation cache
  • chokidar — JSONL tail + directory watcher
  • zod — runtime validation at HTTP and scanner boundaries
  • date-fns — ISO timestamp parsing and comparison helpers
  • pg — PostgreSQL client (lazy-loaded, only when THREADBASE_DATABASE_URL is configured)
  • commander — CLI argument parsing
Ver o original no GitHub

Bom para

Relacionados