@emblemvault/hustle-react 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +225 -0
  2. package/dist/browser/hustle-react.js +14705 -0
  3. package/dist/browser/hustle-react.js.map +1 -0
  4. package/dist/components/index.cjs +3170 -0
  5. package/dist/components/index.cjs.map +1 -0
  6. package/dist/components/index.d.cts +58 -0
  7. package/dist/components/index.d.ts +58 -0
  8. package/dist/components/index.js +3143 -0
  9. package/dist/components/index.js.map +1 -0
  10. package/dist/hooks/index.cjs +695 -0
  11. package/dist/hooks/index.cjs.map +1 -0
  12. package/dist/hooks/index.d.cts +46 -0
  13. package/dist/hooks/index.d.ts +46 -0
  14. package/dist/hooks/index.js +691 -0
  15. package/dist/hooks/index.js.map +1 -0
  16. package/dist/hustle-S48t4lTZ.d.cts +222 -0
  17. package/dist/hustle-S48t4lTZ.d.ts +222 -0
  18. package/dist/index.cjs +3588 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +229 -0
  21. package/dist/index.d.ts +229 -0
  22. package/dist/index.js +3547 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/plugin-BUg7vMxe.d.cts +172 -0
  25. package/dist/plugin-BUg7vMxe.d.ts +172 -0
  26. package/dist/plugins/index.cjs +1235 -0
  27. package/dist/plugins/index.cjs.map +1 -0
  28. package/dist/plugins/index.d.cts +192 -0
  29. package/dist/plugins/index.d.ts +192 -0
  30. package/dist/plugins/index.js +1225 -0
  31. package/dist/plugins/index.js.map +1 -0
  32. package/dist/providers/index.cjs +694 -0
  33. package/dist/providers/index.cjs.map +1 -0
  34. package/dist/providers/index.d.cts +46 -0
  35. package/dist/providers/index.d.ts +46 -0
  36. package/dist/providers/index.js +691 -0
  37. package/dist/providers/index.js.map +1 -0
  38. package/package.json +87 -0
@@ -0,0 +1,3143 @@
1
+ import { createContext, useState, useRef, useEffect, useCallback, useContext } from 'react';
2
+ import 'hustle-incognito';
3
+ import { useEmblemAuthOptional } from '@emblemvault/emblem-auth-react';
4
+ import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
5
+ import { marked } from 'marked';
6
+ import hljs from 'highlight.js/lib/core';
7
+ import javascript from 'highlight.js/lib/languages/javascript';
8
+ import typescript from 'highlight.js/lib/languages/typescript';
9
+ import python from 'highlight.js/lib/languages/python';
10
+ import json from 'highlight.js/lib/languages/json';
11
+ import bash from 'highlight.js/lib/languages/bash';
12
+ import shell from 'highlight.js/lib/languages/shell';
13
+ import css from 'highlight.js/lib/languages/css';
14
+ import xml from 'highlight.js/lib/languages/xml';
15
+ import markdown from 'highlight.js/lib/languages/markdown';
16
+ import sql from 'highlight.js/lib/languages/sql';
17
+ import yaml from 'highlight.js/lib/languages/yaml';
18
+ import rust from 'highlight.js/lib/languages/rust';
19
+ import go from 'highlight.js/lib/languages/go';
20
+ import java from 'highlight.js/lib/languages/java';
21
+ import cpp from 'highlight.js/lib/languages/cpp';
22
+ import csharp from 'highlight.js/lib/languages/csharp';
23
+ import php from 'highlight.js/lib/languages/php';
24
+ import ruby from 'highlight.js/lib/languages/ruby';
25
+ import swift from 'highlight.js/lib/languages/swift';
26
+ import kotlin from 'highlight.js/lib/languages/kotlin';
27
+
28
+ // src/utils/pluginRegistry.ts
29
+ var PLUGINS_KEY = "hustle-plugins";
30
+ function getEnabledStateKey(instanceId) {
31
+ return `hustle-plugin-state-${instanceId}`;
32
+ }
33
+ function serializeFunction(fn) {
34
+ return fn.toString();
35
+ }
36
+ function deserializeExecutor(code) {
37
+ try {
38
+ return eval(`(${code})`);
39
+ } catch (err) {
40
+ console.error("[Hustle] Failed to deserialize executor:", err);
41
+ return async () => ({ error: "Failed to deserialize executor", code });
42
+ }
43
+ }
44
+ function deserializeHook(code) {
45
+ try {
46
+ return eval(`(${code})`);
47
+ } catch (err) {
48
+ console.error("[Hustle] Failed to deserialize hook:", err);
49
+ return (() => {
50
+ });
51
+ }
52
+ }
53
+ function serializePluginTools(tools, executors) {
54
+ if (!tools) return [];
55
+ return tools.map((tool) => ({
56
+ ...tool,
57
+ executorCode: executors?.[tool.name] ? serializeFunction(executors[tool.name]) : void 0
58
+ }));
59
+ }
60
+ function serializeHooks(hooks) {
61
+ if (!hooks) return void 0;
62
+ const serialized = {};
63
+ if (hooks.onRegister) {
64
+ serialized.onRegisterCode = serializeFunction(hooks.onRegister);
65
+ }
66
+ if (hooks.beforeRequest) {
67
+ serialized.beforeRequestCode = serializeFunction(hooks.beforeRequest);
68
+ }
69
+ if (hooks.afterResponse) {
70
+ serialized.afterResponseCode = serializeFunction(hooks.afterResponse);
71
+ }
72
+ if (hooks.onError) {
73
+ serialized.onErrorCode = serializeFunction(hooks.onError);
74
+ }
75
+ return Object.keys(serialized).length > 0 ? serialized : void 0;
76
+ }
77
+ function hydratePlugin(stored) {
78
+ const executors = {};
79
+ if (stored.tools) {
80
+ for (const tool of stored.tools) {
81
+ if (tool.executorCode) {
82
+ executors[tool.name] = deserializeExecutor(tool.executorCode);
83
+ }
84
+ }
85
+ }
86
+ let hooks;
87
+ if (stored.hooksCode) {
88
+ hooks = {};
89
+ if (stored.hooksCode.onRegisterCode) {
90
+ hooks.onRegister = deserializeHook(stored.hooksCode.onRegisterCode);
91
+ }
92
+ if (stored.hooksCode.beforeRequestCode) {
93
+ hooks.beforeRequest = deserializeHook(stored.hooksCode.beforeRequestCode);
94
+ }
95
+ if (stored.hooksCode.afterResponseCode) {
96
+ hooks.afterResponse = deserializeHook(stored.hooksCode.afterResponseCode);
97
+ }
98
+ if (stored.hooksCode.onErrorCode) {
99
+ hooks.onError = deserializeHook(stored.hooksCode.onErrorCode);
100
+ }
101
+ }
102
+ return {
103
+ ...stored,
104
+ executors: Object.keys(executors).length > 0 ? executors : void 0,
105
+ hooks
106
+ };
107
+ }
108
+ var PluginRegistry = class {
109
+ constructor() {
110
+ this.listeners = /* @__PURE__ */ new Map();
111
+ }
112
+ /**
113
+ * Get listeners for a specific instance
114
+ */
115
+ getListeners(instanceId) {
116
+ if (!this.listeners.has(instanceId)) {
117
+ this.listeners.set(instanceId, /* @__PURE__ */ new Set());
118
+ }
119
+ return this.listeners.get(instanceId);
120
+ }
121
+ /**
122
+ * Load installed plugins (global)
123
+ */
124
+ loadInstalledPlugins() {
125
+ if (typeof window === "undefined") return [];
126
+ try {
127
+ const stored = localStorage.getItem(PLUGINS_KEY);
128
+ return stored ? JSON.parse(stored) : [];
129
+ } catch {
130
+ return [];
131
+ }
132
+ }
133
+ /**
134
+ * Save installed plugins (global)
135
+ * Serializes executors as executorCode strings
136
+ */
137
+ saveInstalledPlugins(plugins) {
138
+ if (typeof window === "undefined") return;
139
+ localStorage.setItem(PLUGINS_KEY, JSON.stringify(plugins));
140
+ }
141
+ /**
142
+ * Load enabled state for an instance
143
+ */
144
+ loadEnabledState(instanceId) {
145
+ if (typeof window === "undefined") return {};
146
+ try {
147
+ const stored = localStorage.getItem(getEnabledStateKey(instanceId));
148
+ return stored ? JSON.parse(stored) : {};
149
+ } catch {
150
+ return {};
151
+ }
152
+ }
153
+ /**
154
+ * Save enabled state for an instance
155
+ */
156
+ saveEnabledState(state, instanceId) {
157
+ if (typeof window === "undefined") return;
158
+ localStorage.setItem(getEnabledStateKey(instanceId), JSON.stringify(state));
159
+ }
160
+ /**
161
+ * Load plugins with instance-specific enabled state
162
+ * Combines global plugin list with per-instance enabled state
163
+ */
164
+ loadFromStorage(instanceId = "default") {
165
+ const installed = this.loadInstalledPlugins();
166
+ const enabledState = this.loadEnabledState(instanceId);
167
+ return installed.map((plugin) => ({
168
+ ...plugin,
169
+ // Default to enabled if no state exists for this instance
170
+ enabled: enabledState[plugin.name] ?? true
171
+ }));
172
+ }
173
+ /**
174
+ * Register a new plugin (global - available to all instances)
175
+ * Serializes executors as executorCode for persistence
176
+ *
177
+ * @param plugin The plugin to install
178
+ * @param enabled Initial enabled state for this instance (default: true)
179
+ * @param instanceId Instance to set initial enabled state for
180
+ */
181
+ register(plugin, enabled = true, instanceId = "default") {
182
+ const installed = this.loadInstalledPlugins();
183
+ const existing = installed.findIndex((p) => p.name === plugin.name);
184
+ const storedPlugin = {
185
+ name: plugin.name,
186
+ version: plugin.version,
187
+ description: plugin.description,
188
+ tools: serializePluginTools(plugin.tools, plugin.executors),
189
+ hooksCode: serializeHooks(plugin.hooks),
190
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
191
+ };
192
+ if (existing >= 0) {
193
+ installed[existing] = storedPlugin;
194
+ } else {
195
+ installed.push(storedPlugin);
196
+ }
197
+ this.saveInstalledPlugins(installed);
198
+ const enabledState = this.loadEnabledState(instanceId);
199
+ enabledState[plugin.name] = enabled;
200
+ this.saveEnabledState(enabledState, instanceId);
201
+ this.notifyListeners(instanceId);
202
+ }
203
+ /**
204
+ * Unregister a plugin (global - removes from all instances)
205
+ */
206
+ unregister(pluginName, instanceId = "default") {
207
+ const installed = this.loadInstalledPlugins().filter((p) => p.name !== pluginName);
208
+ this.saveInstalledPlugins(installed);
209
+ const enabledState = this.loadEnabledState(instanceId);
210
+ delete enabledState[pluginName];
211
+ this.saveEnabledState(enabledState, instanceId);
212
+ this.notifyListeners(instanceId);
213
+ }
214
+ /**
215
+ * Enable or disable a plugin (instance-scoped)
216
+ */
217
+ setEnabled(pluginName, enabled, instanceId = "default") {
218
+ const enabledState = this.loadEnabledState(instanceId);
219
+ enabledState[pluginName] = enabled;
220
+ this.saveEnabledState(enabledState, instanceId);
221
+ this.notifyListeners(instanceId);
222
+ }
223
+ /**
224
+ * Check if a plugin is installed (global)
225
+ */
226
+ isRegistered(pluginName) {
227
+ return this.loadInstalledPlugins().some((p) => p.name === pluginName);
228
+ }
229
+ /**
230
+ * Get a specific plugin with instance-specific enabled state
231
+ */
232
+ getPlugin(pluginName, instanceId = "default") {
233
+ return this.loadFromStorage(instanceId).find((p) => p.name === pluginName);
234
+ }
235
+ /**
236
+ * Get all enabled plugins for an instance (hydrated with executors)
237
+ */
238
+ getEnabledPlugins(instanceId = "default") {
239
+ return this.loadFromStorage(instanceId).filter((p) => p.enabled).map(hydratePlugin);
240
+ }
241
+ /**
242
+ * Subscribe to plugin changes for a specific instance
243
+ */
244
+ onChange(callback, instanceId = "default") {
245
+ const listeners = this.getListeners(instanceId);
246
+ listeners.add(callback);
247
+ return () => listeners.delete(callback);
248
+ }
249
+ /**
250
+ * Notify all listeners for a specific instance
251
+ */
252
+ notifyListeners(instanceId = "default") {
253
+ const plugins = this.loadFromStorage(instanceId);
254
+ const listeners = this.getListeners(instanceId);
255
+ listeners.forEach((cb) => cb(plugins));
256
+ }
257
+ /**
258
+ * Clear enabled state for an instance (plugins remain installed globally)
259
+ */
260
+ clear(instanceId = "default") {
261
+ if (typeof window === "undefined") return;
262
+ localStorage.removeItem(getEnabledStateKey(instanceId));
263
+ this.notifyListeners(instanceId);
264
+ }
265
+ /**
266
+ * Clear all installed plugins globally
267
+ */
268
+ clearAll() {
269
+ if (typeof window === "undefined") return;
270
+ localStorage.removeItem(PLUGINS_KEY);
271
+ }
272
+ };
273
+ var pluginRegistry = new PluginRegistry();
274
+
275
+ // src/hooks/usePlugins.ts
276
+ function getStorageKey(instanceId) {
277
+ return `hustle-plugins-${instanceId}`;
278
+ }
279
+ function usePlugins(instanceId = "default") {
280
+ const [plugins, setPlugins] = useState([]);
281
+ useEffect(() => {
282
+ setPlugins(pluginRegistry.loadFromStorage(instanceId));
283
+ const unsubscribe = pluginRegistry.onChange(setPlugins, instanceId);
284
+ const storageKey = getStorageKey(instanceId);
285
+ const handleStorage = (e) => {
286
+ if (e.key === storageKey) {
287
+ setPlugins(pluginRegistry.loadFromStorage(instanceId));
288
+ }
289
+ };
290
+ window.addEventListener("storage", handleStorage);
291
+ return () => {
292
+ unsubscribe();
293
+ window.removeEventListener("storage", handleStorage);
294
+ };
295
+ }, [instanceId]);
296
+ const registerPlugin = useCallback((plugin) => {
297
+ pluginRegistry.register(plugin, true, instanceId);
298
+ }, [instanceId]);
299
+ const unregisterPlugin = useCallback((name) => {
300
+ pluginRegistry.unregister(name, instanceId);
301
+ }, [instanceId]);
302
+ const enablePlugin = useCallback((name) => {
303
+ pluginRegistry.setEnabled(name, true, instanceId);
304
+ }, [instanceId]);
305
+ const disablePlugin = useCallback((name) => {
306
+ pluginRegistry.setEnabled(name, false, instanceId);
307
+ }, [instanceId]);
308
+ const isRegistered = useCallback(
309
+ (name) => plugins.some((p) => p.name === name),
310
+ [plugins]
311
+ );
312
+ const isEnabled = useCallback(
313
+ (name) => plugins.some((p) => p.name === name && p.enabled),
314
+ [plugins]
315
+ );
316
+ const enabledPlugins = plugins.filter((p) => p.enabled).map(hydratePlugin);
317
+ return {
318
+ plugins,
319
+ enabledPlugins,
320
+ registerPlugin,
321
+ unregisterPlugin,
322
+ enablePlugin,
323
+ disablePlugin,
324
+ isRegistered,
325
+ isEnabled
326
+ };
327
+ }
328
+ var HustleContext = createContext(void 0);
329
+ function useHustle() {
330
+ const context = useContext(HustleContext);
331
+ if (context === void 0) {
332
+ throw new Error("useHustle must be used within a HustleProvider (which requires EmblemAuthProvider)");
333
+ }
334
+ return context;
335
+ }
336
+
337
+ // src/plugins/predictionMarket.ts
338
+ var DOME_API_BASE = "https://api.domeapi.io/v1";
339
+ var predictionMarketPlugin = {
340
+ name: "prediction-market-alpha",
341
+ version: "1.1.0",
342
+ description: "Search and analyze prediction markets on Polymarket and Kalshi",
343
+ tools: [
344
+ {
345
+ name: "get_supported_platforms",
346
+ description: "Get a list of supported prediction market platforms. Call this first to know which platforms are available for querying.",
347
+ parameters: {
348
+ type: "object",
349
+ properties: {}
350
+ }
351
+ },
352
+ {
353
+ name: "search_prediction_markets",
354
+ description: "Search for prediction markets. Find markets about politics, crypto, sports, and more. Returns market titles, current odds, volume, and status. You MUST provide tags to filter results.",
355
+ parameters: {
356
+ type: "object",
357
+ properties: {
358
+ platform: {
359
+ type: "string",
360
+ enum: ["polymarket", "kalshi"],
361
+ description: "The prediction market platform to search (default: polymarket)"
362
+ },
363
+ tags: {
364
+ type: "array",
365
+ items: { type: "string" },
366
+ description: 'REQUIRED: Single word categories or tags to identify a market segment (e.g., "politics", "crypto", "sports", "finance", "entertainment", "ai")'
367
+ },
368
+ status: {
369
+ type: "string",
370
+ enum: ["open", "closed"],
371
+ description: "Filter by market status"
372
+ },
373
+ limit: {
374
+ type: "number",
375
+ description: "Number of results (1-100)",
376
+ default: 10
377
+ }
378
+ },
379
+ required: ["tags"]
380
+ }
381
+ },
382
+ {
383
+ name: "get_market_details",
384
+ description: "Get detailed information about a specific prediction market including current prices, trading history, and resolution source.",
385
+ parameters: {
386
+ type: "object",
387
+ properties: {
388
+ platform: {
389
+ type: "string",
390
+ enum: ["polymarket", "kalshi"],
391
+ description: "The prediction market platform (default: polymarket)"
392
+ },
393
+ market_slug: {
394
+ type: "string",
395
+ description: "The market slug/identifier (ticker for Kalshi)"
396
+ }
397
+ },
398
+ required: ["market_slug"]
399
+ }
400
+ },
401
+ {
402
+ name: "get_market_prices",
403
+ description: "Get current prices/odds for a prediction market. Shows probability for each outcome.",
404
+ parameters: {
405
+ type: "object",
406
+ properties: {
407
+ platform: {
408
+ type: "string",
409
+ enum: ["polymarket", "kalshi"],
410
+ description: "The prediction market platform (default: polymarket)"
411
+ },
412
+ market_slug: {
413
+ type: "string",
414
+ description: "The market slug/identifier (ticker for Kalshi)"
415
+ }
416
+ },
417
+ required: ["market_slug"]
418
+ }
419
+ },
420
+ {
421
+ name: "get_market_trades",
422
+ description: "Get recent orders/trading activity for a prediction market.",
423
+ parameters: {
424
+ type: "object",
425
+ properties: {
426
+ platform: {
427
+ type: "string",
428
+ enum: ["polymarket", "kalshi"],
429
+ description: "The prediction market platform (default: polymarket)"
430
+ },
431
+ market_slug: {
432
+ type: "string",
433
+ description: "The market slug/identifier (ticker for Kalshi)"
434
+ },
435
+ limit: {
436
+ type: "number",
437
+ description: "Number of orders to return (max 100)",
438
+ default: 20
439
+ }
440
+ },
441
+ required: ["market_slug"]
442
+ }
443
+ }
444
+ ],
445
+ executors: {
446
+ get_supported_platforms: async () => {
447
+ return {
448
+ platforms: [
449
+ {
450
+ id: "polymarket",
451
+ name: "Polymarket",
452
+ description: "Decentralized prediction market on Polygon",
453
+ features: ["tags", "volume_filtering"]
454
+ },
455
+ {
456
+ id: "kalshi",
457
+ name: "Kalshi",
458
+ description: "CFTC-regulated prediction market exchange",
459
+ features: ["regulated", "event_based"]
460
+ }
461
+ ]
462
+ };
463
+ },
464
+ search_prediction_markets: async (args2) => {
465
+ const platform = args2.platform || "polymarket";
466
+ const params = new URLSearchParams();
467
+ if (args2.limit) params.append("limit", String(args2.limit));
468
+ if (platform === "polymarket") {
469
+ if (args2.tags) params.append("tags", args2.tags.join(","));
470
+ if (args2.status) params.append("status", args2.status);
471
+ const response = await fetch(`${DOME_API_BASE}/polymarket/markets?${params}`);
472
+ if (!response.ok) {
473
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
474
+ }
475
+ const data = await response.json();
476
+ return {
477
+ platform: "polymarket",
478
+ markets: data.markets?.map((m) => ({
479
+ slug: m.market_slug,
480
+ title: m.title,
481
+ status: m.status,
482
+ volume: m.volume_total,
483
+ tags: m.tags,
484
+ outcomes: [
485
+ { label: m.side_a?.label, id: m.side_a?.id },
486
+ { label: m.side_b?.label, id: m.side_b?.id }
487
+ ],
488
+ winner: m.winning_side
489
+ })) || [],
490
+ total: data.pagination?.total || 0,
491
+ hasMore: data.pagination?.has_more || false
492
+ };
493
+ } else if (platform === "kalshi") {
494
+ if (args2.status) params.append("status", args2.status);
495
+ const response = await fetch(`${DOME_API_BASE}/kalshi/markets?${params}`);
496
+ if (!response.ok) {
497
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
498
+ }
499
+ const data = await response.json();
500
+ return {
501
+ platform: "kalshi",
502
+ markets: data.markets?.map((m) => ({
503
+ ticker: m.ticker,
504
+ title: m.title,
505
+ status: m.status,
506
+ category: m.category,
507
+ subtitle: m.subtitle,
508
+ yesAsk: m.yes_ask,
509
+ yesBid: m.yes_bid,
510
+ volume: m.volume
511
+ })) || [],
512
+ total: data.pagination?.total || 0,
513
+ hasMore: data.pagination?.has_more || false
514
+ };
515
+ }
516
+ throw new Error(`Unsupported platform: ${platform}`);
517
+ },
518
+ get_market_details: async (args2) => {
519
+ const platform = args2.platform || "polymarket";
520
+ if (platform === "polymarket") {
521
+ const response = await fetch(
522
+ `${DOME_API_BASE}/polymarket/markets?market_slug=${args2.market_slug}`
523
+ );
524
+ if (!response.ok) {
525
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
526
+ }
527
+ const data = await response.json();
528
+ const market = data.markets?.[0];
529
+ if (!market) {
530
+ throw new Error(`Market not found: ${args2.market_slug}`);
531
+ }
532
+ return {
533
+ platform: "polymarket",
534
+ slug: market.market_slug,
535
+ title: market.title,
536
+ status: market.status,
537
+ startTime: market.start_time ? new Date(market.start_time * 1e3).toISOString() : null,
538
+ endTime: market.end_time ? new Date(market.end_time * 1e3).toISOString() : null,
539
+ volume: {
540
+ total: market.volume_total,
541
+ week: market.volume_1_week,
542
+ month: market.volume_1_month
543
+ },
544
+ resolutionSource: market.resolution_source,
545
+ outcomes: [
546
+ { label: market.side_a?.label, id: market.side_a?.id },
547
+ { label: market.side_b?.label, id: market.side_b?.id }
548
+ ],
549
+ winner: market.winning_side,
550
+ tags: market.tags
551
+ };
552
+ } else if (platform === "kalshi") {
553
+ const response = await fetch(
554
+ `${DOME_API_BASE}/kalshi/markets?ticker=${args2.market_slug}`
555
+ );
556
+ if (!response.ok) {
557
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
558
+ }
559
+ const data = await response.json();
560
+ const market = data.markets?.[0];
561
+ if (!market) {
562
+ throw new Error(`Market not found: ${args2.market_slug}`);
563
+ }
564
+ return {
565
+ platform: "kalshi",
566
+ ticker: market.ticker,
567
+ title: market.title,
568
+ subtitle: market.subtitle,
569
+ status: market.status,
570
+ category: market.category,
571
+ yesAsk: market.yes_ask,
572
+ yesBid: market.yes_bid,
573
+ volume: market.volume,
574
+ openInterest: market.open_interest
575
+ };
576
+ }
577
+ throw new Error(`Unsupported platform: ${platform}`);
578
+ },
579
+ get_market_prices: async (args2) => {
580
+ const platform = args2.platform || "polymarket";
581
+ if (platform === "polymarket") {
582
+ const response = await fetch(
583
+ `${DOME_API_BASE}/polymarket/market-price?market_slug=${args2.market_slug}`
584
+ );
585
+ if (!response.ok) {
586
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
587
+ }
588
+ const data = await response.json();
589
+ return { platform: "polymarket", ...data };
590
+ } else if (platform === "kalshi") {
591
+ const response = await fetch(
592
+ `${DOME_API_BASE}/kalshi/markets?ticker=${args2.market_slug}`
593
+ );
594
+ if (!response.ok) {
595
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
596
+ }
597
+ const data = await response.json();
598
+ const market = data.markets?.[0];
599
+ if (!market) {
600
+ throw new Error(`Market not found: ${args2.market_slug}`);
601
+ }
602
+ return {
603
+ platform: "kalshi",
604
+ ticker: market.ticker,
605
+ yesAsk: market.yes_ask,
606
+ yesBid: market.yes_bid,
607
+ lastPrice: market.last_price
608
+ };
609
+ }
610
+ throw new Error(`Unsupported platform: ${platform}`);
611
+ },
612
+ get_market_trades: async (args2) => {
613
+ const platform = args2.platform || "polymarket";
614
+ const limit = String(args2.limit || 20);
615
+ if (platform === "polymarket") {
616
+ const params = new URLSearchParams({
617
+ market_slug: args2.market_slug,
618
+ limit
619
+ });
620
+ const response = await fetch(
621
+ `${DOME_API_BASE}/polymarket/orders?${params}`
622
+ );
623
+ if (!response.ok) {
624
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
625
+ }
626
+ const data = await response.json();
627
+ return { platform: "polymarket", ...data };
628
+ } else if (platform === "kalshi") {
629
+ const params = new URLSearchParams({
630
+ ticker: args2.market_slug,
631
+ limit
632
+ });
633
+ const response = await fetch(
634
+ `${DOME_API_BASE}/kalshi/trades?${params}`
635
+ );
636
+ if (!response.ok) {
637
+ throw new Error(`Dome API error: ${response.status} ${response.statusText}`);
638
+ }
639
+ const data = await response.json();
640
+ return { platform: "kalshi", ...data };
641
+ }
642
+ throw new Error(`Unsupported platform: ${platform}`);
643
+ }
644
+ },
645
+ hooks: {
646
+ onRegister: () => {
647
+ console.log("[Plugin] Prediction Market Alpha v1.1.0 registered (Polymarket + Kalshi)");
648
+ }
649
+ }
650
+ };
651
+
652
+ // src/plugins/migrateFun.ts
653
+ var QA = [
654
+ { id: "migration-steps-bonk", question: "What are all the steps for migrations to Bonk?", answer: `Here's how MigrateFun migrates your token to BonkFun:
655
+ 1) The creator/team sets up a migration portal through migratefun - Create new CA for BonkFun (Ticker, name, image, supply) and set timeline period (1-30 days, 14 days average)
656
+ 2) After portal setup, holders commit their tokens to migration - tokens are locked in migration vault until time period ends
657
+ 3) Once migration ends, ALL tokens are market sold in a single candle to retrieve as much SOL as possible from the locked liquidity pool
658
+ 4) The recovered SOL seeds the new LP paired with appropriate amount of tokens. Set market cap at or slightly below current market cap
659
+ 5) Claims open for 90 days - users burn MFTs and receive new tokens`, keywords: ["bonk", "bonkfun", "steps", "process", "how"], category: "process" },
660
+ { id: "migration-steps-pumpfun", question: "How does a migration work to Pump Fun?", answer: `Here's how the migration to Pump Fun works:
661
+ 1) Set up a new CA for pumpfun using MigrateFun creator dashboard (Ticker, CA, image)
662
+ 2) Users migrate their tokens in the migration portal for a specific time period
663
+ 3) Once migration ends, MigrateFun sells all migrated tokens
664
+ 4) MigrateFun takes all recovered SOL and buys out new token's bonding curve + purchases until it reaches old market cap levels
665
+ 5) Users return to migratefun and claim their new tokens
666
+ 6) 90-day claim period for all users, regardless if they migrated on time or late
667
+ 7) The claim period can also be used to swap tokens with centralized exchanges
668
+ 8) After 90 days, all unclaimed tokens and remaining SOL are returned to the team`, keywords: ["pump", "pumpfun", "steps", "process", "how"], category: "process" },
669
+ { id: "migration-steps-raydium", question: "How does Migrate Fun migrate tokens to Raydium?", answer: `1) The creator/team sets up a migration portal through migratefun.com - Create new CA (Ticker, name, image, supply) and set timeline period (1-30 days, 14 days average)
670
+ 2) After portal setup, holders commit their tokens to migration and get MFTs in exchange - tokens are locked in migration vault until time period ends
671
+ 3) Once migration ends, ALL old tokens are market sold in a single candle to retrieve as much SOL as possible
672
+ 4) The recovered SOL seeds the new LP paired with appropriate amount of new tokens. Market Cap is set by the user
673
+ 5) Claims open for 90 days - users burn MFTs and receive new tokens. Late migrators can swap at discounted rate
674
+ 6) At the end of the 90 day claim window all remaining tokens can be claimed by the team`, keywords: ["raydium", "steps", "process", "how"], category: "process" },
675
+ { id: "post-migration-checklist", question: "What are the steps I need to do after the migration?", answer: `Admin Checklist - places to register your new CA:
676
+
677
+ PRIMARY:
678
+ - Coingecko (Free + migration application process)
679
+ - Dexscreener ($300)
680
+ - GeckoTerminal (free for 5 days wait)
681
+ - Holderscan (Listing free, Verify $125)
682
+
683
+ SECONDARY:
684
+ - Solscan (if metadata updates needed)
685
+ - CoinMarketCap ($5000 for immediate listing)
686
+ - Dextools ($300 for verification)
687
+ - Photon (2 SOL)
688
+ - Cookie.fun (Free, DM needed) [For AI accounts]
689
+ - Kaito (DM needed) [For AI accounts]
690
+
691
+ Note: Coingecko and CoinMarketCap will ask for a post from official twitter with migration details and new CA.`, keywords: ["after", "post", "checklist", "listing", "dexscreener", "coingecko"], category: "post-migration" },
692
+ { id: "post-migration-approval", question: "Do we need to do anything after the migration ends?", answer: `Yes, the team needs to approve several steps in the migration portal including:
693
+ 1) Selling the migrated tokens into the old LP
694
+ 2) Setting the new market cap
695
+ 3) Opening the claim portal
696
+
697
+ Video tutorial: https://www.youtube.com/watch?v=SjPN-1DnXtM`, keywords: ["after", "ends", "approve", "portal"], category: "post-migration" },
698
+ { id: "market-cap-setting", question: "What market cap should we set?", answer: `Set at or slightly below the ending market cap at migration. For example, if your ending market cap is $1 million, set it to around $950,000. This accounts for the fact you won't receive 1:1 liquidity from the old pool compared to the new pool, which is determined by migration participation.`, keywords: ["market cap", "marketcap", "set", "recommend"], category: "settings" },
699
+ { id: "migrate-fun-cost", question: "What does Migrate Fun cost?", answer: `Migrate Fun charges a flat 3.75% fee on the total SOL unlocked from the old Liquidity Pool. This fee is taken automatically during the migration process.`, keywords: ["cost", "fee", "price", "charge", "3.75", "percent"], category: "fees" },
700
+ { id: "claim-fees-bonk", question: "How does the team claim their fees on Bonk Fun?", answer: `Go to https://bonk.fun/creator-rewards to claim your creator fees.`, keywords: ["claim", "fees", "bonk", "creator", "rewards"], category: "fees" },
701
+ { id: "claim-fees-raydium", question: "How do I claim fees on Raydium?", answer: `You can claim fees from https://raydium.io/portfolio/ with the same wallet that set up the migration.`, keywords: ["claim", "fees", "raydium", "portfolio"], category: "fees" },
702
+ { id: "claim-fees-pumpfun", question: "How do I claim fees on Pump Fun?", answer: `Fees are paid automatically to the wallet used to set up the migration. Once migrated to PumpSwap you will receive creator rewards based on their Ascend Program. Details: https://pump.fun/docs/fees`, keywords: ["claim", "fees", "pump", "pumpfun", "automatic"], category: "fees" },
703
+ { id: "audit-info", question: "Has Migrate Fun been audited?", answer: `Yes. Migrate Fun was audited by Halborn, the same auditing firm used by the Solana Foundation.
704
+ Audit: https://www.halborn.com/audits/emblem-vault/migratefun-8ad34b
705
+ Announcement: https://x.com/HalbornSecurity/status/1978869642744811933`, keywords: ["audit", "audited", "security", "halborn", "safe"], category: "security" },
706
+ { id: "user-experience", question: "What is the process like for the user?", answer: `Super easy - takes less than 20 seconds.
707
+ 1) During migration: users swap old tokens for Migrate Fun Tokens (MFTs)
708
+ 2) Once migration ends: claim period opens for 90 days, users burn MFTs to claim new tokens
709
+ 3) Late migrators: can swap old tokens for new at a discounted rate set by the team
710
+
711
+ Video guides:
712
+ - Migration: https://x.com/MigrateFun/status/1971259552856408433
713
+ - Claims: https://x.com/MigrateFun/status/1976376597906325767`, keywords: ["user", "experience", "process", "simple", "easy"], category: "user-experience" },
714
+ { id: "what-is-migrate-fun", question: "What is Migrate Fun?", answer: `Migrate Fun is the category-defining platform that created the migration meta. It allows users to migrate locked liquidity from one launchpad to another.
715
+
716
+ As of October 2025: 15 migrations completed, $5+ million in liquidity moved, largest migration was $35M market cap project. Supports migrations to Bonk Fun, Raydium, and Pump Fun.
717
+
718
+ Links:
719
+ - Website: https://migrate.fun/
720
+ - X: https://x.com/MigrateFun
721
+ - Docs: https://github.com/EmblemCompany/Migrate-fun-docs/
722
+ - Audit: https://www.halborn.com/audits/emblem-vault/migratefun-8ad34b
723
+ - Calculator: https://migrate.fun/migration-calculator`, keywords: ["what", "migrate fun", "about", "general", "overview"], category: "general" },
724
+ { id: "sol-recovery-estimate", question: "How can I see how much SOL we can get from the old LP?", answer: `Use the migration calculator to estimate SOL recovery based on participation percentages: https://migrate.fun/migration-calculator`, keywords: ["sol", "recovery", "estimate", "calculator", "liquidity", "how much"], category: "tools" },
725
+ { id: "documentation", question: "Do you have documentation?", answer: `Yes, documentation is available at: https://github.com/EmblemCompany/Migrate-fun-docs/`, keywords: ["documentation", "docs", "guide", "help"], category: "general" },
726
+ { id: "rebrand", question: "What if I want to rebrand?", answer: `The migration enables a full rebrand - reset metadata, image, logo, name, everything. Or keep it all the same if you prefer.`, keywords: ["rebrand", "change", "name", "logo", "image", "metadata"], category: "features" },
727
+ { id: "sniper-protection", question: "How do you prevent snipers when migrating to Pump Fun?", answer: `On Solana you can stack transactions. When deploying the bonding curve, you are first to purchase so you can buyout the bonding curve and more in the first transaction, preventing snipers.`, keywords: ["sniper", "snipers", "protection", "front-run", "mev"], category: "security" },
728
+ { id: "claim-period-flexibility", question: "Is there flexibility on the 90 day claim period?", answer: `The 90-day claim period is mandatory. Reasons:
729
+ - All users need time to claim tokens after migration
730
+ - Those who missed migration need a window
731
+ - Users don't get tokens until after migration completes
732
+ - Allowing team to withdraw during claims would be risky (potential rug)`, keywords: ["90 day", "claim", "period", "flexibility", "change"], category: "settings" },
733
+ { id: "migration-duration", question: "How long is the migration?", answer: `You can set the migration window for as long as you'd like. Average is 14 days. Some teams choose 7 days (works great), some go up to 30 days.
734
+
735
+ Note: Majority of participation happens in the first and last 24 hours. Example: 76% participation with 50%+ migrating in first 24 hours and additional 10% on the last day.`, keywords: ["how long", "duration", "time", "days", "period", "window"], category: "settings" },
736
+ { id: "migration-performance", question: "Can you give examples of token performance after migration?", answer: `Migration squeeze: When large percentage of old tokens migrate, sell pressure reduces, often causing market cap spike near migration end.
737
+
738
+ Example charts:
739
+ - ZERA Old: https://dexscreener.com/solana/95at5r4i85gfqeew2yr6byfg8rlry1d9ztps7qrskdvc
740
+ New: https://dexscreener.com/solana/nn9vmhjtqgg9l9f8sp3geufwc5zvuhradcwehh7n7di
741
+ - HUSTLE Old: https://dexscreener.com/solana/gjckb2eesjk65nuvpaw4tn2rabnr8wmfcwcwpagk5dzs
742
+ New: https://dexscreener.com/solana/hxo1wrcrdewek8l2j6rxswnolumej2mweh38gajxtw7y
743
+
744
+ Thread: https://x.com/jakegallen_/status/1973051293213028468`, keywords: ["performance", "charts", "example", "before", "after", "squeeze"], category: "examples" },
745
+ { id: "why-migrate", question: "Why would teams want to migrate?", answer: `Top reasons:
746
+ - Access to creator rewards
747
+ - Rebrand opportunity
748
+ - Fresh chart
749
+ - Reclaim part of the token supply
750
+ - Reinvigorated community on the other side`, keywords: ["why", "reasons", "benefits", "advantages", "should"], category: "general" },
751
+ { id: "migration-recommendation-steps", question: "What steps do you recommend when considering a migration?", answer: `1) Discuss with Migrate Fun team: process details, where to move LP (Raydium, Bonk Fun, or Pump Fun)
752
+ 2) Discuss benefits with your community, especially whale holders - get buy-in
753
+ 3) Announce on all social channels - maximize awareness for maximum participation`, keywords: ["recommend", "steps", "considering", "planning", "prepare"], category: "process" },
754
+ { id: "multiple-wallets", question: "Do holders with multiple wallets need to consolidate?", answer: `No. Migration is linear - users can migrate all tokens together or separately. Makes no difference.`, keywords: ["multiple", "wallets", "consolidate", "separate"], category: "user-experience" },
755
+ { id: "mft-value", question: "Do MFTs show value in wallets?", answer: `MFTs (Migrate Fun Tokens) are just placeholder tokens for the migration. They are valueless.`, keywords: ["mft", "migrate fun tokens", "value", "placeholder"], category: "user-experience" },
756
+ { id: "announcement-examples", question: "Can you give me sample migration announcements?", answer: `Here are announcements made by teams:
757
+ - https://x.com/radrdotfun/status/1952127168101949620
758
+ - https://x.com/project_89/status/1951345024656089368
759
+ - https://x.com/HKittyOnSol/status/1948925330032349210
760
+ - https://x.com/ModernStoicAI/status/1948129627362218483
761
+ - https://x.com/pokithehamster/status/1950238636928327927
762
+ - https://x.com/IQ6900_/status/1953002036599173499
763
+ - https://x.com/TheBongoCat/status/1965538945132843333`, keywords: ["announcement", "sample", "example", "post", "twitter"], category: "examples" },
764
+ { id: "graphics", question: "Does Migrate Fun provide graphics for announcements?", answer: `No. For your own migration announcement you create the graphic. Migrate Fun's designer creates group migration announcements only.`, keywords: ["graphics", "images", "design", "announcement"], category: "general" },
765
+ { id: "developer-required", question: "Do I need to be a developer to migrate?", answer: `No development required. The entire process is a few clicks for both pre-migration and post-migration.`, keywords: ["developer", "technical", "coding", "code"], category: "general" },
766
+ { id: "exchange-tokens", question: "What happens to tokens on exchanges or locked in Streamflow?", answer: `They will miss the migration as those tokens are considered circulating supply onchain. Options:
767
+ 1) Join as late migrator during 90-day claim window
768
+ 2) After 90-day period, team takes possession of unclaimed tokens and can reimburse directly`, keywords: ["exchange", "streamflow", "locked", "vested", "cex"], category: "edge-cases" },
769
+ { id: "unclaimed-tokens", question: "Can we get unclaimed tokens?", answer: `After the 90-day claim period ends, all unclaimed tokens are returned to whichever wallet set up the migration (the team).`, keywords: ["unclaimed", "supply", "remaining", "tokens", "team"], category: "post-migration" },
770
+ { id: "participation-rate", question: "What is typical participation percentage?", answer: `Nearly all projects have had over 50% migration participation. View all stats at https://migrate.fun/projects`, keywords: ["participation", "percentage", "rate", "typical", "average"], category: "statistics" },
771
+ { id: "late-penalty", question: "What penalty can teams set for late migrators?", answer: `Teams can set 0-100% penalty for late migrators who swap during the 90-day claim window. 25% seems to be a good balance - encourages participation without being overly punishing.`, keywords: ["penalty", "late", "discount", "punish", "percent"], category: "settings" },
772
+ { id: "new-ca", question: "Will we get a new CA or just change the pair?", answer: `A new CA. If migrating to Bonk Fun your CA will end with "bonk". If migrating to Pump Fun it will end with "pump".`, keywords: ["ca", "contract", "address", "new", "pair"], category: "process" },
773
+ { id: "vanity-ca", question: "Can we create a vanity CA?", answer: `Yes, but if migrating to Bonk Fun it needs to end with "bonk", or for Pump Fun it needs to end with "pump".`, keywords: ["vanity", "ca", "custom", "address", "contract"], category: "features" },
774
+ { id: "vested-tokens", question: "What about team tokens locked with Streamflow?", answer: `Those tokens can't be migrated. They won't be lost - you'll recapture that supply post-migration. Any unmigrated tokens return to team at full or discounted rate depending on your late migrator penalty setting.`, keywords: ["vested", "streamflow", "locked", "team"], category: "edge-cases" },
775
+ { id: "wallet-tracking", question: "Can I track wallet addresses post-migration?", answer: `At the end of migration, there's a snapshot tool that lets you download a CSV of all wallets holding the old token.`, keywords: ["wallet", "track", "snapshot", "csv", "addresses"], category: "tools" },
776
+ { id: "old-listings", question: "What happens to old token listings?", answer: `You will need to apply to new directories. Migrate Fun provides a list once you begin the migration process.`, keywords: ["listings", "directories", "old", "new", "update"], category: "post-migration" },
777
+ { id: "lp-locking", question: "Does the new LP get locked?", answer: `If migrating to Bonk Fun or Pump Fun: LP is locked (their rules). If migrating to Raydium: LP is unlocked and you control it.`, keywords: ["lp", "locked", "liquidity", "pool", "control"], category: "process" },
778
+ { id: "sol-pairs", question: "Are Bonk migrations confined to SOL pairs?", answer: `As of October 2025, they are SOL migrations. Check with the team to see if USD1 pairs are possible.`, keywords: ["sol", "pair", "usd1", "usdc", "bonk"], category: "settings" },
779
+ { id: "change-penalty", question: "Can I change the penalty after setup?", answer: `No. The penalty must be set during migration creation and cannot be changed after.`, keywords: ["change", "penalty", "modify", "update", "after"], category: "settings" },
780
+ { id: "unhappy-holders", question: "What if someone is unhappy about the migration?", answer: `They can sell their tokens and not participate. Migrations are a fresh start - holders who migrate are voting with their tokens that they support the team and believe in the project's future.`, keywords: ["unhappy", "disagree", "against", "sell"], category: "user-experience" },
781
+ { id: "sample-announcement", question: "What is a good announcement template?", answer: `Sample for Bonk Fun migration:
782
+
783
+ "We're excited to announce that we're migrating with @MigrateFun and officially joining the @bonk_inu ecosystem next month!
784
+
785
+ With our 1-year anniversary less than a month away, this migration to @bonk_fun marks the beginning of our next chapter.
786
+
787
+ Why Bonk Fun?
788
+ \u{1F9F0} Purpose-built tools for community projects
789
+ \u{1F4B8} Transaction fee rev share
790
+ \u{1F501} Seamless LP migration
791
+ \u{1F91D} Strategic alignment with top meme coin teams
792
+
793
+ Our migration timeline + holder instructions drop soon."`, keywords: ["announcement", "template", "sample", "post"], category: "examples" },
794
+ { id: "share-link", question: "Do you have a link to share explaining Migrate Fun?", answer: `Overview thread: https://x.com/migratefun/status/1957492884355314035
795
+ Deep dive docs: https://github.com/EmblemCompany/Migrate-fun-docs/`, keywords: ["link", "share", "explain", "overview"], category: "general" },
796
+ { id: "exchange-rate", question: "Is the exchange rate always 1:1?", answer: `Yes, 1 old token = 1 new token for users who participate in migration. Users who miss can swap during the 90-day claim window at a discounted rate set by the team.`, keywords: ["exchange", "rate", "1:1", "ratio", "same"], category: "process" },
797
+ { id: "change-supply", question: "Can I change the total supply?", answer: `Generally yes, with some constraints depending on destination platform. Reach out to Migrate Fun team to discuss specifics.`, keywords: ["supply", "change", "total", "amount"], category: "features" },
798
+ { id: "contact", question: "How can I get in touch with the Migrate Fun team?", answer: `Send a direct message to the Migrate Fun X account: https://x.com/MigrateFun`, keywords: ["contact", "reach", "touch", "dm", "message", "talk"], category: "general" },
799
+ { id: "ready-to-migrate", question: "I am ready to migrate, what is next?", answer: `Send a direct message to the Migrate Fun X account: https://x.com/MigrateFun`, keywords: ["ready", "start", "begin", "next"], category: "general" },
800
+ { id: "risks", question: "What are the risks of migrating?", answer: `Main risk: Failed migration where not enough tokens migrate to fund the new LP. In that case, migrated tokens are sold into the old LP and SOL is returned to community members who participated.`, keywords: ["risk", "danger", "fail", "problem", "issue"], category: "security" },
801
+ { id: "how-detect-non-migrators", question: "How does Migrate Fun know who did not migrate?", answer: `Migrate Fun has a snapshot and claim tool that puts onchain all wallets holding old tokens at migration end. This enables late migrators to swap old tokens for new during the 90-day claim window at the team-set discount.`, keywords: ["snapshot", "detect", "know", "non-migrators"], category: "tools" },
802
+ { id: "no-penalty", question: "What if I do not want to penalize non-migrators?", answer: `Set the late claim penalty to zero. Holders who didn't migrate can then swap old tokens for new at a 1:1 rate during the 90-day claim window.`, keywords: ["no penalty", "zero", "fair"], category: "settings" },
803
+ { id: "missed-claim-window", question: "What happens if holders miss both migration and claim window?", answer: `They won't have access to new tokens through Migrate Fun platform. All remaining tokens go to the team after 90-day window closes. The team has a snapshot of all old token holders and can handle at their discretion.`, keywords: ["missed", "both", "claim", "window", "late"], category: "edge-cases" },
804
+ { id: "exchange-options", question: "What options do exchanges have to swap tokens?", answer: `Two options:
805
+
806
+ Option 1: Participate onchain through the migration portal (same as retail). Load tokens into Phantom wallet, migrate, then claim. ~10 seconds each step.
807
+
808
+ Option 2: Admin withdraw function during 90-day claim period. Migration admin can withdraw new tokens from claims vault and manually swap with exchange.
809
+ - 90-day window for exchange procedures
810
+ - Exchange can observe migration complete before acting
811
+ - Can receive new tokens before sending old
812
+ - Can pause trading during process`, keywords: ["exchange", "cex", "swap", "options", "centralized"], category: "edge-cases" },
813
+ { id: "buy-prevent-dump", question: "Can we buy supply before migration to prevent dumping?", answer: `I would recommend buying now. There is no arb opportunity as you set the market cap of the new token.
814
+
815
+ To regain control of non-migrated tokens, you can penalize non-migrators. Example: If 60% migrate, 40% didn't. With a 50% penalty on non-migrators, you'd recoup 20% of total supply if everyone claimed.`, keywords: ["buy", "dump", "supply", "control", "arb"], category: "strategy" }
816
+ ];
817
+ var migrateFunPlugin = {
818
+ name: "migrate-fun-knowledge",
819
+ version: "1.0.0",
820
+ description: "Search Migrate.fun knowledge base for token migration answers",
821
+ tools: [
822
+ {
823
+ name: "search_migrate_fun_docs",
824
+ description: "Search the Migrate.fun knowledge base for answers about token migrations. Use this tool when users ask about: how migrations work (Bonk Fun, Pump Fun, Raydium), costs/fees/timelines, post-migration steps, user experience, technical details (LP, CA, penalties), or examples. Returns ranked Q&A pairs from real support conversations.",
825
+ parameters: {
826
+ type: "object",
827
+ properties: {
828
+ query: {
829
+ type: "string",
830
+ description: "The search query - user question or key terms about token migrations"
831
+ },
832
+ topK: {
833
+ type: "number",
834
+ description: "Number of results to return (default: 5, max: 10)"
835
+ }
836
+ },
837
+ required: ["query"]
838
+ }
839
+ }
840
+ ],
841
+ executors: {
842
+ search_migrate_fun_docs: async (args2) => {
843
+ const query = args2.query;
844
+ const topK = Math.min(Math.max(1, args2.topK || 5), 10);
845
+ const queryLower = query.toLowerCase();
846
+ const queryWords = queryLower.split(/\s+/).filter((w) => w.length > 2);
847
+ const scored = QA.map((qa) => {
848
+ let score = 0;
849
+ const questionLower = qa.question.toLowerCase();
850
+ const answerLower = qa.answer.toLowerCase();
851
+ const keywordsStr = qa.keywords.join(" ").toLowerCase();
852
+ const fullText = `${questionLower} ${answerLower} ${keywordsStr}`;
853
+ if (questionLower.includes(queryLower)) score += 15;
854
+ if (fullText.includes(queryLower)) score += 8;
855
+ for (const word of queryWords) {
856
+ if (qa.keywords.some((kw) => kw.toLowerCase().includes(word) || word.includes(kw.toLowerCase()))) {
857
+ score += 4;
858
+ }
859
+ if (questionLower.includes(word)) score += 3;
860
+ if (answerLower.includes(word)) score += 1;
861
+ }
862
+ return { ...qa, score };
863
+ });
864
+ const results = scored.filter((qa) => qa.score > 0).sort((a, b) => b.score - a.score).slice(0, topK).map((qa, i) => ({
865
+ rank: i + 1,
866
+ relevance: Math.round(qa.score / 30 * 100) / 100,
867
+ question: qa.question,
868
+ answer: qa.answer,
869
+ category: qa.category
870
+ }));
871
+ return {
872
+ success: true,
873
+ query,
874
+ resultCount: results.length,
875
+ results,
876
+ hint: results.length === 0 ? "No matches found. Suggest contacting @MigrateFun on X: https://x.com/MigrateFun" : "Use these Q&A pairs to answer. Include relevant links from the answers."
877
+ };
878
+ }
879
+ },
880
+ hooks: {
881
+ onRegister: () => {
882
+ console.log("[Plugin] Migrate.fun Knowledge Base v1.0.0 registered");
883
+ }
884
+ }
885
+ };
886
+
887
+ // src/plugins/piiProtection.ts
888
+ var TOKEN_MAP_KEY = "__piiTokenMaps";
889
+ var PERSISTENT_MAP_KEY = "__piiPersistentMap";
890
+ function getTokenMaps() {
891
+ const storage = typeof window !== "undefined" ? window : global;
892
+ if (!storage[TOKEN_MAP_KEY]) {
893
+ storage[TOKEN_MAP_KEY] = /* @__PURE__ */ new Map();
894
+ }
895
+ return storage[TOKEN_MAP_KEY];
896
+ }
897
+ function getPersistentMap() {
898
+ const storage = typeof window !== "undefined" ? window : global;
899
+ if (!storage[PERSISTENT_MAP_KEY]) {
900
+ storage[PERSISTENT_MAP_KEY] = {
901
+ piiToToken: /* @__PURE__ */ new Map(),
902
+ tokenToPii: /* @__PURE__ */ new Map(),
903
+ counter: { value: 0 }
904
+ };
905
+ }
906
+ return storage[PERSISTENT_MAP_KEY];
907
+ }
908
+ var piiProtectionPlugin = {
909
+ name: "pii-protection",
910
+ version: "1.0.0",
911
+ description: "Tokenizes PII before sending to AI, restores in responses",
912
+ tools: [],
913
+ executors: {},
914
+ hooks: {
915
+ onRegister: () => {
916
+ console.log("[PII Protection] Plugin registered - PII will be tokenized in requests");
917
+ },
918
+ beforeRequest: (request) => {
919
+ const maps = getTokenMaps();
920
+ const persistent = getPersistentMap();
921
+ const requestId = Date.now().toString();
922
+ const requestTokenMap = /* @__PURE__ */ new Map();
923
+ const tokenize = (text) => {
924
+ if (typeof text !== "string") return text;
925
+ return text.replace(/\b\d{3}-\d{2}-\d{4}\b/g, (match) => {
926
+ if (persistent.piiToToken.has(match)) {
927
+ const existingToken = persistent.piiToToken.get(match);
928
+ requestTokenMap.set(existingToken, match);
929
+ return existingToken;
930
+ }
931
+ const token = `{{SSN_${++persistent.counter.value}}}`;
932
+ persistent.piiToToken.set(match, token);
933
+ persistent.tokenToPii.set(token, match);
934
+ requestTokenMap.set(token, match);
935
+ return token;
936
+ }).replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/gi, (match) => {
937
+ if (persistent.piiToToken.has(match)) {
938
+ const existingToken = persistent.piiToToken.get(match);
939
+ requestTokenMap.set(existingToken, match);
940
+ return existingToken;
941
+ }
942
+ const token = `{{EMAIL_${++persistent.counter.value}}}`;
943
+ persistent.piiToToken.set(match, token);
944
+ persistent.tokenToPii.set(token, match);
945
+ requestTokenMap.set(token, match);
946
+ return token;
947
+ }).replace(/\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g, (match) => {
948
+ if (persistent.piiToToken.has(match)) {
949
+ const existingToken = persistent.piiToToken.get(match);
950
+ requestTokenMap.set(existingToken, match);
951
+ return existingToken;
952
+ }
953
+ const token = `{{PHONE_${++persistent.counter.value}}}`;
954
+ persistent.piiToToken.set(match, token);
955
+ persistent.tokenToPii.set(token, match);
956
+ requestTokenMap.set(token, match);
957
+ return token;
958
+ }).replace(/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g, (match) => {
959
+ if (persistent.piiToToken.has(match)) {
960
+ const existingToken = persistent.piiToToken.get(match);
961
+ requestTokenMap.set(existingToken, match);
962
+ return existingToken;
963
+ }
964
+ const token = `{{CARD_${++persistent.counter.value}}}`;
965
+ persistent.piiToToken.set(match, token);
966
+ persistent.tokenToPii.set(token, match);
967
+ requestTokenMap.set(token, match);
968
+ return token;
969
+ });
970
+ };
971
+ const anonymizedMessages = request.messages.map((msg) => ({
972
+ ...msg,
973
+ content: typeof msg.content === "string" ? tokenize(msg.content) : msg.content
974
+ }));
975
+ if (requestTokenMap.size > 0) {
976
+ maps.set(requestId, requestTokenMap);
977
+ console.log(`[PII Protection] Tokenized ${requestTokenMap.size} PII values`);
978
+ }
979
+ return { ...request, messages: anonymizedMessages };
980
+ },
981
+ afterResponse: (response) => {
982
+ const persistent = getPersistentMap();
983
+ if (typeof response.content === "string") {
984
+ let restored = response.content;
985
+ let restoredCount = 0;
986
+ for (const [token, original] of persistent.tokenToPii.entries()) {
987
+ if (restored.includes(token)) {
988
+ restored = restored.split(token).join(original);
989
+ restoredCount++;
990
+ }
991
+ }
992
+ if (restoredCount > 0) {
993
+ response.content = restored;
994
+ console.log(`[PII Protection] Restored ${restoredCount} PII values`);
995
+ }
996
+ }
997
+ }
998
+ }
999
+ };
1000
+
1001
+ // src/plugins/userQuestion.ts
1002
+ function ensureModalStyles() {
1003
+ if (typeof document === "undefined") return;
1004
+ const styleId = "user-question-modal-styles";
1005
+ if (document.getElementById(styleId)) return;
1006
+ const styles2 = document.createElement("style");
1007
+ styles2.id = styleId;
1008
+ styles2.textContent = `
1009
+ .user-question-overlay {
1010
+ position: fixed;
1011
+ top: 0;
1012
+ left: 0;
1013
+ right: 0;
1014
+ bottom: 0;
1015
+ background: rgba(0, 0, 0, 0.6);
1016
+ display: flex;
1017
+ align-items: center;
1018
+ justify-content: center;
1019
+ z-index: 10000;
1020
+ animation: uqFadeIn 0.2s ease-out;
1021
+ }
1022
+
1023
+ @keyframes uqFadeIn {
1024
+ from { opacity: 0; }
1025
+ to { opacity: 1; }
1026
+ }
1027
+
1028
+ .user-question-modal {
1029
+ background: #1a1a2e;
1030
+ border: 1px solid #333;
1031
+ border-radius: 12px;
1032
+ padding: 24px;
1033
+ max-width: 480px;
1034
+ width: 90%;
1035
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
1036
+ animation: uqSlideUp 0.2s ease-out;
1037
+ }
1038
+
1039
+ @keyframes uqSlideUp {
1040
+ from { transform: translateY(20px); opacity: 0; }
1041
+ to { transform: translateY(0); opacity: 1; }
1042
+ }
1043
+
1044
+ .user-question-title {
1045
+ font-size: 18px;
1046
+ font-weight: 600;
1047
+ color: #fff;
1048
+ margin: 0 0 16px 0;
1049
+ }
1050
+
1051
+ .user-question-choices {
1052
+ display: flex;
1053
+ flex-direction: column;
1054
+ gap: 8px;
1055
+ margin-bottom: 20px;
1056
+ }
1057
+
1058
+ .user-question-choice {
1059
+ display: flex;
1060
+ align-items: center;
1061
+ gap: 12px;
1062
+ padding: 12px 16px;
1063
+ background: #252540;
1064
+ border: 1px solid #333;
1065
+ border-radius: 8px;
1066
+ cursor: pointer;
1067
+ transition: all 0.15s ease;
1068
+ }
1069
+
1070
+ .user-question-choice:hover {
1071
+ background: #2a2a4a;
1072
+ border-color: #4a4a6a;
1073
+ }
1074
+
1075
+ .user-question-choice.selected {
1076
+ background: #2a3a5a;
1077
+ border-color: #4a7aff;
1078
+ }
1079
+
1080
+ .user-question-choice input {
1081
+ margin: 0;
1082
+ accent-color: #4a7aff;
1083
+ }
1084
+
1085
+ .user-question-choice label {
1086
+ flex: 1;
1087
+ color: #e0e0e0;
1088
+ cursor: pointer;
1089
+ font-size: 14px;
1090
+ }
1091
+
1092
+ .user-question-actions {
1093
+ display: flex;
1094
+ gap: 12px;
1095
+ justify-content: flex-end;
1096
+ }
1097
+
1098
+ .user-question-btn {
1099
+ padding: 10px 20px;
1100
+ border-radius: 6px;
1101
+ font-size: 14px;
1102
+ font-weight: 500;
1103
+ cursor: pointer;
1104
+ transition: all 0.15s ease;
1105
+ }
1106
+
1107
+ .user-question-btn-cancel {
1108
+ background: transparent;
1109
+ border: 1px solid #444;
1110
+ color: #aaa;
1111
+ }
1112
+
1113
+ .user-question-btn-cancel:hover {
1114
+ background: #333;
1115
+ color: #fff;
1116
+ }
1117
+
1118
+ .user-question-btn-submit {
1119
+ background: #4a7aff;
1120
+ border: none;
1121
+ color: #fff;
1122
+ }
1123
+
1124
+ .user-question-btn-submit:hover {
1125
+ background: #5a8aff;
1126
+ }
1127
+
1128
+ .user-question-btn-submit:disabled {
1129
+ background: #333;
1130
+ color: #666;
1131
+ cursor: not-allowed;
1132
+ }
1133
+ `;
1134
+ document.head.appendChild(styles2);
1135
+ }
1136
+ var askUserTool = {
1137
+ name: "ask_user",
1138
+ description: `Ask the user a multiple choice question and wait for their response. Use this when you need user input to proceed - for example: clarifying requirements, getting preferences, or confirming actions. The tool blocks until the user responds.`,
1139
+ parameters: {
1140
+ type: "object",
1141
+ properties: {
1142
+ question: {
1143
+ type: "string",
1144
+ description: "The question to ask the user"
1145
+ },
1146
+ choices: {
1147
+ type: "array",
1148
+ items: { type: "string" },
1149
+ description: "Array of choices to present (2-6 options recommended)"
1150
+ },
1151
+ allowMultiple: {
1152
+ type: "boolean",
1153
+ description: "If true, user can select multiple choices. Default: false"
1154
+ }
1155
+ },
1156
+ required: ["question", "choices"]
1157
+ }
1158
+ };
1159
+ var askUserExecutor = async (args2) => {
1160
+ const { question, choices, allowMultiple = false } = args2;
1161
+ if (!question || !choices || !Array.isArray(choices) || choices.length === 0) {
1162
+ return {
1163
+ question: question || "",
1164
+ selectedChoices: [],
1165
+ answered: false
1166
+ };
1167
+ }
1168
+ if (typeof document === "undefined") {
1169
+ console.log(`[User Question] Question: ${question}`);
1170
+ console.log(`[User Question] Choices: ${choices.join(", ")}`);
1171
+ return {
1172
+ question,
1173
+ selectedChoices: [choices[0]],
1174
+ answered: true
1175
+ };
1176
+ }
1177
+ ensureModalStyles();
1178
+ return new Promise((resolve) => {
1179
+ const selected = /* @__PURE__ */ new Set();
1180
+ const overlay = document.createElement("div");
1181
+ overlay.className = "user-question-overlay";
1182
+ const modal = document.createElement("div");
1183
+ modal.className = "user-question-modal";
1184
+ const title = document.createElement("h3");
1185
+ title.className = "user-question-title";
1186
+ title.textContent = question;
1187
+ modal.appendChild(title);
1188
+ const choicesDiv = document.createElement("div");
1189
+ choicesDiv.className = "user-question-choices";
1190
+ const inputType = allowMultiple ? "checkbox" : "radio";
1191
+ const inputName = `uq-${Date.now()}`;
1192
+ choices.forEach((choice, index) => {
1193
+ const choiceDiv = document.createElement("div");
1194
+ choiceDiv.className = "user-question-choice";
1195
+ const input = document.createElement("input");
1196
+ input.type = inputType;
1197
+ input.name = inputName;
1198
+ input.id = `${inputName}-${index}`;
1199
+ input.value = choice;
1200
+ const label = document.createElement("label");
1201
+ label.htmlFor = input.id;
1202
+ label.textContent = choice;
1203
+ choiceDiv.appendChild(input);
1204
+ choiceDiv.appendChild(label);
1205
+ const handleSelect = () => {
1206
+ if (allowMultiple) {
1207
+ if (selected.has(choice)) {
1208
+ selected.delete(choice);
1209
+ choiceDiv.classList.remove("selected");
1210
+ } else {
1211
+ selected.add(choice);
1212
+ choiceDiv.classList.add("selected");
1213
+ }
1214
+ } else {
1215
+ selected.clear();
1216
+ selected.add(choice);
1217
+ choicesDiv.querySelectorAll(".user-question-choice").forEach((c) => c.classList.remove("selected"));
1218
+ choiceDiv.classList.add("selected");
1219
+ }
1220
+ updateSubmitButton();
1221
+ };
1222
+ input.addEventListener("change", handleSelect);
1223
+ choiceDiv.addEventListener("click", (e) => {
1224
+ if (e.target !== input) {
1225
+ input.checked = !input.checked || !allowMultiple;
1226
+ handleSelect();
1227
+ }
1228
+ });
1229
+ choicesDiv.appendChild(choiceDiv);
1230
+ });
1231
+ modal.appendChild(choicesDiv);
1232
+ const actions = document.createElement("div");
1233
+ actions.className = "user-question-actions";
1234
+ const cancelBtn = document.createElement("button");
1235
+ cancelBtn.className = "user-question-btn user-question-btn-cancel";
1236
+ cancelBtn.textContent = "Skip";
1237
+ cancelBtn.onclick = () => {
1238
+ cleanup();
1239
+ resolve({
1240
+ question,
1241
+ selectedChoices: [],
1242
+ answered: false
1243
+ });
1244
+ };
1245
+ const submitBtn = document.createElement("button");
1246
+ submitBtn.className = "user-question-btn user-question-btn-submit";
1247
+ submitBtn.textContent = "Submit";
1248
+ submitBtn.disabled = true;
1249
+ submitBtn.onclick = () => {
1250
+ cleanup();
1251
+ resolve({
1252
+ question,
1253
+ selectedChoices: Array.from(selected),
1254
+ answered: true
1255
+ });
1256
+ };
1257
+ const updateSubmitButton = () => {
1258
+ submitBtn.disabled = selected.size === 0;
1259
+ };
1260
+ actions.appendChild(cancelBtn);
1261
+ actions.appendChild(submitBtn);
1262
+ modal.appendChild(actions);
1263
+ overlay.appendChild(modal);
1264
+ document.body.appendChild(overlay);
1265
+ const cleanup = () => {
1266
+ overlay.remove();
1267
+ };
1268
+ const handleEscape = (e) => {
1269
+ if (e.key === "Escape") {
1270
+ document.removeEventListener("keydown", handleEscape);
1271
+ cleanup();
1272
+ resolve({
1273
+ question,
1274
+ selectedChoices: [],
1275
+ answered: false
1276
+ });
1277
+ }
1278
+ };
1279
+ document.addEventListener("keydown", handleEscape);
1280
+ });
1281
+ };
1282
+ var userQuestionPlugin = {
1283
+ name: "user-question",
1284
+ version: "1.0.0",
1285
+ description: "Allows AI to ask users multiple choice questions via modal",
1286
+ tools: [askUserTool],
1287
+ executors: {
1288
+ ask_user: askUserExecutor
1289
+ },
1290
+ hooks: {
1291
+ onRegister: () => {
1292
+ console.log("[User Question] Plugin registered - AI can now ask you questions");
1293
+ }
1294
+ }
1295
+ };
1296
+
1297
+ // src/plugins/alert.ts
1298
+ var sendAlertTool = {
1299
+ name: "send_alert",
1300
+ description: "Display a browser alert popup with a message to the user",
1301
+ parameters: {
1302
+ type: "object",
1303
+ properties: {
1304
+ message: {
1305
+ type: "string",
1306
+ description: "The message to display in the alert popup"
1307
+ }
1308
+ },
1309
+ required: ["message"]
1310
+ }
1311
+ };
1312
+ var sendAlertExecutor = async (args2) => {
1313
+ const message = args2.message;
1314
+ if (typeof window === "undefined") {
1315
+ console.log(`[Alert] ${message}`);
1316
+ return { success: true, message, environment: "server" };
1317
+ }
1318
+ alert(message);
1319
+ return { success: true, message };
1320
+ };
1321
+ var alertPlugin = {
1322
+ name: "alert",
1323
+ version: "1.0.0",
1324
+ description: "Display browser alert popups",
1325
+ tools: [sendAlertTool],
1326
+ executors: {
1327
+ send_alert: sendAlertExecutor
1328
+ },
1329
+ hooks: {
1330
+ onRegister: () => {
1331
+ console.log("[Alert] Plugin registered");
1332
+ }
1333
+ }
1334
+ };
1335
+
1336
+ // src/plugins/jsExecutor.ts
1337
+ var executeJsTool = {
1338
+ name: "execute_javascript",
1339
+ description: `Execute JavaScript code in the browser and return the results. The code runs in the page context with access to DOM, window, localStorage, etc.
1340
+
1341
+ IMPORTANT USAGE NOTES:
1342
+ - Use console.log() to output values that will be captured and returned
1343
+ - The last expression's value OR explicit return statement will be captured as 'returnValue'
1344
+ - All console.log calls are captured in the 'logs' array
1345
+ - For multi-line code, escape newlines or use semicolons: "const x = 1; const y = 2; console.log(x + y);"
1346
+ - Example: "const prices = [100, 200, 150]; const avg = prices.reduce((a,b) => a+b, 0) / prices.length; console.log('Average:', avg); return avg;"
1347
+ - Can access: document, window, localStorage, fetch, etc.`,
1348
+ parameters: {
1349
+ type: "object",
1350
+ properties: {
1351
+ code: {
1352
+ type: "string",
1353
+ description: "The JavaScript code to execute. Use console.log() for output and/or return a value."
1354
+ }
1355
+ },
1356
+ required: ["code"]
1357
+ }
1358
+ };
1359
+ var executeJsExecutor = async (args) => {
1360
+ const code = args.code;
1361
+ if (typeof window === "undefined") {
1362
+ return {
1363
+ success: false,
1364
+ returnValue: null,
1365
+ logs: [],
1366
+ error: { message: "JavaScript execution requires browser environment" }
1367
+ };
1368
+ }
1369
+ const logs = [];
1370
+ const originalLog = console.log;
1371
+ const originalWarn = console.warn;
1372
+ const originalError = console.error;
1373
+ console.log = (...logArgs) => {
1374
+ logs.push({
1375
+ type: "log",
1376
+ args: logArgs.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a))
1377
+ });
1378
+ originalLog.apply(console, logArgs);
1379
+ };
1380
+ console.warn = (...logArgs) => {
1381
+ logs.push({
1382
+ type: "warn",
1383
+ args: logArgs.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a))
1384
+ });
1385
+ originalWarn.apply(console, logArgs);
1386
+ };
1387
+ console.error = (...logArgs) => {
1388
+ logs.push({
1389
+ type: "error",
1390
+ args: logArgs.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a))
1391
+ });
1392
+ originalError.apply(console, logArgs);
1393
+ };
1394
+ let returnValue;
1395
+ let error = null;
1396
+ try {
1397
+ const wrappedCode = "(async () => { " + code + " })()";
1398
+ returnValue = await eval(wrappedCode);
1399
+ } catch (e) {
1400
+ const err = e;
1401
+ error = { message: err.message, stack: err.stack };
1402
+ } finally {
1403
+ console.log = originalLog;
1404
+ console.warn = originalWarn;
1405
+ console.error = originalError;
1406
+ }
1407
+ return {
1408
+ success: !error,
1409
+ returnValue: returnValue !== void 0 ? typeof returnValue === "object" ? JSON.stringify(returnValue) : String(returnValue) : null,
1410
+ logs,
1411
+ error
1412
+ };
1413
+ };
1414
+ var jsExecutorPlugin = {
1415
+ name: "js-executor",
1416
+ version: "1.0.0",
1417
+ description: "Execute JavaScript code in the browser",
1418
+ tools: [executeJsTool],
1419
+ executors: {
1420
+ execute_javascript: executeJsExecutor
1421
+ },
1422
+ hooks: {
1423
+ onRegister: () => {
1424
+ console.log("[JS Executor] Plugin registered - AI can now execute JavaScript");
1425
+ }
1426
+ }
1427
+ };
1428
+
1429
+ // src/plugins/screenshot.ts
1430
+ var screenshotTool = {
1431
+ name: "take_screenshot",
1432
+ description: `Take a screenshot of the current page and upload it. Returns the URL of the uploaded image that can be used in conversation or for analysis.
1433
+
1434
+ The screenshot captures the visible viewport of the page. The image is uploaded to the server and a permanent URL is returned.
1435
+
1436
+ Use this when:
1437
+ - User asks to see what's on their screen
1438
+ - You need to analyze the current page visually
1439
+ - User wants to share/save the current view`,
1440
+ parameters: {
1441
+ type: "object",
1442
+ properties: {
1443
+ selector: {
1444
+ type: "string",
1445
+ description: "Optional CSS selector to capture a specific element instead of the full page. Leave empty for full page screenshot."
1446
+ }
1447
+ }
1448
+ }
1449
+ };
1450
+ var screenshotExecutor = async (args2) => {
1451
+ const selector = args2.selector;
1452
+ if (typeof window === "undefined" || typeof document === "undefined") {
1453
+ return {
1454
+ success: false,
1455
+ error: "Screenshot requires browser environment"
1456
+ };
1457
+ }
1458
+ try {
1459
+ if (!window.html2canvas) {
1460
+ await new Promise((resolve, reject) => {
1461
+ const script = document.createElement("script");
1462
+ script.src = "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js";
1463
+ script.onload = () => resolve();
1464
+ script.onerror = () => reject(new Error("Failed to load html2canvas"));
1465
+ document.head.appendChild(script);
1466
+ });
1467
+ }
1468
+ const target = selector ? document.querySelector(selector) : document.body;
1469
+ if (!target) {
1470
+ return { success: false, error: "Element not found: " + selector };
1471
+ }
1472
+ const canvas = await window.html2canvas(target, {
1473
+ useCORS: true,
1474
+ allowTaint: true,
1475
+ backgroundColor: "#000000",
1476
+ scale: 1
1477
+ });
1478
+ const blob = await new Promise((resolve) => {
1479
+ canvas.toBlob(resolve, "image/png", 0.9);
1480
+ });
1481
+ if (!blob) {
1482
+ return { success: false, error: "Failed to create image blob" };
1483
+ }
1484
+ const formData = new FormData();
1485
+ formData.append("file", blob, "screenshot-" + Date.now() + ".png");
1486
+ const response = await fetch("/api/files/upload", {
1487
+ method: "POST",
1488
+ body: formData
1489
+ });
1490
+ if (!response.ok) {
1491
+ const errorData = await response.json().catch(() => ({}));
1492
+ return { success: false, error: errorData.error || "Upload failed" };
1493
+ }
1494
+ const data = await response.json();
1495
+ return {
1496
+ success: true,
1497
+ url: data.url,
1498
+ contentType: data.contentType,
1499
+ message: "Screenshot captured and uploaded successfully"
1500
+ };
1501
+ } catch (e) {
1502
+ const err = e;
1503
+ return {
1504
+ success: false,
1505
+ error: err.message || "Screenshot failed"
1506
+ };
1507
+ }
1508
+ };
1509
+ var screenshotPlugin = {
1510
+ name: "screenshot",
1511
+ version: "1.0.0",
1512
+ description: "Take screenshots of the current page",
1513
+ tools: [screenshotTool],
1514
+ executors: {
1515
+ take_screenshot: screenshotExecutor
1516
+ },
1517
+ hooks: {
1518
+ onRegister: () => {
1519
+ console.log("[Screenshot] Plugin registered - AI can now take screenshots");
1520
+ }
1521
+ }
1522
+ };
1523
+
1524
+ // src/plugins/index.ts
1525
+ var availablePlugins = [
1526
+ {
1527
+ ...predictionMarketPlugin,
1528
+ description: "Search and analyze Polymarket and Kalshi prediction markets"
1529
+ },
1530
+ {
1531
+ ...migrateFunPlugin,
1532
+ description: "Search Migrate.fun knowledge base for token migration answers"
1533
+ },
1534
+ {
1535
+ ...piiProtectionPlugin,
1536
+ description: "Tokenizes PII before sending to AI, restores in responses"
1537
+ },
1538
+ {
1539
+ ...userQuestionPlugin,
1540
+ description: "Allows AI to ask users multiple choice questions via modal"
1541
+ },
1542
+ {
1543
+ ...alertPlugin,
1544
+ description: "Display browser alert popups"
1545
+ },
1546
+ {
1547
+ ...jsExecutorPlugin,
1548
+ description: "Execute JavaScript code in the browser"
1549
+ },
1550
+ {
1551
+ ...screenshotPlugin,
1552
+ description: "Take screenshots of the current page"
1553
+ }
1554
+ ];
1555
+
1556
+ // src/styles/tokens.ts
1557
+ var defaults = {
1558
+ colors: {
1559
+ // Backgrounds
1560
+ bgPrimary: "#0b0d10",
1561
+ bgSecondary: "#12161b",
1562
+ bgTertiary: "#1a1f25",
1563
+ bgHover: "#252b33",
1564
+ bgOverlay: "rgba(0, 0, 0, 0.7)",
1565
+ // Borders
1566
+ borderPrimary: "#222b35",
1567
+ borderSecondary: "#333",
1568
+ borderHover: "#444",
1569
+ // Text
1570
+ textPrimary: "#e6eef8",
1571
+ textSecondary: "#8892a4",
1572
+ textTertiary: "#6b7280",
1573
+ textInverse: "#fff",
1574
+ // Accent - Primary (blue)
1575
+ accentPrimary: "#4c9aff",
1576
+ accentPrimaryHover: "#7bb6ff",
1577
+ accentPrimaryBg: "rgba(76, 154, 255, 0.1)",
1578
+ // Accent - Success (green)
1579
+ accentSuccess: "#10b981",
1580
+ accentSuccessHover: "#34d399",
1581
+ accentSuccessBg: "rgba(16, 185, 129, 0.1)",
1582
+ // Accent - Warning (yellow/orange)
1583
+ accentWarning: "#f59e0b",
1584
+ accentWarningBg: "rgba(245, 158, 11, 0.1)",
1585
+ // Accent - Error (red)
1586
+ accentError: "#dc2626",
1587
+ accentErrorHover: "#ef4444",
1588
+ accentErrorBg: "rgba(239, 68, 68, 0.1)",
1589
+ // Messages
1590
+ msgUser: "#1e3a5f",
1591
+ msgAssistant: "#1a2633"
1592
+ },
1593
+ typography: {
1594
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1595
+ fontFamilyMono: '"SF Mono", Monaco, monospace',
1596
+ fontSizeXs: "11px",
1597
+ fontSizeSm: "13px",
1598
+ fontSizeMd: "14px",
1599
+ fontSizeLg: "16px",
1600
+ fontSizeXl: "18px",
1601
+ fontWeightNormal: "400",
1602
+ fontWeightMedium: "500",
1603
+ fontWeightSemibold: "600",
1604
+ lineHeightTight: "1.3",
1605
+ lineHeightNormal: "1.5",
1606
+ lineHeightRelaxed: "1.7"
1607
+ },
1608
+ spacing: {
1609
+ xs: "4px",
1610
+ sm: "8px",
1611
+ md: "12px",
1612
+ lg: "16px",
1613
+ xl: "20px",
1614
+ xxl: "24px"
1615
+ },
1616
+ radius: {
1617
+ sm: "4px",
1618
+ md: "6px",
1619
+ lg: "8px",
1620
+ xl: "12px",
1621
+ pill: "20px",
1622
+ full: "50%"
1623
+ },
1624
+ shadows: {
1625
+ sm: "0 2px 8px rgba(0,0,0,0.2)",
1626
+ md: "0 4px 16px rgba(0,0,0,0.3)",
1627
+ lg: "0 8px 32px rgba(0,0,0,0.4)",
1628
+ xl: "0 16px 48px rgba(0,0,0,0.5)"
1629
+ },
1630
+ // Glow effects (for enhanced themes)
1631
+ glows: {
1632
+ primary: "rgba(76, 154, 255, 0.4)",
1633
+ success: "rgba(16, 185, 129, 0.4)",
1634
+ error: "rgba(239, 68, 68, 0.4)",
1635
+ ambient: "rgba(76, 154, 255, 0.08)"
1636
+ },
1637
+ transitions: {
1638
+ fast: "0.15s ease",
1639
+ normal: "0.2s ease",
1640
+ slow: "0.3s ease"
1641
+ },
1642
+ zIndex: {
1643
+ dropdown: "100",
1644
+ modal: "1000",
1645
+ fullscreen: "1000",
1646
+ modalOverFullscreen: "10000"
1647
+ }
1648
+ };
1649
+ function toVarName(category, key) {
1650
+ const kebab = key.replace(/([A-Z])/g, "-$1").toLowerCase();
1651
+ return `--hustle-${category}-${kebab}`;
1652
+ }
1653
+ function generateCSSVariables() {
1654
+ const lines = [":root {"];
1655
+ for (const [key, value] of Object.entries(defaults.colors)) {
1656
+ lines.push(` ${toVarName("color", key)}: ${value};`);
1657
+ }
1658
+ for (const [key, value] of Object.entries(defaults.typography)) {
1659
+ lines.push(` ${toVarName("font", key)}: ${value};`);
1660
+ }
1661
+ for (const [key, value] of Object.entries(defaults.spacing)) {
1662
+ lines.push(` ${toVarName("space", key)}: ${value};`);
1663
+ }
1664
+ for (const [key, value] of Object.entries(defaults.radius)) {
1665
+ lines.push(` ${toVarName("radius", key)}: ${value};`);
1666
+ }
1667
+ for (const [key, value] of Object.entries(defaults.shadows)) {
1668
+ lines.push(` ${toVarName("shadow", key)}: ${value};`);
1669
+ }
1670
+ for (const [key, value] of Object.entries(defaults.glows)) {
1671
+ lines.push(` ${toVarName("glow", key)}: ${value};`);
1672
+ }
1673
+ for (const [key, value] of Object.entries(defaults.transitions)) {
1674
+ lines.push(` ${toVarName("transition", key)}: ${value};`);
1675
+ }
1676
+ for (const [key, value] of Object.entries(defaults.zIndex)) {
1677
+ lines.push(` ${toVarName("z", key)}: ${value};`);
1678
+ }
1679
+ lines.push("}");
1680
+ return lines.join("\n");
1681
+ }
1682
+ generateCSSVariables();
1683
+ function createColorTokens() {
1684
+ const result = {};
1685
+ for (const [key, defaultValue] of Object.entries(defaults.colors)) {
1686
+ result[key] = `var(${toVarName("color", key)}, ${defaultValue})`;
1687
+ }
1688
+ return result;
1689
+ }
1690
+ function createTypographyTokens() {
1691
+ const result = {};
1692
+ for (const [key, defaultValue] of Object.entries(defaults.typography)) {
1693
+ result[key] = `var(${toVarName("font", key)}, ${defaultValue})`;
1694
+ }
1695
+ return result;
1696
+ }
1697
+ function createSpacingTokens() {
1698
+ const result = {};
1699
+ for (const [key, defaultValue] of Object.entries(defaults.spacing)) {
1700
+ result[key] = `var(${toVarName("space", key)}, ${defaultValue})`;
1701
+ }
1702
+ return result;
1703
+ }
1704
+ function createRadiusTokens() {
1705
+ const result = {};
1706
+ for (const [key, defaultValue] of Object.entries(defaults.radius)) {
1707
+ result[key] = `var(${toVarName("radius", key)}, ${defaultValue})`;
1708
+ }
1709
+ return result;
1710
+ }
1711
+ function createShadowTokens() {
1712
+ const result = {};
1713
+ for (const [key, defaultValue] of Object.entries(defaults.shadows)) {
1714
+ result[key] = `var(${toVarName("shadow", key)}, ${defaultValue})`;
1715
+ }
1716
+ return result;
1717
+ }
1718
+ function createGlowTokens() {
1719
+ const result = {};
1720
+ for (const [key, defaultValue] of Object.entries(defaults.glows)) {
1721
+ result[key] = `var(${toVarName("glow", key)}, ${defaultValue})`;
1722
+ }
1723
+ return result;
1724
+ }
1725
+ function createTransitionTokens() {
1726
+ const result = {};
1727
+ for (const [key, defaultValue] of Object.entries(defaults.transitions)) {
1728
+ result[key] = `var(${toVarName("transition", key)}, ${defaultValue})`;
1729
+ }
1730
+ return result;
1731
+ }
1732
+ function createZIndexTokens() {
1733
+ const result = {};
1734
+ for (const [key, defaultValue] of Object.entries(defaults.zIndex)) {
1735
+ result[key] = parseInt(defaultValue, 10);
1736
+ }
1737
+ return result;
1738
+ }
1739
+ var tokens = {
1740
+ colors: createColorTokens(),
1741
+ typography: createTypographyTokens(),
1742
+ spacing: createSpacingTokens(),
1743
+ radius: createRadiusTokens(),
1744
+ shadows: createShadowTokens(),
1745
+ glows: createGlowTokens(),
1746
+ transitions: createTransitionTokens(),
1747
+ zIndex: createZIndexTokens()
1748
+ };
1749
+ var presets = {
1750
+ base: {
1751
+ fontFamily: tokens.typography.fontFamily,
1752
+ fontSize: tokens.typography.fontSizeMd,
1753
+ lineHeight: tokens.typography.lineHeightNormal,
1754
+ color: tokens.colors.textPrimary
1755
+ },
1756
+ card: {
1757
+ background: tokens.colors.bgSecondary,
1758
+ border: `1px solid ${tokens.colors.borderPrimary}`,
1759
+ borderRadius: tokens.radius.xl
1760
+ },
1761
+ input: {
1762
+ background: tokens.colors.bgTertiary,
1763
+ border: `1px solid ${tokens.colors.borderSecondary}`,
1764
+ borderRadius: tokens.radius.lg,
1765
+ color: tokens.colors.textPrimary,
1766
+ fontSize: tokens.typography.fontSizeMd,
1767
+ padding: `${tokens.spacing.md} ${tokens.spacing.lg}`,
1768
+ transition: `border-color ${tokens.transitions.normal}`
1769
+ },
1770
+ button: {
1771
+ gap: tokens.spacing.sm,
1772
+ padding: `${tokens.spacing.sm} ${tokens.spacing.lg}`,
1773
+ borderRadius: tokens.radius.lg,
1774
+ fontSize: tokens.typography.fontSizeMd,
1775
+ fontWeight: tokens.typography.fontWeightMedium,
1776
+ transition: `all ${tokens.transitions.normal}`,
1777
+ border: `1px solid ${tokens.colors.borderSecondary}`},
1778
+ buttonPrimary: {
1779
+ background: tokens.colors.accentPrimary,
1780
+ color: tokens.colors.textInverse,
1781
+ borderColor: tokens.colors.accentPrimary
1782
+ },
1783
+ buttonSecondary: {
1784
+ background: tokens.colors.bgTertiary,
1785
+ color: tokens.colors.textPrimary,
1786
+ borderColor: tokens.colors.borderSecondary
1787
+ },
1788
+ buttonIcon: {
1789
+ width: "36px",
1790
+ height: "36px",
1791
+ padding: 0,
1792
+ // background inherited from global button styles
1793
+ color: tokens.colors.textSecondary
1794
+ },
1795
+ mono: {
1796
+ fontFamily: tokens.typography.fontFamilyMono,
1797
+ fontSize: tokens.typography.fontSizeSm
1798
+ },
1799
+ label: {
1800
+ fontSize: tokens.typography.fontSizeXs,
1801
+ color: tokens.colors.textTertiary,
1802
+ marginBottom: tokens.spacing.xs
1803
+ }
1804
+ };
1805
+ var animations = `
1806
+ @keyframes hustle-spin {
1807
+ to { transform: rotate(360deg); }
1808
+ }
1809
+ @keyframes hustle-pulse {
1810
+ 0%, 100% { opacity: 1; }
1811
+ 50% { opacity: 0.5; }
1812
+ }
1813
+ @keyframes hustle-glow {
1814
+ 0%, 100% {
1815
+ opacity: 1;
1816
+ text-shadow: 0 0 4px ${defaults.colors.accentPrimaryBg};
1817
+ }
1818
+ 50% {
1819
+ opacity: 0.6;
1820
+ text-shadow: 0 0 8px ${defaults.colors.accentPrimary};
1821
+ }
1822
+ }
1823
+ `;
1824
+ hljs.registerLanguage("javascript", javascript);
1825
+ hljs.registerLanguage("js", javascript);
1826
+ hljs.registerLanguage("typescript", typescript);
1827
+ hljs.registerLanguage("ts", typescript);
1828
+ hljs.registerLanguage("python", python);
1829
+ hljs.registerLanguage("py", python);
1830
+ hljs.registerLanguage("json", json);
1831
+ hljs.registerLanguage("bash", bash);
1832
+ hljs.registerLanguage("sh", bash);
1833
+ hljs.registerLanguage("shell", shell);
1834
+ hljs.registerLanguage("css", css);
1835
+ hljs.registerLanguage("xml", xml);
1836
+ hljs.registerLanguage("html", xml);
1837
+ hljs.registerLanguage("markdown", markdown);
1838
+ hljs.registerLanguage("md", markdown);
1839
+ hljs.registerLanguage("sql", sql);
1840
+ hljs.registerLanguage("yaml", yaml);
1841
+ hljs.registerLanguage("yml", yaml);
1842
+ hljs.registerLanguage("rust", rust);
1843
+ hljs.registerLanguage("go", go);
1844
+ hljs.registerLanguage("java", java);
1845
+ hljs.registerLanguage("cpp", cpp);
1846
+ hljs.registerLanguage("c", cpp);
1847
+ hljs.registerLanguage("csharp", csharp);
1848
+ hljs.registerLanguage("cs", csharp);
1849
+ hljs.registerLanguage("php", php);
1850
+ hljs.registerLanguage("ruby", ruby);
1851
+ hljs.registerLanguage("rb", ruby);
1852
+ hljs.registerLanguage("swift", swift);
1853
+ hljs.registerLanguage("kotlin", kotlin);
1854
+ hljs.registerLanguage("kt", kotlin);
1855
+ var containerStyle = {
1856
+ fontFamily: tokens.typography.fontFamily,
1857
+ fontSize: tokens.typography.fontSizeMd,
1858
+ lineHeight: 1.5,
1859
+ color: "inherit",
1860
+ wordBreak: "break-word"
1861
+ };
1862
+ var scopedStyles = `
1863
+ .hljs-md p {
1864
+ margin: 0 0 0.5em 0;
1865
+ }
1866
+ .hljs-md p:last-child {
1867
+ margin-bottom: 0;
1868
+ }
1869
+ .hljs-md ul,
1870
+ .hljs-md ol {
1871
+ margin: 0.25em 0 0.5em 0;
1872
+ padding-left: 1.5em;
1873
+ }
1874
+ .hljs-md li {
1875
+ margin: 0.1em 0;
1876
+ line-height: 1.4;
1877
+ }
1878
+ .hljs-md li > p {
1879
+ margin: 0;
1880
+ display: inline;
1881
+ }
1882
+ .hljs-md li > ul,
1883
+ .hljs-md li > ol {
1884
+ margin: 0.1em 0;
1885
+ }
1886
+ .hljs-md .code-block-wrapper {
1887
+ position: relative;
1888
+ margin: 0.5em 0;
1889
+ }
1890
+ .hljs-md .code-block-wrapper pre {
1891
+ position: relative;
1892
+ margin: 0;
1893
+ padding: 0.75em 1em;
1894
+ border-radius: 6px;
1895
+ background: #1e1e1e;
1896
+ overflow-x: auto;
1897
+ }
1898
+ .hljs-md .code-block-toolbar {
1899
+ position: absolute;
1900
+ top: 6px;
1901
+ right: 6px;
1902
+ display: flex;
1903
+ gap: 4px;
1904
+ z-index: 10;
1905
+ }
1906
+ .hljs-md .code-block-btn {
1907
+ display: flex;
1908
+ align-items: center;
1909
+ justify-content: center;
1910
+ width: 26px;
1911
+ height: 26px;
1912
+ padding: 0;
1913
+ background: #2d2d2d;
1914
+ border: 1px solid #404040;
1915
+ border-radius: 4px;
1916
+ color: #888;
1917
+ cursor: pointer;
1918
+ transition: all 0.15s ease;
1919
+ opacity: 0.7;
1920
+ }
1921
+ .hljs-md .code-block-wrapper:hover .code-block-btn {
1922
+ opacity: 1;
1923
+ }
1924
+ .hljs-md .code-block-btn:hover {
1925
+ background: #3d3d3d;
1926
+ border-color: #555;
1927
+ color: #ccc;
1928
+ }
1929
+ .hljs-md .code-block-btn.copied {
1930
+ color: ${tokens.colors.accentSuccess};
1931
+ }
1932
+ .hljs-md code {
1933
+ font-family: ${tokens.typography.fontFamilyMono};
1934
+ font-size: 0.9em;
1935
+ }
1936
+ .hljs-md :not(pre) > code {
1937
+ padding: 0.15em 0.4em;
1938
+ border-radius: 4px;
1939
+ background: rgba(255, 255, 255, 0.1);
1940
+ }
1941
+ .hljs-md pre code {
1942
+ padding: 0;
1943
+ background: transparent;
1944
+ font-size: 0.875em;
1945
+ line-height: 1.5;
1946
+ }
1947
+ .hljs-md h1, .hljs-md h2, .hljs-md h3, .hljs-md h4 {
1948
+ margin: 0.5em 0 0.25em 0;
1949
+ font-weight: 600;
1950
+ line-height: 1.3;
1951
+ }
1952
+ .hljs-md h1:first-child, .hljs-md h2:first-child, .hljs-md h3:first-child {
1953
+ margin-top: 0;
1954
+ }
1955
+ .hljs-md h1 { font-size: 1.5em; }
1956
+ .hljs-md h2 { font-size: 1.25em; }
1957
+ .hljs-md h3 { font-size: 1.1em; }
1958
+ .hljs-md h4 { font-size: 1em; }
1959
+ .hljs-md blockquote {
1960
+ margin: 0.5em 0;
1961
+ padding: 0.5em 0 0.5em 1em;
1962
+ border-left: 3px solid ${tokens.colors.borderSecondary};
1963
+ color: ${tokens.colors.textSecondary};
1964
+ }
1965
+ .hljs-md a {
1966
+ color: ${tokens.colors.accentPrimary};
1967
+ text-decoration: underline;
1968
+ }
1969
+ .hljs-md hr {
1970
+ margin: 1em 0;
1971
+ border: none;
1972
+ border-top: 1px solid ${tokens.colors.borderSecondary};
1973
+ }
1974
+ .hljs-md table {
1975
+ width: 100%;
1976
+ margin: 0.5em 0;
1977
+ border-collapse: collapse;
1978
+ }
1979
+ .hljs-md th, .hljs-md td {
1980
+ padding: 0.5em;
1981
+ border: 1px solid ${tokens.colors.borderPrimary};
1982
+ text-align: left;
1983
+ }
1984
+ .hljs-md th {
1985
+ font-weight: 600;
1986
+ background: rgba(255, 255, 255, 0.05);
1987
+ }
1988
+
1989
+ /* highlight.js dark theme (VS Code Dark+ inspired) */
1990
+ .hljs {
1991
+ color: #d4d4d4;
1992
+ background: #1e1e1e;
1993
+ }
1994
+ .hljs-keyword,
1995
+ .hljs-selector-tag,
1996
+ .hljs-title,
1997
+ .hljs-section,
1998
+ .hljs-doctag,
1999
+ .hljs-name,
2000
+ .hljs-strong {
2001
+ color: #569cd6;
2002
+ font-weight: normal;
2003
+ }
2004
+ .hljs-built_in,
2005
+ .hljs-literal,
2006
+ .hljs-type,
2007
+ .hljs-params,
2008
+ .hljs-meta,
2009
+ .hljs-link {
2010
+ color: #4ec9b0;
2011
+ }
2012
+ .hljs-string,
2013
+ .hljs-symbol,
2014
+ .hljs-bullet,
2015
+ .hljs-addition {
2016
+ color: #ce9178;
2017
+ }
2018
+ .hljs-number {
2019
+ color: #b5cea8;
2020
+ }
2021
+ .hljs-comment,
2022
+ .hljs-quote,
2023
+ .hljs-deletion {
2024
+ color: #6a9955;
2025
+ }
2026
+ .hljs-variable,
2027
+ .hljs-template-variable,
2028
+ .hljs-attr {
2029
+ color: #9cdcfe;
2030
+ }
2031
+ .hljs-regexp,
2032
+ .hljs-selector-id,
2033
+ .hljs-selector-class {
2034
+ color: #d7ba7d;
2035
+ }
2036
+ .hljs-emphasis {
2037
+ font-style: italic;
2038
+ }
2039
+ `;
2040
+ marked.use({
2041
+ gfm: true,
2042
+ breaks: false
2043
+ });
2044
+ function highlightCode(code2, lang) {
2045
+ if (lang && hljs.getLanguage(lang)) {
2046
+ try {
2047
+ return hljs.highlight(code2, { language: lang }).value;
2048
+ } catch {
2049
+ }
2050
+ }
2051
+ try {
2052
+ return hljs.highlightAuto(code2).value;
2053
+ } catch {
2054
+ return code2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2055
+ }
2056
+ }
2057
+ var codeBlockCounter = 0;
2058
+ function generateCodeBlockId() {
2059
+ return `code-block-${++codeBlockCounter}`;
2060
+ }
2061
+ function renderMarkdown(content) {
2062
+ const html = marked.parse(content, { async: false });
2063
+ const codeBlockRegex = /<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g;
2064
+ let result = html.replace(codeBlockRegex, (_, lang, code2) => {
2065
+ const decoded = code2.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"');
2066
+ const highlighted = highlightCode(decoded, lang);
2067
+ const id = generateCodeBlockId();
2068
+ const encodedCode = encodeURIComponent(decoded);
2069
+ return `<div class="code-block-wrapper" data-code-id="${id}" data-code="${encodedCode}"><pre><code class="hljs language-${lang}">${highlighted}</code></pre><div class="code-block-toolbar"><button class="code-block-btn" data-action="copy" data-code-id="${id}" title="Copy code"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg></button><button class="code-block-btn" data-action="emblem" data-code-id="${id}" title="Open in Emblem AI"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg></button></div></div>`;
2070
+ });
2071
+ const plainCodeRegex = /<pre><code>([\s\S]*?)<\/code><\/pre>/g;
2072
+ result = result.replace(plainCodeRegex, (_, code2) => {
2073
+ const decoded = code2.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"');
2074
+ const highlighted = highlightCode(decoded, "");
2075
+ const id = generateCodeBlockId();
2076
+ const encodedCode = encodeURIComponent(decoded);
2077
+ return `<div class="code-block-wrapper" data-code-id="${id}" data-code="${encodedCode}"><pre><code class="hljs">${highlighted}</code></pre><div class="code-block-toolbar"><button class="code-block-btn" data-action="copy" data-code-id="${id}" title="Copy code"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg></button><button class="code-block-btn" data-action="emblem" data-code-id="${id}" title="Open in Emblem AI"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg></button></div></div>`;
2078
+ });
2079
+ return result;
2080
+ }
2081
+ function MarkdownContent({ content, className }) {
2082
+ const [rendered, setRendered] = useState("");
2083
+ const containerRef = useRef(null);
2084
+ useEffect(() => {
2085
+ try {
2086
+ const html = renderMarkdown(content);
2087
+ setRendered(html);
2088
+ } catch (err) {
2089
+ console.error("[MarkdownContent] Render error:", err);
2090
+ setRendered(
2091
+ content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>")
2092
+ );
2093
+ }
2094
+ }, [content]);
2095
+ useEffect(() => {
2096
+ const container = containerRef.current;
2097
+ if (!container) return;
2098
+ const handleClick = async (e) => {
2099
+ const target = e.target;
2100
+ const button = target.closest("[data-action]");
2101
+ if (!button) return;
2102
+ const action = button.dataset.action;
2103
+ const codeId = button.dataset.codeId;
2104
+ if (!codeId) return;
2105
+ const wrapper = container.querySelector(`[data-code-id="${codeId}"]`);
2106
+ if (!wrapper) return;
2107
+ const encodedCode = wrapper.dataset.code;
2108
+ if (!encodedCode) return;
2109
+ const code2 = decodeURIComponent(encodedCode);
2110
+ if (action === "copy") {
2111
+ e.preventDefault();
2112
+ try {
2113
+ await navigator.clipboard.writeText(code2);
2114
+ button.classList.add("copied");
2115
+ button.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2116
+ <polyline points="20 6 9 17 4 12"></polyline>
2117
+ </svg>`;
2118
+ setTimeout(() => {
2119
+ button.classList.remove("copied");
2120
+ button.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2121
+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
2122
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
2123
+ </svg>`;
2124
+ }, 2e3);
2125
+ } catch (err) {
2126
+ console.error("Failed to copy:", err);
2127
+ }
2128
+ } else if (action === "emblem") {
2129
+ e.preventDefault();
2130
+ const url = `https://build.emblemvault.ai/?q=${encodeURIComponent(code2)}`;
2131
+ window.open(url, "_blank", "noopener,noreferrer");
2132
+ }
2133
+ };
2134
+ container.addEventListener("click", handleClick);
2135
+ return () => container.removeEventListener("click", handleClick);
2136
+ }, [rendered]);
2137
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2138
+ /* @__PURE__ */ jsx("style", { children: scopedStyles }),
2139
+ /* @__PURE__ */ jsx(
2140
+ "div",
2141
+ {
2142
+ ref: containerRef,
2143
+ style: containerStyle,
2144
+ className: `hljs-md ${className || ""}`,
2145
+ dangerouslySetInnerHTML: { __html: rendered }
2146
+ }
2147
+ )
2148
+ ] });
2149
+ }
2150
+ var styles = {
2151
+ // Container
2152
+ container: {
2153
+ display: "flex",
2154
+ flexDirection: "column",
2155
+ height: "100%",
2156
+ background: tokens.colors.bgSecondary,
2157
+ borderRadius: tokens.radius.xl,
2158
+ border: `1px solid ${tokens.colors.borderPrimary}`,
2159
+ fontFamily: tokens.typography.fontFamily,
2160
+ color: tokens.colors.textPrimary
2161
+ },
2162
+ // Not ready / auth required states
2163
+ placeholder: {
2164
+ padding: tokens.spacing.xxl,
2165
+ background: tokens.colors.bgSecondary,
2166
+ borderRadius: tokens.radius.xl,
2167
+ border: `1px solid ${tokens.colors.borderPrimary}`
2168
+ },
2169
+ placeholderContent: {
2170
+ color: tokens.colors.textSecondary
2171
+ },
2172
+ placeholderTitle: {
2173
+ fontSize: tokens.typography.fontSizeLg,
2174
+ fontWeight: tokens.typography.fontWeightMedium,
2175
+ marginBottom: tokens.spacing.xs
2176
+ },
2177
+ placeholderText: {
2178
+ fontSize: tokens.typography.fontSizeSm,
2179
+ color: tokens.colors.textTertiary
2180
+ },
2181
+ loadingSpinner: {
2182
+ border: `2px solid ${tokens.colors.textTertiary}`,
2183
+ borderRadius: tokens.radius.full,
2184
+ marginBottom: tokens.spacing.sm
2185
+ },
2186
+ // Header - darker shade
2187
+ header: {
2188
+ display: "flex",
2189
+ alignItems: "center",
2190
+ justifyContent: "space-between",
2191
+ padding: `${tokens.spacing.md} ${tokens.spacing.lg}`,
2192
+ background: tokens.colors.bgPrimary,
2193
+ borderBottom: `1px solid ${tokens.colors.borderPrimary}`,
2194
+ borderRadius: `${tokens.radius.xl} ${tokens.radius.xl} 0 0`
2195
+ },
2196
+ headerTitle: {
2197
+ fontWeight: tokens.typography.fontWeightSemibold,
2198
+ color: tokens.colors.textPrimary,
2199
+ fontSize: tokens.typography.fontSizeMd
2200
+ },
2201
+ headerActions: {
2202
+ display: "flex",
2203
+ alignItems: "center",
2204
+ gap: tokens.spacing.sm
2205
+ },
2206
+ // Model selector
2207
+ select: {
2208
+ fontSize: tokens.typography.fontSizeSm,
2209
+ padding: `${tokens.spacing.xs} ${tokens.spacing.sm}`,
2210
+ border: `1px solid ${tokens.colors.borderSecondary}`,
2211
+ borderRadius: tokens.radius.md,
2212
+ background: tokens.colors.bgTertiary,
2213
+ color: tokens.colors.textPrimary},
2214
+ // Settings button
2215
+ settingsBtn: {
2216
+ ...presets.buttonIcon,
2217
+ borderRadius: tokens.radius.md
2218
+ },
2219
+ settingsBtnActive: {
2220
+ background: tokens.colors.accentPrimaryBg,
2221
+ color: tokens.colors.accentPrimary
2222
+ },
2223
+ settingsBtnInactive: {
2224
+ color: tokens.colors.textSecondary
2225
+ },
2226
+ // Settings Modal
2227
+ modalOverlay: {
2228
+ position: "fixed",
2229
+ top: 0,
2230
+ left: 0,
2231
+ right: 0,
2232
+ bottom: 0,
2233
+ background: tokens.colors.bgOverlay,
2234
+ display: "flex",
2235
+ alignItems: "center",
2236
+ justifyContent: "center",
2237
+ zIndex: tokens.zIndex.modal
2238
+ },
2239
+ modal: {
2240
+ background: tokens.colors.bgSecondary,
2241
+ borderRadius: tokens.radius.xl,
2242
+ border: `1px solid ${tokens.colors.borderPrimary}`,
2243
+ width: "100%",
2244
+ maxWidth: "440px",
2245
+ maxHeight: "90vh",
2246
+ overflow: "auto",
2247
+ boxShadow: tokens.shadows.xl
2248
+ },
2249
+ modalHeader: {
2250
+ display: "flex",
2251
+ alignItems: "center",
2252
+ justifyContent: "space-between",
2253
+ padding: `${tokens.spacing.lg} ${tokens.spacing.xl}`,
2254
+ borderBottom: `1px solid ${tokens.colors.borderPrimary}`
2255
+ },
2256
+ modalTitle: {
2257
+ fontSize: tokens.typography.fontSizeLg,
2258
+ fontWeight: tokens.typography.fontWeightSemibold,
2259
+ color: tokens.colors.textPrimary
2260
+ },
2261
+ modalClose: {
2262
+ background: "transparent",
2263
+ border: "none",
2264
+ color: tokens.colors.textTertiary,
2265
+ fontSize: "20px",
2266
+ cursor: "pointer",
2267
+ padding: tokens.spacing.xs,
2268
+ lineHeight: 1,
2269
+ transition: `color ${tokens.transitions.fast}`
2270
+ },
2271
+ modalBody: {
2272
+ padding: tokens.spacing.xl
2273
+ },
2274
+ // Settings sections
2275
+ settingGroup: {
2276
+ marginBottom: tokens.spacing.xl
2277
+ },
2278
+ settingLabel: {
2279
+ display: "block",
2280
+ fontSize: tokens.typography.fontSizeMd,
2281
+ fontWeight: tokens.typography.fontWeightMedium,
2282
+ color: tokens.colors.textPrimary,
2283
+ marginBottom: tokens.spacing.xs
2284
+ },
2285
+ settingDescription: {
2286
+ fontSize: tokens.typography.fontSizeSm,
2287
+ color: tokens.colors.textTertiary,
2288
+ marginBottom: tokens.spacing.md
2289
+ },
2290
+ settingSelect: {
2291
+ width: "100%",
2292
+ padding: `${tokens.spacing.md} ${tokens.spacing.lg}`,
2293
+ fontSize: tokens.typography.fontSizeMd,
2294
+ background: tokens.colors.bgTertiary,
2295
+ border: `1px solid ${tokens.colors.borderSecondary}`,
2296
+ borderRadius: tokens.radius.lg,
2297
+ color: tokens.colors.textPrimary,
2298
+ outline: "none",
2299
+ cursor: "pointer",
2300
+ appearance: "none",
2301
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238892a4' d='M6 8L1 3h10z'/%3E%3C/svg%3E")`,
2302
+ backgroundRepeat: "no-repeat",
2303
+ backgroundPosition: "right 12px center",
2304
+ paddingRight: "36px"
2305
+ },
2306
+ modelInfo: {
2307
+ fontSize: tokens.typography.fontSizeXs,
2308
+ color: tokens.colors.textTertiary,
2309
+ marginTop: tokens.spacing.sm
2310
+ },
2311
+ // Toggle switch row
2312
+ toggleRow: {
2313
+ display: "flex",
2314
+ alignItems: "center",
2315
+ justifyContent: "space-between",
2316
+ padding: `${tokens.spacing.md} ${tokens.spacing.lg}`,
2317
+ background: tokens.colors.bgTertiary,
2318
+ borderRadius: tokens.radius.lg,
2319
+ marginBottom: tokens.spacing.sm
2320
+ },
2321
+ toggleLabel: {
2322
+ fontSize: tokens.typography.fontSizeMd,
2323
+ color: tokens.colors.textPrimary
2324
+ },
2325
+ toggleSwitch: {
2326
+ position: "relative",
2327
+ width: "44px",
2328
+ height: "24px",
2329
+ background: tokens.colors.borderSecondary,
2330
+ borderRadius: "12px",
2331
+ cursor: "pointer",
2332
+ transition: `background ${tokens.transitions.fast}`
2333
+ },
2334
+ toggleSwitchActive: {
2335
+ background: tokens.colors.accentPrimary
2336
+ },
2337
+ toggleKnob: {
2338
+ position: "absolute",
2339
+ top: "2px",
2340
+ left: "2px",
2341
+ width: "20px",
2342
+ height: "20px",
2343
+ background: tokens.colors.textPrimary,
2344
+ borderRadius: tokens.radius.full,
2345
+ transition: `transform ${tokens.transitions.fast}`
2346
+ },
2347
+ toggleKnobActive: {
2348
+ transform: "translateX(20px)"
2349
+ },
2350
+ // Settings textarea
2351
+ settingTextarea: {
2352
+ width: "100%",
2353
+ minHeight: "100px",
2354
+ padding: tokens.spacing.lg,
2355
+ fontSize: tokens.typography.fontSizeMd,
2356
+ background: tokens.colors.bgTertiary,
2357
+ border: `1px solid ${tokens.colors.borderSecondary}`,
2358
+ borderRadius: tokens.radius.lg,
2359
+ color: tokens.colors.textPrimary,
2360
+ outline: "none",
2361
+ resize: "vertical",
2362
+ fontFamily: tokens.typography.fontFamily
2363
+ },
2364
+ // Messages area
2365
+ messagesArea: {
2366
+ flex: 1,
2367
+ overflowY: "auto",
2368
+ padding: tokens.spacing.lg,
2369
+ background: tokens.colors.bgSecondary
2370
+ },
2371
+ messagesEmpty: {
2372
+ textAlign: "center",
2373
+ color: tokens.colors.textTertiary,
2374
+ padding: tokens.spacing.xxl
2375
+ },
2376
+ messagesContainer: {
2377
+ display: "flex",
2378
+ flexDirection: "column",
2379
+ gap: tokens.spacing.lg
2380
+ },
2381
+ // Tool calls indicator
2382
+ toolCallsIndicator: {
2383
+ display: "flex",
2384
+ flexWrap: "wrap",
2385
+ gap: tokens.spacing.sm,
2386
+ padding: `0 ${tokens.spacing.lg}`
2387
+ },
2388
+ toolCallBadge: {
2389
+ display: "inline-flex",
2390
+ alignItems: "center",
2391
+ gap: tokens.spacing.xs,
2392
+ padding: `${tokens.spacing.xs} ${tokens.spacing.sm}`,
2393
+ fontSize: tokens.typography.fontSizeXs,
2394
+ background: tokens.colors.accentWarningBg,
2395
+ color: tokens.colors.accentWarning,
2396
+ borderRadius: tokens.radius.pill
2397
+ },
2398
+ toolCallDot: {
2399
+ width: "8px",
2400
+ height: "8px",
2401
+ background: tokens.colors.accentWarning,
2402
+ borderRadius: tokens.radius.full,
2403
+ animation: "hustle-pulse 1s ease-in-out infinite"
2404
+ },
2405
+ // Attachments preview
2406
+ attachmentsPreview: {
2407
+ padding: `${tokens.spacing.sm} ${tokens.spacing.lg}`,
2408
+ borderTop: `1px solid ${tokens.colors.borderPrimary}`,
2409
+ display: "flex",
2410
+ flexWrap: "wrap",
2411
+ gap: tokens.spacing.sm
2412
+ },
2413
+ attachmentItem: {
2414
+ display: "inline-flex",
2415
+ alignItems: "center",
2416
+ gap: tokens.spacing.xs,
2417
+ padding: `${tokens.spacing.xs} ${tokens.spacing.sm}`,
2418
+ background: tokens.colors.bgTertiary,
2419
+ borderRadius: tokens.radius.md,
2420
+ fontSize: tokens.typography.fontSizeSm
2421
+ },
2422
+ attachmentName: {
2423
+ maxWidth: "100px",
2424
+ overflow: "hidden",
2425
+ textOverflow: "ellipsis",
2426
+ whiteSpace: "nowrap"
2427
+ },
2428
+ attachmentRemove: {
2429
+ background: "none",
2430
+ border: "none",
2431
+ color: tokens.colors.textTertiary,
2432
+ cursor: "pointer",
2433
+ fontSize: "14px",
2434
+ padding: 0,
2435
+ lineHeight: 1
2436
+ },
2437
+ // Input area - slightly darker than messages
2438
+ inputArea: {
2439
+ padding: tokens.spacing.lg,
2440
+ background: tokens.colors.bgPrimary,
2441
+ borderTop: `1px solid ${tokens.colors.borderPrimary}`,
2442
+ borderRadius: `0 0 ${tokens.radius.xl} ${tokens.radius.xl}`
2443
+ },
2444
+ inputRow: {
2445
+ display: "flex",
2446
+ alignItems: "center",
2447
+ gap: tokens.spacing.sm
2448
+ },
2449
+ inputContainer: {
2450
+ flex: 1,
2451
+ display: "flex",
2452
+ alignItems: "center",
2453
+ background: tokens.colors.bgTertiary,
2454
+ border: `1px solid ${tokens.colors.borderSecondary}`,
2455
+ borderRadius: tokens.radius.lg,
2456
+ overflow: "hidden"
2457
+ },
2458
+ attachBtn: {
2459
+ width: "40px",
2460
+ height: "40px",
2461
+ padding: 0,
2462
+ background: "transparent",
2463
+ border: "none",
2464
+ borderRadius: 0,
2465
+ color: tokens.colors.textTertiary,
2466
+ flexShrink: 0
2467
+ },
2468
+ inputWrapper: {
2469
+ flex: 1
2470
+ },
2471
+ input: {
2472
+ width: "100%",
2473
+ padding: `${tokens.spacing.md} ${tokens.spacing.sm}`,
2474
+ background: "transparent",
2475
+ border: "none",
2476
+ color: tokens.colors.textPrimary,
2477
+ fontSize: tokens.typography.fontSizeMd,
2478
+ outline: "none",
2479
+ resize: "none"
2480
+ },
2481
+ inputDisabled: {
2482
+ background: tokens.colors.bgTertiary,
2483
+ cursor: "not-allowed"
2484
+ },
2485
+ sendBtn: {
2486
+ // Inherits global button styles from CSS
2487
+ height: "40px",
2488
+ padding: `0 ${tokens.spacing.lg}`,
2489
+ fontWeight: tokens.typography.fontWeightMedium
2490
+ },
2491
+ sendBtnDisabled: {
2492
+ opacity: 0.5,
2493
+ cursor: "not-allowed"
2494
+ },
2495
+ sendSpinner: {
2496
+ display: "inline-block",
2497
+ width: "16px",
2498
+ height: "16px",
2499
+ border: "2px solid currentColor",
2500
+ borderTopColor: "transparent",
2501
+ borderRadius: tokens.radius.full,
2502
+ animation: "hustle-spin 0.8s linear infinite"
2503
+ },
2504
+ // Error display
2505
+ errorBox: {
2506
+ marginTop: tokens.spacing.sm,
2507
+ padding: `${tokens.spacing.sm} ${tokens.spacing.md}`,
2508
+ background: tokens.colors.accentErrorBg,
2509
+ color: tokens.colors.accentError,
2510
+ fontSize: tokens.typography.fontSizeSm,
2511
+ borderRadius: tokens.radius.md
2512
+ },
2513
+ // Message bubbles
2514
+ messageBubbleContainer: {
2515
+ display: "flex"
2516
+ },
2517
+ messageBubbleUser: {
2518
+ justifyContent: "flex-end"
2519
+ },
2520
+ messageBubbleAssistant: {
2521
+ justifyContent: "flex-start"
2522
+ },
2523
+ messageBubble: {
2524
+ maxWidth: "80%",
2525
+ padding: `${tokens.spacing.sm} ${tokens.spacing.lg}`,
2526
+ borderRadius: tokens.radius.lg
2527
+ },
2528
+ messageBubbleUserStyle: {
2529
+ background: tokens.colors.msgUser,
2530
+ color: tokens.colors.textPrimary
2531
+ },
2532
+ messageBubbleAssistantStyle: {
2533
+ background: tokens.colors.msgAssistant,
2534
+ color: tokens.colors.textPrimary
2535
+ },
2536
+ messageBubbleSystemStyle: {
2537
+ background: tokens.colors.bgTertiary,
2538
+ color: tokens.colors.textSecondary,
2539
+ fontSize: tokens.typography.fontSizeSm,
2540
+ fontStyle: "italic"
2541
+ },
2542
+ messageContent: {
2543
+ whiteSpace: "pre-wrap",
2544
+ wordBreak: "break-word",
2545
+ lineHeight: tokens.typography.lineHeightRelaxed
2546
+ },
2547
+ streamingCursor: {
2548
+ display: "inline-block",
2549
+ width: "2px",
2550
+ height: "16px",
2551
+ marginLeft: tokens.spacing.xs,
2552
+ background: "currentColor",
2553
+ animation: "hustle-pulse 0.8s ease-in-out infinite"
2554
+ },
2555
+ // Tool calls debug
2556
+ toolCallsDebug: {
2557
+ marginTop: tokens.spacing.sm,
2558
+ paddingTop: tokens.spacing.sm,
2559
+ borderTop: `1px solid ${tokens.colors.borderSecondary}`,
2560
+ fontSize: tokens.typography.fontSizeXs
2561
+ },
2562
+ toolCallsDebugTitle: {
2563
+ fontWeight: tokens.typography.fontWeightMedium,
2564
+ color: tokens.colors.textSecondary,
2565
+ marginBottom: tokens.spacing.xs
2566
+ },
2567
+ toolCallDebugItem: {
2568
+ background: "rgba(255,255,255,0.05)",
2569
+ borderRadius: tokens.radius.sm,
2570
+ padding: tokens.spacing.xs,
2571
+ marginTop: tokens.spacing.xs
2572
+ },
2573
+ toolCallDebugName: {
2574
+ ...presets.mono
2575
+ },
2576
+ toolCallDebugArgs: {
2577
+ ...presets.mono,
2578
+ marginTop: tokens.spacing.xs,
2579
+ fontSize: "10px",
2580
+ overflow: "auto"
2581
+ },
2582
+ // Plugin management styles
2583
+ settingDivider: {
2584
+ height: "1px",
2585
+ background: tokens.colors.borderPrimary,
2586
+ margin: `${tokens.spacing.xl} 0`
2587
+ },
2588
+ pluginList: {
2589
+ display: "flex",
2590
+ flexDirection: "column",
2591
+ gap: tokens.spacing.sm
2592
+ },
2593
+ pluginRow: {
2594
+ display: "flex",
2595
+ alignItems: "center",
2596
+ justifyContent: "space-between",
2597
+ padding: `${tokens.spacing.md} ${tokens.spacing.lg}`,
2598
+ background: tokens.colors.bgTertiary,
2599
+ borderRadius: tokens.radius.lg
2600
+ },
2601
+ pluginInfo: {
2602
+ display: "flex",
2603
+ alignItems: "center",
2604
+ gap: tokens.spacing.md,
2605
+ flex: 1,
2606
+ minWidth: 0
2607
+ },
2608
+ pluginIcon: {
2609
+ fontSize: "20px",
2610
+ flexShrink: 0
2611
+ },
2612
+ pluginDetails: {
2613
+ flex: 1,
2614
+ minWidth: 0
2615
+ },
2616
+ pluginName: {
2617
+ display: "block",
2618
+ fontWeight: tokens.typography.fontWeightMedium,
2619
+ color: tokens.colors.textPrimary,
2620
+ whiteSpace: "nowrap",
2621
+ overflow: "hidden",
2622
+ textOverflow: "ellipsis"
2623
+ },
2624
+ pluginMeta: {
2625
+ display: "block",
2626
+ fontSize: tokens.typography.fontSizeXs,
2627
+ color: tokens.colors.textTertiary
2628
+ },
2629
+ pluginEmpty: {
2630
+ padding: tokens.spacing.lg,
2631
+ textAlign: "center",
2632
+ color: tokens.colors.textTertiary,
2633
+ fontSize: tokens.typography.fontSizeSm
2634
+ },
2635
+ availablePluginsHeader: {
2636
+ fontSize: tokens.typography.fontSizeXs,
2637
+ fontWeight: tokens.typography.fontWeightSemibold,
2638
+ color: tokens.colors.textSecondary,
2639
+ textTransform: "uppercase",
2640
+ letterSpacing: "0.5px",
2641
+ marginTop: tokens.spacing.lg,
2642
+ marginBottom: tokens.spacing.sm
2643
+ },
2644
+ installBtn: {
2645
+ padding: `${tokens.spacing.xs} ${tokens.spacing.md}`,
2646
+ fontSize: tokens.typography.fontSizeSm,
2647
+ background: "transparent",
2648
+ border: `1px solid ${tokens.colors.accentPrimary}`,
2649
+ borderRadius: tokens.radius.md,
2650
+ color: tokens.colors.accentPrimary,
2651
+ cursor: "pointer",
2652
+ transition: `all ${tokens.transitions.fast}`,
2653
+ whiteSpace: "nowrap"
2654
+ },
2655
+ uninstallBtn: {
2656
+ padding: `${tokens.spacing.xs} ${tokens.spacing.md}`,
2657
+ fontSize: tokens.typography.fontSizeSm,
2658
+ background: "transparent",
2659
+ border: `1px solid ${tokens.colors.accentError}`,
2660
+ borderRadius: tokens.radius.md,
2661
+ color: tokens.colors.accentError,
2662
+ cursor: "pointer",
2663
+ transition: `all ${tokens.transitions.fast}`,
2664
+ whiteSpace: "nowrap"
2665
+ }
2666
+ };
2667
+ function generateId() {
2668
+ return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
2669
+ }
2670
+ function HustleChat({
2671
+ className = "",
2672
+ placeholder = "Type a message...",
2673
+ showSettings = false,
2674
+ showDebug = false,
2675
+ initialSystemPrompt = "",
2676
+ onMessage,
2677
+ onToolCall,
2678
+ onResponse
2679
+ }) {
2680
+ const {
2681
+ instanceId,
2682
+ isApiKeyMode,
2683
+ isReady,
2684
+ isLoading,
2685
+ error: error2,
2686
+ models,
2687
+ chatStream,
2688
+ uploadFile,
2689
+ selectedModel,
2690
+ setSelectedModel,
2691
+ systemPrompt,
2692
+ setSystemPrompt,
2693
+ skipServerPrompt,
2694
+ setSkipServerPrompt
2695
+ } = useHustle();
2696
+ const authContext = useEmblemAuthOptional();
2697
+ const isAuthenticated = isApiKeyMode || (authContext?.isAuthenticated ?? false);
2698
+ const {
2699
+ plugins,
2700
+ registerPlugin,
2701
+ unregisterPlugin,
2702
+ enablePlugin,
2703
+ disablePlugin
2704
+ } = usePlugins(instanceId);
2705
+ const [messages, setMessages] = useState([]);
2706
+ const [inputValue, setInputValue] = useState("");
2707
+ const [isStreaming, setIsStreaming] = useState(false);
2708
+ const [attachments, setAttachments] = useState([]);
2709
+ const [currentToolCalls, setCurrentToolCalls] = useState([]);
2710
+ const [showSettingsPanel, setShowSettingsPanel] = useState(false);
2711
+ const messagesEndRef = useRef(null);
2712
+ const fileInputRef = useRef(null);
2713
+ useEffect(() => {
2714
+ if (initialSystemPrompt && !systemPrompt) {
2715
+ setSystemPrompt(initialSystemPrompt);
2716
+ }
2717
+ }, [initialSystemPrompt, systemPrompt, setSystemPrompt]);
2718
+ useEffect(() => {
2719
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
2720
+ }, [messages]);
2721
+ const handleFileSelect = useCallback(
2722
+ async (e) => {
2723
+ const files = e.target.files;
2724
+ if (!files || files.length === 0) return;
2725
+ for (const file of Array.from(files)) {
2726
+ try {
2727
+ const attachment = await uploadFile(file);
2728
+ setAttachments((prev) => [...prev, attachment]);
2729
+ } catch (err) {
2730
+ console.error("Upload failed:", err);
2731
+ }
2732
+ }
2733
+ if (fileInputRef.current) {
2734
+ fileInputRef.current.value = "";
2735
+ }
2736
+ },
2737
+ [uploadFile]
2738
+ );
2739
+ const removeAttachment = useCallback((index) => {
2740
+ setAttachments((prev) => prev.filter((_, i) => i !== index));
2741
+ }, []);
2742
+ const sendMessage = useCallback(async () => {
2743
+ const content = inputValue.trim();
2744
+ if (!content || isStreaming || !isReady) return;
2745
+ const userMessage = {
2746
+ id: generateId(),
2747
+ role: "user",
2748
+ content
2749
+ };
2750
+ setMessages((prev) => [...prev, userMessage]);
2751
+ setInputValue("");
2752
+ onMessage?.(userMessage);
2753
+ const assistantMessage = {
2754
+ id: generateId(),
2755
+ role: "assistant",
2756
+ content: "",
2757
+ isStreaming: true,
2758
+ toolCalls: []
2759
+ };
2760
+ setMessages((prev) => [...prev, assistantMessage]);
2761
+ setIsStreaming(true);
2762
+ setCurrentToolCalls([]);
2763
+ try {
2764
+ const chatMessages = messages.filter((m) => !m.isStreaming).map((m) => ({ role: m.role, content: m.content }));
2765
+ chatMessages.push({ role: "user", content });
2766
+ const stream = chatStream({
2767
+ messages: chatMessages,
2768
+ attachments: attachments.length > 0 ? attachments : void 0,
2769
+ processChunks: true
2770
+ });
2771
+ setAttachments([]);
2772
+ let fullContent = "";
2773
+ const toolCallsAccumulated = [];
2774
+ for await (const chunk of stream) {
2775
+ if (chunk.type === "text") {
2776
+ fullContent += chunk.value;
2777
+ setMessages(
2778
+ (prev) => prev.map(
2779
+ (m) => m.id === assistantMessage.id ? { ...m, content: fullContent } : m
2780
+ )
2781
+ );
2782
+ } else if (chunk.type === "tool_call") {
2783
+ const toolCall = chunk.value;
2784
+ toolCallsAccumulated.push(toolCall);
2785
+ setCurrentToolCalls([...toolCallsAccumulated]);
2786
+ setMessages(
2787
+ (prev) => prev.map(
2788
+ (m) => m.id === assistantMessage.id ? { ...m, toolCalls: [...toolCallsAccumulated] } : m
2789
+ )
2790
+ );
2791
+ onToolCall?.(toolCall);
2792
+ } else if (chunk.type === "error") {
2793
+ console.error("Stream error:", chunk.value);
2794
+ }
2795
+ }
2796
+ const processedResponse = await stream.response;
2797
+ const finalContent = processedResponse?.content || fullContent || "(No response)";
2798
+ setMessages(
2799
+ (prev) => prev.map(
2800
+ (m) => m.id === assistantMessage.id ? { ...m, isStreaming: false, content: finalContent } : m
2801
+ )
2802
+ );
2803
+ onResponse?.(finalContent);
2804
+ } catch (err) {
2805
+ console.error("Chat error:", err);
2806
+ setMessages(
2807
+ (prev) => prev.map(
2808
+ (m) => m.id === assistantMessage.id ? { ...m, isStreaming: false, content: `Error: ${err instanceof Error ? err.message : "Unknown error"}` } : m
2809
+ )
2810
+ );
2811
+ } finally {
2812
+ setIsStreaming(false);
2813
+ setCurrentToolCalls([]);
2814
+ }
2815
+ }, [inputValue, isStreaming, isReady, messages, chatStream, attachments, onMessage, onToolCall, onResponse]);
2816
+ const handleKeyPress = useCallback(
2817
+ (e) => {
2818
+ if (e.key === "Enter" && !e.shiftKey) {
2819
+ e.preventDefault();
2820
+ sendMessage();
2821
+ }
2822
+ },
2823
+ [sendMessage]
2824
+ );
2825
+ const getPlaceholderMessage = () => {
2826
+ if (!isAuthenticated) {
2827
+ return "Connect to start chatting...";
2828
+ }
2829
+ if (!isReady) {
2830
+ return "Initializing...";
2831
+ }
2832
+ return "Start a conversation...";
2833
+ };
2834
+ const canChat = isAuthenticated && isReady;
2835
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2836
+ /* @__PURE__ */ jsx("style", { children: animations }),
2837
+ /* @__PURE__ */ jsxs("div", { className, style: styles.container, children: [
2838
+ /* @__PURE__ */ jsxs("div", { style: styles.header, children: [
2839
+ /* @__PURE__ */ jsx("h2", { style: styles.headerTitle, children: "Chat" }),
2840
+ /* @__PURE__ */ jsxs("div", { style: styles.headerActions, children: [
2841
+ selectedModel && /* @__PURE__ */ jsx("span", { style: { fontSize: tokens.typography.fontSizeSm, color: tokens.colors.textSecondary }, children: selectedModel.split("/").pop() }),
2842
+ showSettings && /* @__PURE__ */ jsx(
2843
+ "button",
2844
+ {
2845
+ type: "button",
2846
+ onClick: () => setShowSettingsPanel(!showSettingsPanel),
2847
+ style: {
2848
+ ...styles.settingsBtn,
2849
+ ...showSettingsPanel ? styles.settingsBtnActive : styles.settingsBtnInactive
2850
+ },
2851
+ title: "Settings",
2852
+ children: /* @__PURE__ */ jsx(SettingsIcon, {})
2853
+ }
2854
+ )
2855
+ ] })
2856
+ ] }),
2857
+ showSettings && showSettingsPanel && /* @__PURE__ */ jsx("div", { style: styles.modalOverlay, onClick: () => setShowSettingsPanel(false), children: /* @__PURE__ */ jsxs("div", { style: styles.modal, onClick: (e) => e.stopPropagation(), children: [
2858
+ /* @__PURE__ */ jsxs("div", { style: styles.modalHeader, children: [
2859
+ /* @__PURE__ */ jsx("span", { style: styles.modalTitle, children: "Settings" }),
2860
+ /* @__PURE__ */ jsx(
2861
+ "button",
2862
+ {
2863
+ type: "button",
2864
+ style: styles.modalClose,
2865
+ onClick: () => setShowSettingsPanel(false),
2866
+ children: "\xD7"
2867
+ }
2868
+ )
2869
+ ] }),
2870
+ /* @__PURE__ */ jsxs("div", { style: styles.modalBody, children: [
2871
+ /* @__PURE__ */ jsxs("div", { style: styles.settingGroup, children: [
2872
+ /* @__PURE__ */ jsx("label", { style: styles.settingLabel, children: "Model" }),
2873
+ /* @__PURE__ */ jsx("p", { style: styles.settingDescription, children: "Select the AI model to use for chat responses" }),
2874
+ /* @__PURE__ */ jsxs(
2875
+ "select",
2876
+ {
2877
+ value: selectedModel,
2878
+ onChange: (e) => setSelectedModel(e.target.value),
2879
+ style: styles.settingSelect,
2880
+ children: [
2881
+ /* @__PURE__ */ jsx("option", { value: "", children: "Default (server decides)" }),
2882
+ (() => {
2883
+ const grouped = {};
2884
+ models.forEach((model) => {
2885
+ const [provider] = model.id.split("/");
2886
+ if (!grouped[provider]) grouped[provider] = [];
2887
+ grouped[provider].push(model);
2888
+ });
2889
+ return Object.entries(grouped).map(([provider, providerModels]) => /* @__PURE__ */ jsx("optgroup", { label: provider.charAt(0).toUpperCase() + provider.slice(1), children: providerModels.map((model) => /* @__PURE__ */ jsx("option", { value: model.id, children: model.name }, model.id)) }, provider));
2890
+ })()
2891
+ ]
2892
+ }
2893
+ ),
2894
+ selectedModel && (() => {
2895
+ const model = models.find((m) => m.id === selectedModel);
2896
+ if (!model) return null;
2897
+ const contextK = Math.round(model.context_length / 1e3);
2898
+ const promptCost = parseFloat(model.pricing?.prompt || "0") * 1e6;
2899
+ const completionCost = parseFloat(model.pricing?.completion || "0") * 1e6;
2900
+ return /* @__PURE__ */ jsxs("div", { style: styles.modelInfo, children: [
2901
+ "Context: ",
2902
+ contextK,
2903
+ "K tokens | Cost: $",
2904
+ promptCost.toFixed(2),
2905
+ "/$",
2906
+ completionCost.toFixed(2),
2907
+ " per 1M tokens"
2908
+ ] });
2909
+ })()
2910
+ ] }),
2911
+ /* @__PURE__ */ jsxs("div", { style: styles.settingGroup, children: [
2912
+ /* @__PURE__ */ jsx("label", { style: styles.settingLabel, children: "Server System Prompt" }),
2913
+ /* @__PURE__ */ jsxs(
2914
+ "div",
2915
+ {
2916
+ style: styles.toggleRow,
2917
+ onClick: () => setSkipServerPrompt(!skipServerPrompt),
2918
+ children: [
2919
+ /* @__PURE__ */ jsx("span", { style: styles.toggleLabel, children: "Skip server-provided system prompt" }),
2920
+ /* @__PURE__ */ jsx("div", { style: {
2921
+ ...styles.toggleSwitch,
2922
+ ...skipServerPrompt ? styles.toggleSwitchActive : {}
2923
+ }, children: /* @__PURE__ */ jsx("div", { style: {
2924
+ ...styles.toggleKnob,
2925
+ ...skipServerPrompt ? styles.toggleKnobActive : {}
2926
+ } }) })
2927
+ ]
2928
+ }
2929
+ ),
2930
+ /* @__PURE__ */ jsx("p", { style: styles.settingDescription, children: "When enabled, the server's default system prompt will not be used" })
2931
+ ] }),
2932
+ /* @__PURE__ */ jsxs("div", { style: styles.settingGroup, children: [
2933
+ /* @__PURE__ */ jsx("label", { style: styles.settingLabel, children: "Custom System Prompt" }),
2934
+ /* @__PURE__ */ jsx("p", { style: styles.settingDescription, children: "Provide instructions for how the AI should behave" }),
2935
+ /* @__PURE__ */ jsx(
2936
+ "textarea",
2937
+ {
2938
+ value: systemPrompt,
2939
+ onChange: (e) => setSystemPrompt(e.target.value),
2940
+ placeholder: "You are a helpful assistant...",
2941
+ style: styles.settingTextarea
2942
+ }
2943
+ )
2944
+ ] }),
2945
+ /* @__PURE__ */ jsx("div", { style: styles.settingDivider }),
2946
+ /* @__PURE__ */ jsxs("div", { style: { ...styles.settingGroup, marginBottom: 0 }, children: [
2947
+ /* @__PURE__ */ jsx("label", { style: styles.settingLabel, children: "Plugins" }),
2948
+ /* @__PURE__ */ jsx("p", { style: styles.settingDescription, children: "Extend the AI with custom tools" }),
2949
+ plugins.length > 0 ? /* @__PURE__ */ jsx("div", { style: styles.pluginList, children: plugins.map((plugin) => /* @__PURE__ */ jsxs("div", { style: styles.pluginRow, children: [
2950
+ /* @__PURE__ */ jsxs("div", { style: styles.pluginInfo, children: [
2951
+ /* @__PURE__ */ jsx("span", { style: styles.pluginIcon, children: plugin.enabled ? "\u{1F50C}" : "\u26AA" }),
2952
+ /* @__PURE__ */ jsxs("div", { style: styles.pluginDetails, children: [
2953
+ /* @__PURE__ */ jsx("span", { style: styles.pluginName, children: plugin.name }),
2954
+ /* @__PURE__ */ jsxs("span", { style: styles.pluginMeta, children: [
2955
+ "v",
2956
+ plugin.version,
2957
+ " \u2022 ",
2958
+ plugin.tools?.length || 0,
2959
+ " tools"
2960
+ ] })
2961
+ ] })
2962
+ ] }),
2963
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: tokens.spacing.sm }, children: [
2964
+ /* @__PURE__ */ jsx(
2965
+ "div",
2966
+ {
2967
+ style: {
2968
+ ...styles.toggleSwitch,
2969
+ ...plugin.enabled ? styles.toggleSwitchActive : {}
2970
+ },
2971
+ onClick: () => plugin.enabled ? disablePlugin(plugin.name) : enablePlugin(plugin.name),
2972
+ children: /* @__PURE__ */ jsx("div", { style: {
2973
+ ...styles.toggleKnob,
2974
+ ...plugin.enabled ? styles.toggleKnobActive : {}
2975
+ } })
2976
+ }
2977
+ ),
2978
+ /* @__PURE__ */ jsx(
2979
+ "button",
2980
+ {
2981
+ type: "button",
2982
+ style: styles.uninstallBtn,
2983
+ onClick: () => unregisterPlugin(plugin.name),
2984
+ children: "Remove"
2985
+ }
2986
+ )
2987
+ ] })
2988
+ ] }, plugin.name)) }) : /* @__PURE__ */ jsx("div", { style: styles.pluginEmpty, children: "No plugins installed" }),
2989
+ availablePlugins.filter((p) => !plugins.some((installed) => installed.name === p.name)).length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
2990
+ /* @__PURE__ */ jsx("div", { style: styles.availablePluginsHeader, children: "Available" }),
2991
+ /* @__PURE__ */ jsx("div", { style: styles.pluginList, children: availablePlugins.filter((p) => !plugins.some((installed) => installed.name === p.name)).map((plugin) => /* @__PURE__ */ jsxs("div", { style: styles.pluginRow, children: [
2992
+ /* @__PURE__ */ jsxs("div", { style: styles.pluginInfo, children: [
2993
+ /* @__PURE__ */ jsx("span", { style: styles.pluginIcon, children: "\u{1F4E6}" }),
2994
+ /* @__PURE__ */ jsxs("div", { style: styles.pluginDetails, children: [
2995
+ /* @__PURE__ */ jsx("span", { style: styles.pluginName, children: plugin.name }),
2996
+ /* @__PURE__ */ jsx("span", { style: styles.pluginMeta, children: plugin.description })
2997
+ ] })
2998
+ ] }),
2999
+ /* @__PURE__ */ jsx(
3000
+ "button",
3001
+ {
3002
+ type: "button",
3003
+ style: styles.installBtn,
3004
+ onClick: () => registerPlugin(plugin),
3005
+ children: "+ Install"
3006
+ }
3007
+ )
3008
+ ] }, plugin.name)) })
3009
+ ] })
3010
+ ] })
3011
+ ] })
3012
+ ] }) }),
3013
+ /* @__PURE__ */ jsxs("div", { style: styles.messagesArea, children: [
3014
+ messages.length === 0 && /* @__PURE__ */ jsx("div", { style: styles.messagesEmpty, children: /* @__PURE__ */ jsx("p", { children: getPlaceholderMessage() }) }),
3015
+ /* @__PURE__ */ jsx("div", { style: styles.messagesContainer, children: messages.map((message) => /* @__PURE__ */ jsx(
3016
+ MessageBubble,
3017
+ {
3018
+ message,
3019
+ showDebug
3020
+ },
3021
+ message.id
3022
+ )) }),
3023
+ currentToolCalls.length > 0 && /* @__PURE__ */ jsx("div", { style: styles.toolCallsIndicator, children: currentToolCalls.map((tool) => /* @__PURE__ */ jsxs("span", { style: styles.toolCallBadge, children: [
3024
+ /* @__PURE__ */ jsx("span", { style: styles.toolCallDot }),
3025
+ tool.toolName
3026
+ ] }, tool.toolCallId)) }),
3027
+ /* @__PURE__ */ jsx("div", { ref: messagesEndRef })
3028
+ ] }),
3029
+ attachments.length > 0 && /* @__PURE__ */ jsx("div", { style: styles.attachmentsPreview, children: attachments.map((att, index) => /* @__PURE__ */ jsxs("div", { style: styles.attachmentItem, children: [
3030
+ /* @__PURE__ */ jsx("span", { style: styles.attachmentName, children: att.name }),
3031
+ /* @__PURE__ */ jsx(
3032
+ "button",
3033
+ {
3034
+ type: "button",
3035
+ onClick: () => removeAttachment(index),
3036
+ style: styles.attachmentRemove,
3037
+ children: "\xD7"
3038
+ }
3039
+ )
3040
+ ] }, index)) }),
3041
+ /* @__PURE__ */ jsxs("div", { style: styles.inputArea, children: [
3042
+ /* @__PURE__ */ jsxs("div", { style: styles.inputRow, children: [
3043
+ /* @__PURE__ */ jsxs("div", { style: styles.inputContainer, children: [
3044
+ /* @__PURE__ */ jsx(
3045
+ "button",
3046
+ {
3047
+ type: "button",
3048
+ onClick: () => fileInputRef.current?.click(),
3049
+ style: styles.attachBtn,
3050
+ title: "Attach file",
3051
+ children: /* @__PURE__ */ jsx(AttachIcon, {})
3052
+ }
3053
+ ),
3054
+ /* @__PURE__ */ jsx(
3055
+ "input",
3056
+ {
3057
+ ref: fileInputRef,
3058
+ type: "file",
3059
+ accept: "image/*",
3060
+ multiple: true,
3061
+ onChange: handleFileSelect,
3062
+ style: { display: "none" }
3063
+ }
3064
+ ),
3065
+ /* @__PURE__ */ jsx("div", { style: styles.inputWrapper, children: /* @__PURE__ */ jsx(
3066
+ "textarea",
3067
+ {
3068
+ value: inputValue,
3069
+ onChange: (e) => setInputValue(e.target.value),
3070
+ onKeyPress: handleKeyPress,
3071
+ placeholder,
3072
+ disabled: !canChat || isStreaming || isLoading,
3073
+ rows: 1,
3074
+ style: {
3075
+ ...styles.input,
3076
+ ...!canChat || isStreaming || isLoading ? styles.inputDisabled : {}
3077
+ }
3078
+ }
3079
+ ) })
3080
+ ] }),
3081
+ /* @__PURE__ */ jsx(
3082
+ "button",
3083
+ {
3084
+ type: "button",
3085
+ onClick: sendMessage,
3086
+ disabled: !canChat || !inputValue.trim() || isStreaming || isLoading,
3087
+ style: {
3088
+ ...styles.sendBtn,
3089
+ ...!canChat || !inputValue.trim() || isStreaming || isLoading ? styles.sendBtnDisabled : {}
3090
+ },
3091
+ children: isStreaming ? /* @__PURE__ */ jsx("span", { style: styles.sendSpinner }) : "Send"
3092
+ }
3093
+ )
3094
+ ] }),
3095
+ error2 && /* @__PURE__ */ jsx("div", { style: styles.errorBox, children: error2.message })
3096
+ ] })
3097
+ ] })
3098
+ ] });
3099
+ }
3100
+ function MessageBubble({ message, showDebug }) {
3101
+ const isUser = message.role === "user";
3102
+ const isSystem = message.role === "system";
3103
+ const containerStyle2 = {
3104
+ ...styles.messageBubbleContainer,
3105
+ ...isUser ? styles.messageBubbleUser : styles.messageBubbleAssistant
3106
+ };
3107
+ const bubbleStyle = {
3108
+ ...styles.messageBubble,
3109
+ ...isUser ? styles.messageBubbleUserStyle : isSystem ? styles.messageBubbleSystemStyle : styles.messageBubbleAssistantStyle
3110
+ };
3111
+ return /* @__PURE__ */ jsx("div", { style: containerStyle2, children: /* @__PURE__ */ jsxs("div", { style: bubbleStyle, children: [
3112
+ /* @__PURE__ */ jsxs("div", { style: styles.messageContent, children: [
3113
+ isUser || isSystem ? (
3114
+ // User and system messages: plain text
3115
+ message.content
3116
+ ) : (
3117
+ // Assistant messages: render markdown
3118
+ /* @__PURE__ */ jsx(MarkdownContent, { content: message.content })
3119
+ ),
3120
+ message.isStreaming && /* @__PURE__ */ jsx("span", { style: styles.streamingCursor })
3121
+ ] }),
3122
+ showDebug && message.toolCalls && message.toolCalls.length > 0 && /* @__PURE__ */ jsxs("div", { style: styles.toolCallsDebug, children: [
3123
+ /* @__PURE__ */ jsx("div", { style: styles.toolCallsDebugTitle, children: "Tool calls:" }),
3124
+ message.toolCalls.map((tool) => /* @__PURE__ */ jsxs("div", { style: styles.toolCallDebugItem, children: [
3125
+ /* @__PURE__ */ jsx("span", { style: styles.toolCallDebugName, children: tool.toolName }),
3126
+ tool.args && /* @__PURE__ */ jsx("pre", { style: styles.toolCallDebugArgs, children: JSON.stringify(tool.args, null, 2) })
3127
+ ] }, tool.toolCallId))
3128
+ ] })
3129
+ ] }) });
3130
+ }
3131
+ function SettingsIcon() {
3132
+ return /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: [
3133
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "3" }),
3134
+ /* @__PURE__ */ jsx("path", { d: "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" })
3135
+ ] });
3136
+ }
3137
+ function AttachIcon() {
3138
+ return /* @__PURE__ */ jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", children: /* @__PURE__ */ jsx("path", { d: "M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" }) });
3139
+ }
3140
+
3141
+ export { HustleChat, MarkdownContent };
3142
+ //# sourceMappingURL=index.js.map
3143
+ //# sourceMappingURL=index.js.map