Skip to content

Commit c47ed75

Browse files
authored
Merge pull request #23 from ThinkOffApp/feat/ide-chat-mirror
IDE-chat mirror — tail Claude transcripts into CodeWatch
2 parents b910ab6 + 1fc23c3 commit c47ed75

2 files changed

Lines changed: 230 additions & 0 deletions

File tree

‎bin/iak-claude-tail.mjs‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
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);

‎src/confirmations.mjs‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,13 +729,79 @@ export function startConfirmationsServer({
729729
});
730730
return;
731731
}
732+
// POST /ide-chat/<handle> body { role, text, ts, session_id, tool_calls? }
733+
// GET /ide-chat/<handle>?since=<iso> → { events: [...] }
734+
//
735+
// Per-handle in-memory ring buffer. Backs the IDE-chat-in-CodeWatch
736+
// feature — `bin/iak-claude-tail.mjs` tails ~/.claude/projects/*.jsonl
737+
// and POSTs each user/assistant message here; CodeWatch polls GET to
738+
// render the conversation as an IDE channel.
739+
const ideChatMatch = url.pathname.match(/^\/ide-chat\/([^/]+)$/);
740+
if (ideChatMatch) {
741+
const handle = decodeURIComponent(ideChatMatch[1]);
742+
if (req.method === 'POST') {
743+
let body = '';
744+
req.on('data', (c) => { body += c; });
745+
req.on('end', () => {
746+
let payload;
747+
try { payload = JSON.parse(body); } catch {
748+
res.writeHead(400, { 'Content-Type': 'application/json' });
749+
res.end(JSON.stringify({ ok: false, error: 'invalid json' }));
750+
return;
751+
}
752+
const event = appendIdeChatEvent(handle, payload);
753+
res.writeHead(200, { 'Content-Type': 'application/json' });
754+
res.end(JSON.stringify({ ok: true, ts: event.ts }));
755+
});
756+
return;
757+
}
758+
if (req.method === 'GET') {
759+
const since = url.searchParams.get('since');
760+
const limit = parseInt(url.searchParams.get('limit') || '200', 10);
761+
const events = listIdeChatEvents(handle, since, limit);
762+
res.writeHead(200, { 'Content-Type': 'application/json' });
763+
res.end(JSON.stringify({ events }));
764+
return;
765+
}
766+
}
732767
res.writeHead(404, { 'Content-Type': 'application/json' });
733768
res.end(JSON.stringify({ ok: false, error: 'not found' }));
734769
});
735770
server.listen(port, host);
736771
return server;
737772
}
738773

774+
// In-memory IDE-chat ring buffer per handle. Bounded to keep memory flat
775+
// even on long-running daemons. Persisted nowhere — restart drops history,
776+
// CodeWatch will repopulate on next tail run.
777+
const IDE_CHAT_MAX_PER_HANDLE = 500;
778+
const ideChat = new Map(); // handle → array of events (oldest first)
779+
780+
export function appendIdeChatEvent(handle, raw) {
781+
const event = {
782+
role: raw.role || 'unknown',
783+
text: typeof raw.text === 'string' ? raw.text : String(raw.text ?? ''),
784+
ts: raw.ts || new Date().toISOString(),
785+
session_id: raw.session_id || null,
786+
tool_calls: Array.isArray(raw.tool_calls) ? raw.tool_calls : undefined,
787+
};
788+
let buf = ideChat.get(handle);
789+
if (!buf) { buf = []; ideChat.set(handle, buf); }
790+
buf.push(event);
791+
if (buf.length > IDE_CHAT_MAX_PER_HANDLE) buf.splice(0, buf.length - IDE_CHAT_MAX_PER_HANDLE);
792+
return event;
793+
}
794+
795+
export function listIdeChatEvents(handle, since, limit = 200) {
796+
const buf = ideChat.get(handle) || [];
797+
let filtered = buf;
798+
if (since) {
799+
filtered = buf.filter((e) => e.ts > since);
800+
}
801+
if (filtered.length > limit) filtered = filtered.slice(filtered.length - limit);
802+
return filtered;
803+
}
804+
739805
// Tiny self-contained HTML UI for tap-to-approve. Inlined so the
740806
// confirmations server has no external assets / templates to ship.
741807
function renderIntentsHtml() {

0 commit comments

Comments
 (0)