machinaos 0.0.60 → 0.0.61

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.
@@ -513,7 +513,7 @@ END:VCARD`,description:"vCard 3.0 format string (optional if phone provided)",di
513
513
  <circle fill="#ff5555" cx="19" cy="5" r="4"/>
514
514
  <circle fill="#fff" cx="19" cy="5" r="2"/>
515
515
  </svg>
516
- `,L5=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,i8e=L5(o8e),l8e=L5(sD),s8e=L5(a8e),c8e={read:sD},u8e=[{name:"Gmail",value:"gmail"},{name:"Outlook / Office 365",value:"outlook"},{name:"Yahoo Mail",value:"yahoo"},{name:"iCloud Mail",value:"icloud"},{name:"ProtonMail (Bridge)",value:"protonmail"},{name:"Fastmail",value:"fastmail"},{name:"Custom / Self-hosted",value:"custom"}],Fx={displayName:"Provider",name:"provider",type:"options",options:u8e,default:"gmail",description:"Email provider"},d8e={emailSend:{displayName:"Email Send",name:"emailSend",icon:i8e,group:["email","tool"],version:1,subtitle:"Send Email via SMTP",description:"Send email via Himalaya SMTP. Supports Gmail, Outlook, Yahoo, iCloud, ProtonMail, Fastmail, or custom.",defaults:{name:"Email Send",color:Un.blue},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Send result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[Fx,{displayName:"To",name:"to",type:"string",default:"",required:!0,placeholder:"recipient@example.com",description:"Recipients (comma-separated)"},{displayName:"Subject",name:"subject",type:"string",default:"",required:!0,placeholder:"Email subject"},{displayName:"Body",name:"body",type:"string",default:"",required:!0,typeOptions:{rows:6},placeholder:"Email body..."},{displayName:"CC",name:"cc",type:"string",default:"",placeholder:"cc@example.com"},{displayName:"BCC",name:"bcc",type:"string",default:"",placeholder:"bcc@example.com"},{displayName:"Body Type",name:"body_type",type:"options",options:[{name:"Plain Text",value:"text"},{name:"HTML",value:"html"}],default:"text"}]},emailRead:{displayName:"Email Read",name:"emailRead",icon:l8e,group:["email","tool"],version:1,subtitle:"Read & Manage via IMAP",description:"List, search, read, move, delete, or flag emails via Himalaya IMAP.",defaults:{name:"Email Read",color:Un.blue},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Send result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[Fx,{displayName:"Operation",name:"operation",type:"options",required:!0,default:"list",options:[{name:"List Envelopes",value:"list"},{name:"Search Emails",value:"search"},{name:"Read Message",value:"read"},{name:"List Folders",value:"folders"},{name:"Move Message",value:"move"},{name:"Delete Message",value:"delete"},{name:"Flag Message",value:"flag"}]},{displayName:"Folder",name:"folder",type:"string",default:"INBOX",displayOptions:{show:{operation:["list","search","read","move","delete","flag"]}}},{displayName:"Query",name:"query",type:"string",default:"",required:!0,placeholder:"from:john subject:meeting",displayOptions:{show:{operation:["search"]}}},{displayName:"Message ID",name:"message_id",type:"string",default:"",required:!0,displayOptions:{show:{operation:["read","move","delete","flag"]}}},{displayName:"Target Folder",name:"target_folder",type:"string",default:"",required:!0,placeholder:"Archive",displayOptions:{show:{operation:["move"]}}},{displayName:"Flag",name:"flag",type:"options",default:"Seen",options:[{name:"Seen",value:"Seen"},{name:"Answered",value:"Answered"},{name:"Flagged",value:"Flagged"},{name:"Draft",value:"Draft"},{name:"Deleted",value:"Deleted"}],displayOptions:{show:{operation:["flag"]}}},{displayName:"Flag Action",name:"flag_action",type:"options",default:"add",options:[{name:"Add",value:"add"},{name:"Remove",value:"remove"}],displayOptions:{show:{operation:["flag"]}}},{displayName:"Page",name:"page",type:"number",default:1,typeOptions:{minValue:1},displayOptions:{show:{operation:["list"]}}},{displayName:"Page Size",name:"page_size",type:"number",default:20,typeOptions:{minValue:1,maxValue:100},displayOptions:{show:{operation:["list"]}}}]},emailReceive:{displayName:"Email Receive",name:"emailReceive",icon:s8e,group:["email","trigger"],version:1,subtitle:"On Email Received",description:"Trigger workflow when new email arrives. Polls IMAP via Himalaya.",defaults:{name:"Email Receive",color:Un.blue},inputs:[],outputs:[{name:"main",displayName:"Email",type:"main",description:"message_id, from, to, subject, date, body, folder"}],properties:[Fx,{displayName:"Folder",name:"folder",type:"string",default:"INBOX"},{displayName:"Poll Interval (seconds)",name:"poll_interval",type:"number",default:60,typeOptions:{minValue:30,maxValue:3600}},{displayName:"Filter Query",name:"filter_query",type:"string",default:"",placeholder:"from:important@company.com"},{displayName:"Mark as Read",name:"mark_as_read",type:"boolean",default:!1}]}},f8e=["emailSend","emailRead","emailReceive"],wr={...rCe,...oCe,...BP,...F6e,...H6e,...V6e,...U6e,...Z6e,...tCe,...aCe,...iCe,...sCe,...cCe,...Dm,...uCe,...hCe,...wCe,..._Ce,...jCe,...GCe,...KCe,...QCe,...t8e,...n8e,...d8e};[...hs];const Pj=e=>{let t;const n=new Set,r=(f,p)=>{const m=typeof f=="function"?f(t):f;if(!Object.is(m,t)){const y=t;t=p??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(v=>v(t,y))}},o=()=>t,s={setState:r,getState:o,getInitialState:()=>d,subscribe:f=>(n.add(f),()=>n.delete(f))},d=t=e(r,o,s);return s},p8e=(e=>e?Pj(e):Pj),m8e=e=>e;function g8e(e,t=m8e){const n=Y.useSyncExternalStore(e.subscribe,Y.useCallback(()=>t(e.getState()),[e,t]),Y.useCallback(()=>t(e.getInitialState()),[e,t]));return Y.useDebugValue(n),n}const Dj=e=>{const t=p8e(e),n=r=>g8e(t,r);return Object.assign(n,t),n},h8e=(e=>e?Dj(e):Dj),cD=()=>`workflow-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Lj=e=>e.map(t=>({...t,selected:void 0,dragging:void 0})),Fj=e=>e.map(t=>({...t,selected:void 0})),y8e=(e,t=20)=>({x:Math.round(e.x/t)*t,y:Math.round(e.y/t)*t}),v8e=e=>e===0?{x:100,y:200}:{x:0,y:0};function _y(e){const t=[];return(!e.id||typeof e.id!="string")&&t.push("Workflow must have a valid id"),(!e.name||typeof e.name!="string")&&t.push("Workflow must have a valid name"),Array.isArray(e.nodes)||t.push("Workflow must have a nodes array"),Array.isArray(e.edges)||t.push("Workflow must have an edges array"),e.createdAt||t.push("Workflow must have a createdAt timestamp"),e.lastModified||t.push("Workflow must have a lastModified timestamp"),e.nodes?.forEach((n,r)=>{n.id||t.push(`Node at index ${r} must have an id`),n.type||t.push(`Node at index ${r} must have a type`),(!n.position||typeof n.position.x!="number"||typeof n.position.y!="number")&&t.push(`Node at index ${r} must have a valid position with x and y coordinates`)}),e.edges?.forEach((n,r)=>{n.id||t.push(`Edge at index ${r} must have an id`),n.source||t.push(`Edge at index ${r} must have a source node`),n.target||t.push(`Edge at index ${r} must have a target node`);const o=e.nodes?.some(i=>i.id===n.source),a=e.nodes?.some(i=>i.id===n.target);o||t.push(`Edge ${n.id} references non-existent source node: ${n.source}`),a||t.push(`Edge ${n.id} references non-existent target node: ${n.target}`)}),{valid:t.length===0,errors:t}}function uD(e){return JSON.stringify(e,null,2)}function dD(e){try{const t=JSON.parse(e);return t.createdAt&&(t.createdAt=new Date(t.createdAt)),t.lastModified&&(t.lastModified=new Date(t.lastModified)),t}catch(t){throw new Error(`Failed to parse workflow JSON: ${t}`)}}const b8e=new Set(["apiKey","api_key","apikey","accessToken","access_token","refreshToken","refresh_token","secret","password","passwd","client_id","client_secret","clientId","clientSecret","token","bearerToken","bearer_token","privateKey","private_key","encryptionKey","encryption_key","oauthToken","oauth_token"]),x8e=new Set(["maxTokens","max_tokens","budgetTokens","budget_tokens","page_token","pageToken","nextPageToken","next_page_token","tokenCount","token_count","totalTokens","total_tokens","inputTokens","input_tokens","outputTokens","output_tokens"]),S8e=["api_key","apikey","secret","password","private_key","privatekey","accesstoken","access_token","refreshtoken","refresh_token","bearertoken","bearer_token","oauthtoken","oauth_token","authtoken","auth_token"];function w8e(e){if(x8e.has(e))return!1;if(b8e.has(e))return!0;const t=e.toLowerCase();return S8e.some(n=>t.includes(n))}const C8e=new Set(["memoryContent","token_usage","execution_time","last_execution","last_result"]);function fD(e){const t={};for(const[n,r]of Object.entries(e))if(!w8e(n)&&!C8e.has(n))if(r&&typeof r=="object"&&!Array.isArray(r)){const o=fD(r);Object.keys(o).length>0&&(t[n]=o)}else t[n]=r;return t}const pD="0.0.60",E8e=new Set(["label","disabled","condition"]);function b1(e){return e.map(t=>({...t,data:Object.fromEntries(Object.entries(t.data||{}).filter(([n])=>E8e.has(n)))}))}function mD(e){if(!e||Object.keys(e).length===0)return;const t={};for(const[n,r]of Object.entries(e)){const o=fD(r);Object.keys(o).length>0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}function $8e(e,t){const n=_y(e);if(!n.valid)throw console.error("Workflow validation errors:",n.errors),new Error(`Cannot export invalid workflow: ${n.errors.join(", ")}`);const r={...e,nodes:b1(e.nodes),createdAt:e.createdAt.toISOString(),lastModified:e.lastModified.toISOString(),version:pD},o=mD(t);o&&(r.nodeParameters=o);const a=uD(r),i=new Blob([a],{type:"application/json"}),s=URL.createObjectURL(i),d=document.createElement("a");d.href=s,d.download=`${e.name||"workflow"}_${e.id}.json`,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(s)}function O8e(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{try{const a=o.target?.result,s=JSON.parse(a).nodeParameters||void 0,d=dD(a),f=_y(d);if(!f.valid){n(new Error(`Invalid workflow JSON: ${f.errors.join(", ")}`));return}t({...d,nodeParameters:s})}catch(a){n(a)}},r.onerror=()=>{n(new Error("Failed to read file"))},r.readAsText(e)})}function _8e(e,t){const n=_y(e);if(!n.valid)throw new Error(`Cannot export invalid workflow: ${n.errors.join(", ")}`);const r={...e,nodes:b1(e.nodes),createdAt:e.createdAt.toISOString(),lastModified:e.lastModified.toISOString(),version:pD},o=mD(t);return o&&(r.nodeParameters=o),uD(r)}function j8e(e){const n=JSON.parse(e).nodeParameters||void 0,r=dD(e),o=_y(r);if(!o.valid)throw new Error(`Invalid workflow JSON: ${o.errors.join(", ")}`);return{...r,nodeParameters:n}}const Qh=()=>`${$c.PYTHON_BASE_URL}/api/database`,Zf={async saveWorkflow(e,t,n){try{return(await(await fetch(`${Qh()}/workflows`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workflow_id:e,name:t,data:n})})).json()).success}catch(r){return console.error("Failed to save workflow:",r),!1}},async getWorkflow(e){try{const n=await(await fetch(`${Qh()}/workflows/${e}`,{credentials:"include"})).json();return n.success&&n.workflow?n.workflow:null}catch(t){return console.error("Failed to get workflow:",t),null}},async getAllWorkflows(){try{const t=await(await fetch(`${Qh()}/workflows`,{credentials:"include"})).json();return t.success&&t.workflows?t.workflows:[]}catch(e){return console.error("Failed to get workflows:",e),[]}},async deleteWorkflow(e){try{return(await(await fetch(`${Qh()}/workflows/${e}`,{method:"DELETE",credentials:"include"})).json()).success}catch(t){return console.error("Failed to delete workflow:",t),!1}}},Bj=()=>({id:cD(),name:ht.constants.defaultWorkflowName,nodes:[],edges:[],createdAt:new Date,lastModified:new Date}),$u=()=>({selectedNodeId:null,executedNodes:[],executionOrder:[],isExecuting:!1,viewport:void 0}),Hj=e=>e.map(t=>t.type==="googleChatModel"?{...t,type:"geminiChatModel"}:t),Go={sidebarVisible:"ui_sidebar_visible",componentPaletteVisible:"ui_component_palette_visible",consolePanelVisible:"ui_console_panel_visible",proMode:"ui_pro_mode"},Zh=(e,t)=>{try{const n=localStorage.getItem(e);if(n!==null)return n==="true"}catch{}return t},wi=(e,t)=>{try{localStorage.setItem(e,String(t))}catch{}},Sr=h8e((e,t)=>({currentWorkflow:null,hasUnsavedChanges:!1,workflowUIStates:{},selectedNode:null,sidebarVisible:Zh(Go.sidebarVisible,!0),componentPaletteVisible:Zh(Go.componentPaletteVisible,!0),consolePanelVisible:Zh(Go.consolePanelVisible,!1),proMode:Zh(Go.proMode,!1),renamingNodeId:null,savedWorkflows:[],setCurrentWorkflow:n=>{e({currentWorkflow:n,hasUnsavedChanges:!1})},updateWorkflow:n=>{const r=t().currentWorkflow;if(!r)return;const o={...r,...n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},createNewWorkflow:()=>{const n=Bj();e({currentWorkflow:n,hasUnsavedChanges:!1,selectedNode:null})},saveWorkflow:async()=>{const{currentWorkflow:n,savedWorkflows:r}=t();if(!n)return;const o={...n,lastModified:new Date};if(!await Zf.saveWorkflow(o.id,o.name,{nodes:b1(o.nodes),edges:o.edges})){console.error("Failed to save workflow to database");return}const i=r.findIndex(f=>f.id===o.id),s={id:o.id,name:o.name,createdAt:o.createdAt,lastModified:o.lastModified,nodeCount:o.nodes.length};let d;i>=0?(d=[...r],d[i]=s):d=[s,...r],e({currentWorkflow:o,savedWorkflows:d,hasUnsavedChanges:!1})},loadWorkflow:async n=>{const r=await Zf.getWorkflow(n);if(r){const o=Hj(r.data?.nodes||[]),a=r.data?.edges||[],i={id:r.id,name:r.name,nodes:o,edges:a,createdAt:new Date(r.createdAt),lastModified:new Date(r.lastModified)};e({currentWorkflow:i,hasUnsavedChanges:!1,selectedNode:null})}},loadSavedWorkflows:async()=>{const r=(await Zf.getAllWorkflows()).map(a=>({id:a.id,name:a.name,nodeCount:a.nodeCount,createdAt:new Date(a.createdAt),lastModified:new Date(a.lastModified)}));e({savedWorkflows:r});const{currentWorkflow:o}=t();if(!o&&r.length>0){const i=[...r].sort((s,d)=>d.lastModified.getTime()-s.lastModified.getTime())[0];await t().loadWorkflow(i.id)}},deleteWorkflow:async n=>{const{currentWorkflow:r,savedWorkflows:o}=t();if(!await Zf.deleteWorkflow(n))return console.error("Failed to delete workflow from database"),!1;const i=o.filter(s=>s.id!==n);if(r?.id===n){const s=Bj();e({currentWorkflow:s,savedWorkflows:i,hasUnsavedChanges:!1,selectedNode:null})}else e({savedWorkflows:i});return!0},migrateCurrentWorkflow:async()=>{const{currentWorkflow:n}=t();if(!n||!n.nodes)return;const r=Hj(n.nodes);if(r.some((a,i)=>a.type!==n.nodes[i]?.type)){const a={...n,nodes:r};await Zf.saveWorkflow(a.id,a.name,{nodes:b1(a.nodes),edges:a.edges}),e({currentWorkflow:a,hasUnsavedChanges:!1})}},setSelectedNode:n=>{e({selectedNode:n})},toggleSidebar:()=>{e(n=>{const r=!n.sidebarVisible;return wi(Go.sidebarVisible,r),{sidebarVisible:r}})},toggleComponentPalette:()=>{e(n=>{const r=!n.componentPaletteVisible;return wi(Go.componentPaletteVisible,r),{componentPaletteVisible:r}})},toggleProMode:()=>{e(n=>{const r=!n.proMode;return wi(Go.proMode,r),{proMode:r}})},setRenamingNodeId:n=>{e({renamingNodeId:n})},setSidebarVisible:n=>{wi(Go.sidebarVisible,n),e({sidebarVisible:n})},setComponentPaletteVisible:n=>{wi(Go.componentPaletteVisible,n),e({componentPaletteVisible:n})},setConsolePanelVisible:n=>{wi(Go.consolePanelVisible,n),e({consolePanelVisible:n})},toggleConsolePanelVisible:()=>{e(n=>{const r=!n.consolePanelVisible;return wi(Go.consolePanelVisible,r),{consolePanelVisible:r}})},applyUIDefaults:n=>{const r={};n.sidebarDefaultOpen!==void 0&&(r.sidebarVisible=n.sidebarDefaultOpen,wi(Go.sidebarVisible,n.sidebarDefaultOpen)),n.componentPaletteDefaultOpen!==void 0&&(r.componentPaletteVisible=n.componentPaletteDefaultOpen,wi(Go.componentPaletteVisible,n.componentPaletteDefaultOpen)),n.consolePanelDefaultOpen!==void 0&&(r.consolePanelVisible=n.consolePanelDefaultOpen,wi(Go.consolePanelVisible,n.consolePanelDefaultOpen)),Object.keys(r).length>0&&e(r)},getWorkflowUIState:n=>{const{workflowUIStates:r}=t();return r[n]||$u()},setWorkflowExecuting:(n,r)=>{e(o=>{const a=o.workflowUIStates[n];return{workflowUIStates:{...o.workflowUIStates,[n]:{...a||$u(),isExecuting:r}}}})},setWorkflowExecutedNodes:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),executedNodes:r}}}))},setWorkflowExecutionOrder:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),executionOrder:r}}}))},setWorkflowViewport:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),viewport:r}}}))},clearWorkflowExecutionState:n=>{e(r=>({workflowUIStates:{...r.workflowUIStates,[n]:{...r.workflowUIStates[n]||$u(),isExecuting:!1,executedNodes:[],executionOrder:[]}}}))},updateNodeData:(n,r)=>{const{currentWorkflow:o,selectedNode:a}=t();if(!o)return;const i=o.nodes.map(d=>d.id===n?{...d,data:{...d.data,...r}}:d),s={...o,nodes:i,lastModified:new Date};e({currentWorkflow:s,hasUnsavedChanges:!0,selectedNode:a?.id===n?{...a,data:{...a.data,...r}}:a})},updateNodes:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,nodes:n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},updateEdges:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,edges:n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},addNode:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,nodes:[...r.nodes,n],lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},removeNodes:n=>{const{currentWorkflow:r}=t();if(!r)return;const o=r.nodes.filter(s=>!n.includes(s.id)),a=r.edges.filter(s=>!n.includes(s.source)&&!n.includes(s.target)),i={...r,nodes:o,edges:a,lastModified:new Date};e({currentWorkflow:i,hasUnsavedChanges:!0,selectedNode:n.includes(t().selectedNode?.id||"")?null:t().selectedNode})},removeEdges:n=>{const{currentWorkflow:r}=t();if(!r)return;const o=r.edges.filter(i=>!n.includes(i.id)),a={...r,edges:o,lastModified:new Date};e({currentWorkflow:a,hasUnsavedChanges:!0})},exportWorkflowToJSON:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");return _8e(r,n)},exportWorkflowToFile:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");$8e(r,n)},importWorkflowFromJSON:n=>{const r=j8e(n);return e({currentWorkflow:r,hasUnsavedChanges:!0}),r}})),gD=u.createContext(void 0),k8e=({children:e})=>{const[t,n]=u.useState(()=>{const o=localStorage.getItem("darkMode");return o===null?!0:o==="true"});u.useEffect(()=>{localStorage.setItem("darkMode",t.toString()),t?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[t]);const r=()=>{n(o=>!o)};return g.jsx(gD.Provider,{value:{isDarkMode:t,toggleTheme:r},children:e})},mg=()=>{const e=u.useContext(gD);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e},_n=()=>{const{isDarkMode:e}=mg();return u.useMemo(()=>({...ht,colors:e?Kr:ga,isDarkMode:e}),[e])},hD=u.createContext(void 0),Jh=()=>`${$c.PYTHON_BASE_URL}/api/auth`,N8e=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(!0),[a,i]=u.useState("single"),[s,d]=u.useState(!1),[f,p]=u.useState(null),m=u.useCallback(async(x=0)=>{try{const O=await(await fetch(`${Jh()}/status`,{credentials:"include"})).json();if(O.auth_enabled===!1){n({id:0,email:"anonymous",display_name:"Anonymous",is_owner:!0}),o(!1),p(null);return}i(O.auth_mode),d(O.can_register),O.authenticated&&O.user?n(O.user):n(null),p(null),o(!1)}catch($){if(console.error(`Failed to check auth status (attempt ${x+1}/6):`,$),x<5){const O=1e3*Math.pow(2,x);console.log(`Retrying in ${O}ms...`),setTimeout(()=>m(x+1),O)}else n(null),p("Failed to connect to server"),o(!1)}},[]);u.useEffect(()=>{m()},[m]);const y=u.useCallback(async(x,C)=>{p(null),o(!0);try{const E=await fetch(`${Jh()}/login`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C})}),$=await E.json();return E.ok?$.success&&$.user?(n($.user),o(!1),!0):(p("Login failed"),o(!1),!1):(p($.detail||"Login failed"),o(!1),!1)}catch(E){return console.error("Login error:",E),p("Failed to connect to server"),o(!1),!1}},[]),v=u.useCallback(async(x,C,E)=>{p(null),o(!0);try{const $=await fetch(`${Jh()}/register`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C,display_name:E})}),O=await $.json();return $.ok?O.success&&O.user?(n(O.user),d(!1),o(!1),!0):(p("Registration failed"),o(!1),!1):(p(O.detail||"Registration failed"),o(!1),!1)}catch($){return console.error("Register error:",$),p("Failed to connect to server"),o(!1),!1}},[]),w=u.useCallback(async()=>{try{await fetch(`${Jh()}/logout`,{method:"POST",credentials:"include"})}catch(x){console.error("Logout error:",x)}finally{n(null),await m()}},[m]),b={user:t,isAuthenticated:t!==null,isLoading:r,authMode:a,canRegister:s,error:f,login:y,register:v,logout:w,checkAuth:m};return g.jsx(hD.Provider,{value:b,children:e})},jy=()=>{const e=u.useContext(hD);if(e===void 0)throw new Error("useAuth must be used within an AuthProvider");return e},Wj=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,M8e=3e4,T8e=["whatsappReceive","webhookTrigger","cronScheduler","chatTrigger","telegramReceive"],R8e=["aiAgent","chatAgent","rlm_agent","android_agent","coding_agent","web_agent","task_agent","social_agent","travel_agent","tool_agent","productivity_agent","payments_agent","consumer_agent","autonomous_agent","orchestrator_agent","ai_employee","deep_agent"],Vj={connected:!1,paired:!1,device_id:null,device_name:null,connected_devices:[],connection_type:null,qr_data:null,session_token:null},Uj={executing:!1,current_node:null},qj={isRunning:!1,activeRuns:0,status:"idle"},A8e={locked:!1,workflow_id:null,locked_at:null,reason:null},Gj={connected:!1,has_session:!1,running:!1,pairing:!1},I8e={connected:!1,username:null,user_id:null},z8e={connected:!1,email:null},P8e={connected:!1,bot_username:null,bot_name:null,bot_id:null,owner_chat_id:null},yD=u.createContext(null),D8e=()=>{const e=$c.PYTHON_BASE_URL;if(!e)return`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws/status`;const t=e.startsWith("https")?"wss":"ws";return`${e.replace(/^https?/,t)}/ws/status`},L8e=100,F8e=({children:e})=>{const{isAuthenticated:t,isLoading:n}=jy(),o=Sr(de=>de.currentWorkflow)?.id,[a,i]=u.useState(!1),[s,d]=u.useState(!1),[f,p]=u.useState(Vj),[m,y]=u.useState(Gj),[v,w]=u.useState(I8e),[b,x]=u.useState(z8e),[C,E]=u.useState(P8e),[$,O]=u.useState([]),[_,j]=u.useState(null),[N,A]=u.useState({}),[I,R]=u.useState([]),[B,z]=u.useState([]),[L,T]=u.useState([]),[F,P]=u.useState({}),[H,D]=u.useState({}),[q,W]=u.useState({}),[U,G]=u.useState(Uj),[V,X]=u.useState(qj),[Q,J]=u.useState(A8e),[te,ae]=u.useState({}),ee=u.useRef(null),ve=u.useRef(null),pe=u.useRef(null),fe=u.useRef(new Map),Ce=u.useRef(o);u.useEffect(()=>{const de=Ce.current;Ce.current=o,de&&o&&de!==o&&ee.current?.readyState===WebSocket.OPEN&&(async()=>{try{const Me=Wj(),se=await new Promise((ct,Nt)=>{const et=setTimeout(()=>Nt(new Error("Timeout")),5e3),gt=Ve=>{try{const Et=JSON.parse(Ve.data);Et.request_id===Me&&(clearTimeout(et),ee.current?.removeEventListener("message",gt),ct(Et))}catch{}};ee.current?.addEventListener("message",gt),ee.current?.send(JSON.stringify({type:"get_deployment_status",request_id:Me,workflow_id:o}))}),Ne=se.is_running||!1;X({isRunning:Ne,activeRuns:se.active_runs||0,status:Ne?"running":"idle",workflow_id:se.workflow_id||null});const{setWorkflowExecuting:ze}=Sr.getState();ze(o,Ne),J({locked:Ne,workflow_id:Ne?o:null,locked_at:Ne?Date.now():null,reason:Ne?"Workflow is running":null})}catch(Me){console.error("[WebSocket] Failed to fetch deployment status:",Me)}})()},[o]);const $e=u.useCallback(de=>{try{const ce=JSON.parse(de.data),{type:Me,data:se,node_id:Ne,name:ze,value:ct,output:Nt,variables:et,request_id:gt}=ce;if(gt&&fe.current.has(gt)){const Ve=fe.current.get(gt);Ve.timeout&&clearTimeout(Ve.timeout),fe.current.delete(gt),Ve.resolve(ce);return}switch(Me){case"initial_status":case"full_status":if(se){if(se.android&&p(se.android),se.whatsapp&&y(se.whatsapp),se.twitter&&w(se.twitter),se.google&&x(se.google),se.telegram&&E(se.telegram),se.api_keys&&A(se.api_keys),se.nodes){const Ve={};for(const[Et,Gt]of Object.entries(se.nodes)){const Ke=Gt,Ze=Ke?.workflow_id||"unknown";Ve[Ze]||(Ve[Ze]={}),Ve[Ze][Et]=Ke}P(Et=>({...Et,...Ve}))}if(se.node_parameters&&D(se.node_parameters),se.variables){const Ve={};for(const[Et,Gt]of Object.entries(se.variables)){const Ke=Gt?.workflow_id||"unknown";Ve[Ke]||(Ve[Ke]={}),Ve[Ke][Et]=Gt}W(Et=>({...Et,...Ve}))}se.workflow&&G(se.workflow),se.workflow_lock&&J(se.workflow_lock),se.deployment&&X({isRunning:se.deployment.isRunning||!1,activeRuns:se.deployment.activeRuns||0,status:se.deployment.status||"idle"})}break;case"api_key_status":ce.provider&&A(Ve=>({...Ve,[ce.provider]:se}));break;case"android_status":p(se||Vj);break;case"whatsapp_status":y(se||Gj);break;case"twitter_oauth_complete":se?.success&&w({connected:!0,username:se.username||null,user_id:se.user_id||null,name:se.name,profile_image_url:se.profile_image_url});break;case"google_oauth_complete":se?.success&&x({connected:!0,email:se.email||null,name:se.name,profile_image_url:se.profile_image_url});break;case"google_status":se&&x({connected:se.connected||!1,email:se.email||null,name:se.name});break;case"telegram_status":se&&E({connected:se.connected||!1,bot_username:se.bot_username||null,bot_name:se.bot_name||null,bot_id:se.bot_id||null,owner_chat_id:se.owner_chat_id??null});break;case"whatsapp_message_received":if(se){const Ve={message_id:se.message_id||se.id||"",sender:se.sender||se.from||"",chat_id:se.chat_id||se.chat||"",type:se.type||"text",text:se.text||se.message||se.body||"",timestamp:se.timestamp||Date.now(),is_group:se.is_group||se.isGroup||!1,push_name:se.push_name||se.pushName||se.name,media_url:se.media_url||se.mediaUrl,media_data:se.media_data||se.mediaData,caption:se.caption,latitude:se.latitude,longitude:se.longitude,contact_name:se.contact_name||se.contactName,vcard:se.vcard};j(Ve),O(Et=>[Ve,...Et].slice(0,L8e))}break;case"node_status":if(Ne){const Ve=ce.workflow_id||"unknown",Et=se?.data||{},Gt={...se,...Et,workflow_id:Ve};P(Ke=>({...Ke,[Ve]:{...Ke[Ve]||{},[Ne]:Gt}}))}break;case"node_output":if(Ne){const Ve=ce.workflow_id||"unknown";P(Et=>({...Et,[Ve]:{...Et[Ve]||{},[Ne]:{...Et[Ve]?.[Ne]||{},output:Nt,workflow_id:Ve}}}))}break;case"node_status_cleared":if(Ne||ce.node_id){const Ve=Ne||ce.node_id,Et=ce.workflow_id;P(Gt=>{if(Et&&Gt[Et]){const Ze={...Gt[Et]};return delete Ze[Ve],{...Gt,[Et]:Ze}}const Ke={};for(const[Ze,it]of Object.entries(Gt)){const Yt={...it};delete Yt[Ve],Ke[Ze]=Yt}return Ke})}break;case"node_parameters_updated":Ne&&D(Ve=>({...Ve,[Ne]:{parameters:ce.parameters,version:ce.version,timestamp:ce.timestamp}}));break;case"node_parameters_deleted":Ne&&D(Ve=>{const Et={...Ve};return delete Et[Ne],Et});break;case"variable_update":if(ze!==void 0){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},[ze]:ct}}))}break;case"variables_update":if(et){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},...et}}))}break;case"workflow_status":G(se||Uj);break;case"deployment_status":if(ce.status){const Ve=ce.workflow_id,Et=Ce.current,Gt=["stopped","cancelled","error"].includes(ce.status);if((!Ve||Ve===Et||Gt)&&(X(Ze=>{const it={...Ze};switch(ce.workflow_id&&(it.workflow_id=ce.workflow_id),ce.status){case"starting":it.isRunning=!0,it.status="starting",it.activeRuns=0;break;case"running":case"started":it.isRunning=!0,it.status="running",it.activeRuns=ce.data?.active_runs??Ze.activeRuns;break;case"run_started":it.isRunning=!0,it.status="running",it.activeRuns=ce.data?.active_runs||Ze.activeRuns+1;break;case"run_complete":it.activeRuns=Math.max(0,ce.data?.active_runs||Ze.activeRuns-1);break;case"stopped":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="stopped",it.totalTime=ce.data?.total_time,it.activeRuns=0,it.workflow_id=null);break;case"cancelled":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="cancelled",it.activeRuns=0,it.workflow_id=null);break;case"error":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="error",it.error=ce.error,it.workflow_id=null);break}return it}),Ve)){const{setWorkflowExecuting:Ze}=Sr.getState(),it=["starting","running","started","run_started"].includes(ce.status),Yt=["stopped","cancelled","error"].includes(ce.status);(it||Yt)&&Ze(Ve,it)}}break;case"pong":break;case"console_log":if(se){const Ve={node_id:se.node_id||"",label:se.label||"Console",timestamp:se.timestamp||new Date().toISOString(),data:se.data,formatted:se.formatted||JSON.stringify(se.data,null,2),format:se.format||"json",workflow_id:se.workflow_id,source_node_id:se.source_node_id,source_node_type:se.source_node_type,source_node_label:se.source_node_label};R(Et=>[Ve,...Et].slice(0,100))}break;case"console_logs_cleared":ce.workflow_id?R(Ve=>Ve.filter(Et=>Et.workflow_id!==ce.workflow_id)):R([]);break;case"terminal_log":if(se){const Ve={timestamp:se.timestamp||new Date().toISOString(),level:se.level||"info",message:se.message||"",source:se.source,details:se.details};z(Et=>[Ve,...Et].slice(0,200))}break;case"terminal_logs_cleared":z([]);break;case"workflow_lock":if(se){const Ve=ce.workflow_id||se.workflow_id,Et=Ce.current;(!Ve||Ve===Et||!se.locked)&&J({locked:se.locked||!1,workflow_id:se.workflow_id||null,locked_at:se.locked_at||null,reason:se.reason||null})}break;case"token_usage_update":{const Ve=ce.session_id,Et=ce.workflow_id||Ce.current||"",Gt=ce.data||{};Ve&&Et&&ae(Ke=>{const Ze=Ke[Et]||{},it=Ze[Ve];return{...Ke,[Et]:{...Ze,[Ve]:{session_id:Ve,total:Gt.total??it?.total??0,threshold:Gt.threshold??it?.threshold??0,count:it?.count??0,total_cost:Gt.total_cost??it?.total_cost}}}});break}case"compaction_completed":{const Ve=ce.session_id;Ve&&ae(Et=>{const Gt={...Et};for(const Ke of Object.keys(Gt))Gt[Ke]?.[Ve]&&(Gt[Ke]={...Gt[Ke],[Ve]:{...Gt[Ke][Ve],count:(Gt[Ke][Ve].count||0)+(ce.success?1:0),total:ce.tokens_after??Gt[Ke][Ve].total}});return Gt});break}case"compaction_starting":break;case"error":console.error("[WebSocket] Server error:",ce.code,ce.message);break;default:break}}catch(ce){console.error("[WebSocket] Failed to parse message:",ce)}},[]),re=u.useCallback(()=>{if(ee.current?.readyState===WebSocket.OPEN)return;const de=D8e();try{const ce=new WebSocket(de);ce.onopen=async()=>{i(!0),d(!1),pe.current=setInterval(()=>{ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"ping"}))},3e4);const Me=["openai","anthropic","gemini","google_maps","android_remote"];for(const se of Me)try{(await new Promise((ze,ct)=>{const Nt=`init_${se}_${Date.now()}`,et=setTimeout(()=>ct(new Error("Timeout")),5e3),gt=Ve=>{try{const Et=JSON.parse(Ve.data);Et.request_id===Nt&&(clearTimeout(et),ce.removeEventListener("message",gt),ze(Et))}catch{}};ce.addEventListener("message",gt),ce.send(JSON.stringify({type:"get_stored_api_key",provider:se,request_id:Nt}))})).has_key&&A(ze=>({...ze,[se]:{hasKey:!0,valid:!0}}))}catch{}try{const se=await new Promise((Ne,ze)=>{const ct=`terminal_logs_${Date.now()}`,Nt=setTimeout(()=>ze(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===ct&&(clearTimeout(Nt),ce.removeEventListener("message",et),Ne(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_terminal_logs",request_id:ct}))});if(se.success&&se.logs){const Ne=se.logs.map(ze=>({timestamp:ze.timestamp||new Date().toISOString(),level:ze.level||"info",message:ze.message||"",source:ze.source,details:ze.details})).reverse();z(Ne)}}catch{}try{const se=await new Promise((Ne,ze)=>{const ct=`chat_messages_${Date.now()}`,Nt=setTimeout(()=>ze(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===ct&&(clearTimeout(Nt),ce.removeEventListener("message",et),Ne(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_chat_messages",session_id:"default",request_id:ct}))});if(se.success&&se.messages){const Ne=se.messages.map(ze=>({role:ze.role,message:ze.message,timestamp:ze.timestamp}));T(Ne)}}catch{}try{const se=`console_${Date.now()}`,Ne=await new Promise((ze,ct)=>{const Nt=setTimeout(()=>ct(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===se&&(clearTimeout(Nt),ce.removeEventListener("message",et),ze(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_console_logs",limit:100,request_id:se}))});if(Ne.success&&Ne.logs){const ze=Ne.logs.map(ct=>({node_id:ct.node_id,label:ct.label,timestamp:ct.timestamp,data:ct.data,formatted:ct.formatted,format:ct.format,workflow_id:ct.workflow_id,source_node_id:ct.source_node_id,source_node_type:ct.source_node_type,source_node_label:ct.source_node_label}));R(ze)}}catch{}},ce.onmessage=$e,ce.onclose=Me=>{console.log("[WebSocket] Disconnected:",Me.code,Me.reason),i(!1),ee.current=null,pe.current&&(clearInterval(pe.current),pe.current=null),Me.code!==1e3&&(d(!0),ve.current=setTimeout(()=>{re()},3e3))},ce.onerror=Me=>{console.error("[WebSocket] Error:",Me)},ee.current=ce}catch(ce){console.error("[WebSocket] Failed to create connection:",ce),d(!0),ve.current=setTimeout(re,3e3)}},[$e]),Z=u.useCallback(()=>{ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"get_status"}))},[]),ie=u.useCallback(de=>{if(o)return F[o]?.[de]},[F,o]),le=u.useCallback(de=>N[de],[N]),be=u.useCallback(de=>{if(o)return q[o]?.[de]},[q,o]),Oe=u.useCallback(async de=>{const ce=Ce.current;P(Me=>{if(!ce||!Me[ce])return Me;const se={...Me[ce]};return delete se[de],{...Me,[ce]:se}});try{ee.current&&ee.current.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_node_output",node_id:de,workflow_id:ce}))}catch(Me){console.error("[WebSocket] Failed to clear backend node output:",Me)}},[]),Pe=u.useCallback(()=>{O([]),j(null)},[]),Be=u.useCallback(()=>{R([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_console_logs"}))},[]),Ae=u.useCallback(()=>{z([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_terminal_logs"}))},[]),Ee=u.useCallback(()=>{T([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_chat_messages",session_id:"default"}))},[]),qe=u.useMemo(()=>o?F[o]||{}:{},[F,o]),xe=u.useMemo(()=>o?q[o]||{}:{},[q,o]),Re=u.useMemo(()=>o?te[o]||{}:{},[te,o]),De=u.useCallback((de,ce,Me)=>{ae(se=>({...se,[de]:{...se[de]||{},[ce]:Me}}))},[]),he=u.useCallback(async(de,ce,Me)=>new Promise((se,Ne)=>{if(!ee.current||ee.current.readyState!==WebSocket.OPEN){Ne(new Error("WebSocket not connected"));return}const ze=Wj(),ct=Me===void 0||Me>=0,Nt=Me&&Me>0?Me:M8e;let et=null;ct&&Me!==-1&&(et=setTimeout(()=>{fe.current.delete(ze),Ne(new Error(`Request timeout: ${de}`))},Nt)),fe.current.set(ze,{resolve:se,reject:Ne,timeout:et}),ee.current.send(JSON.stringify({type:de,request_id:ze,...ce}))}),[]),Qe=u.useCallback(async(de,ce)=>{const Me=new Date().toISOString(),se={role:"user",message:de,timestamp:Me};T(Ne=>[...Ne,se]);try{await he("send_chat_message",{message:de,role:"user",node_id:ce,session_id:"default",timestamp:Me})}catch(Ne){throw console.error("[WebSocket] Failed to send chat message:",Ne),Ne}},[he]),Je=u.useCallback(async de=>{try{const ce=await he("get_node_parameters",{node_id:de});if(ce.parameters){const Me={parameters:ce.parameters,version:ce.version||0,timestamp:ce.timestamp};return D(se=>({...se,[de]:Me})),Me}return null}catch(ce){return console.error("[WebSocket] Failed to get node parameters:",ce),null}},[he]),lt=u.useCallback(async de=>{if(!de.length)return{};try{const ce=await he("get_all_node_parameters",{node_ids:de}),Me={};if(ce.parameters){for(const[se,Ne]of Object.entries(ce.parameters))Me[se]={parameters:Ne.parameters||{},version:Ne.version||0,timestamp:ce.timestamp};D(se=>({...se,...Me}))}return Me}catch(ce){return console.error("[WebSocket] Failed to get all node parameters:",ce),{}}},[he]),tt=u.useCallback(async(de,ce,Me)=>{try{const se=H[de]?.version||Me||0,Ne=await he("save_node_parameters",{node_id:de,parameters:ce,version:se});return Ne.success!==!1?(D(ze=>({...ze,[de]:{parameters:Ne.parameters||ce,version:Ne.version||se+1,timestamp:Ne.timestamp}})),!0):!1}catch(se){return console.error("[WebSocket] Failed to save node parameters:",se),!1}},[he,H]),we=u.useCallback(async de=>{try{return await he("delete_node_parameters",{node_id:de}),D(ce=>{const Me={...ce};return delete Me[de],Me}),!0}catch(ce){return console.error("[WebSocket] Failed to delete node parameters:",ce),!1}},[he]),Ge=u.useCallback(async(de,ce,Me,se,Ne)=>{try{const ct=T8e.includes(ce)||R8e.includes(ce)?-1:void 0;return await he("execute_node",{node_id:de,node_type:ce,parameters:Me,nodes:se,edges:Ne,workflow_id:o},ct)}catch(ze){throw console.error("[WebSocket] Failed to execute node:",ze),ze}},[he,o]),je=u.useCallback(async(de,ce)=>{try{const Me=await he("get_node_output",{node_id:de,output_name:ce||"output_0"});return Me.success?Me.data:null}catch(Me){return console.error("[WebSocket] Failed to get node output:",Me),null}},[he]),Le=u.useCallback(async(de,ce)=>{try{return await he("cancel_event_wait",{node_id:de,waiter_id:ce})}catch(Me){return console.error("[WebSocket] Failed to cancel event wait:",Me),{success:!1}}},[he]),dt=u.useCallback(async(de,ce,Me)=>{try{return await he("execute_workflow",{nodes:de.map(Ne=>({id:Ne.id,type:Ne.type||"",data:Ne.data||{}})),edges:ce.map(Ne=>({id:Ne.id,source:Ne.source,target:Ne.target,sourceHandle:Ne.sourceHandle||void 0,targetHandle:Ne.targetHandle||void 0})),session_id:Me||"default"})}catch(se){throw console.error("[WebSocket] Failed to execute workflow:",se),se}},[he]),St=u.useCallback(async(de,ce,Me,se)=>{try{return await he("deploy_workflow",{workflow_id:de,nodes:ce.map(ze=>({id:ze.id,type:ze.type||"",data:ze.data||{}})),edges:Me.map(ze=>({id:ze.id,source:ze.source,target:ze.target,sourceHandle:ze.sourceHandle||void 0,targetHandle:ze.targetHandle||void 0})),session_id:se||"default"})}catch(Ne){throw console.error("[WebSocket] Failed to start deployment:",Ne),Ne}},[he]),Kt=u.useCallback(async de=>{try{const ce=await he("cancel_deployment",{workflow_id:de});return(!de||de===V.workflow_id)&&X(qj),ce}catch(ce){throw console.error("[WebSocket] Failed to cancel deployment:",ce),ce}},[he,V.workflow_id]),Xt=u.useCallback(async de=>{try{const ce=await he("get_deployment_status",{workflow_id:de});return{isRunning:ce.is_running||!1,activeRuns:ce.active_runs||0,settings:ce.settings,workflow_id:ce.workflow_id}}catch(ce){return console.error("[WebSocket] Failed to get deployment status:",ce),{isRunning:!1,activeRuns:0}}},[he]),mt=u.useCallback(async(de,ce,Me,se,Ne,ze,ct)=>{try{return await he("execute_ai_node",{node_id:de,node_type:ce,parameters:Me,model:se,workflow_id:Ne,nodes:ze,edges:ct},-1)}catch(Nt){throw console.error("[WebSocket] Failed to execute AI node:",Nt),Nt}},[he]),rt=u.useCallback(async(de,ce)=>{try{return(await he("get_ai_models",{provider:de,api_key:ce})).models||[]}catch(Me){return console.error("[WebSocket] Failed to get AI models:",Me),[]}},[he]),yt=u.useCallback(async(de,ce)=>{try{const Me=await he("validate_api_key",{provider:de,api_key:ce}),se={valid:Me.valid||!1,message:Me.message,models:Me.models};return se.valid&&A(Ne=>({...Ne,[de]:{hasKey:!0,valid:!0,models:se.models}})),se}catch(Me){return console.error("[WebSocket] Failed to validate API key:",Me),{valid:!1,message:"Validation failed"}}},[he]),ut=u.useCallback(async de=>{try{const ce=await he("get_stored_api_key",{provider:de}),Me={hasKey:ce.has_key||!1,apiKey:ce.api_key,models:ce.models};return Me.hasKey&&A(se=>({...se,[de]:{hasKey:!0,valid:!0,models:Me.models}})),Me}catch(ce){return console.error("[WebSocket] Failed to get stored API key:",ce),{hasKey:!1}}},[he]),Ct=u.useCallback(async(de,ce,Me)=>{try{const Ne=(await he("save_api_key",{provider:de,api_key:ce,models:Me})).success!==!1;return Ne&&A(ze=>({...ze,[de]:{hasKey:!0,valid:!0,models:Me}})),Ne}catch(se){return console.error("[WebSocket] Failed to save API key:",se),!1}},[he]),Bt=u.useCallback(async de=>{try{return await he("delete_api_key",{provider:de}),A(ce=>{const Me={...ce};return delete Me[de],Me}),!0}catch(ce){return console.error("[WebSocket] Failed to delete API key:",ce),!1}},[he]),Ht=u.useCallback(async()=>{try{return(await he("get_android_devices",{})).devices||[]}catch(de){return console.error("[WebSocket] Failed to get Android devices:",de),[]}},[he]),wt=u.useCallback(async(de,ce,Me,se)=>{try{return await he("execute_android_action",{service_id:de,action:ce,parameters:Me,device_id:se})}catch(Ne){throw console.error("[WebSocket] Failed to execute Android action:",Ne),Ne}},[he]),It=u.useCallback(async de=>{try{const ce=await he("validate_maps_key",{api_key:de});return{valid:ce.valid||!1,message:ce.message}}catch(ce){return console.error("[WebSocket] Failed to validate Maps key:",ce),{valid:!1,message:"Validation failed"}}},[he]),Mt=u.useCallback(async de=>{try{const ce=await he("validate_apify_key",{api_key:de});return{valid:ce.valid||!1,message:ce.message,username:ce.username}}catch(ce){return console.error("[WebSocket] Failed to validate Apify key:",ce),{valid:!1,message:"Validation failed"}}},[he]),ot=u.useCallback(async()=>{try{const de=await he("whatsapp_status",{});return{connected:de.connected||!1,deviceId:de.device_id,data:de.data}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp status:",de),{connected:!1}}},[he]),Fe=u.useCallback(async()=>{try{const de=await he("whatsapp_qr",{});return{connected:de.connected||!1,qr:de.qr,message:de.message}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp QR:",de),{connected:!1,message:"Failed to get QR code"}}},[he]),Xe=u.useCallback(async(de,ce)=>{try{const Me=await he("whatsapp_send",{phone:de,message:ce});return{success:Me.success||!1,messageId:Me.messageId,error:Me.error}}catch(Me){return console.error("[WebSocket] Failed to send WhatsApp message:",Me),{success:!1,error:Me.message||"Send failed"}}},[he]),at=u.useCallback(async()=>{try{const de=await he("whatsapp_start",{});return{success:de.success!==!1,message:de.message}}catch(de){return console.error("[WebSocket] Failed to start WhatsApp connection:",de),{success:!1,message:de.message||"Failed to start"}}},[he]),$t=u.useCallback(async()=>{try{const de=await he("whatsapp_restart",{});return{success:de.success!==!1,message:de.message}}catch(de){return console.error("[WebSocket] Failed to restart WhatsApp connection:",de),{success:!1,message:de.message||"Failed to restart"}}},[he]),jt=u.useCallback(async()=>{try{const de=await he("whatsapp_groups",{});return{success:de.success!==!1,groups:de.groups||[],error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp groups:",de),{success:!1,groups:[],error:de.message||"Failed to get groups"}}},[he]),Wt=u.useCallback(async()=>{try{const de=await he("whatsapp_newsletters",{}),ce=de.channels||de.result?.channels||[];return{success:de.success!==!1,channels:ce,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp channels:",de),{success:!1,channels:[],error:de.message||"Failed to get channels"}}},[he]),Pt=u.useCallback(async de=>{try{const ce=await he("whatsapp_group_info",{group_id:de});return{success:ce.success!==!1,participants:ce.participants||[],name:ce.name,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to get WhatsApp group info:",ce),{success:!1,participants:[],error:ce.message||"Failed to get group info"}}},[he]),Rt=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_get",{});return{success:de.success!==!1,config:de.config,stats:de.stats,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp rate limit config:",de),{success:!1,error:de.message||"Failed to get rate limit config"}}},[he]),en=u.useCallback(async de=>{try{const ce=await he("whatsapp_rate_limit_set",{config:de});return{success:ce.success!==!1,config:ce.config,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to set WhatsApp rate limit config:",ce),{success:!1,error:ce.message||"Failed to set rate limit config"}}},[he]),yn=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_stats",{});return{success:de.success!==!1,stats:de.stats||de,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp rate limit stats:",de),{success:!1,error:de.message||"Failed to get rate limit stats"}}},[he]),Te=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_unpause",{});return{success:de.success!==!1,stats:de.stats,error:de.error}}catch(de){return console.error("[WebSocket] Failed to unpause WhatsApp rate limit:",de),{success:!1,error:de.message||"Failed to unpause rate limit"}}},[he]),Ot=u.useCallback(async(de,ce=!1)=>{try{const Me=await he("clear_memory",{session_id:de,clear_long_term:ce});return{success:Me.success!==!1,default_content:Me.default_content,cleared_vector_store:Me.cleared_vector_store,error:Me.error}}catch(Me){return console.error("[WebSocket] Failed to clear memory:",Me),{success:!1,error:Me.message||"Failed to clear memory"}}},[he]),Vt=u.useCallback(async de=>{try{const ce=await he("reset_skill",{skill_name:de});return{success:ce.success!==!1,original_content:ce.original_content,is_builtin:ce.is_builtin,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to reset skill:",ce),{success:!1,error:ce.message||"Failed to reset skill"}}},[he]),Lt=u.useRef(!0);u.useEffect(()=>{if(Lt.current=!0,n||!t||ee.current?.readyState===WebSocket.OPEN)return;const de=setTimeout(()=>{Lt.current&&t&&!ee.current&&re()},100);return()=>{clearTimeout(de)}},[re,t,n]),u.useEffect(()=>{!t&&ee.current&&(ee.current.close(1e3,"User logged out"),ee.current=null,i(!1))},[t]),u.useEffect(()=>()=>{Lt.current=!1,ve.current&&clearTimeout(ve.current),pe.current&&clearInterval(pe.current),ee.current?.readyState===WebSocket.OPEN&&ee.current.close(1e3,"Component unmounted")},[]);const cn={isConnected:a,reconnecting:s,androidStatus:f,setAndroidStatus:p,whatsappStatus:m,twitterStatus:v,googleStatus:b,telegramStatus:C,whatsappMessages:$,lastWhatsAppMessage:_,apiKeyStatuses:N,consoleLogs:I,terminalLogs:B,chatMessages:L,nodeStatuses:qe,nodeParameters:H,variables:xe,workflowStatus:U,deploymentStatus:V,workflowLock:Q,compactionStats:Re,updateCompactionStats:De,getNodeStatus:ie,getApiKeyStatus:le,getVariable:be,requestStatus:Z,clearNodeStatus:Oe,clearWhatsAppMessages:Pe,clearConsoleLogs:Be,clearTerminalLogs:Ae,clearChatMessages:Ee,sendChatMessage:Qe,sendRequest:he,getNodeParameters:Je,getAllNodeParameters:lt,saveNodeParameters:tt,deleteNodeParameters:we,executeNode:Ge,executeWorkflow:dt,getNodeOutput:je,cancelEventWait:Le,deployWorkflow:St,cancelDeployment:Kt,getDeploymentStatus:Xt,executeAiNode:mt,getAiModels:rt,validateApiKey:yt,getStoredApiKey:ut,saveApiKey:Ct,deleteApiKey:Bt,getAndroidDevices:Ht,executeAndroidAction:wt,validateMapsKey:It,validateApifyKey:Mt,getWhatsAppStatus:ot,getWhatsAppQR:Fe,sendWhatsAppMessage:Xe,startWhatsAppConnection:at,restartWhatsAppConnection:$t,getWhatsAppGroups:jt,getWhatsAppChannels:Wt,getWhatsAppGroupInfo:Pt,getWhatsAppRateLimitConfig:Rt,setWhatsAppRateLimitConfig:en,getWhatsAppRateLimitStats:yn,unpauseWhatsAppRateLimit:Te,clearMemory:Ot,resetSkill:Vt};return g.jsx(yD.Provider,{value:cn,children:e})},Qn=()=>{const e=u.useContext(yD);if(!e)throw new Error("useWebSocket must be used within a WebSocketProvider");return e},B8e=()=>{const{androidStatus:e,isConnected:t}=Qn();return{...e,isConnected:t}},vD=e=>{const{getNodeStatus:t}=Qn();return t(e)},F5=()=>{const{whatsappStatus:e}=Qn();return e},H8e=()=>{const{twitterStatus:e}=Qn();return e},W8e=()=>{const{googleStatus:e}=Qn();return e},V8e=()=>{const{telegramStatus:e}=Qn();return e},U8e=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i,renamingNodeId:s,setRenamingNodeId:d,updateNodeData:f}=Sr(),{getNodeStatus:p}=Qn(),m=n?.disabled===!0,v=p(e)?.status||"idle",w=v==="executing"||v==="waiting",b=t&&wr[t]?wr[t]:null,[x,C]=u.useState(!1),[E,$]=u.useState(""),O=u.useRef(null);u.useEffect(()=>{s===e?(C(!0),$(n?.label||b?.displayName||t||"")):C(!1)},[s,e,n?.label,b?.displayName,t]),u.useEffect(()=>{x&&O.current&&(O.current.focus(),O.current.select())},[x]);const _=u.useCallback(()=>{const H=E.trim(),D=n?.label||b?.displayName||t||"";H&&H!==D&&f(e,{...n,label:H}),C(!1),d(null)},[E,n,b?.displayName,t,e,f,d]),j=u.useCallback(()=>{C(!1),d(null)},[d]),N=u.useCallback(H=>{H.stopPropagation(),d(e)},[e,d]),A=H=>{H.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})};if(!t||!b)return g.jsx("div",{style:{padding:"8px 12px",backgroundColor:"#ef4444",color:"white",borderRadius:"8px",fontSize:"12px",minWidth:"120px",textAlign:"center"},children:"Unknown node type"});const I=()=>b.inputs?b.inputs.length>0&&typeof b.inputs[0]=="object"?b.inputs:b.inputs.map((H,D)=>({name:`input_${D}`,displayName:"Input",type:H||"main",description:"Node input connection"})):[],R=()=>b.outputs?b.outputs.length>0&&typeof b.outputs[0]=="object"?b.outputs:b.outputs.map((H,D)=>({name:`output_${D}`,displayName:"Output",type:H||"main",description:"Node output connection"})):[],B=I(),z=R(),L=H=>/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F600}-\u{1F64F}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2300}-\u{23FF}]|[\u{2B50}]|[\u{231A}-\u{231B}]|[\u{25AA}-\u{25AB}]|[\u{25B6}]|[\u{25C0}]|[\u{25FB}-\u{25FE}]|[\u{2614}-\u{2615}]|[\u{2648}-\u{2653}]|[\u{267F}]|[\u{2693}]|[\u{26A1}]|[\u{26AA}-\u{26AB}]|[\u{26BD}-\u{26BE}]|[\u{26C4}-\u{26C5}]|[\u{26CE}]|[\u{26D4}]|[\u{26EA}]|[\u{26F2}-\u{26F3}]|[\u{26F5}]|[\u{26FA}]|[\u{26FD}]|[\u{2702}]|[\u{2705}]|[\u{2708}-\u{270D}]|[\u{270F}]|[\u{2712}]|[\u{2714}]|[\u{2716}]|[\u{271D}]|[\u{2721}]|[\u{2728}]|[\u{2733}-\u{2734}]|[\u{2744}]|[\u{2747}]|[\u{274C}]|[\u{274E}]|[\u{2753}-\u{2755}]|[\u{2757}]|[\u{2763}-\u{2764}]|[\u{2795}-\u{2797}]|[\u{27A1}]|[\u{27B0}]|[\u{27BF}]|[\u{E000}-\u{F8FF}]/u.test(H),T=H=>H?H.startsWith("http")||H.startsWith("data:")||H.startsWith("/")?g.jsx("img",{src:H,alt:"icon",style:{width:"24px",height:"24px",objectFit:"contain",borderRadius:"4px"}}):L(H)?H:H||"📦":"📦",F=()=>b.defaults.color||"#9E9E9E",P=()=>{const H=F();if(H.startsWith("#")){const D=H.substring(1),q=Math.max(0,parseInt(D.substring(0,2),16)-40),W=Math.max(0,parseInt(D.substring(2,4),16)-40),U=Math.max(0,parseInt(D.substring(4,6),16)-40);return`#${q.toString(16).padStart(2,"0")}${W.toString(16).padStart(2,"0")}${U.toString(16).padStart(2,"0")}`}return H};return g.jsxs("div",{style:{position:"relative",padding:"12px 32px 12px 16px",minWidth:"160px",minHeight:"60px",borderRadius:"12px",background:`linear-gradient(135deg, ${F()} 0%, ${P()} 100%)`,border:`2px solid ${w?a.isDarkMode?a.dracula.cyan:"#2563eb":o?"#3b82f6":P()}`,color:"white",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"14px",fontWeight:"600",textAlign:"center",cursor:"pointer",transition:"all 0.2s ease",boxShadow:w?a.isDarkMode?`0 4px 12px ${a.dracula.cyan}66, 0 0 0 3px ${a.dracula.cyan}4D`:"0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)":o?`0 8px 25px ${F()}40, 0 0 0 2px ${a.colors.focus}`:a.isDarkMode?`0 4px 12px ${F()}40`:`0 2px 8px ${F()}25, 0 4px 16px rgba(0, 0, 0, 0.08)`,overflow:"visible",opacity:m?.5:1,animation:w?"pulse 1.5s ease-in-out infinite":"none"},children:[m&&g.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(128, 128, 128, 0.4)",borderRadius:"inherit",zIndex:25,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:g.jsx("span",{style:{fontSize:"24px",opacity:.8},children:"||"})}),B.map((H,D)=>{const q=B.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Br,{id:`input-${H.name}`,type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:W,transform:"translateY(-50%)",width:"12px",height:"12px",backgroundColor:"rgba(255,255,255,0.9)",border:`2px solid ${P()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`input-${H.name}-${D}`)}),g.jsx("button",{onClick:A,style:{position:"absolute",top:"8px",right:"8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.95)",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",color:F(),fontWeight:"600",transition:"all 0.2s ease",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.2)",zIndex:20},onMouseEnter:H=>{H.currentTarget.style.backgroundColor="white",H.currentTarget.style.transform="scale(1.15)",H.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3)"},onMouseLeave:H=>{H.currentTarget.style.backgroundColor="rgba(255, 255, 255, 0.95)",H.currentTarget.style.transform="scale(1)",H.currentTarget.style.boxShadow="0 1px 3px rgba(0, 0, 0, 0.2)"},title:"Edit Parameters",children:"⚙️"}),g.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",position:"relative",zIndex:10,paddingRight:"4px"},children:[g.jsx("span",{style:{fontSize:t==="aiAgent"?"18px":"24px",display:"flex",alignItems:"center"},children:T(b.icon)}),x?g.jsx("input",{ref:O,type:"text",value:E,onChange:H=>$(H.target.value),onKeyDown:H=>{H.key==="Enter"?_():H.key==="Escape"&&j(),H.stopPropagation()},onBlur:_,onClick:H=>H.stopPropagation(),style:{padding:"2px 4px",fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,color:a.colors.text,backgroundColor:a.colors.backgroundElevated,border:`1px solid ${a.dracula.purple}`,borderRadius:a.borderRadius.sm,outline:"none",minWidth:"60px",maxWidth:"120px"}}):g.jsx("span",{onDoubleClick:N,style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",cursor:"text"},title:"Double-click to rename",children:n?.label||b.displayName})]}),z.map((H,D)=>{const q=z.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Br,{id:`output-${H.name}`,type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:W,transform:"translateY(-50%)",width:"12px",height:"12px",backgroundColor:"rgba(255,255,255,0.9)",border:`2px solid ${P()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`output-${H.name}-${D}`)})]})};class q8e{static validateConfiguration(t){const n=[];return(!t.prompt||t.prompt.trim()==="")&&n.push("Prompt is required"),{valid:n.length===0,errors:n}}}const G8e={initializing:{icon:"⚡",label:"Initializing",color:"#8be9fd"},loading_memory:{icon:"💾",label:"Loading Memory",color:"#bd93f9"},memory_loaded:{icon:"✓",label:"Memory Ready",color:"#50fa7b"},building_tools:{icon:"🔧",label:"Building Tools",color:"#ffb86c"},building_graph:{icon:"🔗",label:"Building Graph",color:"#ffb86c"},invoking_llm:{icon:"🧠",label:"Thinking...",color:"#ff79c6"},executing_tool:{icon:"⚡",label:"Using Tool",color:"#ff79c6"},tool_completed:{icon:"✓",label:"Tool Done",color:"#50fa7b"},saving_memory:{icon:"💾",label:"Saving Memory",color:"#bd93f9"}},K8e=({size:e=32,color:t="#6366F1"})=>g.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:t,children:g.jsx("path",{d:"M4.25 5.61C6.27 8.2 10 13 10 13v6c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-6s3.73-4.8 5.75-7.39C20.26 4.95 19.79 4 18.95 4H5.04c-.83 0-1.31.95-.79 1.61z"})}),X8e=({size:e=32,color:t="#6366F1"})=>g.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:t,children:[g.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"}),g.jsx("circle",{cx:"18",cy:"18",r:"4",fill:t,stroke:"#fff",strokeWidth:"1"})]}),Kj={aiAgent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🤖"}),title:"AI Agent",subtitle:"LangGraph Agent",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},chatAgent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧞"}),title:"Zeenie",subtitle:"Personal Assistant",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},socialReceive:{icon:g.jsx(K8e,{}),title:"Social Receive",subtitle:"Normalize Message",themeColorKey:"purple",bottomHandles:[],rightHandles:[{id:"output-message",label:"Message",position:"20%"},{id:"output-media",label:"Media",position:"40%"},{id:"output-contact",label:"Contact",position:"60%"},{id:"output-metadata",label:"Metadata",position:"80%"}],width:260,height:160},socialSend:{icon:g.jsx(X8e,{}),title:"Social Send",subtitle:"Send Message",themeColorKey:"purple",bottomHandles:[],skipInputHandle:!0,leftHandles:[{id:"input-message",label:"Message",position:"15%"},{id:"input-media",label:"Media",position:"35%"},{id:"input-contact",label:"Contact",position:"55%"},{id:"input-metadata",label:"Metadata",position:"75%"}],width:260,height:160},android_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📱"}),title:"Android Agent",subtitle:"Device Control",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},coding_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"💻"}),title:"Coding Agent",subtitle:"Code Execution",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},web_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🌐"}),title:"Web Agent",subtitle:"Browser Automation",themeColorKey:"pink",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},task_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📋"}),title:"Task Agent",subtitle:"Task Automation",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},social_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📱"}),title:"Social Agent",subtitle:"Social Messaging",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},travel_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"✈️"}),title:"Travel Agent",subtitle:"Travel Planning",themeColorKey:"orange",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},tool_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🔧"}),title:"Tool Agent",subtitle:"Tool Orchestration",themeColorKey:"yellow",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},productivity_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"⏰"}),title:"Productivity Agent",subtitle:"Workflows",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},payments_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"💳"}),title:"Payments Agent",subtitle:"Payment Processing",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},consumer_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🛒"}),title:"Consumer Agent",subtitle:"Consumer Support",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},autonomous_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🎯"}),title:"Autonomous Agent",subtitle:"Autonomous Ops",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},orchestrator_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🎼"}),title:"Orchestrator Agent",subtitle:"Agent Coordination",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"20%"},{id:"input-tools",label:"Tool",position:"50%"},{id:"input-teammates",label:"Team",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},ai_employee:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"👥"}),title:"AI Employee",subtitle:"Team Orchestration",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"20%"},{id:"input-tools",label:"Tool",position:"50%"},{id:"input-teammates",label:"Team",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},rlm_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧠"}),title:"RLM Agent",subtitle:"Recursive Reasoning",themeColorKey:"orange",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},claude_code_agent:{icon:g.jsx(pg,{size:28}),title:"Claude Code",subtitle:"Agentic Coding",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},deep_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧠"}),title:"Deep Agent",subtitle:"LangChain DeepAgents",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"30%"},{id:"input-teammates",label:"Team",position:"55%"},{id:"input-tools",label:"Tool",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200}},e0=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i}=Sr(),[s,d]=u.useState(!0),[f,p]=u.useState([]),m=Kj[t||"aiAgent"]||Kj.aiAgent,y=u.useMemo(()=>Dt[m.themeColorKey]||Dt.purple,[m.themeColorKey]),v=vD(e),w=v?.status==="executing",b=v?.data?.phase,x=b?G8e[b]:null;u.useEffect(()=>{try{const _=q8e.validateConfiguration(n||{});d(_.valid),p(_.errors)}catch(_){console.error("Configuration validation error:",_),d(!1),p(["Configuration validation failed"])}},[n,e,m.title]);const C=_=>{_.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=()=>w?a.isDarkMode&&x?x.color:y:o?a.colors.focus:a.colors.border,$=()=>w?a.isDarkMode&&x?`0 0 20px ${x.color}80, 0 0 40px ${x.color}40`:`0 0 0 3px ${y}80, 0 4px 16px ${y}60`:o?`0 4px 12px ${a.colors.focusRing}, 0 0 0 1px ${a.colors.focusRing}`:`0 2px 4px ${a.colors.shadow}`,O=m.rightHandles&&m.rightHandles.length>0;return g.jsxs("div",{style:{position:"relative",padding:a.spacing.lg,paddingRight:O?"60px":a.spacing.lg,paddingLeft:a.spacing.lg,minWidth:m.width?`${m.width}px`:m.wider?"220px":O?"200px":"180px",minHeight:m.height?`${m.height}px`:"120px",borderRadius:a.borderRadius.lg,background:a.isDarkMode?`linear-gradient(135deg, ${y}20 0%, ${a.colors.backgroundAlt} 100%)`:`linear-gradient(145deg, #ffffff 0%, ${y}08 100%)`,border:`2px solid ${E()}`,color:a.colors.text,fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,textAlign:"center",cursor:"pointer",transition:"all 0.3s ease",boxShadow:$(),overflow:"visible",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:a.spacing.sm,animation:w?"pulse 1.5s ease-in-out infinite":"none"},children:[!m.skipInputHandle&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:{position:"absolute",left:"10px",top:"30%",transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap"},children:"Input"}),g.jsx(Br,{id:"input-main",type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:"30%",transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:"Input"})]}),g.jsx("button",{onClick:C,style:{position:"absolute",top:a.spacing.xs,right:a.spacing.xs,width:a.nodeSize.paramButton,height:a.nodeSize.paramButton,borderRadius:a.borderRadius.sm,backgroundColor:a.colors.backgroundAlt,border:`1px solid ${a.colors.border}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:a.fontSize.xs,color:a.colors.textSecondary,fontWeight:a.fontWeight.normal,transition:a.transitions.fast,zIndex:20},title:"Edit Parameters",children:"⚙️"}),g.jsx("div",{style:{lineHeight:"1",marginBottom:a.spacing.xs,color:y},children:m.icon}),g.jsx("div",{style:{fontSize:a.fontSize.base,fontWeight:a.fontWeight.semibold,color:a.colors.text,lineHeight:"1.2",marginBottom:a.spacing.xs},children:n?.label||m.title}),g.jsx("div",{style:{fontSize:a.fontSize.xs,fontWeight:a.fontWeight.normal,color:w&&x?x.color:a.colors.focus,lineHeight:"1.2",marginBottom:a.spacing.lg,transition:"color 0.3s ease"},children:w&&x?x.label:m.subtitle}),m.leftHandles&&m.leftHandles.map(_=>g.jsxs(Y.Fragment,{children:[g.jsx("div",{style:{position:"absolute",left:"12px",top:_.position,transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap"},children:_.label}),g.jsx(Br,{id:_.id,type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:_.position,width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"0",transform:"translateY(-50%) rotate(45deg)"},title:_.label})]},_.id)),m.bottomHandles.map(_=>g.jsx("span",{style:{position:"absolute",bottom:a.spacing.lg,left:_.position,transform:"translateX(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,whiteSpace:"nowrap"},children:_.label},`label-${_.id}`)),m.bottomHandles.map(_=>g.jsx(Br,{id:_.id,type:"target",position:Ut.Bottom,isConnectable:r,style:{position:"absolute",bottom:"-6px",left:_.position,width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"0",transform:"translateX(-50%) rotate(45deg)"},title:_.label},_.id)),m.topOutputHandle&&g.jsx(Br,{id:m.topOutputHandle.id,type:"source",position:Ut.Top,isConnectable:r,style:{position:"absolute",top:"-6px",left:"50%",transform:"translateX(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:y,border:`2px solid ${a.isDarkMode?a.colors.background:"#ffffff"}`,borderRadius:"50%",zIndex:20},title:m.topOutputHandle.label}),!m.skipRightOutput&&m.rightHandles&&m.rightHandles.length>0?g.jsx(g.Fragment,{children:m.rightHandles.map(_=>g.jsxs(Y.Fragment,{children:[g.jsx("div",{style:{position:"absolute",right:"10px",top:_.position,transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap",textAlign:"right"},children:_.label}),g.jsx(Br,{id:_.id,type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:_.position,transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:_.label})]},_.id))}):m.skipRightOutput?null:g.jsx(Br,{id:"output-main",type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:"50%",transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:"Main Output"})]})},Xj={openaiApi:"openai",anthropicApi:"anthropic",googleAiApi:"gemini",azureOpenaiApi:"azure_openai",cohereApi:"cohere",ollamaApi:"ollama",mistralApi:"mistral",openrouterApi:"openrouter",groqApi:"groq",cerebrasApi:"cerebras"},Yj=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i}=Sr(),{apiKeyStatuses:s}=Qn(),f=vD(e)?.status||"idle",p=f==="executing"||f==="waiting",m=wr[t],y=u.useMemo(()=>{const O=m?.credentials?.[0];return O?.name&&Xj[O.name]?Xj[O.name]:t?.includes("deepseek")?"deepseek":t?.includes("kimi")?"kimi":t?.includes("mistral")?"mistral":t?.includes("cerebras")?"cerebras":t?.includes("groq")?"groq":t?.includes("openrouter")?"openrouter":t?.includes("openai")?"openai":t?.includes("claude")?"anthropic":t?.includes("gemini")?"gemini":t?.includes("azure")?"azure_openai":t?.includes("cohere")?"cohere":t?.includes("ollama")?"ollama":""},[t,m?.credentials]),v=u.useMemo(()=>y&&s[y]?.hasKey||!1,[y,s]),w=t==="simpleMemory",b=w?"output-memory":"output-model",x=u.useMemo(()=>w?!0:n?.model&&n.model.trim()!==""&&v,[n?.model,v,w]),C=O=>{O.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=m?.defaults?.color||"#6b7280",$=()=>{const O=MP(y);return O?g.jsx(O,{size:28}):m?.icon?g.jsx("span",{children:m.icon}):t?.includes("azure")?g.jsx("span",{children:"☁️"}):t?.includes("cohere")?g.jsx("span",{children:"🌊"}):t?.includes("ollama")?g.jsx("span",{children:"🦙"}):g.jsx("span",{children:"AI"})};return g.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:a.fontSize.xs,cursor:"pointer"},children:[g.jsxs("div",{style:{position:"relative",width:a.nodeSize.square,height:a.nodeSize.square,borderRadius:"50%",background:a.isDarkMode?`linear-gradient(135deg, ${E}20 0%, ${a.colors.backgroundAlt} 100%)`:`linear-gradient(145deg, #ffffff 0%, ${E}10 100%)`,border:`2px solid ${p?a.isDarkMode?a.dracula.cyan:"#2563eb":o?a.colors.focus:x?a.isDarkMode?`${E}60`:`${E}50`:a.dracula.red}`,display:"flex",alignItems:"center",justifyContent:"center",color:a.colors.text,fontSize:t==="aiAgent"?a.fontSize.lg:a.iconSize.xl,fontWeight:a.fontWeight.semibold,transition:a.transitions.fast,boxShadow:p?a.isDarkMode?`0 4px 12px ${a.dracula.cyan}66, 0 0 0 3px ${a.dracula.cyan}4D`:"0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)":o?`0 4px 12px ${a.colors.focusRing}, 0 0 0 2px ${a.colors.focusRing}`:x?a.isDarkMode?`0 2px 8px ${E}30`:`0 2px 8px ${E}25, 0 4px 12px rgba(0,0,0,0.06)`:`0 2px 8px ${a.dracula.red}4D`,animation:p?"pulse 1.5s ease-in-out infinite":"none"},children:[$(),g.jsx("button",{onClick:C,style:{position:"absolute",top:"-8px",right:"-8px",width:a.nodeSize.paramButton,height:a.nodeSize.paramButton,borderRadius:"50%",backgroundColor:a.isDarkMode?a.colors.backgroundAlt:"#ffffff",border:`1px solid ${a.isDarkMode?a.colors.border:`${E}40`}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:a.fontSize.xs,color:a.colors.textSecondary,fontWeight:"400",transition:a.transitions.fast,zIndex:30,boxShadow:a.isDarkMode?`0 1px 3px ${a.colors.shadow}`:`0 1px 4px ${E}20`},title:"Edit Model Parameters",children:"⚙️"}),g.jsx("div",{style:{position:"absolute",top:"-4px",left:"-4px",width:a.nodeSize.statusIndicator,height:a.nodeSize.statusIndicator,borderRadius:"50%",backgroundColor:p?a.dracula.cyan:f==="success"?a.dracula.green:f==="error"?a.dracula.red:x?a.dracula.green:v?a.dracula.orange:a.dracula.red,border:`2px solid ${a.isDarkMode?a.colors.background:"#ffffff"}`,boxShadow:p?a.isDarkMode?`0 0 6px ${a.dracula.cyan}80`:"0 0 4px rgba(37, 99, 235, 0.5)":a.isDarkMode?`0 1px 3px ${a.colors.shadow}`:"0 1px 3px rgba(0,0,0,0.15)",zIndex:30,animation:p?"pulse 1s ease-in-out infinite":"none"},title:p?"Executing...":w?"Memory node ready":x?"Model configured and ready":v?"API key found, model needs configuration":"API key required"}),g.jsx(Br,{id:b,type:"source",position:Ut.Top,isConnectable:r&&x,style:{position:"absolute",top:"-6px",left:"50%",transform:"translateX(-50%) rotate(45deg)",width:a.nodeSize.statusIndicator,height:a.nodeSize.statusIndicator,backgroundColor:x?a.dracula.cyan:a.colors.textMuted,border:`2px solid ${a.isDarkMode?a.colors.backgroundAlt:"#ffffff"}`,borderRadius:"0",opacity:x?1:.6,zIndex:20,boxShadow:a.isDarkMode?"none":"0 1px 2px rgba(0,0,0,0.1)"},title:w?"Memory Output":x?"Model Configuration Output":"Configure model to enable connection"})]}),g.jsx("div",{style:{marginTop:a.spacing.sm,fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,color:a.colors.text,lineHeight:"1.2",textAlign:"center",maxWidth:"120px"},children:n?.label||m?.displayName})]})},Wd=()=>{const{validateApiKey:e,getStoredApiKey:t,saveApiKey:n,deleteApiKey:r,validateMapsKey:o,validateApifyKey:a,getAiModels:i,sendRequest:s,isConnected:d}=Qn(),[f,p]=u.useState(!1),[m,y]=u.useState(null),v=u.useCallback(async(L,T)=>{p(!0),y(null);try{const F=await e(L,T);return F.valid||y(F.message||"Validation failed"),{isValid:F.valid,error:F.message,models:F.models}}catch(F){const P=F.message||"Validation failed";return y(P),{isValid:!1,error:P}}finally{p(!1)}},[e]),w=u.useCallback(async(L,T)=>{try{const F=await n(L,T);return{isValid:F,error:F?void 0:"Failed to save API key"}}catch(F){return{isValid:!1,error:F.message||"Failed to save API key"}}},[n]),b=u.useCallback(async L=>{try{const T=await t(L);return T.hasKey&&T.apiKey||null}catch(T){return console.warn(`Error retrieving API key for ${L}:`,T),null}},[t]),x=u.useCallback(async L=>{try{return(await t(L)).hasKey}catch{return!1}},[t]),C=u.useCallback(async L=>{try{const T=await t(L);return T.hasKey&&T.models&&T.models.length>0?T.models:null}catch(T){return console.warn(`Error retrieving models for ${L}:`,T),null}},[t]),E=u.useCallback(async L=>{try{await r(L)}catch(T){console.warn(`Error removing API key for ${L}:`,T)}},[r]),$=u.useCallback(async L=>{p(!0),y(null);try{const T=await o(L);return T.valid||y(T.message||"Validation failed"),{isValid:T.valid,error:T.message}}catch(T){const F=T.message||"Validation failed";return y(F),{isValid:!1,error:F}}finally{p(!1)}},[o]),O=u.useCallback(async L=>{p(!0),y(null);try{const T=await a(L);return T.valid||y(T.message||"Validation failed"),{isValid:T.valid,error:T.message}}catch(T){const F=T.message||"Validation failed";return y(F),{isValid:!1,error:F}}finally{p(!1)}},[a]),_=u.useCallback(async(L,T)=>{try{return await i(L,T)}catch(F){return console.warn(`Error fetching AI models for ${L}:`,F),[]}},[i]),j=u.useCallback(async L=>{const T={default_model:"",temperature:.7,max_tokens:4096,thinking_enabled:!1,thinking_budget:2048,reasoning_effort:"medium",reasoning_format:"parsed"};if(!d)return T;try{return(await s("get_provider_defaults",{provider:L}))?.defaults||T}catch(F){return console.warn(`Error fetching provider defaults for ${L}:`,F),T}},[s,d]),N=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_provider_defaults",{provider:L,defaults:T}))?.success||!1}catch(F){return console.warn(`Error saving provider defaults for ${L}:`,F),!1}},[s,d]),A=u.useCallback(async()=>{if(!d)return[];try{return(await s("get_provider_usage_summary",{}))?.providers||[]}catch(L){return console.warn("Error fetching provider usage summary:",L),[]}},[s,d]),I=u.useCallback(async L=>{if(!d)return[];try{return(await s("get_api_usage_summary",{service:L}))?.services||[]}catch(T){return console.warn("Error fetching API usage summary:",T),[]}},[s,d]),R=u.useCallback(async(L,T)=>{const F={found:!1,model:L,provider:T,max_output_tokens:4096,context_length:128e3,temperature_range:[0,2],supports_thinking:!1,thinking_type:"none",is_reasoning_model:!1};if(!d)return F;try{return await s("get_model_constraints",{model:L,provider:T})||F}catch(P){return console.warn(`Error fetching model constraints for ${T}/${L}:`,P),F}},[s,d]),B=u.useCallback(async()=>{const L={providers:[],global_provider:null,global_model:null};if(!d)return L;try{return await s("get_validated_ai_providers",{})||L}catch(T){return console.warn("Error fetching validated AI providers:",T),L}},[s,d]),z=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_global_model",{provider:L,model:T}))?.success??!1}catch(F){return console.warn("Error saving global model:",F),!1}},[s,d]);return{validateApiKey:v,saveApiKey:w,getStoredApiKey:b,hasStoredKey:x,getStoredModels:C,removeApiKey:E,validateGoogleMapsKey:$,validateApifyKey:O,getAiModels:_,getProviderDefaults:j,saveProviderDefaults:N,getProviderUsageSummary:A,getAPIUsageSummary:I,getModelConstraints:R,getValidatedAiProviders:B,saveGlobalModel:z,isValidating:f,validationError:m,isConnected:d}},bD=u.createContext({}),Y8e={aliceblue:"9ehhb",antiquewhite:"9sgk7",aqua:"1ekf",aquamarine:"4zsno",azure:"9eiv3",beige:"9lhp8",bisque:"9zg04",black:"0",blanchedalmond:"9zhe5",blue:"73",blueviolet:"5e31e",brown:"6g016",burlywood:"8ouiv",cadetblue:"3qba8",chartreuse:"4zshs",chocolate:"87k0u",coral:"9yvyo",cornflowerblue:"3xael",cornsilk:"9zjz0",crimson:"8l4xo",cyan:"1ekf",darkblue:"3v",darkcyan:"rkb",darkgoldenrod:"776yz",darkgray:"6mbhl",darkgreen:"jr4",darkgrey:"6mbhl",darkkhaki:"7ehkb",darkmagenta:"5f91n",darkolivegreen:"3bzfz",darkorange:"9yygw",darkorchid:"5z6x8",darkred:"5f8xs",darksalmon:"9441m",darkseagreen:"5lwgf",darkslateblue:"2th1n",darkslategray:"1ugcv",darkslategrey:"1ugcv",darkturquoise:"14up",darkviolet:"5rw7n",deeppink:"9yavn",deepskyblue:"11xb",dimgray:"442g9",dimgrey:"442g9",dodgerblue:"16xof",firebrick:"6y7tu",floralwhite:"9zkds",forestgreen:"1cisi",fuchsia:"9y70f",gainsboro:"8m8kc",ghostwhite:"9pq0v",goldenrod:"8j4f4",gold:"9zda8",gray:"50i2o",green:"pa8",greenyellow:"6senj",grey:"50i2o",honeydew:"9eiuo",hotpink:"9yrp0",indianred:"80gnw",indigo:"2xcoy",ivory:"9zldc",khaki:"9edu4",lavenderblush:"9ziet",lavender:"90c8q",lawngreen:"4vk74",lemonchiffon:"9zkct",lightblue:"6s73a",lightcoral:"9dtog",lightcyan:"8s1rz",lightgoldenrodyellow:"9sjiq",lightgray:"89jo3",lightgreen:"5nkwg",lightgrey:"89jo3",lightpink:"9z6wx",lightsalmon:"9z2ii",lightseagreen:"19xgq",lightskyblue:"5arju",lightslategray:"4nwk9",lightslategrey:"4nwk9",lightsteelblue:"6wau6",lightyellow:"9zlcw",lime:"1edc",limegreen:"1zcxe",linen:"9shk6",magenta:"9y70f",maroon:"4zsow",mediumaquamarine:"40eju",mediumblue:"5p",mediumorchid:"79qkz",mediumpurple:"5r3rv",mediumseagreen:"2d9ip",mediumslateblue:"4tcku",mediumspringgreen:"1di2",mediumturquoise:"2uabw",mediumvioletred:"7rn9h",midnightblue:"z980",mintcream:"9ljp6",mistyrose:"9zg0x",moccasin:"9zfzp",navajowhite:"9zest",navy:"3k",oldlace:"9wq92",olive:"50hz4",olivedrab:"472ub",orange:"9z3eo",orangered:"9ykg0",orchid:"8iu3a",palegoldenrod:"9bl4a",palegreen:"5yw0o",paleturquoise:"6v4ku",palevioletred:"8k8lv",papayawhip:"9zi6t",peachpuff:"9ze0p",peru:"80oqn",pink:"9z8wb",plum:"8nba5",powderblue:"6wgdi",purple:"4zssg",rebeccapurple:"3zk49",red:"9y6tc",rosybrown:"7cv4f",royalblue:"2jvtt",saddlebrown:"5fmkz",salmon:"9rvci",sandybrown:"9jn1c",seagreen:"1tdnb",seashell:"9zje6",sienna:"6973h",silver:"7ir40",skyblue:"5arjf",slateblue:"45e4t",slategray:"4e100",slategrey:"4e100",snow:"9zke2",springgreen:"1egv",steelblue:"2r1kk",tan:"87yx8",teal:"pds",thistle:"8ggk8",tomato:"9yqfb",turquoise:"2j4r4",violet:"9b10u",wheat:"9ld4j",white:"9zldr",whitesmoke:"9lhpx",yellow:"9zl6o",yellowgreen:"61fzm"},lo=Math.round;function Bx(e,t){const n=e.replace(/^[^(]*\((.*)/,"$1").replace(/\).*/,"").match(/\d*\.?\d+%?/g)||[],r=n.map(o=>parseFloat(o));for(let o=0;o<3;o+=1)r[o]=t(r[o]||0,n[o]||"",o);return n[3]?r[3]=n[3].includes("%")?r[3]/100:r[3]:r[3]=1,r}const Qj=(e,t,n)=>n===0?e:e/100;function Jf(e,t){const n=t||255;return e>n?n:e<0?0:e}class Lu{isValid=!0;r=0;g=0;b=0;a=1;_h;_s;_l;_v;_max;_min;_brightness;constructor(t){function n(o){return o[0]in t&&o[1]in t&&o[2]in t}if(t)if(typeof t=="string"){let a=function(i){return o.startsWith(i)};var r=a;const o=t.trim();if(/^#?[A-F\d]{3,8}$/i.test(o))this.fromHexString(o);else if(a("rgb"))this.fromRgbString(o);else if(a("hsl"))this.fromHslString(o);else if(a("hsv")||a("hsb"))this.fromHsvString(o);else{const i=Y8e[o.toLowerCase()];i&&this.fromHexString(parseInt(i,36).toString(16).padStart(6,"0"))}}else if(t instanceof Lu)this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this._h=t._h,this._s=t._s,this._l=t._l,this._v=t._v;else if(n("rgb"))this.r=Jf(t.r),this.g=Jf(t.g),this.b=Jf(t.b),this.a=typeof t.a=="number"?Jf(t.a,1):1;else if(n("hsl"))this.fromHsl(t);else if(n("hsv"))this.fromHsv(t);else throw new Error("@ant-design/fast-color: unsupported input "+JSON.stringify(t))}setR(t){return this._sc("r",t)}setG(t){return this._sc("g",t)}setB(t){return this._sc("b",t)}setA(t){return this._sc("a",t,1)}setHue(t){const n=this.toHsv();return n.h=t,this._c(n)}getLuminance(){function t(a){const i=a/255;return i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)}const n=t(this.r),r=t(this.g),o=t(this.b);return .2126*n+.7152*r+.0722*o}getHue(){if(typeof this._h>"u"){const t=this.getMax()-this.getMin();t===0?this._h=0:this._h=lo(60*(this.r===this.getMax()?(this.g-this.b)/t+(this.g<this.b?6:0):this.g===this.getMax()?(this.b-this.r)/t+2:(this.r-this.g)/t+4))}return this._h}getSaturation(){if(typeof this._s>"u"){const t=this.getMax()-this.getMin();t===0?this._s=0:this._s=t/this.getMax()}return this._s}getLightness(){return typeof this._l>"u"&&(this._l=(this.getMax()+this.getMin())/510),this._l}getValue(){return typeof this._v>"u"&&(this._v=this.getMax()/255),this._v}getBrightness(){return typeof this._brightness>"u"&&(this._brightness=(this.r*299+this.g*587+this.b*114)/1e3),this._brightness}darken(t=10){const n=this.getHue(),r=this.getSaturation();let o=this.getLightness()-t/100;return o<0&&(o=0),this._c({h:n,s:r,l:o,a:this.a})}lighten(t=10){const n=this.getHue(),r=this.getSaturation();let o=this.getLightness()+t/100;return o>1&&(o=1),this._c({h:n,s:r,l:o,a:this.a})}mix(t,n=50){const r=this._c(t),o=n/100,a=s=>(r[s]-this[s])*o+this[s],i={r:lo(a("r")),g:lo(a("g")),b:lo(a("b")),a:lo(a("a")*100)/100};return this._c(i)}tint(t=10){return this.mix({r:255,g:255,b:255,a:1},t)}shade(t=10){return this.mix({r:0,g:0,b:0,a:1},t)}onBackground(t){const n=this._c(t),r=this.a+n.a*(1-this.a),o=a=>lo((this[a]*this.a+n[a]*n.a*(1-this.a))/r);return this._c({r:o("r"),g:o("g"),b:o("b"),a:r})}isDark(){return this.getBrightness()<128}isLight(){return this.getBrightness()>=128}equals(t){return this.r===t.r&&this.g===t.g&&this.b===t.b&&this.a===t.a}clone(){return this._c(this)}toHexString(){let t="#";const n=(this.r||0).toString(16);t+=n.length===2?n:"0"+n;const r=(this.g||0).toString(16);t+=r.length===2?r:"0"+r;const o=(this.b||0).toString(16);if(t+=o.length===2?o:"0"+o,typeof this.a=="number"&&this.a>=0&&this.a<1){const a=lo(this.a*255).toString(16);t+=a.length===2?a:"0"+a}return t}toHsl(){return{h:this.getHue(),s:this.getSaturation(),l:this.getLightness(),a:this.a}}toHslString(){const t=this.getHue(),n=lo(this.getSaturation()*100),r=lo(this.getLightness()*100);return this.a!==1?`hsla(${t},${n}%,${r}%,${this.a})`:`hsl(${t},${n}%,${r}%)`}toHsv(){return{h:this.getHue(),s:this.getSaturation(),v:this.getValue(),a:this.a}}toRgb(){return{r:this.r,g:this.g,b:this.b,a:this.a}}toRgbString(){return this.a!==1?`rgba(${this.r},${this.g},${this.b},${this.a})`:`rgb(${this.r},${this.g},${this.b})`}toString(){return this.toRgbString()}_sc(t,n,r){const o=this.clone();return o[t]=Jf(n,r),o}_c(t){return new this.constructor(t)}getMax(){return typeof this._max>"u"&&(this._max=Math.max(this.r,this.g,this.b)),this._max}getMin(){return typeof this._min>"u"&&(this._min=Math.min(this.r,this.g,this.b)),this._min}fromHexString(t){const n=t.replace("#","");function r(o,a){return parseInt(n[o]+n[a||o],16)}n.length<6?(this.r=r(0),this.g=r(1),this.b=r(2),this.a=n[3]?r(3)/255:1):(this.r=r(0,1),this.g=r(2,3),this.b=r(4,5),this.a=n[6]?r(6,7)/255:1)}fromHsl({h:t,s:n,l:r,a:o}){if(this._h=t%360,this._s=n,this._l=r,this.a=typeof o=="number"?o:1,n<=0){const y=lo(r*255);this.r=y,this.g=y,this.b=y}let a=0,i=0,s=0;const d=t/60,f=(1-Math.abs(2*r-1))*n,p=f*(1-Math.abs(d%2-1));d>=0&&d<1?(a=f,i=p):d>=1&&d<2?(a=p,i=f):d>=2&&d<3?(i=f,s=p):d>=3&&d<4?(i=p,s=f):d>=4&&d<5?(a=p,s=f):d>=5&&d<6&&(a=f,s=p);const m=r-f/2;this.r=lo((a+m)*255),this.g=lo((i+m)*255),this.b=lo((s+m)*255)}fromHsv({h:t,s:n,v:r,a:o}){this._h=t%360,this._s=n,this._v=r,this.a=typeof o=="number"?o:1;const a=lo(r*255);if(this.r=a,this.g=a,this.b=a,n<=0)return;const i=t/60,s=Math.floor(i),d=i-s,f=lo(r*(1-n)*255),p=lo(r*(1-n*d)*255),m=lo(r*(1-n*(1-d))*255);switch(s){case 0:this.g=m,this.b=f;break;case 1:this.r=p,this.b=f;break;case 2:this.r=f,this.b=m;break;case 3:this.r=f,this.g=p;break;case 4:this.r=m,this.g=f;break;case 5:default:this.g=f,this.b=p;break}}fromHsvString(t){const n=Bx(t,Qj);this.fromHsv({h:n[0],s:n[1],v:n[2],a:n[3]})}fromHslString(t){const n=Bx(t,Qj);this.fromHsl({h:n[0],s:n[1],l:n[2],a:n[3]})}fromRgbString(t){const n=Bx(t,(r,o)=>o.includes("%")?lo(r/100*255):r);this.r=n[0],this.g=n[1],this.b=n[2],this.a=n[3]}}const t0=2,Zj=.16,Q8e=.05,Z8e=.05,J8e=.15,xD=5,SD=4,e7e=[{index:7,amount:15},{index:6,amount:25},{index:5,amount:30},{index:5,amount:45},{index:5,amount:65},{index:5,amount:85},{index:4,amount:90},{index:3,amount:95},{index:2,amount:97},{index:1,amount:98}];function Jj(e,t,n){let r;return Math.round(e.h)>=60&&Math.round(e.h)<=240?r=n?Math.round(e.h)-t0*t:Math.round(e.h)+t0*t:r=n?Math.round(e.h)+t0*t:Math.round(e.h)-t0*t,r<0?r+=360:r>=360&&(r-=360),r}function ek(e,t,n){if(e.h===0&&e.s===0)return e.s;let r;return n?r=e.s-Zj*t:t===SD?r=e.s+Zj:r=e.s+Q8e*t,r>1&&(r=1),n&&t===xD&&r>.1&&(r=.1),r<.06&&(r=.06),Math.round(r*100)/100}function tk(e,t,n){let r;return n?r=e.v+Z8e*t:r=e.v-J8e*t,r=Math.max(0,Math.min(1,r)),Math.round(r*100)/100}function t7e(e,t={}){const n=[],r=new Lu(e),o=r.toHsv();for(let a=xD;a>0;a-=1){const i=new Lu({h:Jj(o,a,!0),s:ek(o,a,!0),v:tk(o,a,!0)});n.push(i)}n.push(r);for(let a=1;a<=SD;a+=1){const i=new Lu({h:Jj(o,a),s:ek(o,a),v:tk(o,a)});n.push(i)}return t.theme==="dark"?e7e.map(({index:a,amount:i})=>new Lu(t.backgroundColor||"#141414").mix(n[a],i).toHexString()):n.map(a=>a.toHexString())}const P3=["#e6f4ff","#bae0ff","#91caff","#69b1ff","#4096ff","#1677ff","#0958d9","#003eb3","#002c8c","#001d66"];P3.primary=P3[5];function n7e(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function r7e(e,t){if(!e)return!1;if(e.contains)return e.contains(t);let n=t;for(;n;){if(n===e)return!0;n=n.parentNode}return!1}const nk="data-rc-order",rk="data-rc-priority",o7e="rc-util-key",D3=new Map;function wD({mark:e}={}){return e?e.startsWith("data-")?e:`data-${e}`:o7e}function B5(e){return e.attachTo?e.attachTo:document.querySelector("head")||document.body}function a7e(e){return e==="queue"?"prependQueue":e?"prepend":"append"}function H5(e){return Array.from((D3.get(e)||e).children).filter(t=>t.tagName==="STYLE")}function CD(e,t={}){if(!n7e())return null;const{csp:n,prepend:r,priority:o=0}=t,a=a7e(r),i=a==="prependQueue",s=document.createElement("style");s.setAttribute(nk,a),i&&o&&s.setAttribute(rk,`${o}`),n?.nonce&&(s.nonce=n?.nonce),s.innerHTML=e;const d=B5(t),{firstChild:f}=d;if(r){if(i){const p=(t.styles||H5(d)).filter(m=>{if(!["prepend","prependQueue"].includes(m.getAttribute(nk)))return!1;const y=Number(m.getAttribute(rk)||0);return o>=y});if(p.length)return d.insertBefore(s,p[p.length-1].nextSibling),s}d.insertBefore(s,f)}else d.appendChild(s);return s}function i7e(e,t={}){let{styles:n}=t;return n||=H5(B5(t)),n.find(r=>r.getAttribute(wD(t))===e)}function l7e(e,t){const n=D3.get(e);if(!n||!r7e(document,n)){const r=CD("",t),{parentNode:o}=r;D3.set(e,o),e.removeChild(r)}}function s7e(e,t,n={}){const r=B5(n),o=H5(r),a={...n,styles:o};l7e(r,a);const i=i7e(t,a);if(i)return a.csp?.nonce&&i.nonce!==a.csp?.nonce&&(i.nonce=a.csp?.nonce),i.innerHTML!==e&&(i.innerHTML=e),i;const s=CD(e,a);return s.setAttribute(wD(a),t),s}function ED(e){return e?.getRootNode?.()}function c7e(e){return ED(e)instanceof ShadowRoot}function u7e(e){return c7e(e)?ED(e):null}let L3={};const d7e=e=>{};function f7e(e,t){}function p7e(e,t){}function m7e(){L3={}}function $D(e,t,n){!t&&!L3[n]&&(e(!1,n),L3[n]=!0)}function ky(e,t){$D(f7e,e,t)}function g7e(e,t){$D(p7e,e,t)}ky.preMessage=d7e;ky.resetWarned=m7e;ky.noteOnce=g7e;function h7e(e){return e.replace(/-(.)/g,(t,n)=>n.toUpperCase())}function y7e(e,t){ky(e,`[@ant-design/icons] ${t}`)}function ok(e){return typeof e=="object"&&typeof e.name=="string"&&typeof e.theme=="string"&&(typeof e.icon=="object"||typeof e.icon=="function")}function ak(e={}){return Object.keys(e).reduce((t,n)=>{const r=e[n];switch(n){case"class":t.className=r,delete t.class;break;default:delete t[n],t[h7e(n)]=r}return t},{})}function F3(e,t,n){return n?Y.createElement(e.tag,{key:t,...ak(e.attrs),...n},(e.children||[]).map((r,o)=>F3(r,`${t}-${e.tag}-${o}`))):Y.createElement(e.tag,{key:t,...ak(e.attrs)},(e.children||[]).map((r,o)=>F3(r,`${t}-${e.tag}-${o}`)))}function OD(e){return t7e(e)[0]}function _D(e){return e?Array.isArray(e)?e:[e]:[]}const v7e=`
516
+ `,L5=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,i8e=L5(o8e),l8e=L5(sD),s8e=L5(a8e),c8e={read:sD},u8e=[{name:"Gmail",value:"gmail"},{name:"Outlook / Office 365",value:"outlook"},{name:"Yahoo Mail",value:"yahoo"},{name:"iCloud Mail",value:"icloud"},{name:"ProtonMail (Bridge)",value:"protonmail"},{name:"Fastmail",value:"fastmail"},{name:"Custom / Self-hosted",value:"custom"}],Fx={displayName:"Provider",name:"provider",type:"options",options:u8e,default:"gmail",description:"Email provider"},d8e={emailSend:{displayName:"Email Send",name:"emailSend",icon:i8e,group:["email","tool"],version:1,subtitle:"Send Email via SMTP",description:"Send email via Himalaya SMTP. Supports Gmail, Outlook, Yahoo, iCloud, ProtonMail, Fastmail, or custom.",defaults:{name:"Email Send",color:Un.blue},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Send result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[Fx,{displayName:"To",name:"to",type:"string",default:"",required:!0,placeholder:"recipient@example.com",description:"Recipients (comma-separated)"},{displayName:"Subject",name:"subject",type:"string",default:"",required:!0,placeholder:"Email subject"},{displayName:"Body",name:"body",type:"string",default:"",required:!0,typeOptions:{rows:6},placeholder:"Email body..."},{displayName:"CC",name:"cc",type:"string",default:"",placeholder:"cc@example.com"},{displayName:"BCC",name:"bcc",type:"string",default:"",placeholder:"bcc@example.com"},{displayName:"Body Type",name:"body_type",type:"options",options:[{name:"Plain Text",value:"text"},{name:"HTML",value:"html"}],default:"text"}]},emailRead:{displayName:"Email Read",name:"emailRead",icon:l8e,group:["email","tool"],version:1,subtitle:"Read & Manage via IMAP",description:"List, search, read, move, delete, or flag emails via Himalaya IMAP.",defaults:{name:"Email Read",color:Un.blue},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Send result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[Fx,{displayName:"Operation",name:"operation",type:"options",required:!0,default:"list",options:[{name:"List Envelopes",value:"list"},{name:"Search Emails",value:"search"},{name:"Read Message",value:"read"},{name:"List Folders",value:"folders"},{name:"Move Message",value:"move"},{name:"Delete Message",value:"delete"},{name:"Flag Message",value:"flag"}]},{displayName:"Folder",name:"folder",type:"string",default:"INBOX",displayOptions:{show:{operation:["list","search","read","move","delete","flag"]}}},{displayName:"Query",name:"query",type:"string",default:"",required:!0,placeholder:"from:john subject:meeting",displayOptions:{show:{operation:["search"]}}},{displayName:"Message ID",name:"message_id",type:"string",default:"",required:!0,displayOptions:{show:{operation:["read","move","delete","flag"]}}},{displayName:"Target Folder",name:"target_folder",type:"string",default:"",required:!0,placeholder:"Archive",displayOptions:{show:{operation:["move"]}}},{displayName:"Flag",name:"flag",type:"options",default:"Seen",options:[{name:"Seen",value:"Seen"},{name:"Answered",value:"Answered"},{name:"Flagged",value:"Flagged"},{name:"Draft",value:"Draft"},{name:"Deleted",value:"Deleted"}],displayOptions:{show:{operation:["flag"]}}},{displayName:"Flag Action",name:"flag_action",type:"options",default:"add",options:[{name:"Add",value:"add"},{name:"Remove",value:"remove"}],displayOptions:{show:{operation:["flag"]}}},{displayName:"Page",name:"page",type:"number",default:1,typeOptions:{minValue:1},displayOptions:{show:{operation:["list"]}}},{displayName:"Page Size",name:"page_size",type:"number",default:20,typeOptions:{minValue:1,maxValue:100},displayOptions:{show:{operation:["list"]}}}]},emailReceive:{displayName:"Email Receive",name:"emailReceive",icon:s8e,group:["email","trigger"],version:1,subtitle:"On Email Received",description:"Trigger workflow when new email arrives. Polls IMAP via Himalaya.",defaults:{name:"Email Receive",color:Un.blue},inputs:[],outputs:[{name:"main",displayName:"Email",type:"main",description:"message_id, from, to, subject, date, body, folder"}],properties:[Fx,{displayName:"Folder",name:"folder",type:"string",default:"INBOX"},{displayName:"Poll Interval (seconds)",name:"poll_interval",type:"number",default:60,typeOptions:{minValue:30,maxValue:3600}},{displayName:"Filter Query",name:"filter_query",type:"string",default:"",placeholder:"from:important@company.com"},{displayName:"Mark as Read",name:"mark_as_read",type:"boolean",default:!1}]}},f8e=["emailSend","emailRead","emailReceive"],wr={...rCe,...oCe,...BP,...F6e,...H6e,...V6e,...U6e,...Z6e,...tCe,...aCe,...iCe,...sCe,...cCe,...Dm,...uCe,...hCe,...wCe,..._Ce,...jCe,...GCe,...KCe,...QCe,...t8e,...n8e,...d8e};[...hs];const Pj=e=>{let t;const n=new Set,r=(f,p)=>{const m=typeof f=="function"?f(t):f;if(!Object.is(m,t)){const y=t;t=p??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(v=>v(t,y))}},o=()=>t,s={setState:r,getState:o,getInitialState:()=>d,subscribe:f=>(n.add(f),()=>n.delete(f))},d=t=e(r,o,s);return s},p8e=(e=>e?Pj(e):Pj),m8e=e=>e;function g8e(e,t=m8e){const n=Y.useSyncExternalStore(e.subscribe,Y.useCallback(()=>t(e.getState()),[e,t]),Y.useCallback(()=>t(e.getInitialState()),[e,t]));return Y.useDebugValue(n),n}const Dj=e=>{const t=p8e(e),n=r=>g8e(t,r);return Object.assign(n,t),n},h8e=(e=>e?Dj(e):Dj),cD=()=>`workflow-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Lj=e=>e.map(t=>({...t,selected:void 0,dragging:void 0})),Fj=e=>e.map(t=>({...t,selected:void 0})),y8e=(e,t=20)=>({x:Math.round(e.x/t)*t,y:Math.round(e.y/t)*t}),v8e=e=>e===0?{x:100,y:200}:{x:0,y:0};function _y(e){const t=[];return(!e.id||typeof e.id!="string")&&t.push("Workflow must have a valid id"),(!e.name||typeof e.name!="string")&&t.push("Workflow must have a valid name"),Array.isArray(e.nodes)||t.push("Workflow must have a nodes array"),Array.isArray(e.edges)||t.push("Workflow must have an edges array"),e.createdAt||t.push("Workflow must have a createdAt timestamp"),e.lastModified||t.push("Workflow must have a lastModified timestamp"),e.nodes?.forEach((n,r)=>{n.id||t.push(`Node at index ${r} must have an id`),n.type||t.push(`Node at index ${r} must have a type`),(!n.position||typeof n.position.x!="number"||typeof n.position.y!="number")&&t.push(`Node at index ${r} must have a valid position with x and y coordinates`)}),e.edges?.forEach((n,r)=>{n.id||t.push(`Edge at index ${r} must have an id`),n.source||t.push(`Edge at index ${r} must have a source node`),n.target||t.push(`Edge at index ${r} must have a target node`);const o=e.nodes?.some(i=>i.id===n.source),a=e.nodes?.some(i=>i.id===n.target);o||t.push(`Edge ${n.id} references non-existent source node: ${n.source}`),a||t.push(`Edge ${n.id} references non-existent target node: ${n.target}`)}),{valid:t.length===0,errors:t}}function uD(e){return JSON.stringify(e,null,2)}function dD(e){try{const t=JSON.parse(e);return t.createdAt&&(t.createdAt=new Date(t.createdAt)),t.lastModified&&(t.lastModified=new Date(t.lastModified)),t}catch(t){throw new Error(`Failed to parse workflow JSON: ${t}`)}}const b8e=new Set(["apiKey","api_key","apikey","accessToken","access_token","refreshToken","refresh_token","secret","password","passwd","client_id","client_secret","clientId","clientSecret","token","bearerToken","bearer_token","privateKey","private_key","encryptionKey","encryption_key","oauthToken","oauth_token"]),x8e=new Set(["maxTokens","max_tokens","budgetTokens","budget_tokens","page_token","pageToken","nextPageToken","next_page_token","tokenCount","token_count","totalTokens","total_tokens","inputTokens","input_tokens","outputTokens","output_tokens"]),S8e=["api_key","apikey","secret","password","private_key","privatekey","accesstoken","access_token","refreshtoken","refresh_token","bearertoken","bearer_token","oauthtoken","oauth_token","authtoken","auth_token"];function w8e(e){if(x8e.has(e))return!1;if(b8e.has(e))return!0;const t=e.toLowerCase();return S8e.some(n=>t.includes(n))}const C8e=new Set(["memoryContent","token_usage","execution_time","last_execution","last_result"]);function fD(e){const t={};for(const[n,r]of Object.entries(e))if(!w8e(n)&&!C8e.has(n))if(r&&typeof r=="object"&&!Array.isArray(r)){const o=fD(r);Object.keys(o).length>0&&(t[n]=o)}else t[n]=r;return t}const pD="0.0.61",E8e=new Set(["label","disabled","condition"]);function b1(e){return e.map(t=>({...t,data:Object.fromEntries(Object.entries(t.data||{}).filter(([n])=>E8e.has(n)))}))}function mD(e){if(!e||Object.keys(e).length===0)return;const t={};for(const[n,r]of Object.entries(e)){const o=fD(r);Object.keys(o).length>0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}function $8e(e,t){const n=_y(e);if(!n.valid)throw console.error("Workflow validation errors:",n.errors),new Error(`Cannot export invalid workflow: ${n.errors.join(", ")}`);const r={...e,nodes:b1(e.nodes),createdAt:e.createdAt.toISOString(),lastModified:e.lastModified.toISOString(),version:pD},o=mD(t);o&&(r.nodeParameters=o);const a=uD(r),i=new Blob([a],{type:"application/json"}),s=URL.createObjectURL(i),d=document.createElement("a");d.href=s,d.download=`${e.name||"workflow"}_${e.id}.json`,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(s)}function O8e(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{try{const a=o.target?.result,s=JSON.parse(a).nodeParameters||void 0,d=dD(a),f=_y(d);if(!f.valid){n(new Error(`Invalid workflow JSON: ${f.errors.join(", ")}`));return}t({...d,nodeParameters:s})}catch(a){n(a)}},r.onerror=()=>{n(new Error("Failed to read file"))},r.readAsText(e)})}function _8e(e,t){const n=_y(e);if(!n.valid)throw new Error(`Cannot export invalid workflow: ${n.errors.join(", ")}`);const r={...e,nodes:b1(e.nodes),createdAt:e.createdAt.toISOString(),lastModified:e.lastModified.toISOString(),version:pD},o=mD(t);return o&&(r.nodeParameters=o),uD(r)}function j8e(e){const n=JSON.parse(e).nodeParameters||void 0,r=dD(e),o=_y(r);if(!o.valid)throw new Error(`Invalid workflow JSON: ${o.errors.join(", ")}`);return{...r,nodeParameters:n}}const Qh=()=>`${$c.PYTHON_BASE_URL}/api/database`,Zf={async saveWorkflow(e,t,n){try{return(await(await fetch(`${Qh()}/workflows`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workflow_id:e,name:t,data:n})})).json()).success}catch(r){return console.error("Failed to save workflow:",r),!1}},async getWorkflow(e){try{const n=await(await fetch(`${Qh()}/workflows/${e}`,{credentials:"include"})).json();return n.success&&n.workflow?n.workflow:null}catch(t){return console.error("Failed to get workflow:",t),null}},async getAllWorkflows(){try{const t=await(await fetch(`${Qh()}/workflows`,{credentials:"include"})).json();return t.success&&t.workflows?t.workflows:[]}catch(e){return console.error("Failed to get workflows:",e),[]}},async deleteWorkflow(e){try{return(await(await fetch(`${Qh()}/workflows/${e}`,{method:"DELETE",credentials:"include"})).json()).success}catch(t){return console.error("Failed to delete workflow:",t),!1}}},Bj=()=>({id:cD(),name:ht.constants.defaultWorkflowName,nodes:[],edges:[],createdAt:new Date,lastModified:new Date}),$u=()=>({selectedNodeId:null,executedNodes:[],executionOrder:[],isExecuting:!1,viewport:void 0}),Hj=e=>e.map(t=>t.type==="googleChatModel"?{...t,type:"geminiChatModel"}:t),Go={sidebarVisible:"ui_sidebar_visible",componentPaletteVisible:"ui_component_palette_visible",consolePanelVisible:"ui_console_panel_visible",proMode:"ui_pro_mode"},Zh=(e,t)=>{try{const n=localStorage.getItem(e);if(n!==null)return n==="true"}catch{}return t},wi=(e,t)=>{try{localStorage.setItem(e,String(t))}catch{}},Sr=h8e((e,t)=>({currentWorkflow:null,hasUnsavedChanges:!1,workflowUIStates:{},selectedNode:null,sidebarVisible:Zh(Go.sidebarVisible,!0),componentPaletteVisible:Zh(Go.componentPaletteVisible,!0),consolePanelVisible:Zh(Go.consolePanelVisible,!1),proMode:Zh(Go.proMode,!1),renamingNodeId:null,savedWorkflows:[],setCurrentWorkflow:n=>{e({currentWorkflow:n,hasUnsavedChanges:!1})},updateWorkflow:n=>{const r=t().currentWorkflow;if(!r)return;const o={...r,...n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},createNewWorkflow:()=>{const n=Bj();e({currentWorkflow:n,hasUnsavedChanges:!1,selectedNode:null})},saveWorkflow:async()=>{const{currentWorkflow:n,savedWorkflows:r}=t();if(!n)return;const o={...n,lastModified:new Date};if(!await Zf.saveWorkflow(o.id,o.name,{nodes:b1(o.nodes),edges:o.edges})){console.error("Failed to save workflow to database");return}const i=r.findIndex(f=>f.id===o.id),s={id:o.id,name:o.name,createdAt:o.createdAt,lastModified:o.lastModified,nodeCount:o.nodes.length};let d;i>=0?(d=[...r],d[i]=s):d=[s,...r],e({currentWorkflow:o,savedWorkflows:d,hasUnsavedChanges:!1})},loadWorkflow:async n=>{const r=await Zf.getWorkflow(n);if(r){const o=Hj(r.data?.nodes||[]),a=r.data?.edges||[],i={id:r.id,name:r.name,nodes:o,edges:a,createdAt:new Date(r.createdAt),lastModified:new Date(r.lastModified)};e({currentWorkflow:i,hasUnsavedChanges:!1,selectedNode:null})}},loadSavedWorkflows:async()=>{const r=(await Zf.getAllWorkflows()).map(a=>({id:a.id,name:a.name,nodeCount:a.nodeCount,createdAt:new Date(a.createdAt),lastModified:new Date(a.lastModified)}));e({savedWorkflows:r});const{currentWorkflow:o}=t();if(!o&&r.length>0){const i=[...r].sort((s,d)=>d.lastModified.getTime()-s.lastModified.getTime())[0];await t().loadWorkflow(i.id)}},deleteWorkflow:async n=>{const{currentWorkflow:r,savedWorkflows:o}=t();if(!await Zf.deleteWorkflow(n))return console.error("Failed to delete workflow from database"),!1;const i=o.filter(s=>s.id!==n);if(r?.id===n){const s=Bj();e({currentWorkflow:s,savedWorkflows:i,hasUnsavedChanges:!1,selectedNode:null})}else e({savedWorkflows:i});return!0},migrateCurrentWorkflow:async()=>{const{currentWorkflow:n}=t();if(!n||!n.nodes)return;const r=Hj(n.nodes);if(r.some((a,i)=>a.type!==n.nodes[i]?.type)){const a={...n,nodes:r};await Zf.saveWorkflow(a.id,a.name,{nodes:b1(a.nodes),edges:a.edges}),e({currentWorkflow:a,hasUnsavedChanges:!1})}},setSelectedNode:n=>{e({selectedNode:n})},toggleSidebar:()=>{e(n=>{const r=!n.sidebarVisible;return wi(Go.sidebarVisible,r),{sidebarVisible:r}})},toggleComponentPalette:()=>{e(n=>{const r=!n.componentPaletteVisible;return wi(Go.componentPaletteVisible,r),{componentPaletteVisible:r}})},toggleProMode:()=>{e(n=>{const r=!n.proMode;return wi(Go.proMode,r),{proMode:r}})},setRenamingNodeId:n=>{e({renamingNodeId:n})},setSidebarVisible:n=>{wi(Go.sidebarVisible,n),e({sidebarVisible:n})},setComponentPaletteVisible:n=>{wi(Go.componentPaletteVisible,n),e({componentPaletteVisible:n})},setConsolePanelVisible:n=>{wi(Go.consolePanelVisible,n),e({consolePanelVisible:n})},toggleConsolePanelVisible:()=>{e(n=>{const r=!n.consolePanelVisible;return wi(Go.consolePanelVisible,r),{consolePanelVisible:r}})},applyUIDefaults:n=>{const r={};n.sidebarDefaultOpen!==void 0&&(r.sidebarVisible=n.sidebarDefaultOpen,wi(Go.sidebarVisible,n.sidebarDefaultOpen)),n.componentPaletteDefaultOpen!==void 0&&(r.componentPaletteVisible=n.componentPaletteDefaultOpen,wi(Go.componentPaletteVisible,n.componentPaletteDefaultOpen)),n.consolePanelDefaultOpen!==void 0&&(r.consolePanelVisible=n.consolePanelDefaultOpen,wi(Go.consolePanelVisible,n.consolePanelDefaultOpen)),Object.keys(r).length>0&&e(r)},getWorkflowUIState:n=>{const{workflowUIStates:r}=t();return r[n]||$u()},setWorkflowExecuting:(n,r)=>{e(o=>{const a=o.workflowUIStates[n];return{workflowUIStates:{...o.workflowUIStates,[n]:{...a||$u(),isExecuting:r}}}})},setWorkflowExecutedNodes:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),executedNodes:r}}}))},setWorkflowExecutionOrder:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),executionOrder:r}}}))},setWorkflowViewport:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||$u(),viewport:r}}}))},clearWorkflowExecutionState:n=>{e(r=>({workflowUIStates:{...r.workflowUIStates,[n]:{...r.workflowUIStates[n]||$u(),isExecuting:!1,executedNodes:[],executionOrder:[]}}}))},updateNodeData:(n,r)=>{const{currentWorkflow:o,selectedNode:a}=t();if(!o)return;const i=o.nodes.map(d=>d.id===n?{...d,data:{...d.data,...r}}:d),s={...o,nodes:i,lastModified:new Date};e({currentWorkflow:s,hasUnsavedChanges:!0,selectedNode:a?.id===n?{...a,data:{...a.data,...r}}:a})},updateNodes:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,nodes:n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},updateEdges:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,edges:n,lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},addNode:n=>{const{currentWorkflow:r}=t();if(!r)return;const o={...r,nodes:[...r.nodes,n],lastModified:new Date};e({currentWorkflow:o,hasUnsavedChanges:!0})},removeNodes:n=>{const{currentWorkflow:r}=t();if(!r)return;const o=r.nodes.filter(s=>!n.includes(s.id)),a=r.edges.filter(s=>!n.includes(s.source)&&!n.includes(s.target)),i={...r,nodes:o,edges:a,lastModified:new Date};e({currentWorkflow:i,hasUnsavedChanges:!0,selectedNode:n.includes(t().selectedNode?.id||"")?null:t().selectedNode})},removeEdges:n=>{const{currentWorkflow:r}=t();if(!r)return;const o=r.edges.filter(i=>!n.includes(i.id)),a={...r,edges:o,lastModified:new Date};e({currentWorkflow:a,hasUnsavedChanges:!0})},exportWorkflowToJSON:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");return _8e(r,n)},exportWorkflowToFile:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");$8e(r,n)},importWorkflowFromJSON:n=>{const r=j8e(n);return e({currentWorkflow:r,hasUnsavedChanges:!0}),r}})),gD=u.createContext(void 0),k8e=({children:e})=>{const[t,n]=u.useState(()=>{const o=localStorage.getItem("darkMode");return o===null?!0:o==="true"});u.useEffect(()=>{localStorage.setItem("darkMode",t.toString()),t?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[t]);const r=()=>{n(o=>!o)};return g.jsx(gD.Provider,{value:{isDarkMode:t,toggleTheme:r},children:e})},mg=()=>{const e=u.useContext(gD);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e},_n=()=>{const{isDarkMode:e}=mg();return u.useMemo(()=>({...ht,colors:e?Kr:ga,isDarkMode:e}),[e])},hD=u.createContext(void 0),Jh=()=>`${$c.PYTHON_BASE_URL}/api/auth`,N8e=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(!0),[a,i]=u.useState("single"),[s,d]=u.useState(!1),[f,p]=u.useState(null),m=u.useCallback(async(x=0)=>{try{const O=await(await fetch(`${Jh()}/status`,{credentials:"include"})).json();if(O.auth_enabled===!1){n({id:0,email:"anonymous",display_name:"Anonymous",is_owner:!0}),o(!1),p(null);return}i(O.auth_mode),d(O.can_register),O.authenticated&&O.user?n(O.user):n(null),p(null),o(!1)}catch($){if(console.error(`Failed to check auth status (attempt ${x+1}/6):`,$),x<5){const O=1e3*Math.pow(2,x);console.log(`Retrying in ${O}ms...`),setTimeout(()=>m(x+1),O)}else n(null),p("Failed to connect to server"),o(!1)}},[]);u.useEffect(()=>{m()},[m]);const y=u.useCallback(async(x,C)=>{p(null),o(!0);try{const E=await fetch(`${Jh()}/login`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C})}),$=await E.json();return E.ok?$.success&&$.user?(n($.user),o(!1),!0):(p("Login failed"),o(!1),!1):(p($.detail||"Login failed"),o(!1),!1)}catch(E){return console.error("Login error:",E),p("Failed to connect to server"),o(!1),!1}},[]),v=u.useCallback(async(x,C,E)=>{p(null),o(!0);try{const $=await fetch(`${Jh()}/register`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C,display_name:E})}),O=await $.json();return $.ok?O.success&&O.user?(n(O.user),d(!1),o(!1),!0):(p("Registration failed"),o(!1),!1):(p(O.detail||"Registration failed"),o(!1),!1)}catch($){return console.error("Register error:",$),p("Failed to connect to server"),o(!1),!1}},[]),w=u.useCallback(async()=>{try{await fetch(`${Jh()}/logout`,{method:"POST",credentials:"include"})}catch(x){console.error("Logout error:",x)}finally{n(null),await m()}},[m]),b={user:t,isAuthenticated:t!==null,isLoading:r,authMode:a,canRegister:s,error:f,login:y,register:v,logout:w,checkAuth:m};return g.jsx(hD.Provider,{value:b,children:e})},jy=()=>{const e=u.useContext(hD);if(e===void 0)throw new Error("useAuth must be used within an AuthProvider");return e},Wj=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,M8e=3e4,T8e=["whatsappReceive","webhookTrigger","cronScheduler","chatTrigger","telegramReceive"],R8e=["aiAgent","chatAgent","rlm_agent","android_agent","coding_agent","web_agent","task_agent","social_agent","travel_agent","tool_agent","productivity_agent","payments_agent","consumer_agent","autonomous_agent","orchestrator_agent","ai_employee","deep_agent"],Vj={connected:!1,paired:!1,device_id:null,device_name:null,connected_devices:[],connection_type:null,qr_data:null,session_token:null},Uj={executing:!1,current_node:null},qj={isRunning:!1,activeRuns:0,status:"idle"},A8e={locked:!1,workflow_id:null,locked_at:null,reason:null},Gj={connected:!1,has_session:!1,running:!1,pairing:!1},I8e={connected:!1,username:null,user_id:null},z8e={connected:!1,email:null},P8e={connected:!1,bot_username:null,bot_name:null,bot_id:null,owner_chat_id:null},yD=u.createContext(null),D8e=()=>{const e=$c.PYTHON_BASE_URL;if(!e)return`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws/status`;const t=e.startsWith("https")?"wss":"ws";return`${e.replace(/^https?/,t)}/ws/status`},L8e=100,F8e=({children:e})=>{const{isAuthenticated:t,isLoading:n}=jy(),o=Sr(de=>de.currentWorkflow)?.id,[a,i]=u.useState(!1),[s,d]=u.useState(!1),[f,p]=u.useState(Vj),[m,y]=u.useState(Gj),[v,w]=u.useState(I8e),[b,x]=u.useState(z8e),[C,E]=u.useState(P8e),[$,O]=u.useState([]),[_,j]=u.useState(null),[N,A]=u.useState({}),[I,R]=u.useState([]),[B,z]=u.useState([]),[L,T]=u.useState([]),[F,P]=u.useState({}),[H,D]=u.useState({}),[q,W]=u.useState({}),[U,G]=u.useState(Uj),[V,X]=u.useState(qj),[Q,J]=u.useState(A8e),[te,ae]=u.useState({}),ee=u.useRef(null),ve=u.useRef(null),pe=u.useRef(null),fe=u.useRef(new Map),Ce=u.useRef(o);u.useEffect(()=>{const de=Ce.current;Ce.current=o,de&&o&&de!==o&&ee.current?.readyState===WebSocket.OPEN&&(async()=>{try{const Me=Wj(),se=await new Promise((ct,Nt)=>{const et=setTimeout(()=>Nt(new Error("Timeout")),5e3),gt=Ve=>{try{const Et=JSON.parse(Ve.data);Et.request_id===Me&&(clearTimeout(et),ee.current?.removeEventListener("message",gt),ct(Et))}catch{}};ee.current?.addEventListener("message",gt),ee.current?.send(JSON.stringify({type:"get_deployment_status",request_id:Me,workflow_id:o}))}),Ne=se.is_running||!1;X({isRunning:Ne,activeRuns:se.active_runs||0,status:Ne?"running":"idle",workflow_id:se.workflow_id||null});const{setWorkflowExecuting:ze}=Sr.getState();ze(o,Ne),J({locked:Ne,workflow_id:Ne?o:null,locked_at:Ne?Date.now():null,reason:Ne?"Workflow is running":null})}catch(Me){console.error("[WebSocket] Failed to fetch deployment status:",Me)}})()},[o]);const $e=u.useCallback(de=>{try{const ce=JSON.parse(de.data),{type:Me,data:se,node_id:Ne,name:ze,value:ct,output:Nt,variables:et,request_id:gt}=ce;if(gt&&fe.current.has(gt)){const Ve=fe.current.get(gt);Ve.timeout&&clearTimeout(Ve.timeout),fe.current.delete(gt),Ve.resolve(ce);return}switch(Me){case"initial_status":case"full_status":if(se){if(se.android&&p(se.android),se.whatsapp&&y(se.whatsapp),se.twitter&&w(se.twitter),se.google&&x(se.google),se.telegram&&E(se.telegram),se.api_keys&&A(se.api_keys),se.nodes){const Ve={};for(const[Et,Gt]of Object.entries(se.nodes)){const Ke=Gt,Ze=Ke?.workflow_id||"unknown";Ve[Ze]||(Ve[Ze]={}),Ve[Ze][Et]=Ke}P(Et=>({...Et,...Ve}))}if(se.node_parameters&&D(se.node_parameters),se.variables){const Ve={};for(const[Et,Gt]of Object.entries(se.variables)){const Ke=Gt?.workflow_id||"unknown";Ve[Ke]||(Ve[Ke]={}),Ve[Ke][Et]=Gt}W(Et=>({...Et,...Ve}))}se.workflow&&G(se.workflow),se.workflow_lock&&J(se.workflow_lock),se.deployment&&X({isRunning:se.deployment.isRunning||!1,activeRuns:se.deployment.activeRuns||0,status:se.deployment.status||"idle"})}break;case"api_key_status":ce.provider&&A(Ve=>({...Ve,[ce.provider]:se}));break;case"android_status":p(se||Vj);break;case"whatsapp_status":y(se||Gj);break;case"twitter_oauth_complete":se?.success&&w({connected:!0,username:se.username||null,user_id:se.user_id||null,name:se.name,profile_image_url:se.profile_image_url});break;case"google_oauth_complete":se?.success&&x({connected:!0,email:se.email||null,name:se.name,profile_image_url:se.profile_image_url});break;case"google_status":se&&x({connected:se.connected||!1,email:se.email||null,name:se.name});break;case"telegram_status":se&&E({connected:se.connected||!1,bot_username:se.bot_username||null,bot_name:se.bot_name||null,bot_id:se.bot_id||null,owner_chat_id:se.owner_chat_id??null});break;case"whatsapp_message_received":if(se){const Ve={message_id:se.message_id||se.id||"",sender:se.sender||se.from||"",chat_id:se.chat_id||se.chat||"",type:se.type||"text",text:se.text||se.message||se.body||"",timestamp:se.timestamp||Date.now(),is_group:se.is_group||se.isGroup||!1,push_name:se.push_name||se.pushName||se.name,media_url:se.media_url||se.mediaUrl,media_data:se.media_data||se.mediaData,caption:se.caption,latitude:se.latitude,longitude:se.longitude,contact_name:se.contact_name||se.contactName,vcard:se.vcard};j(Ve),O(Et=>[Ve,...Et].slice(0,L8e))}break;case"node_status":if(Ne){const Ve=ce.workflow_id||"unknown",Et=se?.data||{},Gt={...se,...Et,workflow_id:Ve};P(Ke=>({...Ke,[Ve]:{...Ke[Ve]||{},[Ne]:Gt}}))}break;case"node_output":if(Ne){const Ve=ce.workflow_id||"unknown";P(Et=>({...Et,[Ve]:{...Et[Ve]||{},[Ne]:{...Et[Ve]?.[Ne]||{},output:Nt,workflow_id:Ve}}}))}break;case"node_status_cleared":if(Ne||ce.node_id){const Ve=Ne||ce.node_id,Et=ce.workflow_id;P(Gt=>{if(Et&&Gt[Et]){const Ze={...Gt[Et]};return delete Ze[Ve],{...Gt,[Et]:Ze}}const Ke={};for(const[Ze,it]of Object.entries(Gt)){const Yt={...it};delete Yt[Ve],Ke[Ze]=Yt}return Ke})}break;case"node_parameters_updated":Ne&&D(Ve=>({...Ve,[Ne]:{parameters:ce.parameters,version:ce.version,timestamp:ce.timestamp}}));break;case"node_parameters_deleted":Ne&&D(Ve=>{const Et={...Ve};return delete Et[Ne],Et});break;case"variable_update":if(ze!==void 0){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},[ze]:ct}}))}break;case"variables_update":if(et){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},...et}}))}break;case"workflow_status":G(se||Uj);break;case"deployment_status":if(ce.status){const Ve=ce.workflow_id,Et=Ce.current,Gt=["stopped","cancelled","error"].includes(ce.status);if((!Ve||Ve===Et||Gt)&&(X(Ze=>{const it={...Ze};switch(ce.workflow_id&&(it.workflow_id=ce.workflow_id),ce.status){case"starting":it.isRunning=!0,it.status="starting",it.activeRuns=0;break;case"running":case"started":it.isRunning=!0,it.status="running",it.activeRuns=ce.data?.active_runs??Ze.activeRuns;break;case"run_started":it.isRunning=!0,it.status="running",it.activeRuns=ce.data?.active_runs||Ze.activeRuns+1;break;case"run_complete":it.activeRuns=Math.max(0,ce.data?.active_runs||Ze.activeRuns-1);break;case"stopped":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="stopped",it.totalTime=ce.data?.total_time,it.activeRuns=0,it.workflow_id=null);break;case"cancelled":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="cancelled",it.activeRuns=0,it.workflow_id=null);break;case"error":(!Ze.workflow_id||Ze.workflow_id===Ve)&&(it.isRunning=!1,it.status="error",it.error=ce.error,it.workflow_id=null);break}return it}),Ve)){const{setWorkflowExecuting:Ze}=Sr.getState(),it=["starting","running","started","run_started"].includes(ce.status),Yt=["stopped","cancelled","error"].includes(ce.status);(it||Yt)&&Ze(Ve,it)}}break;case"pong":break;case"console_log":if(se){const Ve={node_id:se.node_id||"",label:se.label||"Console",timestamp:se.timestamp||new Date().toISOString(),data:se.data,formatted:se.formatted||JSON.stringify(se.data,null,2),format:se.format||"json",workflow_id:se.workflow_id,source_node_id:se.source_node_id,source_node_type:se.source_node_type,source_node_label:se.source_node_label};R(Et=>[Ve,...Et].slice(0,100))}break;case"console_logs_cleared":ce.workflow_id?R(Ve=>Ve.filter(Et=>Et.workflow_id!==ce.workflow_id)):R([]);break;case"terminal_log":if(se){const Ve={timestamp:se.timestamp||new Date().toISOString(),level:se.level||"info",message:se.message||"",source:se.source,details:se.details};z(Et=>[Ve,...Et].slice(0,200))}break;case"terminal_logs_cleared":z([]);break;case"workflow_lock":if(se){const Ve=ce.workflow_id||se.workflow_id,Et=Ce.current;(!Ve||Ve===Et||!se.locked)&&J({locked:se.locked||!1,workflow_id:se.workflow_id||null,locked_at:se.locked_at||null,reason:se.reason||null})}break;case"token_usage_update":{const Ve=ce.session_id,Et=ce.workflow_id||Ce.current||"",Gt=ce.data||{};Ve&&Et&&ae(Ke=>{const Ze=Ke[Et]||{},it=Ze[Ve];return{...Ke,[Et]:{...Ze,[Ve]:{session_id:Ve,total:Gt.total??it?.total??0,threshold:Gt.threshold??it?.threshold??0,count:it?.count??0,total_cost:Gt.total_cost??it?.total_cost}}}});break}case"compaction_completed":{const Ve=ce.session_id;Ve&&ae(Et=>{const Gt={...Et};for(const Ke of Object.keys(Gt))Gt[Ke]?.[Ve]&&(Gt[Ke]={...Gt[Ke],[Ve]:{...Gt[Ke][Ve],count:(Gt[Ke][Ve].count||0)+(ce.success?1:0),total:ce.tokens_after??Gt[Ke][Ve].total}});return Gt});break}case"compaction_starting":break;case"error":console.error("[WebSocket] Server error:",ce.code,ce.message);break;default:break}}catch(ce){console.error("[WebSocket] Failed to parse message:",ce)}},[]),re=u.useCallback(()=>{if(ee.current?.readyState===WebSocket.OPEN)return;const de=D8e();try{const ce=new WebSocket(de);ce.onopen=async()=>{i(!0),d(!1),pe.current=setInterval(()=>{ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"ping"}))},3e4);const Me=["openai","anthropic","gemini","google_maps","android_remote"];for(const se of Me)try{(await new Promise((ze,ct)=>{const Nt=`init_${se}_${Date.now()}`,et=setTimeout(()=>ct(new Error("Timeout")),5e3),gt=Ve=>{try{const Et=JSON.parse(Ve.data);Et.request_id===Nt&&(clearTimeout(et),ce.removeEventListener("message",gt),ze(Et))}catch{}};ce.addEventListener("message",gt),ce.send(JSON.stringify({type:"get_stored_api_key",provider:se,request_id:Nt}))})).has_key&&A(ze=>({...ze,[se]:{hasKey:!0,valid:!0}}))}catch{}try{const se=await new Promise((Ne,ze)=>{const ct=`terminal_logs_${Date.now()}`,Nt=setTimeout(()=>ze(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===ct&&(clearTimeout(Nt),ce.removeEventListener("message",et),Ne(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_terminal_logs",request_id:ct}))});if(se.success&&se.logs){const Ne=se.logs.map(ze=>({timestamp:ze.timestamp||new Date().toISOString(),level:ze.level||"info",message:ze.message||"",source:ze.source,details:ze.details})).reverse();z(Ne)}}catch{}try{const se=await new Promise((Ne,ze)=>{const ct=`chat_messages_${Date.now()}`,Nt=setTimeout(()=>ze(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===ct&&(clearTimeout(Nt),ce.removeEventListener("message",et),Ne(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_chat_messages",session_id:"default",request_id:ct}))});if(se.success&&se.messages){const Ne=se.messages.map(ze=>({role:ze.role,message:ze.message,timestamp:ze.timestamp}));T(Ne)}}catch{}try{const se=`console_${Date.now()}`,Ne=await new Promise((ze,ct)=>{const Nt=setTimeout(()=>ct(new Error("Timeout")),5e3),et=gt=>{try{const Ve=JSON.parse(gt.data);Ve.request_id===se&&(clearTimeout(Nt),ce.removeEventListener("message",et),ze(Ve))}catch{}};ce.addEventListener("message",et),ce.send(JSON.stringify({type:"get_console_logs",limit:100,request_id:se}))});if(Ne.success&&Ne.logs){const ze=Ne.logs.map(ct=>({node_id:ct.node_id,label:ct.label,timestamp:ct.timestamp,data:ct.data,formatted:ct.formatted,format:ct.format,workflow_id:ct.workflow_id,source_node_id:ct.source_node_id,source_node_type:ct.source_node_type,source_node_label:ct.source_node_label}));R(ze)}}catch{}},ce.onmessage=$e,ce.onclose=Me=>{console.log("[WebSocket] Disconnected:",Me.code,Me.reason),i(!1),ee.current=null,pe.current&&(clearInterval(pe.current),pe.current=null),Me.code!==1e3&&(d(!0),ve.current=setTimeout(()=>{re()},3e3))},ce.onerror=Me=>{console.error("[WebSocket] Error:",Me)},ee.current=ce}catch(ce){console.error("[WebSocket] Failed to create connection:",ce),d(!0),ve.current=setTimeout(re,3e3)}},[$e]),Z=u.useCallback(()=>{ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"get_status"}))},[]),ie=u.useCallback(de=>{if(o)return F[o]?.[de]},[F,o]),le=u.useCallback(de=>N[de],[N]),be=u.useCallback(de=>{if(o)return q[o]?.[de]},[q,o]),Oe=u.useCallback(async de=>{const ce=Ce.current;P(Me=>{if(!ce||!Me[ce])return Me;const se={...Me[ce]};return delete se[de],{...Me,[ce]:se}});try{ee.current&&ee.current.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_node_output",node_id:de,workflow_id:ce}))}catch(Me){console.error("[WebSocket] Failed to clear backend node output:",Me)}},[]),Pe=u.useCallback(()=>{O([]),j(null)},[]),Be=u.useCallback(()=>{R([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_console_logs"}))},[]),Ae=u.useCallback(()=>{z([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_terminal_logs"}))},[]),Ee=u.useCallback(()=>{T([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_chat_messages",session_id:"default"}))},[]),qe=u.useMemo(()=>o?F[o]||{}:{},[F,o]),xe=u.useMemo(()=>o?q[o]||{}:{},[q,o]),Re=u.useMemo(()=>o?te[o]||{}:{},[te,o]),De=u.useCallback((de,ce,Me)=>{ae(se=>({...se,[de]:{...se[de]||{},[ce]:Me}}))},[]),he=u.useCallback(async(de,ce,Me)=>new Promise((se,Ne)=>{if(!ee.current||ee.current.readyState!==WebSocket.OPEN){Ne(new Error("WebSocket not connected"));return}const ze=Wj(),ct=Me===void 0||Me>=0,Nt=Me&&Me>0?Me:M8e;let et=null;ct&&Me!==-1&&(et=setTimeout(()=>{fe.current.delete(ze),Ne(new Error(`Request timeout: ${de}`))},Nt)),fe.current.set(ze,{resolve:se,reject:Ne,timeout:et}),ee.current.send(JSON.stringify({type:de,request_id:ze,...ce}))}),[]),Qe=u.useCallback(async(de,ce)=>{const Me=new Date().toISOString(),se={role:"user",message:de,timestamp:Me};T(Ne=>[...Ne,se]);try{await he("send_chat_message",{message:de,role:"user",node_id:ce,session_id:"default",timestamp:Me})}catch(Ne){throw console.error("[WebSocket] Failed to send chat message:",Ne),Ne}},[he]),Je=u.useCallback(async de=>{try{const ce=await he("get_node_parameters",{node_id:de});if(ce.parameters){const Me={parameters:ce.parameters,version:ce.version||0,timestamp:ce.timestamp};return D(se=>({...se,[de]:Me})),Me}return null}catch(ce){return console.error("[WebSocket] Failed to get node parameters:",ce),null}},[he]),lt=u.useCallback(async de=>{if(!de.length)return{};try{const ce=await he("get_all_node_parameters",{node_ids:de}),Me={};if(ce.parameters){for(const[se,Ne]of Object.entries(ce.parameters))Me[se]={parameters:Ne.parameters||{},version:Ne.version||0,timestamp:ce.timestamp};D(se=>({...se,...Me}))}return Me}catch(ce){return console.error("[WebSocket] Failed to get all node parameters:",ce),{}}},[he]),tt=u.useCallback(async(de,ce,Me)=>{try{const se=H[de]?.version||Me||0,Ne=await he("save_node_parameters",{node_id:de,parameters:ce,version:se});return Ne.success!==!1?(D(ze=>({...ze,[de]:{parameters:Ne.parameters||ce,version:Ne.version||se+1,timestamp:Ne.timestamp}})),!0):!1}catch(se){return console.error("[WebSocket] Failed to save node parameters:",se),!1}},[he,H]),we=u.useCallback(async de=>{try{return await he("delete_node_parameters",{node_id:de}),D(ce=>{const Me={...ce};return delete Me[de],Me}),!0}catch(ce){return console.error("[WebSocket] Failed to delete node parameters:",ce),!1}},[he]),Ge=u.useCallback(async(de,ce,Me,se,Ne)=>{try{const ct=T8e.includes(ce)||R8e.includes(ce)?-1:void 0;return await he("execute_node",{node_id:de,node_type:ce,parameters:Me,nodes:se,edges:Ne,workflow_id:o},ct)}catch(ze){throw console.error("[WebSocket] Failed to execute node:",ze),ze}},[he,o]),je=u.useCallback(async(de,ce)=>{try{const Me=await he("get_node_output",{node_id:de,output_name:ce||"output_0"});return Me.success?Me.data:null}catch(Me){return console.error("[WebSocket] Failed to get node output:",Me),null}},[he]),Le=u.useCallback(async(de,ce)=>{try{return await he("cancel_event_wait",{node_id:de,waiter_id:ce})}catch(Me){return console.error("[WebSocket] Failed to cancel event wait:",Me),{success:!1}}},[he]),dt=u.useCallback(async(de,ce,Me)=>{try{return await he("execute_workflow",{nodes:de.map(Ne=>({id:Ne.id,type:Ne.type||"",data:Ne.data||{}})),edges:ce.map(Ne=>({id:Ne.id,source:Ne.source,target:Ne.target,sourceHandle:Ne.sourceHandle||void 0,targetHandle:Ne.targetHandle||void 0})),session_id:Me||"default"})}catch(se){throw console.error("[WebSocket] Failed to execute workflow:",se),se}},[he]),St=u.useCallback(async(de,ce,Me,se)=>{try{return await he("deploy_workflow",{workflow_id:de,nodes:ce.map(ze=>({id:ze.id,type:ze.type||"",data:ze.data||{}})),edges:Me.map(ze=>({id:ze.id,source:ze.source,target:ze.target,sourceHandle:ze.sourceHandle||void 0,targetHandle:ze.targetHandle||void 0})),session_id:se||"default"})}catch(Ne){throw console.error("[WebSocket] Failed to start deployment:",Ne),Ne}},[he]),Kt=u.useCallback(async de=>{try{const ce=await he("cancel_deployment",{workflow_id:de});return(!de||de===V.workflow_id)&&X(qj),ce}catch(ce){throw console.error("[WebSocket] Failed to cancel deployment:",ce),ce}},[he,V.workflow_id]),Xt=u.useCallback(async de=>{try{const ce=await he("get_deployment_status",{workflow_id:de});return{isRunning:ce.is_running||!1,activeRuns:ce.active_runs||0,settings:ce.settings,workflow_id:ce.workflow_id}}catch(ce){return console.error("[WebSocket] Failed to get deployment status:",ce),{isRunning:!1,activeRuns:0}}},[he]),mt=u.useCallback(async(de,ce,Me,se,Ne,ze,ct)=>{try{return await he("execute_ai_node",{node_id:de,node_type:ce,parameters:Me,model:se,workflow_id:Ne,nodes:ze,edges:ct},-1)}catch(Nt){throw console.error("[WebSocket] Failed to execute AI node:",Nt),Nt}},[he]),rt=u.useCallback(async(de,ce)=>{try{return(await he("get_ai_models",{provider:de,api_key:ce})).models||[]}catch(Me){return console.error("[WebSocket] Failed to get AI models:",Me),[]}},[he]),yt=u.useCallback(async(de,ce)=>{try{const Me=await he("validate_api_key",{provider:de,api_key:ce}),se={valid:Me.valid||!1,message:Me.message,models:Me.models};return se.valid&&A(Ne=>({...Ne,[de]:{hasKey:!0,valid:!0,models:se.models}})),se}catch(Me){return console.error("[WebSocket] Failed to validate API key:",Me),{valid:!1,message:"Validation failed"}}},[he]),ut=u.useCallback(async de=>{try{const ce=await he("get_stored_api_key",{provider:de}),Me={hasKey:ce.has_key||!1,apiKey:ce.api_key,models:ce.models};return Me.hasKey&&A(se=>({...se,[de]:{hasKey:!0,valid:!0,models:Me.models}})),Me}catch(ce){return console.error("[WebSocket] Failed to get stored API key:",ce),{hasKey:!1}}},[he]),Ct=u.useCallback(async(de,ce,Me)=>{try{const Ne=(await he("save_api_key",{provider:de,api_key:ce,models:Me})).success!==!1;return Ne&&A(ze=>({...ze,[de]:{hasKey:!0,valid:!0,models:Me}})),Ne}catch(se){return console.error("[WebSocket] Failed to save API key:",se),!1}},[he]),Bt=u.useCallback(async de=>{try{return await he("delete_api_key",{provider:de}),A(ce=>{const Me={...ce};return delete Me[de],Me}),!0}catch(ce){return console.error("[WebSocket] Failed to delete API key:",ce),!1}},[he]),Ht=u.useCallback(async()=>{try{return(await he("get_android_devices",{})).devices||[]}catch(de){return console.error("[WebSocket] Failed to get Android devices:",de),[]}},[he]),wt=u.useCallback(async(de,ce,Me,se)=>{try{return await he("execute_android_action",{service_id:de,action:ce,parameters:Me,device_id:se})}catch(Ne){throw console.error("[WebSocket] Failed to execute Android action:",Ne),Ne}},[he]),It=u.useCallback(async de=>{try{const ce=await he("validate_maps_key",{api_key:de});return{valid:ce.valid||!1,message:ce.message}}catch(ce){return console.error("[WebSocket] Failed to validate Maps key:",ce),{valid:!1,message:"Validation failed"}}},[he]),Mt=u.useCallback(async de=>{try{const ce=await he("validate_apify_key",{api_key:de});return{valid:ce.valid||!1,message:ce.message,username:ce.username}}catch(ce){return console.error("[WebSocket] Failed to validate Apify key:",ce),{valid:!1,message:"Validation failed"}}},[he]),ot=u.useCallback(async()=>{try{const de=await he("whatsapp_status",{});return{connected:de.connected||!1,deviceId:de.device_id,data:de.data}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp status:",de),{connected:!1}}},[he]),Fe=u.useCallback(async()=>{try{const de=await he("whatsapp_qr",{});return{connected:de.connected||!1,qr:de.qr,message:de.message}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp QR:",de),{connected:!1,message:"Failed to get QR code"}}},[he]),Xe=u.useCallback(async(de,ce)=>{try{const Me=await he("whatsapp_send",{phone:de,message:ce});return{success:Me.success||!1,messageId:Me.messageId,error:Me.error}}catch(Me){return console.error("[WebSocket] Failed to send WhatsApp message:",Me),{success:!1,error:Me.message||"Send failed"}}},[he]),at=u.useCallback(async()=>{try{const de=await he("whatsapp_start",{});return{success:de.success!==!1,message:de.message}}catch(de){return console.error("[WebSocket] Failed to start WhatsApp connection:",de),{success:!1,message:de.message||"Failed to start"}}},[he]),$t=u.useCallback(async()=>{try{const de=await he("whatsapp_restart",{});return{success:de.success!==!1,message:de.message}}catch(de){return console.error("[WebSocket] Failed to restart WhatsApp connection:",de),{success:!1,message:de.message||"Failed to restart"}}},[he]),jt=u.useCallback(async()=>{try{const de=await he("whatsapp_groups",{});return{success:de.success!==!1,groups:de.groups||[],error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp groups:",de),{success:!1,groups:[],error:de.message||"Failed to get groups"}}},[he]),Wt=u.useCallback(async()=>{try{const de=await he("whatsapp_newsletters",{}),ce=de.channels||de.result?.channels||[];return{success:de.success!==!1,channels:ce,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp channels:",de),{success:!1,channels:[],error:de.message||"Failed to get channels"}}},[he]),Pt=u.useCallback(async de=>{try{const ce=await he("whatsapp_group_info",{group_id:de});return{success:ce.success!==!1,participants:ce.participants||[],name:ce.name,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to get WhatsApp group info:",ce),{success:!1,participants:[],error:ce.message||"Failed to get group info"}}},[he]),Rt=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_get",{});return{success:de.success!==!1,config:de.config,stats:de.stats,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp rate limit config:",de),{success:!1,error:de.message||"Failed to get rate limit config"}}},[he]),en=u.useCallback(async de=>{try{const ce=await he("whatsapp_rate_limit_set",{config:de});return{success:ce.success!==!1,config:ce.config,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to set WhatsApp rate limit config:",ce),{success:!1,error:ce.message||"Failed to set rate limit config"}}},[he]),yn=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_stats",{});return{success:de.success!==!1,stats:de.stats||de,error:de.error}}catch(de){return console.error("[WebSocket] Failed to get WhatsApp rate limit stats:",de),{success:!1,error:de.message||"Failed to get rate limit stats"}}},[he]),Te=u.useCallback(async()=>{try{const de=await he("whatsapp_rate_limit_unpause",{});return{success:de.success!==!1,stats:de.stats,error:de.error}}catch(de){return console.error("[WebSocket] Failed to unpause WhatsApp rate limit:",de),{success:!1,error:de.message||"Failed to unpause rate limit"}}},[he]),Ot=u.useCallback(async(de,ce=!1)=>{try{const Me=await he("clear_memory",{session_id:de,clear_long_term:ce});return{success:Me.success!==!1,default_content:Me.default_content,cleared_vector_store:Me.cleared_vector_store,error:Me.error}}catch(Me){return console.error("[WebSocket] Failed to clear memory:",Me),{success:!1,error:Me.message||"Failed to clear memory"}}},[he]),Vt=u.useCallback(async de=>{try{const ce=await he("reset_skill",{skill_name:de});return{success:ce.success!==!1,original_content:ce.original_content,is_builtin:ce.is_builtin,error:ce.error}}catch(ce){return console.error("[WebSocket] Failed to reset skill:",ce),{success:!1,error:ce.message||"Failed to reset skill"}}},[he]),Lt=u.useRef(!0);u.useEffect(()=>{if(Lt.current=!0,n||!t||ee.current?.readyState===WebSocket.OPEN)return;const de=setTimeout(()=>{Lt.current&&t&&!ee.current&&re()},100);return()=>{clearTimeout(de)}},[re,t,n]),u.useEffect(()=>{!t&&ee.current&&(ee.current.close(1e3,"User logged out"),ee.current=null,i(!1))},[t]),u.useEffect(()=>()=>{Lt.current=!1,ve.current&&clearTimeout(ve.current),pe.current&&clearInterval(pe.current),ee.current?.readyState===WebSocket.OPEN&&ee.current.close(1e3,"Component unmounted")},[]);const cn={isConnected:a,reconnecting:s,androidStatus:f,setAndroidStatus:p,whatsappStatus:m,twitterStatus:v,googleStatus:b,telegramStatus:C,whatsappMessages:$,lastWhatsAppMessage:_,apiKeyStatuses:N,consoleLogs:I,terminalLogs:B,chatMessages:L,nodeStatuses:qe,nodeParameters:H,variables:xe,workflowStatus:U,deploymentStatus:V,workflowLock:Q,compactionStats:Re,updateCompactionStats:De,getNodeStatus:ie,getApiKeyStatus:le,getVariable:be,requestStatus:Z,clearNodeStatus:Oe,clearWhatsAppMessages:Pe,clearConsoleLogs:Be,clearTerminalLogs:Ae,clearChatMessages:Ee,sendChatMessage:Qe,sendRequest:he,getNodeParameters:Je,getAllNodeParameters:lt,saveNodeParameters:tt,deleteNodeParameters:we,executeNode:Ge,executeWorkflow:dt,getNodeOutput:je,cancelEventWait:Le,deployWorkflow:St,cancelDeployment:Kt,getDeploymentStatus:Xt,executeAiNode:mt,getAiModels:rt,validateApiKey:yt,getStoredApiKey:ut,saveApiKey:Ct,deleteApiKey:Bt,getAndroidDevices:Ht,executeAndroidAction:wt,validateMapsKey:It,validateApifyKey:Mt,getWhatsAppStatus:ot,getWhatsAppQR:Fe,sendWhatsAppMessage:Xe,startWhatsAppConnection:at,restartWhatsAppConnection:$t,getWhatsAppGroups:jt,getWhatsAppChannels:Wt,getWhatsAppGroupInfo:Pt,getWhatsAppRateLimitConfig:Rt,setWhatsAppRateLimitConfig:en,getWhatsAppRateLimitStats:yn,unpauseWhatsAppRateLimit:Te,clearMemory:Ot,resetSkill:Vt};return g.jsx(yD.Provider,{value:cn,children:e})},Qn=()=>{const e=u.useContext(yD);if(!e)throw new Error("useWebSocket must be used within a WebSocketProvider");return e},B8e=()=>{const{androidStatus:e,isConnected:t}=Qn();return{...e,isConnected:t}},vD=e=>{const{getNodeStatus:t}=Qn();return t(e)},F5=()=>{const{whatsappStatus:e}=Qn();return e},H8e=()=>{const{twitterStatus:e}=Qn();return e},W8e=()=>{const{googleStatus:e}=Qn();return e},V8e=()=>{const{telegramStatus:e}=Qn();return e},U8e=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i,renamingNodeId:s,setRenamingNodeId:d,updateNodeData:f}=Sr(),{getNodeStatus:p}=Qn(),m=n?.disabled===!0,v=p(e)?.status||"idle",w=v==="executing"||v==="waiting",b=t&&wr[t]?wr[t]:null,[x,C]=u.useState(!1),[E,$]=u.useState(""),O=u.useRef(null);u.useEffect(()=>{s===e?(C(!0),$(n?.label||b?.displayName||t||"")):C(!1)},[s,e,n?.label,b?.displayName,t]),u.useEffect(()=>{x&&O.current&&(O.current.focus(),O.current.select())},[x]);const _=u.useCallback(()=>{const H=E.trim(),D=n?.label||b?.displayName||t||"";H&&H!==D&&f(e,{...n,label:H}),C(!1),d(null)},[E,n,b?.displayName,t,e,f,d]),j=u.useCallback(()=>{C(!1),d(null)},[d]),N=u.useCallback(H=>{H.stopPropagation(),d(e)},[e,d]),A=H=>{H.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})};if(!t||!b)return g.jsx("div",{style:{padding:"8px 12px",backgroundColor:"#ef4444",color:"white",borderRadius:"8px",fontSize:"12px",minWidth:"120px",textAlign:"center"},children:"Unknown node type"});const I=()=>b.inputs?b.inputs.length>0&&typeof b.inputs[0]=="object"?b.inputs:b.inputs.map((H,D)=>({name:`input_${D}`,displayName:"Input",type:H||"main",description:"Node input connection"})):[],R=()=>b.outputs?b.outputs.length>0&&typeof b.outputs[0]=="object"?b.outputs:b.outputs.map((H,D)=>({name:`output_${D}`,displayName:"Output",type:H||"main",description:"Node output connection"})):[],B=I(),z=R(),L=H=>/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F600}-\u{1F64F}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2300}-\u{23FF}]|[\u{2B50}]|[\u{231A}-\u{231B}]|[\u{25AA}-\u{25AB}]|[\u{25B6}]|[\u{25C0}]|[\u{25FB}-\u{25FE}]|[\u{2614}-\u{2615}]|[\u{2648}-\u{2653}]|[\u{267F}]|[\u{2693}]|[\u{26A1}]|[\u{26AA}-\u{26AB}]|[\u{26BD}-\u{26BE}]|[\u{26C4}-\u{26C5}]|[\u{26CE}]|[\u{26D4}]|[\u{26EA}]|[\u{26F2}-\u{26F3}]|[\u{26F5}]|[\u{26FA}]|[\u{26FD}]|[\u{2702}]|[\u{2705}]|[\u{2708}-\u{270D}]|[\u{270F}]|[\u{2712}]|[\u{2714}]|[\u{2716}]|[\u{271D}]|[\u{2721}]|[\u{2728}]|[\u{2733}-\u{2734}]|[\u{2744}]|[\u{2747}]|[\u{274C}]|[\u{274E}]|[\u{2753}-\u{2755}]|[\u{2757}]|[\u{2763}-\u{2764}]|[\u{2795}-\u{2797}]|[\u{27A1}]|[\u{27B0}]|[\u{27BF}]|[\u{E000}-\u{F8FF}]/u.test(H),T=H=>H?H.startsWith("http")||H.startsWith("data:")||H.startsWith("/")?g.jsx("img",{src:H,alt:"icon",style:{width:"24px",height:"24px",objectFit:"contain",borderRadius:"4px"}}):L(H)?H:H||"📦":"📦",F=()=>b.defaults.color||"#9E9E9E",P=()=>{const H=F();if(H.startsWith("#")){const D=H.substring(1),q=Math.max(0,parseInt(D.substring(0,2),16)-40),W=Math.max(0,parseInt(D.substring(2,4),16)-40),U=Math.max(0,parseInt(D.substring(4,6),16)-40);return`#${q.toString(16).padStart(2,"0")}${W.toString(16).padStart(2,"0")}${U.toString(16).padStart(2,"0")}`}return H};return g.jsxs("div",{style:{position:"relative",padding:"12px 32px 12px 16px",minWidth:"160px",minHeight:"60px",borderRadius:"12px",background:`linear-gradient(135deg, ${F()} 0%, ${P()} 100%)`,border:`2px solid ${w?a.isDarkMode?a.dracula.cyan:"#2563eb":o?"#3b82f6":P()}`,color:"white",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"14px",fontWeight:"600",textAlign:"center",cursor:"pointer",transition:"all 0.2s ease",boxShadow:w?a.isDarkMode?`0 4px 12px ${a.dracula.cyan}66, 0 0 0 3px ${a.dracula.cyan}4D`:"0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)":o?`0 8px 25px ${F()}40, 0 0 0 2px ${a.colors.focus}`:a.isDarkMode?`0 4px 12px ${F()}40`:`0 2px 8px ${F()}25, 0 4px 16px rgba(0, 0, 0, 0.08)`,overflow:"visible",opacity:m?.5:1,animation:w?"pulse 1.5s ease-in-out infinite":"none"},children:[m&&g.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(128, 128, 128, 0.4)",borderRadius:"inherit",zIndex:25,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:g.jsx("span",{style:{fontSize:"24px",opacity:.8},children:"||"})}),B.map((H,D)=>{const q=B.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Br,{id:`input-${H.name}`,type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:W,transform:"translateY(-50%)",width:"12px",height:"12px",backgroundColor:"rgba(255,255,255,0.9)",border:`2px solid ${P()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`input-${H.name}-${D}`)}),g.jsx("button",{onClick:A,style:{position:"absolute",top:"8px",right:"8px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"rgba(255, 255, 255, 0.95)",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",color:F(),fontWeight:"600",transition:"all 0.2s ease",boxShadow:"0 1px 3px rgba(0, 0, 0, 0.2)",zIndex:20},onMouseEnter:H=>{H.currentTarget.style.backgroundColor="white",H.currentTarget.style.transform="scale(1.15)",H.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3)"},onMouseLeave:H=>{H.currentTarget.style.backgroundColor="rgba(255, 255, 255, 0.95)",H.currentTarget.style.transform="scale(1)",H.currentTarget.style.boxShadow="0 1px 3px rgba(0, 0, 0, 0.2)"},title:"Edit Parameters",children:"⚙️"}),g.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",position:"relative",zIndex:10,paddingRight:"4px"},children:[g.jsx("span",{style:{fontSize:t==="aiAgent"?"18px":"24px",display:"flex",alignItems:"center"},children:T(b.icon)}),x?g.jsx("input",{ref:O,type:"text",value:E,onChange:H=>$(H.target.value),onKeyDown:H=>{H.key==="Enter"?_():H.key==="Escape"&&j(),H.stopPropagation()},onBlur:_,onClick:H=>H.stopPropagation(),style:{padding:"2px 4px",fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,color:a.colors.text,backgroundColor:a.colors.backgroundElevated,border:`1px solid ${a.dracula.purple}`,borderRadius:a.borderRadius.sm,outline:"none",minWidth:"60px",maxWidth:"120px"}}):g.jsx("span",{onDoubleClick:N,style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",cursor:"text"},title:"Double-click to rename",children:n?.label||b.displayName})]}),z.map((H,D)=>{const q=z.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Br,{id:`output-${H.name}`,type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:W,transform:"translateY(-50%)",width:"12px",height:"12px",backgroundColor:"rgba(255,255,255,0.9)",border:`2px solid ${P()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`output-${H.name}-${D}`)})]})};class q8e{static validateConfiguration(t){const n=[];return(!t.prompt||t.prompt.trim()==="")&&n.push("Prompt is required"),{valid:n.length===0,errors:n}}}const G8e={initializing:{icon:"⚡",label:"Initializing",color:"#8be9fd"},loading_memory:{icon:"💾",label:"Loading Memory",color:"#bd93f9"},memory_loaded:{icon:"✓",label:"Memory Ready",color:"#50fa7b"},building_tools:{icon:"🔧",label:"Building Tools",color:"#ffb86c"},building_graph:{icon:"🔗",label:"Building Graph",color:"#ffb86c"},invoking_llm:{icon:"🧠",label:"Thinking...",color:"#ff79c6"},executing_tool:{icon:"⚡",label:"Using Tool",color:"#ff79c6"},tool_completed:{icon:"✓",label:"Tool Done",color:"#50fa7b"},saving_memory:{icon:"💾",label:"Saving Memory",color:"#bd93f9"}},K8e=({size:e=32,color:t="#6366F1"})=>g.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:t,children:g.jsx("path",{d:"M4.25 5.61C6.27 8.2 10 13 10 13v6c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-6s3.73-4.8 5.75-7.39C20.26 4.95 19.79 4 18.95 4H5.04c-.83 0-1.31.95-.79 1.61z"})}),X8e=({size:e=32,color:t="#6366F1"})=>g.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:t,children:[g.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"}),g.jsx("circle",{cx:"18",cy:"18",r:"4",fill:t,stroke:"#fff",strokeWidth:"1"})]}),Kj={aiAgent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🤖"}),title:"AI Agent",subtitle:"LangGraph Agent",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},chatAgent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧞"}),title:"Zeenie",subtitle:"Personal Assistant",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},socialReceive:{icon:g.jsx(K8e,{}),title:"Social Receive",subtitle:"Normalize Message",themeColorKey:"purple",bottomHandles:[],rightHandles:[{id:"output-message",label:"Message",position:"20%"},{id:"output-media",label:"Media",position:"40%"},{id:"output-contact",label:"Contact",position:"60%"},{id:"output-metadata",label:"Metadata",position:"80%"}],width:260,height:160},socialSend:{icon:g.jsx(X8e,{}),title:"Social Send",subtitle:"Send Message",themeColorKey:"purple",bottomHandles:[],skipInputHandle:!0,leftHandles:[{id:"input-message",label:"Message",position:"15%"},{id:"input-media",label:"Media",position:"35%"},{id:"input-contact",label:"Contact",position:"55%"},{id:"input-metadata",label:"Metadata",position:"75%"}],width:260,height:160},android_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📱"}),title:"Android Agent",subtitle:"Device Control",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},coding_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"💻"}),title:"Coding Agent",subtitle:"Code Execution",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},web_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🌐"}),title:"Web Agent",subtitle:"Browser Automation",themeColorKey:"pink",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},task_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📋"}),title:"Task Agent",subtitle:"Task Automation",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},social_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"📱"}),title:"Social Agent",subtitle:"Social Messaging",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},travel_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"✈️"}),title:"Travel Agent",subtitle:"Travel Planning",themeColorKey:"orange",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},tool_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🔧"}),title:"Tool Agent",subtitle:"Tool Orchestration",themeColorKey:"yellow",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},productivity_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"⏰"}),title:"Productivity Agent",subtitle:"Workflows",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},payments_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"💳"}),title:"Payments Agent",subtitle:"Payment Processing",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},consumer_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🛒"}),title:"Consumer Agent",subtitle:"Consumer Support",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},autonomous_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🎯"}),title:"Autonomous Agent",subtitle:"Autonomous Ops",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},orchestrator_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🎼"}),title:"Orchestrator Agent",subtitle:"Agent Coordination",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"20%"},{id:"input-tools",label:"Tool",position:"50%"},{id:"input-teammates",label:"Team",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},ai_employee:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"👥"}),title:"AI Employee",subtitle:"Team Orchestration",themeColorKey:"purple",bottomHandles:[{id:"input-skill",label:"Skill",position:"20%"},{id:"input-tools",label:"Tool",position:"50%"},{id:"input-teammates",label:"Team",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},rlm_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧠"}),title:"RLM Agent",subtitle:"Recursive Reasoning",themeColorKey:"orange",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},claude_code_agent:{icon:g.jsx(pg,{size:28}),title:"Claude Code",subtitle:"Agentic Coding",themeColorKey:"cyan",bottomHandles:[{id:"input-skill",label:"Skill",position:"25%"},{id:"input-tools",label:"Tool",position:"75%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200},deep_agent:{icon:g.jsx("span",{style:{fontSize:"28px"},children:"🧠"}),title:"Deep Agent",subtitle:"LangChain DeepAgents",themeColorKey:"green",bottomHandles:[{id:"input-skill",label:"Skill",position:"30%"},{id:"input-teammates",label:"Team",position:"55%"},{id:"input-tools",label:"Tool",position:"80%"}],leftHandles:[{id:"input-memory",label:"Memory",position:"65%"},{id:"input-task",label:"Task",position:"85%"}],topOutputHandle:{id:"output-top",label:"Output"},width:300,height:200}},e0=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i}=Sr(),[s,d]=u.useState(!0),[f,p]=u.useState([]),m=Kj[t||"aiAgent"]||Kj.aiAgent,y=u.useMemo(()=>Dt[m.themeColorKey]||Dt.purple,[m.themeColorKey]),v=vD(e),w=v?.status==="executing",b=v?.data?.phase,x=b?G8e[b]:null;u.useEffect(()=>{try{const _=q8e.validateConfiguration(n||{});d(_.valid),p(_.errors)}catch(_){console.error("Configuration validation error:",_),d(!1),p(["Configuration validation failed"])}},[n,e,m.title]);const C=_=>{_.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=()=>w?a.isDarkMode&&x?x.color:y:o?a.colors.focus:a.colors.border,$=()=>w?a.isDarkMode&&x?`0 0 20px ${x.color}80, 0 0 40px ${x.color}40`:`0 0 0 3px ${y}80, 0 4px 16px ${y}60`:o?`0 4px 12px ${a.colors.focusRing}, 0 0 0 1px ${a.colors.focusRing}`:`0 2px 4px ${a.colors.shadow}`,O=m.rightHandles&&m.rightHandles.length>0;return g.jsxs("div",{style:{position:"relative",padding:a.spacing.lg,paddingRight:O?"60px":a.spacing.lg,paddingLeft:a.spacing.lg,minWidth:m.width?`${m.width}px`:m.wider?"220px":O?"200px":"180px",minHeight:m.height?`${m.height}px`:"120px",borderRadius:a.borderRadius.lg,background:a.isDarkMode?`linear-gradient(135deg, ${y}20 0%, ${a.colors.backgroundAlt} 100%)`:`linear-gradient(145deg, #ffffff 0%, ${y}08 100%)`,border:`2px solid ${E()}`,color:a.colors.text,fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,textAlign:"center",cursor:"pointer",transition:"all 0.3s ease",boxShadow:$(),overflow:"visible",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:a.spacing.sm,animation:w?"pulse 1.5s ease-in-out infinite":"none"},children:[!m.skipInputHandle&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:{position:"absolute",left:"10px",top:"30%",transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap"},children:"Input"}),g.jsx(Br,{id:"input-main",type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:"30%",transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:"Input"})]}),g.jsx("button",{onClick:C,style:{position:"absolute",top:a.spacing.xs,right:a.spacing.xs,width:a.nodeSize.paramButton,height:a.nodeSize.paramButton,borderRadius:a.borderRadius.sm,backgroundColor:a.colors.backgroundAlt,border:`1px solid ${a.colors.border}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:a.fontSize.xs,color:a.colors.textSecondary,fontWeight:a.fontWeight.normal,transition:a.transitions.fast,zIndex:20},title:"Edit Parameters",children:"⚙️"}),g.jsx("div",{style:{lineHeight:"1",marginBottom:a.spacing.xs,color:y},children:m.icon}),g.jsx("div",{style:{fontSize:a.fontSize.base,fontWeight:a.fontWeight.semibold,color:a.colors.text,lineHeight:"1.2",marginBottom:a.spacing.xs},children:n?.label||m.title}),g.jsx("div",{style:{fontSize:a.fontSize.xs,fontWeight:a.fontWeight.normal,color:w&&x?x.color:a.colors.focus,lineHeight:"1.2",marginBottom:a.spacing.lg,transition:"color 0.3s ease"},children:w&&x?x.label:m.subtitle}),m.leftHandles&&m.leftHandles.map(_=>g.jsxs(Y.Fragment,{children:[g.jsx("div",{style:{position:"absolute",left:"12px",top:_.position,transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap"},children:_.label}),g.jsx(Br,{id:_.id,type:"target",position:Ut.Left,isConnectable:r,style:{position:"absolute",left:"-6px",top:_.position,width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"0",transform:"translateY(-50%) rotate(45deg)"},title:_.label})]},_.id)),m.bottomHandles.map(_=>g.jsx("span",{style:{position:"absolute",bottom:a.spacing.lg,left:_.position,transform:"translateX(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,whiteSpace:"nowrap"},children:_.label},`label-${_.id}`)),m.bottomHandles.map(_=>g.jsx(Br,{id:_.id,type:"target",position:Ut.Bottom,isConnectable:r,style:{position:"absolute",bottom:"-6px",left:_.position,width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"0",transform:"translateX(-50%) rotate(45deg)"},title:_.label},_.id)),m.topOutputHandle&&g.jsx(Br,{id:m.topOutputHandle.id,type:"source",position:Ut.Top,isConnectable:r,style:{position:"absolute",top:"-6px",left:"50%",transform:"translateX(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:y,border:`2px solid ${a.isDarkMode?a.colors.background:"#ffffff"}`,borderRadius:"50%",zIndex:20},title:m.topOutputHandle.label}),!m.skipRightOutput&&m.rightHandles&&m.rightHandles.length>0?g.jsx(g.Fragment,{children:m.rightHandles.map(_=>g.jsxs(Y.Fragment,{children:[g.jsx("div",{style:{position:"absolute",right:"10px",top:_.position,transform:"translateY(-50%)",fontSize:a.fontSize.sm,color:a.colors.text,fontWeight:a.fontWeight.medium,pointerEvents:"none",whiteSpace:"nowrap",textAlign:"right"},children:_.label}),g.jsx(Br,{id:_.id,type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:_.position,transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:_.label})]},_.id))}):m.skipRightOutput?null:g.jsx(Br,{id:"output-main",type:"source",position:Ut.Right,isConnectable:r,style:{position:"absolute",right:"-6px",top:"50%",transform:"translateY(-50%)",width:a.nodeSize.handle,height:a.nodeSize.handle,backgroundColor:a.colors.background,border:`2px solid ${a.colors.textSecondary}`,borderRadius:"50%"},title:"Main Output"})]})},Xj={openaiApi:"openai",anthropicApi:"anthropic",googleAiApi:"gemini",azureOpenaiApi:"azure_openai",cohereApi:"cohere",ollamaApi:"ollama",mistralApi:"mistral",openrouterApi:"openrouter",groqApi:"groq",cerebrasApi:"cerebras"},Yj=({id:e,type:t,data:n,isConnectable:r,selected:o})=>{const a=_n(),{setSelectedNode:i}=Sr(),{apiKeyStatuses:s}=Qn(),f=vD(e)?.status||"idle",p=f==="executing"||f==="waiting",m=wr[t],y=u.useMemo(()=>{const O=m?.credentials?.[0];return O?.name&&Xj[O.name]?Xj[O.name]:t?.includes("deepseek")?"deepseek":t?.includes("kimi")?"kimi":t?.includes("mistral")?"mistral":t?.includes("cerebras")?"cerebras":t?.includes("groq")?"groq":t?.includes("openrouter")?"openrouter":t?.includes("openai")?"openai":t?.includes("claude")?"anthropic":t?.includes("gemini")?"gemini":t?.includes("azure")?"azure_openai":t?.includes("cohere")?"cohere":t?.includes("ollama")?"ollama":""},[t,m?.credentials]),v=u.useMemo(()=>y&&s[y]?.hasKey||!1,[y,s]),w=t==="simpleMemory",b=w?"output-memory":"output-model",x=u.useMemo(()=>w?!0:n?.model&&n.model.trim()!==""&&v,[n?.model,v,w]),C=O=>{O.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=m?.defaults?.color||"#6b7280",$=()=>{const O=MP(y);return O?g.jsx(O,{size:28}):m?.icon?g.jsx("span",{children:m.icon}):t?.includes("azure")?g.jsx("span",{children:"☁️"}):t?.includes("cohere")?g.jsx("span",{children:"🌊"}):t?.includes("ollama")?g.jsx("span",{children:"🦙"}):g.jsx("span",{children:"AI"})};return g.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",alignItems:"center",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:a.fontSize.xs,cursor:"pointer"},children:[g.jsxs("div",{style:{position:"relative",width:a.nodeSize.square,height:a.nodeSize.square,borderRadius:"50%",background:a.isDarkMode?`linear-gradient(135deg, ${E}20 0%, ${a.colors.backgroundAlt} 100%)`:`linear-gradient(145deg, #ffffff 0%, ${E}10 100%)`,border:`2px solid ${p?a.isDarkMode?a.dracula.cyan:"#2563eb":o?a.colors.focus:x?a.isDarkMode?`${E}60`:`${E}50`:a.dracula.red}`,display:"flex",alignItems:"center",justifyContent:"center",color:a.colors.text,fontSize:t==="aiAgent"?a.fontSize.lg:a.iconSize.xl,fontWeight:a.fontWeight.semibold,transition:a.transitions.fast,boxShadow:p?a.isDarkMode?`0 4px 12px ${a.dracula.cyan}66, 0 0 0 3px ${a.dracula.cyan}4D`:"0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)":o?`0 4px 12px ${a.colors.focusRing}, 0 0 0 2px ${a.colors.focusRing}`:x?a.isDarkMode?`0 2px 8px ${E}30`:`0 2px 8px ${E}25, 0 4px 12px rgba(0,0,0,0.06)`:`0 2px 8px ${a.dracula.red}4D`,animation:p?"pulse 1.5s ease-in-out infinite":"none"},children:[$(),g.jsx("button",{onClick:C,style:{position:"absolute",top:"-8px",right:"-8px",width:a.nodeSize.paramButton,height:a.nodeSize.paramButton,borderRadius:"50%",backgroundColor:a.isDarkMode?a.colors.backgroundAlt:"#ffffff",border:`1px solid ${a.isDarkMode?a.colors.border:`${E}40`}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:a.fontSize.xs,color:a.colors.textSecondary,fontWeight:"400",transition:a.transitions.fast,zIndex:30,boxShadow:a.isDarkMode?`0 1px 3px ${a.colors.shadow}`:`0 1px 4px ${E}20`},title:"Edit Model Parameters",children:"⚙️"}),g.jsx("div",{style:{position:"absolute",top:"-4px",left:"-4px",width:a.nodeSize.statusIndicator,height:a.nodeSize.statusIndicator,borderRadius:"50%",backgroundColor:p?a.dracula.cyan:f==="success"?a.dracula.green:f==="error"?a.dracula.red:x?a.dracula.green:v?a.dracula.orange:a.dracula.red,border:`2px solid ${a.isDarkMode?a.colors.background:"#ffffff"}`,boxShadow:p?a.isDarkMode?`0 0 6px ${a.dracula.cyan}80`:"0 0 4px rgba(37, 99, 235, 0.5)":a.isDarkMode?`0 1px 3px ${a.colors.shadow}`:"0 1px 3px rgba(0,0,0,0.15)",zIndex:30,animation:p?"pulse 1s ease-in-out infinite":"none"},title:p?"Executing...":w?"Memory node ready":x?"Model configured and ready":v?"API key found, model needs configuration":"API key required"}),g.jsx(Br,{id:b,type:"source",position:Ut.Top,isConnectable:r&&x,style:{position:"absolute",top:"-6px",left:"50%",transform:"translateX(-50%) rotate(45deg)",width:a.nodeSize.statusIndicator,height:a.nodeSize.statusIndicator,backgroundColor:x?a.dracula.cyan:a.colors.textMuted,border:`2px solid ${a.isDarkMode?a.colors.backgroundAlt:"#ffffff"}`,borderRadius:"0",opacity:x?1:.6,zIndex:20,boxShadow:a.isDarkMode?"none":"0 1px 2px rgba(0,0,0,0.1)"},title:w?"Memory Output":x?"Model Configuration Output":"Configure model to enable connection"})]}),g.jsx("div",{style:{marginTop:a.spacing.sm,fontSize:a.fontSize.sm,fontWeight:a.fontWeight.medium,color:a.colors.text,lineHeight:"1.2",textAlign:"center",maxWidth:"120px"},children:n?.label||m?.displayName})]})},Wd=()=>{const{validateApiKey:e,getStoredApiKey:t,saveApiKey:n,deleteApiKey:r,validateMapsKey:o,validateApifyKey:a,getAiModels:i,sendRequest:s,isConnected:d}=Qn(),[f,p]=u.useState(!1),[m,y]=u.useState(null),v=u.useCallback(async(L,T)=>{p(!0),y(null);try{const F=await e(L,T);return F.valid||y(F.message||"Validation failed"),{isValid:F.valid,error:F.message,models:F.models}}catch(F){const P=F.message||"Validation failed";return y(P),{isValid:!1,error:P}}finally{p(!1)}},[e]),w=u.useCallback(async(L,T)=>{try{const F=await n(L,T);return{isValid:F,error:F?void 0:"Failed to save API key"}}catch(F){return{isValid:!1,error:F.message||"Failed to save API key"}}},[n]),b=u.useCallback(async L=>{try{const T=await t(L);return T.hasKey&&T.apiKey||null}catch(T){return console.warn(`Error retrieving API key for ${L}:`,T),null}},[t]),x=u.useCallback(async L=>{try{return(await t(L)).hasKey}catch{return!1}},[t]),C=u.useCallback(async L=>{try{const T=await t(L);return T.hasKey&&T.models&&T.models.length>0?T.models:null}catch(T){return console.warn(`Error retrieving models for ${L}:`,T),null}},[t]),E=u.useCallback(async L=>{try{await r(L)}catch(T){console.warn(`Error removing API key for ${L}:`,T)}},[r]),$=u.useCallback(async L=>{p(!0),y(null);try{const T=await o(L);return T.valid||y(T.message||"Validation failed"),{isValid:T.valid,error:T.message}}catch(T){const F=T.message||"Validation failed";return y(F),{isValid:!1,error:F}}finally{p(!1)}},[o]),O=u.useCallback(async L=>{p(!0),y(null);try{const T=await a(L);return T.valid||y(T.message||"Validation failed"),{isValid:T.valid,error:T.message}}catch(T){const F=T.message||"Validation failed";return y(F),{isValid:!1,error:F}}finally{p(!1)}},[a]),_=u.useCallback(async(L,T)=>{try{return await i(L,T)}catch(F){return console.warn(`Error fetching AI models for ${L}:`,F),[]}},[i]),j=u.useCallback(async L=>{const T={default_model:"",temperature:.7,max_tokens:4096,thinking_enabled:!1,thinking_budget:2048,reasoning_effort:"medium",reasoning_format:"parsed"};if(!d)return T;try{return(await s("get_provider_defaults",{provider:L}))?.defaults||T}catch(F){return console.warn(`Error fetching provider defaults for ${L}:`,F),T}},[s,d]),N=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_provider_defaults",{provider:L,defaults:T}))?.success||!1}catch(F){return console.warn(`Error saving provider defaults for ${L}:`,F),!1}},[s,d]),A=u.useCallback(async()=>{if(!d)return[];try{return(await s("get_provider_usage_summary",{}))?.providers||[]}catch(L){return console.warn("Error fetching provider usage summary:",L),[]}},[s,d]),I=u.useCallback(async L=>{if(!d)return[];try{return(await s("get_api_usage_summary",{service:L}))?.services||[]}catch(T){return console.warn("Error fetching API usage summary:",T),[]}},[s,d]),R=u.useCallback(async(L,T)=>{const F={found:!1,model:L,provider:T,max_output_tokens:4096,context_length:128e3,temperature_range:[0,2],supports_thinking:!1,thinking_type:"none",is_reasoning_model:!1};if(!d)return F;try{return await s("get_model_constraints",{model:L,provider:T})||F}catch(P){return console.warn(`Error fetching model constraints for ${T}/${L}:`,P),F}},[s,d]),B=u.useCallback(async()=>{const L={providers:[],global_provider:null,global_model:null};if(!d)return L;try{return await s("get_validated_ai_providers",{})||L}catch(T){return console.warn("Error fetching validated AI providers:",T),L}},[s,d]),z=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_global_model",{provider:L,model:T}))?.success??!1}catch(F){return console.warn("Error saving global model:",F),!1}},[s,d]);return{validateApiKey:v,saveApiKey:w,getStoredApiKey:b,hasStoredKey:x,getStoredModels:C,removeApiKey:E,validateGoogleMapsKey:$,validateApifyKey:O,getAiModels:_,getProviderDefaults:j,saveProviderDefaults:N,getProviderUsageSummary:A,getAPIUsageSummary:I,getModelConstraints:R,getValidatedAiProviders:B,saveGlobalModel:z,isValidating:f,validationError:m,isConnected:d}},bD=u.createContext({}),Y8e={aliceblue:"9ehhb",antiquewhite:"9sgk7",aqua:"1ekf",aquamarine:"4zsno",azure:"9eiv3",beige:"9lhp8",bisque:"9zg04",black:"0",blanchedalmond:"9zhe5",blue:"73",blueviolet:"5e31e",brown:"6g016",burlywood:"8ouiv",cadetblue:"3qba8",chartreuse:"4zshs",chocolate:"87k0u",coral:"9yvyo",cornflowerblue:"3xael",cornsilk:"9zjz0",crimson:"8l4xo",cyan:"1ekf",darkblue:"3v",darkcyan:"rkb",darkgoldenrod:"776yz",darkgray:"6mbhl",darkgreen:"jr4",darkgrey:"6mbhl",darkkhaki:"7ehkb",darkmagenta:"5f91n",darkolivegreen:"3bzfz",darkorange:"9yygw",darkorchid:"5z6x8",darkred:"5f8xs",darksalmon:"9441m",darkseagreen:"5lwgf",darkslateblue:"2th1n",darkslategray:"1ugcv",darkslategrey:"1ugcv",darkturquoise:"14up",darkviolet:"5rw7n",deeppink:"9yavn",deepskyblue:"11xb",dimgray:"442g9",dimgrey:"442g9",dodgerblue:"16xof",firebrick:"6y7tu",floralwhite:"9zkds",forestgreen:"1cisi",fuchsia:"9y70f",gainsboro:"8m8kc",ghostwhite:"9pq0v",goldenrod:"8j4f4",gold:"9zda8",gray:"50i2o",green:"pa8",greenyellow:"6senj",grey:"50i2o",honeydew:"9eiuo",hotpink:"9yrp0",indianred:"80gnw",indigo:"2xcoy",ivory:"9zldc",khaki:"9edu4",lavenderblush:"9ziet",lavender:"90c8q",lawngreen:"4vk74",lemonchiffon:"9zkct",lightblue:"6s73a",lightcoral:"9dtog",lightcyan:"8s1rz",lightgoldenrodyellow:"9sjiq",lightgray:"89jo3",lightgreen:"5nkwg",lightgrey:"89jo3",lightpink:"9z6wx",lightsalmon:"9z2ii",lightseagreen:"19xgq",lightskyblue:"5arju",lightslategray:"4nwk9",lightslategrey:"4nwk9",lightsteelblue:"6wau6",lightyellow:"9zlcw",lime:"1edc",limegreen:"1zcxe",linen:"9shk6",magenta:"9y70f",maroon:"4zsow",mediumaquamarine:"40eju",mediumblue:"5p",mediumorchid:"79qkz",mediumpurple:"5r3rv",mediumseagreen:"2d9ip",mediumslateblue:"4tcku",mediumspringgreen:"1di2",mediumturquoise:"2uabw",mediumvioletred:"7rn9h",midnightblue:"z980",mintcream:"9ljp6",mistyrose:"9zg0x",moccasin:"9zfzp",navajowhite:"9zest",navy:"3k",oldlace:"9wq92",olive:"50hz4",olivedrab:"472ub",orange:"9z3eo",orangered:"9ykg0",orchid:"8iu3a",palegoldenrod:"9bl4a",palegreen:"5yw0o",paleturquoise:"6v4ku",palevioletred:"8k8lv",papayawhip:"9zi6t",peachpuff:"9ze0p",peru:"80oqn",pink:"9z8wb",plum:"8nba5",powderblue:"6wgdi",purple:"4zssg",rebeccapurple:"3zk49",red:"9y6tc",rosybrown:"7cv4f",royalblue:"2jvtt",saddlebrown:"5fmkz",salmon:"9rvci",sandybrown:"9jn1c",seagreen:"1tdnb",seashell:"9zje6",sienna:"6973h",silver:"7ir40",skyblue:"5arjf",slateblue:"45e4t",slategray:"4e100",slategrey:"4e100",snow:"9zke2",springgreen:"1egv",steelblue:"2r1kk",tan:"87yx8",teal:"pds",thistle:"8ggk8",tomato:"9yqfb",turquoise:"2j4r4",violet:"9b10u",wheat:"9ld4j",white:"9zldr",whitesmoke:"9lhpx",yellow:"9zl6o",yellowgreen:"61fzm"},lo=Math.round;function Bx(e,t){const n=e.replace(/^[^(]*\((.*)/,"$1").replace(/\).*/,"").match(/\d*\.?\d+%?/g)||[],r=n.map(o=>parseFloat(o));for(let o=0;o<3;o+=1)r[o]=t(r[o]||0,n[o]||"",o);return n[3]?r[3]=n[3].includes("%")?r[3]/100:r[3]:r[3]=1,r}const Qj=(e,t,n)=>n===0?e:e/100;function Jf(e,t){const n=t||255;return e>n?n:e<0?0:e}class Lu{isValid=!0;r=0;g=0;b=0;a=1;_h;_s;_l;_v;_max;_min;_brightness;constructor(t){function n(o){return o[0]in t&&o[1]in t&&o[2]in t}if(t)if(typeof t=="string"){let a=function(i){return o.startsWith(i)};var r=a;const o=t.trim();if(/^#?[A-F\d]{3,8}$/i.test(o))this.fromHexString(o);else if(a("rgb"))this.fromRgbString(o);else if(a("hsl"))this.fromHslString(o);else if(a("hsv")||a("hsb"))this.fromHsvString(o);else{const i=Y8e[o.toLowerCase()];i&&this.fromHexString(parseInt(i,36).toString(16).padStart(6,"0"))}}else if(t instanceof Lu)this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this._h=t._h,this._s=t._s,this._l=t._l,this._v=t._v;else if(n("rgb"))this.r=Jf(t.r),this.g=Jf(t.g),this.b=Jf(t.b),this.a=typeof t.a=="number"?Jf(t.a,1):1;else if(n("hsl"))this.fromHsl(t);else if(n("hsv"))this.fromHsv(t);else throw new Error("@ant-design/fast-color: unsupported input "+JSON.stringify(t))}setR(t){return this._sc("r",t)}setG(t){return this._sc("g",t)}setB(t){return this._sc("b",t)}setA(t){return this._sc("a",t,1)}setHue(t){const n=this.toHsv();return n.h=t,this._c(n)}getLuminance(){function t(a){const i=a/255;return i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)}const n=t(this.r),r=t(this.g),o=t(this.b);return .2126*n+.7152*r+.0722*o}getHue(){if(typeof this._h>"u"){const t=this.getMax()-this.getMin();t===0?this._h=0:this._h=lo(60*(this.r===this.getMax()?(this.g-this.b)/t+(this.g<this.b?6:0):this.g===this.getMax()?(this.b-this.r)/t+2:(this.r-this.g)/t+4))}return this._h}getSaturation(){if(typeof this._s>"u"){const t=this.getMax()-this.getMin();t===0?this._s=0:this._s=t/this.getMax()}return this._s}getLightness(){return typeof this._l>"u"&&(this._l=(this.getMax()+this.getMin())/510),this._l}getValue(){return typeof this._v>"u"&&(this._v=this.getMax()/255),this._v}getBrightness(){return typeof this._brightness>"u"&&(this._brightness=(this.r*299+this.g*587+this.b*114)/1e3),this._brightness}darken(t=10){const n=this.getHue(),r=this.getSaturation();let o=this.getLightness()-t/100;return o<0&&(o=0),this._c({h:n,s:r,l:o,a:this.a})}lighten(t=10){const n=this.getHue(),r=this.getSaturation();let o=this.getLightness()+t/100;return o>1&&(o=1),this._c({h:n,s:r,l:o,a:this.a})}mix(t,n=50){const r=this._c(t),o=n/100,a=s=>(r[s]-this[s])*o+this[s],i={r:lo(a("r")),g:lo(a("g")),b:lo(a("b")),a:lo(a("a")*100)/100};return this._c(i)}tint(t=10){return this.mix({r:255,g:255,b:255,a:1},t)}shade(t=10){return this.mix({r:0,g:0,b:0,a:1},t)}onBackground(t){const n=this._c(t),r=this.a+n.a*(1-this.a),o=a=>lo((this[a]*this.a+n[a]*n.a*(1-this.a))/r);return this._c({r:o("r"),g:o("g"),b:o("b"),a:r})}isDark(){return this.getBrightness()<128}isLight(){return this.getBrightness()>=128}equals(t){return this.r===t.r&&this.g===t.g&&this.b===t.b&&this.a===t.a}clone(){return this._c(this)}toHexString(){let t="#";const n=(this.r||0).toString(16);t+=n.length===2?n:"0"+n;const r=(this.g||0).toString(16);t+=r.length===2?r:"0"+r;const o=(this.b||0).toString(16);if(t+=o.length===2?o:"0"+o,typeof this.a=="number"&&this.a>=0&&this.a<1){const a=lo(this.a*255).toString(16);t+=a.length===2?a:"0"+a}return t}toHsl(){return{h:this.getHue(),s:this.getSaturation(),l:this.getLightness(),a:this.a}}toHslString(){const t=this.getHue(),n=lo(this.getSaturation()*100),r=lo(this.getLightness()*100);return this.a!==1?`hsla(${t},${n}%,${r}%,${this.a})`:`hsl(${t},${n}%,${r}%)`}toHsv(){return{h:this.getHue(),s:this.getSaturation(),v:this.getValue(),a:this.a}}toRgb(){return{r:this.r,g:this.g,b:this.b,a:this.a}}toRgbString(){return this.a!==1?`rgba(${this.r},${this.g},${this.b},${this.a})`:`rgb(${this.r},${this.g},${this.b})`}toString(){return this.toRgbString()}_sc(t,n,r){const o=this.clone();return o[t]=Jf(n,r),o}_c(t){return new this.constructor(t)}getMax(){return typeof this._max>"u"&&(this._max=Math.max(this.r,this.g,this.b)),this._max}getMin(){return typeof this._min>"u"&&(this._min=Math.min(this.r,this.g,this.b)),this._min}fromHexString(t){const n=t.replace("#","");function r(o,a){return parseInt(n[o]+n[a||o],16)}n.length<6?(this.r=r(0),this.g=r(1),this.b=r(2),this.a=n[3]?r(3)/255:1):(this.r=r(0,1),this.g=r(2,3),this.b=r(4,5),this.a=n[6]?r(6,7)/255:1)}fromHsl({h:t,s:n,l:r,a:o}){if(this._h=t%360,this._s=n,this._l=r,this.a=typeof o=="number"?o:1,n<=0){const y=lo(r*255);this.r=y,this.g=y,this.b=y}let a=0,i=0,s=0;const d=t/60,f=(1-Math.abs(2*r-1))*n,p=f*(1-Math.abs(d%2-1));d>=0&&d<1?(a=f,i=p):d>=1&&d<2?(a=p,i=f):d>=2&&d<3?(i=f,s=p):d>=3&&d<4?(i=p,s=f):d>=4&&d<5?(a=p,s=f):d>=5&&d<6&&(a=f,s=p);const m=r-f/2;this.r=lo((a+m)*255),this.g=lo((i+m)*255),this.b=lo((s+m)*255)}fromHsv({h:t,s:n,v:r,a:o}){this._h=t%360,this._s=n,this._v=r,this.a=typeof o=="number"?o:1;const a=lo(r*255);if(this.r=a,this.g=a,this.b=a,n<=0)return;const i=t/60,s=Math.floor(i),d=i-s,f=lo(r*(1-n)*255),p=lo(r*(1-n*d)*255),m=lo(r*(1-n*(1-d))*255);switch(s){case 0:this.g=m,this.b=f;break;case 1:this.r=p,this.b=f;break;case 2:this.r=f,this.b=m;break;case 3:this.r=f,this.g=p;break;case 4:this.r=m,this.g=f;break;case 5:default:this.g=f,this.b=p;break}}fromHsvString(t){const n=Bx(t,Qj);this.fromHsv({h:n[0],s:n[1],v:n[2],a:n[3]})}fromHslString(t){const n=Bx(t,Qj);this.fromHsl({h:n[0],s:n[1],l:n[2],a:n[3]})}fromRgbString(t){const n=Bx(t,(r,o)=>o.includes("%")?lo(r/100*255):r);this.r=n[0],this.g=n[1],this.b=n[2],this.a=n[3]}}const t0=2,Zj=.16,Q8e=.05,Z8e=.05,J8e=.15,xD=5,SD=4,e7e=[{index:7,amount:15},{index:6,amount:25},{index:5,amount:30},{index:5,amount:45},{index:5,amount:65},{index:5,amount:85},{index:4,amount:90},{index:3,amount:95},{index:2,amount:97},{index:1,amount:98}];function Jj(e,t,n){let r;return Math.round(e.h)>=60&&Math.round(e.h)<=240?r=n?Math.round(e.h)-t0*t:Math.round(e.h)+t0*t:r=n?Math.round(e.h)+t0*t:Math.round(e.h)-t0*t,r<0?r+=360:r>=360&&(r-=360),r}function ek(e,t,n){if(e.h===0&&e.s===0)return e.s;let r;return n?r=e.s-Zj*t:t===SD?r=e.s+Zj:r=e.s+Q8e*t,r>1&&(r=1),n&&t===xD&&r>.1&&(r=.1),r<.06&&(r=.06),Math.round(r*100)/100}function tk(e,t,n){let r;return n?r=e.v+Z8e*t:r=e.v-J8e*t,r=Math.max(0,Math.min(1,r)),Math.round(r*100)/100}function t7e(e,t={}){const n=[],r=new Lu(e),o=r.toHsv();for(let a=xD;a>0;a-=1){const i=new Lu({h:Jj(o,a,!0),s:ek(o,a,!0),v:tk(o,a,!0)});n.push(i)}n.push(r);for(let a=1;a<=SD;a+=1){const i=new Lu({h:Jj(o,a),s:ek(o,a),v:tk(o,a)});n.push(i)}return t.theme==="dark"?e7e.map(({index:a,amount:i})=>new Lu(t.backgroundColor||"#141414").mix(n[a],i).toHexString()):n.map(a=>a.toHexString())}const P3=["#e6f4ff","#bae0ff","#91caff","#69b1ff","#4096ff","#1677ff","#0958d9","#003eb3","#002c8c","#001d66"];P3.primary=P3[5];function n7e(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function r7e(e,t){if(!e)return!1;if(e.contains)return e.contains(t);let n=t;for(;n;){if(n===e)return!0;n=n.parentNode}return!1}const nk="data-rc-order",rk="data-rc-priority",o7e="rc-util-key",D3=new Map;function wD({mark:e}={}){return e?e.startsWith("data-")?e:`data-${e}`:o7e}function B5(e){return e.attachTo?e.attachTo:document.querySelector("head")||document.body}function a7e(e){return e==="queue"?"prependQueue":e?"prepend":"append"}function H5(e){return Array.from((D3.get(e)||e).children).filter(t=>t.tagName==="STYLE")}function CD(e,t={}){if(!n7e())return null;const{csp:n,prepend:r,priority:o=0}=t,a=a7e(r),i=a==="prependQueue",s=document.createElement("style");s.setAttribute(nk,a),i&&o&&s.setAttribute(rk,`${o}`),n?.nonce&&(s.nonce=n?.nonce),s.innerHTML=e;const d=B5(t),{firstChild:f}=d;if(r){if(i){const p=(t.styles||H5(d)).filter(m=>{if(!["prepend","prependQueue"].includes(m.getAttribute(nk)))return!1;const y=Number(m.getAttribute(rk)||0);return o>=y});if(p.length)return d.insertBefore(s,p[p.length-1].nextSibling),s}d.insertBefore(s,f)}else d.appendChild(s);return s}function i7e(e,t={}){let{styles:n}=t;return n||=H5(B5(t)),n.find(r=>r.getAttribute(wD(t))===e)}function l7e(e,t){const n=D3.get(e);if(!n||!r7e(document,n)){const r=CD("",t),{parentNode:o}=r;D3.set(e,o),e.removeChild(r)}}function s7e(e,t,n={}){const r=B5(n),o=H5(r),a={...n,styles:o};l7e(r,a);const i=i7e(t,a);if(i)return a.csp?.nonce&&i.nonce!==a.csp?.nonce&&(i.nonce=a.csp?.nonce),i.innerHTML!==e&&(i.innerHTML=e),i;const s=CD(e,a);return s.setAttribute(wD(a),t),s}function ED(e){return e?.getRootNode?.()}function c7e(e){return ED(e)instanceof ShadowRoot}function u7e(e){return c7e(e)?ED(e):null}let L3={};const d7e=e=>{};function f7e(e,t){}function p7e(e,t){}function m7e(){L3={}}function $D(e,t,n){!t&&!L3[n]&&(e(!1,n),L3[n]=!0)}function ky(e,t){$D(f7e,e,t)}function g7e(e,t){$D(p7e,e,t)}ky.preMessage=d7e;ky.resetWarned=m7e;ky.noteOnce=g7e;function h7e(e){return e.replace(/-(.)/g,(t,n)=>n.toUpperCase())}function y7e(e,t){ky(e,`[@ant-design/icons] ${t}`)}function ok(e){return typeof e=="object"&&typeof e.name=="string"&&typeof e.theme=="string"&&(typeof e.icon=="object"||typeof e.icon=="function")}function ak(e={}){return Object.keys(e).reduce((t,n)=>{const r=e[n];switch(n){case"class":t.className=r,delete t.class;break;default:delete t[n],t[h7e(n)]=r}return t},{})}function F3(e,t,n){return n?Y.createElement(e.tag,{key:t,...ak(e.attrs),...n},(e.children||[]).map((r,o)=>F3(r,`${t}-${e.tag}-${o}`))):Y.createElement(e.tag,{key:t,...ak(e.attrs)},(e.children||[]).map((r,o)=>F3(r,`${t}-${e.tag}-${o}`)))}function OD(e){return t7e(e)[0]}function _D(e){return e?Array.isArray(e)?e:[e]:[]}const v7e=`
517
517
  .anticon {
518
518
  display: inline-flex;
519
519
  align-items: center;
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>React Flow Project</title>
8
- <script type="module" crossorigin src="/assets/index-DPhPeFHY.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-CHx1LnyZ.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/assets/index-DFSC53FP.css">
10
10
  </head>
11
11
  <body>
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-flow-client",
3
3
  "private": true,
4
- "version": "0.0.60",
4
+ "version": "0.0.61",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "start": "vite --host 0.0.0.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "machinaos",
3
- "version": "0.0.60",
3
+ "version": "0.0.61",
4
4
  "description": "Open source workflow automation platform with AI agents, React Flow, and n8n-inspired architecture",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -98,7 +98,7 @@
98
98
  "rimraf": "^6.0.1",
99
99
  "temporal-server": "^0.0.9",
100
100
  "agent-browser": "latest",
101
- "edgymeow": "^0.0.18"
101
+ "edgymeow": "^0.0.19"
102
102
  },
103
103
  "pnpm": {
104
104
  "peerDependencyRules": {