-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathclaude-cli-query.js
More file actions
436 lines (374 loc) · 12.4 KB
/
claude-cli-query.js
File metadata and controls
436 lines (374 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/**
* Claude CLI Query Runner (Full REPL Mode v2)
*
* Spawns the native `claude` CLI with `--output-format stream-json`
* via node-pty (pseudo-terminal) and maps the streaming JSON events
* to the same WebSocket message format the Chat UI already expects.
*
* The claude binary requires a TTY to produce output, so we must use
* node-pty instead of child_process.spawn.
*/
import pty from 'node-pty';
import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
const activeCliSessions = new Map();
/**
* Maps projectPath → last CLI session UUID.
* Used for bidirectional session sync between Chat and Shell tabs.
*/
const projectSessionRegistry = new Map();
export function getProjectSessionId(projectPath) {
return projectSessionRegistry.get(projectPath) || null;
}
export function setProjectSessionId(projectPath, sessionId) {
if (projectPath && sessionId) {
projectSessionRegistry.set(projectPath, sessionId);
console.log(`[Full REPL v2] Registry: ${projectPath} → ${sessionId}`);
}
}
/**
* Scans ~/.claude/projects/ for the most recently modified session file
* for a given project path. Returns the session UUID or null.
*/
export async function findLatestSessionForProject(projectPath) {
try {
// Claude encodes project paths by replacing / with -
const encoded = projectPath.replace(/\//g, '-');
const projectDir = path.join(os.homedir(), '.claude', 'projects', encoded);
const entries = await fs.readdir(projectDir);
const jsonlFiles = entries.filter(e => e.endsWith('.jsonl'));
if (jsonlFiles.length === 0) return null;
// Find the most recently modified
let latest = null;
let latestMtime = 0;
for (const file of jsonlFiles) {
const filePath = path.join(projectDir, file);
const stat = await fs.stat(filePath);
if (stat.mtimeMs > latestMtime) {
latestMtime = stat.mtimeMs;
latest = file.replace('.jsonl', '');
}
}
return latest;
} catch {
return null;
}
}
let cachedClaudeBin = null;
/**
* Finds the actual claude binary path, skipping shell functions/aliases.
*/
async function resolveClaudeBinary() {
if (cachedClaudeBin) return cachedClaudeBin;
const candidates = [
path.join(os.homedir(), '.local', 'bin', 'claude'),
'/usr/local/bin/claude',
'/opt/homebrew/bin/claude',
];
for (const candidate of candidates) {
try {
await fs.access(candidate);
cachedClaudeBin = candidate;
console.log(`[Full REPL v2] Resolved claude binary: ${cachedClaudeBin}`);
return cachedClaudeBin;
} catch {
// Not found, try next
}
}
console.log('[Full REPL v2] Could not resolve claude binary, falling back to PATH');
cachedClaudeBin = 'claude';
return cachedClaudeBin;
}
/**
* Spawns the native claude CLI and streams structured JSON events to the WebSocket.
*/
export async function queryClaudeCLI(command, options = {}, ws) {
const { sessionId, cwd, model, permissionMode, images } = options;
const args = ['--output-format', 'stream-json', '--verbose'];
// Skip MCP server loading for --print mode queries. The CLI waits for all
// MCP servers to connect/fail before processing, which adds 20-30s for servers
// that timeout. MCP tools are available in the Shell tab (persistent REPL).
// MCP_CONNECTION_NONBLOCKING only works for the interactive SDK mode, not --print.
args.push('--mcp-config', '{"mcpServers":{}}', '--strict-mcp-config');
// Resume: explicit session ID > registry > none
const isValidUUID = sessionId && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
const resolvedCwd = cwd || process.env.HOME;
let resumeId = isValidUUID ? sessionId : null;
if (!resumeId) {
// Check registry for a session created by Shell or a previous Chat query
const registryId = getProjectSessionId(resolvedCwd);
if (registryId) {
resumeId = registryId;
console.log(`[Full REPL v2] Chat resuming session from registry: ${resumeId}`);
}
}
const isResumed = Boolean(resumeId);
if (resumeId) {
args.push('--resume', resumeId);
}
if (model) {
args.push('--model', model);
}
if (permissionMode === 'plan') {
args.push('--permission-mode', 'plan');
} else if (permissionMode && permissionMode !== 'default') {
args.push('--permission-mode', permissionMode);
}
// Handle images
let finalCommand = command;
let tempImagePaths = [];
let tempDir = null;
if (images && images.length > 0) {
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-img-'));
for (let i = 0; i < images.length; i++) {
const img = images[i];
if (img.data && img.mediaType) {
const ext = img.mediaType.split('/')[1] || 'png';
const imgPath = path.join(tempDir, `image_${i}.${ext}`);
const buffer = Buffer.from(img.data, 'base64');
await fs.writeFile(imgPath, buffer);
tempImagePaths.push(imgPath);
}
}
if (tempImagePaths.length > 0) {
const imageRefs = tempImagePaths.map(p => `[Image: ${p}]`).join(' ');
finalCommand = `${imageRefs}\n\n${command}`;
}
}
args.push('--print', finalCommand);
// Build the full command string for bash -c.
// The claude binary is a Bun executable that requires a proper shell
// environment (same way the Shell tab spawns it).
const claudeBin = await resolveClaudeBinary();
const isWindows = os.platform() === 'win32';
const escapedArgs = args.map(a => {
if (isWindows) {
return `'${a.replace(/'/g, "''")}'`;
}
return `'${a.replace(/'/g, "'\\''")}'`;
}).join(' ');
const shellCommand = `${claudeBin} ${escapedArgs}`;
console.log(`[Full REPL v2] Spawning via bash: claude ${args.slice(0, 6).join(' ')}...`);
console.log(`[Full REPL v2] cwd: ${resolvedCwd}`);
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
const shellArgs = os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
const cliProcess = pty.spawn(shell, shellArgs, {
name: 'xterm-256color',
cols: 120,
rows: 40,
cwd: resolvedCwd,
env: {
...process.env,
NO_COLOR: '1',
},
});
let capturedSessionId = sessionId || null;
let partialLine = '';
let sessionCreatedSent = false;
let bufferedMessages = [];
let lastPlaintextLine = '';
let structuredErrorSent = false;
const session = {
process: cliProcess,
startTime: Date.now(),
sessionId: capturedSessionId,
};
const sessionKey = sessionId || `pending_${Date.now()}`;
activeCliSessions.set(sessionKey, session);
console.log(`[Full REPL v2] Process PID: ${cliProcess.pid}`);
// Parse PTY output as JSONL
cliProcess.onData((rawData) => {
partialLine += rawData;
const lines = partialLine.split('\n');
partialLine = lines.pop(); // Keep incomplete line
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
// Strip any ANSI escape sequences that might leak through
const cleaned = trimmed.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').trim();
if (!cleaned) continue;
if (cleaned[0] !== '{') {
lastPlaintextLine = cleaned;
continue;
}
try {
const event = JSON.parse(cleaned);
console.log(`[Full REPL v2] Event: ${event.type}/${event.subtype || ''}`);
// Capture session ID from init event BEFORE mapping messages
if (event.type === 'system' && event.subtype === 'init' && event.session_id) {
capturedSessionId = event.session_id;
session.sessionId = capturedSessionId;
// Store in registry for Shell tab to pick up
setProjectSessionId(resolvedCwd, capturedSessionId);
if (sessionKey !== capturedSessionId) {
activeCliSessions.delete(sessionKey);
activeCliSessions.set(capturedSessionId, session);
}
}
const wsMessages = mapCliEventToWsMessages(event, session);
for (const msg of wsMessages) {
if (msg.type === 'session-created') {
console.log(`[Full REPL v2] Sending WS: ${JSON.stringify(msg)}`);
ws.send(msg);
// Flush buffered messages synchronously after session-created
for (const buffered of bufferedMessages) {
ws.send(buffered);
}
bufferedMessages = [];
sessionCreatedSent = true;
} else if (!sessionCreatedSent) {
// Buffer messages until session-created has been sent
bufferedMessages.push(msg);
} else {
ws.send(msg);
}
}
} catch {
// Not valid JSON, skip
}
}
});
cliProcess.onExit(({ exitCode }) => {
console.log(`[Full REPL v2] CLI process exited with code ${exitCode}`);
// Process any remaining partial line
if (partialLine.trim()) {
const cleaned = partialLine.trim().replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').trim();
if (cleaned && cleaned[0] === '{') {
try {
const event = JSON.parse(cleaned);
const wsMessages = mapCliEventToWsMessages(event, session);
for (const msg of wsMessages) {
ws.send(msg);
}
} catch {
// ignore
}
}
}
// Emit plaintext CLI error if process failed without a structured error
if (exitCode && exitCode !== 0 && !structuredErrorSent && lastPlaintextLine) {
ws.send({
type: 'claude-error',
error: lastPlaintextLine,
sessionId: capturedSessionId || null,
});
}
ws.send({
type: 'claude-complete',
sessionId: capturedSessionId,
exitCode: exitCode || 0,
isNewSession: !isResumed,
});
activeCliSessions.delete(capturedSessionId || sessionKey);
// Clean up temp images
if (tempImagePaths.length > 0) {
for (const p of tempImagePaths) {
fs.unlink(p).catch(() => {});
}
if (tempDir) {
fs.rmdir(tempDir).catch(() => {});
}
}
});
}
/**
* Maps a CLI stream-json event to WebSocket messages the Chat UI expects.
*/
function mapCliEventToWsMessages(event, session) {
const sid = session.sessionId;
const messages = [];
switch (event.type) {
case 'system': {
if (event.subtype === 'init') {
messages.push({
type: 'session-created',
sessionId: event.session_id,
});
}
break;
}
case 'assistant': {
const msg = event.message;
if (msg) {
messages.push({
type: 'claude-response',
data: {
message: msg,
parent_tool_use_id: event.parent_tool_use_id || null,
},
sessionId: sid,
});
}
break;
}
case 'user': {
const msg = event.message;
if (msg) {
messages.push({
type: 'claude-response',
data: {
message: msg,
parent_tool_use_id: event.parent_tool_use_id || null,
tool_use_result: event.tool_use_result || null,
},
sessionId: sid,
});
}
break;
}
case 'result': {
if (event.modelUsage) {
const models = Object.keys(event.modelUsage);
if (models.length > 0) {
const usage = event.modelUsage[models[0]];
messages.push({
type: 'token-budget',
data: {
used: (usage.inputTokens || 0) + (usage.outputTokens || 0) +
(usage.cacheReadInputTokens || 0) + (usage.cacheCreationInputTokens || 0),
total: usage.contextWindow || 200000,
},
sessionId: sid,
});
}
}
break;
}
case 'rate_limit_event':
break;
default: {
if (event.message) {
messages.push({
type: 'claude-response',
data: { message: event.message },
sessionId: sid,
});
}
break;
}
}
return messages;
}
/**
* Aborts an active CLI session.
*/
export function abortClaudeCLISession(sessionId) {
const session = activeCliSessions.get(sessionId);
if (session?.process) {
session.process.write('\x03'); // Ctrl+C
setTimeout(() => {
try { session.process.kill(); } catch { /* already dead */ }
activeCliSessions.delete(sessionId);
}, 1000);
return true;
}
return false;
}
export function isClaudeCLISessionActive(sessionId) {
return activeCliSessions.has(sessionId);
}
export function getActiveClaudeCLISessions() {
return Array.from(activeCliSessions.keys());
}
export { activeCliSessions };