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