machinaos 0.0.62 → 0.0.63
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.
- package/client/dist/assets/{index-C-5BE5Qe.js → index-BdaCgeVr.js} +2 -2
- package/client/dist/index.html +1 -1
- package/client/package.json +1 -1
- package/client/src/nodeDefinitions/browserNodes.ts +29 -0
- package/package.json +1 -1
- package/server/services/agents/adapters.py +12 -0
- package/server/services/handlers/browser.py +12 -1
- package/server/services/handlers/process.py +15 -7
- package/server/services/process_service.py +58 -5
- package/server/skills/terminal/shell-skill/SKILL.md +58 -34
- package/server/skills/web_agent/browser-skill/SKILL.md +13 -0
|
@@ -493,7 +493,7 @@ END:VCARD`,description:"vCard 3.0 format string (optional if phone provided)",di
|
|
|
493
493
|
`,Hd=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,oD=Hd(kCe),ICe=Hd(NCe),PCe=Hd(MCe),zCe=Hd(TCe),DCe=Hd(RCe),LCe=Hd(ACe),$c={displayName:"Account",name:"account_mode",type:"options",options:[{name:"Owner Account",value:"owner"},{name:"Customer Account",value:"customer"}],default:"owner",description:"Which Google account to use"},_c={displayName:"Customer ID",name:"customer_id",type:"string",default:"",placeholder:"customer_123 or {{input.customer_id}}",description:"Customer identifier to look up their Google connection",displayOptions:{show:{account_mode:["customer"]}}},FCe={displayName:"Gmail",name:"gmail",icon:oD,group:["google","tool"],version:1,subtitle:"Email Operations",description:"Send, search, and read emails via Gmail API",defaults:{name:"Gmail",color:"#EA4335"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Send Email",value:"send"},{name:"Search Emails",value:"search"},{name:"Read Email",value:"read"}],default:"send",required:!0,description:"Operation to perform"},$c,_c,{displayName:"To",name:"to",type:"string",default:"",required:!0,placeholder:"recipient@example.com, another@example.com",description:"Recipient email addresses (comma-separated)",displayOptions:{show:{operation:["send"]}}},{displayName:"CC",name:"cc",type:"string",default:"",placeholder:"cc@example.com",description:"CC recipients (optional)",displayOptions:{show:{operation:["send"]}}},{displayName:"BCC",name:"bcc",type:"string",default:"",placeholder:"bcc@example.com",description:"BCC recipients (optional)",displayOptions:{show:{operation:["send"]}}},{displayName:"Subject",name:"subject",type:"string",default:"",required:!0,placeholder:"Email subject line",description:"Email subject",displayOptions:{show:{operation:["send"]}}},{displayName:"Body Type",name:"body_type",type:"options",options:[{name:"Plain Text",value:"text"},{name:"HTML",value:"html"}],default:"text",description:"Email body format",displayOptions:{show:{operation:["send"]}}},{displayName:"Body",name:"body",type:"string",default:"",required:!0,typeOptions:{rows:6},placeholder:"Email content...",description:"Email body content",displayOptions:{show:{operation:["send"]}}},{displayName:"Search Query",name:"query",type:"string",default:"",required:!0,placeholder:"from:someone@example.com subject:meeting",description:"Gmail search query (same syntax as Gmail web)",displayOptions:{show:{operation:["search"]}}},{displayName:"Max Results",name:"max_results",type:"number",default:10,typeOptions:{minValue:1,maxValue:100},description:"Maximum number of messages to return",displayOptions:{show:{operation:["search"]}}},{displayName:"Include Body",name:"include_body",type:"boolean",default:!1,description:"Fetch full message body (slower but includes content)",displayOptions:{show:{operation:["search"]}}},{displayName:"Message ID",name:"message_id",type:"string",default:"",required:!0,placeholder:"18d5a7e2c3b4f5a6",description:"Gmail message ID to read",displayOptions:{show:{operation:["read"]}}},{displayName:"Format",name:"format",type:"options",options:[{name:"Full (with body)",value:"full"},{name:"Metadata (headers only)",value:"metadata"},{name:"Minimal",value:"minimal"},{name:"Raw",value:"raw"}],default:"full",description:"Message format to retrieve",displayOptions:{show:{operation:["read"]}}}]},BCe={displayName:"Gmail Receive",name:"gmailReceive",icon:oD,group:["google","trigger"],version:1,subtitle:"On New Email",description:"Trigger workflow on new emails (polling-based)",defaults:{name:"Gmail Receive",color:"#EA4335"},inputs:[],outputs:[{name:"main",displayName:"Email",type:"main",description:"Received email (message_id, from, to, subject, body, date, labels, attachments)"}],properties:[$c,_c,{displayName:"Filter Query",name:"filter_query",type:"string",default:"is:unread",placeholder:"from:important@company.com OR label:work",description:"Gmail filter query (same as Gmail search)"},{displayName:"Label Filter",name:"label_filter",type:"options",options:[{name:"All Labels",value:"all"},{name:"Inbox Only",value:"INBOX"},{name:"Important",value:"IMPORTANT"},{name:"Starred",value:"STARRED"},{name:"Sent",value:"SENT"},{name:"Drafts",value:"DRAFT"}],default:"INBOX",description:"Filter by Gmail label"},{displayName:"Mark as Read",name:"mark_as_read",type:"boolean",default:!1,description:"Automatically mark emails as read after processing"},{displayName:"Poll Interval (seconds)",name:"poll_interval",type:"number",default:60,typeOptions:{minValue:30,maxValue:3600},description:"How often to check for new emails (30s - 1 hour)"}]},HCe={displayName:"Calendar",name:"calendar",icon:ICe,group:["google","tool"],version:1,subtitle:"Calendar Events",description:"Create, list, update, and delete calendar events via Google Calendar API",defaults:{name:"Calendar",color:"#4285F4"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Create Event",value:"create"},{name:"List Events",value:"list"},{name:"Update Event",value:"update"},{name:"Delete Event",value:"delete"}],default:"create",required:!0,description:"Operation to perform"},$c,_c,{displayName:"Calendar ID",name:"calendar_id",type:"string",default:"primary",placeholder:"primary or calendar@group.calendar.google.com",description:'Calendar ID (use "primary" for main calendar)'},{displayName:"Title",name:"title",type:"string",default:"",required:!0,placeholder:"Meeting with Team",description:"Event title/summary",displayOptions:{show:{operation:["create"]}}},{displayName:"Start Time",name:"start_time",type:"string",default:"",required:!0,placeholder:"2026-02-22T14:00:00",description:"Start time in ISO format (e.g., 2026-02-22T14:00:00)",displayOptions:{show:{operation:["create"]}}},{displayName:"End Time",name:"end_time",type:"string",default:"",required:!0,placeholder:"2026-02-22T15:00:00",description:"End time in ISO format",displayOptions:{show:{operation:["create"]}}},{displayName:"Description",name:"description",type:"string",default:"",typeOptions:{rows:3},placeholder:"Meeting agenda and notes...",description:"Event description (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Location",name:"location",type:"string",default:"",placeholder:"Conference Room A or https://meet.google.com/...",description:"Event location (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Attendees",name:"attendees",type:"string",default:"",placeholder:"alice@example.com, bob@example.com",description:"Attendee email addresses (comma-separated)",displayOptions:{show:{operation:["create"]}}},{displayName:"Timezone",name:"timezone",type:"string",default:"UTC",placeholder:"America/New_York",description:"Timezone for the event (e.g., America/New_York, Europe/London)",displayOptions:{show:{operation:["create"]}}},{displayName:"Reminder (minutes)",name:"reminder_minutes",type:"number",default:30,typeOptions:{minValue:0,maxValue:40320},description:"Minutes before event for popup reminder",displayOptions:{show:{operation:["create"]}}},{displayName:"Start Date",name:"start_date",type:"string",default:"today",placeholder:"today or 2026-02-22T00:00:00Z",description:'Start date for query ("today" or ISO format)',displayOptions:{show:{operation:["list"]}}},{displayName:"End Date",name:"end_date",type:"string",default:"today+7d",placeholder:"today+7d or 2026-02-29T23:59:59Z",description:'End date ("today+Nd" for N days from now, or ISO format)',displayOptions:{show:{operation:["list"]}}},{displayName:"Max Results",name:"max_results",type:"number",default:10,typeOptions:{minValue:1,maxValue:250},description:"Maximum number of events to return",displayOptions:{show:{operation:["list"]}}},{displayName:"Expand Recurring",name:"single_events",type:"boolean",default:!0,description:"Expand recurring events into individual instances",displayOptions:{show:{operation:["list"]}}},{displayName:"Order By",name:"order_by",type:"options",options:[{name:"Start Time",value:"startTime"},{name:"Last Updated",value:"updated"}],default:"startTime",description:"Sort order for events",displayOptions:{show:{operation:["list"]}}},{displayName:"Event ID",name:"event_id",type:"string",default:"",required:!0,placeholder:"abc123xyz",description:"ID of the event to update or delete",displayOptions:{show:{operation:["update","delete"]}}},{displayName:"Title",name:"update_title",type:"string",default:"",placeholder:"New meeting title",description:"New event title (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Start Time",name:"update_start_time",type:"string",default:"",placeholder:"2026-02-22T14:00:00",description:"New start time (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"End Time",name:"update_end_time",type:"string",default:"",placeholder:"2026-02-22T15:00:00",description:"New end time (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Description",name:"update_description",type:"string",default:"",typeOptions:{rows:3},placeholder:"Updated description...",description:"New description (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Location",name:"update_location",type:"string",default:"",placeholder:"New location",description:"New location (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Send Cancellation",name:"send_updates",type:"options",options:[{name:"Send to All Attendees",value:"all"},{name:"Do Not Send",value:"none"}],default:"all",description:"Send cancellation emails to attendees",displayOptions:{show:{operation:["delete"]}}}]},WCe={displayName:"Drive",name:"drive",icon:PCe,group:["google","tool"],version:1,subtitle:"File Operations",description:"Upload, download, list, and share files via Google Drive API",defaults:{name:"Drive",color:"#0F9D58"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Upload File",value:"upload"},{name:"Download File",value:"download"},{name:"List Files",value:"list"},{name:"Share File",value:"share"}],default:"list",required:!0,description:"Operation to perform"},$c,_c,{displayName:"File URL",name:"file_url",type:"string",default:"",placeholder:"https://example.com/document.pdf",description:"URL to download file from (for remote files)",displayOptions:{show:{operation:["upload"]}}},{displayName:"File Content (Base64)",name:"file_content",type:"string",default:"",typeOptions:{rows:3},placeholder:"SGVsbG8gV29ybGQh...",description:"Base64-encoded file content (alternative to URL)",displayOptions:{show:{operation:["upload"]}}},{displayName:"Filename",name:"filename",type:"string",default:"",required:!0,placeholder:"document.pdf",description:"Name for the uploaded file",displayOptions:{show:{operation:["upload"]}}},{displayName:"MIME Type",name:"mime_type",type:"string",default:"",placeholder:"application/pdf",description:"File MIME type (auto-detected if empty)",displayOptions:{show:{operation:["upload"]}}},{displayName:"Folder ID",name:"folder_id",type:"string",default:"",placeholder:"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs",description:"Parent folder ID (leave empty for root)",displayOptions:{show:{operation:["upload","list"]}}},{displayName:"Description",name:"file_description",type:"string",default:"",placeholder:"File description...",description:"File description (optional)",displayOptions:{show:{operation:["upload"]}}},{displayName:"File ID",name:"file_id",type:"string",default:"",required:!0,placeholder:"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs",description:"ID of the file to download or share",displayOptions:{show:{operation:["download","share"]}}},{displayName:"Output Format",name:"output_format",type:"options",options:[{name:"Base64 Content",value:"base64"},{name:"Download URL",value:"url"}],default:"base64",description:"How to return the file content",displayOptions:{show:{operation:["download"]}}},{displayName:"Search Query",name:"query",type:"string",default:"",placeholder:"name contains 'report'",description:"Drive search query (see Google Drive query syntax)",displayOptions:{show:{operation:["list"]}}},{displayName:"File Type",name:"file_types",type:"options",options:[{name:"All Files",value:"all"},{name:"Folders Only",value:"folder"},{name:"Documents",value:"document"},{name:"Spreadsheets",value:"spreadsheet"},{name:"Images",value:"image"}],default:"all",description:"Filter by file type",displayOptions:{show:{operation:["list"]}}},{displayName:"Max Results",name:"max_results",type:"number",default:20,typeOptions:{minValue:1,maxValue:1e3},description:"Maximum number of files to return",displayOptions:{show:{operation:["list"]}}},{displayName:"Order By",name:"order_by",type:"options",options:[{name:"Last Modified (Newest)",value:"modifiedTime desc"},{name:"Last Modified (Oldest)",value:"modifiedTime"},{name:"Created (Newest)",value:"createdTime desc"},{name:"Created (Oldest)",value:"createdTime"},{name:"Name (A-Z)",value:"name"},{name:"Name (Z-A)",value:"name desc"}],default:"modifiedTime desc",description:"Sort order for files",displayOptions:{show:{operation:["list"]}}},{displayName:"Email",name:"email",type:"string",default:"",required:!0,placeholder:"user@example.com",description:"Email address to share with",displayOptions:{show:{operation:["share"]}}},{displayName:"Role",name:"role",type:"options",options:[{name:"Viewer (read-only)",value:"reader"},{name:"Commenter (view + comment)",value:"commenter"},{name:"Editor (full access)",value:"writer"}],default:"reader",description:"Permission level for the user",displayOptions:{show:{operation:["share"]}}},{displayName:"Send Notification",name:"send_notification",type:"boolean",default:!0,description:"Send email notification to the user",displayOptions:{show:{operation:["share"]}}},{displayName:"Message",name:"message",type:"string",default:"",typeOptions:{rows:2},placeholder:"Here is the file you requested...",description:"Custom message for the notification email",displayOptions:{show:{operation:["share"],send_notification:[!0]}}}]},VCe={displayName:"Sheets",name:"sheets",icon:zCe,group:["google","tool"],version:1,subtitle:"Spreadsheet Operations",description:"Read, write, and append data to Google Sheets",defaults:{name:"Sheets",color:"#0F9D58"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Read Data",value:"read"},{name:"Write Data",value:"write"},{name:"Append Rows",value:"append"}],default:"read",required:!0,description:"Operation to perform"},$c,_c,{displayName:"Spreadsheet ID",name:"spreadsheet_id",type:"string",default:"",required:!0,placeholder:"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",description:"ID from the spreadsheet URL (between /d/ and /edit)"},{displayName:"Range",name:"range",type:"string",default:"",required:!0,placeholder:"Sheet1!A1:D10",description:'A1 notation range (e.g., "Sheet1!A1:D10" or "A:D")'},{displayName:"Value Render Option",name:"value_render_option",type:"options",options:[{name:"Formatted Value",value:"FORMATTED_VALUE"},{name:"Unformatted Value",value:"UNFORMATTED_VALUE"},{name:"Formula",value:"FORMULA"}],default:"FORMATTED_VALUE",description:"How values should be rendered in the output",displayOptions:{show:{operation:["read"]}}},{displayName:"Major Dimension",name:"major_dimension",type:"options",options:[{name:"Rows",value:"ROWS"},{name:"Columns",value:"COLUMNS"}],default:"ROWS",description:"Whether to return rows or columns first",displayOptions:{show:{operation:["read"]}}},{displayName:"Values",name:"values",type:"string",default:"",required:!0,typeOptions:{rows:4},placeholder:'[["Name", "Age"], ["Alice", 25], ["Bob", 30]]',description:"2D array of values in JSON format or {{input.data}}",displayOptions:{show:{operation:["write","append"]}}},{displayName:"Value Input Option",name:"value_input_option",type:"options",options:[{name:"User Entered",value:"USER_ENTERED"},{name:"Raw",value:"RAW"}],default:"USER_ENTERED",description:"How input values should be interpreted (USER_ENTERED parses formulas)",displayOptions:{show:{operation:["write","append"]}}},{displayName:"Insert Data Option",name:"insert_data_option",type:"options",options:[{name:"Insert Rows",value:"INSERT_ROWS"},{name:"Overwrite",value:"OVERWRITE"}],default:"INSERT_ROWS",description:"How the input data should be inserted",displayOptions:{show:{operation:["append"]}}}]},UCe={displayName:"Tasks",name:"tasks",icon:DCe,group:["google","tool"],version:1,subtitle:"Task Management",description:"Create, list, update, and delete tasks via Google Tasks API",defaults:{name:"Tasks",color:"#4285F4"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Create Task",value:"create"},{name:"List Tasks",value:"list"},{name:"Complete Task",value:"complete"},{name:"Update Task",value:"update"},{name:"Delete Task",value:"delete"}],default:"create",required:!0,description:"Operation to perform"},$c,_c,{displayName:"Task List ID",name:"tasklist_id",type:"string",default:"@default",placeholder:"@default or specific list ID",description:'Task list ID (use "@default" for primary list)'},{displayName:"Title",name:"title",type:"string",default:"",required:!0,placeholder:"Buy groceries",description:"Task title",displayOptions:{show:{operation:["create"]}}},{displayName:"Notes",name:"notes",type:"string",default:"",typeOptions:{rows:3},placeholder:"Remember to check the shopping list...",description:"Task notes/description (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Due Date",name:"due_date",type:"string",default:"",placeholder:"2026-02-25 or 2026-02-25T10:00:00Z",description:"Due date (YYYY-MM-DD or RFC 3339 format)",displayOptions:{show:{operation:["create"]}}},{displayName:"Show Completed",name:"show_completed",type:"boolean",default:!1,description:"Include completed tasks in the list",displayOptions:{show:{operation:["list"]}}},{displayName:"Show Hidden",name:"show_hidden",type:"boolean",default:!1,description:"Include hidden tasks in the list",displayOptions:{show:{operation:["list"]}}},{displayName:"Max Results",name:"max_results",type:"number",default:100,typeOptions:{minValue:1,maxValue:100},description:"Maximum number of tasks to return",displayOptions:{show:{operation:["list"]}}},{displayName:"Task ID",name:"task_id",type:"string",default:"",required:!0,placeholder:"abc123xyz",description:"ID of the task",displayOptions:{show:{operation:["complete","update","delete"]}}},{displayName:"Title",name:"update_title",type:"string",default:"",placeholder:"New task title",description:"New title (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Notes",name:"update_notes",type:"string",default:"",typeOptions:{rows:3},placeholder:"Updated notes...",description:"New notes (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Due Date",name:"update_due_date",type:"string",default:"",placeholder:"2026-02-25",description:"New due date (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Status",name:"status",type:"options",options:[{name:"Keep Current",value:""},{name:"Needs Action",value:"needsAction"},{name:"Completed",value:"completed"}],default:"",description:"New status",displayOptions:{show:{operation:["update"]}}}]},qCe={displayName:"Contacts",name:"contacts",icon:LCe,group:["google","tool"],version:1,subtitle:"Contact Management",description:"Create, list, search, and manage contacts via Google People API",defaults:{name:"Contacts",color:"#4285F4"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",options:[{name:"Create Contact",value:"create"},{name:"List Contacts",value:"list"},{name:"Search Contacts",value:"search"},{name:"Get Contact",value:"get"},{name:"Update Contact",value:"update"},{name:"Delete Contact",value:"delete"}],default:"list",required:!0,description:"Operation to perform"},$c,_c,{displayName:"First Name",name:"first_name",type:"string",default:"",required:!0,placeholder:"John",description:"First name (required)",displayOptions:{show:{operation:["create"]}}},{displayName:"Last Name",name:"last_name",type:"string",default:"",placeholder:"Doe",description:"Last name (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Email",name:"email",type:"string",default:"",placeholder:"john.doe@example.com",description:"Email address (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Phone",name:"phone",type:"string",default:"",placeholder:"+1 555-123-4567",description:"Phone number (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Company",name:"company",type:"string",default:"",placeholder:"Acme Inc.",description:"Company/organization name (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Job Title",name:"job_title",type:"string",default:"",placeholder:"Software Engineer",description:"Job title (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Notes",name:"contact_notes",type:"string",default:"",typeOptions:{rows:3},placeholder:"Additional notes about this contact...",description:"Notes/biography (optional)",displayOptions:{show:{operation:["create"]}}},{displayName:"Page Size",name:"page_size",type:"number",default:100,typeOptions:{minValue:1,maxValue:1e3},description:"Number of contacts to return",displayOptions:{show:{operation:["list"]}}},{displayName:"Sort Order",name:"sort_order",type:"options",options:[{name:"Last Modified (Newest)",value:"LAST_MODIFIED_DESCENDING"},{name:"Last Modified (Oldest)",value:"LAST_MODIFIED_ASCENDING"},{name:"First Name (A-Z)",value:"FIRST_NAME_ASCENDING"},{name:"Last Name (A-Z)",value:"LAST_NAME_ASCENDING"}],default:"LAST_MODIFIED_DESCENDING",description:"Sort order for contacts",displayOptions:{show:{operation:["list"]}}},{displayName:"Page Token",name:"page_token",type:"string",default:"",placeholder:"Next page token from previous request",description:"Token for pagination (from previous request)",displayOptions:{show:{operation:["list"]}}},{displayName:"Query",name:"query",type:"string",default:"",required:!0,placeholder:"John or john@example.com",description:"Search query (name, email, phone)",displayOptions:{show:{operation:["search"]}}},{displayName:"Max Results",name:"search_page_size",type:"number",default:30,typeOptions:{minValue:1,maxValue:100},description:"Maximum number of results",displayOptions:{show:{operation:["search"]}}},{displayName:"Resource Name",name:"resource_name",type:"string",default:"",required:!0,placeholder:"people/c12345678",description:"Contact resource name (from list or search results)",displayOptions:{show:{operation:["get","update","delete"]}}},{displayName:"First Name",name:"update_first_name",type:"string",default:"",placeholder:"John",description:"New first name (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Last Name",name:"update_last_name",type:"string",default:"",placeholder:"Doe",description:"New last name (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Email",name:"update_email",type:"string",default:"",placeholder:"john.doe@example.com",description:"New email (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Phone",name:"update_phone",type:"string",default:"",placeholder:"+1 555-123-4567",description:"New phone (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Company",name:"update_company",type:"string",default:"",placeholder:"Acme Inc.",description:"New company (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}},{displayName:"Job Title",name:"update_job_title",type:"string",default:"",placeholder:"Software Engineer",description:"New job title (leave empty to keep current)",displayOptions:{show:{operation:["update"]}}}]},GCe={gmail:FCe,gmailReceive:BCe,calendar:HCe,drive:WCe,sheets:VCe,tasks:UCe,contacts:qCe},aD=["gmail","gmailReceive","calendar","drive","sheets","tasks","contacts"],KCe={proxyRequest:{displayName:"Proxy Request",name:"proxyRequest",icon:"🛡",group:["proxy","tool"],version:1,description:"Make HTTP requests through residential proxy providers with geo-targeting and failover",defaults:{name:"Proxy Request",color:"#8B5CF6"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Trigger input"}],outputs:[{name:"main",displayName:"Response",type:"main",description:"status, data, headers, proxy_provider, proxy_country"}],properties:[{displayName:"Method",name:"method",type:"options",default:"GET",options:[{name:"GET",value:"GET"},{name:"POST",value:"POST"},{name:"PUT",value:"PUT"},{name:"DELETE",value:"DELETE"},{name:"PATCH",value:"PATCH"}]},{displayName:"URL",name:"url",type:"string",default:"",required:!0,placeholder:"https://api.example.com/endpoint"},{displayName:"Headers",name:"headers",type:"string",default:"{}",typeOptions:{rows:3},placeholder:'{"Authorization": "Bearer token"}'},{displayName:"Body",name:"body",type:"string",default:"",typeOptions:{rows:4},placeholder:'{"key": "value"}',displayOptions:{show:{method:["POST","PUT","PATCH"]}}},{displayName:"Timeout (seconds)",name:"timeout",type:"number",default:30,typeOptions:{minValue:5,maxValue:300}},{displayName:"Proxy Provider",name:"proxyProvider",type:"string",default:"",placeholder:"Auto-select (best score)",description:"Provider name to use, or leave empty for auto-selection"},{displayName:"Country",name:"proxyCountry",type:"string",default:"",placeholder:"US",description:"ISO 3166-1 alpha-2 country code for geo-targeting (e.g., US, GB, DE)"},{displayName:"Session Type",name:"sessionType",type:"options",default:"rotating",options:[{name:"Rotating",value:"rotating"},{name:"Sticky",value:"sticky"}],description:"Rotating: new IP per request. Sticky: same IP for duration."},{displayName:"Sticky Duration (seconds)",name:"stickyDuration",type:"number",default:300,typeOptions:{minValue:30,maxValue:3600},displayOptions:{show:{sessionType:["sticky"]}},description:"How long to maintain the same IP address"},{displayName:"Max Retries",name:"maxRetries",type:"number",default:3,typeOptions:{minValue:0,maxValue:10},description:"Number of retry attempts on failure (with failover to other providers)"},{displayName:"Follow Redirects",name:"followRedirects",type:"boolean",default:!0,description:"Automatically follow HTTP redirects"}]},proxyConfig:{displayName:"Proxy Config",name:"proxyConfig",icon:"🔧",group:["proxy","tool"],version:1,description:"Configure proxy providers and routing rules. Works as workflow node or AI Agent tool.",defaults:{name:"Proxy Config",color:"#8B5CF6"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Trigger input"}],outputs:[{name:"main",displayName:"Result",type:"main",description:"Operation result"}],properties:[{displayName:"Operation",name:"operation",type:"options",default:"list_providers",required:!0,options:[{name:"List Providers",value:"list_providers"},{name:"Add Provider",value:"add_provider"},{name:"Update Provider",value:"update_provider"},{name:"Remove Provider",value:"remove_provider"},{name:"Set Credentials",value:"set_credentials"},{name:"Test Provider",value:"test_provider"},{name:"Get Stats",value:"get_stats"},{name:"Add Routing Rule",value:"add_routing_rule"},{name:"List Routing Rules",value:"list_routing_rules"},{name:"Remove Routing Rule",value:"remove_routing_rule"}]},{displayName:"Provider Name",name:"name",type:"string",default:"",required:!0,placeholder:"my_proxy_provider",description:"Unique name for the proxy provider",displayOptions:{show:{operation:["add_provider","update_provider","remove_provider","set_credentials","test_provider"]}}},{displayName:"Gateway Host",name:"gateway_host",type:"string",default:"",placeholder:"gate.example.com",description:"Proxy gateway hostname",displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"Gateway Port",name:"gateway_port",type:"number",default:0,placeholder:"7777",description:"Proxy gateway port",displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"URL Template (JSON)",name:"url_template",type:"string",default:"{}",typeOptions:{rows:6},description:"JSON template config for proxy URL encoding",displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"Cost per GB (USD)",name:"cost_per_gb",type:"number",default:0,typeOptions:{minValue:0,maxValue:100},description:"Cost per gigabyte in USD",displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"Priority",name:"priority",type:"number",default:50,typeOptions:{minValue:0,maxValue:100},description:"Provider priority (lower = preferred)",displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"Enabled",name:"enabled",type:"boolean",default:!0,displayOptions:{show:{operation:["add_provider","update_provider"]}}},{displayName:"Username",name:"username",type:"string",default:"",description:"Proxy username",displayOptions:{show:{operation:["set_credentials"]}}},{displayName:"Password",name:"password",type:"string",default:"",description:"Proxy password",displayOptions:{show:{operation:["set_credentials"]}}},{displayName:"Domain Pattern",name:"domain_pattern",type:"string",default:"",placeholder:"*.linkedin.com",description:"Domain glob pattern for routing (e.g., *.linkedin.com, *)",displayOptions:{show:{operation:["add_routing_rule"]}}},{displayName:"Preferred Providers (JSON)",name:"preferred_providers",type:"string",default:"[]",placeholder:'["provider1", "provider2"]',description:"JSON array of preferred provider names",displayOptions:{show:{operation:["add_routing_rule"]}}},{displayName:"Required Country",name:"required_country",type:"string",default:"",placeholder:"US",description:"ISO country code required for this domain",displayOptions:{show:{operation:["add_routing_rule"]}}},{displayName:"Session Type",name:"session_type",type:"options",default:"rotating",options:[{name:"Rotating",value:"rotating"},{name:"Sticky",value:"sticky"}],displayOptions:{show:{operation:["add_routing_rule"]}}},{displayName:"Rule ID",name:"rule_id",type:"number",default:0,description:"ID of the routing rule to remove",displayOptions:{show:{operation:["remove_routing_rule"]}}}]},proxyStatus:{displayName:"Proxy Status",name:"proxyStatus",icon:"📊",group:["proxy","tool"],version:1,description:"View proxy provider health, scores, and usage statistics",defaults:{name:"Proxy Status",color:"#6366F1"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Trigger input"}],outputs:[{name:"main",displayName:"Stats",type:"main",description:"providers, routing_rules, stats"}],properties:[{displayName:"Provider",name:"providerFilter",type:"string",default:"",placeholder:"All providers",description:"Filter by specific provider name, or leave empty for all"}]}},XCe=[{displayName:"Use Proxy",name:"useProxy",type:"boolean",default:!1,description:"Route request through a residential proxy provider"},{displayName:"Proxy Provider",name:"proxyProvider",type:"string",default:"",placeholder:"Auto-select",description:"Provider name, or leave empty for auto-selection",displayOptions:{show:{useProxy:[!0]}}},{displayName:"Proxy Country",name:"proxyCountry",type:"string",default:"",placeholder:"US",description:"ISO country code for geo-targeting",displayOptions:{show:{useProxy:[!0]}}}],YCe=["proxyRequest","proxyStatus","proxyConfig"],QCe={crawleeScraper:{displayName:"Web Scraper",name:"crawleeScraper",icon:"🕷",group:["api","tool"],version:1,subtitle:"Crawlee Scraper",description:"Scrape web pages using Crawlee. Supports static HTML (BeautifulSoup) and JS-rendered content (Playwright).",defaults:{name:"Web Scraper",color:"#00D1B2"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Scraping input"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Scraped content and metadata"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Tool Name",name:"toolName",type:"string",default:"web_reader",description:"Name of this tool when used by AI Agent"},{displayName:"Tool Description",name:"toolDescription",type:"string",default:"Read and extract content from web pages. Fetches page text, links, and data. You MUST use this tool when asked to read or fetch any URL.",description:"Description shown to AI Agent"},{displayName:"Crawler Type",name:"crawlerType",type:"options",options:[{name:"BeautifulSoup (Static HTML)",value:"beautifulsoup"},{name:"Playwright (Browser)",value:"playwright"},{name:"Adaptive (Auto-detect)",value:"adaptive"}],default:"beautifulsoup",description:"Crawler engine. BeautifulSoup for static pages, Playwright for JS-rendered content, Adaptive to auto-detect."},{displayName:"URL",name:"url",type:"string",default:"",required:!0,placeholder:"https://example.com",description:"Starting URL to scrape"},{displayName:"Mode",name:"mode",type:"options",options:[{name:"Single Page",value:"single"},{name:"Crawl Links",value:"crawl"}],default:"single",description:"Single page scraping or follow links to crawl multiple pages"},{displayName:"CSS Selector",name:"cssSelector",type:"string",default:"",placeholder:"article, .content, #main",description:"CSS selector to extract specific content. Leave empty for full page text."},{displayName:"Extract Links",name:"extractLinks",type:"boolean",default:!1,description:"Include all discovered links in the output"},{displayName:"Link Selector",name:"linkSelector",type:"string",default:"",placeholder:"a[href]",description:"CSS selector for links to follow. Leave empty to follow all links.",displayOptions:{show:{mode:["crawl"]}}},{displayName:"URL Pattern",name:"urlPattern",type:"string",default:"",placeholder:"https://example.com/blog/**",description:"Glob pattern to filter which URLs to crawl. Leave empty for same-domain only.",displayOptions:{show:{mode:["crawl"]}}},{displayName:"Max Pages",name:"maxPages",type:"number",default:10,typeOptions:{minValue:1,maxValue:1e3},description:"Maximum number of pages to scrape (1-1000)",displayOptions:{show:{mode:["crawl"]}}},{displayName:"Max Depth",name:"maxDepth",type:"number",default:2,typeOptions:{minValue:0,maxValue:10},description:"Maximum link depth to follow (0 = start URL only)",displayOptions:{show:{mode:["crawl"]}}},{displayName:"Wait For Selector",name:"waitForSelector",type:"string",default:"",placeholder:".loaded-content",description:"CSS selector to wait for before extracting content",displayOptions:{show:{crawlerType:["playwright","adaptive"]}}},{displayName:"Wait Timeout (ms)",name:"waitTimeout",type:"number",default:3e4,typeOptions:{minValue:1e3,maxValue:12e4},description:"Maximum time to wait for page load in milliseconds",displayOptions:{show:{crawlerType:["playwright","adaptive"]}}},{displayName:"Take Screenshot",name:"screenshot",type:"boolean",default:!1,description:"Capture a screenshot of each page (returned as base64)",displayOptions:{show:{crawlerType:["playwright","adaptive"]}}},{displayName:"Browser Type",name:"browserType",type:"options",options:[{name:"Chromium",value:"chromium"},{name:"Firefox",value:"firefox"},{name:"WebKit",value:"webkit"}],default:"chromium",description:"Browser engine to use for rendering",displayOptions:{show:{crawlerType:["playwright","adaptive"]}}},{displayName:"Block Resources",name:"blockResources",type:"boolean",default:!0,description:"Block images, fonts, and stylesheets for faster scraping",displayOptions:{show:{crawlerType:["playwright","adaptive"]}}},{displayName:"Timeout (seconds)",name:"timeout",type:"number",default:60,typeOptions:{minValue:10,maxValue:600},description:"Maximum time for the entire scraping operation"},{displayName:"Max Concurrency",name:"maxConcurrency",type:"number",default:5,typeOptions:{minValue:1,maxValue:20},description:"Maximum concurrent requests"},{displayName:"Output Format",name:"outputFormat",type:"options",options:[{name:"Text",value:"text"},{name:"HTML",value:"html"},{name:"Markdown",value:"markdown"}],default:"text",description:"Format of the extracted content"},...XCe]}},iD=["crawleeScraper"],ZCe=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="64 64 896 896">
|
|
494
494
|
<path d="M928 512.3v-.3c0-229.8-186.2-416-416-416S96 282.2 96 512v.4c0 229.8 186.2 416 416 416s416-186.2 416-416v-.3.2zm-6.7-74.6l.6 3.3-.6-3.3zM676.7 638.2c53.5-82.2 52.5-189.4-11.1-263.7l162.4-8.4c20.5 44.4 32 93.8 32 145.9 0 185.2-144.6 336.6-327.1 347.4l143.8-221.2zM512 652.3c-77.5 0-140.2-62.7-140.2-140.2 0-77.7 62.7-140.2 140.2-140.2S652.2 434.5 652.2 512 589.5 652.3 512 652.3zm369.2-331.7l-3-5.7 3 5.7zM512 164c121.3 0 228.2 62.1 290.4 156.2l-263.6-13.9c-97.5-5.7-190.2 49.2-222.3 141.1L227.8 311c63.1-88.9 166.9-147 284.2-147zM102.5 585.8c26 145 127.1 264 261.6 315.1C229.6 850 128.5 731 102.5 585.8zM164 512c0-55.9 13.2-108.7 36.6-155.5l119.7 235.4c44.1 86.7 137.4 139.7 234 121.6l-74 145.1C302.9 842.5 164 693.5 164 512zm324.7 415.4c4 .2 8 .4 12 .5-4-.2-8-.3-12-.5z" fill="#8be9fd"/>
|
|
495
495
|
</svg>
|
|
496
|
-
`,JCe=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,e8e=JCe(ZCe),t8e={browser:{displayName:"Browser",name:"browser",icon:e8e,group:["browser","tool"],version:1,subtitle:"Agent Browser",description:"Interactive browser automation via agent-browser. Navigate, click, type, fill forms, take screenshots, get accessibility snapshots, and execute JavaScript.",defaults:{name:"Browser",color:zt.cyan},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Browser operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Tool Name",name:"toolName",type:"string",default:"browser",description:"Name of this tool when used by AI Agent"},{displayName:"Tool Description",name:"toolDescription",type:"string",default:"Control a web browser. Use snapshot to see the page (returns accessibility tree with @eN refs). Then click/type/fill with those refs. Workflow: navigate -> snapshot -> click/fill -> snapshot.",typeOptions:{rows:3},description:"Description shown to AI Agent for tool usage"},{displayName:"Operation",name:"operation",type:"options",default:"navigate",options:[{name:"Navigate",value:"navigate",description:"Open a URL"},{name:"Click",value:"click",description:"Click an element"},{name:"Type",value:"type",description:"Type text keystroke by keystroke"},{name:"Fill",value:"fill",description:"Clear and fill an input field"},{name:"Screenshot",value:"screenshot",description:"Take a screenshot"},{name:"Snapshot",value:"snapshot",description:"Get accessibility tree with @eN refs (AI-optimized)"},{name:"Get Text",value:"get_text",description:"Extract text from an element"},{name:"Get HTML",value:"get_html",description:"Extract innerHTML from an element"},{name:"Evaluate JS",value:"eval",description:"Execute JavaScript in page context"},{name:"Wait",value:"wait",description:"Wait for an element to appear"},{name:"Scroll",value:"scroll",description:"Scroll the page"},{name:"Select",value:"select",description:"Select a dropdown option"},{name:"Console Logs",value:"console",description:"Get browser console output (log, warn, error)"},{name:"Page Errors",value:"errors",description:"Get JavaScript errors from the page"},{name:"Batch",value:"batch",description:"Execute multiple commands"}],description:"Browser operation to perform"},{displayName:"URL",name:"url",type:"string",default:"",required:!0,placeholder:"https://example.com",description:"URL to navigate to",displayOptions:{show:{operation:["navigate"]}}},{displayName:"Selector",name:"selector",type:"string",default:"",required:!0,placeholder:"@e1 or #login-button or .submit-btn",description:"CSS selector or @eN ref from snapshot",displayOptions:{show:{operation:["click","type","fill","get_text","get_html","wait","select"]}}},{displayName:"Text",name:"text",type:"string",default:"",placeholder:"Text to type",description:"Text to type into the element",displayOptions:{show:{operation:["type"]}}},{displayName:"Value",name:"value",type:"string",default:"",placeholder:"Value to fill or option to select",description:"Value for fill or select operation",displayOptions:{show:{operation:["fill","select"]}}},{displayName:"Full Page",name:"fullPage",type:"boolean",default:!1,description:"Capture the full scrollable page",displayOptions:{show:{operation:["screenshot"]}}},{displayName:"JavaScript Expression",name:"expression",type:"string",default:"",required:!0,placeholder:"document.title",typeOptions:{rows:3},description:"JavaScript to execute in page context",displayOptions:{show:{operation:["eval"]}}},{displayName:"Direction",name:"direction",type:"options",default:"down",options:[{name:"Down",value:"down"},{name:"Up",value:"up"},{name:"Left",value:"left"},{name:"Right",value:"right"}],description:"Scroll direction",displayOptions:{show:{operation:["scroll"]}}},{displayName:"Amount (px)",name:"amount",type:"number",default:500,typeOptions:{minValue:100,maxValue:5e3},description:"Pixels to scroll",displayOptions:{show:{operation:["scroll"]}}},{displayName:"Commands (JSON)",name:"commands",type:"string",default:"[]",typeOptions:{rows:5},placeholder:'[["open", "https://example.com"], ["snapshot", "-i"]]',description:'JSON array of commands: [["command", "arg1", "arg2"], ...]',displayOptions:{show:{operation:["batch"]}}},{displayName:"Show Browser",name:"headed",type:"boolean",default:!0,description:"Open browser in visible (headed) mode instead of headless"},{displayName:"Auto Connect",name:"autoConnect",type:"boolean",default:!1,description:"Auto-discover and connect to an already-running Chrome instance (reuses auth state)"},{displayName:"Browser",name:"browser",type:"options",default:"chrome",options:[{name:"Google Chrome",value:"chrome",description:"System-installed Google Chrome (auto-detected)"},{name:"Microsoft Edge",value:"edge",description:"System-installed Microsoft Edge (auto-detected)"},{name:"Chromium",value:"chromium",description:"System-installed Chromium (auto-detected)"},{name:"Bundled Chromium",value:"bundled_explicit",description:"Use agent-browser built-in Chromium (no system browser)"},{name:"Custom Path",value:"custom",description:"Specify a custom executable path"}],description:"Which browser to use for automation"},{displayName:"Browser Path",name:"executablePath",type:"string",default:"",placeholder:"/usr/bin/google-chrome or C:\\...\\chrome.exe",description:"Custom browser executable path",displayOptions:{show:{browser:["custom"]}}},{displayName:"New Window",name:"newWindow",type:"boolean",default:!0,description:"Open a new browser window instead of a tab in an existing instance",displayOptions:{show:{browser:["chrome","edge","chromium","custom"]}}},{displayName:"Chrome Profile",name:"chromeProfile",type:"string",default:"",placeholder:"Default",description:"Chrome profile name to reuse login state (e.g., Default, Profile 1)"},{displayName:"Action Delay (ms)",name:"actionDelay",type:"number",default:0,typeOptions:{minValue:0,maxValue:1e4},description:"Delay before each action in milliseconds. Simulates human pacing. 0 = instant."},{displayName:"User Agent",name:"userAgent",type:"string",default:"",placeholder:"Mozilla/5.0 ...",description:"Custom user agent string. Empty = Chrome default."},{displayName:"Proxy",name:"proxy",type:"string",default:"",placeholder:"http://user:pass@host:port",description:"Proxy server URL for all browser requests."},{displayName:"Session",name:"session",type:"string",default:"",placeholder:"Auto-derived from execution ID",description:"Browser session name. Leave empty for auto-derived session (shares browser state across chained nodes)"},{displayName:"Timeout",name:"timeout",type:"number",default:30,typeOptions:{minValue:5,maxValue:300},description:"Command timeout in seconds"}]}},lD=["browser"],n8e={fileRead:{displayName:"File Read",name:"fileRead",icon:"📄",group:["utility","tool"],version:1,subtitle:"Read File",description:"Read file contents with line numbers and pagination. Works as workflow node or AI agent tool.",defaults:{name:"File Read",color:"#8be9fd"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"File contents"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"File Path",name:"file_path",type:"string",default:"",required:!0,description:"Path to the file to read"},{displayName:"Offset",name:"offset",type:"number",default:0,typeOptions:{minValue:0},description:"Line number to start reading from (0-indexed)"},{displayName:"Limit",name:"limit",type:"number",default:100,typeOptions:{minValue:1,maxValue:1e4},description:"Maximum number of lines to read"}]},fileModify:{displayName:"File Modify",name:"fileModify",icon:"✏️",group:["utility","tool"],version:1,subtitle:"Write / Edit File",description:"Write a new file or edit an existing file with string replacement. Works as workflow node or AI agent tool.",defaults:{name:"File Modify",color:"#50fa7b"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",default:"write",options:[{name:"Write",value:"write"},{name:"Edit",value:"edit"}],description:"Write creates/overwrites a file. Edit performs string replacement."},{displayName:"File Path",name:"file_path",type:"string",default:"",required:!0,description:"Path to the file"},{displayName:"Content",name:"content",type:"string",default:"",typeOptions:{rows:5},description:"File content to write",displayOptions:{show:{operation:["write"]}}},{displayName:"Old String",name:"old_string",type:"string",default:"",typeOptions:{rows:3},description:"Exact text to find and replace",displayOptions:{show:{operation:["edit"]}}},{displayName:"New String",name:"new_string",type:"string",default:"",typeOptions:{rows:3},description:"Text to replace old_string with",displayOptions:{show:{operation:["edit"]}}},{displayName:"Replace All",name:"replace_all",type:"boolean",default:!1,description:"Replace all occurrences (default: first only, old_string must be unique)",displayOptions:{show:{operation:["edit"]}}}]},shell:{displayName:"Shell",name:"shell",icon:"💻",group:["utility","tool"],version:1,subtitle:"Execute Command",description:"Execute shell commands and return stdout, stderr, and exit code. Works as workflow node or AI agent tool.",defaults:{name:"Shell",color:"#ff79c6"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Command output"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Command",name:"command",type:"string",default:"",required:!0,typeOptions:{rows:3},description:"Shell command to execute"},{displayName:"Timeout (seconds)",name:"timeout",type:"number",default:30,typeOptions:{minValue:1,maxValue:300},description:"Maximum execution time in seconds"}]},fsSearch:{displayName:"FS Search",name:"fsSearch",icon:"🔍",group:["utility","tool"],version:1,subtitle:"List / Glob / Grep",description:"Search the filesystem: list directories, glob pattern match, or grep file contents. Works as workflow node or AI agent tool.",defaults:{name:"FS Search",color:"#f1fa8c"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Search results"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Mode",name:"mode",type:"options",default:"ls",options:[{name:"List Directory",value:"ls"},{name:"Glob Pattern",value:"glob"},{name:"Grep Contents",value:"grep"}],description:"Search mode: list directory, glob file patterns, or grep file contents"},{displayName:"Path",name:"path",type:"string",default:".",description:"Directory path to search in"},{displayName:"Pattern",name:"pattern",type:"string",default:"",description:"Glob pattern (e.g., **/*.py) or grep search text",displayOptions:{show:{mode:["glob","grep"]}}},{displayName:"File Filter",name:"file_filter",type:"string",default:"",description:"Glob pattern to filter which files to grep (e.g., *.py)",displayOptions:{show:{mode:["grep"]}}}]}},r8e=["fileRead","fileModify","shell","fsSearch"],o8e={processManager:{displayName:"Process Manager",name:"processManager",icon:"⚙️",group:["utility","tool"],version:1,subtitle:"Manage Processes",description:"Start, stop, and manage long-running processes (dev servers, watchers, build tools). Streams output to Terminal tab.",defaults:{name:"Process Manager",color:zt.orange},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Process operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Tool Name",name:"toolName",type:"string",default:"process_manager",description:"Name of this tool when used by AI Agent"},{displayName:"Tool Description",name:"toolDescription",type:"string",default:"Start, stop, and manage long-running processes. Use for dev servers, watchers, build tools. Output streams to Terminal.",typeOptions:{rows:2},description:"Description shown to AI Agent"},{displayName:"Operation",name:"operation",type:"options",default:"start",options:[{name:"Start",value:"start",description:"Start a new process"},{name:"Stop",value:"stop",description:"Stop a running process"},{name:"Restart",value:"restart",description:"Restart a process"},{name:"Send Input",value:"send_input",description:"Send text to process stdin"},{name:"List",value:"list",description:"List running processes"},{name:"Get Output",value:"get_output",description:"Get buffered output history"}],description:"Process operation to perform"},{displayName:"Process Name",name:"name",type:"string",default:"",placeholder:"my-server",description:"Unique name for this process",displayOptions:{show:{operation:["start","stop","restart","send_input","get_output"]}}},{displayName:"Command",name:"command",type:"string",default:"",required:!0,placeholder:"python -m http.server 8080",description:"Shell command to run as a long-lived process",displayOptions:{show:{operation:["start"]}}},{displayName:"Working Directory",name:"working_directory",type:"string",default:"",placeholder:"Uses workflow workspace if empty",description:"Working directory for the process",displayOptions:{show:{operation:["start"]}}},{displayName:"Input Text",name:"text",type:"string",default:"",placeholder:"Text to send to stdin",description:"Text to write to the process stdin (newline appended automatically)",displayOptions:{show:{operation:["send_input"]}}}]}},a8e=["processManager"],i8e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
|
496
|
+
`,JCe=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,e8e=JCe(ZCe),t8e={browser:{displayName:"Browser",name:"browser",icon:e8e,group:["browser","tool"],version:1,subtitle:"Agent Browser",description:"Interactive browser automation via agent-browser. Navigate, click, type, fill forms, take screenshots, get accessibility snapshots, and execute JavaScript.",defaults:{name:"Browser",color:zt.cyan},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Browser operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Tool Name",name:"toolName",type:"string",default:"browser",description:"Name of this tool when used by AI Agent"},{displayName:"Tool Description",name:"toolDescription",type:"string",default:"Control a web browser. Use snapshot to see the page (returns accessibility tree with @eN refs). Then click/type/fill with those refs. Workflow: navigate -> snapshot -> click/fill -> snapshot.",typeOptions:{rows:3},description:"Description shown to AI Agent for tool usage"},{displayName:"Operation",name:"operation",type:"options",default:"navigate",options:[{name:"Navigate",value:"navigate",description:"Open a URL"},{name:"Click",value:"click",description:"Click an element"},{name:"Type",value:"type",description:"Type text keystroke by keystroke"},{name:"Fill",value:"fill",description:"Clear and fill an input field"},{name:"Screenshot",value:"screenshot",description:"Take a screenshot"},{name:"Snapshot",value:"snapshot",description:"Get accessibility tree with @eN refs (AI-optimized)"},{name:"Get Text",value:"get_text",description:"Extract text from an element"},{name:"Get HTML",value:"get_html",description:"Extract innerHTML from an element"},{name:"Evaluate JS",value:"eval",description:"Execute JavaScript in page context"},{name:"Wait",value:"wait",description:"Wait for an element to appear"},{name:"Scroll",value:"scroll",description:"Scroll the page"},{name:"Select",value:"select",description:"Select a dropdown option"},{name:"Console Logs",value:"console",description:"Get browser console output (log, warn, error)"},{name:"Page Errors",value:"errors",description:"Get JavaScript errors from the page"},{name:"Batch",value:"batch",description:"Execute multiple commands"}],description:"Browser operation to perform"},{displayName:"URL",name:"url",type:"string",default:"",required:!0,placeholder:"https://example.com",description:"URL to navigate to",displayOptions:{show:{operation:["navigate"]}}},{displayName:"Selector",name:"selector",type:"string",default:"",required:!0,placeholder:"@e1 or #login-button or .submit-btn",description:"CSS selector or @eN ref from snapshot",displayOptions:{show:{operation:["click","type","fill","get_text","get_html","wait","select"]}}},{displayName:"Text",name:"text",type:"string",default:"",placeholder:"Text to type",description:"Text to type into the element",displayOptions:{show:{operation:["type"]}}},{displayName:"Value",name:"value",type:"string",default:"",placeholder:"Value to fill or option to select",description:"Value for fill or select operation",displayOptions:{show:{operation:["fill","select"]}}},{displayName:"Full Page",name:"fullPage",type:"boolean",default:!1,description:"Capture the full scrollable page",displayOptions:{show:{operation:["screenshot"]}}},{displayName:"Annotate",name:"annotate",type:"boolean",default:!1,description:"Add numbered labels to interactive elements (useful for AI vision models)",displayOptions:{show:{operation:["screenshot"]}}},{displayName:"Format",name:"screenshotFormat",type:"options",default:"png",options:[{name:"PNG",value:"png"},{name:"JPEG",value:"jpeg"}],description:"Screenshot image format",displayOptions:{show:{operation:["screenshot"]}}},{displayName:"Quality",name:"screenshotQuality",type:"number",default:80,typeOptions:{minValue:1,maxValue:100},description:"JPEG quality (1-100, only used for JPEG format)",displayOptions:{show:{operation:["screenshot"],screenshotFormat:["jpeg"]}}},{displayName:"JavaScript Expression",name:"expression",type:"string",default:"",required:!0,placeholder:"document.title",typeOptions:{rows:3},description:"JavaScript to execute in page context",displayOptions:{show:{operation:["eval"]}}},{displayName:"Direction",name:"direction",type:"options",default:"down",options:[{name:"Down",value:"down"},{name:"Up",value:"up"},{name:"Left",value:"left"},{name:"Right",value:"right"}],description:"Scroll direction",displayOptions:{show:{operation:["scroll"]}}},{displayName:"Amount (px)",name:"amount",type:"number",default:500,typeOptions:{minValue:100,maxValue:5e3},description:"Pixels to scroll",displayOptions:{show:{operation:["scroll"]}}},{displayName:"Commands (JSON)",name:"commands",type:"string",default:"[]",typeOptions:{rows:5},placeholder:'[["open", "https://example.com"], ["snapshot", "-i"]]',description:'JSON array of commands: [["command", "arg1", "arg2"], ...]',displayOptions:{show:{operation:["batch"]}}},{displayName:"Show Browser",name:"headed",type:"boolean",default:!0,description:"Open browser in visible (headed) mode instead of headless"},{displayName:"Auto Connect",name:"autoConnect",type:"boolean",default:!1,description:"Auto-discover and connect to an already-running Chrome instance (reuses auth state)"},{displayName:"Browser",name:"browser",type:"options",default:"chrome",options:[{name:"Google Chrome",value:"chrome",description:"System-installed Google Chrome (auto-detected)"},{name:"Microsoft Edge",value:"edge",description:"System-installed Microsoft Edge (auto-detected)"},{name:"Chromium",value:"chromium",description:"System-installed Chromium (auto-detected)"},{name:"Bundled Chromium",value:"bundled_explicit",description:"Use agent-browser built-in Chromium (no system browser)"},{name:"Custom Path",value:"custom",description:"Specify a custom executable path"}],description:"Which browser to use for automation"},{displayName:"Browser Path",name:"executablePath",type:"string",default:"",placeholder:"/usr/bin/google-chrome or C:\\...\\chrome.exe",description:"Custom browser executable path",displayOptions:{show:{browser:["custom"]}}},{displayName:"New Window",name:"newWindow",type:"boolean",default:!0,description:"Open a new browser window instead of a tab in an existing instance",displayOptions:{show:{browser:["chrome","edge","chromium","custom"]}}},{displayName:"Chrome Profile",name:"chromeProfile",type:"string",default:"",placeholder:"Default",description:"Chrome profile name to reuse login state (e.g., Default, Profile 1)"},{displayName:"Action Delay (ms)",name:"actionDelay",type:"number",default:0,typeOptions:{minValue:0,maxValue:1e4},description:"Delay before each action in milliseconds. Simulates human pacing. 0 = instant."},{displayName:"User Agent",name:"userAgent",type:"string",default:"",placeholder:"Mozilla/5.0 ...",description:"Custom user agent string. Empty = Chrome default."},{displayName:"Proxy",name:"proxy",type:"string",default:"",placeholder:"http://user:pass@host:port",description:"Proxy server URL for all browser requests."},{displayName:"Session",name:"session",type:"string",default:"",placeholder:"Auto-derived from execution ID",description:"Browser session name. Leave empty for auto-derived session (shares browser state across chained nodes)"},{displayName:"Timeout",name:"timeout",type:"number",default:30,typeOptions:{minValue:5,maxValue:300},description:"Command timeout in seconds"}]}},lD=["browser"],n8e={fileRead:{displayName:"File Read",name:"fileRead",icon:"📄",group:["utility","tool"],version:1,subtitle:"Read File",description:"Read file contents with line numbers and pagination. Works as workflow node or AI agent tool.",defaults:{name:"File Read",color:"#8be9fd"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"File contents"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"File Path",name:"file_path",type:"string",default:"",required:!0,description:"Path to the file to read"},{displayName:"Offset",name:"offset",type:"number",default:0,typeOptions:{minValue:0},description:"Line number to start reading from (0-indexed)"},{displayName:"Limit",name:"limit",type:"number",default:100,typeOptions:{minValue:1,maxValue:1e4},description:"Maximum number of lines to read"}]},fileModify:{displayName:"File Modify",name:"fileModify",icon:"✏️",group:["utility","tool"],version:1,subtitle:"Write / Edit File",description:"Write a new file or edit an existing file with string replacement. Works as workflow node or AI agent tool.",defaults:{name:"File Modify",color:"#50fa7b"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Operation",name:"operation",type:"options",default:"write",options:[{name:"Write",value:"write"},{name:"Edit",value:"edit"}],description:"Write creates/overwrites a file. Edit performs string replacement."},{displayName:"File Path",name:"file_path",type:"string",default:"",required:!0,description:"Path to the file"},{displayName:"Content",name:"content",type:"string",default:"",typeOptions:{rows:5},description:"File content to write",displayOptions:{show:{operation:["write"]}}},{displayName:"Old String",name:"old_string",type:"string",default:"",typeOptions:{rows:3},description:"Exact text to find and replace",displayOptions:{show:{operation:["edit"]}}},{displayName:"New String",name:"new_string",type:"string",default:"",typeOptions:{rows:3},description:"Text to replace old_string with",displayOptions:{show:{operation:["edit"]}}},{displayName:"Replace All",name:"replace_all",type:"boolean",default:!1,description:"Replace all occurrences (default: first only, old_string must be unique)",displayOptions:{show:{operation:["edit"]}}}]},shell:{displayName:"Shell",name:"shell",icon:"💻",group:["utility","tool"],version:1,subtitle:"Execute Command",description:"Execute shell commands and return stdout, stderr, and exit code. Works as workflow node or AI agent tool.",defaults:{name:"Shell",color:"#ff79c6"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Command output"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Command",name:"command",type:"string",default:"",required:!0,typeOptions:{rows:3},description:"Shell command to execute"},{displayName:"Timeout (seconds)",name:"timeout",type:"number",default:30,typeOptions:{minValue:1,maxValue:300},description:"Maximum execution time in seconds"}]},fsSearch:{displayName:"FS Search",name:"fsSearch",icon:"🔍",group:["utility","tool"],version:1,subtitle:"List / Glob / Grep",description:"Search the filesystem: list directories, glob pattern match, or grep file contents. Works as workflow node or AI agent tool.",defaults:{name:"FS Search",color:"#f1fa8c"},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Search results"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Mode",name:"mode",type:"options",default:"ls",options:[{name:"List Directory",value:"ls"},{name:"Glob Pattern",value:"glob"},{name:"Grep Contents",value:"grep"}],description:"Search mode: list directory, glob file patterns, or grep file contents"},{displayName:"Path",name:"path",type:"string",default:".",description:"Directory path to search in"},{displayName:"Pattern",name:"pattern",type:"string",default:"",description:"Glob pattern (e.g., **/*.py) or grep search text",displayOptions:{show:{mode:["glob","grep"]}}},{displayName:"File Filter",name:"file_filter",type:"string",default:"",description:"Glob pattern to filter which files to grep (e.g., *.py)",displayOptions:{show:{mode:["grep"]}}}]}},r8e=["fileRead","fileModify","shell","fsSearch"],o8e={processManager:{displayName:"Process Manager",name:"processManager",icon:"⚙️",group:["utility","tool"],version:1,subtitle:"Manage Processes",description:"Start, stop, and manage long-running processes (dev servers, watchers, build tools). Streams output to Terminal tab.",defaults:{name:"Process Manager",color:zt.orange},inputs:[{name:"main",displayName:"Input",type:"main",description:"Input data"}],outputs:[{name:"main",displayName:"Output",type:"main",description:"Process operation result"},{name:"tool",displayName:"Tool",type:"main",description:"Connect to AI Agent tool handle"}],properties:[{displayName:"Tool Name",name:"toolName",type:"string",default:"process_manager",description:"Name of this tool when used by AI Agent"},{displayName:"Tool Description",name:"toolDescription",type:"string",default:"Start, stop, and manage long-running processes. Use for dev servers, watchers, build tools. Output streams to Terminal.",typeOptions:{rows:2},description:"Description shown to AI Agent"},{displayName:"Operation",name:"operation",type:"options",default:"start",options:[{name:"Start",value:"start",description:"Start a new process"},{name:"Stop",value:"stop",description:"Stop a running process"},{name:"Restart",value:"restart",description:"Restart a process"},{name:"Send Input",value:"send_input",description:"Send text to process stdin"},{name:"List",value:"list",description:"List running processes"},{name:"Get Output",value:"get_output",description:"Get buffered output history"}],description:"Process operation to perform"},{displayName:"Process Name",name:"name",type:"string",default:"",placeholder:"my-server",description:"Unique name for this process",displayOptions:{show:{operation:["start","stop","restart","send_input","get_output"]}}},{displayName:"Command",name:"command",type:"string",default:"",required:!0,placeholder:"python -m http.server 8080",description:"Shell command to run as a long-lived process",displayOptions:{show:{operation:["start"]}}},{displayName:"Working Directory",name:"working_directory",type:"string",default:"",placeholder:"Uses workflow workspace if empty",description:"Working directory for the process",displayOptions:{show:{operation:["start"]}}},{displayName:"Input Text",name:"text",type:"string",default:"",placeholder:"Text to send to stdin",description:"Text to write to the process stdin (newline appended automatically)",displayOptions:{show:{operation:["send_input"]}}}]}},a8e=["processManager"],i8e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
|
497
497
|
<path fill="#268bd2" d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2z"/>
|
|
498
498
|
<path fill="#1a6fb0" d="M20 4H4c-1.1 0-2 .9-2 2l10 6 10-6c0-1.1-.9-2-2-2z"/>
|
|
499
499
|
<path fill="#fff" d="M4 8l8 5 8-5v2l-8 5-8-5z" opacity="0.9"/>
|
|
@@ -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")}`,s8e=L5(i8e),c8e=L5(sD),u8e=L5(l8e),d8e={read:sD},f8e=[{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:f8e,default:"gmail",description:"Email provider"},p8e={emailSend:{displayName:"Email Send",name:"emailSend",icon:s8e,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:c8e,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:u8e,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}]}},m8e=["emailSend","emailRead","emailReceive"],wr={...rCe,...oCe,...Bz,...F6e,...H6e,...V6e,...U6e,...Z6e,...tCe,...aCe,...iCe,...sCe,...cCe,...Dm,...uCe,...hCe,...wCe,..._Ce,...jCe,...GCe,...KCe,...QCe,...t8e,...n8e,...o8e,...p8e};[...hs];const zj=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},g8e=(e=>e?zj(e):zj),h8e=e=>e;function y8e(e,t=h8e){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=g8e(e),n=r=>y8e(t,r);return Object.assign(n,t),n},v8e=(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})),b8e=(e,t=20)=>({x:Math.round(e.x/t)*t,y:Math.round(e.y/t)*t}),x8e=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 S8e=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"]),w8e=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"]),C8e=["api_key","apikey","secret","password","private_key","privatekey","accesstoken","access_token","refreshtoken","refresh_token","bearertoken","bearer_token","oauthtoken","oauth_token","authtoken","auth_token"];function E8e(e){if(w8e.has(e))return!1;if(S8e.has(e))return!0;const t=e.toLowerCase();return C8e.some(n=>t.includes(n))}const O8e=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(!E8e(n)&&!O8e.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.62",$8e=new Set(["label","disabled","condition"]);function b1(e){return e.map(t=>({...t,data:Object.fromEntries(Object.entries(t.data||{}).filter(([n])=>$8e.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 j8e(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 k8e(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 N8e(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=()=>`${Oc.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}),Ou=()=>({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=v8e((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]||Ou()},setWorkflowExecuting:(n,r)=>{e(o=>{const a=o.workflowUIStates[n];return{workflowUIStates:{...o.workflowUIStates,[n]:{...a||Ou(),isExecuting:r}}}})},setWorkflowExecutedNodes:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),executedNodes:r}}}))},setWorkflowExecutionOrder:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),executionOrder:r}}}))},setWorkflowViewport:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),viewport:r}}}))},clearWorkflowExecutionState:n=>{e(r=>({workflowUIStates:{...r.workflowUIStates,[n]:{...r.workflowUIStates[n]||Ou(),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 k8e(r,n)},exportWorkflowToFile:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");_8e(r,n)},importWorkflowFromJSON:n=>{const r=N8e(n);return e({currentWorkflow:r,hasUnsavedChanges:!0}),r}})),gD=u.createContext(void 0),M8e=({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=()=>`${Oc.PYTHON_BASE_URL}/api/auth`,T8e=({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 $=await(await fetch(`${Jh()}/status`,{credentials:"include"})).json();if($.auth_enabled===!1){n({id:0,email:"anonymous",display_name:"Anonymous",is_owner:!0}),o(!1),p(null);return}i($.auth_mode),d($.can_register),$.authenticated&&$.user?n($.user):n(null),p(null),o(!1)}catch(O){if(console.error(`Failed to check auth status (attempt ${x+1}/6):`,O),x<5){const $=1e3*Math.pow(2,x);console.log(`Retrying in ${$}ms...`),setTimeout(()=>m(x+1),$)}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})}),O=await E.json();return E.ok?O.success&&O.user?(n(O.user),o(!1),!0):(p("Login failed"),o(!1),!1):(p(O.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 O=await fetch(`${Jh()}/register`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C,display_name:E})}),$=await O.json();return O.ok?$.success&&$.user?(n($.user),d(!1),o(!1),!0):(p("Registration failed"),o(!1),!1):(p($.detail||"Registration failed"),o(!1),!1)}catch(O){return console.error("Register error:",O),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)}`,R8e=3e4,A8e=["whatsappReceive","webhookTrigger","cronScheduler","chatTrigger","telegramReceive"],I8e=["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"},P8e={locked:!1,workflow_id:null,locked_at:null,reason:null},Gj={connected:!1,has_session:!1,running:!1,pairing:!1},z8e={connected:!1,username:null,user_id:null},D8e={connected:!1,email:null},L8e={connected:!1,bot_username:null,bot_name:null,bot_id:null,owner_chat_id:null},yD=u.createContext(null),F8e=()=>{const e=Oc.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`},B8e=100,H8e=({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(z8e),[b,x]=u.useState(D8e),[C,E]=u.useState(L8e),[O,$]=u.useState([]),[_,j]=u.useState(null),[N,A]=u.useState({}),[I,R]=u.useState([]),[F,P]=u.useState([]),[L,T]=u.useState([]),[B,z]=u.useState({}),[H,D]=u.useState({}),[q,W]=u.useState({}),[U,G]=u.useState(Uj),[V,X]=u.useState(qj),[Q,J]=u.useState(P8e),[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 Te=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===Te&&(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:Te,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:Pe}=Sr.getState();Pe(o,Ne),J({locked:Ne,workflow_id:Ne?o:null,locked_at:Ne?Date.now():null,reason:Ne?"Workflow is running":null})}catch(Te){console.error("[WebSocket] Failed to fetch deployment status:",Te)}})()},[o]);const Oe=u.useCallback(de=>{try{const ce=JSON.parse(de.data),{type:Te,data:se,node_id:Ne,name:Pe,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(Te){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}z(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),$(Et=>[Ve,...Et].slice(0,B8e))}break;case"node_status":if(Ne){const Ve=ce.workflow_id||"unknown",Et=se?.data||{},Gt={...se,...Et,workflow_id:Ve};z(Ke=>({...Ke,[Ve]:{...Ke[Ve]||{},[Ne]:Gt}}))}break;case"node_output":if(Ne){const Ve=ce.workflow_id||"unknown";z(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;z(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(Pe!==void 0){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},[Pe]: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};P(Et=>[Ve,...Et].slice(0,200))}break;case"terminal_logs_cleared":P([]);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=F8e();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 Te=["openai","anthropic","gemini","google_maps","android_remote"];for(const se of Te)try{(await new Promise((Pe,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),Pe(Et))}catch{}};ce.addEventListener("message",gt),ce.send(JSON.stringify({type:"get_stored_api_key",provider:se,request_id:Nt}))})).has_key&&A(Pe=>({...Pe,[se]:{hasKey:!0,valid:!0}}))}catch{}try{const se=await new Promise((Ne,Pe)=>{const ct=`terminal_logs_${Date.now()}`,Nt=setTimeout(()=>Pe(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(Pe=>({timestamp:Pe.timestamp||new Date().toISOString(),level:Pe.level||"info",message:Pe.message||"",source:Pe.source,details:Pe.details})).reverse();P(Ne)}}catch{}try{const se=await new Promise((Ne,Pe)=>{const ct=`chat_messages_${Date.now()}`,Nt=setTimeout(()=>Pe(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(Pe=>({role:Pe.role,message:Pe.message,timestamp:Pe.timestamp}));T(Ne)}}catch{}try{const se=`console_${Date.now()}`,Ne=await new Promise((Pe,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),Pe(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 Pe=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(Pe)}}catch{}},ce.onmessage=Oe,ce.onclose=Te=>{console.log("[WebSocket] Disconnected:",Te.code,Te.reason),i(!1),ee.current=null,pe.current&&(clearInterval(pe.current),pe.current=null),Te.code!==1e3&&(d(!0),ve.current=setTimeout(()=>{re()},3e3))},ce.onerror=Te=>{console.error("[WebSocket] Error:",Te)},ee.current=ce}catch(ce){console.error("[WebSocket] Failed to create connection:",ce),d(!0),ve.current=setTimeout(re,3e3)}},[Oe]),Z=u.useCallback(()=>{ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"get_status"}))},[]),ie=u.useCallback(de=>{if(o)return B[o]?.[de]},[B,o]),le=u.useCallback(de=>N[de],[N]),be=u.useCallback(de=>{if(o)return q[o]?.[de]},[q,o]),$e=u.useCallback(async de=>{const ce=Ce.current;z(Te=>{if(!ce||!Te[ce])return Te;const se={...Te[ce]};return delete se[de],{...Te,[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(Te){console.error("[WebSocket] Failed to clear backend node output:",Te)}},[]),ze=u.useCallback(()=>{$([]),j(null)},[]),Be=u.useCallback(()=>{R([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_console_logs"}))},[]),Ae=u.useCallback(()=>{P([]),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?B[o]||{}:{},[B,o]),xe=u.useMemo(()=>o?q[o]||{}:{},[q,o]),Re=u.useMemo(()=>o?te[o]||{}:{},[te,o]),De=u.useCallback((de,ce,Te)=>{ae(se=>({...se,[de]:{...se[de]||{},[ce]:Te}}))},[]),he=u.useCallback(async(de,ce,Te)=>new Promise((se,Ne)=>{if(!ee.current||ee.current.readyState!==WebSocket.OPEN){Ne(new Error("WebSocket not connected"));return}const Pe=Wj(),ct=Te===void 0||Te>=0,Nt=Te&&Te>0?Te:R8e;let et=null;ct&&Te!==-1&&(et=setTimeout(()=>{fe.current.delete(Pe),Ne(new Error(`Request timeout: ${de}`))},Nt)),fe.current.set(Pe,{resolve:se,reject:Ne,timeout:et}),ee.current.send(JSON.stringify({type:de,request_id:Pe,...ce}))}),[]),Qe=u.useCallback(async(de,ce)=>{const Te=new Date().toISOString(),se={role:"user",message:de,timestamp:Te};T(Ne=>[...Ne,se]);try{await he("send_chat_message",{message:de,role:"user",node_id:ce,session_id:"default",timestamp:Te})}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 Te={parameters:ce.parameters,version:ce.version||0,timestamp:ce.timestamp};return D(se=>({...se,[de]:Te})),Te}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}),Te={};if(ce.parameters){for(const[se,Ne]of Object.entries(ce.parameters))Te[se]={parameters:Ne.parameters||{},version:Ne.version||0,timestamp:ce.timestamp};D(se=>({...se,...Te}))}return Te}catch(ce){return console.error("[WebSocket] Failed to get all node parameters:",ce),{}}},[he]),tt=u.useCallback(async(de,ce,Te)=>{try{const se=H[de]?.version||Te||0,Ne=await he("save_node_parameters",{node_id:de,parameters:ce,version:se});return Ne.success!==!1?(D(Pe=>({...Pe,[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 Te={...ce};return delete Te[de],Te}),!0}catch(ce){return console.error("[WebSocket] Failed to delete node parameters:",ce),!1}},[he]),Ge=u.useCallback(async(de,ce,Te,se,Ne)=>{try{const ct=A8e.includes(ce)||I8e.includes(ce)?-1:void 0;return await he("execute_node",{node_id:de,node_type:ce,parameters:Te,nodes:se,edges:Ne,workflow_id:o},ct)}catch(Pe){throw console.error("[WebSocket] Failed to execute node:",Pe),Pe}},[he,o]),je=u.useCallback(async(de,ce)=>{try{const Te=await he("get_node_output",{node_id:de,output_name:ce||"output_0"});return Te.success?Te.data:null}catch(Te){return console.error("[WebSocket] Failed to get node output:",Te),null}},[he]),Le=u.useCallback(async(de,ce)=>{try{return await he("cancel_event_wait",{node_id:de,waiter_id:ce})}catch(Te){return console.error("[WebSocket] Failed to cancel event wait:",Te),{success:!1}}},[he]),dt=u.useCallback(async(de,ce,Te)=>{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:Te||"default"})}catch(se){throw console.error("[WebSocket] Failed to execute workflow:",se),se}},[he]),St=u.useCallback(async(de,ce,Te,se)=>{try{return await he("deploy_workflow",{workflow_id:de,nodes:ce.map(Pe=>({id:Pe.id,type:Pe.type||"",data:Pe.data||{}})),edges:Te.map(Pe=>({id:Pe.id,source:Pe.source,target:Pe.target,sourceHandle:Pe.sourceHandle||void 0,targetHandle:Pe.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,Te,se,Ne,Pe,ct)=>{try{return await he("execute_ai_node",{node_id:de,node_type:ce,parameters:Te,model:se,workflow_id:Ne,nodes:Pe,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(Te){return console.error("[WebSocket] Failed to get AI models:",Te),[]}},[he]),yt=u.useCallback(async(de,ce)=>{try{const Te=await he("validate_api_key",{provider:de,api_key:ce}),se={valid:Te.valid||!1,message:Te.message,models:Te.models};return se.valid&&A(Ne=>({...Ne,[de]:{hasKey:!0,valid:!0,models:se.models}})),se}catch(Te){return console.error("[WebSocket] Failed to validate API key:",Te),{valid:!1,message:"Validation failed"}}},[he]),ut=u.useCallback(async de=>{try{const ce=await he("get_stored_api_key",{provider:de}),Te={hasKey:ce.has_key||!1,apiKey:ce.api_key,models:ce.models};return Te.hasKey&&A(se=>({...se,[de]:{hasKey:!0,valid:!0,models:Te.models}})),Te}catch(ce){return console.error("[WebSocket] Failed to get stored API key:",ce),{hasKey:!1}}},[he]),Ct=u.useCallback(async(de,ce,Te)=>{try{const Ne=(await he("save_api_key",{provider:de,api_key:ce,models:Te})).success!==!1;return Ne&&A(Pe=>({...Pe,[de]:{hasKey:!0,valid:!0,models:Te}})),Ne}catch(se){return console.error("[WebSocket] Failed to save API key:",se),!1}},[he]),Ht=u.useCallback(async de=>{try{return await he("delete_api_key",{provider:de}),A(ce=>{const Te={...ce};return delete Te[de],Te}),!0}catch(ce){return console.error("[WebSocket] Failed to delete API key:",ce),!1}},[he]),Wt=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,Te,se)=>{try{return await he("execute_android_action",{service_id:de,action:ce,parameters:Te,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 Te=await he("whatsapp_send",{phone:de,message:ce});return{success:Te.success||!1,messageId:Te.messageId,error:Te.error}}catch(Te){return console.error("[WebSocket] Failed to send WhatsApp message:",Te),{success:!1,error:Te.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]),Ot=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]),Vt=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]),Dt=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]),Me=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]),$t=u.useCallback(async(de,ce=!1)=>{try{const Te=await he("clear_memory",{session_id:de,clear_long_term:ce});return{success:Te.success!==!1,default_content:Te.default_content,cleared_vector_store:Te.cleared_vector_store,error:Te.error}}catch(Te){return console.error("[WebSocket] Failed to clear memory:",Te),{success:!1,error:Te.message||"Failed to clear memory"}}},[he]),Lt=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]),Ft=u.useRef(!0);u.useEffect(()=>{if(Ft.current=!0,n||!t||ee.current?.readyState===WebSocket.OPEN)return;const de=setTimeout(()=>{Ft.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(()=>()=>{Ft.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:O,lastWhatsAppMessage:_,apiKeyStatuses:N,consoleLogs:I,terminalLogs:F,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:$e,clearWhatsAppMessages:ze,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:Ht,getAndroidDevices:Wt,executeAndroidAction:wt,validateMapsKey:It,validateApifyKey:Mt,getWhatsAppStatus:ot,getWhatsAppQR:Fe,sendWhatsAppMessage:Xe,startWhatsAppConnection:at,restartWhatsAppConnection:Ot,getWhatsAppGroups:jt,getWhatsAppChannels:Vt,getWhatsAppGroupInfo:Dt,getWhatsAppRateLimitConfig:Rt,setWhatsAppRateLimitConfig:en,getWhatsAppRateLimitStats:yn,unpauseWhatsAppRateLimit:Me,clearMemory:$t,resetSkill:Lt};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},W8e=()=>{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},V8e=()=>{const{twitterStatus:e}=Qn();return e},U8e=()=>{const{googleStatus:e}=Qn();return e},q8e=()=>{const{telegramStatus:e}=Qn();return e},G8e=({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,O]=u.useState(""),$=u.useRef(null);u.useEffect(()=>{s===e?(C(!0),O(n?.label||b?.displayName||t||"")):C(!1)},[s,e,n?.label,b?.displayName,t]),u.useEffect(()=>{x&&$.current&&($.current.focus(),$.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"})):[],F=I(),P=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||"📦":"📦",B=()=>b.defaults.color||"#9E9E9E",z=()=>{const H=B();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, ${B()} 0%, ${z()} 100%)`,border:`2px solid ${w?a.isDarkMode?a.dracula.cyan:"#2563eb":o?"#3b82f6":z()}`,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 ${B()}40, 0 0 0 2px ${a.colors.focus}`:a.isDarkMode?`0 4px 12px ${B()}40`:`0 2px 8px ${B()}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:"||"})}),F.map((H,D)=>{const q=F.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Hr,{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 ${z()}`,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:B(),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:$,type:"text",value:E,onChange:H=>O(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})]}),P.map((H,D)=>{const q=P.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Hr,{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 ${z()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`output-${H.name}-${D}`)})]})};class K8e{static validateConfiguration(t){const n=[];return(!t.prompt||t.prompt.trim()==="")&&n.push("Prompt is required"),{valid:n.length===0,errors:n}}}const X8e={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"}},Y8e=({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"})}),Q8e=({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(Y8e,{}),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(Q8e,{}),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(()=>zt[m.themeColorKey]||zt.purple,[m.themeColorKey]),v=vD(e),w=v?.status==="executing",b=v?.data?.phase,x=b?X8e[b]:null;u.useEffect(()=>{try{const _=K8e.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,O=()=>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}`,$=m.rightHandles&&m.rightHandles.length>0;return g.jsxs("div",{style:{position:"relative",padding:a.spacing.lg,paddingRight:$?"60px":a.spacing.lg,paddingLeft:a.spacing.lg,minWidth:m.width?`${m.width}px`:m.wider?"220px":$?"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:O(),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(Hr,{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(Hr,{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(Hr,{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(Hr,{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(Hr,{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(Hr,{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 $=m?.credentials?.[0];return $?.name&&Xj[$.name]?Xj[$.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=$=>{$.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=m?.defaults?.color||"#6b7280",O=()=>{const $=Mz(y);return $?g.jsx($,{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:[O(),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(Hr,{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 B=await e(L,T);return B.valid||y(B.message||"Validation failed"),{isValid:B.valid,error:B.message,models:B.models}}catch(B){const z=B.message||"Validation failed";return y(z),{isValid:!1,error:z}}finally{p(!1)}},[e]),w=u.useCallback(async(L,T)=>{try{const B=await n(L,T);return{isValid:B,error:B?void 0:"Failed to save API key"}}catch(B){return{isValid:!1,error:B.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]),O=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 B=T.message||"Validation failed";return y(B),{isValid:!1,error:B}}finally{p(!1)}},[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 B=T.message||"Validation failed";return y(B),{isValid:!1,error:B}}finally{p(!1)}},[a]),_=u.useCallback(async(L,T)=>{try{return await i(L,T)}catch(B){return console.warn(`Error fetching AI models for ${L}:`,B),[]}},[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(B){return console.warn(`Error fetching provider defaults for ${L}:`,B),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(B){return console.warn(`Error saving provider defaults for ${L}:`,B),!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 B={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 B;try{return await s("get_model_constraints",{model:L,provider:T})||B}catch(z){return console.warn(`Error fetching model constraints for ${T}/${L}:`,z),B}},[s,d]),F=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]),P=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_global_model",{provider:L,model:T}))?.success??!1}catch(B){return console.warn("Error saving global model:",B),!1}},[s,d]);return{validateApiKey:v,saveApiKey:w,getStoredApiKey:b,hasStoredKey:x,getStoredModels:C,removeApiKey:E,validateGoogleMapsKey:O,validateApifyKey:$,getAiModels:_,getProviderDefaults:j,saveProviderDefaults:N,getProviderUsageSummary:A,getAPIUsageSummary:I,getModelConstraints:R,getValidatedAiProviders:F,saveGlobalModel:P,isValidating:f,validationError:m,isConnected:d}},bD=u.createContext({}),Z8e={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"},so=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=Z8e[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=so(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:so(a("r")),g:so(a("g")),b:so(a("b")),a:so(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=>so((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=so(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=so(this.getSaturation()*100),r=so(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=so(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=so((a+m)*255),this.g=so((i+m)*255),this.b=so((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=so(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=so(r*(1-n)*255),p=so(r*(1-n*d)*255),m=so(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("%")?so(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,J8e=.05,e7e=.05,t7e=.15,xD=5,SD=4,n7e=[{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+J8e*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+e7e*t:r=e.v-t7e*t,r=Math.max(0,Math.min(1,r)),Math.round(r*100)/100}function r7e(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"?n7e.map(({index:a,amount:i})=>new Lu(t.backgroundColor||"#141414").mix(n[a],i).toHexString()):n.map(a=>a.toHexString())}const z3=["#e6f4ff","#bae0ff","#91caff","#69b1ff","#4096ff","#1677ff","#0958d9","#003eb3","#002c8c","#001d66"];z3.primary=z3[5];function o7e(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function a7e(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",i7e="rc-util-key",D3=new Map;function wD({mark:e}={}){return e?e.startsWith("data-")?e:`data-${e}`:i7e}function B5(e){return e.attachTo?e.attachTo:document.querySelector("head")||document.body}function l7e(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(!o7e())return null;const{csp:n,prepend:r,priority:o=0}=t,a=l7e(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 s7e(e,t={}){let{styles:n}=t;return n||=H5(B5(t)),n.find(r=>r.getAttribute(wD(t))===e)}function c7e(e,t){const n=D3.get(e);if(!n||!a7e(document,n)){const r=CD("",t),{parentNode:o}=r;D3.set(e,o),e.removeChild(r)}}function u7e(e,t,n={}){const r=B5(n),o=H5(r),a={...n,styles:o};c7e(r,a);const i=s7e(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 d7e(e){return ED(e)instanceof ShadowRoot}function f7e(e){return d7e(e)?ED(e):null}let L3={};const p7e=e=>{};function m7e(e,t){}function g7e(e,t){}function h7e(){L3={}}function OD(e,t,n){!t&&!L3[n]&&(e(!1,n),L3[n]=!0)}function ky(e,t){OD(m7e,e,t)}function y7e(e,t){OD(g7e,e,t)}ky.preMessage=p7e;ky.resetWarned=h7e;ky.noteOnce=y7e;function v7e(e){return e.replace(/-(.)/g,(t,n)=>n.toUpperCase())}function b7e(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[v7e(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 $D(e){return r7e(e)[0]}function _D(e){return e?Array.isArray(e)?e:[e]:[]}const x7e=`
|
|
516
|
+
`,L5=e=>`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`,s8e=L5(i8e),c8e=L5(sD),u8e=L5(l8e),d8e={read:sD},f8e=[{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:f8e,default:"gmail",description:"Email provider"},p8e={emailSend:{displayName:"Email Send",name:"emailSend",icon:s8e,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:c8e,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:u8e,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}]}},m8e=["emailSend","emailRead","emailReceive"],wr={...rCe,...oCe,...Bz,...F6e,...H6e,...V6e,...U6e,...Z6e,...tCe,...aCe,...iCe,...sCe,...cCe,...Dm,...uCe,...hCe,...wCe,..._Ce,...jCe,...GCe,...KCe,...QCe,...t8e,...n8e,...o8e,...p8e};[...hs];const zj=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},g8e=(e=>e?zj(e):zj),h8e=e=>e;function y8e(e,t=h8e){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=g8e(e),n=r=>y8e(t,r);return Object.assign(n,t),n},v8e=(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})),b8e=(e,t=20)=>({x:Math.round(e.x/t)*t,y:Math.round(e.y/t)*t}),x8e=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 S8e=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"]),w8e=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"]),C8e=["api_key","apikey","secret","password","private_key","privatekey","accesstoken","access_token","refreshtoken","refresh_token","bearertoken","bearer_token","oauthtoken","oauth_token","authtoken","auth_token"];function E8e(e){if(w8e.has(e))return!1;if(S8e.has(e))return!0;const t=e.toLowerCase();return C8e.some(n=>t.includes(n))}const O8e=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(!E8e(n)&&!O8e.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.63",$8e=new Set(["label","disabled","condition"]);function b1(e){return e.map(t=>({...t,data:Object.fromEntries(Object.entries(t.data||{}).filter(([n])=>$8e.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 j8e(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 k8e(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 N8e(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=()=>`${Oc.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}),Ou=()=>({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=v8e((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]||Ou()},setWorkflowExecuting:(n,r)=>{e(o=>{const a=o.workflowUIStates[n];return{workflowUIStates:{...o.workflowUIStates,[n]:{...a||Ou(),isExecuting:r}}}})},setWorkflowExecutedNodes:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),executedNodes:r}}}))},setWorkflowExecutionOrder:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),executionOrder:r}}}))},setWorkflowViewport:(n,r)=>{e(o=>({workflowUIStates:{...o.workflowUIStates,[n]:{...o.workflowUIStates[n]||Ou(),viewport:r}}}))},clearWorkflowExecutionState:n=>{e(r=>({workflowUIStates:{...r.workflowUIStates,[n]:{...r.workflowUIStates[n]||Ou(),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 k8e(r,n)},exportWorkflowToFile:n=>{const{currentWorkflow:r}=t();if(!r)throw new Error("No workflow to export");_8e(r,n)},importWorkflowFromJSON:n=>{const r=N8e(n);return e({currentWorkflow:r,hasUnsavedChanges:!0}),r}})),gD=u.createContext(void 0),M8e=({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=()=>`${Oc.PYTHON_BASE_URL}/api/auth`,T8e=({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 $=await(await fetch(`${Jh()}/status`,{credentials:"include"})).json();if($.auth_enabled===!1){n({id:0,email:"anonymous",display_name:"Anonymous",is_owner:!0}),o(!1),p(null);return}i($.auth_mode),d($.can_register),$.authenticated&&$.user?n($.user):n(null),p(null),o(!1)}catch(O){if(console.error(`Failed to check auth status (attempt ${x+1}/6):`,O),x<5){const $=1e3*Math.pow(2,x);console.log(`Retrying in ${$}ms...`),setTimeout(()=>m(x+1),$)}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})}),O=await E.json();return E.ok?O.success&&O.user?(n(O.user),o(!1),!0):(p("Login failed"),o(!1),!1):(p(O.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 O=await fetch(`${Jh()}/register`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:x,password:C,display_name:E})}),$=await O.json();return O.ok?$.success&&$.user?(n($.user),d(!1),o(!1),!0):(p("Registration failed"),o(!1),!1):(p($.detail||"Registration failed"),o(!1),!1)}catch(O){return console.error("Register error:",O),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)}`,R8e=3e4,A8e=["whatsappReceive","webhookTrigger","cronScheduler","chatTrigger","telegramReceive"],I8e=["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"},P8e={locked:!1,workflow_id:null,locked_at:null,reason:null},Gj={connected:!1,has_session:!1,running:!1,pairing:!1},z8e={connected:!1,username:null,user_id:null},D8e={connected:!1,email:null},L8e={connected:!1,bot_username:null,bot_name:null,bot_id:null,owner_chat_id:null},yD=u.createContext(null),F8e=()=>{const e=Oc.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`},B8e=100,H8e=({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(z8e),[b,x]=u.useState(D8e),[C,E]=u.useState(L8e),[O,$]=u.useState([]),[_,j]=u.useState(null),[N,A]=u.useState({}),[I,R]=u.useState([]),[F,P]=u.useState([]),[L,T]=u.useState([]),[B,z]=u.useState({}),[H,D]=u.useState({}),[q,W]=u.useState({}),[U,G]=u.useState(Uj),[V,X]=u.useState(qj),[Q,J]=u.useState(P8e),[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 Te=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===Te&&(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:Te,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:Pe}=Sr.getState();Pe(o,Ne),J({locked:Ne,workflow_id:Ne?o:null,locked_at:Ne?Date.now():null,reason:Ne?"Workflow is running":null})}catch(Te){console.error("[WebSocket] Failed to fetch deployment status:",Te)}})()},[o]);const Oe=u.useCallback(de=>{try{const ce=JSON.parse(de.data),{type:Te,data:se,node_id:Ne,name:Pe,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(Te){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}z(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),$(Et=>[Ve,...Et].slice(0,B8e))}break;case"node_status":if(Ne){const Ve=ce.workflow_id||"unknown",Et=se?.data||{},Gt={...se,...Et,workflow_id:Ve};z(Ke=>({...Ke,[Ve]:{...Ke[Ve]||{},[Ne]:Gt}}))}break;case"node_output":if(Ne){const Ve=ce.workflow_id||"unknown";z(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;z(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(Pe!==void 0){const Ve=ce.workflow_id||"unknown";W(Et=>({...Et,[Ve]:{...Et[Ve]||{},[Pe]: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};P(Et=>[Ve,...Et].slice(0,200))}break;case"terminal_logs_cleared":P([]);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=F8e();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 Te=["openai","anthropic","gemini","google_maps","android_remote"];for(const se of Te)try{(await new Promise((Pe,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),Pe(Et))}catch{}};ce.addEventListener("message",gt),ce.send(JSON.stringify({type:"get_stored_api_key",provider:se,request_id:Nt}))})).has_key&&A(Pe=>({...Pe,[se]:{hasKey:!0,valid:!0}}))}catch{}try{const se=await new Promise((Ne,Pe)=>{const ct=`terminal_logs_${Date.now()}`,Nt=setTimeout(()=>Pe(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(Pe=>({timestamp:Pe.timestamp||new Date().toISOString(),level:Pe.level||"info",message:Pe.message||"",source:Pe.source,details:Pe.details})).reverse();P(Ne)}}catch{}try{const se=await new Promise((Ne,Pe)=>{const ct=`chat_messages_${Date.now()}`,Nt=setTimeout(()=>Pe(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(Pe=>({role:Pe.role,message:Pe.message,timestamp:Pe.timestamp}));T(Ne)}}catch{}try{const se=`console_${Date.now()}`,Ne=await new Promise((Pe,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),Pe(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 Pe=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(Pe)}}catch{}},ce.onmessage=Oe,ce.onclose=Te=>{console.log("[WebSocket] Disconnected:",Te.code,Te.reason),i(!1),ee.current=null,pe.current&&(clearInterval(pe.current),pe.current=null),Te.code!==1e3&&(d(!0),ve.current=setTimeout(()=>{re()},3e3))},ce.onerror=Te=>{console.error("[WebSocket] Error:",Te)},ee.current=ce}catch(ce){console.error("[WebSocket] Failed to create connection:",ce),d(!0),ve.current=setTimeout(re,3e3)}},[Oe]),Z=u.useCallback(()=>{ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"get_status"}))},[]),ie=u.useCallback(de=>{if(o)return B[o]?.[de]},[B,o]),le=u.useCallback(de=>N[de],[N]),be=u.useCallback(de=>{if(o)return q[o]?.[de]},[q,o]),$e=u.useCallback(async de=>{const ce=Ce.current;z(Te=>{if(!ce||!Te[ce])return Te;const se={...Te[ce]};return delete se[de],{...Te,[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(Te){console.error("[WebSocket] Failed to clear backend node output:",Te)}},[]),ze=u.useCallback(()=>{$([]),j(null)},[]),Be=u.useCallback(()=>{R([]),ee.current?.readyState===WebSocket.OPEN&&ee.current.send(JSON.stringify({type:"clear_console_logs"}))},[]),Ae=u.useCallback(()=>{P([]),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?B[o]||{}:{},[B,o]),xe=u.useMemo(()=>o?q[o]||{}:{},[q,o]),Re=u.useMemo(()=>o?te[o]||{}:{},[te,o]),De=u.useCallback((de,ce,Te)=>{ae(se=>({...se,[de]:{...se[de]||{},[ce]:Te}}))},[]),he=u.useCallback(async(de,ce,Te)=>new Promise((se,Ne)=>{if(!ee.current||ee.current.readyState!==WebSocket.OPEN){Ne(new Error("WebSocket not connected"));return}const Pe=Wj(),ct=Te===void 0||Te>=0,Nt=Te&&Te>0?Te:R8e;let et=null;ct&&Te!==-1&&(et=setTimeout(()=>{fe.current.delete(Pe),Ne(new Error(`Request timeout: ${de}`))},Nt)),fe.current.set(Pe,{resolve:se,reject:Ne,timeout:et}),ee.current.send(JSON.stringify({type:de,request_id:Pe,...ce}))}),[]),Qe=u.useCallback(async(de,ce)=>{const Te=new Date().toISOString(),se={role:"user",message:de,timestamp:Te};T(Ne=>[...Ne,se]);try{await he("send_chat_message",{message:de,role:"user",node_id:ce,session_id:"default",timestamp:Te})}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 Te={parameters:ce.parameters,version:ce.version||0,timestamp:ce.timestamp};return D(se=>({...se,[de]:Te})),Te}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}),Te={};if(ce.parameters){for(const[se,Ne]of Object.entries(ce.parameters))Te[se]={parameters:Ne.parameters||{},version:Ne.version||0,timestamp:ce.timestamp};D(se=>({...se,...Te}))}return Te}catch(ce){return console.error("[WebSocket] Failed to get all node parameters:",ce),{}}},[he]),tt=u.useCallback(async(de,ce,Te)=>{try{const se=H[de]?.version||Te||0,Ne=await he("save_node_parameters",{node_id:de,parameters:ce,version:se});return Ne.success!==!1?(D(Pe=>({...Pe,[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 Te={...ce};return delete Te[de],Te}),!0}catch(ce){return console.error("[WebSocket] Failed to delete node parameters:",ce),!1}},[he]),Ge=u.useCallback(async(de,ce,Te,se,Ne)=>{try{const ct=A8e.includes(ce)||I8e.includes(ce)?-1:void 0;return await he("execute_node",{node_id:de,node_type:ce,parameters:Te,nodes:se,edges:Ne,workflow_id:o},ct)}catch(Pe){throw console.error("[WebSocket] Failed to execute node:",Pe),Pe}},[he,o]),je=u.useCallback(async(de,ce)=>{try{const Te=await he("get_node_output",{node_id:de,output_name:ce||"output_0"});return Te.success?Te.data:null}catch(Te){return console.error("[WebSocket] Failed to get node output:",Te),null}},[he]),Le=u.useCallback(async(de,ce)=>{try{return await he("cancel_event_wait",{node_id:de,waiter_id:ce})}catch(Te){return console.error("[WebSocket] Failed to cancel event wait:",Te),{success:!1}}},[he]),dt=u.useCallback(async(de,ce,Te)=>{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:Te||"default"})}catch(se){throw console.error("[WebSocket] Failed to execute workflow:",se),se}},[he]),St=u.useCallback(async(de,ce,Te,se)=>{try{return await he("deploy_workflow",{workflow_id:de,nodes:ce.map(Pe=>({id:Pe.id,type:Pe.type||"",data:Pe.data||{}})),edges:Te.map(Pe=>({id:Pe.id,source:Pe.source,target:Pe.target,sourceHandle:Pe.sourceHandle||void 0,targetHandle:Pe.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,Te,se,Ne,Pe,ct)=>{try{return await he("execute_ai_node",{node_id:de,node_type:ce,parameters:Te,model:se,workflow_id:Ne,nodes:Pe,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(Te){return console.error("[WebSocket] Failed to get AI models:",Te),[]}},[he]),yt=u.useCallback(async(de,ce)=>{try{const Te=await he("validate_api_key",{provider:de,api_key:ce}),se={valid:Te.valid||!1,message:Te.message,models:Te.models};return se.valid&&A(Ne=>({...Ne,[de]:{hasKey:!0,valid:!0,models:se.models}})),se}catch(Te){return console.error("[WebSocket] Failed to validate API key:",Te),{valid:!1,message:"Validation failed"}}},[he]),ut=u.useCallback(async de=>{try{const ce=await he("get_stored_api_key",{provider:de}),Te={hasKey:ce.has_key||!1,apiKey:ce.api_key,models:ce.models};return Te.hasKey&&A(se=>({...se,[de]:{hasKey:!0,valid:!0,models:Te.models}})),Te}catch(ce){return console.error("[WebSocket] Failed to get stored API key:",ce),{hasKey:!1}}},[he]),Ct=u.useCallback(async(de,ce,Te)=>{try{const Ne=(await he("save_api_key",{provider:de,api_key:ce,models:Te})).success!==!1;return Ne&&A(Pe=>({...Pe,[de]:{hasKey:!0,valid:!0,models:Te}})),Ne}catch(se){return console.error("[WebSocket] Failed to save API key:",se),!1}},[he]),Ht=u.useCallback(async de=>{try{return await he("delete_api_key",{provider:de}),A(ce=>{const Te={...ce};return delete Te[de],Te}),!0}catch(ce){return console.error("[WebSocket] Failed to delete API key:",ce),!1}},[he]),Wt=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,Te,se)=>{try{return await he("execute_android_action",{service_id:de,action:ce,parameters:Te,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 Te=await he("whatsapp_send",{phone:de,message:ce});return{success:Te.success||!1,messageId:Te.messageId,error:Te.error}}catch(Te){return console.error("[WebSocket] Failed to send WhatsApp message:",Te),{success:!1,error:Te.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]),Ot=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]),Vt=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]),Dt=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]),Me=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]),$t=u.useCallback(async(de,ce=!1)=>{try{const Te=await he("clear_memory",{session_id:de,clear_long_term:ce});return{success:Te.success!==!1,default_content:Te.default_content,cleared_vector_store:Te.cleared_vector_store,error:Te.error}}catch(Te){return console.error("[WebSocket] Failed to clear memory:",Te),{success:!1,error:Te.message||"Failed to clear memory"}}},[he]),Lt=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]),Ft=u.useRef(!0);u.useEffect(()=>{if(Ft.current=!0,n||!t||ee.current?.readyState===WebSocket.OPEN)return;const de=setTimeout(()=>{Ft.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(()=>()=>{Ft.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:O,lastWhatsAppMessage:_,apiKeyStatuses:N,consoleLogs:I,terminalLogs:F,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:$e,clearWhatsAppMessages:ze,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:Ht,getAndroidDevices:Wt,executeAndroidAction:wt,validateMapsKey:It,validateApifyKey:Mt,getWhatsAppStatus:ot,getWhatsAppQR:Fe,sendWhatsAppMessage:Xe,startWhatsAppConnection:at,restartWhatsAppConnection:Ot,getWhatsAppGroups:jt,getWhatsAppChannels:Vt,getWhatsAppGroupInfo:Dt,getWhatsAppRateLimitConfig:Rt,setWhatsAppRateLimitConfig:en,getWhatsAppRateLimitStats:yn,unpauseWhatsAppRateLimit:Me,clearMemory:$t,resetSkill:Lt};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},W8e=()=>{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},V8e=()=>{const{twitterStatus:e}=Qn();return e},U8e=()=>{const{googleStatus:e}=Qn();return e},q8e=()=>{const{telegramStatus:e}=Qn();return e},G8e=({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,O]=u.useState(""),$=u.useRef(null);u.useEffect(()=>{s===e?(C(!0),O(n?.label||b?.displayName||t||"")):C(!1)},[s,e,n?.label,b?.displayName,t]),u.useEffect(()=>{x&&$.current&&($.current.focus(),$.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"})):[],F=I(),P=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||"📦":"📦",B=()=>b.defaults.color||"#9E9E9E",z=()=>{const H=B();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, ${B()} 0%, ${z()} 100%)`,border:`2px solid ${w?a.isDarkMode?a.dracula.cyan:"#2563eb":o?"#3b82f6":z()}`,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 ${B()}40, 0 0 0 2px ${a.colors.focus}`:a.isDarkMode?`0 4px 12px ${B()}40`:`0 2px 8px ${B()}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:"||"})}),F.map((H,D)=>{const q=F.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Hr,{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 ${z()}`,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:B(),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:$,type:"text",value:E,onChange:H=>O(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})]}),P.map((H,D)=>{const q=P.length,W=q===1?"50%":`${20+60*D/Math.max(q-1,1)}%`;return g.jsx(Hr,{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 ${z()}`,borderRadius:"50%"},title:`${H.displayName}: ${H.description}`},`output-${H.name}-${D}`)})]})};class K8e{static validateConfiguration(t){const n=[];return(!t.prompt||t.prompt.trim()==="")&&n.push("Prompt is required"),{valid:n.length===0,errors:n}}}const X8e={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"}},Y8e=({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"})}),Q8e=({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(Y8e,{}),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(Q8e,{}),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(()=>zt[m.themeColorKey]||zt.purple,[m.themeColorKey]),v=vD(e),w=v?.status==="executing",b=v?.data?.phase,x=b?X8e[b]:null;u.useEffect(()=>{try{const _=K8e.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,O=()=>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}`,$=m.rightHandles&&m.rightHandles.length>0;return g.jsxs("div",{style:{position:"relative",padding:a.spacing.lg,paddingRight:$?"60px":a.spacing.lg,paddingLeft:a.spacing.lg,minWidth:m.width?`${m.width}px`:m.wider?"220px":$?"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:O(),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(Hr,{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(Hr,{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(Hr,{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(Hr,{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(Hr,{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(Hr,{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 $=m?.credentials?.[0];return $?.name&&Xj[$.name]?Xj[$.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=$=>{$.stopPropagation(),i({id:e,type:t,data:n,position:{x:0,y:0}})},E=m?.defaults?.color||"#6b7280",O=()=>{const $=Mz(y);return $?g.jsx($,{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:[O(),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(Hr,{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 B=await e(L,T);return B.valid||y(B.message||"Validation failed"),{isValid:B.valid,error:B.message,models:B.models}}catch(B){const z=B.message||"Validation failed";return y(z),{isValid:!1,error:z}}finally{p(!1)}},[e]),w=u.useCallback(async(L,T)=>{try{const B=await n(L,T);return{isValid:B,error:B?void 0:"Failed to save API key"}}catch(B){return{isValid:!1,error:B.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]),O=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 B=T.message||"Validation failed";return y(B),{isValid:!1,error:B}}finally{p(!1)}},[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 B=T.message||"Validation failed";return y(B),{isValid:!1,error:B}}finally{p(!1)}},[a]),_=u.useCallback(async(L,T)=>{try{return await i(L,T)}catch(B){return console.warn(`Error fetching AI models for ${L}:`,B),[]}},[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(B){return console.warn(`Error fetching provider defaults for ${L}:`,B),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(B){return console.warn(`Error saving provider defaults for ${L}:`,B),!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 B={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 B;try{return await s("get_model_constraints",{model:L,provider:T})||B}catch(z){return console.warn(`Error fetching model constraints for ${T}/${L}:`,z),B}},[s,d]),F=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]),P=u.useCallback(async(L,T)=>{if(!d)return!1;try{return(await s("save_global_model",{provider:L,model:T}))?.success??!1}catch(B){return console.warn("Error saving global model:",B),!1}},[s,d]);return{validateApiKey:v,saveApiKey:w,getStoredApiKey:b,hasStoredKey:x,getStoredModels:C,removeApiKey:E,validateGoogleMapsKey:O,validateApifyKey:$,getAiModels:_,getProviderDefaults:j,saveProviderDefaults:N,getProviderUsageSummary:A,getAPIUsageSummary:I,getModelConstraints:R,getValidatedAiProviders:F,saveGlobalModel:P,isValidating:f,validationError:m,isConnected:d}},bD=u.createContext({}),Z8e={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"},so=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=Z8e[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=so(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:so(a("r")),g:so(a("g")),b:so(a("b")),a:so(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=>so((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=so(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=so(this.getSaturation()*100),r=so(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=so(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=so((a+m)*255),this.g=so((i+m)*255),this.b=so((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=so(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=so(r*(1-n)*255),p=so(r*(1-n*d)*255),m=so(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("%")?so(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,J8e=.05,e7e=.05,t7e=.15,xD=5,SD=4,n7e=[{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+J8e*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+e7e*t:r=e.v-t7e*t,r=Math.max(0,Math.min(1,r)),Math.round(r*100)/100}function r7e(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"?n7e.map(({index:a,amount:i})=>new Lu(t.backgroundColor||"#141414").mix(n[a],i).toHexString()):n.map(a=>a.toHexString())}const z3=["#e6f4ff","#bae0ff","#91caff","#69b1ff","#4096ff","#1677ff","#0958d9","#003eb3","#002c8c","#001d66"];z3.primary=z3[5];function o7e(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function a7e(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",i7e="rc-util-key",D3=new Map;function wD({mark:e}={}){return e?e.startsWith("data-")?e:`data-${e}`:i7e}function B5(e){return e.attachTo?e.attachTo:document.querySelector("head")||document.body}function l7e(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(!o7e())return null;const{csp:n,prepend:r,priority:o=0}=t,a=l7e(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 s7e(e,t={}){let{styles:n}=t;return n||=H5(B5(t)),n.find(r=>r.getAttribute(wD(t))===e)}function c7e(e,t){const n=D3.get(e);if(!n||!a7e(document,n)){const r=CD("",t),{parentNode:o}=r;D3.set(e,o),e.removeChild(r)}}function u7e(e,t,n={}){const r=B5(n),o=H5(r),a={...n,styles:o};c7e(r,a);const i=s7e(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 d7e(e){return ED(e)instanceof ShadowRoot}function f7e(e){return d7e(e)?ED(e):null}let L3={};const p7e=e=>{};function m7e(e,t){}function g7e(e,t){}function h7e(){L3={}}function OD(e,t,n){!t&&!L3[n]&&(e(!1,n),L3[n]=!0)}function ky(e,t){OD(m7e,e,t)}function y7e(e,t){OD(g7e,e,t)}ky.preMessage=p7e;ky.resetWarned=h7e;ky.noteOnce=y7e;function v7e(e){return e.replace(/-(.)/g,(t,n)=>n.toUpperCase())}function b7e(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[v7e(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 $D(e){return r7e(e)[0]}function _D(e){return e?Array.isArray(e)?e:[e]:[]}const x7e=`
|
|
517
517
|
.anticon {
|
|
518
518
|
display: inline-flex;
|
|
519
519
|
align-items: center;
|
package/client/dist/index.html
CHANGED
|
@@ -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-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-BdaCgeVr.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/assets/index-DFSC53FP.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
package/client/package.json
CHANGED
|
@@ -131,6 +131,35 @@ export const browserNodes: Record<string, INodeTypeDescription> = {
|
|
|
131
131
|
description: 'Capture the full scrollable page',
|
|
132
132
|
displayOptions: { show: { operation: ['screenshot'] } },
|
|
133
133
|
},
|
|
134
|
+
{
|
|
135
|
+
displayName: 'Annotate',
|
|
136
|
+
name: 'annotate',
|
|
137
|
+
type: 'boolean',
|
|
138
|
+
default: false,
|
|
139
|
+
description: 'Add numbered labels to interactive elements (useful for AI vision models)',
|
|
140
|
+
displayOptions: { show: { operation: ['screenshot'] } },
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
displayName: 'Format',
|
|
144
|
+
name: 'screenshotFormat',
|
|
145
|
+
type: 'options',
|
|
146
|
+
default: 'png',
|
|
147
|
+
options: [
|
|
148
|
+
{ name: 'PNG', value: 'png' },
|
|
149
|
+
{ name: 'JPEG', value: 'jpeg' },
|
|
150
|
+
],
|
|
151
|
+
description: 'Screenshot image format',
|
|
152
|
+
displayOptions: { show: { operation: ['screenshot'] } },
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
displayName: 'Quality',
|
|
156
|
+
name: 'screenshotQuality',
|
|
157
|
+
type: 'number',
|
|
158
|
+
default: 80,
|
|
159
|
+
typeOptions: { minValue: 1, maxValue: 100 },
|
|
160
|
+
description: 'JPEG quality (1-100, only used for JPEG format)',
|
|
161
|
+
displayOptions: { show: { operation: ['screenshot'], screenshotFormat: ['jpeg'] } },
|
|
162
|
+
},
|
|
134
163
|
{
|
|
135
164
|
displayName: 'JavaScript Expression',
|
|
136
165
|
name: 'expression',
|
package/package.json
CHANGED
|
@@ -161,6 +161,13 @@ class ResponseExtractor:
|
|
|
161
161
|
if getattr(msg, "type", None) == "ai" and getattr(msg, "tool_calls", None):
|
|
162
162
|
iterations += 1
|
|
163
163
|
|
|
164
|
+
# Log all messages for debugging
|
|
165
|
+
for i, msg in enumerate(messages):
|
|
166
|
+
msg_type = getattr(msg, "type", "?")
|
|
167
|
+
has_tools = bool(getattr(msg, "tool_calls", None))
|
|
168
|
+
content_preview = str(getattr(msg, "content", ""))[:150]
|
|
169
|
+
logger.info("[DeepAgent] msg[%d] type=%s tool_calls=%s content=%s", i, msg_type, has_tools, content_preview)
|
|
170
|
+
|
|
164
171
|
# Extract final AI response
|
|
165
172
|
for msg in reversed(messages):
|
|
166
173
|
if getattr(msg, "type", None) == "ai" and hasattr(msg, "content"):
|
|
@@ -185,6 +192,11 @@ class ResponseExtractor:
|
|
|
185
192
|
_, thinking_content = extract_thinking_from_response(msg)
|
|
186
193
|
break
|
|
187
194
|
|
|
195
|
+
logger.info("[DeepAgent] Extracted: response_len=%d thinking=%s iterations=%d",
|
|
196
|
+
len(response_content), thinking_content is not None, max(iterations, 1))
|
|
197
|
+
if not response_content:
|
|
198
|
+
logger.warning("[DeepAgent] Empty response extracted from %d messages", len(messages))
|
|
199
|
+
|
|
188
200
|
return {
|
|
189
201
|
"response": response_content,
|
|
190
202
|
"thinking": thinking_content,
|
|
@@ -161,7 +161,18 @@ def _build_args(op: str, p: Dict[str, Any]) -> list:
|
|
|
161
161
|
case "fill":
|
|
162
162
|
return ["fill", _req_sel(s), p.get("value") or ""]
|
|
163
163
|
case "screenshot":
|
|
164
|
-
|
|
164
|
+
args = ["screenshot"]
|
|
165
|
+
if p.get("fullPage"):
|
|
166
|
+
args.append("--full")
|
|
167
|
+
if p.get("annotate"):
|
|
168
|
+
args.append("--annotate")
|
|
169
|
+
fmt = p.get("screenshotFormat", "png")
|
|
170
|
+
if fmt and fmt != "png":
|
|
171
|
+
args.extend(["--screenshot-format", fmt])
|
|
172
|
+
quality = p.get("screenshotQuality")
|
|
173
|
+
if quality and fmt == "jpeg":
|
|
174
|
+
args.extend(["--screenshot-quality", str(quality)])
|
|
175
|
+
return args
|
|
165
176
|
case "snapshot":
|
|
166
177
|
return ["snapshot", "-i"]
|
|
167
178
|
case "get_text":
|
|
@@ -42,33 +42,41 @@ async def handle_process_manager(
|
|
|
42
42
|
return result
|
|
43
43
|
|
|
44
44
|
|
|
45
|
+
def _clean_arg(val: str) -> str:
|
|
46
|
+
"""LLMs sometimes pass literal 'None' string instead of omitting the field."""
|
|
47
|
+
if not val or val == "None":
|
|
48
|
+
return ""
|
|
49
|
+
return val
|
|
50
|
+
|
|
51
|
+
|
|
45
52
|
async def execute_process_manager(tool_args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:
|
|
46
53
|
"""AI tool entry point. Dispatches by operation."""
|
|
47
54
|
svc = get_process_service()
|
|
48
55
|
op = tool_args.get("operation", "list")
|
|
49
56
|
workflow_id = config.get("workflow_id", "default")
|
|
50
|
-
name = tool_args.get("name", "")
|
|
57
|
+
name = _clean_arg(tool_args.get("name", ""))
|
|
58
|
+
workspace_dir = config.get("workspace_dir", "")
|
|
51
59
|
|
|
52
|
-
logger.info("[ProcessManager] op=%s name=%s", op, name)
|
|
60
|
+
logger.info("[ProcessManager] op=%s name=%s workspace=%s", op, name, workspace_dir)
|
|
53
61
|
|
|
54
62
|
if op == "start":
|
|
55
63
|
return await svc.start(
|
|
56
64
|
name=name,
|
|
57
|
-
command=tool_args.get("command", ""),
|
|
65
|
+
command=_clean_arg(tool_args.get("command", "")),
|
|
58
66
|
workflow_id=workflow_id,
|
|
59
|
-
working_directory=tool_args.get("working_directory",
|
|
67
|
+
working_directory=_clean_arg(tool_args.get("working_directory", "")) or workspace_dir,
|
|
60
68
|
)
|
|
61
69
|
elif op == "stop":
|
|
62
70
|
return await svc.stop(name, workflow_id)
|
|
63
71
|
elif op == "restart":
|
|
64
72
|
return await svc.restart(name, workflow_id)
|
|
65
73
|
elif op == "send_input":
|
|
66
|
-
return await svc.send_input(name, workflow_id, tool_args.get("text", ""))
|
|
74
|
+
return await svc.send_input(name, workflow_id, _clean_arg(tool_args.get("text", "")))
|
|
67
75
|
elif op == "list":
|
|
68
76
|
return {"success": True, "result": {"processes": svc.list_processes(workflow_id)}}
|
|
69
77
|
elif op == "get_output":
|
|
70
|
-
stream = tool_args.get("stream", "stdout"
|
|
71
|
-
tail = int(tool_args.get("tail", 50))
|
|
78
|
+
stream = _clean_arg(tool_args.get("stream", "")) or "stdout"
|
|
79
|
+
tail = int(tool_args.get("tail", 50) or 50)
|
|
72
80
|
offset = int(tool_args.get("offset", 0))
|
|
73
81
|
return {"success": True, "result": svc.get_output(name, workflow_id, stream, tail, offset)}
|
|
74
82
|
else:
|
|
@@ -192,7 +192,14 @@ class ProcessService:
|
|
|
192
192
|
managed.exit_code = -1
|
|
193
193
|
|
|
194
194
|
logger.info("[Process] Stopped: %s (exit=%s)", name, managed.exit_code)
|
|
195
|
-
|
|
195
|
+
result = self._info(managed)
|
|
196
|
+
|
|
197
|
+
# Schedule cleanup after 60s to allow output reading
|
|
198
|
+
asyncio.get_event_loop().call_later(
|
|
199
|
+
60, lambda: self._cleanup_completed(workflow_id, name)
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
return {"success": True, "result": result}
|
|
196
203
|
|
|
197
204
|
async def restart(self, name: str, workflow_id: str = "default") -> Dict[str, Any]:
|
|
198
205
|
"""Restart a process with the same command."""
|
|
@@ -268,13 +275,54 @@ class ProcessService:
|
|
|
268
275
|
|
|
269
276
|
return {"lines": lines, "total": total, "file": str(log_file)}
|
|
270
277
|
|
|
271
|
-
def
|
|
272
|
-
"""Remove log files for a process.
|
|
278
|
+
def _cleanup_completed(self, workflow_id: str, name: str) -> None:
|
|
279
|
+
"""Remove log files and process entry for a completed process.
|
|
280
|
+
|
|
281
|
+
Called automatically 60s after process exits, giving time to read output.
|
|
282
|
+
Also cleans the parent .processes/ dir if empty.
|
|
283
|
+
"""
|
|
273
284
|
key = self._key(workflow_id, name)
|
|
274
285
|
managed = self._processes.get(key)
|
|
275
|
-
if managed
|
|
286
|
+
if not managed or managed.status == "running":
|
|
287
|
+
return
|
|
288
|
+
|
|
289
|
+
# Remove log directory
|
|
290
|
+
if managed.log_dir.exists():
|
|
276
291
|
shutil.rmtree(managed.log_dir, ignore_errors=True)
|
|
277
|
-
|
|
292
|
+
|
|
293
|
+
# Remove parent .processes/ if empty
|
|
294
|
+
parent = managed.log_dir.parent
|
|
295
|
+
if parent.exists() and parent.name == ".processes" and not any(parent.iterdir()):
|
|
296
|
+
parent.rmdir()
|
|
297
|
+
|
|
298
|
+
# Remove from tracking dict
|
|
299
|
+
self._processes.pop(key, None)
|
|
300
|
+
logger.info("[Process] Cleaned up: %s (workflow=%s)", name, workflow_id)
|
|
301
|
+
|
|
302
|
+
async def stop_workflow(self, workflow_id: str) -> int:
|
|
303
|
+
"""Stop all processes for a workflow and clean up immediately."""
|
|
304
|
+
killed = 0
|
|
305
|
+
for key in list(self._processes.keys()):
|
|
306
|
+
wid, name = key
|
|
307
|
+
if wid != workflow_id:
|
|
308
|
+
continue
|
|
309
|
+
managed = self._processes[key]
|
|
310
|
+
if managed.status == "running":
|
|
311
|
+
_kill_process_tree(managed.pid)
|
|
312
|
+
for task in (managed.stdout_task, managed.stderr_task):
|
|
313
|
+
if task and not task.done():
|
|
314
|
+
task.cancel()
|
|
315
|
+
killed += 1
|
|
316
|
+
logger.info("[Process] Killed for workflow stop: %s (pid=%d)", name, managed.pid)
|
|
317
|
+
# Clean log files and remove entry
|
|
318
|
+
if managed.log_dir.exists():
|
|
319
|
+
shutil.rmtree(managed.log_dir, ignore_errors=True)
|
|
320
|
+
self._processes.pop(key, None)
|
|
321
|
+
|
|
322
|
+
# Clean parent .processes/ dirs if empty
|
|
323
|
+
if killed:
|
|
324
|
+
logger.info("[Process] Stopped %d process(es) for workflow %s", killed, workflow_id)
|
|
325
|
+
return killed
|
|
278
326
|
|
|
279
327
|
async def shutdown(self) -> None:
|
|
280
328
|
"""Kill all managed processes and clean up log files."""
|
|
@@ -340,6 +388,11 @@ class ProcessService:
|
|
|
340
388
|
managed.status = "stopped" if managed.exit_code == 0 else "error"
|
|
341
389
|
logger.info("[Process] Exited: %s (exit=%s)", managed.name, managed.exit_code)
|
|
342
390
|
|
|
391
|
+
# Schedule auto-cleanup of log files and process entry after delay
|
|
392
|
+
asyncio.get_event_loop().call_later(
|
|
393
|
+
60, lambda: self._cleanup_completed(managed.workflow_id, managed.name)
|
|
394
|
+
)
|
|
395
|
+
|
|
343
396
|
@staticmethod
|
|
344
397
|
def _info(m: ManagedProcess) -> Dict[str, Any]:
|
|
345
398
|
return {
|
|
@@ -4,7 +4,7 @@ description: Execute short-lived shell commands in a sandboxed environment. No P
|
|
|
4
4
|
allowed-tools: shell_execute
|
|
5
5
|
metadata:
|
|
6
6
|
author: machina
|
|
7
|
-
version: "
|
|
7
|
+
version: "3.0"
|
|
8
8
|
category: execution
|
|
9
9
|
icon: "\U0001F4BB"
|
|
10
10
|
color: "#ff79c6"
|
|
@@ -23,15 +23,6 @@ Execute short-lived shell commands in a sandboxed workspace. The shell runs with
|
|
|
23
23
|
| command | string | Yes | Shell command to execute |
|
|
24
24
|
| timeout | int | No | Timeout in seconds (default: 30, max: 300) |
|
|
25
25
|
|
|
26
|
-
### Examples
|
|
27
|
-
|
|
28
|
-
```json
|
|
29
|
-
{"command": "ls -la"}
|
|
30
|
-
{"command": "cat README.md"}
|
|
31
|
-
{"command": "echo hello > output.txt"}
|
|
32
|
-
{"command": "find . -name '*.py' -type f"}
|
|
33
|
-
```
|
|
34
|
-
|
|
35
26
|
### Response
|
|
36
27
|
|
|
37
28
|
```json
|
|
@@ -39,7 +30,7 @@ Execute short-lived shell commands in a sandboxed workspace. The shell runs with
|
|
|
39
30
|
"stdout": "command output",
|
|
40
31
|
"exit_code": 0,
|
|
41
32
|
"truncated": false,
|
|
42
|
-
"command": "
|
|
33
|
+
"command": "dir"
|
|
43
34
|
}
|
|
44
35
|
```
|
|
45
36
|
|
|
@@ -51,36 +42,69 @@ Execute short-lived shell commands in a sandboxed workspace. The shell runs with
|
|
|
51
42
|
| 124 | Timed out |
|
|
52
43
|
| non-zero | Failure |
|
|
53
44
|
|
|
45
|
+
## OS-Specific Commands
|
|
46
|
+
|
|
47
|
+
The shell uses the system's native shell (`cmd.exe` on Windows, `/bin/sh` on Linux/macOS). Use the correct commands for the platform.
|
|
48
|
+
|
|
49
|
+
### Detect OS first
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{"command": "ver"}
|
|
53
|
+
```
|
|
54
|
+
If output contains `Windows`, use Windows commands. Otherwise use Unix commands.
|
|
55
|
+
|
|
56
|
+
### Windows (cmd.exe)
|
|
57
|
+
|
|
58
|
+
| Task | Command |
|
|
59
|
+
|------|---------|
|
|
60
|
+
| List files | `dir` |
|
|
61
|
+
| List with details | `dir /a` |
|
|
62
|
+
| Read file | `type README.md` |
|
|
63
|
+
| Write to file | `echo hello > output.txt` |
|
|
64
|
+
| Find files | `dir /s /b *.py` |
|
|
65
|
+
| Search content | `findstr /s /i "pattern" *.py` |
|
|
66
|
+
| Copy file | `copy src.txt dst.txt` |
|
|
67
|
+
| Move file | `move src.txt dst.txt` |
|
|
68
|
+
| Delete file | `del output.txt` |
|
|
69
|
+
| Delete folder | `rmdir /s /q folder` |
|
|
70
|
+
| Create folder | `mkdir newfolder` |
|
|
71
|
+
| Show current dir | `cd` |
|
|
72
|
+
|
|
73
|
+
### Linux / macOS (sh)
|
|
74
|
+
|
|
75
|
+
| Task | Command |
|
|
76
|
+
|------|---------|
|
|
77
|
+
| List files | `ls -la` |
|
|
78
|
+
| Read file | `cat README.md` |
|
|
79
|
+
| Write to file | `echo hello > output.txt` |
|
|
80
|
+
| Find files | `find . -name '*.py' -type f` |
|
|
81
|
+
| Search content | `grep -r "pattern" --include='*.py' .` |
|
|
82
|
+
| Copy file | `cp src.txt dst.txt` |
|
|
83
|
+
| Move file | `mv src.txt dst.txt` |
|
|
84
|
+
| Delete file | `rm output.txt` |
|
|
85
|
+
| Delete folder | `rm -rf folder` |
|
|
86
|
+
| Create folder | `mkdir -p newfolder` |
|
|
87
|
+
| Show current dir | `pwd` |
|
|
88
|
+
|
|
54
89
|
## Shell vs Process Manager
|
|
55
90
|
|
|
56
91
|
| Need | Tool | Why |
|
|
57
92
|
|------|------|-----|
|
|
58
|
-
| List
|
|
59
|
-
| Delete files
|
|
60
|
-
| Search content
|
|
61
|
-
| Echo, cat, simple file ops | **shell_execute** | Sandboxed |
|
|
93
|
+
| List/read/copy/move files | **shell_execute** | Sandboxed, safe |
|
|
94
|
+
| Delete files | **shell_execute** | Confined to workspace |
|
|
95
|
+
| Search file content | **shell_execute** | Fast, no PATH needed |
|
|
62
96
|
| `npm install`, `pip install` | **process_manager** | Needs PATH |
|
|
63
97
|
| `python script.py`, `node app.js` | **process_manager** | Needs PATH |
|
|
64
|
-
| Dev servers, watchers
|
|
65
|
-
|
|
66
|
-
The shell is the **only safe tool for file deletion**. It runs inside the agent's workspace with `virtual_mode=True` (path traversal blocked). The process_manager blocks destructive commands like `rm` since it has full PATH and could reach outside the workspace.
|
|
67
|
-
|
|
68
|
-
## OS-Specific Commands
|
|
69
|
-
|
|
70
|
-
For OS-specific syntax and tools, refer to:
|
|
71
|
-
- **bash-skill** -- Linux/macOS commands (find, grep, apt, brew)
|
|
72
|
-
- **powershell-skill** -- Windows commands (Get-ChildItem, Select-String)
|
|
73
|
-
- **wsl-skill** -- Running Linux tools on Windows via WSL
|
|
98
|
+
| Dev servers, watchers | **process_manager** | Long-running |
|
|
74
99
|
|
|
75
|
-
|
|
100
|
+
The shell is the **only safe tool for file deletion**. It runs inside the agent's workspace with `virtual_mode=True` (path traversal blocked). The process_manager blocks destructive commands since it has full PATH.
|
|
76
101
|
|
|
77
102
|
## Guidelines
|
|
78
103
|
|
|
79
|
-
1. **
|
|
80
|
-
2. **
|
|
81
|
-
3. **No
|
|
82
|
-
4.
|
|
83
|
-
5.
|
|
84
|
-
6.
|
|
85
|
-
7.
|
|
86
|
-
8. Avoid interactive commands requiring user input
|
|
104
|
+
1. **Detect OS first** -- use `ver` to check Windows vs Unix, then use correct commands
|
|
105
|
+
2. **Short-lived commands only** -- the shell waits for completion
|
|
106
|
+
3. **No system PATH** -- `npm`, `python`, `node` will not be found. Use process_manager
|
|
107
|
+
4. **No daemons/servers** -- commands that don't exit will hang until timeout
|
|
108
|
+
5. Use relative paths (workspace is the working directory)
|
|
109
|
+
6. Chain with `&&` for sequential execution
|
|
110
|
+
7. Avoid interactive commands requiring user input
|
|
@@ -35,6 +35,9 @@ Use the **snapshot -> act -> snapshot** loop:
|
|
|
35
35
|
| direction | string | scroll | up, down, left, right (default: down) |
|
|
36
36
|
| amount | int | scroll | Pixels to scroll (default: 500) |
|
|
37
37
|
| fullPage | bool | screenshot | Capture full scrollable page (default: false) |
|
|
38
|
+
| annotate | bool | screenshot | Add numbered labels to elements (default: false) |
|
|
39
|
+
| screenshotFormat | string | screenshot | Image format: png (default) or jpeg |
|
|
40
|
+
| screenshotQuality | int | screenshot | JPEG quality 1-100 (default: 80, only for jpeg) |
|
|
38
41
|
|
|
39
42
|
## Operations
|
|
40
43
|
|
|
@@ -80,6 +83,16 @@ Take a screenshot of the current page.
|
|
|
80
83
|
{"operation": "screenshot", "fullPage": true}
|
|
81
84
|
```
|
|
82
85
|
|
|
86
|
+
**Annotated screenshot** (numbered labels on interactive elements -- best for AI vision):
|
|
87
|
+
```json
|
|
88
|
+
{"operation": "screenshot", "annotate": true}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**JPEG format** (smaller file size):
|
|
92
|
+
```json
|
|
93
|
+
{"operation": "screenshot", "screenshotFormat": "jpeg", "screenshotQuality": 80}
|
|
94
|
+
```
|
|
95
|
+
|
|
83
96
|
### get_text
|
|
84
97
|
Extract text content from an element.
|
|
85
98
|
```json
|