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" @@ -474,11 +474,40 @@ DEBUGGING FAILED PATCHES: • ✅ PREFER: Targeted commands that show only what you need • If you already have the snippet from earlier in the session, reuse it instead of re-running commands. -Evaluation Tool: -Use the 'evaluation' tool periodically to assess task progress: -- Check if the original goal has been achieved -- Provide reasoning about what was accomplished -- Determine if you should continue working or stop +Evaluation Tool - Progress Tracking: +Use the 'evaluation' tool periodically to stay goal-oriented and track progress: + +WHEN TO EVALUATE: +• Every 5-10 steps during complex tasks (3+ distinct operations) +• After completing a major component or feature +• After fixing errors or resolving blockers +• When uncertain about next steps +• DO NOT evaluate on simple tasks (1-2 operations like "change button color") + +EVALUATION GUIDELINES: +• Be specific in progress_summary: list actual components/features completed +• Be concrete in remaining_work: actionable items, not vague goals +• List blockers only if they're currently preventing progress +• Review original user request to ensure nothing is forgotten +• Use evaluation to keep yourself on track during long tasks + +Examples: + +Simple task (no evaluation needed): +User: "Change button color to blue" +→ Just do it, no evaluation needed + +Complex task (use evaluation periodically): +User: "Build a landing page with hero, features, pricing, testimonials" +After completing hero + features sections: +{ + "goal_achieved": false, + "progress_summary": "Completed hero section with CTA, features grid with 6 items and icons", + "remaining_work": ["Add pricing section with 3 tiers", "Create testimonials carousel", "Build footer with social links"], + "blockers": [], + "reasoning": "Good progress. Hero and features are complete and styled. Next I'll add the pricing section.", + "should_continue": true +} Important Notes: - All paths are relative to the project root (/) @@ -488,6 +517,55 @@ Important Notes: - When json_patch fails, read the file again and verify exact string matches - Use evaluation tool to self-assess progress on complex tasks +FILE CREATION GUIDELINES - COMPLETE BUT NOT CLUTTERED: + +GOAL: Create deployable, complete projects without unnecessary clutter + +CREATE THESE FILES (when appropriate): +✅ README.md - For complex projects (3+ features/pages) to explain: + • What was built + • How to run/deploy + • Key features + • DO NOT create README for simple single-file changes + +✅ package.json, tsconfig.json, etc. - When needed for functionality: + • Creating a React/Next.js app → needs package.json + • Using TypeScript → needs tsconfig.json + • ONLY create if project actually uses these tools + +✅ Component files - When building features: + • User asks for "dashboard" → create Dashboard.tsx, widgets, etc. + • Structure should match request scope + +DON'T CREATE THESE (unless explicitly requested): +❌ .gitignore - Users have their own preferences +❌ .prettierrc, .eslintrc - Users configure their own tooling +❌ .env files - Sensitive, user creates manually +❌ LICENSE - User chooses license separately +❌ Temporary/scratch files - Keep VFS clean + +EDITING vs. CREATING: +• ALWAYS prefer editing existing files over creating new ones +• Before creating, check if file already exists: ls /path/to/file +• If exists, use json_patch to modify instead + +Examples: + +Simple request (minimal files): +User: "Add a button component" +→ Create: Button.tsx +→ DON'T create: README.md, package.json (likely already exist) + +Complex request (complete project): +User: "Build a landing page with hero, features, pricing" +→ Create: index.html, styles.css, script.js, README.md (deployment instructions) +→ DON'T create: .gitignore, .prettierrc + +Explicit config request: +User: "Set up a Next.js project with TypeScript" +→ Create: package.json, tsconfig.json, next.config.js, app/page.tsx, README.md +→ DO create config files since they're required for functionality + JSON_PATCH VERIFICATION CHECKLIST: □ Reviewed the relevant snippet (via \`rg -C 5\`, \`head -n 50\`, or \`tail -n 50\` - avoid cat!) and identified exact strings to replace □ Verified oldStr appears exactly once in the file @@ -565,7 +643,7 @@ Available Handlebars Features: - Utility helpers: json, formatDate `;return e&&(t+=` -${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{arrayBufferToBase64(e){let t=new Uint8Array(e),r="";for(let e=0;e{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 if(t.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(t.content);n.set(t.path,{data:e,encoding:"base64"})}else try{let r=await i.OP.readFile(e,t.path);if("string"==typeof r.content)n.set(t.path,r.content);else if(r.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(r.content);n.set(t.path,{data:e,encoding:"base64"})}}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);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&&(await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e))))return s.v.error(`[Checkpoint] Checkpoint not found in database: ${e}`),Array.from(this.checkpoints.keys()),!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){let o;o="object"==typeof s&&"base64"===s.encoding?this.base64ToArrayBuffer(s.data):s,r.some(t=>t.path===e)?await i.OP.updateFile(t.projectId,e,o):await i.OP.createFile(t.projectId,e,o)}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:''}}):(0,i.jsx)("div",{style:{width:e,height:t}})}},97815:(e,t,r)=>{"use strict";r.d(t,{t:()=>F});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),b=r(52581),x=r(59821),w=r(33135),C=r(78200),k=r(56085),S=r(45583),j=r(9593),T=r(24413),_=r(10510),I=r(41862),P=r(78272),A=r(99270),N=r(34429),O=r(24573);function $({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)([]),[$,E]=(0,s.useState)(!0),[F,D]=(0,s.useState)(""),[R,M]=(0,s.useState)(!1),[U,L]=(0,s.useState)(""),[B,W]=(0,s.useState)(!1),H=e=>e.name;(0,s.useCallback)(async()=>{try{E(!0);let e=o.s.getProviderApiKey(m);if(g.apiKeyRequired&&!e){W(!0),g.models?v(g.models):v([]);return}W(!1);let t=o.s.getCachedModels(m);if(t){let e=t.models;v(e),"openrouter"===m&&(0,O.V)("openrouter",e);return}let r=[];if("openrouter"===m){let e=await (0,N.QF)();(0,O.b)(e);let t=e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=["description","name","summary"].map(t=>e[t]).find(e=>"string"==typeof e);if(t)return t;try{return JSON.stringify(e)}catch{}}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&&b.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,O.V)("openrouter",r))}catch(e){c.v.error("Failed to load models:",e),g.isLocal&&b.oR.error(`${g.name} server not running. Please start the server and load some models.`,{duration:5e3}),g.models&&v(g.models)}finally{E(!1)}},[m,g]);let q=e=>{D(e),o.s.setProviderModel(m,e),r?.(e),M(!1),L("")},z=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)(S.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,i.jsx)(j.A,{className:"h-3 w-3"}):t.includes("llama")?(0,i.jsx)(T.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,i.jsx)(_.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"},G=(0,s.useMemo)(()=>{if(!U.trim())return f;let e=U.toLowerCase();return f.filter(t=>{let r=t.id.toLowerCase(),i=H(t).toLowerCase(),s=t.id.split("/")[0].toLowerCase();return r.includes(e)||i.includes(e)||s.includes(e)})},[f,U]),J=f.find(e=>e.id===F);return $?(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)(I.A,{className:"h-4 w-4 animate-spin"}),(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):B?(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:[J?(0,i.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[z(J),(0,i.jsx)("span",{className:"truncate",children:H(J)})]}):(0,i.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,i.jsx)(P.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)(A.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,i.jsx)(u.p,{placeholder:"Search models...",value:U,onChange:e=>L(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:()=>L(""),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===G.length?(0,i.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):G.map(e=>(0,i.jsx)("button",{onClick:()=>q(e.id),className:(0,c.cn)("w-full text-left px-3 py-3 hover:bg-accent hover:text-accent-foreground transition-colors",F===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:[z(e),(0,i.jsx)("span",{className:"font-medium",children:H(e)}),"openrouter"===m&&(0,i.jsx)(x.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,N.WK)(e.pricing.input),"/K | ",(0,N.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&&J&&(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:J.pricing?0===J.pricing.input&&0===J.pricing.output?"Free":`Input: ${(0,N.WK)(J.pricing.input)}/K • Output: ${(0,N.WK)(J.pricing.output)}/K`:"Pricing varies by provider"}),J.description&&(0,i.jsx)("div",{children:J.description})]})]})}var E=r(63974);function F({onClose:e,onModelChange:t}){let[r,n]=(0,s.useState)({}),[l,c]=(0,s.useState)(()=>o.s.getSelectedProvider()),[x,w]=(0,s.useState)(!1),[C,k]=(0,s.useState)(!1),[S,j]=(0,s.useState)(null),[T,_]=(0,s.useState)(""),I=e=>{_(e),o.s.setProviderApiKey(l,e),j(null),o.s.clearModelCache(l),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:l,hasKey:!!e}}))},P=async()=>{if(!T)return void b.oR.error("Please enter an API key");k(!0);try{let e=await d.validateApiKey(T,l);j(e),e?b.oR.success("API key is valid!"):b.oR.error("Invalid API key")}catch{j(!1),b.oR.error("Failed to validate API key")}finally{k(!1)}},A=(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)(E.l6,{value:l,onValueChange:e=>{c(e),o.s.setSelectedProvider(e),_(o.s.getProviderApiKey(e)||""),j(null)},children:[(0,i.jsx)(E.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,i.jsx)(E.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:A.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:A.description})]})})}),(0,i.jsx)(E.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,i.jsx)(E.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))})]})]}),(A.apiKeyRequired||A.isLocal)&&(0,i.jsxs)("div",{children:[(0,i.jsxs)(h.J,{htmlFor:"api-key",children:[A.name," API Key",!A.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:x?"text":"password",value:T,onChange:e=>I(e.target.value),placeholder:A.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,i.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>w(!x),children:x?(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:P,disabled:C||!T,size:"sm",children:C?"Validating...":"Validate"}),null!==S&&(0,i.jsx)("div",{className:"flex items-center",children:S?(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"})})]}),A.apiKeyHelpUrl&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,i.jsxs)("a",{href:A.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[A.name," ",(0,i.jsx)(v.A,{className:"h-3 w-3"})]})]}),A.isLocal&&!A.apiKeyRequired&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",A.name,". Only needed if you've configured authentication on your local server."]})]}),!A.apiKeyRequired&&A.isLocal&&(0,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 ",A.name," is running on your machine."]}),(0,i.jsxs)("p",{children:["Default endpoint: ",(0,i.jsx)("code",{className:"text-xs",children:A.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)($,{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:()=>_});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., "
", "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;rnull!=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"tree":{let r=1/0,i="/";for(let e=0;ee.path===s||e.path.startsWith(a)).map(e=>({path:e.path,isDir:"type"in e&&"directory"===e.type})),c=[s];for(let e of l.filter(e=>e.path!==s).map(e=>e.path).sort()){let t=e.slice(a.length).split("/").filter(Boolean).length;if(t>r)continue;let i=" ".repeat(t-1),s=e.split("/").pop()||e;c.push(`${i}├── ${s}`)}return{stdout:m(c.join("\n")),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"head":{let r=10,i="";for(let e=0;ee-t);for(let s of(d.length>0&&d.push(""),p)){let o=r.n?`${s+1}:`:"";i.has(s),d.push(`${e.path}:${o}${t[s]}`)}}if(0===d.length){let e="/"===o?"workspace root":o;return{stdout:"",stderr:`rg: pattern "${s}" not found in ${e}`,exitCode:1}}return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"find":{let r,i,s;for(let e=0;ee.path===o||e.path.startsWith(l)).map(e=>e.path).filter(e=>!c||c.test(e.split("/").pop()||e)).sort();return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"mkdir":{let 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"touch":{let r=g(n[0]);if(!r)return{stdout:"",stderr:"touch: missing file path",exitCode:2};try{return await e.readFile(t,r),{stdout:"",stderr:"",exitCode:0}}catch{try{return await e.createFile(t,r,""),{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`touch: ${r}: ${e?.message||"cannot create file"}`,exitCode:1}}}}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"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":{let r=n.indexOf(">");if(-1===r)return{stdout:m(n.join(" ")),stderr:"",exitCode:0};let i=n.slice(0,r).join(" "),s=n[r+1],o=g(s);if(!o)return{stdout:"",stderr:"echo: missing file path after >",exitCode:2};try{let r=o.split("/").slice(0,-1).join("/")||"/";"/"!==r&&await f(e,t,r);try{await e.createFile(t,o,i)}catch{await e.updateFile(t,o,i)}return{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`echo: ${o}: ${e?.message||"cannot write file"}`,exitCode:1}}}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{arrayBufferToBase64(e){let t=new Uint8Array(e),r="";for(let e=0;e{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 if(t.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(t.content);n.set(t.path,{data:e,encoding:"base64"})}else try{let r=await i.OP.readFile(e,t.path);if("string"==typeof r.content)n.set(t.path,r.content);else if(r.content instanceof ArrayBuffer){let e=this.arrayBufferToBase64(r.content);n.set(t.path,{data:e,encoding:"base64"})}}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);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&&(await this.loadCheckpointsFromDB(),!(t=this.checkpoints.get(e))))return s.v.error(`[Checkpoint] Checkpoint not found in database: ${e}`),Array.from(this.checkpoints.keys()),!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){let o;o="object"==typeof s&&"base64"===s.encoding?this.base64ToArrayBuffer(s.data):s,r.some(t=>t.path===e)?await i.OP.updateFile(t.projectId,e,o):await i.OP.createFile(t.projectId,e,o)}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:''}}):(0,i.jsx)("div",{style:{width:e,height:t}})}},97815:(e,t,r)=>{"use strict";r.d(t,{t:()=>R});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),b=r(52581),x=r(59821),w=r(33135),C=r(78200),k=r(56085),S=r(45583),j=r(9593),T=r(24413),_=r(10510),I=r(41862),P=r(78272),A=r(99270),N=r(34429),E=r(24573);function O({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)([]),[O,$]=(0,s.useState)(!0),[R,F]=(0,s.useState)(""),[D,M]=(0,s.useState)(!1),[U,L]=(0,s.useState)(""),[B,W]=(0,s.useState)(!1),q=e=>e.name;(0,s.useCallback)(async()=>{try{$(!0);let e=o.s.getProviderApiKey(m);if(g.apiKeyRequired&&!e){W(!0),g.models?v(g.models):v([]);return}W(!1);let t=o.s.getCachedModels(m);if(t){let e=t.models;v(e),"openrouter"===m&&(0,E.V)("openrouter",e);return}let r=[];if("openrouter"===m){let e=await (0,N.QF)();(0,E.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&&b.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,E.V)("openrouter",r))}catch(e){c.v.error("Failed to load models:",e),g.isLocal&&b.oR.error(`${g.name} server not running. Please start the server and load some models.`,{duration:5e3}),g.models&&v(g.models)}finally{$(!1)}},[m,g]);let H=e=>{F(e),o.s.setProviderModel(m,e),r?.(e),M(!1),L("")},z=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)(S.A,{className:"h-3 w-3"}):t.includes("gemini")?(0,i.jsx)(j.A,{className:"h-3 w-3"}):t.includes("llama")?(0,i.jsx)(T.A,{className:"h-3 w-3"}):t.includes("qwen")?(0,i.jsx)(_.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"},G=(0,s.useMemo)(()=>{if(!U.trim())return f;let e=U.toLowerCase();return f.filter(t=>{let r=t.id.toLowerCase(),i=q(t).toLowerCase(),s=t.id.split("/")[0].toLowerCase();return r.includes(e)||i.includes(e)||s.includes(e)})},[f,U]),J=f.find(e=>e.id===R);return O?(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)(I.A,{className:"h-4 w-4 animate-spin"}),(0,i.jsx)("span",{className:"text-sm text-muted-foreground",children:"Loading models..."})]})]}):B?(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:D,onOpenChange:M,children:[(0,i.jsx)(w.Wv,{asChild:!0,children:(0,i.jsxs)(p.$,{variant:"outline",role:"combobox","aria-expanded":D,className:"w-full justify-between font-normal",children:[J?(0,i.jsxs)("div",{className:"flex items-center gap-2 truncate",children:[z(J),(0,i.jsx)("span",{className:"truncate",children:q(J)})]}):(0,i.jsx)("span",{className:"text-muted-foreground",children:"Select a model..."}),(0,i.jsx)(P.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)(A.A,{className:"h-4 w-4 shrink-0 opacity-50"}),(0,i.jsx)(u.p,{placeholder:"Search models...",value:U,onChange:e=>L(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:()=>L(""),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===G.length?(0,i.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No models found"}):G.map(e=>(0,i.jsx)("button",{onClick:()=>H(e.id),className:(0,c.cn)("w-full text-left px-3 py-3 hover:bg-accent hover:text-accent-foreground transition-colors",R===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:[z(e),(0,i.jsx)("span",{className:"font-medium",children:q(e)}),"openrouter"===m&&(0,i.jsx)(x.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,N.WK)(e.pricing.input),"/K | ",(0,N.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&&J&&(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:J.pricing?0===J.pricing.input&&0===J.pricing.output?"Free":`Input: ${(0,N.WK)(J.pricing.input)}/K • Output: ${(0,N.WK)(J.pricing.output)}/K`:"Pricing varies by provider"}),J.description&&(0,i.jsx)("div",{children:J.description})]})]})}var $=r(63974);function R({onClose:e,onModelChange:t}){let[r,n]=(0,s.useState)({}),[l,c]=(0,s.useState)(()=>o.s.getSelectedProvider()),[x,w]=(0,s.useState)(!1),[C,k]=(0,s.useState)(!1),[S,j]=(0,s.useState)(null),[T,_]=(0,s.useState)(""),I=e=>{_(e),o.s.setProviderApiKey(l,e),j(null),o.s.clearModelCache(l),window.dispatchEvent(new CustomEvent("apiKeyUpdated",{detail:{provider:l,hasKey:!!e}}))},P=async()=>{if(!T)return void b.oR.error("Please enter an API key");k(!0);try{let e=await d.validateApiKey(T,l);j(e),e?b.oR.success("API key is valid!"):b.oR.error("Invalid API key")}catch{j(!1),b.oR.error("Failed to validate API key")}finally{k(!1)}},A=(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)($.l6,{value:l,onValueChange:e=>{c(e),o.s.setSelectedProvider(e),_(o.s.getProviderApiKey(e)||""),j(null)},children:[(0,i.jsx)($.bq,{id:"provider",className:"w-full mt-2 !h-fit",children:(0,i.jsx)($.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:A.name}),(0,i.jsx)("span",{className:"text-xs text-muted-foreground",children:A.description})]})})}),(0,i.jsx)($.gC,{className:"max-h-[400px]",children:(0,a.OM)().map(e=>(0,i.jsx)($.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))})]})]}),(A.apiKeyRequired||A.isLocal)&&(0,i.jsxs)("div",{children:[(0,i.jsxs)(h.J,{htmlFor:"api-key",children:[A.name," API Key",!A.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:x?"text":"password",value:T,onChange:e=>I(e.target.value),placeholder:A.apiKeyPlaceholder||"API Key",className:"pr-10","data-tour-id":"provider-key-input"}),(0,i.jsx)(p.$,{size:"icon",variant:"ghost",className:"absolute right-1 top-1 h-7 w-7",onClick:()=>w(!x),children:x?(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:P,disabled:C||!T,size:"sm",children:C?"Validating...":"Validate"}),null!==S&&(0,i.jsx)("div",{className:"flex items-center",children:S?(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"})})]}),A.apiKeyHelpUrl&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["Get your API key from"," ",(0,i.jsxs)("a",{href:A.apiKeyHelpUrl,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:[A.name," ",(0,i.jsx)(v.A,{className:"h-3 w-3"})]})]}),A.isLocal&&!A.apiKeyRequired&&(0,i.jsxs)("p",{className:"text-sm text-muted-foreground mt-2",children:["API key is optional for ",A.name,". Only needed if you've configured authentication on your local server."]})]}),!A.apiKeyRequired&&A.isLocal&&(0,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 ",A.name," is running on your machine."]}),(0,i.jsxs)("p",{children:["Default endpoint: ",(0,i.jsx)("code",{className:"text-xs",children:A.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)(O,{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:()=>_});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., "
", "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:"Periodically assess task progress, track what remains, identify blockers. Use every 5-10 steps on complex tasks to stay goal-oriented.",parameters:{type:"object",properties:{goal_achieved:{type:"boolean",description:"Whether the original task/goal has been fully achieved"},progress_summary:{type:"string",description:'Brief summary of work completed so far (e.g., "Created 3 components: Header, Hero, Features")'},remaining_work:{type:"array",items:{type:"string"},description:'List of specific tasks still needed to complete the goal (e.g., ["Add pricing section", "Create footer", "Fix navigation bug"]). Empty array if goal_achieved is true.'},blockers:{type:"array",items:{type:"string"},description:'Current blockers preventing progress (e.g., ["Navigation component has TypeScript errors"]). Empty array if no blockers.'},reasoning:{type:"string",description:"Detailed explanation of current status and next steps"},should_continue:{type:"boolean",description:"Whether to continue working (false if complete or permanently blocked)"}},required:["goal_achieved","progress_summary","remaining_work","reasoning","should_continue"]}};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;rnull!=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"tree":{let r=1/0,i="/";for(let e=0;ee.path===s||e.path.startsWith(a)).map(e=>({path:e.path,isDir:"type"in e&&"directory"===e.type})),c=[s];for(let e of l.filter(e=>e.path!==s).map(e=>e.path).sort()){let t=e.slice(a.length).split("/").filter(Boolean).length;if(t>r)continue;let i=" ".repeat(t-1),s=e.split("/").pop()||e;c.push(`${i}├── ${s}`)}return{stdout:m(c.join("\n")),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"head":{let r=10,i="";for(let e=0;ee-t);for(let s of(d.length>0&&d.push(""),p)){let o=r.n?`${s+1}:`:"";i.has(s),d.push(`${e.path}:${o}${t[s]}`)}}if(0===d.length){let e="/"===o?"workspace root":o;return{stdout:"",stderr:`rg: pattern "${s}" not found in ${e}`,exitCode:1}}return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"find":{let r,i,s;for(let e=0;ee.path===o||e.path.startsWith(l)).map(e=>e.path).filter(e=>!c||c.test(e.split("/").pop()||e)).sort();return{stdout:m(d.join("\n")),stderr:"",exitCode:0}}case"mkdir":{let 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"touch":{let r=g(n[0]);if(!r)return{stdout:"",stderr:"touch: missing file path",exitCode:2};try{return await e.readFile(t,r),{stdout:"",stderr:"",exitCode:0}}catch{try{return await e.createFile(t,r,""),{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`touch: ${r}: ${e?.message||"cannot create file"}`,exitCode:1}}}}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"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":{let r=n.indexOf(">");if(-1===r)return{stdout:m(n.join(" ")),stderr:"",exitCode:0};let i=n.slice(0,r).join(" "),s=n[r+1],o=g(s);if(!o)return{stdout:"",stderr:"echo: missing file path after >",exitCode:2};try{let r=o.split("/").slice(0,-1).join("/")||"/";"/"!==r&&await f(e,t,r);try{await e.createFile(t,o,i)}catch{await e.updateFile(t,o,i)}return{stdout:"",stderr:"",exitCode:0}}catch(e){return{stdout:"",stderr:`echo: ${o}: ${e?.message||"cannot write file"}`,exitCode:1}}}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"]} @@ -593,13 +671,22 @@ Correct shell tool usage: {"cmd": ["echo", "Hello World"]} - Output text {"cmd": ["echo", "content", ">", "/file.txt"]} - Write text to file -Note: Use json_patch tool for complex file editing. Use rg (ripgrep) instead of grep for better context.`,exitCode:127}}}}catch(e){return{stdout:"",stderr:e?.message||String(e),exitCode:1}}}let v={execute:async(e,t)=>{let r=new i.r8;await r.init();let s=await y(r,e,t);return{success:0===s.exitCode,stdout:s.stdout,stderr:s.stderr}}};var b=r(96241);async function x(e,t,r,i){let s=[];if(!r||!r.startsWith("/"))return{applied:!1,summary:"Invalid file path",warnings:["File path must be absolute and start with /"]};if(!i||0===i.length)return{applied:!1,summary:"No operations provided",warnings:["No patch operations to apply"]};let o=r.replace(/\/+/g,"/");try{let r="",n=!0;try{let i=await e.readFile(t,o);if("string"!=typeof i.content)return{applied:!1,summary:"Cannot patch binary file",warnings:[`File ${o} is binary and cannot be patched`]};r=i.content}catch(e){if(e.message?.includes("not found"))n=!1,r="",b.v.debug(`[StringPatch] File ${o} does not exist, will create it`);else throw e}let a=r,l=0;for(let e=0;e1){s.push(`Operation ${e+1}: oldStr appears ${o} times in file, must be unique. String: "${w(r,100)}"`);continue}a=a.replace(r,i??""),l++}else if("rewrite"===t.type)a=t.content??"",l++;else if("replace_entity"===t.type){let{selector:r,replacement:i,entity_type:o}=t;if(!r){s.push(`Operation ${e+1}: selector is required for replace_entity operations`);continue}if(void 0===i){s.push(`Operation ${e+1}: replacement is required for replace_entity operations`);continue}let n=function(e,t,r,i){try{let s=function(e,t){let r=[],i=new Set,s=e=>{e&&(i.has(e)||(i.add(e),r.push(e)))};for(let i of(s(t),s(t.replace(/^\s+/,"")),s(t.replace(/\s+$/,"")),s(t.replace(/^\s+/,"").replace(/\s+$/,"")),r)){if(!i)continue;let t=e.indexOf(i);if(-1!==t)return{index:t,normalizedSelector:i}}return null}(e,t);if(!s)return{success:!1,error:`Selector not found: "${w(t,100)}"`};let{index:o,normalizedSelector:n}=s,a=function(e,t,r,i){var s,o,n,a,l,c,d,p,u;switch(i||((s=r).startsWith("<")&&s.includes(">")?"html_element":s.includes("React.FC")||s.includes(": FC<")?"react_component":s.includes("function ")||s.includes(" = (")||s.includes(" => {")?"function":s.startsWith(".")||s.startsWith("#")?"css_rule":s.includes("interface ")||s.includes("type ")?s.includes("interface ")?"interface":"type":"bracket_matched")){case"html_element":return function(e,t,r){if(t<0||t>=e.length)return null;let i=r.match(/<(\w+)(?:\s|>)/);if(!i)return null;let s=i[1],o=Math.max(0,t);if(r.includes("/>"))return{start:o,end:e.indexOf("/>",t)+2};let n=0,a=t;for(;a]*)?>`)),r=e.substring(a).match(RegExp(``)),i=-1,l=-1;if(t){let r=e.substring(a).indexOf(t[0]);i=-1!==r?a+r:-1}if(r){let t=e.substring(a).indexOf(r[0]);l=-1!==t?a+t:-1}if(-1===l)break;if(-1!==i&&i0&&(n?await e.updateFile(t,o,a):await e.createFile(t,o,a));let c=l>0?`Applied ${l}/${i.length} operations to ${o}`:`No operations applied to ${o}`;return{applied:l>0,summary:c,warnings:s.length>0?s:void 0}}catch(t){let e=t.message||String(t);return b.v.error(`[StringPatch] Failed to patch ${o}:`,e),{applied:!1,summary:`Failed to patch ${o}`,warnings:[`Error: ${e}`]}}}function w(e,t){return e.length<=t?e:t<=3?e.substring(0,Math.max(0,t)):e.substring(0,t-3)+"..."}function C(e,t){if(t<0||t>=e.length)return null;let r=e.indexOf("{",t);if(-1===r)return null;let i=Math.max(0,t),s=0,o=r;for(;onew Promise(t=>setTimeout(t,e));class _{constructor(e,t,r){this.totalCost=0,this.totalUsage={promptTokens:0,completionTokens:0,totalTokens:0,cost:0},this.conversation=[],this.stepsCompleted=0,this.taskComplete=!1,this.maxIterations=100,this.stopped=!1,this.accumulatedToolCalls=[],this.evaluationResult=null,this.malformedToolCallRetries=0,this.noToolCallRetries=0,this.lastIterationHadWrite=!1,this.lastCheckpointId=null,this.recentCatReads=new Map,this.pricingEnsured=new Set,this.projectId=e,this.onProgress=r,this.conversation=t||[]}stop(){this.stopped=!0,b.v.info("[Orchestrator] Generation stopped by user")}async fetchWithRetry(e,t,r=3,i){for(let s=0;s<=r;s++){let o=await fetch(e,t);if(429!==o.status||s===r)return o;let n=o.headers.get("Retry-After"),a=n?1e3*parseInt(n):1e3*Math.pow(2,s);i?.(s+1,a),await T(a)}throw Error("Unexpected end of retry loop")}getProviderConfig(){let e=n.s.getSelectedProvider(),t=(0,a.sO)(e),r=n.s.getProviderApiKey(e),i=n.s.getProviderModel(e)||void 0;if(t.apiKeyRequired&&!r)throw Error(`API key not configured for provider: ${e}`);return{provider:e,providerConfig:t,apiKey:r||"",model:i||"default-model"}}handleRetry(e,t){let r=`Rate limited. Retry attempt ${e} in ${t/1e3}s...`;b.v.warn(r),k.oR.info(r,{duration:t>2e3?t-500:2e3,description:"Waiting for rate limit to reset"})}async streamLLMResponse(e,t,r,i,s,o){await this.ensurePricing(r,s);let n={messages:e,apiKey:i,model:s,provider:r,tools:t,...t&&t.length>0&&{tool_choice:o?.toolChoice||"auto"},max_tokens:o?.maxTokens};b.v.debug(`[Orchestrator] Making API request to ${r} with ${t?.length||0} tools, model: ${s}`,{toolChoice:n.tool_choice||"none"});let a=await this.fetchWithRetry("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},3,this.handleRetry.bind(this));if(!a.ok)throw Error(`API call failed: ${a.statusText}`);return this.parseStreamingResponse(a,r,o?.suppressAssistantDelta===!0)}async parseStreamingResponse(e,t,r=!1){let s,o=e.body?.getReader();if(!o)throw Error("No response stream");let a=new TextDecoder,d="",p="",u={},h=null,m="",g="1"===process.env.NEXT_PUBLIC_DEBUG_TOOL_STREAM,f={},y={};try{for(;;){let{done:e,value:i}=await o.read();if(e)break;let n=(d+=a.decode(i,{stream:!0})).split("\n");for(let e of(d=n.pop()||"",n))if(e.startsWith("data: ")){let i=e.slice(6);if("[DONE]"===i){h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h);break}try{let e=JSON.parse(i);if("anthropic"===t){if("content_block_delta"===e.type&&e.delta?.text_delta?.text){let t=e.delta.text_delta.text;p+=t,r||this.onProgress?.("assistant_delta",{text:t,snapshot:p})}else if("content_block_start"===e.type&&e.content_block?.type==="tool_use"){let t={id:e.content_block.id,type:"function",function:{name:e.content_block.name,arguments:""}};u[e.content_block.id]=t,f[e.content_block.id]="",y[e.index]=e.content_block.id}else if("content_block_delta"===e.type&&e.delta?.type==="input_json_delta"){let t=y[e.index];t&&e.delta.partial_json&&(f[t]+=e.delta.partial_json)}else if("content_block_stop"===e.type){let t=y[e.index];if(t&&f[t])try{let e=f[t];JSON.parse(e),u[t].function.arguments=e}catch(e){b.v.error("Invalid JSON for tool parameters:",f[t],e),u[t].function.arguments="{}"}}}else{let t=e.choices?.[0]?.delta;if(t?.reasoning&&!t?.content&&!t?.tool_calls){let e=String(t.reasoning);p+=e,r||this.onProgress?.("assistant_delta",{text:e,snapshot:p})}if(t?.content){let e=String(t.content);p+=e,r||this.onProgress?.("assistant_delta",{text:e,snapshot:p})}if(t?.tool_calls)for(let e of t.tool_calls){if(void 0!==e.index){let t=`idx_${e.index}`;if(u[t]||(u[t]={id:e.id||`tool_${e.index}`,type:"function",function:{name:"",arguments:""}}),e.function?.name&&(u[t].function.name=e.function.name),e.function?.arguments){let r=e.function.arguments;u[t].function.arguments+=r}}else if(e.id)h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h),h={id:e.id,type:"function",function:{name:e.function?.name||"",arguments:""}},m=e.function?.arguments||"";else if(e.function?.arguments){let t=e.function.arguments;m+=t}e.function?.name&&h&&h.function&&(h.function.name=e.function.name)}}e.usage&&(s={promptTokens:e.usage.prompt_tokens||0,completionTokens:e.usage.completion_tokens||0,totalTokens:e.usage.total_tokens||0,cachedTokens:e.usage.cached_tokens,model:this.getProviderConfig().model,provider:t}),e.x_groq?.usage&&(s={promptTokens:e.x_groq.usage.prompt_tokens||0,completionTokens:e.x_groq.usage.completion_tokens||0,totalTokens:e.x_groq.usage.total_tokens||0,model:this.getProviderConfig().model,provider:t})}catch(e){i&&i.length>10&&!i.includes("[DONE]")&&b.v.warn("[Orchestrator] Parse error in streaming response:",e,"Data snippet:",i.substring(0,200))}}}}catch(e){b.v.error("Error reading stream:",e),Object.keys(u).length>0&&h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h)}if(p&&b.v.debug("[Orchestrator] Checking content for tool calls",{contentLength:p.length,existingToolCalls:Object.keys(u).length,hasToolKeywords:p.includes("json_patch")||p.includes("evaluation")}),p&&0===Object.keys(u).length){let e=p;if(p.includes("<|channel|>")&&p.includes("<|message|>")){let t=p.match(/to=functions\.(\w+)[\s\S]*?<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/);if(t){let r=t[1],i=t[2];try{let s=JSON.parse(i.trim());u.manual_1={id:"manual_1",type:"function",function:{name:r,arguments:JSON.stringify(s)}},e=p.replace(t[0],"").trim()}catch(e){b.v.debug("Failed to parse reasoning format JSON:",e)}}else if(t=p.match(/commentary to=functions\.(\w+)[\s\S]*?<\|constrain\|>json<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/)){let r=t[2];try{let i=JSON.parse(r.trim());u.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(i)}},e=p.replace(t[0],"").trim()}catch(e){b.v.debug("Failed to parse commentary reasoning format JSON:",e)}}}for(let t of[/\{[^{}]*"cmd"\s*:\s*\[[^\]]*\][^{}]*\}/,/\{"cmd":\s*\[.*?\]\}/,/\{.*?"cmd".*?\}/]){let r=e.match(t);if(r){b.v.debug("[Orchestrator] Found JSON match with pattern",{pattern:t.toString(),jsonPreview:r[0].substring(0,200)});try{let t=r[0],i=JSON.parse(t);if(i.cmd&&Array.isArray(i.cmd)){let r=i.cmd;"bash"===r[0]&&r[1]&&r[1].startsWith("-")&&r[2]&&(i.cmd=r=r[2].trim().split(/\s+/)),u.manual_1||(u.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(i)}}),e=e.replace(t,"").trim();break}}catch(e){b.v.debug("Failed to parse potential tool JSON:",e)}}}p=e}(p.includes("<|channel|>")||p.includes("<|message|>")||p.includes("<|end|>")||p.includes("<|start|>"))&&(p=p.replace(/<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|end\|><\|start\|>assistant<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|call\|>/g,"").replace(/\s+/g," ").trim()),Object.keys(u).length>0&&b.v.debug(`[Orchestrator] Found ${Object.keys(u).length} tool calls before validation`,Object.keys(u));let v=Object.values(u).map(e=>{if(e.function?.arguments)try{JSON.parse(e.function.arguments),b.v.debug(`[Orchestrator] Tool call ${e.id} validated successfully: ${e.function.name}`)}catch{g&&b.v.warn("Incomplete tool arguments detected, attempting to fix");let t=e.function.arguments,r=(t.match(/{/g)||[]).length,i=(t.match(/}/g)||[]).length,s=(t.match(/\[/g)||[]).length,o=(t.match(/]/g)||[]).length,n="";for(let e=0;eb.v.error("Failed to update project cost:",e)),this.onProgress?.("usage",{usage:s,totalCost:this.totalCost}),("openrouter"===t||t.includes("openrouter"))&&s.generationId&&!1!==s.isEstimated){let a=n.s.getProviderApiKey("openrouter");a&&c.I.queueGenerationForCostUpdate(s.generationId,a,this.projectId,t,e,(e,a)=>{let c=l.U.updateWithGenerationApiCost(s,{total_cost:e,native_tokens_total:a.native_tokens_total,native_tokens_prompt:a.native_tokens_prompt,native_tokens_completion:a.native_tokens_completion}),d=e-r;if(Math.abs(d)>1e-4){this.totalCost+=d;let s=c.provider||t||"unknown";n.s.adjustSessionCost(s,d),this.projectId.startsWith("test-")||i.OP.applyProjectCostDelta(this.projectId,{costDelta:d,provider:s,sessionId:o}).catch(e=>b.v.error("Failed to apply corrected project cost:",e)),this.onProgress?.("cost_correction",{originalCost:r,actualCost:e,difference:d,usage:c,totalCost:this.totalCost})}})}}return b.v.debug("[Orchestrator] Final response",{contentLength:p.length,toolCallsCount:v.length,toolCalls:v.map(e=>({id:e.id,name:e.function?.name,argsLength:e.function?.arguments?.length}))}),{content:p,toolCalls:v,usage:s}}async ensurePricing(e,t){let r=`${e}:${t}`;if(this.pricingEnsured.has(r))return;if("openrouter"!==e||n.s.getModelPricing("openrouter",t))return void this.pricingEnsured.add(r);let i=n.s.getCachedModels("openrouter");if(i?.models?.length&&((0,S.V)("openrouter",i.models),n.s.getModelPricing("openrouter",t)))return void this.pricingEnsured.add(r);try{let e=await (0,j.QF)();(0,S.b)(e),n.s.getModelPricing("openrouter",t)&&this.pricingEnsured.add(r)}catch(e){b.v.warn("[Orchestrator] Failed to fetch pricing metadata",e)}}debug(...e){b.v.debug(...e)}getAvailableTools(){return[d,p,u]}async execute(e){b.v.info("[Orchestrator] Starting execution with prompt",{promptPreview:e.substring(0,100)});try{let t;await this.recordAutoCheckpoint(`Before prompt: ${e.substring(0,60)}`);try{let e=await i.OP.listDirectory(this.projectId,"/");e.length>0&&(t=this.buildFileTree(e))}catch{}let r=(0,h.m)(t);0===this.conversation.length&&this.conversation.push({role:"system",content:r}),this.conversation.push({role:"user",content:e});for(let e=0;e({name:e.function?.name,args:e.function?.arguments?.substring(0,100)}))}),!n.toolCalls||0===n.toolCalls.length){if(b.v.debug("[Orchestrator] No tool calls in response"),n.content&&n.content.trim()){this.conversation.push({role:"assistant",content:n.content});let e=n.content.toLowerCase();if(e.includes("complete")||e.includes("done")||e.includes("finished")){this.taskComplete=!0;break}if(0===this.stepsCompleted&&(this.noToolCallRetries++,b.v.debug(`[Orchestrator] No progress made, retry ${this.noToolCallRetries}/2`),this.noToolCallRetries<=2)){this.conversation.push({role:"user",content:"Please proceed with the implementation using the shell tool."});continue}}if(this.noToolCallRetries++,b.v.debug(`[Orchestrator] No tool calls, retry ${this.noToolCallRetries}/3`),this.noToolCallRetries<=3){this.conversation.push({role:"user",content:"Continue with the task. If you need to perform more operations, use the available tools."});continue}b.v.info(`[Orchestrator] Breaking: no tool calls and max retries reached. Steps completed: ${this.stepsCompleted}`);break}n.toolCalls&&n.toolCalls.length>0&&(b.v.debug(`[Orchestrator] Sending ${n.toolCalls.length} tool calls to UI`),this.onProgress?.("toolCalls",{toolCalls:n.toolCalls}));try{t=await this.executeToolCalls(n.toolCalls,e),this.malformedToolCallRetries=0}catch(t){let e=t instanceof Error?t.message:String(t);if(b.v.error("[Orchestrator] Tool execution error:",e),e.includes("Malformed tool call")&&(this.malformedToolCallRetries++,b.v.debug(`[Orchestrator] Malformed tool call, retry ${this.malformedToolCallRetries}/2`),this.malformedToolCallRetries<=2)){this.conversation.push({role:"user",content:`Error: ${e}. Please fix the tool call format and try again.`});continue}throw t}if(n.content||n.toolCalls.length>0){let e={role:"assistant",content:n.content||""};n.toolCalls.length>0&&(e.tool_calls=n.toolCalls),this.conversation.push(e)}for(let e of t)this.conversation.push(e);this.accumulatedToolCalls.push(...n.toolCalls);let a=n.toolCalls.find(e=>e.function?.name==="evaluation");if(a)try{let e=JSON.parse(a.function.arguments);if(this.evaluationResult={goalAchieved:e.goal_achieved||!1,reasoning:e.reasoning||""},this.onProgress?.("divider",{title:"Evaluation"}),e.goal_achieved){b.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0;break}}catch(e){b.v.error("Failed to parse evaluation result:",e)}if(this.taskComplete||this.stepsCompleted>=50){b.v.info(`[Orchestrator] Breaking: taskComplete=${this.taskComplete}, steps=${this.stepsCompleted}`);break}}b.v.info(`[Orchestrator] Execution completed after ${this.maxIterations} iterations max. Steps: ${this.stepsCompleted}`);let s=this.generateSummary();return await this.recordAutoCheckpoint(`After completion: ${e.substring(0,60)}`),{success:this.stepsCompleted>0,summary:s,stepsCompleted:this.stepsCompleted,checkpointId:this.lastCheckpointId??void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}catch(r){b.v.error("Orchestrator error:",r);let t=r instanceof Error?r.message:"Unknown error";try{await this.recordAutoCheckpoint(`After failure: ${e.substring(0,60)}`)}catch(e){b.v.warn("Failed to record checkpoint after error",e)}return{success:!1,summary:`Task failed: ${t}`,stepsCompleted:this.stepsCompleted,checkpointId:this.lastCheckpointId??void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}}async executeToolCalls(e,t){let r=[];for(let t=0;t{let r=new i.r8;await r.init();let s=await y(r,e,t);return{success:0===s.exitCode,stdout:s.stdout,stderr:s.stderr}}};var b=r(96241);async function x(e,t,r,i){let s=[];if(!r||!r.startsWith("/"))return{applied:!1,summary:"Invalid file path",warnings:["File path must be absolute and start with /"]};if(!i||0===i.length)return{applied:!1,summary:"No operations provided",warnings:["No patch operations to apply"]};let o=r.replace(/\/+/g,"/");try{let r="",n=!0;try{let i=await e.readFile(t,o);if("string"!=typeof i.content)return{applied:!1,summary:"Cannot patch binary file",warnings:[`File ${o} is binary and cannot be patched`]};r=i.content}catch(e){if(e.message?.includes("not found"))n=!1,r="",b.v.debug(`[StringPatch] File ${o} does not exist, will create it`);else throw e}let a=r,l=0;for(let e=0;e1){s.push(`Operation ${e+1}: oldStr appears ${o} times in file, must be unique. String: "${w(r,100)}"`);continue}a=a.replace(r,i??""),l++}else if("rewrite"===t.type)a=t.content??"",l++;else if("replace_entity"===t.type){let{selector:r,replacement:i,entity_type:o}=t;if(!r){s.push(`Operation ${e+1}: selector is required for replace_entity operations`);continue}if(void 0===i){s.push(`Operation ${e+1}: replacement is required for replace_entity operations`);continue}let n=function(e,t,r,i){try{let s=function(e,t){let r=[],i=new Set,s=e=>{e&&(i.has(e)||(i.add(e),r.push(e)))};for(let i of(s(t),s(t.replace(/^\s+/,"")),s(t.replace(/\s+$/,"")),s(t.replace(/^\s+/,"").replace(/\s+$/,"")),r)){if(!i)continue;let t=e.indexOf(i);if(-1!==t)return{index:t,normalizedSelector:i}}return null}(e,t);if(!s)return{success:!1,error:`Selector not found: "${w(t,100)}"`};let{index:o,normalizedSelector:n}=s,a=function(e,t,r,i){var s,o,n,a,l,c,d,p,u;switch(i||((s=r).startsWith("<")&&s.includes(">")?"html_element":s.includes("React.FC")||s.includes(": FC<")?"react_component":s.includes("function ")||s.includes(" = (")||s.includes(" => {")?"function":s.startsWith(".")||s.startsWith("#")?"css_rule":s.includes("interface ")||s.includes("type ")?s.includes("interface ")?"interface":"type":"bracket_matched")){case"html_element":return function(e,t,r){if(t<0||t>=e.length)return null;let i=r.match(/<(\w+)(?:\s|>)/);if(!i)return null;let s=i[1],o=Math.max(0,t);if(r.includes("/>"))return{start:o,end:e.indexOf("/>",t)+2};let n=0,a=t;for(;a]*)?>`)),r=e.substring(a).match(RegExp(``)),i=-1,l=-1;if(t){let r=e.substring(a).indexOf(t[0]);i=-1!==r?a+r:-1}if(r){let t=e.substring(a).indexOf(r[0]);l=-1!==t?a+t:-1}if(-1===l)break;if(-1!==i&&i0&&(n?await e.updateFile(t,o,a):await e.createFile(t,o,a));let c=l>0?`Applied ${l}/${i.length} operations to ${o}`:`No operations applied to ${o}`;return{applied:l>0,summary:c,warnings:s.length>0?s:void 0}}catch(t){let e=t.message||String(t);return b.v.error(`[StringPatch] Failed to patch ${o}:`,e),{applied:!1,summary:`Failed to patch ${o}`,warnings:[`Error: ${e}`]}}}function w(e,t){return e.length<=t?e:t<=3?e.substring(0,Math.max(0,t)):e.substring(0,t-3)+"..."}function C(e,t){if(t<0||t>=e.length)return null;let r=e.indexOf("{",t);if(-1===r)return null;let i=Math.max(0,t),s=0,o=r;for(;onew Promise(t=>setTimeout(t,e));class _{constructor(e,t,r){this.totalCost=0,this.totalUsage={promptTokens:0,completionTokens:0,totalTokens:0,cost:0},this.conversation=[],this.stepsCompleted=0,this.taskComplete=!1,this.maxIterations=100,this.stopped=!1,this.accumulatedToolCalls=[],this.evaluationResult=null,this.malformedToolCallRetries=0,this.noToolCallRetries=0,this.evaluationRequested=!1,this.evaluationReceived=!1,this.lastIterationHadWrite=!1,this.lastCheckpointId=null,this.recentCatReads=new Map,this.pricingEnsured=new Set,this.projectId=e,this.onProgress=r,this.conversation=t||[]}stop(){this.stopped=!0,b.v.info("[Orchestrator] Generation stopped by user")}async fetchWithRetry(e,t,r=3,i){for(let s=0;s<=r;s++){let o=await fetch(e,t);if(429!==o.status||s===r)return o;let n=o.headers.get("Retry-After"),a=n?1e3*parseInt(n):1e3*Math.pow(2,s);i?.(s+1,a),await T(a)}throw Error("Unexpected end of retry loop")}getProviderConfig(){let e=n.s.getSelectedProvider(),t=(0,a.sO)(e),r=n.s.getProviderApiKey(e),i=n.s.getProviderModel(e)||void 0;if(t.apiKeyRequired&&!r)throw Error(`API key not configured for provider: ${e}`);return{provider:e,providerConfig:t,apiKey:r||"",model:i||"default-model"}}handleRetry(e,t){let r=`Rate limited. Retry attempt ${e} in ${t/1e3}s...`;b.v.warn(r),k.oR.info(r,{duration:t>2e3?t-500:2e3,description:"Waiting for rate limit to reset"})}async streamLLMResponse(e,t,r,i,s,o){await this.ensurePricing(r,s);let n={messages:e,apiKey:i,model:s,provider:r,tools:t,...t&&t.length>0&&{tool_choice:o?.toolChoice||"auto"},max_tokens:o?.maxTokens};b.v.debug(`[Orchestrator] Making API request to ${r} with ${t?.length||0} tools, model: ${s}`,{toolChoice:n.tool_choice||"none"});let a=await this.fetchWithRetry("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},3,this.handleRetry.bind(this));if(!a.ok)throw Error(`API call failed: ${a.statusText}`);return this.parseStreamingResponse(a,r,o?.suppressAssistantDelta===!0)}async parseStreamingResponse(e,t,r=!1){let s,o=e.body?.getReader();if(!o)throw Error("No response stream");let a=new TextDecoder,d="",p="",u={},h=null,m="",g="1"===process.env.NEXT_PUBLIC_DEBUG_TOOL_STREAM,f={},y={};try{for(;;){let{done:e,value:i}=await o.read();if(e)break;let n=(d+=a.decode(i,{stream:!0})).split("\n");for(let e of(d=n.pop()||"",n))if(e.startsWith("data: ")){let i=e.slice(6);if("[DONE]"===i){h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h);break}try{let e=JSON.parse(i);if("anthropic"===t){if("content_block_delta"===e.type&&e.delta?.text_delta?.text){let t=e.delta.text_delta.text;p+=t,r||this.onProgress?.("assistant_delta",{text:t,snapshot:p})}else if("content_block_start"===e.type&&e.content_block?.type==="tool_use"){let t={id:e.content_block.id,type:"function",function:{name:e.content_block.name,arguments:""}};u[e.content_block.id]=t,f[e.content_block.id]="",y[e.index]=e.content_block.id}else if("content_block_delta"===e.type&&e.delta?.type==="input_json_delta"){let t=y[e.index];t&&e.delta.partial_json&&(f[t]+=e.delta.partial_json)}else if("content_block_stop"===e.type){let t=y[e.index];if(t&&f[t])try{let e=f[t];JSON.parse(e),u[t].function.arguments=e}catch(e){b.v.error("Invalid JSON for tool parameters:",f[t],e),u[t].function.arguments="{}"}}}else{let t=e.choices?.[0]?.delta;if(t?.reasoning&&!t?.content&&!t?.tool_calls){let e=String(t.reasoning);p+=e,r||this.onProgress?.("assistant_delta",{text:e,snapshot:p})}if(t?.content){let e=String(t.content);p+=e,r||this.onProgress?.("assistant_delta",{text:e,snapshot:p})}if(t?.tool_calls)for(let e of t.tool_calls){if(void 0!==e.index){let t=`idx_${e.index}`;if(u[t]||(u[t]={id:e.id||`tool_${e.index}`,type:"function",function:{name:"",arguments:""}}),e.function?.name&&(u[t].function.name=e.function.name),e.function?.arguments){let r=e.function.arguments;u[t].function.arguments+=r}}else if(e.id)h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h),h={id:e.id,type:"function",function:{name:e.function?.name||"",arguments:""}},m=e.function?.arguments||"";else if(e.function?.arguments){let t=e.function.arguments;m+=t}e.function?.name&&h&&h.function&&(h.function.name=e.function.name)}}e.usage&&(s={promptTokens:e.usage.prompt_tokens||0,completionTokens:e.usage.completion_tokens||0,totalTokens:e.usage.total_tokens||0,cachedTokens:e.usage.cached_tokens,model:this.getProviderConfig().model,provider:t}),e.x_groq?.usage&&(s={promptTokens:e.x_groq.usage.prompt_tokens||0,completionTokens:e.x_groq.usage.completion_tokens||0,totalTokens:e.x_groq.usage.total_tokens||0,model:this.getProviderConfig().model,provider:t})}catch(e){i&&i.length>10&&!i.includes("[DONE]")&&b.v.warn("[Orchestrator] Parse error in streaming response:",e,"Data snippet:",i.substring(0,200))}}}}catch(e){b.v.error("Error reading stream:",e),Object.keys(u).length>0&&h&&m&&h.function&&h.id&&(h.function.arguments=m,u[h.id]=h)}if(p&&b.v.debug("[Orchestrator] Checking content for tool calls",{contentLength:p.length,existingToolCalls:Object.keys(u).length,hasToolKeywords:p.includes("json_patch")||p.includes("evaluation")}),p&&0===Object.keys(u).length){let e=p;if(p.includes("<|channel|>")&&p.includes("<|message|>")){let t=p.match(/to=functions\.(\w+)[\s\S]*?<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/);if(t){let r=t[1],i=t[2];try{let s=JSON.parse(i.trim());u.manual_1={id:"manual_1",type:"function",function:{name:r,arguments:JSON.stringify(s)}},e=p.replace(t[0],"").trim()}catch(e){b.v.debug("Failed to parse reasoning format JSON:",e)}}else if(t=p.match(/commentary to=functions\.(\w+)[\s\S]*?<\|constrain\|>json<\|message\|>([\s\S]*?)(?:<\|[^>]*\||$)/)){let r=t[2];try{let i=JSON.parse(r.trim());u.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(i)}},e=p.replace(t[0],"").trim()}catch(e){b.v.debug("Failed to parse commentary reasoning format JSON:",e)}}}for(let t of[/\{[^{}]*"cmd"\s*:\s*\[[^\]]*\][^{}]*\}/,/\{"cmd":\s*\[.*?\]\}/,/\{.*?"cmd".*?\}/]){let r=e.match(t);if(r){b.v.debug("[Orchestrator] Found JSON match with pattern",{pattern:t.toString(),jsonPreview:r[0].substring(0,200)});try{let t=r[0],i=JSON.parse(t);if(i.cmd&&Array.isArray(i.cmd)){let r=i.cmd;"bash"===r[0]&&r[1]&&r[1].startsWith("-")&&r[2]&&(i.cmd=r=r[2].trim().split(/\s+/)),u.manual_1||(u.manual_1={id:"manual_1",type:"function",function:{name:"shell",arguments:JSON.stringify(i)}}),e=e.replace(t,"").trim();break}}catch(e){b.v.debug("Failed to parse potential tool JSON:",e)}}}p=e}(p.includes("<|channel|>")||p.includes("<|message|>")||p.includes("<|end|>")||p.includes("<|start|>"))&&(p=p.replace(/<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|end\|><\|start\|>assistant<\|channel\|>[^<]*<\|message\|>/g,"").replace(/<\|call\|>/g,"").replace(/\s+/g," ").trim()),Object.keys(u).length>0&&b.v.debug(`[Orchestrator] Found ${Object.keys(u).length} tool calls before validation`,Object.keys(u));let v=Object.values(u).map(e=>{if(e.function?.arguments)try{JSON.parse(e.function.arguments),b.v.debug(`[Orchestrator] Tool call ${e.id} validated successfully: ${e.function.name}`)}catch{g&&b.v.warn("Incomplete tool arguments detected, attempting to fix");let t=e.function.arguments,r=(t.match(/{/g)||[]).length,i=(t.match(/}/g)||[]).length,s=(t.match(/\[/g)||[]).length,o=(t.match(/]/g)||[]).length,n="";for(let e=0;eb.v.error("Failed to update project cost:",e)),this.onProgress?.("usage",{usage:s,totalCost:this.totalCost}),("openrouter"===t||t.includes("openrouter"))&&s.generationId&&!1!==s.isEstimated){let a=n.s.getProviderApiKey("openrouter");a&&c.I.queueGenerationForCostUpdate(s.generationId,a,this.projectId,t,e,(e,a)=>{let c=l.U.updateWithGenerationApiCost(s,{total_cost:e,native_tokens_total:a.native_tokens_total,native_tokens_prompt:a.native_tokens_prompt,native_tokens_completion:a.native_tokens_completion}),d=e-r;if(Math.abs(d)>1e-4){this.totalCost+=d;let s=c.provider||t||"unknown";n.s.adjustSessionCost(s,d),this.projectId.startsWith("test-")||i.OP.applyProjectCostDelta(this.projectId,{costDelta:d,provider:s,sessionId:o}).catch(e=>b.v.error("Failed to apply corrected project cost:",e)),this.onProgress?.("cost_correction",{originalCost:r,actualCost:e,difference:d,usage:c,totalCost:this.totalCost})}})}}return b.v.debug("[Orchestrator] Final response",{contentLength:p.length,toolCallsCount:v.length,toolCalls:v.map(e=>({id:e.id,name:e.function?.name,argsLength:e.function?.arguments?.length}))}),{content:p,toolCalls:v,usage:s}}async ensurePricing(e,t){let r=`${e}:${t}`;if(this.pricingEnsured.has(r))return;if("openrouter"!==e||n.s.getModelPricing("openrouter",t))return void this.pricingEnsured.add(r);let i=n.s.getCachedModels("openrouter");if(i?.models?.length&&((0,S.V)("openrouter",i.models),n.s.getModelPricing("openrouter",t)))return void this.pricingEnsured.add(r);try{let e=await (0,j.QF)();(0,S.b)(e),n.s.getModelPricing("openrouter",t)&&this.pricingEnsured.add(r)}catch(e){b.v.warn("[Orchestrator] Failed to fetch pricing metadata",e)}}debug(...e){b.v.debug(...e)}getAvailableTools(){return[d,p,u]}async execute(e){b.v.info("[Orchestrator] Starting execution with prompt",{promptPreview:e.substring(0,100)}),this.evaluationRequested=!1,this.evaluationReceived=!1;try{let t;await this.recordAutoCheckpoint(`Before prompt: ${e.substring(0,60)}`);try{let e=await i.OP.listDirectory(this.projectId,"/");e.length>0&&(t=this.buildFileTree(e))}catch{}let r=(0,h.m)(t);0===this.conversation.length&&this.conversation.push({role:"system",content:r}),this.conversation.push({role:"user",content:e});for(let e=0;e({name:e.function?.name,args:e.function?.arguments?.substring(0,100)}))}),!n.toolCalls||0===n.toolCalls.length){if(b.v.debug("[Orchestrator] No tool calls in response"),n.content&&n.content.trim()){if(this.conversation.push({role:"assistant",content:n.content}),this.stepsCompleted>=3&&!this.evaluationRequested&&!this.evaluationReceived){b.v.debug(`[Orchestrator] Requesting evaluation after ${this.stepsCompleted} steps`),this.evaluationRequested=!0,this.conversation.push({role:"user",content:"Please use the evaluation tool to assess if the task has been completed successfully. Include progress_summary, remaining_work, and any blockers."});continue}if(this.evaluationReceived){if(this.taskComplete||this.evaluationResult?.shouldContinue===!1){b.v.info("[Orchestrator] Breaking: evaluation complete, should not continue");break}b.v.debug("[Orchestrator] Evaluation received but should_continue=true, continuing..."),this.evaluationReceived=!1}if(this.evaluationRequested){b.v.info("[Orchestrator] Breaking: evaluation requested but not provided");break}if(0===this.stepsCompleted&&(this.noToolCallRetries++,b.v.debug(`[Orchestrator] No progress made, retry ${this.noToolCallRetries}/2`),this.noToolCallRetries<=2)){this.conversation.push({role:"user",content:"Please proceed with the implementation using the shell tool."});continue}}if(this.noToolCallRetries++,b.v.debug(`[Orchestrator] No tool calls, retry ${this.noToolCallRetries}/3`),this.noToolCallRetries<=3){this.conversation.push({role:"user",content:"Continue with the task. If you need to perform more operations, use the available tools."});continue}b.v.info(`[Orchestrator] Breaking: no tool calls and max retries reached. Steps completed: ${this.stepsCompleted}`);break}n.toolCalls&&n.toolCalls.length>0&&(b.v.debug(`[Orchestrator] Sending ${n.toolCalls.length} tool calls to UI`),this.onProgress?.("toolCalls",{toolCalls:n.toolCalls}));try{t=await this.executeToolCalls(n.toolCalls,e),this.malformedToolCallRetries=0}catch(t){let e=t instanceof Error?t.message:String(t);if(b.v.error("[Orchestrator] Tool execution error:",e),e.includes("Malformed tool call")&&(this.malformedToolCallRetries++,b.v.debug(`[Orchestrator] Malformed tool call, retry ${this.malformedToolCallRetries}/2`),this.malformedToolCallRetries<=2)){this.conversation.push({role:"user",content:`Error: ${e}. Please fix the tool call format and try again.`});continue}throw t}if(n.content||n.toolCalls.length>0){let e={role:"assistant",content:n.content||""};n.toolCalls.length>0&&(e.tool_calls=n.toolCalls),this.conversation.push(e)}for(let e of t)this.conversation.push(e);this.accumulatedToolCalls.push(...n.toolCalls);let a=n.toolCalls.find(e=>e.function?.name==="evaluation");if(a)try{let e=JSON.parse(a.function.arguments);if(this.evaluationResult={goalAchieved:e.goal_achieved||!1,reasoning:e.reasoning||"",progressSummary:e.progress_summary||"",remainingWork:e.remaining_work||[],blockers:e.blockers||[]},e.goal_achieved){b.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0;break}}catch(e){b.v.error("Failed to parse evaluation result:",e)}if(this.taskComplete||this.stepsCompleted>=50){b.v.info(`[Orchestrator] Breaking: taskComplete=${this.taskComplete}, steps=${this.stepsCompleted}`);break}}b.v.info(`[Orchestrator] Execution completed after ${this.maxIterations} iterations max. Steps: ${this.stepsCompleted}`);let s=this.generateSummary();return await this.recordAutoCheckpoint(`After completion: ${e.substring(0,60)}`),{success:this.stepsCompleted>0,summary:s,stepsCompleted:this.stepsCompleted,checkpointId:this.lastCheckpointId??void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}catch(r){b.v.error("Orchestrator error:",r);let t=r instanceof Error?r.message:"Unknown error";try{await this.recordAutoCheckpoint(`After failure: ${e.substring(0,60)}`)}catch(e){b.v.warn("Failed to record checkpoint after error",e)}return{success:!1,summary:`Task failed: ${t}`,stepsCompleted:this.stepsCompleted,checkpointId:this.lastCheckpointId??void 0,conversation:this.conversation,totalCost:this.totalCost,usageInfo:this.totalUsage}}}async executeToolCalls(e,t){let r=[];for(let t=0;t0&&(t.push(r),r=""):r+=a}return r.length>0&&t.push(r),t}(e.cmd),b.v.debug(`[Orchestrator] Converted string command "${e.cmd}" to array:`,i);else if(Array.isArray(e.cmd))i=e.cmd;else throw Error(`Malformed tool call - cmd must be string or array. +✅ Correct: {"cmd": ["ls", "/"]}`)}if(!e.cmd)throw Error(`Malformed tool call - cmd parameter is required. + +✅ Natural format: {"cmd": "ls -la /"} +✅ Array format: {"cmd": ["ls", "-la", "/"]} + +Examples: +- {"cmd": "cat /index.html"} - Read a file +- {"cmd": ["rg", "-C", "5", "pattern", "/"]} - Search with context +- {"cmd": "head -n 50 /app.js"} - Sample file start +- {"cmd": ["tree", "-L", "2", "/"]} - Show directory structure`);if("string"==typeof e.cmd)i=function(e){let t=[],r="",i=!1,s="",o=!1;for(let n=0;n0&&(t.push(r),r=""):r+=a}return r.length>0&&t.push(r),t}(e.cmd),b.v.debug(`[Orchestrator] Converted string command "${e.cmd}" to array:`,i);else if(Array.isArray(e.cmd))i=e.cmd;else throw Error(`Malformed tool call - cmd must be string or array. ✅ Natural format: {"cmd": "ls -la /"} ✅ Array format: {"cmd": ["ls", "-la", "/"]} @@ -608,9 +695,48 @@ Examples: - {"cmd": "cat /index.html"} - Natural format - {"cmd": ["cat", "/index.html"]} - Array format - {"cmd": "ls -la /"} - Natural format -- {"cmd": ["ls", "-la", "/"]} - Array format`);b.v.debug(`[Orchestrator] Executing shell command: ${i[0]}`),b.v.debug("[Orchestrator] Routing to executeShellCommand");let o=await this.executeShellCommand(i);b.v.debug("[Orchestrator] Command result length:",o?.length),r.push({role:"tool",tool_call_id:n,content:o}),this.stepsCompleted++;let a=o.startsWith("❌");this.onProgress?.("tool_status",{toolIndex:t,status:a?"failed":"completed",result:o}),b.v.debug(`[Orchestrator] Sending tool result for tool ${t}`,{resultPreview:o.substring(0,100)}),this.onProgress?.("tool_result",{toolIndex:t,toolId:n,result:o});let l=this.isWriteOperation(e.cmd),c=this.isFileStructureOperation(e.cmd);l?(this.lastIterationHadWrite=!0,await this.recordAutoCheckpoint(`After step ${this.stepsCompleted}`)):this.lastIterationHadWrite=!1,c&&this.triggerFileExplorerRefresh()}catch(i){let e=i instanceof Error?i.message:String(i);r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}else if("json_patch"===o)try{let e=JSON.parse(s.function.arguments);b.v.debug(`[Orchestrator] Executing json_patch call for ${e.file_path}`);let o=new i.r8;await o.init();let a=await x(o,this.projectId,e.file_path,e.operations);b.v.debug("[Orchestrator] String patch result:",a);let l=a.summary;a.warnings&&a.warnings.length>0&&(l+="\n\nWarnings:\n"+a.warnings.map(e=>`• ${e}`).join("\n")),r.push({role:"tool",tool_call_id:n,content:l}),this.stepsCompleted++,this.onProgress?.("tool_status",{toolIndex:t,status:a.applied?"completed":"failed",result:l}),this.onProgress?.("tool_result",{toolIndex:t,toolId:n,result:l}),a.applied&&(await this.recordAutoCheckpoint(`After step ${this.stepsCompleted}`),this.triggerFileExplorerRefresh())}catch(i){let e=i instanceof Error?i.message:String(i);r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}else if("evaluation"===o)try{let e=JSON.parse(s.function.arguments);b.v.debug("[Orchestrator] Processing evaluation:",e),!0===e.goal_achieved&&(b.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0),r.push({role:"tool",tool_call_id:n,content:JSON.stringify(e)}),this.onProgress?.("tool_status",{toolIndex:t,status:"completed",result:JSON.stringify(e)})}catch(e){r.push({role:"tool",tool_call_id:n,content:`Error parsing evaluation: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:`Error parsing evaluation: ${e}`})}else{let e=`Unknown tool: ${o}`;b.v.warn(`[Orchestrator] ${e}`),r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}}return r}async recordAutoCheckpoint(e){let t=await s.Y.createCheckpoint(this.projectId,e,{kind:"auto",baseRevisionId:o.$.getSavedCheckpointId(this.projectId)});return this.lastCheckpointId=t.id,t}async executeShellCommand(e){try{let t=await v.execute(this.projectId,e);if(t.success){let r=t.stdout&&t.stdout.trim().length>0?t.stdout:"Command succeeded with no output",i=e&&e.length>0?e[0]:void 0;if("cat"===i){let t=e.length>1?e[1]:void 0;if(t){let e=Date.now(),i=this.recentCatReads.get(t);if(i&&e-i<3e4){let e=`Hint: You already read ${t} recently; reuse that context unless the file changed.`;r=`${e} +- {"cmd": ["ls", "-la", "/"]} - Array format`);b.v.debug(`[Orchestrator] Executing shell command: ${i[0]}`),b.v.debug("[Orchestrator] Routing to executeShellCommand");let o=await this.executeShellCommand(i);b.v.debug("[Orchestrator] Command result length:",o?.length),r.push({role:"tool",tool_call_id:n,content:o}),this.stepsCompleted++;let a=o.startsWith("❌");this.onProgress?.("tool_status",{toolIndex:t,status:a?"failed":"completed",result:o}),b.v.debug(`[Orchestrator] Sending tool result for tool ${t}`,{resultPreview:o.substring(0,100)}),this.onProgress?.("tool_result",{toolIndex:t,toolId:n,result:o});let l=this.isWriteOperation(e.cmd),c=this.isFileStructureOperation(e.cmd);l?(this.lastIterationHadWrite=!0,await this.recordAutoCheckpoint(`After step ${this.stepsCompleted}`)):this.lastIterationHadWrite=!1,c&&this.triggerFileExplorerRefresh()}catch(i){let e=i instanceof Error?i.message:String(i);r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}else if("json_patch"===o)try{let e=JSON.parse(s.function.arguments);b.v.debug(`[Orchestrator] Executing json_patch call for ${e.file_path}`);let o=new i.r8;await o.init();let a=await x(o,this.projectId,e.file_path,e.operations);b.v.debug("[Orchestrator] String patch result:",a);let l=a.summary;a.warnings&&a.warnings.length>0&&(l+="\n\nWarnings:\n"+a.warnings.map(e=>`• ${e}`).join("\n")),r.push({role:"tool",tool_call_id:n,content:l}),this.stepsCompleted++,this.onProgress?.("tool_status",{toolIndex:t,status:a.applied?"completed":"failed",result:l}),this.onProgress?.("tool_result",{toolIndex:t,toolId:n,result:l}),a.applied&&(await this.recordAutoCheckpoint(`After step ${this.stepsCompleted}`),this.triggerFileExplorerRefresh())}catch(i){let e=i instanceof Error?i.message:String(i);r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}else if("evaluation"===o)try{let e=JSON.parse(s.function.arguments);b.v.debug("[Orchestrator] Processing evaluation:",e),this.evaluationReceived=!0,this.evaluationRequested=!1,this.evaluationResult={goalAchieved:e.goal_achieved,reasoning:e.reasoning,progressSummary:e.progress_summary,remainingWork:e.remaining_work,blockers:e.blockers,shouldContinue:e.should_continue},!0===e.goal_achieved&&(b.v.info("[Orchestrator] Task marked complete by evaluation"),this.taskComplete=!0),r.push({role:"tool",tool_call_id:n,content:JSON.stringify(e)}),this.onProgress?.("tool_status",{toolIndex:t,status:"completed",result:JSON.stringify(e)})}catch(s){let e=s instanceof Error?s.message:String(s),i=`Error parsing evaluation: ${e} + +✅ Correct format: +{ + "goal_achieved": true, + "progress_summary": "Completed hero section with CTA, features grid with 6 items", + "remaining_work": ["Add pricing section", "Create footer"], + "blockers": [], + "reasoning": "Hero and features complete. Next: pricing section.", + "should_continue": true +} + +Required fields: +• goal_achieved (boolean) - Whether the original task is fully complete +• progress_summary (string) - Brief summary of work completed so far +• remaining_work (array of strings) - Specific tasks still needed (empty if goal_achieved is true) +• reasoning (string) - Detailed explanation of current status and next steps +• should_continue (boolean) - Whether to continue working + +Optional field: +• blockers (array of strings) - Current blockers preventing progress`;r.push({role:"tool",tool_call_id:n,content:`Error: ${i}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:i})}else{let e=`Unknown tool: ${o} + +Available tools are: shell, json_patch, evaluation + +✅ Shell tool (execute commands): + {"name": "shell", "arguments": "{\\"cmd\\": \\"ls -la /\\"}"} + +✅ JSON patch tool (edit files): + {"name": "json_patch", "arguments": "{\\"file_path\\": \\"/index.html\\", \\"operations\\": [...]}"} + +✅ Evaluation tool (assess progress): + {"name": "evaluation", "arguments": "{\\"goal_achieved\\": true, \\"reasoning\\": \\"...\\"...}"} + +Common mistakes: +❌ Wrong tool name: "shell<|channel|>analysis", "functions.shell", "command" +❌ Typos: "shelll", "json-patch", "evaluate"`;b.v.warn(`[Orchestrator] ${e}`),r.push({role:"tool",tool_call_id:n,content:`Error: ${e}`}),this.onProgress?.("tool_status",{toolIndex:t,status:"failed",error:e})}}return r}async recordAutoCheckpoint(e){let t=await s.Y.createCheckpoint(this.projectId,e,{kind:"auto",baseRevisionId:o.$.getSavedCheckpointId(this.projectId)});return this.lastCheckpointId=t.id,t}async executeShellCommand(e){try{let t=await v.execute(this.projectId,e);if(t.success){let r=t.stdout&&t.stdout.trim().length>0?t.stdout:"Command succeeded with no output",i=e&&e.length>0?e[0]:void 0;if("cat"===i){let t=e.length>1?e[1]:void 0;if(t){let e=Date.now(),i=this.recentCatReads.get(t);if(i&&e-i<3e4){let e=`Hint: You already read ${t} recently; reuse that context unless the file changed.`;r=`${e} -${r}`}let s=e-12e4;for(let[e,t]of this.recentCatReads)t=1;r--){let i=e[r];if(!i.startsWith("-")){t=i;break}}t&&r&&"Command succeeded with no output"!==r&&(r=`Hint: Avoid numbering the entire ${t}. Reuse the snippet you already captured or run targeted slices (e.g., sed -n '30,60p' ${t} | nl -ba). No content streamed.`)}return r}{let e=t.stderr&&t.stderr.trim().length>0?t.stderr:"Command failed";return`Error: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return`Error: ${e}`}}isWriteOperation(e){return!!e&&0!==e.length&&["mkdir","rm","rmdir","mv","cp"].includes(e[0])}isFileStructureOperation(e){return!!e&&0!==e.length&&["mv","rm","rmdir","cp","mkdir"].includes(e[0])}triggerFileExplorerRefresh(){}buildFileTree(e){if(0===e.length)return"";let t=new Map;for(let r of e){let e=r.path.split("/").filter(Boolean);for(let r=0;r{if(0===e)return"0B";let t=Math.floor(Math.log(e)/Math.log(1024)),r=e/Math.pow(1024,t);return(0===t?r.toString():r.toFixed(1))+["B","KB","MB"][t]},i=(e,s="",o=!0)=>{let n=t.get(e);if(!n)return[];let a=[],l="/"===e?"":e.split("/").pop()||"";if("/"!==e){let e=n.isDirectory?l+"/":l,t=n.isDirectory?"":` (${r(n.size||0)})`;a.push(s+(o?"└── ":"├── ")+e+t)}let c=Array.from(n.children).sort((e,r)=>{let i=t.get(e),s=t.get(r);return i?.isDirectory!==s?.isDirectory?i?.isDirectory?-1:1:e.localeCompare(r)});return c.forEach((t,r)=>{let n=r===c.length-1,l="/"===e?"":s+(o?" ":"│ ");a.push(...i(t,l,n))}),a},s=i("/");return s.length>0?"Project Structure:\n"+s.join("\n"):""}generateSummary(){if(this.evaluationResult)return this.evaluationResult.reasoning;if(0===this.stepsCompleted)return"No actions were taken.";let e=this.accumulatedToolCalls.filter(e=>e.function?.name==="shell").map(e=>{try{let t=JSON.parse(e.function.arguments);return this.getOperationDescription({name:"shell",parameters:t})}catch{return"Unknown operation"}});if(0===e.length)return`Completed ${this.stepsCompleted} step${1!==this.stepsCompleted?"s":""}.`;let t=[...new Set(e)];return`Completed ${this.stepsCompleted} step${1!==this.stepsCompleted?"s":""}: ${t.slice(0,3).join(", ")}${t.length>3?"...":""}`}getOperationDescription(e){if("shell"!==e.name)return e.name;let t=Array.isArray(e.parameters?.cmd)?e.parameters.cmd:[];if(!t.length)return"Executed shell";let r=(t[0]||"").toLowerCase();switch(r){case"ls":return"Listed files";case"cat":return`Read ${t[1]||"file"}`;case"grep":return"Searched for patterns";case"find":return"Found files";case"mkdir":return"Created directory";case"rm":return`Removed ${t[1]||"file"}`;case"rmdir":return"Removed directory";case"mv":return`Moved ${t[1]||"file"}`;case"cp":return`Copied ${t[1]||"file"}`;default:return`Executed: ${r}`}}async performEvaluation(e){let t=`Review the task and determine if it has been completed successfully. +${r}`}let s=e-12e4;for(let[e,t]of this.recentCatReads)t=1;r--){let i=e[r];if(!i.startsWith("-")){t=i;break}}t&&r&&"Command succeeded with no output"!==r&&(r=`Hint: Avoid numbering the entire ${t}. Reuse the snippet you already captured or run targeted slices (e.g., sed -n '30,60p' ${t} | nl -ba). No content streamed.`)}return r}{let e=t.stderr&&t.stderr.trim().length>0?t.stderr:"Command failed";return`Error: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return`Error: ${e}`}}isWriteOperation(e){return!!e&&0!==e.length&&["mkdir","rm","rmdir","mv","cp"].includes(e[0])}isFileStructureOperation(e){return!!e&&0!==e.length&&["mv","rm","rmdir","cp","mkdir"].includes(e[0])}triggerFileExplorerRefresh(){}buildFileTree(e){if(0===e.length)return"";let t=new Map;for(let r of e){let e=r.path.split("/").filter(Boolean);for(let r=0;r{if(0===e)return"0B";let t=Math.floor(Math.log(e)/Math.log(1024)),r=e/Math.pow(1024,t);return(0===t?r.toString():r.toFixed(1))+["B","KB","MB"][t]},i=(e,s="",o=!0)=>{let n=t.get(e);if(!n)return[];let a=[],l="/"===e?"":e.split("/").pop()||"";if("/"!==e){let e=n.isDirectory?l+"/":l,t=n.isDirectory?"":` (${r(n.size||0)})`;a.push(s+(o?"└── ":"├── ")+e+t)}let c=Array.from(n.children).sort((e,r)=>{let i=t.get(e),s=t.get(r);return i?.isDirectory!==s?.isDirectory?i?.isDirectory?-1:1:e.localeCompare(r)});return c.forEach((t,r)=>{let n=r===c.length-1,l="/"===e?"":s+(o?" ":"│ ");a.push(...i(t,l,n))}),a},s=i("/");return s.length>0?"Project Structure:\n"+s.join("\n"):""}generateSummary(){if(this.evaluationResult){let e=this.evaluationResult.reasoning;if(this.evaluationResult.goalAchieved){e+="\n\n✅ Task Complete";let t=this.getCreatedFilesInSession();t.length>0&&(e+="\n\nCreated/modified files:",t.forEach(t=>e+=` +• ${t}`)),e+="\n\nNext steps: Open the preview to test the application."}else e+="\n\n⚠️ Task Incomplete",this.evaluationResult.remainingWork&&this.evaluationResult.remainingWork.length>0&&(e+="\n\nRemaining work:",this.evaluationResult.remainingWork.forEach(t=>e+=` +• ${t}`)),this.evaluationResult.blockers&&this.evaluationResult.blockers.length>0&&(e+="\n\nBlockers:",this.evaluationResult.blockers.forEach(t=>e+=` +• ${t}`));return e}if(0===this.stepsCompleted)return"No actions were taken.";let e=this.getCreatedFilesInSession(),t=`Completed ${this.stepsCompleted} operation${1!==this.stepsCompleted?"s":""}.`;return e.length>0&&(t+="\n\nCreated/modified files:",e.forEach(e=>t+=` +• ${e}`)),t}getCreatedFilesInSession(){let e=new Set;for(let t of this.accumulatedToolCalls)if(t.function?.name==="json_patch")try{let r=JSON.parse(t.function.arguments);r.file_path&&e.add(r.file_path)}catch{}else if(t.function?.name==="shell")try{let r=JSON.parse(t.function.arguments),i=Array.isArray(r.cmd)?r.cmd:[];if("touch"===i[0]&&i[1]&&e.add(i[1]),"mkdir"===i[0]&&i.includes("-p")){let t=i[i.length-1];t&&t.startsWith("/")&&e.add(t+"/")}if("echo"===i[0]&&i.includes(">")){let t=i.indexOf(">");t>0&&i[t+1]&&e.add(i[t+1])}}catch{}return Array.from(e).sort()}getOperationDescription(e){if("shell"!==e.name)return e.name;let t=Array.isArray(e.parameters?.cmd)?e.parameters.cmd:[];if(!t.length)return"Executed shell";let r=(t[0]||"").toLowerCase();switch(r){case"ls":return"Listed files";case"cat":return`Read ${t[1]||"file"}`;case"grep":return"Searched for patterns";case"find":return"Found files";case"mkdir":return"Created directory";case"rm":return`Removed ${t[1]||"file"}`;case"rmdir":return"Removed directory";case"mv":return`Moved ${t[1]||"file"}`;case"cp":return`Copied ${t[1]||"file"}`;default:return`Executed: ${r}`}}async performEvaluation(e){let t=`Review the task and determine if it has been completed successfully. Original request: "${e}"