(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• Make sure you have inspected the relevant snippet before editing.\n• Prefer scoped reads like `rg`, `sed -n \'30,60p\'`, or `nl -ba` to limit output.\n• Use `cat` only when you need the entire file or broader context.\n• If you already streamed the file in this session and it hasn\'t changed, reuse that context instead of re-running the command.\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- Confirm you have the necessary snippet before editing; prefer targeted reads and reuse recent outputs when possible\n- Avoid re-running `nl` across entire files; stick to targeted slices or reference the snippet you already captured\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`, `sed`, `cat`, etc.) 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\nCurrent project structure:\n".concat(e)),t}},1173:(e,t,i)=>{i.d(t,{I:()=>r});var n=i(3999);class r{static async getGenerationStats(e,t){if(!e||!t)return null;try{let i=await fetch("".concat(this.BASE_URL,"/generation?id=").concat(e),{headers:{Authorization:"Bearer ".concat(t),"Content-Type":"application/json"}});if(!i.ok)return n.v.warn("[GenerationAPI] Failed to fetch generation stats: ".concat(i.status)),null;return await i.json()}catch(e){return n.v.error("[GenerationAPI] Error fetching generation stats:",e),null}}static queueGenerationForCostUpdate(e,t,i,r,s,o){setTimeout(async()=>{let i=await this.getGenerationStats(e,t);if(null==i?void 0:i.usage){var r,s;let t=null!=(s=null!=(r=i.total_cost)?r:i.usage.total_cost)?s:0;n.v.debug("[GenerationAPI] Generation ".concat(e),{normalized_tokens:i.usage.total_tokens,native_tokens:i.usage.native_tokens_total,actual_cost:t}),o(t,i.usage)}},3e3)}static extractGenerationId(e){return e.get("x-openrouter-generation-id")}static extractCostFromHeaders(e){let t,i,r=e.get("x-openrouter-usage"),s=e.get("x-openrouter-cost");if(r)try{t=JSON.parse(r)}catch(e){n.v.warn("[GenerationAPI] Failed to parse usage header:",e)}if(s){let e=parseFloat(s);isNaN(e)||(i=e)}return t||void 0!==i?{usage:t,cost:i}:null}}r.BASE_URL="https://openrouter.ai/api/v1"},2714:(e,t,i)=>{i.d(t,{J:()=>c});var n=i(5155),r=i(2115),s=i(968),o=i(2085),a=i(3999);let l=(0,o.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=r.forwardRef((e,t)=>{let{className:i,...r}=e;return(0,n.jsx)(s.b,{ref:t,className:(0,a.cn)(l(),i),...r})});c.displayName=s.b.displayName},3091:(e,t,i)=>{i.d(t,{V:()=>o,b:()=>a});var n=i(8202);let r="openrouter";function s(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return t<.01?1e6*t:t}function o(e,t){if(!Array.isArray(t)||0===t.length)return;let i={};for(let n of t){if(!(null==n?void 0:n.pricing))continue;let t={input:n.pricing.input,output:n.pricing.output,reasoning:n.pricing.reasoning};Number.isFinite(t.input)&&Number.isFinite(t.output)&&(i[n.id]=t,i["".concat(e,"/").concat(n.id)]=t)}if(e===r)for(let[e,t]of Object.entries(i)){let n=e.split("/").pop();n&&!i[n]&&(i[n]=t)}Object.keys(i).length>0&&n.s.setProviderPricing(e,i)}function a(e){if(!Array.isArray(e)||0===e.length)return;let t={};for(let n of e){var i,o,a;let e=s(null==(i=n.pricing)?void 0:i.prompt),l=s(null==(o=n.pricing)?void 0:o.completion),c=s(null==(a=n.pricing)?void 0:a.internal_reasoning);if(void 0===e||void 0===l)continue;let d={input:e,output:l,reasoning:c};t[n.id]=d,t["".concat(r,"/").concat(n.id)]=d,n.canonical_slug&&(t[n.canonical_slug]=d)}Object.keys(t).length>0&&n.s.setProviderPricing(r,t)}},3462:(e,t,i)=>{i.d(t,{U:()=>a});var n=i(8202),r=i(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,i){var n,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,i),u=this.getDynamicPricing(t,i),h=s[p],m=u||h||this.findBestPricingMatch(t,i);u||h||r.v.warn("[CostCalculator] Falling back to default pricing for ".concat(p));let g=0,f=Math.max(null!=(n=e.promptTokens)?n: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&&r.v.debug("[CostCalculator] Adjusted provisional cost",{provider:t,model:i,reportedCost:c,computedCost:g,finalCost:a})):(a=c,e.isEstimated=!1),e.isEstimated&&("openrouter"===t||t.toString().includes("openrouter"))&&r.v.warn("[CostCalculator] Using estimated cost based on normalized tokens for OpenRouter. This may be inaccurate. Consider using Generation API for native token counts."),a}static getPricingKey(e,t){return"openrouter"===e&&t.includes("/")?"openrouter/".concat(t):"".concat(e,"/").concat(t)}static findBestPricingMatch(e,t){let i="".concat(e,"/");for(let[e,n]of Object.entries(s))if(e.startsWith(i)){let r=e.substring(i.length);if(t.includes(r)||r.includes(t))return n}return"ollama"===e||"lmstudio"===e?{input:0,output:0}:o}static getDynamicPricing(e,t){if(!this.isKnownProvider(e))return null;try{return n.s.getModelPricing(e,t)}catch(i){return r.v.debug("[CostCalculator] Failed to read dynamic pricing",{provider:e,model:t,error:i}),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,i){let n=!(arguments.length>3)||void 0===arguments[3]||arguments[3],r=Math.ceil(1.3*e.split(/\s+/).length),s=this.getPricing(t,i);return r/1e6*(n?s.input:s.output)}static updateWithGenerationApiCost(e,t){let i={...e};if(void 0!==t.total_cost&&(i.cost=t.total_cost,i.isEstimated=!1,e.cost&&Math.abs(e.cost-t.total_cost)>1e-4)){var n;r.v.debug("[CostCalculator] Cost corrected: ".concat(null==(n=e.cost)?void 0:n.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&&(i.nativeTokens={total:t.native_tokens_total,prompt:t.native_tokens_prompt,completion:t.native_tokens_completion}),i}}},3902:(e,t,i)=>{i.d(t,{B:()=>s});var n=i(6126),r=i.n(n);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 i=e.content;this.handlebars.registerPartial(t,i)}this.partialsRegistered=!0}catch(e){}}async compileTemplate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.templateCache.get(e);if(!i)try{let t=(await this.vfs.readFile(this.projectId,e)).content;i=this.handlebars.compile(t),this.templateCache.set(e,i)}catch(t){return console.error("Failed to compile template ".concat(e,":"),t),""}return i(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,"/"),i=new Map(this.blobUrls),n=new Map,r=[];for(let s of t){let t;if("template"===s.type)continue;if("image"===s.type||"video"===s.type)t={path:s.path,content:s.content,mimeType:s.mimeType};else if("html"===s.type)t=await this.processHTML(s);else if("js"===s.type)t=await this.processJS(s);else{if("css"===s.type)continue;t={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&&i.has(t.path)){let e=i.get(t.path);n.set(t.path,e),t.blobUrl=e,i.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),i=URL.createObjectURL(e);n.set(t.path,i),t.blobUrl=i,this.fileHashes.set(t.path,o)}r.push(t)}let s=[...r];for(let r of t)if("css"===r.type){let t=await this.processCSS(r,n),o=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===o&&i.has(t.path)){let e=i.get(t.path);n.set(t.path,e),t.blobUrl=e,i.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),i=URL.createObjectURL(e);n.set(t.path,i),t.blobUrl=i,this.fileHashes.set(t.path,o)}s.push(t)}let o=this.generateRoutes(t);if(e)for(let[,e]of i)URL.revokeObjectURL(e);else e||this.cleanupBlobUrls();return this.blobUrls=n,{entryPoint:"/index.html",files:s,routes:o,blobUrls:this.blobUrls}}hashContent(e){let t=0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);for(let e=0;e0){let i=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(i," \n
\n\x3c!-- Original content:\n").concat(e,"\n--\x3e")}let i={};try{let e=await this.vfs.readFile(this.projectId,"/data.json");i=JSON.parse(e.content)}catch(e){}return this.handlebars.compile(e)(i)}catch(i){console.error("VirtualServer: Error processing Handlebars templates:",i);let t=i instanceof Error?i.message:String(i);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 i=e.content;return i=await this.processUrlReferences(i,t),{path:e.path,content:i,mimeType:e.mimeType}}async processJS(e){let t=e.content;return{path:e.path,content:t,mimeType:e.mimeType}}async processInternalReferences(e){let t=await this.vfs.listDirectory(this.projectId,"/"),i=e;for(let e of[/href="([^"]+)"/g,/src="([^"]+)"/g,/href='([^']+)'/g,/src='([^']+)'/g])i=i.replace(e,(e,i)=>{if(i.startsWith("http")||i.startsWith("data:")||i.startsWith("//"))return e;let n=this.normalizePath(i);return t.some(e=>e.path===n),e});return i}async processUrlReferences(e,t){return e.replace(/url\(['"]?([^'")]+)['"]?\)/g,(e,i)=>{if(i.startsWith("http")||i.startsWith("data:")||i.startsWith("//")||i.startsWith("blob:"))return e;let n=this.normalizePath(i),r=t.get(n);return r?"url('".concat(r,"')"):e})}normalizePath(e){return(e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")||(e="/"+e),e.includes(".")||e.endsWith("/"))?e:e+".html"}generateRoutes(e){return e.filter(e=>"html"===e.type).map(e=>{let t=e.content.match(/([^<]+)<\/title>/i),i=t?t[1]:e.name.replace(".html",""),n=e.path.replace(".html","")||"/";return{path:"/index"===n?"/":n,file:e.path,title:i}})}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);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,i){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,i&&(this.blobUrls=new Map(i)),this.handlebars=r().create(),this.registerHelpers()}}},3999:(e,t,i)=>{i.d(t,{cn:()=>o,v:()=>d});var n=i(2596),r=i(9688),s=i(9509);function o(){for(var e=arguments.length,t=Array(e),i=0;i{i.d(t,{r8:()=>p,OP:()=>u});var n=i(1368),r=i(9311),s=i.n(r);class o{async init(){return new Promise((e,t)=>{let i=indexedDB.open("deepstudio-vfs",1);i.onerror=()=>t(i.error),i.onsuccess=()=>{this.db=i.result,e()},i.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"),i=await this.promisify(t.get(e));return i?this.hydrateProject(i):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 i=t.transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(i.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 i=this.getDB().transaction(["files"],"readonly").objectStore("files").index("path");return await this.promisify(i.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 i=await this.getFile(e,t);if(i){let e=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(e.delete(i.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),i=this.getDB().transaction(["files"],"readwrite").objectStore("files");for(let e of t)await this.promisify(i.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 i=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("path");return await this.promisify(i.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 i=await this.getTreeNode(e,t);if(i){let e=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(e.delete(i.id))}}async getChildNodes(e,t){let i=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("parentPath");return await this.promisify(i.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,i)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>i(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=i(3999),l=i(5337),c=i(7015),d=i(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,i){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 r=(0,l.Gr)(t),s=i instanceof ArrayBuffer?i.byteLength:new Blob([i]).size,o=l.Q6[r];if(s>o)throw Error("File too large. Maximum size for ".concat(r," files is ").concat(Math.round(o/1024/1024),"MB"));let d={id:(0,n.A)(),projectId:e,path:t,name:t.split("/").pop()||"",type:r,content:i,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 i=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(!i)throw a.v.error("VFS: Empty path after cleaning for readFile",{projectId:e,originalPath:t,cleanPath:i}),Error("Empty file path after cleaning");let n=await this.db.getFile(e,i);if(!n)throw a.v.error("VFS: File not found for read",{projectId:e,path:i,originalPath:t}),Error("File not found: ".concat(i));return n}async fileExists(e,t){this.ensureInitialized();try{return!!await this.db.getFile(e,t)}catch(e){return!1}}async updateFile(e,t,i){this.ensureInitialized();try{let n=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(n.includes("\n")||n.includes("@@")||n.includes("\\n")||n.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=n;let r=await this.db.getFile(e,t);if(!r)throw a.v.error("VFS: File not found for update",{projectId:e,path:t}),Error("File not found: ".concat(t));r.content=i,r.size=new Blob([i]).size,r.updatedAt=new Date,await this.db.updateFile(r),c.$.markDirty(e);{let i={projectId:e,path:t};window.dispatchEvent(new CustomEvent("fileContentChanged",{detail:i}))}return r}catch(e){throw e}}async patchFile(e,t,i){this.ensureInitialized();let n=(await this.readFile(e,t)).content;for(let e of i){if(!n.includes(e.search))throw a.v.error("VFS: Pattern not found in file",{path:t,searchPattern:e.search.substring(0,100),contentSnippet:n.substring(0,300)}),Error("Pattern not found in file: ".concat(e.search.substring(0,50),"..."));n=n.replace(e.search,e.replace)}return await this.updateFile(e,t,n)}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,i){this.ensureInitialized();let n=await this.readFile(e,t);return await this.deleteFile(e,t),await this.createFile(e,i,n.content)}async createDirectory(e,t){if(this.ensureInitialized(),await this.db.getTreeNode(e,t))return;let i={id:(0,n.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:[]};await this.db.createTreeNode(i),c.$.markDirty(e),window.dispatchEvent(new Event("filesChanged"))}async listDirectory(e,t){this.ensureInitialized();let i=await this.db.listFiles(e);return"/"===t?i:i.filter(e=>{let i=e.path,n=t.endsWith("/")?t:t+"/";return i.startsWith(n)&&-1===i.slice(n.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 i=await this.db.listFiles(e),n=t.endsWith("/")?t:t+"/";for(let t of i)t.path.startsWith(n)&&await this.deleteFile(e,t.path);await this.db.deleteTreeNode(e,t),c.$.markDirty(e),window.dispatchEvent(new Event("filesChanged"))}async renameDirectory(e,t,i){this.ensureInitialized();let r=await this.db.getTreeNode(e,t);if(r){await this.db.deleteTreeNode(e,t);let s={id:(0,n.A)(),projectId:e,path:i,type:"directory",parentPath:this.getParentPath(i),children:r.children};await this.db.createTreeNode(s),c.$.markDirty(e)}let s=t.endsWith("/")?t:t+"/",o=i.endsWith("/")?i:i+"/";for(let t of(await this.db.listFiles(e)).filter(e=>e.path.startsWith(s))){let i=o+t.path.substring(s.length);await this.renameFile(e,t.path,i)}for(let i of(await this.db.getAllTreeNodes(e)).filter(e=>"directory"===e.type&&e.path.startsWith(s)&&e.path!==t)){let t=o+i.path.substring(s.length);await this.db.deleteTreeNode(e,i.path);let r={id:(0,n.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:i.children};await this.db.createTreeNode(r)}window.dispatchEvent(new Event("filesChanged"))}async moveFile(e,t,i){if(this.ensureInitialized(),await this.db.getFile(e,i))throw Error("File already exists at destination: ".concat(i));let n=await this.readFile(e,t),r=await this.createFile(e,i,n.content);return await this.deleteFile(e,t),r}async moveDirectory(e,t,i){this.ensureInitialized();let n=i.endsWith("/")?i:i+"/",r=t.endsWith("/")?t:t+"/";if(n.startsWith(r))throw Error("Cannot move a directory into itself");await this.renameDirectory(e,t,i),window.dispatchEvent(new Event("filesChanged"))}async createProject(e,t){this.ensureInitialized();try{let i={id:(0,n.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(i);let r={id:(0,n.A)(),projectId:i.id,path:"/",type:"directory",parentPath:null,children:[]};return await this.db.createTreeNode(r),i}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 i=await this.getProject(e);if(!i)throw Error("Project not found: ".concat(e));i.costTracking||(i.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),i.costTracking.totalCost+=t.cost,i.costTracking.providerBreakdown[t.provider]||(i.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let n=i.costTracking.providerBreakdown[t.provider];n.totalCost+=t.cost,"delta"!==t.mode&&(n.requestCount+=1),n.lastUpdated=new Date,t.tokenUsage&&(n.tokenUsage.input+=t.tokenUsage.input,n.tokenUsage.output+=t.tokenUsage.output),t.sessionId&&"delta"!==t.mode&&(i.costTracking.sessionHistory||(i.costTracking.sessionHistory=[]),i.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.cost,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsage}),i.costTracking.sessionHistory.length>100&&(i.costTracking.sessionHistory=i.costTracking.sessionHistory.slice(-100))),await this.updateProject(i)}async applyProjectCostDelta(e,t){this.ensureInitialized();let i=await this.getProject(e);if(!i)throw Error("Project not found: ".concat(e));i.costTracking||(i.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),i.costTracking.totalCost+=t.costDelta,i.costTracking.providerBreakdown[t.provider]||(i.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let n=i.costTracking.providerBreakdown[t.provider];n.totalCost+=t.costDelta,n.lastUpdated=new Date,t.tokenUsageDelta&&(n.tokenUsage.input+=t.tokenUsageDelta.input,n.tokenUsage.output+=t.tokenUsageDelta.output),t.sessionId&&(i.costTracking.sessionHistory||(i.costTracking.sessionHistory=[]),i.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.costDelta,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsageDelta,correction:!0}),i.costTracking.sessionHistory.length>100&&(i.costTracking.sessionHistory=i.costTracking.sessionHistory.slice(-100))),await this.updateProject(i)}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,i){this.ensureInitialized();let n=await this.db.listFiles(e),{regex:r=!1,fileType:s,limit:o=20,searchIn:a="both"}=i||{},l=n;if(s){let e=s.startsWith(".")?s:".".concat(s);l=n.filter(t=>t.path.endsWith(e))}let c=r?e=>{try{return RegExp(t,"i").test(e)}catch(i){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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"any";this.ensureInitialized();let n=await this.db.listFiles(e),r=[],s=[];switch(i){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 n){if("string"!=typeof e.content)continue;let t=[];e.content.split("\n").forEach((e,i)=>{for(let n of s)if(n.test(e)){t.push({line:i+1,text:e.trim()});break}}),t.length>0&&r.push({file:e,matches:t})}return r}async getFileStats(e,t){this.ensureInitialized();let i=await this.db.getFile(e,t);if(!i)throw Error("File not found: ".concat(t));let n=("string"==typeof i.content?i.content:"").split("\n");return{path:i.path,size:i.size,lines:n.length,type:i.type,preview:n.slice(0,10),lastModified:i.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 i=await this.db.listFiles(e),n=0,r={};for(let e of i){var s;n+=e.size;let t=(null==(s=e.path.split(".").pop())?void 0:s.toUpperCase())||"OTHER";r[t]=(r[t]||0)+1}return t=n<1024?"".concat(n," B"):n<1048576?"".concat((n/1024).toFixed(1)," KB"):"".concat((n/1048576).toFixed(2)," MB"),{fileCount:i.length,totalSize:n,fileTypes:r,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 i=new d.B(this,e);for(let e of(await i.compileProject()).files){let i=e.path.startsWith("/")?e.path.slice(1):e.path;this.shouldExcludeFromExport(e.path)||(e.content,t.file(i,e.content))}i.cleanupBlobUrls()}catch(i){for(let n of(a.v.warn("Failed to compile Handlebars templates during export, falling back to raw files:",i),await this.db.listFiles(e))){let e=n.path.startsWith("/")?n.path.slice(1):n.path;this.shouldExcludeFromExport(n.path)||(n.content,t.file(e,n.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),i=await this.db.listFiles(e),n="".concat(t.name," (Copy)").slice(0,50),r=await this.createProject(n,t.description);return await c.$.runWithSuppressedDirty(r.id,async()=>{for(let e of i)await this.createFile(r.id,e.path,e.content)}),r}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 i of e.files)await this.createFile(t.id,i.path,i.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,i){let n=this.getParentPath(t);if(null===n)return;let r=await this.db.getTreeNode(e,n);if(r||"create"!==i||(await this.createDirectory(e,n),r=await this.db.getTreeNode(e,n)),r){let e=r.children||[];if("create"!==i||e.includes(t)){if("delete"===i){let i=e.indexOf(t);i>-1&&e.splice(i,1)}}else e.push(t);r.children=e,await this.db.updateTreeNode(r)}}constructor(){this.initialized=!1,this.db=new o}}let u=new p},4973:(e,t,i)=>{i.d(t,{QF:()=>r,WK:()=>s});var n=i(3999);async function r(){try{let e=await fetch("https://openrouter.ai/api/v1/models");if(!e.ok)throw Error("Failed to fetch models: ".concat(e.statusText));return(await e.json()).data.filter(e=>e.architecture.output_modalities.includes("text")&&e.supported_parameters.includes("tools")).sort((e,t)=>{let i=["gpt-4","claude","deepseek","qwen"],n=i.some(t=>e.id.toLowerCase().includes(t)),r=i.some(e=>t.id.toLowerCase().includes(e));return n&&!r?-1:!n&&r?1:t.created-e.created})}catch(e){return n.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 i=t?e/1e3:e;if(0===i)return"free";if(i<1e-4)return"$".concat(i.toFixed(5).replace(/\.?0+$/,""));if(i<.001)return"$".concat(i.toFixed(4).replace(/\.?0+$/,""));if(i<.01)return"$".concat(i.toFixed(3).replace(/\.?0+$/,""));if(i<.1)return"$".concat(i.toFixed(3).replace(/\.?0+$/,""));if(i<1)return"$".concat(i.toFixed(2).replace(/\.?0+$/,""));else return"$".concat(i.toFixed(2))}},5040:(e,t,i)=>{i.d(t,{r:()=>P});var n=i(4520),r=i(7150),s=i(7015),o=i(8202),a=i(86),l=i(3462),c=i(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=i(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,i){if("/"===i||!i)return;let n=i.split("/").filter(Boolean),r="";for(let i=0;i
3&&void 0!==arguments[3]&&arguments[3],!t||"string"!=typeof t)return{stdout:"",stderr:"Invalid project ID provided",exitCode:2};if(!i||0===i.length)return{stdout:"",stderr:"No command provided",exitCode:2};let n=i.filter(e=>null!=e&&""!==e);if(0===n.length)return{stdout:"",stderr:"No valid command arguments provided",exitCode:2};let[r,...s]=n;try{switch(r){case"ls":{let i=new Set,n=[];for(let e of s)e&&e.startsWith("-")?i.add(e):e&&n.push(e);let r=i.has("-R")||i.has("-r"),o=g(n[0])||"/";if(r){let i=await e.getAllFilesAndDirectories(t),n="/"===o?"/":o.endsWith("/")?o:o+"/",r=i.filter(e=>e.path===o||e.path.startsWith(n)).map(e=>e.path).sort().join("\n");return{stdout:m(r),stderr:"",exitCode:0}}{let i=(await e.listDirectory(t,o)).map(e=>e.path).sort().join("\n");return{stdout:m(i),stderr:"",exitCode:0}}}case"cat":{let i=g(s[0]);if(!i)return{stdout:"",stderr:"cat: missing file path",exitCode:2};if(i.startsWith("/-"))return{stdout:"",stderr:"cat: invalid path (looks like an option). Use: cat /path/to/file",exitCode:2};let n=await e.readFile(t,i);if("string"!=typeof n.content)return{stdout:"",stderr:"cat: ".concat(i,": binary or non-text file"),exitCode:1};return{stdout:m(n.content),stderr:"",exitCode:0}}case"grep":{let i,n={n:!1,i:!1,r:!1,F:!1},r=[];for(let e of s)if(e.startsWith("-"))for(let t of e.slice(1))t in n&&(n[t]=!0);else r.push(e);let o=r[0],a=g(r[1])||"/";if(!o)return{stdout:"",stderr:"grep: missing pattern",exitCode:2};if(n.F){let e=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(e,n.i?"i":"")}else i=new RegExp(o,n.i?"i":"");let l=await e.getAllFilesAndDirectories(t),c="/"===a?"/":a.endsWith("/")?a:a+"/",d=[];for(let e of l){if("type"in e&&"directory"===e.type||!e.path.startsWith(c)&&e.path!==a||"string"!=typeof e.content)continue;let t=e.content.split(/\r?\n/);for(let r=0;re.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 i=s.includes("-p"),n=s[i?s.indexOf("-p")+1:0],r=g(n);if(!r)return{stdout:"",stderr:"mkdir: missing path",exitCode:2};return i?await f(e,t,r):await e.createDirectory(t,r),{stdout:"",stderr:"",exitCode:0}}case"rm":{let i=!1,n=!1,r=!1,o=[];for(let e of s)e&&e.startsWith("-")?((e.includes("r")||e.includes("R"))&&(i=!0),e.includes("f")&&(n=!0),e.includes("v")&&(r=!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){n||(a=!0);continue}try{await e.deleteFile(t,o),r&&l.push("removed '".concat(o,"'"))}catch(s){if(i)try{await e.deleteDirectory(t,o),r&&l.push("removed directory '".concat(o,"'"))}catch(e){!n&&(a=!0,r&&l.push("rm: cannot remove '".concat(o,"': No such file or directory")))}else!n&&(a=!0,r&&l.push("rm: cannot remove '".concat(o,"': Is a directory (use -r to remove directories)")))}}let c=r?l.join("\n"):"",d=a&&!r?"rm: some paths could not be removed":"";return{stdout:m(c),stderr:d,exitCode:+!!a}}case"rmdir":{let i=[],n=!1;for(let e of s)"-v"===e||"--verbose"===e?n=!0:e&&!e.startsWith("-")&&i.push(e);if(0===i.length)return{stdout:"",stderr:"rmdir: missing operand",exitCode:2};let r=!1,o=[];for(let s of i){let i=g(s);if(!i){r=!0;continue}try{(await e.listDirectory(t,i)).length>0?(r=!0,n&&o.push("rmdir: failed to remove '".concat(i,"': Directory not empty"))):(await e.deleteDirectory(t,i),n&&o.push("rmdir: removing directory, '".concat(i,"'")))}catch(e){r=!0,n&&o.push("rmdir: failed to remove '".concat(i,"': No such file or directory"))}}let a=n?o.join("\n"):"",l=r&&!n?"rmdir: failed to remove one or more directories":"";return{stdout:m(a),stderr:l,exitCode:+!!r}}case"mv":{let[i,n]=s,r=g(i),o=g(n);if(!r||!o)return{stdout:"",stderr:"mv: missing operands",exitCode:2};try{return await e.renameFile(t,r,o),{stdout:"",stderr:"",exitCode:0}}catch(i){return await e.renameDirectory(t,r,o),{stdout:"",stderr:"",exitCode:0}}}case"cp":{let i=s.includes("-r"),[n,r]=s.filter(e=>"-r"!==e);if(n=g(n),r=g(r),!n||!r)return{stdout:"",stderr:"cp: missing operands",exitCode:2};try{let i=await e.readFile(t,n),s=(i.content,i.content);try{await e.createFile(t,r,s)}catch(i){await e.updateFile(t,r,s)}return{stdout:"",stderr:"",exitCode:0}}catch(a){if(!i)return{stdout:"",stderr:"cp: -r required for directories",exitCode:1};let s=await e.getAllFilesAndDirectories(t),o=n.endsWith("/")?n:n+"/";for(let i of s)if((!("type"in i)||"directory"!==i.type)&&(i.path===n||i.path.startsWith(o))){let s=i.path.slice(n.length),o=(r.endsWith("/")?r.slice(0,-1):r)+s;await f(e,t,o.split("/").slice(0,-1).join("/"));let a=(i.content,i.content);try{await e.createFile(t,o,a)}catch(i){await e.updateFile(t,o,a)}}return{stdout:"",stderr:"",exitCode:0}}}case"echo":if(s.includes(">")||s.includes(">>"))return{stdout:"",stderr:"echo: redirection is not supported in this environment. Use json_patch to edit files.",exitCode:2};return{stdout:m(s.join(" ")),stderr:"echo prints to stdout only. To modify files, use json_patch.",exitCode:1};case"nl":{let i="";for(let e of s)"-ba"===e||e.startsWith("-")||(i=e);let n=g(i);if(!n)return{stdout:"",stderr:"nl: missing file path",exitCode:2};try{let i=await e.readFile(t,n);if("string"!=typeof i.content)return{stdout:"",stderr:"nl: ".concat(n,": binary file"),exitCode:1};let r=i.content.split(/\r?\n/).map((e,t)=>{let i=String(t+1).padStart(6," ");return"".concat(i," ").concat(e)});return{stdout:m(r.join("\n")),stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:"nl: ".concat(n,": ").concat((null==e?void 0:e.message)||"file not found"),exitCode:1}}}case"sed":{if(0===s.length)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" or sed -n "1,80p" ',exitCode:2};let i=!1,n=0,r=1;"-n"===s[0]&&(i=!0,n=1,r=2);let o=s[n],a=s[r];if(!o||!a)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" or sed -n "1,80p" ',exitCode:2};let l=o.match(/^(\d+),(\d+)p$/);if(l){let i=parseInt(l[1]),n=parseInt(l[2]),r=await e.readFile(t,a);if("string"!=typeof r.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let s=r.content.split("\n").slice(i-1,n);return{stdout:m(s.join("\n")),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let c=o.match(/^(\d+)p$/);if(c){let i=parseInt(c[1]),n=await e.readFile(t,a);if("string"!=typeof n.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let r=n.content.split("\n");if(i<=0||i>r.length)return{stdout:"",stderr:"sed: line ".concat(i," out of range"),exitCode:1};return{stdout:m(r[i-1]),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let d=o.match(/^s\/(.*)\/(.*)\/(g?)$/);if(d){let[,n,r]=d,s=await e.readFile(t,a);if("string"!=typeof s.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let o=RegExp(n,"g"),l=s.content.replace(o,r);return{stdout:m(l),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:+!i}}return{stdout:"",stderr:'sed: supported formats: "s/pat/repl/g", "1,80p", "80p". Use json_patch for file changes.',exitCode:2}}default:return{stdout:"",stderr:"".concat(r,": command not found").concat("bash"===r?'\nDon\'t use "bash" as a command - call the shell tool directly with your command.\nWrong: {"cmd": ["bash", "-c", "ls -la"]}\nRight: {"cmd": ["ls", "-la"]}\n':"",'\n\nSupported commands: ls, cat, grep, find, mkdir, rm, rmdir, mv, cp, echo, nl, sed\n\nCorrect shell tool usage:\n {"cmd": ["ls", "/"]} - List files\n {"cmd": ["cat", "/file.txt"]} - Read file content \n {"cmd": ["grep", "pattern", "/file.txt"]} - Search with regex\n {"cmd": ["grep", "-F", "literal", "/file.txt"]} - Search literal string\n {"cmd": ["find", "/", "-name", "*.js"]} - Find files by name\n {"cmd": ["mkdir", "/dirname"]} - Create directory\n {"cmd": ["rm", "/file.txt"]} - Delete file\n {"cmd": ["rm", "-r", "/dirname"]} - Delete directory recursively\n {"cmd": ["rm", "-rf", "/dirname"]} - Force delete directory\n {"cmd": ["rm", "-rfv", "/dir1", "/dir2"]} - Verbose force delete multiple\n {"cmd": ["rmdir", "/empty-dir"]} - Remove empty directory\n {"cmd": ["rmdir", "-v", "/dir1"]} - Remove empty directory (verbose)\n {"cmd": ["mv", "/old.txt", "/new.txt"]} - Move/rename files\n {"cmd": ["cp", "/file.txt", "/copy.txt"]} - Copy files\n {"cmd": ["echo", "text"]} - Output text (read-only)\n {"cmd": ["nl", "/file.txt"]} - Show file with line numbers\n {"cmd": ["sed", "s/old/new/g", "/file.txt"]} - Preview text replacement\n\nNote: File edits require the json_patch tool, not shell commands.'),exitCode:127}}}catch(e){return{stdout:"",stderr:(null==e?void 0:e.message)||String(e),exitCode:1}}}let y={execute:async(e,t)=>{let i=new n.r8;await i.init();let r=await v(i,e,t);return{success:0===r.exitCode,stdout:r.stdout,stderr:r.stderr}}};var x=i(3999);async function w(e,t,i,n){let r=[];if(!i||!i.startsWith("/"))return{applied:!1,summary:"Invalid file path",warnings:["File path must be absolute and start with /"]};if(!n||0===n.length)return{applied:!1,summary:"No operations provided",warnings:["No patch operations to apply"]};let s=i.replace(/\/+/g,"/");try{var o,a;let i="",l=!0;try{let n=await e.readFile(t,s);if("string"!=typeof n.content)return{applied:!1,summary:"Cannot patch binary file",warnings:["File ".concat(s," is binary and cannot be patched")]};i=n.content}catch(e){if(null==(o=e.message)?void 0:o.includes("not found"))l=!1,i="",x.v.debug("[StringPatch] File ".concat(s," does not exist, will create it"));else throw e}let c=i,d=0;for(let e=0;e1){r.push("Operation ".concat(e+1,": oldStr appears ").concat(s,' times in file, must be unique. String: "').concat(b(i,100),'"'));continue}c=c.replace(i,null!=n?n:""),d++}else if("rewrite"===t.type)c=null!=(a=t.content)?a:"",d++;else if("replace_entity"===t.type){let{selector:i,replacement:n,entity_type:s}=t;if(!i){r.push("Operation ".concat(e+1,": selector is required for replace_entity operations"));continue}if(void 0===n){r.push("Operation ".concat(e+1,": replacement is required for replace_entity operations"));continue}let o=function(e,t,i,n){try{let r=function(e,t){let i=[],n=new Set,r=e=>{e&&(n.has(e)||(n.add(e),i.push(e)))};for(let n of(r(t),r(t.replace(/^\s+/,"")),r(t.replace(/\s+$/,"")),r(t.replace(/^\s+/,"").replace(/\s+$/,"")),i)){if(!n)continue;let t=e.indexOf(n);if(-1!==t)return{index:t,normalizedSelector:n}}return null}(e,t);if(!r)return{success:!1,error:'Selector not found: "'.concat(b(t,100),'"')};let{index:s,normalizedSelector:o}=r,a=function(e,t,i,n){var r,s,o,a,l,c,d,p,u;switch(n||((r=i).startsWith("<")&&r.includes(">")?"html_element":r.includes("React.FC")||r.includes(": FC<")?"react_component":r.includes("function ")||r.includes(" = (")||r.includes(" => {")?"function":r.startsWith(".")||r.startsWith("#")?"css_rule":r.includes("interface ")||r.includes("type ")?r.includes("interface ")?"interface":"type":"bracket_matched")){case"html_element":return function(e,t,i){if(t<0||t>=e.length)return null;let n=i.match(/<(\w+)(?:\s|>)/);if(!n)return null;let r=n[1],s=Math.max(0,t);if(i.includes("/>"))return{start:s,end:e.indexOf("/>",t)+2};let o=0,a=t;for(;a]*)?>"))),i=e.substring(a).match(new RegExp("".concat(r,">"))),n=-1,l=-1;if(t){let i=e.substring(a).indexOf(t[0]);n=-1!==i?a+i:-1}if(i){let t=e.substring(a).indexOf(i[0]);l=-1!==t?a+t:-1}if(-1===l)break;if(-1!==n&&n0&&(l?await e.updateFile(t,s,c):await e.createFile(t,s,c));let p=d>0?"Applied ".concat(d,"/").concat(n.length," operations to ").concat(s):"No operations applied to ".concat(s);return{applied:d>0,summary:p,warnings:r.length>0?r:void 0}}catch(t){let e=t.message||String(t);return x.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 i=e.indexOf("{",t);if(-1===i)return null;let n=Math.max(0,t),r=0,s=i;for(;snew Promise(t=>setTimeout(t,e));class P{stop(){this.stopped=!0,x.v.info("[Orchestrator] Generation stopped by user")}async fetchWithRetry(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=arguments.length>3?arguments[3]:void 0;for(let r=0;r<=i;r++){let s=await fetch(e,t);if(429!==s.status||r===i)return s;let o=s.headers.get("Retry-After"),a=o?1e3*parseInt(o):1e3*Math.pow(2,r);null==n||n(r+1,a),await T(a)}throw Error("Unexpected end of retry loop")}getProviderConfig(){let e=o.s.getSelectedProvider(),t=(0,a.sO)(e),i=o.s.getProviderApiKey(e),n=o.s.getProviderModel(e)||void 0;if(t.apiKeyRequired&&!i)throw Error("API key not configured for provider: ".concat(e));return{provider:e,providerConfig:t,apiKey:i||"",model:n||"default-model"}}handleRetry(e,t){let i="Rate limited. Retry attempt ".concat(e," in ").concat(t/1e3,"s...");x.v.warn(i),k.oR.info(i,{duration:t>2e3?t-500:2e3,description:"Waiting for rate limit to reset"})}async streamLLMResponse(e,t,i,n,r,s){await this.ensurePricing(i,r);let o="".concat(window.location.origin,"/api/generate"),a={messages:e,apiKey:n,model:r,provider:i,tools:t,...t&&t.length>0&&{tool_choice:(null==s?void 0:s.toolChoice)||"auto"},max_tokens:null==s?void 0:s.maxTokens};x.v.debug("[Orchestrator] Making API request to ".concat(i," with ").concat((null==t?void 0:t.length)||0," tools, model: ").concat(r),{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,i,(null==s?void 0:s.suppressAssistantDelta)===!0)}async parseStreamingResponse(e,t){var i,r,s,a,d,p,u,h,m,g,f,v,y,w,b,C,k,j,S;let T,P=arguments.length>2&&void 0!==arguments[2]&&arguments[2],I=null==(i=e.body)?void 0:i.getReader();if(!I)throw Error("No response stream");let N=new TextDecoder,A="",O="",F={},E=null,R="",D="1"===_.env.NEXT_PUBLIC_DEBUG_TOOL_STREAM,M={},U={};try{for(;;){let{done:e,value:i}=await I.read();if(e)break;let n=(A+=N.decode(i,{stream:!0})).split("\n");for(let e of(A=n.pop()||"",n))if(e.startsWith("data: ")){let i=e.slice(6);if("[DONE]"===i){E&&R&&E.function&&E.id&&(E.function.arguments=R,F[E.id]=E);break}try{let e=JSON.parse(i);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,P||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:""}};F[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),F[t].function.arguments=e}catch(e){x.v.error("Invalid JSON for tool parameters:",M[t],e),F[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,P||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,P||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(F[t]||(F[t]={id:e.id||"tool_".concat(e.index),type:"function",function:{name:"",arguments:""}}),(null==(w=e.function)?void 0:w.name)&&(F[t].function.name=e.function.name),null==(b=e.function)?void 0:b.arguments){let i=e.function.arguments;F[t].function.arguments+=i}}else if(e.id)E&&R&&E.function&&E.id&&(E.function.arguments=R,F[E.id]=E),E={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)&&E&&E.function&&(E.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==(r=e.x_groq)?void 0:r.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){i&&i.length>10&&!i.includes("[DONE]")&&x.v.warn("[Orchestrator] Parse error in streaming response:",e,"Data snippet:",i.substring(0,200))}}}}catch(e){x.v.error("Error reading stream:",e),Object.keys(F).length>0&&E&&R&&E.function&&E.id&&(E.function.arguments=R,F[E.id]=E)}if(O&&x.v.debug("[Orchestrator] Checking content for tool calls",{contentLength:O.length,existingToolCalls:Object.keys(F).length,hasToolKeywords:O.includes("json_patch")||O.includes("evaluation")}),O&&0===Object.keys(F).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 i=t[1],n=t[2];try{let r=JSON.parse(n.trim());F.manual_1={id:"manual_1",type:"function",function:{name:i,arguments:JSON.stringify(r)}},e=O.replace(t[0],"").trim()}catch(e){x.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 i=t[2];try{let n=JSON.parse(i.trim());F.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(n)}},e=O.replace(t[0],"").trim()}catch(e){x.v.debug("Failed to parse commentary reasoning format JSON:",e)}}}for(let t of[/\{[^{}]*"cmd"\s*:\s*\[[^\]]*\][^{}]*\}/,/\{"cmd":\s*\[.*?\]\}/,/\{.*?"cmd".*?\}/]){let i=e.match(t);if(i){x.v.debug("[Orchestrator] Found JSON match with pattern",{pattern:t.toString(),jsonPreview:i[0].substring(0,200)});try{let t=i[0],n=JSON.parse(t);if(n.cmd&&Array.isArray(n.cmd)){let i=n.cmd;"bash"===i[0]&&i[1]&&i[1].startsWith("-")&&i[2]&&(n.cmd=i=i[2].trim().split(/\s+/)),F.manual_1||(F.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(n)}}),e=e.replace(t,"").trim();break}}catch(e){x.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(F).length>0&&x.v.debug("[Orchestrator] Found ".concat(Object.keys(F).length," tool calls before validation"),Object.keys(F));let L=Object.values(F).map(e=>{var t;if(null==(t=e.function)?void 0:t.arguments)try{JSON.parse(e.function.arguments),x.v.debug("[Orchestrator] Tool call ".concat(e.id," validated successfully: ").concat(e.function.name))}catch(a){D&&x.v.warn("Incomplete tool arguments detected, attempting to fix");let t=e.function.arguments,i=(t.match(/{/g)||[]).length,n=(t.match(/}/g)||[]).length,r=(t.match(/\[/g)||[]).length,s=(t.match(/]/g)||[]).length,o="";for(let e=0;ex.v.error("Failed to update project cost:",e)),null==(S=this.onProgress)||S.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-i;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-")||n.OP.applyProjectCostDelta(this.projectId,{costDelta:c,provider:s,sessionId:r}).catch(e=>x.v.error("Failed to apply corrected project cost:",e)),null==(d=this.onProgress)||d.call(this,"cost_correction",{originalCost:i,actualCost:e,difference:c,usage:a,totalCost:this.totalCost})}})}}return x.v.debug("[Orchestrator] Final response",{contentLength:O.length,toolCallsCount:L.length,toolCalls:L.map(e=>{var t,i,n;return{id:e.id,name:null==(t=e.function)?void 0:t.name,argsLength:null==(n=e.function)||null==(i=n.arguments)?void 0:i.length}})}),{content:O,toolCalls:L,usage:T}}async ensurePricing(e,t){var i;let n="".concat(e,":").concat(t);if(this.pricingEnsured.has(n))return;if("openrouter"!==e||o.s.getModelPricing("openrouter",t))return void this.pricingEnsured.add(n);let r=o.s.getCachedModels("openrouter");if((null==r||null==(i=r.models)?void 0:i.length)&&((0,j.V)("openrouter",r.models),o.s.getModelPricing("openrouter",t)))return void this.pricingEnsured.add(n);try{let e=await (0,S.QF)();(0,j.b)(e),o.s.getModelPricing("openrouter",t)&&this.pricingEnsured.add(n)}catch(e){x.v.warn("[Orchestrator] Failed to fetch pricing metadata",e)}}debug(){for(var e=arguments.length,t=Array(e),i=0;i0&&(p=e.map(e=>e.path).join("\n"))}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,i,n;return{name:null==(t=e.function)?void 0:t.name,args:null==(n=e.function)||null==(i=n.arguments)?void 0:i.substring(0,100)}})}),!m.toolCalls||0===m.toolCalls.length){if(x.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++,x.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++,x.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}x.v.info("[Orchestrator] Breaking: no tool calls and max retries reached. Steps completed: ".concat(this.stepsCompleted));break}m.toolCalls&&m.toolCalls.length>0&&(x.v.debug("[Orchestrator] Sending ".concat(m.toolCalls.length," tool calls to UI")),null==(l=this.onProgress)||l.call(this,"toolCalls",{toolCalls:m.toolCalls}));try{n=await this.executeToolCalls(m.toolCalls,e),this.malformedToolCallRetries=0}catch(t){let e=t instanceof Error?t.message:String(t);if(x.v.error("[Orchestrator] Tool execution error:",e),e.includes("Malformed tool call")&&(this.malformedToolCallRetries++,x.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 n)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){x.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0;break}}catch(e){x.v.error("Failed to parse evaluation result:",e)}if(this.taskComplete||this.stepsCompleted>=50){x.v.info("[Orchestrator] Breaking: taskComplete=".concat(this.taskComplete,", steps=").concat(this.stepsCompleted));break}}x.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(i){x.v.error("Orchestrator error:",i);let t=i instanceof Error?i.message:"Unknown error";try{await this.recordAutoCheckpoint("After failure: ".concat(e.substring(0,60)))}catch(e){x.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 i=[];for(let t=0;t0&&(t.push(i),i=""):i+=a}return i.length>0&&t.push(i),t}(e.cmd),x.v.debug('[Orchestrator] Converted string command "'.concat(e.cmd,'" to array:'),n);else if(Array.isArray(e.cmd))n=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');x.v.debug("[Orchestrator] Executing shell command: ".concat(n[0])),x.v.debug("[Orchestrator] Routing to executeShellCommand");let r=await this.executeShellCommand(n);x.v.debug("[Orchestrator] Command result length:",null==r?void 0:r.length),i.push({role:"tool",tool_call_id:v,content:r}),this.stepsCompleted++;let s=r.startsWith("❌");null==(o=this.onProgress)||o.call(this,"tool_status",{toolIndex:t,status:s?"failed":"completed",result:r}),x.v.debug("[Orchestrator] Sending tool result for tool ".concat(t),{resultPreview:r.substring(0,100)}),null==(a=this.onProgress)||a.call(this,"tool_result",{toolIndex:t,toolId:v,result:r});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(n){let e=n instanceof Error?n.message:String(n);i.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);x.v.debug("[Orchestrator] Executing json_patch call for ".concat(e.file_path));let r=new n.r8;await r.init();let s=await w(r,this.projectId,e.file_path,e.operations);x.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")),i.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(n){let e=n instanceof Error?n.message:String(n);i.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);x.v.debug("[Orchestrator] Processing evaluation:",e),!0===e.goal_achieved&&(x.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0),i.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){i.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);x.v.warn("[Orchestrator] ".concat(e)),i.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 i}async recordAutoCheckpoint(e){let t=await r.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 i=t.stdout&&t.stdout.trim().length>0?t.stdout:"Command succeeded with no output",n=e&&e.length>0?e[0]:void 0;if("cat"===n){let t=e.length>1?e[1]:void 0;if(t){let e=Date.now(),n=this.recentCatReads.get(t);if(n&&e-n<3e4){let e="Hint: You already read ".concat(t," recently; reuse that context unless the file changed.");i="".concat(e,"\n\n").concat(i)}let r=e-12e4;for(let[e,t]of this.recentCatReads)t=1;i--){let n=e[i];if(!n.startsWith("-")){t=n;break}}t&&i&&"Command succeeded with no output"!==i&&(i="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 i}{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"))}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 i=Array.isArray(null==(t=e.parameters)?void 0:t.cmd)?e.parameters.cmd:[];if(!i.length)return"Executed shell";let n=(i[0]||"").toLowerCase();switch(n){case"ls":return"Listed files";case"cat":return"Read ".concat(i[1]||"file");case"grep":return"Searched for patterns";case"find":return"Found files";case"mkdir":return"Created directory";case"rm":return"Removed ".concat(i[1]||"file");case"rmdir":return"Removed directory";case"mv":return"Moved ".concat(i[1]||"file");case"cp":return"Copied ".concat(i[1]||"file");default:return"Executed: ".concat(n)}}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:i,apiKey:n,model:r}=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}],[],i,n,r,{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 x.v.error("Failed to parse evaluation result:",s.content),{goalAchieved:!1,reasoning:"Could not determine goal achievement",shouldContinue:this.stepsCompleted<3}}}constructor(e,t,i){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=i,this.conversation=t||[]}}},5221:(e,t,i)=>{i.d(t,{g:()=>o});var n=i(5155),r=i(1362),s=i(2115);function o(e){let{width:t=64,height:i=64,className:o}=e,{resolvedTheme:a}=(0,r.D)(),[l,c]=(0,s.useState)(!1);return((0,s.useEffect)(()=>{c(!0)},[]),l)?(0,n.jsx)("div",{style:{width:t,height:i},className:"".concat(o," ").concat("light"===a?"[&_path]:fill-black":"[&_path]:fill-white"),dangerouslySetInnerHTML:{__html:' '}}):(0,n.jsx)("div",{style:{width:t,height:i}})}},5337:(e,t,i)=>{i.d(t,{Gr:()=>s,N$:()=>o,Q6:()=>r,fu:()=>a});let n={html:["html","htm"],css:["css"],js:["js","mjs","jsx"],json:["json"],text:["txt","md","xml","svg"],template:["hbs","handlebars"],image:["png","jpg","jpeg","gif","webp","ico","bmp"],video:["mp4","webm","ogg"]},r={text:5242880,html:5242880,css:5242880,js:5242880,json:5242880,template:5242880,image:0xa00000,video:0x3200000,binary:0xa00000};function s(e){var t;let i=null==(t=e.split(".").pop())?void 0:t.toLowerCase();for(let[e,t]of Object.entries(n))if(t.includes(i||""))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 i=null==(t=e.split(".").pop())?void 0:t.toLowerCase();for(let e of Object.values(n))if(e.includes(i||""))return!0;return!1}},5784:(e,t,i)=>{i.d(t,{bq:()=>p,eb:()=>h,gC:()=>u,l6:()=>c,yv:()=>d});var n=i(5155);i(2115);var r=i(4582),s=i(6474),o=i(5196),a=i(7863),l=i(3999);function c(e){let{...t}=e;return(0,n.jsx)(r.bL,{"data-slot":"select",...t})}function d(e){let{...t}=e;return(0,n.jsx)(r.WT,{"data-slot":"select-value",...t})}function p(e){let{className:t,size:i="default",children:o,...a}=e;return(0,n.jsxs)(r.l9,{"data-slot":"select-trigger","data-size":i,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,n.jsx)(r.In,{asChild:!0,children:(0,n.jsx)(s.A,{className:"size-4 opacity-50"})})]})}function u(e){let{className:t,children:i,position:s="popper",...o}=e;return(0,n.jsx)(r.ZL,{children:(0,n.jsxs)(r.UC,{"data-slot":"select-content",className:(0,l.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:s,...o,children:[(0,n.jsx)(m,{}),(0,n.jsx)(r.LM,{className:(0,l.cn)("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:i}),(0,n.jsx)(g,{})]})})}function h(e){let{className:t,children:i,...s}=e;return(0,n.jsxs)(r.q7,{"data-slot":"select-item",className:(0,l.cn)("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...s,children:[(0,n.jsx)("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,n.jsx)(r.VF,{children:(0,n.jsx)(o.A,{className:"size-4"})})}),(0,n.jsx)(r.p4,{children:i})]})}function m(e){let{className:t,...i}=e;return(0,n.jsx)(r.PP,{"data-slot":"select-scroll-up-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...i,children:(0,n.jsx)(a.A,{className:"size-4"})})}function g(e){let{className:t,...i}=e;return(0,n.jsx)(r.wn,{"data-slot":"select-scroll-down-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",t),...i,children:(0,n.jsx)(s.A,{className:"size-4"})})}},7015:(e,t,i)=>{i.d(t,{$:()=>a});var n=i(7150),r=i(4520),s=i(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 i=this.dirtyProjects.has(e);t&&!i?(this.dirtyProjects.add(e),this.emit(e)):!t&&i&&(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 i=null!=(t=this.suppressionCounts.get(e))?t:0;this.suppressionCounts.set(e,i+1)}endSuppression(e){var t;let i=null!=(t=this.suppressionCounts.get(e))?t:0;if(i<=1)return void this.suppressionCounts.delete(e);this.suppressionCounts.set(e,i-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 i,s;await r.OP.init();let o=await r.OP.getProject(e),a="Manual save @ ".concat(new Date().toLocaleTimeString()),l=await n.Y.createCheckpoint(e,t||a,{kind:"manual",baseRevisionId:null!=(i=o.lastSavedCheckpointId)?i:null,replaceId:null!=(s=o.lastSavedCheckpointId)?s:null});return o.lastSavedCheckpointId=l.id,o.lastSavedAt=new Date(l.timestamp),await r.OP.updateProject(o),this.manualCheckpoints.set(e,l.id),this.markClean(e),l}async restoreLastSaved(e){await r.OP.init();let t=(await r.OP.getProject(e)).lastSavedCheckpointId;if(!t)return s.v.warn("[SaveManager] No saved checkpoint to restore",{projectId:e}),!1;let i=await this.runWithSuppressedDirty(e,async()=>{if(!await n.Y.checkpointExists(t))return s.v.warn("[SaveManager] Saved checkpoint missing",{projectId:e,checkpointId:t}),!1;let i=await n.Y.restoreCheckpoint(t);return i||s.v.error("[SaveManager] Failed to restore saved checkpoint",{projectId:e,checkpointId:t}),i});return i&&this.markClean(e),i}getSavedCheckpointId(e){var t;return null!=(t=this.manualCheckpoints.get(e))?t:null}async syncProjectSaveState(e){await r.OP.init();let t=await r.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,i)=>{i.d(t,{Y:()=>o});var n=i(4520),r=i(3999);class s{async initDB(){if(!this.isInitialized)return new Promise((e,t)=>{let i=indexedDB.open(this.dbName,1);i.onerror=()=>{r.v.error("Failed to open checkpoint database"),t(i.error)},i.onsuccess=()=>{this.db=i.result,this.isInitialized=!0,this.loadCheckpointsFromDB().then(()=>e())},i.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 i=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).getAll();i.onsuccess=()=>{let t=i.result;for(let e of(this.checkpoints.clear(),t)){var n;let t={...e,kind:e.kind||"auto",baseRevisionId:null!=(n=e.baseRevisionId)?n:null,files:new Map(e.files),directories:new Set(e.directories)};this.checkpoints.set(t.id,t)}e()},i.onerror=()=>{r.v.error("Failed to load checkpoints from DB"),t(i.error)}})}async saveCheckpointToDB(e){var t;if(await this.initDB(),!this.db)return;let i={...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 n=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(i);n.onsuccess=()=>e(),n.onerror=()=>{r.v.error("Failed to save checkpoint to DB"),t(n.error)}})}async deleteCheckpointFromDB(e){if(await this.initDB(),this.db)return new Promise((t,i)=>{let n=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(e);n.onsuccess=()=>t(),n.onerror=()=>{r.v.error("Failed to delete checkpoint from DB"),i(n.error)}})}async createCheckpoint(e,t){var i;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};await this.initDB(),await n.OP.init();let o=await n.OP.listDirectory(e,"/"),a=new Map,l=new Set;for(let t of o){let i=t.path.split("/").filter(Boolean);for(let e=1;e<=i.length-1;e++){let t="/"+i.slice(0,e).join("/");l.add(t)}if("string"==typeof t.content)a.set(t.path,t.content);else try{let i=await n.OP.readFile(e,t.path);"string"==typeof i.content&&a.set(t.path,i.content)}catch(e){r.v.error("Failed to read file for checkpoint: ".concat(t.path),e)}}let c={id:"cp_".concat(Date.now()),timestamp:new Date().toISOString(),description:t,files:a,directories:l,projectId:e,kind:s.kind||"auto",baseRevisionId:null!=(i=s.baseRevisionId)?i: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),r.v.debug("[Checkpoint] Deleted old checkpoint: ".concat(e.id));return c}async restoreCheckpoint(e){if("string"!=typeof e)return r.v.error("[Checkpoint] Invalid checkpoint ID type:",typeof e,e),!1;if(!e.startsWith("cp_")||e.length<6)return r.v.error("[Checkpoint] Invalid checkpoint ID format:",e),!1;await this.initDB();let t=this.checkpoints.get(e);if(!t&&(r.v.debug("[Checkpoint] Checkpoint ".concat(e," not in memory, checking database...")),await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e)))){r.v.error("[Checkpoint] Checkpoint not found in database: ".concat(e));let t=Array.from(this.checkpoints.keys());return r.v.debug("[Checkpoint] Available checkpoints:",t),!1}await n.OP.init();try{let i=await n.OP.listDirectory(t.projectId,"/"),r=new Set;for(let e of i){let t=e.path.split("/").filter(Boolean);for(let e=1;e<=t.length-1;e++){let i="/"+t.slice(0,e).join("/");r.add(i)}}for(let e of i)t.files.has(e.path)||await n.OP.deleteFile(t.projectId,e.path);for(let e of Array.from(r).filter(e=>!t.directories||!t.directories.has(e)).sort((e,t)=>t.length-e.length))try{await n.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(!r.has(e))try{await n.OP.createDirectory(t.projectId,e)}catch(e){}}for(let[e,r]of t.files)i.some(t=>t.path===e)?await n.OP.updateFile(t.projectId,e,r):await n.OP.createFile(t.projectId,e,r);return this.currentCheckpoint=e,!0}catch(e){return r.v.error("Failed to restore checkpoint:",e),!1}}async getCheckpoints(e){return await this.initDB(),await this.loadCheckpointsFromDB(),Array.from(this.checkpoints.values()).filter(t=>t.projectId===e).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))}getCurrentCheckpoint(){return this.currentCheckpoint&&this.checkpoints.get(this.currentCheckpoint)||null}async checkpointExists(e){return!!e&&"string"==typeof e&&(await this.initDB(),!!this.checkpoints.has(e)||(await this.loadCheckpointsFromDB(),this.checkpoints.has(e)))}async clearCheckpoints(e){await this.initDB();let t=[];for(let[i,n]of this.checkpoints)n.projectId===e&&(this.checkpoints.delete(i),t.push(i));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,i)=>{i.d(t,{$:()=>l});var n=i(5155);i(2115);var r=i(9708),s=i(2085),o=i(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:i,size:s,asChild:l=!1,...c}=e,d=l?r.DX:"button";return(0,n.jsx)(d,{"data-slot":"button",className:(0,o.cn)(a({variant:i,size:s,className:t})),...c})}},7250:(e,t,i)=>{i.d(t,{t:()=>R});var n=i(5155),r=i(2115),s=i(8202),o=i(1052),a=i(86),l=i(1173),c=i(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,i){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==i?void 0:i.fileTree)},{role:"user",content:e}];try{if("anthropic"===this.provider)return this.generateWithToolsAnthropic(n,t);if("gemini"===this.provider)return this.generateWithToolsGemini(n,t);return this.generateWithToolsOpenAI(n,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 i=[{role:"system",content:(0,o.m)(null==t?void 0:t.fileTree)},{role:"user",content:e}];return"anthropic"===this.provider?this.generateAnthropic(i):"gemini"===this.provider?this.generateGemini(i):this.generateOpenAI(i)}async generateWithToolsOpenAI(e,t){let i=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",n={"Content-Type":"application/json"};this.apiKey&&(n.Authorization="Bearer ".concat(this.apiKey)),"openrouter"===this.provider&&(n["HTTP-Referer"]=window.location.origin,n["X-Title"]="DeepStudio"),this.providerConfig.customHeaders&&Object.assign(n,this.providerConfig.customHeaders);let r=await fetch("".concat(i,"/chat/completions"),{method:"POST",headers:n,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(!r.ok){let e=await r.text();throw Error("".concat(this.providerConfig.name," API error: ").concat(e))}return this.parseStreamResponse(r)}async generateOpenAI(e){var t,i;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");let s=await fetch("".concat(n,"/chat/completions"),{method:"POST",headers:r,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==(i=(await s.json()).choices[0])||null==(t=i.message)?void 0:t.content)||""}async generateWithToolsAnthropic(e,t){var i;let n=(null==(i=e.find(e=>"system"===e.role))?void 0:i.content)||"",r=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:r,system:n,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,i;let n=(null==(t=e.find(e=>"system"===e.role))?void 0:t.content)||"",r=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:r,system:n,temperature:this.temperature,max_tokens:this.maxTokens})});if(!s.ok){let e=await s.text();throw Error("Anthropic API error: ".concat(e))}return(null==(i=(await s.json()).content[0])?void 0:i.text)||""}async generateWithToolsGemini(e,t){throw Error("Gemini tool calling not yet implemented. Please use OpenRouter or another provider.")}async generateGemini(e){var t,i,n;let r=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:r,generationConfig:{temperature:this.temperature,maxOutputTokens:this.maxTokens}})});if(!s.ok){let e=await s.text();throw Error("Gemini API error: ".concat(e))}return(null==(n=(await s.json()).candidates[0])||null==(i=n.content)||null==(t=i.parts[0])?void 0:t.text)||""}async *parseStreamResponse(e){var t,i,n,r,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,x="",w=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==(i=u.usage)?void 0:i.prompt_tokens)?o:0,t=null!=(a=null==(n=u.usage)?void 0:n.completion_tokens)?a:0,l=null!=(d=null==(r=u.usage)?void 0:r.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),i=t.total_cost,n="number"==typeof i&&Number.isFinite(i)&&i>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:n?i:void 0,model:this.model,provider:this.provider,generationId:C||void 0,isEstimated:!n}}catch(e){c.v.error("Error parsing OpenRouter usage header:",e)}}}for(;;){let{done:e,value:t}=await v.read();if(e)break;let i=(x+=y.decode(t,{stream:!0})).split("\n");for(let e of(x=i.pop()||"",i))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),i=null==(h=e.choices)||null==(u=h[0])?void 0:u.delta;if((null==i?void 0:i.content)&&(yield{type:"content",content:i.content}),null==i?void 0:i.tool_calls)for(let e of i.tool_calls)e.id&&(w&&(yield{type:"tool_call",toolCall:w}),w={id:e.id,type:"function",function:{name:(null==(f=e.function)?void 0:f.name)||"",arguments:""}}),(null==(g=e.function)?void 0:g.arguments)&&w&&(w.argumentsBuffer=(w.argumentsBuffer||"")+e.function.arguments,w.function&&(w.function.arguments=w.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(w)try{let e=w.argumentsBuffer;e&&w.function&&(w.function.arguments=e),yield{type:"tool_call",toolCall:w}}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,i,n,r,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==(n=e.delta)||null==(i=n.text_delta)?void 0:i.text))yield{type:"content",content:e.delta.text_delta.text};else if("content_block_start"===e.type&&(null==(r=e.content_block)?void 0:r.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 i=await fetch("/api/validate-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,provider:t})});if(!i.ok)return!1;let{valid:n}=await i.json();return n}catch(e){return!1}}static async getAvailableModels(e,t){var i,n;let r=t||s.s.getSelectedProvider()||"openrouter",o=(0,a.sO)(r),l=e||s.s.getProviderApiKey(r);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:r})});if(!e.ok)return(null==(i=o.models)?void 0:i.map(e=>e.id))||[];let{models:t}=await e.json();return t||[]}catch(e){return(null==(n=o.models)?void 0:n.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=i(7168),u=i(9852),h=i(2714),m=i(8749),g=i(2657),f=i(5196),v=i(4416),y=i(3786),x=i(6671),w=i(8145),b=i(823),C=i(9376),k=i(3311),j=i(1539),S=i(2970),_=i(5487),T=i(3314),P=i(1154),I=i(6474),N=i(7924),A=i(4973),O=i(3091);function F(e){let{provider:t,value:i,onChange:o,className:l,hideModelDetails:m}=e,g=t||s.s.getSelectedProvider(),f=(0,a.sO)(g),[y,F]=(0,r.useState)([]),[E,R]=(0,r.useState)(!0),[D,M]=(0,r.useState)(""),[U,L]=(0,r.useState)(!1),[B,q]=(0,r.useState)(""),[W,K]=(0,r.useState)(!1),z=e=>e.name,H=(0,r.useCallback)(async()=>{try{R(!0);let e=s.s.getProviderApiKey(g);if(f.apiKeyRequired&&!e){K(!0),f.models?F(f.models):F([]);return}K(!1);let t=s.s.getCachedModels(g);if(t){let e=t.models;F(e),"openrouter"===g&&(0,O.V)("openrouter",e);return}let i=[];if("openrouter"===g){let e=await (0,A.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)};i=e.map(e=>{var i,n,r,s,o,a,l;let c=(null==(i=e.pricing)?void 0:i.prompt)?Number(e.pricing.prompt):void 0,d=(null==(n=e.pricing)?void 0:n.completion)?Number(e.pricing.completion):void 0,p=(null==(r=e.pricing)?void 0:r.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 i=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:[];F(i),f.isLocal&&0===i.length&&x.oR.warning("No models found in ".concat(f.name,". Please load some models in the application."),{duration:5e3}),i.length>0&&(s.s.setCachedModels(g,i),"openrouter"===g&&(0,O.V)("openrouter",i))}catch(e){c.v.error("Failed to load models:",e),f.isLocal&&x.oR.error("".concat(f.name," server not running. Please start the server and load some models."),{duration:5e3}),f.models&&F(f.models)}finally{R(!1)}},[g,f]);(0,r.useEffect)(()=>{F([]),M(""),R(!0),s.s.clearModelCache(g),H()},[g,H]),(0,r.useEffect)(()=>{if(0===y.length||E)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,E,g,o]),(0,r.useEffect)(()=>{let e=()=>{setTimeout(()=>{H()},100)};return window.addEventListener("apiKeyUpdated",e),()=>{window.removeEventListener("apiKeyUpdated",e)}},[H]);let J=e=>{M(e),s.s.setProviderModel(g,e),null==o||o(e),L(!1),q("")},$=e=>{let t=e.id.toLowerCase();return t.includes("deepseek")?(0,n.jsx)(C.A,{className:"h-3 w-3"}):t.includes("claude")?(0,n.jsx)(k.A,{className:"h-3 w-3"}):t.includes("gpt")?(0,n.jsx)(j.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,n.jsx)(S.A,{className:"h-3 w-3"}):t.includes("llama")?(0,n.jsx)(_.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,n.jsx)(T.A,{className:"h-3 w-3"}):null},G=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,r.useMemo)(()=>{if(!B.trim())return y;let e=B.toLowerCase();return y.filter(t=>{let i=t.id.toLowerCase(),n=z(t).toLowerCase(),r=t.id.split("/")[0].toLowerCase();return i.includes(e)||n.includes(e)||r.includes(e)})},[y,B]),Y=y.find(e=>e.id===D);return E?(0,n.jsxs)("div",{className:l,children:[(0,n.jsx)(h.J,{children:"AI Model"}),(0,n.jsxs)("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted",children:[(0,n.jsx)(P.A,{className:"h-4 w-4 animate-spin"}),(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):W?(0,n.jsxs)("div",{className:l,children:[(0,n.jsx)(h.J,{children:"AI Model"}),(0,n.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,n.jsxs)("span",{className:"text-sm text-orange-600 dark:text-orange-400",children:["API key required for ",f.name]})}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Set your API key in settings to load available models"})]}):(0,n.jsxs)("div",{className:l,children:[(0,n.jsx)(h.J,{htmlFor:"model-select",children:"AI Model"}),(0,n.jsxs)(b.AM,{open:U,onOpenChange:L,children:[(0,n.jsx)(b.Wv,{asChild:!0,children:(0,n.jsxs)(p.$,{variant:"outline",role:"combobox","aria-expanded":U,className:"w-full justify-between font-normal",children:[Y?(0,n.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[$(Y),(0,n.jsx)("span",{className:"truncate",children:z(Y)})]}):(0,n.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,n.jsx)(I.A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),(0,n.jsxs)(b.hl,{className:"w-[32rem] p-0",align:"start",side:"bottom",sideOffset:5,avoidCollisions:!1,children:[(0,n.jsxs)("div",{className:"flex items-center border-b px-3",children:[(0,n.jsx)(N.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,n.jsx)(u.p,{placeholder:"Search models...",value:B,onChange:e=>q(e.target.value),className:"h-10 border-0 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),B&&(0,n.jsx)(p.$,{variant:"ghost",size:"sm",onClick:()=>q(""),className:"h-5 w-5 p-0",children:(0,n.jsx)(v.A,{className:"h-3 w-3"})})]}),(0,n.jsx)("div",{className:"max-h-[400px] min-h-[300px] overflow-y-auto",children:0===V.length?(0,n.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):V.map(e=>(0,n.jsx)("button",{onClick:()=>J(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,n.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[$(e),(0,n.jsx)("span",{className:"font-medium",children:z(e)}),"openrouter"===g&&(0,n.jsx)(w.E,{variant:"secondary",className:"text-xs ".concat(G(e.id)),children:e.id.split("/")[0]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[(0,n.jsxs)("span",{children:["Context: ",Math.round(e.contextLength/1e3),"K"]}),e.pricing&&(0===e.pricing.input&&0===e.pricing.output?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"•"}),(0,n.jsx)("span",{children:"Free"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"•"}),(0,n.jsxs)("span",{children:[(0,A.WK)(e.pricing.input),"/K | ",(0,A.WK)(e.pricing.output),"/K"]})]})),!e.pricing&&"openrouter"!==g&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"•"}),(0,n.jsx)("span",{children:"Pricing varies"})]})]})]})},e.id))})]})]}),!m&&Y&&(0,n.jsxs)("div",{className:"mt-1 text-xs text-muted-foreground max-h-[150px] overflow-y-auto pr-2",children:[(0,n.jsx)("div",{className:"font-medium mb-1",children:Y.pricing?0===Y.pricing.input&&0===Y.pricing.output?"Free":"Input: ".concat((0,A.WK)(Y.pricing.input),"/K • Output: ").concat((0,A.WK)(Y.pricing.output),"/K"):"Pricing varies by provider"}),Y.description&&(0,n.jsx)("div",{children:Y.description})]})]})}var E=i(5784);function R(e){let{onClose:t,onModelChange:i}=e,[o,l]=(0,r.useState)({}),[c,w]=(0,r.useState)(()=>s.s.getSelectedProvider()),[b,C]=(0,r.useState)(!1),[k,j]=(0,r.useState)(!1),[S,_]=(0,r.useState)(null),[T,P]=(0,r.useState)("");(0,r.useEffect)(()=>{l(s.s.getSettings());let e=s.s.getSelectedProvider();P(s.s.getProviderApiKey(e)||"")},[]),(0,r.useEffect)(()=>{P(s.s.getProviderApiKey(c)||""),_(null)},[c]);let I=e=>{P(e),s.s.setProviderApiKey(c,e),_(null),s.s.clearModelCache(c),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:c,hasKey:!!e}}))},N=async()=>{if(!T)return void x.oR.error("Please enter an API key");j(!0);try{let e=await d.validateApiKey(T,c);_(e),e?x.oR.success("API key is valid!"):x.oR.error("Invalid API key")}catch(e){_(!1),x.oR.error("Failed to validate API key")}finally{j(!1)}},A=(0,a.sO)(c);return(0,n.jsxs)("div",{className:"space-y-6",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h3",{className:"font-medium text-sm",children:"Model Settings"}),(0,n.jsx)("p",{className:"text-muted-foreground text-xs mt-1",children:"Configure your AI model and API connection"})]}),(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(h.J,{htmlFor:"provider",children:"AI Provider"}),(0,n.jsxs)(E.l6,{value:c,onValueChange:e=>{w(e),s.s.setSelectedProvider(e),P(s.s.getProviderApiKey(e)||""),_(null)},children:[(0,n.jsx)(E.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,n.jsx)(E.yv,{placeholder:"Select a provider",children:c&&(0,n.jsxs)("div",{className:"flex flex-col text-left",children:[(0,n.jsx)("span",{className:"font-medium",children:A.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:A.description})]})})}),(0,n.jsx)(E.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,n.jsx)(E.eb,{value:e.id,children:(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsx)("span",{className:"font-medium",children:e.name}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:e.description})]})},e.id))})]})]}),(A.apiKeyRequired||A.isLocal)&&(0,n.jsxs)("div",{children:[(0,n.jsxs)(h.J,{htmlFor:"api-key",children:[A.name," API Key",!A.apiKeyRequired&&(0,n.jsx)("span",{className:"text-muted-foreground text-xs ml-1",children:"(optional)"})]}),(0,n.jsxs)("div",{className:"flex gap-2 mt-2",children:[(0,n.jsxs)("div",{className:"relative flex-1",children:[(0,n.jsx)(u.p,{id:"api-key",type:b?"text":"password",value:T,onChange:e=>I(e.target.value),placeholder:A.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,n.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>C(!b),children:b?(0,n.jsx)(m.A,{className:"h-4 w-4"}):(0,n.jsx)(g.A,{className:"h-4 w-4"})})]}),(0,n.jsx)(p.$,{onClick:N,disabled:k||!T,size:"sm",children:k?"Validating...":"Validate"}),null!==S&&(0,n.jsx)("div",{className:"flex items-center",children:S?(0,n.jsx)(f.A,{className:"h-5 w-5 text-green-500"}):(0,n.jsx)(v.A,{className:"h-5 w-5 text-red-500"})})]}),A.apiKeyHelpUrl&&(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,n.jsxs)("a",{href:A.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[A.name," ",(0,n.jsx)(y.A,{className:"h-3 w-3"})]})]}),A.isLocal&&!A.apiKeyRequired&&(0,n.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",A.name,". Only needed if you've configured authentication on your local server."]})]}),!A.apiKeyRequired&&A.isLocal&&(0,n.jsxs)("div",{className:"text-sm text-muted-foreground p-3 border rounded-md bg-muted/50",children:[(0,n.jsx)("p",{className:"font-medium mb-1",children:"Local Provider"}),(0,n.jsxs)("p",{children:["Make sure ",A.name," is running on your machine."]}),(0,n.jsxs)("p",{children:["Default endpoint: ",(0,n.jsx)("code",{className:"text-xs",children:A.baseUrl})]}),"lmstudio"===c&&(0,n.jsxs)("div",{className:"mt-2 text-xs",children:[(0,n.jsx)("p",{className:"font-medium",children:"For tool use support:"}),(0,n.jsx)("p",{children:"• Load a model like qwen/qwen3-4b-thinking-2507"}),(0,n.jsx)("p",{children:"• Start the local server in LM Studio"}),(0,n.jsx)("p",{children:"• Models will be automatically discovered"})]})]}),(0,n.jsx)(F,{provider:c,onChange:e=>{null==i||i(e)},className:"space-y-2"})]}),t&&(0,n.jsx)("div",{className:"flex justify-end pt-4 border-t",children:(0,n.jsx)(p.$,{onClick:t,size:"sm",children:"Done"})})]})}},8145:(e,t,i)=>{i.d(t,{E:()=>a});var n=i(5155);i(2115);var r=i(2085),s=i(3999);let o=(0,r.F)("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function a(e){let{className:t,variant:i,...r}=e;return(0,n.jsx)("div",{className:(0,s.cn)(o({variant:i}),t),...r})}},8202:(e,t,i)=>{i.d(t,{s:()=>r});class n{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 i=this.getSettings();i[e]=t,localStorage.setItem(this.STORAGE_KEY,JSON.stringify(i))}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 i=this.getSettings();return(null==(t=i.providerKeys)?void 0:t[e])?i.providerKeys[e]:"openrouter"===e&&i.openRouterApiKey?i.openRouterApiKey:null}setProviderApiKey(e,t){let i=this.getSettings().providerKeys||{};i[e]=t,this.setSetting("providerKeys",i),"openrouter"===e&&this.setSetting("openRouterApiKey",t)}getProviderModel(e){var t;let i=this.getSettings();return(null==(t=i.providerModels)?void 0:t[e])?i.providerModels[e]:"openrouter"===e&&i.defaultModel?i.defaultModel:null}setProviderModel(e,t){let i=this.getSettings().providerModels||{};i[e]=t,this.setSetting("providerModels",i),"openrouter"===e&&this.setSetting("defaultModel",t)}getModelPricing(e,t){var i,n;let r=null==(i=this.getSettings().modelPricing)?void 0:i[e];return r&&(r[t]||r["".concat(e,"/").concat(t)]||(t.includes("/")?r[null!=(n=t.split("/").pop())?n:""]:null))||null}setModelPricing(e,t,i){let n={...this.getSettings().modelPricing||{}},r={...n[e]||{}};r[t]=i,n[e]=r,this.setSetting("modelPricing",n)}setProviderPricing(e,t){if(!t||0===Object.keys(t).length)return;let i={...this.getSettings().modelPricing||{}},n={...i[e]||{}};for(let[e,i]of Object.entries(t))n[e]=i;i[e]=n,this.setSetting("modelPricing",i)}clearProviderPricing(e){var t;if(!e)return void this.setSetting("modelPricing",{});let i=this.getSettings();if(!(null==(t=i.modelPricing)?void 0:t[e]))return;let n={...i.modelPricing||{}};delete n[e],this.setSetting("modelPricing",n)}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 i=this.getCurrentSession();i||(i=this.startNewSession()),i.totalCost+=t,i.messageCount+=1;let n=e.provider||"unknown";i.providerBreakdown[n]||(i.providerBreakdown[n]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),i.providerBreakdown[n].cost+=t,i.providerBreakdown[n].tokenUsage.input+=e.promptTokens,i.providerBreakdown[n].tokenUsage.output+=e.completionTokens,i.providerBreakdown[n].requestCount+=1;let r=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};r.total+=t,r.byProvider[n]=(r.byProvider[n]||0)+t,this.setSetting("currentSession",i),this.setSetting("lifetimeCosts",r)}adjustSessionCost(e,t,i){if(!t&&!i)return;let n=this.getCurrentSession();if(!n)return;let r=e||"unknown";n.totalCost+=t,n.providerBreakdown[r]||(n.providerBreakdown[r]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),n.providerBreakdown[r].cost+=t,i&&(n.providerBreakdown[r].tokenUsage.input+=i.input,n.providerBreakdown[r].tokenUsage.output+=i.output);let s=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};s.total+=t,s.byProvider[r]=(s.byProvider[r]||0)+t,this.setSetting("currentSession",n),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 i=t.totalCost/e.dailyLimit*100;return i>=100?{warning:!1,exceeded:!0,message:"Daily limit of $".concat(e.dailyLimit.toFixed(2)," exceeded")}:e.warningThreshold&&i>=e.warningThreshold?{warning:!0,exceeded:!1,message:"".concat(i.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 i=null==(t=this.getSettings().modelCache)?void 0:t[e];return i?new Date>new Date(i.expiresAt)?(this.clearModelCache(e),null):i:null}setCachedModels(e,t){let i=this.getSettings(),n=new Date,r=new Date(n.getTime()+864e5),s=i.modelCache||{};s[e]={models:t,timestamp:n.toISOString(),expiresAt:r.toISOString()},this.setSetting("modelCache",s)}clearModelCache(e){if(e){let t=this.getSettings().modelCache||{};delete t[e],this.setSetting("modelCache",t)}else this.setSetting("modelCache",{})}isCacheValid(e){return null!==this.getCachedModels(e)}constructor(){this.STORAGE_KEY="deepstudio-settings"}}let r=new n},9852:(e,t,i)=>{i.d(t,{p:()=>s});var n=i(5155);i(2115);var r=i(3999);function s(e){let{className:t,type:i,...s}=e;return(0,n.jsx)("input",{type:i,"data-slot":"input",className:(0,r.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,i)=>{i.d(t,{j:()=>d});var n=i(5155),r=i(2115),s=i(7168),o=i(8145),a=i(5221),l=i(7863),c=i(6474);function d(e){let{title:t,subtitle:i,badge:d,onLogoClick:p,actions:u=[],mobileMenuContent:h,desktopOnlyContent:m,className:g="",leftText:f}=e,[v,y]=(0,r.useState)(!1);return(0,n.jsxs)("div",{className:"border-b bg-card shadow-sm relative z-20 ".concat(g),children:[(0,n.jsxs)("div",{className:"px-3 py-2 flex items-center justify-between",children:[(0,n.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,n.jsx)(a.g,{width:24,height:24}),f&&(0,n.jsx)("span",{className:"font-semibold text-lg hidden md:inline",children:f})]}),(0,n.jsx)("div",{className:"flex items-center gap-2 flex-1 justify-center md:justify-start md:ml-6",children:f?(0,n.jsx)("h1",{className:"text-lg font-semibold md:hidden",children:f}):t?(0,n.jsxs)(n.Fragment,{children:[t&&(0,n.jsx)("h1",{className:"text-lg md:text-xl font-semibold",children:t}),d&&(0,n.jsx)(o.E,{variant:"secondary",children:d})]}):null}),!f&&!t&&i&&(0,n.jsx)("div",{className:"hidden md:flex items-center flex-1 ml-6",children:(0,n.jsx)("span",{className:"text-sm text-muted-foreground",children:i})}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("div",{className:"hidden md:flex items-center gap-2",children:[u.map(e=>e.content?(0,n.jsx)("div",{children:e.content},e.id):(0,n.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,n.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id)),m]}),(u.length>0||h)&&(0,n.jsx)(s.$,{variant:"ghost",size:"icon",onClick:()=>y(!v),className:"h-8 w-8 md:hidden",children:v?(0,n.jsx)(l.A,{className:"h-4 w-4"}):(0,n.jsx)(c.A,{className:"h-4 w-4"})})]})]}),v&&(u.length>0||h)&&(0,n.jsxs)("div",{className:"md:hidden border-t bg-muted/30 px-4 py-4 space-y-3",children:[!f&&!t&&i&&(0,n.jsx)("div",{className:"pb-2 border-b border-border/50",children:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:i})}),(0,n.jsx)("div",{className:"space-y-2",children:u.map(e=>e.content?(0,n.jsx)("div",{children:e.content},e.id):(0,n.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,n.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id))}),h&&(0,n.jsx)("div",{className:"pt-2 border-t border-border/50",children:h})]})]})}}}]);
\ No newline at end of file