diff --git "a/.next/server/chunks/617.js" "b/.next/server/chunks/617.js" --- "a/.next/server/chunks/617.js" +++ "b/.next/server/chunks/617.js" @@ -1,4 +1,26 @@ -exports.id=617,exports.ids=[617],exports.modules={4950:(e,t,r)=>{"use strict";r.d(t,{s:()=>s});class i{getSettings(){return{}}setSetting(e,t){}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){let t=this.getSettings();return t.providerKeys?.[e]?t.providerKeys[e]:"openrouter"===e&&t.openRouterApiKey?t.openRouterApiKey:null}setProviderApiKey(e,t){let r=this.getSettings().providerKeys||{};r[e]=t,this.setSetting("providerKeys",r),"openrouter"===e&&this.setSetting("openRouterApiKey",t)}getProviderModel(e){let t=this.getSettings();return t.providerModels?.[e]?t.providerModels[e]:"openrouter"===e&&t.defaultModel?t.defaultModel:null}setProviderModel(e,t){let r=this.getSettings().providerModels||{};r[e]=t,this.setSetting("providerModels",r),"openrouter"===e&&this.setSetting("defaultModel",t)}getModelPricing(e,t){let r=this.getSettings(),i=r.modelPricing?.[e];return i&&(i[t]||i[`${e}/${t}`]||(t.includes("/")?i[t.split("/").pop()??""]:null))||null}setModelPricing(e,t,r){}setProviderPricing(e,t){}clearProviderPricing(e){}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(){}getCostSettings(){return this.getSettings().costSettings||{showCosts:!0,warningThreshold:80}}setCostSettings(e){this.setSetting("costSettings",e)}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 r=this.getCurrentSession();r||(r=this.startNewSession()),r.totalCost+=t,r.messageCount+=1;let i=e.provider||"unknown";r.providerBreakdown[i]||(r.providerBreakdown[i]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),r.providerBreakdown[i].cost+=t,r.providerBreakdown[i].tokenUsage.input+=e.promptTokens,r.providerBreakdown[i].tokenUsage.output+=e.completionTokens,r.providerBreakdown[i].requestCount+=1;let s=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};s.total+=t,s.byProvider[i]=(s.byProvider[i]||0)+t,this.setSetting("currentSession",r),this.setSetting("lifetimeCosts",s)}adjustSessionCost(e,t,r){if(!t&&!r)return;let i=this.getCurrentSession();if(!i)return;let s=e||"unknown";i.totalCost+=t,i.providerBreakdown[s]||(i.providerBreakdown[s]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),i.providerBreakdown[s].cost+=t,r&&(i.providerBreakdown[s].tokenUsage.input+=r.input,i.providerBreakdown[s].tokenUsage.output+=r.output);let o=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};o.total+=t,o.byProvider[s]=(o.byProvider[s]||0)+t,this.setSetting("currentSession",i),this.setSetting("lifetimeCosts",o)}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 r=t.totalCost/e.dailyLimit*100;return r>=100?{warning:!1,exceeded:!0,message:`Daily limit of $${e.dailyLimit.toFixed(2)} exceeded`}:e.warningThreshold&&r>=e.warningThreshold?{warning:!0,exceeded:!1,message:`${r.toFixed(0)}% of daily limit used ($${t.totalCost.toFixed(2)} of $${e.dailyLimit.toFixed(2)})`}:{warning:!1,exceeded:!1}}getCachedModels(e){let t=this.getSettings(),r=t.modelCache?.[e];return r?new Date>new Date(r.expiresAt)?(this.clearModelCache(e),null):r:null}setCachedModels(e,t){let r=this.getSettings(),i=new Date,s=new Date(i.getTime()+864e5),o=r.modelCache||{};o[e]={models:t,timestamp:i.toISOString(),expiresAt:s.toISOString()},this.setSetting("modelCache",o)}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 s=new i},8584:(e,t,r)=>{Promise.resolve().then(r.bind(r,53014)),Promise.resolve().then(r.bind(r,99197)),Promise.resolve().then(r.bind(r,94593))},10158:(e,t,r)=>{"use strict";r.d(t,{OM:()=>o,sO:()=>s});let i={openrouter:{id:"openrouter",name:"OpenRouter",description:"Access multiple AI models through a unified API",apiKeyRequired:!0,apiKeyPlaceholder:"sk-or-...",apiKeyHelpUrl:"https://openrouter.ai/keys",baseUrl:"https://openrouter.ai/api/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},openai:{id:"openai",name:"OpenAI",description:"GPT-4, GPT-3.5 and other OpenAI models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-...",apiKeyHelpUrl:"https://platform.openai.com/api-keys",baseUrl:"https://api.openai.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},anthropic:{id:"anthropic",name:"Anthropic",description:"Claude 3.5 Sonnet, Haiku and Opus models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-ant-...",apiKeyHelpUrl:"https://console.anthropic.com/settings/keys",baseUrl:"https://api.anthropic.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},groq:{id:"groq",name:"Groq",description:"Ultra-fast inference with Llama and Mixtral models",apiKeyRequired:!0,apiKeyPlaceholder:"gsk_...",apiKeyHelpUrl:"https://console.groq.com/keys",baseUrl:"https://api.groq.com/openai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},gemini:{id:"gemini",name:"Google Gemini",description:"Google's multimodal AI models",apiKeyRequired:!0,apiKeyPlaceholder:"AI...",apiKeyHelpUrl:"https://aistudio.google.com/apikey",baseUrl:"https://generativelanguage.googleapis.com/v1beta",models:[{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash",description:"Latest experimental Gemini model",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",description:"Advanced reasoning and analysis",contextLength:2097152,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",description:"Fast and versatile",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0}],supportsFunctions:!0,supportsStreaming:!0},ollama:{id:"ollama",name:"Ollama",description:"Run models locally with Ollama",apiKeyRequired:!1,baseUrl:"http://localhost:11434/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},lmstudio:{id:"lmstudio",name:"LM Studio",description:"Local model server with tool use support",apiKeyRequired:!1,baseUrl:"http://localhost:1234/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},sambanova:{id:"sambanova",name:"SambaNova",description:"High-performance AI chips for inference",apiKeyRequired:!0,apiKeyPlaceholder:"SambaNova API Key",apiKeyHelpUrl:"https://cloud.sambanova.ai/apis",baseUrl:"https://api.sambanova.ai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0}};function s(e){return i[e]}function o(){return Object.values(i)}},19424:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,16444,23)),Promise.resolve().then(r.t.bind(r,16042,23)),Promise.resolve().then(r.t.bind(r,88170,23)),Promise.resolve().then(r.t.bind(r,49477,23)),Promise.resolve().then(r.t.bind(r,29345,23)),Promise.resolve().then(r.t.bind(r,12089,23)),Promise.resolve().then(r.t.bind(r,46577,23)),Promise.resolve().then(r.t.bind(r,31307,23))},21736:(e,t,r)=>{Promise.resolve().then(r.bind(r,41900)),Promise.resolve().then(r.bind(r,39035)),Promise.resolve().then(r.bind(r,80363))},22106:(e,t,r)=>{"use strict";r.d(t,{B:()=>o});var i=r(79170),s=r.n(i);class o{constructor(e,t,r){this.blobUrls=new Map,this.fileHashes=new Map,this.templateCache=new Map,this.partialsRegistered=!1,this.vfs=e,this.projectId=t,this.baseUrl="",r&&(this.blobUrls=new Map(r)),this.handlebars=s().create(),this.registerHelpers()}registerHelpers(){this.handlebars.registerHelper("eq",(e,t)=>e===t),this.handlebars.registerHelper("ne",(e,t)=>e!==t),this.handlebars.registerHelper("lt",(e,t)=>ee>t),this.handlebars.registerHelper("lte",(e,t)=>e<=t),this.handlebars.registerHelper("gte",(e,t)=>e>=t),this.handlebars.registerHelper("and",function(){let e=Array.prototype.slice.call(arguments,0,-1);return e.every(e=>e)}),this.handlebars.registerHelper("or",function(){let e=Array.prototype.slice.call(arguments,0,-1);return e.some(e=>e)}),this.handlebars.registerHelper("not",e=>!e),this.handlebars.registerHelper("add",(e,t)=>e+t),this.handlebars.registerHelper("subtract",(e,t)=>e-t),this.handlebars.registerHelper("multiply",(e,t)=>e*t),this.handlebars.registerHelper("divide",(e,t)=>e/t),this.handlebars.registerHelper("uppercase",e=>e?.toUpperCase()),this.handlebars.registerHelper("lowercase",e=>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 r=e.content;this.handlebars.registerPartial(t,r)}this.partialsRegistered=!0}catch(e){}}async compileTemplate(e,t={}){let r=this.templateCache.get(e);if(!r)try{let t=(await this.vfs.readFile(this.projectId,e)).content;r=this.handlebars.compile(t),this.templateCache.set(e,r)}catch(t){return console.error(`Failed to compile template ${e}:`,t),""}return r(t)}async compileProject(e=!1){await this.registerPartials();let t=await this.vfs.listDirectory(this.projectId,"/"),r=new Map(this.blobUrls),i=new Map,s=[];for(let o of t){let t;if("template"===o.type)continue;if("image"===o.type||"video"===o.type)t={path:o.path,content:o.content,mimeType:o.mimeType};else if("html"===o.type)t=await this.processHTML(o);else if("js"===o.type)t=await this.processJS(o);else{if("css"===o.type)continue;t={path:o.path,content:o.content,mimeType:o.mimeType}}let n=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===n&&r.has(t.path)){let e=r.get(t.path);i.set(t.path,e),t.blobUrl=e,r.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),r=URL.createObjectURL(e);i.set(t.path,r),t.blobUrl=r,this.fileHashes.set(t.path,n)}s.push(t)}let o=[...s];for(let s of t)if("css"===s.type){let t=await this.processCSS(s,i),n=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===n&&r.has(t.path)){let e=r.get(t.path);i.set(t.path,e),t.blobUrl=e,r.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),r=URL.createObjectURL(e);i.set(t.path,r),t.blobUrl=r,this.fileHashes.set(t.path,n)}o.push(t)}let n=this.generateRoutes(t);if(e)for(let[,e]of r)URL.revokeObjectURL(e);else e||this.cleanupBlobUrls();return this.blobUrls=i,{entryPoint:"/index.html",files:o,routes:n,blobUrls:this.blobUrls}}hashContent(e){let t=0;if(e instanceof ArrayBuffer){let r=new Uint8Array(e);for(let e=0;e{if(r.startsWith("http")||r.startsWith("data:")||r.startsWith("//"))return e;let i=this.normalizePath(r);return t.some(e=>e.path===i),e});return r}async processUrlReferences(e,t){return e.replace(/url\(['"]?([^'")]+)['"]?\)/g,(e,r)=>{if(r.startsWith("http")||r.startsWith("data:")||r.startsWith("//")||r.startsWith("blob:"))return e;let i=this.normalizePath(r),s=t.get(i);return s?`url('${s}')`: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),r=t?t[1]:e.name.replace(".html",""),i=e.path.replace(".html","")||"/";return{path:"/index"===i?"/":i,file:e.path,title:r}})}extractTitle(e){let t=e.match(/<title>([^<]+)<\/title>/i);return t?t[1]:"Untitled Page"}cleanupBlobUrls(){for(let e of this.blobUrls.values())URL.revokeObjectURL(e);this.blobUrls.clear(),this.templateCache.clear(),this.partialsRegistered=!1}async getCompiledFile(e){try{let t=await this.vfs.readFile(this.projectId,e);if("html"===t.type)return await this.processHTML(t);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{return null}}}},24573:(e,t,r)=>{"use strict";r.d(t,{V:()=>n,b:()=>a});var i=r(4950);let s="openrouter";function o(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return t<.01?1e6*t:t}function n(e,t){if(!Array.isArray(t)||0===t.length)return;let r={};for(let i of t){if(!i?.pricing)continue;let t={input:i.pricing.input,output:i.pricing.output,reasoning:i.pricing.reasoning};Number.isFinite(t.input)&&Number.isFinite(t.output)&&(r[i.id]=t,r[`${e}/${i.id}`]=t)}if(e===s)for(let[e,t]of Object.entries(r)){let i=e.split("/").pop();i&&!r[i]&&(r[i]=t)}Object.keys(r).length>0&&i.s.setProviderPricing(e,r)}function a(e){if(!Array.isArray(e)||0===e.length)return;let t={};for(let r of e){let e=o(r.pricing?.prompt),i=o(r.pricing?.completion),n=o(r.pricing?.internal_reasoning);if(void 0===e||void 0===i)continue;let a={input:e,output:i,reasoning:n};t[r.id]=a,t[`${s}/${r.id}`]=a,r.canonical_slug&&(t[r.canonical_slug]=a)}Object.keys(t).length>0&&i.s.setProviderPricing(s,t)}},24923:(e,t,r)=>{"use strict";r.d(t,{Gr:()=>o,N$:()=>n,Q6:()=>s,fu:()=>a});let i={html:["html","htm"],css:["css"],js:["js","mjs","jsx"],json:["json"],text:["txt","md","xml","svg"],template:["hbs","handlebars"],image:["png","jpg","jpeg","gif","webp","ico","bmp"],video:["mp4","webm","ogg"]},s={text:5242880,html:5242880,css:5242880,js:5242880,json:5242880,template:5242880,image:0xa00000,video:0x3200000,binary:0xa00000};function o(e){let t=e.split(".").pop()?.toLowerCase();for(let[e,r]of Object.entries(i))if(r.includes(t||""))return e;return"text"}function n(e){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"})[e.split(".").pop()?.toLowerCase()||""]||"application/octet-stream"}function a(e){let t=e.split(".").pop()?.toLowerCase();for(let e of Object.values(i))if(e.includes(t||""))return!0;return!1}},24934:(e,t,r)=>{"use strict";r.d(t,{$:()=>l});var i=r(60687);r(43210);var s=r(8730),o=r(24224),n=r(96241);let a=(0,o.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({className:e,variant:t,size:r,asChild:o=!1,...l}){let c=o?s.DX:"button";return(0,i.jsx)(c,{"data-slot":"button",className:(0,n.cn)(a({variant:t,size:r,className:e})),...l})}},28602:(e,t,r)=>{"use strict";r.d(t,{r8:()=>p,OP:()=>u});var i=r(25495),s=r(94084),o=r.n(s);class n{async init(){return new Promise((e,t)=>{let r=indexedDB.open("deepstudio-vfs",1);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.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"),r=await this.promisify(t.get(e));return r?this.hydrateProject(r):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 r=t.transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(r.delete(e))}async listProjects(){let e=this.getDB().transaction(["projects"],"readonly").objectStore("projects"),t=await this.promisify(e.getAll());return 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 r=this.getDB().transaction(["files"],"readonly").objectStore("files").index("path");return await this.promisify(r.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 r=await this.getFile(e,t);if(r){let e=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(e.delete(r.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),r=this.getDB().transaction(["files"],"readwrite").objectStore("files");for(let e of t)await this.promisify(r.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 r=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("path");return await this.promisify(r.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 r=await this.getTreeNode(e,t);if(r){let e=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(e.delete(r.id))}}async getChildNodes(e,t){let r=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("parentPath");return await this.promisify(r.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,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(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=r(96241),l=r(24923),c=r(32623),d=r(22106);class p{constructor(){this.initialized=!1,this.db=new n}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,r){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: ${t}`);if(!(0,l.fu)(t))throw Error(`Unsupported file type: ${t}`);let s=(0,l.Gr)(t),o=r instanceof ArrayBuffer?r.byteLength:new Blob([r]).size,n=l.Q6[s];if(o>n)throw Error(`File too large. Maximum size for ${s} files is ${Math.round(n/1024/1024)}MB`);let d={id:(0,i.A)(),projectId:e,path:t,name:t.split("/").pop()||"",type:s,content:r,mimeType:(0,l.N$)(t),size:o,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 r=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(!r)throw a.v.error("VFS: Empty path after cleaning for readFile",{projectId:e,originalPath:t,cleanPath:r}),Error("Empty file path after cleaning");let i=await this.db.getFile(e,r);if(!i)throw a.v.error("VFS: File not found for read",{projectId:e,path:r,originalPath:t}),Error(`File not found: ${r}`);return i}async fileExists(e,t){this.ensureInitialized();try{return!!await this.db.getFile(e,t)}catch{return!1}}async updateFile(e,t,r){this.ensureInitialized();try{let i=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(i.includes("\n")||i.includes("@@")||i.includes("\\n")||i.length>200)throw a.v.error("VFS: Invalid path detected",{projectId:e,path:t.slice(0,100)+"..."}),Error(`Invalid file path: ${t.slice(0,50)}...`);t=i;let s=await this.db.getFile(e,t);if(!s)throw a.v.error("VFS: File not found for update",{projectId:e,path:t}),Error(`File not found: ${t}`);return s.content=r,s.size=new Blob([r]).size,s.updatedAt=new Date,await this.db.updateFile(s),c.$.markDirty(e),s}catch(e){throw e}}async patchFile(e,t,r){this.ensureInitialized();let i=(await this.readFile(e,t)).content;for(let e of r){if(!i.includes(e.search))throw a.v.error("VFS: Pattern not found in file",{path:t,searchPattern:e.search.substring(0,100),contentSnippet:i.substring(0,300)}),Error(`Pattern not found in file: ${e.search.substring(0,50)}...`);i=i.replace(e.search,e.replace)}return await this.updateFile(e,t,i)}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,r){this.ensureInitialized();let i=await this.readFile(e,t);return await this.deleteFile(e,t),await this.createFile(e,r,i.content)}async createDirectory(e,t){if(this.ensureInitialized(),await this.db.getTreeNode(e,t))return;let r={id:(0,i.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:[]};await this.db.createTreeNode(r),c.$.markDirty(e)}async listDirectory(e,t){this.ensureInitialized();let r=await this.db.listFiles(e);return"/"===t?r:r.filter(e=>{let r=e.path,i=t.endsWith("/")?t:t+"/";return r.startsWith(i)&&-1===r.slice(i.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 r=await this.db.listFiles(e),i=t.endsWith("/")?t:t+"/";for(let t of r)t.path.startsWith(i)&&await this.deleteFile(e,t.path);await this.db.deleteTreeNode(e,t),c.$.markDirty(e)}async renameDirectory(e,t,r){this.ensureInitialized();let s=await this.db.getTreeNode(e,t);if(s){await this.db.deleteTreeNode(e,t);let o={id:(0,i.A)(),projectId:e,path:r,type:"directory",parentPath:this.getParentPath(r),children:s.children};await this.db.createTreeNode(o),c.$.markDirty(e)}let o=t.endsWith("/")?t:t+"/",n=r.endsWith("/")?r:r+"/";for(let t of(await this.db.listFiles(e)).filter(e=>e.path.startsWith(o))){let r=n+t.path.substring(o.length);await this.renameFile(e,t.path,r)}for(let r of(await this.db.getAllTreeNodes(e)).filter(e=>"directory"===e.type&&e.path.startsWith(o)&&e.path!==t)){let t=n+r.path.substring(o.length);await this.db.deleteTreeNode(e,r.path);let s={id:(0,i.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:r.children};await this.db.createTreeNode(s)}}async moveFile(e,t,r){if(this.ensureInitialized(),await this.db.getFile(e,r))throw Error(`File already exists at destination: ${r}`);let i=await this.readFile(e,t),s=await this.createFile(e,r,i.content);return await this.deleteFile(e,t),s}async moveDirectory(e,t,r){this.ensureInitialized();let i=r.endsWith("/")?r:r+"/",s=t.endsWith("/")?t:t+"/";if(i.startsWith(s))throw Error("Cannot move a directory into itself");await this.renameDirectory(e,t,r)}async createProject(e,t){this.ensureInitialized();try{let r={id:(0,i.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(r);let s={id:(0,i.A)(),projectId:r.id,path:"/",type:"directory",parentPath:null,children:[]};return await this.db.createTreeNode(s),r}catch(e){throw e}}async getProject(e){this.ensureInitialized();let t=await this.db.getProject(e);if(!t)throw Error(`Project not found: ${e}`);return t}async updateProject(e){this.ensureInitialized(),e.updatedAt=new Date,await this.db.updateProject(e)}async updateProjectCost(e,t){this.ensureInitialized();let r=await this.getProject(e);if(!r)throw Error(`Project not found: ${e}`);r.costTracking||(r.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),r.costTracking.totalCost+=t.cost,r.costTracking.providerBreakdown[t.provider]||(r.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let i=r.costTracking.providerBreakdown[t.provider];i.totalCost+=t.cost,"delta"!==t.mode&&(i.requestCount+=1),i.lastUpdated=new Date,t.tokenUsage&&(i.tokenUsage.input+=t.tokenUsage.input,i.tokenUsage.output+=t.tokenUsage.output),t.sessionId&&"delta"!==t.mode&&(r.costTracking.sessionHistory||(r.costTracking.sessionHistory=[]),r.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.cost,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsage}),r.costTracking.sessionHistory.length>100&&(r.costTracking.sessionHistory=r.costTracking.sessionHistory.slice(-100))),await this.updateProject(r)}async applyProjectCostDelta(e,t){this.ensureInitialized();let r=await this.getProject(e);if(!r)throw Error(`Project not found: ${e}`);r.costTracking||(r.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),r.costTracking.totalCost+=t.costDelta,r.costTracking.providerBreakdown[t.provider]||(r.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let i=r.costTracking.providerBreakdown[t.provider];i.totalCost+=t.costDelta,i.lastUpdated=new Date,t.tokenUsageDelta&&(i.tokenUsage.input+=t.tokenUsageDelta.input,i.tokenUsage.output+=t.tokenUsageDelta.output),t.sessionId&&(r.costTracking.sessionHistory||(r.costTracking.sessionHistory=[]),r.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.costDelta,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsageDelta,correction:!0}),r.costTracking.sessionHistory.length>100&&(r.costTracking.sessionHistory=r.costTracking.sessionHistory.slice(-100))),await this.updateProject(r)}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,r){this.ensureInitialized();let i=await this.db.listFiles(e),{regex:s=!1,fileType:o,limit:n=20,searchIn:a="both"}=r||{},l=i;if(o){let e=o.startsWith(".")?o:`.${o}`;l=i.filter(t=>t.path.endsWith(e))}let c=s?e=>{try{return RegExp(t,"i").test(e)}catch{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,n)}async findReferences(e,t,r="any"){this.ensureInitialized();let i=await this.db.listFiles(e),s=[],o=[];switch(r){case"class":o.push(RegExp(`class=["'][^"']*\\b${t}\\b[^"']*["']`,"gi")),o.push(RegExp(`\\.${t}\\b`,"g")),o.push(RegExp(`classList\\.(add|remove|toggle|contains)\\(['"\`]${t}['"\`]`,"g"));break;case"id":o.push(RegExp(`id=["']${t}["']`,"gi")),o.push(RegExp(`#${t}\\b`,"g")),o.push(RegExp(`getElementById\\(['"\`]${t}['"\`]`,"g")),o.push(RegExp(`querySelector\\(['"\`]#${t}['"\`]`,"g"));break;case"function":o.push(RegExp(`function\\s+${t}\\s*\\(`,"g")),o.push(RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*(?:\\([^)]*\\)|[^=])\\s*=>`,"g")),o.push(RegExp(`${t}\\s*\\(`,"g"));break;case"variable":o.push(RegExp(`(?:const|let|var)\\s+${t}\\b`,"g")),o.push(RegExp(`\\b${t}\\b`,"g"));break;default:o.push(RegExp(`\\b${t}\\b`,"gi"))}for(let e of i){if("string"!=typeof e.content)continue;let t=[];e.content.split("\n").forEach((e,r)=>{for(let i of o)if(i.test(e)){t.push({line:r+1,text:e.trim()});break}}),t.length>0&&s.push({file:e,matches:t})}return s}async getFileStats(e,t){this.ensureInitialized();let r=await this.db.getFile(e,t);if(!r)throw Error(`File not found: ${t}`);let i=("string"==typeof r.content?r.content:"").split("\n");return{path:r.path,size:r.size,lines:i.length,type:r.type,preview:i.slice(0,10),lastModified:r.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 r=await this.db.listFiles(e),i=0,s={};for(let e of r){i+=e.size;let t=e.path.split(".").pop()?.toUpperCase()||"OTHER";s[t]=(s[t]||0)+1}return t=i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(1)} KB`:`${(i/1048576).toFixed(2)} MB`,{fileCount:r.length,totalSize:i,fileTypes:s,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(o());try{let r=new d.B(this,e);for(let e of(await r.compileProject()).files){let r=e.path.startsWith("/")?e.path.slice(1):e.path;this.shouldExcludeFromExport(e.path)||(e.content,t.file(r,e.content))}r.cleanupBlobUrls()}catch(r){for(let i of(a.v.warn("Failed to compile Handlebars templates during export, falling back to raw files:",r),await this.db.listFiles(e))){let e=i.path.startsWith("/")?i.path.slice(1):i.path;this.shouldExcludeFromExport(i.path)||(i.content,t.file(e,i.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),r=await this.db.listFiles(e),i=`${t.name} (Copy)`.slice(0,50),s=await this.createProject(i,t.description);return await c.$.runWithSuppressedDirty(s.id,async()=>{for(let e of r)await this.createFile(s.id,e.path,e.content)}),s}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 r of e.files)await this.createFile(t.id,r.path,r.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,r){let i=this.getParentPath(t);if(null===i)return;let s=await this.db.getTreeNode(e,i);if(s||"create"!==r||(await this.createDirectory(e,i),s=await this.db.getTreeNode(e,i)),s){let e=s.children||[];if("create"!==r||e.includes(t)){if("delete"===r){let r=e.indexOf(t);r>-1&&e.splice(r,1)}}else e.push(t);s.children=e,await this.db.updateTreeNode(s)}}}let u=new p},32623:(e,t,r)=>{"use strict";r.d(t,{$:()=>a});var i=r(94742),s=r(28602),o=r(96241);class n{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){o.v.error("[SaveManager] Listener error",e)}}setDirty(e,t){let r=this.dirtyProjects.has(e);t&&!r?(this.dirtyProjects.add(e),this.emit(e)):!t&&r&&(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){let t=this.suppressionCounts.get(e)??0;this.suppressionCounts.set(e,t+1)}endSuppression(e){let t=this.suppressionCounts.get(e)??0;if(t<=1)return void this.suppressionCounts.delete(e);this.suppressionCounts.set(e,t-1)}async runWithSuppressedDirty(e,t){this.beginSuppression(e);try{return await t()}finally{this.endSuppression(e)}}isSuppressed(e){return(this.suppressionCounts.get(e)??0)>0}async save(e,t){await s.OP.init();let r=await s.OP.getProject(e),o=`Manual save @ ${new Date().toLocaleTimeString()}`,n=await i.Y.createCheckpoint(e,t||o,{kind:"manual",baseRevisionId:r.lastSavedCheckpointId??null,replaceId:r.lastSavedCheckpointId??null});return r.lastSavedCheckpointId=n.id,r.lastSavedAt=new Date(n.timestamp),await s.OP.updateProject(r),this.manualCheckpoints.set(e,n.id),this.markClean(e),n}async restoreLastSaved(e){await s.OP.init();let t=(await s.OP.getProject(e)).lastSavedCheckpointId;if(!t)return o.v.warn("[SaveManager] No saved checkpoint to restore",{projectId:e}),!1;let r=await this.runWithSuppressedDirty(e,async()=>{if(!await i.Y.checkpointExists(t))return o.v.warn("[SaveManager] Saved checkpoint missing",{projectId:e,checkpointId:t}),!1;let r=await i.Y.restoreCheckpoint(t);return r||o.v.error("[SaveManager] Failed to restore saved checkpoint",{projectId:e,checkpointId:t}),r});return r&&this.markClean(e),r}getSavedCheckpointId(e){return this.manualCheckpoints.get(e)??null}async syncProjectSaveState(e){await s.OP.init();let t=await s.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 n},33135:(e,t,r)=>{"use strict";r.d(t,{AM:()=>n,Wv:()=>a,hl:()=>l});var i=r(60687);r(43210);var s=r(40599),o=r(96241);function n({...e}){return(0,i.jsx)(s.bL,{"data-slot":"popover",...e})}function a({...e}){return(0,i.jsx)(s.l9,{"data-slot":"popover-trigger",...e})}function l({className:e,align:t="center",sideOffset:r=4,...n}){return(0,i.jsx)(s.ZL,{children:(0,i.jsx)(s.UC,{"data-slot":"popover-content",align:t,sideOffset:r,className:(0,o.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}},34429:(e,t,r)=>{"use strict";r.d(t,{QF:()=>s,WK:()=>o});var i=r(96241);async function s(){try{let e=await fetch("https://openrouter.ai/api/v1/models");if(!e.ok)throw Error(`Failed to fetch models: ${e.statusText}`);return(await e.json()).data.filter(e=>e.architecture.output_modalities.includes("text")&&e.supported_parameters.includes("tools")).sort((e,t)=>{let r=["gpt-4","claude","deepseek","qwen"],i=r.some(t=>e.id.toLowerCase().includes(t)),s=r.some(e=>t.id.toLowerCase().includes(e));return i&&!s?-1:!i&&s?1:t.created-e.created})}catch(e){return i.v.error("Error fetching models:",e),[{id:"deepseek/deepseek-chat",canonical_slug:"deepseek-chat",name:"DeepSeek Chat",created:Date.now(),description:"DeepSeek Chat - Fast and capable model for general tasks",context_length:64e3,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"deepseek"},pricing:{prompt:"0.00014",completion:"0.00028",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:64e3,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"qwen/qwen-2.5-coder-32b-instruct",canonical_slug:"qwen-2.5-coder-32b-instruct",name:"Qwen 2.5 Coder 32B",created:Date.now(),description:"Qwen 2.5 Coder - Specialized for code generation",context_length:32768,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"qwen"},pricing:{prompt:"0.00018",completion:"0.00018",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:32768,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"openai/gpt-4o",canonical_slug:"gpt-4o",name:"GPT-4o",created:Date.now(),description:"OpenAI GPT-4o - Multimodal model with vision capabilities",context_length:128e3,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"openai"},pricing:{prompt:"0.0025",completion:"0.01",request:"0",image:"0.00765",web_search:"0",internal_reasoning:"0",input_cache_read:"0.00125",input_cache_write:"0.0025"},top_provider:{context_length:128e3,max_completion_tokens:16384,is_moderated:!0},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens","response_format"]},{id:"anthropic/claude-3.5-sonnet",canonical_slug:"claude-3.5-sonnet",name:"Claude 3.5 Sonnet",created:Date.now(),description:"Anthropic Claude 3.5 Sonnet - Advanced reasoning and coding",context_length:2e5,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"claude",instruct_type:"anthropic"},pricing:{prompt:"0.003",completion:"0.015",request:"0",image:"0.0048",web_search:"0",internal_reasoning:"0",input_cache_read:"0.0003",input_cache_write:"0.00375"},top_provider:{context_length:2e5,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]}]}}function o(e,t=!0){if(null==e)return"";let r=t?e/1e3:e;if(0===r)return"free";if(r<1e-4)return`$${r.toFixed(5).replace(/\.?0+$/,"")}`;if(r<.001)return`$${r.toFixed(4).replace(/\.?0+$/,"")}`;if(r<.01)return`$${r.toFixed(3).replace(/\.?0+$/,"")}`;if(r<.1)return`$${r.toFixed(3).replace(/\.?0+$/,"")}`;if(r<1)return`$${r.toFixed(2).replace(/\.?0+$/,"")}`;else return`$${r.toFixed(2)}`}},39035:(e,t,r)=>{"use strict";r.d(t,{ThemeProvider:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call ThemeProvider() from the server but ThemeProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/theme-provider.tsx","ThemeProvider")},39390:(e,t,r)=>{"use strict";r.d(t,{J:()=>c});var i=r(60687),s=r(43210),o=r(78148),n=r(24224),a=r(96241);let l=(0,n.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=s.forwardRef(({className:e,...t},r)=>(0,i.jsx)(o.b,{ref:r,className:(0,a.cn)(l(),e),...t}));c.displayName=o.b.displayName},41900:(e,t,r)=>{"use strict";r.d(t,{default:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call the default export of \"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/tanstack-query-provider.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/tanstack-query-provider.tsx","default")},46055:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var i=r(31658);let s=async e=>[{type:"image/x-icon",sizes:"16x16",url:(0,i.fillMetadataSegment)(".",await e.params,"favicon.ico")+""}]},51567:(e,t,r)=>{"use strict";r.d(t,{j:()=>d});var i=r(60687),s=r(43210),o=r(24934),n=r(59821),a=r(96271),l=r(3589),c=r(78272);function d({title:e,subtitle:t,badge:r,onLogoClick:d,actions:p=[],mobileMenuContent:u,desktopOnlyContent:h,className:m="",leftText:g}){let[f,y]=(0,s.useState)(!1);return(0,i.jsxs)("div",{className:`border-b bg-card shadow-sm relative z-20 ${m}`,children:[(0,i.jsxs)("div",{className:"px-3 py-2 flex items-center justify-between",children:[(0,i.jsxs)("button",{onClick:d,className:"flex items-center gap-2 p-1 pr-2 hover:ring-1 hover:ring-border rounded-sm transition-all",children:[(0,i.jsx)(a.g,{width:24,height:24}),g&&(0,i.jsx)("span",{className:"font-semibold text-lg hidden md:inline",children:g})]}),(0,i.jsx)("div",{className:"flex items-center gap-2 flex-1 justify-center md:justify-start md:ml-6",children:g?(0,i.jsx)("h1",{className:"text-lg font-semibold md:hidden",children:g}):e?(0,i.jsxs)(i.Fragment,{children:[e&&(0,i.jsx)("h1",{className:"text-lg md:text-xl font-semibold",children:e}),r&&(0,i.jsx)(n.E,{variant:"secondary",children:r})]}):null}),!g&&!e&&t&&(0,i.jsx)("div",{className:"hidden md:flex items-center flex-1 ml-6",children:(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:t})}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsxs)("div",{className:"hidden md:flex items-center gap-2",children:[p.map(e=>e.content?(0,i.jsx)("div",{children:e.content},e.id):(0,i.jsxs)(o.$,{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,i.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id)),h]}),(p.length>0||u)&&(0,i.jsx)(o.$,{variant:"ghost",size:"icon",onClick:()=>y(!f),className:"h-8 w-8 md:hidden",children:f?(0,i.jsx)(l.A,{className:"h-4 w-4"}):(0,i.jsx)(c.A,{className:"h-4 w-4"})})]})]}),f&&(p.length>0||u)&&(0,i.jsxs)("div",{className:"md:hidden border-t bg-muted/30 px-4 py-4 space-y-3",children:[!g&&!e&&t&&(0,i.jsx)("div",{className:"pb-2 border-b border-border/50",children:(0,i.jsx)("p",{className:"text-sm text-muted-foreground",children:t})}),(0,i.jsx)("div",{className:"space-y-2",children:p.map(e=>e.content?(0,i.jsx)("div",{children:e.content},e.id):(0,i.jsxs)(o.$,{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,i.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id))}),u&&(0,i.jsx)("div",{className:"pt-2 border-t border-border/50",children:u})]})]})}},53014:(e,t,r)=>{"use strict";r.d(t,{default:()=>n});var i=r(60687),s=r(92314),o=r(8693);function n({children:e}){let t=new s.E;return(0,i.jsx)(o.Ht,{client:t,children:e})}},57462:(e,t,r)=>{"use strict";function i(e){let t=`You are an AI assistant that helps users with their coding projects. You work in a sandboxed virtual file system. +exports.id=617,exports.ids=[617],exports.modules={4950:(e,t,r)=>{"use strict";r.d(t,{s:()=>s});class i{getSettings(){return{}}setSetting(e,t){}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){let t=this.getSettings();return t.providerKeys?.[e]?t.providerKeys[e]:"openrouter"===e&&t.openRouterApiKey?t.openRouterApiKey:null}setProviderApiKey(e,t){let r=this.getSettings().providerKeys||{};r[e]=t,this.setSetting("providerKeys",r),"openrouter"===e&&this.setSetting("openRouterApiKey",t)}getProviderModel(e){let t=this.getSettings();return t.providerModels?.[e]?t.providerModels[e]:"openrouter"===e&&t.defaultModel?t.defaultModel:null}setProviderModel(e,t){let r=this.getSettings().providerModels||{};r[e]=t,this.setSetting("providerModels",r),"openrouter"===e&&this.setSetting("defaultModel",t)}getModelPricing(e,t){let r=this.getSettings(),i=r.modelPricing?.[e];return i&&(i[t]||i[`${e}/${t}`]||(t.includes("/")?i[t.split("/").pop()??""]:null))||null}setModelPricing(e,t,r){}setProviderPricing(e,t){}clearProviderPricing(e){}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(){}getCostSettings(){return this.getSettings().costSettings||{showCosts:!0,warningThreshold:80}}setCostSettings(e){this.setSetting("costSettings",e)}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 r=this.getCurrentSession();r||(r=this.startNewSession()),r.totalCost+=t,r.messageCount+=1;let i=e.provider||"unknown";r.providerBreakdown[i]||(r.providerBreakdown[i]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),r.providerBreakdown[i].cost+=t,r.providerBreakdown[i].tokenUsage.input+=e.promptTokens,r.providerBreakdown[i].tokenUsage.output+=e.completionTokens,r.providerBreakdown[i].requestCount+=1;let s=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};s.total+=t,s.byProvider[i]=(s.byProvider[i]||0)+t,this.setSetting("currentSession",r),this.setSetting("lifetimeCosts",s)}adjustSessionCost(e,t,r){if(!t&&!r)return;let i=this.getCurrentSession();if(!i)return;let s=e||"unknown";i.totalCost+=t,i.providerBreakdown[s]||(i.providerBreakdown[s]={cost:0,tokenUsage:{input:0,output:0},requestCount:0}),i.providerBreakdown[s].cost+=t,r&&(i.providerBreakdown[s].tokenUsage.input+=r.input,i.providerBreakdown[s].tokenUsage.output+=r.output);let o=this.getSettings().lifetimeCosts||{total:0,byProvider:{}};o.total+=t,o.byProvider[s]=(o.byProvider[s]||0)+t,this.setSetting("currentSession",i),this.setSetting("lifetimeCosts",o)}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 r=t.totalCost/e.dailyLimit*100;return r>=100?{warning:!1,exceeded:!0,message:`Daily limit of $${e.dailyLimit.toFixed(2)} exceeded`}:e.warningThreshold&&r>=e.warningThreshold?{warning:!0,exceeded:!1,message:`${r.toFixed(0)}% of daily limit used ($${t.totalCost.toFixed(2)} of $${e.dailyLimit.toFixed(2)})`}:{warning:!1,exceeded:!1}}getCachedModels(e){let t=this.getSettings(),r=t.modelCache?.[e];return r?new Date>new Date(r.expiresAt)?(this.clearModelCache(e),null):r:null}setCachedModels(e,t){let r=this.getSettings(),i=new Date,s=new Date(i.getTime()+864e5),o=r.modelCache||{};o[e]={models:t,timestamp:i.toISOString(),expiresAt:s.toISOString()},this.setSetting("modelCache",o)}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 s=new i},8584:(e,t,r)=>{Promise.resolve().then(r.bind(r,53014)),Promise.resolve().then(r.bind(r,99197)),Promise.resolve().then(r.bind(r,94593))},10158:(e,t,r)=>{"use strict";r.d(t,{OM:()=>o,sO:()=>s});let i={openrouter:{id:"openrouter",name:"OpenRouter",description:"Access multiple AI models through a unified API",apiKeyRequired:!0,apiKeyPlaceholder:"sk-or-...",apiKeyHelpUrl:"https://openrouter.ai/keys",baseUrl:"https://openrouter.ai/api/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},openai:{id:"openai",name:"OpenAI",description:"GPT-4, GPT-3.5 and other OpenAI models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-...",apiKeyHelpUrl:"https://platform.openai.com/api-keys",baseUrl:"https://api.openai.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},anthropic:{id:"anthropic",name:"Anthropic",description:"Claude 3.5 Sonnet, Haiku and Opus models",apiKeyRequired:!0,apiKeyPlaceholder:"sk-ant-...",apiKeyHelpUrl:"https://console.anthropic.com/settings/keys",baseUrl:"https://api.anthropic.com/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},groq:{id:"groq",name:"Groq",description:"Ultra-fast inference with Llama and Mixtral models",apiKeyRequired:!0,apiKeyPlaceholder:"gsk_...",apiKeyHelpUrl:"https://console.groq.com/keys",baseUrl:"https://api.groq.com/openai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0},gemini:{id:"gemini",name:"Google Gemini",description:"Google's multimodal AI models",apiKeyRequired:!0,apiKeyPlaceholder:"AI...",apiKeyHelpUrl:"https://aistudio.google.com/apikey",baseUrl:"https://generativelanguage.googleapis.com/v1beta",models:[{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash",description:"Latest experimental Gemini model",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",description:"Advanced reasoning and analysis",contextLength:2097152,maxTokens:8192,supportsFunctions:!0,supportsVision:!0},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",description:"Fast and versatile",contextLength:1048576,maxTokens:8192,supportsFunctions:!0,supportsVision:!0}],supportsFunctions:!0,supportsStreaming:!0},ollama:{id:"ollama",name:"Ollama",description:"Run models locally with Ollama",apiKeyRequired:!1,baseUrl:"http://localhost:11434/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},lmstudio:{id:"lmstudio",name:"LM Studio",description:"Local model server with tool use support",apiKeyRequired:!1,baseUrl:"http://localhost:1234/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0,isLocal:!0},sambanova:{id:"sambanova",name:"SambaNova",description:"High-performance AI chips for inference",apiKeyRequired:!0,apiKeyPlaceholder:"SambaNova API Key",apiKeyHelpUrl:"https://cloud.sambanova.ai/apis",baseUrl:"https://api.sambanova.ai/v1",supportsModelDiscovery:!0,supportsFunctions:!0,supportsStreaming:!0}};function s(e){return i[e]}function o(){return Object.values(i)}},19424:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,16444,23)),Promise.resolve().then(r.t.bind(r,16042,23)),Promise.resolve().then(r.t.bind(r,88170,23)),Promise.resolve().then(r.t.bind(r,49477,23)),Promise.resolve().then(r.t.bind(r,29345,23)),Promise.resolve().then(r.t.bind(r,12089,23)),Promise.resolve().then(r.t.bind(r,46577,23)),Promise.resolve().then(r.t.bind(r,31307,23))},21736:(e,t,r)=>{Promise.resolve().then(r.bind(r,41900)),Promise.resolve().then(r.bind(r,39035)),Promise.resolve().then(r.bind(r,80363))},22106:(e,t,r)=>{"use strict";r.d(t,{B:()=>o});var i=r(79170),s=r.n(i);class o{constructor(e,t,r){this.blobUrls=new Map,this.fileHashes=new Map,this.templateCache=new Map,this.partialsRegistered=!1,this.vfs=e,this.projectId=t,this.baseUrl="",r&&(this.blobUrls=new Map(r)),this.handlebars=s().create(),this.registerHelpers()}registerHelpers(){this.handlebars.registerHelper("eq",(e,t)=>e===t),this.handlebars.registerHelper("ne",(e,t)=>e!==t),this.handlebars.registerHelper("lt",(e,t)=>e<t),this.handlebars.registerHelper("gt",(e,t)=>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=>e?.toUpperCase()),this.handlebars.registerHelper("lowercase",e=>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 r=e.content;this.handlebars.registerPartial(t,r)}this.partialsRegistered=!0}catch(e){}}async compileTemplate(e,t={}){let r=this.templateCache.get(e);if(!r)try{let t=(await this.vfs.readFile(this.projectId,e)).content;r=this.handlebars.compile(t),this.templateCache.set(e,r)}catch(t){return console.error(`Failed to compile template ${e}:`,t),""}return r(t)}async compileProject(e=!1){await this.registerPartials();let t=await this.vfs.listDirectory(this.projectId,"/"),r=new Map(this.blobUrls),i=new Map,s=[];for(let o of t){let t;if("template"===o.type)continue;if("image"===o.type||"video"===o.type)t={path:o.path,content:o.content,mimeType:o.mimeType};else if("html"===o.type)t=await this.processHTML(o);else if("js"===o.type)t=await this.processJS(o);else{if("css"===o.type)continue;t={path:o.path,content:o.content,mimeType:o.mimeType}}let n=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===n&&r.has(t.path)){let e=r.get(t.path);i.set(t.path,e),t.blobUrl=e,r.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),r=URL.createObjectURL(e);i.set(t.path,r),t.blobUrl=r,this.fileHashes.set(t.path,n)}s.push(t)}let o=[...s];for(let s of t)if("css"===s.type){let t=await this.processCSS(s,i),n=this.hashContent(t.content),a=this.fileHashes.get(t.path);if(e&&a===n&&r.has(t.path)){let e=r.get(t.path);i.set(t.path,e),t.blobUrl=e,r.delete(t.path)}else{let e=new Blob([t.content],{type:t.mimeType}),r=URL.createObjectURL(e);i.set(t.path,r),t.blobUrl=r,this.fileHashes.set(t.path,n)}o.push(t)}let n=this.generateRoutes(t);if(e)for(let[,e]of r)URL.revokeObjectURL(e);else e||this.cleanupBlobUrls();return this.blobUrls=i,{entryPoint:"/index.html",files:o,routes:n,blobUrls:this.blobUrls}}hashContent(e){let t=0;if(e instanceof ArrayBuffer){let r=new Uint8Array(e);for(let e=0;e<Math.min(r.length,1e4);e++)t=(t<<5)-t+r[e],t&=t}else for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t&=t;return t.toString(36)}async processFiles(e){let t=[];for(let r of e)"html"===r.type?t.push(await this.processHTML(r)):"css"===r.type?t.push(await this.processCSS(r,new Map)):"js"===r.type?t.push(await this.processJS(r)):("image"===r.type||r.type,t.push({path:r.path,content:r.content,mimeType:r.mimeType}));return t}async processHTML(e){let t=e.content;return t=await this.processHandlebarsTemplates(t),t=await this.processInternalReferences(t),{path:e.path,content:t,mimeType:e.mimeType}}async processHandlebarsTemplates(e){await this.registerPartials();try{let t=this.detectInvalidHandlebarsPatterns(e);if(t.length>0){let r=t.map(e=>`❌ ${e.error} +💡 ${e.suggestion}`).join("\n\n");return`<!-- Handlebars Syntax Error --> +<div style="background: #fee; border: 1px solid #f99; padding: 1rem; margin: 1rem; border-radius: 4px; font-family: monospace;"> +<h3 style="color: #c33; margin: 0 0 1rem 0;">⚠️ Handlebars Template Error</h3> +<pre style="margin: 0; white-space: pre-wrap;">${r}</pre> +</div> +<!-- Original content: +${e} +-->`}let r={};try{let e=await this.vfs.readFile(this.projectId,"/data.json");r=JSON.parse(e.content)}catch{}return this.handlebars.compile(e)(r)}catch(r){console.error("VirtualServer: Error processing Handlebars templates:",r);let t=r instanceof Error?r.message:String(r);return`<!-- Handlebars Compilation Error --> +<div style="background: #fee; border: 1px solid #f99; padding: 1rem; margin: 1rem; border-radius: 4px; font-family: monospace;"> +<h3 style="color: #c33; margin: 0 0 1rem 0;">⚠️ Handlebars Template Error</h3> +<p><strong>Error:</strong> ${t}</p> +<p><strong>Common fixes:</strong></p> +<ul> +<li>Check for typos in helper names and partial references</li> +<li>Ensure all opening tags have matching closing tags</li> +<li>Verify partial names exist in /templates/ directory</li> +<li>Use <code>{{> partialName}}</code> syntax, not <code>(> partialName)</code></li> +</ul> +</div> +<!-- Original content: +${e} +-->`}}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 r=e.content;return r=await this.processUrlReferences(r,t),{path:e.path,content:r,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,"/"),r=e;for(let e of[/href="([^"]+)"/g,/src="([^"]+)"/g,/href='([^']+)'/g,/src='([^']+)'/g])r=r.replace(e,(e,r)=>{if(r.startsWith("http")||r.startsWith("data:")||r.startsWith("//"))return e;let i=this.normalizePath(r);return t.some(e=>e.path===i),e});return r}async processUrlReferences(e,t){return e.replace(/url\(['"]?([^'")]+)['"]?\)/g,(e,r)=>{if(r.startsWith("http")||r.startsWith("data:")||r.startsWith("//")||r.startsWith("blob:"))return e;let i=this.normalizePath(r),s=t.get(i);return s?`url('${s}')`: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>([^<]+)<\/title>/i),r=t?t[1]:e.name.replace(".html",""),i=e.path.replace(".html","")||"/";return{path:"/index"===i?"/":i,file:e.path,title:r}})}extractTitle(e){let t=e.match(/<title>([^<]+)<\/title>/i);return t?t[1]:"Untitled Page"}cleanupBlobUrls(){for(let e of this.blobUrls.values())URL.revokeObjectURL(e);this.blobUrls.clear(),this.templateCache.clear(),this.partialsRegistered=!1}async getCompiledFile(e){try{let t=await this.vfs.readFile(this.projectId,e);if("html"===t.type)return await this.processHTML(t);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{return null}}}},24573:(e,t,r)=>{"use strict";r.d(t,{V:()=>n,b:()=>a});var i=r(4950);let s="openrouter";function o(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&!(t<=0))return t<.01?1e6*t:t}function n(e,t){if(!Array.isArray(t)||0===t.length)return;let r={};for(let i of t){if(!i?.pricing)continue;let t={input:i.pricing.input,output:i.pricing.output,reasoning:i.pricing.reasoning};Number.isFinite(t.input)&&Number.isFinite(t.output)&&(r[i.id]=t,r[`${e}/${i.id}`]=t)}if(e===s)for(let[e,t]of Object.entries(r)){let i=e.split("/").pop();i&&!r[i]&&(r[i]=t)}Object.keys(r).length>0&&i.s.setProviderPricing(e,r)}function a(e){if(!Array.isArray(e)||0===e.length)return;let t={};for(let r of e){let e=o(r.pricing?.prompt),i=o(r.pricing?.completion),n=o(r.pricing?.internal_reasoning);if(void 0===e||void 0===i)continue;let a={input:e,output:i,reasoning:n};t[r.id]=a,t[`${s}/${r.id}`]=a,r.canonical_slug&&(t[r.canonical_slug]=a)}Object.keys(t).length>0&&i.s.setProviderPricing(s,t)}},24923:(e,t,r)=>{"use strict";r.d(t,{Gr:()=>o,N$:()=>n,Q6:()=>s,fu:()=>a});let i={html:["html","htm"],css:["css"],js:["js","mjs","jsx"],json:["json"],text:["txt","md","xml","svg"],template:["hbs","handlebars"],image:["png","jpg","jpeg","gif","webp","ico","bmp"],video:["mp4","webm","ogg"]},s={text:5242880,html:5242880,css:5242880,js:5242880,json:5242880,template:5242880,image:0xa00000,video:0x3200000,binary:0xa00000};function o(e){let t=e.split(".").pop()?.toLowerCase();for(let[e,r]of Object.entries(i))if(r.includes(t||""))return e;return"text"}function n(e){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"})[e.split(".").pop()?.toLowerCase()||""]||"application/octet-stream"}function a(e){let t=e.split(".").pop()?.toLowerCase();for(let e of Object.values(i))if(e.includes(t||""))return!0;return!1}},24934:(e,t,r)=>{"use strict";r.d(t,{$:()=>l});var i=r(60687);r(43210);var s=r(8730),o=r(24224),n=r(96241);let a=(0,o.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({className:e,variant:t,size:r,asChild:o=!1,...l}){let c=o?s.DX:"button";return(0,i.jsx)(c,{"data-slot":"button",className:(0,n.cn)(a({variant:t,size:r,className:e})),...l})}},28602:(e,t,r)=>{"use strict";r.d(t,{r8:()=>p,OP:()=>u});var i=r(25495),s=r(94084),o=r.n(s);class n{async init(){return new Promise((e,t)=>{let r=indexedDB.open("deepstudio-vfs",1);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.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"),r=await this.promisify(t.get(e));return r?this.hydrateProject(r):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 r=t.transaction(["projects"],"readwrite").objectStore("projects");await this.promisify(r.delete(e))}async listProjects(){let e=this.getDB().transaction(["projects"],"readonly").objectStore("projects"),t=await this.promisify(e.getAll());return 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 r=this.getDB().transaction(["files"],"readonly").objectStore("files").index("path");return await this.promisify(r.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 r=await this.getFile(e,t);if(r){let e=this.getDB().transaction(["files"],"readwrite").objectStore("files");await this.promisify(e.delete(r.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),r=this.getDB().transaction(["files"],"readwrite").objectStore("files");for(let e of t)await this.promisify(r.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 r=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("path");return await this.promisify(r.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 r=await this.getTreeNode(e,t);if(r){let e=this.getDB().transaction(["fileTree"],"readwrite").objectStore("fileTree");await this.promisify(e.delete(r.id))}}async getChildNodes(e,t){let r=this.getDB().transaction(["fileTree"],"readonly").objectStore("fileTree").index("parentPath");return await this.promisify(r.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,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(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=r(96241),l=r(24923),c=r(32623),d=r(22106);class p{constructor(){this.initialized=!1,this.db=new n}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,r){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: ${t}`);if(!(0,l.fu)(t))throw Error(`Unsupported file type: ${t}`);let s=(0,l.Gr)(t),o=r instanceof ArrayBuffer?r.byteLength:new Blob([r]).size,n=l.Q6[s];if(o>n)throw Error(`File too large. Maximum size for ${s} files is ${Math.round(n/1024/1024)}MB`);let d={id:(0,i.A)(),projectId:e,path:t,name:t.split("/").pop()||"",type:s,content:r,mimeType:(0,l.N$)(t),size:o,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 r=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(!r)throw a.v.error("VFS: Empty path after cleaning for readFile",{projectId:e,originalPath:t,cleanPath:r}),Error("Empty file path after cleaning");let i=await this.db.getFile(e,r);if(!i)throw a.v.error("VFS: File not found for read",{projectId:e,path:r,originalPath:t}),Error(`File not found: ${r}`);return i}async fileExists(e,t){this.ensureInitialized();try{return!!await this.db.getFile(e,t)}catch{return!1}}async updateFile(e,t,r){this.ensureInitialized();try{let i=t.replace(/\\n$|\\r$|\n$|\r$/,"").trim();if(i.includes("\n")||i.includes("@@")||i.includes("\\n")||i.length>200)throw a.v.error("VFS: Invalid path detected",{projectId:e,path:t.slice(0,100)+"..."}),Error(`Invalid file path: ${t.slice(0,50)}...`);t=i;let s=await this.db.getFile(e,t);if(!s)throw a.v.error("VFS: File not found for update",{projectId:e,path:t}),Error(`File not found: ${t}`);return s.content=r,s.size=new Blob([r]).size,s.updatedAt=new Date,await this.db.updateFile(s),c.$.markDirty(e),s}catch(e){throw e}}async patchFile(e,t,r){this.ensureInitialized();let i=(await this.readFile(e,t)).content;for(let e of r){if(!i.includes(e.search))throw a.v.error("VFS: Pattern not found in file",{path:t,searchPattern:e.search.substring(0,100),contentSnippet:i.substring(0,300)}),Error(`Pattern not found in file: ${e.search.substring(0,50)}...`);i=i.replace(e.search,e.replace)}return await this.updateFile(e,t,i)}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,r){this.ensureInitialized();let i=await this.readFile(e,t);return await this.deleteFile(e,t),await this.createFile(e,r,i.content)}async createDirectory(e,t){if(this.ensureInitialized(),await this.db.getTreeNode(e,t))return;let r={id:(0,i.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:[]};await this.db.createTreeNode(r),c.$.markDirty(e)}async listDirectory(e,t){this.ensureInitialized();let r=await this.db.listFiles(e);return"/"===t?r:r.filter(e=>{let r=e.path,i=t.endsWith("/")?t:t+"/";return r.startsWith(i)&&-1===r.slice(i.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 r=await this.db.listFiles(e),i=t.endsWith("/")?t:t+"/";for(let t of r)t.path.startsWith(i)&&await this.deleteFile(e,t.path);await this.db.deleteTreeNode(e,t),c.$.markDirty(e)}async renameDirectory(e,t,r){this.ensureInitialized();let s=await this.db.getTreeNode(e,t);if(s){await this.db.deleteTreeNode(e,t);let o={id:(0,i.A)(),projectId:e,path:r,type:"directory",parentPath:this.getParentPath(r),children:s.children};await this.db.createTreeNode(o),c.$.markDirty(e)}let o=t.endsWith("/")?t:t+"/",n=r.endsWith("/")?r:r+"/";for(let t of(await this.db.listFiles(e)).filter(e=>e.path.startsWith(o))){let r=n+t.path.substring(o.length);await this.renameFile(e,t.path,r)}for(let r of(await this.db.getAllTreeNodes(e)).filter(e=>"directory"===e.type&&e.path.startsWith(o)&&e.path!==t)){let t=n+r.path.substring(o.length);await this.db.deleteTreeNode(e,r.path);let s={id:(0,i.A)(),projectId:e,path:t,type:"directory",parentPath:this.getParentPath(t),children:r.children};await this.db.createTreeNode(s)}}async moveFile(e,t,r){if(this.ensureInitialized(),await this.db.getFile(e,r))throw Error(`File already exists at destination: ${r}`);let i=await this.readFile(e,t),s=await this.createFile(e,r,i.content);return await this.deleteFile(e,t),s}async moveDirectory(e,t,r){this.ensureInitialized();let i=r.endsWith("/")?r:r+"/",s=t.endsWith("/")?t:t+"/";if(i.startsWith(s))throw Error("Cannot move a directory into itself");await this.renameDirectory(e,t,r)}async createProject(e,t){this.ensureInitialized();try{let r={id:(0,i.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(r);let s={id:(0,i.A)(),projectId:r.id,path:"/",type:"directory",parentPath:null,children:[]};return await this.db.createTreeNode(s),r}catch(e){throw e}}async getProject(e){this.ensureInitialized();let t=await this.db.getProject(e);if(!t)throw Error(`Project not found: ${e}`);return t}async updateProject(e){this.ensureInitialized(),e.updatedAt=new Date,await this.db.updateProject(e)}async updateProjectCost(e,t){this.ensureInitialized();let r=await this.getProject(e);if(!r)throw Error(`Project not found: ${e}`);r.costTracking||(r.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),r.costTracking.totalCost+=t.cost,r.costTracking.providerBreakdown[t.provider]||(r.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let i=r.costTracking.providerBreakdown[t.provider];i.totalCost+=t.cost,"delta"!==t.mode&&(i.requestCount+=1),i.lastUpdated=new Date,t.tokenUsage&&(i.tokenUsage.input+=t.tokenUsage.input,i.tokenUsage.output+=t.tokenUsage.output),t.sessionId&&"delta"!==t.mode&&(r.costTracking.sessionHistory||(r.costTracking.sessionHistory=[]),r.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.cost,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsage}),r.costTracking.sessionHistory.length>100&&(r.costTracking.sessionHistory=r.costTracking.sessionHistory.slice(-100))),await this.updateProject(r)}async applyProjectCostDelta(e,t){this.ensureInitialized();let r=await this.getProject(e);if(!r)throw Error(`Project not found: ${e}`);r.costTracking||(r.costTracking={totalCost:0,providerBreakdown:{},sessionHistory:[]}),r.costTracking.totalCost+=t.costDelta,r.costTracking.providerBreakdown[t.provider]||(r.costTracking.providerBreakdown[t.provider]={totalCost:0,tokenUsage:{input:0,output:0},requestCount:0,lastUpdated:new Date});let i=r.costTracking.providerBreakdown[t.provider];i.totalCost+=t.costDelta,i.lastUpdated=new Date,t.tokenUsageDelta&&(i.tokenUsage.input+=t.tokenUsageDelta.input,i.tokenUsage.output+=t.tokenUsageDelta.output),t.sessionId&&(r.costTracking.sessionHistory||(r.costTracking.sessionHistory=[]),r.costTracking.sessionHistory.push({sessionId:t.sessionId,cost:t.costDelta,provider:t.provider,timestamp:new Date,tokenUsage:t.tokenUsageDelta,correction:!0}),r.costTracking.sessionHistory.length>100&&(r.costTracking.sessionHistory=r.costTracking.sessionHistory.slice(-100))),await this.updateProject(r)}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,r){this.ensureInitialized();let i=await this.db.listFiles(e),{regex:s=!1,fileType:o,limit:n=20,searchIn:a="both"}=r||{},l=i;if(o){let e=o.startsWith(".")?o:`.${o}`;l=i.filter(t=>t.path.endsWith(e))}let c=s?e=>{try{return RegExp(t,"i").test(e)}catch{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,n)}async findReferences(e,t,r="any"){this.ensureInitialized();let i=await this.db.listFiles(e),s=[],o=[];switch(r){case"class":o.push(RegExp(`class=["'][^"']*\\b${t}\\b[^"']*["']`,"gi")),o.push(RegExp(`\\.${t}\\b`,"g")),o.push(RegExp(`classList\\.(add|remove|toggle|contains)\\(['"\`]${t}['"\`]`,"g"));break;case"id":o.push(RegExp(`id=["']${t}["']`,"gi")),o.push(RegExp(`#${t}\\b`,"g")),o.push(RegExp(`getElementById\\(['"\`]${t}['"\`]`,"g")),o.push(RegExp(`querySelector\\(['"\`]#${t}['"\`]`,"g"));break;case"function":o.push(RegExp(`function\\s+${t}\\s*\\(`,"g")),o.push(RegExp(`(?:const|let|var)\\s+${t}\\s*=\\s*(?:\\([^)]*\\)|[^=])\\s*=>`,"g")),o.push(RegExp(`${t}\\s*\\(`,"g"));break;case"variable":o.push(RegExp(`(?:const|let|var)\\s+${t}\\b`,"g")),o.push(RegExp(`\\b${t}\\b`,"g"));break;default:o.push(RegExp(`\\b${t}\\b`,"gi"))}for(let e of i){if("string"!=typeof e.content)continue;let t=[];e.content.split("\n").forEach((e,r)=>{for(let i of o)if(i.test(e)){t.push({line:r+1,text:e.trim()});break}}),t.length>0&&s.push({file:e,matches:t})}return s}async getFileStats(e,t){this.ensureInitialized();let r=await this.db.getFile(e,t);if(!r)throw Error(`File not found: ${t}`);let i=("string"==typeof r.content?r.content:"").split("\n");return{path:r.path,size:r.size,lines:i.length,type:r.type,preview:i.slice(0,10),lastModified:r.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 r=await this.db.listFiles(e),i=0,s={};for(let e of r){i+=e.size;let t=e.path.split(".").pop()?.toUpperCase()||"OTHER";s[t]=(s[t]||0)+1}return t=i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(1)} KB`:`${(i/1048576).toFixed(2)} MB`,{fileCount:r.length,totalSize:i,fileTypes:s,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(o());try{let r=new d.B(this,e);for(let e of(await r.compileProject()).files){let r=e.path.startsWith("/")?e.path.slice(1):e.path;this.shouldExcludeFromExport(e.path)||(e.content,t.file(r,e.content))}r.cleanupBlobUrls()}catch(r){for(let i of(a.v.warn("Failed to compile Handlebars templates during export, falling back to raw files:",r),await this.db.listFiles(e))){let e=i.path.startsWith("/")?i.path.slice(1):i.path;this.shouldExcludeFromExport(i.path)||(i.content,t.file(e,i.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),r=await this.db.listFiles(e),i=`${t.name} (Copy)`.slice(0,50),s=await this.createProject(i,t.description);return await c.$.runWithSuppressedDirty(s.id,async()=>{for(let e of r)await this.createFile(s.id,e.path,e.content)}),s}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 r of e.files)await this.createFile(t.id,r.path,r.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,r){let i=this.getParentPath(t);if(null===i)return;let s=await this.db.getTreeNode(e,i);if(s||"create"!==r||(await this.createDirectory(e,i),s=await this.db.getTreeNode(e,i)),s){let e=s.children||[];if("create"!==r||e.includes(t)){if("delete"===r){let r=e.indexOf(t);r>-1&&e.splice(r,1)}}else e.push(t);s.children=e,await this.db.updateTreeNode(s)}}}let u=new p},32623:(e,t,r)=>{"use strict";r.d(t,{$:()=>a});var i=r(94742),s=r(28602),o=r(96241);class n{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){o.v.error("[SaveManager] Listener error",e)}}setDirty(e,t){let r=this.dirtyProjects.has(e);t&&!r?(this.dirtyProjects.add(e),this.emit(e)):!t&&r&&(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){let t=this.suppressionCounts.get(e)??0;this.suppressionCounts.set(e,t+1)}endSuppression(e){let t=this.suppressionCounts.get(e)??0;if(t<=1)return void this.suppressionCounts.delete(e);this.suppressionCounts.set(e,t-1)}async runWithSuppressedDirty(e,t){this.beginSuppression(e);try{return await t()}finally{this.endSuppression(e)}}isSuppressed(e){return(this.suppressionCounts.get(e)??0)>0}async save(e,t){await s.OP.init();let r=await s.OP.getProject(e),o=`Manual save @ ${new Date().toLocaleTimeString()}`,n=await i.Y.createCheckpoint(e,t||o,{kind:"manual",baseRevisionId:r.lastSavedCheckpointId??null,replaceId:r.lastSavedCheckpointId??null});return r.lastSavedCheckpointId=n.id,r.lastSavedAt=new Date(n.timestamp),await s.OP.updateProject(r),this.manualCheckpoints.set(e,n.id),this.markClean(e),n}async restoreLastSaved(e){await s.OP.init();let t=(await s.OP.getProject(e)).lastSavedCheckpointId;if(!t)return o.v.warn("[SaveManager] No saved checkpoint to restore",{projectId:e}),!1;let r=await this.runWithSuppressedDirty(e,async()=>{if(!await i.Y.checkpointExists(t))return o.v.warn("[SaveManager] Saved checkpoint missing",{projectId:e,checkpointId:t}),!1;let r=await i.Y.restoreCheckpoint(t);return r||o.v.error("[SaveManager] Failed to restore saved checkpoint",{projectId:e,checkpointId:t}),r});return r&&this.markClean(e),r}getSavedCheckpointId(e){return this.manualCheckpoints.get(e)??null}async syncProjectSaveState(e){await s.OP.init();let t=await s.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 n},33135:(e,t,r)=>{"use strict";r.d(t,{AM:()=>n,Wv:()=>a,hl:()=>l});var i=r(60687);r(43210);var s=r(40599),o=r(96241);function n({...e}){return(0,i.jsx)(s.bL,{"data-slot":"popover",...e})}function a({...e}){return(0,i.jsx)(s.l9,{"data-slot":"popover-trigger",...e})}function l({className:e,align:t="center",sideOffset:r=4,...n}){return(0,i.jsx)(s.ZL,{children:(0,i.jsx)(s.UC,{"data-slot":"popover-content",align:t,sideOffset:r,className:(0,o.cn)("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...n})})}},34429:(e,t,r)=>{"use strict";r.d(t,{QF:()=>s,WK:()=>o});var i=r(96241);async function s(){try{let e=await fetch("https://openrouter.ai/api/v1/models");if(!e.ok)throw Error(`Failed to fetch models: ${e.statusText}`);return(await e.json()).data.filter(e=>e.architecture.output_modalities.includes("text")&&e.supported_parameters.includes("tools")).sort((e,t)=>{let r=["gpt-4","claude","deepseek","qwen"],i=r.some(t=>e.id.toLowerCase().includes(t)),s=r.some(e=>t.id.toLowerCase().includes(e));return i&&!s?-1:!i&&s?1:t.created-e.created})}catch(e){return i.v.error("Error fetching models:",e),[{id:"deepseek/deepseek-chat",canonical_slug:"deepseek-chat",name:"DeepSeek Chat",created:Date.now(),description:"DeepSeek Chat - Fast and capable model for general tasks",context_length:64e3,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"deepseek"},pricing:{prompt:"0.00014",completion:"0.00028",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:64e3,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"qwen/qwen-2.5-coder-32b-instruct",canonical_slug:"qwen-2.5-coder-32b-instruct",name:"Qwen 2.5 Coder 32B",created:Date.now(),description:"Qwen 2.5 Coder - Specialized for code generation",context_length:32768,architecture:{input_modalities:["text"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"qwen"},pricing:{prompt:"0.00018",completion:"0.00018",request:"0",image:"0",web_search:"0",internal_reasoning:"0",input_cache_read:"0",input_cache_write:"0"},top_provider:{context_length:32768,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]},{id:"openai/gpt-4o",canonical_slug:"gpt-4o",name:"GPT-4o",created:Date.now(),description:"OpenAI GPT-4o - Multimodal model with vision capabilities",context_length:128e3,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"cl100k_base",instruct_type:"openai"},pricing:{prompt:"0.0025",completion:"0.01",request:"0",image:"0.00765",web_search:"0",internal_reasoning:"0",input_cache_read:"0.00125",input_cache_write:"0.0025"},top_provider:{context_length:128e3,max_completion_tokens:16384,is_moderated:!0},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens","response_format"]},{id:"anthropic/claude-3.5-sonnet",canonical_slug:"claude-3.5-sonnet",name:"Claude 3.5 Sonnet",created:Date.now(),description:"Anthropic Claude 3.5 Sonnet - Advanced reasoning and coding",context_length:2e5,architecture:{input_modalities:["text","image"],output_modalities:["text"],tokenizer:"claude",instruct_type:"anthropic"},pricing:{prompt:"0.003",completion:"0.015",request:"0",image:"0.0048",web_search:"0",internal_reasoning:"0",input_cache_read:"0.0003",input_cache_write:"0.00375"},top_provider:{context_length:2e5,max_completion_tokens:8192,is_moderated:!1},per_request_limits:null,supported_parameters:["tools","tool_choice","temperature","max_tokens"]}]}}function o(e,t=!0){if(null==e)return"";let r=t?e/1e3:e;if(0===r)return"free";if(r<1e-4)return`$${r.toFixed(5).replace(/\.?0+$/,"")}`;if(r<.001)return`$${r.toFixed(4).replace(/\.?0+$/,"")}`;if(r<.01)return`$${r.toFixed(3).replace(/\.?0+$/,"")}`;if(r<.1)return`$${r.toFixed(3).replace(/\.?0+$/,"")}`;if(r<1)return`$${r.toFixed(2).replace(/\.?0+$/,"")}`;else return`$${r.toFixed(2)}`}},39035:(e,t,r)=>{"use strict";r.d(t,{ThemeProvider:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call ThemeProvider() from the server but ThemeProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/theme-provider.tsx","ThemeProvider")},39390:(e,t,r)=>{"use strict";r.d(t,{J:()=>c});var i=r(60687),s=r(43210),o=r(78148),n=r(24224),a=r(96241);let l=(0,n.F)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),c=s.forwardRef(({className:e,...t},r)=>(0,i.jsx)(o.b,{ref:r,className:(0,a.cn)(l(),e),...t}));c.displayName=o.b.displayName},41900:(e,t,r)=>{"use strict";r.d(t,{default:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call the default export of \"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/tanstack-query-provider.tsx\" from the server, but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/providers/tanstack-query-provider.tsx","default")},46055:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var i=r(31658);let s=async e=>[{type:"image/x-icon",sizes:"16x16",url:(0,i.fillMetadataSegment)(".",await e.params,"favicon.ico")+""}]},51567:(e,t,r)=>{"use strict";r.d(t,{j:()=>d});var i=r(60687),s=r(43210),o=r(24934),n=r(59821),a=r(96271),l=r(3589),c=r(78272);function d({title:e,subtitle:t,badge:r,onLogoClick:d,actions:p=[],mobileMenuContent:u,desktopOnlyContent:h,className:m="",leftText:g}){let[f,y]=(0,s.useState)(!1);return(0,i.jsxs)("div",{className:`border-b bg-card shadow-sm relative z-20 ${m}`,children:[(0,i.jsxs)("div",{className:"px-3 py-2 flex items-center justify-between",children:[(0,i.jsxs)("button",{onClick:d,className:"flex items-center gap-2 p-1 pr-2 hover:ring-1 hover:ring-border rounded-sm transition-all",children:[(0,i.jsx)(a.g,{width:24,height:24}),g&&(0,i.jsx)("span",{className:"font-semibold text-lg hidden md:inline",children:g})]}),(0,i.jsx)("div",{className:"flex items-center gap-2 flex-1 justify-center md:justify-start md:ml-6",children:g?(0,i.jsx)("h1",{className:"text-lg font-semibold md:hidden",children:g}):e?(0,i.jsxs)(i.Fragment,{children:[e&&(0,i.jsx)("h1",{className:"text-lg md:text-xl font-semibold",children:e}),r&&(0,i.jsx)(n.E,{variant:"secondary",children:r})]}):null}),!g&&!e&&t&&(0,i.jsx)("div",{className:"hidden md:flex items-center flex-1 ml-6",children:(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:t})}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsxs)("div",{className:"hidden md:flex items-center gap-2",children:[p.map(e=>e.content?(0,i.jsx)("div",{children:e.content},e.id):(0,i.jsxs)(o.$,{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,i.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id)),h]}),(p.length>0||u)&&(0,i.jsx)(o.$,{variant:"ghost",size:"icon",onClick:()=>y(!f),className:"h-8 w-8 md:hidden",children:f?(0,i.jsx)(l.A,{className:"h-4 w-4"}):(0,i.jsx)(c.A,{className:"h-4 w-4"})})]})]}),f&&(p.length>0||u)&&(0,i.jsxs)("div",{className:"md:hidden border-t bg-muted/30 px-4 py-4 space-y-3",children:[!g&&!e&&t&&(0,i.jsx)("div",{className:"pb-2 border-b border-border/50",children:(0,i.jsx)("p",{className:"text-sm text-muted-foreground",children:t})}),(0,i.jsx)("div",{className:"space-y-2",children:p.map(e=>e.content?(0,i.jsx)("div",{children:e.content},e.id):(0,i.jsxs)(o.$,{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,i.jsx)(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},e.id))}),u&&(0,i.jsx)("div",{className:"pt-2 border-t border-border/50",children:u})]})]})}},53014:(e,t,r)=>{"use strict";r.d(t,{default:()=>n});var i=r(60687),s=r(92314),o=r(8693);function n({children:e}){let t=new s.E;return(0,i.jsx)(o.Ht,{client:t,children:e})}},57462:(e,t,r)=>{"use strict";function i(e){let t=`You are an AI assistant that helps users with their coding projects. You work in a sandboxed virtual file system. You have access to a 'shell' tool that executes commands and an 'evaluation' tool for self-assessment. @@ -310,7 +332,7 @@ Available Handlebars Features: `;return e&&(t+=` Current project structure: -${e}`),t}r.d(t,{m:()=>i})},58014:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>h,metadata:()=>p,viewport:()=>u});var i=r(37413),s=r(95474),o=r.n(s),n=r(31015),a=r.n(n),l=r(41900),c=r(39035);r(94348);var d=r(80363);let p={title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",openGraph:{title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",url:"https://huggingface.co/spaces/otst/deepstudio",siteName:"DeepStudio",images:[{url:"https://huggingface.co/spaces/otst/deepstudio/resolve/main/banner.png",width:1200,height:630,alt:"DeepStudio Open Graph Image"}]},twitter:{card:"summary_large_image",title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",images:["https://huggingface.co/spaces/otst/deepstudio/resolve/main/banner.png"]},appleWebApp:{capable:!0,title:"DeepStudio",statusBarStyle:"black-translucent"},icons:{icon:"/deepstudio-logo-dark.svg",shortcut:"/deepstudio-logo-dark.svg",apple:"/deepstudio-logo-dark.svg"}},u={initialScale:1,maximumScale:1,themeColor:"#000000"};function h({children:e}){return(0,i.jsx)("html",{lang:"en",suppressHydrationWarning:!0,children:(0,i.jsx)("body",{className:`${o().variable} ${a().variable} antialiased bg-background h-[100dvh] overflow-hidden`,suppressHydrationWarning:!0,children:(0,i.jsxs)(c.ThemeProvider,{children:[(0,i.jsx)(d.Toaster,{richColors:!0,position:"bottom-center"}),(0,i.jsx)(l.default,{children:e})]})})})}},59821:(e,t,r)=>{"use strict";r.d(t,{E:()=>a});var i=r(60687);r(43210);var s=r(24224),o=r(96241);let n=(0,s.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({className:e,variant:t,...r}){return(0,i.jsx)("div",{className:(0,o.cn)(n({variant:t}),e),...r})}},63974:(e,t,r)=>{"use strict";r.d(t,{bq:()=>p,eb:()=>h,gC:()=>u,l6:()=>c,yv:()=>d});var i=r(60687);r(43210);var s=r(72951),o=r(78272),n=r(13964),a=r(3589),l=r(96241);function c({...e}){return(0,i.jsx)(s.bL,{"data-slot":"select",...e})}function d({...e}){return(0,i.jsx)(s.WT,{"data-slot":"select-value",...e})}function p({className:e,size:t="default",children:r,...n}){return(0,i.jsxs)(s.l9,{"data-slot":"select-trigger","data-size":t,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",e),...n,children:[r,(0,i.jsx)(s.In,{asChild:!0,children:(0,i.jsx)(o.A,{className:"size-4 opacity-50"})})]})}function u({className:e,children:t,position:r="popper",...o}){return(0,i.jsx)(s.ZL,{children:(0,i.jsxs)(s.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"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...o,children:[(0,i.jsx)(m,{}),(0,i.jsx)(s.LM,{className:(0,l.cn)("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),(0,i.jsx)(g,{})]})})}function h({className:e,children:t,...r}){return(0,i.jsxs)(s.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",e),...r,children:[(0,i.jsx)("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,i.jsx)(s.VF,{children:(0,i.jsx)(n.A,{className:"size-4"})})}),(0,i.jsx)(s.p4,{children:t})]})}function m({className:e,...t}){return(0,i.jsx)(s.PP,{"data-slot":"select-scroll-up-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,i.jsx)(a.A,{className:"size-4"})})}function g({className:e,...t}){return(0,i.jsx)(s.wn,{"data-slot":"select-scroll-down-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,i.jsx)(o.A,{className:"size-4"})})}},68988:(e,t,r)=>{"use strict";r.d(t,{p:()=>o});var i=r(60687);r(43210);var s=r(96241);function o({className:e,type:t,...r}){return(0,i.jsx)("input",{type:t,"data-slot":"input",className:(0,s.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",e),...r})}},76741:(e,t,r)=>{"use strict";r.d(t,{I:()=>s});var i=r(96241);class s{static{this.BASE_URL="https://openrouter.ai/api/v1"}static async getGenerationStats(e,t){if(!e||!t)return null;try{let r=await fetch(`${this.BASE_URL}/generation?id=${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!r.ok)return i.v.warn(`[GenerationAPI] Failed to fetch generation stats: ${r.status}`),null;return await r.json()}catch(e){return i.v.error("[GenerationAPI] Error fetching generation stats:",e),null}}static queueGenerationForCostUpdate(e,t,r,s,o,n){setTimeout(async()=>{let r=await this.getGenerationStats(e,t);if(r?.usage){let t=r.total_cost??r.usage.total_cost??0;i.v.debug(`[GenerationAPI] Generation ${e}`,{normalized_tokens:r.usage.total_tokens,native_tokens:r.usage.native_tokens_total,actual_cost:t}),n(t,r.usage)}},3e3)}static extractGenerationId(e){return e.get("x-openrouter-generation-id")}static extractCostFromHeaders(e){let t,r,s=e.get("x-openrouter-usage"),o=e.get("x-openrouter-cost");if(s)try{t=JSON.parse(s)}catch(e){i.v.warn("[GenerationAPI] Failed to parse usage header:",e)}if(o){let e=parseFloat(o);isNaN(e)||(r=e)}return t||void 0!==r?{usage:t,cost:r}:null}}},80363:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call Toaster() from the server but Toaster is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/ui/sonner.tsx","Toaster")},82976:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,86346,23)),Promise.resolve().then(r.t.bind(r,27924,23)),Promise.resolve().then(r.t.bind(r,35656,23)),Promise.resolve().then(r.t.bind(r,40099,23)),Promise.resolve().then(r.t.bind(r,38243,23)),Promise.resolve().then(r.t.bind(r,28827,23)),Promise.resolve().then(r.t.bind(r,62763,23)),Promise.resolve().then(r.t.bind(r,97173,23))},86884:(e,t,r)=>{"use strict";r.d(t,{U:()=>a});var i=r(4950),s=r(96241);let o={"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}},n={input:1,output:2};class a{static calculateCost(e,t,r,i=!1){let n,a="number"==typeof e.cost&&Number.isFinite(e.cost)?e.cost:void 0,l=!0===e.isEstimated||void 0===a||a<1e-6,c=this.getPricingKey(t,r),d=this.getDynamicPricing(t,r),p=o[c],u=d||p||this.findBestPricingMatch(t,r);d||p||s.v.warn(`[CostCalculator] Falling back to default pricing for ${c}`);let h=0,m=Math.max(e.promptTokens??0,0);m&&(h+=m/1e6*u.input);let g=Math.max(e.completionTokens??0,0);return e.reasoningTokens&&(g=Math.max(g-Math.max(e.reasoningTokens,0),0)),g&&(h+=g/1e6*u.output),e.reasoningTokens&&u.reasoning&&(h+=e.reasoningTokens/1e6*u.reasoning),l||void 0===a?(n=Math.max(h,a??0),e.isEstimated=!i||l,void 0!==a&&a>n&&(n=a),void 0!==a&&Math.abs(n-a)>1e-4&&s.v.debug("[CostCalculator] Adjusted provisional cost",{provider:t,model:r,reportedCost:a,computedCost:h,finalCost:n})):(n=a,e.isEstimated=!1),e.isEstimated&&("openrouter"===t||t.toString().includes("openrouter"))&&s.v.warn("[CostCalculator] Using estimated cost based on normalized tokens for OpenRouter. This may be inaccurate. Consider using Generation API for native token counts."),n}static getPricingKey(e,t){return"openrouter"===e&&t.includes("/")?`openrouter/${t}`:`${e}/${t}`}static findBestPricingMatch(e,t){let r=`${e}/`;for(let[e,i]of Object.entries(o))if(e.startsWith(r)){let s=e.substring(r.length);if(t.includes(s)||s.includes(t))return i}return"ollama"===e||"lmstudio"===e?{input:0,output:0}:n}static getDynamicPricing(e,t){if(!this.isKnownProvider(e))return null;try{return i.s.getModelPricing(e,t)}catch(r){return s.v.debug("[CostCalculator] Failed to read dynamic pricing",{provider:e,model:t,error:r}),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?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}static getPricing(e,t){return o[this.getPricingKey(e,t)]||this.findBestPricingMatch(e,t)}static estimateCost(e,t,r,i=!0){let s=Math.ceil(1.3*e.split(/\s+/).length),o=this.getPricing(t,r);return s/1e6*(i?o.input:o.output)}static updateWithGenerationApiCost(e,t){let r={...e};return void 0!==t.total_cost&&(r.cost=t.total_cost,r.isEstimated=!1,e.cost&&Math.abs(e.cost-t.total_cost)>1e-4&&s.v.debug(`[CostCalculator] Cost corrected: ${e.cost?.toFixed(4)} -> ${t.total_cost.toFixed(4)} (${((t.total_cost-e.cost)/e.cost*100).toFixed(1)}% difference)`)),void 0!==t.native_tokens_total&&(r.nativeTokens={total:t.native_tokens_total,prompt:t.native_tokens_prompt,completion:t.native_tokens_completion}),r}}},94348:()=>{},94593:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>n});var i=r(60687),s=r(10218),o=r(52581);let n=({...e})=>{let{theme:t}=(0,s.D)();return(0,i.jsx)(o.l$,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}},94742:(e,t,r)=>{"use strict";r.d(t,{Y:()=>n});var i=r(28602),s=r(96241);class o{async initDB(){if(!this.isInitialized)return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onerror=()=>{s.v.error("Failed to open checkpoint database"),t(r.error)},r.onsuccess=()=>{this.db=r.result,this.isInitialized=!0,this.loadCheckpointsFromDB().then(()=>e())},r.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 r=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).getAll();r.onsuccess=()=>{let t=r.result;for(let e of(this.checkpoints.clear(),t)){let t={...e,kind:e.kind||"auto",baseRevisionId:e.baseRevisionId??null,files:new Map(e.files),directories:new Set(e.directories)};this.checkpoints.set(t.id,t)}e()},r.onerror=()=>{s.v.error("Failed to load checkpoints from DB"),t(r.error)}})}async saveCheckpointToDB(e){if(await this.initDB(),!this.db)return;let t={...e,files:Array.from(e.files.entries()),directories:Array.from(e.directories),kind:e.kind,baseRevisionId:e.baseRevisionId??null};return new Promise((e,r)=>{let i=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(t);i.onsuccess=()=>e(),i.onerror=()=>{s.v.error("Failed to save checkpoint to DB"),r(i.error)}})}async deleteCheckpointFromDB(e){if(await this.initDB(),this.db)return new Promise((t,r)=>{let i=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(e);i.onsuccess=()=>t(),i.onerror=()=>{s.v.error("Failed to delete checkpoint from DB"),r(i.error)}})}async createCheckpoint(e,t,r={}){await this.initDB(),await i.OP.init();let o=await i.OP.listDirectory(e,"/"),n=new Map,a=new Set;for(let t of o){let r=t.path.split("/").filter(Boolean);for(let e=1;e<=r.length-1;e++){let t="/"+r.slice(0,e).join("/");a.add(t)}if("string"==typeof t.content)n.set(t.path,t.content);else try{let r=await i.OP.readFile(e,t.path);"string"==typeof r.content&&n.set(t.path,r.content)}catch(e){s.v.error(`Failed to read file for checkpoint: ${t.path}`,e)}}let l={id:`cp_${Date.now()}`,timestamp:new Date().toISOString(),description:t,files:n,directories:a,projectId:e,kind:r.kind||"auto",baseRevisionId:r.baseRevisionId??null};if(r.replaceId&&(this.checkpoints.delete(r.replaceId),await this.deleteCheckpointFromDB(r.replaceId)),"manual"===l.kind){let t=Array.from(this.checkpoints.values()).find(t=>t.projectId===e&&"manual"===t.kind);t&&t.id!==r.replaceId&&(this.checkpoints.delete(t.id),await this.deleteCheckpointFromDB(t.id))}this.checkpoints.set(l.id,l),this.currentCheckpoint=l.id,await this.saveCheckpointToDB(l);let c=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(c.length>10)for(let e of c.slice(0,c.length-10))this.checkpoints.delete(e.id),await this.deleteCheckpointFromDB(e.id),s.v.debug(`[Checkpoint] Deleted old checkpoint: ${e.id}`);return l}async restoreCheckpoint(e){if("string"!=typeof e)return s.v.error("[Checkpoint] Invalid checkpoint ID type:",typeof e,e),!1;if(!e.startsWith("cp_")||e.length<6)return s.v.error("[Checkpoint] Invalid checkpoint ID format:",e),!1;await this.initDB();let t=this.checkpoints.get(e);if(!t&&(s.v.debug(`[Checkpoint] Checkpoint ${e} not in memory, checking database...`),await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e)))){s.v.error(`[Checkpoint] Checkpoint not found in database: ${e}`);let t=Array.from(this.checkpoints.keys());return s.v.debug("[Checkpoint] Available checkpoints:",t),!1}await i.OP.init();try{let r=await i.OP.listDirectory(t.projectId,"/"),s=new Set;for(let e of r){let t=e.path.split("/").filter(Boolean);for(let e=1;e<=t.length-1;e++){let r="/"+t.slice(0,e).join("/");s.add(r)}}for(let e of r)t.files.has(e.path)||await i.OP.deleteFile(t.projectId,e.path);for(let e of Array.from(s).filter(e=>!t.directories||!t.directories.has(e)).sort((e,t)=>t.length-e.length))try{await i.OP.deleteDirectory(t.projectId,e)}catch{}if(t.directories){for(let e of Array.from(t.directories).sort((e,t)=>e.length-t.length))if(!s.has(e))try{await i.OP.createDirectory(t.projectId,e)}catch{}}for(let[e,s]of t.files)r.some(t=>t.path===e)?await i.OP.updateFile(t.projectId,e,s):await i.OP.createFile(t.projectId,e,s);return this.currentCheckpoint=e,!0}catch(e){return s.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[r,i]of this.checkpoints)i.projectId===e&&(this.checkpoints.delete(r),t.push(r));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 n=new o},96241:(e,t,r)=>{"use strict";r.d(t,{cn:()=>o,v:()=>c});var i=r(49384),s=r(82348);function o(...e){return(0,s.QP)((0,i.$)(e))}let n={debug:10,info:20,warn:30,error:40,silent:50},a="undefined"!=typeof process&&process.env.NEXT_PUBLIC_LOG_LEVEL||"warn";function l(e){return n[a]<=n[e]}let c={debug:(...e)=>{l("debug")&&console.debug(...e)},info:(...e)=>{l("info")&&console.info(...e)},warn:(...e)=>{l("warn")&&console.warn(...e)},error:(...e)=>{l("error")&&console.error(...e)}}},96271:(e,t,r)=>{"use strict";r.d(t,{g:()=>n});var i=r(60687),s=r(10218),o=r(43210);function n({width:e=64,height:t=64,className:r}){let{resolvedTheme:n}=(0,s.D)(),[a,l]=(0,o.useState)(!1);return a?(0,i.jsx)("div",{style:{width:e,height:t},className:`${r} ${"light"===n?"[&_path]:fill-black":"[&_path]:fill-white"}`,dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="-115.152 89.394 256 256" width="100%" height="100%"><defs><clipPath id="_clipPath_dMGkP5G1pEE0GihLKCMn4c6sRumBcOzI"><rect x="-115.152" y="89.394" width="256" height="256"/></clipPath></defs><g clip-path="url(#_clipPath_dMGkP5G1pEE0GihLKCMn4c6sRumBcOzI)"><path d=" M -83.752 90.55 C -95.139 93.664 -105.701 102.02 -110.645 111.895 C -115.439 121.619 -115.289 116.985 -115.065 220.977 C -114.84 315.322 -114.84 315.322 -113.267 319.576 C -108.398 332.414 -98.06 341.377 -84.726 344.188 C -77.385 345.783 90.937 345.783 98.128 344.264 C 105.47 342.669 112.286 338.871 117.38 333.629 C 126.519 324.21 128.242 318.133 128.242 295.42 C 128.242 280 128.242 280 133.336 269.973 C 138.655 259.414 140.003 255.16 140.752 246.197 C 141.276 239.74 139.628 232.371 136.632 228.042 C 134.609 225.079 134.609 225.079 134.385 176.008 C 134.31 144.939 133.935 125.265 133.411 122.378 C 130.789 107.717 117.905 94.348 102.698 90.55 C 98.353 89.487 88.315 89.335 9.061 89.411 C -66.448 89.411 -80.232 89.638 -83.752 90.55 Z M 99.252 103.388 C 101.649 103.995 104.945 105.287 106.668 106.122 C 111.462 108.629 117.38 115.162 119.403 120.251 C 121.126 124.657 121.126 124.657 121.35 167.5 C 121.425 191.124 121.35 210.874 121.201 211.406 C 120.901 212.09 118.878 211.026 114.609 208.14 C 106.368 202.518 97.679 198.416 89.139 195.986 C 79.476 193.251 62.696 192.643 52.059 194.542 C 35.129 197.581 19.848 204.341 -0.228 217.711 C -14.761 227.358 -21.278 230.928 -27.345 232.523 C -39.855 235.866 -49.968 231.536 -52.74 221.737 C -53.863 217.787 -53.714 213.229 -52.365 211.026 C -51.991 210.418 -48.994 209.735 -44.5 209.355 C -31.84 208.14 -25.847 205.557 -18.955 198.416 C -13.562 192.795 -10.64 186.946 -9.592 179.958 C -8.843 174.488 -9.367 173.045 -11.539 174.26 C -16.334 176.767 -21.053 177.679 -32.065 178.21 C -44.2 178.742 -45.773 179.122 -49.519 182.692 C -51.691 184.667 -51.691 184.667 -52.89 182.844 C -53.639 181.781 -55.886 179.198 -57.983 177.071 C -61.279 173.653 -63.002 172.665 -70.793 169.551 C -81.131 165.525 -84.951 163.018 -87.123 158.992 C -87.947 157.397 -88.921 156.257 -89.371 156.409 C -92.367 157.397 -92.667 176.767 -89.82 184.439 C -87.423 190.82 -82.329 197.277 -76.636 201.075 C -73.34 203.354 -71.917 204.797 -72.216 205.557 C -76.186 216.571 -77.085 238.145 -74.089 249.235 C -67.347 274.531 -47.871 293.749 -21.278 301.573 C -13.862 303.776 -5.921 304.763 -1.876 304.004 C -0.378 303.7 2.244 302.181 4.192 300.434 C 6.963 297.927 7.637 297.623 7.637 298.762 C 7.637 302.864 -0.528 311.676 -10.865 318.816 C -16.708 322.842 -17.457 324.134 -16.708 328.616 C -16.184 331.654 -16.184 331.654 -48.02 331.654 C -83.303 331.654 -83.977 331.578 -90.944 326.717 C -93.116 325.197 -96.112 322.159 -97.536 320.032 C -102.779 312.284 -102.555 316.917 -102.33 216.116 C -102.105 125.417 -102.105 125.417 -100.307 121.011 C -96.712 111.895 -88.172 104.527 -79.483 103.008 C -77.46 102.704 -37.458 102.4 9.51 102.324 C 83.146 102.248 95.581 102.4 99.252 103.388 Z M 85.469 223.56 C 88.091 229.029 91.162 232.599 96.406 236.094 C 101.275 239.284 101.275 239.284 96.93 242.019 C 92.136 245.133 88.54 249.007 86.368 253.261 C 84.645 256.679 83.146 258.123 82.098 257.363 C 81.723 257.059 80.749 255.16 79.925 253.033 C 78.277 248.627 73.034 243.006 68.464 240.955 C 66.741 240.12 65.318 239.284 65.318 239.056 C 65.318 238.828 67.191 237.613 69.438 236.397 C 74.457 233.739 78.352 229.485 80.824 224.092 C 81.798 221.813 82.922 219.99 83.221 219.99 C 83.521 219.99 84.495 221.585 85.469 223.56 Z M 128.767 248.627 C 130.04 252.046 125.171 265.871 119.927 273.695 C 116.406 278.936 108.466 287.14 102.698 291.47 C 95.207 297.091 83.521 302.409 72.21 305.371 C 61.048 308.334 60.823 308.41 60.823 310.461 C 60.823 312.588 63.67 313.423 70.487 313.423 C 84.345 313.423 99.776 307.878 110.938 298.99 C 112.961 297.319 114.833 296.256 115.058 296.484 C 115.283 296.787 115.507 299.75 115.507 303.168 C 115.507 314.335 112.361 322.007 105.619 327.02 C 99.402 331.654 99.477 331.654 50.036 331.654 C 20.672 331.654 5.39 331.35 6.139 330.894 C 6.739 330.515 8.986 329.603 11.008 328.919 C 16.327 327.096 26.814 321.779 32.433 317.981 C 35.054 316.158 40.448 311.448 44.343 307.422 C 50.036 301.649 52.059 298.914 54.082 294.585 C 56.554 289.343 56.928 288.887 61.572 286.381 C 64.269 284.937 70.337 280.683 75.056 276.961 C 93.559 262.225 99.702 257.819 107.642 253.793 C 118.129 248.4 127.793 246.045 128.767 248.627 Z " fill="currentColor"/></g></svg>'}}):(0,i.jsx)("div",{style:{width:e,height:t}})}},97815:(e,t,r)=>{"use strict";r.d(t,{t:()=>D});var i=r(60687),s=r(43210),o=r(4950),n=r(57462),a=r(10158),l=r(76741),c=r(96241);class d{constructor(e){this.provider=e?.provider||o.s.getSelectedProvider()||"openrouter",this.providerConfig=(0,a.sO)(this.provider),this.apiKey=e?.apiKey||o.s.getProviderApiKey(this.provider)||"",this.model=e?.model||o.s.getProviderModel(this.provider)||this.getDefaultModel(),this.temperature=e?.temperature||.7,this.maxTokens=e?.maxTokens||4096}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,r){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error(`${this.providerConfig.name} API key is required. Please set it in settings.`);let i=[{role:"system",content:(0,n.m)(r?.fileTree)},{role:"user",content:e}];try{if("anthropic"===this.provider)return this.generateWithToolsAnthropic(i,t);if("gemini"===this.provider)return this.generateWithToolsGemini(i,t);return this.generateWithToolsOpenAI(i,t)}catch(e){throw e}}async generate(e,t){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error(`${this.providerConfig.name} API key is required. Please set it in settings.`);let r=[{role:"system",content:(0,n.m)(t?.fileTree)},{role:"user",content:e}];return"anthropic"===this.provider?this.generateAnthropic(r):"gemini"===this.provider?this.generateGemini(r):this.generateOpenAI(r)}async generateWithToolsOpenAI(e,t){let r=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`),"openrouter"===this.provider&&(i["HTTP-Referer"]="http://localhost:3000",i["X-Title"]="DeepStudio"),this.providerConfig.customHeaders&&Object.assign(i,this.providerConfig.customHeaders);let s=await fetch(`${r}/chat/completions`,{method:"POST",headers:i,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(!s.ok){let e=await s.text();throw Error(`${this.providerConfig.name} API error: ${e}`)}return this.parseStreamResponse(s)}async generateOpenAI(e){let t=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",r={"Content-Type":"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),"openrouter"===this.provider&&(r["HTTP-Referer"]="http://localhost:3000",r["X-Title"]="DeepStudio");let i=await fetch(`${t}/chat/completions`,{method:"POST",headers:r,body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature,max_tokens:this.maxTokens,stream:!1})});if(!i.ok){let e=await i.text();throw Error(`${this.providerConfig.name} API error: ${e}`)}let s=await i.json();return s.choices[0]?.message?.content||""}async generateWithToolsAnthropic(e,t){let r=e.find(e=>"system"===e.role)?.content||"",i=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),s=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-beta":"tools-2024-04-04"},body:JSON.stringify({model:this.model,messages:i,system:r,tools:t.map(e=>({name:e.name,description:e.description,input_schema:e.parameters})),temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})});if(!s.ok){let e=await s.text();throw Error(`Anthropic API error: ${e}`)}return this.parseAnthropicStream(s)}async generateAnthropic(e){let t=e.find(e=>"system"===e.role)?.content||"",r=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),i=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:t,temperature:this.temperature,max_tokens:this.maxTokens})});if(!i.ok){let e=await i.text();throw Error(`Anthropic API error: ${e}`)}let s=await i.json();return s.content[0]?.text||""}async generateWithToolsGemini(e,t){throw Error("Gemini tool calling not yet implemented. Please use OpenRouter or another provider.")}async generateGemini(e){let t=e.map(e=>({role:"system"===e.role?"user":e.role,parts:[{text:e.content}]})),r=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:t,generationConfig:{temperature:this.temperature,maxOutputTokens:this.maxTokens}})});if(!r.ok){let e=await r.text();throw Error(`Gemini API error: ${e}`)}let i=await r.json();return i.candidates[0]?.content?.parts[0]?.text||""}async *parseStreamResponse(e){let t=e.body?.getReader();if(!t)throw Error("Response body is not readable");let r=new TextDecoder,i="",s=null,o=null,n=null;if("openrouter"===this.provider){let t=e.headers;n=l.I.extractGenerationId(t);let r=l.I.extractCostFromHeaders(t);if(r?.cost!==void 0||r?.usage){let e=r.usage?.prompt_tokens??0,t=r.usage?.completion_tokens??0,i=r.usage?.total_tokens??e+t,s=r.cost??r.usage?.total_cost,a="number"==typeof s&&Number.isFinite(s)&&s>1e-6;o={promptTokens:e,completionTokens:t,totalTokens:i,cost:a?s:void 0,model:this.model,provider:this.provider,generationId:n||void 0,isEstimated:!a}}if(!o){let e=t.get("x-openrouter-usage");if(e)try{let t=JSON.parse(e),r=t.total_cost,i="number"==typeof r&&Number.isFinite(r)&&r>1e-6;o={promptTokens:t.prompt_tokens||0,completionTokens:t.completion_tokens||0,totalTokens:t.total_tokens||(t.prompt_tokens||0)+(t.completion_tokens||0),cost:i?r:void 0,model:this.model,provider:this.provider,generationId:n||void 0,isEstimated:!i}}catch(e){c.v.error("Error parsing OpenRouter usage header:",e)}}}for(;;){let{done:e,value:a}=await t.read();if(e)break;let l=(i+=r.decode(a,{stream:!0})).split("\n");for(let e of(i=l.pop()||"",l))if(e.startsWith("data: ")){let t=e.slice(6);if("[DONE]"===t){o&&o.totalTokens&&(yield{type:"usage",usage:o}),yield{type:"done"};return}try{let e=JSON.parse(t),r=e.choices?.[0]?.delta;if(r?.content&&(yield{type:"content",content:r.content}),r?.tool_calls)for(let e of r.tool_calls)e.id&&(s&&(yield{type:"tool_call",toolCall:s}),s={id:e.id,type:"function",function:{name:e.function?.name||"",arguments:""}}),e.function?.arguments&&s&&(s.argumentsBuffer=(s.argumentsBuffer||"")+e.function.arguments,s.function&&(s.function.arguments=s.argumentsBuffer));e.usage&&(o={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:n||void 0}),e.x_groq?.usage&&(o={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(s)try{let e=s.argumentsBuffer;e&&s.function&&(s.function.arguments=e),yield{type:"tool_call",toolCall:s}}catch(e){c.v.error("Error parsing tool call parameters:",e)}o&&o.totalTokens&&(yield{type:"usage",usage:o}),yield{type:"done"}}async *parseAnthropicStream(e){let t=e.body?.getReader();if(!t)throw Error("Response body is not readable");let r=new TextDecoder,i="",s=null;for(;;){let{done:e,value:o}=await t.read();if(e)break;let n=(i+=r.decode(o,{stream:!0})).split("\n");for(let e of(i=n.pop()||"",n))if(e.startsWith("data: ")){let t=e.slice(6);try{let e=JSON.parse(t);if("content_block_delta"===e.type&&e.delta?.text_delta?.text)yield{type:"content",content:e.delta.text_delta.text};else if("content_block_start"===e.type&&e.content_block?.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&&e.message?.usage)s={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)s&&(s.completionTokens=e.usage.output_tokens||s.completionTokens,s.totalTokens=(s.promptTokens||0)+(s.completionTokens||0));else if("message_stop"===e.type){s&&s.totalTokens&&(yield{type:"usage",usage:s}),yield{type:"done"};return}}catch(e){c.v.error("Error parsing Anthropic stream:",e)}}}s&&s.totalTokens&&(yield{type:"usage",usage:s}),yield{type:"done"}}static async validateApiKey(e,t){if(!e)return!1;try{let r=await fetch("/api/validate-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,provider:t})});if(!r.ok)return!1;let{valid:i}=await r.json();return i}catch{return!1}}static async getAvailableModels(e,t){let r=t||o.s.getSelectedProvider()||"openrouter",i=(0,a.sO)(r),s=e||o.s.getProviderApiKey(r);if(!i.supportsModelDiscovery&&i.models)return i.models.map(e=>e.id);try{let e=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s,provider:r})});if(!e.ok)return i.models?.map(e=>e.id)||[];let{models:t}=await e.json();return t||[]}catch{return i.models?.map(e=>e.id)||[]}}}var p=r(24934),u=r(68988),h=r(39390),m=r(12597),g=r(13861),f=r(13964),y=r(11860),v=r(25334),x=r(52581),b=r(59821),w=r(33135),C=r(78200),k=r(56085),j=r(45583),S=r(9593),_=r(24413),T=r(10510),P=r(41862),I=r(78272),N=r(99270),$=r(34429),A=r(24573);function F({provider:e,value:t,onChange:r,className:n,hideModelDetails:l}){let m=e||o.s.getSelectedProvider(),g=(0,a.sO)(m),[f,v]=(0,s.useState)([]),[F,O]=(0,s.useState)(!0),[D,E]=(0,s.useState)(""),[R,M]=(0,s.useState)(!1),[U,B]=(0,s.useState)(""),[L,q]=(0,s.useState)(!1),W=e=>e.name;(0,s.useCallback)(async()=>{try{O(!0);let e=o.s.getProviderApiKey(m);if(g.apiKeyRequired&&!e){q(!0),g.models?v(g.models):v([]);return}q(!1);let t=o.s.getCachedModels(m);if(t){let e=t.models;v(e),"openrouter"===m&&(0,A.V)("openrouter",e);return}let r=[];if("openrouter"===m){let e=await (0,$.QF)();(0,A.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{}}return null==e?"":String(e)};r=e.map(e=>{let r=e.pricing?.prompt?Number(e.pricing.prompt):void 0,i=e.pricing?.completion?Number(e.pricing.completion):void 0,s=e.pricing?.internal_reasoning?Number(e.pricing.internal_reasoning):void 0,o=e=>{if(void 0!==e&&Number.isFinite(e))return 1e6*e},n=o(r),a=o(i),l=o(s);return{id:e.id,name:e.name,description:t(e.description),contextLength:e.context_length,maxTokens:e.top_provider?.max_completion_tokens,supportsFunctions:e.supported_parameters?.includes("tools"),supportsVision:e.architecture?.input_modalities?.includes("image"),pricing:void 0!==n&&void 0!==a?{input:n,output:a,reasoning:l}:void 0}})}else r=g.supportsModelDiscovery?(await d.getAvailableModels(e||void 0,m)).map(e=>({id:e,name:e.split("/").pop()||e,contextLength:32e3,supportsFunctions:!0})):g.models?g.models:[];v(r),g.isLocal&&0===r.length&&x.oR.warning(`No models found in ${g.name}. Please load some models in the application.`,{duration:5e3}),r.length>0&&(o.s.setCachedModels(m,r),"openrouter"===m&&(0,A.V)("openrouter",r))}catch(e){c.v.error("Failed to load models:",e),g.isLocal&&x.oR.error(`${g.name} server not running. Please start the server and load some models.`,{duration:5e3}),g.models&&v(g.models)}finally{O(!1)}},[m,g]);let z=e=>{E(e),o.s.setProviderModel(m,e),r?.(e),M(!1),B("")},K=e=>{let t=e.id.toLowerCase();return t.includes("deepseek")?(0,i.jsx)(C.A,{className:"h-3 w-3"}):t.includes("claude")?(0,i.jsx)(k.A,{className:"h-3 w-3"}):t.includes("gpt")?(0,i.jsx)(j.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,i.jsx)(S.A,{className:"h-3 w-3"}):t.includes("llama")?(0,i.jsx)(_.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,i.jsx)(T.A,{className:"h-3 w-3"}):null},H=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"},J=(0,s.useMemo)(()=>{if(!U.trim())return f;let e=U.toLowerCase();return f.filter(t=>{let r=t.id.toLowerCase(),i=W(t).toLowerCase(),s=t.id.split("/")[0].toLowerCase();return r.includes(e)||i.includes(e)||s.includes(e)})},[f,U]),G=f.find(e=>e.id===D);return F?(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{children:"AI Model"}),(0,i.jsxs)("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted",children:[(0,i.jsx)(P.A,{className:"h-4 w-4 animate-spin"}),(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):L?(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{children:"AI Model"}),(0,i.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,i.jsxs)("span",{className:"text-sm text-orange-600 dark:text-orange-400",children:["API key required for ",g.name]})}),(0,i.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Set your API key in settings to load available models"})]}):(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{htmlFor:"model-select",children:"AI Model"}),(0,i.jsxs)(w.AM,{open:R,onOpenChange:M,children:[(0,i.jsx)(w.Wv,{asChild:!0,children:(0,i.jsxs)(p.$,{variant:"outline",role:"combobox","aria-expanded":R,className:"w-full justify-between font-normal",children:[G?(0,i.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[K(G),(0,i.jsx)("span",{className:"truncate",children:W(G)})]}):(0,i.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,i.jsx)(I.A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),(0,i.jsxs)(w.hl,{className:"w-[32rem] p-0",align:"start",side:"bottom",sideOffset:5,avoidCollisions:!1,children:[(0,i.jsxs)("div",{className:"flex items-center border-b px-3",children:[(0,i.jsx)(N.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,i.jsx)(u.p,{placeholder:"Search models...",value:U,onChange:e=>B(e.target.value),className:"h-10 border-0 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),U&&(0,i.jsx)(p.$,{variant:"ghost",size:"sm",onClick:()=>B(""),className:"h-5 w-5 p-0",children:(0,i.jsx)(y.A,{className:"h-3 w-3"})})]}),(0,i.jsx)("div",{className:"max-h-[400px] min-h-[300px] overflow-y-auto",children:0===J.length?(0,i.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):J.map(e=>(0,i.jsx)("button",{onClick:()=>z(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,i.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[K(e),(0,i.jsx)("span",{className:"font-medium",children:W(e)}),"openrouter"===m&&(0,i.jsx)(b.E,{variant:"secondary",className:`text-xs ${H(e.id)}`,children:e.id.split("/")[0]})]}),(0,i.jsxs)("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[(0,i.jsxs)("span",{children:["Context: ",Math.round(e.contextLength/1e3),"K"]}),e.pricing&&(0===e.pricing.input&&0===e.pricing.output?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsx)("span",{children:"Free"})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsxs)("span",{children:[(0,$.WK)(e.pricing.input),"/K | ",(0,$.WK)(e.pricing.output),"/K"]})]})),!e.pricing&&"openrouter"!==m&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsx)("span",{children:"Pricing varies"})]})]})]})},e.id))})]})]}),!l&&G&&(0,i.jsxs)("div",{className:"mt-1 text-xs text-muted-foreground max-h-[150px] overflow-y-auto pr-2",children:[(0,i.jsx)("div",{className:"font-medium mb-1",children:G.pricing?0===G.pricing.input&&0===G.pricing.output?"Free":`Input: ${(0,$.WK)(G.pricing.input)}/K • Output: ${(0,$.WK)(G.pricing.output)}/K`:"Pricing varies by provider"}),G.description&&(0,i.jsx)("div",{children:G.description})]})]})}var O=r(63974);function D({onClose:e,onModelChange:t}){let[r,n]=(0,s.useState)({}),[l,c]=(0,s.useState)(()=>o.s.getSelectedProvider()),[b,w]=(0,s.useState)(!1),[C,k]=(0,s.useState)(!1),[j,S]=(0,s.useState)(null),[_,T]=(0,s.useState)(""),P=e=>{T(e),o.s.setProviderApiKey(l,e),S(null),o.s.clearModelCache(l),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:l,hasKey:!!e}}))},I=async()=>{if(!_)return void x.oR.error("Please enter an API key");k(!0);try{let e=await d.validateApiKey(_,l);S(e),e?x.oR.success("API key is valid!"):x.oR.error("Invalid API key")}catch{S(!1),x.oR.error("Failed to validate API key")}finally{k(!1)}},N=(0,a.sO)(l);return(0,i.jsxs)("div",{className:"space-y-6",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("h3",{className:"font-medium text-sm",children:"Model Settings"}),(0,i.jsx)("p",{className:"text-muted-foreground text-xs mt-1",children:"Configure your AI model and API connection"})]}),(0,i.jsxs)("div",{className:"space-y-4",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)(h.J,{htmlFor:"provider",children:"AI Provider"}),(0,i.jsxs)(O.l6,{value:l,onValueChange:e=>{c(e),o.s.setSelectedProvider(e),T(o.s.getProviderApiKey(e)||""),S(null)},children:[(0,i.jsx)(O.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,i.jsx)(O.yv,{placeholder:"Select a provider",children:l&&(0,i.jsxs)("div",{className:"flex flex-col text-left",children:[(0,i.jsx)("span",{className:"font-medium",children:N.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:N.description})]})})}),(0,i.jsx)(O.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,i.jsx)(O.eb,{value:e.id,children:(0,i.jsxs)("div",{className:"flex flex-col",children:[(0,i.jsx)("span",{className:"font-medium",children:e.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:e.description})]})},e.id))})]})]}),(N.apiKeyRequired||N.isLocal)&&(0,i.jsxs)("div",{children:[(0,i.jsxs)(h.J,{htmlFor:"api-key",children:[N.name," API Key",!N.apiKeyRequired&&(0,i.jsx)("span",{className:"text-muted-foreground text-xs ml-1",children:"(optional)"})]}),(0,i.jsxs)("div",{className:"flex gap-2 mt-2",children:[(0,i.jsxs)("div",{className:"relative flex-1",children:[(0,i.jsx)(u.p,{id:"api-key",type:b?"text":"password",value:_,onChange:e=>P(e.target.value),placeholder:N.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,i.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>w(!b),children:b?(0,i.jsx)(m.A,{className:"h-4 w-4"}):(0,i.jsx)(g.A,{className:"h-4 w-4"})})]}),(0,i.jsx)(p.$,{onClick:I,disabled:C||!_,size:"sm",children:C?"Validating...":"Validate"}),null!==j&&(0,i.jsx)("div",{className:"flex items-center",children:j?(0,i.jsx)(f.A,{className:"h-5 w-5 text-green-500"}):(0,i.jsx)(y.A,{className:"h-5 w-5 text-red-500"})})]}),N.apiKeyHelpUrl&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,i.jsxs)("a",{href:N.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[N.name," ",(0,i.jsx)(v.A,{className:"h-3 w-3"})]})]}),N.isLocal&&!N.apiKeyRequired&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",N.name,". Only needed if you've configured authentication on your local server."]})]}),!N.apiKeyRequired&&N.isLocal&&(0,i.jsxs)("div",{className:"text-sm text-muted-foreground p-3 border rounded-md bg-muted/50",children:[(0,i.jsx)("p",{className:"font-medium mb-1",children:"Local Provider"}),(0,i.jsxs)("p",{children:["Make sure ",N.name," is running on your machine."]}),(0,i.jsxs)("p",{children:["Default endpoint: ",(0,i.jsx)("code",{className:"text-xs",children:N.baseUrl})]}),"lmstudio"===l&&(0,i.jsxs)("div",{className:"mt-2 text-xs",children:[(0,i.jsx)("p",{className:"font-medium",children:"For tool use support:"}),(0,i.jsx)("p",{children:"• Load a model like qwen/qwen3-4b-thinking-2507"}),(0,i.jsx)("p",{children:"• Start the local server in LM Studio"}),(0,i.jsx)("p",{children:"• Models will be automatically discovered"})]})]}),(0,i.jsx)(F,{provider:l,onChange:e=>{t?.(e)},className:"space-y-2"})]}),e&&(0,i.jsx)("div",{className:"flex justify-end pt-4 border-t",children:(0,i.jsx)(p.$,{onClick:e,size:"sm",children:"Done"})})]})}},99197:(e,t,r)=>{"use strict";r.d(t,{ThemeProvider:()=>o});var i=r(60687);r(43210);var s=r(10218);function o({children:e,attribute:t="class",defaultTheme:r="dark",enableSystem:o=!0,storageKey:n="deepstudio-theme",...a}){return(0,i.jsx)(s.N,{attribute:t,defaultTheme:r,enableSystem:o,storageKey:n,disableTransitionOnChange:!0,...a,children:e})}},99526:(e,t,r)=>{"use strict";r.d(t,{r:()=>T});var i=r(28602),s=r(94742),o=r(32623),n=r(4950),a=r(10158),l=r(86884),c=r(76741);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., "<div className=\\"contact\\">", "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=r(57462);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,r){if("/"===r||!r)return;let i=r.split("/").filter(Boolean),s="";for(let r=0;r<i.length;r++){s="/"+i.slice(0,r+1).join("/");try{await e.createDirectory(t,s)}catch{}}}async function y(e,t,r,i={}){if(!t||"string"!=typeof t)return{stdout:"",stderr:"Invalid project ID provided",exitCode:2};if(!r||0===r.length)return{stdout:"",stderr:"No command provided",exitCode:2};let s=r.filter(e=>null!=e&&""!==e);if(0===s.length)return{stdout:"",stderr:"No valid command arguments provided",exitCode:2};let[o,...n]=s;try{switch(o){case"ls":{let r=new Set,i=[];for(let e of n)e&&e.startsWith("-")?r.add(e):e&&i.push(e);let s=r.has("-R")||r.has("-r"),o=g(i[0])||"/";if(s){let r=await e.getAllFilesAndDirectories(t),i="/"===o?"/":o.endsWith("/")?o:o+"/",s=r.filter(e=>e.path===o||e.path.startsWith(i)).map(e=>e.path).sort().join("\n");return{stdout:m(s),stderr:"",exitCode:0}}{let r=(await e.listDirectory(t,o)).map(e=>e.path).sort().join("\n");return{stdout:m(r),stderr:"",exitCode:0}}}case"cat":{let r=g(n[0]);if(!r)return{stdout:"",stderr:"cat: missing file path",exitCode:2};if(r.startsWith("/-"))return{stdout:"",stderr:"cat: invalid path (looks like an option). Use: cat /path/to/file",exitCode:2};let i=await e.readFile(t,r);if("string"!=typeof i.content)return{stdout:"",stderr:`cat: ${r}: binary or non-text file`,exitCode:1};return{stdout:m(i.content),stderr:"",exitCode:0}}case"grep":{let r,i={n:!1,i:!1,r:!1,F:!1},s=[];for(let e of n)if(e.startsWith("-"))for(let t of e.slice(1))t in i&&(i[t]=!0);else s.push(e);let o=s[0],a=g(s[1])||"/";if(!o)return{stdout:"",stderr:"grep: missing pattern",exitCode:2};if(i.F){let e=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=new RegExp(e,i.i?"i":"")}else r=new RegExp(o,i.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 s=0;s<t.length;s++){let o=t[s];r.test(o)&&d.push(`${e.path}${i.n?":"+(s+1):""}:${o}`)}}let p=d.join("\n");if(0===d.length){let e="/"===a?"workspace root":a;return{stdout:"",stderr:`grep: pattern "${o}" not found in ${e}`,exitCode:1}}return{stdout:m(p),stderr:"",exitCode:0}}case"find":{let r,i,s;for(let e=0;e<n.length;e++){let t=n[e];if(t){if("-name"===t){i=n[e+1],e++;continue}if("-maxdepth"===t||"-type"===t){e++;continue}t.startsWith("-")||r||(r=t)}}let o=g(r)||"/",a=await e.getAllFilesAndDirectories(t),l="/"===o?"/":o.endsWith("/")?o:o+"/",c=i?(s=i,RegExp("^"+s.replace(/[.+^${}()|\[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$")):null,d=a.filter(e=>e.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 r=n.includes("-p"),i=n[r?n.indexOf("-p")+1:0],s=g(i);if(!s)return{stdout:"",stderr:"mkdir: missing path",exitCode:2};return r?await f(e,t,s):await e.createDirectory(t,s),{stdout:"",stderr:"",exitCode:0}}case"rm":{let r=!1,i=!1,s=!1,o=[];for(let e of n)e&&e.startsWith("-")?((e.includes("r")||e.includes("R"))&&(r=!0),e.includes("f")&&(i=!0),e.includes("v")&&(s=!0)):e&&o.push(e);if(0===o.length)return{stdout:"",stderr:"rm: missing operand",exitCode:2};let a=!1,l=[];for(let n of o){let o=g(n);if(!o){i||(a=!0);continue}try{await e.deleteFile(t,o),s&&l.push(`removed '${o}'`)}catch{if(r)try{await e.deleteDirectory(t,o),s&&l.push(`removed directory '${o}'`)}catch{!i&&(a=!0,s&&l.push(`rm: cannot remove '${o}': No such file or directory`))}else!i&&(a=!0,s&&l.push(`rm: cannot remove '${o}': Is a directory (use -r to remove directories)`))}}let c=s?l.join("\n"):"",d=a&&!s?"rm: some paths could not be removed":"";return{stdout:m(c),stderr:d,exitCode:+!!a}}case"rmdir":{let r=[],i=!1;for(let e of n)"-v"===e||"--verbose"===e?i=!0:e&&!e.startsWith("-")&&r.push(e);if(0===r.length)return{stdout:"",stderr:"rmdir: missing operand",exitCode:2};let s=!1,o=[];for(let n of r){let r=g(n);if(!r){s=!0;continue}try{(await e.listDirectory(t,r)).length>0?(s=!0,i&&o.push(`rmdir: failed to remove '${r}': Directory not empty`)):(await e.deleteDirectory(t,r),i&&o.push(`rmdir: removing directory, '${r}'`))}catch{s=!0,i&&o.push(`rmdir: failed to remove '${r}': No such file or directory`)}}let a=i?o.join("\n"):"",l=s&&!i?"rmdir: failed to remove one or more directories":"";return{stdout:m(a),stderr:l,exitCode:+!!s}}case"mv":{let[r,i]=n,s=g(r),o=g(i);if(!s||!o)return{stdout:"",stderr:"mv: missing operands",exitCode:2};try{return await e.renameFile(t,s,o),{stdout:"",stderr:"",exitCode:0}}catch{return await e.renameDirectory(t,s,o),{stdout:"",stderr:"",exitCode:0}}}case"cp":{let r=n.includes("-r"),[i,s]=n.filter(e=>"-r"!==e);if(i=g(i),s=g(s),!i||!s)return{stdout:"",stderr:"cp: missing operands",exitCode:2};try{let r=await e.readFile(t,i),o=(r.content,r.content);try{await e.createFile(t,s,o)}catch{await e.updateFile(t,s,o)}return{stdout:"",stderr:"",exitCode:0}}catch{if(!r)return{stdout:"",stderr:"cp: -r required for directories",exitCode:1};let o=await e.getAllFilesAndDirectories(t),n=i.endsWith("/")?i:i+"/";for(let r of o)if((!("type"in r)||"directory"!==r.type)&&(r.path===i||r.path.startsWith(n))){let o=r.path.slice(i.length),n=(s.endsWith("/")?s.slice(0,-1):s)+o;await f(e,t,n.split("/").slice(0,-1).join("/"));let a=(r.content,r.content);try{await e.createFile(t,n,a)}catch{await e.updateFile(t,n,a)}}return{stdout:"",stderr:"",exitCode:0}}}case"echo":if(n.includes(">")||n.includes(">>"))return{stdout:"",stderr:"echo: redirection is not supported in this environment. Use json_patch to edit files.",exitCode:2};return{stdout:m(n.join(" ")),stderr:"echo prints to stdout only. To modify files, use json_patch.",exitCode:1};case"nl":{let r="";for(let e of n)"-ba"===e||e.startsWith("-")||(r=e);let i=g(r);if(!i)return{stdout:"",stderr:"nl: missing file path",exitCode:2};try{let r=await e.readFile(t,i);if("string"!=typeof r.content)return{stdout:"",stderr:`nl: ${i}: binary file`,exitCode:1};let s=r.content.split(/\r?\n/).map((e,t)=>{let r=String(t+1).padStart(6," ");return`${r} ${e}`});return{stdout:m(s.join("\n")),stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`nl: ${i}: ${e?.message||"file not found"}`,exitCode:1}}}case"sed":{if(0===n.length)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" <file> or sed -n "1,80p" <file>',exitCode:2};let r=!1,i=0,s=1;"-n"===n[0]&&(r=!0,i=1,s=2);let o=n[i],a=n[s];if(!o||!a)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" <file> or sed -n "1,80p" <file>',exitCode:2};let l=o.match(/^(\d+),(\d+)p$/);if(l){let r=parseInt(l[1]),i=parseInt(l[2]),s=await e.readFile(t,a);if("string"!=typeof s.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let o=s.content.split("\n").slice(r-1,i);return{stdout:m(o.join("\n")),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let c=o.match(/^(\d+)p$/);if(c){let r=parseInt(c[1]),i=await e.readFile(t,a);if("string"!=typeof i.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let s=i.content.split("\n");if(r<=0||r>s.length)return{stdout:"",stderr:`sed: line ${r} out of range`,exitCode:1};return{stdout:m(s[r-1]),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let d=o.match(/^s\/(.*)\/(.*)\/(g?)$/);if(d){let[,i,s]=d,o=await e.readFile(t,a);if("string"!=typeof o.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let n=RegExp(i,"g"),l=o.content.replace(n,s);return{stdout:m(l),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:+!r}}return{stdout:"",stderr:'sed: supported formats: "s/pat/repl/g", "1,80p", "80p". Use json_patch for file changes.',exitCode:2}}default:{let e="bash"===o?` +${e}`),t}r.d(t,{m:()=>i})},58014:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>h,metadata:()=>p,viewport:()=>u});var i=r(37413),s=r(95474),o=r.n(s),n=r(31015),a=r.n(n),l=r(41900),c=r(39035);r(94348);var d=r(80363);let p={title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",openGraph:{title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",url:"https://huggingface.co/spaces/otst/deepstudio",siteName:"DeepStudio",images:[{url:"https://huggingface.co/spaces/otst/deepstudio/resolve/main/banner.png",width:1200,height:630,alt:"DeepStudio Open Graph Image"}]},twitter:{card:"summary_large_image",title:"DeepStudio | Agentic AI Development \uD83C\uDFA8",description:"DeepStudio is an AI-powered development environment that enables autonomous multi-file development through intelligent tool usage. Build complete applications with natural language.",images:["https://huggingface.co/spaces/otst/deepstudio/resolve/main/banner.png"]},appleWebApp:{capable:!0,title:"DeepStudio",statusBarStyle:"black-translucent"},icons:{icon:"/deepstudio-logo-dark.svg",shortcut:"/deepstudio-logo-dark.svg",apple:"/deepstudio-logo-dark.svg"}},u={initialScale:1,maximumScale:1,themeColor:"#000000"};function h({children:e}){return(0,i.jsx)("html",{lang:"en",suppressHydrationWarning:!0,children:(0,i.jsx)("body",{className:`${o().variable} ${a().variable} antialiased bg-background h-[100dvh] overflow-hidden`,suppressHydrationWarning:!0,children:(0,i.jsxs)(c.ThemeProvider,{children:[(0,i.jsx)(d.Toaster,{richColors:!0,position:"bottom-center"}),(0,i.jsx)(l.default,{children:e})]})})})}},59821:(e,t,r)=>{"use strict";r.d(t,{E:()=>a});var i=r(60687);r(43210);var s=r(24224),o=r(96241);let n=(0,s.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({className:e,variant:t,...r}){return(0,i.jsx)("div",{className:(0,o.cn)(n({variant:t}),e),...r})}},63974:(e,t,r)=>{"use strict";r.d(t,{bq:()=>p,eb:()=>h,gC:()=>u,l6:()=>c,yv:()=>d});var i=r(60687);r(43210);var s=r(72951),o=r(78272),n=r(13964),a=r(3589),l=r(96241);function c({...e}){return(0,i.jsx)(s.bL,{"data-slot":"select",...e})}function d({...e}){return(0,i.jsx)(s.WT,{"data-slot":"select-value",...e})}function p({className:e,size:t="default",children:r,...n}){return(0,i.jsxs)(s.l9,{"data-slot":"select-trigger","data-size":t,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",e),...n,children:[r,(0,i.jsx)(s.In,{asChild:!0,children:(0,i.jsx)(o.A,{className:"size-4 opacity-50"})})]})}function u({className:e,children:t,position:r="popper",...o}){return(0,i.jsx)(s.ZL,{children:(0,i.jsxs)(s.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"===r&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...o,children:[(0,i.jsx)(m,{}),(0,i.jsx)(s.LM,{className:(0,l.cn)("p-1","popper"===r&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),(0,i.jsx)(g,{})]})})}function h({className:e,children:t,...r}){return(0,i.jsxs)(s.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",e),...r,children:[(0,i.jsx)("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:(0,i.jsx)(s.VF,{children:(0,i.jsx)(n.A,{className:"size-4"})})}),(0,i.jsx)(s.p4,{children:t})]})}function m({className:e,...t}){return(0,i.jsx)(s.PP,{"data-slot":"select-scroll-up-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,i.jsx)(a.A,{className:"size-4"})})}function g({className:e,...t}){return(0,i.jsx)(s.wn,{"data-slot":"select-scroll-down-button",className:(0,l.cn)("flex cursor-default items-center justify-center py-1",e),...t,children:(0,i.jsx)(o.A,{className:"size-4"})})}},68988:(e,t,r)=>{"use strict";r.d(t,{p:()=>o});var i=r(60687);r(43210);var s=r(96241);function o({className:e,type:t,...r}){return(0,i.jsx)("input",{type:t,"data-slot":"input",className:(0,s.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",e),...r})}},76741:(e,t,r)=>{"use strict";r.d(t,{I:()=>s});var i=r(96241);class s{static{this.BASE_URL="https://openrouter.ai/api/v1"}static async getGenerationStats(e,t){if(!e||!t)return null;try{let r=await fetch(`${this.BASE_URL}/generation?id=${e}`,{headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!r.ok)return i.v.warn(`[GenerationAPI] Failed to fetch generation stats: ${r.status}`),null;return await r.json()}catch(e){return i.v.error("[GenerationAPI] Error fetching generation stats:",e),null}}static queueGenerationForCostUpdate(e,t,r,s,o,n){setTimeout(async()=>{let r=await this.getGenerationStats(e,t);if(r?.usage){let t=r.total_cost??r.usage.total_cost??0;i.v.debug(`[GenerationAPI] Generation ${e}`,{normalized_tokens:r.usage.total_tokens,native_tokens:r.usage.native_tokens_total,actual_cost:t}),n(t,r.usage)}},3e3)}static extractGenerationId(e){return e.get("x-openrouter-generation-id")}static extractCostFromHeaders(e){let t,r,s=e.get("x-openrouter-usage"),o=e.get("x-openrouter-cost");if(s)try{t=JSON.parse(s)}catch(e){i.v.warn("[GenerationAPI] Failed to parse usage header:",e)}if(o){let e=parseFloat(o);isNaN(e)||(r=e)}return t||void 0!==r?{usage:t,cost:r}:null}}},80363:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>i});let i=(0,r(12907).registerClientReference)(function(){throw Error("Attempted to call Toaster() from the server but Toaster is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/otto/Desktop/deepstudio/deepstudio-git/components/ui/sonner.tsx","Toaster")},82976:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,86346,23)),Promise.resolve().then(r.t.bind(r,27924,23)),Promise.resolve().then(r.t.bind(r,35656,23)),Promise.resolve().then(r.t.bind(r,40099,23)),Promise.resolve().then(r.t.bind(r,38243,23)),Promise.resolve().then(r.t.bind(r,28827,23)),Promise.resolve().then(r.t.bind(r,62763,23)),Promise.resolve().then(r.t.bind(r,97173,23))},86884:(e,t,r)=>{"use strict";r.d(t,{U:()=>a});var i=r(4950),s=r(96241);let o={"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}},n={input:1,output:2};class a{static calculateCost(e,t,r,i=!1){let n,a="number"==typeof e.cost&&Number.isFinite(e.cost)?e.cost:void 0,l=!0===e.isEstimated||void 0===a||a<1e-6,c=this.getPricingKey(t,r),d=this.getDynamicPricing(t,r),p=o[c],u=d||p||this.findBestPricingMatch(t,r);d||p||s.v.warn(`[CostCalculator] Falling back to default pricing for ${c}`);let h=0,m=Math.max(e.promptTokens??0,0);m&&(h+=m/1e6*u.input);let g=Math.max(e.completionTokens??0,0);return e.reasoningTokens&&(g=Math.max(g-Math.max(e.reasoningTokens,0),0)),g&&(h+=g/1e6*u.output),e.reasoningTokens&&u.reasoning&&(h+=e.reasoningTokens/1e6*u.reasoning),l||void 0===a?(n=Math.max(h,a??0),e.isEstimated=!i||l,void 0!==a&&a>n&&(n=a),void 0!==a&&Math.abs(n-a)>1e-4&&s.v.debug("[CostCalculator] Adjusted provisional cost",{provider:t,model:r,reportedCost:a,computedCost:h,finalCost:n})):(n=a,e.isEstimated=!1),e.isEstimated&&("openrouter"===t||t.toString().includes("openrouter"))&&s.v.warn("[CostCalculator] Using estimated cost based on normalized tokens for OpenRouter. This may be inaccurate. Consider using Generation API for native token counts."),n}static getPricingKey(e,t){return"openrouter"===e&&t.includes("/")?`openrouter/${t}`:`${e}/${t}`}static findBestPricingMatch(e,t){let r=`${e}/`;for(let[e,i]of Object.entries(o))if(e.startsWith(r)){let s=e.substring(r.length);if(t.includes(s)||s.includes(t))return i}return"ollama"===e||"lmstudio"===e?{input:0,output:0}:n}static getDynamicPricing(e,t){if(!this.isKnownProvider(e))return null;try{return i.s.getModelPricing(e,t)}catch(r){return s.v.debug("[CostCalculator] Failed to read dynamic pricing",{provider:e,model:t,error:r}),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?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}static getPricing(e,t){return o[this.getPricingKey(e,t)]||this.findBestPricingMatch(e,t)}static estimateCost(e,t,r,i=!0){let s=Math.ceil(1.3*e.split(/\s+/).length),o=this.getPricing(t,r);return s/1e6*(i?o.input:o.output)}static updateWithGenerationApiCost(e,t){let r={...e};return void 0!==t.total_cost&&(r.cost=t.total_cost,r.isEstimated=!1,e.cost&&Math.abs(e.cost-t.total_cost)>1e-4&&s.v.debug(`[CostCalculator] Cost corrected: ${e.cost?.toFixed(4)} -> ${t.total_cost.toFixed(4)} (${((t.total_cost-e.cost)/e.cost*100).toFixed(1)}% difference)`)),void 0!==t.native_tokens_total&&(r.nativeTokens={total:t.native_tokens_total,prompt:t.native_tokens_prompt,completion:t.native_tokens_completion}),r}}},94348:()=>{},94593:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>n});var i=r(60687),s=r(10218),o=r(52581);let n=({...e})=>{let{theme:t}=(0,s.D)();return(0,i.jsx)(o.l$,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}},94742:(e,t,r)=>{"use strict";r.d(t,{Y:()=>n});var i=r(28602),s=r(96241);class o{async initDB(){if(!this.isInitialized)return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onerror=()=>{s.v.error("Failed to open checkpoint database"),t(r.error)},r.onsuccess=()=>{this.db=r.result,this.isInitialized=!0,this.loadCheckpointsFromDB().then(()=>e())},r.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 r=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).getAll();r.onsuccess=()=>{let t=r.result;for(let e of(this.checkpoints.clear(),t)){let t={...e,kind:e.kind||"auto",baseRevisionId:e.baseRevisionId??null,files:new Map(e.files),directories:new Set(e.directories)};this.checkpoints.set(t.id,t)}e()},r.onerror=()=>{s.v.error("Failed to load checkpoints from DB"),t(r.error)}})}async saveCheckpointToDB(e){if(await this.initDB(),!this.db)return;let t={...e,files:Array.from(e.files.entries()),directories:Array.from(e.directories),kind:e.kind,baseRevisionId:e.baseRevisionId??null};return new Promise((e,r)=>{let i=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(t);i.onsuccess=()=>e(),i.onerror=()=>{s.v.error("Failed to save checkpoint to DB"),r(i.error)}})}async deleteCheckpointFromDB(e){if(await this.initDB(),this.db)return new Promise((t,r)=>{let i=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(e);i.onsuccess=()=>t(),i.onerror=()=>{s.v.error("Failed to delete checkpoint from DB"),r(i.error)}})}async createCheckpoint(e,t,r={}){await this.initDB(),await i.OP.init();let o=await i.OP.listDirectory(e,"/"),n=new Map,a=new Set;for(let t of o){let r=t.path.split("/").filter(Boolean);for(let e=1;e<=r.length-1;e++){let t="/"+r.slice(0,e).join("/");a.add(t)}if("string"==typeof t.content)n.set(t.path,t.content);else try{let r=await i.OP.readFile(e,t.path);"string"==typeof r.content&&n.set(t.path,r.content)}catch(e){s.v.error(`Failed to read file for checkpoint: ${t.path}`,e)}}let l={id:`cp_${Date.now()}`,timestamp:new Date().toISOString(),description:t,files:n,directories:a,projectId:e,kind:r.kind||"auto",baseRevisionId:r.baseRevisionId??null};if(r.replaceId&&(this.checkpoints.delete(r.replaceId),await this.deleteCheckpointFromDB(r.replaceId)),"manual"===l.kind){let t=Array.from(this.checkpoints.values()).find(t=>t.projectId===e&&"manual"===t.kind);t&&t.id!==r.replaceId&&(this.checkpoints.delete(t.id),await this.deleteCheckpointFromDB(t.id))}this.checkpoints.set(l.id,l),this.currentCheckpoint=l.id,await this.saveCheckpointToDB(l);let c=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(c.length>10)for(let e of c.slice(0,c.length-10))this.checkpoints.delete(e.id),await this.deleteCheckpointFromDB(e.id),s.v.debug(`[Checkpoint] Deleted old checkpoint: ${e.id}`);return l}async restoreCheckpoint(e){if("string"!=typeof e)return s.v.error("[Checkpoint] Invalid checkpoint ID type:",typeof e,e),!1;if(!e.startsWith("cp_")||e.length<6)return s.v.error("[Checkpoint] Invalid checkpoint ID format:",e),!1;await this.initDB();let t=this.checkpoints.get(e);if(!t&&(s.v.debug(`[Checkpoint] Checkpoint ${e} not in memory, checking database...`),await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e)))){s.v.error(`[Checkpoint] Checkpoint not found in database: ${e}`);let t=Array.from(this.checkpoints.keys());return s.v.debug("[Checkpoint] Available checkpoints:",t),!1}await i.OP.init();try{let r=await i.OP.listDirectory(t.projectId,"/"),s=new Set;for(let e of r){let t=e.path.split("/").filter(Boolean);for(let e=1;e<=t.length-1;e++){let r="/"+t.slice(0,e).join("/");s.add(r)}}for(let e of r)t.files.has(e.path)||await i.OP.deleteFile(t.projectId,e.path);for(let e of Array.from(s).filter(e=>!t.directories||!t.directories.has(e)).sort((e,t)=>t.length-e.length))try{await i.OP.deleteDirectory(t.projectId,e)}catch{}if(t.directories){for(let e of Array.from(t.directories).sort((e,t)=>e.length-t.length))if(!s.has(e))try{await i.OP.createDirectory(t.projectId,e)}catch{}}for(let[e,s]of t.files)r.some(t=>t.path===e)?await i.OP.updateFile(t.projectId,e,s):await i.OP.createFile(t.projectId,e,s);return this.currentCheckpoint=e,!0}catch(e){return s.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[r,i]of this.checkpoints)i.projectId===e&&(this.checkpoints.delete(r),t.push(r));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 n=new o},96241:(e,t,r)=>{"use strict";r.d(t,{cn:()=>o,v:()=>c});var i=r(49384),s=r(82348);function o(...e){return(0,s.QP)((0,i.$)(e))}let n={debug:10,info:20,warn:30,error:40,silent:50},a="undefined"!=typeof process&&process.env.NEXT_PUBLIC_LOG_LEVEL||"warn";function l(e){return n[a]<=n[e]}let c={debug:(...e)=>{l("debug")&&console.debug(...e)},info:(...e)=>{l("info")&&console.info(...e)},warn:(...e)=>{l("warn")&&console.warn(...e)},error:(...e)=>{l("error")&&console.error(...e)}}},96271:(e,t,r)=>{"use strict";r.d(t,{g:()=>n});var i=r(60687),s=r(10218),o=r(43210);function n({width:e=64,height:t=64,className:r}){let{resolvedTheme:n}=(0,s.D)(),[a,l]=(0,o.useState)(!1);return a?(0,i.jsx)("div",{style:{width:e,height:t},className:`${r} ${"light"===n?"[&_path]:fill-black":"[&_path]:fill-white"}`,dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="-115.152 89.394 256 256" width="100%" height="100%"><defs><clipPath id="_clipPath_dMGkP5G1pEE0GihLKCMn4c6sRumBcOzI"><rect x="-115.152" y="89.394" width="256" height="256"/></clipPath></defs><g clip-path="url(#_clipPath_dMGkP5G1pEE0GihLKCMn4c6sRumBcOzI)"><path d=" M -83.752 90.55 C -95.139 93.664 -105.701 102.02 -110.645 111.895 C -115.439 121.619 -115.289 116.985 -115.065 220.977 C -114.84 315.322 -114.84 315.322 -113.267 319.576 C -108.398 332.414 -98.06 341.377 -84.726 344.188 C -77.385 345.783 90.937 345.783 98.128 344.264 C 105.47 342.669 112.286 338.871 117.38 333.629 C 126.519 324.21 128.242 318.133 128.242 295.42 C 128.242 280 128.242 280 133.336 269.973 C 138.655 259.414 140.003 255.16 140.752 246.197 C 141.276 239.74 139.628 232.371 136.632 228.042 C 134.609 225.079 134.609 225.079 134.385 176.008 C 134.31 144.939 133.935 125.265 133.411 122.378 C 130.789 107.717 117.905 94.348 102.698 90.55 C 98.353 89.487 88.315 89.335 9.061 89.411 C -66.448 89.411 -80.232 89.638 -83.752 90.55 Z M 99.252 103.388 C 101.649 103.995 104.945 105.287 106.668 106.122 C 111.462 108.629 117.38 115.162 119.403 120.251 C 121.126 124.657 121.126 124.657 121.35 167.5 C 121.425 191.124 121.35 210.874 121.201 211.406 C 120.901 212.09 118.878 211.026 114.609 208.14 C 106.368 202.518 97.679 198.416 89.139 195.986 C 79.476 193.251 62.696 192.643 52.059 194.542 C 35.129 197.581 19.848 204.341 -0.228 217.711 C -14.761 227.358 -21.278 230.928 -27.345 232.523 C -39.855 235.866 -49.968 231.536 -52.74 221.737 C -53.863 217.787 -53.714 213.229 -52.365 211.026 C -51.991 210.418 -48.994 209.735 -44.5 209.355 C -31.84 208.14 -25.847 205.557 -18.955 198.416 C -13.562 192.795 -10.64 186.946 -9.592 179.958 C -8.843 174.488 -9.367 173.045 -11.539 174.26 C -16.334 176.767 -21.053 177.679 -32.065 178.21 C -44.2 178.742 -45.773 179.122 -49.519 182.692 C -51.691 184.667 -51.691 184.667 -52.89 182.844 C -53.639 181.781 -55.886 179.198 -57.983 177.071 C -61.279 173.653 -63.002 172.665 -70.793 169.551 C -81.131 165.525 -84.951 163.018 -87.123 158.992 C -87.947 157.397 -88.921 156.257 -89.371 156.409 C -92.367 157.397 -92.667 176.767 -89.82 184.439 C -87.423 190.82 -82.329 197.277 -76.636 201.075 C -73.34 203.354 -71.917 204.797 -72.216 205.557 C -76.186 216.571 -77.085 238.145 -74.089 249.235 C -67.347 274.531 -47.871 293.749 -21.278 301.573 C -13.862 303.776 -5.921 304.763 -1.876 304.004 C -0.378 303.7 2.244 302.181 4.192 300.434 C 6.963 297.927 7.637 297.623 7.637 298.762 C 7.637 302.864 -0.528 311.676 -10.865 318.816 C -16.708 322.842 -17.457 324.134 -16.708 328.616 C -16.184 331.654 -16.184 331.654 -48.02 331.654 C -83.303 331.654 -83.977 331.578 -90.944 326.717 C -93.116 325.197 -96.112 322.159 -97.536 320.032 C -102.779 312.284 -102.555 316.917 -102.33 216.116 C -102.105 125.417 -102.105 125.417 -100.307 121.011 C -96.712 111.895 -88.172 104.527 -79.483 103.008 C -77.46 102.704 -37.458 102.4 9.51 102.324 C 83.146 102.248 95.581 102.4 99.252 103.388 Z M 85.469 223.56 C 88.091 229.029 91.162 232.599 96.406 236.094 C 101.275 239.284 101.275 239.284 96.93 242.019 C 92.136 245.133 88.54 249.007 86.368 253.261 C 84.645 256.679 83.146 258.123 82.098 257.363 C 81.723 257.059 80.749 255.16 79.925 253.033 C 78.277 248.627 73.034 243.006 68.464 240.955 C 66.741 240.12 65.318 239.284 65.318 239.056 C 65.318 238.828 67.191 237.613 69.438 236.397 C 74.457 233.739 78.352 229.485 80.824 224.092 C 81.798 221.813 82.922 219.99 83.221 219.99 C 83.521 219.99 84.495 221.585 85.469 223.56 Z M 128.767 248.627 C 130.04 252.046 125.171 265.871 119.927 273.695 C 116.406 278.936 108.466 287.14 102.698 291.47 C 95.207 297.091 83.521 302.409 72.21 305.371 C 61.048 308.334 60.823 308.41 60.823 310.461 C 60.823 312.588 63.67 313.423 70.487 313.423 C 84.345 313.423 99.776 307.878 110.938 298.99 C 112.961 297.319 114.833 296.256 115.058 296.484 C 115.283 296.787 115.507 299.75 115.507 303.168 C 115.507 314.335 112.361 322.007 105.619 327.02 C 99.402 331.654 99.477 331.654 50.036 331.654 C 20.672 331.654 5.39 331.35 6.139 330.894 C 6.739 330.515 8.986 329.603 11.008 328.919 C 16.327 327.096 26.814 321.779 32.433 317.981 C 35.054 316.158 40.448 311.448 44.343 307.422 C 50.036 301.649 52.059 298.914 54.082 294.585 C 56.554 289.343 56.928 288.887 61.572 286.381 C 64.269 284.937 70.337 280.683 75.056 276.961 C 93.559 262.225 99.702 257.819 107.642 253.793 C 118.129 248.4 127.793 246.045 128.767 248.627 Z " fill="currentColor"/></g></svg>'}}):(0,i.jsx)("div",{style:{width:e,height:t}})}},97815:(e,t,r)=>{"use strict";r.d(t,{t:()=>E});var i=r(60687),s=r(43210),o=r(4950),n=r(57462),a=r(10158),l=r(76741),c=r(96241);class d{constructor(e){this.provider=e?.provider||o.s.getSelectedProvider()||"openrouter",this.providerConfig=(0,a.sO)(this.provider),this.apiKey=e?.apiKey||o.s.getProviderApiKey(this.provider)||"",this.model=e?.model||o.s.getProviderModel(this.provider)||this.getDefaultModel(),this.temperature=e?.temperature||.7,this.maxTokens=e?.maxTokens||4096}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,r){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error(`${this.providerConfig.name} API key is required. Please set it in settings.`);let i=[{role:"system",content:(0,n.m)(r?.fileTree)},{role:"user",content:e}];try{if("anthropic"===this.provider)return this.generateWithToolsAnthropic(i,t);if("gemini"===this.provider)return this.generateWithToolsGemini(i,t);return this.generateWithToolsOpenAI(i,t)}catch(e){throw e}}async generate(e,t){if(this.providerConfig.apiKeyRequired&&!this.apiKey)throw Error(`${this.providerConfig.name} API key is required. Please set it in settings.`);let r=[{role:"system",content:(0,n.m)(t?.fileTree)},{role:"user",content:e}];return"anthropic"===this.provider?this.generateAnthropic(r):"gemini"===this.provider?this.generateGemini(r):this.generateOpenAI(r)}async generateWithToolsOpenAI(e,t){let r=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`),"openrouter"===this.provider&&(i["HTTP-Referer"]="http://localhost:3000",i["X-Title"]="DeepStudio"),this.providerConfig.customHeaders&&Object.assign(i,this.providerConfig.customHeaders);let s=await fetch(`${r}/chat/completions`,{method:"POST",headers:i,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(!s.ok){let e=await s.text();throw Error(`${this.providerConfig.name} API error: ${e}`)}return this.parseStreamResponse(s)}async generateOpenAI(e){let t=this.providerConfig.baseUrl||"https://openrouter.ai/api/v1",r={"Content-Type":"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),"openrouter"===this.provider&&(r["HTTP-Referer"]="http://localhost:3000",r["X-Title"]="DeepStudio");let i=await fetch(`${t}/chat/completions`,{method:"POST",headers:r,body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature,max_tokens:this.maxTokens,stream:!1})});if(!i.ok){let e=await i.text();throw Error(`${this.providerConfig.name} API error: ${e}`)}let s=await i.json();return s.choices[0]?.message?.content||""}async generateWithToolsAnthropic(e,t){let r=e.find(e=>"system"===e.role)?.content||"",i=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),s=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01","anthropic-beta":"tools-2024-04-04"},body:JSON.stringify({model:this.model,messages:i,system:r,tools:t.map(e=>({name:e.name,description:e.description,input_schema:e.parameters})),temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})});if(!s.ok){let e=await s.text();throw Error(`Anthropic API error: ${e}`)}return this.parseAnthropicStream(s)}async generateAnthropic(e){let t=e.find(e=>"system"===e.role)?.content||"",r=e.filter(e=>"system"!==e.role).map(e=>({role:"user"===e.role?"user":"assistant",content:e.content})),i=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:t,temperature:this.temperature,max_tokens:this.maxTokens})});if(!i.ok){let e=await i.text();throw Error(`Anthropic API error: ${e}`)}let s=await i.json();return s.content[0]?.text||""}async generateWithToolsGemini(e,t){throw Error("Gemini tool calling not yet implemented. Please use OpenRouter or another provider.")}async generateGemini(e){let t=e.map(e=>({role:"system"===e.role?"user":e.role,parts:[{text:e.content}]})),r=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:t,generationConfig:{temperature:this.temperature,maxOutputTokens:this.maxTokens}})});if(!r.ok){let e=await r.text();throw Error(`Gemini API error: ${e}`)}let i=await r.json();return i.candidates[0]?.content?.parts[0]?.text||""}async *parseStreamResponse(e){let t=e.body?.getReader();if(!t)throw Error("Response body is not readable");let r=new TextDecoder,i="",s=null,o=null,n=null;if("openrouter"===this.provider){let t=e.headers;n=l.I.extractGenerationId(t);let r=l.I.extractCostFromHeaders(t);if(r?.cost!==void 0||r?.usage){let e=r.usage?.prompt_tokens??0,t=r.usage?.completion_tokens??0,i=r.usage?.total_tokens??e+t,s=r.cost??r.usage?.total_cost,a="number"==typeof s&&Number.isFinite(s)&&s>1e-6;o={promptTokens:e,completionTokens:t,totalTokens:i,cost:a?s:void 0,model:this.model,provider:this.provider,generationId:n||void 0,isEstimated:!a}}if(!o){let e=t.get("x-openrouter-usage");if(e)try{let t=JSON.parse(e),r=t.total_cost,i="number"==typeof r&&Number.isFinite(r)&&r>1e-6;o={promptTokens:t.prompt_tokens||0,completionTokens:t.completion_tokens||0,totalTokens:t.total_tokens||(t.prompt_tokens||0)+(t.completion_tokens||0),cost:i?r:void 0,model:this.model,provider:this.provider,generationId:n||void 0,isEstimated:!i}}catch(e){c.v.error("Error parsing OpenRouter usage header:",e)}}}for(;;){let{done:e,value:a}=await t.read();if(e)break;let l=(i+=r.decode(a,{stream:!0})).split("\n");for(let e of(i=l.pop()||"",l))if(e.startsWith("data: ")){let t=e.slice(6);if("[DONE]"===t){o&&o.totalTokens&&(yield{type:"usage",usage:o}),yield{type:"done"};return}try{let e=JSON.parse(t),r=e.choices?.[0]?.delta;if(r?.content&&(yield{type:"content",content:r.content}),r?.tool_calls)for(let e of r.tool_calls)e.id&&(s&&(yield{type:"tool_call",toolCall:s}),s={id:e.id,type:"function",function:{name:e.function?.name||"",arguments:""}}),e.function?.arguments&&s&&(s.argumentsBuffer=(s.argumentsBuffer||"")+e.function.arguments,s.function&&(s.function.arguments=s.argumentsBuffer));e.usage&&(o={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:n||void 0}),e.x_groq?.usage&&(o={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(s)try{let e=s.argumentsBuffer;e&&s.function&&(s.function.arguments=e),yield{type:"tool_call",toolCall:s}}catch(e){c.v.error("Error parsing tool call parameters:",e)}o&&o.totalTokens&&(yield{type:"usage",usage:o}),yield{type:"done"}}async *parseAnthropicStream(e){let t=e.body?.getReader();if(!t)throw Error("Response body is not readable");let r=new TextDecoder,i="",s=null;for(;;){let{done:e,value:o}=await t.read();if(e)break;let n=(i+=r.decode(o,{stream:!0})).split("\n");for(let e of(i=n.pop()||"",n))if(e.startsWith("data: ")){let t=e.slice(6);try{let e=JSON.parse(t);if("content_block_delta"===e.type&&e.delta?.text_delta?.text)yield{type:"content",content:e.delta.text_delta.text};else if("content_block_start"===e.type&&e.content_block?.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&&e.message?.usage)s={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)s&&(s.completionTokens=e.usage.output_tokens||s.completionTokens,s.totalTokens=(s.promptTokens||0)+(s.completionTokens||0));else if("message_stop"===e.type){s&&s.totalTokens&&(yield{type:"usage",usage:s}),yield{type:"done"};return}}catch(e){c.v.error("Error parsing Anthropic stream:",e)}}}s&&s.totalTokens&&(yield{type:"usage",usage:s}),yield{type:"done"}}static async validateApiKey(e,t){if(!e)return!1;try{let r=await fetch("/api/validate-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,provider:t})});if(!r.ok)return!1;let{valid:i}=await r.json();return i}catch{return!1}}static async getAvailableModels(e,t){let r=t||o.s.getSelectedProvider()||"openrouter",i=(0,a.sO)(r),s=e||o.s.getProviderApiKey(r);if(!i.supportsModelDiscovery&&i.models)return i.models.map(e=>e.id);try{let e=await fetch("/api/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s,provider:r})});if(!e.ok)return i.models?.map(e=>e.id)||[];let{models:t}=await e.json();return t||[]}catch{return i.models?.map(e=>e.id)||[]}}}var p=r(24934),u=r(68988),h=r(39390),m=r(12597),g=r(13861),f=r(13964),y=r(11860),v=r(25334),x=r(52581),b=r(59821),w=r(33135),C=r(78200),k=r(56085),j=r(45583),S=r(9593),_=r(24413),T=r(10510),P=r(41862),I=r(78272),N=r(99270),$=r(34429),A=r(24573);function F({provider:e,value:t,onChange:r,className:n,hideModelDetails:l}){let m=e||o.s.getSelectedProvider(),g=(0,a.sO)(m),[f,v]=(0,s.useState)([]),[F,O]=(0,s.useState)(!0),[E,D]=(0,s.useState)(""),[R,M]=(0,s.useState)(!1),[U,B]=(0,s.useState)(""),[L,q]=(0,s.useState)(!1),W=e=>e.name;(0,s.useCallback)(async()=>{try{O(!0);let e=o.s.getProviderApiKey(m);if(g.apiKeyRequired&&!e){q(!0),g.models?v(g.models):v([]);return}q(!1);let t=o.s.getCachedModels(m);if(t){let e=t.models;v(e),"openrouter"===m&&(0,A.V)("openrouter",e);return}let r=[];if("openrouter"===m){let e=await (0,$.QF)();(0,A.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{}}return null==e?"":String(e)};r=e.map(e=>{let r=e.pricing?.prompt?Number(e.pricing.prompt):void 0,i=e.pricing?.completion?Number(e.pricing.completion):void 0,s=e.pricing?.internal_reasoning?Number(e.pricing.internal_reasoning):void 0,o=e=>{if(void 0!==e&&Number.isFinite(e))return 1e6*e},n=o(r),a=o(i),l=o(s);return{id:e.id,name:e.name,description:t(e.description),contextLength:e.context_length,maxTokens:e.top_provider?.max_completion_tokens,supportsFunctions:e.supported_parameters?.includes("tools"),supportsVision:e.architecture?.input_modalities?.includes("image"),pricing:void 0!==n&&void 0!==a?{input:n,output:a,reasoning:l}:void 0}})}else r=g.supportsModelDiscovery?(await d.getAvailableModels(e||void 0,m)).map(e=>({id:e,name:e.split("/").pop()||e,contextLength:32e3,supportsFunctions:!0})):g.models?g.models:[];v(r),g.isLocal&&0===r.length&&x.oR.warning(`No models found in ${g.name}. Please load some models in the application.`,{duration:5e3}),r.length>0&&(o.s.setCachedModels(m,r),"openrouter"===m&&(0,A.V)("openrouter",r))}catch(e){c.v.error("Failed to load models:",e),g.isLocal&&x.oR.error(`${g.name} server not running. Please start the server and load some models.`,{duration:5e3}),g.models&&v(g.models)}finally{O(!1)}},[m,g]);let z=e=>{D(e),o.s.setProviderModel(m,e),r?.(e),M(!1),B("")},H=e=>{let t=e.id.toLowerCase();return t.includes("deepseek")?(0,i.jsx)(C.A,{className:"h-3 w-3"}):t.includes("claude")?(0,i.jsx)(k.A,{className:"h-3 w-3"}):t.includes("gpt")?(0,i.jsx)(j.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,i.jsx)(S.A,{className:"h-3 w-3"}):t.includes("llama")?(0,i.jsx)(_.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,i.jsx)(T.A,{className:"h-3 w-3"}):null},K=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"},J=(0,s.useMemo)(()=>{if(!U.trim())return f;let e=U.toLowerCase();return f.filter(t=>{let r=t.id.toLowerCase(),i=W(t).toLowerCase(),s=t.id.split("/")[0].toLowerCase();return r.includes(e)||i.includes(e)||s.includes(e)})},[f,U]),G=f.find(e=>e.id===E);return F?(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{children:"AI Model"}),(0,i.jsxs)("div",{className:"flex items-center gap-2 h-10 px-3 border rounded-md bg-muted",children:[(0,i.jsx)(P.A,{className:"h-4 w-4 animate-spin"}),(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):L?(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{children:"AI Model"}),(0,i.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,i.jsxs)("span",{className:"text-sm text-orange-600 dark:text-orange-400",children:["API key required for ",g.name]})}),(0,i.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Set your API key in settings to load available models"})]}):(0,i.jsxs)("div",{className:n,children:[(0,i.jsx)(h.J,{htmlFor:"model-select",children:"AI Model"}),(0,i.jsxs)(w.AM,{open:R,onOpenChange:M,children:[(0,i.jsx)(w.Wv,{asChild:!0,children:(0,i.jsxs)(p.$,{variant:"outline",role:"combobox","aria-expanded":R,className:"w-full justify-between font-normal",children:[G?(0,i.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[H(G),(0,i.jsx)("span",{className:"truncate",children:W(G)})]}):(0,i.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,i.jsx)(I.A,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),(0,i.jsxs)(w.hl,{className:"w-[32rem] p-0",align:"start",side:"bottom",sideOffset:5,avoidCollisions:!1,children:[(0,i.jsxs)("div",{className:"flex items-center border-b px-3",children:[(0,i.jsx)(N.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,i.jsx)(u.p,{placeholder:"Search models...",value:U,onChange:e=>B(e.target.value),className:"h-10 border-0 focus:ring-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),U&&(0,i.jsx)(p.$,{variant:"ghost",size:"sm",onClick:()=>B(""),className:"h-5 w-5 p-0",children:(0,i.jsx)(y.A,{className:"h-3 w-3"})})]}),(0,i.jsx)("div",{className:"max-h-[400px] min-h-[300px] overflow-y-auto",children:0===J.length?(0,i.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):J.map(e=>(0,i.jsx)("button",{onClick:()=>z(e.id),className:(0,c.cn)("w-full text-left px-3 py-3 hover:bg-accent hover:text-accent-foreground transition-colors",E===e.id&&"bg-accent"),children:(0,i.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[H(e),(0,i.jsx)("span",{className:"font-medium",children:W(e)}),"openrouter"===m&&(0,i.jsx)(b.E,{variant:"secondary",className:`text-xs ${K(e.id)}`,children:e.id.split("/")[0]})]}),(0,i.jsxs)("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[(0,i.jsxs)("span",{children:["Context: ",Math.round(e.contextLength/1e3),"K"]}),e.pricing&&(0===e.pricing.input&&0===e.pricing.output?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsx)("span",{children:"Free"})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsxs)("span",{children:[(0,$.WK)(e.pricing.input),"/K | ",(0,$.WK)(e.pricing.output),"/K"]})]})),!e.pricing&&"openrouter"!==m&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{children:"•"}),(0,i.jsx)("span",{children:"Pricing varies"})]})]})]})},e.id))})]})]}),!l&&G&&(0,i.jsxs)("div",{className:"mt-1 text-xs text-muted-foreground max-h-[150px] overflow-y-auto pr-2",children:[(0,i.jsx)("div",{className:"font-medium mb-1",children:G.pricing?0===G.pricing.input&&0===G.pricing.output?"Free":`Input: ${(0,$.WK)(G.pricing.input)}/K • Output: ${(0,$.WK)(G.pricing.output)}/K`:"Pricing varies by provider"}),G.description&&(0,i.jsx)("div",{children:G.description})]})]})}var O=r(63974);function E({onClose:e,onModelChange:t}){let[r,n]=(0,s.useState)({}),[l,c]=(0,s.useState)(()=>o.s.getSelectedProvider()),[b,w]=(0,s.useState)(!1),[C,k]=(0,s.useState)(!1),[j,S]=(0,s.useState)(null),[_,T]=(0,s.useState)(""),P=e=>{T(e),o.s.setProviderApiKey(l,e),S(null),o.s.clearModelCache(l),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:l,hasKey:!!e}}))},I=async()=>{if(!_)return void x.oR.error("Please enter an API key");k(!0);try{let e=await d.validateApiKey(_,l);S(e),e?x.oR.success("API key is valid!"):x.oR.error("Invalid API key")}catch{S(!1),x.oR.error("Failed to validate API key")}finally{k(!1)}},N=(0,a.sO)(l);return(0,i.jsxs)("div",{className:"space-y-6",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("h3",{className:"font-medium text-sm",children:"Model Settings"}),(0,i.jsx)("p",{className:"text-muted-foreground text-xs mt-1",children:"Configure your AI model and API connection"})]}),(0,i.jsxs)("div",{className:"space-y-4",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)(h.J,{htmlFor:"provider",children:"AI Provider"}),(0,i.jsxs)(O.l6,{value:l,onValueChange:e=>{c(e),o.s.setSelectedProvider(e),T(o.s.getProviderApiKey(e)||""),S(null)},children:[(0,i.jsx)(O.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,i.jsx)(O.yv,{placeholder:"Select a provider",children:l&&(0,i.jsxs)("div",{className:"flex flex-col text-left",children:[(0,i.jsx)("span",{className:"font-medium",children:N.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:N.description})]})})}),(0,i.jsx)(O.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,i.jsx)(O.eb,{value:e.id,children:(0,i.jsxs)("div",{className:"flex flex-col",children:[(0,i.jsx)("span",{className:"font-medium",children:e.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:e.description})]})},e.id))})]})]}),(N.apiKeyRequired||N.isLocal)&&(0,i.jsxs)("div",{children:[(0,i.jsxs)(h.J,{htmlFor:"api-key",children:[N.name," API Key",!N.apiKeyRequired&&(0,i.jsx)("span",{className:"text-muted-foreground text-xs ml-1",children:"(optional)"})]}),(0,i.jsxs)("div",{className:"flex gap-2 mt-2",children:[(0,i.jsxs)("div",{className:"relative flex-1",children:[(0,i.jsx)(u.p,{id:"api-key",type:b?"text":"password",value:_,onChange:e=>P(e.target.value),placeholder:N.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,i.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>w(!b),children:b?(0,i.jsx)(m.A,{className:"h-4 w-4"}):(0,i.jsx)(g.A,{className:"h-4 w-4"})})]}),(0,i.jsx)(p.$,{onClick:I,disabled:C||!_,size:"sm",children:C?"Validating...":"Validate"}),null!==j&&(0,i.jsx)("div",{className:"flex items-center",children:j?(0,i.jsx)(f.A,{className:"h-5 w-5 text-green-500"}):(0,i.jsx)(y.A,{className:"h-5 w-5 text-red-500"})})]}),N.apiKeyHelpUrl&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,i.jsxs)("a",{href:N.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[N.name," ",(0,i.jsx)(v.A,{className:"h-3 w-3"})]})]}),N.isLocal&&!N.apiKeyRequired&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",N.name,". Only needed if you've configured authentication on your local server."]})]}),!N.apiKeyRequired&&N.isLocal&&(0,i.jsxs)("div",{className:"text-sm text-muted-foreground p-3 border rounded-md bg-muted/50",children:[(0,i.jsx)("p",{className:"font-medium mb-1",children:"Local Provider"}),(0,i.jsxs)("p",{children:["Make sure ",N.name," is running on your machine."]}),(0,i.jsxs)("p",{children:["Default endpoint: ",(0,i.jsx)("code",{className:"text-xs",children:N.baseUrl})]}),"lmstudio"===l&&(0,i.jsxs)("div",{className:"mt-2 text-xs",children:[(0,i.jsx)("p",{className:"font-medium",children:"For tool use support:"}),(0,i.jsx)("p",{children:"• Load a model like qwen/qwen3-4b-thinking-2507"}),(0,i.jsx)("p",{children:"• Start the local server in LM Studio"}),(0,i.jsx)("p",{children:"• Models will be automatically discovered"})]})]}),(0,i.jsx)(F,{provider:l,onChange:e=>{t?.(e)},className:"space-y-2"})]}),e&&(0,i.jsx)("div",{className:"flex justify-end pt-4 border-t",children:(0,i.jsx)(p.$,{onClick:e,size:"sm",children:"Done"})})]})}},99197:(e,t,r)=>{"use strict";r.d(t,{ThemeProvider:()=>o});var i=r(60687);r(43210);var s=r(10218);function o({children:e,attribute:t="class",defaultTheme:r="dark",enableSystem:o=!0,storageKey:n="deepstudio-theme",...a}){return(0,i.jsx)(s.N,{attribute:t,defaultTheme:r,enableSystem:o,storageKey:n,disableTransitionOnChange:!0,...a,children:e})}},99526:(e,t,r)=>{"use strict";r.d(t,{r:()=>T});var i=r(28602),s=r(94742),o=r(32623),n=r(4950),a=r(10158),l=r(86884),c=r(76741);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., "<div className=\\"contact\\">", "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=r(57462);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,r){if("/"===r||!r)return;let i=r.split("/").filter(Boolean),s="";for(let r=0;r<i.length;r++){s="/"+i.slice(0,r+1).join("/");try{await e.createDirectory(t,s)}catch{}}}async function y(e,t,r,i={}){if(!t||"string"!=typeof t)return{stdout:"",stderr:"Invalid project ID provided",exitCode:2};if(!r||0===r.length)return{stdout:"",stderr:"No command provided",exitCode:2};let s=r.filter(e=>null!=e&&""!==e);if(0===s.length)return{stdout:"",stderr:"No valid command arguments provided",exitCode:2};let[o,...n]=s;try{switch(o){case"ls":{let r=new Set,i=[];for(let e of n)e&&e.startsWith("-")?r.add(e):e&&i.push(e);let s=r.has("-R")||r.has("-r"),o=g(i[0])||"/";if(s){let r=await e.getAllFilesAndDirectories(t),i="/"===o?"/":o.endsWith("/")?o:o+"/",s=r.filter(e=>e.path===o||e.path.startsWith(i)).map(e=>e.path).sort().join("\n");return{stdout:m(s),stderr:"",exitCode:0}}{let r=(await e.listDirectory(t,o)).map(e=>e.path).sort().join("\n");return{stdout:m(r),stderr:"",exitCode:0}}}case"cat":{let r=g(n[0]);if(!r)return{stdout:"",stderr:"cat: missing file path",exitCode:2};if(r.startsWith("/-"))return{stdout:"",stderr:"cat: invalid path (looks like an option). Use: cat /path/to/file",exitCode:2};let i=await e.readFile(t,r);if("string"!=typeof i.content)return{stdout:"",stderr:`cat: ${r}: binary or non-text file`,exitCode:1};return{stdout:m(i.content),stderr:"",exitCode:0}}case"grep":{let r,i={n:!1,i:!1,r:!1,F:!1},s=[];for(let e of n)if(e.startsWith("-"))for(let t of e.slice(1))t in i&&(i[t]=!0);else s.push(e);let o=s[0],a=g(s[1])||"/";if(!o)return{stdout:"",stderr:"grep: missing pattern",exitCode:2};if(i.F){let e=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=new RegExp(e,i.i?"i":"")}else r=new RegExp(o,i.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 s=0;s<t.length;s++){let o=t[s];r.test(o)&&d.push(`${e.path}${i.n?":"+(s+1):""}:${o}`)}}let p=d.join("\n");if(0===d.length){let e="/"===a?"workspace root":a;return{stdout:"",stderr:`grep: pattern "${o}" not found in ${e}`,exitCode:1}}return{stdout:m(p),stderr:"",exitCode:0}}case"find":{let r,i,s;for(let e=0;e<n.length;e++){let t=n[e];if(t){if("-name"===t){i=n[e+1],e++;continue}if("-maxdepth"===t||"-type"===t){e++;continue}t.startsWith("-")||r||(r=t)}}let o=g(r)||"/",a=await e.getAllFilesAndDirectories(t),l="/"===o?"/":o.endsWith("/")?o:o+"/",c=i?(s=i,RegExp("^"+s.replace(/[.+^${}()|\[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$")):null,d=a.filter(e=>e.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 r=n.includes("-p"),i=n[r?n.indexOf("-p")+1:0],s=g(i);if(!s)return{stdout:"",stderr:"mkdir: missing path",exitCode:2};return r?await f(e,t,s):await e.createDirectory(t,s),{stdout:"",stderr:"",exitCode:0}}case"rm":{let r=!1,i=!1,s=!1,o=[];for(let e of n)e&&e.startsWith("-")?((e.includes("r")||e.includes("R"))&&(r=!0),e.includes("f")&&(i=!0),e.includes("v")&&(s=!0)):e&&o.push(e);if(0===o.length)return{stdout:"",stderr:"rm: missing operand",exitCode:2};let a=!1,l=[];for(let n of o){let o=g(n);if(!o){i||(a=!0);continue}try{await e.deleteFile(t,o),s&&l.push(`removed '${o}'`)}catch{if(r)try{await e.deleteDirectory(t,o),s&&l.push(`removed directory '${o}'`)}catch{!i&&(a=!0,s&&l.push(`rm: cannot remove '${o}': No such file or directory`))}else!i&&(a=!0,s&&l.push(`rm: cannot remove '${o}': Is a directory (use -r to remove directories)`))}}let c=s?l.join("\n"):"",d=a&&!s?"rm: some paths could not be removed":"";return{stdout:m(c),stderr:d,exitCode:+!!a}}case"rmdir":{let r=[],i=!1;for(let e of n)"-v"===e||"--verbose"===e?i=!0:e&&!e.startsWith("-")&&r.push(e);if(0===r.length)return{stdout:"",stderr:"rmdir: missing operand",exitCode:2};let s=!1,o=[];for(let n of r){let r=g(n);if(!r){s=!0;continue}try{(await e.listDirectory(t,r)).length>0?(s=!0,i&&o.push(`rmdir: failed to remove '${r}': Directory not empty`)):(await e.deleteDirectory(t,r),i&&o.push(`rmdir: removing directory, '${r}'`))}catch{s=!0,i&&o.push(`rmdir: failed to remove '${r}': No such file or directory`)}}let a=i?o.join("\n"):"",l=s&&!i?"rmdir: failed to remove one or more directories":"";return{stdout:m(a),stderr:l,exitCode:+!!s}}case"mv":{let[r,i]=n,s=g(r),o=g(i);if(!s||!o)return{stdout:"",stderr:"mv: missing operands",exitCode:2};try{return await e.renameFile(t,s,o),{stdout:"",stderr:"",exitCode:0}}catch{return await e.renameDirectory(t,s,o),{stdout:"",stderr:"",exitCode:0}}}case"cp":{let r=n.includes("-r"),[i,s]=n.filter(e=>"-r"!==e);if(i=g(i),s=g(s),!i||!s)return{stdout:"",stderr:"cp: missing operands",exitCode:2};try{let r=await e.readFile(t,i),o=(r.content,r.content);try{await e.createFile(t,s,o)}catch{await e.updateFile(t,s,o)}return{stdout:"",stderr:"",exitCode:0}}catch{if(!r)return{stdout:"",stderr:"cp: -r required for directories",exitCode:1};let o=await e.getAllFilesAndDirectories(t),n=i.endsWith("/")?i:i+"/";for(let r of o)if((!("type"in r)||"directory"!==r.type)&&(r.path===i||r.path.startsWith(n))){let o=r.path.slice(i.length),n=(s.endsWith("/")?s.slice(0,-1):s)+o;await f(e,t,n.split("/").slice(0,-1).join("/"));let a=(r.content,r.content);try{await e.createFile(t,n,a)}catch{await e.updateFile(t,n,a)}}return{stdout:"",stderr:"",exitCode:0}}}case"echo":if(n.includes(">")||n.includes(">>"))return{stdout:"",stderr:"echo: redirection is not supported in this environment. Use json_patch to edit files.",exitCode:2};return{stdout:m(n.join(" ")),stderr:"echo prints to stdout only. To modify files, use json_patch.",exitCode:1};case"nl":{let r="";for(let e of n)"-ba"===e||e.startsWith("-")||(r=e);let i=g(r);if(!i)return{stdout:"",stderr:"nl: missing file path",exitCode:2};try{let r=await e.readFile(t,i);if("string"!=typeof r.content)return{stdout:"",stderr:`nl: ${i}: binary file`,exitCode:1};let s=r.content.split(/\r?\n/).map((e,t)=>{let r=String(t+1).padStart(6," ");return`${r} ${e}`});return{stdout:m(s.join("\n")),stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`nl: ${i}: ${e?.message||"file not found"}`,exitCode:1}}}case"sed":{if(0===n.length)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" <file> or sed -n "1,80p" <file>',exitCode:2};let r=!1,i=0,s=1;"-n"===n[0]&&(r=!0,i=1,s=2);let o=n[i],a=n[s];if(!o||!a)return{stdout:"",stderr:'sed: usage: sed "s/pat/repl/g" <file> or sed -n "1,80p" <file>',exitCode:2};let l=o.match(/^(\d+),(\d+)p$/);if(l){let r=parseInt(l[1]),i=parseInt(l[2]),s=await e.readFile(t,a);if("string"!=typeof s.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let o=s.content.split("\n").slice(r-1,i);return{stdout:m(o.join("\n")),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let c=o.match(/^(\d+)p$/);if(c){let r=parseInt(c[1]),i=await e.readFile(t,a);if("string"!=typeof i.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let s=i.content.split("\n");if(r<=0||r>s.length)return{stdout:"",stderr:`sed: line ${r} out of range`,exitCode:1};return{stdout:m(s[r-1]),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:0}}let d=o.match(/^s\/(.*)\/(.*)\/(g?)$/);if(d){let[,i,s]=d,o=await e.readFile(t,a);if("string"!=typeof o.content)return{stdout:"",stderr:"sed: binary file",exitCode:1};let n=RegExp(i,"g"),l=o.content.replace(n,s);return{stdout:m(l),stderr:"sed output is preview-only. To save, use json_patch.",exitCode:+!r}}return{stdout:"",stderr:'sed: supported formats: "s/pat/repl/g", "1,80p", "80p". Use json_patch for file changes.',exitCode:2}}default:{let e="bash"===o?` Don't use "bash" as a command - call the shell tool directly with your command. Wrong: {"cmd": ["bash", "-c", "ls -la"]} Right: {"cmd": ["ls", "-la"]}