|
| 1 | +#!/usr/bin/env node |
| 2 | +// SPDX-License-Identifier: AGPL-3.0-only |
| 3 | +// |
| 4 | +// Tails Claude Code transcript JSONL files and forwards user/assistant |
| 5 | +// messages to the IAK daemon's /ide-chat/<handle> endpoint, so CodeWatch |
| 6 | +// can render the IDE conversation as a per-handle channel. |
| 7 | +// |
| 8 | +// Run: node bin/iak-claude-tail.mjs |
| 9 | +// |
| 10 | +// Env: |
| 11 | +// IAK_HANDLE (default: @claudemm) — handle this tail represents |
| 12 | +// IAK_DAEMON_URL (default: http://127.0.0.1:8788) |
| 13 | +// IAK_TAIL_INTERVAL (default: 2000) — poll interval in ms |
| 14 | +// IAK_PROJECTS_DIR (default: ~/.claude/projects) |
| 15 | +// IAK_TAIL_INCLUDE_TOOLS (default: 0) — 1 to include tool_use / tool_result |
| 16 | +// IAK_TAIL_MAX_TEXT (default: 4000) — clamp text length per event |
| 17 | + |
| 18 | +import { readdir, stat, open } from 'node:fs/promises'; |
| 19 | +import { join } from 'node:path'; |
| 20 | +import { homedir } from 'node:os'; |
| 21 | + |
| 22 | +const HANDLE = process.env.IAK_HANDLE || '@claudemm'; |
| 23 | +const DAEMON_URL = (process.env.IAK_DAEMON_URL || 'http://127.0.0.1:8788').replace(/\/$/, ''); |
| 24 | +const POLL_MS = parseInt(process.env.IAK_TAIL_INTERVAL || '2000', 10); |
| 25 | +const PROJECTS_DIR = process.env.IAK_PROJECTS_DIR || join(homedir(), '.claude', 'projects'); |
| 26 | +const INCLUDE_TOOLS = process.env.IAK_TAIL_INCLUDE_TOOLS === '1'; |
| 27 | +const MAX_TEXT = parseInt(process.env.IAK_TAIL_MAX_TEXT || '4000', 10); |
| 28 | +const ACTIVE_WINDOW_MS = 24 * 60 * 60 * 1000; |
| 29 | +const PRIME_BYTES = 64 * 1024; |
| 30 | + |
| 31 | +const positions = new Map(); |
| 32 | + |
| 33 | +async function findActiveSessions() { |
| 34 | + const out = []; |
| 35 | + let projects; |
| 36 | + try { |
| 37 | + projects = await readdir(PROJECTS_DIR, { withFileTypes: true }); |
| 38 | + } catch { |
| 39 | + return out; |
| 40 | + } |
| 41 | + const now = Date.now(); |
| 42 | + for (const p of projects) { |
| 43 | + if (!p.isDirectory()) continue; |
| 44 | + const projDir = join(PROJECTS_DIR, p.name); |
| 45 | + let files; |
| 46 | + try { files = await readdir(projDir); } catch { continue; } |
| 47 | + let latest = null; |
| 48 | + let latestMtime = 0; |
| 49 | + for (const f of files) { |
| 50 | + if (!f.endsWith('.jsonl')) continue; |
| 51 | + const full = join(projDir, f); |
| 52 | + try { |
| 53 | + const s = await stat(full); |
| 54 | + if (s.mtimeMs > latestMtime) { |
| 55 | + latestMtime = s.mtimeMs; |
| 56 | + latest = full; |
| 57 | + } |
| 58 | + } catch {} |
| 59 | + } |
| 60 | + if (latest && now - latestMtime < ACTIVE_WINDOW_MS) { |
| 61 | + out.push({ path: latest, project: p.name, mtimeMs: latestMtime }); |
| 62 | + } |
| 63 | + } |
| 64 | + return out; |
| 65 | +} |
| 66 | + |
| 67 | +async function readNewLines(path) { |
| 68 | + let s; |
| 69 | + try { s = await stat(path); } catch { return []; } |
| 70 | + let startPos = positions.get(path); |
| 71 | + if (startPos === undefined) { |
| 72 | + // Prime: only read the tail of the file on first encounter so we |
| 73 | + // don't replay history when the script (re)starts. |
| 74 | + startPos = Math.max(0, s.size - PRIME_BYTES); |
| 75 | + } |
| 76 | + if (s.size <= startPos) return []; |
| 77 | + let fh; |
| 78 | + try { fh = await open(path, 'r'); } catch { return []; } |
| 79 | + try { |
| 80 | + const buf = Buffer.alloc(s.size - startPos); |
| 81 | + await fh.read(buf, 0, buf.length, startPos); |
| 82 | + positions.set(path, s.size); |
| 83 | + let text = buf.toString('utf-8'); |
| 84 | + // If we primed mid-line, drop the partial leading line. |
| 85 | + if (startPos > 0 && !text.startsWith('{')) { |
| 86 | + const nl = text.indexOf('\n'); |
| 87 | + if (nl >= 0) text = text.slice(nl + 1); |
| 88 | + } |
| 89 | + return text.split('\n').filter(Boolean); |
| 90 | + } finally { |
| 91 | + await fh.close(); |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +function extractEvent(obj, sessionId) { |
| 96 | + const t = obj.type; |
| 97 | + if (!['user', 'assistant'].includes(t)) return null; |
| 98 | + const msg = obj.message || {}; |
| 99 | + let content = msg.content; |
| 100 | + let toolCalls = []; |
| 101 | + if (Array.isArray(content)) { |
| 102 | + const parts = []; |
| 103 | + for (const c of content) { |
| 104 | + if (typeof c !== 'object' || c === null) { |
| 105 | + parts.push(String(c)); |
| 106 | + } else if (c.type === 'text' && typeof c.text === 'string') { |
| 107 | + parts.push(c.text); |
| 108 | + } else if (c.type === 'tool_use') { |
| 109 | + if (INCLUDE_TOOLS) { |
| 110 | + toolCalls.push({ name: c.name, input: c.input }); |
| 111 | + parts.push(`[tool_use ${c.name}]`); |
| 112 | + } |
| 113 | + } else if (c.type === 'tool_result') { |
| 114 | + if (INCLUDE_TOOLS) { |
| 115 | + parts.push(`[tool_result] ${typeof c.content === 'string' ? c.content : JSON.stringify(c.content).slice(0, 200)}`); |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + content = parts.join('\n').trim(); |
| 120 | + } else if (typeof content !== 'string') { |
| 121 | + content = String(content ?? ''); |
| 122 | + } |
| 123 | + if (!content && toolCalls.length === 0) return null; |
| 124 | + return { |
| 125 | + handle: HANDLE, |
| 126 | + role: t, |
| 127 | + text: content.slice(0, MAX_TEXT), |
| 128 | + ts: obj.timestamp || new Date().toISOString(), |
| 129 | + session_id: sessionId || obj.sessionId || null, |
| 130 | + tool_calls: INCLUDE_TOOLS && toolCalls.length ? toolCalls : undefined, |
| 131 | + }; |
| 132 | +} |
| 133 | + |
| 134 | +async function postEvent(event) { |
| 135 | + try { |
| 136 | + const res = await fetch(`${DAEMON_URL}/ide-chat/${encodeURIComponent(HANDLE)}`, { |
| 137 | + method: 'POST', |
| 138 | + headers: { 'Content-Type': 'application/json' }, |
| 139 | + body: JSON.stringify(event), |
| 140 | + }); |
| 141 | + if (!res.ok && res.status !== 404) { |
| 142 | + console.warn(`[iak-claude-tail] daemon ${res.status} on POST /ide-chat`); |
| 143 | + } |
| 144 | + } catch (e) { |
| 145 | + console.warn(`[iak-claude-tail] post failed: ${e.message}`); |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +async function poll() { |
| 150 | + const sessions = await findActiveSessions(); |
| 151 | + for (const sess of sessions) { |
| 152 | + const lines = await readNewLines(sess.path); |
| 153 | + for (const line of lines) { |
| 154 | + let obj; |
| 155 | + try { obj = JSON.parse(line); } catch { continue; } |
| 156 | + const event = extractEvent(obj, obj.sessionId); |
| 157 | + if (event) await postEvent(event); |
| 158 | + } |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +console.log(`[iak-claude-tail] handle=${HANDLE} daemon=${DAEMON_URL} dir=${PROJECTS_DIR} interval=${POLL_MS}ms tools=${INCLUDE_TOOLS}`); |
| 163 | +poll(); |
| 164 | +setInterval(poll, POLL_MS); |
0 commit comments