Skip to content
Back to search

vibecraft

SkillWorks with Claude CodeGitHub

3D visualization of Claude Code activity as an interactive workshop

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nearcyan--vibecraft/badge.svg)](/listings/nearcyan--vibecraft)

HTML

<a href="/listings/nearcyan--vibecraft"><img src="/api/listings/nearcyan--vibecraft/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# 1. Install dependencies
brew install jq tmux       # macOS
# sudo apt install jq tmux  # Ubuntu/Debian

# 2. Configure hooks (one time)
npx vibecraft setup

# 3. Start server
npx vibecraft

Open http://localhost:4003 and use Claude Code normally. You'll see Claude move around the workshop as it uses tools.

**From source:**

git clone https://github.com/nearcyan/vibecraft
cd vibecraft && npm install && npm run dev
# Opens on http://localhost:4002

**To uninstall:** `npx vibecraft uninstall` (removes hooks, keeps your data)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/plugin.json · Manifest · 8 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "vibecraft",
  3. "version": "0.1.0",
  4. "description": "3D visualization of Claude Code activity as an interactive workshop",
  5. "author": "nearcyan",
  6. "license": "MIT",
  7. "keywords": ["visualization", "3d", "vibecoding", "workshop", "monitoring"]
  8. }
README.md · README · 138 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Vibecraft
  2. ![Vibecraft Screenshot](public/og-image.png)
  3. Manage Claude Code in style!
  4. **[Try it instantly at vibecraft.sh](https://vibecraft.sh)** — still connects to your local Claude Code instances!
  5. **New:**
  6. - **Spatial Audio** — Claude behind you? Claude on your left? No claublem!
  7. - **Animations** — What's Claude up to? Watch him! ◕ ‿ ◕
  8. Vibecraft uses your own local Claude Code instances — no files or prompts are shared.
  9. ![Three.js](https://img.shields.io/badge/Three.js-black?logo=threedotjs) ![TypeScript](https://img.shields.io/badge/TypeScript-blue?logo=typescript&logoColor=white) ![npm](https://img.shields.io/npm/v/vibecraft)
  10. ## Requirements
  11. - **macOS or Linux** (Windows not supported - hooks require bash)
  12. - **Node.js** 18+
  13. - **jq** - for hook scripts (`brew install jq` / `apt install jq`)
  14. - **tmux** - for session management (`brew install tmux` / `apt install tmux`)
  15. ## Quick Start
  16. ```bash
  17. # 1. Install dependencies
  18. brew install jq tmux # macOS
  19. # sudo apt install jq tmux # Ubuntu/Debian
  20. # 2. Configure hooks (one time)
  21. npx vibecraft setup
  22. # 3. Start server
  23. npx vibecraft
  24. ```
  25. Open http://localhost:4003 and use Claude Code normally. You'll see Claude move around the workshop as it uses tools.
  26. **From source:**
  27. ```bash
  28. git clone https://github.com/nearcyan/vibecraft
  29. cd vibecraft && npm install && npm run dev
  30. # Opens on http://localhost:4002
  31. ```
  32. **To uninstall:** `npx vibecraft uninstall` (removes hooks, keeps your data)
  33. ## Browser Control (Optional)
  34. Run Claude in tmux to send prompts from browser:
  35. ```bash
  36. tmux new -s claude
  37. claude
  38. ```
  39. Then use the input field in the visualization with "Send to tmux" checked.
  40. ## Stations
  41. | Station | Tools | Details |
  42. |---------|-------|---------|
  43. | Bookshelf | Read | Books on shelves |
  44. | Desk | Write | Paper, pencil, ink pot |
  45. | Workbench | Edit | Wrench, gears, bolts |
  46. | Terminal | Bash | Glowing screen |
  47. | Scanner | Grep, Glob | Telescope with lens |
  48. | Antenna | WebFetch, WebSearch | Satellite dish |
  49. | Portal | Task (subagents) | Glowing ring portal |
  50. | Taskboard | TodoWrite | Board with sticky notes |
  51. ## Features
  52. - **Floating context labels** - See file paths and commands above active stations
  53. - **Thought bubbles** - Claude shows thinking animation while processing
  54. - **Response capture** - Claude's responses appear in the activity feed
  55. - **Subagent visualization** - Mini-Claudes spawn at portal for parallel tasks
  56. - **Cancel button** - Send Ctrl+C to interrupt Claude
  57. - **Split-screen layout** - 60% 3D scene (Workshop), 40% activity feed
  58. - **Voice input** - Speak prompts with real-time transcription (requires Deepgram API key)
  59. - **Attention system** - Zones pulse when sessions need input or finish
  60. - **Sound effects** - Synthesized audio feedback for tools and events ([docs/SOUND.md](docs/SOUND.md))
  61. - **Draw mode** - Paint hex tiles with colors, 3D stacking, and text labels (press `D`)
  62. - **Text labels** - Add multi-line labels to hex tiles with custom modal
  63. - **Zone context menus** - Right-click zones for Info (`I`) or quick Command (`C`) input
  64. - **Station panels** - Toggle with `P` to see recent tool history per workstation
  65. - **Context-aware animations** - Claude celebrates commits, shakes head on errors
  66. ## Multi-clauding
  67. ![Multi-clauding](public/multiclaude.png)
  68. Run multiple Claude instances and direct work to each:
  69. 1. Click **"+ New"** (or `Alt+N`) to spawn a new session
  70. 2. Configure name, directory, and flags (`-r`, `--chrome`, `--dangerously-skip-permissions`)
  71. 3. Click a session or press `1-6` (or `Alt+1-6` in inputs) to select it
  72. 4. Send prompts to whichever Claude you want
  73. Each session runs in its own tmux, with status tracking (idle/working/offline).
  74. See [docs/ORCHESTRATION.md](docs/ORCHESTRATION.md) for the full API and architecture.
  75. ## Keyboard Shortcuts
  76. | Key | Action |
  77. |-----|--------|
  78. | `Tab` / `Esc` | Switch focus between Workshop and Feed |
  79. | `1-6` | Switch to session (extended: QWERTY, ASDFGH, ZXCVBN) |
  80. | `0` / `` ` `` | All sessions / overview |
  81. | `Alt+N` | New session |
  82. | `Alt+R` | Toggle voice input |
  83. | `F` | Toggle follow mode |
  84. | `P` | Toggle station panels |
  85. | `D` | Toggle draw mode |
  86. **Draw mode:** `1-6` colors, `0` eraser, `Q/E` brush size, `R` 3D stack, `X` clear
  87. ## CLI Options
  88. ```bash
  89. vibecraft [options]
  90. Options:
  91. --port, -p <port> WebSocket server port (default: 4003)
  92. --help, -h Show help
  93. --version, -v Show version
  94. ```
  95. See [docs/SETUP.md](docs/SETUP.md) for detailed setup guide.
  96. See [CLAUDE.md](CLAUDE.md) for technical documentation.
  97. Website: https://vibecraft.sh
  98. ## License
  99. MIT
server/index.ts · Bundled script · 2,354 lines · 1 finding marked
  1. /**
  2. * Vibecraft WebSocket Server
  3. *
  4. * This server:
  5. * 1. Watches the events JSONL file for changes
  6. * 2. Accepts HTTP POST /event for real-time hook notifications
  7. * 3. Broadcasts events to connected WebSocket clients
  8. * 4. Tracks tool durations by matching pre/post events
  9. * 5. Proxies voice input to Deepgram for transcription
  10. */
  11. import { createServer, IncomingMessage, ServerResponse } from 'http'
  12. import { WebSocketServer, WebSocket, RawData } from 'ws'
  13. import { watch } from 'chokidar'
  14. import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync, unlinkSync, statSync } from 'fs'
  15. import { exec, execFile } from 'child_process'
  16. import { dirname, resolve, join, extname } from 'path'
  17. import { hostname } from 'os'
  18. import { randomUUID, randomBytes } from 'crypto'
  19. import { createClient, LiveTranscriptionEvents } from '@deepgram/sdk'
  20. import type { LiveClient } from '@deepgram/sdk'
  21. import type {
  22. ClaudeEvent,
  23. ServerMessage,
  24. ClientMessage,
  25. PreToolUseEvent,
  26. PostToolUseEvent,
  27. ManagedSession,
  28. CreateSessionRequest,
  29. UpdateSessionRequest,
  30. SessionPromptRequest,
  31. GitStatus,
  32. TextTile,
  33. CreateTextTileRequest,
  34. UpdateTextTileRequest,
  35. } from '../shared/types.js'
  36. import { DEFAULTS } from '../shared/defaults.js'
  37. import { GitStatusManager } from './GitStatusManager.js'
  38. import { ProjectsManager } from './ProjectsManager.js'
  39. import { fileURLToPath } from 'url'
  40. // ============================================================================
  41. // Version (read from package.json)
  42. // ============================================================================
  43. const __filename = fileURLToPath(import.meta.url)
  44. const __dirname = dirname(__filename)
  45. function getPackageVersion(): string {
  46. try {
  47. // Try multiple locations (dev vs compiled)
  48. const locations = [
  49. resolve(__dirname, '../package.json'), // dev: server/ -> package.json
  50. resolve(__dirname, '../../package.json'), // compiled: dist/server/ -> package.json
  51. ]
  52. for (const loc of locations) {
  53. if (existsSync(loc)) {
  54. const pkg = JSON.parse(readFileSync(loc, 'utf-8'))
  55. return pkg.version || 'unknown'
  56. }
  57. }
  58. } catch {
  59. // Ignore errors
  60. }
  61. return 'unknown'
  62. }
  63. const VERSION = getPackageVersion()
  64. // ============================================================================
  65. // Configuration (env vars override DEFAULTS from shared/defaults.ts)
  66. // ============================================================================
  67. /** Expand ~ to home directory in paths */
  68. function expandHome(path: string): string {
  69. if (path.startsWith('~/') || path === '~') {
  70. return path.replace('~', process.env.HOME || '')
  71. }
  72. return path
  73. }
  74. const PORT = parseInt(process.env.VIBECRAFT_PORT ?? String(DEFAULTS.SERVER_PORT), 10)
  75. const EVENTS_FILE = resolve(expandHome(process.env.VIBECRAFT_EVENTS_FILE ?? DEFAULTS.EVENTS_FILE))
  76. const PENDING_PROMPT_FILE = resolve(expandHome(process.env.VIBECRAFT_PROMPT_FILE ?? '~/.vibecraft/data/pending-prompt.txt'))
  77. const MAX_EVENTS = parseInt(process.env.VIBECRAFT_MAX_EVENTS ?? String(DEFAULTS.MAX_EVENTS), 10)
  78. const DEBUG = process.env.VIBECRAFT_DEBUG === 'true'
  79. const TMUX_SESSION = process.env.VIBECRAFT_TMUX_SESSION ?? DEFAULTS.TMUX_SESSION
  80. const SESSIONS_FILE = resolve(expandHome(process.env.VIBECRAFT_SESSIONS_FILE ?? DEFAULTS.SESSIONS_FILE))
  81. const TILES_FILE = resolve(expandHome(process.env.VIBECRAFT_TILES_FILE ?? '~/.vibecraft/data/tiles.json'))
  82. /** Time before a "working" session auto-transitions to idle (failsafe for missed events) */
  83. const WORKING_TIMEOUT_MS = 120_000 // 2 minutes
  84. /** Maximum request body size (1MB) - prevents DoS via memory exhaustion */
  85. const MAX_BODY_SIZE = 1024 * 1024
  86. /** How often to check for stale "working" sessions */
  87. const WORKING_CHECK_INTERVAL_MS = 10_000 // 10 seconds
  88. /** Extended PATH for exec() - includes Homebrew and user paths for macOS/Linux */
  89. const HOME = process.env.HOME || ''
  90. const EXEC_PATH = [
  91. `${HOME}/.local/bin`, // User local bin (Claude CLI default location)
  92. '/opt/homebrew/bin', // macOS Apple Silicon Homebrew
  93. '/usr/local/bin', // macOS Intel Homebrew / Linux local
  94. process.env.PATH || '',
  95. ].join(':')
  96. /** Options for exec() with extended PATH */
  97. const EXEC_OPTIONS = { env: { ...process.env, PATH: EXEC_PATH } }
  98. /** Deepgram API key from environment */
  99. const DEEPGRAM_API_KEY_ENV = 'DEEPGRAM_API_KEY'
  100. /** Deepgram transcription settings */
  101. const DEEPGRAM_MODEL = 'nova-2'
  102. const DEEPGRAM_LANGUAGE = 'en'
  103. /**
  104. * Validate WebSocket origin header to prevent CSRF attacks.
  105. * Only browser clients should connect, so we require a valid origin.
  106. */
  107. function isOriginAllowed(origin: string | undefined): boolean {
  108. // Require origin header - only browsers send this
  109. if (!origin) return false
  110. try {
  111. const url = new URL(origin)
  112. // Allow any port on localhost/127.0.0.1 (local development)
  113. if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {
  114. return true
  115. }
  116. // Production: exact hostname match with HTTPS required
  117. if (url.hostname === 'vibecraft.sh' && url.protocol === 'https:') {
  118. return true
  119. }
  120. return false
  121. } catch {
  122. return false // Invalid URL format
  123. }
  124. }
  125. /**
  126. * Validate and sanitize a directory path for use in shell commands.
  127. * Returns the resolved path if valid, throws if invalid.
  128. */
  129. function validateDirectoryPath(inputPath: string): string {
  130. // Resolve to absolute path (handles ~, .., etc.)
  131. const resolved = resolve(expandHome(inputPath))
  132. // Check path exists and is a directory
  133. if (!existsSync(resolved)) {
  134. throw new Error(`Directory does not exist: ${inputPath}`)
  135. }
  136. const stat = statSync(resolved)
  137. if (!stat.isDirectory()) {
  138. throw new Error(`Path is not a directory: ${inputPath}`)
  139. }
  140. // Reject paths with shell metacharacters that could enable injection
  141. // Even with execFile, tmux passes commands to a shell
  142. const dangerousChars = /[;&|`$(){}[\]<>\\'"!#*?]/
  143. if (dangerousChars.test(resolved)) {
  144. throw new Error(`Directory path contains invalid characters: ${inputPath}`)
  145. }
  146. return resolved
  147. }
  148. /**
  149. * Validate a tmux session name.
  150. * tmux session names should only contain alphanumeric, underscore, hyphen.
  151. */
  152. function validateTmuxSession(name: string): string {
  153. if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
  154. throw new Error(`Invalid tmux session name: ${name}`)
  155. }
  156. return name
  157. }
  158. /**
  159. * Promisified execFile helper
  160. */
  161. function execFileAsync(cmd: string, args: string[]): Promise<void> {
  162. return new Promise((resolve, reject) => {
  163. execFile(cmd, args, EXEC_OPTIONS, (error) => {
  164. if (error) reject(error)
  165. else resolve()
  166. })
  167. })
  168. }
  169. /**
  170. * Safely collect request body with size limit to prevent DoS.
  171. * Returns a promise that resolves with the body string or rejects on error/oversized.
  172. */
  173. function collectRequestBody(req: IncomingMessage, maxSize: number = MAX_BODY_SIZE): Promise<string> {
  174. return new Promise((resolve, reject) => {
  175. let body = ''
  176. let size = 0
  177. req.on('data', (chunk: Buffer | string) => {
  178. size += chunk.length
  179. if (size > maxSize) {
  180. req.destroy()
  181. reject(new Error('Request body too large'))
  182. return
  183. }
  184. body += chunk
  185. })
  186. req.on('end', () => resolve(body))
  187. req.on('error', reject)
  188. })
  189. }
  190. /**
  191. * Safely send text to a tmux session using load-buffer + paste-buffer.
  192. * Uses execFile with proper arguments to prevent shell injection.
  193. */
  194. async function sendToTmuxSafe(tmuxSession: string, text: string): Promise<void> {
  195. // Validate session name
  196. validateTmuxSession(tmuxSession)
  197. // Create temp file with cryptographically secure random name
  198. const tempFile = `/tmp/vibecraft-prompt-${Date.now()}-${randomBytes(16).toString('hex')}.txt`
  199. writeFileSync(tempFile, text)
  200. try {
  201. // Load text into tmux buffer
  202. await execFileAsync('tmux', ['load-buffer', tempFile])
  203. // Paste buffer into session
  204. await execFileAsync('tmux', ['paste-buffer', '-t', tmuxSession])
  205. // Send Enter to submit
  206. await new Promise(r => setTimeout(r, 100)) // Small delay like original
  207. await execFileAsync('tmux', ['send-keys', '-t', tmuxSession, 'Enter'])
  208. } finally {
  209. // Clean up temp file
  210. try {
  211. unlinkSync(tempFile)
  212. } catch {
  213. // Ignore cleanup errors
  214. }
  215. }
  216. }
  217. // ============================================================================
  218. // State
  219. // ============================================================================
  220. /** All events in memory */
  221. const events: ClaudeEvent[] = []
  222. /** Track seen event IDs to prevent duplicates (from file watcher + POST) */
  223. const seenEventIds = new Set<string>()
  224. /** Track in-flight tool uses for duration calculation */
  225. const pendingToolUses = new Map<string, PreToolUseEvent>()
  226. /** Connected WebSocket clients */
  227. const clients = new Set<WebSocket>()
  228. /** Last read position in file */
  229. let lastFileSize = 0
  230. /** Token tracking per session */
  231. interface SessionTokens {
  232. lastSeen: number // Last token count seen in output
  233. cumulative: number // Running total (estimated)
  234. lastUpdate: number // Timestamp
  235. }
  236. const sessionTokens = new Map<string, SessionTokens>()
  237. /** Last parsed tmux output (to detect changes) */
  238. let lastTmuxHash = ''
  239. /** Track pending permission prompts per session */
  240. interface PermissionOption {
  241. number: string // "1", "2", "3"
  242. label: string // "Yes", "Yes, and always allow...", "No"
  243. }
  244. interface PermissionPrompt {
  245. tool: string
  246. context: string // The full prompt text
  247. options: PermissionOption[] // Available choices
  248. detectedAt: number
  249. }
  250. const pendingPermissions = new Map<string, PermissionPrompt>()
  251. /** Track sessions that have had the bypass permissions warning handled */
  252. const bypassWarningHandled = new Set<string>()
  253. /** Managed sessions registry */
  254. const managedSessions = new Map<string, ManagedSession>()
  255. /** Text tiles (grid labels) */
  256. const textTiles = new Map<string, TextTile>()
  257. /** Git status tracker for managed sessions */
  258. const gitStatusManager = new GitStatusManager()
  259. /** Project directories manager */
  260. const projectsManager = new ProjectsManager()
  261. /** Active voice transcription sessions (WebSocket client → Deepgram connection) */
  262. const voiceSessions = new Map<WebSocket, LiveClient>()
  263. /** Deepgram API key (loaded on startup) */
  264. let deepgramApiKey: string | null = null
  265. /** Load Deepgram API key from environment */
  266. function loadDeepgramKey(): string | null {
  267. const key = process.env[DEEPGRAM_API_KEY_ENV]?.trim()
  268. if (key) {
  269. log('Deepgram API key loaded from environment')
  270. return key
  271. }
  272. log(`${DEEPGRAM_API_KEY_ENV} not set - voice input disabled`)
  273. return null
  274. }
  275. /** Map Claude Code session IDs to our managed session IDs */
  276. const claudeToManagedMap = new Map<string, string>()
  277. /** Counter for generating session names */
  278. let sessionCounter = 0
  279. // ============================================================================
  280. // Logging
  281. // ============================================================================
  282. function log(...args: unknown[]) {
  283. console.log(`[${new Date().toISOString()}]`, ...args)
  284. }
  285. function debug(...args: unknown[]) {
  286. if (DEBUG) {
  287. console.log(`[DEBUG ${new Date().toISOString()}]`, ...args)
  288. }
  289. }
  290. // ============================================================================
  291. // Token Tracking
  292. // ============================================================================
  293. /**
  294. * Parse token count from Claude Code output
  295. * Patterns:
  296. * ↓ 879 tokens
  297. * ↓ 1,234 tokens
  298. * ↓ 12.5k tokens
  299. * ↓ 12k tokens
  300. */
  301. function parseTokensFromOutput(output: string): number | null {
  302. // Match patterns like: ↓ 879 tokens, ↓ 1,234 tokens, ↓ 12.5k tokens
  303. const patterns = [
  304. /↓\s*([0-9,]+)\s*tokens?/gi, // ↓ 879 tokens, ↓ 1,234 tokens
  305. /↓\s*([0-9.]+)k\s*tokens?/gi, // ↓ 12.5k tokens, ↓ 12k tokens
  306. ]
  307. let maxTokens = 0
  308. // Pattern 1: plain numbers (possibly with commas)
  309. const plainMatches = output.matchAll(patterns[0])
  310. for (const match of plainMatches) {
  311. const num = parseInt(match[1].replace(/,/g, ''), 10)
  312. if (num > maxTokens) maxTokens = num
  313. }
  314. // Pattern 2: k suffix (thousands)
  315. const kMatches = output.matchAll(patterns[1])
  316. for (const match of kMatches) {
  317. const num = Math.round(parseFloat(match[1]) * 1000)
  318. if (num > maxTokens) maxTokens = num
  319. }
  320. return maxTokens > 0 ? maxTokens : null
  321. }
  322. /**
  323. * Poll tmux output for token counts
  324. */
  325. function pollTokens(tmuxSession: string): void {
  326. try {
  327. validateTmuxSession(tmuxSession)
  328. } catch {
  329. debug(`Invalid tmux session for token polling: ${tmuxSession}`)
  330. return
  331. }
  332. execFile('tmux', ['capture-pane', '-t', tmuxSession, '-p', '-S', '-50'], { ...EXEC_OPTIONS, maxBuffer: 1024 * 1024 }, (error, stdout) => {
  333. if (error) {
  334. debug(`Token poll failed: ${error.message}`)
  335. return
  336. }
  337. // Simple hash to detect changes
  338. const hash = stdout.slice(-500)
  339. if (hash === lastTmuxHash) return
  340. lastTmuxHash = hash
  341. const tokens = parseTokensFromOutput(stdout)
  342. if (tokens === null) return
  343. // Update session tokens (use TMUX_SESSION as session ID for now)
  344. let session = sessionTokens.get(tmuxSession)
  345. if (!session) {
  346. session = { lastSeen: 0, cumulative: 0, lastUpdate: Date.now() }
  347. sessionTokens.set(tmuxSession, session)
  348. }
  349. // If we see a higher token count, update cumulative
  350. if (tokens > session.lastSeen) {
  351. const delta = tokens - session.lastSeen
  352. session.cumulative += delta
  353. session.lastSeen = tokens
  354. session.lastUpdate = Date.now()
  355. debug(`Tokens updated: ${tokens} (cumulative: ${session.cumulative})`)
  356. // Broadcast token update
  357. broadcast({
  358. type: 'tokens',
  359. payload: {
  360. session: tmuxSession,
  361. current: tokens,
  362. cumulative: session.cumulative,
  363. },
  364. } as ServerMessage)
  365. } else if (tokens < session.lastSeen && tokens > 0) {
  366. // Token count dropped - likely new conversation, reset tracking
  367. session.lastSeen = tokens
  368. session.lastUpdate = Date.now()
  369. debug(`Token count reset detected: ${tokens}`)
  370. }
  371. })
  372. }
  373. /**
  374. * Start polling for tokens
  375. */
  376. function startTokenPolling(): void {
  377. // Poll every 2 seconds - poll all managed sessions
  378. setInterval(() => {
  379. for (const session of managedSessions.values()) {
  380. if (session.status !== 'offline') {
  381. pollTokens(session.tmuxSession)
  382. }
  383. }
  384. // Also poll the default session for backwards compatibility
  385. if (!managedSessions.size) {
  386. pollTokens(TMUX_SESSION)
  387. }
  388. }, 2000)
  389. log(`Token polling started`)
  390. }
  391. // ============================================================================
  392. // Permission Prompt Detection
  393. // ============================================================================
  394. /**
  395. * Parse tmux output to detect Claude Code permission prompts.
  396. *
  397. * Claude Code prompts look like:
  398. * ● Bash(rm /tmp/test.txt)
  399. * ⎿ Running PreToolUse hook…
  400. * ─────────────────────────────
  401. * Bash command
  402. *
  403. * rm /tmp/test.txt
  404. *
  405. * Do you want to proceed?
  406. * ❯ 1. Yes
  407. * 2. Yes, and always allow access to tmp/ from this project
  408. * 3. No
  409. *
  410. * Esc to cancel · Tab to add additional instructions
  411. *
  412. * OR (plan mode):
  413. * · Bash(prompt: run TypeScript compiler)
  414. * Would you like to proceed?
  415. *
  416. * 1. Yes, and bypass permissions
  417. * ❯ 2. Yes, and manually approve edits
  418. * 3. Type here to tell Claude what to change
  419. *
  420. * ctrl-g to edit in Vim · ~/.claude/plans/...
  421. */
  422. function detectPermissionPrompt(output: string): { tool: string; context: string; options: PermissionOption[] } | null {
  423. const lines = output.split('\n')
  424. // Look for "Do you want to proceed?" OR "Would you like to proceed?" in recent output
  425. let proceedLineIdx = -1
  426. for (let i = lines.length - 1; i >= Math.max(0, lines.length - 30); i--) {
  427. if (/(Do you want|Would you like) to proceed\?/i.test(lines[i])) {
  428. proceedLineIdx = i
  429. break
  430. }
  431. }
  432. if (proceedLineIdx === -1) return null
  433. // CRITICAL: Verify this is a real Claude Code prompt by checking for the footer
  434. // "Esc to cancel · Tab to add additional instructions" OR "ctrl-g to edit in Vim"
  435. let hasFooter = false
  436. let hasSelector = false
  437. for (let i = proceedLineIdx + 1; i < Math.min(lines.length, proceedLineIdx + 15); i++) {
  438. if (/Esc to cancel|ctrl-g to edit/i.test(lines[i])) {
  439. hasFooter = true
  440. break
  441. }
  442. // Also check for the ❯ selector arrow which indicates the interactive menu
  443. if (/^\s*❯/.test(lines[i])) {
  444. hasSelector = true
  445. }
  446. }
  447. // Must have either the footer or the selector arrow to be a real prompt
  448. if (!hasFooter && !hasSelector) {
  449. debug('Skipping false positive: no "Esc to cancel"/"ctrl-g" footer or ❯ selector found')
  450. return null
  451. }
  452. // Parse numbered options below the "Do you want to proceed?" line
  453. const options: PermissionOption[] = []
  454. for (let i = proceedLineIdx + 1; i < Math.min(lines.length, proceedLineIdx + 10); i++) {
  455. const line = lines[i]
  456. // Stop if we hit the footer
  457. if (/Esc to cancel/i.test(line)) break
  458. // Match options like "❯ 1. Yes" or " 2. Yes, and always..."
  459. // The arrow (❯) indicates current selection, but we want all options
  460. const optionMatch = line.match(/^\s*[❯>]?\s*(\d+)\.\s+(.+)$/)
  461. if (optionMatch) {
  462. options.push({
  463. number: optionMatch[1],
  464. label: optionMatch[2].trim()
  465. })
  466. }
  467. }
  468. // Need at least 2 options to be valid
  469. if (options.length < 2) return null
  470. // Find the tool name - look backwards for "● ToolName(...)" or "Bash command" header
  471. let tool = 'Unknown'
  472. for (let i = proceedLineIdx; i >= Math.max(0, proceedLineIdx - 20); i--) {
  473. // Match tool header like "● Bash(rm /tmp/test.txt)" or "· Bash(prompt: ...)"
  474. // ● = bullet, ◐ = half-filled circle, · = middle dot (plan mode)
  475. const toolMatch = lines[i].match(/[●◐·]\s*(\w+)\s*\(/)
  476. if (toolMatch) {
  477. tool = toolMatch[1]
  478. break
  479. }
  480. // Also match standalone tool type like "Bash command" or "Read file"
  481. const cmdMatch = lines[i].match(/^\s*(Bash|Read|Write|Edit|Grep|Glob|Task|WebFetch|WebSearch)\s+\w+/i)
  482. if (cmdMatch) {
  483. tool = cmdMatch[1]
  484. break
  485. }
  486. }
  487. // Build context from the prompt area (between tool header and options)
  488. const contextStart = Math.max(0, proceedLineIdx - 10)
  489. const contextEnd = proceedLineIdx + 1 + options.length
  490. const context = lines.slice(contextStart, contextEnd).join('\n').trim()
  491. debug(`Detected permission prompt: tool=${tool}, options=${options.map(o => o.number + ':' + o.label).join(', ')}`)
  492. return { tool, context, options }
  493. }
  494. /**
  495. * Detect the bypass permissions warning that appears on first use of --dangerously-skip-permissions.
  496. * Returns true if the warning is detected and needs to be accepted.
  497. *
  498. * The warning looks like:
  499. * ╭──────────────────────────────────────────────────────────────────────────────╮
  500. * │ WARNING │
  501. * │ │
  502. * │ You are entering Bypass Permissions mode. In this mode: │
  503. * │ • All tool calls will be auto-approved │
  504. * │ ... │
  505. * │ │
  506. * │ Are you sure you want to continue? │
  507. * │ │
  508. * │ 1. No, exit Claude Code │
  509. * │ ❯ 2. Yes, I understand and accept the risks │
  510. * ╰──────────────────────────────────────────────────────────────────────────────╯
  511. */
  512. function detectBypassWarning(output: string): boolean {
  513. // Must have both WARNING and Bypass Permissions mode
  514. return output.includes('WARNING') && output.includes('Bypass Permissions mode')
  515. }
  516. /**
  517. * Poll a session for permission prompts
  518. */
  519. function pollPermissions(sessionId: string, tmuxSession: string): void {
  520. try {
  521. validateTmuxSession(tmuxSession)
  522. } catch {
  523. debug(`Invalid tmux session for permission polling: ${tmuxSession}`)
  524. return
  525. }
  526. execFile('tmux', ['capture-pane', '-t', tmuxSession, '-p', '-S', '-50'], { ...EXEC_OPTIONS, maxBuffer: 1024 * 1024 }, (error, stdout) => {
  527. if (error) {
  528. debug(`Permission poll failed for ${tmuxSession}: ${error.message}`)
  529. return
  530. }
  531. // Check for bypass permissions warning (first-time use of --dangerously-skip-permissions)
  532. if (detectBypassWarning(stdout) && !bypassWarningHandled.has(sessionId)) {
  533. log(`Bypass permissions warning detected for session ${sessionId}, auto-accepting...`)
  534. bypassWarningHandled.add(sessionId)
  535. // Send "2" to accept the warning
  536. execFile('tmux', ['send-keys', '-t', tmuxSession, '2'], EXEC_OPTIONS, (err) => {
  537. if (err) {
  538. log(`Failed to auto-accept bypass warning: ${err.message}`)
  539. } else {
  540. log(`Bypass permissions warning accepted for session ${sessionId}`)
  541. }
  542. })
  543. return // Don't process further this poll cycle
  544. }
  545. const prompt = detectPermissionPrompt(stdout)
  546. const existing = pendingPermissions.get(sessionId)
  547. if (prompt && !existing) {
  548. // New permission prompt detected
  549. pendingPermissions.set(sessionId, {
  550. tool: prompt.tool,
  551. context: prompt.context,
  552. options: prompt.options,
  553. detectedAt: Date.now(),
  554. })
  555. log(`Permission prompt detected for session ${sessionId}: ${prompt.tool} (${prompt.options.length} options)`)
  556. // Broadcast to clients with options
  557. broadcast({
  558. type: 'permission_prompt',
  559. payload: {
  560. sessionId,
  561. tool: prompt.tool,
  562. context: prompt.context,
  563. options: prompt.options,
  564. },
  565. } as ServerMessage)
  566. // Update session status
  567. const session = managedSessions.get(sessionId)
  568. if (session) {
  569. session.status = 'waiting'
  570. session.currentTool = prompt.tool
  571. broadcastSessions()
  572. }
  573. } else if (!prompt && existing) {
  574. // Permission prompt was resolved (user responded in terminal or elsewhere)
  575. pendingPermissions.delete(sessionId)
  576. log(`Permission prompt resolved for session ${sessionId}`)
  577. // Broadcast resolution
  578. broadcast({
  579. type: 'permission_resolved',
  580. payload: { sessionId },
  581. } as ServerMessage)
  582. // Reset session status
  583. const session = managedSessions.get(sessionId)
  584. if (session && session.status === 'waiting') {
  585. session.status = 'working'
  586. session.currentTool = undefined
  587. broadcastSessions()
  588. }
  589. }
  590. })
  591. }
  592. /**
  593. * Start polling for permission prompts
  594. */
  595. function startPermissionPolling(): void {
  596. // Poll every 1 second (more frequent than tokens since permissions are time-sensitive)
  597. setInterval(() => {
  598. for (const session of managedSessions.values()) {
  599. if (session.status !== 'offline') {
  600. pollPermissions(session.id, session.tmuxSession)
  601. }
  602. }
  603. }, 1000)
  604. log(`Permission polling started`)
  605. }
  606. /**
  607. * Send a permission response to a session.
  608. * The response should be the option number ("1", "2", "3", etc.)
  609. */
  610. function sendPermissionResponse(sessionId: string, optionNumber: string): boolean {
  611. const session = managedSessions.get(sessionId)
  612. if (!session) {
  613. log(`Cannot send permission response: session ${sessionId} not found`)
  614. return false
  615. }
  616. // Validate it's a number
  617. if (!/^\d+$/.test(optionNumber)) {
  618. log(`Invalid permission response: ${optionNumber} (expected number)`)
  619. return false
  620. }
  621. // Validate tmux session name
  622. try {
  623. validateTmuxSession(session.tmuxSession)
  624. } catch {
  625. log(`Invalid tmux session name: ${session.tmuxSession}`)
  626. return false
  627. }
  628. // Send the option number to tmux - Claude Code expects just the number
  629. execFile('tmux', ['send-keys', '-t', session.tmuxSession, optionNumber], EXEC_OPTIONS, (error) => {
  630. if (error) {
  631. log(`Failed to send permission response: ${error.message}`)
  632. return
  633. }
  634. log(`Sent permission response to ${session.name}: option ${optionNumber}`)
  635. // Clear the pending permission
  636. pendingPermissions.delete(sessionId)
  637. // Update session status
  638. session.status = 'working'
  639. session.currentTool = undefined
  640. broadcastSessions()
  641. })
  642. return true
  643. }
  644. // ============================================================================
  645. // Session Management
  646. // ============================================================================
  647. /**
  648. * Generate a short ID for tmux session names
  649. */
  650. function shortId(): string {
  651. return randomUUID().slice(0, 8)
  652. }
  653. /**
  654. * Create a new managed session
  655. */
  656. function createSession(options: CreateSessionRequest = {}): Promise<ManagedSession> {
  657. return new Promise((resolve, reject) => {
  658. const id = randomUUID()
  659. sessionCounter++
  660. const name = options.name || `Claude ${sessionCounter}`
  661. const tmuxSession = `vibecraft-${shortId()}`
  662. // Validate cwd to prevent command injection
  663. let cwd: string
  664. try {
  665. cwd = validateDirectoryPath(options.cwd || process.cwd())
  666. } catch (err) {
  667. reject(err)
  668. return
  669. }
  670. // Build claude command with flags
  671. const flags = options.flags || {}
  672. const claudeArgs: string[] = []
  673. // Defaults: continue=true, skipPermissions=true, chrome=false
  674. if (flags.continue !== false) {
  675. claudeArgs.push('-c')
  676. }
  677. if (flags.skipPermissions !== false) {
  678. // --permission-mode=bypassPermissions skips the workspace trust dialog
  679. // --dangerously-skip-permissions skips tool permission prompts
  680. claudeArgs.push('--permission-mode=bypassPermissions')
  681. claudeArgs.push('--dangerously-skip-permissions')
  682. }
  683. if (flags.chrome) {
  684. claudeArgs.push('--chrome')
  685. }
  686. const claudeCmd = claudeArgs.length > 0 ? `claude ${claudeArgs.join(' ')}` : 'claude'
  687. // Spawn tmux session with claude using execFile to prevent shell injection
  688. // Arguments are passed as array, not interpolated into a shell string
  689. execFile('tmux', [
  690. 'new-session',
  691. '-d',
  692. '-s', tmuxSession,
  693. '-c', cwd,
  694. `PATH=${EXEC_PATH} ${claudeCmd}`
  695. ], EXEC_OPTIONS, (error) => {
  696. if (error) {
  697. log(`Failed to spawn session: ${error.message}`)
  698. reject(new Error(`Failed to spawn session: ${error.message}`))
  699. return
  700. }
  701. const session: ManagedSession = {
  702. id,
  703. name,
  704. tmuxSession,
  705. status: 'idle',
  706. createdAt: Date.now(),
  707. lastActivity: Date.now(),
  708. cwd,
  709. }
  710. managedSessions.set(id, session)
  711. log(`Created session: ${name} (${id.slice(0, 8)}) -> tmux:${tmuxSession} cmd:'${claudeCmd}'`)
  712. // Track git status for this session
  713. if (cwd) {
  714. gitStatusManager.track(id, cwd)
  715. // Remember this directory for future autocomplete
  716. projectsManager.addProject(cwd, name)
  717. }
  718. // Broadcast and persist
  719. broadcastSessions()
  720. saveSessions()
  721. resolve(session)
  722. })
  723. })
  724. }
  725. /**
  726. * Get all managed sessions
  727. */
  728. function getSessions(): ManagedSession[] {
  729. return Array.from(managedSessions.values()).map(session => ({
  730. ...session,
  731. gitStatus: gitStatusManager.getStatus(session.id) ?? undefined,
  732. }))
  733. }
  734. /**
  735. * Get a session by ID
  736. */
  737. function getSession(id: string): ManagedSession | undefined {
  738. return managedSessions.get(id)
  739. }
  740. /**
  741. * Update a session
  742. */
  743. function updateSession(id: string, updates: UpdateSessionRequest): ManagedSession | null {
  744. const session = managedSessions.get(id)
  745. if (!session) return null
  746. if (updates.name) {
  747. session.name = updates.name
  748. }
  749. if (updates.zonePosition) {
  750. session.zonePosition = updates.zonePosition
  751. }
  752. log(`Updated session: ${session.name} (${id.slice(0, 8)})`)
  753. broadcastSessions()
  754. saveSessions()
  755. return session
  756. }
  757. /**
  758. * Delete/kill a session
  759. */
  760. function deleteSession(id: string): Promise<boolean> {
  761. return new Promise((resolve) => {
  762. const session = managedSessions.get(id)
  763. if (!session) {
  764. resolve(false)
  765. return
  766. }
  767. // Kill the tmux session using execFile to prevent shell injection
  768. try {
  769. validateTmuxSession(session.tmuxSession)
  770. } catch {
  771. log(`Invalid tmux session name: ${session.tmuxSession}`)
  772. resolve(false)
  773. return
  774. }
  775. execFile('tmux', ['kill-session', '-t', session.tmuxSession], EXEC_OPTIONS, (error) => {
  776. if (error) {
  777. log(`Warning: Failed to kill tmux session: ${error.message}`)
  778. }
  779. managedSessions.delete(id)
  780. gitStatusManager.untrack(id)
  781. // Clean up mapping
  782. for (const [claudeId, managedId] of claudeToManagedMap) {
  783. if (managedId === id) {
  784. claudeToManagedMap.delete(claudeId)
  785. }
  786. }
  787. log(`Deleted session: ${session.name} (${id.slice(0, 8)})`)
  788. broadcastSessions()
  789. saveSessions()
  790. resolve(true)
  791. })
  792. })
  793. }
  794. /**
  795. * Send a prompt to a specific session
  796. */
  797. async function sendPromptToSession(id: string, prompt: string): Promise<{ ok: boolean; error?: string }> {
  798. const session = managedSessions.get(id)
  799. if (!session) {
  800. return { ok: false, error: 'Session not found' }
  801. }
  802. try {
  803. await sendToTmuxSafe(session.tmuxSession, prompt)
  804. session.lastActivity = Date.now()
  805. log(`Prompt sent to ${session.name}: ${prompt.slice(0, 50)}...`)
  806. return { ok: true }
  807. } catch (error) {
  808. const msg = error instanceof Error ? error.message : String(error)
  809. log(`Failed to send prompt to ${session.name}: ${msg}`)
  810. return { ok: false, error: msg }
  811. }
  812. }
  813. /**
  814. * Check if tmux sessions are still alive and update status
  815. */
  816. function checkSessionHealth(): void {
  817. exec('tmux list-sessions -F "#{session_name}"', EXEC_OPTIONS, (error, stdout) => {
  818. if (error) {
  819. // tmux might not be running
  820. for (const session of managedSessions.values()) {
  821. if (session.status !== 'offline') {
  822. session.status = 'offline'
  823. }
  824. }
  825. return
  826. }
  827. const activeSessions = new Set(stdout.trim().split('\n'))
  828. let changed = false
  829. for (const session of managedSessions.values()) {
  830. const isAlive = activeSessions.has(session.tmuxSession)
  831. const newStatus = isAlive ? (session.status === 'offline' ? 'idle' : session.status) : 'offline'
  832. if (session.status !== newStatus) {
  833. session.status = newStatus
  834. changed = true
  835. }
  836. }
  837. if (changed) {
  838. broadcastSessions()
  839. saveSessions() // Persist state changes
  840. }
  841. })
  842. }
  843. /**
  844. * Check for stale "working" sessions and transition them to idle
  845. * This is a failsafe for missed stop events
  846. */
  847. function checkWorkingTimeout(): void {
  848. const now = Date.now()
  849. let changed = false
  850. for (const session of managedSessions.values()) {
  851. if (session.status === 'working') {
  852. const timeSinceActivity = now - session.lastActivity
  853. if (timeSinceActivity > WORKING_TIMEOUT_MS) {
  854. log(`Session "${session.name}" timed out after ${Math.round(timeSinceActivity / 1000)}s of no activity`)
  855. session.status = 'idle'
  856. session.currentTool = undefined
  857. changed = true
  858. }
  859. }
  860. }
  861. if (changed) {
  862. broadcastSessions()
  863. saveSessions()
  864. }
  865. }
  866. /**
  867. * Save sessions to disk for persistence across restarts
  868. */
  869. function saveSessions(): void {
  870. try {
  871. const data = {
  872. sessions: Array.from(managedSessions.values()),
  873. claudeToManagedMap: Array.from(claudeToManagedMap.entries()),
  874. sessionCounter,
  875. }
  876. writeFileSync(SESSIONS_FILE, JSON.stringify(data, null, 2))
  877. debug(`Saved ${managedSessions.size} sessions to ${SESSIONS_FILE}`)
  878. } catch (e) {
  879. console.error('Failed to save sessions:', e)
  880. }
  881. }
  882. /**
  883. * Load sessions from disk on startup
  884. */
  885. function loadSessions(): void {
  886. if (!existsSync(SESSIONS_FILE)) {
  887. debug('No saved sessions file found')
  888. return
  889. }
  890. try {
  891. const content = readFileSync(SESSIONS_FILE, 'utf-8')
  892. const data = JSON.parse(content)
  893. // Restore sessions
  894. if (Array.isArray(data.sessions)) {
  895. for (const session of data.sessions) {
  896. // Mark all as offline initially - health check will update
  897. session.status = 'offline'
  898. session.currentTool = undefined
  899. managedSessions.set(session.id, session)
  900. // Track git status if session has a cwd
  901. if (session.cwd) {
  902. gitStatusManager.track(session.id, session.cwd)
  903. }
  904. }
  905. }
  906. // Restore linking map
  907. if (Array.isArray(data.claudeToManagedMap)) {
  908. for (const [claudeId, managedId] of data.claudeToManagedMap) {
  909. claudeToManagedMap.set(claudeId, managedId)
  910. }
  911. }
  912. // Restore counter
  913. if (typeof data.sessionCounter === 'number') {
  914. sessionCounter = data.sessionCounter
  915. }
  916. log(`Loaded ${managedSessions.size} sessions from ${SESSIONS_FILE}`)
  917. } catch (e) {
  918. console.error('Failed to load sessions:', e)
  919. }
  920. }
  921. /**
  922. * Broadcast current sessions to all clients
  923. */
  924. function broadcastSessions(): void {
  925. broadcast({
  926. type: 'sessions',
  927. payload: getSessions(),
  928. })
  929. }
  930. // ============================================================================
  931. // Text Tiles (Grid Labels)
  932. // ============================================================================
  933. /**
  934. * Get all text tiles
  935. */
  936. function getTiles(): TextTile[] {
  937. return Array.from(textTiles.values())
  938. }
  939. /**
  940. * Save text tiles to disk
  941. */
  942. function saveTiles(): void {
  943. try {
  944. const data = Array.from(textTiles.values())
  945. writeFileSync(TILES_FILE, JSON.stringify(data, null, 2))
  946. debug(`Saved ${textTiles.size} tiles to ${TILES_FILE}`)
  947. } catch (e) {
  948. console.error('Failed to save tiles:', e)
  949. }
  950. }
  951. /**
  952. * Load text tiles from disk
  953. */
  954. function loadTiles(): void {
  955. if (!existsSync(TILES_FILE)) {
  956. debug('No saved tiles file found')
  957. return
  958. }
  959. try {
  960. const content = readFileSync(TILES_FILE, 'utf-8')
  961. const data = JSON.parse(content) as TextTile[]
  962. for (const tile of data) {
  963. textTiles.set(tile.id, tile)
  964. }
  965. log(`Loaded ${textTiles.size} tiles from ${TILES_FILE}`)
  966. } catch (e) {
  967. console.error('Failed to load tiles:', e)
  968. }
  969. }
  970. /**
  971. * Broadcast text tiles to all clients
  972. */
  973. function broadcastTiles(): void {
  974. broadcast({
  975. type: 'text_tiles',
  976. payload: getTiles(),
  977. })
  978. }
  979. // ============================================================================
  980. // Voice Transcription (Deepgram)
  981. // ============================================================================
  982. /**
  983. * Start a voice transcription session for a WebSocket client
  984. */
  985. function startVoiceSession(ws: WebSocket): boolean {
  986. if (!deepgramApiKey) {
  987. ws.send(JSON.stringify({ type: 'voice_error', payload: { error: 'Voice input not configured' } }))
  988. return false
  989. }
  990. // Clean up any existing session
  991. stopVoiceSession(ws)
  992. try {
  993. const deepgram = createClient(deepgramApiKey)
  994. const connection = deepgram.listen.live({
  995. model: DEEPGRAM_MODEL,
  996. language: DEEPGRAM_LANGUAGE,
  997. smart_format: true,
  998. interim_results: true,
  999. utterance_end_ms: 1000,
  1000. vad_events: true,
  1001. encoding: 'linear16',
  1002. sample_rate: 16000,
  1003. })
  1004. connection.on(LiveTranscriptionEvents.Open, () => {
  1005. ws.send(JSON.stringify({ type: 'voice_ready', payload: {} }))
  1006. })
  1007. connection.on(LiveTranscriptionEvents.Transcript, (data) => {
  1008. const transcript = data.channel?.alternatives?.[0]?.transcript
  1009. if (transcript) {
  1010. ws.send(JSON.stringify({
  1011. type: 'voice_transcript',
  1012. payload: { transcript, isFinal: data.is_final }
  1013. }))
  1014. }
  1015. })
  1016. connection.on(LiveTranscriptionEvents.UtteranceEnd, () => {
  1017. ws.send(JSON.stringify({ type: 'voice_utterance_end', payload: {} }))
  1018. })
  1019. connection.on(LiveTranscriptionEvents.Error, (error) => {
  1020. log(`Deepgram error: ${error}`)
  1021. ws.send(JSON.stringify({ type: 'voice_error', payload: { error: String(error) } }))
  1022. })
  1023. connection.on(LiveTranscriptionEvents.Close, () => {
  1024. voiceSessions.delete(ws)
  1025. })
  1026. voiceSessions.set(ws, connection)
  1027. debug('Voice session started')
  1028. return true
  1029. } catch (e) {
  1030. log(`Failed to start voice session: ${e}`)
  1031. ws.send(JSON.stringify({ type: 'voice_error', payload: { error: String(e) } }))
  1032. return false
  1033. }
  1034. }
  1035. /**
  1036. * Stop a voice transcription session
  1037. */
  1038. function stopVoiceSession(ws: WebSocket): void {
  1039. const connection = voiceSessions.get(ws)
  1040. if (connection) {
  1041. try {
  1042. connection.requestClose()
  1043. } catch (e) {
  1044. // Ignore close errors
  1045. }
  1046. voiceSessions.delete(ws)
  1047. debug('Voice session stopped')
  1048. }
  1049. }
  1050. /**
  1051. * Send audio data to Deepgram for transcription
  1052. */
  1053. function sendVoiceAudio(ws: WebSocket, audioData: Buffer): void {
  1054. const connection = voiceSessions.get(ws)
  1055. if (!connection) return
  1056. try {
  1057. // Convert Node.js Buffer to ArrayBuffer for Deepgram SDK
  1058. const arrayBuffer = audioData.buffer.slice(
  1059. audioData.byteOffset,
  1060. audioData.byteOffset + audioData.byteLength
  1061. )
  1062. connection.send(arrayBuffer)
  1063. } catch (e) {
  1064. debug(`Error sending audio: ${e}`)
  1065. }
  1066. }
  1067. /**
  1068. * Link a Claude Code session ID to a managed session
  1069. */
  1070. function linkClaudeSession(claudeSessionId: string, managedSessionId: string): void {
  1071. claudeToManagedMap.set(claudeSessionId, managedSessionId)
  1072. }
  1073. /**
  1074. * Find managed session by Claude Code session ID
  1075. */
  1076. function findManagedSession(claudeSessionId: string): ManagedSession | undefined {
  1077. const managedId = claudeToManagedMap.get(claudeSessionId)
  1078. if (managedId) {
  1079. return managedSessions.get(managedId)
  1080. }
  1081. return undefined
  1082. }
  1083. // ============================================================================
  1084. // Event Processing
  1085. // ============================================================================
  1086. function processEvent(event: ClaudeEvent): ClaudeEvent {
  1087. // Track pre_tool_use for duration calculation
  1088. if (event.type === 'pre_tool_use') {
  1089. const preEvent = event as PreToolUseEvent
  1090. pendingToolUses.set(preEvent.toolUseId, preEvent)
  1091. debug(`Tracking tool use: ${preEvent.tool} (${preEvent.toolUseId})`)
  1092. }
  1093. // Calculate duration for post_tool_use
  1094. if (event.type === 'post_tool_use') {
  1095. const postEvent = event as PostToolUseEvent
  1096. const preEvent = pendingToolUses.get(postEvent.toolUseId)
  1097. if (preEvent) {
  1098. postEvent.duration = postEvent.timestamp - preEvent.timestamp
  1099. pendingToolUses.delete(postEvent.toolUseId)
  1100. debug(`Tool ${postEvent.tool} took ${postEvent.duration}ms`)
  1101. }
  1102. }
  1103. return event
  1104. }
  1105. function addEvent(event: ClaudeEvent) {
  1106. // Skip duplicates (hook writes to file AND posts to server)
  1107. if (seenEventIds.has(event.id)) {
  1108. debug(`Skipping duplicate event: ${event.id}`)
  1109. return
  1110. }
  1111. seenEventIds.add(event.id)
  1112. // Trim old IDs to prevent memory leak (keep last 2x MAX_EVENTS)
  1113. if (seenEventIds.size > MAX_EVENTS * 2) {
  1114. const idsToKeep = [...seenEventIds].slice(-MAX_EVENTS)
  1115. seenEventIds.clear()
  1116. idsToKeep.forEach(id => seenEventIds.add(id))
  1117. }
  1118. const processed = processEvent(event)
  1119. events.push(processed)
  1120. // Trim old events if over limit
  1121. if (events.length > MAX_EVENTS) {
  1122. events.splice(0, events.length - MAX_EVENTS)
  1123. }
  1124. // Update managed session status based on event
  1125. const managedSession = findManagedSession(event.sessionId)
  1126. if (managedSession) {
  1127. const prevStatus = managedSession.status
  1128. managedSession.lastActivity = Date.now() // Use current time for accurate timeout tracking
  1129. managedSession.cwd = event.cwd
  1130. // Update status based on event type
  1131. switch (event.type) {
  1132. case 'pre_tool_use':
  1133. managedSession.status = 'working'
  1134. managedSession.currentTool = (event as PreToolUseEvent).tool
  1135. break
  1136. case 'post_tool_use':
  1137. // Tool completed - update activity time but stay "working"
  1138. // (Claude might be using more tools, stop event marks idle)
  1139. managedSession.currentTool = undefined
  1140. break
  1141. case 'user_prompt_submit':
  1142. // User submitted prompt - Claude is now processing
  1143. managedSession.status = 'working'
  1144. managedSession.currentTool = undefined
  1145. break
  1146. case 'stop':
  1147. case 'session_end':
  1148. managedSession.status = 'idle'
  1149. managedSession.currentTool = undefined
  1150. break
  1151. }
  1152. // Broadcast and persist if status changed
  1153. if (managedSession.status !== prevStatus) {
  1154. broadcastSessions()
  1155. saveSessions()
  1156. }
  1157. }
  1158. // Broadcast to all clients
  1159. broadcast({ type: 'event', payload: processed })
  1160. }
  1161. // ============================================================================
  1162. // File Watching
  1163. // ============================================================================
  1164. function loadEventsFromFile() {
  1165. if (!existsSync(EVENTS_FILE)) {
  1166. debug(`Events file not found: ${EVENTS_FILE}`)
  1167. return
  1168. }
  1169. const content = readFileSync(EVENTS_FILE, 'utf-8')
  1170. const lines = content.trim().split('\n').filter(Boolean)
  1171. for (const line of lines) {
  1172. try {
  1173. const event = JSON.parse(line) as ClaudeEvent
  1174. processEvent(event)
  1175. events.push(event)
  1176. } catch (e) {
  1177. debug(`Failed to parse event line: ${line}`)
  1178. }
  1179. }
  1180. lastFileSize = content.length
  1181. log(`Loaded ${events.length} events from file`)
  1182. }
  1183. function watchEventsFile() {
  1184. // Ensure directory exists
  1185. const dir = dirname(EVENTS_FILE)
  1186. if (!existsSync(dir)) {
  1187. mkdirSync(dir, { recursive: true })
  1188. }
  1189. // Create file if it doesn't exist
  1190. if (!existsSync(EVENTS_FILE)) {
  1191. appendFileSync(EVENTS_FILE, '')
  1192. }
  1193. const watcher = watch(EVENTS_FILE, {
  1194. persistent: true,
  1195. usePolling: true,
  1196. interval: 100,
  1197. })
  1198. watcher.on('change', () => {
  1199. try {
  1200. const content = readFileSync(EVENTS_FILE, 'utf-8')
  1201. // Only process new content
  1202. if (content.length > lastFileSize) {
  1203. const newContent = content.slice(lastFileSize)
  1204. const newLines = newContent.trim().split('\n').filter(Boolean)
  1205. for (const line of newLines) {
  1206. try {
  1207. const event = JSON.parse(line) as ClaudeEvent
  1208. addEvent(event)
  1209. debug(`New event from file: ${event.type}`)
  1210. } catch (e) {
  1211. debug(`Failed to parse new event: ${line}`)
  1212. }
  1213. }
  1214. lastFileSize = content.length
  1215. }
  1216. } catch (e) {
  1217. debug(`Error reading events file: ${e}`)
  1218. }
  1219. })
  1220. log(`Watching events file: ${EVENTS_FILE}`)
  1221. }
  1222. // ============================================================================
  1223. // WebSocket
  1224. // ============================================================================
  1225. function broadcast(message: ServerMessage) {
  1226. const data = JSON.stringify(message)
  1227. for (const client of clients) {
  1228. if (client.readyState === WebSocket.OPEN) {
  1229. client.send(data)
  1230. }
  1231. }
  1232. }
  1233. function handleClientMessage(ws: WebSocket, message: ClientMessage) {
  1234. switch (message.type) {
  1235. case 'subscribe':
  1236. debug('Client subscribed')
  1237. break
  1238. case 'get_history': {
  1239. const limit = message.payload?.limit ?? 100
  1240. const history = events.slice(-limit)
  1241. const response: ServerMessage = { type: 'history', payload: history }
  1242. ws.send(JSON.stringify(response))
  1243. debug(`Sent ${history.length} historical events`)
  1244. break
  1245. }
  1246. case 'ping':
  1247. // Just acknowledge, no response needed
  1248. break
  1249. case 'voice_start':
  1250. startVoiceSession(ws)
  1251. break
  1252. case 'voice_stop':
  1253. stopVoiceSession(ws)
  1254. break
  1255. case 'permission_response': {
  1256. const { sessionId, response } = message.payload
  1257. sendPermissionResponse(sessionId, response)
  1258. break
  1259. }
  1260. default:
  1261. debug(`Unknown message type: ${(message as { type: string }).type}`)
  1262. }
  1263. }
  1264. // ============================================================================
  1265. // HTTP Server (for hook notifications)
  1266. // ============================================================================
  1267. function handleHttpRequest(req: IncomingMessage, res: ServerResponse) {
  1268. const origin = req.headers.origin
  1269. // CORS headers - only allow specific origins
  1270. if (origin && isOriginAllowed(origin)) {
  1271. res.setHeader('Access-Control-Allow-Origin', origin)
  1272. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
  1273. res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
  1274. }
  1275. if (req.method === 'OPTIONS') {
  1276. // Preflight: reject if origin not allowed
  1277. if (!origin || !isOriginAllowed(origin)) {
  1278. res.writeHead(403)
  1279. res.end()
  1280. return
  1281. }
  1282. res.writeHead(204)
  1283. res.end()
  1284. return
  1285. }
  1286. if (req.method === 'POST' && req.url === '/event') {
  1287. collectRequestBody(req).then(body => {
  1288. try {
  1289. const event = JSON.parse(body) as ClaudeEvent
  1290. addEvent(event)
  1291. debug(`Received event via HTTP: ${event.type}`)
  1292. res.writeHead(200, { 'Content-Type': 'application/json' })
  1293. res.end(JSON.stringify({ ok: true }))
  1294. } catch (e) {
  1295. debug(`Failed to parse HTTP event: ${e}`)
  1296. res.writeHead(400, { 'Content-Type': 'application/json' })
  1297. res.end(JSON.stringify({ error: 'Invalid JSON' }))
  1298. }
  1299. }).catch(() => {
  1300. res.writeHead(413, { 'Content-Type': 'application/json' })
  1301. res.end(JSON.stringify({ error: 'Request body too large' }))
  1302. })
  1303. return
  1304. }
  1305. // Health check
  1306. if (req.method === 'GET' && req.url === '/health') {
  1307. res.writeHead(200, { 'Content-Type': 'application/json' })
  1308. res.end(JSON.stringify({
  1309. ok: true,
  1310. version: VERSION,
  1311. clients: clients.size,
  1312. events: events.length,
  1313. voiceEnabled: !!deepgramApiKey,
  1314. }))
  1315. return
  1316. }
  1317. // Config (username, etc)
  1318. if (req.method === 'GET' && req.url === '/config') {
  1319. const username = process.env.USER || process.env.USERNAME || 'claude-user'
  1320. const host = hostname()
  1321. res.writeHead(200, { 'Content-Type': 'application/json' })
  1322. res.end(JSON.stringify({
  1323. username,
  1324. hostname: host,
  1325. tmuxSession: TMUX_SESSION,
  1326. }))
  1327. return
  1328. }
  1329. // Stats
  1330. if (req.method === 'GET' && req.url === '/stats') {
  1331. const toolCounts: Record<string, number> = {}
  1332. const toolDurations: Record<string, number[]> = {}
  1333. for (const event of events) {
  1334. if (event.type === 'post_tool_use') {
  1335. const e = event as PostToolUseEvent
  1336. toolCounts[e.tool] = (toolCounts[e.tool] ?? 0) + 1
  1337. if (e.duration !== undefined) {
  1338. toolDurations[e.tool] = toolDurations[e.tool] ?? []
  1339. toolDurations[e.tool].push(e.duration)
  1340. }
  1341. }
  1342. }
  1343. const avgDurations: Record<string, number> = {}
  1344. for (const [tool, durations] of Object.entries(toolDurations)) {
  1345. avgDurations[tool] = Math.round(
  1346. durations.reduce((a, b) => a + b, 0) / durations.length
  1347. )
  1348. }
  1349. // Collect token data
  1350. const tokens: Record<string, { current: number; cumulative: number }> = {}
  1351. for (const [session, data] of sessionTokens) {
  1352. tokens[session] = { current: data.lastSeen, cumulative: data.cumulative }
  1353. }
  1354. res.writeHead(200, { 'Content-Type': 'application/json' })
  1355. res.end(JSON.stringify({
  1356. totalEvents: events.length,
  1357. toolCounts,
  1358. avgDurations,
  1359. tokens,
  1360. }))
  1361. return
  1362. }
  1363. // Submit prompt from browser
  1364. if (req.method === 'POST' && req.url === '/prompt') {
  1365. collectRequestBody(req).then(body => {
  1366. try {
  1367. const { prompt, send } = JSON.parse(body) as { prompt: string; send?: boolean }
  1368. if (!prompt || typeof prompt !== 'string') {
  1369. res.writeHead(400, { 'Content-Type': 'application/json' })
  1370. res.end(JSON.stringify({ error: 'Prompt is required' }))
  1371. return
  1372. }
  1373. // Write prompt to file
  1374. const dir = dirname(PENDING_PROMPT_FILE)
  1375. if (!existsSync(dir)) {
  1376. mkdirSync(dir, { recursive: true })
  1377. }
  1378. writeFileSync(PENDING_PROMPT_FILE, prompt, 'utf-8')
  1379. log(`Prompt saved: ${prompt.slice(0, 50)}...`)
  1380. // If send=true, inject into tmux session
  1381. if (send) {
  1382. // Use safe helper to prevent command injection
  1383. sendToTmuxSafe(TMUX_SESSION, prompt)
  1384. .then(() => {
  1385. log(`Prompt sent to tmux session: ${TMUX_SESSION}`)
  1386. res.writeHead(200, { 'Content-Type': 'application/json' })
  1387. res.end(JSON.stringify({ ok: true, saved: PENDING_PROMPT_FILE, sent: true }))
  1388. })
  1389. .catch((error) => {
  1390. log(`tmux send failed: ${error.message}`)
  1391. res.writeHead(200, { 'Content-Type': 'application/json' })
  1392. res.end(JSON.stringify({
  1393. ok: true,
  1394. saved: PENDING_PROMPT_FILE,
  1395. sent: false,
  1396. tmuxError: error.message
  1397. }))
  1398. })
  1399. return
  1400. }
  1401. res.writeHead(200, { 'Content-Type': 'application/json' })
  1402. res.end(JSON.stringify({ ok: true, saved: PENDING_PROMPT_FILE }))
  1403. } catch (e) {
  1404. debug(`Failed to save prompt: ${e}`)
  1405. res.writeHead(400, { 'Content-Type': 'application/json' })
  1406. res.end(JSON.stringify({ error: 'Invalid JSON' }))
  1407. }
  1408. }).catch(() => {
  1409. res.writeHead(413, { 'Content-Type': 'application/json' })
  1410. res.end(JSON.stringify({ error: 'Request body too large' }))
  1411. })
  1412. return
  1413. }
  1414. // Get pending prompt
  1415. if (req.method === 'GET' && req.url === '/prompt') {
  1416. if (existsSync(PENDING_PROMPT_FILE)) {
  1417. const prompt = readFileSync(PENDING_PROMPT_FILE, 'utf-8')
  1418. res.writeHead(200, { 'Content-Type': 'application/json' })
  1419. res.end(JSON.stringify({ prompt, file: PENDING_PROMPT_FILE }))
  1420. } else {
  1421. res.writeHead(200, { 'Content-Type': 'application/json' })
  1422. res.end(JSON.stringify({ prompt: null }))
  1423. }
  1424. return
  1425. }
  1426. // Clear pending prompt
  1427. if (req.method === 'DELETE' && req.url === '/prompt') {
  1428. if (existsSync(PENDING_PROMPT_FILE)) {
  1429. unlinkSync(PENDING_PROMPT_FILE)
  1430. log('Pending prompt cleared')
  1431. }
  1432. res.writeHead(200, { 'Content-Type': 'application/json' })
  1433. res.end(JSON.stringify({ ok: true }))
  1434. return
  1435. }
  1436. // Get tmux output (Claude's responses)
  1437. if (req.method === 'GET' && req.url === '/tmux-output') {
  1438. try {
  1439. validateTmuxSession(TMUX_SESSION)
  1440. } catch {
  1441. res.writeHead(400, { 'Content-Type': 'application/json' })
  1442. res.end(JSON.stringify({ ok: false, error: 'Invalid tmux session name', output: '' }))
  1443. return
  1444. }
  1445. // Capture last 100 lines from tmux pane
  1446. execFile('tmux', ['capture-pane', '-t', TMUX_SESSION, '-p', '-S', '-100'], { ...EXEC_OPTIONS, maxBuffer: 1024 * 1024 }, (error, stdout) => {
  1447. if (error) {
  1448. res.writeHead(200, { 'Content-Type': 'application/json' })
  1449. res.end(JSON.stringify({ ok: false, error: error.message, output: '' }))
  1450. return
  1451. }
  1452. res.writeHead(200, { 'Content-Type': 'application/json' })
  1453. res.end(JSON.stringify({ ok: true, output: stdout }))
  1454. })
  1455. return
  1456. }
  1457. // Cancel - send Ctrl+C to tmux (legacy, for backwards compat)
  1458. if (req.method === 'POST' && req.url === '/cancel') {
  1459. try {
  1460. validateTmuxSession(TMUX_SESSION)
  1461. } catch {
  1462. res.writeHead(400, { 'Content-Type': 'application/json' })
  1463. res.end(JSON.stringify({ ok: false, error: 'Invalid tmux session name' }))
  1464. return
  1465. }
  1466. execFile('tmux', ['send-keys', '-t', TMUX_SESSION, 'C-c'], EXEC_OPTIONS, (error) => {
  1467. res.writeHead(200, { 'Content-Type': 'application/json' })
  1468. if (error) {
  1469. log(`Cancel failed: ${error.message}`)
  1470. res.end(JSON.stringify({ ok: false, error: error.message }))
  1471. } else {
  1472. log(`Sent Ctrl+C to tmux session: ${TMUX_SESSION}`)
  1473. res.end(JSON.stringify({ ok: true }))
  1474. }
  1475. })
  1476. return
  1477. }
  1478. // ============================================================================
  1479. // Session Management Endpoints
  1480. // ============================================================================
  1481. // Get server info (cwd, etc.)
  1482. if (req.method === 'GET' && req.url === '/info') {
  1483. res.writeHead(200, { 'Content-Type': 'application/json' })
  1484. res.end(JSON.stringify({ ok: true, cwd: process.cwd() }))
  1485. return
  1486. }
  1487. // List all sessions
  1488. if (req.method === 'GET' && req.url === '/sessions') {
  1489. res.writeHead(200, { 'Content-Type': 'application/json' })
  1490. res.end(JSON.stringify({ ok: true, sessions: getSessions() }))
  1491. return
  1492. }
  1493. // Force refresh sessions (trigger health check)
  1494. if (req.method === 'POST' && req.url === '/sessions/refresh') {
  1495. log('Manual session refresh requested')
  1496. checkSessionHealth()
  1497. // Return current sessions (health check updates async, but we give immediate response)
  1498. res.writeHead(200, { 'Content-Type': 'application/json' })
  1499. res.end(JSON.stringify({ ok: true, sessions: getSessions() }))
  1500. return
  1501. }
  1502. // Create a new session
  1503. if (req.method === 'POST' && req.url === '/sessions') {
  1504. collectRequestBody(req).then(async body => {
  1505. try {
  1506. const options = body ? JSON.parse(body) as CreateSessionRequest : {}
  1507. const session = await createSession(options)
  1508. res.writeHead(201, { 'Content-Type': 'application/json' })
  1509. res.end(JSON.stringify({ ok: true, session }))
  1510. } catch (e) {
  1511. res.writeHead(500, { 'Content-Type': 'application/json' })
  1512. res.end(JSON.stringify({ ok: false, error: (e as Error).message }))
  1513. }
  1514. }).catch(() => {
  1515. res.writeHead(413, { 'Content-Type': 'application/json' })
  1516. res.end(JSON.stringify({ error: 'Request body too large' }))
  1517. })
  1518. return
  1519. }
  1520. // ============================================================================
  1521. // Projects API (known directories for autocomplete)
  1522. // ============================================================================
  1523. // List all known projects
  1524. if (req.method === 'GET' && req.url === '/projects') {
  1525. res.writeHead(200, { 'Content-Type': 'application/json' })
  1526. res.end(JSON.stringify({ ok: true, projects: projectsManager.getProjects() }))
  1527. return
  1528. }
  1529. // Autocomplete path
  1530. if (req.method === 'GET' && req.url?.startsWith('/projects/autocomplete')) {
  1531. const url = new URL(req.url, `http://localhost:${PORT}`)
  1532. const query = url.searchParams.get('q') || ''
  1533. const results = projectsManager.autocomplete(query)
  1534. res.writeHead(200, { 'Content-Type': 'application/json' })
  1535. res.end(JSON.stringify({ ok: true, results }))
  1536. return
  1537. }
  1538. // Remove a project from the list
  1539. if (req.method === 'DELETE' && req.url?.startsWith('/projects/')) {
  1540. const path = decodeURIComponent(req.url.slice('/projects/'.length))
  1541. projectsManager.removeProject(path)
  1542. res.writeHead(200, { 'Content-Type': 'application/json' })
  1543. res.end(JSON.stringify({ ok: true }))
  1544. return
  1545. }
  1546. // Session-specific endpoints: /sessions/:id
  1547. const sessionMatch = req.url?.match(/^\/sessions\/([a-f0-9-]+)(?:\/(.+))?$/)
  1548. if (sessionMatch) {
  1549. const sessionId = sessionMatch[1]
  1550. const action = sessionMatch[2] // e.g., "prompt", "cancel"
  1551. // GET /sessions/:id - Get session details
  1552. if (req.method === 'GET' && !action) {
  1553. const session = getSession(sessionId)
  1554. if (session) {
  1555. res.writeHead(200, { 'Content-Type': 'application/json' })
  1556. res.end(JSON.stringify({ ok: true, session }))
  1557. } else {
  1558. res.writeHead(404, { 'Content-Type': 'application/json' })
  1559. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1560. }
  1561. return
  1562. }
  1563. // PATCH /sessions/:id - Update session (rename)
  1564. if (req.method === 'PATCH' && !action) {
  1565. collectRequestBody(req).then(body => {
  1566. try {
  1567. const updates = JSON.parse(body) as UpdateSessionRequest
  1568. const session = updateSession(sessionId, updates)
  1569. if (session) {
  1570. res.writeHead(200, { 'Content-Type': 'application/json' })
  1571. res.end(JSON.stringify({ ok: true, session }))
  1572. } else {
  1573. res.writeHead(404, { 'Content-Type': 'application/json' })
  1574. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1575. }
  1576. } catch (e) {
  1577. res.writeHead(400, { 'Content-Type': 'application/json' })
  1578. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1579. }
  1580. }).catch(() => {
  1581. res.writeHead(413, { 'Content-Type': 'application/json' })
  1582. res.end(JSON.stringify({ error: 'Request body too large' }))
  1583. })
  1584. return
  1585. }
  1586. // DELETE /sessions/:id - Kill session
  1587. if (req.method === 'DELETE' && !action) {
  1588. deleteSession(sessionId).then((deleted) => {
  1589. if (deleted) {
  1590. res.writeHead(200, { 'Content-Type': 'application/json' })
  1591. res.end(JSON.stringify({ ok: true }))
  1592. } else {
  1593. res.writeHead(404, { 'Content-Type': 'application/json' })
  1594. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1595. }
  1596. })
  1597. return
  1598. }
  1599. // POST /sessions/:id/prompt - Send prompt to specific session
  1600. if (req.method === 'POST' && action === 'prompt') {
  1601. collectRequestBody(req).then(async body => {
  1602. try {
  1603. const { prompt } = JSON.parse(body) as SessionPromptRequest
  1604. if (!prompt) {
  1605. res.writeHead(400, { 'Content-Type': 'application/json' })
  1606. res.end(JSON.stringify({ ok: false, error: 'Prompt is required' }))
  1607. return
  1608. }
  1609. const result = await sendPromptToSession(sessionId, prompt)
  1610. res.writeHead(result.ok ? 200 : 404, { 'Content-Type': 'application/json' })
  1611. res.end(JSON.stringify(result))
  1612. } catch (e) {
  1613. res.writeHead(400, { 'Content-Type': 'application/json' })
  1614. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1615. }
  1616. }).catch(() => {
  1617. res.writeHead(413, { 'Content-Type': 'application/json' })
  1618. res.end(JSON.stringify({ error: 'Request body too large' }))
  1619. })
  1620. return
  1621. }
  1622. // POST /sessions/:id/cancel - Send Ctrl+C to specific session
  1623. if (req.method === 'POST' && action === 'cancel') {
  1624. const session = getSession(sessionId)
  1625. if (!session) {
  1626. res.writeHead(404, { 'Content-Type': 'application/json' })
  1627. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1628. return
  1629. }
  1630. try {
  1631. validateTmuxSession(session.tmuxSession)
  1632. } catch {
  1633. res.writeHead(400, { 'Content-Type': 'application/json' })
  1634. res.end(JSON.stringify({ ok: false, error: 'Invalid tmux session name' }))
  1635. return
  1636. }
  1637. execFile('tmux', ['send-keys', '-t', session.tmuxSession, 'C-c'], EXEC_OPTIONS, (error) => {
  1638. res.writeHead(200, { 'Content-Type': 'application/json' })
  1639. if (error) {
  1640. res.end(JSON.stringify({ ok: false, error: error.message }))
  1641. } else {
  1642. log(`Sent Ctrl+C to ${session.name}`)
  1643. res.end(JSON.stringify({ ok: true }))
  1644. }
  1645. })
  1646. return
  1647. }
  1648. // POST /sessions/:id/permission - Respond to a permission prompt
  1649. if (req.method === 'POST' && action === 'permission') {
  1650. const session = getSession(sessionId)
  1651. if (!session) {
  1652. res.writeHead(404, { 'Content-Type': 'application/json' })
  1653. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1654. return
  1655. }
  1656. collectRequestBody(req).then(body => {
  1657. try {
  1658. const { response } = JSON.parse(body) as { response: string }
  1659. if (!response) {
  1660. res.writeHead(400, { 'Content-Type': 'application/json' })
  1661. res.end(JSON.stringify({ ok: false, error: 'Missing response field' }))
  1662. return
  1663. }
  1664. sendPermissionResponse(sessionId, response)
  1665. res.writeHead(200, { 'Content-Type': 'application/json' })
  1666. res.end(JSON.stringify({ ok: true }))
  1667. } catch (e) {
  1668. res.writeHead(400, { 'Content-Type': 'application/json' })
  1669. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1670. }
  1671. }).catch(() => {
  1672. res.writeHead(413, { 'Content-Type': 'application/json' })
  1673. res.end(JSON.stringify({ error: 'Request body too large' }))
  1674. })
  1675. return
  1676. }
  1677. // POST /sessions/:id/restart - Restart an offline session
  1678. if (req.method === 'POST' && action === 'restart') {
  1679. const session = getSession(sessionId)
  1680. if (!session) {
  1681. res.writeHead(404, { 'Content-Type': 'application/json' })
  1682. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1683. return
  1684. }
  1685. // Validate inputs to prevent command injection
  1686. try {
  1687. validateTmuxSession(session.tmuxSession)
  1688. } catch {
  1689. res.writeHead(400, { 'Content-Type': 'application/json' })
  1690. res.end(JSON.stringify({ ok: false, error: 'Invalid tmux session name' }))
  1691. return
  1692. }
  1693. let cwd: string
  1694. try {
  1695. cwd = validateDirectoryPath(session.cwd || process.cwd())
  1696. } catch (err) {
  1697. res.writeHead(400, { 'Content-Type': 'application/json' })
  1698. res.end(JSON.stringify({ ok: false, error: `Invalid directory: ${err instanceof Error ? err.message : err}` }))
  1699. return
  1700. }
  1701. // Kill existing tmux session if it exists (ignore errors)
  1702. execFile('tmux', ['kill-session', '-t', session.tmuxSession], EXEC_OPTIONS, () => {
  1703. // Respawn tmux session with claude using execFile
  1704. execFile('tmux', [
  1705. 'new-session',
  1706. '-d',
  1707. '-s', session.tmuxSession,
  1708. '-c', cwd,
  1709. `PATH=${EXEC_PATH} claude -c --permission-mode=bypassPermissions --dangerously-skip-permissions`
  1710. ], EXEC_OPTIONS, (error) => {
  1711. if (error) {
  1712. res.writeHead(500, { 'Content-Type': 'application/json' })
  1713. res.end(JSON.stringify({ ok: false, error: `Failed to restart: ${error.message}` }))
  1714. return
  1715. }
  1716. // Update session state
  1717. session.status = 'idle'
  1718. session.lastActivity = Date.now()
  1719. session.claudeSessionId = undefined // Will be re-linked when events come in
  1720. session.currentTool = undefined
  1721. // Clear old linking
  1722. for (const [claudeId, managedId] of claudeToManagedMap) {
  1723. if (managedId === session.id) {
  1724. claudeToManagedMap.delete(claudeId)
  1725. }
  1726. }
  1727. log(`Restarted session: ${session.name} (${session.id.slice(0, 8)})`)
  1728. broadcastSessions()
  1729. saveSessions()
  1730. res.writeHead(200, { 'Content-Type': 'application/json' })
  1731. res.end(JSON.stringify({ ok: true, session }))
  1732. })
  1733. })
  1734. return
  1735. }
  1736. // POST /sessions/:id/link - Link Claude session ID to managed session
  1737. if (req.method === 'POST' && action === 'link') {
  1738. collectRequestBody(req).then(body => {
  1739. try {
  1740. const { claudeSessionId } = JSON.parse(body) as { claudeSessionId: string }
  1741. if (!claudeSessionId) {
  1742. res.writeHead(400, { 'Content-Type': 'application/json' })
  1743. res.end(JSON.stringify({ ok: false, error: 'claudeSessionId is required' }))
  1744. return
  1745. }
  1746. const session = getSession(sessionId)
  1747. if (!session) {
  1748. res.writeHead(404, { 'Content-Type': 'application/json' })
  1749. res.end(JSON.stringify({ ok: false, error: 'Session not found' }))
  1750. return
  1751. }
  1752. linkClaudeSession(claudeSessionId, sessionId)
  1753. session.claudeSessionId = claudeSessionId
  1754. log(`Linked Claude session ${claudeSessionId.slice(0, 8)} to ${session.name}`)
  1755. broadcastSessions()
  1756. saveSessions()
  1757. res.writeHead(200, { 'Content-Type': 'application/json' })
  1758. res.end(JSON.stringify({ ok: true, session }))
  1759. } catch (e) {
  1760. res.writeHead(400, { 'Content-Type': 'application/json' })
  1761. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1762. }
  1763. }).catch(() => {
  1764. res.writeHead(413, { 'Content-Type': 'application/json' })
  1765. res.end(JSON.stringify({ error: 'Request body too large' }))
  1766. })
  1767. return
  1768. }
  1769. }
  1770. // -------------------------------------------------------------------------
  1771. // Text Tiles API
  1772. // -------------------------------------------------------------------------
  1773. // GET /tiles - List all text tiles
  1774. if (req.method === 'GET' && req.url === '/tiles') {
  1775. res.writeHead(200, { 'Content-Type': 'application/json' })
  1776. res.end(JSON.stringify({ ok: true, tiles: getTiles() }))
  1777. return
  1778. }
  1779. // POST /tiles - Create a new text tile
  1780. if (req.method === 'POST' && req.url === '/tiles') {
  1781. collectRequestBody(req).then(body => {
  1782. try {
  1783. const data = JSON.parse(body) as CreateTextTileRequest
  1784. if (!data.text || !data.position) {
  1785. res.writeHead(400, { 'Content-Type': 'application/json' })
  1786. res.end(JSON.stringify({ ok: false, error: 'Missing text or position' }))
  1787. return
  1788. }
  1789. const tile: TextTile = {
  1790. id: crypto.randomUUID(),
  1791. text: data.text,
  1792. position: data.position,
  1793. color: data.color,
  1794. createdAt: Date.now(),
  1795. }
  1796. textTiles.set(tile.id, tile)
  1797. saveTiles()
  1798. broadcastTiles()
  1799. log(`Created text tile: "${tile.text}" at (${tile.position.q}, ${tile.position.r})`)
  1800. res.writeHead(201, { 'Content-Type': 'application/json' })
  1801. res.end(JSON.stringify({ ok: true, tile }))
  1802. } catch (e) {
  1803. res.writeHead(400, { 'Content-Type': 'application/json' })
  1804. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1805. }
  1806. }).catch(() => {
  1807. res.writeHead(413, { 'Content-Type': 'application/json' })
  1808. res.end(JSON.stringify({ error: 'Request body too large' }))
  1809. })
  1810. return
  1811. }
  1812. // Handle /tiles/:id routes
  1813. const tilesIdMatch = req.url?.match(/^\/tiles\/([^/?]+)/)
  1814. if (tilesIdMatch) {
  1815. const tileId = tilesIdMatch[1]
  1816. const tile = textTiles.get(tileId)
  1817. // PUT /tiles/:id - Update a text tile
  1818. if (req.method === 'PUT') {
  1819. if (!tile) {
  1820. res.writeHead(404, { 'Content-Type': 'application/json' })
  1821. res.end(JSON.stringify({ ok: false, error: 'Tile not found' }))
  1822. return
  1823. }
  1824. collectRequestBody(req).then(body => {
  1825. try {
  1826. const data = JSON.parse(body) as UpdateTextTileRequest
  1827. if (data.text !== undefined) tile.text = data.text
  1828. if (data.position !== undefined) tile.position = data.position
  1829. if (data.color !== undefined) tile.color = data.color
  1830. saveTiles()
  1831. broadcastTiles()
  1832. log(`Updated text tile: "${tile.text}"`)
  1833. res.writeHead(200, { 'Content-Type': 'application/json' })
  1834. res.end(JSON.stringify({ ok: true, tile }))
  1835. } catch (e) {
  1836. res.writeHead(400, { 'Content-Type': 'application/json' })
  1837. res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }))
  1838. }
  1839. }).catch(() => {
  1840. res.writeHead(413, { 'Content-Type': 'application/json' })
  1841. res.end(JSON.stringify({ error: 'Request body too large' }))
  1842. })
  1843. return
  1844. }
  1845. // DELETE /tiles/:id - Delete a text tile
  1846. if (req.method === 'DELETE') {
  1847. if (!tile) {
  1848. res.writeHead(404, { 'Content-Type': 'application/json' })
  1849. res.end(JSON.stringify({ ok: false, error: 'Tile not found' }))
  1850. return
  1851. }
  1852. textTiles.delete(tileId)
  1853. saveTiles()
  1854. broadcastTiles()
  1855. log(`Deleted text tile: "${tile.text}"`)
  1856. res.writeHead(200, { 'Content-Type': 'application/json' })
  1857. res.end(JSON.stringify({ ok: true }))
  1858. return
  1859. }
  1860. }
  1861. // Static file serving for frontend (production mode)
  1862. serveStaticFile(req, res)
  1863. }
  1864. /** MIME types for static files */
  1865. const MIME_TYPES: Record<string, string> = {
  1866. '.html': 'text/html',
  1867. '.js': 'application/javascript',
  1868. '.css': 'text/css',
  1869. '.json': 'application/json',
  1870. '.svg': 'image/svg+xml',
  1871. '.png': 'image/png',
  1872. '.ico': 'image/x-icon',
  1873. }
  1874. /** Serve static files from dist/ directory */
  1875. function serveStaticFile(req: IncomingMessage, res: ServerResponse): void {
  1876. // Determine the dist directory (relative to this file when compiled)
  1877. // Compiled server is at: dist/server/server/index.js
  1878. // So ../../ gets us to dist/
  1879. const distDir = resolve(dirname(new URL(import.meta.url).pathname), '../..')
  1880. // Parse the URL path
  1881. let urlPath = req.url?.split('?')[0] ?? '/'
  1882. if (urlPath === '/') urlPath = '/index.html'
  1883. // Security: prevent directory traversal
  1884. // 1. Decode URL-encoded characters to catch %2e%2e (encoded ..)
  1885. // 2. Resolve to absolute path
  1886. // 3. Verify result is within distDir
  1887. let decodedPath: string
  1888. try {
  1889. decodedPath = decodeURIComponent(urlPath)
  1890. } catch {
  1891. // Invalid URL encoding
  1892. res.writeHead(400)
  1893. res.end('Bad request')
  1894. return
  1895. }
  1896. const filePath = resolve(distDir, '.' + decodedPath)
  1897. // Check for path traversal: resolved path must start with distDir
  1898. if (!filePath.startsWith(distDir + '/') && filePath !== distDir) {
  1899. res.writeHead(403)
  1900. res.end('Forbidden')
  1901. return
  1902. }
  1903. // Check if file exists
  1904. if (!existsSync(filePath)) {
  1905. // For SPA, serve index.html for non-API routes
  1906. const indexPath = join(distDir, 'index.html')
  1907. if (existsSync(indexPath) && !decodedPath.startsWith('/api')) {
  1908. const content = readFileSync(indexPath)
  1909. res.writeHead(200, { 'Content-Type': 'text/html' })
  1910. res.end(content)
  1911. return
  1912. }
  1913. res.writeHead(404)
  1914. res.end('Not found')
  1915. return
  1916. }
  1917. // Serve the file
  1918. const ext = extname(filePath).toLowerCase()
  1919. const contentType = MIME_TYPES[ext] || 'application/octet-stream'
  1920. const content = readFileSync(filePath)
  1921. res.writeHead(200, { 'Content-Type': contentType })
  1922. res.end(content)
  1923. }
  1924. // ============================================================================
  1925. // Main
  1926. // ============================================================================
  1927. function main() {
  1928. log('Starting Vibecraft server...')
  1929. // Load Deepgram API key for voice transcription
  1930. deepgramApiKey = loadDeepgramKey()
  1931. // Load existing events
  1932. loadEventsFromFile()
  1933. // Load saved sessions (for persistence across restarts)
  1934. loadSessions()
  1935. // Load saved text tiles
  1936. loadTiles()
  1937. // Start git status tracking
  1938. gitStatusManager.setUpdateHandler(({ sessionId, status }) => {
  1939. const session = managedSessions.get(sessionId)
  1940. if (session) {
  1941. debug(`Git status updated for ${session.name}: ${status.branch} +${status.linesAdded}/-${status.linesRemoved}`)
  1942. // Broadcast updated sessions to all clients
  1943. broadcastSessions()
  1944. }
  1945. })
  1946. gitStatusManager.start()
  1947. // Watch for new events
  1948. watchEventsFile()
  1949. // Create HTTP server
  1950. const httpServer = createServer(handleHttpRequest)
  1951. // Create WebSocket server
  1952. const wss = new WebSocketServer({ server: httpServer })
  1953. wss.on('connection', (ws, req) => {
  1954. // CSRF protection: validate Origin header
  1955. const origin = req.headers.origin
  1956. if (!isOriginAllowed(origin)) {
  1957. log(`Rejected WebSocket connection from origin: ${origin}`)
  1958. ws.close(1008, 'Origin not allowed')
  1959. return
  1960. }
  1961. clients.add(ws)
  1962. log(`Client connected (${clients.size} total)${origin ? ` from ${origin}` : ''}`)
  1963. // Send connection confirmation
  1964. const connectMsg: ServerMessage = {
  1965. type: 'connected',
  1966. payload: { sessionId: events[events.length - 1]?.sessionId ?? 'unknown' },
  1967. }
  1968. ws.send(JSON.stringify(connectMsg))
  1969. // IMPORTANT: Send sessions BEFORE history so client can link events to sessions
  1970. const sessionsMsg: ServerMessage = {
  1971. type: 'sessions',
  1972. payload: getSessions(),
  1973. }
  1974. ws.send(JSON.stringify(sessionsMsg))
  1975. // Send text tiles
  1976. const tilesMsg: ServerMessage = {
  1977. type: 'text_tiles',
  1978. payload: getTiles(),
  1979. }
  1980. ws.send(JSON.stringify(tilesMsg))
  1981. // Send recent history - filtered to only include events from current managed sessions
  1982. const activeClaudeSessionIds = new Set(
  1983. Array.from(managedSessions.values())
  1984. .map(s => s.claudeSessionId)
  1985. .filter(Boolean)
  1986. )
  1987. const filteredHistory = events
  1988. .filter(e => activeClaudeSessionIds.has(e.sessionId))
  1989. .slice(-50)
  1990. const historyMsg: ServerMessage = {
  1991. type: 'history',
  1992. payload: filteredHistory,
  1993. }
  1994. ws.send(JSON.stringify(historyMsg))
  1995. ws.on('message', (data: RawData, isBinary: boolean) => {
  1996. // Handle binary audio data for voice transcription
  1997. if (isBinary) {
  1998. const audioBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer)
  1999. sendVoiceAudio(ws, audioBuffer)
  2000. return
  2001. }
  2002. // Handle JSON messages
  2003. try {
  2004. const message = JSON.parse(data.toString()) as ClientMessage
  2005. handleClientMessage(ws, message)
  2006. } catch (e) {
  2007. debug(`Failed to parse client message: ${e}`)
  2008. }
  2009. })
  2010. ws.on('close', () => {
  2011. stopVoiceSession(ws) // Clean up any voice session
  2012. clients.delete(ws)
  2013. log(`Client disconnected (${clients.size} total)`)
  2014. })
  2015. ws.on('error', (error) => {
  2016. debug(`WebSocket error: ${error}`)
  2017. stopVoiceSession(ws) // Clean up any voice session
  2018. clients.delete(ws)
  2019. })
  2020. })
  2021. httpServer.listen(PORT, () => {
  2022. log(`Server running on port ${PORT}`)
  2023. log(``)
  2024. log(`Open https://vibecraft.sh to view your workshop`)
  2025. log(``)
  2026. log(`Local API endpoints:`)
  2027. log(` WebSocket: ws://localhost:${PORT}`)
  2028. log(` Events: http://localhost:${PORT}/event`)
  2029. log(` Prompt: http://localhost:${PORT}/prompt`)
  2030. log(` Health: http://localhost:${PORT}/health`)
  2031. log(` Stats: http://localhost:${PORT}/stats`)
  2032. log(` Sessions: http://localhost:${PORT}/sessions`)
  2033. // Start token polling after server is ready
  2034. startTokenPolling()
  2035. // Start permission prompt polling
  2036. startPermissionPolling()
  2037. // Start session health checking (every 5 seconds)
  2038. setInterval(checkSessionHealth, 5000)
  2039. // Start working timeout checking (every 10 seconds)
  2040. setInterval(checkWorkingTimeout, WORKING_CHECK_INTERVAL_MS)
  2041. // Run initial health check to update session statuses
  2042. checkSessionHealth()
  2043. })
  2044. }
  2045. main()

Version history

  • v0.1.011/1/2026

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.