@emblemvault/hustle-react 1.0.0

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