agent-hustle-demo 1.0.1

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