(the actual text)\nThe JSON parser handles this automatically - just copy what you see!\n\nDEBUGGING FAILED PATCHES:\n• If "oldStr not found", the text doesn\'t match exactly\n• Use smaller, more specific oldStr targets\n• Or switch to \'rewrite\' for the entire file\n\n⚠️ SOURCE REVIEW BEFORE EDITING\n• ALWAYS inspect the relevant snippet before editing.\n• REQUIRED: Use scoped reads - `rg -C 5`, `head -n 50`, or `tail -n 50`\n• ❌ AVOID: Using `cat` on large files wastes tokens and may cause failures\n• ✅ PREFER: Targeted commands that show only what you need\n• If you already have the snippet from earlier in the session, reuse it instead of re-running commands.\n\nEvaluation Tool:\nUse the \'evaluation\' tool periodically to assess task progress:\n- Check if the original goal has been achieved\n- Provide reasoning about what was accomplished\n- Determine if you should continue working or stop\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- When json_patch fails, read the file again and verify exact string matches\n- Use evaluation tool to self-assess progress on complex tasks\n\nJSON_PATCH VERIFICATION CHECKLIST:\n□ Reviewed the relevant snippet (via `rg -C 5`, `head -n 50`, or `tail -n 50` - avoid cat!) and identified exact strings to replace\n□ Verified oldStr appears exactly once in the file\n□ Used sufficient context in oldStr to ensure uniqueness\n□ Considered using \'rewrite\' for extensive changes\n\nHANDLEBARS TEMPLATES:\nThe system supports Handlebars templating for reusable components and dynamic content.\n\nCreating Template Files:\nTemplates should be placed in the /templates directory with .hbs or .handlebars extension.\n\nExample - Creating a reusable component:\n{\n "file_path": "/templates/card.hbs",\n "operations": [\n {\n "type": "rewrite",\n "content": "
\n
{{title}} \n {{#if description}}\n
{{description}}
\n {{/if}}\n {{#each tags}}\n
{{this}} \n {{/each}}\n
"\n }\n ]\n}\n\nUsing Templates in HTML:\nInclude templates using the {{> partialName}} syntax:\n{\n "file_path": "/index.html",\n "operations": [\n {\n "type": "update",\n "oldStr": "
",\n "newStr": "
\n {{> card title=\\"My Product\\" description=\\"Amazing product\\" featured=true}}\n
"\n }\n ]\n}\n\nTemplate Data:\nCreate a /data.json file to provide data context for templates:\n{\n "file_path": "/data.json",\n "operations": [\n {\n "type": "rewrite",\n "content": "{\n \\"pageTitle\\": \\"My Website\\",\n \\"products\\": [\n {\\"name\\": \\"Product 1\\", \\"price\\": 99},\n {\\"name\\": \\"Product 2\\", \\"price\\": 149}\n ]\n}"\n }\n ]\n}\n\nAvailable Handlebars Features:\n- Variables: {{variable}}, {{{unescapedHtml}}}\n- Conditionals: {{#if}}, {{else}}, {{#unless}}\n- Loops: {{#each array}}...{{@index}}...{{/each}}\n- Partials: {{> partialName param=\\"value\\"}}\n- Comments: {{! This is a comment }}\n- Block helpers: {{#with object}}...{{/with}}\n- Built-in helpers: eq, ne, lt, gt, lte, gte, and, or, not\n- Math helpers: add, subtract, multiply, divide\n- String helpers: uppercase, lowercase, concat\n- Utility helpers: json, formatDate\n';return e&&(t+="\n\n".concat(e)),t}},1173:(e,t,n)=>{n.d(t,{I:()=>i});var r=n(3999);class i{static async getGenerationStats(e,t){if(!e||!t)return null;try{let n=await fetch("".concat(this.BASE_URL,"/generation?id=").concat(e),{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}});if(!n.ok)return r.v.warn("[GenerationAPI] Failed to fetch generation stats: ".concat(n.status)),null;return await n.json()}catch(e){return r.v.error("[GenerationAPI] Error fetching generation stats:",e),null}}static queueGenerationForCostUpdate(e,t,n,i,s,o){setTimeout(async()=>{let n=await this.getGenerationStats(e,t);if(null==n?void 0:n.usage){var i,s;let t=null!=(s=null!=(i=n.total_cost)?i:n.usage.total_cost)?s:0;r.v.debug("[GenerationAPI] Generation ".concat(e),{normalized_tokens:n.usage.total_tokens,native_tokens:n.usage.native_tokens_total,actual_cost:t}),o(t,n.usage)}},3e3)}static extractGenerationId(e){return e.get("x-openrouter-generation-id")}static extractCostFromHeaders(e){let t,n,i=e.get("x-openrouter-usage"),s=e.get("x-openrouter-cost");if(i)try{t=JSON.parse(i)}catch(e){r.v.warn("[GenerationAPI] Failed to parse usage header:",e)}if(s){let e=parseFloat(s);isNaN(e)||(n=e)}return t||void 0!==n?{usage:t,cost:n}:null}}i.BASE_URL="https://openrouter.ai/api/v1"},2714:(e,t,n)=>{n.d(t,{J:()=>c});var r=n(5155),i=n(2115),s=n(968),o=n(2085),a=n(3999);let l=(0,o.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=i.forwardRef((e,t)=>{let{className:n,...i}=e;return(0,r.jsx)(s.b,{ref:t,className:(0,a.cn)(l(),n),...i})});c.displayName=s.b.displayName},3091:(e,t,n)=>{n.d(t,{V:()=>o,b:()=>a});var r=n(8202);let i="openrouter";function s(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return t<.01?1e6*t:t}function o(e,t){if(!Array.isArray(t)||0===t.length)return;let n={};for(let r of t){if(!(null==r?void 0:r.pricing))continue;let t={input:r.pricing.input,output:r.pricing.output,reasoning:r.pricing.reasoning};Number.isFinite(t.input)&&Number.isFinite(t.output)&&(n[r.id]=t,n["".concat(e,"/").concat(r.id)]=t)}if(e===i)for(let[e,t]of Object.entries(n)){let r=e.split("/").pop();r&&!n[r]&&(n[r]=t)}Object.keys(n).length>0&&r.s.setProviderPricing(e,n)}function a(e){if(!Array.isArray(e)||0===e.length)return;let t={};for(let r of e){var n,o,a;let e=s(null==(n=r.pricing)?void 0:n.prompt),l=s(null==(o=r.pricing)?void 0:o.completion),c=s(null==(a=r.pricing)?void 0:a.internal_reasoning);if(void 0===e||void 0===l)continue;let d={input:e,output:l,reasoning:c};t[r.id]=d,t["".concat(i,"/").concat(r.id)]=d,r.canonical_slug&&(t[r.canonical_slug]=d)}Object.keys(t).length>0&&r.s.setProviderPricing(i,t)}},3462:(e,t,n)=>{n.d(t,{U:()=>a});var r=n(8202),i=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}},o={input:1,output:2};class a{static calculateCost(e,t,n){var r,o;let a,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||i.v.warn("[CostCalculator] Falling back to default pricing for ".concat(p));let g=0,f=Math.max(null!=(r=e.promptTokens)?r:0,0);f&&(g+=f/1e6*m.input);let v=Math.max(null!=(o=e.completionTokens)?o:0,0);return e.reasoningTokens&&(v=Math.max(v-Math.max(e.reasoningTokens,0),0)),v&&(g+=v/1e6*m.output),e.reasoningTokens&&m.reasoning&&(g+=e.reasoningTokens/1e6*m.reasoning),d||void 0===c?(a=Math.max(g,null!=c?c:0),e.isEstimated=!l||d,void 0!==c&&c>a&&(a=c),void 0!==c&&Math.abs(a-c)>1e-4&&i.v.debug("[CostCalculator] Adjusted provisional cost",{provider:t,model:n,reportedCost:c,computedCost:g,finalCost:a})):(a=c,e.isEstimated=!1),e.isEstimated&&("openrouter"===t||t.toString().includes("openrouter"))&&i.v.warn("[CostCalculator] Using estimated cost based on normalized tokens for OpenRouter. This may be inaccurate. Consider using Generation API for native token counts."),a}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,r]of Object.entries(s))if(e.startsWith(n)){let i=e.substring(n.length);if(t.includes(i)||i.includes(t))return r}return"ollama"===e||"lmstudio"===e?{input:0,output:0}:o}static getDynamicPricing(e,t){if(!this.isKnownProvider(e))return null;try{return r.s.getModelPricing(e,t)}catch(n){return i.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 r=!(arguments.length>3)||void 0===arguments[3]||arguments[3],i=Math.ceil(1.3*e.split(/\s+/).length),s=this.getPricing(t,n);return i/1e6*(r?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 r;i.v.debug("[CostCalculator] Cost corrected: ".concat(null==(r=e.cost)?void 0:r.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 r=n(6126),i=n.n(r);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)=>e
e>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())}async registerPartials(){if(!this.partialsRegistered)try{for(let e of(await this.vfs.listDirectory(this.projectId,"/templates")))if("template"===e.type||e.path.endsWith(".hbs")||e.path.endsWith(".handlebars")){let t=e.name.replace(/\.hbs$/,"").replace(/\.handlebars$/,"");t.includes("/")&&(t=t.split("/").pop()||t);let n=e.content;this.handlebars.registerPartial(t,n)}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),r=new Map,i=[];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 o=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===o&&n.has(t.path)){let e=n.get(t.path);r.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);r.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,o)}i.push(t)}for(let s of t){if("html"!==s.type)continue;let t=await this.processHTML(s,r),o=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===o&&n.has(t.path)){let e=n.get(t.path);r.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);r.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,o)}i.push(t)}let s=[...i];for(let i of t)if("css"===i.type){let t=await this.processCSS(i,r),o=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===o&&n.has(t.path)){let e=n.get(t.path);r.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);r.set(t.path,n),t.blobUrl=n,this.fileHashes.set(t.path,o)}s.push(t)}let o=this.generateRoutes(t);if(e)for(let[,e]of n)URL.revokeObjectURL(e);else e||this.cleanupBlobUrls();return this.blobUrls=r,{entryPoint:"/index.html",files:s,routes:o,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 DeepStudio\n(function() {\n const vfsBlobUrls = ".concat(JSON.stringify(r),";\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("",i+"\n"):n.includes("")?n.replace("",i+"\n"):i+"\n"+n,{path:e.path,content:n,mimeType:e.mimeType}}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={};try{let e=await this.vfs.readFile(this.projectId,"/data.json");n=JSON.parse(e.content)}catch(e){}return this.handlebars.compile(e)(n)}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
\nCheck for typos in helper names and partial references \nEnsure all opening tags have matching closing tags \nVerify partial names exist in /templates/ directory \nUse {{> 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,"/"),r=t||this.blobUrls,i=e;for(let e of[/href="([^"]+)"/g,/src="([^"]+)"/g,/href='([^']+)'/g,/src='([^']+)'/g])i=i.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 i=this.normalizePath(t);if(n.some(e=>e.path===i)){let n=r.get(i);if(n)return e.replace(t,n)}return e});return i}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 r=this.normalizePath(n),i=t.get(r);return i?"url('".concat(i,"')"):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",""),r=e.path.replace(".html","")||"/";return{path:"/index"===r?"/":r,file:e.path,title:n}})}extractTitle(e){let t=e.match(/([^<]+)<\/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=i().create(),this.registerHelpers()}}},3999:(e,t,n)=>{n.d(t,{cn:()=>o,v:()=>d});var r=n(2596),i=n(9688),s=n(9509);function o(){for(var e=arguments.length,t=Array(e),n=0;n{n.d(t,{r8:()=>p,OP:()=>u});var r=n(1368),i=n(9311),s=n.n(i);class o{async init(){return new Promise((e,t)=>{let n=indexedDB.open("deepstudio-vfs",1);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})}}})}getDB(){if(!this.db)throw Error("Database not initialized. Call init() first.");return this.db}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}}constructor(){this.db=null}}var a=n(3999),l=n(5337),c=n(7015),d=n(3902);class p{async init(){this.initialized||(await this.db.init(),this.initialized=!0)}ensureInitialized(){if(!this.initialized)throw Error("VirtualFileSystem not initialized. Call init() first.")}async createFile(e,t,n){this.ensureInitialized();try{if(t=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim(),await this.db.getFile(e,t))throw a.v.error("VFS: File already exists",{projectId:e,path:t}),Error("File already exists: ".concat(t));if(!(0,l.fu)(t))throw Error("Unsupported file type: ".concat(t));let i=(0,l.Gr)(t),s=n instanceof ArrayBuffer?n.byteLength:new Blob([n]).size,o=l.Q6[i];if(s>o)throw Error("File too large. Maximum size for ".concat(i," files is ").concat(Math.round(o/1024/1024),"MB"));let d={id:(0,r.A)(),projectId:e,path:t,name:t.split("/").pop()||"",type:i,content:n,mimeType:(0,l.N$)(t),size:s,createdAt:new Date,updatedAt:new Date,metadata:{isEntry:"/index.html"===t}};return await this.db.createFile(d),await this.updateFileTree(e,t,"create"),c.$.markDirty(e),d}catch(e){throw e}}async readFile(e,t){if(this.ensureInitialized(),!e||"string"!=typeof e)throw a.v.error("VFS: Invalid projectId for readFile",{projectId:e,path:t}),Error("Invalid projectId provided");if(!t||"string"!=typeof t)throw a.v.error("VFS: Invalid path for readFile",{projectId:e,path:t}),Error("Invalid file path provided");let n=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(!n)throw a.v.error("VFS: Empty path after cleaning for readFile",{projectId:e,originalPath:t,cleanPath:n}),Error("Empty file path after cleaning");let r=await this.db.getFile(e,n);if(!r)throw a.v.error("VFS: File not found for read",{projectId:e,path:n,originalPath:t}),Error("File not found: ".concat(n));return r}async fileExists(e,t){this.ensureInitialized();try{return!!await this.db.getFile(e,t)}catch(e){return!1}}async updateFile(e,t,n){this.ensureInitialized();try{let r=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(r.includes("\n")||r.includes("@@")||r.includes("\\n")||r.length>200)throw a.v.error("VFS: Invalid path detected",{projectId:e,path:t.slice(0,100)+"..."}),Error("Invalid file path: ".concat(t.slice(0,50),"..."));t=r;let i=await this.db.getFile(e,t);if(!i)throw a.v.error("VFS: File not found for update",{projectId:e,path:t}),Error("File not found: ".concat(t));i.content=n,i.size=n instanceof ArrayBuffer?n.byteLength:new Blob([n]).size,i.updatedAt=new Date,await this.db.updateFile(i),c.$.markDirty(e);{let n={projectId:e,path:t};window.dispatchEvent(new CustomEvent("fileContentChanged",{detail:n}))}return i}catch(e){throw e}}async patchFile(e,t,n){this.ensureInitialized();let r=(await this.readFile(e,t)).content;for(let e of n){if(!r.includes(e.search))throw a.v.error("VFS: Pattern not found in file",{path:t,searchPattern:e.search.substring(0,100),contentSnippet:r.substring(0,300)}),Error("Pattern not found in file: ".concat(e.search.substring(0,50),"..."));r=r.replace(e.search,e.replace)}return await this.updateFile(e,t,r)}async deleteFile(e,t){this.ensureInitialized();try{await this.db.deleteFile(e,t),await this.updateFileTree(e,t,"delete"),c.$.markDirty(e)}catch(e){throw e}}async renameFile(e,t,n){this.ensureInitialized();let r=await this.readFile(e,t);return await this.deleteFile(e,t),await this.createFile(e,n,r.content)}async createDirectory(e,t){if(this.ensureInitialized(),await this.db.getTreeNode(e,t))return;let n={id:(0,r.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:[]};await this.db.createTreeNode(n),c.$.markDirty(e),window.dispatchEvent(new Event("filesChanged"))}async listDirectory(e,t){this.ensureInitialized();let n=await this.db.listFiles(e);return"/"===t?n:n.filter(e=>{let n=e.path,r=t.endsWith("/")?t:t+"/";return n.startsWith(r)&&-1===n.slice(r.length).indexOf("/")})}async getAllFilesAndDirectories(e){return this.ensureInitialized(),[...await this.db.listFiles(e),...(await this.db.getAllTreeNodes(e)).filter(e=>"directory"===e.type).map(e=>({path:e.path,name:e.path.split("/").filter(Boolean).pop()||e.path,type:"directory"}))]}async deleteDirectory(e,t){this.ensureInitialized();let n=await this.db.listFiles(e),r=t.endsWith("/")?t:t+"/";for(let t of n)t.path.startsWith(r)&&await this.deleteFile(e,t.path);await this.db.deleteTreeNode(e,t),c.$.markDirty(e),window.dispatchEvent(new Event("filesChanged"))}async renameDirectory(e,t,n){this.ensureInitialized();let i=await this.db.getTreeNode(e,t);if(i){await this.db.deleteTreeNode(e,t);let s={id:(0,r.A)(),projectId:e,path:n,type:"directory",parentPath:this.getParentPath(n),children:i.children};await this.db.createTreeNode(s),c.$.markDirty(e)}let s=t.endsWith("/")?t:t+"/",o=n.endsWith("/")?n:n+"/";for(let t of(await this.db.listFiles(e)).filter(e=>e.path.startsWith(s))){let n=o+t.path.substring(s.length);await this.renameFile(e,t.path,n)}for(let n of(await this.db.getAllTreeNodes(e)).filter(e=>"directory"===e.type&&e.path.startsWith(s)&&e.path!==t)){let t=o+n.path.substring(s.length);await this.db.deleteTreeNode(e,n.path);let i={id:(0,r.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:n.children};await this.db.createTreeNode(i)}window.dispatchEvent(new Event("filesChanged"))}async moveFile(e,t,n){if(this.ensureInitialized(),await this.db.getFile(e,n))throw Error("File already exists at destination: ".concat(n));let r=await this.readFile(e,t),i=await this.createFile(e,n,r.content);return await this.deleteFile(e,t),i}async moveDirectory(e,t,n){this.ensureInitialized();let r=n.endsWith("/")?n:n+"/",i=t.endsWith("/")?t:t+"/";if(r.startsWith(i))throw Error("Cannot move a directory into itself");await this.renameDirectory(e,t,n),window.dispatchEvent(new Event("filesChanged"))}async createProject(e,t){this.ensureInitialized();try{let n={id:(0,r.A)(),name:e,description:t,createdAt:new Date,updatedAt:new Date,settings:{},lastSavedCheckpointId:null,lastSavedAt:null,costTracking:{totalCost:0,providerBreakdown:{},sessionHistory:[]}};await this.db.createProject(n);let i={id:(0,r.A)(),projectId:n.id,path:"/",type:"directory",parentPath:null,children:[]};return await this.db.createTreeNode(i),n}catch(e){throw e}}async getProject(e){this.ensureInitialized();let t=await this.db.getProject(e);if(!t)throw Error("Project not found: ".concat(e));return t}async updateProject(e){this.ensureInitialized(),e.updatedAt=new Date,await this.db.updateProject(e)}async updateProjectCost(e,t){this.ensureInitialized();let n=await this.getProject(e);if(!n)throw Error("Project not found: ".concat(e));n.costTracking||(n.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),n.costTracking.totalCost+=t.cost,n.costTracking.providerBreakdown[t.provider]||(n.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let r=n.costTracking.providerBreakdown[t.provider];r.totalCost+=t.cost,"delta"!==t.mode&&(r.requestCount+=1),r.lastUpdated=new Date,t.tokenUsage&&(r.tokenUsage.input+=t.tokenUsage.input,r.tokenUsage.output+=t.tokenUsage.output),t.sessionId&&"delta"!==t.mode&&(n.costTracking.sessionHistory||(n.costTracking.sessionHistory=[]),n.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.cost,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsage}),n.costTracking.sessionHistory.length>100&&(n.costTracking.sessionHistory=n.costTracking.sessionHistory.slice(-100))),await this.updateProject(n)}async applyProjectCostDelta(e,t){this.ensureInitialized();let n=await this.getProject(e);if(!n)throw Error("Project not found: ".concat(e));n.costTracking||(n.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),n.costTracking.totalCost+=t.costDelta,n.costTracking.providerBreakdown[t.provider]||(n.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let r=n.costTracking.providerBreakdown[t.provider];r.totalCost+=t.costDelta,r.lastUpdated=new Date,t.tokenUsageDelta&&(r.tokenUsage.input+=t.tokenUsageDelta.input,r.tokenUsage.output+=t.tokenUsageDelta.output),t.sessionId&&(n.costTracking.sessionHistory||(n.costTracking.sessionHistory=[]),n.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.costDelta,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsageDelta,correction:!0}),n.costTracking.sessionHistory.length>100&&(n.costTracking.sessionHistory=n.costTracking.sessionHistory.slice(-100))),await this.updateProject(n)}async deleteProject(e){this.ensureInitialized(),await this.db.deleteProject(e)}async listProjects(){return this.ensureInitialized(),await this.db.listProjects()}async getFileTree(e){return this.ensureInitialized(),await this.db.getTreeNode(e,"/")}async searchFiles(e,t,n){this.ensureInitialized();let r=await this.db.listFiles(e),{regex:i=!1,fileType:s,limit:o=20,searchIn:a="both"}=n||{},l=r;if(s){let e=s.startsWith(".")?s:".".concat(s);l=r.filter(t=>t.path.endsWith(e))}let c=i?e=>{try{return RegExp(t,"i").test(e)}catch(n){return e.toLowerCase().includes(t.toLowerCase())}}:e=>e.toLowerCase().includes(t.toLowerCase());return l.filter(e=>"filename"===a?c(e.name)||c(e.path):"content"===a?"string"==typeof e.content&&c(e.content):c(e.name)||c(e.path)||"string"==typeof e.content&&c(e.content)).slice(0,o)}async findReferences(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"any";this.ensureInitialized();let r=await this.db.listFiles(e),i=[],s=[];switch(n){case"class":s.push(RegExp("class=[\"'][^\"']*\\b".concat(t,"\\b[^\"']*[\"']"),"gi")),s.push(RegExp("\\.".concat(t,"\\b"),"g")),s.push(RegExp("classList\\.(add|remove|toggle|contains)\\(['\"`]".concat(t,"['\"`]"),"g"));break;case"id":s.push(RegExp("id=[\"']".concat(t,"[\"']"),"gi")),s.push(RegExp("#".concat(t,"\\b"),"g")),s.push(RegExp("getElementById\\(['\"`]".concat(t,"['\"`]"),"g")),s.push(RegExp("querySelector\\(['\"`]#".concat(t,"['\"`]"),"g"));break;case"function":s.push(RegExp("function\\s+".concat(t,"\\s*\\("),"g")),s.push(RegExp("(?:const|let|var)\\s+".concat(t,"\\s*=\\s*(?:\\([^)]*\\)|[^=])\\s*=>"),"g")),s.push(RegExp("".concat(t,"\\s*\\("),"g"));break;case"variable":s.push(RegExp("(?:const|let|var)\\s+".concat(t,"\\b"),"g")),s.push(RegExp("\\b".concat(t,"\\b"),"g"));break;default:s.push(RegExp("\\b".concat(t,"\\b"),"gi"))}for(let e of r){if("string"!=typeof e.content)continue;let t=[];e.content.split("\n").forEach((e,n)=>{for(let r of s)if(r.test(e)){t.push({line:n+1,text:e.trim()});break}}),t.length>0&&i.push({file:e,matches:t})}return i}async getFileStats(e,t){this.ensureInitialized();let n=await this.db.getFile(e,t);if(!n)throw Error("File not found: ".concat(t));let r=("string"==typeof n.content?n.content:"").split("\n");return{path:n.path,size:n.size,lines:r.length,type:n.type,preview:r.slice(0,10),lastModified:n.updatedAt}}async getProjectSize(e){return this.ensureInitialized(),(await this.db.listFiles(e)).reduce((e,t)=>e+t.size,0)}async getProjectStats(e){let t;this.ensureInitialized();let n=await this.db.listFiles(e),r=0,i={};for(let e of n){var s;r+=e.size;let t=(null==(s=e.path.split(".").pop())?void 0:s.toUpperCase())||"OTHER";i[t]=(i[t]||0)+1}return t=r<1024?"".concat(r," B"):r<1048576?"".concat((r/1024).toFixed(1)," KB"):"".concat((r/1048576).toFixed(2)," MB"),{fileCount:n.length,totalSize:r,fileTypes:i,formattedSize:t}}async exportProject(e){return this.ensureInitialized(),{project:await this.getProject(e),files:await this.db.listFiles(e)}}async exportProjectAsZip(e){this.ensureInitialized();let t=new(s());try{let n=new d.B(this,e);for(let e of(await n.compileProject()).files){let n=e.path.startsWith("/")?e.path.slice(1):e.path;this.shouldExcludeFromExport(e.path)||(e.content,t.file(n,e.content))}n.cleanupBlobUrls()}catch(n){for(let r of(a.v.warn("Failed to compile Handlebars templates during export, falling back to raw files:",n),await this.db.listFiles(e))){let e=r.path.startsWith("/")?r.path.slice(1):r.path;this.shouldExcludeFromExport(r.path)||(r.content,t.file(e,r.content))}}return await t.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}shouldExcludeFromExport(e){return!!(e.endsWith(".hbs")||e.endsWith(".handlebars")||e.startsWith("/templates/"))||"/data.json"===e}async duplicateProject(e){this.ensureInitialized();let t=await this.getProject(e),n=await this.db.listFiles(e),r="".concat(t.name," (Copy)").slice(0,50),i=await this.createProject(r,t.description);return await c.$.runWithSuppressedDirty(i.id,async()=>{for(let e of n)await this.createFile(i.id,e.path,e.content)}),i}async importProject(e){this.ensureInitialized();let t=await this.createProject(e.project.name,e.project.description);return await c.$.runWithSuppressedDirty(t.id,async()=>{for(let n of e.files)await this.createFile(t.id,n.path,n.content)}),t}getParentPath(e){if("/"===e)return null;let t=e.split("/").filter(Boolean);return 1===t.length?"/":(t.pop(),"/"+t.join("/"))}async updateFileTree(e,t,n){let r=this.getParentPath(t);if(null===r)return;let i=await this.db.getTreeNode(e,r);if(i||"create"!==n||(await this.createDirectory(e,r),i=await this.db.getTreeNode(e,r)),i){let e=i.children||[];if("create"!==n||e.includes(t)){if("delete"===n){let n=e.indexOf(t);n>-1&&e.splice(n,1)}}else e.push(t);i.children=e,await this.db.updateTreeNode(i)}}constructor(){this.initialized=!1,this.db=new o}}let u=new p},4973:(e,t,n)=>{n.d(t,{QF:()=>i,WK:()=>s});var r=n(3999);async function i(){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"],r=n.some(t=>e.id.toLowerCase().includes(t)),i=n.some(e=>t.id.toLowerCase().includes(e));return r&&!i?-1:!r&&i?1:t.created-e.created})}catch(e){return r.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))}},5040:(e,t,n)=>{n.d(t,{r:()=>I});var r=n(4520),i=n(7150),s=n(7015),o=n(8202),a=n(86),l=n(3462),c=n(1173);let d={name:"shell",description:"Run a command in the sandboxed VFS terminal. Use natural command format (string) or array format.",parameters:{type:"object",properties:{cmd:{oneOf:[{type:"string",description:'Natural command format, e.g., "cat /index.html" or "ls -la /"'},{type:"array",description:'argv vector format, e.g., ["cat","/index.html"]',items:{type:"string"}}]},cwd:{type:"string",description:"working directory (ignored; paths are absolute under /)"},timeoutMs:{type:"number",description:"command timeout (ms)"}},required:["cmd"]}},p={name:"json_patch",description:"Apply precise string-based patches to files using JSON operations. Reliable file editing with exact string matching.",parameters:{type:"object",properties:{file_path:{type:"string",description:'Absolute path to the file to modify (e.g., "/src/components/App.tsx")'},operations:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["update","rewrite","replace_entity"],description:'Operation type: "update" for string replacement, "rewrite" for complete file replacement, "replace_entity" for semantic entity replacement'},oldStr:{type:"string",description:'For "update": EXACT string to find and replace - copy directly from file content as seen with cat. MUST be unique in file. JSON escaping handled automatically.'},newStr:{type:"string",description:'For "update": Replacement string'},content:{type:"string",description:'For "rewrite": Complete new file content'},selector:{type:"string",description:'For "replace_entity": Opening pattern to identify the entity (e.g., "", "const ContactForm = () => {", "function calculateTotal("). Copy the snippet starting at the first non-space character—do NOT include leading indentation, trailing whitespace, or extra escape characters. Ensure the selector is specific enough to be unique (add distinguishing attributes if necessary).'},replacement:{type:"string",description:'For "replace_entity": Complete new entity content to replace the identified entity'},entity_type:{type:"string",description:'For "replace_entity": Optional hint for boundary detection (html_element, react_component, function, css_rule, interface, type)'}},required:["type"]},description:'Array of patch operations to apply sequentially. Each "update" operation requires oldStr and newStr. Each "rewrite" operation requires content. Each "replace_entity" operation requires selector and replacement.'}},required:["file_path","operations"]}},u={name:"evaluation",description:"Evaluate if the task has been completed successfully. Use this periodically to assess progress.",parameters:{type:"object",properties:{goal_achieved:{type:"boolean",description:"Whether the original task/goal has been fully achieved"},reasoning:{type:"string",description:"Detailed explanation of what was accomplished and why the goal is/is not achieved"},should_continue:{type:"boolean",description:"Whether to continue working on the task (false if complete or stuck)"}},required:["goal_achieved","reasoning","should_continue"]}};var h=n(1052);function m(e){return e.length>1e5?e.slice(0,1e5)+"\n… [truncated]":e}function g(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 f(e,t,n){if("/"===n||!n)return;let r=n.split("/").filter(Boolean),i="";for(let n=0;n
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 r=n.filter(e=>null!=e&&""!==e);if(0===r.length)return{stdout:"",stderr:"No valid command arguments provided",exitCode:2};let[i,...s]=r;try{switch(i){case"ls":{let n=new Set,r=[];for(let e of s)e&&e.startsWith("-")?n.add(e):e&&r.push(e);let i=n.has("-R")||n.has("-r"),o=g(r[0])||"/";if(i){let n=await e.getAllFilesAndDirectories(t),r="/"===o?"/":o.endsWith("/")?o:o+"/",i=n.filter(e=>e.path===o||e.path.startsWith(r)).map(e=>e.path).sort().join("\n");return{stdout:m(i),stderr:"",exitCode:0}}{let n=(await e.listDirectory(t,o)).map(e=>e.path).sort().join("\n");return{stdout:m(n),stderr:"",exitCode:0}}}case"tree":{let n=1/0,r="/";for(let e=0;ee.path===i||e.path.startsWith(a)).map(e=>({path:e.path,isDir:"type"in e&&"directory"===e.type})),c=[i];for(let e of l.filter(e=>e.path!==i).map(e=>e.path).sort()){let t=e.slice(a.length).split("/").filter(Boolean).length;if(t>n)continue;let r=" ".repeat(t-1),i=e.split("/").pop()||e;c.push("".concat(r,"├── ").concat(i))}return{stdout:m(c.join("\n")),stderr:"",exitCode:0}}case"cat":{let n=g(s[0]);if(!n)return{stdout:"",stderr:"cat: missing file path",exitCode:2};if(n.startsWith("/-"))return{stdout:"",stderr:"cat: invalid path (looks like an option). Use: cat /path/to/file",exitCode:2};let r=await e.readFile(t,n);if("string"!=typeof r.content)return{stdout:"",stderr:"cat: ".concat(n,": binary or non-text file"),exitCode:1};return{stdout:m(r.content),stderr:"",exitCode:0}}case"head":{let n=10,r="";for(let e=0;ee-t);for(let i of(d.length>0&&d.push(""),p)){let s=n.n?"".concat(i+1,":"):"";r.has(i),d.push("".concat(e.path,":").concat(s).concat(t[i]))}}if(0===d.length){let e="/"===o?"workspace root":o;return{stdout:"",stderr:'rg: pattern "'.concat(i,'" not found in ').concat(e),exitCode:1}}return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"find":{let n,r,i;for(let e=0;ee.path===o||e.path.startsWith(l)).map(e=>e.path).filter(e=>!c||c.test(e.split("/").pop()||e)).sort();return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"mkdir":{let n=s.includes("-p"),r=s[n?s.indexOf("-p")+1:0],i=g(r);if(!i)return{stdout:"",stderr:"mkdir: missing path",exitCode:2};return n?await f(e,t,i):await e.createDirectory(t,i),{stdout:"",stderr:"",exitCode:0}}case"touch":{let n=g(s[0]);if(!n)return{stdout:"",stderr:"touch: missing file path",exitCode:2};try{return await e.readFile(t,n),{stdout:"",stderr:"",exitCode:0}}catch(r){try{return await e.createFile(t,n,""),{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"touch: ".concat(n,": ").concat((null==e?void 0:e.message)||"cannot create file"),exitCode:1}}}}case"rm":{let n=!1,r=!1,i=!1,o=[];for(let e of s)e&&e.startsWith("-")?((e.includes("r")||e.includes("R"))&&(n=!0),e.includes("f")&&(r=!0),e.includes("v")&&(i=!0)):e&&o.push(e);if(0===o.length)return{stdout:"",stderr:"rm: missing operand",exitCode:2};let a=!1,l=[];for(let s of o){let o=g(s);if(!o){r||(a=!0);continue}try{await e.deleteFile(t,o),i&&l.push("removed '".concat(o,"'"))}catch(s){if(n)try{await e.deleteDirectory(t,o),i&&l.push("removed directory '".concat(o,"'"))}catch(e){!r&&(a=!0,i&&l.push("rm: cannot remove '".concat(o,"': No such file or directory")))}else!r&&(a=!0,i&&l.push("rm: cannot remove '".concat(o,"': Is a directory (use -r to remove directories)")))}}let c=i?l.join("\n"):"",d=a&&!i?"rm: some paths could not be removed":"";return{stdout:m(c),stderr:d,exitCode:+!!a}}case"mv":{let[n,r]=s,i=g(n),o=g(r);if(!i||!o)return{stdout:"",stderr:"mv: missing operands",exitCode:2};try{return await e.renameFile(t,i,o),{stdout:"",stderr:"",exitCode:0}}catch(n){return await e.renameDirectory(t,i,o),{stdout:"",stderr:"",exitCode:0}}}case"cp":{let n=s.includes("-r"),[r,i]=s.filter(e=>"-r"!==e);if(r=g(r),i=g(i),!r||!i)return{stdout:"",stderr:"cp: missing operands",exitCode:2};try{let n=await e.readFile(t,r),s=(n.content,n.content);try{await e.createFile(t,i,s)}catch(n){await e.updateFile(t,i,s)}return{stdout:"",stderr:"",exitCode:0}}catch(a){if(!n)return{stdout:"",stderr:"cp: -r required for directories",exitCode:1};let s=await e.getAllFilesAndDirectories(t),o=r.endsWith("/")?r:r+"/";for(let n of s)if((!("type"in n)||"directory"!==n.type)&&(n.path===r||n.path.startsWith(o))){let s=n.path.slice(r.length),o=(i.endsWith("/")?i.slice(0,-1):i)+s;await f(e,t,o.split("/").slice(0,-1).join("/"));let a=(n.content,n.content);try{await e.createFile(t,o,a)}catch(n){await e.updateFile(t,o,a)}}return{stdout:"",stderr:"",exitCode:0}}}case"echo":{let n=s.indexOf(">");if(-1===n)return{stdout:m(s.join(" ")),stderr:"",exitCode:0};let r=s.slice(0,n).join(" "),i=s[n+1],o=g(i);if(!o)return{stdout:"",stderr:"echo: missing file path after >",exitCode:2};try{let n=o.split("/").slice(0,-1).join("/")||"/";"/"!==n&&await f(e,t,n);try{await e.createFile(t,o,r)}catch(n){await e.updateFile(t,o,r)}return{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"echo: ".concat(o,": ").concat((null==e?void 0:e.message)||"cannot write file"),exitCode:1}}}default:return{stdout:"",stderr:"".concat(i,": command not found").concat("bash"===i?'\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 y={execute:async(e,t)=>{let n=new r.r8;await n.init();let i=await v(n,e,t);return{success:0===i.exitCode,stdout:i.stdout,stderr:i.stderr}}};var w=n(3999);async function x(e,t,n,r){let i=[];if(!n||!n.startsWith("/"))return{applied:!1,summary:"Invalid file path",warnings:["File path must be absolute and start with /"]};if(!r||0===r.length)return{applied:!1,summary:"No operations provided",warnings:["No patch operations to apply"]};let s=n.replace(/\/+/g,"/");try{var o,a;let n="",l=!0;try{let r=await e.readFile(t,s);if("string"!=typeof r.content)return{applied:!1,summary:"Cannot patch binary file",warnings:["File ".concat(s," is binary and cannot be patched")]};n=r.content}catch(e){if(null==(o=e.message)?void 0:o.includes("not found"))l=!1,n="",w.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){i.push("Operation ".concat(e+1,": oldStr appears ").concat(s,' times in file, must be unique. String: "').concat(b(n,100),'"'));continue}c=c.replace(n,null!=r?r:""),d++}else if("rewrite"===t.type)c=null!=(a=t.content)?a:"",d++;else if("replace_entity"===t.type){let{selector:n,replacement:r,entity_type:s}=t;if(!n){i.push("Operation ".concat(e+1,": selector is required for replace_entity operations"));continue}if(void 0===r){i.push("Operation ".concat(e+1,": replacement is required for replace_entity operations"));continue}let o=function(e,t,n,r){try{let i=function(e,t){let n=[],r=new Set,i=e=>{e&&(r.has(e)||(r.add(e),n.push(e)))};for(let r of(i(t),i(t.replace(/^\s+/,"")),i(t.replace(/\s+$/,"")),i(t.replace(/^\s+/,"").replace(/\s+$/,"")),n)){if(!r)continue;let t=e.indexOf(r);if(-1!==t)return{index:t,normalizedSelector:r}}return null}(e,t);if(!i)return{success:!1,error:'Selector not found: "'.concat(b(t,100),'"')};let{index:s,normalizedSelector:o}=i,a=function(e,t,n,r){var i,s,o,a,l,c,d,p,u;switch(r||((i=n).startsWith("<")&&i.includes(">")?"html_element":i.includes("React.FC")||i.includes(": FC<")?"react_component":i.includes("function ")||i.includes(" = (")||i.includes(" => {")?"function":i.startsWith(".")||i.startsWith("#")?"css_rule":i.includes("interface ")||i.includes("type ")?i.includes("interface ")?"interface":"type":"bracket_matched")){case"html_element":return function(e,t,n){if(t<0||t>=e.length)return null;let r=n.match(/<(\w+)(?:\s|>)/);if(!r)return null;let i=r[1],s=Math.max(0,t);if(n.includes("/>"))return{start:s,end:e.indexOf("/>",t)+2};let o=0,a=t;for(;a]*)?>"))),n=e.substring(a).match(new RegExp("".concat(i,">"))),r=-1,l=-1;if(t){let n=e.substring(a).indexOf(t[0]);r=-1!==n?a+n:-1}if(n){let t=e.substring(a).indexOf(n[0]);l=-1!==t?a+t:-1}if(-1===l)break;if(-1!==r&&r0&&(l?await e.updateFile(t,s,c):await e.createFile(t,s,c));let p=d>0?"Applied ".concat(d,"/").concat(r.length," operations to ").concat(s):"No operations applied to ".concat(s);return{applied:d>0,summary:p,warnings:i.length>0?i:void 0}}catch(t){let e=t.message||String(t);return w.v.error("[StringPatch] Failed to patch ".concat(s,":"),e),{applied:!1,summary:"Failed to patch ".concat(s),warnings:["Error: ".concat(e)]}}}function b(e,t){return e.length<=t?e:t<=3?e.substring(0,Math.max(0,t)):e.substring(0,t-3)+"..."}function C(e,t){if(t<0||t>=e.length)return null;let n=e.indexOf("{",t);if(-1===n)return null;let r=Math.max(0,t),i=0,s=n;for(;snew Promise(t=>setTimeout(t,e));class I{stop(){this.stopped=!0,w.v.info("[Orchestrator] Generation stopped by user")}async fetchWithRetry(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,r=arguments.length>3?arguments[3]:void 0;for(let i=0;i<=n;i++){let s=await fetch(e,t);if(429!==s.status||i===n)return s;let o=s.headers.get("Retry-After"),a=o?1e3*parseInt(o):1e3*Math.pow(2,i);null==r||r(i+1,a),await T(a)}throw Error("Unexpected end of retry loop")}getProviderConfig(){let e=o.s.getSelectedProvider(),t=(0,a.sO)(e),n=o.s.getProviderApiKey(e),r=o.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:r||"default-model"}}handleRetry(e,t){let n="Rate limited. Retry attempt ".concat(e," in ").concat(t/1e3,"s...");w.v.warn(n),k.oR.info(n,{duration:t>2e3?t-500:2e3,description:"Waiting for rate limit to reset"})}async streamLLMResponse(e,t,n,r,i,s){await this.ensurePricing(n,i);let o="".concat(window.location.origin,"/api/generate"),a={messages:e,apiKey:r,model:i,provider:n,tools:t,...t&&t.length>0&&{tool_choice:(null==s?void 0:s.toolChoice)||"auto"},max_tokens:null==s?void 0:s.maxTokens};w.v.debug("[Orchestrator] Making API request to ".concat(n," with ").concat((null==t?void 0:t.length)||0," tools, model: ").concat(i),{toolChoice:a.tool_choice||"none"});let l=await this.fetchWithRetry(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},3,this.handleRetry.bind(this));if(!l.ok)throw Error("API call failed: ".concat(l.statusText));return this.parseStreamingResponse(l,n,(null==s?void 0:s.suppressAssistantDelta)===!0)}async parseStreamingResponse(e,t){var n,i,s,a,d,p,u,h,m,g,f,v,y,x,b,C,k,S,j;let T,I=arguments.length>2&&void 0!==arguments[2]&&arguments[2],P=null==(n=e.body)?void 0:n.getReader();if(!P)throw Error("No response stream");let A=new TextDecoder,N="",O="",E={},F=null,R="",D="1"===_.env.NEXT_PUBLIC_DEBUG_TOOL_STREAM,M={},U={};try{for(;;){let{done:e,value:n}=await P.read();if(e)break;let r=(N+=A.decode(n,{stream:!0})).split("\n");for(let e of(N=r.pop()||"",r))if(e.startsWith("data: ")){let n=e.slice(6);if("[DONE]"===n){F&&R&&F.function&&F.id&&(F.function.arguments=R,E[F.id]=F);break}try{let e=JSON.parse(n);if("anthropic"===t){if("content_block_delta"===e.type&&(null==(a=e.delta)||null==(s=a.text_delta)?void 0:s.text)){let t=e.delta.text_delta.text;O+=t,I||null==(u=this.onProgress)||u.call(this,"assistant_delta",{text:t,snapshot:O})}else if("content_block_start"===e.type&&(null==(d=e.content_block)?void 0:d.type)==="tool_use"){let t={id:e.content_block.id,type:"function",function:{name:e.content_block.name,arguments:""}};E[e.content_block.id]=t,M[e.content_block.id]="",U[e.index]=e.content_block.id}else if("content_block_delta"===e.type&&(null==(p=e.delta)?void 0:p.type)==="input_json_delta"){let t=U[e.index];t&&e.delta.partial_json&&(M[t]+=e.delta.partial_json)}else if("content_block_stop"===e.type){let t=U[e.index];if(t&&M[t])try{let e=M[t];JSON.parse(e),E[t].function.arguments=e}catch(e){w.v.error("Invalid JSON for tool parameters:",M[t],e),E[t].function.arguments="{}"}}}else{let t=null==(m=e.choices)||null==(h=m[0])?void 0:h.delta;if((null==t?void 0:t.reasoning)&&!(null==t?void 0:t.content)&&!(null==t?void 0:t.tool_calls)){let e=String(t.reasoning);O+=e,I||null==(g=this.onProgress)||g.call(this,"assistant_delta",{text:e,snapshot:O})}if(null==t?void 0:t.content){let e=String(t.content);O+=e,I||null==(f=this.onProgress)||f.call(this,"assistant_delta",{text:e,snapshot:O})}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);if(E[t]||(E[t]={id:e.id||"tool_".concat(e.index),type:"function",function:{name:"",arguments:""}}),(null==(x=e.function)?void 0:x.name)&&(E[t].function.name=e.function.name),null==(b=e.function)?void 0:b.arguments){let n=e.function.arguments;E[t].function.arguments+=n}}else if(e.id)F&&R&&F.function&&F.id&&(F.function.arguments=R,E[F.id]=F),F={id:e.id,type:"function",function:{name:(null==(C=e.function)?void 0:C.name)||"",arguments:""}},R=(null==(k=e.function)?void 0:k.arguments)||"";else if(null==(v=e.function)?void 0:v.arguments){let t=e.function.arguments;R+=t}(null==(y=e.function)?void 0:y.name)&&F&&F.function&&(F.function.name=e.function.name)}}e.usage&&(T={promptTokens:e.usage.prompt_tokens||0,completionTokens:e.usage.completion_tokens||0,totalTokens:e.usage.total_tokens||0,cachedTokens:e.usage.cached_tokens,model:this.getProviderConfig().model,provider:t}),(null==(i=e.x_groq)?void 0:i.usage)&&(T={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:this.getProviderConfig().model,provider:t})}catch(e){n&&n.length>10&&!n.includes("[DONE]")&&w.v.warn("[Orchestrator] Parse error in streaming response:",e,"Data snippet:",n.substring(0,200))}}}}catch(e){w.v.error("Error reading stream:",e),Object.keys(E).length>0&&F&&R&&F.function&&F.id&&(F.function.arguments=R,E[F.id]=F)}if(O&&w.v.debug("[Orchestrator] Checking content for tool calls",{contentLength:O.length,existingToolCalls:Object.keys(E).length,hasToolKeywords:O.includes("json_patch")||O.includes("evaluation")}),O&&0===Object.keys(E).length){let e=O;if(O.includes("<|channel|>")&&O.includes("<|message|>")){let t=O.match(/to=functions\.(\w+)[\s\S]*?<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/);if(t){let n=t[1],r=t[2];try{let i=JSON.parse(r.trim());E.manual_1={id:"manual_1",type:"function",function:{name:n,arguments:JSON.stringify(i)}},e=O.replace(t[0],"").trim()}catch(e){w.v.debug("Failed to parse reasoning format JSON:",e)}}else if(t=O.match(/commentary to=functions\.(\w+)[\s\S]*?<\|constrain\|>json<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/)){let n=t[2];try{let r=JSON.parse(n.trim());E.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(r)}},e=O.replace(t[0],"").trim()}catch(e){w.v.debug("Failed to parse commentary reasoning format JSON:",e)}}}for(let t of[/\{[^{}]*"cmd"\s*:\s*\[[^\]]*\][^{}]*\}/,/\{"cmd":\s*\[.*?\]\}/,/\{.*?"cmd".*?\}/]){let n=e.match(t);if(n){w.v.debug("[Orchestrator] Found JSON match with pattern",{pattern:t.toString(),jsonPreview:n[0].substring(0,200)});try{let t=n[0],r=JSON.parse(t);if(r.cmd&&Array.isArray(r.cmd)){let n=r.cmd;"bash"===n[0]&&n[1]&&n[1].startsWith("-")&&n[2]&&(r.cmd=n=n[2].trim().split(/\s+/)),E.manual_1||(E.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(r)}}),e=e.replace(t,"").trim();break}}catch(e){w.v.debug("Failed to parse potential tool JSON:",e)}}}O=e}(O.includes("<|channel|>")||O.includes("<|message|>")||O.includes("<|end|>")||O.includes("<|start|>"))&&(O=O.replace(/<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|end\|><\|start\|>assistant<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|call\|>/g,"").replace(/\s+/g," ").trim()),Object.keys(E).length>0&&w.v.debug("[Orchestrator] Found ".concat(Object.keys(E).length," tool calls before validation"),Object.keys(E));let L=Object.values(E).map(e=>{var t;if(null==(t=e.function)?void 0:t.arguments)try{JSON.parse(e.function.arguments),w.v.debug("[Orchestrator] Tool call ".concat(e.id," validated successfully: ").concat(e.function.name))}catch(a){D&&w.v.warn("Incomplete tool arguments detected, attempting to fix");let t=e.function.arguments,n=(t.match(/{/g)||[]).length,r=(t.match(/}/g)||[]).length,i=(t.match(/\[/g)||[]).length,s=(t.match(/]/g)||[]).length,o="";for(let e=0;ew.v.error("Failed to update project cost:",e)),null==(j=this.onProgress)||j.call(this,"usage",{usage:T,totalCost:this.totalCost}),("openrouter"===t||t.includes("openrouter"))&&T.generationId&&!1!==T.isEstimated){let s=o.s.getProviderApiKey("openrouter");s&&c.I.queueGenerationForCostUpdate(T.generationId,s,this.projectId,t,e,(e,s)=>{let a=l.U.updateWithGenerationApiCost(T,{total_cost:e,native_tokens_total:s.native_tokens_total,native_tokens_prompt:s.native_tokens_prompt,native_tokens_completion:s.native_tokens_completion}),c=e-n;if(Math.abs(c)>1e-4){var d;this.totalCost+=c;let s=a.provider||t||"unknown";o.s.adjustSessionCost(s,c),this.projectId.startsWith("test-")||r.OP.applyProjectCostDelta(this.projectId,{costDelta:c,provider:s,sessionId:i}).catch(e=>w.v.error("Failed to apply corrected project cost:",e)),null==(d=this.onProgress)||d.call(this,"cost_correction",{originalCost:n,actualCost:e,difference:c,usage:a,totalCost:this.totalCost})}})}}return w.v.debug("[Orchestrator] Final response",{contentLength:O.length,toolCallsCount:L.length,toolCalls:L.map(e=>{var t,n,r;return{id:e.id,name:null==(t=e.function)?void 0:t.name,argsLength:null==(r=e.function)||null==(n=r.arguments)?void 0:n.length}})}),{content:O,toolCalls:L,usage:T}}async ensurePricing(e,t){var n;let r="".concat(e,":").concat(t);if(this.pricingEnsured.has(r))return;if("openrouter"!==e||o.s.getModelPricing("openrouter",t))return void this.pricingEnsured.add(r);let i=o.s.getCachedModels("openrouter");if((null==i||null==(n=i.models)?void 0:n.length)&&((0,S.V)("openrouter",i.models),o.s.getModelPricing("openrouter",t)))return void this.pricingEnsured.add(r);try{let e=await (0,j.QF)();(0,S.b)(e),o.s.getModelPricing("openrouter",t)&&this.pricingEnsured.add(r)}catch(e){w.v.warn("[Orchestrator] Failed to fetch pricing metadata",e)}}debug(){for(var e=arguments.length,t=Array(e),n=0;n0&&(p=this.buildFileTree(e))}catch(e){}let u=(0,h.m)(p);0===this.conversation.length&&this.conversation.push({role:"system",content:u}),this.conversation.push({role:"user",content:e});for(let e=0;e{var t,n,r;return{name:null==(t=e.function)?void 0:t.name,args:null==(r=e.function)||null==(n=r.arguments)?void 0:n.substring(0,100)}})}),!m.toolCalls||0===m.toolCalls.length){if(w.v.debug("[Orchestrator] No tool calls in response"),m.content&&m.content.trim()){this.conversation.push({role:"assistant",content:m.content});let e=m.content.toLowerCase();if(e.includes("complete")||e.includes("done")||e.includes("finished")){this.taskComplete=!0;break}if(0===this.stepsCompleted&&(this.noToolCallRetries++,w.v.debug("[Orchestrator] No progress made, retry ".concat(this.noToolCallRetries,"/2")),this.noToolCallRetries<=2)){this.conversation.push({role:"user",content:"Please proceed with the implementation using the shell tool."});continue}}if(this.noToolCallRetries++,w.v.debug("[Orchestrator] No tool calls, retry ".concat(this.noToolCallRetries,"/3")),this.noToolCallRetries<=3){this.conversation.push({role:"user",content:"Continue with the task. If you need to perform more operations, use the available tools."});continue}w.v.info("[Orchestrator] Breaking: no tool calls and max retries reached. Steps completed: ".concat(this.stepsCompleted));break}m.toolCalls&&m.toolCalls.length>0&&(w.v.debug("[Orchestrator] Sending ".concat(m.toolCalls.length," tool calls to UI")),null==(l=this.onProgress)||l.call(this,"toolCalls",{toolCalls:m.toolCalls}));try{r=await this.executeToolCalls(m.toolCalls,e),this.malformedToolCallRetries=0}catch(t){let e=t instanceof Error?t.message:String(t);if(w.v.error("[Orchestrator] Tool execution error:",e),e.includes("Malformed tool call")&&(this.malformedToolCallRetries++,w.v.debug("[Orchestrator] Malformed tool call, retry ".concat(this.malformedToolCallRetries,"/2")),this.malformedToolCallRetries<=2)){this.conversation.push({role:"user",content:"Error: ".concat(e,". Please fix the tool call format and try again.")});continue}throw t}if(m.content||m.toolCalls.length>0){let e={role:"assistant",content:m.content||""};m.toolCalls.length>0&&(e.tool_calls=m.toolCalls),this.conversation.push(e)}for(let e of r)this.conversation.push(e);this.accumulatedToolCalls.push(...m.toolCalls);let g=m.toolCalls.find(e=>{var t;return(null==(t=e.function)?void 0:t.name)==="evaluation"});if(g)try{let e=JSON.parse(g.function.arguments);if(this.evaluationResult={goalAchieved:e.goal_achieved||!1,reasoning:e.reasoning||""},null==(c=this.onProgress)||c.call(this,"divider",{title:"Evaluation"}),e.goal_achieved){w.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0;break}}catch(e){w.v.error("Failed to parse evaluation result:",e)}if(this.taskComplete||this.stepsCompleted>=50){w.v.info("[Orchestrator] Breaking: taskComplete=".concat(this.taskComplete,", steps=").concat(this.stepsCompleted));break}}w.v.info("[Orchestrator] Execution completed after ".concat(this.maxIterations," iterations max. Steps: ").concat(this.stepsCompleted));let m=this.generateSummary();return await this.recordAutoCheckpoint("After completion: ".concat(e.substring(0,60))),{success:this.stepsCompleted>0,summary:m,stepsCompleted:this.stepsCompleted,checkpointId:null!=(d=this.lastCheckpointId)?d:void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}catch(n){w.v.error("Orchestrator error:",n);let t=n instanceof Error?n.message:"Unknown error";try{await this.recordAutoCheckpoint("After failure: ".concat(e.substring(0,60)))}catch(e){w.v.warn("Failed to record checkpoint after error",e)}return{success:!1,summary:"Task failed: ".concat(t),stepsCompleted:this.stepsCompleted,checkpointId:null!=(p=this.lastCheckpointId)?p:void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}}async executeToolCalls(e,t){let n=[];for(let t=0;t0&&(t.push(n),n=""):n+=a}return n.length>0&&t.push(n),t}(e.cmd),w.v.debug('[Orchestrator] Converted string command "'.concat(e.cmd,'" to array:'),r);else if(Array.isArray(e.cmd))r=e.cmd;else throw Error('Malformed tool call - cmd must be string or array.\n\n✅ Natural format: {"cmd": "ls -la /"}\n✅ Array format: {"cmd": ["ls", "-la", "/"]}\n\nExamples:\n- {"cmd": "cat /index.html"} - Natural format\n- {"cmd": ["cat", "/index.html"]} - Array format\n- {"cmd": "ls -la /"} - Natural format \n- {"cmd": ["ls", "-la", "/"]} - Array format');w.v.debug("[Orchestrator] Executing shell command: ".concat(r[0])),w.v.debug("[Orchestrator] Routing to executeShellCommand");let i=await this.executeShellCommand(r);w.v.debug("[Orchestrator] Command result length:",null==i?void 0:i.length),n.push({role:"tool",tool_call_id:v,content:i}),this.stepsCompleted++;let s=i.startsWith("❌");null==(o=this.onProgress)||o.call(this,"tool_status",{toolIndex:t,status:s?"failed":"completed",result:i}),w.v.debug("[Orchestrator] Sending tool result for tool ".concat(t),{resultPreview:i.substring(0,100)}),null==(a=this.onProgress)||a.call(this,"tool_result",{toolIndex:t,toolId:v,result:i});let l=this.isWriteOperation(e.cmd),c=this.isFileStructureOperation(e.cmd);l?(this.lastIterationHadWrite=!0,await this.recordAutoCheckpoint("After step ".concat(this.stepsCompleted))):this.lastIterationHadWrite=!1,c&&this.triggerFileExplorerRefresh()}catch(r){let e=r instanceof Error?r.message:String(r);n.push({role:"tool",tool_call_id:v,content:"Error: ".concat(e)}),null==(l=this.onProgress)||l.call(this,"tool_status",{toolIndex:t,status:"failed",error:e})}else if("json_patch"===f)try{let e=JSON.parse(g.function.arguments);w.v.debug("[Orchestrator] Executing json_patch call for ".concat(e.file_path));let i=new r.r8;await i.init();let s=await x(i,this.projectId,e.file_path,e.operations);w.v.debug("[Orchestrator] String patch result:",s);let o=s.summary;s.warnings&&s.warnings.length>0&&(o+="\n\nWarnings:\n"+s.warnings.map(e=>"• ".concat(e)).join("\n")),n.push({role:"tool",tool_call_id:v,content:o}),this.stepsCompleted++,null==(c=this.onProgress)||c.call(this,"tool_status",{toolIndex:t,status:s.applied?"completed":"failed",result:o}),null==(d=this.onProgress)||d.call(this,"tool_result",{toolIndex:t,toolId:v,result:o}),s.applied&&(await this.recordAutoCheckpoint("After step ".concat(this.stepsCompleted)),this.triggerFileExplorerRefresh())}catch(r){let e=r instanceof Error?r.message:String(r);n.push({role:"tool",tool_call_id:v,content:"Error: ".concat(e)}),null==(p=this.onProgress)||p.call(this,"tool_status",{toolIndex:t,status:"failed",error:e})}else if("evaluation"===f)try{let e=JSON.parse(g.function.arguments);w.v.debug("[Orchestrator] Processing evaluation:",e),!0===e.goal_achieved&&(w.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0),n.push({role:"tool",tool_call_id:v,content:JSON.stringify(e)}),null==(u=this.onProgress)||u.call(this,"tool_status",{toolIndex:t,status:"completed",result:JSON.stringify(e)})}catch(e){n.push({role:"tool",tool_call_id:v,content:"Error parsing evaluation: ".concat(e)}),null==(h=this.onProgress)||h.call(this,"tool_status",{toolIndex:t,status:"failed",error:"Error parsing evaluation: ".concat(e)})}else{let e="Unknown tool: ".concat(f);w.v.warn("[Orchestrator] ".concat(e)),n.push({role:"tool",tool_call_id:v,content:"Error: ".concat(e)}),null==(m=this.onProgress)||m.call(this,"tool_status",{toolIndex:t,status:"failed",error:e})}}return n}async recordAutoCheckpoint(e){let t=await i.Y.createCheckpoint(this.projectId,e,{kind:"auto",baseRevisionId:s.$.getSavedCheckpointId(this.projectId)});return this.lastCheckpointId=t.id,t}async executeShellCommand(e){try{let t=await y.execute(this.projectId,e);if(t.success){let n=t.stdout&&t.stdout.trim().length>0?t.stdout:"Command succeeded with no output",r=e&&e.length>0?e[0]:void 0;if("cat"===r){let t=e.length>1?e[1]:void 0;if(t){let e=Date.now(),r=this.recentCatReads.get(t);if(r&&e-r<3e4){let e="Hint: You already read ".concat(t," recently; reuse that context unless the file changed.");n="".concat(e,"\n\n").concat(n)}let i=e-12e4;for(let[e,t]of this.recentCatReads)t=1;n--){let r=e[n];if(!r.startsWith("-")){t=r;break}}t&&n&&"Command succeeded with no output"!==n&&(n="Hint: Avoid numbering the entire ".concat(t,". Reuse the snippet you already captured or run targeted slices (e.g., sed -n '30,60p' ").concat(t," | nl -ba). No content streamed."))}return n}{let e=t.stderr&&t.stderr.trim().length>0?t.stderr:"Command failed";return"Error: ".concat(e)}}catch(t){let e=t instanceof Error?t.message:String(t);return"Error: ".concat(e)}}isWriteOperation(e){return!!e&&0!==e.length&&["mkdir","rm","rmdir","mv","cp"].includes(e[0])}isFileStructureOperation(e){return!!e&&0!==e.length&&["mv","rm","rmdir","cp","mkdir"].includes(e[0])}triggerFileExplorerRefresh(){window.dispatchEvent(new CustomEvent("filesChanged"))}buildFileTree(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]},r=function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=!(arguments.length>2)||void 0===arguments[2]||arguments[2],o=t.get(e);if(!o)return[];let a=[],l="/"===e?"":e.split("/").pop()||"";if("/"!==e){let e=o.isDirectory?l+"/":l,t=o.isDirectory?"":" (".concat(n(o.size||0),")");a.push(i+(s?"└── ":"├── ")+e+t)}let c=Array.from(o.children).sort((e,n)=>{let r=t.get(e),i=t.get(n);return(null==r?void 0:r.isDirectory)!==(null==i?void 0:i.isDirectory)?(null==r?void 0:r.isDirectory)?-1:1:e.localeCompare(n)});return c.forEach((t,n)=>{let o=n===c.length-1,l="/"===e?"":i+(s?" ":"│ ");a.push(...r(t,l,o))}),a},i=r("/");return i.length>0?"Project Structure:\n"+i.join("\n"):""}generateSummary(){if(this.evaluationResult)return this.evaluationResult.reasoning;if(0===this.stepsCompleted)return"No actions were taken.";let e=this.accumulatedToolCalls.filter(e=>{var t;return(null==(t=e.function)?void 0:t.name)==="shell"}).map(e=>{try{let t=JSON.parse(e.function.arguments);return this.getOperationDescription({name:"shell",parameters:t})}catch(e){return"Unknown operation"}});if(0===e.length)return"Completed ".concat(this.stepsCompleted," step").concat(1!==this.stepsCompleted?"s":"",".");let t=[...new Set(e)];return"Completed ".concat(this.stepsCompleted," step").concat(1!==this.stepsCompleted?"s":"",": ").concat(t.slice(0,3).join(", ")).concat(t.length>3?"...":"")}getOperationDescription(e){var t;if("shell"!==e.name)return e.name;let n=Array.isArray(null==(t=e.parameters)?void 0:t.cmd)?e.parameters.cmd:[];if(!n.length)return"Executed shell";let r=(n[0]||"").toLowerCase();switch(r){case"ls":return"Listed files";case"cat":return"Read ".concat(n[1]||"file");case"grep":return"Searched for patterns";case"find":return"Found files";case"mkdir":return"Created directory";case"rm":return"Removed ".concat(n[1]||"file");case"rmdir":return"Removed directory";case"mv":return"Moved ".concat(n[1]||"file");case"cp":return"Copied ".concat(n[1]||"file");default:return"Executed: ".concat(r)}}async performEvaluation(e){let t='Review the task and determine if it has been completed successfully.\n\nOriginal request: "'.concat(e,'"\n\nSteps completed: ').concat(this.stepsCompleted,"\nLast operation had write: ").concat(this.lastIterationHadWrite,"\n\nRecent conversation context:\n").concat(this.conversation.slice(-5).map(e=>{var t;return"".concat(e.role,": ").concat(null==(t=e.content)?void 0:t.substring(0,200),"...")}).join("\n"),'\n\nCRITICAL: You MUST respond with ONLY valid JSON in this exact format:\n{\n "reasoning": "Brief explanation of why goal was/wasn\'t achieved",\n "goal_achieved": true or false,\n "should_continue": true or false\n}\n\nDO NOT include any other text, explanations, or formatting outside the JSON object.'),{provider:n,apiKey:r,model:i}=this.getProviderConfig(),s=await this.streamLLMResponse([{role:"system",content:"You are an objective evaluator. Respond ONLY with the requested JSON format."},{role:"user",content:t}],[],n,r,i,{suppressAssistantDelta:!0,maxTokens:200});try{let e=JSON.parse(s.content||"{}");return{goalAchieved:!0===e.goal_achieved,reasoning:e.reasoning||"No reasoning provided",shouldContinue:!1!==e.should_continue}}catch(e){return w.v.error("Failed to parse evaluation result:",s.content),{goalAchieved:!1,reasoning:"Could not determine goal achievement",shouldContinue:this.stepsCompleted<3}}}constructor(e,t,n){this.totalCost=0,this.totalUsage={promptTokens:0,completionTokens:0,totalTokens:0,cost:0},this.conversation=[],this.stepsCompleted=0,this.taskComplete=!1,this.maxIterations=100,this.stopped=!1,this.accumulatedToolCalls=[],this.evaluationResult=null,this.malformedToolCallRetries=0,this.noToolCallRetries=0,this.lastIterationHadWrite=!1,this.lastCheckpointId=null,this.recentCatReads=new Map,this.pricingEnsured=new Set,this.projectId=e,this.onProgress=n,this.conversation=t||[]}}},5221:(e,t,n)=>{n.d(t,{g:()=>o});var r=n(5155),i=n(1362),s=n(2115);function o(e){let{width:t=64,height:n=64,className:o}=e,{resolvedTheme:a}=(0,i.D)(),[l,c]=(0,s.useState)(!1);return((0,s.useEffect)(()=>{c(!0)},[]),l)?(0,r.jsx)("div",{style:{width:t,height:n},className:"".concat(o," ").concat("light"===a?"[&_path]:fill-black":"[&_path]:fill-white"),dangerouslySetInnerHTML:{__html:' '}}):(0,r.jsx)("div",{style:{width:t,height:n}})}},5337:(e,t,n)=>{n.d(t,{Gr:()=>s,N$:()=>o,Q6:()=>i,fu:()=>a});let r={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"]},i={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(r))if(t.includes(n||""))return e;return"text"}function o(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 a(e){var t;let n=null==(t=e.split(".").pop())?void 0:t.toLowerCase();for(let e of Object.values(r))if(e.includes(n||""))return!0;return!1}},5784:(e,t,n)=>{n.d(t,{bq:()=>p,eb:()=>h,gC:()=>u,l6:()=>c,yv:()=>d});var r=n(5155);n(2115);var i=n(4582),s=n(6474),o=n(5196),a=n(7863),l=n(3999);function c(e){let{...t}=e;return(0,r.jsx)(i.bL,{"data-slot":"select",...t})}function d(e){let{...t}=e;return(0,r.jsx)(i.WT,{"data-slot":"select-value",...t})}function p(e){let{className:t,size:n="default",children:o,...a}=e;return(0,r.jsxs)(i.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),...a,children:[o,(0,r.jsx)(i.In,{asChild:!0,children:(0,r.jsx)(s.A,{className:"size-4 opacity-50"})})]})}function u(e){let{className:t,children:n,position:s="popper",...o}=e;return(0,r.jsx)(i.ZL,{children:(0,r.jsxs)(i.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,...o,children:[(0,r.jsx)(m,{}),(0,r.jsx)(i.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,r.jsx)(g,{})]})})}function h(e){let{className:t,children:n,...s}=e;return(0,r.jsxs)(i.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,r.jsx)("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,r.jsx)(i.VF,{children:(0,r.jsx)(o.A,{className:"size-4"})})}),(0,r.jsx)(i.p4,{children:n})]})}function m(e){let{className:t,...n}=e;return(0,r.jsx)(i.PP,{"data-slot":"select-scroll-up-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...n,children:(0,r.jsx)(a.A,{className:"size-4"})})}function g(e){let{className:t,...n}=e;return(0,r.jsx)(i.wn,{"data-slot":"select-scroll-down-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...n,children:(0,r.jsx)(s.A,{className:"size-4"})})}},7015:(e,t,n)=>{n.d(t,{$:()=>a});var r=n(7150),i=n(4520),s=n(3999);class o{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 i.OP.init();let o=await i.OP.getProject(e),a="Manual save @ ".concat(new Date().toLocaleTimeString()),l=await r.Y.createCheckpoint(e,t||a,{kind:"manual",baseRevisionId:null!=(n=o.lastSavedCheckpointId)?n:null,replaceId:null!=(s=o.lastSavedCheckpointId)?s:null});return o.lastSavedCheckpointId=l.id,o.lastSavedAt=new Date(l.timestamp),await i.OP.updateProject(o),this.manualCheckpoints.set(e,l.id),this.markClean(e),l}async restoreLastSaved(e){await i.OP.init();let t=(await i.OP.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 r.Y.checkpointExists(t))return s.v.warn("[SaveManager] Saved checkpoint missing",{projectId:e,checkpointId:t}),!1;let n=await r.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 i.OP.init();let t=await i.OP.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 a=new o},7150:(e,t,n)=>{n.d(t,{Y:()=>o});var r=n(4520),i=n(3999);class s{arrayBufferToBase64(e){let t=new Uint8Array(e),n="";for(let e=0;e{let n=indexedDB.open(this.dbName,1);n.onerror=()=>{i.v.error("Failed to open checkpoint database"),t(n.error)},n.onsuccess=()=>{this.db=n.result,this.isInitialized=!0,this.loadCheckpointsFromDB().then(()=>e())},n.onupgradeneeded=e=>{let t=e.target.result;if(!t.objectStoreNames.contains(this.storeName)){let e=t.createObjectStore(this.storeName,{keyPath:"id"});e.createIndex("projectId","projectId",{unique:!1}),e.createIndex("timestamp","timestamp",{unique:!1})}}})}async loadCheckpointsFromDB(){if(this.db)return new Promise((e,t)=>{let n=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).getAll();n.onsuccess=()=>{let t=n.result;for(let e of(this.checkpoints.clear(),t)){var r;let t={...e,kind:e.kind||"auto",baseRevisionId:null!=(r=e.baseRevisionId)?r:null,files:new Map(e.files),directories:new Set(e.directories)};this.checkpoints.set(t.id,t)}e()},n.onerror=()=>{i.v.error("Failed to load checkpoints from DB"),t(n.error)}})}async saveCheckpointToDB(e){var t;if(await this.initDB(),!this.db)return;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 r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(n);r.onsuccess=()=>e(),r.onerror=()=>{i.v.error("Failed to save checkpoint to DB"),t(r.error)}})}async deleteCheckpointFromDB(e){if(await this.initDB(),this.db)return new Promise((t,n)=>{let r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(e);r.onsuccess=()=>t(),r.onerror=()=>{i.v.error("Failed to delete checkpoint from DB"),n(r.error)}})}async createCheckpoint(e,t){var n;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};await this.initDB(),await r.OP.init();let o=await r.OP.listDirectory(e,"/"),a=new Map,l=new Set;for(let t of o){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)a.set(t.path,t.content);else if(t.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(t.content);a.set(t.path,{data:e,encoding:"base64"})}else try{let n=await r.OP.readFile(e,t.path);if("string"==typeof n.content)a.set(t.path,n.content);else if(n.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(n.content);a.set(t.path,{data:e,encoding:"base64"})}}catch(e){i.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:a,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 i.v.error("[Checkpoint] Invalid checkpoint ID type:",typeof e,e),!1;if(!e.startsWith("cp_")||e.length<6)return i.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 i.v.error("[Checkpoint] Checkpoint not found in database: ".concat(e)),Array.from(this.checkpoints.keys()),!1;await r.OP.init();try{let n=await r.OP.listDirectory(t.projectId,"/"),i=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("/");i.add(n)}}for(let e of n)t.files.has(e.path)||await r.OP.deleteFile(t.projectId,e.path);for(let e of Array.from(i).filter(e=>!t.directories||!t.directories.has(e)).sort((e,t)=>t.length-e.length))try{await r.OP.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(!i.has(e))try{await r.OP.createDirectory(t.projectId,e)}catch(e){}}for(let[e,i]of t.files){let s;s="object"==typeof i&&"base64"===i.encoding?this.base64ToArrayBuffer(i.data):i,n.some(t=>t.path===e)?await r.OP.updateFile(t.projectId,e,s):await r.OP.createFile(t.projectId,e,s)}return this.currentCheckpoint=e,!0}catch(e){return i.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,r]of this.checkpoints)r.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.dbName="DeepStudioCheckpoints",this.storeName="checkpoints",this.db=null,this.isInitialized=!1}}let o=new s},7168:(e,t,n)=>{n.d(t,{$:()=>l});var r=n(5155);n(2115);var i=n(9708),s=n(2085),o=n(3999);let a=(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?i.DX:"button";return(0,r.jsx)(d,{"data-slot":"button",className:(0,o.cn)(a({variant:n,size:s,className:t})),...c})}},7250:(e,t,n)=>{n.d(t,{t:()=>R});var r=n(5155),i=n(2115),s=n(8202),o=n(1052),a=n(86),l=n(1173),c=n(3999);class d{getDefaultModel(){switch(this.provider){case"openrouter":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"qwen/qwen3-4b-thinking-2507";case"sambanova":return"Meta-Llama-3.3-70B-Instruct";default:return""}}async generateWithTools(e,t,n){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error("".concat(this.providerConfig.name," API key is required. Please set it in settings."));let r=[{role:"system",content:(0,o.m)(null==n?void 0:n.fileTree)},{role:"user",content:e}];try{if("anthropic"===this.provider)return this.generateWithToolsAnthropic(r,t);if("gemini"===this.provider)return this.generateWithToolsGemini(r,t);return this.generateWithToolsOpenAI(r,t)}catch(e){throw e}}async generate(e,t){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error("".concat(this.providerConfig.name," API key is required. Please set it in settings."));let n=[{role:"system",content:(0,o.m)(null==t?void 0:t.fileTree)},{role:"user",content:e}];return"anthropic"===this.provider?this.generateAnthropic(n):"gemini"===this.provider?this.generateGemini(n):this.generateOpenAI(n)}async generateWithToolsOpenAI(e,t){let n=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",r={"Content-Type":"application/json"};this.apiKey&&(r.Authorization="Bearer ".concat(this.apiKey)),"openrouter"===this.provider&&(r["HTTP-Referer"]=window.location.origin,r["X-Title"]="DeepStudio"),this.providerConfig.customHeaders&&Object.assign(r,this.providerConfig.customHeaders);let i=await fetch("".concat(n,"/chat/completions"),{method:"POST",headers:r,body:JSON.stringify({model:this.model,messages:e,tools:t.map(e=>({type:"function",function:e})),tool_choice:"auto",temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})});if(!i.ok){let e=await i.text();throw Error("".concat(this.providerConfig.name," API error: ").concat(e))}return this.parseStreamResponse(i)}async generateOpenAI(e){var t,n;let r=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization="Bearer ".concat(this.apiKey)),"openrouter"===this.provider&&(i["HTTP-Referer"]=window.location.origin,i["X-Title"]="DeepStudio");let s=await fetch("".concat(r,"/chat/completions"),{method:"POST",headers:i,body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature,max_tokens:this.maxTokens,stream:!1})});if(!s.ok){let e=await s.text();throw Error("".concat(this.providerConfig.name," API error: ").concat(e))}return(null==(n=(await s.json()).choices[0])||null==(t=n.message)?void 0:t.content)||""}async generateWithToolsAnthropic(e,t){var n;let r=(null==(n=e.find(e=>"system"===e.role))?void 0:n.content)||"",i=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),s=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-beta":"tools-2024-04-04"},body:JSON.stringify({model:this.model,messages:i,system:r,tools:t.map(e=>({name:e.name,description:e.description,input_schema:e.parameters})),temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})});if(!s.ok){let e=await s.text();throw Error("Anthropic API error: ".concat(e))}return this.parseAnthropicStream(s)}async generateAnthropic(e){var t,n;let r=(null==(t=e.find(e=>"system"===e.role))?void 0:t.content)||"",i=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),s=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.model,messages:i,system:r,temperature:this.temperature,max_tokens:this.maxTokens})});if(!s.ok){let e=await s.text();throw Error("Anthropic API error: ".concat(e))}return(null==(n=(await s.json()).content[0])?void 0:n.text)||""}async generateWithToolsGemini(e,t){throw Error("Gemini tool calling not yet implemented. Please use OpenRouter or another provider.")}async generateGemini(e){var t,n,r;let i=e.map(e=>({role:"system"===e.role?"user":e.role,parts:[{text:e.content}]})),s=await fetch("https://generativelanguage.googleapis.com/v1beta/models/".concat(this.model,":generateContent?key=").concat(this.apiKey),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:i,generationConfig:{temperature:this.temperature,maxOutputTokens:this.maxTokens}})});if(!s.ok){let e=await s.text();throw Error("Gemini API error: ".concat(e))}return(null==(r=(await s.json()).candidates[0])||null==(n=r.content)||null==(t=n.parts[0])?void 0:t.text)||""}async *parseStreamResponse(e){var t,n,r,i,s,o,a,d,p,u,h,m,g,f;let v=null==(t=e.body)?void 0:t.getReader();if(!v)throw Error("Response body is not readable");let y=new TextDecoder,w="",x=null,b=null,C=null;if("openrouter"===this.provider){let t=e.headers;C=l.I.extractGenerationId(t);let u=l.I.extractCostFromHeaders(t);if((null==u?void 0:u.cost)!==void 0||(null==u?void 0:u.usage)){let e=null!=(o=null==(n=u.usage)?void 0:n.prompt_tokens)?o:0,t=null!=(a=null==(r=u.usage)?void 0:r.completion_tokens)?a:0,l=null!=(d=null==(i=u.usage)?void 0:i.total_tokens)?d:e+t,c=null!=(p=u.cost)?p:null==(s=u.usage)?void 0:s.total_cost,h="number"==typeof c&&Number.isFinite(c)&&c>1e-6;b={promptTokens:e,completionTokens:t,totalTokens:l,cost:h?c:void 0,model:this.model,provider:this.provider,generationId:C||void 0,isEstimated:!h}}if(!b){let e=t.get("x-openrouter-usage");if(e)try{let t=JSON.parse(e),n=t.total_cost,r="number"==typeof n&&Number.isFinite(n)&&n>1e-6;b={promptTokens:t.prompt_tokens||0,completionTokens:t.completion_tokens||0,totalTokens:t.total_tokens||(t.prompt_tokens||0)+(t.completion_tokens||0),cost:r?n:void 0,model:this.model,provider:this.provider,generationId:C||void 0,isEstimated:!r}}catch(e){c.v.error("Error parsing OpenRouter usage header:",e)}}}for(;;){let{done:e,value:t}=await v.read();if(e)break;let n=(w+=y.decode(t,{stream:!0})).split("\n");for(let e of(w=n.pop()||"",n))if(e.startsWith("data: ")){let t=e.slice(6);if("[DONE]"===t){b&&b.totalTokens&&(yield{type:"usage",usage:b}),yield{type:"done"};return}try{let e=JSON.parse(t),n=null==(h=e.choices)||null==(u=h[0])?void 0:u.delta;if((null==n?void 0:n.content)&&(yield{type:"content",content:n.content}),null==n?void 0:n.tool_calls)for(let e of n.tool_calls)e.id&&(x&&(yield{type:"tool_call",toolCall:x}),x={id:e.id,type:"function",function:{name:(null==(f=e.function)?void 0:f.name)||"",arguments:""}}),(null==(g=e.function)?void 0:g.arguments)&&x&&(x.argumentsBuffer=(x.argumentsBuffer||"")+e.function.arguments,x.function&&(x.function.arguments=x.argumentsBuffer));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:this.model,provider:this.provider,generationId:C||void 0}),(null==(m=e.x_groq)?void 0:m.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:this.model,provider:this.provider})}catch(e){c.v.error("Error parsing stream chunk:",e)}}}if(x)try{let e=x.argumentsBuffer;e&&x.function&&(x.function.arguments=e),yield{type:"tool_call",toolCall:x}}catch(e){c.v.error("Error parsing tool call parameters:",e)}b&&b.totalTokens&&(yield{type:"usage",usage:b}),yield{type:"done"}}async *parseAnthropicStream(e){var t,n,r,i,s;let o=null==(t=e.body)?void 0:t.getReader();if(!o)throw Error("Response body is not readable");let a=new TextDecoder,l="",d=null;for(;;){let{done:e,value:t}=await o.read();if(e)break;let p=(l+=a.decode(t,{stream:!0})).split("\n");for(let e of(l=p.pop()||"",p))if(e.startsWith("data: ")){let t=e.slice(6);try{let e=JSON.parse(t);if("content_block_delta"===e.type&&(null==(r=e.delta)||null==(n=r.text_delta)?void 0:n.text))yield{type:"content",content:e.delta.text_delta.text};else if("content_block_start"===e.type&&(null==(i=e.content_block)?void 0:i.type)==="tool_use")yield{type:"tool_call",toolCall:{id:e.content_block.id,type:"function",function:{name:e.content_block.name,arguments:JSON.stringify(e.content_block.input||{})}}};else if("message_start"===e.type&&(null==(s=e.message)?void 0:s.usage))d={promptTokens:e.message.usage.input_tokens||0,completionTokens:e.message.usage.output_tokens||0,totalTokens:(e.message.usage.input_tokens||0)+(e.message.usage.output_tokens||0),cachedTokens:e.message.usage.cache_creation_input_tokens||e.message.usage.cache_read_input_tokens,model:this.model,provider:this.provider};else if("message_delta"===e.type&&e.usage)d&&(d.completionTokens=e.usage.output_tokens||d.completionTokens,d.totalTokens=(d.promptTokens||0)+(d.completionTokens||0));else if("message_stop"===e.type){d&&d.totalTokens&&(yield{type:"usage",usage:d}),yield{type:"done"};return}}catch(e){c.v.error("Error parsing Anthropic stream:",e)}}}d&&d.totalTokens&&(yield{type:"usage",usage:d}),yield{type:"done"}}static async validateApiKey(e,t){if(!e)return!1;try{let n=await fetch("/api/validate-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,provider:t})});if(!n.ok)return!1;let{valid:r}=await n.json();return r}catch(e){return!1}}static async getAvailableModels(e,t){var n,r;let i=t||s.s.getSelectedProvider()||"openrouter",o=(0,a.sO)(i),l=e||s.s.getProviderApiKey(i);if(!o.supportsModelDiscovery&&o.models)return o.models.map(e=>e.id);try{let e=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,provider:i})});if(!e.ok)return(null==(n=o.models)?void 0:n.map(e=>e.id))||[];let{models:t}=await e.json();return t||[]}catch(e){return(null==(r=o.models)?void 0:r.map(e=>e.id))||[]}}constructor(e){this.provider=(null==e?void 0:e.provider)||s.s.getSelectedProvider()||"openrouter",this.providerConfig=(0,a.sO)(this.provider),this.apiKey=(null==e?void 0:e.apiKey)||s.s.getProviderApiKey(this.provider)||"",this.model=(null==e?void 0:e.model)||s.s.getProviderModel(this.provider)||this.getDefaultModel(),this.temperature=(null==e?void 0:e.temperature)||.7,this.maxTokens=(null==e?void 0:e.maxTokens)||4096}}var p=n(7168),u=n(9852),h=n(2714),m=n(8749),g=n(2657),f=n(5196),v=n(4416),y=n(3786),w=n(6671),x=n(8145),b=n(823),C=n(9376),k=n(3311),S=n(1539),j=n(2970),_=n(5487),T=n(3314),I=n(1154),P=n(6474),A=n(7924),N=n(4973),O=n(3091);function E(e){let{provider:t,value:n,onChange:o,className:l,hideModelDetails:m}=e,g=t||s.s.getSelectedProvider(),f=(0,a.sO)(g),[y,E]=(0,i.useState)([]),[F,R]=(0,i.useState)(!0),[D,M]=(0,i.useState)(""),[U,L]=(0,i.useState)(!1),[B,W]=(0,i.useState)(""),[q,H]=(0,i.useState)(!1),z=e=>e.name,K=(0,i.useCallback)(async()=>{try{R(!0);let e=s.s.getProviderApiKey(g);if(f.apiKeyRequired&&!e){H(!0),f.models?E(f.models):E([]);return}H(!1);let t=s.s.getCachedModels(g);if(t){let e=t.models;E(e),"openrouter"===g&&(0,O.V)("openrouter",e);return}let n=[];if("openrouter"===g){let e=await (0,N.QF)();(0,O.b)(e);let t=e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=["description","name","summary"].map(t=>e[t]).find(e=>"string"==typeof e);if(t)return t;try{return JSON.stringify(e)}catch(e){}}return null==e?"":String(e)};n=e.map(e=>{var n,r,i,s,o,a,l;let c=(null==(n=e.pricing)?void 0:n.prompt)?Number(e.pricing.prompt):void 0,d=(null==(r=e.pricing)?void 0:r.completion)?Number(e.pricing.completion):void 0,p=(null==(i=e.pricing)?void 0:i.internal_reasoning)?Number(e.pricing.internal_reasoning):void 0,u=e=>{if(void 0!==e&&Number.isFinite(e))return 1e6*e},h=u(c),m=u(d),g=u(p);return{id:e.id,name:e.name,description:t(e.description),contextLength:e.context_length,maxTokens:null==(s=e.top_provider)?void 0:s.max_completion_tokens,supportsFunctions:null==(o=e.supported_parameters)?void 0:o.includes("tools"),supportsVision:null==(l=e.architecture)||null==(a=l.input_modalities)?void 0:a.includes("image"),pricing:void 0!==h&&void 0!==m?{input:h,output:m,reasoning:g}:void 0}})}else n=f.supportsModelDiscovery?(await d.getAvailableModels(e||void 0,g)).map(e=>({id:e,name:e.split("/").pop()||e,contextLength:32e3,supportsFunctions:!0})):f.models?f.models:[];E(n),f.isLocal&&0===n.length&&w.oR.warning("No models found in ".concat(f.name,". Please load some models in the application."),{duration:5e3}),n.length>0&&(s.s.setCachedModels(g,n),"openrouter"===g&&(0,O.V)("openrouter",n))}catch(e){c.v.error("Failed to load models:",e),f.isLocal&&w.oR.error("".concat(f.name," server not running. Please start the server and load some models."),{duration:5e3}),f.models&&E(f.models)}finally{R(!1)}},[g,f]);(0,i.useEffect)(()=>{E([]),M(""),R(!0),s.s.clearModelCache(g),K()},[g,K]),(0,i.useEffect)(()=>{if(0===y.length||F)return;let e=s.s.getProviderModel(g);if(e&&y.some(t=>t.id===e))M(e),null==o||o(e);else{var t;let e=null==(t=y[0])?void 0:t.id;e&&(M(e),s.s.setProviderModel(g,e),null==o||o(e))}},[y,F,g,o]),(0,i.useEffect)(()=>{let e=()=>{setTimeout(()=>{K()},100)};return window.addEventListener("apiKeyUpdated",e),()=>{window.removeEventListener("apiKeyUpdated",e)}},[K]);let G=e=>{M(e),s.s.setProviderModel(g,e),null==o||o(e),L(!1),W("")},J=e=>{let t=e.id.toLowerCase();return t.includes("deepseek")?(0,r.jsx)(C.A,{className:"h-3 w-3"}):t.includes("claude")?(0,r.jsx)(k.A,{className:"h-3 w-3"}):t.includes("gpt")?(0,r.jsx)(S.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,r.jsx)(j.A,{className:"h-3 w-3"}):t.includes("llama")?(0,r.jsx)(_.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,r.jsx)(T.A,{className:"h-3 w-3"}):null},$=e=>{let t=e.toLowerCase();return t.includes("deepseek")?"bg-blue-500/10 text-blue-500":t.includes("claude")?"bg-orange-500/10 text-orange-500":t.includes("openai")||t.includes("gpt")?"bg-green-500/10 text-green-500":t.includes("qwen")?"bg-orange-500/10 text-orange-500":t.includes("google")?"bg-red-500/10 text-red-500":t.includes("meta")?"bg-indigo-500/10 text-indigo-500":"bg-gray-500/10 text-gray-500"},V=(0,i.useMemo)(()=>{if(!B.trim())return y;let e=B.toLowerCase();return y.filter(t=>{let n=t.id.toLowerCase(),r=z(t).toLowerCase(),i=t.id.split("/")[0].toLowerCase();return n.includes(e)||r.includes(e)||i.includes(e)})},[y,B]),Y=y.find(e=>e.id===D);return F?(0,r.jsxs)("div",{className:l,children:[(0,r.jsx)(h.J,{children:"AI Model"}),(0,r.jsxs)("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted",children:[(0,r.jsx)(I.A,{className:"h-4 w-4 animate-spin"}),(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):q?(0,r.jsxs)("div",{className:l,children:[(0,r.jsx)(h.J,{children:"AI Model"}),(0,r.jsx)("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted/50 border-orange-200 dark:border-orange-800",children:(0,r.jsxs)("span",{className:"text-sm text-orange-600 dark:text-orange-400",children:["API key required for ",f.name]})}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Set your API key in settings to load available models"})]}):(0,r.jsxs)("div",{className:l,children:[(0,r.jsx)(h.J,{htmlFor:"model-select",children:"AI Model"}),(0,r.jsxs)(b.AM,{open:U,onOpenChange:L,children:[(0,r.jsx)(b.Wv,{asChild:!0,children:(0,r.jsxs)(p.$,{variant:"outline",role:"combobox","aria-expanded":U,className:"w-full justify-between font-normal",children:[Y?(0,r.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[J(Y),(0,r.jsx)("span",{className:"truncate",children:z(Y)})]}):(0,r.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,r.jsx)(P.A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),(0,r.jsxs)(b.hl,{className:"w-[32rem] p-0",align:"start",side:"bottom",sideOffset:5,avoidCollisions:!1,children:[(0,r.jsxs)("div",{className:"flex items-center border-b px-3",children:[(0,r.jsx)(A.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,r.jsx)(u.p,{placeholder:"Search models...",value:B,onChange:e=>W(e.target.value),className:"h-10 border-0 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),B&&(0,r.jsx)(p.$,{variant:"ghost",size:"sm",onClick:()=>W(""),className:"h-5 w-5 p-0",children:(0,r.jsx)(v.A,{className:"h-3 w-3"})})]}),(0,r.jsx)("div",{className:"max-h-[400px] min-h-[300px] overflow-y-auto",children:0===V.length?(0,r.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):V.map(e=>(0,r.jsx)("button",{onClick:()=>G(e.id),className:(0,c.cn)("w-full text-left px-3 py-3 hover:bg-accent hover:text-accent-foreground transition-colors",D===e.id&&"bg-accent"),children:(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[J(e),(0,r.jsx)("span",{className:"font-medium",children:z(e)}),"openrouter"===g&&(0,r.jsx)(x.E,{variant:"secondary",className:"text-xs ".concat($(e.id)),children:e.id.split("/")[0]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[(0,r.jsxs)("span",{children:["Context: ",Math.round(e.contextLength/1e3),"K"]}),e.pricing&&(0===e.pricing.input&&0===e.pricing.output?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:"•"}),(0,r.jsx)("span",{children:"Free"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:"•"}),(0,r.jsxs)("span",{children:[(0,N.WK)(e.pricing.input),"/K | ",(0,N.WK)(e.pricing.output),"/K"]})]})),!e.pricing&&"openrouter"!==g&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:"•"}),(0,r.jsx)("span",{children:"Pricing varies"})]})]})]})},e.id))})]})]}),!m&&Y&&(0,r.jsxs)("div",{className:"mt-1 text-xs text-muted-foreground max-h-[150px] overflow-y-auto pr-2",children:[(0,r.jsx)("div",{className:"font-medium mb-1",children:Y.pricing?0===Y.pricing.input&&0===Y.pricing.output?"Free":"Input: ".concat((0,N.WK)(Y.pricing.input),"/K • Output: ").concat((0,N.WK)(Y.pricing.output),"/K"):"Pricing varies by provider"}),Y.description&&(0,r.jsx)("div",{children:Y.description})]})]})}var F=n(5784);function R(e){let{onClose:t,onModelChange:n}=e,[o,l]=(0,i.useState)({}),[c,x]=(0,i.useState)(()=>s.s.getSelectedProvider()),[b,C]=(0,i.useState)(!1),[k,S]=(0,i.useState)(!1),[j,_]=(0,i.useState)(null),[T,I]=(0,i.useState)("");(0,i.useEffect)(()=>{l(s.s.getSettings());let e=s.s.getSelectedProvider();I(s.s.getProviderApiKey(e)||"")},[]),(0,i.useEffect)(()=>{I(s.s.getProviderApiKey(c)||""),_(null)},[c]);let P=e=>{I(e),s.s.setProviderApiKey(c,e),_(null),s.s.clearModelCache(c),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:c,hasKey:!!e}}))},A=async()=>{if(!T)return void w.oR.error("Please enter an API key");S(!0);try{let e=await d.validateApiKey(T,c);_(e),e?w.oR.success("API key is valid!"):w.oR.error("Invalid API key")}catch(e){_(!1),w.oR.error("Failed to validate API key")}finally{S(!1)}},N=(0,a.sO)(c);return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"font-medium text-sm",children:"Model Settings"}),(0,r.jsx)("p",{className:"text-muted-foreground text-xs mt-1",children:"Configure your AI model and API connection"})]}),(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)(h.J,{htmlFor:"provider",children:"AI Provider"}),(0,r.jsxs)(F.l6,{value:c,onValueChange:e=>{x(e),s.s.setSelectedProvider(e),I(s.s.getProviderApiKey(e)||""),_(null)},children:[(0,r.jsx)(F.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,r.jsx)(F.yv,{placeholder:"Select a provider",children:c&&(0,r.jsxs)("div",{className:"flex flex-col text-left",children:[(0,r.jsx)("span",{className:"font-medium",children:N.name}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:N.description})]})})}),(0,r.jsx)(F.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,r.jsx)(F.eb,{value:e.id,children:(0,r.jsxs)("div",{className:"flex flex-col",children:[(0,r.jsx)("span",{className:"font-medium",children:e.name}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:e.description})]})},e.id))})]})]}),(N.apiKeyRequired||N.isLocal)&&(0,r.jsxs)("div",{children:[(0,r.jsxs)(h.J,{htmlFor:"api-key",children:[N.name," API Key",!N.apiKeyRequired&&(0,r.jsx)("span",{className:"text-muted-foreground text-xs ml-1",children:"(optional)"})]}),(0,r.jsxs)("div",{className:"flex gap-2 mt-2",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)(u.p,{id:"api-key",type:b?"text":"password",value:T,onChange:e=>P(e.target.value),placeholder:N.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,r.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>C(!b),children:b?(0,r.jsx)(m.A,{className:"h-4 w-4"}):(0,r.jsx)(g.A,{className:"h-4 w-4"})})]}),(0,r.jsx)(p.$,{onClick:A,disabled:k||!T,size:"sm",children:k?"Validating...":"Validate"}),null!==j&&(0,r.jsx)("div",{className:"flex items-center",children:j?(0,r.jsx)(f.A,{className:"h-5 w-5 text-green-500"}):(0,r.jsx)(v.A,{className:"h-5 w-5 text-red-500"})})]}),N.apiKeyHelpUrl&&(0,r.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,r.jsxs)("a",{href:N.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[N.name," ",(0,r.jsx)(y.A,{className:"h-3 w-3"})]})]}),N.isLocal&&!N.apiKeyRequired&&(0,r.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",N.name,". Only needed if you've configured authentication on your local server."]})]}),!N.apiKeyRequired&&N.isLocal&&(0,r.jsxs)("div",{className:"text-sm text-muted-foreground p-3 border rounded-md bg-muted/50",children:[(0,r.jsx)("p",{className:"font-medium mb-1",children:"Local Provider"}),(0,r.jsxs)("p",{children:["Make sure ",N.name," is running on your machine."]}),(0,r.jsxs)("p",{children:["Default endpoint: ",(0,r.jsx)("code",{className:"text-xs",children:N.baseUrl})]}),"lmstudio"===c&&(0,r.jsxs)("div",{className:"mt-2 text-xs",children:[(0,r.jsx)("p",{className:"font-medium",children:"For tool use support:"}),(0,r.jsx)("p",{children:"• Load a model like qwen/qwen3-4b-thinking-2507"}),(0,r.jsx)("p",{children:"• Start the local server in LM Studio"}),(0,r.jsx)("p",{children:"• Models will be automatically discovered"})]})]}),(0,r.jsx)(E,{provider:c,onChange:e=>{null==n||n(e)},className:"space-y-2"})]}),t&&(0,r.jsx)("div",{className:"flex justify-end pt-4 border-t",children:(0,r.jsx)(p.$,{onClick:t,size:"sm",children:"Done"})})]})}},8145:(e,t,n)=>{n.d(t,{E:()=>a});var r=n(5155);n(2115);var i=n(2085),s=n(3999);let o=(0,i.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 a(e){let{className:t,variant:n,...i}=e;return(0,r.jsx)("div",{className:(0,s.cn)(o({variant:n}),t),...i})}},8202:(e,t,n)=>{n.d(t,{s:()=>i});class r{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,r;let i=null==(n=this.getSettings().modelPricing)?void 0:n[e];return i&&(i[t]||i["".concat(e,"/").concat(t)]||(t.includes("/")?i[null!=(r=t.split("/").pop())?r:""]:null))||null}setModelPricing(e,t,n){let r={...this.getSettings().modelPricing||{}},i={...r[e]||{}};i[t]=n,r[e]=i,this.setSetting("modelPricing",r)}setProviderPricing(e,t){if(!t||0===Object.keys(t).length)return;let n={...this.getSettings().modelPricing||{}},r={...n[e]||{}};for(let[e,n]of Object.entries(t))r[e]=n;n[e]=r,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 r={...n.modelPricing||{}};delete r[e],this.setSetting("modelPricing",r)}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("deepstudio-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 r=e.provider||"unknown";n.providerBreakdown[r]||(n.providerBreakdown[r]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),n.providerBreakdown[r].cost+=t,n.providerBreakdown[r].tokenUsage.input+=e.promptTokens,n.providerBreakdown[r].tokenUsage.output+=e.completionTokens,n.providerBreakdown[r].requestCount+=1;let i=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};i.total+=t,i.byProvider[r]=(i.byProvider[r]||0)+t,this.setSetting("currentSession",n),this.setSetting("lifetimeCosts",i)}adjustSessionCost(e,t,n){if(!t&&!n)return;let r=this.getCurrentSession();if(!r)return;let i=e||"unknown";r.totalCost+=t,r.providerBreakdown[i]||(r.providerBreakdown[i]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),r.providerBreakdown[i].cost+=t,n&&(r.providerBreakdown[i].tokenUsage.input+=n.input,r.providerBreakdown[i].tokenUsage.output+=n.output);let s=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};s.total+=t,s.byProvider[i]=(s.byProvider[i]||0)+t,this.setSetting("currentSession",r),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(),r=new Date,i=new Date(r.getTime()+864e5),s=n.modelCache||{};s[e]={models:t,timestamp:r.toISOString(),expiresAt:i.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="deepstudio-settings"}}let i=new r},9852:(e,t,n)=>{n.d(t,{p:()=>s});var r=n(5155);n(2115);var i=n(3999);function s(e){let{className:t,type:n,...s}=e;return(0,r.jsx)("input",{type:n,"data-slot":"input",className:(0,i.cn)("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","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",t),...s})}},9945:(e,t,n)=>{n.d(t,{j:()=>d});var r=n(5155),i=n(2115),s=n(7168),o=n(8145),a=n(5221),l=n(7863),c=n(6474);function d(e){let{title:t,subtitle:n,badge:d,onLogoClick:p,actions:u=[],mobileMenuContent:h,desktopOnlyContent:m,className:g="",leftText:f}=e,[v,y]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"border-b bg-card shadow-sm relative z-20 ".concat(g),children:[(0,r.jsxs)("div",{className:"px-3 py-2 flex items-center justify-between",children:[(0,r.jsxs)("button",{onClick:p,className:"flex items-center gap-2 p-1 pr-2 hover:ring-1 hover:ring-border rounded-sm transition-all",children:[(0,r.jsx)(a.g,{width:24,height:24}),f&&(0,r.jsx)("span",{className:"font-semibold text-lg hidden md:inline",children:f})]}),(0,r.jsx)("div",{className:"flex items-center gap-2 flex-1 justify-center md:justify-start md:ml-6",children:f?(0,r.jsx)("h1",{className:"text-lg font-semibold md:hidden",children:f}):t?(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsx)("h1",{className:"text-lg md:text-xl font-semibold",children:t}),d&&(0,r.jsx)(o.E,{variant:"secondary",children:d})]}):null}),!f&&!t&&n&&(0,r.jsx)("div",{className:"hidden md:flex items-center flex-1 ml-6",children:(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:n})}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("div",{className:"hidden md:flex items-center gap-2",children:[u.map(e=>e.content?(0,r.jsx)("div",{children:e.content},e.id):(0,r.jsxs)(s.$,{variant:e.variant||"outline",size:e.size||"sm",onClick:e.onClick,disabled:e.disabled,className:"justify-start","data-tour-id":e.dataTourId,children:[e.icon&&(0,r.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id)),m]}),(u.length>0||h)&&(0,r.jsx)(s.$,{variant:"ghost",size:"icon",onClick:()=>y(!v),className:"h-8 w-8 md:hidden",children:v?(0,r.jsx)(l.A,{className:"h-4 w-4"}):(0,r.jsx)(c.A,{className:"h-4 w-4"})})]})]}),v&&(u.length>0||h)&&(0,r.jsxs)("div",{className:"md:hidden border-t bg-muted/30 px-4 py-4 space-y-3",children:[!f&&!t&&n&&(0,r.jsx)("div",{className:"pb-2 border-b border-border/50",children:(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:n})}),(0,r.jsx)("div",{className:"space-y-2",children:u.map(e=>e.content?(0,r.jsx)("div",{children:e.content},e.id):(0,r.jsxs)(s.$,{variant:e.variant||"outline",size:e.size||"sm",onClick:()=>{e.onClick(),y(!1)},disabled:e.disabled,className:"w-full justify-start","data-tour-id":e.dataTourId,children:[e.icon&&(0,r.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id))}),h&&(0,r.jsx)("div",{className:"pt-2 border-t border-border/50",children:h})]})]})}}}]);
\ No newline at end of file