-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathclaude-code-agent.js
More file actions
877 lines (807 loc) · 36.2 KB
/
claude-code-agent.js
File metadata and controls
877 lines (807 loc) · 36.2 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/*
* 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";
const CLARIFICATION_HINT =
" IMPORTANT: The user has typed a follow-up clarification while you were working." +
" Call the getUserClarification tool to read it before proceeding.";
// 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;
// Pending question resolver — used by AskUserQuestion hook
let _questionResolve = null;
// Queued clarification from the user (typed while AI is streaming)
// Shape: { text: string, images: [{mediaType, base64Data}] } or null
let _queuedClarification = null;
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, images } = params;
const requestId = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
// Handle session
if (sessionAction === "new") {
currentSessionId = null;
}
// Clear any stale clarification from a previous turn
_queuedClarification = 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) {
if (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;
} else {
let previewSnippet = "";
if (selectionContext.selectionPreview) {
previewSnippet = "\nPreview of selection:\n```\n" +
selectionContext.selectionPreview + "\n```\n";
}
enrichedPrompt =
"The user has selected lines " + selectionContext.startLine + "-" +
selectionContext.endLine + " in " + selectionContext.filePath +
". Use the Read tool with offset=" + (selectionContext.startLine - 1) +
" and limit=" + (selectionContext.endLine - selectionContext.startLine + 1) +
" to read the selected content if needed." + previewSnippet + "\n" + prompt;
}
}
// Run the query asynchronously — don't await here so we return requestId immediately
_runQuery(requestId, enrichedPrompt, projectPath, model, currentAbortController.signal, locale, images)
.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;
// Clear any pending question
_questionResolve = null;
_queuedClarification = null;
return { success: true };
}
return { success: false };
};
/**
* Receive the user's answer to an AskUserQuestion prompt.
* Called from browser via execPeer("answerQuestion", {answers}).
*/
exports.answerQuestion = async function (params) {
if (_questionResolve) {
_questionResolve(params);
_questionResolve = null;
}
return { success: true };
};
/**
* Resume a previous session by setting the session ID.
* The next sendPrompt call will use queryOptions.resume with this session ID.
*/
exports.resumeSession = async function (params) {
if (currentAbortController) {
currentAbortController.abort();
currentAbortController = null;
}
_questionResolve = null;
_queuedClarification = null;
currentSessionId = params.sessionId;
return { success: true };
};
/**
* Destroy the current session (clear session ID).
*/
exports.destroySession = async function () {
currentSessionId = null;
currentAbortController = null;
_queuedClarification = null;
return { success: true };
};
/**
* Queue a clarification message from the user (typed while AI is streaming).
* If text is already queued, appends with a newline.
*/
exports.queueClarification = async function (params) {
const newImages = params.images || [];
if (_queuedClarification) {
if (params.text) {
_queuedClarification.text += "\n" + params.text;
}
_queuedClarification.images = _queuedClarification.images.concat(newImages);
} else {
_queuedClarification = {
text: params.text || "",
images: newImages
};
}
return { success: true };
};
/**
* Get and clear the queued clarification (text + images).
* Called by the getUserClarification MCP tool.
*/
exports.getAndClearClarification = async function () {
const result = _queuedClarification;
_queuedClarification = null;
return result || { text: null, images: [] };
};
/**
* Clear any queued clarification without reading it.
* Used when the user clicks Edit on the queue bubble.
*/
exports.clearClarification = async function () {
_queuedClarification = 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, images) {
let editCount = 0;
let toolCounter = 0;
let queryFn;
try {
queryFn = await getQueryFn();
if (!editorMcpServer) {
editorMcpServer = createEditorMcpServer(queryModule, nodeConnector, {
hasClarification: function () { return !!_queuedClarification; },
getAndClearClarification: exports.getAndClearClarification
});
}
} 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", "Bash",
"AskUserQuestion", "Task",
"TodoRead", "TodoWrite",
"WebFetch", "WebSearch",
"mcp__phoenix-editor__getEditorState",
"mcp__phoenix-editor__takeScreenshot",
"mcp__phoenix-editor__execJsInLivePreview",
"mcp__phoenix-editor__controlEditor",
"mcp__phoenix-editor__resizeLivePreview",
"mcp__phoenix-editor__wait",
"mcp__phoenix-editor__getUserClarification"
],
agents: {
"researcher": {
description: "Explores the codebase, reads files, and searches" +
" for patterns. Use for research tasks.",
prompt: "You are a code research assistant. Search and read" +
" files to answer questions. Do not modify files.",
tools: ["Read", "Glob", "Grep",
"mcp__phoenix-editor__getEditorState",
"mcp__phoenix-editor__takeScreenshot",
"mcp__phoenix-editor__execJsInLivePreview"]
},
"coder": {
description: "Reads, edits, and writes code files." +
" Use for implementation tasks.",
prompt: "You are a coding assistant. Implement the requested" +
" changes using Edit for existing files and Write" +
" only for new files.",
tools: ["Read", "Edit", "Write", "Glob", "Grep",
"mcp__phoenix-editor__getEditorState",
"mcp__phoenix-editor__takeScreenshot",
"mcp__phoenix-editor__execJsInLivePreview"]
}
},
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." +
"\n\nWhen a tool response mentions the user has typed a clarification, immediately " +
"call getUserClarification to read it and incorporate the user's feedback into your current work." +
(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++;
let editResult;
try {
editResult = await nodeConnector.execPeer("applyEditToBuffer", edit);
} catch (err) {
console.warn("[Phoenix AI] Failed to apply edit to buffer:", err.message);
editResult = { applied: false, error: err.message };
}
nodeConnector.triggerPeer("aiToolEdit", {
requestId: requestId,
toolId: myToolId,
edit: edit
});
let reason;
if (editResult && editResult.applied === false) {
reason = "Edit FAILED: " + (editResult.error || "unknown error");
} else {
reason = "Edit applied successfully via Phoenix editor.";
if (editResult && editResult.isLivePreviewRelated) {
reason += " The edited file is part of the active live preview." +
" Reload when ready with execJsInLivePreview: `location.reload()`";
}
}
if (_queuedClarification) {
reason += CLARIFICATION_HINT;
}
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: reason
}
};
}
]
},
{
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);
if (_queuedClarification) {
formatted += CLARIFICATION_HINT;
}
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++;
let writeResult;
try {
writeResult = await nodeConnector.execPeer("applyEditToBuffer", edit);
} catch (err) {
console.warn("[Phoenix AI] Failed to apply write to buffer:", err.message);
writeResult = { applied: false, error: err.message };
}
nodeConnector.triggerPeer("aiToolEdit", {
requestId: requestId,
toolId: myToolId,
edit: edit
});
let reason;
if (writeResult && writeResult.applied === false) {
reason = "Write FAILED: " + (writeResult.error || "unknown error");
} else {
reason = "Write applied successfully via Phoenix editor.";
if (writeResult && writeResult.isLivePreviewRelated) {
reason += " The written file is part of the active live preview." +
" Reload when ready with execJsInLivePreview: `location.reload()`";
}
}
if (_queuedClarification) {
reason += CLARIFICATION_HINT;
}
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: reason
}
};
}
]
},
{
matcher: "AskUserQuestion",
hooks: [
async (input) => {
console.log("[Phoenix AI] Intercepted AskUserQuestion");
const questions = input.tool_input.questions || [];
nodeConnector.triggerPeer("aiQuestion", {
requestId: requestId,
questions: questions
});
// Wait for the user's answer from the browser UI
const answer = await new Promise((resolve, reject) => {
_questionResolve = resolve;
if (signal.aborted) {
_questionResolve = null;
reject(new Error("Aborted"));
return;
}
const onAbort = () => {
_questionResolve = null;
reject(new Error("Aborted"));
};
signal.addEventListener("abort", onAbort, { once: true });
});
// Format answers as readable text for the AI
let answerText = "";
if (answer.answers) {
const keys = Object.keys(answer.answers);
keys.forEach(function (q) {
answerText += "Q: " + q + "\nA: " + answer.answers[q] + "\n\n";
});
}
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: answerText.trim() || "No answer provided"
}
};
}
]
}
]
}
};
// 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 || "?"));
// Build prompt: multi-modal with images, or plain string
let sdkPrompt = prompt;
if (images && images.length > 0) {
const contentBlocks = [{ type: "text", text: prompt }];
images.forEach(function (img) {
contentBlocks.push({
type: "image",
source: { type: "base64", media_type: img.mediaType, data: img.base64Data }
});
});
sdkPrompt = (async function* () {
yield {
type: "user",
session_id: currentSessionId || "",
message: { role: "user", content: contentBlocks },
parent_tool_use_id: null
};
})();
}
const result = queryFn({
prompt: sdkPrompt,
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");
// Send sessionId so browser side can save partial history for later resume
const cancelledSessionId = currentSessionId;
// Clear session so next query starts fresh
currentSessionId = null;
nodeConnector.triggerPeer("aiComplete", {
requestId: requestId,
sessionId: cancelledSessionId
});
return;
}
_log("Error:", errMsg.slice(0, 200));
// Clear session after error to prevent cascading failures from resuming a broken session
currentSessionId = null;
nodeConnector.triggerPeer("aiError", {
requestId: requestId,
error: errMsg
});
// Always send aiComplete after aiError so the UI exits streaming state
nodeConnector.triggerPeer("aiComplete", {
requestId: requestId,
sessionId: null
});
}
}