1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/studio-DBF2iBkc.js","assets/react-vendor-CTdMSdEp.js","assets/index-B5HoNsi5.js","assets/index-Vwvl9AZL.css","assets/contract-pze_Egfr.js","assets/templateService-CAk8Pj3N.js","assets/authCache-C6hXs4ZD.js"])))=>i.map(i=>d[i]); 2import{_ as U}from"./react-vendor-CTdMSdEp.js";import{n as x}from"./agentTemplates-BsMoq5AN.js";import{s as m,G,j as f,q as z,u as N,a1 as W,a5 as Y}from"./index-B5HoNsi5.js";import{getTemplates as H,getTemplateById as J}from"./useTemplateStore-DrMF1N6c.js";import{t as Q}from"./templateService-CAk8Pj3N.js";const K="agent_studio_offline",V=1,y="agents",S="sync_queue",D="settings";class X{db=null;initPromise=null;async init(){if(!this.db)return this.initPromise?this.initPromise:(this.initPromise=new Promise((a,t)=>{try{const e=indexedDB.open(K,V);e.onupgradeneeded=n=>{const s=n.target.result;if(!s.objectStoreNames.contains(y)){const r=s.createObjectStore(y,{keyPath:"id"});r.createIndex("user_id","user_id",{unique:!1}),r.createIndex("updated_at","updated_at",{unique:!1})}s.objectStoreNames.contains(S)||s.createObjectStore(S,{keyPath:"id"}),s.objectStoreNames.contains(D)||s.createObjectStore(D,{keyPath:"key"})},e.onsuccess=n=>{this.db=n.target.result,a()},e.onerror=()=>{console.warn("[OfflineStorage] IndexedDB not available, falling back to localStorage"),t(e.error)}}catch(e){console.warn("[OfflineStorage] IndexedDB not supported:",e),t(e)}}),this.initPromise)}async ensureDB(){if(await this.init(),!this.db)throw new Error("IndexedDB not available");return this.db}async getAllAgents(){try{const a=await this.ensureDB();return new Promise((t,e)=>{const r=a.transaction(y,"readonly").objectStore(y).getAll();r.onsuccess=()=>t(r.result||[]),r.onerror=()=>e(r.error)})}catch{return this.getAgentsFromLocalStorage()}}async getAgent(a){try{const t=await this.ensureDB();return new Promise((e,n)=>{const o=t.transaction(y,"readonly").objectStore(y).get(a);o.onsuccess=()=>e(o.result||null),o.onerror=()=>n(o.error)})}catch{return this.getAgentsFromLocalStorage().find(e=>e.id===a)||null}}async saveAgent(a){try{const t=await this.ensureDB();return new Promise((e,n)=>{const s=t.transaction(y,"readwrite");s.objectStore(y).put(a),s.oncomplete=()=>e(),s.onerror=()=>n(s.error)})}catch{this.saveAgentToLocalStorage(a)}}async saveAgents(a){try{const t=await this.ensureDB();return new Promise((e,n)=>{const s=t.transaction(y,"readwrite"),r=s.objectStore(y);for(const o of a)r.put(o);s.oncomplete=()=>e(),s.onerror=()=>n(s.error)})}catch{for(const t of a)this.saveAgentToLocalStorage(t)}}async deleteAgent(a){try{const t=await this.ensureDB();return new Promise((e,n)=>{const s=t.transaction(y,"readwrite");s.objectStore(y).delete(a),s.oncomplete=()=>e(),s.onerror=()=>n(s.error)})}catch{this.deleteAgentFromLocalStorage(a)}}async addToSyncQueue(a){const t={...a,id:`sync_${Date.now()}_${Math.random().toString(36).slice(2,8)}`};try{const e=await this.ensureDB();return new Promise((n,s)=>{const r=e.transaction(S,"readwrite");r.objectStore(S).put(t),r.oncomplete=()=>n(),r.onerror=()=>s(r.error)})}catch{const e=this.getSyncQueueFromLocalStorage();e.push(t),localStorage.setItem("agent_studio_sync_queue",JSON.stringify(e))}}async getSyncQueue(){try{const a=await this.ensureDB();return new Promise((t,e)=>{const r=a.transaction(S,"readonly").objectStore(S).getAll();r.onsuccess=()=>t(r.result||[]),r.onerror=()=>e(r.error)})}catch{return this.getSyncQueueFromLocalStorage()}}async clearSyncQueue(){try{const a=await this.ensureDB();return new Promise((t,e)=>{const n=a.transaction(S,"readwrite");n.objectStore(S).clear(),n.oncomplete=()=>t(),n.onerror=()=>e(n.error)})}catch{localStorage.removeItem("agent_studio_sync_queue")}}async removeSyncItem(a){try{const t=await this.ensureDB();return new Promise((e,n)=>{const s=t.transaction(S,"readwrite");s.objectStore(S).delete(a),s.oncomplete=()=>e(),s.onerror=()=>n(s.error)})}catch{const t=this.getSyncQueueFromLocalStorage().filter(e=>e.id!==a);localStorage.setItem("agent_studio_sync_queue",JSON.stringify(t))}}async getSetting(a){try{const t=await this.ensureDB();
2return new Promise((e,n)=>{const o=t.transaction(D,"readonly").objectStore(D).get(a);o.onsuccess=()=>e(o.result?.value??null),o.onerror=()=>n(o.error)})}catch{const t=localStorage.getItem(`agent_studio_setting_${a}`);return t?JSON.parse(t):null}}async setSetting(a,t){try{const e=await this.ensureDB();return new Promise((n,s)=>{const r=e.transaction(D,"readwrite");r.objectStore(D).put({key:a,value:t}),r.oncomplete=()=>n(),r.onerror=()=>s(r.error)})}catch{localStorage.setItem(`agent_studio_setting_${a}`,JSON.stringify(t))}}getAgentsFromLocalStorage(){try{const a=localStorage.getItem("agent_studio_offline_agents");return a?JSON.parse(a):[]}catch{return[]}}saveAgentToLocalStorage(a){try{const t=this.getAgentsFromLocalStorage(),e=t.findIndex(n=>n.id===a.id);e>=0?t[e]=a:t.push(a),localStorage.setItem("agent_studio_offline_agents",JSON.stringify(t))}catch{}}deleteAgentFromLocalStorage(a){try{const t=this.getAgentsFromLocalStorage().filter(e=>e.id!==a);localStorage.setItem("agent_studio_offline_agents",JSON.stringify(t))}catch{}}getSyncQueueFromLocalStorage(){try{const a=localStorage.getItem("agent_studio_sync_queue");return a?JSON.parse(a):[]}catch{return[]}}}const h=new X,q="reenvisionos.recentRecommendedAgentIds",Z=10;function k(){try{if(typeof window>"u")return[];const i=window.localStorage.getItem(q);if(!i)return[];const a=JSON.parse(i);return Array.isArray(a)?a.filter(t=>typeof t=="string"):[]}catch{return[]}}function ee(){return k()}function he(i){if(!(!i||typeof window>"u"))try{const a=k(),t=[i,...a.filter(e=>e!==i)].slice(0,Z);window.localStorage.setItem(q,JSON.stringify(t))}catch{}}const O=6e4,$=20,te=new Set(["default-template-research-team-agent","6ba7b810-9dad-11d1-80b4-00c04fd430c8","os-guide-agent-default","1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"]),ne=new Set(["default-template-research-writer","default-template-document-author","default-template-spreadsheet-assistant","default-template-calculator-assistant","default-template-content-creator","default-template-code-assistant","default-template-web-to-document","default-template-hybrid-research-processor"]);class ae{directoryCache=null;manifestCache=new Map;async getAgentDirectory(a){if(this.directoryCache&&Date.now()-this.directoryCache.timestamp<O)return this.directoryCache.data;try{const{data:t,error:e}=await m.rpc("get_agent_directory",{user_uuid:a});if(e)return console.warn("[AgentRegistry] Failed to fetch directory from DB, falling back to local:",e.message),this.getLocalDirectory();const n=t||[],s=this.mergeWithDefaults(n);return this.directoryCache={data:s,timestamp:Date.now()},s}catch(t){return console.warn("[AgentRegistry] Directory fetch failed, using local fallback:",t),this.getLocalDirectory()}}getPromptDirectory(a){const t=[],e=[],n=[],s=[];for(const c of a)te.has(c.id)?t.push(c):ne.has(c.id)?e.push(c):c.id.startsWith("default-template-")?n.push(c):s.push(c);n.sort((c,l)=>{const u=c.manifest?.capabilities?.length||0;return(l.manifest?.capabilities?.length||0)-u});const r=ee(),o=c=>{const l=r.indexOf(c);return l===-1?0:20-l};s.sort((c,l)=>{const u=o(c.id)+(c.manifest?.capabilities?.length||0)+(c.manifest?.tool_count||0);return o(l.id)+(l.manifest?.capabilities?.length||0)+(l.manifest?.tool_count||0)-u});const d=[...t,...e];for(const c of n){if(d.length>=$)break;d.push(c)}for(const c of s.slice(0,3)){if(d.length>=$)break;d.push({...c,directory_entry:`${c.directory_entry} (user-created shortlist; confirm before running)`})}return d}async searchAgents(a,t,e=5){try{const{data:n,error:s}=await m.rpc("search_agents",{query:a,user_uuid:t||null,max_results:e});if(s)return console.warn("[AgentRegistry] Search failed, falling back to local:",s.message),this.localSearch(a);const r=n||[],o=this.localSearch(a),d=new Set(r.map(l=>l.id)),c=o.filter(l=>!d.has(l.id));return[...r,...c].slice(0,e)}catch(n){return console.warn("[AgentRegistry] Search failed:",n),this.localSearch(a)}}async getAgentManifest(a){const t=this.manifestCache.get(a);if(t&&Date.now()-t.timestamp<O)return t.data;if(this.directoryCache){const n=this.directoryCache.data.find(s=>s.id===a);if(n)return this.manifestCache.set(a,{data:n.manifest,timestamp:Date.now()}),n.manifest}const e=this.generateLocalManifest(a);return e?(this.manifestCache.set(a,{data:e,timestamp:Date.now()}),e):null}buildDirectoryPrompt(a){return a.length===0?"":a.map(e=>{const n=e.manifest?.capabilities||[],s=n.length>0?` [${n.join(", ")}]`:"",r=e.manifest?.input_schema;let o="";return r&&r.length>0&&(o=` {inputs: ${r.map(c=>{let l=c.key;return c.options&&c.options.length>0&&(l+=`(${c.options.map(u=>u.value||u.label).join("|")})`),c.required&&(l+="*"),l}).join(", ")}}`),`- ${e.name}: ${e.directory_entry.replace(e.name+": ","")}${s}${o}`}).join(` 3`)}async resolveAgentByName(a,t){const e=a.toLowerCase().trim();if(this.directoryCache){const o=this.directoryCache.data.find(c=>c.name.toLowerCase()===e);if(o)return o.id;const d=this.directoryCache.data.find(c=>c.name.toLowerCase().includes(e)||e.includes(c.name.toLowerCase()));if(d)return d.id}const s=[...w(),...C.getState().agents].find(o=>o.name.toLowerCase()===e||o.name.toLowerCase().includes(e)||e.includes(o.name.toLowerCase()));if(s)return s.id;const r=await this.searchAgents(a,t,1);return r.length>0?r[0].id:null}invalidateCache(){this.directoryCache=null,this.manifestCache.clear()}getLocalDirectory(){const a=[...w(),...C.getState().agents],t=new Set;return a.filter(e=>t.has(e.id)?!1:(t.add(e.id),!e.is_hidden)).map(e=>({id:e.id,name:e.name,directory_entry:`${e.name}: ${e.description||"No description"}`,manifest:this.analyzeFlowLocally(e),execution_mode:e.execution_mode||"online"}))}mergeWithDefaults(a){const t=new Set(a.map(n=>n.id));return[...w().filter(n=>!t.has(n.id)&&!n.is_hidden).map(n=>({id:n.id,name:n.name,directory_entry:`${n.name}: ${n.description||"No description"}`,manifest:this.analyzeFlowLocally(n),execution_mode:n.execution_mode||"online"})),...a]}localSearch(a){const t=a.toLowerCase(),e=[...w(),...C.getState().agents],n=new Set;return e.filter(s=>n.has(s.id)?!1:(n.add(s.id),`${s.name} ${s.description||""} ${(s.tags||[]).join(" ")} ${(s.categories||[]).join(" ")} ${s.system_prompt||""}`.toLowerCase().includes(t))).map(s=>({id:s.id,name:s.name,description:s.description||null,icon:s.icon||null,manifest:this.analyzeFlowLocally(s),directory_entry:`${s.name}: ${s.description||"No description"}`,execution_mode:s.execution_mode||"online",tags:s.tags||null,categories:s.categories||null,rank:.5})).slice(0,5)}generateLocalManifest(a){const e=[...w(),...C.getState().agents].find(n=>n.id===a);return e?this.analyzeFlowLocally(e):null}analyzeFlowLocally(a){const t={capabilities:[],node_types:[],has_web_search:!1,has_deep_research:!1,has_document_output:!1,has_spreadsheet_output:!1,has_email:!1,has_scheduler:!1,has_mcp:!1,has_a2a:!1,has_memory:!1,has_audio:!1,accepts_input:!0,produces_output:!0,tool_count:0,execution_complexity:"minimal"};if(!a.flow)return t;let e;try{e=typeof a.flow=="string"?JSON.parse(a.flow):a.flow}catch{return t}
3const n=Array.isArray(e?.nodes)?e.nodes:[];if(n.length===0)return t;const s=new Set,r=[],o={...t,tool_count:n.length,accepts_input:!0},d={webNode:"has_web_search",deepResearchNode:"has_deep_research",aiDocumentNode:"has_document_output",aiSpreadsheetNode:"has_spreadsheet_output",emailNode:"has_email",gmailNode:"has_email",outlookNode:"has_email",schedulerNode:"has_scheduler",mcpNode:"has_mcp",a2aNode:"has_a2a",calculatorNode:"has_a2a",memoryNode:"has_memory",localAudioNode:"has_audio"},c={has_web_search:"web-search",has_deep_research:"deep-research",has_document_output:"document-output",has_spreadsheet_output:"spreadsheet-output",has_email:"email",has_scheduler:"scheduled-execution",has_mcp:"mcp-tools",has_a2a:"app-integration",has_memory:"memory",has_audio:"audio"};for(const l of n){const u=l.type;u&&(s.add(u),d[u]&&(o[d[u]]=!0),u==="deepResearchNode"&&(o.has_web_search=!0),u==="llmNode"&&(o.produces_output=!0),u==="chatNode"&&(o.accepts_input=!0),u==="functionNode"&&(o._has_function=!0),u==="llmNode"&&(o._has_llm=!0),u==="conditionNode"&&(o._has_condition=!0),u==="loopNode"&&(o._has_loop=!0))}for(const[l,u]of Object.entries(c))o[l]&&r.push(u);return o._has_function&&r.push("custom-code"),o._has_llm&&r.push("llm-reasoning"),o._has_condition&&r.push("conditional-logic"),o._has_loop&&r.push("iteration"),o.capabilities=r,o.node_types=Array.from(s),o.execution_complexity=n.length>10?"complex":n.length>5?"moderate":n.length>0?"simple":"minimal",o.input_schema=this.extractInputSchema(n),o}extractInputSchema(a){const t=[],e=new Set;for(const n of a){if(n.type!=="chatNode")continue;const s=n.data?.config;if(!(!s?.questions||!Array.isArray(s.questions)))for(const r of s.questions){if(typeof r=="string")continue;const o=r.key||r.id||r.name;if(!o||e.has(o))continue;e.add(o);const d={key:o,prompt:r.prompt||r.label||r.question||o,type:r.type||"text",required:r.required??!1,default:r.default};r.options&&Array.isArray(r.options)&&(d.options=r.options.map(c=>({value:typeof c=="string"?c:c.value||"",label:typeof c=="string"?c:c.label||c.value||""}))),t.push(d)}}return t}}const T=new ae;function v(i){if(!i)return!1;const a=(i?.message||i?.toString()||"").toLowerCase();return a.includes("fetch")||a.includes("network")||a.includes("failed to fetch")||a.includes("load failed")||a.includes("networkerror")||a.includes("timeout")||a.includes("econnrefused")||a.includes("host_not_allowed")||!navigator.onLine}const se=i=>{if(!i)return;const a=J(i);return a?{nodes:a.nodes,edges:a.edges}:void 0},P=[{id:W,user_id:"",name:"Writer",description:"Creative and technical writing expert.",system_prompt:"You are a writing assistant. Help with creative, technical, and business writing tasks.",icon:"PenLine",categories:["Write & Create"],created_at:"",updated_at:"",templateId:"content-creator"},{id:Y,user_id:"",name:"OS Guide",description:"Expert on this Operating System. Ask me how to use features!",system_prompt:`You are the OS Guide for ReEnvision OS. 4Your goal is to help users navigate and use the features of this web-based operating system. 5 6KEY FEATURES TO KNOW: 71. **Taskbar**: Located at the bottom (by default). Contains the Start Menu (sphere), open apps, and system tray. 82. **Start Menu**: Click the spinning sphere to open. It features: 9 - **AI Chat**: The main interface is a chat where you can ask questions or run agents. 10 - **App Grid**: Access all installed apps. 11 - **File Search**: Quickly find documents. 123. **Agent Studio**: A powerful visual builder for creating custom AI agents. You can drag and drop nodes (LLM, Chat, Tools) to create workflows. 134. **AI Apps Store**: Install new applications like "AI Spreadsheet", "Documents", or "AI Calculator". 145. **AI Spreadsheet**: A spreadsheet tool that can use AI to generate formulas or analyze data. 156. **Documents**: A rich text editor with AI writing assistance and APA citation support. 167. **Window Management**: Windows can be minimized, maximized, and snapped. Right-click title bars for options. 178. **Workspaces**: Swipe horizontally on the desktop background to switch workspaces (if multiple are active). 189. **Settings**: Customize the theme (Neo-Glass), wallpaper, and configure AI models (OpenAI, Anthropic). 19 20If a user asks "How do I...", provide step-by-step instructions based on these features. 21Be concise, friendly, and helpful.`,icon:"Compass",categories:["General & Utilities"],created_at:"",updated_at:""},{id:"1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed",user_id:"",name:"Coding",description:"Programming and code generation specialist.",system_prompt:"You are a coding assistant. Write, explain, and debug code in any language.",icon:"Code2",categories:["Code & Technical"],created_at:"",updated_at:"",templateId:"code-assistant-template"}],B=()=>P.map(({templateId:i,...a})=>({...a,flow:se(i)})),re=P.map(({templateId:i,...a})=>({...a,flow:void 0})),R={"content-creator":"Write & Create","document-author":"Write & Create","research-writer":"Write & Create","offline-email-assistant":"Write & Create","research-team-agent":"Research & Analyze","web-researcher":"Research & Analyze","offline-research-team":"Research & Analyze","hybrid-research-processor":"Research & Analyze","web-to-document":"Research & Analyze","hourly-research-monitor":"Business & Productivity","spreadsheet-assistant":"Business & Productivity","code-assistant":"Code & Technical","calculator-assistant":"Code & Technical","graphics-sandbox":"Code & Technical","iot-control-center":"Code & Technical","multi-agent-app-builder":"Code & Technical","multi-agent-app-builder-offline":"Code & Technical","offline-workflow-starter":"AI Agents & Automation","offline-test-kit":"AI Agents & Automation","offline-web-search-test":"AI Agents & Automation","chat-orchestrator":"AI Agents & Automation","advanced-chatbot":"General & Utilities","learning-assistant":"General & Utilities","audio-generator":"General & Utilities","image-generator":"General & Utilities","getting-started-tour":"General & Utilities","autonomous-researcher":"Research & Analyze"},M=()=>H().map(a=>{let t=["AI Agents & Automation"];return a.category==="it-automation"?t=["IT Automation"]:R[a.id]?t=[R[a.id]]:a.category&&(t=[a.category]),{id:`default-template-${a.id}`,user_id:"",name:a.name,description:a.description,system_prompt:a.systemPrompt||"",icon:a.icon||"Bot",categories:t,flow:{nodes:a.nodes,edges:a.edges},model_id:a.modelId,is_hidden:!!a.internal,execution_mode:a.id.includes("offline")?"offline":"online",created_at:"",updated_at:""}}),w=()=>{const i=new Set;return[...B(),...M()].filter(a=>i.has(a.id)?!1:(i.add(a.id),!0))},F=i=>!!i&&w().some(a=>a.id===i),j=i=>F(i),oe=i=>!!i&&!j(i.id),ie=(i,a)=>i?F(i.id)||a&&i.user_id&&i.user_id===a?!0:i.review_status==="approved"&&i.publish_scope==="public":!1;function b(i){const a=w(),t=new Set(a.map(n=>n.id)),e=i.filter(n=>!t.has(n.id));return[...a,...e]}let I=null,E=0;const ce=3e4,C=G((i,a)=>({agents:[],categories:[],installedAgentIds:[],isLoading:!1,showHidden:!1,error:null,currentAgentFlow:null,activeAgent:null,isDraft:!1,fetchAgents:async()=>I||(Date.now()-E<ce&&a().agents.length>0?void 0:(I=(async()=>{i({isLoading:!0,error:null});try{try{await Q.fetchCloudTemplates()}catch(r){console.warn("Failed to fetch cloud templates:",r)}const{data:{user:e}}=await m.auth.getUser();let n=[],s=[];if(e){const[r,o,d,c]=await Promise.all([m.from("ai_agents").select("*").eq("user_id",e.id).order("created_at",{ascending:!1}).limit(200),m.from("ai_agents").select("*").eq("featured",!0).eq("review_status","approved").eq("publish_scope","public").limit(50),m.from("user_installed_agents").select("agent_id, ai_agents(*)").eq("user_id",e.id),m.from("agent_shares").select("agent_id, permission, ai_agents(*)").eq("user_id",e.id)]);if(r.error)throw r.error;const l=d.data||[];s=l.map(g=>
21g.agent_id).filter(Boolean);const u=l.map(g=>g.ai_agents).filter(Boolean),p=(c.data||[]).map(g=>g.ai_agents).filter(Boolean),A=new Map;for(const g of[...r.data||[],...o.data||[],...u,...p])g&&!A.has(g.id)&&A.set(g.id,g);n=[...A.values()],console.log(`Fetched ${n.length} library agents (${s.length} installed)`);let _=[];try{const{data:g,error:L}=await m.from("agent_categories").select("*").order("name");!L&&g&&(_=g)}catch(g){console.warn("Failed to fetch categories:",g)}try{await h.saveAgents(n)}catch{}try{const{data:g}=await m.from("user_settings").select("show_hidden_agents").eq("user_id",e.id).maybeSingle(),L=g?.show_hidden_agents||!1;await h.setSetting("show_hidden_agents",L).catch(()=>{}),i({agents:b(n),categories:_,isLoading:!1,showHidden:L,installedAgentIds:s})}catch(g){console.warn("Error loading hidden agents preference:",g),i({agents:b(n),categories:_,isLoading:!1,installedAgentIds:s})}}else i({agents:b([]),isLoading:!1,installedAgentIds:[]})}catch(e){if(v(e)){console.log("[OfflineMode] Network unavailable, loading agents from local cache");try{const n=await h.getAllAgents(),s=await h.getSetting("show_hidden_agents")||!1;i({agents:b(n),isLoading:!1,showHidden:s}),n.length>0?f.info(`No network: Loaded ${n.length} cached agent${n.length!==1?"s":""}`):f.info("No network: Working with default agents");return}catch{}}i({error:e.message,isLoading:!1,agents:b([])}),f.error(`Failed to fetch agents: ${e.message}`)}})().finally(()=>{I=null,E=Date.now()}),I)),fetchAgentCatalog:async()=>{const{data:t,error:e}=await m.from("ai_agents").select("*").eq("review_status","approved").in("publish_scope",["public","org"]).order("created_at",{ascending:!1}).limit(200);return e?(console.warn("[useAgentStore] fetchAgentCatalog failed:",e),[]):t||[]},installAgent:async t=>{const e=N.getState().user?.id;if(!e)throw new Error("You must be signed in to install agents.");if(a().installedAgentIds.includes(t))return;const{error:n}=await m.from("user_installed_agents").upsert({user_id:e,agent_id:t},{onConflict:"user_id,agent_id"});if(n)throw n;i(s=>({installedAgentIds:[...s.installedAgentIds,t]})),E=0,await a().fetchAgents()},uninstallAgent:async t=>{const e=N.getState().user?.id;if(!e)throw new Error("You must be signed in.");const{error:n}=await m.from("user_installed_agents").delete().eq("user_id",e).eq("agent_id",t);if(n)throw n;i(s=>({installedAgentIds:s.installedAgentIds.filter(r=>r!==t),agents:s.agents.filter(r=>{if(r.id!==t)return!0;const o=r.user_id===e,d=w().some(l=>l.id===r.id),c=r.featured===!0;return o||d||c})}))},createDraftAgent:(t={})=>{const e={id:"draft-"+x(),user_id:N.getState().user?.id||"",name:"Untitled Agent",description:"New agent draft",system_prompt:"You are a helpful AI assistant.",icon:"Bot",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),flow:{nodes:[],edges:[]},...t};i({activeAgent:e,currentAgentFlow:e.flow,isDraft:!0}),console.log("Draft agent created:",e)},addAgent:async t=>{i({isLoading:!0});try{const{data:{user:e}}=await m.auth.getUser();if(!e)throw new Error("User not authenticated");console.log(`Creating new agent for user ${e.id}:`,t.name);const{data:n,error:s}=await m.from("ai_agents").insert([{...t,user_id:e.id}]).select().single();if(s)throw s;return console.log("Agent created successfully:",n),h.saveAgent(n).catch(()=>{}),i(r=>({agents:b([...r.agents.filter(o=>!w().some(d=>d.id===o.id)),n]),isLoading:!1,activeAgent:n,isDraft:!1,currentAgentFlow:n.flow?typeof n.flow=="string"?JSON.parse(n.flow):n.flow:{nodes:[],edges:[]}})),f.success(`Agent "${n.name}" created!`),T.invalidateCache(),n}catch(e){if(v(e)){const n=N.getState().user?.id||"offline-user",s={id:x(),user_id:n,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...t,_offline:!0};return await h.saveAgent(s).catch(()=>{}),await h.addToSyncQueue({action:"create",agentId:s.id,data:s,timestamp:Date.now()}).catch(()=>{}),i(r=>({agents:b([...r.agents.filter(o=>!w().some(d=>d.id===o.id)),s]),isLoading:!1,activeAgent:s,isDraft:!1,currentAgentFlow:s.flow?typeof s.flow=="string"?JSON.parse(s.flow):s.flow:{nodes:[],edges:[]}})),f.success(`Agent "${s.name}
21" created locally (will sync when online)`),s}return i({error:e.message,isLoading:!1}),f.error(`Failed to create agent: ${e.message}`),null}},updateAgent:async(t,e)=>{if(a().isDraft&&a().activeAgent?.id===t)return i(n=>({activeAgent:{...n.activeAgent,...e}})),a().activeAgent;i({isLoading:!0});try{const{data:n,error:s}=await m.from("ai_agents").update(e).eq("id",t).select().single();if(s)throw s;return console.log("Agent updated successfully:",n),h.saveAgent(n).catch(()=>{}),i(r=>({agents:b(r.agents.map(o=>o.id===t?n:o)),activeAgent:r.activeAgent?.id===t?n:r.activeAgent,isLoading:!1})),f.success(`Agent "${n.name}" updated!`),T.invalidateCache(),n}catch(n){if(v(n)){const s=a().agents.find(r=>r.id===t);if(s){const r={...s,...e,updated_at:new Date().toISOString()};return h.saveAgent(r).catch(()=>{}),h.addToSyncQueue({action:"update",agentId:t,data:e,timestamp:Date.now()}).catch(()=>{}),i(o=>({agents:b(o.agents.map(d=>d.id===t?r:d)),activeAgent:o.activeAgent?.id===t?r:o.activeAgent,isLoading:!1})),f.success(`Agent "${r.name}" updated locally (will sync when online)`),r}}return i({error:n.message,isLoading:!1}),f.error(`Failed to update agent: ${n.message}`),null}},deleteAgent:async t=>{if(w().some(e=>e.id===t)){console.warn("Attempted to delete system default agent:",t),f.error("Default agents cannot be deleted");return}if(a().isDraft&&a().activeAgent?.id===t){i({activeAgent:null,currentAgentFlow:null,isDraft:!1});return}try{const e=a().agents.find(s=>s.id===t);if(!e)throw new Error("Agent not found");const{error:n}=await m.from("ai_agents").delete().eq("id",t);if(n)throw n;console.log(`Agent deleted successfully: ${t}`),h.deleteAgent(t).catch(()=>{}),i(s=>({agents:s.agents.filter(r=>r.id!==t),activeAgent:s.activeAgent?.id===t?null:s.activeAgent})),f.success(`Agent "${e.name}" deleted.`),T.invalidateCache()}catch(e){if(v(e)){const n=a().agents.find(s=>s.id===t);h.deleteAgent(t).catch(()=>{}),h.addToSyncQueue({action:"delete",agentId:t,timestamp:Date.now()}).catch(()=>{}),i(s=>({agents:s.agents.filter(r=>r.id!==t),activeAgent:s.activeAgent?.id===t?null:s.activeAgent})),f.success(`Agent "${n?.name}" deleted locally (will sync when online)`);return}i({error:e.message}),f.error(`Failed to delete agent: ${e.message}`)}},toggleAgentVisibility:async t=>{if(w().some(e=>e.id===t)){console.warn("Attempted to toggle visibility of system default agent:",t),f.error("Cannot hide default agents");return}try{const e=a().agents.find(r=>r.id===t);if(!e)throw new Error("Agent not found");const n=!e.is_hidden,{error:s}=await m.from("ai_agents").update({is_hidden:n}).eq("id",t);if(s)throw s;i(r=>({agents:r.agents.map(o=>o.id===t?{...o,is_hidden:n}:o),error:null})),f.success(n?`Agent "${e.name}" hidden`:`Agent "${e.name}" visible`)}catch(e){if(v(e)){const n=a().agents.find(s=>s.id===t);if(n){const s=!n.is_hidden;h.saveAgent({...n,is_hidden:s}).catch(()=>{}),h.addToSyncQueue({action:"update",agentId:t,data:{is_hidden:s},timestamp:Date.now()}).catch(()=>{}),i(r=>({agents:r.agents.map(o=>o.id===t?{...o,is_hidden:s}:o),error:null})),f.success(s?`Agent "${n.name}" hidden (offline)`:`Agent "${n.name}" visible (offline)`);return}}console.error("Error toggling agent visibility:",e),f.error(`Failed to update agent: ${e.message}`)}},toggleShowHidden:async()=>{const t=!a().showHidden;i({showHidden:t,error:null});try{const{data:{user:e}}=await m.auth.getUser();if(!e)return;await z(e.id,{show_hidden_agents:t})}catch(e){console.warn("Error saving hidden agents preference:",e)}},getVisibleAgents:()=>{const{agents:t,showHidden:e}=a(),n=w(),s=r=>e||!r.is_hidden;return[...n.filter(s),...t.filter(r=>!n.some(o=>o.id===r.id)&&s(r))]},setActiveAgent:t=>{if(!t){i({activeAgent:null,currentAgentFlow:null,isDraft:!1}),localStorage.removeItem("lastActiveAgentId");return}const e=a().agents,s=[...w(),...e].find(r=>r.id===t);if(s)if(console.log(`Setting active agent: ${s.name} (${t})`),i({activeAgent:s,isDraft:!1}),localStorage.setItem("lastActiveAgentId",t),s.flow)try{const r=typeof s.flow=="string"?JSON.parse(s.flow):s.flow;i({currentAgentFlow:r})}catch(r){console.error("Error parsing agent flow:",r),i({currentAgentFlow:null})}else i({currentAgentFlow:null});else console.warn(`Agent not found: ${t}`)},loadAgent:async t=>{if(i({isLoading:!0}),[...w(),...a().agents].find(r=>r.id===t)){a().setActiveAgent(t),i({isLoading:!1});return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){console.warn(`[AgentStore] Skipping DB fetch for non-UUID agent id: ${t}`),i({isLoading:!1});return}try{const{data:r,error:o}=await m.from("ai_agents").select("*").eq("id",t).single();if(o)throw o;
21h.saveAgent(r).catch(()=>{});const c=a().agents.some(l=>l.id===r.id);i(l=>({agents:c?l.agents:[...l.agents,r],isLoading:!1})),a().setActiveAgent(t)}catch(r){if(v(r))try{const o=await h.getAgent(t);if(o){const c=a().agents.some(l=>l.id===o.id);i(l=>({agents:c?l.agents:[...l.agents,o],isLoading:!1})),a().setActiveAgent(t);return}}catch{}i({error:r.message,isLoading:!1}),f.error(`Failed to load agent: ${r.message}`)}},saveCurrentAgentFlow:async(t,e)=>{const{activeAgent:n,isDraft:s,addAgent:r}=a();if(!n){f.error("No active agent selected");return}if(w().some(p=>p.id===n.id)){f.error("Cannot modify flow of a default template agent. Please duplicate or create a new agent.");return}const{serializeAgentFlow:o,saveRunningAgentFromStudio:d}=await U(async()=>{const{serializeAgentFlow:p,saveRunningAgentFromStudio:A}=await import("./studio-DBF2iBkc.js").then(_=>_.d);return{serializeAgentFlow:p,saveRunningAgentFromStudio:A}},__vite__mapDeps([0,1,2,3,4,5,6])),{nodesToSave:c,prevMeta:l,flow:u}=o(n.flow,t,e);if(l?.runningAgent){const p=await d(n.id,l.runningAgent.version,n.name,c,e);i(A=>({activeAgent:{...A.activeAgent,flow:p},agents:A.agents.map(_=>_.id===n.id?{..._,flow:p}:_),currentAgentFlow:{nodes:c,edges:e}})),f.success("Revision saved. Review and activate it in Running agents.");return}if(s){const p={name:n.name||"Untitled Agent",description:n.description||"",system_prompt:n.system_prompt||"",icon:n.icon||"Bot",flow:u,is_hidden:n.is_hidden||!1,is_public:!1};await r(p)&&i({currentAgentFlow:{nodes:c,edges:e},isDraft:!1});return}try{const{data:p,error:A}=await m.from("ai_agents").update({flow:u}).eq("id",n.id).select().single();if(A)throw A;h.saveAgent(p).catch(()=>{}),i(_=>({activeAgent:{..._.activeAgent,flow:u},agents:_.agents.map(g=>g.id===n.id?{...g,flow:u}:g),currentAgentFlow:{nodes:c,edges:e}})),f.success("Agent flow saved successfully"),T.invalidateCache()}catch(p){if(v(p)){const A={...n,flow:u,updated_at:new Date().toISOString()};h.saveAgent(A).catch(()=>{}),h.addToSyncQueue({action:"update",agentId:n.id,data:{flow:u},timestamp:Date.now()}).catch(()=>{}),i(_=>({activeAgent:{..._.activeAgent,flow:u},agents:_.agents.map(g=>g.id===n.id?{...g,flow:u}:g),currentAgentFlow:{nodes:c,edges:e}})),f.success("Flow saved locally (will sync when online)");return}console.error("Failed to save flow:",p),f.error(`Failed to save flow: ${p.message}`)}},setCurrentAgentFlow:t=>{i({currentAgentFlow:t})}})),me=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_AGENTS:re,getDefaultAgents:B,getSystemDefaultAgents:w,getTemplateDefaultAgents:M,isEditableAgent:oe,isSystemDefaultAgent:j,isTrustedAgentFlow:ie,isTrustedSystemAgentId:F,useAgentStore:C},Symbol.toStringTag,{value:"Module"}));export{F as a,T as b,j as c,oe as d,B as e,me as f,w as g,ie as i,h as o,he as r,C as u};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.