Open History to see the last commit
1import { useEffect, useState } from 'react'
2import {
3 AlertTriangle,
4 ChevronDown,
5 ChevronRight,
6 Code2,
7 Cpu,
8 Terminal,
9 Wrench,
10} from 'lucide-react'
11
12// LLM Tools - tools the LLM can call directly
13export interface LLMTool {
14 name: string
15 description: string
16}
17
18// Isolate VM options
19export type IsolateVM = 'node' | 'quickjs' | 'quickjs-bun' | 'cloudflare'
20
21export interface IsolateVMOption {
22 id: IsolateVM
23 name: string
24 description: string
25 available: boolean
26}
27
28// Isolate VM Tools - external_* functions available inside the sandbox
29export interface IsolateVMTool {
30 name: string
31 externalName: string
32 description: string
33 category: string
34}
35
36// Collapsible section component
37interface CollapsibleSectionProps {
38 title: string
39 icon: React.ReactNode
40 iconColorClass: string
41 titleColorClass: string
42 defaultOpen?: boolean
43 badge?: React.ReactNode
44 children: React.ReactNode
45}
46
47export function CollapsibleSection({
48 title,
49 icon,
50 iconColorClass,
51 titleColorClass,
52 defaultOpen = true,
53 badge,
54 children,
55}: CollapsibleSectionProps) {
56 const [isOpen, setIsOpen] = useState(defaultOpen)
57
58 return (
59 <section>
60 <button
61 onClick={() => setIsOpen(!isOpen)}
62 className="w-full flex items-center gap-2 mb-3 hover:opacity-80 transition-opacity"
63 >
64 {isOpen ? (
65 <ChevronDown className="w-4 h-4 text-gray-500" />
66 ) : (
67 <ChevronRight className="w-4 h-4 text-gray-500" />
68 )}
69 <span className={iconColorClass}>{icon}</span>
70 <h3
71 className={`text-sm font-semibold uppercase tracking-wide ${titleColorClass}`}
72 >
73 {title}
74 </h3>
75 {badge}
76 </button>
77 {isOpen && children}
78 </section>
79 )
80}
81
82// Default tool configurations
83export const DEFAULT_LLM_TOOLS: Array<LLMTool> = [
84 {
85 name: 'execute_typescript',
86 description: 'Runs TypeScript code in a sandboxed environment',
87 },
88 {
89 name: 'export_conversation_to_pdf',
90 description: 'Exports the conversation to a downloadable PDF',
91 },
92]
93
94export const DEFAULT_ISOLATE_VM_OPTIONS: Array<IsolateVMOption> = [
95 {
96 id: 'node',
97 name: 'Node.js (isolated-vm)',
98 description: 'V8 isolate with full Node.js API access',
99 available: true,
100 },
101 {
102 id: 'quickjs',
103 name: 'QuickJS',
104 description: 'Lightweight JavaScript engine',
105 available: true,
106 },
107 {
108 id: 'quickjs-bun',
109 name: 'QuickJS Bun',
110 description:
111 'Native QuickJS via bun:ffi — requires running the server with Bun; falls back to QuickJS (WASM) on a Node server',
112 available: true,
113 },
114 {
115 id: 'cloudflare',
116 name: 'Cloudflare Workers',
117 description: 'Edge runtime isolate (requires wrangler dev)',
118 available: true,
119 },
120]
121
122export const DEFAULT_ISOLATE_VM_TOOLS: Array<IsolateVMTool> = [
123 // GitHub tools
124 {
125 name: 'getStarredRepos',
126 externalName: 'external_getStarredRepos',
127 description: 'Fetch starred repos for a user',
128 category: 'github',
129 },
130 {
131 name: 'getRepoDetails',
132 externalName: 'external_getRepoDetails',
133 description: 'Get repo info (stars, forks, issues)',
134 category: 'github',
135 },
136 {
137 name: 'getRepoReleases',
138 externalName: 'external_getRepoReleases',
139 description: 'Get release history',
140 category: 'github',
141 },
142 {
143 name: 'getRepoContributors',
144 externalName: 'external_getRepoContributors',
145 description: 'Get top contributors',
146 category: 'github',
147 },
148 {
149 name: 'searchRepositories',
150 externalName: 'external_searchRepositories',
151 description: 'Search GitHub repos',
152 category: 'github',
153 },
154 // NPM tools
155 {
156 name: 'getNpmPackageInfo',
157 externalName: 'external_getNpmPackageInfo',
158 description: 'Get package metadata',
159 category: 'npm',
160 },
161 {
162 name: 'createNPMComparison',
163 externalName: 'external_createNPMComparison',
164 description: 'Create a comparison session',
165 category: 'npm',
166 },
167 {
168 name: 'addToNPMComparison',
169 externalName: 'external_addToNPMComparison',
170 description: 'Add a package to a comparison',
171 category: 'npm',
172 },
173 {
174 name: 'executeNPMComparison',
175 externalName: 'external_executeNPMComparison',
176 description: 'Run a comparison by ID',
177 category: 'npm',
178 },
179 // Utility tools
180 {
181 name: 'getCurrentDate',
182 externalName: 'external_getCurrentDate',
183 description: 'Get current date/time',
184 category: 'utility',
185 },
186 {
187 name: 'calculateStats',
188 externalName: 'external_calculateStats',
189 description: 'Calculate statistics',
190 category: 'utility',
191 },
192 {
193 name: 'formatDateRange',
194 externalName: 'external_formatDateRange',
195 description: 'Format date ranges',
196 category: 'utility',
197 },
198]
199
200// Audio-specific VM tools
201export const AUDIO_ISOLATE_VM_TOOLS: Array<IsolateVMTool> = [
202 // Audio I/O tools
203 {
204 name: 'audio_load',
205 externalName: 'external_audio_load',
206 description: 'Load audio from file, mic, or storage',
207 category: 'audio',
208 },
209 {
210 name: 'audio_store',
211 externalName: 'external_audio_store',
212 description: 'Store audio with a name',
213 category: 'audio',
214 },
215 {
216 name: 'audio_list',
217 externalName: 'external_audio_list',
218 description: 'List stored audio files',
219 category: 'audio',
220 },
221 {
222 name: 'audio_play',
223 externalName: 'external_audio_play',
224 description: 'Play stored audio',
225 category: 'audio',
226 },
227 {
228 name: 'audio_delete',
229 externalName: 'external_audio_delete',
230 description: 'Delete stored audio',
231 category: 'audio',
232 },
233 // DSP tools
234 {
235 name: 'dsp_fft',
236 externalName: 'external_dsp_fft',
237 description: 'Compute FFT spectrum',
238 category: 'dsp',
239 },
240 {
241 name: 'dsp_welch',
242 externalName: 'external_dsp_welch',
243 description: 'Welch power spectral density',
244 category: 'dsp',
245 },
246 {
247 name: 'dsp_filter',
248 externalName: 'external_dsp_filter',
249 description: 'Apply audio filters',
250 category: 'dsp',
251 },
252 {
253 name: 'dsp_eq',
254 externalName: 'external_dsp_eq',
255 description: 'Apply parametric EQ',
256 category: 'dsp',
257 },
258 {
259 name: 'dsp_normalize',
260 externalName: 'external_dsp_normalize',
261 description: 'Normalize audio level',
262 category: 'dsp',
263 },
264 // Analysis tools
265 {
266 name: 'analyze_rms',
267 externalName: 'external_analyze_rms',
268 description: 'Measure RMS level',
269 category: 'analyze',
270 },
271 {
272 name: 'analyze_peak',
273 externalName: 'external_analyze_peak',
274 description: 'Find peak amplitude',
275 category: 'analyze',
276 },
277 {
278 name: 'analyze_noiseFloor',
279 externalName: 'external_analyze_noiseFloor',
280 description: 'Measure noise floor',
281 category: 'analyze',
282 },
283 {
284 name: 'analyze_findResonances',
285 externalName: 'external_analyze_findResonances',
286 description: 'Find resonant frequencies',
287 category: 'analyze',
288 },
289 // Plot tools
290 {
291 name: 'plot_spectrum',
292 externalName: 'external_plot_spectrum',
293 description: 'Plot frequency spectrum',
294 category: 'plot',
295 },
296 {
297 name: 'plot_waveform',
298 externalName: 'external_plot_waveform',
299 description: 'Plot time-domain waveform',
300 category: 'plot',
301 },
302 {
303 name: 'plot_comparison',
304 externalName: 'external_plot_comparison',
305 description: 'Before/after comparison',
306 category: 'plot',
307 },
308]
309
310// Category configuration
311export interface CategoryConfig {
312 name: string
313 color: string
314 dotColor: string
315}
316
317export const DEFAULT_CATEGORY_CONFIG: Record<string, CategoryConfig> = {
318 github: { name: 'GitHub', color: 'text-gray-400', dotColor: 'bg-gray-500' },
319 npm: { name: 'NPM', color: 'text-gray-400', dotColor: 'bg-red-500' },
320 utility: { name: 'Utility', color: 'text-gray-400', dotColor: 'bg-blue-500' },
321}
322
323export const AUDIO_CATEGORY_CONFIG: Record<string, CategoryConfig> = {
324 audio: { name: 'Audio I/O', color: 'text-gray-400', dotColor: 'bg-cyan-500' },
325 dsp: { name: 'DSP', color: 'text-gray-400', dotColor: 'bg-purple-500' },
326 analyze: {
327 name: 'Analysis',
328 color: 'text-gray-400',
329 dotColor: 'bg-green-500',
330 },
331 plot: {
332 name: 'Visualization',
333 color: 'text-gray-400',
334 dotColor: 'bg-amber-500',
335 },
336}
337
338// LLM Tools Section Component
339interface LLMToolsSectionProps {
340 tools?: Array<LLMTool>
341 llmToolCounts?: Map<string, number>
342 llmCallCount?: number
343 totalContextBytes?: number
344 averageContextBytes?: number
345 defaultOpen?: boolean
346}
347
348export function LLMToolsSection({
349 tools = DEFAULT_LLM_TOOLS,
350 llmToolCounts = new Map(),
351 llmCallCount,
352 totalContextBytes: _totalContextBytes,
353 averageContextBytes: _averageContextBytes,
354 defaultOpen = true,
355}: LLMToolsSectionProps) {
356 const totalLLMCalls =
357 llmCallCount ??
358 Array.from(llmToolCounts.values()).reduce((a, b) => a + b, 0)
359
360 return (
361 <CollapsibleSection
362 title="LLM Tools"
363 icon={<Terminal className="w-4 h-4" />}
364 iconColorClass="text-cyan-400"
365 titleColorClass="text-cyan-300"
366 defaultOpen={defaultOpen}
367 badge={
368 totalLLMCalls > 0 ? (
369 <span className="ml-auto text-xs font-mono px-2 py-0.5 rounded-full bg-cyan-500/20 text-cyan-300">
370 {totalLLMCalls}
371 </span>
372 ) : null
373 }
374 >
375 <div className="space-y-2">
376 {tools.map((tool) => {
377 const count = llmToolCounts.get(tool.name) || 0
378 return (
379 <div
380 key={tool.name}
381 className="rounded-lg border border-cyan-500/30 bg-cyan-900/20 p-3"
382 >
383 <div className="flex items-center gap-2">
384 <Code2 className="w-4 h-4 text-cyan-400" />
385 <code className="text-sm font-mono text-cyan-300">
386 {tool.name}
387 </code>
388 {count > 0 && (
389 <span className="ml-auto text-xs font-mono px-2 py-0.5 rounded-full bg-cyan-500/30 text-cyan-200 font-medium">
390 {count}
391 </span>
392 )}
393 </div>
394 <p className="mt-1 text-xs text-gray-400">{tool.description}</p>
395 </div>
396 )
397 })}
398 </div>
399 </CollapsibleSection>
400 )
401}
402
403// Isolate VM Section Component
404interface IsolateVMSectionProps {
405 selectedVM: IsolateVM
406 onVMChange: (vm: IsolateVM) => void
407 options?: Array<IsolateVMOption>
408 defaultOpen?: boolean
409}
410
411type ServerRuntimeInfo = {
412 isBun: boolean
413 runtime: 'bun' | 'node'
414}
415
416export function IsolateVMSection({
417 selectedVM,
418 onVMChange,
419 options = DEFAULT_ISOLATE_VM_OPTIONS,
420 defaultOpen = true,
421}: IsolateVMSectionProps) {
422 const [serverRuntime, setServerRuntime] = useState<
423 ServerRuntimeInfo | null | 'error'
424 >(null)
425
426 useEffect(() => {
427 let cancelled = false
428 fetch('/api/runtime')
429 .then(async (res) => {
430 if (!res.ok) throw new Error(`HTTP ${res.status}`)
431 const data: unknown = await res.json()
432 if (
433 typeof data !== 'object' ||
434 data === null ||
435 !('isBun' in data) ||
436 typeof (data as { isBun: unknown }).isBun !== 'boolean'
437 ) {
438 throw new Error('Invalid runtime response')
439 }
440 const isBun = (data as { isBun: boolean }).isBun
441 if (!cancelled) {
442 setServerRuntime({
443 isBun,
444 runtime: isBun ? 'bun' : 'node',
445 })
446 }
447 })
448 .catch(() => {
449 if (!cancelled) setServerRuntime('error')
450 })
451 return () => {
452 cancelled = true
453 }
454 }, [])
455
456 const showBunFallbackWarning =
457 selectedVM === 'quickjs-bun' &&
458 serverRuntime !== null &&
459 serverRuntime !== 'error' &&
460 !serverRuntime.isBun
461
462 const showBunActive =
463 selectedVM === 'quickjs-bun' &&
464 serverRuntime !== null &&
465 serverRuntime !== 'error' &&
466 serverRuntime.isBun
467
468 return (
469 <CollapsibleSection
470 title="Isolate VM"
471 icon={<Cpu className="w-4 h-4" />}
472 iconColorClass="text-purple-400"
473 titleColorClass="text-purple-300"
474 defaultOpen={defaultOpen}
475 >
476 <select
477 value={selectedVM}
478 onChange={(e) => onVMChange(e.target.value as IsolateVM)}
479 className="w-full rounded-lg border border-purple-500/30 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-purple-500/50"
480 >
481 {options.map((option) => (
482 <option
483 key={option.id}
484 value={option.id}
485 disabled={!option.available}
486 >
487 {option.name}
488 {!option.available ? ' (coming soon)' : ''}
489 </option>
490 ))}
491 </select>
492 <p className="mt-2 text-xs text-gray-500">
493 {options.find((o) => o.id === selectedVM)?.description}
494 </p>
495 {showBunFallbackWarning && (
496 <div
497 role="alert"
498 className="mt-2 flex gap-2 rounded-lg border border-amber-500/40 bg-amber-950/50 px-2.5 py-2 text-xs text-amber-100"
499 >
500 <AlertTriangle
501 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-400"
502 aria-hidden
503 />
504 <div className="space-y-1">
505 <p className="font-medium text-amber-200">
506 Server is not Bun — using QuickJS (WASM) fallback
507 </p>
508 <p className="text-amber-100/80 leading-relaxed">
509 The native <code className="text-amber-50">bun:ffi</code> driver
510 only loads when the app server process has a global{' '}
511 <code className="text-amber-50">Bun</code>. Right now the server
512 reports <code className="text-amber-50">node</code>, so selections
513 of QuickJS Bun silently fall back to the WASM driver (which is
514 less reliable for multi-tool sandbox runs). Start the example
515 under a real Bun server process to exercise the native driver.
516 </p>
517 </div>
518 </div>
519 )}
520 {showBunActive && (
521 <p className="mt-2 text-xs text-emerald-400/90">
522 Server runtime is Bun — native QuickJS Bun driver will be used.
523 </p>
524 )}
525 </CollapsibleSection>
526 )
527}
528
529// VM Tools Section Component
530interface VMToolsSectionProps {
531 tools?: Array<IsolateVMTool>
532 toolInvocationCounts?: Map<string, number>
533 categoryConfig?: Record<string, CategoryConfig>
534 defaultOpen?: boolean
535}
536
537export function VMToolsSection({
538 tools = DEFAULT_ISOLATE_VM_TOOLS,
539 toolInvocationCounts = new Map(),
540 categoryConfig = DEFAULT_CATEGORY_CONFIG,
541 defaultOpen = true,
542}: VMToolsSectionProps) {
543 const totalVMCalls = Array.from(toolInvocationCounts.values()).reduce(
544 (a, b) => a + b,
545 0,
546 )
547
548 // Group tools by category
549 const toolsByCategory = tools.reduce(
550 (acc, tool) => {
551 if (!acc[tool.category]) {
552 acc[tool.category] = []
553 }
554 acc[tool.category].push(tool)
555 return acc
556 },
557 {} as Record<string, Array<IsolateVMTool>>,
558 )
559
560 return (
561 <CollapsibleSection
562 title="VM Tools"
563 icon={<Wrench className="w-4 h-4" />}
564 iconColorClass="text-amber-400"
565 titleColorClass="text-amber-300"
566 defaultOpen={defaultOpen}
567 badge={
568 totalVMCalls > 0 ? (
569 <span className="ml-auto text-xs font-mono px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-300">
570 {totalVMCalls}
571 </span>
572 ) : null
573 }
574 >
575 {Object.entries(toolsByCategory).map(([category, categoryTools]) => {
576 const config = categoryConfig[category] || {
577 name: category,
578 color: 'text-gray-400',
579 dotColor: 'bg-gray-500',
580 }
581
582 return (
583 <div key={category} className="mb-4 last:mb-0">
584 <h4 className="text-xs font-medium text-gray-400 mb-2 flex items-center gap-1.5">
585 <span className={`w-2 h-2 rounded-full ${config.dotColor}`} />
586 {config.name}
587 </h4>
588 <div className="space-y-1.5">
589 {categoryTools.map((tool) => {
590 const count = toolInvocationCounts.get(tool.externalName) || 0
591 return (
592 <div
593 key={tool.name}
594 className="group rounded border border-gray-700 bg-gray-800/50 px-2.5 py-1.5 hover:border-pink-500/40 hover:bg-pink-900/10 transition-colors"
595 >
596 <div className="flex items-center justify-between">
597 <code className="text-xs font-mono text-pink-400 group-hover:text-pink-300">
598 {tool.externalName}
599 </code>
600 {count > 0 && (
601 <span className="text-xs font-mono px-1.5 py-0.5 rounded-full bg-pink-500/20 text-pink-300 font-medium">
602 {count}
603 </span>
604 )}
605 </div>
606 <p className="text-[10px] text-gray-500 mt-0.5">
607 {tool.description}
608 </p>
609 </div>
610 )
611 })}
612 </div>
613 </div>
614 )
615 })}
616 </CollapsibleSection>
617 )
618}
619
620// Main ToolSidebar Component
621interface ToolSidebarProps {
622 selectedVM: IsolateVM
623 onVMChange: (vm: IsolateVM) => void
624 toolInvocationCounts?: Map<string, number>
625 llmToolCounts?: Map<string, number>
626 llmCallCount?: number
627 totalContextBytes?: number
628 averageContextBytes?: number
629 llmTools?: Array<LLMTool>
630 vmTools?: Array<IsolateVMTool>
631 vmOptions?: Array<IsolateVMOption>
632 categoryConfig?: Record<string, CategoryConfig>
633 llmToolsDefaultOpen?: boolean
634 isolateVMDefaultOpen?: boolean
635 vmToolsDefaultOpen?: boolean
636 children?: React.ReactNode
637 className?: string
638}
639
640export default function ToolSidebar({
641 selectedVM,
642 onVMChange,
643 toolInvocationCounts = new Map(),
644 llmToolCounts = new Map(),
645 llmCallCount,
646 totalContextBytes,
647 averageContextBytes,
648 llmTools = DEFAULT_LLM_TOOLS,
649 vmTools = DEFAULT_ISOLATE_VM_TOOLS,
650 vmOptions = DEFAULT_ISOLATE_VM_OPTIONS,
651 categoryConfig = DEFAULT_CATEGORY_CONFIG,
652 llmToolsDefaultOpen = true,
653 isolateVMDefaultOpen = true,
654 vmToolsDefaultOpen = true,
655 children,
656 className = '',
657}: ToolSidebarProps) {
658 return (
659 <aside
660 className={`w-96 border-r border-cyan-500/20 bg-gray-800/50 overflow-y-auto ${className}`}
661 >
662 <div className="p-4 space-y-6">
663 {/* Custom sections (like audio files) go first */}
664 {children}
665
666 {/* LLM Tools Section */}
667 <LLMToolsSection
668 tools={llmTools}
669 llmToolCounts={llmToolCounts}
670 llmCallCount={llmCallCount}
671 totalContextBytes={totalContextBytes}
672 averageContextBytes={averageContextBytes}
673 defaultOpen={llmToolsDefaultOpen}
674 />
675
676 {/* Isolate VM Selector */}
677 <IsolateVMSection
678 selectedVM={selectedVM}
679 onVMChange={onVMChange}
680 options={vmOptions}
681 defaultOpen={isolateVMDefaultOpen}
682 />
683
684 {/* VM Tools Section */}
685 <VMToolsSection
686 tools={vmTools}
687 toolInvocationCounts={toolInvocationCounts}
688 categoryConfig={categoryConfig}
689 defaultOpen={vmToolsDefaultOpen}
690 />
691 </div>
692 </aside>
693 )
694}