@decido/shell 1.0.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +31 -0
  2. package/package.json +17 -14
  3. package/.turbo/turbo-build.log +0 -13
  4. package/src/AgentPlayer.tsx +0 -105
  5. package/src/DecidoPlayer.tsx +0 -117
  6. package/src/bridge/BridgeAgent.ts +0 -443
  7. package/src/components/DecidoIcon.tsx +0 -56
  8. package/src/components/JsonTreeEditor.tsx +0 -117
  9. package/src/components/PanelSplitter.tsx +0 -71
  10. package/src/components/PluginErrorBoundary.tsx +0 -69
  11. package/src/components/SafeLiquidUI.tsx +0 -114
  12. package/src/components/TransientLayer.tsx +0 -92
  13. package/src/components/agent/AgentChat.tsx +0 -134
  14. package/src/components/chat-extensions/IntentCatalogPanel.tsx +0 -81
  15. package/src/components/chat-extensions/chatSlashCommands.ts +0 -101
  16. package/src/components/controls/CreatorInputBar.tsx +0 -144
  17. package/src/components/controls/OSToolbar.tsx +0 -90
  18. package/src/components/controls/TimelineTape.tsx +0 -43
  19. package/src/components/debug/ActionTimelineTab.tsx +0 -111
  20. package/src/components/debug/CSSInspectorTab.tsx +0 -436
  21. package/src/components/debug/ExportTab.tsx +0 -192
  22. package/src/components/debug/FlowHealthTab.tsx +0 -86
  23. package/src/components/debug/LogsTab.tsx +0 -110
  24. package/src/components/debug/MorphStackTab.tsx +0 -241
  25. package/src/components/debug/NetworkTab.tsx +0 -173
  26. package/src/components/debug/PerformanceTab.tsx +0 -171
  27. package/src/components/debug/ProfilesTab.tsx +0 -238
  28. package/src/components/debug/ReplayTab.tsx +0 -70
  29. package/src/components/debug/StoresTab.tsx +0 -255
  30. package/src/components/debug/TopologyTab.tsx +0 -59
  31. package/src/components/debug/debugConfig.tsx +0 -66
  32. package/src/components/playground/DebugPanel.tsx +0 -112
  33. package/src/components/playground/HeaderCenterControls.tsx +0 -92
  34. package/src/components/playground/KeyframeListItem.tsx +0 -70
  35. package/src/components/playground/PlaygroundAppSidebar.tsx +0 -171
  36. package/src/components/playground/PlaygroundBottomControls.tsx +0 -132
  37. package/src/components/playground/PlaygroundCanvas.tsx +0 -87
  38. package/src/components/playground/PlaygroundChat.tsx +0 -236
  39. package/src/components/playground/PlaygroundErrorBoundary.tsx +0 -63
  40. package/src/components/playground/PlaygroundFloatingInput.tsx +0 -352
  41. package/src/components/playground/PlaygroundHeader.tsx +0 -222
  42. package/src/components/playground/PlaygroundSidebar.tsx +0 -136
  43. package/src/components/playground/PlaygroundTerminal.tsx +0 -44
  44. package/src/components/playground/SuggestionCards.tsx +0 -29
  45. package/src/components/playground/demos/ClinicaAINode.tsx +0 -221
  46. package/src/components/playground/demos/FinanceAINode.tsx +0 -226
  47. package/src/components/playground/demos/KiaAcademyNode.tsx +0 -250
  48. package/src/components/playground/demos/KiaBotNode.tsx +0 -207
  49. package/src/components/playground/demos/KiaCampaignNode.tsx +0 -191
  50. package/src/components/playground/demos/KiaComplianceNode.tsx +0 -140
  51. package/src/components/playground/demos/KiaCustomerJourneyNode.tsx +0 -220
  52. package/src/components/playground/demos/KiaCyberNode.tsx +0 -203
  53. package/src/components/playground/demos/KiaDashboardNode.tsx +0 -399
  54. package/src/components/playground/demos/KiaEmbudoOverviewNode.tsx +0 -168
  55. package/src/components/playground/demos/KiaExecutiveNode.tsx +0 -169
  56. package/src/components/playground/demos/KiaGamificationNode.tsx +0 -229
  57. package/src/components/playground/demos/KiaIntelligenceHubNode.tsx +0 -165
  58. package/src/components/playground/demos/KiaInventoryNode.tsx +0 -183
  59. package/src/components/playground/demos/KiaLeadScoringNode.tsx +0 -226
  60. package/src/components/playground/demos/KiaLiveSimulationNode.tsx +0 -177
  61. package/src/components/playground/demos/KiaMultiDealerNode.tsx +0 -223
  62. package/src/components/playground/demos/KiaNPSVoiceNode.tsx +0 -214
  63. package/src/components/playground/demos/KiaOmnichannelNode.tsx +0 -162
  64. package/src/components/playground/demos/KiaPBIBudgetNode.tsx +0 -152
  65. package/src/components/playground/demos/KiaPBIConversionNode.tsx +0 -206
  66. package/src/components/playground/demos/KiaPBIFunnelNode.tsx +0 -184
  67. package/src/components/playground/demos/KiaPBIOwnershipNode.tsx +0 -113
  68. package/src/components/playground/demos/KiaPBIPartnerNode.tsx +0 -143
  69. package/src/components/playground/demos/KiaPBIPreciosNode.tsx +0 -120
  70. package/src/components/playground/demos/KiaPBIRuntNode.tsx +0 -205
  71. package/src/components/playground/demos/KiaPartnerScoreNode.tsx +0 -206
  72. package/src/components/playground/demos/KiaPredictiveNode.tsx +0 -226
  73. package/src/components/playground/demos/KiaShowroomNode.tsx +0 -194
  74. package/src/components/playground/demos/KiaStoreNode.tsx +0 -215
  75. package/src/components/playground/demos/KiaSustainabilityNode.tsx +0 -173
  76. package/src/components/playground/demos/KiaUsedVehiclesNode.tsx +0 -163
  77. package/src/components/playground/demos/KiaWorkshopNode.tsx +0 -221
  78. package/src/components/playground/demos/SmartCityNode.tsx +0 -205
  79. package/src/components/playground/demos/kia_campaign_manifest.json +0 -112
  80. package/src/components/playground/input-parts/AIModelSelector.tsx +0 -156
  81. package/src/components/playground/input-parts/InputActions.tsx +0 -80
  82. package/src/components/playground/input-parts/InputToolbar.tsx +0 -245
  83. package/src/components/playground/input-parts/ResourceLibraryPanel.tsx +0 -287
  84. package/src/components/playground/sidebarDsdIO.ts +0 -82
  85. package/src/components/settings/SettingsPanel.tsx +0 -267
  86. package/src/components/shell/AppHeader.tsx +0 -9
  87. package/src/components/shell/AppShell.tsx +0 -139
  88. package/src/components/shell/ArtifactBar.tsx +0 -97
  89. package/src/components/shell/BootScreen.tsx +0 -19
  90. package/src/components/shell/CenterComposite.tsx +0 -87
  91. package/src/components/shell/CodeEditorPanel.tsx +0 -88
  92. package/src/components/shell/GlobalOverlays.tsx +0 -228
  93. package/src/components/shell/LayoutConfigurator.tsx +0 -209
  94. package/src/components/shell/LayoutGrid.tsx +0 -178
  95. package/src/components/shell/MorphShell.tsx +0 -368
  96. package/src/components/shell/PluginViewer.tsx +0 -147
  97. package/src/components/shell/ShellNexusPreview.tsx +0 -458
  98. package/src/components/shell/SlotRenderer.tsx +0 -115
  99. package/src/components/shell/TabBar.tsx +0 -94
  100. package/src/components/shell/TemplateLibrary.tsx +0 -195
  101. package/src/components/shell/layoutConstants.ts +0 -35
  102. package/src/components/shell/morphStageMeta.ts +0 -15
  103. package/src/components/shell/shells/BuiltInShells.tsx +0 -443
  104. package/src/components/shell/shells/DatawayChatShell.tsx +0 -42
  105. package/src/components/shell/shells/TokenPreview.tsx +0 -339
  106. package/src/components/shell/shells/bootShells.ts +0 -31
  107. package/src/components/shells/CreatorShell.tsx +0 -37
  108. package/src/components/shells/DecidoShell.tsx +0 -447
  109. package/src/components/shells/ExperimentalChatShell.tsx +0 -245
  110. package/src/components/shells/UserCanvas.tsx +0 -44
  111. package/src/components/studio/BlueprintManagerPanel.tsx +0 -137
  112. package/src/components/studio/DependencyTreePanel.tsx +0 -192
  113. package/src/components/studio/NodePalette.tsx +0 -92
  114. package/src/components/studio/NodePropertiesPanel.tsx +0 -81
  115. package/src/components/studio/ReactFlowEditor.tsx +0 -242
  116. package/src/components/studio/TimelineEditor.tsx +0 -122
  117. package/src/components/studio/TimelineKeyframeCard.tsx +0 -99
  118. package/src/components/studio/VariablePanel.tsx +0 -181
  119. package/src/components/studio/blueprint/BlueprintCard.tsx +0 -82
  120. package/src/components/studio/editor/CanvasContextMenu.tsx +0 -107
  121. package/src/components/studio/editor/EditorToolbar.tsx +0 -80
  122. package/src/components/studio/editor/StageContentRenderer.tsx +0 -134
  123. package/src/components/studio/editor/TrackPropertyEditors.tsx +0 -133
  124. package/src/components/studio/editor/TreeNodeItem.tsx +0 -91
  125. package/src/components/studio/editor/edgeStyles.ts +0 -43
  126. package/src/components/studio/editor/editorKeyHandler.ts +0 -95
  127. package/src/components/studio/editor/nodeTypeRegistry.ts +0 -137
  128. package/src/components/studio/editor/paletteCatalog.tsx +0 -84
  129. package/src/components/studio/nodes/shell/InteractionNodes.tsx +0 -82
  130. package/src/components/studio/nodes/shell/LayoutControlNodes.tsx +0 -69
  131. package/src/components/studio/nodes/shell/RegisterActionNode.tsx +0 -20
  132. package/src/components/studio/nodes/shell/RegisterButtonNode.tsx +0 -22
  133. package/src/components/studio/nodes/shell/RegisterPanelNode.tsx +0 -19
  134. package/src/components/studio/nodes/shell/RegisterSidebarNode.tsx +0 -19
  135. package/src/components/studio/nodes/shell/RegisterStatusBarNode.tsx +0 -22
  136. package/src/components/studio/nodes/shell/RegisterTabNode.tsx +0 -21
  137. package/src/components/studio/nodes/shell/RegisterTopBarNode.tsx +0 -22
  138. package/src/components/studio/nodes/shell/ShellConfigNode.tsx +0 -51
  139. package/src/components/studio/nodes/shell/ShellNodeBase.tsx +0 -100
  140. package/src/components/studio/nodes/shell/ThemeNodes.tsx +0 -51
  141. package/src/components/studio/nodes/shell/index.ts +0 -12
  142. package/src/components/widgets/BroadcastWidget.tsx +0 -93
  143. package/src/components/widgets/MarketplaceWidget.tsx +0 -298
  144. package/src/components/widgets/McpToolsWidget.tsx +0 -231
  145. package/src/components/widgets/OpsDashboard.tsx +0 -59
  146. package/src/components/widgets/QuickActionsWidget.tsx +0 -60
  147. package/src/components/widgets/UsageWidget.tsx +0 -112
  148. package/src/components/widgets/WidgetRenderer.tsx +0 -892
  149. package/src/components/widgets/WidgetSlotPanel.tsx +0 -213
  150. package/src/config/IconRegistry.ts +0 -126
  151. package/src/contexts/NetworkProvider.tsx +0 -162
  152. package/src/core/AIDirector.ts +0 -71
  153. package/src/core/EventBus.ts +0 -37
  154. package/src/core/PluginContext.tsx +0 -141
  155. package/src/hooks/listeners/useUIStateListener.ts +0 -59
  156. package/src/hooks/listeners/useWhatsAppListener.ts +0 -110
  157. package/src/hooks/morphBridge.ts +0 -82
  158. package/src/hooks/useAIModelSelector.ts +0 -144
  159. package/src/hooks/useAgentStream.ts +0 -220
  160. package/src/hooks/useAutoUpdater.ts +0 -89
  161. package/src/hooks/useBootSequence.ts +0 -20
  162. package/src/hooks/useExportDSD.ts +0 -53
  163. package/src/hooks/useFullscreen.ts +0 -35
  164. package/src/hooks/useGeminiStream.ts +0 -282
  165. package/src/hooks/useIntentLens.ts +0 -224
  166. package/src/hooks/useKeyboardShortcuts.ts +0 -69
  167. package/src/hooks/useLoggerBridge.ts +0 -32
  168. package/src/hooks/useMcpClient.ts +0 -112
  169. package/src/hooks/useNexusaiDeploy.ts +0 -118
  170. package/src/hooks/usePlaybackEngine.ts +0 -21
  171. package/src/hooks/usePlaygroundCommander.ts +0 -475
  172. package/src/hooks/usePluginEngine.ts +0 -165
  173. package/src/hooks/useScreenRecorder.ts +0 -73
  174. package/src/hooks/useShellKeyboard.ts +0 -40
  175. package/src/hooks/useShellShortcuts.ts +0 -118
  176. package/src/hooks/useSoundEffects.ts +0 -35
  177. package/src/hooks/useStudioConfig.ts +0 -72
  178. package/src/hooks/useSystemBoot.ts +0 -84
  179. package/src/hooks/useSystemTelemetry.ts +0 -62
  180. package/src/lib/debugLogger.ts +0 -80
  181. package/src/lib/networkInterceptor.ts +0 -100
  182. package/src/mocks/decido.tsx +0 -41
  183. package/src/plugins/pluginAPI.ts +0 -190
  184. package/src/store/McpStore.ts +0 -69
  185. package/src/store/UpdaterStore.ts +0 -60
  186. package/src/store/engine.ts +0 -392
  187. package/src/store/index.ts +0 -4
  188. package/src/store/layoutPresets.ts +0 -66
  189. package/src/store/playgroundTypes.ts +0 -98
  190. package/src/store/useActionTimelineStore.ts +0 -48
  191. package/src/store/useDebugPanelStore.ts +0 -98
  192. package/src/store/useDebugProfileStore.ts +0 -130
  193. package/src/store/useLayoutStore.ts +0 -205
  194. package/src/store/useMorphInstanceStore.ts +0 -289
  195. package/src/store/useMorphologyStore.ts +0 -103
  196. package/src/store/usePlaygroundStore.ts +0 -236
  197. package/src/store/useShellRegistry.ts +0 -123
  198. package/src/store/useSuggestionsStore.ts +0 -57
  199. package/src/store/useThemeStore.ts +0 -399
  200. package/src/store/useUIComponentStore.ts +0 -179
  201. package/src/types/DecidoStoryDefinition.ts +0 -43
  202. package/src/utils/ai/ai-architect.ts +0 -92
  203. package/src/utils/ai/ai-code.ts +0 -187
  204. package/src/utils/ai/ai-core.ts +0 -50
  205. package/src/utils/ai/ai-media.ts +0 -292
  206. package/src/utils/layoutGraph.ts +0 -67
  207. package/tsconfig.json +0 -17
  208. package/tsconfig.tsbuildinfo +0 -1
@@ -1,475 +0,0 @@
1
- import { useCallback, useEffect } from 'react';
2
- import { usePlaygroundStore } from '../store/usePlaygroundStore';
3
- import { useTimelineStore } from '@decido/engine';
4
- import { useEngineStore } from '@decido/engine';
5
- import { useUIComponentStore } from '../store/useUIComponentStore';
6
- import { useReactiveEngine } from '@decido/engine';
7
- import { useAIDirector } from '@decido/engine';
8
- import { useNetwork } from '../contexts/NetworkProvider';
9
- import { AudioController } from '@decido/engine';
10
- import { bridgeToMorph } from './morphBridge';
11
- import { useMorphInstanceStore } from '../store/useMorphInstanceStore';
12
- import { dlog } from '../lib/debugLogger';
13
-
14
- export const usePlaygroundCommander = (aiProvider: any) => {
15
- const prototypeBrand = usePlaygroundStore((state: any) => state.prototypeBrand);
16
- const setInputValue = usePlaygroundStore((state: any) => state.setInputValue);
17
- const addLog = usePlaygroundStore((state: any) => state.addLog);
18
- const addChatMessage = usePlaygroundStore((state: any) => state.addChatMessage);
19
-
20
- const timelines = useTimelineStore((state: any) => state.timelines);
21
-
22
- // AI Tools
23
- const { semanticMatch, isThinking } = useReactiveEngine(aiProvider);
24
- const { generateKeyframeOnTheFly, generateTimeline, isGenerating } = useAIDirector(aiProvider);
25
- const { emitEvent, isConnected } = useNetwork();
26
-
27
- const currentBlueprint = timelines[prototypeBrand];
28
- const lastEvent = useEngineStore((state: any) => state.lastEvent);
29
-
30
- useEffect(() => {
31
- const handleRenderPreview = (e: any) => {
32
- const html = e.detail?.html;
33
- if (html) {
34
- const instanceId = `web-${Date.now()}`;
35
- bridgeToMorph({
36
- chatId: instanceId,
37
- shellType: 'nexusai-preview',
38
- label: 'Reporte en Vivo',
39
- data: { html, css: '', javascript: '' },
40
- });
41
- usePlaygroundStore.getState().setIsSidebarOpen(false);
42
- }
43
- };
44
-
45
- const handleSearchOrder = (e: any) => {
46
- const query = e.detail?.query;
47
- if (query) {
48
- usePlaygroundStore.getState().setIsSidebarOpen(false);
49
- }
50
- };
51
-
52
- window.addEventListener('studio:render-preview', handleRenderPreview);
53
- window.addEventListener('studio:search-order', handleSearchOrder);
54
-
55
- return () => {
56
- window.removeEventListener('studio:render-preview', handleRenderPreview);
57
- window.removeEventListener('studio:search-order', handleSearchOrder);
58
- };
59
- }, []);
60
-
61
- // EL NUEVO JUMP: Ahora le pide permiso al Motor en lugar de hackear el estado
62
- const jumpToNode = useCallback((nodeId: string) => {
63
- if (!currentBlueprint) return;
64
- const targetNode = currentBlueprint.keyframes.find((kf: any) => kf.id === nodeId);
65
- if (targetNode) {
66
- addLog(`Reaccionando a Nodo: ${targetNode.state || targetNode.id}`, 'system');
67
-
68
- // En lugar de mutar directamente, DISPARAMOS UN EVENTO DE SISTEMA.
69
- // Para forzar la transición a este nodo específico, pasamos targetNodeId.
70
- useEngineStore.getState().dispatchEvent({
71
- type: 'USER_INTENT_MATCHED',
72
- targetNodeId: nodeId,
73
- routeHandle: 'success'
74
- });
75
- }
76
- }, [currentBlueprint, addLog]);
77
-
78
- const handleUserCommand = useCallback(async (input: string) => {
79
- if (!input || !input.trim()) return;
80
-
81
- // Phase 24.2: Abortar TTS activo si el usuario interrumpe
82
- addLog(`Analizando intención: "${input}"`, 'system');
83
- AudioController.stop();
84
-
85
- // El usuario real escribe en el chat
86
- addChatMessage({ type: 'text', sender: 'user', text: input });
87
-
88
- // ─── Sprint AC: Web Preview interceptor with iterative context ───
89
- // When 'nexusai-preview' is the selected shell, bypass intent router
90
- // and generate HTML/CSS/JS directly with Gemini.
91
- // If there's existing HTML in the active instance, send it as context
92
- // for iterative refinement (e.g. "change header color to red").
93
- const selectedShell = localStorage.getItem('decido_selected_shell');
94
- if (selectedShell === 'nexusai-preview' || selectedShell === 'iframe') {
95
- addLog('🌐 Web Preview mode — generando HTML directo...', 'system');
96
- addChatMessage({ type: 'text', sender: 'system', text: '🌐 Generando diseño web...' });
97
-
98
- const apiKey = localStorage.getItem('google_gemini_api_key')
99
- || (window as any).__DECIDO__?._apiKey
100
- || (import.meta as any).env?.VITE_GEMINI_API_KEY || '';
101
- const model = localStorage.getItem('decido_gemini_model') || 'gemini-3-flash-preview';
102
-
103
- if (!apiKey) {
104
- addChatMessage({ type: 'error', sender: 'system', text: '⚠️ No se encontró API key de Gemini.' });
105
- return;
106
- }
107
-
108
- // Sprint AC: Check for existing code in active MorphInstance
109
- const activeInst = useMorphInstanceStore.getState().getActiveInstance();
110
- const existingHtml = activeInst?.data?.html || '';
111
- const existingCss = activeInst?.data?.css || '';
112
- const existingJs = activeInst?.data?.javascript || '';
113
- const hasContext = !!(existingHtml.trim());
114
-
115
- // Sprint AH: Check if user selected a specific element
116
- const selectedSelector = (window as any).__DECIDO__?.selectedElementSelector || null;
117
- const elementContext = selectedSelector
118
- ? `\n\nIMPORTANT: The user has SELECTED a specific element: \`${selectedSelector}\`. Focus your changes ONLY on this element and its children. Do not modify other parts of the page.`
119
- : '';
120
-
121
- const systemPrompt = hasContext
122
- ? `You are an expert web developer. The user has an EXISTING web page and wants to MODIFY it.${elementContext}
123
-
124
- CURRENT HTML:
125
- \`\`\`html
126
- ${existingHtml}
127
- \`\`\`
128
-
129
- CURRENT CSS:
130
- \`\`\`css
131
- ${existingCss}
132
- \`\`\`
133
-
134
- CURRENT JavaScript:
135
- \`\`\`javascript
136
- ${existingJs}
137
- \`\`\`
138
-
139
- Apply the user's requested changes to the EXISTING code above. Keep everything else intact.
140
- IMPORTANT: DO NOT USE JSON. Instead, strictly format your response using these XML-like tags:
141
- <decido-html>
142
- <!-- your html here without <html> or <body> tags -->
143
- </decido-html>
144
- <decido-css>
145
- /* your tailwind/custom css here */
146
- </decido-css>
147
- <decido-js>
148
- // your javascript here
149
- </decido-js>
150
- Use Tailwind CSS classes. Do not include explanatory text outside the tags.`
151
- : `You are an expert web developer. Generate HTML, CSS, and JavaScript for the user's request.
152
- IMPORTANT: DO NOT USE JSON. Instead, strictly format your response using these XML-like tags:
153
- <decido-html>
154
- <!-- your html here without <html> or <body> tags -->
155
- </decido-html>
156
- <decido-css>
157
- /* your tailwind/custom css here */
158
- </decido-css>
159
- <decido-js>
160
- // your javascript here
161
- </decido-js>
162
- Use Tailwind CSS classes for styling (it will be auto-loaded). Write modern, responsive, visually stunning code.
163
- Use vibrant gradients, dark backgrounds (#0a0a0a, #1a1a2e), neon accent colors, smooth animations, and premium typography.
164
- Do not include any explanatory text outside the tags.`;
165
-
166
- try {
167
- // Sprint AI: Build multi-turn conversation history for Gemini
168
- const chatId = usePlaygroundStore.getState().activeChatId || '_default';
169
- const allMessages = usePlaygroundStore.getState().chatMessagesByInstance[chatId] || [];
170
- // Take last 10 relevant messages (user + agent text only, skip system/error/ui-artifact)
171
- const recentMsgs = allMessages
172
- .filter(m => (m.sender === 'user' || m.sender === 'agent') && m.type === 'text' && m.text?.trim())
173
- .slice(-10);
174
-
175
- // Build Gemini contents[] — alternate user/model roles
176
- const contents: Array<{ role: string; parts: Array<{ text: string }> }> = [];
177
- for (const m of recentMsgs) {
178
- const role = m.sender === 'user' ? 'user' : 'model';
179
- // Gemini requires alternating roles — merge consecutive same-role
180
- if (contents.length > 0 && contents[contents.length - 1].role === role) {
181
- contents[contents.length - 1].parts[0].text += '\n' + (m.text || '');
182
- } else {
183
- contents.push({ role, parts: [{ text: m.text || '' }] });
184
- }
185
- }
186
- // Ensure last message is the current user input (it was already added to chat above)
187
- // If last content is already user role with our input, keep it. Otherwise add.
188
- if (contents.length === 0 || contents[contents.length - 1].role !== 'user') {
189
- contents.push({ role: 'user', parts: [{ text: input }] });
190
- }
191
-
192
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
193
- dlog.gemini(`POST ${model} | ${contents.length} turns | prompt: ${systemPrompt.length} chars`, { model, turnsCount: contents.length });
194
- const _t0 = performance.now();
195
- const res = await fetch(url, {
196
- method: 'POST',
197
- headers: { 'Content-Type': 'application/json' },
198
- body: JSON.stringify({
199
- contents,
200
- systemInstruction: { parts: [{ text: systemPrompt }] },
201
- generationConfig: { temperature: 0.7, maxOutputTokens: 16384 },
202
- }),
203
- });
204
- const _dur = Math.round(performance.now() - _t0);
205
-
206
- const data = await res.json();
207
- const rawText = data?.candidates?.[0]?.content?.parts?.[0]?.text || '';
208
- const tokenCount = data?.usageMetadata?.totalTokenCount || 0;
209
- dlog.gemini(`Response ${res.status} | ${_dur}ms | ${tokenCount} tokens | ${rawText.length} chars`, { status: res.status, duration: _dur, tokens: tokenCount });
210
- let code = { html: '', css: '', javascript: '' };
211
-
212
- // 1. Primary parsing Strategy: Extract XML tags
213
- const htmlMatch = /<decido-html>([\s\S]*?)<\/decido-html>/i.exec(rawText);
214
- const cssMatch = /<decido-css>([\s\S]*?)<\/decido-css>/i.exec(rawText);
215
- const jsMatch = /<decido-js>([\s\S]*?)<\/decido-js>/i.exec(rawText);
216
-
217
- if (htmlMatch || cssMatch || jsMatch) {
218
- code.html = htmlMatch ? htmlMatch[1].trim() : '';
219
- code.css = cssMatch ? cssMatch[1].trim() : '';
220
- code.javascript = jsMatch ? jsMatch[1].trim() : '';
221
- } else {
222
- // 2. Fallback parsing Strategy: Old JSON method
223
- let jsonText = rawText.trim();
224
- const jsonMatch = /```(?:json)?\s*([\s\S]*?)```/i.exec(rawText);
225
- if (jsonMatch) {
226
- jsonText = jsonMatch[1].trim();
227
- } else {
228
- jsonText = jsonText.replace(/^```json\s*/i, '').replace(/\s*```$/i, '').trim();
229
- }
230
- try {
231
- code = JSON.parse(jsonText);
232
- } catch (e: any) {
233
- console.error("Web Preview Parse Error:", e, rawText);
234
- code.html = `
235
- <div class="fixed inset-0 flex flex-col items-center justify-center bg-gray-900 text-white p-6 text-center font-sans z-[9999]">
236
- <div class="bg-red-500/10 border border-red-500 text-red-400 p-4 rounded-xl max-w-lg shadow-2xl">
237
- <h3 class="font-bold text-lg mb-2">Error de Generación AI</h3>
238
- <p class="text-sm opacity-80 mb-4">El modelo generó código que no cumple con el formato XML o JSON estricto.</p>
239
- <div class="text-xs text-left bg-black/50 p-2 rounded overflow-auto max-h-48 text-gray-300">
240
- ${e.message}
241
- </div>
242
- </div>
243
- </div>`;
244
- }
245
- }
246
-
247
- // Sprint AC: Reuse active instance if refining, else create new
248
- let instanceId: string;
249
- if (hasContext && activeInst) {
250
- instanceId = activeInst.id;
251
- // Update existing instance data in-place
252
- useMorphInstanceStore.getState().upsertInstance({
253
- id: instanceId,
254
- sourceChatId: activeInst.sourceChatId,
255
- shellType: 'nexusai-preview',
256
- label: activeInst.label,
257
- data: { html: code.html, css: code.css, javascript: code.javascript },
258
- });
259
- } else {
260
- instanceId = `web-${Date.now()}`;
261
- bridgeToMorph({
262
- chatId: instanceId,
263
- shellType: 'nexusai-preview',
264
- label: input.slice(0, 40),
265
- data: { html: code.html, css: code.css, javascript: code.javascript },
266
- });
267
- }
268
-
269
- const verb = hasContext ? '🔄 Diseño actualizado' : '✅ Diseño web generado';
270
- addChatMessage({ type: 'text', sender: 'agent', text: `${verb}. Revisa el panel derecho.`, morphInstanceId: instanceId });
271
- addLog(`🌐 HTML ${hasContext ? 'actualizado' : 'generado'} en Web Preview`, 'success');
272
- } catch (err: any) {
273
- dlog.gemini(`ERROR: ${err.message}`, { error: err.message }, 'error');
274
- addChatMessage({ type: 'error', sender: 'system', text: `Error generando HTML: ${err.message}` });
275
- }
276
- return;
277
- } else if (selectedShell === 'dataway-studio') {
278
- addLog('Dataway Studio — generando M-Script...', 'system');
279
-
280
- const activeResource = localStorage.getItem('dataway_active_resource');
281
- const activeConnector = localStorage.getItem('dataway_active_connector') || 'google_sheets';
282
-
283
- if (!activeResource) {
284
- addChatMessage({ type: 'error', sender: 'system', text: 'Debes seleccionar una tabla en el panel Recursos de Dataway primero.' });
285
- return;
286
- }
287
-
288
- const loadingId = `loading-${Date.now()}`;
289
- addChatMessage({ id: loadingId, type: 'text', sender: 'system', text: 'Analizando esquema y generando M-Script...' });
290
-
291
- try {
292
- const baseUrl = (import.meta as any).env?.VITE_API_BASE_URL || 'http://localhost:3001';
293
- const res = await fetch(`${baseUrl}/api/dataway/copilot`, {
294
- method: 'POST',
295
- headers: { 'Content-Type': 'application/json' },
296
- body: JSON.stringify({
297
- prompt: input,
298
- connectorId: activeConnector,
299
- resource: activeResource
300
- })
301
- });
302
-
303
- if (!res.ok) {
304
- const errData = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
305
- throw new Error(errData.error || `Error del servidor HTTP ${res.status}`);
306
- }
307
-
308
- const data = await res.json();
309
-
310
- if (data.script) {
311
- const explanationText = data.explanation ? `**Análisis de la IA:** ${data.explanation}\n\n` : '';
312
- addChatMessage({
313
- type: 'text',
314
- sender: 'agent',
315
- text: `${explanationText}Pipeline actualizado. Revisa el resultado:\n\n\`\`\`dataway\n${data.script}\n\`\`\``
316
- });
317
-
318
- // Dispatch directly to the active Dataway Studio View without opening new tabs
319
- window.dispatchEvent(new CustomEvent('intent:dataway-generate-script', { detail: {
320
- script: data.script,
321
- resource: data.targetResource
322
- } }));
323
- } else {
324
- addChatMessage({ type: 'error', sender: 'system', text: 'El agente no retornó código.' });
325
- }
326
- } catch (err: any) {
327
- addChatMessage({ type: 'error', sender: 'system', text: `Error de IA: ${err.message}` });
328
- }
329
- return;
330
- }
331
-
332
- if (!currentBlueprint) {
333
- addLog(`No hay blueprint activo para evaluar.`, 'error');
334
- return;
335
- }
336
-
337
- // 1. Check if intent detection is enabled (Brain toggle)
338
- const intentEnabled = (typeof window !== 'undefined' && (window as any).__DECIDO__?.intentEnabled !== false);
339
-
340
- // 2. Heurística primaria para Generación Compleja (Bypasses Router) — only when intents ON
341
- const isEditRequest = intentEnabled && /agrega|suma|añade|conecta|modifica|cambia|elimina|borra|parchea|actualiza|inserta|mueve/i.test(input);
342
- const isCreateRequest = intentEnabled && /grafo|flujo|nodos|complejo|historia|blueprint|escenario|onboarding|proceso|workflow|pipeline|crea\s+(un|una|el|la|los|las)\s|diseña|genera\s+(un|una)|construye|orquest|trigger|subflujo|set\s+variable|marque\s+user\.|shell|tema|theme|sidebar|panel|activity\s*bar|status\s*bar|top\s*bar|notificaci[oó]n|shortcut|atajo|layout|configura\s+(el|la|los|las)\s/i.test(input);
343
-
344
- if (isCreateRequest || isEditRequest) {
345
- addLog(`Intención compleja detectada. ${isEditRequest ? 'Editando Grafo...' : 'Construyendo Nuevo Grafo...'}`, 'system');
346
-
347
- // Si es edit, se pasa isEditRequest=true y currentBlueprint para que procese el diff
348
- const result = await generateTimeline(input, prototypeBrand as any, 15, isEditRequest, currentBlueprint);
349
-
350
- if (result === true) {
351
- // Edit mode exitoso (Devuelve true porque el estado se parchó in-place)
352
- addChatMessage({ type: 'text', sender: 'system', text: `Se ha modificado el grafo contextualmente según tus instrucciones.` });
353
- } else if (result && result.keyframes && result.keyframes.length > 0) {
354
- // Modo Creación: Saltamos al primer nodo del nuevo grafo
355
- jumpToNode(result.keyframes[0].id);
356
- addChatMessage({ type: 'text', sender: 'system', text: `Se ha creado un nuevo grafo.` });
357
- } else {
358
- addLog(`Fallo al generar el Blueprint con IA.`, 'error');
359
- }
360
- return; // Detenemos aquí
361
- }
362
-
363
- // 3. Semantic Match para enrutamiento (Navegación, UI Actions, MCPs) — only when intents ON
364
- const matchResult = intentEnabled ? await semanticMatch(input, currentBlueprint) : null;
365
-
366
- if (matchResult && matchResult !== "GENERATE" && typeof matchResult === "string") {
367
- // Hizo match con un nodo existente localmente
368
- jumpToNode(matchResult);
369
-
370
- } else if (matchResult && typeof matchResult === "object" && matchResult.intent === "UI_ACTION") {
371
- addLog(`🎨 UI_ACTION detectada. Montando artefacto: ${matchResult.artifact}`, 'system');
372
-
373
- // 1. Guardamos el payload que envió Gemini en el Store Global
374
- usePlaygroundStore.getState().setActiveArtifactData({
375
- artifact: matchResult.artifact,
376
- ...matchResult.payload
377
- });
378
-
379
- // 2. Bridge → MorphInstance (auto-abre canvas)
380
- const uiInstanceId = `ui-${matchResult.artifact}-${Date.now()}`;
381
- bridgeToMorph({
382
- chatId: uiInstanceId,
383
- shellType: 'nexusai-preview',
384
- label: matchResult.artifact || 'Visualización',
385
- data: { artifact: matchResult.artifact, ...matchResult.payload }
386
- });
387
-
388
- addChatMessage({ type: 'text', sender: 'agent', text: "He preparado la visualización solicitada en el panel derecho.", morphInstanceId: uiInstanceId });
389
-
390
- } else if (matchResult && typeof matchResult === "object" && matchResult.intent === "MCP_ACTION") {
391
- addLog(`Manejando intención MCP_ACTION: ${matchResult.tool}`, 'system');
392
-
393
- useEngineStore.getState().dispatchEvent({
394
- type: 'MCP_EXECUTION_REQUESTED',
395
- payload: { tool: matchResult.tool, parameters: matchResult.parameters }
396
- });
397
-
398
- addChatMessage({ type: 'text', sender: 'system', text: `Ejecutando herramienta externa: ${matchResult.tool}` });
399
-
400
- } else if (matchResult && typeof matchResult === "object" && matchResult.intent === "UI_COMPONENT") {
401
- addLog(`🎨 UI_COMPONENT generado por IA: ${matchResult.name}`, 'system');
402
-
403
- // 1. Save to UI Component Store
404
- const componentId = `ai_${Date.now()}`;
405
- useUIComponentStore.getState().addComponent({
406
- id: componentId,
407
- name: matchResult.name || 'AI Component',
408
- category: matchResult.category || 'custom',
409
- schema: matchResult.schema,
410
- dataContract: { inputs: {}, outputs: {} },
411
- tags: matchResult.tags || ['ai-generated'],
412
- source: 'ai-generated',
413
- createdAt: Date.now(),
414
- updatedAt: Date.now()
415
- });
416
-
417
- // 2. Bridge → MorphInstance with artifact
418
- bridgeToMorph({
419
- chatId: `comp-${componentId}`,
420
- shellType: 'nexusai-preview',
421
- label: matchResult.name || 'AI Component',
422
- data: { html: matchResult.schema, schema: matchResult.schema },
423
- artifact: {
424
- id: componentId,
425
- name: matchResult.name || 'AI Component',
426
- data: { html: matchResult.schema, schema: matchResult.schema }
427
- }
428
- });
429
-
430
- // 3. Render it immediately in chat via SafeLiquidUI
431
- addChatMessage({
432
- type: 'ui-artifact',
433
- sender: 'agent',
434
- text: `🎨 ${matchResult.name}`,
435
- actorId: 'system',
436
- uiSchema: JSON.stringify(matchResult.schema),
437
- morphInstanceId: `comp-${componentId}`
438
- });
439
-
440
- addChatMessage({ type: 'text', sender: 'system', text: `Componente "${matchResult.name}" guardado en la biblioteca UI. Accede con /ui.`, morphInstanceId: `comp-${componentId}` });
441
-
442
- } else {
443
- // 3. Fallback: On the Fly Generation para un solo keyframe
444
- addLog(`Intención reactiva detectada. Inventando nodo en vivo...`, 'system');
445
- const newKf = await generateKeyframeOnTheFly(input, prototypeBrand as any, currentBlueprint);
446
- if (newKf) {
447
- jumpToNode(newKf.id);
448
- } else {
449
- addLog(`Fallo al generar morfología reactiva.`, 'error');
450
- }
451
- }
452
- }, [currentBlueprint, prototypeBrand, semanticMatch, generateKeyframeOnTheFly, generateTimeline, jumpToNode, addLog, addChatMessage, emitEvent, isConnected]);
453
-
454
- const handleGeneratePlayground = useCallback(async (eOrOverride?: React.FormEvent | string) => {
455
- let promptOverride = typeof eOrOverride === 'string' ? eOrOverride : undefined;
456
- if (eOrOverride && typeof (eOrOverride as React.FormEvent).preventDefault === 'function') {
457
- (eOrOverride as React.FormEvent).preventDefault();
458
- }
459
-
460
- let currentInput = usePlaygroundStore.getState().inputValue;
461
- const promptToUse = promptOverride || currentInput;
462
-
463
- if (!promptToUse || typeof promptToUse !== 'string' || !promptToUse.trim()) return;
464
-
465
- await handleUserCommand(promptToUse);
466
- setInputValue("");
467
-
468
- }, [handleUserCommand, setInputValue]);
469
-
470
- return {
471
- handleUserCommand,
472
- handleGeneratePlayground,
473
- isGenerating: isGenerating || isThinking
474
- };
475
- };
@@ -1,165 +0,0 @@
1
- import { useEffect } from 'react';
2
- import { ed25519 } from '@noble/curves/ed25519.js';
3
- import type { PluginRegistryEntry } from '@decido/plugin-engine';
4
-
5
- export interface UsePluginEngineOptions {
6
- // 1. Module Federation Hooks
7
- setRemote: (name: string, config: any) => void;
8
- getRemote: (name: string, module: string) => Promise<any>;
9
-
10
- // 2. Data
11
- registry: PluginRegistryEntry[];
12
- publicKeyB64?: string; // Optional, overrides the default Decido public key
13
-
14
- // 3. Lifecycle Callbacks
15
- onPluginLoaded: (manifest: any, name: string) => void;
16
- onMCPServerDiscovered?: (serverConfig: any) => void;
17
- onSecurityAlert?: (pluginName: string, reason: string) => void;
18
- /** Called when a plugin registers sidebar menu items */
19
- onSidebarItemsRegistered?: (pluginId: string, items: any[]) => void;
20
- }
21
-
22
- export const usePluginEngine = ({
23
- setRemote,
24
- getRemote,
25
- registry,
26
- publicKeyB64,
27
- onPluginLoaded,
28
- onMCPServerDiscovered,
29
- onSecurityAlert,
30
- onSidebarItemsRegistered
31
- }: UsePluginEngineOptions) => {
32
- useEffect(() => {
33
- const loadDynamicPlugin = async (remoteName: string, url: string, exposedModule: string, expectedSignature?: string) => {
34
- try {
35
- if (expectedSignature && expectedSignature !== 'offline_or_invalid_signature') {
36
- console.info(`🔒 [Security] Verifying Cryptographic Signature for ${remoteName}...`);
37
- try {
38
- const response = await fetch(url);
39
- if (!response.ok) throw new Error("Could not fetch remote bundle for verification");
40
- const scriptText = await response.text();
41
-
42
- if (!publicKeyB64) {
43
- console.error(`🚨 [Security Breach] No public key provided to verify ${remoteName}. Halting execution.`);
44
- if (onSecurityAlert) onSecurityAlert(remoteName, "El host no proveyó una llave pública para verificar la firma criptográfica.");
45
- return;
46
- }
47
-
48
- const pubKeyBuf = Uint8Array.from(atob(publicKeyB64), c => c.charCodeAt(0)).slice(12);
49
- const sigBuf = Uint8Array.from(atob(expectedSignature), c => c.charCodeAt(0));
50
- const msgBuf = new TextEncoder().encode(scriptText);
51
-
52
- const isValid = ed25519.verify(sigBuf, msgBuf, pubKeyBuf);
53
- if (!isValid) {
54
- console.error(`🚨 [Security Breach] Invalid signature for ${remoteName}. Halting execution.`);
55
- if (onSecurityAlert) onSecurityAlert(remoteName, "El plugin ha sido modificado en tránsito o no tiene firma válida.");
56
- return;
57
- }
58
- console.info(`✅ [Security] Signature verified for ${remoteName}. Secure to execute.`);
59
- } catch (secErr) {
60
- console.error(`🚨 [Security] Failed to verify signature for ${remoteName}:`, secErr);
61
- if (onSecurityAlert) onSecurityAlert(remoteName, "Fallo al verificar firma criptográfica.");
62
- return;
63
- }
64
- } else {
65
- console.debug(`[Security] Loaded ${remoteName} without a cryptographic signature (Local Dev Mode).`);
66
- }
67
-
68
- setRemote(remoteName, {
69
- url: () => Promise.resolve(`${url}?t=${Date.now()}`),
70
- format: 'esm',
71
- from: 'vite'
72
- });
73
-
74
- const extractRemote = async (factory: any): Promise<any> => {
75
- const r = factory && typeof factory === 'object' && 'default' in factory
76
- ? factory.default
77
- : factory;
78
- return r;
79
- };
80
-
81
- const setupCortex = (manifest: any, name: string) => {
82
- if (manifest && manifest.widgets) {
83
- console.info(`🔥 [Federation Marketplace] Registering Cortex: ${name} with ${manifest.widgets.length} widgets`);
84
-
85
- manifest.widgets = manifest.widgets.map((w: any) => {
86
- let actualComponent = w.component;
87
- if (actualComponent && typeof actualComponent === 'object' && !actualComponent.$$typeof) {
88
- try {
89
- const keys = Object.keys(actualComponent);
90
- if (keys.length > 0 && typeof actualComponent[keys[0]] === 'function') {
91
- actualComponent = actualComponent[keys[0]];
92
- } else if (actualComponent.default) {
93
- actualComponent = actualComponent.default;
94
- }
95
- } catch (e) {
96
- console.warn(`[Federation Marketplace] TDZ / Getter Exception unpacking component for ${w.name}:`, e);
97
- }
98
- }
99
- return { ...w, component: actualComponent };
100
- });
101
-
102
- onPluginLoaded(manifest, name);
103
-
104
- if (manifest.mcp_servers && Array.isArray(manifest.mcp_servers)) {
105
- console.info(`🔌 [Dynamic MCP] Discovered ${manifest.mcp_servers.length} MCP Servers in ${name}.`);
106
- if (onMCPServerDiscovered) {
107
- manifest.mcp_servers.forEach((server: any) => {
108
- onMCPServerDiscovered(server);
109
- });
110
- }
111
- }
112
-
113
- // Process sidebar items
114
- if (manifest.sidebarItems && Array.isArray(manifest.sidebarItems) && onSidebarItemsRegistered) {
115
- console.info(`📌 [Sidebar] ${name} registered ${manifest.sidebarItems.length} sidebar items`);
116
- onSidebarItemsRegistered(manifest.id || name, manifest.sidebarItems);
117
- }
118
- } else {
119
- console.warn(`⚠️ [Federation Marketplace] Manifest ${name} is invalid or has no widgets`, manifest);
120
- }
121
- };
122
-
123
- const attemptLoad = async (retries: number) => {
124
- try {
125
- const moduleFactory = await getRemote(remoteName, exposedModule);
126
- const remote = await extractRemote(moduleFactory);
127
-
128
- if (remote.id && remote.widgets) {
129
- console.log(`[Plugin Injector] Setup Root Cortex: ${remote.name}`);
130
- setupCortex(remote, remote.name);
131
- } else if (remote.default && remote.default.id && remote.default.widgets) {
132
- console.log(`[Plugin Injector] Setup Default Cortex: ${remote.default.name}`);
133
- setupCortex(remote.default, remote.default.name);
134
- } else {
135
- console.warn("[Plugin Injector] No raw CORTEX structure found at root, checking legacy namespaces...");
136
- if (remote.PlantaErpPlugin) setupCortex(remote.PlantaErpPlugin, 'PlantaErpPlugin');
137
- if (remote.FrubealaUiPlugin) setupCortex(remote.FrubealaUiPlugin, 'FrubealaUiPlugin');
138
- if (remote.ForgeCortex) setupCortex(remote.ForgeCortex, 'ForgeCortex');
139
- if (remote.CommanderCortex) setupCortex(remote.CommanderCortex, 'CommanderCortex');
140
- if (remote.BridgeCortex) setupCortex(remote.BridgeCortex, 'BridgeCortex');
141
- }
142
- } catch (err: any) {
143
- if (err instanceof ReferenceError && retries > 0) {
144
- console.warn(`⏳ [Plugin Engine] TDZ ReferenceError dynamically loading ${remoteName}, waiting 100ms... (${retries} left)`);
145
- await new Promise(res => setTimeout(res, 100));
146
- await attemptLoad(retries - 1);
147
- } else {
148
- console.error(`❌ [Federation Marketplace] Could not load Remote ${remoteName} from ${url}:`, err);
149
- }
150
- }
151
- };
152
-
153
- await attemptLoad(10);
154
- } catch (err) {
155
- console.error(`❌ [Federation Marketplace] execution error resolving Remote ${remoteName} from ${url}:`, err);
156
- }
157
- };
158
-
159
- for (const entry of registry) {
160
- if (entry.enabled && entry.url && entry.exposedModule) {
161
- loadDynamicPlugin(entry.name, entry.url, entry.exposedModule, entry.signature);
162
- }
163
- }
164
- }, [registry, setRemote, getRemote, publicKeyB64, onPluginLoaded, onMCPServerDiscovered, onSecurityAlert, onSidebarItemsRegistered]);
165
- };