@kumologica/sdk 4.0.0-beta8 → 4.0.0-beta9

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.
@@ -652,6 +652,7 @@ jQuery.propHooks.disabled = {
652
652
  RED.palette.init();
653
653
  RED.palette.explorer.init();
654
654
  RED.palette.nodes.init();
655
+ RED.palette.aiassistant.init();
655
656
  RED.eventLog.init();
656
657
  if (RED.settings.theme("palette.editable") !== false) {
657
658
  RED.palette.editor.init();
@@ -25463,216 +25464,7 @@ RED.sidebar.nodeinfo = (function(){
25463
25464
  refreshTab,
25464
25465
  };
25465
25466
  })();
25466
- ;RED.sidebar.ai = (function () {
25467
- let tabContent;
25468
- let sections;
25469
- let stackContainer;
25470
- let latestCodeGenerated = '[]';
25471
-
25472
- const INITIAL_MESSAGE = `Generate flow or node that ... (ctrl+enter to generate)`;
25473
-
25474
- const openAIClient = window.__kumologica.libs.openAIClient; // TODO: javier
25475
-
25476
- function initHTML() {
25477
- tabContent = document.createElement('div');
25478
- tabContent.className = 'sidebar-ai';
25479
- tabContent.style = "height: 100%";
25480
-
25481
- RED.actions.add('core:show-ai-tab', show);
25482
-
25483
- stackContainer = $('<div>', {
25484
- class: 'sidebar-node-info-stack',
25485
- style: 'height: 100%'
25486
- }).appendTo(tabContent);
25487
-
25488
- // Append the header
25489
- let headerContentHtml = `
25490
- <div class="sidebar-ai-title-wrapper">
25491
- <div style="display:flex;flex-direction:column;padding-right:10px; width:100%; height: 100%">
25492
- <div id="sidebar-title-wrapper" style="display:flex">
25493
- <span>Generative AI</span>
25494
- </div>
25495
-
25496
- <div id="sidebar-ai-body">
25497
- <div id="sidebar-ai-error-wrapper" style="display:none">
25498
- <span><b>An error occurred during processing your request</b>
25499
- <span>Please check the logs for additional details or contact support for assistance</span>
25500
- </div>
25501
- <div id="sidebar-ai-response-wrapper" style="display:none">
25502
- <div class="pt-0.5">
25503
- <div class="gizmo-shadow-stroke flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
25504
- <div class="relative p-1 rounded-sm h-9 w-9 text-white flex items-center justify-center" style="background-color: rgb(25, 195, 125); width: 24px; height: 24px; border-radius: 9999px; justify-content: center; align-items: center; color: white; margin-bottom: 7px">
25505
- <svg width="41" height="41" viewBox="0 0 41 41" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-sm" role="img"><text x="-9999" y="-9999">ChatGPT</text><path d="M37.5324 16.8707C37.9808 15.5241 38.1363 14.0974 37.9886 12.6859C37.8409 11.2744 37.3934 9.91076 36.676 8.68622C35.6126 6.83404 33.9882 5.3676 32.0373 4.4985C30.0864 3.62941 27.9098 3.40259 25.8215 3.85078C24.8796 2.7893 23.7219 1.94125 22.4257 1.36341C21.1295 0.785575 19.7249 0.491269 18.3058 0.500197C16.1708 0.495044 14.0893 1.16803 12.3614 2.42214C10.6335 3.67624 9.34853 5.44666 8.6917 7.47815C7.30085 7.76286 5.98686 8.3414 4.8377 9.17505C3.68854 10.0087 2.73073 11.0782 2.02839 12.312C0.956464 14.1591 0.498905 16.2988 0.721698 18.4228C0.944492 20.5467 1.83612 22.5449 3.268 24.1293C2.81966 25.4759 2.66413 26.9026 2.81182 28.3141C2.95951 29.7256 3.40701 31.0892 4.12437 32.3138C5.18791 34.1659 6.8123 35.6322 8.76321 36.5013C10.7141 37.3704 12.8907 37.5973 14.9789 37.1492C15.9208 38.2107 17.0786 39.0587 18.3747 39.6366C19.6709 40.2144 21.0755 40.5087 22.4946 40.4998C24.6307 40.5054 26.7133 39.8321 28.4418 38.5772C30.1704 37.3223 31.4556 35.5506 32.1119 33.5179C33.5027 33.2332 34.8167 32.6547 35.9659 31.821C37.115 30.9874 38.0728 29.9178 38.7752 28.684C39.8458 26.8371 40.3023 24.6979 40.0789 22.5748C39.8556 20.4517 38.9639 18.4544 37.5324 16.8707ZM22.4978 37.8849C20.7443 37.8874 19.0459 37.2733 17.6994 36.1501C17.7601 36.117 17.8666 36.0586 17.936 36.0161L25.9004 31.4156C26.1003 31.3019 26.2663 31.137 26.3813 30.9378C26.4964 30.7386 26.5563 30.5124 26.5549 30.2825V19.0542L29.9213 20.998C29.9389 21.0068 29.9541 21.0198 29.9656 21.0359C29.977 21.052 29.9842 21.0707 29.9867 21.0902V30.3889C29.9842 32.375 29.1946 34.2791 27.7909 35.6841C26.3872 37.0892 24.4838 37.8806 22.4978 37.8849ZM6.39227 31.0064C5.51397 29.4888 5.19742 27.7107 5.49804 25.9832C5.55718 26.0187 5.66048 26.0818 5.73461 26.1244L13.699 30.7248C13.8975 30.8408 14.1233 30.902 14.3532 30.902C14.583 30.902 14.8088 30.8408 15.0073 30.7248L24.731 25.1103V28.9979C24.7321 29.0177 24.7283 29.0376 24.7199 29.0556C24.7115 29.0736 24.6988 29.0893 24.6829 29.1012L16.6317 33.7497C14.9096 34.7416 12.8643 35.0097 10.9447 34.4954C9.02506 33.9811 7.38785 32.7263 6.39227 31.0064ZM4.29707 13.6194C5.17156 12.0998 6.55279 10.9364 8.19885 10.3327C8.19885 10.4013 8.19491 10.5228 8.19491 10.6071V19.808C8.19351 20.0378 8.25334 20.2638 8.36823 20.4629C8.48312 20.6619 8.64893 20.8267 8.84863 20.9404L18.5723 26.5542L15.206 28.4979C15.1894 28.5089 15.1703 28.5155 15.1505 28.5173C15.1307 28.5191 15.1107 28.516 15.0924 28.5082L7.04046 23.8557C5.32135 22.8601 4.06716 21.2235 3.55289 19.3046C3.03862 17.3858 3.30624 15.3413 4.29707 13.6194ZM31.955 20.0556L22.2312 14.4411L25.5976 12.4981C25.6142 12.4872 25.6333 12.4805 25.6531 12.4787C25.6729 12.4769 25.6928 12.4801 25.7111 12.4879L33.7631 17.1364C34.9967 17.849 36.0017 18.8982 36.6606 20.1613C37.3194 21.4244 37.6047 22.849 37.4832 24.2684C37.3617 25.6878 36.8382 27.0432 35.9743 28.1759C35.1103 29.3086 33.9415 30.1717 32.6047 30.6641C32.6047 30.5947 32.6047 30.4733 32.6047 30.3889V21.188C32.6066 20.9586 32.5474 20.7328 32.4332 20.5338C32.319 20.3348 32.154 20.1698 31.955 20.0556ZM35.3055 15.0128C35.2464 14.9765 35.1431 14.9142 35.069 14.8717L27.1045 10.2712C26.906 10.1554 26.6803 10.0943 26.4504 10.0943C26.2206 10.0943 25.9948 10.1554 25.7963 10.2712L16.0726 15.8858V11.9982C16.0715 11.9783 16.0753 11.9585 16.0837 11.9405C16.0921 11.9225 16.1048 11.9068 16.1207 11.8949L24.1719 7.25025C25.4053 6.53903 26.8158 6.19376 28.2383 6.25482C29.6608 6.31589 31.0364 6.78077 32.2044 7.59508C33.3723 8.40939 34.2842 9.53945 34.8334 10.8531C35.3826 12.1667 35.5464 13.6095 35.3055 15.0128ZM14.2424 21.9419L10.8752 19.9981C10.8576 19.9893 10.8423 19.9763 10.8309 19.9602C10.8195 19.9441 10.8122 19.9254 10.8098 19.9058V10.6071C10.8107 9.18295 11.2173 7.78848 11.9819 6.58696C12.7466 5.38544 13.8377 4.42659 15.1275 3.82264C16.4173 3.21869 17.8524 2.99464 19.2649 3.1767C20.6775 3.35876 22.0089 3.93941 23.1034 4.85067C23.0427 4.88379 22.937 4.94215 22.8668 4.98473L14.9024 9.58517C14.7025 9.69878 14.5366 9.86356 14.4215 10.0626C14.3065 10.2616 14.2466 10.4877 14.2479 10.7175L14.2424 21.9419ZM16.071 17.9991L20.4018 15.4978L24.7325 17.9975V22.9985L20.4018 25.4983L16.071 22.9985V17.9991Z" fill="currentColor"></path>
25506
- </svg>
25507
- </div>
25508
- </div>
25509
- </div>
25510
- <div id="sidebar-ai-response-message">
25511
- <div id="sidebar-ai-response-action-wrapper">
25512
- <a id="sidebar-ai-import-flow" class="sidebar-header-button" href="#" style="margin-right:5px">
25513
- Import Flow
25514
- </a>
25515
- </div>
25516
- <span id="sidebar-ai-response-flow-value"></span>
25517
- </div>
25518
-
25519
- </div>
25520
- </div>
25521
-
25522
- <div id="sidebar-ai-prompt">
25523
- <div id="sidebar-ai-prompt-message-wrapper">
25524
- <textarea id="sidebar-ai-prompt-message" rows="4" placeholder="${INITIAL_MESSAGE}" style="min-height:130px"></textarea>
25525
- </div>
25526
- <div id="sidebar-ai-prompt-actions">
25527
- <a id="sidebar-ai-clear-btn" class="sidebar-header-button" href="#" style="margin-right:5px">
25528
- Clear
25529
- </a>
25530
- <a id="sidebar-ai-generate-btn" class="sidebar-header-button" href="#" style="color: white !important; background: #2979ff;">
25531
- Generate
25532
- </a>
25533
- </div>
25534
- <div id="sidebar-ai-prompt-noactions" style="display:none">
25535
- <a id="sidebar-ai-generating" class="sidebar-header-button" href="#" style="color: white !important; height: 24px;">
25536
- <img src="red/images/spin.svg" class="palette-spinner" style="height: 16px; width: 57px" />
25537
- </a>
25538
- </div>
25539
- </div>
25540
-
25541
- <div id="ai-not-initialized" style="display:none">
25542
- <div style="display:flex; flex-direction: column; align-items: center; margin-top: 150px">
25543
- <div><i class="fa fa-magic" style="font-size: 56px; color: lightgrey;"></i></div>
25544
- <div style="font-weight: bold; font-size: 22px; margin-top: 15px;color: grey;">OpenAI API Key not found</div>
25545
- <div style="margin-top: 5px; color: grey;font-weight: 400; font-size: 13px;">To use this feature, you need to add your OpenAI key. </div>
25546
- <div style="margin-top: 10px"><span id="add-ai-key" style="font-weight: 500;font-size: 12px; color: #2979ff">Add key</span></div>
25547
- </div>
25548
- </div>
25549
- </div>
25550
- </div>
25551
- `;
25552
-
25553
- $(headerContentHtml).appendTo(stackContainer);
25554
-
25555
- RED.sidebar.addTab({
25556
- id: 'ai',
25557
- label: 'Gen AI',
25558
- name: 'Generative AI',
25559
- iconClass: 'fa fa-magic',
25560
- action: 'core:show-git-tab',
25561
- content: tabContent,
25562
- pinned: true,
25563
- enableOnEdit: true,
25564
- onchange: refreshTab,
25565
- onsame: onsame
25566
- })
25567
- }
25568
- function displayGeneratedCode(code) {
25569
- // update the latest code generated
25570
- latestCodeGenerated = JSON.stringify(code, null, 2);
25571
-
25572
- $('#sidebar-ai-response-wrapper').show();
25573
- let $response = $('#sidebar-ai-response-flow-value');
25574
-
25575
- RED.utils
25576
- .createObjectElement({ "code": code }, {
25577
- key: /*true*/ null,
25578
- typeHint: 'object',
25579
- hideKey: false,
25580
- path: '',
25581
- sourceId: 0,
25582
- rootPath: '',
25583
- })
25584
- .appendTo($response);
25585
- }
25586
-
25587
- function changeStateToGenerating() {
25588
- latestCodeGenerated = '[]';
25589
- // Clear the previous response if required
25590
- $('#sidebar-ai-response-wrapper').hide();
25591
- $('#sidebar-ai-response-flow-value').empty();
25592
-
25593
- // Control buttons
25594
- $('#sidebar-ai-prompt-actions').hide();
25595
- $('#sidebar-ai-prompt-noactions').show();
25596
- }
25597
-
25598
- function changeStateToGenerated() {
25599
- $('#sidebar-ai-prompt-actions').show();
25600
- $('#sidebar-ai-prompt-noactions').hide();
25601
-
25602
- }
25603
-
25604
- function initJS() {
25605
- // Generate action
25606
- $('#sidebar-ai-generate-btn').click(async e => {
25607
- console.log('Asking AI to generate code...');
25608
- // Change the icon to loading
25609
- changeStateToGenerating();
25610
-
25611
- let userPrompt = $('#sidebar-ai-prompt-message').val();
25612
- if (userPrompt) {
25613
- let response = await openAIClient.t2c(userPrompt);
25614
- displayGeneratedCode(response);
25615
- changeStateToGenerated();
25616
- } else {
25617
- changeStateToGenerated();
25618
- }
25619
-
25620
-
25621
- })
25622
- // Trigger generate action from ctrl+click
25623
- $('#sidebar-ai-prompt-message').keydown(e => {
25624
- if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
25625
- $('#sidebar-ai-generate-btn').click();
25626
- }
25627
- })
25628
-
25629
- // Clear button
25630
- $('#sidebar-ai-clear-btn').click(async e => {
25631
- // Clear all messages
25632
- $('#sidebar-ai-response-wrapper').hide();
25633
- $('#sidebar-ai-response-flow-value').empty();
25634
-
25635
- // Clear user prompt
25636
- $('#sidebar-ai-prompt-message').val('');
25637
- });
25638
-
25639
- $('#sidebar-ai-import-flow').click(e => {
25640
- // Copy code to clipboard
25641
- const { clipboard } = window.__kumologica.electron;
25642
- clipboard.writeText(latestCodeGenerated);
25643
-
25644
- // Open the import flow dialog
25645
- RED.actions.invoke('core:show-import-dialog')
25646
-
25647
- // automatically trigger the import-from-clipboard option
25648
- setTimeout(() => { $('#import-from-clipboard').click() }, 100);
25649
- })
25650
- }
25651
-
25652
- function init() {
25653
- initHTML();
25654
- initJS();
25655
- }
25656
-
25657
- function show() {
25658
- RED.sidebar.show('ai');
25659
- }
25660
-
25661
- function refreshTab(silently) {
25662
- if (!silently) {
25663
- RED.actions.invoke('core:show-sidebar');
25664
- }
25665
- }
25666
-
25667
- function onsame() {
25668
- RED.actions.invoke('core:hide-sidebar');
25669
- }
25670
-
25671
- return {
25672
- init: init,
25673
- show: show,
25674
- }
25675
- })();;RED.sidebar.git = (function(){
25467
+ ;RED.sidebar.git = (function(){
25676
25468
 
25677
25469
  let tabContent;
25678
25470
  let sections;
@@ -26857,6 +26649,13 @@ RED.sidebar.azure = (function () {
26857
26649
  onSelect: () => {
26858
26650
  RED.palette.explorer.refresh()
26859
26651
  }
26652
+ },
26653
+ aiassist: {
26654
+ header: 'palette-option-aiassist-a',
26655
+ panel: 'palette-aiassistant',
26656
+ onSelect: () => {
26657
+ RED.palette.aiassist.refresh()
26658
+ }
26860
26659
  }
26861
26660
  }
26862
26661
 
@@ -26870,11 +26669,17 @@ RED.sidebar.azure = (function () {
26870
26669
  deselectAll();
26871
26670
  select(options.explorer);
26872
26671
  });
26672
+
26673
+ $(`#${options.aiassist.header}`).click(e=> {
26674
+ deselectAll();
26675
+ select(options.aiassist);
26676
+ });
26873
26677
  }
26874
26678
 
26875
26679
  const deselectAll = () => {
26876
26680
  deselect(options.nodes);
26877
26681
  deselect(options.explorer);
26682
+ deselect(options.aiassist);
26878
26683
 
26879
26684
  }
26880
26685
 
@@ -26892,9 +26697,128 @@ RED.sidebar.azure = (function () {
26892
26697
 
26893
26698
  }
26894
26699
 
26700
+ $('#palette-separator').draggable({
26701
+ axis: 'x',
26702
+ start: function (event, ui) {
26703
+ sidebarDragging = true;
26704
+ sidebarWidthP0 = $('#sidebar').width();
26705
+ delta = 0;
26706
+ },
26707
+ drag: function (event, ui) {
26708
+ let d = ui.position.left;
26709
+ delta = sidebarWidthP0 - d;
26710
+ $('#sidebar').width(delta);
26711
+ if ($('#sidebar').width() > maxWidthSidebar()) {
26712
+ $('#sidebar').width(maxWidthSidebar());
26713
+ }
26714
+ event.stopImmediatePropagation();
26715
+ RED.events.emit('palette:resize');
26716
+ },
26717
+ stop: function (event, ui) {
26718
+ setTimeout(function () {
26719
+ sidebarDragging = false;
26720
+ }, 1000);
26721
+ RED.events.emit('palette:resize');
26722
+ },
26723
+ });
26724
+
26725
+ var sidebarControls = $(
26726
+ '<div class="sidebar-control-right"><i class="fa fa-chevron-right"</div>'
26727
+ ).appendTo($('#palette-separator'));
26728
+ sidebarControls.click(function () {
26729
+ sidebarControls.hide();
26730
+ RED.menu.toggleSelected('menu-item-sidebar');
26731
+ });
26732
+
26733
+ function maxWidthSidebar() {
26734
+ const totalWidth = $('#main-container').width();
26735
+ const shortcutsWidth = 50;
26736
+ const paletteWidth = $('#palette').width();
26737
+ const sidebarSeparatorWidth = $('#palette-separator').width()
26738
+
26739
+ return totalWidth - shortcutsWidth - paletteWidth - sidebarSeparatorWidth;
26740
+ }
26741
+
26742
+ function maximizeSidebar() {
26743
+ const targetWidth = maxWidthSidebar();
26744
+ $('#sidebar').width(targetWidth);
26745
+
26746
+ // Hack: Make sure the workspace if reset before maximizing the sidebar. This is because when dragging the sidebar the workspace width is also modified
26747
+ $('#workspace').css('right', 485);
26748
+ RED.events.emit('sidebar:resize');
26749
+ }
26750
+
26751
+ function restoreSidebar() {
26752
+ const offsetWidth = 435;
26753
+
26754
+ $('#sidebar').width(offsetWidth);
26755
+ // $('#sidebar-separator').css('left', '');
26756
+ RED.events.emit('sidebar:resize');
26757
+ }
26758
+
26759
+ function isSidebarVisible() {
26760
+ return !$('#main-container').hasClass('sidebar-closed');
26761
+ }
26762
+
26763
+ function toggleSidebar(state) {
26764
+ let checkIfscrollWorkspaceRequired = false;
26765
+ if (!state) {
26766
+ // Hide the sidebar and sidebar-separator
26767
+ // $('#sidebar-separator').hide();
26768
+ $('#main-container').addClass('sidebar-closed');
26769
+ $('#shelve-right').removeClass('shelf-selected');
26770
+ } else {
26771
+ if (!$('#shelve-right').hasClass('shelf-selected')) {
26772
+ checkIfscrollWorkspaceRequired = true;
26773
+ }
26774
+ // Show the sidebar and sidebar-separator
26775
+ // $('#sidebar-separator').show();
26776
+ $('#main-container').removeClass('sidebar-closed');
26777
+ $('#shelve-right').addClass('shelf-selected');
26778
+ sidebar_tabs.resize();
26779
+ }
26780
+ RED.events.emit('sidebar:resize');
26781
+ if (checkIfscrollWorkspaceRequired && RED.editor.getLatestNodeSelected()) {
26782
+ // Reposition the workspace if the node may be left hidden behind the sidebar
26783
+ const safeDistNodeSidebar = 300;
26784
+ let nodeSelectedPosX = RED.editor.getLatestNodeSelected().x;
26785
+ let initialScrollLeft = $('#chart').scrollLeft();
26786
+ let sidebarPosLeftX = $('#sidebar').position().left;
26787
+ // console.log(`[sidebar]
26788
+ // - initalScrollLeft: ${initialScrollLeft}
26789
+ // - nodeSelectedPosX: ${nodeSelectedPosX}
26790
+ // - sidebarPosLeftX: ${sidebarPosLeftX}
26791
+ // ----------------------------------------
26792
+ // `);
26793
+ if (nodeSelectedPosX - initialScrollLeft + safeDistNodeSidebar > sidebarPosLeftX) {
26794
+ let targetScrollLeft = nodeSelectedPosX - sidebarPosLeftX + safeDistNodeSidebar;
26795
+ $('#chart').animate({ scrollLeft: targetScrollLeft })
26796
+ }
26797
+ }
26798
+ }
26799
+
26800
+ function isSidebarDragging() {
26801
+ return sidebarDragging;
26802
+ }
26803
+
26804
+ function showSidebar(id) {
26805
+ if (id) {
26806
+ if (!containsTab(id)) {
26807
+ sidebar_tabs.addTab(knownTabs[id]);
26808
+ }
26809
+ sidebar_tabs.activateTab(id);
26810
+ }
26811
+ }
26812
+
26813
+ function containsTab(id) {
26814
+ return sidebar_tabs.contains(id);
26815
+ }
26816
+
26817
+
26895
26818
  const init = () => {
26896
26819
  // Preselection
26897
26820
  deselect(options.explorer);
26821
+ deselect(options.aiassist);
26898
26822
  select(options.nodes);
26899
26823
 
26900
26824
  // Handle the click events
@@ -27436,6 +27360,533 @@ RED.sidebar.azure = (function () {
27436
27360
  };
27437
27361
 
27438
27362
  })();
27363
+ ;RED.palette.aiassistant = (function () {
27364
+
27365
+ let conversation = [];
27366
+
27367
+ // returns array of sections defined in the ai config file (all ai configurations)
27368
+ function getSettingsFromConfig() {
27369
+ const aiConfigStore = window.__kumologica.settings.aiConfigStore;
27370
+ const aiConfig = aiConfigStore.getSections();
27371
+ return aiConfig;
27372
+ }
27373
+
27374
+ // returns defined provider for the given alias
27375
+ function getProvider(alias) {
27376
+ const aiConfigStore = window.__kumologica.settings.aiConfigStore;
27377
+ return {
27378
+ provider: aiConfigStore.getAliasInfo(alias, 'provider'),
27379
+ model: aiConfigStore.getAliasInfo(alias, 'model'),
27380
+ api_key: aiConfigStore.getAliasInfo(alias, 'api_key'),
27381
+ temperature: parseFloat(aiConfigStore.getAliasInfo(alias, 'temperature')) || 0.7,
27382
+ max_tokens: parseInt(aiConfigStore.getAliasInfo(alias, 'max_tokens')) || 4096,
27383
+ systemPrompt: aiConfigStore.getPrompt() || null,
27384
+ region: aiConfigStore.getAliasInfo(alias, 'region') || 'us-east-1', // for AWS Bedrock
27385
+ profile: aiConfigStore.getAliasInfo(alias, 'profile') || null, // for AWS Bedrock
27386
+ }
27387
+ }
27388
+
27389
+ function applyCode(code) {
27390
+ try {
27391
+ // First, escape newlines and tabs within quoted strings
27392
+ code = code.replace(/("(?:[^"\\]|\\.)*")/g, function(match) {
27393
+ // Process content inside quotes
27394
+ return match
27395
+ .replace(/\n/g, '\\n') // Replace actual newlines with \n
27396
+ .replace(/\r/g, '\\r') // Replace carriage returns with \r
27397
+ .replace(/\t/g, '\\t'); // Replace tabs with \t
27398
+ });
27399
+
27400
+ // Validate that the code is a valid JSON array (nodes)
27401
+ if (!/^\[[\s\S]*\]$/m.test(code.trim())) {
27402
+ alert('Error: Code is not a valid JSON array format');
27403
+ return;
27404
+ }
27405
+
27406
+ var nodes = JSON.parse(code.trim());
27407
+
27408
+ // Validate that it contains valid node objects
27409
+ for (var i = 0; i < nodes.length; i++) {
27410
+ if (typeof nodes[i] !== "object") {
27411
+ alert('Error: Input not a valid flow');
27412
+ return;
27413
+ }
27414
+ if (!nodes[i].hasOwnProperty('id')) {
27415
+ alert('Error: Input not a valid flow');
27416
+ return;
27417
+ }
27418
+ if (!nodes[i].hasOwnProperty('type')) {
27419
+ alert('Error: Input not a valid flow');
27420
+ return;
27421
+ }
27422
+ }
27423
+
27424
+ // If validation passes, import the nodes into the desktop
27425
+ RED.view.importNodes(code.trim(), false);
27426
+ RED.notify('Nodes imported from AI Assistant', {id: "ai-assistant-import"});
27427
+
27428
+ } catch(err) {
27429
+ alert('Error applying code: ' + err.toString());
27430
+ }
27431
+ }
27432
+ function convertMarkdownToHtml(text) {
27433
+ // Escape HTML special characters first
27434
+ text = $('<div>').text(text).html();
27435
+
27436
+ // Convert headings: # text, ## text, etc.
27437
+ text = text.replace(/^### (.+)$/gm, '<h5 style="font-size:14px;font-weight:bold;margin:8px 0;font-family:\'JetBrains Mono\', \'Fira Code\', \'Courier New\', monospace;">$1</h5>');
27438
+ text = text.replace(/^## (.+)$/gm, '<h4 style="font-size:16px;font-weight:bold;margin:8px 0;font-family:\'JetBrains Mono\', \'Fira Code\', \'Courier New\', monospace;">$1</h4>');
27439
+ text = text.replace(/^# (.+)$/gm, '<h3 style="font-size:18px;font-weight:bold;margin:8px 0;font-family:\'JetBrains Mono\', \'Fira Code\', \'Courier New\', monospace;">$1</h3>');
27440
+
27441
+ // Convert bold: **text** or __text__
27442
+ text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
27443
+ text = text.replace(/__(.+?)__/g, '<strong>$1</strong>');
27444
+
27445
+ // Convert italic: *text* or _text_
27446
+ text = text.replace(/\*(.+?)\*/g, '<em>$1</em>');
27447
+ text = text.replace(/_(.+?)_/g, '<em>$1</em>');
27448
+
27449
+ // Convert inline code: `text`
27450
+ text = text.replace(/`(.+?)`/g, '<code style="background:#f0f0f0;color:#d63384;padding:2px 6px;border-radius:3px;font-family:\'JetBrains Mono\', \'Fira Code\', \'Courier New\', monospace;font-size:14px;font-weight:bold;">$1</code>');
27451
+
27452
+ // Convert newlines to <br> tags
27453
+ text = text.replace(/\n/g, '<br>');
27454
+
27455
+ // Convert unordered lists: - item or * item
27456
+ text = text.replace(/^[\*\-]\s+(.+)$/gm, '<li>$1</li>');
27457
+ text = text.replace(/(<li>.*<\/li>)/s, '<ul style="margin:8px 0;padding-left:20px;">$1</ul>');
27458
+
27459
+ return text;
27460
+ }
27461
+
27462
+ function getLanguageStyles(language) {
27463
+ const styles = {
27464
+ javascript: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27465
+ python: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27466
+ sql: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27467
+ html: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', tag: '#4ec9b0', number: '#b5cea8' },
27468
+ css: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', property: '#9cdcfe', number: '#b5cea8' },
27469
+ java: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27470
+ csharp: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27471
+ go: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27472
+ rust: { keywords: '#569cd6', string: '#ce9178', comment: '#6a9955', function: '#dcdcaa', number: '#b5cea8' },
27473
+ json: { key: '#9cdcfe', string: '#ce9178', number: '#b5cea8', boolean: '#569cd6', null: '#569cd6' },
27474
+ xml: { tag: '#569cd6', attribute: '#9cdcfe', string: '#ce9178', comment: '#6a9955' },
27475
+ };
27476
+ return styles[language] || styles.javascript;
27477
+ }
27478
+
27479
+ function highlightCode(code, language) {
27480
+ // Escape HTML FIRST - before any highlighting
27481
+ let highlighted = $('<div>').text(code).html();
27482
+
27483
+ const keywordPatterns = {
27484
+ javascript: /\b(function|const|let|var|if|else|for|while|return|class|async|await|import|export|try|catch|new|throw)\b/g,
27485
+ python: /\b(def|class|if|else|for|while|return|import|from|async|await|with|try|except)\b/g,
27486
+ sql: /\b(SELECT|FROM|WHERE|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|JOIN|ON|GROUP|ORDER|BY|HAVING)\b/gi,
27487
+ html: /(<\/?[a-z][a-z0-9]*\b[^>]*>)/gi,
27488
+ css: /([a-z-]+)(\s*:)/gi,
27489
+ java: /\b(public|private|class|interface|void|int|String|if|else|for|while|return|static|final)\b/g,
27490
+ csharp: /\b(public|private|class|interface|void|int|string|if|else|for|while|return|static|async|await)\b/g,
27491
+ go: /\b(func|package|import|const|var|if|else|for|return|type|interface|struct)\b/g,
27492
+ rust: /\b(fn|let|mut|const|struct|impl|trait|if|else|for|while|return|pub|async|await)\b/g,
27493
+ };
27494
+
27495
+ const commentPatterns = {
27496
+ javascript: /&#x2F;&#x2F;.+$/gm,
27497
+ python: /#.+$/gm,
27498
+ sql: /&#x2D;&#x2D;.+$/gm,
27499
+ java: /&#x2F;&#x2F;.+$/gm,
27500
+ csharp: /&#x2F;&#x2F;.+$/gm,
27501
+ go: /&#x2F;&#x2F;.+$/gm,
27502
+ rust: /&#x2F;&#x2F;.+$/gm,
27503
+ };
27504
+
27505
+ const stringPattern = /(['"`])(.*?)\1/g;
27506
+ const numberPattern = /\b(\d+\.?\d*)\b/g;
27507
+
27508
+ const styles = getLanguageStyles(language);
27509
+
27510
+ // JSON specific highlighting
27511
+ if (language === 'json') {
27512
+ highlighted = highlighted.replace(/"([^"]+)"\s*:/g,
27513
+ `<span style="color:${styles.key};">"$1"</span>:`);
27514
+ highlighted = highlighted.replace(/:\s*"([^"]*)"/g,
27515
+ `:<span style="color:${styles.string};"> "$1"</span>`);
27516
+ highlighted = highlighted.replace(/:\s*(\d+\.?\d*)/g,
27517
+ `:<span style="color:${styles.number};"> $1</span>`);
27518
+ highlighted = highlighted.replace(/\b(true|false|null)\b/g,
27519
+ `<span style="color:${styles.boolean};">$1</span>`);
27520
+ return highlighted;
27521
+ }
27522
+
27523
+ // XML specific highlighting
27524
+ if (language === 'xml') {
27525
+ highlighted = highlighted.replace(/(&lt;!--[\s\S]*?--&gt;)/g,
27526
+ match => `<span style="color:${styles.comment};">${match}</span>`);
27527
+ highlighted = highlighted.replace(/(&lt;\/?)\b([a-zA-Z_][\w.-]*)\b/g,
27528
+ `<span style="color:${styles.tag};">$1$2</span>`);
27529
+ highlighted = highlighted.replace(/="([^"]*)"/g,
27530
+ `="<span style="color:${styles.string};">$1</span>"`);
27531
+ return highlighted;
27532
+ }
27533
+
27534
+ // For all other languages: apply highlighting in correct order
27535
+ // 1. Comments FIRST (before strings, keywords, numbers)
27536
+ if (commentPatterns[language]) {
27537
+ highlighted = highlighted.replace(commentPatterns[language],
27538
+ match => `<span style="color:${styles.comment};font-style:italic;">${match}</span>`);
27539
+ }
27540
+
27541
+ // 2. Strings (to protect them from keyword/number replacements)
27542
+ highlighted = highlighted.replace(stringPattern,
27543
+ match => `<span style="color:${styles.string};">${match}</span>`);
27544
+
27545
+ // 3. Numbers (after strings to avoid conflicts)
27546
+ highlighted = highlighted.replace(numberPattern,
27547
+ match => `<span style="color:${styles.number};">${match}</span>`);
27548
+
27549
+ // 4. Keywords last (lowest priority)
27550
+ if (keywordPatterns[language]) {
27551
+ highlighted = highlighted.replace(keywordPatterns[language],
27552
+ match => `<span style="color:${styles.keywords};font-weight:bold;">${match}</span>`);
27553
+ }
27554
+
27555
+ return highlighted;
27556
+ }
27557
+ async function chatWithAi(conversation, question) {
27558
+ const $chat = $('#palette-aiassistant-chat');
27559
+
27560
+ // Add user question to chat (right aligned)
27561
+ const userMsgHtml = `
27562
+ <div class="ai-chat-msg ai-chat-user" style="text-align: right; margin: 5px;">
27563
+ <span style="background: #f0f1f1; color: #333; padding: 8px 12px; border-radius: 4px; display: inline-block; max-width: 80%; text-align: left; user-select: text; cursor: text;">${$('<div>').text(question).html()}</span>
27564
+ </div>
27565
+ `;
27566
+ $chat.append(userMsgHtml);
27567
+
27568
+ // Auto-scroll to bottom after user message
27569
+ $chat.scrollTop($chat[0].scrollHeight);
27570
+
27571
+ // Add question to conversation history
27572
+ conversation.push({ role: 'user', content: question });
27573
+
27574
+ // Get selected model and provider (if needed)
27575
+ const model = $('#palette-aiassistant-model').val();
27576
+ const provider = getProvider(model);
27577
+
27578
+ const options = {
27579
+ provider: provider.provider,
27580
+ model: provider.model,
27581
+ apiKey: provider.api_key,
27582
+ messages: conversation, // Include full conversation history
27583
+ systemPrompt: provider.systemPrompt,
27584
+ region: provider.region,
27585
+ profile: provider.profile,
27586
+ params: { temperature: provider.temperature, maxTokens: provider.max_tokens }
27587
+ };
27588
+
27589
+ try {
27590
+ console.log("Calling chatAi with options:", options);
27591
+ const res = await window.__kumologica.libs.chatAi(options);
27592
+
27593
+ console.log("response:", JSON.stringify(res));
27594
+
27595
+
27596
+ let responseHtml = res.content || '[No response]';
27597
+ responseHtml = responseHtml.replace(/\\n/g, '\n')
27598
+ .replace(/\\t/g, '\t')
27599
+ .replace(/\\r/g, '\r')
27600
+ .replace(/\\\`/g, '`');
27601
+
27602
+ console.log("Unescaped responseHtml:", responseHtml);
27603
+
27604
+ let assistantMsgHtml = ''; // INITIALIZE HERE
27605
+ const codeBlockRegex = /```(\w+)?\s*([\s\S]*?)(?:```|$)/g;
27606
+
27607
+ let lastIndex = 0;
27608
+ let match;
27609
+ let hasCode = false;
27610
+
27611
+ // Process all code blocks and surrounding text
27612
+ while ((match = codeBlockRegex.exec(responseHtml)) !== null) {
27613
+ hasCode = true;
27614
+ // Text before code block
27615
+ const textBefore = responseHtml.slice(lastIndex, match.index);
27616
+ if (textBefore.trim()) {
27617
+ const formattedText = convertMarkdownToHtml(textBefore);
27618
+ assistantMsgHtml += `
27619
+ <div class="ai-chat-msg ai-chat-assistant" style="text-align: left; margin: 8px 0;">
27620
+ <span style="color: #222; padding: 8px 12px; border-radius: 5px; display: inline-block; max-width: 100%;">${formattedText}</span>
27621
+ </div>
27622
+ `;
27623
+ }
27624
+ // Code block
27625
+ const language = match[1] || 'plaintext';
27626
+ const code = match[2].trim();
27627
+ const codeLines = code.split('\n').map(line => line.trimEnd()); // Trim trailing whitespace from each line
27628
+ const displayedCode = codeLines.join('\n');
27629
+ const highlightedCode = language === 'plaintext' ? $('<div>').text(displayedCode).html() : highlightCode(displayedCode, language);
27630
+ const codeId = `ai-code-${Date.now()}-${Math.floor(Math.random()*10000)}`;
27631
+
27632
+ assistantMsgHtml += `
27633
+ <div class="ai-chat-msg ai-chat-assistant" style="text-align: left; margin: 8px 0;">
27634
+ <span style="color: #222; padding: 8px 12px; border-radius: 5px; display: inline-block; max-width: 85%; margin: 5px; border: 1px solid darkgrey;">
27635
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
27636
+ <div style="font-weight: bold;">${language}:</div>
27637
+ <div style="display: flex; gap: 8px; align-items: center;">
27638
+ <button class="ai-apply-btn" data-full-code="${btoa(code)}" style="background: none; border: none; cursor: pointer; padding: 4px 8px; color: #000000; transition: opacity 0.2s;" title="Apply code">
27639
+ <i class="fa fa-refresh" style="font-size: 14px;"></i>
27640
+ </button>
27641
+ <button class="ai-copy-btn" data-full-code="${btoa(code)}" style="background: none; border: none; cursor: pointer; padding: 4px 8px; color: #000000; transition: opacity 0.2s;" title="Copy code">
27642
+ <i class="fa fa-clone" style="font-size: 14px;"></i>
27643
+ </button>
27644
+ </div>
27645
+ </div>
27646
+ <pre style="
27647
+ margin: 0;
27648
+ padding: 5px 0;
27649
+ background: #1e1e1e;
27650
+ color: #d4d4d4;
27651
+ border-radius: 8px;
27652
+ overflow: auto;
27653
+ max-height: 500px;
27654
+ white-space: pre;
27655
+ scrollbar-width: thin;
27656
+ scrollbar-color: #555 #2d2d2d;
27657
+ user-select: text;
27658
+ cursor: text;
27659
+ ">
27660
+ <code id="${codeId}"
27661
+ class="language-${language}"
27662
+ style="
27663
+ font-size: 12px !important;
27664
+ line-height: 1.45;
27665
+ font-family: 'JetBrains Mono', 'Fira Code', 'Courier New', monospace;
27666
+ display: block;
27667
+ white-space: pre !important;
27668
+ margin: 0 !important;
27669
+ padding: 0 12px !important;
27670
+ overflow-x: auto;
27671
+ min-width: 100%;
27672
+ box-sizing: border-box;
27673
+ tab-size: 2;
27674
+ user-select: text;
27675
+ ">
27676
+ ${highlightedCode}
27677
+ </code>
27678
+ </pre>
27679
+ </span>
27680
+ </div>
27681
+ `;
27682
+
27683
+ lastIndex = codeBlockRegex.lastIndex;
27684
+ }
27685
+
27686
+ // Text after last code block
27687
+ const textAfter = responseHtml.slice(lastIndex);
27688
+ if (textAfter.trim()) {
27689
+ const formattedText = convertMarkdownToHtml(textAfter);
27690
+ assistantMsgHtml += `
27691
+ <div class="ai-chat-msg ai-chat-assistant" style="text-align: left; margin: 8px 0;">
27692
+ <span style="color: #222; padding: 8px 12px; border-radius: 5px; display: inline-block; max-width: 100%;">${formattedText}</span>
27693
+ </div>
27694
+ `;
27695
+ }
27696
+
27697
+ if (!hasCode) {
27698
+ console.log("No code blocks detected in response.");
27699
+ const formattedText = convertMarkdownToHtml(responseHtml);
27700
+ assistantMsgHtml = `
27701
+ <div class="ai-chat-msg ai-chat-assistant" style="text-align: left; margin: 8px 0;">
27702
+ <span style="color: #222; padding: 8px 12px; border-radius: 5px; display: inline-block; max-width: 100%;">${formattedText}</span>
27703
+ </div>
27704
+ `;
27705
+ }
27706
+
27707
+ console.log("Appending assistant message HTML:", assistantMsgHtml);
27708
+ $chat.append(assistantMsgHtml);
27709
+
27710
+ // Auto-scroll to bottom after assistant message with 250ms delay
27711
+ setTimeout(() => {
27712
+ $chat.scrollTop($chat[0].scrollHeight);
27713
+ }, 250);
27714
+
27715
+ // Check if response was truncated
27716
+ if (res.finishReason === 'MAX_TOKENS') {
27717
+ const warningHtml = `
27718
+ <div style="background-color: #fff3cd; border: 1px solid #ffc107; color: #856404; padding: 12px; border-radius: 4px; margin: 8px 0; text-align: left;">
27719
+ <strong>⚠️ Response Truncated:</strong> The response was cut off due to token limit. Consider rephrasing your question or breaking it into smaller parts.
27720
+ </div>
27721
+ `;
27722
+ $chat.append(warningHtml);
27723
+
27724
+ // Auto-scroll again after warning
27725
+ $chat.scrollTop($chat[0].scrollHeight);
27726
+ }
27727
+ // Add event listeners for copy and apply buttons AFTER appending to DOM
27728
+ // Use event delegation to avoid duplicate listeners
27729
+ $chat.off('click', '.ai-copy-btn').on('click', '.ai-copy-btn', function() {
27730
+ const btn = $(this);
27731
+ const encodedCode = btn.data('fullCode');
27732
+ const fullCode = atob(encodedCode);
27733
+
27734
+ navigator.clipboard.writeText(fullCode).then(() => {
27735
+ const icon = btn.find('i');
27736
+ icon.removeClass('fa-clone').addClass('fa-check');
27737
+ setTimeout(() => icon.removeClass('fa-check').addClass('fa-clone'), 1000);
27738
+ }).catch(err => console.error('Copy failed:', err));
27739
+ });
27740
+
27741
+ // Add event listeners for apply button
27742
+ $chat.off('click', '.ai-apply-btn').on('click', '.ai-apply-btn', function() {
27743
+ const btn = $(this);
27744
+ const encodedCode = btn.data('fullCode');
27745
+ const fullCode = atob(encodedCode);
27746
+ applyCode(fullCode);
27747
+
27748
+ const icon = btn.find('i');
27749
+ icon.removeClass('fa-refresh').addClass('fa-check');
27750
+ setTimeout(() => icon.removeClass('fa-check').addClass('fa-refresh'), 1000);
27751
+ });
27752
+
27753
+ // Add assistant response to conversation history
27754
+ conversation.push({ role: 'assistant', content: responseHtml });
27755
+ } catch(err) {
27756
+ $chat.append(`<div style="color:red; text-align:left;">Error: ${err.message}</div>`);
27757
+
27758
+ // Auto-scroll on error
27759
+ $chat.scrollTop($chat[0].scrollHeight);
27760
+ }
27761
+ }
27762
+
27763
+ function initializeModelSelect() {
27764
+
27765
+ console.log("Initializing AI Assistant model select");
27766
+ const $select = $('#palette-aiassistant-model');
27767
+ $select.empty(); // Clear everything
27768
+
27769
+ const sections = getSettingsFromConfig();
27770
+
27771
+ if (sections.length === 0) {
27772
+ // No models defined → show placeholder
27773
+ $select.append(
27774
+ $('<option>', {
27775
+ value: '-',
27776
+ text: 'No values defined, configure first',
27777
+ disabled: true,
27778
+ selected: true
27779
+ })
27780
+ );
27781
+ } else {
27782
+ // Add each section as a selectable option
27783
+ $.each(sections, function(i, section) {
27784
+ console.log("Adding model option:", section);
27785
+ $select.append(
27786
+ $('<option>', {
27787
+ value: section,
27788
+ text: section
27789
+ })
27790
+ );
27791
+ });
27792
+ }
27793
+ }
27794
+
27795
+
27796
+ function setupAiAssistantFooterActions() {
27797
+ const $chat = $('#palette-aiassistant-chat');
27798
+ const $questionInput = $('#palette-aiassistant-question-input');
27799
+ const $newBtn = $('#palette-aiassistant-add-btn');
27800
+ const $settingsBtn = $('#palette-aiassistant-settings-btn');
27801
+ const $modelSelect = $('#palette-aiassistant-model');
27802
+
27803
+ // Handle "New" button - clear conversation and chat
27804
+ $newBtn.on('click', function() {
27805
+ conversation = []; // Clear conversation history
27806
+ $chat.empty(); // Clear chat display
27807
+ $questionInput.val(''); // Clear input field
27808
+ $questionInput.focus(); // Focus on input field
27809
+ console.log("New conversation started");
27810
+ });
27811
+
27812
+ $settingsBtn.on('click', (e) => {
27813
+ e.stopPropagation();
27814
+ RED.actions.invoke('core:settings:select-ai');
27815
+ });
27816
+
27817
+ // Handle textarea auto-expand on input
27818
+ $questionInput.on('input', function() {
27819
+ // Reset height to auto to get the correct scrollHeight
27820
+ this.style.height = 'auto';
27821
+
27822
+ // Calculate new height (line-height is 1.4 * font-size)
27823
+ // Assuming default font-size, each line is approximately 24px
27824
+ const newHeight = Math.min(this.scrollHeight, 112); // 112px = 5 lines * ~24px
27825
+ this.style.height = newHeight + 'px';
27826
+ });
27827
+
27828
+ // Allow pressing Enter to send message, Shift+Enter for new line
27829
+ $questionInput.on('keypress', function(e) {
27830
+ if (e.which === 13) { // Enter key
27831
+ if (e.shiftKey) {
27832
+ // Shift+Enter: Allow new line (let browser handle it naturally)
27833
+ return true;
27834
+ }
27835
+
27836
+ // Regular Enter: Send message
27837
+ const model = $modelSelect.val();
27838
+
27839
+ // Check if model is selected
27840
+ if (!model || model === '') {
27841
+ $chat.append(`
27842
+ <div style="background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 12px; border-radius: 4px; margin: 8px 0; text-align: left;">
27843
+ <strong>⚠️ Model Required:</strong> Please select an AI model from the dropdown before asking a question.
27844
+ </div>
27845
+ `);
27846
+ $modelSelect.focus();
27847
+ return false;
27848
+ }
27849
+
27850
+ const question = $questionInput.val().trim();
27851
+ if (question) {
27852
+ chatWithAi(conversation, question);
27853
+ $questionInput.val(''); // Clear textarea
27854
+ $questionInput.css('height', '48px'); // Reset height to single line
27855
+ $questionInput.focus();
27856
+ }
27857
+
27858
+ return false; // Prevent default Enter behavior
27859
+ }
27860
+ });
27861
+ }
27862
+
27863
+ function init() {
27864
+
27865
+ initializeModelSelect();
27866
+ setupAiAssistantFooterActions();
27867
+
27868
+ RED.events.on('settings:ai-config-changed', initializeModelSelect);
27869
+
27870
+ /* var def = RED.nodes.getType(nodeType);
27871
+ addNodeType(nodeType, def);
27872
+ if (def.onpaletteadd && typeof def.onpaletteadd === 'function') {
27873
+ def.onpaletteadd.call(def);
27874
+ }
27875
+ });*/
27876
+
27877
+ // $('#palette > .palette-spinner').show();
27878
+
27879
+ }
27880
+
27881
+
27882
+
27883
+ function refresh() {}
27884
+
27885
+ return {
27886
+ init: init,
27887
+ refresh: refresh
27888
+ };
27889
+ })();
27439
27890
  ;RED.palette.nodes = (function () {
27440
27891
  var exclusion = ['config', 'unknown', 'deprecated'];
27441
27892
  // var coreCategories = [
@@ -31157,6 +31608,120 @@ RED.editor = (function () {
31157
31608
  nodeInfoEditor = buildDescriptionForm(descriptionTab.content, node);
31158
31609
  }
31159
31610
 
31611
+ // ...inside showEditDialog, after Help tab and before Notes tab...
31612
+
31613
+ // AI tab
31614
+ let aiTab = {
31615
+ id: 'editor-tab-ai',
31616
+ label: 'AI',
31617
+ name: 'AI',
31618
+ content: $('<div>', {
31619
+ class: 'editor-tray-content',
31620
+ id: 'ai-tab',
31621
+ css: { position: 'relative', height: '100%' }
31622
+ })
31623
+ .appendTo(editorContent)
31624
+ .hide(),
31625
+ iconClass: 'fa fa-magic',
31626
+ };
31627
+
31628
+ // List of text items (history/messages)
31629
+ const aiList = $('<div>', {
31630
+ id: 'ai-list',
31631
+ css: {
31632
+ 'max-height': 'calc(100% - 120px)',
31633
+ 'overflow-y': 'auto',
31634
+ 'margin-bottom': '10px'
31635
+ }
31636
+ }).appendTo(aiTab.content);
31637
+
31638
+ // Text editor area
31639
+ const aiInputContainer = $('<div>', {
31640
+ css: {
31641
+ position: 'absolute',
31642
+ left: 0,
31643
+ right: 0,
31644
+ bottom: 0,
31645
+ padding: '10px',
31646
+ 'background': '#f9f9f9',
31647
+ 'box-shadow': '0 -1px 4px rgba(0,0,0,0.04)'
31648
+ }
31649
+ }).appendTo(aiTab.content);
31650
+
31651
+ const aiInput = $('<textarea>', {
31652
+ id: 'ai-input',
31653
+ rows: 3,
31654
+ css: {
31655
+ width: 'calc(100% - 110px)',
31656
+ resize: 'none',
31657
+ display: 'inline-block',
31658
+ verticalAlign: 'bottom'
31659
+ },
31660
+ placeholder: 'Type your AI prompt...'
31661
+ }).appendTo(aiInputContainer);
31662
+
31663
+ // Send button
31664
+ const aiSendBtn = $('<button>', {
31665
+ text: 'Send',
31666
+ class: 'editor-button primary',
31667
+ css: {
31668
+ float: 'right',
31669
+ marginLeft: '10px',
31670
+ width: '90px',
31671
+ height: '48px',
31672
+ position: 'relative',
31673
+ bottom: '0'
31674
+ }
31675
+ }).appendTo(aiInputContainer);
31676
+
31677
+ aiSendBtn.on('click', async function () {
31678
+ const val = aiInput.val().trim();
31679
+ if (val) {
31680
+ // Log the sent text to the console
31681
+ console.log('AI Tab Sent:', val);
31682
+
31683
+
31684
+ let res;
31685
+
31686
+ try {
31687
+ res = await window.__kumologica.libs.chatAi({conversation: [], question: val});
31688
+ console.log('AI Tab Response:', res);
31689
+ } catch (error) {
31690
+ console.log('AI Tab err:', error);
31691
+ res = error;
31692
+ }
31693
+
31694
+ // Add the original text to the list, aligned right
31695
+ $('<div>', {
31696
+ text: val,
31697
+ css: {
31698
+ padding: '6px 8px',
31699
+ margin: '2px 0',
31700
+ background: '#eaeaea',
31701
+ borderRadius: '4px',
31702
+ textAlign: 'right',
31703
+ display: 'flex',
31704
+ justifyContent: 'flex-end'
31705
+ }
31706
+ }).appendTo(aiList);
31707
+
31708
+ // Add the response text to the list, aligned left
31709
+ $('<div>', {
31710
+ text: 'Response to your text: ' + res,
31711
+ css: {
31712
+ padding: '6px 8px',
31713
+ margin: '2px 0',
31714
+ background: '#d0f5d8',
31715
+ borderRadius: '4px',
31716
+ textAlign: 'left'
31717
+ }
31718
+ }).appendTo(aiList);
31719
+
31720
+ aiInput.val('');
31721
+ }
31722
+ });
31723
+ // editorTabs.addTab(aiTab);
31724
+
31160
31725
  var appearanceTab = {
31161
31726
  id: 'editor-tab-appearance',
31162
31727
  label: 'Appearance',
@@ -31407,7 +31972,7 @@ RED.editor = (function () {
31407
31972
  '<option value="' +
31408
31973
  ws.id +
31409
31974
  '"' +
31410
- (ws.id == editing_config_node.z ? ' selected' : '') +
31975
+ (ws.id == editing_config_node.z ? ' selected' : '') +
31411
31976
  '></option>'
31412
31977
  )
31413
31978
  .text(workspaceLabel)
@@ -33814,10 +34379,12 @@ RED.eventLog = (function() {
33814
34379
  $('#optionSettings').removeClass('node-property-selected');
33815
34380
  $('#optionHelp').removeClass('node-property-selected');
33816
34381
  $('#optionDocumentation').removeClass('node-property-selected');
34382
+ $('#optionAi').removeClass('node-property-selected');
33817
34383
 
33818
34384
  $('#properties-tab').hide();
33819
34385
  $('#help-tab').hide();
33820
34386
  $('#documentation-tab').hide();
34387
+ $('#ai-tab').hide();
33821
34388
 
33822
34389
  domEl.addClass('node-property-selected');
33823
34390
 
@@ -33831,6 +34398,9 @@ RED.eventLog = (function() {
33831
34398
  case 'notes':
33832
34399
  $('#documentation-tab').show();
33833
34400
  break;
34401
+ case 'ai':
34402
+ $('#ai-tab').show();
34403
+ break;
33834
34404
  }
33835
34405
  }
33836
34406
 
@@ -33853,6 +34423,7 @@ RED.eventLog = (function() {
33853
34423
  <div id="optionSettings" class="node-property-option node-property-selected">Settings</div>
33854
34424
  <div id="optionHelp" class="node-property-option">Help</div>
33855
34425
  <div id="optionDocumentation" class="node-property-option">Notes</div>
34426
+ <!--<div id="optionAi" class="node-property-option">AI</div>-->
33856
34427
  </div>
33857
34428
  `).appendTo(el);
33858
34429
  }
@@ -34069,6 +34640,10 @@ RED.eventLog = (function() {
34069
34640
  let $this = $(e.currentTarget);
34070
34641
  selectOption($this, 'help');
34071
34642
  });
34643
+ $('#optionAi').click((e) => {
34644
+ let $this = $(e.currentTarget);
34645
+ selectOption($this, 'ai');
34646
+ });
34072
34647
  $('#optionDocumentation').click((e) => {
34073
34648
  let $this = $(e.currentTarget);
34074
34649
  selectOption($this, 'notes');
@@ -36593,11 +37168,13 @@ RED.notifications = (function() {
36593
37168
  ;RED.uiSettings = (function () {
36594
37169
  let testConfigStore;
36595
37170
  let cloudConfigStore = window.__kumologica.settings.cloudConfigStore;
37171
+ let aiConfigStore = window.__kumologica.settings.aiConfigStore;
36596
37172
  let networkConfigStore = window.__kumologica.settings.networkConfigStore;
36597
37173
  let shell = window.__kumologica.electron.shell;
36598
37174
  let dialog = null;
36599
37175
  let visible = false;
36600
37176
  let cmInstanceCloud = null;
37177
+ let cmInstanceAI = null;
36601
37178
  let cmInstanceEnvvars = null;
36602
37179
  let totalHeightAvailable;
36603
37180
 
@@ -36640,6 +37217,7 @@ RED.notifications = (function() {
36640
37217
  },
36641
37218
  onSave: () => {
36642
37219
  cloudConfigStore.writeCloudConfigFile(cmInstanceCloud.getValue());
37220
+ console.log("Emitting cloud-config-changed event");
36643
37221
  RED.events.emit("settings:cloud-config-changed");
36644
37222
  },
36645
37223
  },
@@ -36727,6 +37305,42 @@ RED.notifications = (function() {
36727
37305
  RED.events.emit("settings:environment-variables-changed");
36728
37306
  },
36729
37307
  },
37308
+ {
37309
+ selected: false,
37310
+ id: "ui-settings-ai",
37311
+ label: "AI Settings",
37312
+ body: {
37313
+ title: "AI Settings",
37314
+ subtitle: `
37315
+ Configure all of your ai providers and its settings that can be used by Kumologica Designer AI assistant for flow creation and node specific settings.
37316
+ <a href="https://docs.kumologica.com/docs/guide/AI.html" target="_blank">Learn more</a>`,
37317
+ html: `
37318
+ <div>
37319
+ <div id="aifileLocationPath">
37320
+ <span id="aisettingFilePath">${aiConfigStore.getAiConfigFileFullPath()}</span>
37321
+ </div>
37322
+ <textarea id="ai-settings-editor" rows="20">
37323
+ </textarea>
37324
+ </div>`,
37325
+ },
37326
+ onInit: () => {
37327
+ // load content of config credentials file: ~/.kumologica/ai
37328
+ let aiConfigContent = aiConfigStore.readAiConfigFile();
37329
+ cmInstanceAI = initEditor(
37330
+ "ai-settings-editor",
37331
+ aiConfigContent
37332
+ );
37333
+ },
37334
+ onSelect: () => {
37335
+ cmInstanceAI.refresh();
37336
+ },
37337
+ onSave: () => {
37338
+ aiConfigStore.writeAiConfigFile(cmInstanceAI.getValue());
37339
+
37340
+ console.log("Emitting ai-config-changed event");
37341
+ RED.events.emit("settings:ai-config-changed");
37342
+ },
37343
+ },
36730
37344
  ];
36731
37345
  }
36732
37346
  return screen;
@@ -36742,12 +37356,13 @@ RED.notifications = (function() {
36742
37356
  }).appendTo("#main-container");
36743
37357
 
36744
37358
  let dialogContainer = $(
36745
- `<div id="ui-settings-container" class="ui-settings-conatiner" style="display:flex; height: 100%" </div>`
37359
+ `<div id="ui-settings-container" class="ui-settings-container" style="display:flex; height: 100%" </div>`
36746
37360
  ).appendTo(dialog);
37361
+
36747
37362
  // Programmatically calculate the height of the ui-settings window
36748
37363
  totalHeightAvailable = $("#main-container").height();
36749
- let offset = 74;
36750
- $("#ui-settings").height(totalHeightAvailable - 200);
37364
+
37365
+ // $("#ui-settings").height(totalHeightAvailable - 200);
36751
37366
 
36752
37367
  // Left pannel of settings
36753
37368
  let optionsLeft = $(`<div id="ui-settings-left"></div>`).appendTo(
@@ -36815,6 +37430,7 @@ RED.notifications = (function() {
36815
37430
  $(`#${option.id}-body`).show();
36816
37431
  option.onSelect();
36817
37432
  });
37433
+
36818
37434
  // Specific functionality
36819
37435
  option.onInit();
36820
37436
 
@@ -37007,7 +37623,7 @@ RED.notifications = (function() {
37007
37623
  //console.log(`lineCount: ${cmInstance.lineCount()}`)
37008
37624
  // Set the cursor at the end of existing content
37009
37625
  cmInstance.setCursor(cmInstance.lineCount(), 0);
37010
- let codeMirrorHeight = totalHeightAvailable - 440;
37626
+ let codeMirrorHeight = totalHeightAvailable - 340;
37011
37627
 
37012
37628
  cmInstance.setSize(null, codeMirrorHeight);
37013
37629
  // cmInstance.refresh();
@@ -37053,7 +37669,10 @@ RED.notifications = (function() {
37053
37669
  show();
37054
37670
  $("#ui-settings-envvars").click();
37055
37671
  }
37056
-
37672
+ function showAi() {
37673
+ show();
37674
+ $("#ui-settings-ai").click();
37675
+ }
37057
37676
  function hide() {
37058
37677
  if (visible) {
37059
37678
  $("#main-container").off("click");
@@ -37095,6 +37714,7 @@ RED.notifications = (function() {
37095
37714
  RED.actions.add("core:settings:open", show);
37096
37715
  RED.actions.add("core:settings:close", hide);
37097
37716
  RED.actions.add("core:settings:select-environments", showEnvironments);
37717
+ RED.actions.add("core:settings:select-ai", showAi);
37098
37718
  }
37099
37719
 
37100
37720
  return {