Repository navigation
Expand file tree
/
Copy pathclaude-code-agent.js
More file actions
2873 lines (2734 loc) · 136 KB
/
Copy pathclaude-code-agent.js
File metadata and controls
2873 lines (2734 loc) · 136 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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 fs = require("fs");
const os = require("os");
const path = require("path");
const { createEditorMcpServer, getImageSearchResult } = require("./mcp-editor-tools");
const CliLocator = require("./cli-locator");
const ImagePreview = require("./ai-image-preview");
const {buildSystemPrompt, buildEditorContextLine} = require("./ai-system-prompt");
const CliConnector = require("./ai-cli-connector");
const CliCapabilities = require("./ai-cli-capabilities");
const ModelEffort = require("./ai-model-effort");
const {updatePricing} = require("./ai-cli-pricing");
const NodeConnector = require("./node-connector");
exports.readImagePreview = ImagePreview.readImage;
const isWindows = process.platform === "win32";
const CONNECTOR_ID = "ph_ai_claude";
// The user's follow-up is addressed to the main agent, like a queued
// message in the Claude Code CLI. Hooks fire inside subagents too
// (input.agent_id is set there), and a subagent that reads the queue
// consumes it — the main agent then finds it empty and never sees what
// the user asked. Subagents also lack the conversation context to apply
// it sensibly. So they get neither the hint nor the tool; the main agent
// reads it as soon as it regains control.
function _clarificationHintFor(hookInput) {
if (!_queuedClarification || (hookInput && hookInput.agent_id)) {
return "";
}
return CLARIFICATION_HINT;
}
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.";
// Nudge the model when it has edited files that render in the user's live
// preview without ever looking at the result. Deliberately phrased as an FYI
// the model may act on or ignore — whether a change is worth verifying, and
// with which tool, is its call.
//
// Stated as a count rather than "you just edited…" because the PostToolUse
// fallback path can deliver this a tool call after the edit, and because
// naming the number makes it read as a summary rather than a per-edit echo.
function _livePreviewHintText(count) {
return "FYI: " + count + " file(s) you edited are rendered in the user's live preview," +
" and you have not inspected it since. Decide for yourself whether looking is worth" +
" a tool call here — a trivial or self-evident change usually is not. If it is, you" +
" pick the tool: execJsInLivePreview to read the DOM / computed styles / console," +
" takeScreenshot with selector='#panel-live-preview-frame' for a visual check, or" +
" resizeLivePreview for responsive behavior.";
}
// Reason returned when a file-rewriting shell command is stopped on its first
// attempt. A speed bump, not a wall: re-running the identical command goes
// through (see _shellEditNeedsConfirm). That protects the first edit — which a
// note after the fact cannot, since by then undo is already gone — while
// leaving the final call with the model, at the cost of one extra round trip.
//
// Preferring Edit/Write is a default, not a rule. Shell rewrites genuinely win
// on mechanical bulk changes and on large files where Edit would burn tokens
// re-reading to change a little, so the text asks the model to weigh that
// against the lost undo rather than treating the shell as forbidden. One round
// trip is negligible next to the bulk operation it is gating.
function _shellEditDenyText(what) {
return "Phoenix did not run that. It rewrites a file from the shell (" + what + "), which" +
" bypasses the editor: the user's open buffer is not refreshed, no reviewable diff is" +
" rendered, and the change cannot be undone from the AI panel's Undo button. For an" +
" ordinary content change, use Edit for existing files or Write for new ones — those" +
" keep all three. But this is a default, not a rule: if the shell is genuinely the" +
" better tool here — the user named this command, the change is mechanical across many" +
" files or matches, doing it with Edit would mean dozens of calls or reading a very" +
" large file to change a little of it, or the target is generated / build output / a" +
" log — then run it again unchanged and it will go through. Weigh the token cost" +
" against the user losing undo for that file, and tell them which way you went.";
}
// Nudge on the first unverified live preview edit, then stay quiet until this
// many more pile up without the model ever looking at the preview.
const LP_NUDGE_REPEAT_AFTER = 5;
// Hard ceiling per user request. Without it a long unverified run (30 edits)
// would emit ~6 nudges, and every one persists in the transcript. If two
// haven't changed the model's behavior, a third won't either.
const LP_MAX_NUDGES_PER_REQUEST = 2;
// Calling any of these means the model is already looking at the preview, so
// there is nothing to nag about — seeing one resets the pending count.
const LP_INSPECT_TOOLS = [
"mcp__phoenix-editor__takeScreenshot",
"mcp__phoenix-editor__execJsInLivePreview",
"mcp__phoenix-editor__resizeLivePreview"
];
// Lazy-loaded ESM module reference
let queryModule = null;
// Session state
let currentSessionId = null;
// Model list from the SDK's supportedModels() — fetched once per process,
// best-effort, from the first live query. null until available.
let cachedModelList = null;
// The model the last query sent without a model resolved to (the user's saved
// Claude Code default) and the endpoint it was resolved on, so an effort asked
// for on the default model is checked against that model, and only while the
// endpoint is the same. null until a default query has started.
let _lastResolvedDefault = null;
/**
* Fetch the model list from a live Query once per process. Best-effort:
* the control request can fail on older CLIs or non-streaming input —
* the browser keeps its static fallback list in that case.
*/
function _fetchModelListOnce(queryResult) {
if (cachedModelList) {
return;
}
queryResult.supportedModels().then(function (models) {
if (models && models.length) {
cachedModelList = models;
nodeConnector.triggerPeer("aiModelList", { models: models });
}
}).catch(function () {});
}
// Active query state
let currentAbortController = null;
let activeQuery = null;
// Lazily-initialized in-process MCP server for editor context
let editorMcpServer = null;
// Streaming throttle
const TEXT_STREAM_THROTTLE_MS = 50;
// Pending browser answers (question, plan, toolConfirm, planModeConfirm
// cards), keyed by card kind and then by confirm id. The SDK runs
// PreToolUse hooks and permission prompts for parallel tool calls
// concurrently, so several cards can be up at once — a single resolver
// slot per kind kept only the last one, and clicking any earlier card did
// nothing. Each card carries its confirmId back in the answer; an answer
// without one resolves the oldest card of that kind.
const _pendingAnswers = {};
let _confirmSeq = 0;
// Stores the last plan content written to .claude/plans/
let _lastPlanContent = null;
// Queued clarification from the user (typed while AI is streaming)
// Shape: { text: string, images: [{mediaType, base64Data}] } or null
let _queuedClarification = null;
// Module-level "runtime" permission mode that hooks read at decision time.
// One of "plan" | "acceptEdits" | "auto" (SDK classifier-approved) |
// "bypassPermissions" (Allow Everything). Updated on every sendPrompt and
// via the setPermissionMode peer when the user cycles the panel's
// permission bar mid-stream — without this, the Bash hook would close over
// the value at query start and continue prompting for confirmation even
// after the user has flipped to Allow Everything. Defaults to "auto" to
// match the browser's default (see AIChatPanel.js's _permissionMode).
let _runtimePermissionMode = "auto";
const nodeConnector = global.createNodeConnector(CONNECTOR_ID, exports);
CliConnector.setBrowserConnector(nodeConnector, NodeConnector.isConnected);
/** Create a connector only for the entitled AI-panel launch path. */
exports.createCliConnectorSession = async params => {
const command = await CliCapabilities.checkLaunch(params.cli, params.projectRoot);
const launch = await CliConnector.createSession(params);
return Object.assign(launch, {command, replaceArgs: true});
};
/** Revoke the session before its terminal is disposed. */
exports.endCliConnectorSession = async params => CliConnector.revokeSession(params.sessionId, "stopped");
/** Return connection state without exposing the window's transport credential. */
exports.getCliConnectorStatus = async params => CliConnector.getStatus(params.sessionId);
/** Disconnect or reconnect only this CLI's Phoenix tools; its terminal keeps running. */
exports.setCliConnectorEnabled = async params => CliConnector.setEnabled(params.sessionId, params.enabled);
/** Validate and atomically replace this window's Codex estimate prices; never reprices saved usage. */
exports.setExternalModelPricing = async params => updatePricing(params && params.catalog);
// Tools whose permission request in Plan Mode means "the model wants to
// start editing user files" — they share the plan-mode write-confirm card.
const FILE_WRITE_TOOLS = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
// The preferences tool both reads and writes, so it cannot carry a static
// readOnlyHint the way getEditorState does — whether a call is harmless
// depends on its `operation`.
const EDITOR_PREFS_TOOL = "mcp__phoenix-editor__editorPreferences";
function _isPreferenceRead(input) {
const op = input && input.operation;
return op === "get" || op === "list";
}
// Handed to the model right after the user approves a plan. The CLI leaves
// plan mode on approval and the model carries on in the same turn, so this
// is where "proceed" gets spelled out for Phoenix.
const PLAN_APPROVED_HINT = "The user approved the plan. Proceed with the " +
"implementation now, in this same turn. After building, verify by using " +
"execJsInLivePreview to check the result and takeScreenshot to confirm it " +
"looks correct.";
/**
* Register a card that waits for a browser answer through one of the
* answer* peers. Returns {id, promise}: send `id` to the browser as
* confirmId, then await `promise`. It resolves with the browser's payload,
* or null when the query is cancelled while the card is still up.
*/
function _registerAnswer(kind, signal) {
const id = ++_confirmSeq;
const bucket = _pendingAnswers[kind] || (_pendingAnswers[kind] = new Map());
const promise = new Promise((resolve) => {
if (signal.aborted) {
resolve(null);
return;
}
const onAbort = () => {
bucket.delete(id);
resolve(null);
};
bucket.set(id, (response) => {
signal.removeEventListener("abort", onAbort);
bucket.delete(id);
resolve(response);
});
signal.addEventListener("abort", onAbort, { once: true });
});
return { id: id, promise: promise };
}
/**
* Deliver an answer by confirmId, or to the oldest card only when no ID is supplied.
* An expired ID must never answer a newer question or permission request.
* @param {string} kind Card category.
* @param {Object} params Answer payload with an optional confirmId.
* @return {boolean} Whether a matching pending card accepted the answer.
*/
function _resolveAnswer(kind, params) {
const bucket = _pendingAnswers[kind];
if (!bucket || !bucket.size) {
return false;
}
let resolve;
if (params && params.confirmId !== undefined) {
resolve = bucket.get(params.confirmId);
} else {
resolve = bucket.values().next().value;
}
if (!resolve) { return false; }
resolve(params || {});
return true;
}
function _clearPendingAnswers() {
Object.keys(_pendingAnswers).forEach((kind) => _pendingAnswers[kind].clear());
}
/**
* Ask the user to allow or deny a tool call (the Allow/Deny card). Used by
* the Edit Mode Bash hook and for every permission request the CLI hands to
* canUseTool that no more specific card covers. Resolves true on Allow,
* false on Deny or when the query is aborted while the card is up.
*/
async function _askToolConfirm(requestId, toolName, toolInput, signal) {
const pending = _registerAnswer("toolConfirm", signal);
nodeConnector.triggerPeer("aiBashConfirm", {
requestId: requestId,
confirmId: pending.id,
toolName: toolName,
command: toolName === "Bash" ? ((toolInput && toolInput.command) || "") : "",
toolInput: toolInput || {}
});
const response = await pending.promise;
return !!(response && response.allowed);
}
/**
* Ask the user (via the browser's plan-mode write-confirm card) whether an
* Edit/Write on a user file may go through while the panel is in Plan Mode.
* Resolves true for "Allow & Switch to Auto", false for "Stay in Plan
* Mode" or when the query is aborted while the card is up.
*/
async function _askPlanModeWriteConfirm(requestId, toolName, filePath, signal) {
const pending = _registerAnswer("planModeConfirm", signal);
nodeConnector.triggerPeer("aiPlanModeWriteConfirm", {
requestId: requestId,
confirmId: pending.id,
toolName: toolName,
filePath: filePath
});
const response = await pending.promise;
return !!(response && response.approved);
}
/**
* Show the AskUserQuestion card in the browser and wait for the answers.
* Close that card when the SDK ends its wait; timeout policy belongs to the SDK.
* @param {string} requestId Owning query ID.
* @param {Array<Object>} questions Questions supplied by Claude.
* @param {AbortSignal} signal SDK question or query cancellation signal.
* @return {Promise<Object|null>} The browser's answers, or null on cancellation.
*/
async function _askUserQuestions(requestId, questions, signal) {
if (signal.aborted) { return null; }
const pending = _registerAnswer("question", signal);
nodeConnector.triggerPeer("aiQuestion", {
requestId: requestId,
confirmId: pending.id,
questions: questions
});
try {
return await pending.promise;
} finally {
nodeConnector.triggerPeer("aiQuestionClosed", {
requestId: requestId,
confirmId: pending.id
});
}
}
/**
* Format AskUserQuestion answers as readable text for the model.
*/
function _formatAnswers(answer) {
let answerText = "";
if (answer && answer.answers) {
Object.keys(answer.answers).forEach(function (q) {
answerText += "Q: " + q + "\nA: " + answer.answers[q] + "\n\n";
});
}
return answerText.trim();
}
/**
* Detect whether a PostToolUse `tool_response` represents an error result.
* Used to suppress diff-card painting when the SDK's native Edit/Write itself
* failed (e.g. oldText not found on disk). The shape of tool_response is
* `unknown` per the SDK types — handle the common variants defensively.
*/
function _isToolResponseError(toolResponse) {
if (!toolResponse) { return false; }
if (typeof toolResponse === "object") {
if (toolResponse.is_error === true || toolResponse.isError === true) { return true; }
if (Array.isArray(toolResponse.content)) {
for (const c of toolResponse.content) {
if (c && typeof c.text === "string" && /<tool_use_error>/i.test(c.text)) {
return true;
}
}
}
}
if (typeof toolResponse === "string" && /<tool_use_error>/i.test(toolResponse)) {
return true;
}
return false;
}
// Bash commands the agent can run without prompting the user in Edit
// Mode. Mirrors the CLI's default "permissions.allow" set
// (cli.js:2925) plus a small handful of universally read-only shell
// utilities. The safety belt in _isSafeReadOnlyBash splits on
// `;` / `&&` / `||` and checks every segment, so chaining safe
// commands (e.g. `git status && git log`, `sleep 1; echo done`)
// works while `git status; rm -rf /` correctly falls through.
const _SAFE_BASH_PATTERNS = [
// git read-only
/^git\s+status(\s|$)/,
/^git\s+log(\s|$)/,
/^git\s+diff(\s|$)/,
/^git\s+show(\s|$)/,
/^git\s+branch(\s|$)/,
/^git\s+ls-files(\s|$)/,
/^git\s+rev-parse(\s|$)/,
/^git\s+remote\s+show(\s|$)/,
/^git\s+--version$/,
// generic read-only shell
/^ls(\s|$)/,
/^pwd$/,
/^echo(\s|$)/,
/^which\s/,
/^cat(\s|$)/,
/^head(\s|$)/,
/^tail(\s|$)/,
/^wc(\s|$)/,
/^file\s/,
/^stat\s/,
// numeric-only sleep — no `sleep $(...)` since process substitution
// is rejected separately, but be explicit so `sleep $VAR` also fails.
/^sleep\s+\d+(\.\d+)?$/,
// version probes
/^node\s+--version$/,
/^npm\s+--version$/,
/^yarn\s+--version$/,
/^pnpm\s+--version$/
];
// Shell constructs whose purpose is rewriting a file in place. Bash is not
// interchangeable with Edit/Write here: the Edit/Write PostToolUse hooks
// refresh the open buffer, paint the diff card that backs the panel's Undo
// button, and carry the live preview signal. A shell rewrite skips all
// three, so the user silently loses undo for that change.
//
// A match stops the command once and offers a retry (see _shellEditDenyText),
// so the cost of a false positive is one wasted round trip rather than a
// refusal. Still worth keeping narrow: only constructs that exist to rewrite
// files belong here.
const _INPLACE_EDIT_PATTERNS = [
// sed -i / -i.bak / -ri / --in-place. The lookahead stops at a pipe or
// separator so `grep -i x | sed 's/a/b/'` isn't caught by the grep flag.
{ rx: /\bsed\b(?=[^|;&]*\s-(?:-in-place|[a-zA-Z]*i))/, what: "sed -i" },
// perl -pi -e / perl -i.bak
{ rx: /\bperl\b(?=[^|;&]*\s-[a-zA-Z]*i)/, what: "perl -i" },
{ rx: /\bawk\b(?=[^|;&]*\s-i\s+inplace)/, what: "awk -i inplace" },
{ rx: /\bed\s+-s\b/, what: "ed -s" },
{ rx: /\bex\s+-s(c|\s)/, what: "ex -s" },
// PowerShell equivalents — on Windows the model may reach for these
// instead of sed. Set-Content/Add-Content/Out-File all rewrite a file.
{ rx: /\b(?:Set-Content|Add-Content|Out-File)\b/i, what: "PowerShell Set-Content / Out-File" }
];
// Redirection / tee targets that aren't the user's files: device sinks and
// scratch dirs. `> /dev/null` and `> $TMPDIR/x` are ubiquitous and carry no
// undo cost, so hinting about them would be pure noise.
//
// Covers all three platforms, since the model may be driving bash, PowerShell
// or cmd depending on where Phoenix is running: macOS puts TMPDIR under
// /var/folders, Windows under %TEMP% / AppData\Local\Temp, and the null sink
// is /dev/null, NUL or $null respectively.
const _EXEMPT_WRITE_TARGETS = [
/^\/dev\//,
/^\/proc\//,
/^\/(?:private\/)?tmp\//,
/^\/var\/(?:tmp|folders)\//,
/^(?:nul|\$null)$/i,
/^\$\{?TMPDIR\}?[\\/]/i,
/^%(?:TEMP|TMP)%[\\/]/i,
/^[a-zA-Z]:[\\/](?:temp|tmp)[\\/]/i,
// Git Bash rewrites C:\Temp to MSYS form (/c/temp), and it is the shell
// the Bash tool actually uses on Windows.
/^\/[a-zA-Z]\/(?:temp|tmp)\//i,
/[\\/]AppData[\\/]Local[\\/]Temp[\\/]/i,
/^[a-zA-Z]:[\\/]Windows[\\/]Temp[\\/]/i
];
function _isExemptWriteTarget(target) {
if (target === "-") { return true; }
return _EXEMPT_WRITE_TARGETS.some(function (rx) { return rx.test(target); });
}
// Walk the command tracking quote state so a `>` inside a string literal
// (`echo "a > b"`, `python -c "print(1 > 0)"`) is not mistaken for a
// redirection. Returns the write destinations found outside quotes.
// A heuristic guard, not a shell parser.
function _shellWriteTargets(rawCmd) {
// Drop file-descriptor duplications (2>&1, >&2, 1>&2) up front.
const cmd = (rawCmd || "").replace(/\d*>&\d*/g, " ");
const targets = [];
let quote = null;
for (let i = 0; i < cmd.length; i++) {
const ch = cmd[i];
if (quote) {
if (ch === quote && cmd[i - 1] !== "\\") { quote = null; }
continue;
}
if (ch === "\"" || ch === "'") { quote = ch; continue; }
if (ch !== ">") { continue; }
// Skip the rest of a `>>` pair, then the whitespace before the target.
let j = i + 1;
while (cmd[j] === ">") { j++; }
while (cmd[j] === " " || cmd[j] === "\t") { j++; }
// Read the target, honouring quotes around a path with spaces.
let target = "";
if (cmd[j] === "\"" || cmd[j] === "'") {
const closer = cmd[j];
j++;
while (j < cmd.length && cmd[j] !== closer) { target += cmd[j++]; }
} else {
while (j < cmd.length && !/[\s;|&()]/.test(cmd[j])) { target += cmd[j++]; }
}
if (target) { targets.push(target); }
i = j - 1;
}
// tee writes to its path arguments rather than via redirection.
const tee = /\btee\s+(?:-a\s+)?("[^"]*"|'[^']*'|[^\s;|&()-][^\s;|&()]*)/g;
let m;
while ((m = tee.exec(cmd)) !== null) {
targets.push(m[1].replace(/^["']|["']$/g, ""));
}
return targets.filter(function (t) { return t && !_isExemptWriteTarget(t); });
}
/**
* Classify a Bash command that would rewrite file content instead of going
* through Edit/Write. Returns a short description of what was matched, or
* null when the command is fine to run.
*/
function _describeInPlaceFileEdit(rawCmd) {
const cmd = (rawCmd || "").trim();
if (!cmd) { return null; }
for (const entry of _INPLACE_EDIT_PATTERNS) {
if (entry.rx.test(cmd)) { return entry.what; }
}
const targets = _shellWriteTargets(cmd);
if (targets.length) {
return "shell redirection to " + targets[0];
}
return null;
}
function _isSafeReadOnlyBash(rawCmd) {
const cmd = (rawCmd || "").trim();
if (!cmd) { return false; }
// Reject command/process substitution, redirection, and pipes —
// these can hide arbitrary commands or send output to dangerous
// places. Backticks, `$(...)`, `<`, `>`, `|`. Plain `$VAR` is
// allowed (substitution-without-command).
if (/[`<>|]|\$\(/.test(cmd)) { return false; }
// Split on `;`, `&&`, `||` and verify EVERY segment matches a safe
// pattern. Quotes around delimiters are not handled — a command
// like `echo "a; b"` will split mid-string and fail safe-check
// (which is fine: false negatives are OK, false positives are not).
const segments = cmd.split(/\s*(?:;|&&|\|\|)\s*/).filter(Boolean);
return segments.every(function (seg) {
return _SAFE_BASH_PATTERNS.some(function (rx) { return rx.test(seg); });
});
}
/**
* Lazily import the ESM Claude Agent SDK module.
*/
async function getQueryFn() {
if (!queryModule) {
// The JS SDK was split out of @anthropic-ai/claude-code in v2 and
// moved to @anthropic-ai/claude-agent-sdk. The CLI binary still
// ships under @anthropic-ai/claude-code (used by Phoenix's
// terminal "claude" command); the SDK now lives in its own
// package with the same query() signature and SDKResultMessage
// shape, so the rest of this file is unchanged.
queryModule = await import("@anthropic-ai/claude-agent-sdk");
}
return queryModule.query;
}
/**
* Best-effort AI-generated title for a session.
*
* The CLI writes an `ai-title` entry into the session JSONL on the first
* turn — a few words describing what the conversation is actually about.
* The SDK surfaces it as `SDKSessionInfo.summary`, preferring a user-set
* custom title and falling back to the raw first prompt when neither
* exists. We only report a title that beats that fallback, so the panel
* keeps its own first-message title when the CLI has nothing better
* (older CLI builds, or a session that ended before the title landed).
*
* @param {string} sessionId
* @param {string} projectPath
* @return {Promise<string|null>} short title, or null when unavailable
*/
async function _getAISessionTitle(sessionId, projectPath) {
if (!sessionId) {
return null;
}
try {
if (!queryModule) {
queryModule = await import("@anthropic-ai/claude-agent-sdk");
}
if (typeof queryModule.getSessionInfo !== "function") {
return null;
}
const info = await queryModule.getSessionInfo(sessionId,
projectPath ? { dir: projectPath } : undefined);
const title = info && info.summary ? info.summary.trim() : "";
if (!title || title === (info.firstPrompt || "").trim()) {
return null;
}
return title;
} catch (e) {
console.log("[Phoenix AI] Session title lookup failed:", e.message);
return null;
}
}
// Brand names for the messages below. Not translatable and never shown
// raw — the browser maps errorCode to a localized string; these only reach
// logs and metrics.
const CLI_DISPLAY_NAMES = { claude: "Claude Code CLI", codex: "Codex CLI" };
/**
* Human-readable summary of why a CLI could not be resolved. The browser
* localizes from `errorCode`; this string is for logs, metrics, and the
* existing `_renderUnavailableUI(result.error)` path.
*/
function _cliErrorMessage(cliId, located) {
const name = CLI_DISPLAY_NAMES[cliId] || cliId;
switch (located.errorCode) {
case CliLocator.ERROR_CODES.OVERRIDE_MISSING:
return "Configured " + name + " path not found: " + (located.override && located.override.path);
case CliLocator.ERROR_CODES.OVERRIDE_NOT_EXECUTABLE:
return "Configured " + name + " path is not executable: " + (located.override && located.override.path);
case CliLocator.ERROR_CODES.OVERRIDE_INVALID:
return "Configured " + name + " path is not a working " + name;
case CliLocator.ERROR_CODES.OVERRIDE_TIMEOUT:
return "Configured " + name + " path did not respond in time";
case CliLocator.ERROR_CODES.OVERRIDE_REJECTED:
return "Configured " + name + " path contains unsupported characters";
default:
return name + " not found";
}
}
/**
* Ask claude whether the user is signed in. Only claude has a
* machine-readable answer (`claude auth status` prints JSON); codex's login
* lives behind a browser/TTY flow, so its terminal shows that itself.
* @return {Promise<{loggedIn: boolean, claudePath: string|null}>} claudePath
* is re-resolved when the cached binary turns out to be gone
*/
async function _probeClaudeLogin(claudePath) {
let loggedIn = false;
let result;
try {
result = await CliLocator.spawnCli(claudePath, ["auth", "status"], {
encoding: "utf8",
timeout: 10000
});
// Spawn-level failure (ENOENT/EACCES — e.g. user uninstalled
// mid-session) means the cached binary is unusable. Invalidate
// and re-discover once. Distinct from "binary ran but exited
// non-zero", which we still treat as "not logged in".
if (result.error && result.status === null) {
const relocated = await CliLocator.locateCli("claude", { force: true });
if (!relocated.path) {
return { loggedIn: false, claudePath: null };
}
claudePath = relocated.path;
result = await CliLocator.spawnCli(claudePath, ["auth", "status"], {
encoding: "utf8",
timeout: 10000
});
}
if (result.status === 0 && result.stdout) {
const authStatus = JSON.parse(result.stdout);
loggedIn = authStatus.loggedIn === true;
}
} catch (e) {
// auth status failed — treat as not logged in
}
return { loggedIn: loggedIn, claudePath: claudePath };
}
/**
* Whether one of the CLIs the AI panel can drive is installed and usable.
* Called from browser via execPeer("checkCliAvailability", {cli}).
*
* @param {Object} opts - `{cli}` "claude" (default) or "codex";
* `{refresh}` bypasses the cached miss — the install/login poll loops
* pass it because they are explicitly waiting on state to change;
* `{overridePath}` resolves against that path for this call only, so
* the settings UI can test a path without committing it;
* `{probeLogin}` defaults to true for claude, false for codex.
* @return {Promise<Object>} `{cli, available, path, source, version, loggedIn,
* loginProbeSupported, error, errorCode, override, searchedPaths}`
*/
exports.checkCliAvailability = async function (opts) {
const cliId = (opts && opts.cli) || "claude";
const canProbeLogin = cliId === "claude";
const probeLogin = (opts && opts.probeLogin !== undefined) ? !!opts.probeLogin : canProbeLogin;
try {
const locateOpts = {};
if (opts && opts.refresh) {
locateOpts.force = true;
}
if (opts && opts.overridePath !== undefined) {
locateOpts.override = opts.overridePath;
}
const located = await CliLocator.locateCli(cliId, locateOpts);
const base = {
cli: cliId,
loginProbeSupported: canProbeLogin,
source: located.source,
version: located.version,
userInstalled: located.userInstalled,
override: located.override,
searchedPaths: located.searchedPaths
};
if (!located.path) {
return Object.assign(base, {
available: false,
path: null,
error: _cliErrorMessage(cliId, located),
errorCode: located.errorCode
});
}
let cliPath = located.path;
let loggedIn;
if (probeLogin && canProbeLogin) {
const login = await _probeClaudeLogin(cliPath);
if (!login.claudePath) {
return Object.assign(base, {
available: false,
path: null,
error: _cliErrorMessage(cliId, { errorCode: CliLocator.ERROR_CODES.NOT_FOUND }),
errorCode: CliLocator.ERROR_CODES.NOT_FOUND
});
}
cliPath = login.claudePath;
loggedIn = login.loggedIn;
}
return Object.assign(base, {
available: true,
path: cliPath,
loggedIn: loggedIn,
error: null,
errorCode: null
});
} catch (err) {
return {
cli: cliId,
available: false,
path: null,
loginProbeSupported: canProbeLogin,
error: err.message,
errorCode: CliLocator.ERROR_CODES.NOT_FOUND
};
}
};
/**
* Check whether Claude CLI is available.
* Called from browser via execPeer("checkAvailability").
*
* Kept as its own peer on top of checkCliAvailability: several browser call
* sites read `claudePath` and the login state, and that legacy key belongs
* on a claude-shaped result rather than becoming a lie on a codex one.
*/
exports.checkAvailability = async function (opts) {
const result = await exports.checkCliAvailability(
Object.assign({}, opts, { cli: "claude", probeLogin: true }));
result.claudePath = result.path;
return result;
};
/**
* Record the CLI executable paths the user configured in AI Settings.
* Called from browser via execPeer("setCliPathOverrides", {claude, codex}).
* An empty string clears an override and restores auto-detection.
*/
exports.setCliPathOverrides = async function (params) {
const applied = CliLocator.setOverrides(params || {});
console.log("[Phoenix AI] CLI path overrides:", JSON.stringify(applied));
return { applied: applied };
};
/**
* Test one CLI path without disturbing the cache — for the settings UI, so
* it never has to reimplement what counts as a working CLI.
* Called from browser via execPeer("validateCliPath", {cli, path}).
*/
exports.validateCliPath = async function (params) {
const cliId = (params && params.cli) || "claude";
return CliLocator.validateCliPath(cliId, (params && params.path) || "");
};
/**
* Which downloader the CLI install one-liner can use on this machine.
* Called from browser via execPeer("getInstallDownloader").
* @return {Promise<{downloader: ?string}>} "curl", "wget", or null
*/
exports.getInstallDownloader = async function () {
return { downloader: CliLocator.findDownloader() };
};
/**
* How to spawn a CLI in a PTY: availability plus the command/args the
* terminal should use. Callers must not spawn `path` directly — on Windows
* an npm-installed CLI resolves to a `.cmd` shim, which node-pty cannot
* execute (CreateProcess runs .exe/.com only), so it has to go through
* `cmd.exe /c`.
* Called from browser via execPeer("getCliSpawnProfile", {cli}).
*/
exports.getCliSpawnProfile = async function (params) {
const cliId = (params && params.cli) || "claude";
const result = await exports.checkCliAvailability({
cli: cliId,
probeLogin: false,
overridePath: params && params.overridePath
});
if (!result.available) {
return Object.assign({}, result, { command: null, args: [] });
}
const profile = CliLocator.getSpawnProfile(result.path, result.source);
return Object.assign({}, result, profile);
};
// The assistant's own UI files for askInLivePreview live in Phoenix's app data, never in the
// project. Writing there is the assistant's business: no permission card, no snapshot, no
// edit event, no card in the chat.
let _aiScratchDir = null;
function _isAiScratchPath(filePath) {
if (!_aiScratchDir || !filePath || !path.isAbsolute(filePath)) {
return false;
}
const root = path.resolve(_aiScratchDir);
const target = path.resolve(filePath);
return target === root || target.startsWith(root + path.sep);
}
/**
* Send a prompt to Claude and stream results back to the browser.
* Called from browser via execPeer("sendPrompt", {prompt, projectPath, sessionAction, model, effort}).
* effort is a thinking effort level for the model, or absent to leave the default to the SDK.
*
* 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, effort, locale, selectionContext, editorContext,
images, envOverrides, permissionMode, additionalDirectories, aiScratchDir } = params;
if (typeof aiScratchDir === "string" && aiScratchDir) {
_aiScratchDir = aiScratchDir;
}
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 what the user is looking at. The panel knows the active file,
// the unsaved buffers and the live preview target for certain, so stating
// them costs one line and removes the reason to go hunting: without it
// the model opens by grepping the project for a file already on screen.
const editorContextLine = buildEditorContextLine(editorContext);
// 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;
}
}
if (editorContextLine) {
enrichedPrompt = editorContextLine + "\n\n" + enrichedPrompt;
}
// Run the query asynchronously — don't await here so we return requestId immediately
_runQuery(requestId, enrichedPrompt, projectPath, model, currentAbortController.signal, locale, images, envOverrides, permissionMode, additionalDirectories, effort)
.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;
// Keep currentSessionId so the next prompt resumes the same SDK session.
// Aborts leave an interrupt marker in the session log, not a corrupted state.
// Drop any cards still waiting for an answer
_clearPendingAnswers();
_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) {
_resolveAnswer("question", params);
return { success: true };
};
/**
* Receive the user's response to a proposed plan.
* Called from browser via execPeer("answerPlan", {approved, feedback}).
*/
exports.answerPlan = async function (params) {
_resolveAnswer("plan", params);
return { success: true };
};
/**
* Receive the user's response to a bash confirmation prompt (Edit Mode).
* Called from browser via execPeer("answerBashConfirm", {allowed}).
*/
exports.answerBashConfirm = async function (params) {
_resolveAnswer("toolConfirm", params);
return { success: true };
};
/**
* Receive the user's response to a plan-mode write confirmation prompt.
* Called from browser via execPeer("answerPlanModeWriteConfirm", {approved}).
*/
exports.answerPlanModeWriteConfirm = async function (params) {
_resolveAnswer("planModeConfirm", params);
return { success: true };
};
/**
* Apply a mid-stream permission-mode change so hooks running for the rest
* of the turn use the new value. Called from the browser when the user
* cycles the permission bar (so e.g. Bash stops prompting immediately
* after switching from Edit Mode to Allow Everything). The next sendPrompt also
* passes permissionMode in params, so this peer is only strictly required
* during streaming — but calling it on every cycle keeps the agent's
* tracker and the SDK session authoritative.
* @param {{mode: string}} params Requested SDK permission mode.
* @return {Promise<{success: boolean}>} Resolves after the active SDK session is updated.
*/
exports.setPermissionMode = async function (params) {
if (params && typeof params.mode === "string") {
_runtimePermissionMode = params.mode;
if (activeQuery && !activeQuery.signal.aborted) {
const current = activeQuery;
// Keep rapid mode changes in order; a failed earlier update must
// not prevent a subsequent explicit choice from reaching the SDK.
current.modeUpdate = current.modeUpdate.catch(() => {}).then(async () => {
if (current.signal.aborted) { throw new Error("Permission mode update cancelled"); }
let timeout;
try {
await Promise.race([
current.query.setPermissionMode(params.mode),
new Promise((resolve, reject) => {
timeout = setTimeout(() => reject(new Error("Permission mode update timed out")), 10000);
})
]);
} finally {
clearTimeout(timeout);
}
});
try {
await current.modeUpdate;
} catch (err) {