diff --git "a/.next/static/chunks/856-f7e6d25ec70892ad.js" "b/.next/static/chunks/856-f7e6d25ec70892ad.js" deleted file mode 100644--- "a/.next/static/chunks/856-f7e6d25ec70892ad.js" +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[856],{86:(e,t,n)=>{n.d(t,{OM:()=>s,sO:()=>r});let i={openrouter:{id:"openrouter",name:"OpenRouter",description:"Access multiple AI models through a unified API",apiKeyRequired:!0,apiKeyPlaceholder:"sk-or-...",apiKeyHelpUrl:"https://openrouter.ai/keys",baseUrl:"https://openrouter.ai/api/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},openai:{id:"openai",name:"OpenAI",description:"GPT-4, GPT-3.5 and other OpenAI models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-...",apiKeyHelpUrl:"https://platform.openai.com/api-keys",baseUrl:"https://api.openai.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},anthropic:{id:"anthropic",name:"Anthropic",description:"Claude 3.5 Sonnet, Haiku and Opus models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-ant-...",apiKeyHelpUrl:"https://console.anthropic.com/settings/keys",baseUrl:"https://api.anthropic.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},groq:{id:"groq",name:"Groq",description:"Ultra-fast inference with Llama and Mixtral models",apiKeyRequired:!0,apiKeyPlaceholder:"gsk_...",apiKeyHelpUrl:"https://console.groq.com/keys",baseUrl:"https://api.groq.com/openai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},gemini:{id:"gemini",name:"Google Gemini",description:"Google's multimodal AI models",apiKeyRequired:!0,apiKeyPlaceholder:"AI...",apiKeyHelpUrl:"https://aistudio.google.com/apikey",baseUrl:"https://generativelanguage.googleapis.com/v1beta",models:[{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash",description:"Latest experimental Gemini model",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",description:"Advanced reasoning and analysis",contextLength:2097152,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",description:"Fast and versatile",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0}],supportsFunctions:!0,supportsStreaming:!0},ollama:{id:"ollama",name:"Ollama",description:"Run models locally with Ollama",apiKeyRequired:!1,baseUrl:"http://localhost:11434/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},lmstudio:{id:"lmstudio",name:"LM Studio",description:"Local model server with tool use support",apiKeyRequired:!1,baseUrl:"http://localhost:1234/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},sambanova:{id:"sambanova",name:"SambaNova",description:"High-performance AI chips for inference",apiKeyRequired:!0,apiKeyPlaceholder:"SambaNova API Key",apiKeyHelpUrl:"https://cloud.sambanova.ai/apis",baseUrl:"https://api.sambanova.ai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0}};function r(e){return i[e]}function s(){return Object.values(i)}},823:(e,t,n)=>{n.d(t,{AM:()=>a,Wv:()=>o,hl:()=>l});var i=n(5155);n(2115);var r=n(547),s=n(3999);function a(e){let{...t}=e;return(0,i.jsx)(r.bL,{"data-slot":"popover",...t})}function o(e){let{...t}=e;return(0,i.jsx)(r.l9,{"data-slot":"popover-trigger",...t})}function l(e){let{className:t,align:n="center",sideOffset:a=4,...o}=e;return(0,i.jsx)(r.ZL,{children:(0,i.jsx)(r.UC,{"data-slot":"popover-content",align:n,sideOffset:a,className:(0,s.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",t),...o})})}},2714:(e,t,n)=>{n.d(t,{J:()=>c});var i=n(5155),r=n(2115),s=n(968),a=n(2085),o=n(3999);let l=(0,a.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=r.forwardRef((e,t)=>{let{className:n,...r}=e;return(0,i.jsx)(s.b,{ref:t,className:(0,o.cn)(l(),n),...r})});c.displayName=s.b.displayName},3091:(e,t,n)=>{n.d(t,{V:()=>a,b:()=>o});var i=n(8202);let r="openrouter";function s(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return t<.01?1e6*t:t}function a(e,t){if(!Array.isArray(t)||0===t.length)return;let n={};for(let i of t){if(!(null==i?void 0:i.pricing))continue;let t={input:i.pricing.input,output:i.pricing.output,reasoning:i.pricing.reasoning};Number.isFinite(t.input)&&Number.isFinite(t.output)&&(n[i.id]=t,n["".concat(e,"/").concat(i.id)]=t)}if(e===r)for(let[e,t]of Object.entries(n)){let i=e.split("/").pop();i&&!n[i]&&(n[i]=t)}Object.keys(n).length>0&&i.s.setProviderPricing(e,n)}function o(e){if(!Array.isArray(e)||0===e.length)return;let t={};for(let i of e){var n,a,o;let e=s(null==(n=i.pricing)?void 0:n.prompt),l=s(null==(a=i.pricing)?void 0:a.completion),c=s(null==(o=i.pricing)?void 0:o.internal_reasoning);if(void 0===e||void 0===l)continue;let d={input:e,output:l,reasoning:c};t[i.id]=d,t["".concat(r,"/").concat(i.id)]=d,i.canonical_slug&&(t[i.canonical_slug]=d)}Object.keys(t).length>0&&i.s.setProviderPricing(r,t)}},3462:(e,t,n)=>{n.d(t,{U:()=>o});var i=n(8202),r=n(3999);let s={"openrouter/deepseek/deepseek-chat":{input:.14,output:.28},"openrouter/deepseek/deepseek-reasoner":{input:.55,output:2.19,reasoning:5.5},"openrouter/anthropic/claude-3-5-sonnet":{input:3,output:15},"openrouter/anthropic/claude-3-5-haiku":{input:1,output:5},"openrouter/openai/gpt-4o":{input:2.5,output:10},"openrouter/openai/gpt-4o-mini":{input:.15,output:.6},"openrouter/meta-llama/llama-3.3-70b-instruct":{input:.88,output:.88},"openrouter/qwen/qwen-2.5-72b-instruct":{input:.35,output:.4},"openai/gpt-4o":{input:2.5,output:10},"openai/gpt-4o-mini":{input:.15,output:.6},"openai/gpt-4-turbo":{input:10,output:30},"openai/gpt-3.5-turbo":{input:.5,output:1.5},"openai/o1-preview":{input:15,output:60,reasoning:60},"openai/o1-mini":{input:3,output:12,reasoning:12},"anthropic/claude-3-5-sonnet-20241022":{input:3,output:15},"anthropic/claude-3-5-haiku-20241022":{input:1,output:5},"anthropic/claude-3-opus-20240229":{input:15,output:75},"anthropic/claude-3-sonnet-20240229":{input:3,output:15},"anthropic/claude-3-haiku-20240307":{input:.25,output:1.25},"gemini/gemini-1.5-pro":{input:1.25,output:5},"gemini/gemini-1.5-flash":{input:.075,output:.3},"gemini/gemini-1.5-flash-8b":{input:.0375,output:.15},"groq/llama-3.3-70b-versatile":{input:.59,output:.79},"groq/llama-3.3-70b-specdec":{input:.59,output:.99},"groq/llama-3.2-90b-text-preview":{input:.9,output:.9},"groq/mixtral-8x7b-32768":{input:.24,output:.24},"fireworks/llama-v3p3-70b-instruct":{input:.9,output:.9},"fireworks/llama-v3p1-405b-instruct":{input:3,output:3},"fireworks/qwen2p5-72b-instruct":{input:.9,output:.9},"together/meta-llama/Llama-3.3-70B-Instruct-Turbo":{input:.88,output:.88},"together/meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo":{input:3.5,output:3.5},"together/Qwen/Qwen2.5-72B-Instruct-Turbo":{input:1.2,output:1.2},"sambanova/Meta-Llama-3.3-70B-Instruct":{input:.6,output:.6},"sambanova/Meta-Llama-3.1-405B-Instruct":{input:3,output:3},"sambanova/Qwen2.5-72B-Instruct":{input:.6,output:.6},"hyperbolic/meta-llama/Llama-3.3-70B-Instruct":{input:.8,output:.8},"hyperbolic/Qwen/Qwen2.5-72B-Instruct":{input:.8,output:.8},"nebius/llama-3.3-70b":{input:.8,output:.8},"nebius/qwen2.5-72b":{input:.8,output:.8},"ollama/local":{input:0,output:0},"lmstudio/local":{input:0,output:0}},a={input:1,output:2};class o{static calculateCost(e,t,n){var i,a;let o,l=arguments.length>3&&void 0!==arguments[3]&&arguments[3],c="number"==typeof e.cost&&Number.isFinite(e.cost)?e.cost:void 0,d=!0===e.isEstimated||void 0===c||c<1e-6,p=this.getPricingKey(t,n),u=this.getDynamicPricing(t,n),h=s[p],m=u||h||this.findBestPricingMatch(t,n);u||h||r.v.warn("[CostCalculator] Falling back to default pricing for ".concat(p));let g=0,f=Math.max(null!=(i=e.promptTokens)?i:0,0);f&&(g+=f/1e6*m.input);let y=Math.max(null!=(a=e.completionTokens)?a:0,0);return e.reasoningTokens&&(y=Math.max(y-Math.max(e.reasoningTokens,0),0)),y&&(g+=y/1e6*m.output),e.reasoningTokens&&m.reasoning&&(g+=e.reasoningTokens/1e6*m.reasoning),d||void 0===c?(o=Math.max(g,null!=c?c:0),e.isEstimated=!l||d,void 0!==c&&c>o&&(o=c),void 0!==c&&Math.abs(o-c)>1e-4&&r.v.debug("[CostCalculator] Adjusted provisional cost",{provider:t,model:n,reportedCost:c,computedCost:g,finalCost:o})):(o=c,e.isEstimated=!1),e.isEstimated&&("openrouter"===t||t.toString().includes("openrouter"))&&r.v.warn("[CostCalculator] Using estimated cost based on normalized tokens for OpenRouter. This may be inaccurate. Consider using Generation API for native token counts."),o}static getPricingKey(e,t){return"openrouter"===e&&t.includes("/")?"openrouter/".concat(t):"".concat(e,"/").concat(t)}static findBestPricingMatch(e,t){let n="".concat(e,"/");for(let[e,i]of Object.entries(s))if(e.startsWith(n)){let r=e.substring(n.length);if(t.includes(r)||r.includes(t))return i}return"ollama"===e||"lmstudio"===e?{input:0,output:0}:a}static getDynamicPricing(e,t){if(!this.isKnownProvider(e))return null;try{return i.s.getModelPricing(e,t)}catch(n){return r.v.debug("[CostCalculator] Failed to read dynamic pricing",{provider:e,model:t,error:n}),null}}static isKnownProvider(e){return"openrouter"===e||"openai"===e||"anthropic"===e||"groq"===e||"gemini"===e||"ollama"===e||"lmstudio"===e||"sambanova"===e}static formatCost(e){return 0===e?"$0.00":e<1e-4?"<$0.0001":e<.01?"$".concat(e.toFixed(4)):e<1?"$".concat(e.toFixed(3)):"$".concat(e.toFixed(2))}static getPricing(e,t){return s[this.getPricingKey(e,t)]||this.findBestPricingMatch(e,t)}static estimateCost(e,t,n){let i=!(arguments.length>3)||void 0===arguments[3]||arguments[3],r=Math.ceil(1.3*e.split(/\s+/).length),s=this.getPricing(t,n);return r/1e6*(i?s.input:s.output)}static updateWithGenerationApiCost(e,t){let n={...e};if(void 0!==t.total_cost&&(n.cost=t.total_cost,n.isEstimated=!1,e.cost&&Math.abs(e.cost-t.total_cost)>1e-4)){var i;r.v.debug("[CostCalculator] Cost corrected: ".concat(null==(i=e.cost)?void 0:i.toFixed(4)," -> ").concat(t.total_cost.toFixed(4)," (").concat(((t.total_cost-e.cost)/e.cost*100).toFixed(1),"% difference)"))}return void 0!==t.native_tokens_total&&(n.nativeTokens={total:t.native_tokens_total,prompt:t.native_tokens_prompt,completion:t.native_tokens_completion}),n}}},3902:(e,t,n)=>{n.d(t,{B:()=>s});var i=n(6126),r=n.n(i);class s{registerHelpers(){this.handlebars.registerHelper("eq",(e,t)=>e===t),this.handlebars.registerHelper("ne",(e,t)=>e!==t),this.handlebars.registerHelper("lt",(e,t)=>ee>t),this.handlebars.registerHelper("lte",(e,t)=>e<=t),this.handlebars.registerHelper("gte",(e,t)=>e>=t),this.handlebars.registerHelper("and",function(){let e=Array.prototype.slice.call(arguments,0,-1);return e.every(e=>e)}),this.handlebars.registerHelper("or",function(){let e=Array.prototype.slice.call(arguments,0,-1);return e.some(e=>e)}),this.handlebars.registerHelper("not",e=>!e),this.handlebars.registerHelper("add",(e,t)=>e+t),this.handlebars.registerHelper("subtract",(e,t)=>e-t),this.handlebars.registerHelper("multiply",(e,t)=>e*t),this.handlebars.registerHelper("divide",(e,t)=>e/t),this.handlebars.registerHelper("uppercase",e=>null==e?void 0:e.toUpperCase()),this.handlebars.registerHelper("lowercase",e=>null==e?void 0:e.toLowerCase()),this.handlebars.registerHelper("concat",function(){let e=Array.prototype.slice.call(arguments,0,-1);return e.join("")}),this.handlebars.registerHelper("json",e=>JSON.stringify(e,null,2)),this.handlebars.registerHelper("formatDate",e=>new Date(e).toLocaleDateString()),this.handlebars.registerHelper("limit",(e,t)=>null==e?void 0:e.slice(0,t))}async registerPartials(){if(!this.partialsRegistered)try{for(let e of(await this.vfs.getAllFilesAndDirectories(this.projectId)).filter(e=>"content"in e&&e.path.startsWith("/templates/")&&(e.path.endsWith(".hbs")||e.path.endsWith(".handlebars")))){let t=e.content,n=e.path.replace(/^\/templates\//,"").replace(/\.hbs$/,"").replace(/\.handlebars$/,"");this.handlebars.registerPartial(n,t);let i=n.split("/").pop();if(i&&this.handlebars.registerPartial(i,t),n.includes("/")){let e=n.replace(/\//g,"-");this.handlebars.registerPartial(e,t)}}this.partialsRegistered=!0}catch(e){}}async compileTemplate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.templateCache.get(e);if(!n)try{let t=(await this.vfs.readFile(this.projectId,e)).content;n=this.handlebars.compile(t),this.templateCache.set(e,n)}catch(t){return console.error("Failed to compile template ".concat(e,":"),t),""}return n(t)}async compileProject(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];await this.registerPartials();let t=await this.vfs.listDirectory(this.projectId,"/"),n=new Map(this.blobUrls),i=new Map,r=[];for(let s of t){let t;if("template"===s.type||"html"===s.type||"css"===s.type)continue;t="image"===s.type||"video"===s.type?{path:s.path,content:s.content,mimeType:s.mimeType}:"js"===s.type?await this.processJS(s):{path:s.path,content:s.content,mimeType:s.mimeType};let a=this.hashContent(t.content),o=this.fileHashes.get(t.path);if(e&&o===a&&n.has(t.path)){let e=n.get(t.path);i.set(t.path,e),t.blobUrl=e,n.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),n=URL.createObjectURL(e);i.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,a)}r.push(t)}for(let s of t){if("html"!==s.type)continue;let t=await this.processHTML(s,i),a=this.hashContent(t.content),o=this.fileHashes.get(t.path);if(e&&o===a&&n.has(t.path)){let e=n.get(t.path);i.set(t.path,e),t.blobUrl=e,n.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),n=URL.createObjectURL(e);i.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,a)}r.push(t)}let s=[...r];for(let r of t)if("css"===r.type){let t=await this.processCSS(r,i),a=this.hashContent(t.content),o=this.fileHashes.get(t.path);if(e&&o===a&&n.has(t.path)){let e=n.get(t.path);i.set(t.path,e),t.blobUrl=e,n.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),n=URL.createObjectURL(e);i.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,a)}s.push(t)}let a=this.generateRoutes(t);if(e)for(let[,e]of n)URL.revokeObjectURL(e);else e||this.cleanupBlobUrls();return this.blobUrls=i,{entryPoint:"/index.html",files:s,routes:a,blobUrls:this.blobUrls}}hashContent(e){let t=0;if(e instanceof ArrayBuffer){let n=new Uint8Array(e);for(let e=0;e\n// VFS Asset Interceptor - Auto-injected by OSW Studio\n(function() {\n const vfsBlobUrls = ".concat(JSON.stringify(i),";\n \n // Helper function to resolve VFS paths to blob URLs\n function resolveVfsUrl(url) {\n if (!url || typeof url !== 'string') return url;\n if (url.startsWith('/assets/') && vfsBlobUrls[url]) {\n return vfsBlobUrls[url];\n }\n return url;\n }\n \n // Intercept Image src setter to handle ALL image loading\n const originalSrcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');\n Object.defineProperty(HTMLImageElement.prototype, 'src', {\n get: function() {\n return originalSrcDescriptor.get.call(this);\n },\n set: function(value) {\n const resolvedUrl = resolveVfsUrl(value);\n return originalSrcDescriptor.set.call(this, resolvedUrl);\n },\n enumerable: true,\n configurable: true\n });\n \n // Intercept setAttribute for src attributes\n const originalSetAttribute = Element.prototype.setAttribute;\n Element.prototype.setAttribute = function(name, value) {\n if ((name === 'src' || name === 'href') && this instanceof HTMLImageElement) {\n value = resolveVfsUrl(value);\n }\n return originalSetAttribute.call(this, name, value);\n };\n \n // Intercept innerHTML to catch template-generated images\n const originalInnerHTMLDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');\n Object.defineProperty(Element.prototype, 'innerHTML', {\n get: function() {\n return originalInnerHTMLDescriptor.get.call(this);\n },\n set: function(value) {\n if (typeof value === 'string' && value.includes('/assets/')) {\n // Replace asset URLs in the HTML string before setting\n const srcRegex = new RegExp('src=[\"\\']([^\"\\']*/assets/[^\"\\']*)[\"\\']', 'g');\n value = value.replace(srcRegex, function(match, url) {\n const resolvedUrl = resolveVfsUrl(url);\n if (resolvedUrl !== url) {\n return match.replace(url, resolvedUrl);\n }\n return match;\n });\n }\n return originalInnerHTMLDescriptor.set.call(this, value);\n },\n enumerable: true,\n configurable: true\n });\n \n // Intercept Image constructor\n const OriginalImage = window.Image;\n window.Image = function(...args) {\n const img = new OriginalImage(...args);\n // Override src setter for this instance too\n const descriptor = Object.getOwnPropertyDescriptor(img, 'src') || \n Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');\n if (descriptor) {\n Object.defineProperty(img, 'src', {\n get: descriptor.get,\n set: function(value) {\n const resolvedUrl = resolveVfsUrl(value);\n return originalSrcDescriptor.set.call(this, resolvedUrl);\n },\n enumerable: true,\n configurable: true\n });\n }\n return img;\n };\n // Preserve original Image properties\n Object.setPrototypeOf(window.Image, OriginalImage);\n window.Image.prototype = OriginalImage.prototype;\n \n // Intercept createElement for img elements\n const originalCreateElement = document.createElement;\n document.createElement = function(tagName, options) {\n const element = originalCreateElement.call(this, tagName, options);\n if (tagName.toLowerCase() === 'img') {\n const originalSrcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');\n Object.defineProperty(element, 'src', {\n get: function() {\n return originalSrcDescriptor.get.call(this);\n },\n set: function(value) {\n const resolvedUrl = resolveVfsUrl(value);\n return originalSrcDescriptor.set.call(this, resolvedUrl);\n },\n enumerable: true,\n configurable: true\n });\n }\n return element;\n };\n \n // Intercept fetch requests to VFS assets\n const originalFetch = window.fetch;\n window.fetch = function(input, init) {\n const url = typeof input === 'string' ? input : input.url;\n const resolvedUrl = resolveVfsUrl(url);\n \n if (resolvedUrl !== url) {\n return originalFetch(resolvedUrl, init);\n }\n \n return originalFetch(input, init);\n };\n \n // Intercept XMLHttpRequest for older code\n const OriginalXHR = window.XMLHttpRequest;\n window.XMLHttpRequest = function() {\n const xhr = new OriginalXHR();\n const originalOpen = xhr.open;\n \n xhr.open = function(method, url, ...args) {\n const resolvedUrl = resolveVfsUrl(url);\n return originalOpen.call(this, method, resolvedUrl, ...args);\n };\n \n return xhr;\n };\n \n // Process any existing images in the DOM when ready\n function processExistingImages() {\n const images = document.querySelectorAll('img[src*=\"/assets/\"]');\n images.forEach(img => {\n const currentSrc = img.src;\n const resolvedSrc = resolveVfsUrl(currentSrc);\n if (resolvedSrc !== currentSrc) {\n img.src = resolvedSrc;\n }\n });\n }\n \n // Use MutationObserver to catch dynamically added images\n function setupMutationObserver() {\n if (typeof MutationObserver !== 'undefined') {\n const observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(mutation) {\n mutation.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) { // Element node\n if (node.tagName === 'IMG' && node.src && node.src.includes('/assets/')) {\n const resolvedSrc = resolveVfsUrl(node.src);\n if (resolvedSrc !== node.src) {\n node.src = resolvedSrc;\n }\n }\n // Also check children\n const childImages = node.querySelectorAll && node.querySelectorAll('img[src*=\"/assets/\"]');\n if (childImages) {\n childImages.forEach(img => {\n const resolvedSrc = resolveVfsUrl(img.src);\n if (resolvedSrc !== img.src) {\n img.src = resolvedSrc;\n }\n });\n }\n }\n });\n });\n });\n \n observer.observe(document.body || document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n }\n \n // Setup everything when DOM is ready\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', function() {\n processExistingImages();\n setupMutationObserver();\n });\n } else {\n processExistingImages();\n setupMutationObserver();\n }\n})();\n<\/script>");return n=n.includes("")?n.replace("",r+"\n"):n.includes("")?n.replace("",r+"\n"):r+"\n"+n,{path:e.path,content:n,mimeType:e.mimeType}}extractPartialReferences(e){let t,n=/\{\{>\s*([\w-]+)\s*(?:\s+[^}]*)?\}\}/g,i=new Set;for(;null!==(t=n.exec(e));)i.add(t[1]);return Array.from(i)}registerErrorStubsForMissingPartials(e){for(let t of e)if(!this.handlebars.partials[t]){let e='
\n ⚠️ Missing partial: "'.concat(t,'"\n

Create file in /templates/ directory (e.g., /templates/').concat(t,".hbs or /templates/components/").concat(t,".hbs)

\n
");this.handlebars.registerPartial(t,e)}}async processHandlebarsTemplates(e){await this.registerPartials();try{let t=this.detectInvalidHandlebarsPatterns(e);if(t.length>0){let n=t.map(e=>"❌ ".concat(e.error,"\n\uD83D\uDCA1 ").concat(e.suggestion)).join("\n\n");return'\x3c!-- Handlebars Syntax Error --\x3e\n
\n

⚠️ Handlebars Template Error

\n
'.concat(n,"
\n
\n\x3c!-- Original content:\n").concat(e,"\n--\x3e")}let n=this.extractPartialReferences(e);this.registerErrorStubsForMissingPartials(n);let i={};try{let e=await this.vfs.readFile(this.projectId,"/data.json");i=JSON.parse(e.content)}catch(e){}return this.handlebars.compile(e)(i)}catch(n){console.error("VirtualServer: Error processing Handlebars templates:",n);let t=n instanceof Error?n.message:String(n);return'\x3c!-- Handlebars Compilation Error --\x3e\n
\n

⚠️ Handlebars Template Error

\n

Error: '.concat(t,"

\n

Common fixes:

\n
    \n
  • Check for typos in helper names and partial references
  • \n
  • Ensure all opening tags have matching closing tags
  • \n
  • Verify partial names exist in /templates/ directory
  • \n
  • Use {{> partialName}} syntax, not (> partialName)
  • \n
\n
\n\x3c!-- Original content:\n").concat(e,"\n--\x3e")}}detectInvalidHandlebarsPatterns(e){let t=[];return/\w+\s*=\s*\(\s*>\s*[\w-]+\s*\)/g.test(e)&&t.push({error:"Invalid syntax: Using (> partial) as parameter value",suggestion:"Use string-based dynamic partials: content=\"partial-name\" then {{> (lookup this 'content')}}"}),/\{\{\s*>\s*\(\s*>\s*[\w-]+\s*\)\s*\}\}/g.test(e)&&t.push({error:"Invalid syntax: Double partial reference {{> (> partial)}}",suggestion:"Use {{> partialName}} for static partials or {{> (lookup data 'partialName')}} for dynamic"}),/\{\{\s*>\s*[\w-]+\s+\w+\s*=\s*[^"'\s}][^}]*\s[^}]*(?:\s|}})/g.test(e)&&t.push({error:"Missing quotes in parameter values",suggestion:'Wrap parameter values in quotes: title="My Title" not title=My Title'}),t}async processCSS(e,t){let n=e.content;return n=await this.processUrlReferences(n,t),{path:e.path,content:n,mimeType:e.mimeType}}async processJS(e){let t=e.content;return{path:e.path,content:t,mimeType:e.mimeType}}isAssetReference(e){let t=e.split("?")[0].split("#")[0];return[".css",".js",".jsx",".ts",".tsx",".png",".jpg",".jpeg",".gif",".svg",".ico",".webp",".woff",".woff2",".ttf",".otf",".eot",".mp4",".webm",".ogg",".mp3",".wav",".pdf",".zip",".json",".xml"].includes(t.substring(t.lastIndexOf(".")).toLowerCase())}async processInternalReferences(e,t){let n=await this.vfs.listDirectory(this.projectId,"/"),i=t||this.blobUrls,r=e;for(let e of[/href="([^"]+)"/g,/src="([^"]+)"/g,/href='([^']+)'/g,/src='([^']+)'/g])r=r.replace(e,(e,t)=>{if(t.startsWith("http")||t.startsWith("data:")||t.startsWith("//")||t.startsWith("blob:")||t.startsWith("#")||e.includes("href=")&&!this.isAssetReference(t))return e;let r=this.normalizePath(t);if(n.some(e=>e.path===r)){let n=i.get(r);if(n)return e.replace(t,n)}return e});return r}async processUrlReferences(e,t){return e.replace(/url\(['"]?([^'")]+)['"]?\)/g,(e,n)=>{if(n.startsWith("http")||n.startsWith("data:")||n.startsWith("//")||n.startsWith("blob:"))return e;let i=this.normalizePath(n),r=t.get(i);return r?"url('".concat(r,"')"):e})}normalizePath(e){return(e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")||(e="/"+e),e.includes(".")||e.endsWith("/"))?e:e+".html"}generateRoutes(e){return e.filter(e=>"html"===e.type).map(e=>{let t=e.content.match(/([^<]+)<\/title>/i),n=t?t[1]:e.name.replace(".html",""),i=e.path.replace(".html","")||"/";return{path:"/index"===i?"/":i,file:e.path,title:n}})}extractTitle(e){let t=e.match(/<title>([^<]+)<\/title>/i);return t?t[1]:"Untitled Page"}cleanupBlobUrls(){for(let e of this.blobUrls.values())URL.revokeObjectURL(e);this.blobUrls.clear(),this.templateCache.clear(),this.partialsRegistered=!1}async getCompiledFile(e){try{let t=await this.vfs.readFile(this.projectId,e);if("html"===t.type)return await this.processHTML(t,this.blobUrls);if("css"===t.type)return await this.processCSS(t,new Map);if("js"===t.type)return await this.processJS(t);else return{path:t.path,content:t.content,mimeType:t.mimeType}}catch(e){return null}}constructor(e,t,n){this.blobUrls=new Map,this.fileHashes=new Map,this.templateCache=new Map,this.partialsRegistered=!1,this.vfs=e,this.projectId=t,this.baseUrl=window.location.origin,n&&(this.blobUrls=new Map(n)),this.handlebars=r().create(),this.registerHelpers()}}},3999:(e,t,n)=>{n.d(t,{cn:()=>a,v:()=>d});var i=n(2596),r=n(9688),s=n(9509);function a(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,r.QP)((0,i.$)(t))}let o={debug:10,info:20,warn:30,error:40,silent:50},l=void 0!==s&&s.env.NEXT_PUBLIC_LOG_LEVEL||"warn";function c(e){return o[l]<=o[e]}let d={debug:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];c("debug")&&console.debug(...t)},info:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];c("info")&&console.info(...t)},warn:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];c("warn")&&console.warn(...t)},error:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];c("error")&&console.error(...t)}}},4469:(e,t,n)=>{n.d(t,{n:()=>i});class i{async init(){return new Promise((e,t)=>{let n=indexedDB.open("osw-studio-db",3);n.onerror=()=>t(n.error),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=e=>{let t=e.target.result;if(!t.objectStoreNames.contains("projects")){let e=t.createObjectStore("projects",{keyPath:"id"});e.createIndex("name","name",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!t.objectStoreNames.contains("files")){let e=t.createObjectStore("files",{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("path",["projectId","path"],{unique:!0}),e.createIndex("type","type",{unique:!1})}if(!t.objectStoreNames.contains("fileTree")){let e=t.createObjectStore("fileTree",{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("path",["projectId","path"],{unique:!0}),e.createIndex("parentPath",["projectId","parentPath"],{unique:!1})}if(!t.objectStoreNames.contains("conversations")){let e=t.createObjectStore("conversations",{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("lastUpdated","lastUpdated",{unique:!1})}if(!t.objectStoreNames.contains("checkpoints")){let e=t.createObjectStore("checkpoints",{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}if(!t.objectStoreNames.contains("customTemplates")){let e=t.createObjectStore("customTemplates",{keyPath:"id"});e.createIndex("name","name",{unique:!1}),e.createIndex("importedAt","importedAt",{unique:!1})}if(!t.objectStoreNames.contains("debugEvents")){let e=t.createObjectStore("debugEvents",{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}}})}getDB(){if(!this.db)throw Error("Database not initialized. Call init() first.");return this.db}getDatabase(){return this.getDB()}async createProject(e){let t=this.getDB().transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(t.add(e))}async getProject(e){let t=this.getDB().transaction(["projects"],"readonly").objectStore("projects"),n=await this.promisify(t.get(e));return n?this.hydrateProject(n):null}async updateProject(e){let t=this.getDB().transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(t.put(e))}async deleteProject(e){let t=this.getDB();await this.deleteProjectFiles(e);let n=t.transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(n.delete(e))}async listProjects(){let e=this.getDB().transaction(["projects"],"readonly").objectStore("projects"),t=await this.promisify(e.getAll());return(null==t?void 0:t.map(e=>this.hydrateProject(e)))||[]}async createFile(e){let t=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(t.add(e))}async getFile(e,t){let n=this.getDB().transaction(["files"],"readonly").objectStore("files").index("path");return await this.promisify(n.get([e,t]))||null}async updateFile(e){let t=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(t.put(e))}async deleteFile(e,t){let n=await this.getFile(e,t);if(n){let e=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(e.delete(n.id))}}async listFiles(e){let t=this.getDB().transaction(["files"],"readonly").objectStore("files").index("projectId");return await this.promisify(t.getAll(e))||[]}async deleteProjectFiles(e){let t=await this.listFiles(e),n=this.getDB().transaction(["files"],"readwrite").objectStore("files");for(let e of t)await this.promisify(n.delete(e.id))}async createTreeNode(e){let t=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(t.add(e))}async getTreeNode(e,t){let n=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("path");return await this.promisify(n.get([e,t]))||null}async updateTreeNode(e){let t=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(t.put(e))}async deleteTreeNode(e,t){let n=await this.getTreeNode(e,t);if(n){let e=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(e.delete(n.id))}}async getChildNodes(e,t){let n=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("parentPath");return await this.promisify(n.getAll(null===t?[e]:[e,t]))||[]}async getAllTreeNodes(e){let t=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("projectId");return await this.promisify(t.getAll(e))||[]}promisify(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}hydrateProject(e){return{...e,createdAt:e.createdAt?new Date(e.createdAt):new Date,updatedAt:e.updatedAt?new Date(e.updatedAt):new Date,lastSavedAt:e.lastSavedAt?new Date(e.lastSavedAt):null}}async saveCustomTemplate(e){let t=this.getDB().transaction(["customTemplates"],"readwrite").objectStore("customTemplates");await this.promisify(t.put(e))}async getCustomTemplate(e){let t=this.getDB().transaction(["customTemplates"],"readonly").objectStore("customTemplates"),n=await this.promisify(t.get(e));return n?this.hydrateCustomTemplate(n):null}async getAllCustomTemplates(){let e=this.getDB().transaction(["customTemplates"],"readonly").objectStore("customTemplates");return(await this.promisify(e.getAll())).map(e=>this.hydrateCustomTemplate(e))}async deleteCustomTemplate(e){let t=this.getDB().transaction(["customTemplates"],"readwrite").objectStore("customTemplates");await this.promisify(t.delete(e))}hydrateCustomTemplate(e){return{...e,importedAt:e.importedAt?new Date(e.importedAt):new Date}}constructor(){this.db=null}}},4973:(e,t,n)=>{n.d(t,{QF:()=>r,WK:()=>s});var i=n(3999);async function r(){try{let e=await fetch("https://openrouter.ai/api/v1/models");if(!e.ok)throw Error("Failed to fetch models: ".concat(e.statusText));return(await e.json()).data.filter(e=>e.architecture.output_modalities.includes("text")&&e.supported_parameters.includes("tools")).sort((e,t)=>{let n=["gpt-4","claude","deepseek","qwen"],i=n.some(t=>e.id.toLowerCase().includes(t)),r=n.some(e=>t.id.toLowerCase().includes(e));return i&&!r?-1:!i&&r?1:t.created-e.created})}catch(e){return i.v.error("Error fetching models:",e),[{id:"deepseek/deepseek-chat",canonical_slug:"deepseek-chat",name:"DeepSeek Chat",created:Date.now(),description:"DeepSeek Chat - Fast and capable model for general tasks",context_length:64e3,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"deepseek"},pricing:{prompt:"0.00014",completion:"0.00028",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:64e3,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"qwen/qwen-2.5-coder-32b-instruct",canonical_slug:"qwen-2.5-coder-32b-instruct",name:"Qwen 2.5 Coder 32B",created:Date.now(),description:"Qwen 2.5 Coder - Specialized for code generation",context_length:32768,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"qwen"},pricing:{prompt:"0.00018",completion:"0.00018",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:32768,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"openai/gpt-4o",canonical_slug:"gpt-4o",name:"GPT-4o",created:Date.now(),description:"OpenAI GPT-4o - Multimodal model with vision capabilities",context_length:128e3,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"openai"},pricing:{prompt:"0.0025",completion:"0.01",request:"0",image:"0.00765",web_search:"0",internal_reasoning:"0",input_cache_read:"0.00125",input_cache_write:"0.0025"},top_provider:{context_length:128e3,max_completion_tokens:16384,is_moderated:!0},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens","response_format"]},{id:"anthropic/claude-3.5-sonnet",canonical_slug:"claude-3.5-sonnet",name:"Claude 3.5 Sonnet",created:Date.now(),description:"Anthropic Claude 3.5 Sonnet - Advanced reasoning and coding",context_length:2e5,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"claude",instruct_type:"anthropic"},pricing:{prompt:"0.003",completion:"0.015",request:"0",image:"0.0048",web_search:"0",internal_reasoning:"0",input_cache_read:"0.0003",input_cache_write:"0.00375"},top_provider:{context_length:2e5,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]}]}}function s(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(null==e)return"";let n=t?e/1e3:e;if(0===n)return"free";if(n<1e-4)return"$".concat(n.toFixed(5).replace(/\.?0+$/,""));if(n<.001)return"$".concat(n.toFixed(4).replace(/\.?0+$/,""));if(n<.01)return"$".concat(n.toFixed(3).replace(/\.?0+$/,""));if(n<.1)return"$".concat(n.toFixed(3).replace(/\.?0+$/,""));if(n<1)return"$".concat(n.toFixed(2).replace(/\.?0+$/,""));else return"$".concat(n.toFixed(2))}},5221:(e,t,n)=>{n.d(t,{g:()=>r});var i=n(5155);function r(e){let{width:t=64,height:n=64,className:r}=e;return(0,i.jsx)("div",{style:{width:t,height:n},className:r,dangerouslySetInnerHTML:{__html:'<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 256 256" preserveAspectRatio="xMidYMid meet">\n<rect x="0" y="0" width="256" height="256" rx="20" ry="20" fill="#000000"/>\n<g transform="translate(0,256) scale(0.0476,-0.0476)" fill="#ffffff" stroke="none">\n<path d="M725 4825 c-50 -18 -100 -71 -114 -122 -15 -54 -15 -1573 0 -1628 16\n-55 44 -92 89 -115 38 -19 62 -20 855 -20 781 0 817 1 853 19 46 23 67 46 87\n94 13 32 15 138 15 830 0 566 -3 804 -11 828 -16 45 -55 87 -104 110 -38 18\n-82 19 -835 18 -659 0 -802 -2 -835 -14z m1351 -371 c15 -11 37 -33 48 -48 21\n-27 21 -38 21 -520 0 -547 3 -523 -68 -566 -31 -19 -54 -20 -521 -20 -483 0\n-489 0 -524 22 -20 12 -42 38 -53 62 -17 38 -19 74 -19 504 0 496 1 503 51\n548 46 41 66 43 561 41 464 -2 477 -3 504 -23z"/>\n<path d="M3058 4830 c-44 -13 -87 -49 -108 -90 -19 -37 -20 -61 -20 -471 0\n-428 0 -432 22 -471 13 -22 41 -51 64 -64 41 -24 41 -24 685 -24 645 0 645 0\n689 -22 63 -33 80 -71 80 -183 0 -101 -15 -144 -63 -179 -28 -21 -41 -21 -695\n-26 -666 -5 -667 -5 -702 -27 -109 -68 -106 -247 5 -310 40 -23 40 -23 858\n-23 664 0 824 3 850 14 43 17 95 78 102 118 3 18 5 225 3 459 -3 426 -3 426\n-31 462 -58 76 -15 71 -757 77 -620 5 -667 6 -692 23 -44 30 -58 74 -58 179 0\n116 16 153 80 186 44 22 44 22 693 22 710 0 678 -3 731 60 80 96 41 240 -79\n287 -35 14 -1612 17 -1657 3z"/>\n<path d="M702 2509 c-48 -24 -75 -57 -91 -114 -9 -29 -11 -253 -9 -840 3 -779\n4 -801 23 -834 11 -19 37 -48 58 -65 39 -31 39 -31 380 -31 342 0 342 0 399\n28 31 15 63 39 73 53 16 25 16 25 62 -16 77 -67 104 -71 470 -68 320 3 320 3\n360 30 24 16 49 44 62 70 21 44 21 49 21 854 0 773 -1 811 -19 851 -35 76\n-135 120 -215 93 -41 -13 -90 -51 -109 -84 -9 -16 -13 -187 -17 -688 -5 -654\n-5 -667 -26 -694 -43 -58 -68 -69 -169 -72 -82 -3 -99 -1 -133 18 -22 12 -49\n39 -61 60 -21 37 -21 45 -21 664 0 439 -3 641 -11 673 -32 123 -190 174 -285\n91 -73 -64 -69 -20 -70 -743 0 -721 3 -687 -66 -737 -28 -20 -47 -23 -133 -26\n-91 -3 -103 -2 -134 20 -19 13 -44 36 -55 51 -21 28 -21 38 -26 695 -4 481 -8\n673 -17 687 -50 87 -152 118 -241 74z"/>\n<path d="M3047 2515 c-47 -16 -81 -46 -101 -90 -14 -28 -16 -95 -16 -463 0\n-281 4 -440 11 -459 15 -40 48 -73 94 -94 38 -17 79 -19 685 -19 626 0 646 -1\n678 -20 58 -35 72 -72 72 -185 0 -110 -14 -147 -67 -182 -25 -17 -73 -18 -698\n-23 -672 -5 -672 -5 -708 -33 -20 -15 -44 -42 -53 -60 -21 -39 -21 -125 -1\n-163 20 -38 65 -80 100 -93 19 -8 289 -11 833 -11 701 0 809 2 841 15 48 20\n71 41 94 88 19 35 19 60 17 480 -3 444 -3 444 -30 479 -54 71 -23 68 -740 68\n-612 0 -645 1 -685 20 -67 30 -83 66 -83 183 0 116 14 156 68 189 35 21 35 21\n691 22 606 1 658 2 688 19 137 74 130 264 -12 328 -38 18 -85 19 -840 18 -652\n0 -807 -2 -838 -14z"/>\n</g>\n</svg>'}})}},5337:(e,t,n)=>{n.d(t,{Gr:()=>s,N$:()=>a,N2:()=>l,Q6:()=>r,fu:()=>o});let i={html:["html","htm"],css:["css"],js:["js","mjs","jsx"],json:["json"],text:["txt","md","xml","svg"],template:["hbs","handlebars"],image:["png","jpg","jpeg","gif","webp","ico","bmp"],video:["mp4","webm","ogg"]},r={text:5242880,html:5242880,css:5242880,js:5242880,json:5242880,template:5242880,image:0xa00000,video:0x3200000,binary:0xa00000};function s(e){var t;let n=null==(t=e.split(".").pop())?void 0:t.toLowerCase();for(let[e,t]of Object.entries(i))if(t.includes(n||""))return e;return"text"}function a(e){var t;return({html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",jsx:"application/javascript",json:"application/json",txt:"text/plain",md:"text/markdown",xml:"application/xml",svg:"image/svg+xml",hbs:"text/x-handlebars-template",handlebars:"text/x-handlebars-template",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg"})[(null==(t=e.split(".").pop())?void 0:t.toLowerCase())||""]||"application/octet-stream"}function o(e){var t;let n=null==(t=e.split(".").pop())?void 0:t.toLowerCase();for(let e of Object.values(i))if(e.includes(n||""))return!0;return!1}let l=[{value:"personal",label:"Personal Use Only",description:"Cannot be resold or used commercially"},{value:"commercial",label:"Commercial Use",description:"Can be used in commercial projects, cannot resell template"},{value:"mit",label:"MIT License",description:"Use freely, must include copyright notice"},{value:"apache-2.0",label:"Apache 2.0",description:"Similar to MIT, with patent protection"},{value:"gpl-3.0",label:"GPL 3.0",description:"Open source, derivatives must also be GPL"},{value:"bsd-3-clause",label:"BSD 3-Clause",description:"Permissive, cannot use author name for promotion"},{value:"cc-by-4.0",label:"CC BY 4.0",description:"Free use with attribution"},{value:"cc-by-sa-4.0",label:"CC BY-SA 4.0",description:"Free use with attribution, share-alike"},{value:"cc-by-nc-4.0",label:"CC BY-NC 4.0",description:"Free for non-commercial use with attribution"},{value:"unlicense",label:"Unlicense (Public Domain)",description:"No restrictions, completely free to use"},{value:"all-rights-reserved",label:"All Rights Reserved",description:"Most restrictive, requires explicit permission"},{value:"custom",label:"Custom License",description:"Specify your own terms"}]},5784:(e,t,n)=>{n.d(t,{TR:()=>m,bq:()=>u,eb:()=>g,gC:()=>h,l6:()=>c,s3:()=>d,yv:()=>p});var i=n(5155);n(2115);var r=n(4582),s=n(6474),a=n(5196),o=n(7863),l=n(3999);function c(e){let{...t}=e;return(0,i.jsx)(r.bL,{"data-slot":"select",...t})}function d(e){let{...t}=e;return(0,i.jsx)(r.YJ,{"data-slot":"select-group",...t})}function p(e){let{...t}=e;return(0,i.jsx)(r.WT,{"data-slot":"select-value",...t})}function u(e){let{className:t,size:n="default",children:a,...o}=e;return(0,i.jsxs)(r.l9,{"data-slot":"select-trigger","data-size":n,className:(0,l.cn)("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...o,children:[a,(0,i.jsx)(r.In,{asChild:!0,children:(0,i.jsx)(s.A,{className:"size-4 opacity-50"})})]})}function h(e){let{className:t,children:n,position:s="popper",...a}=e;return(0,i.jsx)(r.ZL,{children:(0,i.jsxs)(r.UC,{"data-slot":"select-content",className:(0,l.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,...a,children:[(0,i.jsx)(f,{}),(0,i.jsx)(r.LM,{className:(0,l.cn)("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:n}),(0,i.jsx)(y,{})]})})}function m(e){let{className:t,...n}=e;return(0,i.jsx)(r.JU,{"data-slot":"select-label",className:(0,l.cn)("text-muted-foreground px-2 py-1.5 text-xs",t),...n})}function g(e){let{className:t,children:n,...s}=e;return(0,i.jsxs)(r.q7,{"data-slot":"select-item",className:(0,l.cn)("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[(0,i.jsx)("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,i.jsx)(r.VF,{children:(0,i.jsx)(a.A,{className:"size-4"})})}),(0,i.jsx)(r.p4,{children:n})]})}function f(e){let{className:t,...n}=e;return(0,i.jsx)(r.PP,{"data-slot":"select-scroll-up-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...n,children:(0,i.jsx)(o.A,{className:"size-4"})})}function y(e){let{className:t,...n}=e;return(0,i.jsx)(r.wn,{"data-slot":"select-scroll-down-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...n,children:(0,i.jsx)(s.A,{className:"size-4"})})}},7015:(e,t,n)=>{n.d(t,{$:()=>o});var i=n(7150),r=n(9396),s=n(3999);class a{subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){let t={projectId:e,dirty:this.isDirty(e)};for(let e of this.listeners)try{e(t)}catch(e){s.v.error("[SaveManager] Listener error",e)}}setDirty(e,t){let n=this.dirtyProjects.has(e);t&&!n?(this.dirtyProjects.add(e),this.emit(e)):!t&&n&&(this.dirtyProjects.delete(e),this.emit(e))}markDirty(e){this.isSuppressed(e)||this.setDirty(e,!0)}markClean(e){this.setDirty(e,!1)}isDirty(e){return this.dirtyProjects.has(e)}beginSuppression(e){var t;let n=null!=(t=this.suppressionCounts.get(e))?t:0;this.suppressionCounts.set(e,n+1)}endSuppression(e){var t;let n=null!=(t=this.suppressionCounts.get(e))?t:0;if(n<=1)return void this.suppressionCounts.delete(e);this.suppressionCounts.set(e,n-1)}async runWithSuppressedDirty(e,t){this.beginSuppression(e);try{return await t()}finally{this.endSuppression(e)}}isSuppressed(e){var t;return(null!=(t=this.suppressionCounts.get(e))?t:0)>0}async save(e,t){var n,s;await r.vfs.init();let a=await r.vfs.getProject(e),o="Manual save @ ".concat(new Date().toLocaleTimeString()),l=await i.Y.createCheckpoint(e,t||o,{kind:"manual",baseRevisionId:null!=(n=a.lastSavedCheckpointId)?n:null,replaceId:null!=(s=a.lastSavedCheckpointId)?s:null});return a.lastSavedCheckpointId=l.id,a.lastSavedAt=new Date(l.timestamp),await r.vfs.updateProject(a),this.manualCheckpoints.set(e,l.id),this.markClean(e),l}async restoreLastSaved(e){await r.vfs.init();let t=(await r.vfs.getProject(e)).lastSavedCheckpointId;if(!t)return s.v.warn("[SaveManager] No saved checkpoint to restore",{projectId:e}),!1;let n=await this.runWithSuppressedDirty(e,async()=>{if(!await i.Y.checkpointExists(t))return s.v.warn("[SaveManager] Saved checkpoint missing",{projectId:e,checkpointId:t}),!1;let n=await i.Y.restoreCheckpoint(t);return n||s.v.error("[SaveManager] Failed to restore saved checkpoint",{projectId:e,checkpointId:t}),n});return n&&this.markClean(e),n}getSavedCheckpointId(e){var t;return null!=(t=this.manualCheckpoints.get(e))?t:null}async syncProjectSaveState(e){await r.vfs.init();let t=await r.vfs.getProject(e);t.lastSavedCheckpointId?this.manualCheckpoints.set(e,t.lastSavedCheckpointId):this.manualCheckpoints.delete(e)}constructor(){this.dirtyProjects=new Set,this.listeners=new Set,this.suppressionCounts=new Map,this.manualCheckpoints=new Map}}let o=new a},7150:(e,t,n)=>{n.d(t,{Y:()=>a});var i=n(9396),r=n(3999);class s{arrayBufferToBase64(e){let t=new Uint8Array(e),n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}base64ToArrayBuffer(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async initDB(){this.isInitialized||(await i.vfs.init(),this.isInitialized=!0,await this.loadCheckpointsFromDB())}getDB(){return i.vfs.db.getDatabase()}async loadCheckpointsFromDB(){return new Promise((e,t)=>{let n=this.getDB().transaction([this.storeName],"readonly").objectStore(this.storeName).getAll();n.onsuccess=()=>{let t=n.result;for(let e of(this.checkpoints.clear(),t)){var i;let t={...e,kind:e.kind||"auto",baseRevisionId:null!=(i=e.baseRevisionId)?i:null,files:new Map(e.files),directories:new Set(e.directories)};this.checkpoints.set(t.id,t)}e()},n.onerror=()=>{r.v.error("Failed to load checkpoints from DB"),t(n.error)}})}async saveCheckpointToDB(e){var t;await this.initDB();let n={...e,files:Array.from(e.files.entries()),directories:Array.from(e.directories),kind:e.kind,baseRevisionId:null!=(t=e.baseRevisionId)?t:null};return new Promise((e,t)=>{let i=this.getDB().transaction([this.storeName],"readwrite").objectStore(this.storeName).put(n);i.onsuccess=()=>e(),i.onerror=()=>{r.v.error("Failed to save checkpoint to DB"),t(i.error)}})}async deleteCheckpointFromDB(e){return await this.initDB(),new Promise((t,n)=>{let i=this.getDB().transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(e);i.onsuccess=()=>t(),i.onerror=()=>{r.v.error("Failed to delete checkpoint from DB"),n(i.error)}})}async createCheckpoint(e,t){var n;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};await this.initDB(),await i.vfs.init();let a=await i.vfs.listDirectory(e,"/"),o=new Map,l=new Set;for(let t of a){let n=t.path.split("/").filter(Boolean);for(let e=1;e<=n.length-1;e++){let t="/"+n.slice(0,e).join("/");l.add(t)}if("string"==typeof t.content)o.set(t.path,t.content);else if(t.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(t.content);o.set(t.path,{data:e,encoding:"base64"})}else try{let n=await i.vfs.readFile(e,t.path);if("string"==typeof n.content)o.set(t.path,n.content);else if(n.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(n.content);o.set(t.path,{data:e,encoding:"base64"})}}catch(e){r.v.error("Failed to read file for checkpoint: ".concat(t.path),e)}}let c={id:"cp_".concat(Date.now()),timestamp:new Date().toISOString(),description:t,files:o,directories:l,projectId:e,kind:s.kind||"auto",baseRevisionId:null!=(n=s.baseRevisionId)?n:null};if(s.replaceId&&(this.checkpoints.delete(s.replaceId),await this.deleteCheckpointFromDB(s.replaceId)),"manual"===c.kind){let t=Array.from(this.checkpoints.values()).find(t=>t.projectId===e&&"manual"===t.kind);t&&t.id!==s.replaceId&&(this.checkpoints.delete(t.id),await this.deleteCheckpointFromDB(t.id))}this.checkpoints.set(c.id,c),this.currentCheckpoint=c.id,await this.saveCheckpointToDB(c);let d=Array.from(this.checkpoints.values()).filter(t=>t.projectId===e&&"auto"===t.kind).sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime());if(d.length>10)for(let e of d.slice(0,d.length-10))this.checkpoints.delete(e.id),await this.deleteCheckpointFromDB(e.id);return c}async restoreCheckpoint(e){if("string"!=typeof e)return r.v.error("[Checkpoint] Invalid checkpoint ID type:",typeof e,e),!1;if(!e.startsWith("cp_")||e.length<6)return r.v.error("[Checkpoint] Invalid checkpoint ID format:",e),!1;await this.initDB();let t=this.checkpoints.get(e);if(!t&&(await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e))))return r.v.error("[Checkpoint] Checkpoint not found in database: ".concat(e)),Array.from(this.checkpoints.keys()),!1;await i.vfs.init();try{let n=await i.vfs.listDirectory(t.projectId,"/"),r=new Set;for(let e of n){let t=e.path.split("/").filter(Boolean);for(let e=1;e<=t.length-1;e++){let n="/"+t.slice(0,e).join("/");r.add(n)}}for(let e of n)t.files.has(e.path)||await i.vfs.deleteFile(t.projectId,e.path);for(let e of Array.from(r).filter(e=>!t.directories||!t.directories.has(e)).sort((e,t)=>t.length-e.length))try{await i.vfs.deleteDirectory(t.projectId,e)}catch(e){}if(t.directories){for(let e of Array.from(t.directories).sort((e,t)=>e.length-t.length))if(!r.has(e))try{await i.vfs.createDirectory(t.projectId,e)}catch(e){}}for(let[e,r]of t.files){let s;s="object"==typeof r&&"base64"===r.encoding?this.base64ToArrayBuffer(r.data):r,n.some(t=>t.path===e)?await i.vfs.updateFile(t.projectId,e,s):await i.vfs.createFile(t.projectId,e,s)}return this.currentCheckpoint=e,!0}catch(e){return r.v.error("Failed to restore checkpoint:",e),!1}}async getCheckpoints(e){return await this.initDB(),await this.loadCheckpointsFromDB(),Array.from(this.checkpoints.values()).filter(t=>t.projectId===e).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))}getCurrentCheckpoint(){return this.currentCheckpoint&&this.checkpoints.get(this.currentCheckpoint)||null}async checkpointExists(e){return!!e&&"string"==typeof e&&(await this.initDB(),!!this.checkpoints.has(e)||(await this.loadCheckpointsFromDB(),this.checkpoints.has(e)))}async clearCheckpoints(e){await this.initDB();let t=[];for(let[n,i]of this.checkpoints)i.projectId===e&&(this.checkpoints.delete(n),t.push(n));for(let e of t)await this.deleteCheckpointFromDB(e);this.currentCheckpoint=null}constructor(){this.checkpoints=new Map,this.currentCheckpoint=null,this.storeName="checkpoints",this.isInitialized=!1}}let a=new s},7168:(e,t,n)=>{n.d(t,{$:()=>l});var i=n(5155);n(2115);var r=n(9708),s=n(2085),a=n(3999);let o=(0,s.F)("inline-flex items-center cursor-pointer justify-center gap-2 whitespace-nowrap rounded-full text-sm font-sans font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-red-500 text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 [&_svg]:!text-white",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",lightGray:"bg-neutral-200/60 hover:bg-neutral-200",link:"text-primary underline-offset-4 hover:underline",ghostDarker:"text-white shadow-xs focus-visible:ring-black/40 bg-black/40 hover:bg-black/70",black:"bg-neutral-950 text-neutral-300 hover:brightness-110",sky:"bg-sky-500 text-white hover:brightness-110"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-full text-[13px] gap-1.5 px-3",lg:"h-10 rounded-full px-6 has-[>svg]:px-4",icon:"size-9",iconXs:"size-7",iconXss:"size-6",xs:"h-6 text-xs rounded-full pl-2 pr-2 gap-1"}},defaultVariants:{variant:"default",size:"default"}});function l(e){let{className:t,variant:n,size:s,asChild:l=!1,...c}=e,d=l?r.DX:"button";return(0,i.jsx)(d,{"data-slot":"button",className:(0,a.cn)(o({variant:n,size:s,className:t})),...c})}},7793:(e,t,n)=>{n.d(t,{t:()=>I});class i{hasTool(e){return this.tools.includes(e)}constructor(e){var t;this.type=e.type,this.name=e.name,this.description=e.description,this.systemPrompt=e.systemPrompt,this.tools=e.tools,this.maxIterations=e.maxIterations,this.isReadOnly=null!=(t=e.isReadOnly)&&t}}class r{registerBuiltInAgents(){this.register(new i({type:"orchestrator",name:"Orchestrator",description:"Direct execution agent for web development tasks",systemPrompt:this.getOrchestratorPrompt(),tools:["shell","json_patch","evaluation"],maxIterations:100}))}register(e){this.agents.set(e.type,e)}get(e){return this.agents.get(e)}getAll(){return Array.from(this.agents.values())}has(e){return this.agents.has(e)}getOrchestratorPrompt(){return"You are a web development AI assistant that helps users build static websites.\n\nYour responsibilities:\n1. Understand user requests and implement them directly\n2. Write clean, production-quality HTML, CSS, and JavaScript\n3. Use shell commands to explore and read files\n4. Use json_patch to edit files precisely\n5. Evaluate your work before finishing\n\nAvailable tools:\n- shell: Execute commands (ls, cat, grep, mkdir, etc.)\n- json_patch: Edit files using structured operations\n- evaluation: Required before finishing - assess whether the task is complete\n\nGuidelines:\n- Read files before editing to understand current structure\n- Use targeted reads (head -n 50, tail -n 50, rg -C 5) instead of cat\n- Make precise edits with json_patch (ensure oldStr is unique)\n- Follow existing code patterns and conventions\n- Write semantic HTML and accessible markup\n- Keep CSS organized and maintainable\n\nEvaluation requirement:\n- Before finishing, you MUST call the evaluation tool\n- Assess whether the user's request has been fully completed\n- If work remains (should_continue: true), you will continue working\n- If complete (should_continue: false), the task will finish\n\nYou are working in a JAMstack environment (static HTML/CSS/JS only, no backend)."}constructor(){this.agents=new Map,this.registerBuiltInAgents()}}let s=new r;var a=n(9396);function o(e){return e.length>1e5?e.slice(0,1e5)+"\n… [truncated]":e}function l(e){if(!e)return e;if(e.startsWith("/workspace")){let t=e.slice(10);e=t.length?t:"/"}return e.startsWith("/")||(e="/"+e),e}async function c(e,t,n){if("/"===n||!n)return;let i=n.split("/").filter(Boolean),r="";for(let n=0;n<i.length;n++){r="/"+i.slice(0,n+1).join("/");try{await e.createDirectory(t,r)}catch(e){}}}async function d(e,t,n){if(arguments.length>3&&void 0!==arguments[3]&&arguments[3],!t||"string"!=typeof t)return{stdout:"",stderr:"Invalid project ID provided",exitCode:2};if(!n||0===n.length)return{stdout:"",stderr:"No command provided",exitCode:2};let i=n.filter(e=>null!=e&&""!==e);if(0===i.length)return{stdout:"",stderr:"No valid command arguments provided",exitCode:2};let[r,...s]=i;try{switch(r){case"ls":{let n=new Set,i=[];for(let e of s)e&&e.startsWith("-")?n.add(e):e&&i.push(e);let r=n.has("-R")||n.has("-r"),a=l(i[0])||"/";if(r){let n=await e.getAllFilesAndDirectories(t),i="/"===a?"/":a.endsWith("/")?a:a+"/",r=n.filter(e=>e.path===a||e.path.startsWith(i)).map(e=>e.path).sort().join("\n");return{stdout:o(r),stderr:"",exitCode:0}}{let n=(await e.listDirectory(t,a)).map(e=>e.path).sort().join("\n");return{stdout:o(n),stderr:"",exitCode:0}}}case"tree":{let n=1/0,i="/";for(let e=0;e<s.length;e++){let t=s[e];"-L"===t&&s[e+1]?n=parseInt(s[++e])||1/0:t.startsWith("-")||(i=t)}let r=l(i)||"/",a=await e.getAllFilesAndDirectories(t),c="/"===r?"/":r.endsWith("/")?r:r+"/",d=a.filter(e=>e.path===r||e.path.startsWith(c)).map(e=>({path:e.path,isDir:"type"in e&&"directory"===e.type})),p=[r];for(let e of d.filter(e=>e.path!==r).map(e=>e.path).sort()){let t=e.slice(c.length).split("/").filter(Boolean).length;if(t>n)continue;let i=" ".repeat(t-1),r=e.split("/").pop()||e;p.push("".concat(i,"├── ").concat(r))}return{stdout:o(p.join("\n")),stderr:"",exitCode:0}}case"cat":{let n=s.filter(e=>e&&!e.startsWith("-")).map(e=>l(e));if(0===n.length)return{stdout:"",stderr:"cat: missing file path",exitCode:2};if(n.length>5)return{stdout:"",stderr:"cat: too many files. You requested ".concat(n.length," files, but cat supports a maximum of ").concat(5," files at a time. Please split into multiple cat calls."),exitCode:2};let i=[],r=!1,a=[];for(let s of n){if(!s){a.push("cat: invalid path"),r=!0;continue}if(s.startsWith("/-")){a.push('cat: invalid path "'.concat(s,'" (looks like an option)')),r=!0;continue}try{let o=await e.readFile(t,s);"string"!=typeof o.content?(a.push("cat: ".concat(s,": binary or non-text file")),r=!0):n.length>1?i.push("=== ".concat(s," ===\n").concat(o.content)):i.push(o.content)}catch(t){let e=t instanceof Error?t.message:String(t);a.push("cat: ".concat(s,": ").concat(e)),r=!0}}let c=i.join("\n\n"),d=a.join("\n");return{stdout:o(c),stderr:d,exitCode:+!!r}}case"head":{let n=10,i="";for(let e=0;e<s.length;e++){let t=s[e];"-n"===t&&s[e+1]?n=parseInt(s[++e])||10:t.startsWith("-")||(i=t)}let r=l(i);if(!r)return{stdout:"",stderr:"head: missing file path",exitCode:2};try{let i=await e.readFile(t,r);if("string"!=typeof i.content)return{stdout:"",stderr:"head: ".concat(r,": binary file"),exitCode:1};let s=i.content.split(/\r?\n/).slice(0,n).join("\n");return{stdout:o(s),stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"head: ".concat(r,": ").concat((null==e?void 0:e.message)||"file not found"),exitCode:1}}}case"tail":{let n=10,i="";for(let e=0;e<s.length;e++){let t=s[e];"-n"===t&&s[e+1]?n=parseInt(s[++e])||10:t.startsWith("-")||(i=t)}let r=l(i);if(!r)return{stdout:"",stderr:"tail: missing file path",exitCode:2};try{let i=await e.readFile(t,r);if("string"!=typeof i.content)return{stdout:"",stderr:"tail: ".concat(r,": binary file"),exitCode:1};let s=i.content.split(/\r?\n/).slice(-n).join("\n");return{stdout:o(s),stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"tail: ".concat(r,": ").concat((null==e?void 0:e.message)||"file not found"),exitCode:1}}}case"grep":{let n,i={n:!1,i:!1,r:!1,F:!1},r=[];for(let e of s)if(e.startsWith("-"))for(let t of e.slice(1))t in i&&(i[t]=!0);else r.push(e);let a=r[0],c=l(r[1])||"/";if(!a)return{stdout:"",stderr:'grep: missing pattern\n\nUsage: grep [FLAGS] PATTERN [PATH]\n\nSupported flags:\n -n Show line numbers\n -i Case insensitive search\n -F Treat pattern as literal string (not regex)\n\nExamples:\n {"cmd": ["grep", "searchterm", "/path"]}\n {"cmd": ["grep", "-n", "pattern", "/file.txt"]}\n {"cmd": ["grep", "-i", "TODO", "/"]}\n {"cmd": ["grep", "-F", "exact.string", "/src"]}\n\nNote: grep always searches recursively. For context around matches, use rg (ripgrep) instead.',exitCode:2};if(i.F){let e=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=new RegExp(e,i.i?"i":"")}else n=new RegExp(a,i.i?"i":"");let d=await e.getAllFilesAndDirectories(t),p="/"===c?"/":c.endsWith("/")?c:c+"/",u=[];for(let e of d){if("type"in e&&"directory"===e.type||!e.path.startsWith(p)&&e.path!==c||"string"!=typeof e.content)continue;let t=e.content.split(/\r?\n/);for(let r=0;r<t.length;r++){let s=t[r];n.test(s)&&u.push("".concat(e.path).concat(i.n?":"+(r+1):"",":").concat(s))}}let h=u.join("\n");if(0===u.length){let e="/"===c?"workspace root":c;return{stdout:"",stderr:'grep: pattern "'.concat(a,'" not found in ').concat(e),exitCode:1}}return{stdout:o(h),stderr:"",exitCode:0}}case"rg":{let n={n:!0,i:!1,C:0,A:0,B:0},i=[];for(let e=0;e<s.length;e++){let t=s[e];t.startsWith("-")?"-n"===t?n.n=!0:"-i"===t?n.i=!0:"-C"===t?n.C=parseInt(s[++e])||2:"-A"===t?n.A=parseInt(s[++e])||2:"-B"===t&&(n.B=parseInt(s[++e])||2):i.push(t)}let r=i[0],a=l(i[1])||"/";if(!r)return{stdout:"",stderr:'rg: missing pattern\n\nUsage: rg [FLAGS] PATTERN [PATH]\n\nSupported flags:\n -C NUM Show NUM lines of context (before and after)\n -A NUM Show NUM lines after each match\n -B NUM Show NUM lines before each match\n -i Case insensitive search\n -n Show line numbers (enabled by default)\n\nExamples:\n {"cmd": ["rg", "searchterm", "/"]}\n {"cmd": ["rg", "-C", "3", "pattern", "/"]}\n {"cmd": ["rg", "-A", "5", "-B", "2", "function", "/src"]}\n {"cmd": ["rg", "-i", "todo", "/"]}\n\nTip: Use -C for balanced context. PATH defaults to / if omitted.',exitCode:2};let c=new RegExp(r,n.i?"i":""),d=await e.getAllFilesAndDirectories(t),p="/"===a?"/":a.endsWith("/")?a:a+"/",u=[];for(let e of d){if("type"in e&&"directory"===e.type||!e.path.startsWith(p)&&e.path!==a||"string"!=typeof e.content)continue;let t=e.content.split(/\r?\n/),i=new Set;for(let e=0;e<t.length;e++)c.test(t[e])&&i.add(e);if(0===i.size)continue;let r=new Set,s=n.C||n.B,o=n.C||n.A;for(let e of i)for(let n=Math.max(0,e-s);n<=Math.min(t.length-1,e+o);n++)r.add(n);let l=Array.from(r).sort((e,t)=>e-t);for(let r of(u.length>0&&u.push(""),l)){let s=n.n?"".concat(r+1,":"):"";i.has(r),u.push("".concat(e.path,":").concat(s).concat(t[r]))}}if(0===u.length){let e="/"===a?"workspace root":a;return{stdout:"",stderr:'rg: pattern "'.concat(r,'" not found in ').concat(e),exitCode:1}}return{stdout:o(u.join("\n")),stderr:"",exitCode:0}}case"find":{let n,i,r,a;for(let e=0;e<s.length;e++){let t=s[e];if(t){if("-name"===t){i=s[e+1],e++;continue}if("-type"===t){let t=s[e+1];("f"===t||"d"===t)&&(r=t),e++;continue}if("-maxdepth"===t){e++;continue}t.startsWith("-")||n||(n=t)}}let c=l(n)||"/",d=await e.getAllFilesAndDirectories(t),p="/"===c?"/":c.endsWith("/")?c:c+"/",u=i?(a=i,RegExp("^"+a.replace(/[.+^${}()|\[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$")):null,h=d.filter(e=>e.path===c||e.path.startsWith(p)).filter(e=>"f"===r?!("type"in e)||"directory"!==e.type:"d"!==r||"type"in e&&"directory"===e.type).map(e=>e.path).filter(e=>!u||u.test(e.split("/").pop()||e)).sort();return{stdout:o(h.join("\n")),stderr:"",exitCode:0}}case"mkdir":{let n=s.includes("-p"),i=s.filter(e=>e&&"-p"!==e).map(e=>l(e));if(0===i.length)return{stdout:"",stderr:"mkdir: missing operand",exitCode:2};let r=!1,a=[];for(let s of i)if(s)try{n?await c(e,t,s):await e.createDirectory(t,s)}catch(e){r=!0,a.push("mkdir: cannot create directory '".concat(s,"': ").concat((null==e?void 0:e.message)||"unknown error"))}return{stdout:"",stderr:a.join("\n"),exitCode:+!!r}}case"touch":{let n=s.filter(e=>e&&!e.startsWith("-")).map(e=>l(e));if(0===n.length)return{stdout:"",stderr:"touch: missing file operand",exitCode:2};let i=!1,r=[];for(let s of n)if(s)try{await e.readFile(t,s)}catch(n){try{await e.createFile(t,s,"")}catch(e){i=!0,r.push("touch: cannot touch '".concat(s,"': ").concat((null==e?void 0:e.message)||"cannot create file"))}}return{stdout:"",stderr:r.join("\n"),exitCode:+!!i}}case"rm":{let n=!1,i=!1,r=!1,a=[];for(let e of s)e&&e.startsWith("-")?((e.includes("r")||e.includes("R"))&&(n=!0),e.includes("f")&&(i=!0),e.includes("v")&&(r=!0)):e&&a.push(e);if(0===a.length)return{stdout:"",stderr:"rm: missing operand",exitCode:2};let c=!1,d=[];for(let s of a){let a=l(s);if(!a){i||(c=!0);continue}try{await e.deleteFile(t,a),r&&d.push("removed '".concat(a,"'"))}catch(s){if(n)try{await e.deleteDirectory(t,a),r&&d.push("removed directory '".concat(a,"'"))}catch(e){!i&&(c=!0,r&&d.push("rm: cannot remove '".concat(a,"': No such file or directory")))}else!i&&(c=!0,r&&d.push("rm: cannot remove '".concat(a,"': Is a directory (use -r to remove directories)")))}}let p=r?d.join("\n"):"",u=c&&!r?"rm: some paths could not be removed":"";return{stdout:o(p),stderr:u,exitCode:+!!c}}case"mv":{let[n,i]=s,r=l(n),a=l(i);if(!r||!a)return{stdout:"",stderr:"mv: missing operands",exitCode:2};try{return await e.renameFile(t,r,a),{stdout:"",stderr:"",exitCode:0}}catch(n){return await e.renameDirectory(t,r,a),{stdout:"",stderr:"",exitCode:0}}}case"cp":{let n=s.includes("-r"),[i,r]=s.filter(e=>"-r"!==e);if(i=l(i),r=l(r),!i||!r)return{stdout:"",stderr:"cp: missing operands",exitCode:2};try{let n=await e.readFile(t,i),s=(n.content,n.content);try{await e.createFile(t,r,s)}catch(n){await e.updateFile(t,r,s)}return{stdout:"",stderr:"",exitCode:0}}catch(o){if(!n)return{stdout:"",stderr:"cp: -r required for directories",exitCode:1};let s=await e.getAllFilesAndDirectories(t),a=i.endsWith("/")?i:i+"/";for(let n of s)if((!("type"in n)||"directory"!==n.type)&&(n.path===i||n.path.startsWith(a))){let s=n.path.slice(i.length),a=(r.endsWith("/")?r.slice(0,-1):r)+s;await c(e,t,a.split("/").slice(0,-1).join("/"));let o=(n.content,n.content);try{await e.createFile(t,a,o)}catch(n){await e.updateFile(t,a,o)}}return{stdout:"",stderr:"",exitCode:0}}}case"echo":{let n=s.indexOf(">");if(-1===n)return{stdout:o(s.join(" ")),stderr:"",exitCode:0};let i=s.slice(0,n).join(" "),r=s[n+1],a=l(r);if(!a)return{stdout:"",stderr:"echo: missing file path after >",exitCode:2};try{let n=a.split("/").slice(0,-1).join("/")||"/";"/"!==n&&await c(e,t,n);try{await e.createFile(t,a,i)}catch(n){await e.updateFile(t,a,i)}return{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"echo: ".concat(a,": ").concat((null==e?void 0:e.message)||"cannot write file"),exitCode:1}}}default:return{stdout:"",stderr:"".concat(r,": command not found").concat("bash"===r?'\nDon\'t use "bash" as a command - call the shell tool directly with your command.\nWrong: {"cmd": ["bash", "-c", "ls -la"]}\nRight: {"cmd": ["ls", "-la"]}\n':"",'\n\nSupported commands: ls, tree, cat, head, tail, rg, grep, find, mkdir, touch, rm, mv, cp, echo\n\nCorrect shell tool usage:\n {"cmd": ["ls", "/"]} - List files\n {"cmd": ["ls", "-R", "/"]} - List files recursively\n {"cmd": ["tree", "/", "-L", "2"]} - Show directory tree (max depth 2)\n {"cmd": ["cat", "/file.txt"]} - Read entire file\n {"cmd": ["head", "-n", "20", "/file.txt"]} - Read first 20 lines\n {"cmd": ["tail", "-n", "20", "/file.txt"]} - Read last 20 lines\n {"cmd": ["rg", "-C", "3", "pattern", "/"]} - Search with 3 lines context (recommended)\n {"cmd": ["rg", "-A", "2", "-B", "1", "pattern"]} - Search with custom context\n {"cmd": ["grep", "-n", "pattern", "/file.txt"]} - Search with line numbers\n {"cmd": ["grep", "-F", "literal", "/file.txt"]} - Search literal string\n {"cmd": ["find", "/", "-name", "*.js"]} - Find files by name\n {"cmd": ["mkdir", "-p", "/path/to/dir"]} - Create directory (with parents)\n {"cmd": ["touch", "/file.txt"]} - Create empty file\n {"cmd": ["rm", "-rf", "/dirname"]} - Delete directory recursively\n {"cmd": ["mv", "/old.txt", "/new.txt"]} - Move/rename files\n {"cmd": ["cp", "-r", "/src", "/dest"]} - Copy files/directories\n {"cmd": ["echo", "Hello World"]} - Output text\n {"cmd": ["echo", "content", ">", "/file.txt"]} - Write text to file\n\nNote: Use json_patch tool for complex file editing. Use rg (ripgrep) instead of grep for better context.'),exitCode:127}}}catch(e){return{stdout:"",stderr:(null==e?void 0:e.message)||String(e),exitCode:1}}}let p={execute:async(e,t)=>{let n=new a.r8;await n.init();let i=await d(n,e,t);return{success:0===i.exitCode,stdout:i.stdout,stderr:i.stderr}}};var u=n(3999);async function h(e,t,n,i){let r=[];if(!n)return{applied:!1,summary:"Missing file path",warnings:["File path is required"]};if(n.startsWith("/")||(n="/"+n),"string"==typeof i)return{applied:!1,summary:"Invalid operations format - received string instead of array",warnings:['The operations parameter is a JSON string instead of an array.\n\nYou sent: "operations": "[{...}]" (STRING - JSON serialized)\nCorrect: "operations": [{...}] (ARRAY - direct object)\n\nDo not stringify the operations array. Pass it directly as an array of objects.\n\nCorrect format:\n{\n "file_path": "/path/to/file",\n "operations": [\n {"type": "update", "oldStr": "exact text", "newStr": "replacement"}\n ]\n}\n\nNOT this (wrong):\n{\n "file_path": "/path/to/file",\n "operations": "[{\\"type\\": \\"update\\", \\"oldStr\\": \\"exact text\\", \\"newStr\\": \\"replacement\\"}]"\n}']};if(!i||0===i.length)return{applied:!1,summary:"Missing operations parameter",warnings:['json_patch requires an operations array with at least one operation.\n\nRequired format:\n{\n "file_path": "/path/to/file",\n "operations": [\n {\n "type": "update",\n "oldStr": "exact text to find",\n "newStr": "replacement text"\n }\n ]\n}\n\nOperation types:\n• update: Replace exact string (oldStr must be unique in file)\n• rewrite: Replace entire file content\n• replace_entity: Replace entire code entity (function, class, etc.) by its opening pattern\n\nExamples:\n✅ Update text: {"file_path": "/index.html", "operations": [{"type": "update", "oldStr": "<title>Old", "newStr": "New"}]}\n✅ Rewrite file: {"file_path": "/style.css", "operations": [{"type": "rewrite", "content": "body { margin: 0; }"}]}\n✅ Replace function: {"file_path": "/app.js", "operations": [{"type": "replace_entity", "selector": "function myFunc()", "replacement": "function myFunc() { return true; }"}]}\n\n❌ Wrong - Missing operations: {"file_path": "/file.js"}\n❌ Wrong - Empty operations: {"file_path": "/file.js", "operations": []}']};let s=n.replace(/\/+/g,"/");try{var a,o;let n="",l=!0;try{let i=await e.readFile(t,s);if("string"!=typeof i.content)return{applied:!1,summary:"Cannot patch binary file",warnings:["File ".concat(s," is binary and cannot be patched")]};n=i.content}catch(e){if(null==(a=e.message)?void 0:a.includes("not found"))l=!1,n="",u.v.debug("[StringPatch] File ".concat(s," does not exist, will create it"));else throw e}let c=n,d=0;for(let e=0;e1){r.push("Operation ".concat(e+1,": oldStr appears ").concat(s,' times in file, must be unique. String: "').concat(m(n,100),'"'));continue}c=c.replace(n,null!=i?i:""),d++}else if("rewrite"===t.type)c=null!=(o=t.content)?o:"",d++;else if("replace_entity"===t.type){let{selector:n,replacement:i,entity_type:s}=t;if(!n){r.push("Operation ".concat(e+1,": selector is required for replace_entity operations"));continue}if(void 0===i){r.push("Operation ".concat(e+1,": replacement is required for replace_entity operations"));continue}let a=function(e,t,n,i){try{let r=function(e,t){let n=[],i=new Set,r=e=>{e&&(i.has(e)||(i.add(e),n.push(e)))};for(let i of(r(t),r(t.replace(/^\s+/,"")),r(t.replace(/\s+$/,"")),r(t.replace(/^\s+/,"").replace(/\s+$/,"")),n)){if(!i)continue;let t=e.indexOf(i);if(-1!==t)return{index:t,normalizedSelector:i}}return null}(e,t);if(!r)return{success:!1,error:'Selector not found: "'.concat(m(t,100),'"')};let{index:s,normalizedSelector:a}=r,o=function(e,t,n,i){var r,s,a,o,l,c,d,p,u;switch(i||((r=n).startsWith("<")&&r.includes(">")?"html_element":r.includes("React.FC")||r.includes(": FC<")?"react_component":r.includes("function ")||r.includes(" = (")||r.includes(" => {")?"function":r.startsWith(".")||r.startsWith("#")?"css_rule":r.includes("interface ")||r.includes("type ")?r.includes("interface ")?"interface":"type":"bracket_matched")){case"html_element":return function(e,t,n){if(t<0||t>=e.length)return null;let i=n.match(/<(\w+)(?:\s|>)/);if(!i)return null;let r=i[1],s=Math.max(0,t);if(n.includes("/>"))return{start:s,end:e.indexOf("/>",t)+2};let a=0,o=t;for(;o]*)?>"))),n=e.substring(o).match(new RegExp(""))),i=-1,l=-1;if(t){let n=e.substring(o).indexOf(t[0]);i=-1!==n?o+n:-1}if(n){let t=e.substring(o).indexOf(n[0]);l=-1!==t?o+t:-1}if(-1===l)break;if(-1!==i&&i0?i.join(", "):"none",'\n\nValid operation types: "update", "rewrite", "replace_entity"\n\nCommon mistakes:\n• Malformed key name like "\\"type\\"" instead of "type" (check JSON escaping)\n• Missing "type" field entirely\n• Typo in type value (e.g., "rewite" instead of "rewrite")\n\nCorrect formats:\n{"type": "update", "oldStr": "exact text to find", "newStr": "replacement"}\n{"type": "rewrite", "content": "complete new file content"}\n{"type": "replace_entity", "selector": "opening pattern", "replacement": "new entity content"}'))}}catch(t){r.push("Operation ".concat(e+1,": ").concat(t.message||String(t)))}}d>0&&(l?await e.updateFile(t,s,c):await e.createFile(t,s,c));let p=d>0?"Applied ".concat(d,"/").concat(i.length," operations to ").concat(s):"No operations applied to ".concat(s);return{applied:d>0,summary:p,warnings:r.length>0?r:void 0}}catch(t){let e=t.message||String(t);return u.v.error("[StringPatch] Failed to patch ".concat(s,":"),e),{applied:!1,summary:"Failed to patch ".concat(s),warnings:["Error: ".concat(e)]}}}function m(e,t){return e.length<=t?e:t<=3?e.substring(0,Math.max(0,t)):e.substring(0,t-3)+"..."}function g(e,t){if(t<0||t>=e.length)return null;let n=e.indexOf("{",t);if(-1===n)return null;let i=Math.max(0,t),r=0,s=n;for(;s{var i;if("string"!=typeof t.cmd)return'Error: cmd must be a string. Pass the complete command as a single string (e.g., "ls -la /")';let r=function(e){let t=[],n="",i=!1,r="",s=!1;for(let a=0;a0&&(t.push(n),n=""):n+=o}return n.length>0&&t.push(n),function(e){let t=[];for(let n of e){let e=n.match(/^(.+)\{([^}]+)\}(.*)$/);if(e){let[,n,i,r]=e;for(let e of i.split(",").map(e=>e.trim()))t.push(n+e+r)}else t.push(n)}return t}(t)}(t.cmd);if(n.isReadOnly&&(i=r)&&0!==i.length&&(["mkdir","rm","rmdir","mv","cp","touch"].includes(i[0])||("echo"===i[0]?i.some(e=>">"===e||">>"===e):i.some(e=>">"===e||">>"===e))))return'Error: Write operations are disabled in read-only mode. "'.concat(r[0],'" is not allowed.');let s=await p.execute(e,r);if(s.success)return s.stdout&&s.stdout.trim().length>0?s.stdout:"Command succeeded with no output";{let e=s.stderr&&s.stderr.trim().length>0?s.stderr:"Command failed";return"Error: ".concat(e)}}}}),this.register({id:"json_patch",definition:{name:"json_patch",description:'Edit files using structured patch operations. Supports three operation types:\n\nIMPORTANT: The \'operations\' parameter must be a direct array, NOT a JSON string.\n❌ Wrong: "operations": "[{...}]"\n✅ Correct: "operations": [{...}]\n\n1. UPDATE - Replace exact string (must be unique in file):\n {"type": "update", "oldStr": "exact text to find", "newStr": "replacement text"}\n\n2. REWRITE - Replace entire file content:\n {"type": "rewrite", "content": "complete new file content"}\n\n3. REPLACE_ENTITY - Replace code entity (function, CSS rule, HTML element) by opening pattern:\n {"type": "replace_entity", "selector": "opening pattern", "replacement": "new entity content"}\n\nExamples:\n{\n "file_path": "/index.html",\n "operations": [\n {"type": "update", "oldStr": "Old Title", "newStr": "New Title"}\n ]\n}\n\n{\n "file_path": "/style.css",\n "operations": [\n {"type": "rewrite", "content": "body { margin: 0; padding: 0; }"}\n ]\n}\n\n{\n "file_path": "/app.js",\n "operations": [\n {"type": "replace_entity", "selector": "function myFunc()", "replacement": "function myFunc() { return true; }"}\n ]\n}',parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to file to edit (must start with /)"},operations:{type:"array",description:"Array of patch operations",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["update"],description:"Update operation type"},oldStr:{type:"string",description:"Exact text to find (must be unique)"},newStr:{type:"string",description:"Replacement text"}},required:["type","oldStr","newStr"]},{type:"object",properties:{type:{type:"string",enum:["rewrite"],description:"Rewrite operation type"},content:{type:"string",description:"Complete new file content"}},required:["type","content"]},{type:"object",properties:{type:{type:"string",enum:["replace_entity"],description:"Replace entity operation type"},selector:{type:"string",description:"Opening pattern to identify entity"},replacement:{type:"string",description:"New entity content"},entity_type:{type:"string",description:"Optional: html_element, function, css_rule, etc."}},required:["type","selector","replacement"]}]}}},required:["file_path","operations"]}},executor:{execute:async(e,t,n)=>{if(n.isReadOnly)return"Error: File editing is disabled in read-only mode.";if("string"==typeof t.operations)try{t.operations=JSON.parse(t.operations)}catch(t){let e=t instanceof Error?t.message:String(t);return"Error: operations parameter appears to be a stringified JSON array, but parsing failed.\n\nThis usually means the JSON is malformed or truncated. Common causes:\n1. Content string not properly escaped or too long\n2. JSON syntax error in the operations array\n3. Unclosed quotes or brackets\n\nParse error: ".concat(e,'\n\nFor large file rewrites, ensure:\n- Content is properly escaped (use raw strings or escape quotes)\n- JSON is complete and valid\n- Consider breaking very large content into smaller operations\n\n❌ Wrong: "operations": "[{...}]" (stringified)\n✅ Correct: "operations": [{...}] (direct array)')}Array.isArray(t.operations)&&(t.operations=t.operations.map(e=>{if("string"==typeof e&&/^\s*[{\[]/.test(e))try{return JSON.parse(e)}catch(e){}return e}));let i=new a.r8;await i.init();let r=await h(i,e,t.file_path,t.operations),s=r.summary;return(r.warnings&&r.warnings.length>0&&(s+="\n\nWarnings:\n"+r.warnings.map(e=>"• ".concat(e)).join("\n")),r.applied)?s:"Error: ".concat(s)}}}),this.register({id:"evaluation",definition:{name:"evaluation",description:"Assess whether the task has been completed successfully. Required before finishing work.",parameters:{type:"object",properties:{goal_achieved:{type:"boolean",description:"Whether the original task/goal has been fully achieved"},progress_summary:{type:"string",description:"Brief summary of work completed so far"},remaining_work:{type:"array",items:{type:"string"},description:"List of specific tasks still needed. Empty array if goal_achieved is true."},blockers:{type:"array",items:{type:"string"},description:"Current blockers preventing progress. Empty array if no blockers."},reasoning:{type:"string",description:"Detailed explanation of current status and next steps"},should_continue:{type:"boolean",description:"Whether to continue working (false if complete or permanently blocked)"}},required:["goal_achieved","progress_summary","remaining_work","reasoning","should_continue"]}},executor:{execute:async(e,t,n)=>["Goal achieved: ".concat(t.goal_achieved?"Yes":"No"),"Progress: ".concat(t.progress_summary),t.remaining_work.length>0?"Remaining: ".concat(t.remaining_work.join(", ")):"",t.blockers&&t.blockers.length>0?"Blockers: ".concat(t.blockers.join(", ")):"","Should continue: ".concat(t.should_continue?"Yes":"No")].filter(Boolean).join("\n")}})}register(e){this.tools.set(e.id,e)}get(e){return this.tools.get(e)}getDefinition(e){var t;return null==(t=this.tools.get(e))?void 0:t.definition}getExecutor(e){var t;return null==(t=this.tools.get(e))?void 0:t.executor}getDefinitions(e){return e.map(e=>this.getDefinition(e)).filter(e=>void 0!==e)}async execute(e,t,n){var i;let r=null==(i=e.function)?void 0:i.name,s=this.get(r);if(!s)return'Error: Unknown tool "'.concat(r,'"');try{let i=JSON.parse(e.function.arguments);return await s.executor.execute(t,i,n)}catch(t){let e=t instanceof Error?t.message:String(t);return u.v.error("Tool execution error (".concat(r,"):"),e),"Error: ".concat(e)}}has(e){return this.tools.has(e)}getAll(){return Array.from(this.tools.values())}constructor(){this.tools=new Map,this.registerBuiltInTools()}}let y=new f;var v=n(7150),w=n(7015),b=n(8202),x=n(86),S=n(3462),k=n(6671),C=n(3091),T=n(4973),j=n(9509);async function A(e,t){var n,i,r,s,a,o,l,c,d,p,h,m,g,f,y,v,w;let b,{provider:x,suppressAssistantDelta:S=!1,onProgress:k}=t,C=null==(n=e.body)?void 0:n.getReader();if(!C)throw Error("No response stream");let T=new TextDecoder,A="",E="",I={},N=null,_="",O="1"===j.env.NEXT_PUBLIC_DEBUG_TOOL_STREAM,P={},R={};try{for(;;){let{done:e,value:n}=await C.read();if(e)break;let j=(A+=T.decode(n,{stream:!0})).split("\n");for(let e of(A=j.pop()||"",j))if(!e.startsWith(":")&&e.startsWith("data: ")){let n=e.slice(6);if("[DONE]"===n){N&&_&&N.function&&N.id&&(N.function.arguments=_,I[N.id]=N);break}try{let e=JSON.parse(n);if("anthropic"===x){if("content_block_delta"===e.type&&(null==(s=e.delta)||null==(r=s.text_delta)?void 0:r.text)){let t=e.delta.text_delta.text;E+=t,S||null==k||k("assistant_delta",{text:t,snapshot:E})}else if("content_block_start"===e.type&&(null==(a=e.content_block)?void 0:a.type)==="tool_use"){let t={id:e.content_block.id,type:"function",function:{name:e.content_block.name,arguments:""}};I[e.content_block.id]=t,P[e.content_block.id]="",R[e.index]=e.content_block.id,S||null==k||k("toolCalls",{toolCalls:[t]})}else if("content_block_delta"===e.type&&(null==(o=e.delta)?void 0:o.type)==="input_json_delta"){let t=R[e.index];t&&e.delta.partial_json&&(P[t]+=e.delta.partial_json,!S&&I[t]&&(I[t].function.arguments=P[t],null==k||k("tool_param_delta",{toolId:t,partialArguments:P[t]})))}else if("content_block_stop"===e.type){let t=R[e.index];if(t&&P[t])try{let e=P[t];JSON.parse(e),I[t].function.arguments=e}catch(e){u.v.error("Invalid JSON for tool parameters:",P[t],e),I[t].function.arguments="{}"}}}else{let t=null==(c=e.choices)||null==(l=c[0])?void 0:l.delta,n=null==(p=e.choices)||null==(d=p[0])?void 0:d.finish_reason;if(("stop"===n||"tool_calls"===n)&&N&&_&&N.function&&N.id&&(N.function.arguments=_,I[N.id]=N,N=null,_=""),(null==t?void 0:t.reasoning)&&!(null==t?void 0:t.content)&&!(null==t?void 0:t.tool_calls)){let e=String(t.reasoning);E+=e,S||null==k||k("assistant_delta",{text:e,snapshot:E})}if(null==t?void 0:t.content){let e=String(t.content);E+=e,S||null==k||k("assistant_delta",{text:e,snapshot:E})}if(null==t?void 0:t.tool_calls)for(let e of t.tool_calls){if(void 0!==e.index){let t="idx_".concat(e.index),n=!I[t];if(n&&(I[t]={id:e.id||"tool_".concat(e.index),type:"function",function:{name:"",arguments:""}}),(null==(g=e.function)?void 0:g.name)&&(I[t].function.name=e.function.name,n&&!S&&(null==k||k("toolCalls",{toolCalls:[I[t]]}))),null==(f=e.function)?void 0:f.arguments){let n=e.function.arguments;I[t].function.arguments+=n,S||null==k||k("tool_param_delta",{toolId:I[t].id,partialArguments:I[t].function.arguments})}}else if(e.id)N&&_&&N.function&&N.id&&(N.function.arguments=_,I[N.id]=N),N={id:e.id,type:"function",function:{name:(null==(y=e.function)?void 0:y.name)||"",arguments:""}},_=(null==(v=e.function)?void 0:v.arguments)||"",!S&&(null==(w=N.function)?void 0:w.name)&&(null==k||k("toolCalls",{toolCalls:[N]}));else if(null==(h=e.function)?void 0:h.arguments){let t=e.function.arguments;_+=t,!S&&N&&(null==k||k("tool_param_delta",{toolId:N.id,partialArguments:_}))}(null==(m=e.function)?void 0:m.name)&&N&&N.function&&(N.function.name=e.function.name)}}e.usage&&(b={promptTokens:e.usage.prompt_tokens||0,completionTokens:e.usage.completion_tokens||0,totalTokens:e.usage.total_tokens||0,cachedTokens:e.usage.cached_tokens,model:t.model,provider:x}),(null==(i=e.x_groq)?void 0:i.usage)&&(b={promptTokens:e.x_groq.usage.prompt_tokens||0,completionTokens:e.x_groq.usage.completion_tokens||0,totalTokens:e.x_groq.usage.total_tokens||0,model:t.model,provider:x})}catch(e){n&&n.length>10&&!n.includes("[DONE]")&&u.v.warn("[StreamParser] Parse error:",e,"Data:",n.substring(0,200))}}}}catch(e){u.v.error("Error reading stream:",e),Object.keys(I).length>0&&N&&_&&N.function&&N.id&&(N.function.arguments=_,I[N.id]=N)}return{content:E,toolCalls:Object.values(I).map(e=>{var t;if(null==(t=e.function)?void 0:t.arguments)try{JSON.parse(e.function.arguments)}catch(o){O&&u.v.warn("Incomplete tool arguments, attempting to fix");let t=e.function.arguments,n=(t.match(/{/g)||[]).length,i=(t.match(/}/g)||[]).length,r=(t.match(/\[/g)||[]).length,s=(t.match(/]/g)||[]).length,a="";for(let e=0;enew Promise(t=>setTimeout(t,e));class I{stop(){this.stopped=!0,u.v.info("[MultiAgentOrchestrator] Execution stopped by user")}importConversation(e){let t=this.conversations.get(this.currentConversationId);if(!t)throw Error("Cannot import conversation: root conversation not found");t.messages=e,u.v.info("[MultiAgentOrchestrator] Imported ".concat(e.length," conversation messages"))}addMessage(e,t){let n=this.conversations.get(e);if(!n)throw Error("Conversation ".concat(e," not found"));if(n.messages.push(t),e===this.currentConversationId){var i;null==(i=this.onProgress)||i.call(this,"conversation_message",{message:t})}}async execute(e){u.v.info("[MultiAgentOrchestrator] Starting execution",{agent:this.rootAgent.type}),this.lastToolCallSignature=null,this.duplicateToolCallCount=0;try{let t;try{let e=await a.vfs.listDirectory(this.projectId,"/");e.length>0&&(t=function(e){if(0===e.length)return"";let t=new Map;for(let n of e){let e=n.path.split("/").filter(Boolean);for(let n=0;n{if(0===e)return"0B";let t=Math.floor(Math.log(e)/Math.log(1024)),n=e/Math.pow(1024,t);return(0===t?n.toString():n.toFixed(1))+["B","KB","MB"][t]},i=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=!(arguments.length>2)||void 0===arguments[2]||arguments[2],a=t.get(e);if(!a)return[];let o=[],l="/"===e?"":e.split("/").pop()||"";if("/"!==e){let e=a.isDirectory?l+"/":l,t=a.isDirectory?"":" (".concat(n(a.size||0),")");o.push(r+(s?"└── ":"├── ")+e+t)}let c=Array.from(a.children).sort((e,n)=>{let i=t.get(e),r=t.get(n);return(null==i?void 0:i.isDirectory)!==(null==r?void 0:r.isDirectory)?(null==i?void 0:i.isDirectory)?-1:1:e.localeCompare(n)});return c.forEach((t,n)=>{let a=n===c.length-1,l="/"===e?"":r+(s?" ":"│ ");o.push(...i(t,l,a))}),o},r=i("/");return r.length>0?"Project Structure:\n"+r.join("\n"):""}(e))}catch(e){}let n=this.rootAgent.systemPrompt;return t&&(n+="\n\n".concat(t)),this.addMessage(this.currentConversationId,{role:"system",content:n}),this.addMessage(this.currentConversationId,{role:"user",content:e}),await this.runAgentLoop(this.currentConversationId,this.rootAgent),await this.recordAutoCheckpoint("After: ".concat(e.substring(0,60))),{success:!0,summary:this.generateSummary(),conversation:Array.from(this.conversations.values()),totalCost:this.totalCost,totalUsage:this.totalUsage}}catch(i){var t;let n=i instanceof Error?i.message:"Unknown error";return u.v.error("[MultiAgentOrchestrator] Execution error:",n),null==(t=this.onProgress)||t.call(this,"error",{message:n,type:"execution_error",stack:i instanceof Error?i.stack:void 0}),await this.recordAutoCheckpoint("After failure: ".concat(e.substring(0,60))),{success:!1,summary:"Error: ".concat(n),conversation:Array.from(this.conversations.values()),totalCost:this.totalCost,totalUsage:this.totalUsage}}}async runAgentLoop(e,t){let n=this.conversations.get(e);if(!n)throw Error("Conversation ".concat(e," not found"));let i=t.maxIterations;for(let a=0;a"".concat(e,": ").concat(JSON.stringify(t[e]).substring(0,50))).join(", "),Object.keys(t).length>3&&(e+="...")}catch(t){e=p.function.arguments.substring(0,100)}let n="❌ Loop detected: Duplicate tool call detected.\n\nTool: ".concat(h,"\nParameters: ").concat(e,"\n\nThe previous call returned a result, but you're calling it again with identical parameters.\n\n\uD83D\uDCA1 Next steps:\n• Review the previous tool result - did it contain what you needed?\n• If the result was incomplete or unexpected, try a different approach\n• If you need additional data, modify your parameters or use a different tool\n• Do NOT retry the exact same call\n\nPlease revise your approach.");if(i.push({role:"tool",tool_call_id:p.id,content:n}),null==(o=this.onProgress)||o.call(this,"tool_status",{toolIndex:t,status:"failed",error:"Loop detected - duplicate tool call #".concat(this.duplicateToolCallCount)}),this.duplicateToolCallCount>=3)throw Error("Execution terminated: Too many consecutive duplicate tool calls (".concat(this.duplicateToolCallCount,"). The model appears stuck in a loop."));continue}this.duplicateToolCallCount=0,this.lastToolCallSignature=m,null==(s=this.onProgress)||s.call(this,"tool_status",{toolIndex:t,status:"executing"});let g={agentType:n.type,isReadOnly:this.chatMode||n.isReadOnly,onProgress:this.onProgress};try{let e=await y.execute(p,this.projectId,g);if("evaluation"===h)try{let e=JSON.parse(p.function.arguments);this.lastEvaluationResult={should_continue:!1!==e.should_continue},u.v.info("[MultiAgentOrchestrator] Captured evaluation result: should_continue=".concat(this.lastEvaluationResult.should_continue))}catch(e){u.v.error("[MultiAgentOrchestrator] Failed to parse evaluation arguments:",e)}let n=e.startsWith("Error:");i.push({role:"tool",tool_call_id:p.id,content:e}),null==(l=this.onProgress)||l.call(this,"tool_status",{toolIndex:t,status:n?"failed":"completed",result:e,...n&&{error:e}}),null==(c=this.onProgress)||c.call(this,"tool_result",{toolIndex:t,result:e})}catch(n){let e=n instanceof Error?n.message:String(n);i.push({role:"tool",tool_call_id:p.id,content:"Error: ".concat(e)}),null==(d=this.onProgress)||d.call(this,"tool_status",{toolIndex:t,status:"failed",error:e})}}return i}async streamLLMResponse(e,t){let{provider:n,apiKey:i,model:r}=this.getProviderConfig();await this.ensurePricing(n,r);let s=y.getDefinitions(t.tools),a="".concat(window.location.origin,"/api/generate"),o={messages:e.map(e=>{let{ui_metadata:t,...n}=e;return n}),apiKey:i,model:r,provider:n,tools:s,...s&&s.length>0&&{tool_choice:"auto"}},l=await this.fetchWithRetry(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},3,this.handleRetry.bind(this));if(!l.ok){let e="API call failed: ".concat(l.statusText);try{let t=await l.json();t.error&&(e=t.error)}catch(e){}throw Error(e)}return this.parseStreamingResponseWithTracking(l,n,r)}createConversation(e,t){let n="conv_".concat(Date.now(),"_").concat(Math.random().toString(36).substr(2,9)),i={id:n,agent_type:e,messages:[],metadata:{started_at:Date.now(),cost:0,status:"running"}};return this.conversations.set(n,i),n}async recordAutoCheckpoint(e){var t;let n=await v.Y.createCheckpoint(this.projectId,e,{kind:"auto",baseRevisionId:w.$.getSavedCheckpointId(this.projectId)});return this.lastCheckpointId=n.id,null==(t=this.onProgress)||t.call(this,"checkpoint_created",{checkpointId:n.id,description:e,timestamp:n.timestamp}),n}getProviderConfig(){let e=b.s.getSelectedProvider(),t=(0,x.sO)(e),n=b.s.getProviderApiKey(e),i=this.model||b.s.getProviderModel(e)||void 0;if(t.apiKeyRequired&&!n)throw Error("API key not configured for provider: ".concat(e));return{provider:e,providerConfig:t,apiKey:n||"",model:i||"default-model"}}handleRetry(e,t){var n;let i="Rate limited. Retry attempt ".concat(e," in ").concat(t/1e3,"s...");u.v.warn(i),null==(n=this.onProgress)||n.call(this,"retry",{attempt:e,delay:t,reason:"Rate limited",message:i}),k.oR.info(i,{duration:t>2e3?t-500:2e3,description:"Waiting for rate limit to reset"})}async ensurePricing(e,t){var n;let i="".concat(e,":").concat(t);if(this.pricingEnsured.has(i))return;if("openrouter"!==e||b.s.getModelPricing("openrouter",t))return void this.pricingEnsured.add(i);let r=b.s.getCachedModels("openrouter");if((null==r||null==(n=r.models)?void 0:n.length)&&((0,C.V)("openrouter",r.models),b.s.getModelPricing("openrouter",t)))return void this.pricingEnsured.add(i);try{let e=await (0,T.QF)();(0,C.b)(e),b.s.getModelPricing("openrouter",t)&&this.pricingEnsured.add(i)}catch(e){u.v.warn("[MultiAgentOrchestrator] Failed to fetch pricing metadata",e)}}async fetchWithRetry(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,i=arguments.length>3?arguments[3]:void 0;for(let r=0;r<=n;r++){let s=await fetch(e,t);if(429!==s.status||r===n)return s;let a=s.headers.get("Retry-After"),o=a?1e3*parseInt(a):1e3*Math.pow(2,r);null==i||i(r+1,o),await E(o)}throw Error("Unexpected end of retry loop")}async parseStreamingResponseWithTracking(e,t,n){let i=await A(e,{provider:t,model:n,projectId:this.projectId,onProgress:this.onProgress,onCostUpdate:(e,n)=>{var i,r;this.totalCost+=e,this.totalUsage.promptTokens+=n.promptTokens,this.totalUsage.completionTokens+=n.completionTokens,this.totalUsage.totalTokens+=n.totalTokens,b.s.updateSessionCost(n,e);let s=null==(i=b.s.getCurrentSession())?void 0:i.sessionId;this.projectId.startsWith("test-")||a.vfs.updateProjectCost(this.projectId,{cost:e,provider:n.provider||t||"unknown",tokenUsage:{input:n.promptTokens,output:n.completionTokens},sessionId:s,mode:"absolute"}).catch(e=>u.v.error("Failed to update project cost:",e)),null==(r=this.onProgress)||r.call(this,"usage",{usage:n,totalCost:this.totalCost})}});if(i.usage){var r,s;let e=i.usage;e.provider||(e.provider=t),e.model||(e.model=n);let o=S.U.calculateCost(e,t,n,!0);e.cost=o,this.totalUsage.promptTokens+=e.promptTokens,this.totalUsage.completionTokens+=e.completionTokens,this.totalUsage.totalTokens+=e.totalTokens,this.totalCost+=o,b.s.updateSessionCost(e,o);let l=null==(r=b.s.getCurrentSession())?void 0:r.sessionId;this.projectId.startsWith("test-")||a.vfs.updateProjectCost(this.projectId,{cost:o,provider:e.provider||t||"unknown",tokenUsage:{input:e.promptTokens,output:e.completionTokens},sessionId:l,mode:"absolute"}).catch(e=>u.v.error("Failed to update project cost:",e)),null==(s=this.onProgress)||s.call(this,"usage",{usage:e,totalCost:this.totalCost})}return i}getToolCallSignature(e){var t;let n=(null==(t=e.function)?void 0:t.name)||"unknown";try{let t=JSON.parse(e.function.arguments);if("shell"===n){let e=Array.isArray(t.cmd)?t.cmd.join(" "):String(t.cmd||"");return"shell:".concat(e)}if("json_patch"===n){let e=t.file_path||"",n=this.hashString(JSON.stringify(t.operations||null));return"json_patch:".concat(e,":").concat(n)}let i=this.stableStringify(t);return"".concat(n,":").concat(i)}catch(t){return"".concat(n,":").concat(e.function.arguments)}}hashString(e){let t=0;for(let n=0;nt&&"object"==typeof t&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}generateSummary(){return"Task completed"}constructor(e,t="orchestrator",n,i){var r;this.conversations=new Map,this.totalCost=0,this.totalUsage={promptTokens:0,completionTokens:0,totalTokens:0,cost:0},this.stopped=!1,this.pricingEnsured=new Set,this.lastCheckpointId=null,this.lastToolCallSignature=null,this.duplicateToolCallCount=0,this.evaluationRequested=!1,this.lastEvaluationResult=null,this.projectId=e,this.onProgress=n,this.chatMode=null!=(r=null==i?void 0:i.chatMode)&&r,this.model=null==i?void 0:i.model;let a=s.get(t);if(!a)throw Error('Agent type "'.concat(t,'" not found'));this.rootAgent=a,this.currentConversationId=this.createConversation(t)}}},8145:(e,t,n)=>{n.d(t,{E:()=>o});var i=n(5155);n(2115);var r=n(2085),s=n(3999);let a=(0,r.F)("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function o(e){let{className:t,variant:n,...r}=e;return(0,i.jsx)("div",{className:(0,s.cn)(a({variant:n}),t),...r})}},8202:(e,t,n)=>{n.d(t,{s:()=>r});class i{getSettings(){let e=localStorage.getItem(this.STORAGE_KEY);if(!e)return{};let t=JSON.parse(e);return("autoSave"in t||"autoSaveInterval"in t)&&(delete t.autoSave,delete t.autoSaveInterval,localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t))),t}setSetting(e,t){let n=this.getSettings();n[e]=t,localStorage.setItem(this.STORAGE_KEY,JSON.stringify(n))}hasSeenTour(){return!!this.getSettings().hasSeenGuidedTour}setHasSeenTour(e){this.setSetting("hasSeenGuidedTour",e)}getApiKey(){let e=this.getSelectedProvider();return e?this.getProviderApiKey(e):this.getSettings().openRouterApiKey||null}setApiKey(e){let t=this.getSelectedProvider();t&&this.setProviderApiKey(t,e),this.setSetting("openRouterApiKey",e)}getDefaultModel(){let e=this.getSelectedProvider();return e?this.getProviderModel(e)||this.getProviderDefaultModel(e):this.getSettings().defaultModel||"deepseek/deepseek-chat"}setDefaultModel(e){let t=this.getSelectedProvider();t&&this.setProviderModel(t,e),this.setSetting("defaultModel",e)}getSelectedProvider(){return this.getSettings().selectedProvider||"openrouter"}setSelectedProvider(e){this.setSetting("selectedProvider",e)}getProviderApiKey(e){var t;let n=this.getSettings();return(null==(t=n.providerKeys)?void 0:t[e])?n.providerKeys[e]:"openrouter"===e&&n.openRouterApiKey?n.openRouterApiKey:null}setProviderApiKey(e,t){let n=this.getSettings().providerKeys||{};n[e]=t,this.setSetting("providerKeys",n),"openrouter"===e&&this.setSetting("openRouterApiKey",t)}getProviderModel(e){var t;let n=this.getSettings();return(null==(t=n.providerModels)?void 0:t[e])?n.providerModels[e]:"openrouter"===e&&n.defaultModel?n.defaultModel:null}setProviderModel(e,t){let n=this.getSettings().providerModels||{};n[e]=t,this.setSetting("providerModels",n),"openrouter"===e&&this.setSetting("defaultModel",t)}getModelPricing(e,t){var n,i;let r=null==(n=this.getSettings().modelPricing)?void 0:n[e];return r&&(r[t]||r["".concat(e,"/").concat(t)]||(t.includes("/")?r[null!=(i=t.split("/").pop())?i:""]:null))||null}setModelPricing(e,t,n){let i={...this.getSettings().modelPricing||{}},r={...i[e]||{}};r[t]=n,i[e]=r,this.setSetting("modelPricing",i)}setProviderPricing(e,t){if(!t||0===Object.keys(t).length)return;let n={...this.getSettings().modelPricing||{}},i={...n[e]||{}};for(let[e,n]of Object.entries(t))i[e]=n;n[e]=i,this.setSetting("modelPricing",n)}clearProviderPricing(e){var t;if(!e)return void this.setSetting("modelPricing",{});let n=this.getSettings();if(!(null==(t=n.modelPricing)?void 0:t[e]))return;let i={...n.modelPricing||{}};delete i[e],this.setSetting("modelPricing",i)}getProviderDefaultModel(e){switch(e){case"openrouter":default:return"deepseek/deepseek-chat";case"openai":return"gpt-4o-mini";case"anthropic":return"claude-3-5-haiku-20241022";case"groq":return"llama-3.3-70b-versatile";case"gemini":return"gemini-1.5-flash";case"ollama":return"llama3.2:latest";case"lmstudio":return"local-model";case"sambanova":return"Meta-Llama-3.3-70B-Instruct"}}getTheme(){return this.getSettings().theme||"dark"}setTheme(e){this.setSetting("theme",e)}clearSettings(){localStorage.removeItem(this.STORAGE_KEY)}getCostSettings(){return this.getSettings().costSettings||{showCosts:!0,warningThreshold:80}}setCostSettings(e){this.setSetting("costSettings",e),window.dispatchEvent(new CustomEvent("osw-studio-cost-settings-changed"))}getCurrentSession(){let e=this.getSettings().currentSession;return e?{...e,startTime:new Date(e.startTime)}:null}startNewSession(){let e={sessionId:Date.now().toString(),startTime:new Date,totalCost:0,messageCount:0,providerBreakdown:{}};return this.setSetting("currentSession",e),e}updateSessionCost(e,t){let n=this.getCurrentSession();n||(n=this.startNewSession()),n.totalCost+=t,n.messageCount+=1;let i=e.provider||"unknown";n.providerBreakdown[i]||(n.providerBreakdown[i]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),n.providerBreakdown[i].cost+=t,n.providerBreakdown[i].tokenUsage.input+=e.promptTokens,n.providerBreakdown[i].tokenUsage.output+=e.completionTokens,n.providerBreakdown[i].requestCount+=1;let r=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};r.total+=t,r.byProvider[i]=(r.byProvider[i]||0)+t,this.setSetting("currentSession",n),this.setSetting("lifetimeCosts",r)}adjustSessionCost(e,t,n){if(!t&&!n)return;let i=this.getCurrentSession();if(!i)return;let r=e||"unknown";i.totalCost+=t,i.providerBreakdown[r]||(i.providerBreakdown[r]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),i.providerBreakdown[r].cost+=t,n&&(i.providerBreakdown[r].tokenUsage.input+=n.input,i.providerBreakdown[r].tokenUsage.output+=n.output);let s=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};s.total+=t,s.byProvider[r]=(s.byProvider[r]||0)+t,this.setSetting("currentSession",i),this.setSetting("lifetimeCosts",s)}getLifetimeCosts(){return this.getSettings().lifetimeCosts||{total:0,byProvider:{}}}resetLifetimeCosts(){this.setSetting("lifetimeCosts",{total:0,byProvider:{},lastReset:new Date})}checkCostLimits(){let e=this.getCostSettings(),t=this.getCurrentSession();if(!t||!e.dailyLimit)return{warning:!1,exceeded:!1};let n=t.totalCost/e.dailyLimit*100;return n>=100?{warning:!1,exceeded:!0,message:"Daily limit of $".concat(e.dailyLimit.toFixed(2)," exceeded")}:e.warningThreshold&&n>=e.warningThreshold?{warning:!0,exceeded:!1,message:"".concat(n.toFixed(0),"% of daily limit used ($").concat(t.totalCost.toFixed(2)," of $").concat(e.dailyLimit.toFixed(2),")")}:{warning:!1,exceeded:!1}}getCachedModels(e){var t;let n=null==(t=this.getSettings().modelCache)?void 0:t[e];return n?new Date>new Date(n.expiresAt)?(this.clearModelCache(e),null):n:null}setCachedModels(e,t){let n=this.getSettings(),i=new Date,r=new Date(i.getTime()+864e5),s=n.modelCache||{};s[e]={models:t,timestamp:i.toISOString(),expiresAt:r.toISOString()},this.setSetting("modelCache",s)}clearModelCache(e){if(e){let t=this.getSettings().modelCache||{};delete t[e],this.setSetting("modelCache",t)}else this.setSetting("modelCache",{})}isCacheValid(e){return null!==this.getCachedModels(e)}constructor(){this.STORAGE_KEY="osw-studio-settings"}}let r=new i},9052:(e,t,n)=>{n.d(t,{t:()=>M});var i=n(5155),r=n(2115),s=n(8202);function a(e,t){var n,i;let r,s;return t?(r='You are an AI assistant that helps users with their coding projects. You work in a sandboxed virtual file system.\n\n\uD83D\uDD12 CHAT MODE - READ-ONLY EXPLORATION AND PLANNING\n\nYou have access ONLY to the \'shell\' tool with READ-ONLY commands.\nYOU CANNOT EDIT FILES IN CHAT MODE.\nFocus on exploring the codebase, analyzing code, and discussing approaches.\n\nSHELL TOOL FORMAT:\nThe \'cmd\' parameter accepts BOTH natural string format and array format - use whichever feels more natural!\n\nNatural format: {"cmd": "ls -la /"}\nNatural format: {"cmd": "rg -C 3 \'pattern\' /"}\nNatural format: {"cmd": "head -n 50 /index.html"}\nArray format: {"cmd": ["ls", "-la", "/"]}\nArray format: ["rg", "-C", "3", "pattern", "/"]\nArray format: {"cmd": ["head", "-n", "50", "/index.html"]}\n\nUse the shell tool to execute commands. The natural string format is preferred for readability.\n\n⚠️ CRITICAL: MINIMIZE TOKEN USAGE - AVOID CAT\nDO NOT use \'cat\' to read entire files unless absolutely necessary!\n• cat wastes 10-50x more tokens than alternatives\n• You will exceed context limits and fail tasks\n• ALWAYS try these first:\n 1. rg -C 5 \'searchterm\' / (search with context - best for finding code)\n 2. head -n 50 /file (sample start of file)\n 3. tail -n 50 /file (sample end of file)\n 4. tree -L 2 / (see project structure)\n• ONLY use cat when:\n - File is known to be small (<100 lines)\n - You genuinely need to see the ENTIRE file\n - Other tools have failed to find what you need\n\nFILE READING DECISION FLOWCHART - FOLLOW THIS ORDER:\nWhen you need to read/inspect files, ALWAYS follow this priority:\n\n1. **SEARCHING for specific code/patterns?**\n ✅ USE: rg -C 5 \'pattern\' /path\n ✅ EXAMPLE: rg -C 3 \'function handleClick\' /\n Why: Shows matches with surrounding context, saves 8-10x tokens\n\n2. **EXPLORING a file\'s structure/beginning?**\n ✅ USE: head -n 50 /file.js\n ✅ EXAMPLE: head -n 100 /components/App.tsx\n Why: Sample without reading entire file, saves 10-50x tokens\n\n3. **CHECKING end of file (logs, recent additions)?**\n ✅ USE: tail -n 50 /file.js\n ✅ EXAMPLE: tail -n 100 /utils/helpers.js\n Why: Sample end without reading entire file\n\n4. **UNDERSTANDING project structure?**\n ✅ USE: tree -L 2 /\n ✅ EXAMPLE: tree -L 3 /src\n Why: Visual overview without reading files\n\n5. **NEED ENTIRE FILE** (LAST RESORT ONLY):\n ⚠️ USE: cat /file.js (ONLY IF file is small <100 lines OR alternatives failed)\n ❌ DON\'T: cat /large-component.tsx (will waste massive tokens)\n\nAvailable Commands (READ-ONLY):\n- Search with context: rg [-C num] [-A num] [-B num] [-n] [-i] [pattern] [path] ← PREFER THIS FOR SEARCH\n- Read file head: head [-n lines] [filepath] ← PREFER THIS\n- Read file tail: tail [-n lines] [filepath] ← PREFER THIS\n- Directory tree: tree [path] [-L depth] ← PREFER THIS\n- List files: ls [-R] [path]\n- Read entire files: cat [filepath] ← AVOID (use only for small files)\n- Search (basic, no context): grep [-n] [-i] [-F] [pattern] [path] ← Use rg instead for context\n- Find files: find [path] -name [pattern]\n\n⚠️ IMPORTANT: grep does NOT support -A, -B, or -C flags. For context around matches, use rg (ripgrep)!\n\n❌ DISABLED IN CHAT MODE:\n- mkdir, touch, mv, rm, cp, echo > (all write operations)\n- json_patch tool (not available)\n- evaluation tool (not available)\n\nImportant Notes:\n- All paths are relative to the project root (/)\n- ALWAYS use targeted reads: `rg -C 5`, `head -n 50`, or `tail -n 50` (NOT cat!)\n- Reuse snippets from earlier in the conversation when possible\n- Use the shell tool via function calling, not by outputting JSON text\n- Focus on exploration, analysis, and planning - no file modifications\n',(n=e)&&(r+="\n\n".concat(n)),r):(s='You are an AI assistant that helps users with their coding projects. You work in a sandboxed virtual file system.\n\n\uD83D\uDEA8 PLATFORM CONSTRAINTS - READ THIS FIRST:\n\nThis is a STATIC WEBSITE builder - you can ONLY create client-side HTML/CSS/JS:\n• ❌ NO backend code (no Node.js, Python, PHP, Ruby, etc.)\n• ❌ NO server-side rendering (no Express, Next.js API routes, etc.)\n• ❌ NO databases or server-side storage\n• ✅ ONLY static files that run in the browser (HTML, CSS, vanilla JS)\n\nHANDLEBARS IS BUILD-TIME, NOT RUNTIME:\n• Handlebars templates are compiled AUTOMATICALLY when the preview loads\n• DO NOT write JavaScript code to compile or render Handlebars templates\n• DO NOT import Handlebars library or use Handlebars.compile() in your JS\n• Just create .hbs files and use {{> partial}} syntax - the system handles compilation\n\nROUTING IS AUTOMATIC:\n• Navigation works with standard HTML links: About\n• DO NOT create routing logic (no History API, hash routing, or SPA routers)\n• DO NOT write JavaScript to handle page navigation\n• Create separate .html files for each page - the preview handles routing\n\nWHAT YOU CAN BUILD:\n• Multi-page websites with .html files\n• Interactive features with vanilla JavaScript (DOM manipulation, fetch API, localStorage)\n• Reusable components with Handlebars templates (.hbs files)\n• Responsive layouts with CSS\n• Client-side data visualization, forms, animations, etc.\n\nSHELL TOOL FORMAT:\nThe \'cmd\' parameter accepts BOTH natural string format and array format - use whichever feels more natural!\n\nNatural format: {"cmd": "ls -la /"}\nNatural format: {"cmd": "rg -C 3 \'pattern\' /"}\nNatural format: {"cmd": "head -n 50 /index.html"}\nArray format: {"cmd": ["ls", "-la", "/"]}\nArray format: ["rg", "-C", "3", "pattern", "/"]\nArray format: {"cmd": ["head", "-n", "50", "/index.html"]}\n\nUse the shell tool to execute commands. The natural string format is preferred for readability.\n\n⚠️ CRITICAL: MINIMIZE TOKEN USAGE - AVOID CAT\nDO NOT use \'cat\' to read entire files unless absolutely necessary!\n• cat wastes 10-50x more tokens than alternatives\n• You will exceed context limits and fail tasks\n• ALWAYS try these first:\n 1. rg -C 5 \'searchterm\' / (search with context - best for finding code)\n 2. head -n 50 /file (sample start of file)\n 3. tail -n 50 /file (sample end of file)\n 4. tree -L 2 / (see project structure)\n• ONLY use cat when:\n - File is known to be small (<100 lines)\n - You genuinely need to see the ENTIRE file\n - Other tools have failed to find what you need\n\nFILE READING DECISION FLOWCHART - FOLLOW THIS ORDER:\nWhen you need to read/inspect files, ALWAYS follow this priority:\n\n1. **SEARCHING for specific code/patterns?**\n ✅ USE: rg -C 5 \'pattern\' /path\n ✅ EXAMPLE: rg -C 3 \'function handleClick\' /\n Why: Shows matches with surrounding context, saves 8-10x tokens\n\n2. **EXPLORING a file\'s structure/beginning?**\n ✅ USE: head -n 50 /file.js\n ✅ EXAMPLE: head -n 100 /components/App.tsx\n Why: Sample without reading entire file, saves 10-50x tokens\n\n3. **CHECKING end of file (logs, recent additions)?**\n ✅ USE: tail -n 50 /file.js\n ✅ EXAMPLE: tail -n 100 /utils/helpers.js\n Why: Sample end without reading entire file\n\n4. **UNDERSTANDING project structure?**\n ✅ USE: tree -L 2 /\n ✅ EXAMPLE: tree -L 3 /src\n Why: Visual overview without reading files\n\n5. **NEED ENTIRE FILE** (LAST RESORT ONLY):\n ⚠️ USE: cat /file.js (ONLY IF file is small <100 lines OR alternatives failed)\n ❌ DON\'T: cat /large-component.tsx (will waste massive tokens)\n\nAvailable Commands for the shell tool:\n- Search with context: rg [-C num] [-A num] [-B num] [-n] [-i] [pattern] [path] ← PREFER THIS FOR SEARCH\n- Read file head: head [-n lines] [filepath] ← PREFER THIS\n- Read file tail: tail [-n lines] [filepath] ← PREFER THIS\n- Directory tree: tree [path] [-L depth] ← PREFER THIS\n- List files: ls [-R] [path]\n- Read entire files: cat [filepath] ← AVOID (use only for small files)\n- Search (basic, no context): grep [-n] [-i] [-F] [pattern] [path] ← Use rg instead for context\n- Find files: find [path] -name [pattern]\n- Create directories: mkdir [-p] [path1] [path2] ... ← Supports multiple paths and brace expansion\n- Create empty files: touch [file1] [file2] ... ← Supports multiple files and brace expansion\n- Move/rename: mv [source] [dest]\n- Remove files/directories: rm [-rf] [path1] [path2] ... ← Supports multiple paths\n- Copy: cp [-r] [source] [dest]\n- Output text: echo [text]\n- Write to file: echo [text] > [filepath]\n- Edit files: Use json_patch tool for reliable file editing\n\n⚠️ IMPORTANT: grep does NOT support -A, -B, or -C flags. For context around matches, use rg (ripgrep)!\n\nBash Brace Expansion:\nThe shell supports brace expansion like real bash - use {a,b,c} to expand into multiple arguments:\n- mkdir -p templates/{layout,components,pages} ← Creates 3 directories\n- touch src/{index,app,utils}.js ← Creates 3 files\n- Combines with paths: mkdir -p src/{components,utils}/{common,helpers}\n\nFile Editing with json_patch:\n\n⚠️ CRITICAL WORKFLOW - YOU MUST FOLLOW THIS ORDER:\n1. Ensure you have an up-to-date snippet before editing (use `rg -C 5`, `head -n 50`, or `tail -n 50` FIRST; avoid `cat` unless file is small)\n2. Study the exact content to identify unique strings for replacement\n3. Use the json_patch tool with precise string operations\n\n⚠️ TOKEN LIMITS FOR LARGE FILE CREATION:\n- Your output is limited to ~4000 tokens (~16,000 characters)\n- Creating large files (500+ lines of CSS/HTML/JS) in one REWRITE operation will FAIL with truncated JSON\n- **Solution**: Break large files into multiple smaller operations:\n - Create file with basic structure first (headers, skeleton)\n - Add sections incrementally using UPDATE operations\n - Or create multiple smaller module files instead of one massive file\n- Example: Instead of 1000-line style.css, create style.css (base), components.css, layout.css, utilities.css\n\nThe json_patch tool uses simple JSON operations for reliable file editing:\n\nOperation Types:\n1. UPDATE: Replace exact strings (oldStr must be unique in file)\n2. REWRITE: Replace entire file content\n3. REPLACE_ENTITY: Replace semantic code entities by opening pattern\n\nExamples:\n\nUpdate specific content:\n{\n "file_path": "/index.html",\n "operations": [\n {\n "type": "update",\n "oldStr": "Old Title",\n "newStr": "New Title"\n }\n ]\n}\n\nAdd content by expanding existing text:\n{\n "file_path": "/app.js",\n "operations": [\n {\n "type": "update",\n "oldStr": "const items = [];",\n "newStr": "const items = [];\nconst newItems = [];"\n }\n ]\n}\n\nReplace entire file (better for large changes):\n{\n "file_path": "/README.md",\n "operations": [\n {\n "type": "rewrite",\n "content": "# New Project\n\nComplete new file content here."\n }\n ]\n}\n\nSmall targeted update (safer approach):\n{\n "file_path": "/index.html",\n "operations": [\n {\n "type": "update",\n "oldStr": "

Ajankohtaista

",\n "newStr": "

News Gallery

"\n }\n ]\n}\n\nReplace HTML element (robust approach):\n{\n "file_path": "/index.html",\n "operations": [\n {\n "type": "replace_entity",\n "selector": "
",\n "replacement": "
\n \x3c!-- Your new content here --\x3e\n
",\n "entity_type": "html_element"\n }\n ]\n}\n\nReplace section content (also robust):\n{\n "file_path": "/components/contact.tsx",\n "operations": [\n {\n "type": "replace_entity",\n "selector": "
",\n "replacement": "
\n

Get In Touch

\n

Contact us at info@example.com

\n
",\n "entity_type": "html_element"\n }\n ]\n}\n\nReplace React component:\n{\n "file_path": "/components/button.tsx",\n "operations": [\n {\n "type": "replace_entity",\n "selector": "const Button: React.FC = ({",\n "replacement": "const Button: React.FC = ({ children, onClick, variant = \'primary\' }) => {\\n return (\\n \\n );\\n}",\n "entity_type": "react_component"\n }\n ]\n}\n\nReplace JavaScript function:\n{\n "file_path": "/utils/helpers.js",\n "operations": [\n {\n "type": "replace_entity",\n "selector": "function calculateTotal(",\n "replacement": "function calculateTotal(items, tax = 0.1) {\n const subtotal = items.reduce((sum, item) => sum + item.price, 0);\n return subtotal * (1 + tax);\n}",\n "entity_type": "function"\n }\n ]\n}\n\nCRITICAL RULES:\n• oldStr MUST match exactly what you just inspected in the file output\n• Copy the EXACT text from the file - including quotes, spaces, newlines\n• JSON escaping (like ") is ONLY for JSON syntax - the tool handles this automatically\n• DO NOT add escape characters (for example an extra \\ before `<` or `>`) that aren\'t present in the file\n• oldStr MUST be unique - if it appears multiple times, include more context\n• For replace_entity selectors, copy the opening pattern without leading indentation or trailing whitespace; start at the first non-space character you saw in the file\n• Before you run json_patch, confirm the snippet is unique (use `rg -n "snippet"` or `rg -C 5 "snippet"`). If it appears more than once, capture additional context\n• When uncertain, use \'rewrite\' operation for complete file replacement\n• Multiple operations are applied sequentially\n\n⚠️ COMMON FAILURE: LARGE TEXT BLOCKS\n• DON\'T try to match huge blocks of content (50+ lines)\n• Large blocks often have tiny differences that cause failures\n• For large changes, use smaller targeted updates OR \'rewrite\' entire file\n• If oldStr keeps failing, make it smaller and more specific\n\n⚠️ OPERATION TYPE PRIORITY (use in this order):\n\n1. **FIRST CHOICE - "replace_entity"** for:\n • HTML elements: `
`, `