-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathclaude-code-agent.js
More file actions
644 lines (586 loc) · 25.8 KB
/
claude-code-agent.js
File metadata and controls
644 lines (586 loc) · 25.8 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/**
* Claude Code SDK integration via NodeConnector.
*
* Provides AI chat capabilities by bridging the Claude Code CLI/SDK
* with Phoenix's browser-side chat panel. Handles streaming responses,
* edit/write interception, and session management.
*/
const { execSync } = require("child_process");
const path = require("path");
const { createEditorMcpServer } = require("./mcp-editor-tools");
const CONNECTOR_ID = "ph_ai_claude";
// Lazy-loaded ESM module reference
let queryModule = null;
// Session state
let currentSessionId = null;
// Active query state
let currentAbortController = null;
// Lazily-initialized in-process MCP server for editor context
let editorMcpServer = null;
// Streaming throttle
const TEXT_STREAM_THROTTLE_MS = 50;
const nodeConnector = global.createNodeConnector(CONNECTOR_ID, exports);
/**
* Lazily import the ESM @anthropic-ai/claude-code module.
*/
async function getQueryFn() {
if (!queryModule) {
queryModule = await import("@anthropic-ai/claude-code");
}
return queryModule.query;
}
/**
* Find the user's globally installed Claude CLI, skipping node_modules copies.
*/
function findGlobalClaudeCli() {
const locations = [
"/usr/local/bin/claude",
"/usr/bin/claude",
(process.env.HOME || "") + "/.local/bin/claude",
(process.env.HOME || "") + "/.nvm/versions/node/" +
(process.version.startsWith("v") ? process.version : "v" + process.version) +
"/bin/claude"
];
// Try 'which -a' first to find all claude binaries, filtering out node_modules
try {
const allPaths = execSync("which -a claude 2>/dev/null || which claude", { encoding: "utf8" })
.trim()
.split("\n")
.filter(p => p && !p.includes("node_modules"));
if (allPaths.length > 0) {
console.log("[Phoenix AI] Found global Claude CLI at:", allPaths[0]);
return allPaths[0];
}
} catch {
// which failed, try manual locations
}
// Check common locations
for (const loc of locations) {
try {
execSync(`test -x "${loc}"`, { encoding: "utf8" });
console.log("[Phoenix AI] Found global Claude CLI at:", loc);
return loc;
} catch {
// Not found at this location
}
}
console.log("[Phoenix AI] Global Claude CLI not found");
return null;
}
/**
* Check whether Claude CLI is available.
* Called from browser via execPeer("checkAvailability").
*/
exports.checkAvailability = async function () {
try {
const claudePath = findGlobalClaudeCli();
if (claudePath) {
// Also verify the SDK can be imported
await getQueryFn();
return { available: true, claudePath: claudePath };
}
// No global CLI found — try importing SDK anyway (it might find its own)
await getQueryFn();
return { available: true, claudePath: null };
} catch (err) {
return { available: false, claudePath: null, error: err.message };
}
};
/**
* Send a prompt to Claude and stream results back to the browser.
* Called from browser via execPeer("sendPrompt", {prompt, projectPath, sessionAction, model}).
*
* Returns immediately with a requestId. Results are sent as events:
* aiProgress, aiTextStream, aiToolEdit, aiError, aiComplete
*/
exports.sendPrompt = async function (params) {
const { prompt, projectPath, sessionAction, model, locale, selectionContext } = params;
const requestId = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
// Handle session
if (sessionAction === "new") {
currentSessionId = null;
}
// Cancel any in-flight query
if (currentAbortController) {
currentAbortController.abort();
currentAbortController = null;
}
currentAbortController = new AbortController();
// Prepend selection context to the prompt if available
let enrichedPrompt = prompt;
if (selectionContext && selectionContext.selectedText) {
enrichedPrompt =
"The user has selected the following text in " + selectionContext.filePath +
" (lines " + selectionContext.startLine + "-" + selectionContext.endLine + "):\n" +
"```\n" + selectionContext.selectedText + "\n```\n\n" + prompt;
}
// Run the query asynchronously — don't await here so we return requestId immediately
_runQuery(requestId, enrichedPrompt, projectPath, model, currentAbortController.signal, locale)
.catch(err => {
console.error("[Phoenix AI] Query error:", err);
});
return { requestId: requestId };
};
/**
* Cancel the current in-flight query.
*/
exports.cancelQuery = async function () {
if (currentAbortController) {
currentAbortController.abort();
currentAbortController = null;
// Clear session so next query starts fresh instead of resuming a killed session
currentSessionId = null;
return { success: true };
}
return { success: false };
};
/**
* Destroy the current session (clear session ID).
*/
exports.destroySession = async function () {
currentSessionId = null;
currentAbortController = null;
return { success: true };
};
/**
* Internal: run a Claude SDK query and stream results back to the browser.
*/
async function _runQuery(requestId, prompt, projectPath, model, signal, locale) {
let editCount = 0;
let toolCounter = 0;
let queryFn;
try {
queryFn = await getQueryFn();
if (!editorMcpServer) {
editorMcpServer = createEditorMcpServer(queryModule, nodeConnector);
}
} catch (err) {
nodeConnector.triggerPeer("aiError", {
requestId: requestId,
error: "Failed to load Claude Code SDK: " + err.message
});
return;
}
// Send initial progress
nodeConnector.triggerPeer("aiProgress", {
requestId: requestId,
message: "Analyzing...",
phase: "start"
});
const queryOptions = {
cwd: projectPath || process.cwd(),
maxTurns: undefined,
allowedTools: [
"Read", "Edit", "Write", "Glob", "Grep",
"mcp__phoenix-editor__getEditorState",
"mcp__phoenix-editor__takeScreenshot",
"mcp__phoenix-editor__execJsInLivePreview",
"mcp__phoenix-editor__controlEditor"
],
mcpServers: { "phoenix-editor": editorMcpServer },
permissionMode: "acceptEdits",
appendSystemPrompt:
"When modifying an existing file, always prefer the Edit tool " +
"(find-and-replace) instead of the Write tool. The Write tool should ONLY be used " +
"to create brand new files that do not exist yet. For existing files, always use " +
"multiple Edit calls to make targeted changes rather than rewriting the entire " +
"file with Write. This is critical because Write replaces the entire file content " +
"which is slow and loses undo history." +
(locale && !locale.startsWith("en")
? "\n\nThe user's display language is " + locale + ". " +
"Respond in this language unless they write in a different language."
: ""),
includePartialMessages: true,
abortController: currentAbortController,
hooks: {
PreToolUse: [
{
matcher: "Edit",
hooks: [
async (input) => {
console.log("[Phoenix AI] Intercepted Edit tool");
const myToolId = toolCounter; // capture before any await
const edit = {
file: input.tool_input.file_path,
oldText: input.tool_input.old_string,
newText: input.tool_input.new_string
};
editCount++;
try {
await nodeConnector.execPeer("applyEditToBuffer", edit);
} catch (err) {
console.warn("[Phoenix AI] Failed to apply edit to buffer:", err.message);
}
nodeConnector.triggerPeer("aiToolEdit", {
requestId: requestId,
toolId: myToolId,
edit: edit
});
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Edit applied successfully via Phoenix editor."
}
};
}
]
},
{
matcher: "Read",
hooks: [
async (input) => {
const filePath = input.tool_input.file_path;
if (!filePath) {
return undefined;
}
try {
const result = await nodeConnector.execPeer("getFileContent", { filePath });
if (result && result.isDirty && result.content !== null) {
const MAX_LINES = 2000;
const MAX_LINE_LENGTH = 2000;
const lines = result.content.split("\n");
const offset = input.tool_input.offset || 0;
const limit = input.tool_input.limit || MAX_LINES;
const selected = lines.slice(offset, offset + limit);
let formatted = selected.map((line, i) => {
const truncated = line.length > MAX_LINE_LENGTH
? line.slice(0, MAX_LINE_LENGTH) + "..."
: line;
return String(offset + i + 1).padStart(6) + "\t" + truncated;
}).join("\n");
formatted = filePath + " (" +
lines.length + " lines total)\n\n" + formatted;
console.log("[Phoenix AI] Serving dirty file content for:", filePath);
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: formatted
}
};
}
} catch (err) {
console.warn("[Phoenix AI] Failed to check dirty state:", filePath, err.message);
}
return undefined;
}
]
},
{
matcher: "Write",
hooks: [
async (input) => {
console.log("[Phoenix AI] Intercepted Write tool");
const myToolId = toolCounter; // capture before any await
const edit = {
file: input.tool_input.file_path,
oldText: null,
newText: input.tool_input.content
};
editCount++;
try {
await nodeConnector.execPeer("applyEditToBuffer", edit);
} catch (err) {
console.warn("[Phoenix AI] Failed to apply write to buffer:", err.message);
}
nodeConnector.triggerPeer("aiToolEdit", {
requestId: requestId,
toolId: myToolId,
edit: edit
});
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Write applied successfully via Phoenix editor."
}
};
}
]
}
]
}
};
// Set Claude CLI path if found
const claudePath = findGlobalClaudeCli();
if (claudePath) {
queryOptions.pathToClaudeCodeExecutable = claudePath;
}
if (model) {
queryOptions.model = model;
}
// Resume session if we have an existing one (already cleared if sessionAction was "new")
if (currentSessionId) {
queryOptions.resume = currentSessionId;
}
const _log = (...args) => console.log("[AI]", ...args);
try {
_log("Query start:", JSON.stringify(prompt).slice(0, 80), "cwd=" + (projectPath || "?"));
const result = queryFn({
prompt: prompt,
options: queryOptions
});
let accumulatedText = "";
let lastStreamTime = 0;
// Tool input tracking (parent-level)
let activeToolName = null;
let activeToolIndex = null;
let activeToolInputJson = "";
let lastToolStreamTime = 0;
// Sub-agent tool tracking
let subagentToolName = null;
let subagentToolIndex = null;
let subagentToolInputJson = "";
let lastSubagentToolStreamTime = 0;
// Trace counters (logged at tool/query completion, not per-delta)
let toolDeltaCount = 0;
let toolStreamSendCount = 0;
let textDeltaCount = 0;
let textStreamSendCount = 0;
for await (const message of result) {
// Check abort
if (signal.aborted) {
_log("Aborted");
break;
}
// Capture session_id from first message
if (message.session_id && !currentSessionId) {
currentSessionId = message.session_id;
_log("Session:", currentSessionId);
}
// Handle streaming events
if (message.type === "stream_event") {
const event = message.event;
const isSubagent = !!message.parent_tool_use_id;
if (isSubagent) {
// --- Sub-agent events ---
// Sub-agent tool use start
if (event.type === "content_block_start" &&
event.content_block?.type === "tool_use") {
subagentToolName = event.content_block.name;
subagentToolIndex = event.index;
subagentToolInputJson = "";
toolCounter++;
lastSubagentToolStreamTime = 0;
_log("Subagent tool start:", subagentToolName, "#" + toolCounter);
nodeConnector.triggerPeer("aiProgress", {
requestId: requestId,
toolName: subagentToolName,
toolId: toolCounter,
phase: "tool_use"
});
}
// Sub-agent tool input streaming
if (event.type === "content_block_delta" &&
event.delta?.type === "input_json_delta" &&
event.index === subagentToolIndex) {
subagentToolInputJson += event.delta.partial_json;
const now = Date.now();
if (subagentToolInputJson &&
now - lastSubagentToolStreamTime >= TEXT_STREAM_THROTTLE_MS) {
lastSubagentToolStreamTime = now;
nodeConnector.triggerPeer("aiToolStream", {
requestId: requestId,
toolId: toolCounter,
toolName: subagentToolName,
partialJson: subagentToolInputJson
});
}
}
// Sub-agent tool block complete
if (event.type === "content_block_stop" &&
event.index === subagentToolIndex &&
subagentToolName) {
if (subagentToolInputJson) {
nodeConnector.triggerPeer("aiToolStream", {
requestId: requestId,
toolId: toolCounter,
toolName: subagentToolName,
partialJson: subagentToolInputJson
});
}
let toolInput = {};
try {
toolInput = JSON.parse(subagentToolInputJson);
} catch (e) {
// ignore parse errors
}
_log("Subagent tool done:", subagentToolName, "#" + toolCounter,
"json=" + subagentToolInputJson.length + "ch");
nodeConnector.triggerPeer("aiToolInfo", {
requestId: requestId,
toolName: subagentToolName,
toolId: toolCounter,
toolInput: toolInput
});
subagentToolName = null;
subagentToolIndex = null;
subagentToolInputJson = "";
}
// Sub-agent text deltas — stream as regular text
if (event.type === "content_block_delta" &&
event.delta?.type === "text_delta") {
accumulatedText += event.delta.text;
textDeltaCount++;
const now = Date.now();
if (now - lastStreamTime >= TEXT_STREAM_THROTTLE_MS) {
lastStreamTime = now;
textStreamSendCount++;
nodeConnector.triggerPeer("aiTextStream", {
requestId: requestId,
text: accumulatedText
});
accumulatedText = "";
}
}
} else {
// --- Parent-level events (unchanged) ---
// Tool use start — send initial indicator
if (event.type === "content_block_start" &&
event.content_block?.type === "tool_use") {
activeToolName = event.content_block.name;
activeToolIndex = event.index;
activeToolInputJson = "";
toolCounter++;
toolDeltaCount = 0;
toolStreamSendCount = 0;
lastToolStreamTime = 0;
_log("Tool start:", activeToolName, "#" + toolCounter);
nodeConnector.triggerPeer("aiProgress", {
requestId: requestId,
toolName: activeToolName,
toolId: toolCounter,
phase: "tool_use"
});
}
// Accumulate tool input JSON and stream preview
if (event.type === "content_block_delta" &&
event.delta?.type === "input_json_delta" &&
event.index === activeToolIndex) {
activeToolInputJson += event.delta.partial_json;
toolDeltaCount++;
const now = Date.now();
if (activeToolInputJson &&
now - lastToolStreamTime >= TEXT_STREAM_THROTTLE_MS) {
lastToolStreamTime = now;
toolStreamSendCount++;
nodeConnector.triggerPeer("aiToolStream", {
requestId: requestId,
toolId: toolCounter,
toolName: activeToolName,
partialJson: activeToolInputJson
});
}
}
// Tool block complete — flush final stream preview and send details
if (event.type === "content_block_stop" &&
event.index === activeToolIndex &&
activeToolName) {
// Final flush of tool stream (bypasses throttle)
if (activeToolInputJson) {
toolStreamSendCount++;
nodeConnector.triggerPeer("aiToolStream", {
requestId: requestId,
toolId: toolCounter,
toolName: activeToolName,
partialJson: activeToolInputJson
});
}
let toolInput = {};
try {
toolInput = JSON.parse(activeToolInputJson);
} catch (e) {
// ignore parse errors
}
_log("Tool done:", activeToolName, "#" + toolCounter,
"deltas=" + toolDeltaCount, "sent=" + toolStreamSendCount,
"json=" + activeToolInputJson.length + "ch");
nodeConnector.triggerPeer("aiToolInfo", {
requestId: requestId,
toolName: activeToolName,
toolId: toolCounter,
toolInput: toolInput
});
activeToolName = null;
activeToolIndex = null;
activeToolInputJson = "";
}
// Stream text deltas (throttled)
if (event.type === "content_block_delta" &&
event.delta?.type === "text_delta") {
accumulatedText += event.delta.text;
textDeltaCount++;
const now = Date.now();
if (now - lastStreamTime >= TEXT_STREAM_THROTTLE_MS) {
lastStreamTime = now;
textStreamSendCount++;
nodeConnector.triggerPeer("aiTextStream", {
requestId: requestId,
text: accumulatedText
});
accumulatedText = "";
}
}
}
}
}
// Flush any remaining accumulated text
if (accumulatedText) {
textStreamSendCount++;
nodeConnector.triggerPeer("aiTextStream", {
requestId: requestId,
text: accumulatedText
});
}
_log("Complete: tools=" + toolCounter, "edits=" + editCount,
"textDeltas=" + textDeltaCount, "textSent=" + textStreamSendCount);
// Signal completion
nodeConnector.triggerPeer("aiComplete", {
requestId: requestId,
sessionId: currentSessionId
});
} catch (err) {
const errMsg = err.message || String(err);
const isAbort = signal.aborted || /abort/i.test(errMsg);
if (isAbort) {
_log("Cancelled");
// Query was cancelled — clear session so next query starts fresh
currentSessionId = null;
nodeConnector.triggerPeer("aiComplete", {
requestId: requestId,
sessionId: null
});
return;
}
_log("Error:", errMsg.slice(0, 200));
nodeConnector.triggerPeer("aiError", {
requestId: requestId,
error: errMsg
});
// Always send aiComplete after aiError so the UI exits streaming state
nodeConnector.triggerPeer("aiComplete", {
requestId: requestId,
sessionId: currentSessionId
});
}
}