@kodadev/koda-cli 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bundle/koda.js +6 -6
  2. package/package.json +1 -1
package/bundle/koda.js CHANGED
@@ -394,7 +394,7 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
394
394
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
395
395
 
396
396
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
397
- `);super({baseURL:s.baseURL,timeout:s.timeout??6e5,httpAgent:s.httpAgent,maxRetries:s.maxRetries,fetch:s.fetch}),this.completions=new Ax(this),this.chat=new Vv(this),this.embeddings=new Ex(this),this.files=new WD(this),this.images=new bx(this),this.audio=new x9(this),this.moderations=new Ix(this),this.models=new JD(this),this.fineTuning=new KA(this),this.graders=new KD(this),this.vectorStores=new JA(this),this.beta=new PE(this),this.batches=new GD(this),this.uploads=new tS(this),this.responses=new eS(this),this.evals=new F9(this),this.containers=new O9(this),this._options=s,this.apiKey=r,this.organization=n,this.project=i}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return kTe(e,{arrayFormat:"brackets"})}};PBt=Ii;Ii.OpenAI=PBt;Ii.DEFAULT_TIMEOUT=6e5;Ii.OpenAIError=An;Ii.APIError=Ep;Ii.APIConnectionError=QD;Ii.APIConnectionTimeoutError=kD;Ii.APIUserAbortError=Hd;Ii.NotFoundError=wY;Ii.ConflictError=IY;Ii.RateLimitError=xY;Ii.BadRequestError=DY;Ii.AuthenticationError=SY;Ii.InternalServerError=BY;Ii.PermissionDeniedError=bY;Ii.UnprocessableEntityError=TY;Ii.toFile=uBe;Ii.fileFromPath=mce;Ii.Completions=Ax;Ii.Chat=Vv;Ii.ChatCompletionsPage=HD;Ii.Embeddings=Ex;Ii.Files=WD;Ii.FileObjectsPage=Cx;Ii.Images=bx;Ii.Audio=x9;Ii.Moderations=Ix;Ii.Models=JD;Ii.ModelsPage=wx;Ii.FineTuning=KA;Ii.Graders=KD;Ii.VectorStores=JA;Ii.VectorStoresPage=Tx;Ii.VectorStoreSearchResponsesPage=xx;Ii.Beta=PE;Ii.Batches=GD;Ii.BatchesPage=ux;Ii.Uploads=tS;Ii.Responses=eS;Ii.Evals=F9;Ii.EvalListResponsesPage=vx;Ii.Containers=O9;Ii.ContainerListResponsesPage=gx;QBt=Ii});import*as Vde from"node:fs";import UBt from"node:path";import $sn from"node:os";function sQ(t){t.include_reasoning=!1;let e=t.extra_body,r=QE(e)?{...e}:{},n=QE(r.reasoning)?r.reasoning:void 0;return r.reasoning={...n??{},exclude:!0},r.include_reasoning=!1,t.extra_body=r,t}function HBt(t){return!t||t.indexOf("<think")===-1?t:t.replace(/<think>[\s\S]*?<\/think>\s*/g,"").replace(/<\/?think>/g,"")}function QE(t){return typeof t=="object"&&t!==null}function Ude(t){return typeof t=="string"?t:void 0}function jsn(t){return Array.isArray(t)?t.map(e=>typeof e=="string"?{text:e}:e):typeof t=="string"?[{text:t}]:[t]}function Hde(t){return!t||t.length===0?"":t.map(e=>{if(e.text)return e.text;if(e.functionResponse?.response){let r=e.functionResponse.response;if(typeof r.output=="string")return r.output;try{return JSON.stringify(r)}catch{return""}}return""}).join("")}function VBt(t){return Array.isArray(t)?t.map(e=>Array.isArray(e)?{role:"user",parts:jsn(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?e:{role:"user",parts:[e]}):typeof t=="string"?[{role:"user",parts:[{text:t}]}]:"parts"in t?[t]:[{role:"user",parts:[t]}]}function Ysn(t){let e=t.role==="model"?"assistant":"user",r=(t.parts||[]).filter(o=>o.functionResponse),n=(t.parts||[]).filter(o=>o.functionCall),i=(t.parts||[]).filter(o=>!o.functionResponse&&!o.functionCall),a=Hde(i),s=[];if(n.length>0){let o=n.map((l,u)=>{let c=l.functionCall;if(!c||!c.name)return;let d="{}";if(c.args&&typeof c.args=="object")try{d=JSON.stringify(c.args)}catch{d="{}"}return{id:c.id||`${c.name}-${u}`,type:"function",function:{name:c.name,arguments:d}}}).filter(Boolean);(o.length>0||a)&&s.push({role:e,content:a||"",...o.length>0?{tool_calls:o}:{}})}else a&&s.push({role:e,content:a});for(let o of r){let l=o.functionResponse,u=(()=>{let c=l.response;if(!c)return"";if(typeof c.output=="string")return c.output;try{return JSON.stringify(c)}catch{return""}})();l.id&&s.push({role:"tool",tool_call_id:l.id,content:u})}return s.length===0&&s.push({role:e,content:""}),s}function zY(t,e){let r=VBt(t),n=e?[{role:"system",content:typeof e=="string"?e:Hde(e.parts)}]:[],i=r.flatMap(Ysn);return[...n,...i]}function Wsn(t){return typeof t=="object"&&t!==null&&"functionDeclarations"in t&&Array.isArray(t.functionDeclarations)}function TRe(t){if(!t)return;let e=[];for(let r of t){let n=Wsn(r)?r.functionDeclarations:void 0;if(Array.isArray(n))for(let i of n)i?.name&&e.push({type:"function",function:{name:i.name,description:i.description,parameters:i.parametersJsonSchema??i.parameters}})}return e.length?e:void 0}function xRe(t){let r=t.choices?.[0]?.message,n=r?.tool_calls?r.tool_calls.map(d=>({id:d.id,name:d.function.name,args:(()=>{try{let h=JSON.parse(d.function.arguments||"{}");return h&&typeof h=="object"?h:{}}catch{return{}}})()})):void 0,i=d=>{let h="";for(let f of d)QE(f)&&(typeof f.text=="string"?h+=f.text:typeof f.output_text=="string"?h+=String(f.output_text):typeof f.content=="string"&&(h+=String(f.content)));return h},a="";if(typeof r?.content=="string"?a=r.content:Array.isArray(r?.content)&&(a=i(r.content)),!a||a.trim()===""){let d=r,h=d?.parsed??d?.json??void 0;if(h&&typeof h=="object")try{a=JSON.stringify(h)}catch{}}if((!a||a.trim()==="")&&Array.isArray(r?.tool_calls)&&r.tool_calls.length){let d=r.tool_calls[0]?.function?.arguments;typeof d=="string"&&(a=d)}let s=(n??[]).map(d=>({functionCall:{name:d.name,args:d.args,id:d.id}})),o=[];a&&o.push({text:a}),s.length>0&&o.push(...s);let l=[{content:{role:"model",parts:o}}],u=GBt(t.usage),c={candidates:l,...u?{usageMetadata:u}:{}};return c.functionCalls=n,c}var GBt,Gde,qBt=Oe(()=>{"use strict";G4();kBt();GBt=t=>{if(t)return{promptTokenCount:t.prompt_tokens??0,candidatesTokenCount:t.completion_tokens??0}};Gde=class{apiBase;apiKey;githubToken;httpOptions;openai;authType;constructor(e={}){let n=e.apiBase||process.env.KODA_API_BASE||"https://api.kodacode.ru/dev/v1";this.apiBase=n.endsWith("/")?n:`${n}/`,this.apiKey=e.apiKey||process.env.KODA_API_KEY,this.githubToken=process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN,this.httpOptions=e.httpOptions,this.authType=e.authType,this.loadTokensFromDiskSync()}shouldOmitAuthHeader(){return this.isKodaHost(this.apiBase)?this.apiKey||this.githubToken?!1:process.env.KODA_FORCE_AUTH!=="true":!1}isKodaHost(e){try{let r=new URL(e).hostname;return r==="api.kodacode.ru"||r.endsWith(".kodacode.ru")}catch{return!1}}loadTokensFromDiskSync(){try{let e=process.env.XDG_CONFIG_HOME||UBt.join($sn.homedir(),".config"),r=UBt.join(e,"koda","credentials.json");if(!Vde.existsSync(r))return;let n=Vde.readFileSync(r,"utf-8"),i=JSON.parse(n);!this.apiKey&&typeof i.kodaApiKey=="string"&&i.kodaApiKey&&(this.apiKey=i.kodaApiKey,process.env.KODA_API_KEY||(process.env.KODA_API_KEY=i.kodaApiKey)),!this.githubToken&&typeof i.githubToken=="string"&&i.githubToken&&(this.githubToken=i.githubToken,process.env.KODA_GITHUB_TOKEN||(process.env.KODA_GITHUB_TOKEN=i.githubToken),process.env.GITHUB_TOKEN||(process.env.GITHUB_TOKEN=i.githubToken))}catch{}}async generateContent(e,r){let n=e.config?.systemInstruction,i=typeof n=="string"||n&&typeof n=="object"&&"parts"in n?n:n?{role:"user",parts:[n]}:void 0,a=e.config,s=a?.maxOutputTokens??a?.maxTokens??4e3,o=sQ({model:e.model,messages:zY(e.contents,i),temperature:e.config?.temperature??null,top_p:e.config?.topP??null,stream:!1,max_tokens:s});try{let u=TRe(e.config?.tools);u&&u.length&&(o.tools=u,o.tool_choice||="auto")}catch{}if(["KodaChat","KodaEdit","KodaApply"].includes(e.model)){let u=[...o.messages].reverse().find(c=>c.role==="user");u&&typeof u.content=="string"&&(u.content+=`
397
+ `);super({baseURL:s.baseURL,timeout:s.timeout??6e5,httpAgent:s.httpAgent,maxRetries:s.maxRetries,fetch:s.fetch}),this.completions=new Ax(this),this.chat=new Vv(this),this.embeddings=new Ex(this),this.files=new WD(this),this.images=new bx(this),this.audio=new x9(this),this.moderations=new Ix(this),this.models=new JD(this),this.fineTuning=new KA(this),this.graders=new KD(this),this.vectorStores=new JA(this),this.beta=new PE(this),this.batches=new GD(this),this.uploads=new tS(this),this.responses=new eS(this),this.evals=new F9(this),this.containers=new O9(this),this._options=s,this.apiKey=r,this.organization=n,this.project=i}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return kTe(e,{arrayFormat:"brackets"})}};PBt=Ii;Ii.OpenAI=PBt;Ii.DEFAULT_TIMEOUT=6e5;Ii.OpenAIError=An;Ii.APIError=Ep;Ii.APIConnectionError=QD;Ii.APIConnectionTimeoutError=kD;Ii.APIUserAbortError=Hd;Ii.NotFoundError=wY;Ii.ConflictError=IY;Ii.RateLimitError=xY;Ii.BadRequestError=DY;Ii.AuthenticationError=SY;Ii.InternalServerError=BY;Ii.PermissionDeniedError=bY;Ii.UnprocessableEntityError=TY;Ii.toFile=uBe;Ii.fileFromPath=mce;Ii.Completions=Ax;Ii.Chat=Vv;Ii.ChatCompletionsPage=HD;Ii.Embeddings=Ex;Ii.Files=WD;Ii.FileObjectsPage=Cx;Ii.Images=bx;Ii.Audio=x9;Ii.Moderations=Ix;Ii.Models=JD;Ii.ModelsPage=wx;Ii.FineTuning=KA;Ii.Graders=KD;Ii.VectorStores=JA;Ii.VectorStoresPage=Tx;Ii.VectorStoreSearchResponsesPage=xx;Ii.Beta=PE;Ii.Batches=GD;Ii.BatchesPage=ux;Ii.Uploads=tS;Ii.Responses=eS;Ii.Evals=F9;Ii.EvalListResponsesPage=vx;Ii.Containers=O9;Ii.ContainerListResponsesPage=gx;QBt=Ii});import*as Vde from"node:fs";import UBt from"node:path";import $sn from"node:os";function sQ(t){t.include_reasoning=!1;let e=t.extra_body,r=QE(e)?{...e}:{},n=QE(r.reasoning)?r.reasoning:void 0;return r.reasoning={...n??{},exclude:!0},r.include_reasoning=!1,t.extra_body=r,t}function HBt(t){return!t||t.indexOf("<think")===-1?t:t.replace(/<think>[\s\S]*?<\/think>\s*/g,"").replace(/<\/?think>/g,"")}function QE(t){return typeof t=="object"&&t!==null}function Ude(t){return typeof t=="string"?t:void 0}function jsn(t){return Array.isArray(t)?t.map(e=>typeof e=="string"?{text:e}:e):typeof t=="string"?[{text:t}]:[t]}function Hde(t){return!t||t.length===0?"":t.map(e=>{if(e.text)return e.text;if(e.functionResponse?.response){let r=e.functionResponse.response;if(typeof r.output=="string")return r.output;try{return JSON.stringify(r)}catch{return""}}return""}).join("")}function VBt(t){return Array.isArray(t)?t.map(e=>Array.isArray(e)?{role:"user",parts:jsn(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?e:{role:"user",parts:[e]}):typeof t=="string"?[{role:"user",parts:[{text:t}]}]:"parts"in t?[t]:[{role:"user",parts:[t]}]}function Ysn(t){let e=t.role==="model"?"assistant":"user",r=(t.parts||[]).filter(o=>o.functionResponse),n=(t.parts||[]).filter(o=>o.functionCall),i=(t.parts||[]).filter(o=>!o.functionResponse&&!o.functionCall),a=Hde(i),s=[];if(n.length>0){let o=n.map((l,u)=>{let c=l.functionCall;if(!c||!c.name)return;let d="{}";if(c.args&&typeof c.args=="object")try{d=JSON.stringify(c.args)}catch{d="{}"}return{id:c.id||`${c.name}-${u}`,type:"function",function:{name:c.name,arguments:d}}}).filter(Boolean);(o.length>0||a)&&s.push({role:e,content:a||"",...o.length>0?{tool_calls:o}:{}})}else a&&s.push({role:e,content:a});for(let o of r){let l=o.functionResponse,u=(()=>{let c=l.response;if(!c)return"";if(typeof c.output=="string")return c.output;try{return JSON.stringify(c)}catch{return""}})();l.id&&s.push({role:"tool",tool_call_id:l.id,content:u})}return s.length===0&&s.push({role:e,content:""}),s}function zY(t,e){let r=VBt(t),n=e?[{role:"system",content:typeof e=="string"?e:Hde(e.parts)}]:[],i=r.flatMap(Ysn);return[...n,...i]}function Wsn(t){return typeof t=="object"&&t!==null&&"functionDeclarations"in t&&Array.isArray(t.functionDeclarations)}function TRe(t){if(!t)return;let e=[];for(let r of t){let n=Wsn(r)?r.functionDeclarations:void 0;if(Array.isArray(n))for(let i of n)i?.name&&e.push({type:"function",function:{name:i.name,description:i.description,parameters:i.parametersJsonSchema??i.parameters}})}return e.length?e:void 0}function xRe(t){let r=t.choices?.[0]?.message,n=r?.tool_calls?r.tool_calls.map(d=>({id:d.id,name:d.function.name,args:(()=>{try{let h=JSON.parse(d.function.arguments||"{}");return h&&typeof h=="object"?h:{}}catch{return{}}})()})):void 0,i=d=>{let h="";for(let f of d)QE(f)&&(typeof f.text=="string"?h+=f.text:typeof f.output_text=="string"?h+=String(f.output_text):typeof f.content=="string"&&(h+=String(f.content)));return h},a="";if(typeof r?.content=="string"?a=r.content:Array.isArray(r?.content)&&(a=i(r.content)),!a||a.trim()===""){let d=r,h=d?.parsed??d?.json??void 0;if(h&&typeof h=="object")try{a=JSON.stringify(h)}catch{}}if((!a||a.trim()==="")&&Array.isArray(r?.tool_calls)&&r.tool_calls.length){let d=r.tool_calls[0]?.function?.arguments;typeof d=="string"&&(a=d)}let s=(n??[]).map(d=>({functionCall:{name:d.name,args:d.args,id:d.id}})),o=[];a&&o.push({text:a}),s.length>0&&o.push(...s);let l=[{content:{role:"model",parts:o}}],u=GBt(t.usage),c={candidates:l,...u?{usageMetadata:u}:{}};return c.functionCalls=n,c}var GBt,Gde,qBt=Oe(()=>{"use strict";G4();kBt();GBt=t=>{if(t)return{promptTokenCount:t.prompt_tokens??0,candidatesTokenCount:t.completion_tokens??0}};Gde=class{apiBase;apiKey;githubToken;httpOptions;openai;authType;constructor(e={}){let n=e.apiBase||process.env.KODA_API_BASE||"https://api.kodacode.ru/v1";this.apiBase=n.endsWith("/")?n:`${n}/`,this.apiKey=e.apiKey||process.env.KODA_API_KEY,this.githubToken=process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN,this.httpOptions=e.httpOptions,this.authType=e.authType,this.loadTokensFromDiskSync()}shouldOmitAuthHeader(){return this.isKodaHost(this.apiBase)?this.apiKey||this.githubToken?!1:process.env.KODA_FORCE_AUTH!=="true":!1}isKodaHost(e){try{let r=new URL(e).hostname;return r==="api.kodacode.ru"||r.endsWith(".kodacode.ru")}catch{return!1}}loadTokensFromDiskSync(){try{let e=process.env.XDG_CONFIG_HOME||UBt.join($sn.homedir(),".config"),r=UBt.join(e,"koda","credentials.json");if(!Vde.existsSync(r))return;let n=Vde.readFileSync(r,"utf-8"),i=JSON.parse(n);!this.apiKey&&typeof i.kodaApiKey=="string"&&i.kodaApiKey&&(this.apiKey=i.kodaApiKey,process.env.KODA_API_KEY||(process.env.KODA_API_KEY=i.kodaApiKey)),!this.githubToken&&typeof i.githubToken=="string"&&i.githubToken&&(this.githubToken=i.githubToken,process.env.KODA_GITHUB_TOKEN||(process.env.KODA_GITHUB_TOKEN=i.githubToken),process.env.GITHUB_TOKEN||(process.env.GITHUB_TOKEN=i.githubToken))}catch{}}async generateContent(e,r){let n=e.config?.systemInstruction,i=typeof n=="string"||n&&typeof n=="object"&&"parts"in n?n:n?{role:"user",parts:[n]}:void 0,a=e.config,s=a?.maxOutputTokens??a?.maxTokens??4e3,o=sQ({model:e.model,messages:zY(e.contents,i),temperature:e.config?.temperature??null,top_p:e.config?.topP??null,stream:!1,max_tokens:s});try{let u=TRe(e.config?.tools);u&&u.length&&(o.tools=u,o.tool_choice||="auto")}catch{}if(["KodaChat","KodaEdit","KodaApply"].includes(e.model)){let u=[...o.messages].reverse().find(c=>c.role==="user");u&&typeof u.content=="string"&&(u.content+=`
398
398
  /no_think`)}try{let c=e.config,d=c?.response_format;if(d&&typeof d=="object")o.response_format=d;else{let h=c?.responseJsonSchema,f=c?.responseMimeType;h&&typeof h=="object"?o.response_format={type:"json_schema",json_schema:{name:"koda_structured",schema:h,strict:!0}}:f==="application/json"&&(o.response_format={type:"json_object"})}}catch(u){console.warn("Failed to process response format parameters:",u)}let l=this.getOpenAI();try{let u=await l.chat.completions.create(o);return xRe(u)}catch(u){let c=E=>{if(typeof E=="string")return E;if(QE(E)){let y=Ude(E.message),g=QE(E.error)?Ude(E.error.message):void 0,C=QE(E.response)?E.response:void 0,D=C&&QE(C.data)?C.data:void 0,S=D?Ude(D.message):void 0,w=D&&QE(D.error)?Ude(D.error.message):void 0;return y||g||S||w||""}return""},d=c(u).toLowerCase();if(d.includes("response_format")&&(d.includes("unavailable")||d.includes("unsupported")||d.includes("invalid"))){if(o.response_format?.type==="json_schema")try{let g=sQ({...o,response_format:{type:"json_object"}}),C=await l.chat.completions.create(g);return xRe(C)}catch(g){let C=c(g).toLowerCase();if(!(C.includes("response_format")&&(C.includes("unavailable")||C.includes("unsupported")||C.includes("invalid"))))throw g}if(!!(e.config?.responseJsonSchema||e.config?.responseMimeType==="application/json")){let g=typeof i=="string"?i:i?Hde(i.parts):"",C=e.config.responseJsonSchema,D=C?`Return only a valid JSON object that strictly matches this JSON Schema. No extra text, no code fences. Schema:
399
399
  ${JSON.stringify(C)}`:"Return only a valid JSON object. No extra text, no code fences.",S=[g,D].filter(Boolean).join(`
400
400
 
@@ -850,7 +850,7 @@ Sources:
850
850
  ${E.join(`
851
851
  `)}`)}let y=l;return console.debug(`[WebFetchTool] Formatted tool response for prompt "${r}:
852
852
 
853
- ":`,y),{llmContent:y,returnDisplay:"Content processed from prompt."}}catch(o){let l=`Error processing web content for prompt "${r.substring(0,50)}...": ${sr(o)}`;return console.error(l,o),{llmContent:`Error: ${l}`,returnDisplay:`Error: ${l}`}}}},eJ=class t extends xo{config;static Name="web_fetch";constructor(e){super(t.Name,"WebFetch","Processes content from URL(s), including local and private network addresses (e.g., localhost), embedded in a prompt. Include up to 20 URLs and instructions (e.g., summarize, extract specific data) directly in the 'prompt' parameter.",Bo.Fetch,{properties:{prompt:{description:'A comprehensive prompt that includes the URL(s) (up to 20) to fetch and specific instructions on how to process their content (e.g., "Summarize https://example.com/article and extract key points from https://another.com/data"). Must contain as least one URL starting with http:// or https://.',type:"string"}},required:["prompt"],type:"object"}),this.config=e;let r=e.getProxy();r&&(0,Kme.setGlobalDispatcher)(new Kme.ProxyAgent(r))}validateToolParams(e){let r=ql.validate(this.schema.parametersJsonSchema,e);return r||(!e.prompt||e.prompt.trim()===""?"The 'prompt' parameter cannot be empty and must contain URL(s) and instructions.":!e.prompt.includes("http://")&&!e.prompt.includes("https://")?"The 'prompt' must contain at least one valid URL (starting with http:// or https://).":null)}createInvocation(e){return new yHe(this.config,e)}}});var Jme,MKt=Oe(()=>{"use strict";Jme=class{apiKey;baseUrl;constructor(e,r="https://google.serper.dev"){this.apiKey=e,this.baseUrl=r}buildAdvancedQuery(e){let r=e.q.trim().replace(/\s+/g," ");if(e.site&&(r+=` site:${e.site}`),e.filetype&&(r+=` filetype:${e.filetype}`),e.inurl&&(r+=` inurl:${e.inurl}`),e.intitle&&(r+=` intitle:${e.intitle}`),e.related&&(r+=` related:${e.related}`),e.cache&&(r+=` cache:${e.cache}`),e.before&&(r+=` before:${e.before}`),e.after&&(r+=` after:${e.after}`),e.exact&&(r+=` "${e.exact}"`),e.exclude&&(r+=e.exclude.split(",").map(n=>` -${n.trim()}`).join("")),e.or){let n=e.or.split(",").map(i=>i.trim()).join(" OR ");r+=` (${n})`}return r.trim()}async search(e,r){let n=this.buildAdvancedQuery(e),i={...e,q:n},a=await fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i),signal:r});if(!a.ok){let s=await a.text();throw new Error(`Serper API error: ${a.status} ${a.statusText} - ${s}`)}return await a.json()}}});var tJ,LKt=Oe(()=>{"use strict";tJ=class t{static ghAuthToken;static setupGhAuthToken(e){t.ghAuthToken=e}static async getConfig(){let r=process.env.KODA_WEB_SEARCH_BASE_URL||"https://api.kodacode.ru/dev/web_search",n=t.ghAuthToken||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN||"";if(!n)throw new Error("Web search requires Koda to be authenticated to Github");return{apiKey:n,baseUrl:r,language:process.env.KODA_WEB_SEARCH_LANGUAGE||"ru",location:process.env.KODA_WEB_SEARCH_LOCATION||"ru",numResults:1}}}});var CHe,rJ,_He=Oe(()=>{"use strict";ZA();$1();ed();MKt();LKt();CHe=class extends rl{constructor(e){super(e)}getDescription(){return`Searching the web for: "${this.params.query}"`}async execute(e){try{let r=await tJ.getConfig(),n=new Jme(r.apiKey,r.baseUrl),i={q:this.params.query,num:r.numResults??1,gl:r.location??"us",hl:r.language??"en"},s=(await n.search(i,e)).organic??[];if(s.length===0)return{llmContent:`No search results found for query: "${this.params.query}"`,returnDisplay:"No information found.",results:[]};let o=this.formatResults(s),l=o.map((u,c)=>`${`Search Result ${c+1}`}
853
+ ":`,y),{llmContent:y,returnDisplay:"Content processed from prompt."}}catch(o){let l=`Error processing web content for prompt "${r.substring(0,50)}...": ${sr(o)}`;return console.error(l,o),{llmContent:`Error: ${l}`,returnDisplay:`Error: ${l}`}}}},eJ=class t extends xo{config;static Name="web_fetch";constructor(e){super(t.Name,"WebFetch","Processes content from URL(s), including local and private network addresses (e.g., localhost), embedded in a prompt. Include up to 20 URLs and instructions (e.g., summarize, extract specific data) directly in the 'prompt' parameter.",Bo.Fetch,{properties:{prompt:{description:'A comprehensive prompt that includes the URL(s) (up to 20) to fetch and specific instructions on how to process their content (e.g., "Summarize https://example.com/article and extract key points from https://another.com/data"). Must contain as least one URL starting with http:// or https://.',type:"string"}},required:["prompt"],type:"object"}),this.config=e;let r=e.getProxy();r&&(0,Kme.setGlobalDispatcher)(new Kme.ProxyAgent(r))}validateToolParams(e){let r=ql.validate(this.schema.parametersJsonSchema,e);return r||(!e.prompt||e.prompt.trim()===""?"The 'prompt' parameter cannot be empty and must contain URL(s) and instructions.":!e.prompt.includes("http://")&&!e.prompt.includes("https://")?"The 'prompt' must contain at least one valid URL (starting with http:// or https://).":null)}createInvocation(e){return new yHe(this.config,e)}}});var Jme,MKt=Oe(()=>{"use strict";Jme=class{apiKey;baseUrl;constructor(e,r="https://google.serper.dev"){this.apiKey=e,this.baseUrl=r}buildAdvancedQuery(e){let r=e.q.trim().replace(/\s+/g," ");if(e.site&&(r+=` site:${e.site}`),e.filetype&&(r+=` filetype:${e.filetype}`),e.inurl&&(r+=` inurl:${e.inurl}`),e.intitle&&(r+=` intitle:${e.intitle}`),e.related&&(r+=` related:${e.related}`),e.cache&&(r+=` cache:${e.cache}`),e.before&&(r+=` before:${e.before}`),e.after&&(r+=` after:${e.after}`),e.exact&&(r+=` "${e.exact}"`),e.exclude&&(r+=e.exclude.split(",").map(n=>` -${n.trim()}`).join("")),e.or){let n=e.or.split(",").map(i=>i.trim()).join(" OR ");r+=` (${n})`}return r.trim()}async search(e,r){let n=this.buildAdvancedQuery(e),i={...e,q:n},a=await fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i),signal:r});if(!a.ok){let s=await a.text();throw new Error(`Serper API error: ${a.status} ${a.statusText} - ${s}`)}return await a.json()}}});var tJ,LKt=Oe(()=>{"use strict";tJ=class t{static ghAuthToken;static setupGhAuthToken(e){t.ghAuthToken=e}static async getConfig(){let r=process.env.KODA_WEB_SEARCH_BASE_URL||"https://api.kodacode.ru/web_search",n=t.ghAuthToken||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN||"";if(!n)throw new Error("Web search requires Koda to be authenticated to Github");return{apiKey:n,baseUrl:r,language:process.env.KODA_WEB_SEARCH_LANGUAGE||"ru",location:process.env.KODA_WEB_SEARCH_LOCATION||"ru",numResults:1}}}});var CHe,rJ,_He=Oe(()=>{"use strict";ZA();$1();ed();MKt();LKt();CHe=class extends rl{constructor(e){super(e)}getDescription(){return`Searching the web for: "${this.params.query}"`}async execute(e){try{let r=await tJ.getConfig(),n=new Jme(r.apiKey,r.baseUrl),i={q:this.params.query,num:r.numResults??1,gl:r.location??"us",hl:r.language??"en"},s=(await n.search(i,e)).organic??[];if(s.length===0)return{llmContent:`No search results found for query: "${this.params.query}"`,returnDisplay:"No information found.",results:[]};let o=this.formatResults(s),l=o.map((u,c)=>`${`Search Result ${c+1}`}
854
854
  Title: ${u.title}
855
855
  URL: ${u.url}
856
856
  Snippet: ${u.snippet}`).join(`
@@ -1416,7 +1416,7 @@ ${t}`:t}var nJt=Oe(()=>{"use strict";});function iJt(t,e){if(e<=0||e>=1)throw ne
1416
1416
  email = gemini-cli@google.com
1417
1417
  [commit]
1418
1418
  gpgsign = false
1419
- `);let i=OGe(e);await i.checkIsRepo(mJ.IS_REPO_ROOT)||(await i.init(!1,{"--initial-branch":"main"}),await i.commit("Initial commit",{"--allow-empty":null}));let s=lb.join(this.projectRoot,".gitignore"),o=lb.join(e,".gitignore"),l="";try{l=await uR.readFile(s,"utf-8")}catch(u){if(Ns(u)&&u.code!=="ENOENT")throw u}await uR.writeFile(o,l)}get shadowGitRepository(){let e=this.getHistoryDir();return OGe(this.projectRoot).env({GIT_DIR:lb.join(e,".git"),GIT_WORK_TREE:this.projectRoot,HOME:e,XDG_CONFIG_HOME:e})}async getCurrentCommitHash(){return(await this.shadowGitRepository.raw("rev-parse","HEAD")).trim()}async createFileSnapshot(e){let r=this.shadowGitRepository;return await r.add("."),(await r.commit(e)).commit}async restoreProjectFromSnapshot(e){let r=this.shadowGitRepository;await r.raw(["restore","--source",e,"."]),await r.clean("f",["-d"])}}});var XZt,Nhe,Ohe,Fhe,MGe=Oe(()=>{"use strict";Obe();bT();p_();Er();XZt=Ve(Y1(),1);Fbe();(function(t){t.GCP="gcp",t.LOCAL="local"})(Nhe||(Nhe={}));Ohe=Nhe.LOCAL,Fhe="http://localhost:4317"});function LGe(){let t=["www-browser"],e=process.env.BROWSER;if(e&&t.includes(e)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let r=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(a=>!!process.env[a])||r&&process.platform!=="linux")}var PGe=Oe(()=>{"use strict";});function ZZt(t){if(t){let n=t.trim();return n.endsWith("/")?n.slice(0,-1):n}let r=process.env.KODA_DEFAULT_API_BASE||process.env.KODA_API_BASE||(!0?"https://api.kodacode.ru/dev/v1":"https://api.kodacode.ru/v1");return r.endsWith("/")?r.slice(0,-1):r}function eer(t){try{let e=new URL(t).hostname;if(e==="api.kodacode.ru"||e.endsWith(".kodacode.ru"))return process.env.KODA_FORCE_AUTH!=="true"}catch{}return!1}async function mU(t){let e=ZZt(t?.baseUrl),r=`${e}/models`,n={Accept:"application/json","Accept-Encoding":"identity"},i=eer(e),a=t?.apiKey||process.env.KODA_API_KEY||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN;!i&&a&&(n.Authorization=`Bearer ${a}`);let s=await fetch(r,{headers:n});if(!s.ok)throw new Error(`Failed to list models: ${s.status} ${s.statusText}`);let o=await s.json(),l=Array.isArray(o.data)?o.data:[],u=Array.isArray(o.koda_data)?o.koda_data:[],d=[...t?.includeDefaults===!1?[]:rNn.map(h=>{if(!h.id)return h;let f=h.id.toLowerCase(),E=u.find(y=>{if(!nNn(y))return!1;let g=y.id;return typeof g=="string"&&g.toLowerCase()===f});return E&&typeof E.context_length=="number"?{...h,context_length:E.context_length}:h}),...l].map(h=>h?.id).filter(h=>typeof h=="string"&&h.length>0);return Array.from(new Set(d)).sort((h,f)=>h.localeCompare(f))}function nNn(t){if(!t)return!1;let e=(t.id??"").toLowerCase(),r=(t.owned_by??"").toLowerCase();return e.includes("koda")||r==="koda"}async function Mhe(){let t=ZZt(),e=`${t}/models`,r={Accept:"application/json","Accept-Encoding":"identity"},n=eer(t),i=process.env.KODA_API_KEY||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN;!n&&i&&(r.Authorization=`Bearer ${i}`);try{let a=await fetch(e,{headers:r});if(!a.ok){console.warn(`Failed to fetch model context lengths: ${a.status} ${a.statusText}`),sJ([{id:"KodaAgent",context_length:122e3}]);return}let s=await a.json(),o=Array.isArray(s.data)?s.data:[],l=Array.isArray(s.koda_data)?s.koda_data:[];l.some(c=>c.id&&c.id.toLowerCase()==="kodaagent")||l.push({id:"KodaAgent",owned_by:"z-ai",context_length:122e3}),sJ([...o,...l])}catch(a){console.warn("Error fetching model context lengths from API:",a),sJ([{id:"KodaAgent",context_length:122e3}])}}var rNn,Lhe=Oe(()=>{"use strict";ihe();rNn=[{id:"KodaAgent",owned_by:"z-ai",context_length:122e3}]});import*as O7 from"fs";import*as F7 from"path";var Phe,ter=Oe(()=>{"use strict";ed();Phe=class{directories=new Set;initialDirectories;constructor(e,r=[]){this.addDirectory(e);for(let n of r)this.addDirectory(n);this.initialDirectories=new Set(this.directories)}addDirectory(e,r=process.cwd()){this.directories.add(this.resolveAndValidateDir(e,r))}resolveAndValidateDir(e,r=process.cwd()){let n=F7.isAbsolute(e)?e:F7.resolve(r,e);if(!O7.existsSync(n))throw new Error(`Directory does not exist: ${n}`);if(!O7.statSync(n).isDirectory())throw new Error(`Path is not a directory: ${n}`);return O7.realpathSync(n)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){this.directories.clear();for(let r of e)this.addDirectory(r)}isPathWithinWorkspace(e){try{let r=this.fullyResolvedPath(e);for(let n of this.directories)if(this.isPathWithinRoot(r,n))return!0;return!1}catch{return!1}}fullyResolvedPath(e){try{return O7.realpathSync(e)}catch(r){if(Ns(r)&&r.code==="ENOENT"&&r.path&&!this.isFileSymlink(r.path))return r.path;throw r}}isPathWithinRoot(e,r){let n=F7.relative(r,e);return!n.startsWith(`..${F7.sep}`)&&n!==".."&&!F7.isAbsolute(n)}isFileSymlink(e){try{return!O7.readlinkSync(e).endsWith("/")}catch{return!1}}}});import*as Qhe from"node:path";import rer from"node:process";var qa,hU,lB,CJ,hW,cR,HE=Oe(()=>{"use strict";G4();$Bt();tOe();B1e();GQ();mz();Z1e();xz();Sfe();Sz();vHe();bz();yB();_He();OHe();GHe();FGe();ef();MGe();Jw();j$();PGe();Lhe();Cz();bT();p_();ter();(function(t){t.DEFAULT="default",t.AUTO_EDIT="autoEdit",t.YOLO="yolo"})(qa||(qa={}));hU={respectGitIgnore:!1,respectKodaIgnore:!0},lB={respectGitIgnore:!0,respectKodaIgnore:!0},CJ=class{command;args;env;cwd;url;httpUrl;headers;tcp;timeout;trust;description;includeTools;excludeTools;extensionName;oauth;authProviderType;constructor(e,r,n,i,a,s,o,l,u,c,d,h,f,E,y,g){this.command=e,this.args=r,this.env=n,this.cwd=i,this.url=a,this.httpUrl=s,this.headers=o,this.tcp=l,this.timeout=u,this.trust=c,this.description=d,this.includeTools=h,this.excludeTools=f,this.extensionName=E,this.oauth=y,this.authProviderType=g}};(function(t){t.DYNAMIC_DISCOVERY="dynamic_discovery",t.GOOGLE_CREDENTIALS="google_credentials"})(hW||(hW={}));cR=class{toolRegistry;promptRegistry;sessionId;contentGeneratorConfig;embeddingModel;sandbox;targetDir;workspaceContext;debugMode;question;fullContext;coreTools;excludeTools;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;userMemory;geminiMdFileCount;approvalMode;showMemoryUsage;accessibility;telemetrySettings;usageStatisticsEnabled;geminiClient;fileFiltering;fileDiscoveryService=null;gitService=void 0;checkpointing;proxy;cwd;bugCommand;model;extensionContextFilePaths;noBrowser;folderTrustFeature;folderTrust;ideMode;ideClient;inFallbackMode=!1;maxSessionTurns;listExtensions;_extensions;_blockedMcpServers;flashFallbackHandler;quotaErrorOccurred=!1;summarizeToolOutput;experimentalZedIntegration=!1;loadMemoryFromIncludeDirectories=!1;chatCompression;interactive;trustedFolder;initialized=!1;constructor(e){this.sessionId=e.sessionId,this.embeddingModel=e.embeddingModel??jO,this.sandbox=e.sandbox,this.targetDir=Qhe.resolve(e.targetDir),this.workspaceContext=new Phe(this.targetDir,e.includeDirectories??[]),this.debugMode=e.debugMode,this.question=e.question,this.fullContext=e.fullContext??!1,this.coreTools=e.coreTools,this.excludeTools=e.excludeTools,this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.approvalMode=e.approvalMode??qa.DEFAULT,this.showMemoryUsage=e.showMemoryUsage??!1,this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??Ohe,otlpEndpoint:e.telemetry?.otlpEndpoint??Fhe,logPrompts:e.telemetry?.logPrompts??!0,outfile:e.telemetry?.outfile},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!0,this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectKodaIgnore:e.fileFiltering?.respectKodaIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0},this.checkpointing=e.checkpointing??!1,this.proxy=e.proxy,this.cwd=e.cwd??rer.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.model=e.model,this.extensionContextFilePaths=e.extensionContextFilePaths??[],this.maxSessionTurns=e.maxSessionTurns??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.listExtensions=e.listExtensions??!1,this._extensions=e.extensions??[],this._blockedMcpServers=e.blockedMcpServers??[],this.noBrowser=e.noBrowser??!1,this.summarizeToolOutput=e.summarizeToolOutput,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.ideClient=vz.getInstance(),this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,e.contextFileName&&gB(e.contextFileName),this.telemetrySettings.enabled&&vle(this),this.getUsageStatisticsEnabled()?ac.getInstance(this)?.logStartSessionEvent(new YO(this)):console.log("Data collection is disabled.")}async initialize(){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.getFileService(),this.getCheckpointingEnabled()&&await this.getGitService(),await Mhe(),this.promptRegistry=new qde,this.toolRegistry=await this.createToolRegistry()}async refreshAuth(e){let r=[];this.geminiClient&&this.geminiClient.isInitialized()&&(r=this.geminiClient.getHistory());let n=BRe(this,e),i=new uJ(this);await i.initialize(n);let a=this.contentGeneratorConfig?.authType===ln.LOGIN_WITH_GITHUB&&e===ln.LOGIN_WITH_GITHUB;this.contentGeneratorConfig=n,this.geminiClient=i,r.length>0&&this.geminiClient.setHistory(r,{stripThoughts:a}),this.inFallbackMode=!1}getSessionId(){return this.sessionId}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getContentGeneratorConfig(){return this.contentGeneratorConfig}getModel(){let e=this.contentGeneratorConfig?.model||this.model;return typeof e=="object"&&e!==null&&"name"in e?e.name||this.model:e}setModel(e){typeof e=="object"&&e!==null&&"name"in e&&(e=e.name),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e)}isInFallbackMode(){return this.inFallbackMode}setFallbackMode(e){this.inFallbackMode=e}setFlashFallbackHandler(e){this.flashFallbackHandler=e}getMaxSessionTurns(){return this.maxSessionTurns}setQuotaErrorOccurred(e){this.quotaErrorOccurred=e}getQuotaErrorOccurred(){return this.quotaErrorOccurred}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),r=rer.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!r&&r.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getProjectRoot(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return Promise.resolve(this.toolRegistry)}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getFullContext(){return this.fullContext}getCoreTools(){return this.coreTools}getExcludeTools(){return this.excludeTools}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}getMcpServers(){return this.mcpServers}getUserMemory(){return this.userMemory}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}getApprovalMode(){return this.approvalMode}setApprovalMode(e){this.approvalMode=e}getShowMemoryUsage(){return this.showMemoryUsage}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??Fhe}getTelemetryTarget(){return this.telemetrySettings.target??Ohe}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGeminiClient(){return this.geminiClient}getGeminiDir(){return Qhe.join(this.targetDir,Ph)}getProjectTempDir(){return cv(this.getProjectRoot())}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectKodaIgnore(){return this.fileFiltering.respectKodaIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectKodaIgnore:this.fileFiltering.respectKodaIgnore}}getCheckpointingEnabled(){return this.checkpointing}getProxy(){return this.proxy}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new iR(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionContextFilePaths(){return this.extensionContextFilePaths}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getListExtensions(){return this.listExtensions}getExtensions(){return this._extensions}getBlockedMcpServers(){return this._blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!LGe()}getSummarizeToolOutputConfig(){return this.summarizeToolOutput}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}isTrustedFolder(){return this.trustedFolder}setIdeMode(e){this.ideMode=e}async setIdeModeAndSyncConnection(e){this.ideMode=e,e?(await this.ideClient.connect(),AL(this,new d_(c_.SESSION))):await this.ideClient.disconnect()}getIdeClient(){return this.ideClient}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}async getGitService(){return this.gitService||(this.gitService=new N7(this.targetDir),await this.gitService.initialize()),this.gitService}async createToolRegistry(){let e=new gW(this),r=(n,...i)=>{let a=n.name,s=n.Name||a,o=this.getCoreTools(),l=this.getExcludeTools(),u=!1;o===void 0?u=!0:u=o.some(c=>c===a||c===s||c.startsWith(`${a}(`)||c.startsWith(`${s}(`)),(l?.includes(a)||l?.includes(s))&&(u=!1),u&&e.registerTool(new n(...i))};return r(IS,this),r(ul,this),r(_6,this),r(Lh,this),r(h0,this),r(yc,this),r(eJ,this),r(Qh,this),r(pl,this),r(u7),r(rJ,this),await e.discoverAllTools(),e}}});import khe from"node:path";import{promises as m2}from"node:fs";function ner(t){return encodeURIComponent(t)}function pR(t){try{return decodeURIComponent(t)}catch{return t.replace(/%([0-9A-F]{2})/g,(r,n)=>String.fromCharCode(parseInt(n,16)))}}var iNn,AU,dR,ier=Oe(()=>{"use strict";ef();iNn="logs.json";(function(t){t.USER="user"})(AU||(AU={}));dR=class{geminiDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];constructor(e){this.sessionId=e}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await m2.readFile(this.logFilePath,"utf-8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(console.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return console.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw console.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let r=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await m2.rename(this.logFilePath,r),console.debug(`Backed up corrupted log file to ${r}`)}catch{}}async initialize(){if(!this.initialized){this.geminiDir=cv(process.cwd()),this.logFilePath=khe.join(this.geminiDir,iNn);try{await m2.mkdir(this.geminiDir,{recursive:!0});let e=!0;try{await m2.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await m2.writeFile(this.logFilePath,"[]","utf-8");let r=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=r.length>0?Math.max(...r.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){console.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw console.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let r;try{r=await this._readLogFile()}catch(s){throw console.debug("Critical error reading log file before append:",s),s}let n=r.filter(s=>s.sessionId===e.sessionId),i=n.length>0?Math.max(...n.map(s=>s.messageId))+1:0;if(e.messageId=i,r.some(s=>s.sessionId===e.sessionId&&s.messageId===e.messageId&&s.timestamp===e.timestamp&&s.message===e.message))return console.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=r,null;r.push(e);try{return await m2.writeFile(this.logFilePath,JSON.stringify(r,null,2),"utf-8"),this.logs=r,e}catch(s){throw console.debug("Error writing to log file:",s),s}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type===AU.USER).sort((e,r)=>{let n=new Date(e.timestamp).getTime();return new Date(r.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,r){if(!this.initialized||this.sessionId===void 0){console.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:r,timestamp:new Date().toISOString()};try{let i=await this._updateLogFile(n);i&&(this.messageId=i.messageId+1)}catch{}}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.geminiDir)throw new Error("Checkpoint file path not set.");let r=ner(e);return khe.join(this.geminiDir,`checkpoint-${r}.json`)}async _getCheckpointPath(e){let r=this._checkpointPath(e);try{return await m2.access(r),r}catch(i){if(i.code!=="ENOENT")throw i}let n=khe.join(this.geminiDir,`checkpoint-${e}.json`);try{return await m2.access(n),n}catch(i){if(i.code!=="ENOENT")throw i}return r}async saveCheckpoint(e,r){if(!this.initialized){console.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(r);try{await m2.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(i){console.error("Error writing to checkpoint file:",i)}}async loadCheckpoint(e){if(!this.initialized)return console.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let r=await this._getCheckpointPath(e);try{let n=await m2.readFile(r,"utf-8"),i=JSON.parse(n);return Array.isArray(i)?i:(console.warn(`Checkpoint file at ${r} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return n.code==="ENOENT"?[]:(console.error(`Failed to read or parse checkpoint file ${r}:`,n),[])}}async deleteCheckpoint(e){if(!this.initialized||!this.geminiDir)return console.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let r=!1,n=this._checkpointPath(e);try{await m2.unlink(n),r=!0}catch(a){if(a.code!=="ENOENT")throw console.error(`Failed to delete checkpoint file ${n}:`,a),a}let i=khe.join(this.geminiDir,`checkpoint-${e}.json`);if(n!==i)try{await m2.unlink(i),r=!0}catch(a){if(a.code!=="ENOENT")throw console.error(`Failed to delete checkpoint file ${i}:`,a),a}return r}async checkpointExists(e){if(!this.initialized)throw new Error("Logger not initialized. Cannot check for checkpoint existence.");let r;try{return r=await this._getCheckpointPath(e),await m2.access(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw console.error(`Failed to check checkpoint existence for ${r??`path for tag "${e}"`}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.sessionId=void 0,this.messageId=0}}});function aNn(t){return pfe(t,{verbose:!0})}var aer=Oe(()=>{"use strict";GMe();});import{execSync as ser,spawn as sNn}from"child_process";function oer(t){return["vscode","vscodium","windsurf","cursor","vim","neovim","zed","emacs","intellij","webstorm","pycharm","phpstorm","rubymine","clion","goland","datagrip","rider","androidstudio"].includes(t)}function ler(t){try{return ser(process.platform==="win32"?`where.exe ${t}`:`command -v ${t}`,{stdio:"ignore"}),!0}catch{return!1}}function gU(t){let e=uer[t];return(process.platform==="win32"?e.win32:e.default).some(n=>ler(n))}function EU(t){let e=!process.env.SANDBOX;return["vscode","vscodium","windsurf","cursor","zed","intellij","webstorm","pycharm","phpstorm","rubymine","clion","goland","datagrip","rider","androidstudio"].includes(t)?e:!0}function _J(t){return t&&oer(t)?gU(t)&&EU(t):!1}function cer(t,e,r){if(!oer(r))return null;let n=uer[r],i=process.platform==="win32"?n.win32:n.default,a=i.slice(0,-1).find(s=>ler(s))||i[i.length-1];switch(r){case"vscode":case"vscodium":case"windsurf":case"cursor":case"zed":return{command:a,args:["--wait","--diff",t,e]};case"intellij":case"webstorm":case"pycharm":case"phpstorm":case"rubymine":case"clion":case"goland":case"datagrip":case"rider":case"androidstudio":return{command:a,args:["--wait","--diff",t,e]};case"vim":case"neovim":return{command:a,args:["-d","-i","NONE","-c","wincmd h | set readonly | wincmd l","-c","highlight DiffAdd cterm=bold ctermbg=22 guibg=#005f00 | highlight DiffChange cterm=bold ctermbg=24 guibg=#005f87 | highlight DiffText ctermbg=21 guibg=#0000af | highlight DiffDelete ctermbg=52 guibg=#5f0000","-c","set showtabline=2 | set tabline=[Instructions]\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)","-c","wincmd h | setlocal statusline=OLD\\ FILE","-c","wincmd l | setlocal statusline=%#StatusBold#NEW\\ FILE\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)","-c","autocmd WinClosed * wqa",t,e]};case"emacs":return{command:"emacs",args:["--eval",`(ediff "${t}" "${e}")`]};default:return null}}async function QGe(t,e,r,n){let i=cer(t,e,r);if(!i){console.error("No diff tool available. Install a supported editor.");return}try{switch(r){case"vscode":case"vscodium":case"windsurf":case"cursor":case"zed":case"intellij":case"webstorm":case"pycharm":case"phpstorm":case"rubymine":case"clion":case"goland":case"datagrip":case"rider":case"androidstudio":return new Promise((a,s)=>{let o=sNn(i.command,i.args,{stdio:"inherit",shell:!0});o.on("close",l=>{l===0?a():s(new Error(`${r} exited with code ${l}`))}),o.on("error",l=>{s(l)})});case"vim":case"emacs":case"neovim":{let a=process.platform==="win32"?`${i.command} ${i.args.join(" ")}`:`${i.command} ${i.args.map(s=>`"${s}"`).join(" ")}`;try{ser(a,{stdio:"inherit",encoding:"utf8"})}catch(s){console.error("Error in onEditorClose callback:",s)}finally{n()}break}default:throw new Error(`Unsupported editor: ${r}`)}}catch(a){console.error(a)}}var uer,kGe=Oe(()=>{"use strict";uer={vscode:{win32:["code.cmd"],default:["code"]},vscodium:{win32:["codium.cmd"],default:["codium"]},windsurf:{win32:["windsurf"],default:["windsurf"]},cursor:{win32:["cursor"],default:["cursor"]},vim:{win32:["vim"],default:["vim"]},neovim:{win32:["nvim"],default:["nvim"]},zed:{win32:["zed"],default:["zed","zeditor"]},emacs:{win32:["emacs.exe"],default:["emacs"]},intellij:{win32:["idea64.exe"],default:["idea"]},webstorm:{win32:["webstorm64.exe"],default:["webstorm"]},pycharm:{win32:["pycharm64.exe"],default:["pycharm"]},phpstorm:{win32:["phpstorm64.exe"],default:["phpstorm"]},rubymine:{win32:["rubymine64.exe"],default:["rubymine"]},clion:{win32:["clion64.exe"],default:["clion"]},goland:{win32:["goland64.exe"],default:["goland"]},datagrip:{win32:["datagrip64.exe"],default:["datagrip"]},rider:{win32:["rider64.exe"],default:["rider"]},androidstudio:{win32:["studio64.exe"],default:["studio"]}}});import oNn from"os";import yU from"path";import ub from"fs";function UGe(t){return"getModifyContext"in t}function lNn(t,e,r){let n=oNn.tmpdir(),i=yU.join(n,"gemini-cli-tool-modify-diffs");ub.existsSync(i)||ub.mkdirSync(i,{recursive:!0});let a=yU.extname(r),s=yU.basename(r,a),o=Date.now(),l=yU.join(i,`gemini-cli-modify-${s}-old-${o}${a}`),u=yU.join(i,`gemini-cli-modify-${s}-new-${o}${a}`);return ub.writeFileSync(l,t,"utf8"),ub.writeFileSync(u,e,"utf8"),{oldPath:l,newPath:u}}function uNn(t,e,r,n){let i="",a="";try{i=ub.readFileSync(t,"utf8")}catch(l){if(!Ns(l)||l.code!=="ENOENT")throw l;i=""}try{a=ub.readFileSync(e,"utf8")}catch(l){if(!Ns(l)||l.code!=="ENOENT")throw l;a=""}let s=n.createUpdatedParams(i,a,r),o=D6(yU.basename(n.getFilePath(r)),i,a,"Current","Proposed",S6);return{updatedParams:s,updatedDiff:o}}function cNn(t,e){try{ub.unlinkSync(t)}catch{console.error(`Error deleting temp diff file: ${t}`)}try{ub.unlinkSync(e)}catch{console.error(`Error deleting temp diff file: ${e}`)}}async function der(t,e,r,n,i){let a=await e.getCurrentContent(t),s=await e.getProposedContent(t),{oldPath:o,newPath:l}=lNn(a,s,e.getFilePath(t));try{return await QGe(o,l,r,i),uNn(o,l,t,e)}finally{cNn(o,l)}}var per=Oe(()=>{"use strict";kGe();fB();yz();ed();});function vU(t,e,r){return{functionResponse:{id:t,name:e,response:{output:r}}}}function _U(t,e,r){let n=Array.isArray(r)&&r.length===1?r[0]:r;if(typeof n=="string")return vU(e,t,n);if(Array.isArray(n))return[vU(e,t,"Tool execution succeeded."),...n];if(n.functionResponse){if(n.functionResponse.response?.content){let i=fUt(n.functionResponse.response.content)||"";return vU(e,t,i)}return n}if(n.inlineData||n.fileData){let i=n.inlineData?.mimeType||n.fileData?.mimeType||"unknown";return[vU(e,t,`Binary content of type ${i} was processed.`),n]}return n.text!==void 0?vU(e,t,n.text):vU(e,t,"Tool execution succeeded.")}var CU,DJ,HGe=Oe(()=>{"use strict";Uhe();Lz();per();fB();CU=(t,e,r)=>({callId:t.callId,error:e,responseParts:{functionResponse:{id:t.callId,name:t.name,response:{error:e.message}}},resultDisplay:e.message,errorType:r}),DJ=class{toolRegistry;toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;onToolCallsUpdate;getPreferredEditor;config;getTerminalSize;onEditorClose;isFinalizingToolCalls=!1;isScheduling=!1;requestQueue=[];constructor(e){this.config=e.config,this.toolRegistry=e.toolRegistry,this.outputUpdateHandler=e.outputUpdateHandler,this.onAllToolCallsComplete=e.onAllToolCallsComplete,this.onToolCallsUpdate=e.onToolCallsUpdate,this.getPreferredEditor=e.getPreferredEditor,this.getTerminalSize=e.getTerminalSize,this.onEditorClose=e.onEditorClose}setStatusInternal(e,r,n){this.toolCalls=this.toolCalls.map(i=>{if(i.request.callId!==e||i.status==="success"||i.status==="error"||i.status==="cancelled")return i;let a=i.startTime,s=i.tool,o=i.invocation,l=i.outcome;switch(r){case"success":{let u=a?Date.now()-a:void 0;return{request:i.request,tool:s,invocation:o,status:"success",response:n,durationMs:u,outcome:l}}case"error":{let u=a?Date.now()-a:void 0;return{request:i.request,status:"error",tool:s,response:n,durationMs:u,outcome:l}}case"awaiting_approval":return{request:i.request,tool:s,status:"awaiting_approval",confirmationDetails:n,startTime:a,outcome:l,invocation:o};case"scheduled":return{request:i.request,tool:s,status:"scheduled",startTime:a,outcome:l,invocation:o};case"cancelled":{let u=a?Date.now()-a:void 0,c;if(i.status==="awaiting_approval"){let d=i;d.confirmationDetails.type==="edit"&&(c={fileDiff:d.confirmationDetails.fileDiff,fileName:d.confirmationDetails.fileName,originalContent:d.confirmationDetails.originalContent,newContent:d.confirmationDetails.newContent})}return{request:i.request,tool:s,invocation:o,status:"cancelled",response:{callId:i.request.callId,responseParts:{functionResponse:{id:i.request.callId,name:i.request.name,response:{error:`[Operation Cancelled] Reason: ${n}`}}},resultDisplay:c,error:void 0,errorType:void 0},durationMs:u,outcome:l}}case"validating":return{request:i.request,tool:s,status:"validating",startTime:a,outcome:l,invocation:o};case"executing":return{request:i.request,tool:s,status:"executing",startTime:a,outcome:l,invocation:o};default:return r}}),this.notifyToolCallsUpdate(),this.checkAndNotifyCompletion()}setArgsInternal(e,r){this.toolCalls=this.toolCalls.map(n=>{if(n.request.callId!==e||n.status==="error")return n;let i=this.buildInvocation(n.tool,r);if(i instanceof Error){let a=CU(n.request,i,ms.INVALID_TOOL_PARAMS);return{request:{...n.request,args:r},status:"error",tool:n.tool,response:a}}return{...n,request:{...n.request,args:r},invocation:i}})}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(e=>e.status==="executing"||e.status==="awaiting_approval")}buildInvocation(e,r){try{return e.build(r)}catch(n){return n instanceof Error?n:new Error(String(n))}}schedule(e,r){return this.isRunning()||this.isScheduling?new Promise((n,i)=>{let a=()=>{let s=this.requestQueue.findIndex(o=>o.request===e);s>-1&&(this.requestQueue.splice(s,1),i(new Error("Tool call cancelled while in queue.")))};r.addEventListener("abort",a,{once:!0}),this.requestQueue.push({request:e,signal:r,resolve:()=>{r.removeEventListener("abort",a),n()},reject:s=>{r.removeEventListener("abort",a),i(s)}})}):this._schedule(e,r)}async _schedule(e,r){this.isScheduling=!0;try{if(this.isRunning())throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");let n=Array.isArray(e)?e:[e],i=await this.toolRegistry,a=n.map(s=>{let o=i.getTool(s.name);if(!o)return{status:"error",request:s,response:CU(s,new Error(`Tool "${s.name}" not found in registry.`),ms.TOOL_NOT_REGISTERED),durationMs:0};let l=this.buildInvocation(o,s.args);return l instanceof Error?{status:"error",request:s,tool:o,response:CU(s,l,ms.INVALID_TOOL_PARAMS),durationMs:0}:{status:"validating",request:s,tool:o,invocation:l,startTime:Date.now()}});this.toolCalls=this.toolCalls.concat(a),this.notifyToolCallsUpdate();for(let s of a){if(s.status!=="validating")continue;let{request:o,invocation:l}=s;try{if(this.config.getApprovalMode()===qa.YOLO)this.setToolCallOutcome(o.callId,Br.ProceedAlways),this.setStatusInternal(o.callId,"scheduled");else{let u=await l.shouldConfirmExecute(r);if(u){u.type==="edit"&&u.ideConfirmation&&u.ideConfirmation.then(h=>{h.status==="accepted"?this.handleConfirmationResponse(o.callId,u.onConfirm,Br.ProceedOnce,r):this.handleConfirmationResponse(o.callId,u.onConfirm,Br.Cancel,r)});let c=u.onConfirm,d={...u,onConfirm:(h,f)=>this.handleConfirmationResponse(o.callId,c,h,r,f)};this.setStatusInternal(o.callId,"awaiting_approval",d)}else this.setToolCallOutcome(o.callId,Br.ProceedAlways),this.setStatusInternal(o.callId,"scheduled")}}catch(u){this.setStatusInternal(o.callId,"error",CU(o,u instanceof Error?u:new Error(String(u)),ms.UNHANDLED_EXCEPTION))}}this.attemptExecutionOfScheduledCalls(r),this.checkAndNotifyCompletion()}finally{this.isScheduling=!1}}async handleConfirmationResponse(e,r,n,i,a){let s=this.toolCalls.find(o=>o.request.callId===e&&o.status==="awaiting_approval");if(s&&s.status==="awaiting_approval"&&await r(n),this.setToolCallOutcome(e,n),n===Br.Cancel||i.aborted)this.setStatusInternal(e,"cancelled","User did not allow tool call");else if(n===Br.ModifyWithEditor){let o=s;if(UGe(o.tool)){let l=o.tool.getModifyContext(i),u=this.getPreferredEditor();if(!u)return;this.setStatusInternal(e,"awaiting_approval",{...o.confirmationDetails,isModifying:!0});let{updatedParams:c,updatedDiff:d}=await der(o.request.args,l,u,i,this.onEditorClose);this.setArgsInternal(e,c),this.setStatusInternal(e,"awaiting_approval",{...o.confirmationDetails,fileDiff:d,isModifying:!1})}}else a?.newContent&&s&&await this._applyInlineModify(s,a,i),this.setStatusInternal(e,"scheduled");this.attemptExecutionOfScheduledCalls(i)}async _applyInlineModify(e,r,n){if(e.confirmationDetails.type!=="edit"||!UGe(e.tool))return;let i=e.tool.getModifyContext(n),a=await i.getCurrentContent(e.request.args),s=i.createUpdatedParams(a,r.newContent,e.request.args),o=D6(i.getFilePath(e.request.args),a,r.newContent,"Current","Proposed");this.setArgsInternal(e.request.callId,s),this.setStatusInternal(e.request.callId,"awaiting_approval",{...e.confirmationDetails,fileDiff:o})}attemptExecutionOfScheduledCalls(e){this.toolCalls.every(n=>n.status==="scheduled"||n.status==="cancelled"||n.status==="success"||n.status==="error")&&this.toolCalls.filter(i=>i.status==="scheduled").forEach(i=>{if(i.status!=="scheduled")return;let a=i,{callId:s,name:o}=a.request,l=a.invocation;this.setStatusInternal(s,"executing");let u=a.tool.canUpdateOutput&&this.outputUpdateHandler?d=>{this.outputUpdateHandler&&this.outputUpdateHandler(s,d),this.toolCalls=this.toolCalls.map(h=>h.request.callId===s&&h.status==="executing"?{...h,liveOutput:d}:h),this.notifyToolCallsUpdate()}:void 0,c=this.getTerminalSize();l.execute(e,u,c.columns,c.rows).then(async d=>{if(e.aborted){this.setStatusInternal(s,"cancelled","User cancelled tool execution.");return}if(d.error===void 0){let h=_U(o,s,d.llmContent),f={callId:s,responseParts:h,resultDisplay:d.returnDisplay,error:void 0,errorType:void 0};this.setStatusInternal(s,"success",f)}else{let h=new Error(d.error.message),f=CU(a.request,h,d.error.type);this.setStatusInternal(s,"error",f)}}).catch(d=>{this.setStatusInternal(s,"error",CU(a.request,d instanceof Error?d:new Error(String(d)),ms.UNHANDLED_EXCEPTION))})})}async checkAndNotifyCompletion(){let e=this.toolCalls.every(r=>r.status==="success"||r.status==="error"||r.status==="cancelled");if(this.toolCalls.length>0&&e){let r=[...this.toolCalls];this.toolCalls=[];for(let n of r)cE(this.config,new KO(n));if(this.onAllToolCallsComplete&&(this.isFinalizingToolCalls=!0,await this.onAllToolCallsComplete(r),this.isFinalizingToolCalls=!1),this.notifyToolCallsUpdate(),this.requestQueue.length>0){let n=this.requestQueue.shift();this._schedule(n.request,n.signal).then(n.resolve).catch(n.reject)}}}notifyToolCallsUpdate(){this.onToolCallsUpdate&&this.onToolCallsUpdate([...this.toolCalls])}setToolCallOutcome(e,r){this.toolCalls=this.toolCalls.map(n=>n.request.callId!==e?n:{...n,outcome:r})}}});async function GGe(t,e,r,n){let i=r.getTool(e.name),a=Date.now();if(!i){let s=new Error(`Tool "${e.name}" not found in registry.`),o=Date.now()-a;return cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:o,success:!1,error:s.message,prompt_id:e.prompt_id}),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:s.message}}}],resultDisplay:s.message,error:s,errorType:ms.TOOL_NOT_REGISTERED}}try{let s=n??new AbortController().signal,o=await i.buildAndExecute(e.args,s),l=o.llmContent,u=o.returnDisplay,c={};if(o.error===void 0&&typeof u=="object"&&u!==null&&"diffStat"in u){let f=u.diffStat;f&&(c={ai_added_lines:f.ai_added_lines,ai_removed_lines:f.ai_removed_lines,user_added_lines:f.user_added_lines,user_removed_lines:f.user_removed_lines})}let d=Date.now()-a;cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:d,success:o.error===void 0,error:o.error===void 0?void 0:o.error.message,error_type:o.error===void 0?void 0:o.error.type,prompt_id:e.prompt_id,metadata:c,decision:j1.AUTO_ACCEPT});let h=_U(e.name,e.callId,l);return{callId:e.callId,responseParts:h,resultDisplay:u,error:o.error===void 0?void 0:new Error(o.error.message),errorType:o.error===void 0?void 0:o.error.type}}catch(s){let o=s instanceof Error?s:new Error(String(s)),l=Date.now()-a;return cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:l,success:!1,error:o.message,error_type:ms.UNHANDLED_EXCEPTION,prompt_id:e.prompt_id}),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:o.message}}}],resultDisplay:o.message,error:o,errorType:ms.UNHANDLED_EXCEPTION}}}var fer=Oe(()=>{"use strict";Uhe();HGe();Yee();});import mer from"node:fs";function dNn(){try{return mer.statSync("/.dockerenv"),!0}catch{return!1}}function pNn(){try{return mer.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function qGe(){return VGe===void 0&&(VGe=dNn()||pNn()),VGe}var VGe,her=Oe(()=>{});import fNn from"node:fs";function DU(){return $Ge===void 0&&($Ge=mNn()||qGe()),$Ge}var $Ge,mNn,jGe=Oe(()=>{her();mNn=()=>{try{return fNn.statSync("/run/.containerenv"),!0}catch{return!1}}});import ger from"node:process";import hNn from"node:os";import ANn from"node:fs";var Aer,SU,Eer=Oe(()=>{jGe();Aer=()=>{if(ger.platform!=="linux")return!1;if(hNn.release().toLowerCase().includes("microsoft"))return!DU();try{return ANn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!DU():!1}catch{return!1}},SU=ger.env.__IS_WSL_TEST__?Aer:Aer()});function fR(t,e,r){let n=i=>Object.defineProperty(t,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){let i=r();return n(i),i},set(i){n(i)}}),t}var yer=Oe(()=>{});import{promisify as gNn}from"node:util";import ENn from"node:process";import{execFile as yNn}from"node:child_process";async function YGe(){if(ENn.platform!=="darwin")throw new Error("macOS only");let{stdout:t}=await vNn("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(t)?.groups.id??"com.apple.Safari"}var vNn,ver=Oe(()=>{vNn=gNn(yNn)});import CNn from"node:process";import{promisify as _Nn}from"node:util";import{execFile as DNn,execFileSync as vLi}from"node:child_process";async function Cer(t,{humanReadableOutput:e=!0}={}){if(CNn.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],{stdout:n}=await SNn("osascript",["-e",t,r]);return n.trim()}var SNn,_er=Oe(()=>{SNn=_Nn(DNn)});async function WGe(t){return Cer(`tell application "Finder" to set app_path to application file id "${t}" as string
1419
+ `);let i=OGe(e);await i.checkIsRepo(mJ.IS_REPO_ROOT)||(await i.init(!1,{"--initial-branch":"main"}),await i.commit("Initial commit",{"--allow-empty":null}));let s=lb.join(this.projectRoot,".gitignore"),o=lb.join(e,".gitignore"),l="";try{l=await uR.readFile(s,"utf-8")}catch(u){if(Ns(u)&&u.code!=="ENOENT")throw u}await uR.writeFile(o,l)}get shadowGitRepository(){let e=this.getHistoryDir();return OGe(this.projectRoot).env({GIT_DIR:lb.join(e,".git"),GIT_WORK_TREE:this.projectRoot,HOME:e,XDG_CONFIG_HOME:e})}async getCurrentCommitHash(){return(await this.shadowGitRepository.raw("rev-parse","HEAD")).trim()}async createFileSnapshot(e){let r=this.shadowGitRepository;return await r.add("."),(await r.commit(e)).commit}async restoreProjectFromSnapshot(e){let r=this.shadowGitRepository;await r.raw(["restore","--source",e,"."]),await r.clean("f",["-d"])}}});var XZt,Nhe,Ohe,Fhe,MGe=Oe(()=>{"use strict";Obe();bT();p_();Er();XZt=Ve(Y1(),1);Fbe();(function(t){t.GCP="gcp",t.LOCAL="local"})(Nhe||(Nhe={}));Ohe=Nhe.LOCAL,Fhe="http://localhost:4317"});function LGe(){let t=["www-browser"],e=process.env.BROWSER;if(e&&t.includes(e)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let r=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(a=>!!process.env[a])||r&&process.platform!=="linux")}var PGe=Oe(()=>{"use strict";});function ZZt(t){if(t){let n=t.trim();return n.endsWith("/")?n.slice(0,-1):n}let r=process.env.KODA_DEFAULT_API_BASE||process.env.KODA_API_BASE||(!1?"https://api.kodacode.ru/dev/v1":"https://api.kodacode.ru/v1");return r.endsWith("/")?r.slice(0,-1):r}function eer(t){try{let e=new URL(t).hostname;if(e==="api.kodacode.ru"||e.endsWith(".kodacode.ru"))return process.env.KODA_FORCE_AUTH!=="true"}catch{}return!1}async function mU(t){let e=ZZt(t?.baseUrl),r=`${e}/models`,n={Accept:"application/json","Accept-Encoding":"identity"},i=eer(e),a=t?.apiKey||process.env.KODA_API_KEY||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN;!i&&a&&(n.Authorization=`Bearer ${a}`);let s=await fetch(r,{headers:n});if(!s.ok)throw new Error(`Failed to list models: ${s.status} ${s.statusText}`);let o=await s.json(),l=Array.isArray(o.data)?o.data:[],u=Array.isArray(o.koda_data)?o.koda_data:[],d=[...t?.includeDefaults===!1?[]:rNn.map(h=>{if(!h.id)return h;let f=h.id.toLowerCase(),E=u.find(y=>{if(!nNn(y))return!1;let g=y.id;return typeof g=="string"&&g.toLowerCase()===f});return E&&typeof E.context_length=="number"?{...h,context_length:E.context_length}:h}),...l].map(h=>h?.id).filter(h=>typeof h=="string"&&h.length>0);return Array.from(new Set(d)).sort((h,f)=>h.localeCompare(f))}function nNn(t){if(!t)return!1;let e=(t.id??"").toLowerCase(),r=(t.owned_by??"").toLowerCase();return e.includes("koda")||r==="koda"}async function Mhe(){let t=ZZt(),e=`${t}/models`,r={Accept:"application/json","Accept-Encoding":"identity"},n=eer(t),i=process.env.KODA_API_KEY||process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN;!n&&i&&(r.Authorization=`Bearer ${i}`);try{let a=await fetch(e,{headers:r});if(!a.ok){console.warn(`Failed to fetch model context lengths: ${a.status} ${a.statusText}`),sJ([{id:"KodaAgent",context_length:122e3}]);return}let s=await a.json(),o=Array.isArray(s.data)?s.data:[],l=Array.isArray(s.koda_data)?s.koda_data:[];l.some(c=>c.id&&c.id.toLowerCase()==="kodaagent")||l.push({id:"KodaAgent",owned_by:"z-ai",context_length:122e3}),sJ([...o,...l])}catch(a){console.warn("Error fetching model context lengths from API:",a),sJ([{id:"KodaAgent",context_length:122e3}])}}var rNn,Lhe=Oe(()=>{"use strict";ihe();rNn=[{id:"KodaAgent",owned_by:"z-ai",context_length:122e3}]});import*as O7 from"fs";import*as F7 from"path";var Phe,ter=Oe(()=>{"use strict";ed();Phe=class{directories=new Set;initialDirectories;constructor(e,r=[]){this.addDirectory(e);for(let n of r)this.addDirectory(n);this.initialDirectories=new Set(this.directories)}addDirectory(e,r=process.cwd()){this.directories.add(this.resolveAndValidateDir(e,r))}resolveAndValidateDir(e,r=process.cwd()){let n=F7.isAbsolute(e)?e:F7.resolve(r,e);if(!O7.existsSync(n))throw new Error(`Directory does not exist: ${n}`);if(!O7.statSync(n).isDirectory())throw new Error(`Path is not a directory: ${n}`);return O7.realpathSync(n)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){this.directories.clear();for(let r of e)this.addDirectory(r)}isPathWithinWorkspace(e){try{let r=this.fullyResolvedPath(e);for(let n of this.directories)if(this.isPathWithinRoot(r,n))return!0;return!1}catch{return!1}}fullyResolvedPath(e){try{return O7.realpathSync(e)}catch(r){if(Ns(r)&&r.code==="ENOENT"&&r.path&&!this.isFileSymlink(r.path))return r.path;throw r}}isPathWithinRoot(e,r){let n=F7.relative(r,e);return!n.startsWith(`..${F7.sep}`)&&n!==".."&&!F7.isAbsolute(n)}isFileSymlink(e){try{return!O7.readlinkSync(e).endsWith("/")}catch{return!1}}}});import*as Qhe from"node:path";import rer from"node:process";var qa,hU,lB,CJ,hW,cR,HE=Oe(()=>{"use strict";G4();$Bt();tOe();B1e();GQ();mz();Z1e();xz();Sfe();Sz();vHe();bz();yB();_He();OHe();GHe();FGe();ef();MGe();Jw();j$();PGe();Lhe();Cz();bT();p_();ter();(function(t){t.DEFAULT="default",t.AUTO_EDIT="autoEdit",t.YOLO="yolo"})(qa||(qa={}));hU={respectGitIgnore:!1,respectKodaIgnore:!0},lB={respectGitIgnore:!0,respectKodaIgnore:!0},CJ=class{command;args;env;cwd;url;httpUrl;headers;tcp;timeout;trust;description;includeTools;excludeTools;extensionName;oauth;authProviderType;constructor(e,r,n,i,a,s,o,l,u,c,d,h,f,E,y,g){this.command=e,this.args=r,this.env=n,this.cwd=i,this.url=a,this.httpUrl=s,this.headers=o,this.tcp=l,this.timeout=u,this.trust=c,this.description=d,this.includeTools=h,this.excludeTools=f,this.extensionName=E,this.oauth=y,this.authProviderType=g}};(function(t){t.DYNAMIC_DISCOVERY="dynamic_discovery",t.GOOGLE_CREDENTIALS="google_credentials"})(hW||(hW={}));cR=class{toolRegistry;promptRegistry;sessionId;contentGeneratorConfig;embeddingModel;sandbox;targetDir;workspaceContext;debugMode;question;fullContext;coreTools;excludeTools;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;userMemory;geminiMdFileCount;approvalMode;showMemoryUsage;accessibility;telemetrySettings;usageStatisticsEnabled;geminiClient;fileFiltering;fileDiscoveryService=null;gitService=void 0;checkpointing;proxy;cwd;bugCommand;model;extensionContextFilePaths;noBrowser;folderTrustFeature;folderTrust;ideMode;ideClient;inFallbackMode=!1;maxSessionTurns;listExtensions;_extensions;_blockedMcpServers;flashFallbackHandler;quotaErrorOccurred=!1;summarizeToolOutput;experimentalZedIntegration=!1;loadMemoryFromIncludeDirectories=!1;chatCompression;interactive;trustedFolder;initialized=!1;constructor(e){this.sessionId=e.sessionId,this.embeddingModel=e.embeddingModel??jO,this.sandbox=e.sandbox,this.targetDir=Qhe.resolve(e.targetDir),this.workspaceContext=new Phe(this.targetDir,e.includeDirectories??[]),this.debugMode=e.debugMode,this.question=e.question,this.fullContext=e.fullContext??!1,this.coreTools=e.coreTools,this.excludeTools=e.excludeTools,this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.approvalMode=e.approvalMode??qa.DEFAULT,this.showMemoryUsage=e.showMemoryUsage??!1,this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??Ohe,otlpEndpoint:e.telemetry?.otlpEndpoint??Fhe,logPrompts:e.telemetry?.logPrompts??!0,outfile:e.telemetry?.outfile},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!0,this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectKodaIgnore:e.fileFiltering?.respectKodaIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0},this.checkpointing=e.checkpointing??!1,this.proxy=e.proxy,this.cwd=e.cwd??rer.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.model=e.model,this.extensionContextFilePaths=e.extensionContextFilePaths??[],this.maxSessionTurns=e.maxSessionTurns??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.listExtensions=e.listExtensions??!1,this._extensions=e.extensions??[],this._blockedMcpServers=e.blockedMcpServers??[],this.noBrowser=e.noBrowser??!1,this.summarizeToolOutput=e.summarizeToolOutput,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.ideClient=vz.getInstance(),this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,e.contextFileName&&gB(e.contextFileName),this.telemetrySettings.enabled&&vle(this),this.getUsageStatisticsEnabled()?ac.getInstance(this)?.logStartSessionEvent(new YO(this)):console.log("Data collection is disabled.")}async initialize(){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.getFileService(),this.getCheckpointingEnabled()&&await this.getGitService(),await Mhe(),this.promptRegistry=new qde,this.toolRegistry=await this.createToolRegistry()}async refreshAuth(e){let r=[];this.geminiClient&&this.geminiClient.isInitialized()&&(r=this.geminiClient.getHistory());let n=BRe(this,e),i=new uJ(this);await i.initialize(n);let a=this.contentGeneratorConfig?.authType===ln.LOGIN_WITH_GITHUB&&e===ln.LOGIN_WITH_GITHUB;this.contentGeneratorConfig=n,this.geminiClient=i,r.length>0&&this.geminiClient.setHistory(r,{stripThoughts:a}),this.inFallbackMode=!1}getSessionId(){return this.sessionId}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getContentGeneratorConfig(){return this.contentGeneratorConfig}getModel(){let e=this.contentGeneratorConfig?.model||this.model;return typeof e=="object"&&e!==null&&"name"in e?e.name||this.model:e}setModel(e){typeof e=="object"&&e!==null&&"name"in e&&(e=e.name),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e)}isInFallbackMode(){return this.inFallbackMode}setFallbackMode(e){this.inFallbackMode=e}setFlashFallbackHandler(e){this.flashFallbackHandler=e}getMaxSessionTurns(){return this.maxSessionTurns}setQuotaErrorOccurred(e){this.quotaErrorOccurred=e}getQuotaErrorOccurred(){return this.quotaErrorOccurred}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),r=rer.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!r&&r.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getProjectRoot(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return Promise.resolve(this.toolRegistry)}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getFullContext(){return this.fullContext}getCoreTools(){return this.coreTools}getExcludeTools(){return this.excludeTools}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}getMcpServers(){return this.mcpServers}getUserMemory(){return this.userMemory}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}getApprovalMode(){return this.approvalMode}setApprovalMode(e){this.approvalMode=e}getShowMemoryUsage(){return this.showMemoryUsage}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??Fhe}getTelemetryTarget(){return this.telemetrySettings.target??Ohe}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGeminiClient(){return this.geminiClient}getGeminiDir(){return Qhe.join(this.targetDir,Ph)}getProjectTempDir(){return cv(this.getProjectRoot())}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectKodaIgnore(){return this.fileFiltering.respectKodaIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectKodaIgnore:this.fileFiltering.respectKodaIgnore}}getCheckpointingEnabled(){return this.checkpointing}getProxy(){return this.proxy}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new iR(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionContextFilePaths(){return this.extensionContextFilePaths}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getListExtensions(){return this.listExtensions}getExtensions(){return this._extensions}getBlockedMcpServers(){return this._blockedMcpServers}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!LGe()}getSummarizeToolOutputConfig(){return this.summarizeToolOutput}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}isTrustedFolder(){return this.trustedFolder}setIdeMode(e){this.ideMode=e}async setIdeModeAndSyncConnection(e){this.ideMode=e,e?(await this.ideClient.connect(),AL(this,new d_(c_.SESSION))):await this.ideClient.disconnect()}getIdeClient(){return this.ideClient}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}async getGitService(){return this.gitService||(this.gitService=new N7(this.targetDir),await this.gitService.initialize()),this.gitService}async createToolRegistry(){let e=new gW(this),r=(n,...i)=>{let a=n.name,s=n.Name||a,o=this.getCoreTools(),l=this.getExcludeTools(),u=!1;o===void 0?u=!0:u=o.some(c=>c===a||c===s||c.startsWith(`${a}(`)||c.startsWith(`${s}(`)),(l?.includes(a)||l?.includes(s))&&(u=!1),u&&e.registerTool(new n(...i))};return r(IS,this),r(ul,this),r(_6,this),r(Lh,this),r(h0,this),r(yc,this),r(eJ,this),r(Qh,this),r(pl,this),r(u7),r(rJ,this),await e.discoverAllTools(),e}}});import khe from"node:path";import{promises as m2}from"node:fs";function ner(t){return encodeURIComponent(t)}function pR(t){try{return decodeURIComponent(t)}catch{return t.replace(/%([0-9A-F]{2})/g,(r,n)=>String.fromCharCode(parseInt(n,16)))}}var iNn,AU,dR,ier=Oe(()=>{"use strict";ef();iNn="logs.json";(function(t){t.USER="user"})(AU||(AU={}));dR=class{geminiDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];constructor(e){this.sessionId=e}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await m2.readFile(this.logFilePath,"utf-8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(console.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return console.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw console.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let r=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await m2.rename(this.logFilePath,r),console.debug(`Backed up corrupted log file to ${r}`)}catch{}}async initialize(){if(!this.initialized){this.geminiDir=cv(process.cwd()),this.logFilePath=khe.join(this.geminiDir,iNn);try{await m2.mkdir(this.geminiDir,{recursive:!0});let e=!0;try{await m2.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await m2.writeFile(this.logFilePath,"[]","utf-8");let r=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=r.length>0?Math.max(...r.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){console.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw console.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let r;try{r=await this._readLogFile()}catch(s){throw console.debug("Critical error reading log file before append:",s),s}let n=r.filter(s=>s.sessionId===e.sessionId),i=n.length>0?Math.max(...n.map(s=>s.messageId))+1:0;if(e.messageId=i,r.some(s=>s.sessionId===e.sessionId&&s.messageId===e.messageId&&s.timestamp===e.timestamp&&s.message===e.message))return console.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=r,null;r.push(e);try{return await m2.writeFile(this.logFilePath,JSON.stringify(r,null,2),"utf-8"),this.logs=r,e}catch(s){throw console.debug("Error writing to log file:",s),s}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type===AU.USER).sort((e,r)=>{let n=new Date(e.timestamp).getTime();return new Date(r.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,r){if(!this.initialized||this.sessionId===void 0){console.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:r,timestamp:new Date().toISOString()};try{let i=await this._updateLogFile(n);i&&(this.messageId=i.messageId+1)}catch{}}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.geminiDir)throw new Error("Checkpoint file path not set.");let r=ner(e);return khe.join(this.geminiDir,`checkpoint-${r}.json`)}async _getCheckpointPath(e){let r=this._checkpointPath(e);try{return await m2.access(r),r}catch(i){if(i.code!=="ENOENT")throw i}let n=khe.join(this.geminiDir,`checkpoint-${e}.json`);try{return await m2.access(n),n}catch(i){if(i.code!=="ENOENT")throw i}return r}async saveCheckpoint(e,r){if(!this.initialized){console.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(r);try{await m2.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(i){console.error("Error writing to checkpoint file:",i)}}async loadCheckpoint(e){if(!this.initialized)return console.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let r=await this._getCheckpointPath(e);try{let n=await m2.readFile(r,"utf-8"),i=JSON.parse(n);return Array.isArray(i)?i:(console.warn(`Checkpoint file at ${r} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return n.code==="ENOENT"?[]:(console.error(`Failed to read or parse checkpoint file ${r}:`,n),[])}}async deleteCheckpoint(e){if(!this.initialized||!this.geminiDir)return console.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let r=!1,n=this._checkpointPath(e);try{await m2.unlink(n),r=!0}catch(a){if(a.code!=="ENOENT")throw console.error(`Failed to delete checkpoint file ${n}:`,a),a}let i=khe.join(this.geminiDir,`checkpoint-${e}.json`);if(n!==i)try{await m2.unlink(i),r=!0}catch(a){if(a.code!=="ENOENT")throw console.error(`Failed to delete checkpoint file ${i}:`,a),a}return r}async checkpointExists(e){if(!this.initialized)throw new Error("Logger not initialized. Cannot check for checkpoint existence.");let r;try{return r=await this._getCheckpointPath(e),await m2.access(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw console.error(`Failed to check checkpoint existence for ${r??`path for tag "${e}"`}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.sessionId=void 0,this.messageId=0}}});function aNn(t){return pfe(t,{verbose:!0})}var aer=Oe(()=>{"use strict";GMe();});import{execSync as ser,spawn as sNn}from"child_process";function oer(t){return["vscode","vscodium","windsurf","cursor","vim","neovim","zed","emacs","intellij","webstorm","pycharm","phpstorm","rubymine","clion","goland","datagrip","rider","androidstudio"].includes(t)}function ler(t){try{return ser(process.platform==="win32"?`where.exe ${t}`:`command -v ${t}`,{stdio:"ignore"}),!0}catch{return!1}}function gU(t){let e=uer[t];return(process.platform==="win32"?e.win32:e.default).some(n=>ler(n))}function EU(t){let e=!process.env.SANDBOX;return["vscode","vscodium","windsurf","cursor","zed","intellij","webstorm","pycharm","phpstorm","rubymine","clion","goland","datagrip","rider","androidstudio"].includes(t)?e:!0}function _J(t){return t&&oer(t)?gU(t)&&EU(t):!1}function cer(t,e,r){if(!oer(r))return null;let n=uer[r],i=process.platform==="win32"?n.win32:n.default,a=i.slice(0,-1).find(s=>ler(s))||i[i.length-1];switch(r){case"vscode":case"vscodium":case"windsurf":case"cursor":case"zed":return{command:a,args:["--wait","--diff",t,e]};case"intellij":case"webstorm":case"pycharm":case"phpstorm":case"rubymine":case"clion":case"goland":case"datagrip":case"rider":case"androidstudio":return{command:a,args:["--wait","--diff",t,e]};case"vim":case"neovim":return{command:a,args:["-d","-i","NONE","-c","wincmd h | set readonly | wincmd l","-c","highlight DiffAdd cterm=bold ctermbg=22 guibg=#005f00 | highlight DiffChange cterm=bold ctermbg=24 guibg=#005f87 | highlight DiffText ctermbg=21 guibg=#0000af | highlight DiffDelete ctermbg=52 guibg=#5f0000","-c","set showtabline=2 | set tabline=[Instructions]\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)","-c","wincmd h | setlocal statusline=OLD\\ FILE","-c","wincmd l | setlocal statusline=%#StatusBold#NEW\\ FILE\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)","-c","autocmd WinClosed * wqa",t,e]};case"emacs":return{command:"emacs",args:["--eval",`(ediff "${t}" "${e}")`]};default:return null}}async function QGe(t,e,r,n){let i=cer(t,e,r);if(!i){console.error("No diff tool available. Install a supported editor.");return}try{switch(r){case"vscode":case"vscodium":case"windsurf":case"cursor":case"zed":case"intellij":case"webstorm":case"pycharm":case"phpstorm":case"rubymine":case"clion":case"goland":case"datagrip":case"rider":case"androidstudio":return new Promise((a,s)=>{let o=sNn(i.command,i.args,{stdio:"inherit",shell:!0});o.on("close",l=>{l===0?a():s(new Error(`${r} exited with code ${l}`))}),o.on("error",l=>{s(l)})});case"vim":case"emacs":case"neovim":{let a=process.platform==="win32"?`${i.command} ${i.args.join(" ")}`:`${i.command} ${i.args.map(s=>`"${s}"`).join(" ")}`;try{ser(a,{stdio:"inherit",encoding:"utf8"})}catch(s){console.error("Error in onEditorClose callback:",s)}finally{n()}break}default:throw new Error(`Unsupported editor: ${r}`)}}catch(a){console.error(a)}}var uer,kGe=Oe(()=>{"use strict";uer={vscode:{win32:["code.cmd"],default:["code"]},vscodium:{win32:["codium.cmd"],default:["codium"]},windsurf:{win32:["windsurf"],default:["windsurf"]},cursor:{win32:["cursor"],default:["cursor"]},vim:{win32:["vim"],default:["vim"]},neovim:{win32:["nvim"],default:["nvim"]},zed:{win32:["zed"],default:["zed","zeditor"]},emacs:{win32:["emacs.exe"],default:["emacs"]},intellij:{win32:["idea64.exe"],default:["idea"]},webstorm:{win32:["webstorm64.exe"],default:["webstorm"]},pycharm:{win32:["pycharm64.exe"],default:["pycharm"]},phpstorm:{win32:["phpstorm64.exe"],default:["phpstorm"]},rubymine:{win32:["rubymine64.exe"],default:["rubymine"]},clion:{win32:["clion64.exe"],default:["clion"]},goland:{win32:["goland64.exe"],default:["goland"]},datagrip:{win32:["datagrip64.exe"],default:["datagrip"]},rider:{win32:["rider64.exe"],default:["rider"]},androidstudio:{win32:["studio64.exe"],default:["studio"]}}});import oNn from"os";import yU from"path";import ub from"fs";function UGe(t){return"getModifyContext"in t}function lNn(t,e,r){let n=oNn.tmpdir(),i=yU.join(n,"gemini-cli-tool-modify-diffs");ub.existsSync(i)||ub.mkdirSync(i,{recursive:!0});let a=yU.extname(r),s=yU.basename(r,a),o=Date.now(),l=yU.join(i,`gemini-cli-modify-${s}-old-${o}${a}`),u=yU.join(i,`gemini-cli-modify-${s}-new-${o}${a}`);return ub.writeFileSync(l,t,"utf8"),ub.writeFileSync(u,e,"utf8"),{oldPath:l,newPath:u}}function uNn(t,e,r,n){let i="",a="";try{i=ub.readFileSync(t,"utf8")}catch(l){if(!Ns(l)||l.code!=="ENOENT")throw l;i=""}try{a=ub.readFileSync(e,"utf8")}catch(l){if(!Ns(l)||l.code!=="ENOENT")throw l;a=""}let s=n.createUpdatedParams(i,a,r),o=D6(yU.basename(n.getFilePath(r)),i,a,"Current","Proposed",S6);return{updatedParams:s,updatedDiff:o}}function cNn(t,e){try{ub.unlinkSync(t)}catch{console.error(`Error deleting temp diff file: ${t}`)}try{ub.unlinkSync(e)}catch{console.error(`Error deleting temp diff file: ${e}`)}}async function der(t,e,r,n,i){let a=await e.getCurrentContent(t),s=await e.getProposedContent(t),{oldPath:o,newPath:l}=lNn(a,s,e.getFilePath(t));try{return await QGe(o,l,r,i),uNn(o,l,t,e)}finally{cNn(o,l)}}var per=Oe(()=>{"use strict";kGe();fB();yz();ed();});function vU(t,e,r){return{functionResponse:{id:t,name:e,response:{output:r}}}}function _U(t,e,r){let n=Array.isArray(r)&&r.length===1?r[0]:r;if(typeof n=="string")return vU(e,t,n);if(Array.isArray(n))return[vU(e,t,"Tool execution succeeded."),...n];if(n.functionResponse){if(n.functionResponse.response?.content){let i=fUt(n.functionResponse.response.content)||"";return vU(e,t,i)}return n}if(n.inlineData||n.fileData){let i=n.inlineData?.mimeType||n.fileData?.mimeType||"unknown";return[vU(e,t,`Binary content of type ${i} was processed.`),n]}return n.text!==void 0?vU(e,t,n.text):vU(e,t,"Tool execution succeeded.")}var CU,DJ,HGe=Oe(()=>{"use strict";Uhe();Lz();per();fB();CU=(t,e,r)=>({callId:t.callId,error:e,responseParts:{functionResponse:{id:t.callId,name:t.name,response:{error:e.message}}},resultDisplay:e.message,errorType:r}),DJ=class{toolRegistry;toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;onToolCallsUpdate;getPreferredEditor;config;getTerminalSize;onEditorClose;isFinalizingToolCalls=!1;isScheduling=!1;requestQueue=[];constructor(e){this.config=e.config,this.toolRegistry=e.toolRegistry,this.outputUpdateHandler=e.outputUpdateHandler,this.onAllToolCallsComplete=e.onAllToolCallsComplete,this.onToolCallsUpdate=e.onToolCallsUpdate,this.getPreferredEditor=e.getPreferredEditor,this.getTerminalSize=e.getTerminalSize,this.onEditorClose=e.onEditorClose}setStatusInternal(e,r,n){this.toolCalls=this.toolCalls.map(i=>{if(i.request.callId!==e||i.status==="success"||i.status==="error"||i.status==="cancelled")return i;let a=i.startTime,s=i.tool,o=i.invocation,l=i.outcome;switch(r){case"success":{let u=a?Date.now()-a:void 0;return{request:i.request,tool:s,invocation:o,status:"success",response:n,durationMs:u,outcome:l}}case"error":{let u=a?Date.now()-a:void 0;return{request:i.request,status:"error",tool:s,response:n,durationMs:u,outcome:l}}case"awaiting_approval":return{request:i.request,tool:s,status:"awaiting_approval",confirmationDetails:n,startTime:a,outcome:l,invocation:o};case"scheduled":return{request:i.request,tool:s,status:"scheduled",startTime:a,outcome:l,invocation:o};case"cancelled":{let u=a?Date.now()-a:void 0,c;if(i.status==="awaiting_approval"){let d=i;d.confirmationDetails.type==="edit"&&(c={fileDiff:d.confirmationDetails.fileDiff,fileName:d.confirmationDetails.fileName,originalContent:d.confirmationDetails.originalContent,newContent:d.confirmationDetails.newContent})}return{request:i.request,tool:s,invocation:o,status:"cancelled",response:{callId:i.request.callId,responseParts:{functionResponse:{id:i.request.callId,name:i.request.name,response:{error:`[Operation Cancelled] Reason: ${n}`}}},resultDisplay:c,error:void 0,errorType:void 0},durationMs:u,outcome:l}}case"validating":return{request:i.request,tool:s,status:"validating",startTime:a,outcome:l,invocation:o};case"executing":return{request:i.request,tool:s,status:"executing",startTime:a,outcome:l,invocation:o};default:return r}}),this.notifyToolCallsUpdate(),this.checkAndNotifyCompletion()}setArgsInternal(e,r){this.toolCalls=this.toolCalls.map(n=>{if(n.request.callId!==e||n.status==="error")return n;let i=this.buildInvocation(n.tool,r);if(i instanceof Error){let a=CU(n.request,i,ms.INVALID_TOOL_PARAMS);return{request:{...n.request,args:r},status:"error",tool:n.tool,response:a}}return{...n,request:{...n.request,args:r},invocation:i}})}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(e=>e.status==="executing"||e.status==="awaiting_approval")}buildInvocation(e,r){try{return e.build(r)}catch(n){return n instanceof Error?n:new Error(String(n))}}schedule(e,r){return this.isRunning()||this.isScheduling?new Promise((n,i)=>{let a=()=>{let s=this.requestQueue.findIndex(o=>o.request===e);s>-1&&(this.requestQueue.splice(s,1),i(new Error("Tool call cancelled while in queue.")))};r.addEventListener("abort",a,{once:!0}),this.requestQueue.push({request:e,signal:r,resolve:()=>{r.removeEventListener("abort",a),n()},reject:s=>{r.removeEventListener("abort",a),i(s)}})}):this._schedule(e,r)}async _schedule(e,r){this.isScheduling=!0;try{if(this.isRunning())throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");let n=Array.isArray(e)?e:[e],i=await this.toolRegistry,a=n.map(s=>{let o=i.getTool(s.name);if(!o)return{status:"error",request:s,response:CU(s,new Error(`Tool "${s.name}" not found in registry.`),ms.TOOL_NOT_REGISTERED),durationMs:0};let l=this.buildInvocation(o,s.args);return l instanceof Error?{status:"error",request:s,tool:o,response:CU(s,l,ms.INVALID_TOOL_PARAMS),durationMs:0}:{status:"validating",request:s,tool:o,invocation:l,startTime:Date.now()}});this.toolCalls=this.toolCalls.concat(a),this.notifyToolCallsUpdate();for(let s of a){if(s.status!=="validating")continue;let{request:o,invocation:l}=s;try{if(this.config.getApprovalMode()===qa.YOLO)this.setToolCallOutcome(o.callId,Br.ProceedAlways),this.setStatusInternal(o.callId,"scheduled");else{let u=await l.shouldConfirmExecute(r);if(u){u.type==="edit"&&u.ideConfirmation&&u.ideConfirmation.then(h=>{h.status==="accepted"?this.handleConfirmationResponse(o.callId,u.onConfirm,Br.ProceedOnce,r):this.handleConfirmationResponse(o.callId,u.onConfirm,Br.Cancel,r)});let c=u.onConfirm,d={...u,onConfirm:(h,f)=>this.handleConfirmationResponse(o.callId,c,h,r,f)};this.setStatusInternal(o.callId,"awaiting_approval",d)}else this.setToolCallOutcome(o.callId,Br.ProceedAlways),this.setStatusInternal(o.callId,"scheduled")}}catch(u){this.setStatusInternal(o.callId,"error",CU(o,u instanceof Error?u:new Error(String(u)),ms.UNHANDLED_EXCEPTION))}}this.attemptExecutionOfScheduledCalls(r),this.checkAndNotifyCompletion()}finally{this.isScheduling=!1}}async handleConfirmationResponse(e,r,n,i,a){let s=this.toolCalls.find(o=>o.request.callId===e&&o.status==="awaiting_approval");if(s&&s.status==="awaiting_approval"&&await r(n),this.setToolCallOutcome(e,n),n===Br.Cancel||i.aborted)this.setStatusInternal(e,"cancelled","User did not allow tool call");else if(n===Br.ModifyWithEditor){let o=s;if(UGe(o.tool)){let l=o.tool.getModifyContext(i),u=this.getPreferredEditor();if(!u)return;this.setStatusInternal(e,"awaiting_approval",{...o.confirmationDetails,isModifying:!0});let{updatedParams:c,updatedDiff:d}=await der(o.request.args,l,u,i,this.onEditorClose);this.setArgsInternal(e,c),this.setStatusInternal(e,"awaiting_approval",{...o.confirmationDetails,fileDiff:d,isModifying:!1})}}else a?.newContent&&s&&await this._applyInlineModify(s,a,i),this.setStatusInternal(e,"scheduled");this.attemptExecutionOfScheduledCalls(i)}async _applyInlineModify(e,r,n){if(e.confirmationDetails.type!=="edit"||!UGe(e.tool))return;let i=e.tool.getModifyContext(n),a=await i.getCurrentContent(e.request.args),s=i.createUpdatedParams(a,r.newContent,e.request.args),o=D6(i.getFilePath(e.request.args),a,r.newContent,"Current","Proposed");this.setArgsInternal(e.request.callId,s),this.setStatusInternal(e.request.callId,"awaiting_approval",{...e.confirmationDetails,fileDiff:o})}attemptExecutionOfScheduledCalls(e){this.toolCalls.every(n=>n.status==="scheduled"||n.status==="cancelled"||n.status==="success"||n.status==="error")&&this.toolCalls.filter(i=>i.status==="scheduled").forEach(i=>{if(i.status!=="scheduled")return;let a=i,{callId:s,name:o}=a.request,l=a.invocation;this.setStatusInternal(s,"executing");let u=a.tool.canUpdateOutput&&this.outputUpdateHandler?d=>{this.outputUpdateHandler&&this.outputUpdateHandler(s,d),this.toolCalls=this.toolCalls.map(h=>h.request.callId===s&&h.status==="executing"?{...h,liveOutput:d}:h),this.notifyToolCallsUpdate()}:void 0,c=this.getTerminalSize();l.execute(e,u,c.columns,c.rows).then(async d=>{if(e.aborted){this.setStatusInternal(s,"cancelled","User cancelled tool execution.");return}if(d.error===void 0){let h=_U(o,s,d.llmContent),f={callId:s,responseParts:h,resultDisplay:d.returnDisplay,error:void 0,errorType:void 0};this.setStatusInternal(s,"success",f)}else{let h=new Error(d.error.message),f=CU(a.request,h,d.error.type);this.setStatusInternal(s,"error",f)}}).catch(d=>{this.setStatusInternal(s,"error",CU(a.request,d instanceof Error?d:new Error(String(d)),ms.UNHANDLED_EXCEPTION))})})}async checkAndNotifyCompletion(){let e=this.toolCalls.every(r=>r.status==="success"||r.status==="error"||r.status==="cancelled");if(this.toolCalls.length>0&&e){let r=[...this.toolCalls];this.toolCalls=[];for(let n of r)cE(this.config,new KO(n));if(this.onAllToolCallsComplete&&(this.isFinalizingToolCalls=!0,await this.onAllToolCallsComplete(r),this.isFinalizingToolCalls=!1),this.notifyToolCallsUpdate(),this.requestQueue.length>0){let n=this.requestQueue.shift();this._schedule(n.request,n.signal).then(n.resolve).catch(n.reject)}}}notifyToolCallsUpdate(){this.onToolCallsUpdate&&this.onToolCallsUpdate([...this.toolCalls])}setToolCallOutcome(e,r){this.toolCalls=this.toolCalls.map(n=>n.request.callId!==e?n:{...n,outcome:r})}}});async function GGe(t,e,r,n){let i=r.getTool(e.name),a=Date.now();if(!i){let s=new Error(`Tool "${e.name}" not found in registry.`),o=Date.now()-a;return cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:o,success:!1,error:s.message,prompt_id:e.prompt_id}),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:s.message}}}],resultDisplay:s.message,error:s,errorType:ms.TOOL_NOT_REGISTERED}}try{let s=n??new AbortController().signal,o=await i.buildAndExecute(e.args,s),l=o.llmContent,u=o.returnDisplay,c={};if(o.error===void 0&&typeof u=="object"&&u!==null&&"diffStat"in u){let f=u.diffStat;f&&(c={ai_added_lines:f.ai_added_lines,ai_removed_lines:f.ai_removed_lines,user_added_lines:f.user_added_lines,user_removed_lines:f.user_removed_lines})}let d=Date.now()-a;cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:d,success:o.error===void 0,error:o.error===void 0?void 0:o.error.message,error_type:o.error===void 0?void 0:o.error.type,prompt_id:e.prompt_id,metadata:c,decision:j1.AUTO_ACCEPT});let h=_U(e.name,e.callId,l);return{callId:e.callId,responseParts:h,resultDisplay:u,error:o.error===void 0?void 0:new Error(o.error.message),errorType:o.error===void 0?void 0:o.error.type}}catch(s){let o=s instanceof Error?s:new Error(String(s)),l=Date.now()-a;return cE(t,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),function_name:e.name,function_args:e.args,duration_ms:l,success:!1,error:o.message,error_type:ms.UNHANDLED_EXCEPTION,prompt_id:e.prompt_id}),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:o.message}}}],resultDisplay:o.message,error:o,errorType:ms.UNHANDLED_EXCEPTION}}}var fer=Oe(()=>{"use strict";Uhe();HGe();Yee();});import mer from"node:fs";function dNn(){try{return mer.statSync("/.dockerenv"),!0}catch{return!1}}function pNn(){try{return mer.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function qGe(){return VGe===void 0&&(VGe=dNn()||pNn()),VGe}var VGe,her=Oe(()=>{});import fNn from"node:fs";function DU(){return $Ge===void 0&&($Ge=mNn()||qGe()),$Ge}var $Ge,mNn,jGe=Oe(()=>{her();mNn=()=>{try{return fNn.statSync("/run/.containerenv"),!0}catch{return!1}}});import ger from"node:process";import hNn from"node:os";import ANn from"node:fs";var Aer,SU,Eer=Oe(()=>{jGe();Aer=()=>{if(ger.platform!=="linux")return!1;if(hNn.release().toLowerCase().includes("microsoft"))return!DU();try{return ANn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!DU():!1}catch{return!1}},SU=ger.env.__IS_WSL_TEST__?Aer:Aer()});function fR(t,e,r){let n=i=>Object.defineProperty(t,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){let i=r();return n(i),i},set(i){n(i)}}),t}var yer=Oe(()=>{});import{promisify as gNn}from"node:util";import ENn from"node:process";import{execFile as yNn}from"node:child_process";async function YGe(){if(ENn.platform!=="darwin")throw new Error("macOS only");let{stdout:t}=await vNn("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(t)?.groups.id??"com.apple.Safari"}var vNn,ver=Oe(()=>{vNn=gNn(yNn)});import CNn from"node:process";import{promisify as _Nn}from"node:util";import{execFile as DNn,execFileSync as vLi}from"node:child_process";async function Cer(t,{humanReadableOutput:e=!0}={}){if(CNn.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],{stdout:n}=await SNn("osascript",["-e",t,r]);return n.trim()}var SNn,_er=Oe(()=>{SNn=_Nn(DNn)});async function WGe(t){return Cer(`tell application "Finder" to set app_path to application file id "${t}" as string
1420
1420
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Der=Oe(()=>{_er()});import{promisify as bNn}from"node:util";import{execFile as wNn}from"node:child_process";async function zGe(t=INn){let{stdout:e}=await t("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!r)throw new Hhe(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=r.groups,i=TNn[n];if(!i)throw new Hhe(`Unknown browser ID: ${n}`);return i}var INn,TNn,Hhe,Ser=Oe(()=>{INn=bNn(wNn),TNn={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}},Hhe=class extends Error{}});import{promisify as xNn}from"node:util";import KGe from"node:process";import{execFile as BNn}from"node:child_process";async function JGe(){if(KGe.platform==="darwin"){let t=await YGe();return{name:await WGe(t),id:t}}if(KGe.platform==="linux"){let{stdout:t}=await RNn("xdg-mime",["query","default","x-scheme-handler/http"]),e=t.trim();return{name:NNn(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(KGe.platform==="win32")return zGe();throw new Error("Only macOS, Linux, and Windows are supported")}var RNn,NNn,ber=Oe(()=>{ver();Der();Ser();RNn=xNn(BNn),NNn=t=>t.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});import Ghe from"node:process";import{Buffer as Ber}from"node:buffer";import Rer from"node:path";import{fileURLToPath as ONn}from"node:url";import FNn from"node:util";import Ner from"node:child_process";import XGe,{constants as Oer}from"node:fs/promises";async function PNn(){let t=await Fer(),r=Ber.from('(Get-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice").ProgId',"utf16le").toString("base64"),{stdout:n}=await MNn(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",r],{encoding:"utf8"}),i=n.trim(),a={ChromeHTML:"com.google.chrome",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return a[i]?{id:a[i]}:{}}function xer(t){if(typeof t=="string"||Array.isArray(t))return t;let{[Ier]:e}=t;if(!e)throw new Error(`${Ier} is not supported`);return e}function eVe({[bU]:t},{wsl:e}){if(e&&SU)return xer(e);if(!t)throw new Error(`${bU} is not supported`);return xer(t)}var MNn,ZGe,wer,bU,Ier,LNn,Fer,Ter,Vhe,QNn,wU,h5,IU=Oe(()=>{Eer();yer();ber();jGe();MNn=FNn.promisify(Ner.execFile),ZGe=Rer.dirname(ONn(import.meta.url)),wer=Rer.join(ZGe,"xdg-open"),{platform:bU,arch:Ier}=Ghe,LNn=(()=>{let t="/mnt/",e;return async function(){if(e)return e;let r="/etc/wsl.conf",n=!1;try{await XGe.access(r,Oer.F_OK),n=!0}catch{}if(!n)return t;let i=await XGe.readFile(r,{encoding:"utf8"}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(e=a.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):t}})(),Fer=async()=>`${await LNn()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;Ter=async(t,e)=>{let r;for(let n of t)try{return await e(n)}catch(i){r=i}throw r},Vhe=async t=>{if(t={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...t},Array.isArray(t.app))return Ter(t.app,o=>Vhe({...t,app:o}));let{name:e,arguments:r=[]}=t.app??{};if(r=[...r],Array.isArray(e))return Ter(e,o=>Vhe({...t,app:{name:o,arguments:r}}));if(e==="browser"||e==="browserPrivate"){let o={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"},u=SU?await PNn():await JGe();if(u.id in o){let c=o[u.id];return e==="browserPrivate"&&r.push(l[c]),Vhe({...t,app:{name:wU[c],arguments:r}})}throw new Error(`${u.name} is not supported as a default browser`)}let n,i=[],a={};if(bU==="darwin")n="open",t.wait&&i.push("--wait-apps"),t.background&&i.push("--background"),t.newInstance&&i.push("--new"),e&&i.push("-a",e);else if(bU==="win32"||SU&&!DU()&&!e){n=SU?await Fer():`${Ghe.env.SYSTEMROOT||Ghe.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,i.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),SU||(a.windowsVerbatimArguments=!0);let o=["Start"];t.wait&&o.push("-Wait"),e?(o.push(`"\`"${e}\`""`),t.target&&r.push(t.target)):t.target&&o.push(`"${t.target}"`),r.length>0&&(r=r.map(l=>`"\`"${l}\`""`),o.push("-ArgumentList",r.join(","))),t.target=Ber.from(o.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let o=!ZGe||ZGe==="/",l=!1;try{await XGe.access(wer,Oer.X_OK),l=!0}catch{}n=Ghe.versions.electron??(bU==="android"||o||!l)?"xdg-open":wer}r.length>0&&i.push(...r),t.wait||(a.stdio="ignore",a.detached=!0)}bU==="darwin"&&r.length>0&&i.push("--args",...r),t.target&&i.push(t.target);let s=Ner.spawn(n,i,a);return t.wait?new Promise((o,l)=>{s.once("error",l),s.once("close",u=>{if(!t.allowNonzeroExitCode&&u>0){l(new Error(`Exited with code ${u}`));return}o(s)})}):(s.unref(),s)},QNn=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a `target`");return Vhe({...e,target:t})};wU={};fR(wU,"chrome",()=>eVe({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));fR(wU,"firefox",()=>eVe({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));fR(wU,"edge",()=>eVe({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));fR(wU,"browser",()=>"browser");fR(wU,"browserPrivate",()=>"browserPrivate");h5=QNn});import*as Ler from"http";import kNn from"url";import Per from"crypto";import*as Qer from"net";import ker from"node:path";import{promises as qhe}from"node:fs";import*as Uer from"os";import UNn from"node:readline";async function nVe(t,e){let r=new TU.OAuth2Client({clientId:HNn,clientSecret:GNn,transporterOptions:{proxy:e.getProxy()}});if(process.env.GOOGLE_GENAI_USE_GCA&&process.env.GOOGLE_CLOUD_ACCESS_TOKEN)return r.setCredentials({access_token:process.env.GOOGLE_CLOUD_ACCESS_TOKEN}),await rVe(r),r;if(r.on("tokens",async n=>{await WNn(n)}),await YNn(r)){if(!ile())try{await rVe(r)}catch{}return console.log("Loaded cached credentials."),r}if(t===ln.LOGIN_WITH_GITHUB)try{console.log("Attempting to authenticate via Cloud Shell VM's ADC.");let n=new TU.Compute({});return await n.getAccessToken(),console.log("Authentication successful."),n}catch(n){throw new Error(`Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ${sr(n)}`)}if(e.isBrowserLaunchSuppressed()){let n=!1,i=2;for(let a=0;!n&&a<i;a++)n=await $Nn(r),n||console.error(`
1421
1421
  Failed to authenticate with user code.`,a===i-1?"":`Retrying...
1422
1422
  `);n||process.exit(1)}else{let n=await jNn(r);console.log(`
@@ -1841,13 +1841,13 @@ Do NOT use this tool:
1841
1841
  \u26A1 \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /auth, \u0447\u0442\u043E\u0431\u044B \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C \u0434\u0440\u0443\u0433\u043E\u0439 \u0442\u043E\u043A\u0435\u043D \u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u0438 \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C.`,freeDefault:`\u26A1 \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u044E\u0441\u044C \u0441 {currentModel} \u043D\u0430 {fallbackModel} \u0434\u043E \u043A\u043E\u043D\u0446\u0430 \u0441\u0435\u0441\u0441\u0438\u0438: \u0442\u0435\u043A\u0443\u0449\u0430\u044F \u043C\u043E\u0434\u0435\u043B\u044C \u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430.
1842
1842
  \u26A1 \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /auth, \u0447\u0442\u043E\u0431\u044B \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C \u0434\u0440\u0443\u0433\u043E\u0439 \u0442\u043E\u043A\u0435\u043D \u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u0438 \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C.`},trial:{footerLabel:"\u043F\u0440\u043E\u0431\u043D\u044B\u0435 \u0437\u0430\u043F\u0440\u043E\u0441\u044B {used}{limitPart}",limitReached:`\u26A1 \u0412\u044B \u0438\u0437\u0440\u0430\u0441\u0445\u043E\u0434\u043E\u0432\u0430\u043B\u0438 \u0432\u0441\u0435 \u043F\u0440\u043E\u0431\u043D\u044B\u0435 \u0437\u0430\u043F\u0440\u043E\u0441\u044B Koda.
1843
1843
  \u26A1 \u0417\u0430\u043F\u0440\u043E\u0441\u044B \u0431\u0443\u0434\u0443\u0442 \u043F\u0440\u0438\u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u044B \u0434\u043E \u0441\u0431\u0440\u043E\u0441\u0430 \u043B\u0438\u043C\u0438\u0442\u0430.
1844
- \u26A1 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u0442\u0435 \u043F\u043E\u0441\u0442\u043E\u044F\u043D\u043D\u044B\u0439 \u0434\u043E\u0441\u0442\u0443\u043F \u0447\u0435\u0440\u0435\u0437 /auth \u0438\u043B\u0438 \u043E\u0444\u043E\u0440\u043C\u0438\u0442\u0435 \u0442\u0430\u0440\u0438\u0444: https://kodacode.ru `},auth:{reauthRequired:"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",timeout:"\u0412\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E. \u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."},prompts:{pressCtrlCAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+C \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0439\u0442\u0438.",pressCtrlDAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+D \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0439\u0442\u0438.",pressEscAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Esc \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C."},extensions:{noActive:"\u041D\u0435\u0442 \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439.",activeTitle:"\u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F:"},placeholders:{vim:" \u041D\u0430\u0436\u043C\u0438\u0442\u0435 'i' \u0434\u043B\u044F \u0440\u0435\u0436\u0438\u043C\u0430 INSERT \u0438 'Esc' \u0434\u043B\u044F \u0440\u0435\u0436\u0438\u043C\u0430 NORMAL.",default:" \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0438\u043B\u0438 @\u043F\u0443\u0442\u044C/\u043A/\u0444\u0430\u0439\u043B\u0443"},confirmation:{yes:"\u0414\u0430",no:"\u041D\u0435\u0442"},toolConfirmation:{modifyInProgress:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u0432 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0435: ",saveAndCloseExternalEditor:"\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u0435 \u0438 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 \u0432\u043D\u0435\u0448\u043D\u0438\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440, \u0447\u0442\u043E\u0431\u044B \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C",applyThisChange:"\u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C \u044D\u0442\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435?",yesAllowOnce:"\u0414\u0430, \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u043E\u0434\u0438\u043D \u0440\u0430\u0437",yesAllowAlways:"\u0414\u0430, \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u0441\u0435\u0433\u0434\u0430",noEsc:"\u041D\u0435\u0442 (esc)",modifyWithExternalEditor:"\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0432\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u043C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0435",noSuggestChanges:"\u041D\u0435\u0442, \u043F\u0440\u0435\u0434\u043B\u043E\u0436\u0438\u0442\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F (esc)",allowExecutionOf:"\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435: '{command}'?",doYouWantToProceed:"\u0412\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C?",urlsToFetch:"URL-\u0430\u0434\u0440\u0435\u0441\u0430 \u0434\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F:",allowExecutionOfMcpTool:'\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 MCP "{toolName}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"?',yesAlwaysAllowToolFromServer:'\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 "{toolName}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"',yesAlwaysAllowAllToolsFromServer:'\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0432\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"'},init:{error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438: {error}",checkConfig:"\u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 API-\u043A\u043B\u044E\u0447 \u0438 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E."}}},bnr={en:FLn,ru:MLn},Aqe=class{currentLanguage;constructor(e){let r=e?.language;r==="en"||r==="ru"?this.currentLanguage=r:this.currentLanguage="en"}setLanguage(e){this.currentLanguage=e}getLanguage(){return this.currentLanguage}t(e,r){let n=e.split("."),i=bnr[this.currentLanguage],a=!0;for(let s of n)if(typeof i=="object"&&i!==null&&s in i)i=i[s];else{a=!1;break}if(a&&typeof i=="string"){if(r){let s=i;for(let[o,l]of Object.entries(r))s=s.replace(new RegExp(`{${o}}`,"g"),String(l));return s}return i}if(this.currentLanguage!=="en"){let s=bnr.en,o=!0;for(let l of n)if(typeof s=="object"&&s!==null&&l in s)s=s[l];else{o=!1;break}if(o&&typeof s=="string"){if(r){let l=s;for(let[u,c]of Object.entries(r))l=l.replace(new RegExp(`{${u}}`,"g"),String(c));return l}return s}}return e}},De=new Aqe;function LLn(t){let e=[];for(let r of t)Array.isArray(r)?e.push(...r):e.push(r);return e}var Inr=(t,e,r,n,i,a,s,o,l,u,c,d,h,f)=>{(0,Ys.useEffect)(()=>{(async()=>{try{let Ae=await n.getToolRegistry(),te={},H=["search_file_content","list_directory","glob","google_web_search","save_memory","run_shell_command"];for(let ge of H){let xe=`toolDescriptions.${ge}`,He=De.t(xe);He&&He!==xe&&(te[ge]=He)}Object.keys(te).length>0&&Ae.updateToolDescriptions(te)}catch(Ae){console.error("Error updating tool descriptions:",Ae)}})()},[n]);let[E,y]=(0,Ys.useState)(null),g=(0,Ys.useRef)(null),C=(0,Ys.useRef)(!1),[D,S]=(0,Ys.useState)(!1),[w,N]=(0,Ys.useState)(null),[M,U]=Anr(null),k=(0,Ys.useRef)(new Set),{startNewPrompt:B,getPromptCount:q}=U6(),W=RAe(),re=(0,Ys.useMemo)(()=>{if(n.getProjectRoot())return new N7(n.getProjectRoot())},[n]),[$,R,Q]=gnr(async Y=>{Y.length>0&&(r(fqe(Y),Date.now()),await le(Y))},n,U,o,h),J=(0,Ys.useMemo)(()=>$.length?fqe($):void 0,[$]),ae=(0,Ys.useRef)(!1),fe=(0,Ys.useCallback)(async Y=>{S(!0),await Y,S(!1)},[]),{handleShellCommand:K}=dnr(r,U,fe,i,n,t),ne=(0,Ys.useMemo)(()=>$.some(Y=>Y.status==="awaiting_approval")?"waiting_for_confirmation":D||$.some(Y=>Y.status==="executing"||Y.status==="scheduled"||Y.status==="validating"||(Y.status==="success"||Y.status==="error"||Y.status==="cancelled")&&!Y.responseSubmittedToGemini)?"responding":"idle",[D,$]),he=(0,Ys.useMemo)(()=>{let Y=["awaiting_approval","executing","validating","scheduled","success","error","cancelled"];for(let Ae of Y){let te=$.find(H=>H.status===Ae);if(te)return te}return null},[$]),Ee=(0,Ys.useMemo)(()=>{if(he){let Y=he.tool?.displayName??he.request.name,te=("invocation"in he?he.invocation:void 0)?.getDescription?.(),H=typeof te=="string"?te.trim():"",ge=H.length>0,He={awaiting_approval:{withDescription:"loading.activity.awaitingApproval.withDescription",withoutDescription:"loading.activity.awaitingApproval.withoutDescription"},executing:{withDescription:"loading.activity.executing.withDescription",withoutDescription:"loading.activity.executing.withoutDescription"},validating:{withDescription:"loading.activity.validating.withDescription",withoutDescription:"loading.activity.validating.withoutDescription"},scheduled:{withDescription:"loading.activity.scheduled.withDescription",withoutDescription:"loading.activity.scheduled.withoutDescription"},success:{withDescription:"loading.activity.success.withDescription",withoutDescription:"loading.activity.success.withoutDescription"},error:{withDescription:"loading.activity.error.withDescription",withoutDescription:"loading.activity.error.withoutDescription"},cancelled:{withDescription:"loading.activity.cancelled.withDescription",withoutDescription:"loading.activity.cancelled.withoutDescription"}}[he.status];if(!He)return null;let mt=ge?He.withDescription:He.withoutDescription,xt={tool:Y};ge&&(xt.description=H);let Yt=`loading.activity.tool.${he.request.name}.${he.status}`,ht=ge?`${Yt}.withDescription`:`${Yt}.withoutDescription`,vt=De.t(ht,xt);return vt!==ht?vt:De.t(mt,xt)}return ne==="responding"?De.t("loading.activity.processingResponse"):ne==="waiting_for_confirmation"?De.t("loading.activity.awaitingUserConfirmation"):null},[he,ne]),pe=(0,Ys.useCallback)(()=>{ne==="responding"&&(C.current||(C.current=!0,g.current?.abort(),M.current&&r(M.current,Date.now()),r({type:"info",text:De.t("app.requestCancelled")},Date.now()),U(null),f(),S(!1)))},[ne,r,U,f,M]);ts(Y=>{Y.name==="escape"&&pe()},{isActive:ne==="responding"});let _e=(0,Ys.useCallback)(async(Y,Ae,te,H)=>{if(C.current)return{queryToSend:null,shouldProceed:!1};if(typeof Y=="string"&&Y.trim().length===0)return{queryToSend:null,shouldProceed:!1};let ge=null;if(typeof Y=="string"){let xe=Y.trim();hL(n,new zO(xe.length,H,n.getContentGeneratorConfig()?.authType,xe)),i(`User query: '${xe}'`),await W?.logMessage(AU.USER,xe);let He=await a(xe);if(He)switch(He.type){case"schedule_tool":{let{toolName:mt,toolArgs:xt}=He,Yt={callId:`${mt}-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:mt,args:xt,isClientInitiated:!0,prompt_id:H};return R([Yt],te),{queryToSend:null,shouldProceed:!1}}case"submit_prompt":return ge=He.content,{queryToSend:ge,shouldProceed:!0};case"handled":return{queryToSend:null,shouldProceed:!1};default:{let mt=He;throw new Error(`Unhandled slash command result type: ${mt}`)}}if(s&&K(xe,te))return{queryToSend:null,shouldProceed:!1};if(anr(xe)){let mt=await fnr({query:xe,config:n,addItem:r,onDebugMessage:i,messageId:Ae,signal:te});if(!mt.shouldProceed)return{queryToSend:null,shouldProceed:!1};ge=mt.processedQuery}else r({type:"user",text:xe},Ae),ge=xe}else ge=Y;return ge===null?(i("Query processing resulted in null, not sending to Gemini."),{queryToSend:null,shouldProceed:!1}):{queryToSend:ge,shouldProceed:!0}},[n,r,i,K,a,W,s,R]),Se=(0,Ys.useCallback)((Y,Ae,te)=>{if(C.current)return"";let H=Ae+Y;M.current?.type!=="gemini"&&M.current?.type!=="gemini_content"&&(M.current&&r(M.current,te),U({type:"gemini",text:""}),H=Y);let ge=hnr(H);if(ge===H.length)U(xe=>({type:xe?.type,text:H}));else{let xe=H.substring(0,ge),He=H.substring(ge);r({type:M.current?.type,text:xe},te),U({type:"gemini_content",text:He}),H=He}return H},[r,M,U]),se=(0,Ys.useCallback)(Y=>{if(!C.current){if(M.current){if(M.current.type==="tool_group"){let Ae=M.current.tools.map(H=>H.status==="Pending"||H.status==="Confirming"||H.status==="Executing"?{...H,status:"Canceled"}:H),te={...M.current,tools:Ae};r(te,Y)}else r(M.current,Y);U(null)}r({type:"info",text:"User cancelled the request."},Y),S(!1),N(null)}},[r,M,U,N]),ve=(0,Ys.useCallback)((Y,Ae)=>{M.current&&(r(M.current,Ae),U(null)),r({type:"error",text:MU(Y.error,n.getContentGeneratorConfig()?.authType,void 0,n.getModel(),Od)},Ae),N(null)},[r,M,U,n,N]),X=(0,Ys.useCallback)((Y,Ae)=>{let te=Y.value,ge={[a0.FINISH_REASON_UNSPECIFIED]:void 0,[a0.STOP]:void 0,[a0.MAX_TOKENS]:"Response truncated due to token limits.",[a0.SAFETY]:"Response stopped due to safety reasons.",[a0.RECITATION]:"Response stopped due to recitation policy.",[a0.LANGUAGE]:"Response stopped due to unsupported language.",[a0.BLOCKLIST]:"Response stopped due to forbidden terms.",[a0.PROHIBITED_CONTENT]:"Response stopped due to prohibited content.",[a0.SPII]:"Response stopped due to sensitive personally identifiable information.",[a0.OTHER]:"Response stopped for other reasons.",[a0.MALFORMED_FUNCTION_CALL]:"Response stopped due to malformed function call.",[a0.IMAGE_SAFETY]:"Response stopped due to image safety violations.",[a0.UNEXPECTED_TOOL_CALL]:"Response stopped due to unexpected tool call."}[te];ge&&r({type:"info",text:`\u26A0\uFE0F ${ge}`},Ae)},[r]),ee=(0,Ys.useCallback)(Y=>r({type:"info",text:`IMPORTANT: This conversation approached the input token limit for ${n.getModel()}. A compressed context will be sent for future messages (compressed from: ${Y?.originalTokenCount??"unknown"} to ${Y?.newTokenCount??"unknown"} tokens).`},Date.now()),[r,n]),ie=(0,Ys.useCallback)(()=>r({type:"info",text:`The session has reached the maximum number of turns: ${n.getMaxSessionTurns()}. Please update this limit in your setting.json file.`},Date.now()),[r,n]),me=(0,Ys.useCallback)(()=>{r({type:"info",text:"A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted."},Date.now())},[r]),ue=(0,Ys.useCallback)(async(Y,Ae,te)=>{let H="",ge=[];for await(let xe of Y)switch(xe.type){case $s.Thought:N(xe.value);break;case $s.Content:H=Se(xe.value,H,Ae);break;case $s.ToolCallRequest:ge.push(xe.value);break;case $s.UserCancelled:se(Ae);break;case $s.Error:ve(xe.value,Ae);break;case $s.ChatCompressed:ee(xe.value);break;case $s.ToolCallConfirmation:case $s.ToolCallResponse:break;case $s.MaxSessionTurns:ie();break;case $s.Finished:X(xe,Ae);break;case $s.LoopDetected:ae.current=!0;break;default:return xe}return ge.length>0&&R(ge,te),0},[Se,se,ve,R,ee,X,ie]),Ce=(0,Ys.useCallback)(async(Y,Ae,te)=>{if((ne==="responding"||ne==="waiting_for_confirmation")&&!Ae?.isContinuation)return;let H=Date.now();Ae?.isContinuation||(d(!1),n.setQuotaErrorOccurred(!1)),g.current=new AbortController;let ge=g.current.signal;C.current=!1,te||(te=n.getSessionId()+"########"+q());let{queryToSend:xe,shouldProceed:He}=await _e(Y,H,ge,te);if(!(!He||xe===null)){Ae?.isContinuation||(B(),N(null)),S(!0),y(null);try{let mt=t.sendMessageStream(xe,ge,te);if(await ue(mt,H,ge)===1)return;M.current&&(r(M.current,H),U(null)),ae.current&&(ae.current=!1,me())}catch(mt){mt instanceof ES?l():(!Ns(mt)||mt.name!=="AbortError")&&r({type:"error",text:MU(sr(mt)||"Unknown error",n.getContentGeneratorConfig()?.authType,void 0,n.getModel(),Od)},H)}finally{S(!1)}}},[ne,d,_e,ue,M,r,U,y,t,l,n,B,q,me]),le=(0,Ys.useCallback)(async Y=>{if(D)return;let Ae=Y.filter(Yt=>Yt.status==="success"||Yt.status==="error"||Yt.status==="cancelled"?Yt.response?.responseParts!==void 0:!1),te=Ae.filter(Yt=>Yt.request.isClientInitiated);te.length>0&&Q(te.map(Yt=>Yt.request.callId));let H=Ae.filter(Yt=>Yt.request.name==="save_memory"&&Yt.status==="success"&&!k.current.has(Yt.request.callId));H.length>0&&(u(),H.forEach(Yt=>k.current.add(Yt.request.callId)));let ge=Ae.filter(Yt=>!Yt.request.isClientInitiated);if(ge.length===0)return;if(ge.every(Yt=>Yt.status==="cancelled")){if(t){let ht=ge.flatMap(Ut=>Ut.response.responseParts),vt=[];for(let Ut of ht)Array.isArray(Ut)?vt.push(...Ut):typeof Ut=="string"?vt.push({text:Ut}):vt.push(Ut);t.addHistory({role:"user",parts:vt})}let Yt=ge.map(ht=>ht.request.callId);Q(Yt);return}let He=ge.map(Yt=>Yt.response.responseParts),mt=ge.map(Yt=>Yt.request.callId),xt=ge.map(Yt=>Yt.request.prompt_id);Q(mt),!c&&Ce(LLn(He),{isContinuation:!0},xt[0])},[D,Ce,Q,t,u,c]),G=[M.current,J].filter(Y=>Y!=null);return(0,Ys.useEffect)(()=>{(async()=>{if(!n.getCheckpointingEnabled())return;let Ae=$.filter(te=>(te.request.name==="replace"||te.request.name==="write_file")&&te.status==="awaiting_approval");if(Ae.length>0){let te=n.getProjectTempDir()?gqe.join(n.getProjectTempDir(),"checkpoints"):void 0;if(!te)return;try{await wnr.mkdir(te,{recursive:!0})}catch(H){if(!Ns(H)||H.code!=="EEXIST"){i(`Failed to create checkpoint directory: ${sr(H)}`);return}}for(let H of Ae){let ge=H.request.args.file_path;if(!ge){i(`Skipping restorable tool call due to missing file_path: ${H.request.name}`);continue}try{let xe=await re?.createFileSnapshot(`Snapshot for ${H.request.name}`);if(xe||(xe=await re?.getCurrentCommitHash()),!xe){i(`Failed to create snapshot for ${ge}. Skipping restorable tool call.`);continue}let He=new Date().toISOString().replace(/:/g,"-").replace(/\./g,"_"),mt=H.request.name,xt=gqe.basename(ge),Yt=`${He}-${xt}-${mt}.json`,ht=await t?.getHistory(),vt=gqe.join(te,Yt);await wnr.writeFile(vt,JSON.stringify({history:e,clientHistory:ht,toolCall:{name:H.request.name,args:H.request.args},commitHash:xe,filePath:ge},null,2))}catch(xe){i(`Failed to write restorable tool call file: ${sr(xe)}`)}}}})()},[$,n,i,re,e,t]),{streamingState:ne,submitQuery:Ce,initError:E,pendingHistoryItems:G,thought:w,cancelOngoingRequest:pe,activeActivity:Ee}};var hb=Ve(lr(),1);var Tnr=(t,e)=>{let[r,n]=(0,hb.useState)(0),i=(0,hb.useRef)(null),a=(0,hb.useRef)(e),s=(0,hb.useRef)(t);return(0,hb.useEffect)(()=>{let o=!1;return a.current!==e&&(o=!0,a.current=e),s.current===!1&&t&&(o=!0),o&&n(0),s.current=t,t?(i.current&&clearInterval(i.current),i.current=setInterval(()=>{n(l=>l+1)},1e3)):i.current&&(clearInterval(i.current),i.current=null),()=>{i.current&&(clearInterval(i.current),i.current=null)}},[t,e]),r};var Ab=Ve(lr(),1);var PLn=5e3;function QLn(){return["Generating responses with 110% accuracy","Reticulating splines...","Consulting the Oracle...","Waking up the AI overlords...","Booting up consciousness...","Calibrating neural pathways...","Compiling ideas into thoughts...","Loading witty loading messages...","Calculating the meaning of life...","Sharpening the algorithms...","Preparing digital magic tricks...","Downloading more RAM...","Compressing algorithms...","Decompressing responses...","Rearranging the bits...","Initializing the response factory...","Assembling the knowledge engine...","Polishing the AI gemstones...","Warming up the neural networks...","Fine-tuning the intelligence...","Loading AI with coffee...","Preparing your AI-powered response...","Consulting the digital encyclopedia...","Generating thoughts with 99.9% confidence"]}function xnr(t,e){let r=(0,Ab.useMemo)(()=>QLn(),[]),[n,i]=(0,Ab.useState)(()=>r[0]??"Loading..."),a=(0,Ab.useCallback)(()=>{if(r.length===0)return"Loading...";let s=Math.floor(Math.random()*r.length);return r[s]},[r]);return(0,Ab.useEffect)(()=>{let s=null;if(e)i("Waiting for user confirmation...");else if(t){let o=a();i(o),s=setInterval(()=>{i(l=>{let u=r.indexOf(l);if(u===-1)return r[0];let c=(u+1)%r.length;return r[c]})},PLn)}else i(r[0]);return()=>{s&&clearInterval(s)}},[t,e,a,r]),n}var vR=Ve(lr(),1);var Bnr=(t,e)=>{let[r,n]=(0,vR.useState)(0),i=t==="responding",a=Tnr(i,r),s=t==="responding",o=t==="waiting_for_confirmation",l=xnr(s,o),u=e&&t!=="idle"?e:l,[c,d]=(0,vR.useState)(0),h=(0,vR.useRef)(null);return(0,vR.useEffect)(()=>{h.current==="waiting_for_confirmation"&&t==="responding"?(n(f=>f+1),d(0)):t==="idle"&&h.current==="responding"?(n(f=>f+1),d(0)):t==="waiting_for_confirmation"&&d(a),h.current=t},[t,a]),{elapsedTime:t==="waiting_for_confirmation"?c:a,currentLoadingPhrase:u}};var G7=Ve(lr(),1);var Rnr={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",blanchedalmond:"#ffebcd",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgrey:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",whitesmoke:"#f5f5f5",yellowgreen:"#9acd32"},kLn=new Set(["black","red","green","yellow","blue","cyan","magenta","white","gray","grey","blackbright","redbright","greenbright","yellowbright","bluebright","cyanbright","magentabright","whitebright"]);function Nnr(t){let e=t.toLowerCase();if(e.startsWith("#"))return/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/.test(t)?e:void 0;if(kLn.has(e))return e;if(Rnr[e])return Rnr[e];console.warn(`[ColorUtils] Could not resolve color "${t}" to an Ink-compatible format.`)}var mi={type:"light",Background:"#FAFAFA",Foreground:"#3C3C43",LightBlue:"#89BDCD",AccentBlue:"#3B82F6",AccentPurple:"#8B5CF6",AccentCyan:"#06B6D4",AccentGreen:"#3CA84B",AccentYellow:"#D5A40A",AccentRed:"#DD4C4C",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#008000",Gray:"#97a0b0",GradientColors:["#4796E4","#847ACE","#C3677F"]},Pn={type:"dark",Background:"#1E1E2E",Foreground:"#CDD6F4",LightBlue:"#ADD8E6",AccentBlue:"#89B4FA",AccentPurple:"#CBA6F7",AccentCyan:"#89DCEB",AccentGreen:"#A6E3A1",AccentYellow:"#F9E2AF",AccentRed:"#F38BA8",DiffAdded:"#28350B",DiffRemoved:"#430000",Comment:"#6C7086",Gray:"#6C7086",GradientColors:["#8b20c5ff","#e4b424ff","#C3677F"]},_0={type:"ansi",Background:"black",Foreground:"white",LightBlue:"blue",AccentBlue:"blue",AccentPurple:"magenta",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"yellow",AccentRed:"red",DiffAdded:"green",DiffRemoved:"red",Comment:"gray",Gray:"gray"},oo=class t{constructor(e,r,n,i,a){this.name=e;this.type=r;this.colors=i;this.semanticColors=a;this._colorMap=Object.freeze(this._buildColorMap(n));let s=n.hljs?.color;this.defaultColor=(s?t._resolveColor(s):void 0)??""}defaultColor;_colorMap;getInkColor(e){return this._colorMap[e]}static _resolveColor(e){return Nnr(e)}_buildColorMap(e){let r={};for(let n in e){if(!n.startsWith("hljs-")&&n!=="hljs")continue;let i=e[n];if(i?.color){let a=t._resolveColor(i.color);a!==void 0&&(r[n]=a)}}return r}};function Onr(t){let e={type:"custom",Background:t.background?.primary??t.Background??"",Foreground:t.text?.primary??t.Foreground??"",LightBlue:t.text?.link??t.LightBlue??"",AccentBlue:t.text?.link??t.AccentBlue??"",AccentPurple:t.text?.accent??t.AccentPurple??"",AccentCyan:t.text?.link??t.AccentCyan??"",AccentGreen:t.status?.success??t.AccentGreen??"",AccentYellow:t.status?.warning??t.AccentYellow??"",AccentRed:t.status?.error??t.AccentRed??"",DiffAdded:t.background?.diff?.added??t.DiffAdded??"",DiffRemoved:t.background?.diff?.removed??t.DiffRemoved??"",Comment:t.ui?.comment??t.Comment??"",Gray:t.text?.secondary??t.Gray??"",GradientColors:t.ui?.gradient??t.GradientColors},r={hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:e.Background,color:e.Foreground},"hljs-keyword":{color:e.AccentBlue},"hljs-literal":{color:e.AccentBlue},"hljs-symbol":{color:e.AccentBlue},"hljs-name":{color:e.AccentBlue},"hljs-link":{color:e.AccentBlue,textDecoration:"underline"},"hljs-built_in":{color:e.AccentCyan},"hljs-type":{color:e.AccentCyan},"hljs-number":{color:e.AccentGreen},"hljs-class":{color:e.AccentGreen},"hljs-string":{color:e.AccentYellow},"hljs-meta-string":{color:e.AccentYellow},"hljs-regexp":{color:e.AccentRed},"hljs-template-tag":{color:e.AccentRed},"hljs-subst":{color:e.Foreground},"hljs-function":{color:e.Foreground},"hljs-title":{color:e.Foreground},"hljs-params":{color:e.Foreground},"hljs-formula":{color:e.Foreground},"hljs-comment":{color:e.Comment,fontStyle:"italic"},"hljs-quote":{color:e.Comment,fontStyle:"italic"},"hljs-doctag":{color:e.Comment},"hljs-meta":{color:e.Gray},"hljs-meta-keyword":{color:e.Gray},"hljs-tag":{color:e.Gray},"hljs-variable":{color:e.AccentPurple},"hljs-template-variable":{color:e.AccentPurple},"hljs-attr":{color:e.LightBlue},"hljs-attribute":{color:e.LightBlue},"hljs-builtin-name":{color:e.LightBlue},"hljs-section":{color:e.AccentYellow},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{color:e.AccentYellow},"hljs-selector-tag":{color:e.AccentYellow},"hljs-selector-id":{color:e.AccentYellow},"hljs-selector-class":{color:e.AccentYellow},"hljs-selector-attr":{color:e.AccentYellow},"hljs-selector-pseudo":{color:e.AccentYellow},"hljs-addition":{backgroundColor:e.AccentGreen,display:"inline-block",width:"100%"},"hljs-deletion":{backgroundColor:e.AccentRed,display:"inline-block",width:"100%"}},n={text:{primary:e.Foreground,secondary:e.Gray,link:e.AccentBlue,accent:e.AccentPurple},background:{primary:e.Background,diff:{added:e.DiffAdded,removed:e.DiffRemoved}},border:{default:e.Gray,focused:e.AccentBlue},ui:{comment:e.Comment,symbol:e.Gray,gradient:e.GradientColors},status:{error:e.AccentRed,success:e.AccentGreen,warning:e.AccentYellow}};return new oo(t.name,"custom",r,e,n)}function Fnr(t){return t.name&&!ULn(t.name)?{isValid:!1,error:`Invalid theme name: ${t.name}`}:{isValid:!0}}function ULn(t){return t.trim().length>0&&t.trim().length<=50}var H6={text:{primary:mi.Foreground,secondary:mi.Gray,link:mi.AccentBlue,accent:mi.AccentPurple},background:{primary:mi.Background,diff:{added:mi.DiffAdded,removed:mi.DiffRemoved}},border:{default:mi.Gray,focused:mi.AccentBlue},ui:{comment:mi.Comment,symbol:mi.Gray,gradient:mi.GradientColors},status:{error:mi.AccentRed,success:mi.AccentGreen,warning:mi.AccentYellow}},Xh={text:{primary:Pn.Foreground,secondary:Pn.Gray,link:Pn.AccentBlue,accent:Pn.AccentPurple},background:{primary:Pn.Background,diff:{added:Pn.DiffAdded,removed:Pn.DiffRemoved}},border:{default:Pn.Gray,focused:Pn.AccentBlue},ui:{comment:Pn.Comment,symbol:Pn.Gray,gradient:Pn.GradientColors},status:{error:Pn.AccentRed,success:Pn.AccentGreen,warning:Pn.AccentYellow}},cGi={text:{primary:_0.Foreground,secondary:_0.Gray,link:_0.AccentBlue,accent:_0.AccentPurple},background:{primary:_0.Background,diff:{added:_0.DiffAdded,removed:_0.DiffRemoved}},border:{default:_0.Gray,focused:_0.AccentBlue},ui:{comment:_0.Comment,symbol:_0.Gray,gradient:_0.GradientColors},status:{error:_0.AccentRed,success:_0.AccentGreen,warning:_0.AccentYellow}};var Gu={type:"dark",Background:"#0b0e14",Foreground:"#bfbdb6",LightBlue:"#59C2FF",AccentBlue:"#39BAE6",AccentPurple:"#D2A6FF",AccentCyan:"#95E6CB",AccentGreen:"#AAD94C",AccentYellow:"#FFB454",AccentRed:"#F26D78",DiffAdded:"#293022",DiffRemoved:"#3D1215",Comment:"#646A71",Gray:"#3D4149",GradientColors:["#FFB454","#F26D78"]},Mnr=new oo("Ayu","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Gu.Background,color:Gu.Foreground},"hljs-keyword":{color:Gu.AccentYellow},"hljs-literal":{color:Gu.AccentPurple},"hljs-symbol":{color:Gu.AccentCyan},"hljs-name":{color:Gu.LightBlue},"hljs-link":{color:Gu.AccentBlue},"hljs-function .hljs-keyword":{color:Gu.AccentYellow},"hljs-subst":{color:Gu.Foreground},"hljs-string":{color:Gu.AccentGreen},"hljs-title":{color:Gu.AccentYellow},"hljs-type":{color:Gu.AccentBlue},"hljs-attribute":{color:Gu.AccentYellow},"hljs-bullet":{color:Gu.AccentYellow},"hljs-addition":{color:Gu.AccentGreen},"hljs-variable":{color:Gu.Foreground},"hljs-template-tag":{color:Gu.AccentYellow},"hljs-template-variable":{color:Gu.AccentYellow},"hljs-comment":{color:Gu.Comment,fontStyle:"italic"},"hljs-quote":{color:Gu.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:Gu.AccentRed},"hljs-meta":{color:Gu.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Gu,Xh);var Ws={type:"light",Background:"#f8f9fa",Foreground:"#5c6166",LightBlue:"#55b4d4",AccentBlue:"#399ee6",AccentPurple:"#a37acc",AccentCyan:"#4cbf99",AccentGreen:"#86b300",AccentYellow:"#f2ae49",AccentRed:"#f07171",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#ABADB1",Gray:"#a6aaaf",GradientColors:["#399ee6","#86b300"]},Lnr=new oo("Ayu Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ws.Background,color:Ws.Foreground},"hljs-comment":{color:Ws.Comment,fontStyle:"italic"},"hljs-quote":{color:Ws.AccentCyan,fontStyle:"italic"},"hljs-string":{color:Ws.AccentGreen},"hljs-constant":{color:Ws.AccentCyan},"hljs-number":{color:Ws.AccentPurple},"hljs-keyword":{color:Ws.AccentYellow},"hljs-selector-tag":{color:Ws.AccentYellow},"hljs-attribute":{color:Ws.AccentYellow},"hljs-variable":{color:Ws.Foreground},"hljs-variable.language":{color:Ws.LightBlue,fontStyle:"italic"},"hljs-title":{color:Ws.AccentBlue},"hljs-section":{color:Ws.AccentGreen,fontWeight:"bold"},"hljs-type":{color:Ws.LightBlue},"hljs-class .hljs-title":{color:Ws.AccentBlue},"hljs-tag":{color:Ws.LightBlue},"hljs-name":{color:Ws.AccentBlue},"hljs-builtin-name":{color:Ws.AccentYellow},"hljs-meta":{color:Ws.AccentYellow},"hljs-symbol":{color:Ws.AccentRed},"hljs-bullet":{color:Ws.AccentYellow},"hljs-regexp":{color:Ws.AccentCyan},"hljs-link":{color:Ws.LightBlue},"hljs-deletion":{color:Ws.AccentRed},"hljs-addition":{color:Ws.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-literal":{color:Ws.AccentCyan},"hljs-built_in":{color:Ws.AccentRed},"hljs-doctag":{color:Ws.AccentRed},"hljs-template-variable":{color:Ws.AccentCyan},"hljs-selector-id":{color:Ws.AccentRed}},Ws,H6);var As={type:"dark",Background:"#282c34",Foreground:"#abb2bf",LightBlue:"#61aeee",AccentBlue:"#61aeee",AccentPurple:"#c678dd",AccentCyan:"#56b6c2",AccentGreen:"#98c379",AccentYellow:"#e6c07b",AccentRed:"#e06c75",DiffAdded:"#39544E",DiffRemoved:"#562B2F",Comment:"#5c6370",Gray:"#5c6370",GradientColors:["#61aeee","#98c379"]},Pnr=new oo("Atom One","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:As.Foreground,background:As.Background},"hljs-comment":{color:As.Comment,fontStyle:"italic"},"hljs-quote":{color:As.Comment,fontStyle:"italic"},"hljs-doctag":{color:As.AccentPurple},"hljs-keyword":{color:As.AccentPurple},"hljs-formula":{color:As.AccentPurple},"hljs-section":{color:As.AccentRed},"hljs-name":{color:As.AccentRed},"hljs-selector-tag":{color:As.AccentRed},"hljs-deletion":{color:As.AccentRed},"hljs-subst":{color:As.AccentRed},"hljs-literal":{color:As.AccentCyan},"hljs-string":{color:As.AccentGreen},"hljs-regexp":{color:As.AccentGreen},"hljs-addition":{color:As.AccentGreen},"hljs-attribute":{color:As.AccentGreen},"hljs-meta-string":{color:As.AccentGreen},"hljs-built_in":{color:As.AccentYellow},"hljs-class .hljs-title":{color:As.AccentYellow},"hljs-attr":{color:As.AccentYellow},"hljs-variable":{color:As.AccentYellow},"hljs-template-variable":{color:As.AccentYellow},"hljs-type":{color:As.AccentYellow},"hljs-selector-class":{color:As.AccentYellow},"hljs-selector-attr":{color:As.AccentYellow},"hljs-selector-pseudo":{color:As.AccentYellow},"hljs-number":{color:As.AccentYellow},"hljs-symbol":{color:As.AccentBlue},"hljs-bullet":{color:As.AccentBlue},"hljs-link":{color:As.AccentBlue,textDecoration:"underline"},"hljs-meta":{color:As.AccentBlue},"hljs-selector-id":{color:As.AccentBlue},"hljs-title":{color:As.AccentBlue},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},As,Xh);var Yl={type:"dark",Background:"#282a36",Foreground:"#f8f8f2",LightBlue:"#8be9fd",AccentBlue:"#8be9fd",AccentPurple:"#ff79c6",AccentCyan:"#8be9fd",AccentGreen:"#50fa7b",AccentYellow:"#f1fa8c",AccentRed:"#ff5555",DiffAdded:"#11431d",DiffRemoved:"#6e1818",Comment:"#6272a4",Gray:"#6272a4",GradientColors:["#ff79c6","#8be9fd"]},Qnr=new oo("Dracula","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Yl.Background,color:Yl.Foreground},"hljs-keyword":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-selector-tag":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-literal":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-section":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-link":{color:Yl.AccentBlue},"hljs-function .hljs-keyword":{color:Yl.AccentPurple},"hljs-subst":{color:Yl.Foreground},"hljs-string":{color:Yl.AccentYellow},"hljs-title":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-name":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-type":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-attribute":{color:Yl.AccentYellow},"hljs-symbol":{color:Yl.AccentYellow},"hljs-bullet":{color:Yl.AccentYellow},"hljs-addition":{color:Yl.AccentGreen},"hljs-variable":{color:Yl.AccentYellow},"hljs-template-tag":{color:Yl.AccentYellow},"hljs-template-variable":{color:Yl.AccentYellow},"hljs-comment":{color:Yl.Comment},"hljs-quote":{color:Yl.Comment},"hljs-deletion":{color:Yl.AccentRed},"hljs-meta":{color:Yl.Comment},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Yl,Xh);var zs={type:"dark",Background:"#24292e",Foreground:"#d1d5da",LightBlue:"#79B8FF",AccentBlue:"#79B8FF",AccentPurple:"#B392F0",AccentCyan:"#9ECBFF",AccentGreen:"#85E89D",AccentYellow:"#FFAB70",AccentRed:"#F97583",DiffAdded:"#3C4636",DiffRemoved:"#502125",Comment:"#6A737D",Gray:"#6A737D",GradientColors:["#79B8FF","#85E89D"]},knr=new oo("GitHub","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:zs.Foreground,background:zs.Background},"hljs-comment":{color:zs.Comment,fontStyle:"italic"},"hljs-quote":{color:zs.Comment,fontStyle:"italic"},"hljs-keyword":{color:zs.AccentRed,fontWeight:"bold"},"hljs-selector-tag":{color:zs.AccentRed,fontWeight:"bold"},"hljs-subst":{color:zs.Foreground},"hljs-number":{color:zs.LightBlue},"hljs-literal":{color:zs.LightBlue},"hljs-variable":{color:zs.AccentYellow},"hljs-template-variable":{color:zs.AccentYellow},"hljs-tag .hljs-attr":{color:zs.AccentYellow},"hljs-string":{color:zs.AccentCyan},"hljs-doctag":{color:zs.AccentCyan},"hljs-title":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-section":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-type":{color:zs.AccentGreen,fontWeight:"bold"},"hljs-class .hljs-title":{color:zs.AccentGreen,fontWeight:"bold"},"hljs-tag":{color:zs.AccentGreen},"hljs-name":{color:zs.AccentGreen},"hljs-attribute":{color:zs.LightBlue},"hljs-regexp":{color:zs.AccentCyan},"hljs-link":{color:zs.AccentCyan},"hljs-symbol":{color:zs.AccentPurple},"hljs-bullet":{color:zs.AccentPurple},"hljs-built_in":{color:zs.LightBlue},"hljs-builtin-name":{color:zs.LightBlue},"hljs-meta":{color:zs.LightBlue,fontWeight:"bold"},"hljs-deletion":{background:"#86181D",color:zs.AccentRed},"hljs-addition":{background:"#144620",color:zs.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},zs,Xh);var yo={type:"light",Background:"#f8f8f8",Foreground:"#24292E",LightBlue:"#0086b3",AccentBlue:"#458",AccentPurple:"#900",AccentCyan:"#009926",AccentGreen:"#008080",AccentYellow:"#990073",AccentRed:"#d14",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#998",Gray:"#999",GradientColors:["#458","#008080"]},Unr=new oo("GitHub Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:yo.Foreground,background:yo.Background},"hljs-comment":{color:yo.Comment,fontStyle:"italic"},"hljs-quote":{color:yo.Comment,fontStyle:"italic"},"hljs-keyword":{color:yo.Foreground,fontWeight:"bold"},"hljs-selector-tag":{color:yo.Foreground,fontWeight:"bold"},"hljs-subst":{color:yo.Foreground,fontWeight:"normal"},"hljs-number":{color:yo.AccentGreen},"hljs-literal":{color:yo.AccentGreen},"hljs-variable":{color:yo.AccentGreen},"hljs-template-variable":{color:yo.AccentGreen},"hljs-tag .hljs-attr":{color:yo.AccentGreen},"hljs-string":{color:yo.AccentRed},"hljs-doctag":{color:yo.AccentRed},"hljs-title":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:yo.AccentBlue,fontWeight:"bold"},"hljs-class .hljs-title":{color:yo.AccentBlue,fontWeight:"bold"},"hljs-tag":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-name":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-attribute":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-regexp":{color:yo.AccentCyan},"hljs-link":{color:yo.AccentCyan},"hljs-symbol":{color:yo.AccentYellow},"hljs-bullet":{color:yo.AccentYellow},"hljs-built_in":{color:yo.LightBlue},"hljs-builtin-name":{color:yo.LightBlue},"hljs-meta":{color:yo.Gray,fontWeight:"bold"},"hljs-deletion":{background:"#fdd"},"hljs-addition":{background:"#dfd"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},yo,H6);var Ks={type:"light",Background:"white",Foreground:"#444",LightBlue:"#066",AccentBlue:"#008",AccentPurple:"#606",AccentCyan:"#066",AccentGreen:"#080",AccentYellow:"#660",AccentRed:"#800",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#5f6368",Gray:mi.Gray,GradientColors:["#066","#606"]},Hnr=new oo("Google Code","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ks.Background,color:Ks.Foreground},"hljs-comment":{color:Ks.AccentRed},"hljs-quote":{color:Ks.AccentRed},"hljs-keyword":{color:Ks.AccentBlue},"hljs-selector-tag":{color:Ks.AccentBlue},"hljs-section":{color:Ks.AccentBlue},"hljs-title":{color:Ks.AccentPurple},"hljs-name":{color:Ks.AccentBlue},"hljs-variable":{color:Ks.AccentYellow},"hljs-template-variable":{color:Ks.AccentYellow},"hljs-string":{color:Ks.AccentGreen},"hljs-selector-attr":{color:Ks.AccentGreen},"hljs-selector-pseudo":{color:Ks.AccentGreen},"hljs-regexp":{color:Ks.AccentGreen},"hljs-literal":{color:Ks.AccentCyan},"hljs-symbol":{color:Ks.AccentCyan},"hljs-bullet":{color:Ks.AccentCyan},"hljs-meta":{color:Ks.AccentCyan},"hljs-number":{color:Ks.AccentCyan},"hljs-link":{color:Ks.AccentCyan},"hljs-doctag":{color:Ks.AccentPurple,fontWeight:"bold"},"hljs-type":{color:Ks.AccentPurple},"hljs-attr":{color:Ks.AccentPurple},"hljs-built_in":{color:Ks.AccentPurple},"hljs-builtin-name":{color:Ks.AccentPurple},"hljs-params":{color:Ks.AccentPurple},"hljs-attribute":{color:Ks.Foreground},"hljs-subst":{color:Ks.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-selector-id":{color:Ks.AccentYellow},"hljs-selector-class":{color:Ks.AccentYellow},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Ks,H6);var VJ=new oo("Default Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:mi.Background,color:mi.Foreground},"hljs-comment":{color:mi.Comment},"hljs-quote":{color:mi.Comment},"hljs-variable":{color:mi.Foreground},"hljs-keyword":{color:mi.AccentBlue},"hljs-selector-tag":{color:mi.AccentBlue},"hljs-built_in":{color:mi.AccentBlue},"hljs-name":{color:mi.AccentBlue},"hljs-tag":{color:mi.AccentBlue},"hljs-string":{color:mi.AccentRed},"hljs-title":{color:mi.AccentRed},"hljs-section":{color:mi.AccentRed},"hljs-attribute":{color:mi.AccentRed},"hljs-literal":{color:mi.AccentRed},"hljs-template-tag":{color:mi.AccentRed},"hljs-template-variable":{color:mi.AccentRed},"hljs-type":{color:mi.AccentRed},"hljs-addition":{color:mi.AccentGreen},"hljs-deletion":{color:mi.AccentRed},"hljs-selector-attr":{color:mi.AccentCyan},"hljs-selector-pseudo":{color:mi.AccentCyan},"hljs-meta":{color:mi.AccentCyan},"hljs-doctag":{color:mi.Gray},"hljs-attr":{color:mi.AccentRed},"hljs-symbol":{color:mi.AccentCyan},"hljs-bullet":{color:mi.AccentCyan},"hljs-link":{color:mi.AccentCyan},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},mi,H6);var qU=new oo("Default","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Pn.Background,color:Pn.Foreground},"hljs-keyword":{color:Pn.AccentBlue},"hljs-literal":{color:Pn.AccentBlue},"hljs-symbol":{color:Pn.AccentBlue},"hljs-name":{color:Pn.AccentBlue},"hljs-link":{color:Pn.AccentBlue,textDecoration:"underline"},"hljs-built_in":{color:Pn.AccentCyan},"hljs-type":{color:Pn.AccentCyan},"hljs-number":{color:Pn.AccentGreen},"hljs-class":{color:Pn.AccentGreen},"hljs-string":{color:Pn.AccentYellow},"hljs-meta-string":{color:Pn.AccentYellow},"hljs-regexp":{color:Pn.AccentRed},"hljs-template-tag":{color:Pn.AccentRed},"hljs-subst":{color:Pn.Foreground},"hljs-function":{color:Pn.Foreground},"hljs-title":{color:Pn.Foreground},"hljs-params":{color:Pn.Foreground},"hljs-formula":{color:Pn.Foreground},"hljs-comment":{color:Pn.Comment,fontStyle:"italic"},"hljs-quote":{color:Pn.Comment,fontStyle:"italic"},"hljs-doctag":{color:Pn.Comment},"hljs-meta":{color:Pn.Gray},"hljs-meta-keyword":{color:Pn.Gray},"hljs-tag":{color:Pn.Gray},"hljs-variable":{color:Pn.AccentPurple},"hljs-template-variable":{color:Pn.AccentPurple},"hljs-attr":{color:Pn.LightBlue},"hljs-attribute":{color:Pn.LightBlue},"hljs-builtin-name":{color:Pn.LightBlue},"hljs-section":{color:Pn.AccentYellow},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{color:Pn.AccentYellow},"hljs-selector-tag":{color:Pn.AccentYellow},"hljs-selector-id":{color:Pn.AccentYellow},"hljs-selector-class":{color:Pn.AccentYellow},"hljs-selector-attr":{color:Pn.AccentYellow},"hljs-selector-pseudo":{color:Pn.AccentYellow},"hljs-addition":{backgroundColor:"#144212",display:"inline-block",width:"100%"},"hljs-deletion":{backgroundColor:"#600",display:"inline-block",width:"100%"}},Pn,Xh);var Bi={type:"dark",Background:"#2d2b57",Foreground:"#e3dfff",LightBlue:"#847ace",AccentBlue:"#a599e9",AccentPurple:"#ac65ff",AccentCyan:"#a1feff",AccentGreen:"#A5FF90",AccentYellow:"#fad000",AccentRed:"#ff628c",DiffAdded:"#383E45",DiffRemoved:"#572244",Comment:"#B362FF",Gray:"#726c86",GradientColors:["#4d21fc","#847ace","#ff628c"]},Sp={AccentYellowAlt:"#f8d000",AccentOrange:"#fb9e00",AccentPink:"#fa658d",AccentLightPurple:"#c991ff",AccentDarkPurple:"#6943ff",AccentTeal:"#2ee2fa"},Gnr=new oo("Shades Of Purple","dark",{hljs:{display:"block",overflowX:"auto",background:Bi.Background,color:Bi.Foreground},"hljs-title":{color:Bi.AccentYellow,fontWeight:"normal"},"hljs-name":{color:Bi.AccentCyan,fontWeight:"normal"},"hljs-tag":{color:Bi.Foreground},"hljs-attr":{color:Sp.AccentYellowAlt,fontStyle:"italic"},"hljs-built_in":{color:Sp.AccentOrange},"hljs-selector-tag":{color:Sp.AccentOrange,fontWeight:"normal"},"hljs-section":{color:Sp.AccentOrange},"hljs-keyword":{color:Sp.AccentOrange,fontWeight:"normal"},"hljs-subst":{color:Bi.Foreground},"hljs-string":{color:Bi.AccentGreen},"hljs-attribute":{color:Bi.AccentGreen},"hljs-symbol":{color:Bi.AccentGreen},"hljs-bullet":{color:Bi.AccentGreen},"hljs-addition":{color:Bi.AccentGreen},"hljs-code":{color:Bi.AccentGreen},"hljs-regexp":{color:Bi.AccentGreen},"hljs-selector-class":{color:Bi.AccentGreen},"hljs-selector-attr":{color:Bi.AccentGreen},"hljs-selector-pseudo":{color:Bi.AccentGreen},"hljs-template-tag":{color:Bi.AccentGreen},"hljs-quote":{color:Bi.AccentGreen},"hljs-deletion":{color:Bi.AccentRed},"hljs-meta":{color:Sp.AccentOrange},"hljs-meta-string":{color:Sp.AccentOrange},"hljs-comment":{color:Bi.AccentPurple},"hljs-literal":{color:Sp.AccentPink,fontWeight:"normal"},"hljs-number":{color:Sp.AccentPink},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-diff":{color:Bi.Foreground},"hljs-meta.hljs-diff":{color:Bi.AccentBlue},"hljs-ln":{color:Bi.Gray},"hljs-type":{color:Bi.AccentYellow,fontWeight:"normal"},"hljs-variable":{color:Bi.AccentYellow},"hljs-template-variable":{color:Bi.AccentGreen},"hljs-function .hljs-keyword":{color:Sp.AccentOrange},"hljs-link":{color:Bi.LightBlue},"hljs-doctag":{fontWeight:"bold"},"hljs-params":{color:Sp.AccentLightPurple,fontStyle:"italic"},"hljs-class":{color:Bi.AccentCyan,fontWeight:"bold"},"hljs-function":{color:Bi.AccentCyan},"hljs-property":{color:Bi.AccentBlue},"hljs-operator":{color:Sp.AccentDarkPurple},"hljs-punctuation":{color:Bi.Gray},"hljs-selector-id":{color:Bi.AccentYellow,fontWeight:"bold"},"hljs-char":{color:Bi.AccentGreen},"hljs-escape":{color:Sp.AccentPink,fontWeight:"bold"},"hljs-meta-keyword":{color:Sp.AccentOrange,fontWeight:"bold"},"hljs-builtin-name":{color:Sp.AccentTeal},"hljs-module":{color:Bi.AccentCyan},"hljs-namespace":{color:Bi.LightBlue},"hljs-important":{color:Bi.AccentRed,fontWeight:"bold"},"hljs-formula":{color:Bi.AccentCyan,fontStyle:"italic"},"hljs-decorator":{color:Sp.AccentTeal,fontWeight:"bold"},"hljs-symbol.ruby":{color:Sp.AccentPink},"hljs-keyword.sql":{color:Sp.AccentOrange,textTransform:"uppercase"},"hljs-section.markdown":{color:Bi.AccentYellow,fontWeight:"bold"},"hljs-attr.json":{color:Bi.AccentCyan},"hljs-tag .hljs-name":{color:Bi.AccentRed},"hljs-tag .hljs-attr":{color:Sp.AccentYellowAlt},"hljs.hljs-line-numbers":{borderRight:`1px solid ${Bi.Gray}`},"hljs.hljs-line-numbers .hljs-ln-numbers":{color:Bi.Gray,paddingRight:"1em"},"hljs.hljs-line-numbers .hljs-ln-code":{paddingLeft:"1em"},"hljs::selection":{background:Bi.AccentBlue+"40"},"hljs ::-moz-selection":{background:Bi.AccentBlue+"40"},"hljs .hljs-highlight":{background:Bi.AccentPurple+"20",display:"block",width:"100%"}},Bi,Xh);var Is={type:"light",Background:"#fff",Foreground:"#444",LightBlue:"#0E0EFF",AccentBlue:"#1c00cf",AccentPurple:"#aa0d91",AccentCyan:"#3F6E74",AccentGreen:"#007400",AccentYellow:"#836C28",AccentRed:"#c41a16",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#007400",Gray:"#c0c0c0",GradientColors:["#1c00cf","#007400"]},Vnr=new oo("Xcode","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Is.Background,color:Is.Foreground},"xml .hljs-meta":{color:Is.Gray},"hljs-comment":{color:Is.Comment},"hljs-quote":{color:Is.Comment},"hljs-tag":{color:Is.AccentPurple},"hljs-attribute":{color:Is.AccentPurple},"hljs-keyword":{color:Is.AccentPurple},"hljs-selector-tag":{color:Is.AccentPurple},"hljs-literal":{color:Is.AccentPurple},"hljs-name":{color:Is.AccentPurple},"hljs-variable":{color:Is.AccentCyan},"hljs-template-variable":{color:Is.AccentCyan},"hljs-code":{color:Is.AccentRed},"hljs-string":{color:Is.AccentRed},"hljs-meta-string":{color:Is.AccentRed},"hljs-regexp":{color:Is.LightBlue},"hljs-link":{color:Is.LightBlue},"hljs-title":{color:Is.AccentBlue},"hljs-symbol":{color:Is.AccentBlue},"hljs-bullet":{color:Is.AccentBlue},"hljs-number":{color:Is.AccentBlue},"hljs-section":{color:Is.AccentYellow},"hljs-meta":{color:Is.AccentYellow},"hljs-class .hljs-title":{color:Is.AccentPurple},"hljs-type":{color:Is.AccentPurple},"hljs-built_in":{color:Is.AccentPurple},"hljs-builtin-name":{color:Is.AccentPurple},"hljs-params":{color:Is.AccentPurple},"hljs-attr":{color:Is.AccentYellow},"hljs-subst":{color:Is.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-selector-id":{color:Is.AccentYellow},"hljs-selector-class":{color:Is.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Is,H6);var HLn={type:"dark",Background:"black",Foreground:"white",LightBlue:"bluebright",AccentBlue:"blue",AccentPurple:"magenta",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"yellow",AccentRed:"red",DiffAdded:"#003300",DiffRemoved:"#4D0000",Comment:"gray",Gray:"gray",GradientColors:["cyan","green"]},qnr=new oo("ANSI","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"black",color:"white"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"yellow"},"hljs-meta-string":{color:"yellow"},"hljs-regexp":{color:"red"},"hljs-template-tag":{color:"red"},"hljs-subst":{color:"white"},"hljs-function":{color:"white"},"hljs-title":{color:"white"},"hljs-params":{color:"white"},"hljs-formula":{color:"white"},"hljs-comment":{color:"green"},"hljs-quote":{color:"green"},"hljs-doctag":{color:"green"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"magenta"},"hljs-template-variable":{color:"magenta"},"hljs-attr":{color:"bluebright"},"hljs-attribute":{color:"bluebright"},"hljs-builtin-name":{color:"bluebright"},"hljs-section":{color:"yellow"},"hljs-emphasis":{},"hljs-strong":{},"hljs-bullet":{color:"yellow"},"hljs-selector-tag":{color:"yellow"},"hljs-selector-id":{color:"yellow"},"hljs-selector-class":{color:"yellow"},"hljs-selector-attr":{color:"yellow"},"hljs-selector-pseudo":{color:"yellow"}},HLn,Xh);var GLn={type:"light",Background:"white",Foreground:"#444",LightBlue:"blue",AccentBlue:"blue",AccentPurple:"purple",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"orange",AccentRed:"red",DiffAdded:"#E5F2E5",DiffRemoved:"#FFE5E5",Comment:"gray",Gray:"gray",GradientColors:["blue","green"]},$nr=new oo("ANSI Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"white",color:"black"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"red"},"hljs-meta-string":{color:"red"},"hljs-regexp":{color:"magenta"},"hljs-template-tag":{color:"magenta"},"hljs-subst":{color:"black"},"hljs-function":{color:"black"},"hljs-title":{color:"black"},"hljs-params":{color:"black"},"hljs-formula":{color:"black"},"hljs-comment":{color:"gray"},"hljs-quote":{color:"gray"},"hljs-doctag":{color:"gray"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"purple"},"hljs-template-variable":{color:"purple"},"hljs-attr":{color:"blue"},"hljs-attribute":{color:"blue"},"hljs-builtin-name":{color:"blue"},"hljs-section":{color:"orange"},"hljs-bullet":{color:"orange"},"hljs-selector-tag":{color:"orange"},"hljs-selector-id":{color:"orange"},"hljs-selector-class":{color:"orange"},"hljs-selector-attr":{color:"orange"},"hljs-selector-pseudo":{color:"orange"}},GLn,H6);var VLn={type:"ansi",Background:"",Foreground:"",LightBlue:"",AccentBlue:"",AccentPurple:"",AccentCyan:"",AccentGreen:"",AccentYellow:"",AccentRed:"",DiffAdded:"",DiffRemoved:"",Comment:"",Gray:""},qLn={text:{primary:"",secondary:"",link:"",accent:""},background:{primary:"",diff:{added:"",removed:""}},border:{default:"",focused:""},ui:{comment:"",symbol:"",gradient:[]},status:{error:"",success:"",warning:""}},jnr=new oo("NoColor","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em"},"hljs-keyword":{},"hljs-literal":{},"hljs-symbol":{},"hljs-name":{},"hljs-link":{textDecoration:"underline"},"hljs-built_in":{},"hljs-type":{},"hljs-number":{},"hljs-class":{},"hljs-string":{},"hljs-meta-string":{},"hljs-regexp":{},"hljs-template-tag":{},"hljs-subst":{},"hljs-function":{},"hljs-title":{},"hljs-params":{},"hljs-formula":{},"hljs-comment":{fontStyle:"italic"},"hljs-quote":{fontStyle:"italic"},"hljs-doctag":{},"hljs-meta":{},"hljs-meta-keyword":{},"hljs-tag":{},"hljs-variable":{},"hljs-template-variable":{},"hljs-attr":{},"hljs-attribute":{},"hljs-builtin-name":{},"hljs-section":{},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{},"hljs-selector-tag":{},"hljs-selector-id":{},"hljs-selector-class":{},"hljs-selector-attr":{},"hljs-selector-pseudo":{},"hljs-addition":{display:"inline-block",width:"100%"},"hljs-deletion":{display:"inline-block",width:"100%"}},VLn,qLn);import $Ln from"node:process";var H7=qU,Eqe=class{availableThemes;activeTheme;customThemes=new Map;constructor(){this.availableThemes=[Mnr,Lnr,Pnr,Qnr,VJ,qU,knr,Unr,Hnr,Gnr,Vnr,qnr,$nr],this.activeTheme=H7}loadCustomThemes(e){if(this.customThemes.clear(),!!e){for(let[r,n]of Object.entries(e)){let i=Fnr(n);if(i.isValid){i.warning&&console.warn(`Theme "${r}": ${i.warning}`);let a={...H7.colors,...n,name:n.name||r,type:"custom"};try{let s=Onr(a);this.customThemes.set(r,s)}catch(s){console.warn(`Failed to load custom theme "${r}":`,s)}}else console.warn(`Invalid custom theme "${r}": ${i.error}`)}this.activeTheme&&this.activeTheme.type==="custom"&&this.customThemes.has(this.activeTheme.name)&&(this.activeTheme=this.customThemes.get(this.activeTheme.name))}}setActiveTheme(e){let r=this.findThemeByName(e);return r?(this.activeTheme=r,!0):!1}getActiveTheme(){return $Ln.env.NO_COLOR?jnr:((!this.activeTheme||!this.findThemeByName(this.activeTheme.name))&&(this.activeTheme=H7),this.activeTheme)}getSemanticColors(){return this.getActiveTheme().semanticColors}getCustomThemeNames(){return Array.from(this.customThemes.keys())}isCustomTheme(e){return this.customThemes.has(e)}getAvailableThemes(){let e=this.availableThemes.map(a=>({name:a.name,type:a.type,isCustom:!1})),r=Array.from(this.customThemes.values()).map(a=>({name:a.name,type:a.type,isCustom:!0}));return[...e,...r].sort((a,s)=>{let o=u=>{switch(u){case"dark":return 1;case"light":return 2;case"ansi":return 3;case"custom":return 4;default:return 5}},l=o(a.type)-o(s.type);return l!==0?l:a.name.localeCompare(s.name)})}getTheme(e){return this.findThemeByName(e)}findThemeByName(e){if(!e)return H7;let r=this.availableThemes.find(n=>n.name===e);return r||this.customThemes.get(e)}},rs=new Eqe;import jLn from"node:process";var Ynr=(t,e,r)=>{let[n,i]=(0,G7.useState)(!1);(0,G7.useEffect)(()=>{let u=t.merged.theme;u&&!rs.findThemeByName(u)?(i(!0),e(`Theme "${u}" not found.`)):e(null)},[t.merged.theme,e]);let a=(0,G7.useCallback)(()=>{if(jLn.env.NO_COLOR){r({type:"info",text:"Theme configuration unavailable due to NO_COLOR env variable."},Date.now());return}i(!0)},[r]),s=(0,G7.useCallback)(u=>{rs.setActiveTheme(u)?e(null):(i(!0),e(`Theme "${u}" not found.`))},[e]),o=(0,G7.useCallback)(u=>{s(u)},[s]),l=(0,G7.useCallback)((u,c)=>{try{let d={...t.user.settings.customThemes||{},...t.workspace.settings.customThemes||{}},h=rs.findThemeByName(u),f=u&&d[u];if(!h&&!f){e(`Theme "${u}" not found in selected scope.`),i(!0);return}t.setValue(c,"theme",u),t.merged.customThemes&&rs.loadCustomThemes(t.merged.customThemes),s(t.merged.theme),e(null)}finally{i(!1)}},[s,t,e]);return{isThemeDialogOpen:n,openThemeDialog:a,handleThemeSelect:l,handleThemeHighlight:o}};var zl=Ve(lr(),1);Hn();var Sqe=Ve(eir(),1);Hn();var $J=Ve(_qe(),1);import*as Wl from"fs";import*as Im from"path";import{homedir as UAe,platform as nir}from"os";var q7=".kodacli",bqe=Im.join(UAe(),q7),kAe=Im.join(bqe,"settings.json"),fPn=["DEBUG","DEBUG_MODE"];function mPn(){return process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH:nir()==="darwin"?"/Library/Application Support/GeminiCli/settings.json":nir()==="win32"?"C:\\ProgramData\\gemini-cli\\settings.json":"/etc/gemini-cli/settings.json"}function iir(t){return Im.join(t,q7,"settings.json")}var gf=(n=>(n.User="User",n.Workspace="Workspace",n.System="System",n))(gf||{}),Dqe=class{constructor(e,r,n,i){this.system=e,this.user=r,this.workspace=n,this.errors=i,this._merged=this.computeMergedSettings()}system;user;workspace;errors;_merged;get merged(){return this._merged}computeMergedSettings(){let e=this.system.settings,r=this.user.settings,n=this.workspace.settings,{folderTrust:i,...a}=n;return{...r,...a,...e,customThemes:{...r.customThemes||{},...n.customThemes||{},...e.customThemes||{}},mcpServers:{...r.mcpServers||{},...n.mcpServers||{},...e.mcpServers||{}},includeDirectories:[...e.includeDirectories||[],...r.includeDirectories||[],...n.includeDirectories||[]],chatCompression:{...e.chatCompression||{},...r.chatCompression||{},...n.chatCompression||{}}}}forScope(e){switch(e){case"User":return this.user;case"Workspace":return this.workspace;case"System":return this.system;default:throw new Error(`Invalid scope: ${e}`)}}setValue(e,r,n){let i=this.forScope(e);i.settings[r]=n,this._merged=this.computeMergedSettings(),EPn(i)}};function hPn(t){let e=/\$(?:(\w+)|{([^}]+)})/g;return t.replace(e,(r,n,i)=>{let a=n||i;return process&&process.env&&typeof process.env[a]=="string"?process.env[a]:r})}function jU(t){if(t==null||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="string")return hPn(t);if(Array.isArray(t))return t.map(e=>jU(e));if(typeof t=="object"){let e={...t};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=jU(e[r]));return e}return t}function APn(t){let e=Im.resolve(t);for(;;){let r=Im.join(e,Ph,".env");if(Wl.existsSync(r))return r;let n=Im.join(e,".env");if(Wl.existsSync(n))return n;let i=Im.dirname(e);if(i===e||!i){let a=Im.join(UAe(),Ph,".env");if(Wl.existsSync(a))return a;let s=Im.join(UAe(),".env");return Wl.existsSync(s)?s:null}e=i}}function gPn(t){if(t&&Wl.existsSync(t)){let e=Wl.readFileSync(t),r=Sqe.parse(e);r.GOOGLE_CLOUD_PROJECT?process.env.GOOGLE_CLOUD_PROJECT=r.GOOGLE_CLOUD_PROJECT:process.env.GOOGLE_CLOUD_PROJECT="cloudshell-gca"}else process.env.GOOGLE_CLOUD_PROJECT="cloudshell-gca"}function wqe(t){let e=APn(process.cwd());process.env.CLOUD_SHELL==="true"&&gPn(e);let r=t;if(!r){let n=iir(process.cwd());try{if(Wl.existsSync(n)){let i=Wl.readFileSync(n,"utf-8"),a=JSON.parse((0,$J.default)(i));r=jU(a)}}catch{}}if(e)try{let n=Wl.readFileSync(e,"utf-8"),i=Sqe.parse(n),a=r?.excludedProjectEnvVars||fPn,s=!e.includes(Ph);for(let o in i)if(Object.hasOwn(i,o)){if(s&&a.includes(o))continue;Object.hasOwn(process.env,o)||(process.env[o]=i[o])}}catch{}}function D5(t){let e={},r={},n={},i=[],a=mPn(),s=Im.resolve(t),o=Im.resolve(UAe()),l=s;try{l=Wl.realpathSync(s)}catch{}let u=Wl.realpathSync(o),c=iir(t);try{if(Wl.existsSync(a)){let E=Wl.readFileSync(a,"utf-8"),y=JSON.parse((0,$J.default)(E));e=jU(y)}}catch(E){i.push({message:sr(E),path:a})}try{if(Wl.existsSync(kAe)){let E=Wl.readFileSync(kAe,"utf-8"),y=JSON.parse((0,$J.default)(E));r=jU(y),r.theme&&r.theme==="VS"?r.theme=VJ.name:r.theme&&r.theme==="VS2015"&&(r.theme=qU.name)}}catch(E){i.push({message:sr(E),path:kAe})}if(l!==u)try{if(Wl.existsSync(c)){let E=Wl.readFileSync(c,"utf-8"),y=JSON.parse((0,$J.default)(E));n=jU(y),n.theme&&n.theme==="VS"?n.theme=VJ.name:n.theme&&n.theme==="VS2015"&&(n.theme=qU.name)}}catch(E){i.push({message:sr(E),path:c})}let d=new Dqe({path:a,settings:e},{path:kAe,settings:r},{path:c,settings:n},i),f=d.merged.chatCompression?.contextPercentageThreshold;return f!=null&&(typeof f!="number"||f<0||f>1)&&(console.warn(`Invalid value for chatCompression.contextPercentageThreshold: "${f}". Please use a value between 0 and 1. Using default compression settings.`),delete d.merged.chatCompression),wqe(d.merged),d}function EPn(t){try{let e=Im.dirname(t.path);Wl.existsSync(e)||Wl.mkdirSync(e,{recursive:!0}),Wl.writeFileSync(t.path,JSON.stringify(t.settings,null,2),"utf-8")}catch(e){console.error("Error saving user settings file:",e)}}Hn();async function HAe(){try{if(!process.env.KODA_API_KEY){let t=await tqe();t&&(process.env.KODA_API_KEY=t)}}catch{}try{if(!process.env.KODA_GITHUB_TOKEN&&!process.env.GITHUB_TOKEN){let t=await eqe();t&&(process.env.KODA_GITHUB_TOKEN=t,process.env.GITHUB_TOKEN||(process.env.GITHUB_TOKEN=t))}}catch{}}function YU(){return[process.env.KODA_API_KEY,process.env.KODA_GITHUB_TOKEN,process.env.GITHUB_TOKEN].some(e=>typeof e=="string"&&e.trim().length>0)}Hn();var Iqe="https://api.openai.com/v1",gb=null;function yPn(){return"https://api.kodacode.ru/dev/v1"}function Tqe(t){let e=(t||Iqe).trim();if(!/^https?:\/\//i.test(e))throw new Error("Base URL must start with http:// or https://");try{let r=new URL(e);return r.pathname=r.pathname.replace(/\/+$/,""),r.pathname.endsWith("/responses")&&(r.pathname=r.pathname.replace(/\/responses$/,"")),r.toString().replace(/\/+$/,"")}catch{return e.replace(/\/+$/,"")}}async function WU(){let t=await nqe();return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,{model:e,...r}]))}async function air(t){let e=Tqe(t.baseUrl);await rqe(t.model,{apiKey:t.apiKey,baseUrl:e})}async function xqe(t){await iqe(t)}async function sir(t,e){return mU({baseUrl:Tqe(t),apiKey:e,includeDefaults:!1})}async function GAe(t){let r=(await WU())[t];if(!r)return null;gb||(gb={baseUrl:process.env.KODA_API_BASE,apiKey:process.env.KODA_API_KEY,openAiKey:process.env.OPENAI_API_KEY,defaultBaseUrl:process.env.KODA_DEFAULT_API_BASE});let n=gb.baseUrl||gb.defaultBaseUrl||yPn();process.env.KODA_DEFAULT_API_BASE=n;let i=Tqe(r.baseUrl);return process.env.KODA_API_BASE=i,process.env.KODA_API_KEY=r.apiKey,process.env.OPENAI_API_KEY=r.apiKey,{...r,baseUrl:i}}async function VAe(){if(gb){let{baseUrl:t,apiKey:e,openAiKey:r,defaultBaseUrl:n}=gb;gb=null,t?process.env.KODA_API_BASE=t:delete process.env.KODA_API_BASE,e?process.env.KODA_API_KEY=e:delete process.env.KODA_API_KEY,r?process.env.OPENAI_API_KEY=r:delete process.env.OPENAI_API_KEY,n?process.env.KODA_DEFAULT_API_BASE=n:delete process.env.KODA_DEFAULT_API_BASE;return}delete process.env.KODA_API_BASE,delete process.env.KODA_API_KEY,delete process.env.OPENAI_API_KEY,await HAe()}async function oir(t){if(t){let e=await GAe(t);if(e)return e}return gb&&await VAe(),null}var lir="__add_custom_model__";function uir(t,e){let[r,n]=(0,zl.useState)(!1),[i,a]=(0,zl.useState)(!1),[s,o]=(0,zl.useState)([]),[l,u]=(0,zl.useState)([]),[c,d]=(0,zl.useState)(!1),[h,f]=(0,zl.useState)(null),[E,y]=(0,zl.useState)(null),[g,C]=(0,zl.useState)(null),[D,S]=(0,zl.useState)(!1),[w,N]=(0,zl.useState)({}),[M,U]=(0,zl.useState)(null),[k,B]=(0,zl.useState)("add"),[q,W]=(0,zl.useState)(null),[re,$]=(0,zl.useState)(null),R=(0,zl.useCallback)((pe,_e)=>{let Se=new Set,se=[];for(let ve of pe){if(Se.has(ve))continue;Se.add(ve);let X=!!_e[ve];se.push({value:ve,label:X?De.t("app.modelDialog.customModelLabel",{model:ve}):ve,source:X?"custom":"builtin"})}for(let ve of Object.values(_e))Se.has(ve.model)||(Se.add(ve.model),se.push({value:ve.model,label:De.t("app.modelDialog.customModelLabel",{model:ve.model}),source:"custom"}));return se.push({value:lir,label:De.t("app.modelDialog.addCustomModelAction"),source:"action"}),se},[]),Q=(0,zl.useCallback)((pe,_e)=>{o(R(_e??l,pe))},[l,R]),J=(0,zl.useCallback)(()=>{n(!0),a(!1),d(!0),f(null),y(null),C(null);let pe=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU());(async()=>{try{let[_e,Se]=await Promise.all([WU(),pe?mU():Promise.resolve(["KodaAgent"])]);N(_e);let se=t.getModel()||lp,ve=!!_e[se];!pe&&!ve&&se!=="KodaAgent"&&(y(De.t("app.modelDialog.kodaAuthRequired")),t.setModel("KodaAgent"),e.setValue("User","model","KodaAgent"),se="KodaAgent",ve=!1);let X=new Set;se&&!ve&&X.add(se);for(let ie of Se)X.add(ie);let ee=Array.from(X);u(ee),o(R(ee,_e)),U(ve?se:null)}catch(_e){f(_e?.message||De.t("app.modelDialog.loadError"));let Se=t.getModel()||lp,se=await WU().catch(()=>({})),X=!!se[Se]?[]:[Se];u(X),o(R(X,se))}finally{d(!1)}})()},[R,t,e]),ae=(0,zl.useCallback)(()=>n(!1),[]),fe=(0,zl.useCallback)((pe,_e)=>{if(!pe){n(!1);return}if(pe===lir){n(!1),C(null),B("add"),W(null),$(null),a(!0);return}let Se=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU()),se=!!w[pe];(async()=>{try{if(!Se&&!se&&pe!=="KodaAgent"){y(De.t("app.modelDialog.kodaAuthRequired")),e.setValue(_e,"model","KodaAgent"),t.setModel("KodaAgent"),n(!1);return}se?(await GAe(pe),U(pe)):M&&(await VAe(),U(null)),e.setValue(_e,"model",pe),t.setModel(pe),(se||M)&&await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH)}catch(ve){f(ve?.message||De.t("app.modelDialog.switchError"))}finally{n(!1)}})()},[M,t,w,e]),K=(0,zl.useCallback)((pe,_e)=>{let Se=w[pe];Se&&(C(null),f(null),B("edit"),W({model:pe,baseUrl:Se.baseUrl,apiKey:Se.apiKey}),$(pe),n(!1),a(!0))},[w]),ne=(0,zl.useCallback)((pe,_e)=>{if(!w[pe])return;f(null),C(null);let se=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU());(async()=>{try{let X=(t.getModel()||lp)===pe,ee=s.findIndex(Ce=>Ce.value===pe);await xqe(pe);let ie=await WU();N(ie);let me=l,ue=null;if(X){if(await VAe(),U(null),ue=se?lp:"KodaAgent",se&&!l.includes(lp)){let Ce=s.slice(ee+1).find(G=>G.source==="builtin"),le=s.slice(0,Math.max(0,ee)).reverse().find(G=>G.source==="builtin");ue=Ce?.value||le?.value||ue}ue&&!me.includes(ue)&&(me=[ue,...me],u(me))}Q(ie,me),X&&ue&&(e.setValue(_e,"model",ue),t.setModel(ue),await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH))}catch(ve){f(ve?.message||De.t("app.modelDialog.deleteError"))}})()},[l,t,w,s,Q,e]),he=(0,zl.useCallback)(pe=>{let _e=re,Se=!!_e;S(!0),C(null),(async()=>{try{let se=pe.model.trim();if(!se)throw new Error(De.t("app.customModel.validationMissingId"));let ve=!Se||t.getModel()===_e,X=null;try{if(X=await sir(pe.baseUrl,pe.apiKey),X.length>0&&!X.includes(se))throw new Error(De.t("app.customModel.modelNotFound",{modelId:se}))}catch(ie){console.warn("[custom model] Unable to verify /models endpoint:",ie?.message||ie)}await air({...pe,model:se}),Se&&_e&&_e!==se&&await xqe(_e);let ee=await WU();N(ee),Q(ee),ve&&(await GAe(se),e.setValue("User","model",se),t.setModel(se),U(se),await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH)),a(!1),B("add"),W(null),$(null)}catch(se){C(se?.message||(Se?De.t("app.customModel.saveErrorEdit"):De.t("app.customModel.saveErrorAdd")))}finally{S(!1)}})()},[t,re,Q,e]),Ee=(0,zl.useCallback)(()=>{a(!1),C(null),B("add"),W(null),$(null)},[]);return{isModelDialogOpen:r,isCustomModelDialogOpen:i,openModelDialog:J,closeModelDialog:ae,models:s,loading:c,error:h,unauthorizedUserError:E,customModelError:g,customModelBusy:D,customModelDraft:q,customModelDialogMode:k,handleModelSelect:fe,handleCustomModelEdit:K,handleCustomModelDelete:ne,handleCustomModelSubmit:he,handleCustomModelCancel:Ee}}var l3=Ve(lr(),1);Hn();IU();import vPn from"node:os";import Bqe from"node:path";import{promises as Rqe}from"node:fs";async function CPn(t,e){if(!e)try{(await h5(t)).on("error",()=>{})}catch{}}var _Pn="https://github.com/login/device/code",DPn="https://github.com/login/oauth/access_token";async function SPn(t,e){let r=await fetch(_Pn,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,scope:e.join(" ")})});if(!r.ok)throw new Error(`GitHub device code failed: ${r.status} ${r.statusText}`);return await r.json()}async function bPn(t,e,r){let n=Math.max(5,r)*1e3;for(;;){await new Promise(s=>setTimeout(s,n));let i=await fetch(DPn,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!i.ok)throw new Error(`GitHub token poll failed: ${i.status} ${i.statusText}`);let a=await i.json();if("access_token"in a)return a.access_token;switch(a.error){case"authorization_pending":break;case"slow_down":n+=5e3;break;case"access_denied":throw new Error("User denied access.");case"expired_token":throw new Error("Device code expired. Please retry login.");default:throw new Error(`OAuth error: ${a.error}${a.error_description?` - ${a.error_description}`:""}`)}}}function cir(){let t=process.env.XDG_CONFIG_HOME||Bqe.join(vPn.homedir(),".config");return Bqe.join(t,"koda")}var dir=Bqe.join(cir(),"credentials.json");async function pir(){try{let t=await Rqe.readFile(dir,"utf-8"),e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}async function fir(t){await Rqe.mkdir(cir(),{recursive:!0}),await Rqe.writeFile(dir,JSON.stringify(t,null,2),{mode:384})}async function wPn(t){let e=await pir();e.githubToken=t,await fir(e)}async function IPn(t){let e=await pir();e.kodaApiKey=t,await fir(e)}async function TPn(t){let e=process.env.KODA_GITHUB_EXCHANGE_URL;if(!e)return null;try{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({})});if(!r.ok)throw new Error(`Exchange failed: ${r.status} ${r.statusText}`);let n=await r.json();return typeof n.apiKey=="string"&&n.apiKey.length>0?n.apiKey:null}catch(r){return console.warn("GitHub token exchange failed:",r),null}}async function qAe(t,e){let r="Ov23li5pZhE4aeH5fTSE";if(!r)throw new Error("GITHUB_CLIENT_ID is not set. Create a GitHub OAuth App and set GITHUB_CLIENT_ID.");let n=(process.env.GITHUB_SCOPES||"read:user user:email").split(/\s+/),{device_code:i,user_code:a,verification_uri:s,interval:o=5}=await SPn(r,n);try{e?.(s,a)}catch{}console.log(`
1844
+ \u26A1 \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u0442\u0435 \u043F\u043E\u0441\u0442\u043E\u044F\u043D\u043D\u044B\u0439 \u0434\u043E\u0441\u0442\u0443\u043F \u0447\u0435\u0440\u0435\u0437 /auth \u0438\u043B\u0438 \u043E\u0444\u043E\u0440\u043C\u0438\u0442\u0435 \u0442\u0430\u0440\u0438\u0444: https://kodacode.ru `},auth:{reauthRequired:"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",timeout:"\u0412\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u0438\u0441\u0442\u0435\u043A\u043B\u043E. \u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."},prompts:{pressCtrlCAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+C \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0439\u0442\u0438.",pressCtrlDAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+D \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0439\u0442\u0438.",pressEscAgain:"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Esc \u0435\u0449\u0435 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C."},extensions:{noActive:"\u041D\u0435\u0442 \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439.",activeTitle:"\u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F:"},placeholders:{vim:" \u041D\u0430\u0436\u043C\u0438\u0442\u0435 'i' \u0434\u043B\u044F \u0440\u0435\u0436\u0438\u043C\u0430 INSERT \u0438 'Esc' \u0434\u043B\u044F \u0440\u0435\u0436\u0438\u043C\u0430 NORMAL.",default:" \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0438\u043B\u0438 @\u043F\u0443\u0442\u044C/\u043A/\u0444\u0430\u0439\u043B\u0443"},confirmation:{yes:"\u0414\u0430",no:"\u041D\u0435\u0442"},toolConfirmation:{modifyInProgress:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435 \u0432 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0435: ",saveAndCloseExternalEditor:"\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u0435 \u0438 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 \u0432\u043D\u0435\u0448\u043D\u0438\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440, \u0447\u0442\u043E\u0431\u044B \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C",applyThisChange:"\u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C \u044D\u0442\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0435?",yesAllowOnce:"\u0414\u0430, \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u043E\u0434\u0438\u043D \u0440\u0430\u0437",yesAllowAlways:"\u0414\u0430, \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u0441\u0435\u0433\u0434\u0430",noEsc:"\u041D\u0435\u0442 (esc)",modifyWithExternalEditor:"\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0432\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u043C \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0435",noSuggestChanges:"\u041D\u0435\u0442, \u043F\u0440\u0435\u0434\u043B\u043E\u0436\u0438\u0442\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F (esc)",allowExecutionOf:"\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435: '{command}'?",doYouWantToProceed:"\u0412\u044B \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C?",urlsToFetch:"URL-\u0430\u0434\u0440\u0435\u0441\u0430 \u0434\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F:",allowExecutionOfMcpTool:'\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 MCP "{toolName}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"?',yesAlwaysAllowToolFromServer:'\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 "{toolName}" \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"',yesAlwaysAllowAllToolsFromServer:'\u0414\u0430, \u0432\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0432\u0441\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 "{serverName}"'},init:{error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438: {error}",checkConfig:"\u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 API-\u043A\u043B\u044E\u0447 \u0438 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E."}}},bnr={en:FLn,ru:MLn},Aqe=class{currentLanguage;constructor(e){let r=e?.language;r==="en"||r==="ru"?this.currentLanguage=r:this.currentLanguage="en"}setLanguage(e){this.currentLanguage=e}getLanguage(){return this.currentLanguage}t(e,r){let n=e.split("."),i=bnr[this.currentLanguage],a=!0;for(let s of n)if(typeof i=="object"&&i!==null&&s in i)i=i[s];else{a=!1;break}if(a&&typeof i=="string"){if(r){let s=i;for(let[o,l]of Object.entries(r))s=s.replace(new RegExp(`{${o}}`,"g"),String(l));return s}return i}if(this.currentLanguage!=="en"){let s=bnr.en,o=!0;for(let l of n)if(typeof s=="object"&&s!==null&&l in s)s=s[l];else{o=!1;break}if(o&&typeof s=="string"){if(r){let l=s;for(let[u,c]of Object.entries(r))l=l.replace(new RegExp(`{${u}}`,"g"),String(c));return l}return s}}return e}},De=new Aqe;function LLn(t){let e=[];for(let r of t)Array.isArray(r)?e.push(...r):e.push(r);return e}var Inr=(t,e,r,n,i,a,s,o,l,u,c,d,h,f)=>{(0,Ys.useEffect)(()=>{(async()=>{try{let Ae=await n.getToolRegistry(),te={},H=["search_file_content","list_directory","glob","google_web_search","save_memory","run_shell_command"];for(let ge of H){let xe=`toolDescriptions.${ge}`,He=De.t(xe);He&&He!==xe&&(te[ge]=He)}Object.keys(te).length>0&&Ae.updateToolDescriptions(te)}catch(Ae){console.error("Error updating tool descriptions:",Ae)}})()},[n]);let[E,y]=(0,Ys.useState)(null),g=(0,Ys.useRef)(null),C=(0,Ys.useRef)(!1),[D,S]=(0,Ys.useState)(!1),[w,N]=(0,Ys.useState)(null),[M,U]=Anr(null),k=(0,Ys.useRef)(new Set),{startNewPrompt:B,getPromptCount:q}=U6(),W=RAe(),re=(0,Ys.useMemo)(()=>{if(n.getProjectRoot())return new N7(n.getProjectRoot())},[n]),[$,R,Q]=gnr(async Y=>{Y.length>0&&(r(fqe(Y),Date.now()),await le(Y))},n,U,o,h),J=(0,Ys.useMemo)(()=>$.length?fqe($):void 0,[$]),ae=(0,Ys.useRef)(!1),fe=(0,Ys.useCallback)(async Y=>{S(!0),await Y,S(!1)},[]),{handleShellCommand:K}=dnr(r,U,fe,i,n,t),ne=(0,Ys.useMemo)(()=>$.some(Y=>Y.status==="awaiting_approval")?"waiting_for_confirmation":D||$.some(Y=>Y.status==="executing"||Y.status==="scheduled"||Y.status==="validating"||(Y.status==="success"||Y.status==="error"||Y.status==="cancelled")&&!Y.responseSubmittedToGemini)?"responding":"idle",[D,$]),he=(0,Ys.useMemo)(()=>{let Y=["awaiting_approval","executing","validating","scheduled","success","error","cancelled"];for(let Ae of Y){let te=$.find(H=>H.status===Ae);if(te)return te}return null},[$]),Ee=(0,Ys.useMemo)(()=>{if(he){let Y=he.tool?.displayName??he.request.name,te=("invocation"in he?he.invocation:void 0)?.getDescription?.(),H=typeof te=="string"?te.trim():"",ge=H.length>0,He={awaiting_approval:{withDescription:"loading.activity.awaitingApproval.withDescription",withoutDescription:"loading.activity.awaitingApproval.withoutDescription"},executing:{withDescription:"loading.activity.executing.withDescription",withoutDescription:"loading.activity.executing.withoutDescription"},validating:{withDescription:"loading.activity.validating.withDescription",withoutDescription:"loading.activity.validating.withoutDescription"},scheduled:{withDescription:"loading.activity.scheduled.withDescription",withoutDescription:"loading.activity.scheduled.withoutDescription"},success:{withDescription:"loading.activity.success.withDescription",withoutDescription:"loading.activity.success.withoutDescription"},error:{withDescription:"loading.activity.error.withDescription",withoutDescription:"loading.activity.error.withoutDescription"},cancelled:{withDescription:"loading.activity.cancelled.withDescription",withoutDescription:"loading.activity.cancelled.withoutDescription"}}[he.status];if(!He)return null;let mt=ge?He.withDescription:He.withoutDescription,xt={tool:Y};ge&&(xt.description=H);let Yt=`loading.activity.tool.${he.request.name}.${he.status}`,ht=ge?`${Yt}.withDescription`:`${Yt}.withoutDescription`,vt=De.t(ht,xt);return vt!==ht?vt:De.t(mt,xt)}return ne==="responding"?De.t("loading.activity.processingResponse"):ne==="waiting_for_confirmation"?De.t("loading.activity.awaitingUserConfirmation"):null},[he,ne]),pe=(0,Ys.useCallback)(()=>{ne==="responding"&&(C.current||(C.current=!0,g.current?.abort(),M.current&&r(M.current,Date.now()),r({type:"info",text:De.t("app.requestCancelled")},Date.now()),U(null),f(),S(!1)))},[ne,r,U,f,M]);ts(Y=>{Y.name==="escape"&&pe()},{isActive:ne==="responding"});let _e=(0,Ys.useCallback)(async(Y,Ae,te,H)=>{if(C.current)return{queryToSend:null,shouldProceed:!1};if(typeof Y=="string"&&Y.trim().length===0)return{queryToSend:null,shouldProceed:!1};let ge=null;if(typeof Y=="string"){let xe=Y.trim();hL(n,new zO(xe.length,H,n.getContentGeneratorConfig()?.authType,xe)),i(`User query: '${xe}'`),await W?.logMessage(AU.USER,xe);let He=await a(xe);if(He)switch(He.type){case"schedule_tool":{let{toolName:mt,toolArgs:xt}=He,Yt={callId:`${mt}-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:mt,args:xt,isClientInitiated:!0,prompt_id:H};return R([Yt],te),{queryToSend:null,shouldProceed:!1}}case"submit_prompt":return ge=He.content,{queryToSend:ge,shouldProceed:!0};case"handled":return{queryToSend:null,shouldProceed:!1};default:{let mt=He;throw new Error(`Unhandled slash command result type: ${mt}`)}}if(s&&K(xe,te))return{queryToSend:null,shouldProceed:!1};if(anr(xe)){let mt=await fnr({query:xe,config:n,addItem:r,onDebugMessage:i,messageId:Ae,signal:te});if(!mt.shouldProceed)return{queryToSend:null,shouldProceed:!1};ge=mt.processedQuery}else r({type:"user",text:xe},Ae),ge=xe}else ge=Y;return ge===null?(i("Query processing resulted in null, not sending to Gemini."),{queryToSend:null,shouldProceed:!1}):{queryToSend:ge,shouldProceed:!0}},[n,r,i,K,a,W,s,R]),Se=(0,Ys.useCallback)((Y,Ae,te)=>{if(C.current)return"";let H=Ae+Y;M.current?.type!=="gemini"&&M.current?.type!=="gemini_content"&&(M.current&&r(M.current,te),U({type:"gemini",text:""}),H=Y);let ge=hnr(H);if(ge===H.length)U(xe=>({type:xe?.type,text:H}));else{let xe=H.substring(0,ge),He=H.substring(ge);r({type:M.current?.type,text:xe},te),U({type:"gemini_content",text:He}),H=He}return H},[r,M,U]),se=(0,Ys.useCallback)(Y=>{if(!C.current){if(M.current){if(M.current.type==="tool_group"){let Ae=M.current.tools.map(H=>H.status==="Pending"||H.status==="Confirming"||H.status==="Executing"?{...H,status:"Canceled"}:H),te={...M.current,tools:Ae};r(te,Y)}else r(M.current,Y);U(null)}r({type:"info",text:"User cancelled the request."},Y),S(!1),N(null)}},[r,M,U,N]),ve=(0,Ys.useCallback)((Y,Ae)=>{M.current&&(r(M.current,Ae),U(null)),r({type:"error",text:MU(Y.error,n.getContentGeneratorConfig()?.authType,void 0,n.getModel(),Od)},Ae),N(null)},[r,M,U,n,N]),X=(0,Ys.useCallback)((Y,Ae)=>{let te=Y.value,ge={[a0.FINISH_REASON_UNSPECIFIED]:void 0,[a0.STOP]:void 0,[a0.MAX_TOKENS]:"Response truncated due to token limits.",[a0.SAFETY]:"Response stopped due to safety reasons.",[a0.RECITATION]:"Response stopped due to recitation policy.",[a0.LANGUAGE]:"Response stopped due to unsupported language.",[a0.BLOCKLIST]:"Response stopped due to forbidden terms.",[a0.PROHIBITED_CONTENT]:"Response stopped due to prohibited content.",[a0.SPII]:"Response stopped due to sensitive personally identifiable information.",[a0.OTHER]:"Response stopped for other reasons.",[a0.MALFORMED_FUNCTION_CALL]:"Response stopped due to malformed function call.",[a0.IMAGE_SAFETY]:"Response stopped due to image safety violations.",[a0.UNEXPECTED_TOOL_CALL]:"Response stopped due to unexpected tool call."}[te];ge&&r({type:"info",text:`\u26A0\uFE0F ${ge}`},Ae)},[r]),ee=(0,Ys.useCallback)(Y=>r({type:"info",text:`IMPORTANT: This conversation approached the input token limit for ${n.getModel()}. A compressed context will be sent for future messages (compressed from: ${Y?.originalTokenCount??"unknown"} to ${Y?.newTokenCount??"unknown"} tokens).`},Date.now()),[r,n]),ie=(0,Ys.useCallback)(()=>r({type:"info",text:`The session has reached the maximum number of turns: ${n.getMaxSessionTurns()}. Please update this limit in your setting.json file.`},Date.now()),[r,n]),me=(0,Ys.useCallback)(()=>{r({type:"info",text:"A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted."},Date.now())},[r]),ue=(0,Ys.useCallback)(async(Y,Ae,te)=>{let H="",ge=[];for await(let xe of Y)switch(xe.type){case $s.Thought:N(xe.value);break;case $s.Content:H=Se(xe.value,H,Ae);break;case $s.ToolCallRequest:ge.push(xe.value);break;case $s.UserCancelled:se(Ae);break;case $s.Error:ve(xe.value,Ae);break;case $s.ChatCompressed:ee(xe.value);break;case $s.ToolCallConfirmation:case $s.ToolCallResponse:break;case $s.MaxSessionTurns:ie();break;case $s.Finished:X(xe,Ae);break;case $s.LoopDetected:ae.current=!0;break;default:return xe}return ge.length>0&&R(ge,te),0},[Se,se,ve,R,ee,X,ie]),Ce=(0,Ys.useCallback)(async(Y,Ae,te)=>{if((ne==="responding"||ne==="waiting_for_confirmation")&&!Ae?.isContinuation)return;let H=Date.now();Ae?.isContinuation||(d(!1),n.setQuotaErrorOccurred(!1)),g.current=new AbortController;let ge=g.current.signal;C.current=!1,te||(te=n.getSessionId()+"########"+q());let{queryToSend:xe,shouldProceed:He}=await _e(Y,H,ge,te);if(!(!He||xe===null)){Ae?.isContinuation||(B(),N(null)),S(!0),y(null);try{let mt=t.sendMessageStream(xe,ge,te);if(await ue(mt,H,ge)===1)return;M.current&&(r(M.current,H),U(null)),ae.current&&(ae.current=!1,me())}catch(mt){mt instanceof ES?l():(!Ns(mt)||mt.name!=="AbortError")&&r({type:"error",text:MU(sr(mt)||"Unknown error",n.getContentGeneratorConfig()?.authType,void 0,n.getModel(),Od)},H)}finally{S(!1)}}},[ne,d,_e,ue,M,r,U,y,t,l,n,B,q,me]),le=(0,Ys.useCallback)(async Y=>{if(D)return;let Ae=Y.filter(Yt=>Yt.status==="success"||Yt.status==="error"||Yt.status==="cancelled"?Yt.response?.responseParts!==void 0:!1),te=Ae.filter(Yt=>Yt.request.isClientInitiated);te.length>0&&Q(te.map(Yt=>Yt.request.callId));let H=Ae.filter(Yt=>Yt.request.name==="save_memory"&&Yt.status==="success"&&!k.current.has(Yt.request.callId));H.length>0&&(u(),H.forEach(Yt=>k.current.add(Yt.request.callId)));let ge=Ae.filter(Yt=>!Yt.request.isClientInitiated);if(ge.length===0)return;if(ge.every(Yt=>Yt.status==="cancelled")){if(t){let ht=ge.flatMap(Ut=>Ut.response.responseParts),vt=[];for(let Ut of ht)Array.isArray(Ut)?vt.push(...Ut):typeof Ut=="string"?vt.push({text:Ut}):vt.push(Ut);t.addHistory({role:"user",parts:vt})}let Yt=ge.map(ht=>ht.request.callId);Q(Yt);return}let He=ge.map(Yt=>Yt.response.responseParts),mt=ge.map(Yt=>Yt.request.callId),xt=ge.map(Yt=>Yt.request.prompt_id);Q(mt),!c&&Ce(LLn(He),{isContinuation:!0},xt[0])},[D,Ce,Q,t,u,c]),G=[M.current,J].filter(Y=>Y!=null);return(0,Ys.useEffect)(()=>{(async()=>{if(!n.getCheckpointingEnabled())return;let Ae=$.filter(te=>(te.request.name==="replace"||te.request.name==="write_file")&&te.status==="awaiting_approval");if(Ae.length>0){let te=n.getProjectTempDir()?gqe.join(n.getProjectTempDir(),"checkpoints"):void 0;if(!te)return;try{await wnr.mkdir(te,{recursive:!0})}catch(H){if(!Ns(H)||H.code!=="EEXIST"){i(`Failed to create checkpoint directory: ${sr(H)}`);return}}for(let H of Ae){let ge=H.request.args.file_path;if(!ge){i(`Skipping restorable tool call due to missing file_path: ${H.request.name}`);continue}try{let xe=await re?.createFileSnapshot(`Snapshot for ${H.request.name}`);if(xe||(xe=await re?.getCurrentCommitHash()),!xe){i(`Failed to create snapshot for ${ge}. Skipping restorable tool call.`);continue}let He=new Date().toISOString().replace(/:/g,"-").replace(/\./g,"_"),mt=H.request.name,xt=gqe.basename(ge),Yt=`${He}-${xt}-${mt}.json`,ht=await t?.getHistory(),vt=gqe.join(te,Yt);await wnr.writeFile(vt,JSON.stringify({history:e,clientHistory:ht,toolCall:{name:H.request.name,args:H.request.args},commitHash:xe,filePath:ge},null,2))}catch(xe){i(`Failed to write restorable tool call file: ${sr(xe)}`)}}}})()},[$,n,i,re,e,t]),{streamingState:ne,submitQuery:Ce,initError:E,pendingHistoryItems:G,thought:w,cancelOngoingRequest:pe,activeActivity:Ee}};var hb=Ve(lr(),1);var Tnr=(t,e)=>{let[r,n]=(0,hb.useState)(0),i=(0,hb.useRef)(null),a=(0,hb.useRef)(e),s=(0,hb.useRef)(t);return(0,hb.useEffect)(()=>{let o=!1;return a.current!==e&&(o=!0,a.current=e),s.current===!1&&t&&(o=!0),o&&n(0),s.current=t,t?(i.current&&clearInterval(i.current),i.current=setInterval(()=>{n(l=>l+1)},1e3)):i.current&&(clearInterval(i.current),i.current=null),()=>{i.current&&(clearInterval(i.current),i.current=null)}},[t,e]),r};var Ab=Ve(lr(),1);var PLn=5e3;function QLn(){return["Generating responses with 110% accuracy","Reticulating splines...","Consulting the Oracle...","Waking up the AI overlords...","Booting up consciousness...","Calibrating neural pathways...","Compiling ideas into thoughts...","Loading witty loading messages...","Calculating the meaning of life...","Sharpening the algorithms...","Preparing digital magic tricks...","Downloading more RAM...","Compressing algorithms...","Decompressing responses...","Rearranging the bits...","Initializing the response factory...","Assembling the knowledge engine...","Polishing the AI gemstones...","Warming up the neural networks...","Fine-tuning the intelligence...","Loading AI with coffee...","Preparing your AI-powered response...","Consulting the digital encyclopedia...","Generating thoughts with 99.9% confidence"]}function xnr(t,e){let r=(0,Ab.useMemo)(()=>QLn(),[]),[n,i]=(0,Ab.useState)(()=>r[0]??"Loading..."),a=(0,Ab.useCallback)(()=>{if(r.length===0)return"Loading...";let s=Math.floor(Math.random()*r.length);return r[s]},[r]);return(0,Ab.useEffect)(()=>{let s=null;if(e)i("Waiting for user confirmation...");else if(t){let o=a();i(o),s=setInterval(()=>{i(l=>{let u=r.indexOf(l);if(u===-1)return r[0];let c=(u+1)%r.length;return r[c]})},PLn)}else i(r[0]);return()=>{s&&clearInterval(s)}},[t,e,a,r]),n}var vR=Ve(lr(),1);var Bnr=(t,e)=>{let[r,n]=(0,vR.useState)(0),i=t==="responding",a=Tnr(i,r),s=t==="responding",o=t==="waiting_for_confirmation",l=xnr(s,o),u=e&&t!=="idle"?e:l,[c,d]=(0,vR.useState)(0),h=(0,vR.useRef)(null);return(0,vR.useEffect)(()=>{h.current==="waiting_for_confirmation"&&t==="responding"?(n(f=>f+1),d(0)):t==="idle"&&h.current==="responding"?(n(f=>f+1),d(0)):t==="waiting_for_confirmation"&&d(a),h.current=t},[t,a]),{elapsedTime:t==="waiting_for_confirmation"?c:a,currentLoadingPhrase:u}};var G7=Ve(lr(),1);var Rnr={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",blanchedalmond:"#ffebcd",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgrey:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",whitesmoke:"#f5f5f5",yellowgreen:"#9acd32"},kLn=new Set(["black","red","green","yellow","blue","cyan","magenta","white","gray","grey","blackbright","redbright","greenbright","yellowbright","bluebright","cyanbright","magentabright","whitebright"]);function Nnr(t){let e=t.toLowerCase();if(e.startsWith("#"))return/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/.test(t)?e:void 0;if(kLn.has(e))return e;if(Rnr[e])return Rnr[e];console.warn(`[ColorUtils] Could not resolve color "${t}" to an Ink-compatible format.`)}var mi={type:"light",Background:"#FAFAFA",Foreground:"#3C3C43",LightBlue:"#89BDCD",AccentBlue:"#3B82F6",AccentPurple:"#8B5CF6",AccentCyan:"#06B6D4",AccentGreen:"#3CA84B",AccentYellow:"#D5A40A",AccentRed:"#DD4C4C",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#008000",Gray:"#97a0b0",GradientColors:["#4796E4","#847ACE","#C3677F"]},Pn={type:"dark",Background:"#1E1E2E",Foreground:"#CDD6F4",LightBlue:"#ADD8E6",AccentBlue:"#89B4FA",AccentPurple:"#CBA6F7",AccentCyan:"#89DCEB",AccentGreen:"#A6E3A1",AccentYellow:"#F9E2AF",AccentRed:"#F38BA8",DiffAdded:"#28350B",DiffRemoved:"#430000",Comment:"#6C7086",Gray:"#6C7086",GradientColors:["#8b20c5ff","#e4b424ff","#C3677F"]},_0={type:"ansi",Background:"black",Foreground:"white",LightBlue:"blue",AccentBlue:"blue",AccentPurple:"magenta",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"yellow",AccentRed:"red",DiffAdded:"green",DiffRemoved:"red",Comment:"gray",Gray:"gray"},oo=class t{constructor(e,r,n,i,a){this.name=e;this.type=r;this.colors=i;this.semanticColors=a;this._colorMap=Object.freeze(this._buildColorMap(n));let s=n.hljs?.color;this.defaultColor=(s?t._resolveColor(s):void 0)??""}defaultColor;_colorMap;getInkColor(e){return this._colorMap[e]}static _resolveColor(e){return Nnr(e)}_buildColorMap(e){let r={};for(let n in e){if(!n.startsWith("hljs-")&&n!=="hljs")continue;let i=e[n];if(i?.color){let a=t._resolveColor(i.color);a!==void 0&&(r[n]=a)}}return r}};function Onr(t){let e={type:"custom",Background:t.background?.primary??t.Background??"",Foreground:t.text?.primary??t.Foreground??"",LightBlue:t.text?.link??t.LightBlue??"",AccentBlue:t.text?.link??t.AccentBlue??"",AccentPurple:t.text?.accent??t.AccentPurple??"",AccentCyan:t.text?.link??t.AccentCyan??"",AccentGreen:t.status?.success??t.AccentGreen??"",AccentYellow:t.status?.warning??t.AccentYellow??"",AccentRed:t.status?.error??t.AccentRed??"",DiffAdded:t.background?.diff?.added??t.DiffAdded??"",DiffRemoved:t.background?.diff?.removed??t.DiffRemoved??"",Comment:t.ui?.comment??t.Comment??"",Gray:t.text?.secondary??t.Gray??"",GradientColors:t.ui?.gradient??t.GradientColors},r={hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:e.Background,color:e.Foreground},"hljs-keyword":{color:e.AccentBlue},"hljs-literal":{color:e.AccentBlue},"hljs-symbol":{color:e.AccentBlue},"hljs-name":{color:e.AccentBlue},"hljs-link":{color:e.AccentBlue,textDecoration:"underline"},"hljs-built_in":{color:e.AccentCyan},"hljs-type":{color:e.AccentCyan},"hljs-number":{color:e.AccentGreen},"hljs-class":{color:e.AccentGreen},"hljs-string":{color:e.AccentYellow},"hljs-meta-string":{color:e.AccentYellow},"hljs-regexp":{color:e.AccentRed},"hljs-template-tag":{color:e.AccentRed},"hljs-subst":{color:e.Foreground},"hljs-function":{color:e.Foreground},"hljs-title":{color:e.Foreground},"hljs-params":{color:e.Foreground},"hljs-formula":{color:e.Foreground},"hljs-comment":{color:e.Comment,fontStyle:"italic"},"hljs-quote":{color:e.Comment,fontStyle:"italic"},"hljs-doctag":{color:e.Comment},"hljs-meta":{color:e.Gray},"hljs-meta-keyword":{color:e.Gray},"hljs-tag":{color:e.Gray},"hljs-variable":{color:e.AccentPurple},"hljs-template-variable":{color:e.AccentPurple},"hljs-attr":{color:e.LightBlue},"hljs-attribute":{color:e.LightBlue},"hljs-builtin-name":{color:e.LightBlue},"hljs-section":{color:e.AccentYellow},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{color:e.AccentYellow},"hljs-selector-tag":{color:e.AccentYellow},"hljs-selector-id":{color:e.AccentYellow},"hljs-selector-class":{color:e.AccentYellow},"hljs-selector-attr":{color:e.AccentYellow},"hljs-selector-pseudo":{color:e.AccentYellow},"hljs-addition":{backgroundColor:e.AccentGreen,display:"inline-block",width:"100%"},"hljs-deletion":{backgroundColor:e.AccentRed,display:"inline-block",width:"100%"}},n={text:{primary:e.Foreground,secondary:e.Gray,link:e.AccentBlue,accent:e.AccentPurple},background:{primary:e.Background,diff:{added:e.DiffAdded,removed:e.DiffRemoved}},border:{default:e.Gray,focused:e.AccentBlue},ui:{comment:e.Comment,symbol:e.Gray,gradient:e.GradientColors},status:{error:e.AccentRed,success:e.AccentGreen,warning:e.AccentYellow}};return new oo(t.name,"custom",r,e,n)}function Fnr(t){return t.name&&!ULn(t.name)?{isValid:!1,error:`Invalid theme name: ${t.name}`}:{isValid:!0}}function ULn(t){return t.trim().length>0&&t.trim().length<=50}var H6={text:{primary:mi.Foreground,secondary:mi.Gray,link:mi.AccentBlue,accent:mi.AccentPurple},background:{primary:mi.Background,diff:{added:mi.DiffAdded,removed:mi.DiffRemoved}},border:{default:mi.Gray,focused:mi.AccentBlue},ui:{comment:mi.Comment,symbol:mi.Gray,gradient:mi.GradientColors},status:{error:mi.AccentRed,success:mi.AccentGreen,warning:mi.AccentYellow}},Xh={text:{primary:Pn.Foreground,secondary:Pn.Gray,link:Pn.AccentBlue,accent:Pn.AccentPurple},background:{primary:Pn.Background,diff:{added:Pn.DiffAdded,removed:Pn.DiffRemoved}},border:{default:Pn.Gray,focused:Pn.AccentBlue},ui:{comment:Pn.Comment,symbol:Pn.Gray,gradient:Pn.GradientColors},status:{error:Pn.AccentRed,success:Pn.AccentGreen,warning:Pn.AccentYellow}},cGi={text:{primary:_0.Foreground,secondary:_0.Gray,link:_0.AccentBlue,accent:_0.AccentPurple},background:{primary:_0.Background,diff:{added:_0.DiffAdded,removed:_0.DiffRemoved}},border:{default:_0.Gray,focused:_0.AccentBlue},ui:{comment:_0.Comment,symbol:_0.Gray,gradient:_0.GradientColors},status:{error:_0.AccentRed,success:_0.AccentGreen,warning:_0.AccentYellow}};var Gu={type:"dark",Background:"#0b0e14",Foreground:"#bfbdb6",LightBlue:"#59C2FF",AccentBlue:"#39BAE6",AccentPurple:"#D2A6FF",AccentCyan:"#95E6CB",AccentGreen:"#AAD94C",AccentYellow:"#FFB454",AccentRed:"#F26D78",DiffAdded:"#293022",DiffRemoved:"#3D1215",Comment:"#646A71",Gray:"#3D4149",GradientColors:["#FFB454","#F26D78"]},Mnr=new oo("Ayu","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Gu.Background,color:Gu.Foreground},"hljs-keyword":{color:Gu.AccentYellow},"hljs-literal":{color:Gu.AccentPurple},"hljs-symbol":{color:Gu.AccentCyan},"hljs-name":{color:Gu.LightBlue},"hljs-link":{color:Gu.AccentBlue},"hljs-function .hljs-keyword":{color:Gu.AccentYellow},"hljs-subst":{color:Gu.Foreground},"hljs-string":{color:Gu.AccentGreen},"hljs-title":{color:Gu.AccentYellow},"hljs-type":{color:Gu.AccentBlue},"hljs-attribute":{color:Gu.AccentYellow},"hljs-bullet":{color:Gu.AccentYellow},"hljs-addition":{color:Gu.AccentGreen},"hljs-variable":{color:Gu.Foreground},"hljs-template-tag":{color:Gu.AccentYellow},"hljs-template-variable":{color:Gu.AccentYellow},"hljs-comment":{color:Gu.Comment,fontStyle:"italic"},"hljs-quote":{color:Gu.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:Gu.AccentRed},"hljs-meta":{color:Gu.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Gu,Xh);var Ws={type:"light",Background:"#f8f9fa",Foreground:"#5c6166",LightBlue:"#55b4d4",AccentBlue:"#399ee6",AccentPurple:"#a37acc",AccentCyan:"#4cbf99",AccentGreen:"#86b300",AccentYellow:"#f2ae49",AccentRed:"#f07171",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#ABADB1",Gray:"#a6aaaf",GradientColors:["#399ee6","#86b300"]},Lnr=new oo("Ayu Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ws.Background,color:Ws.Foreground},"hljs-comment":{color:Ws.Comment,fontStyle:"italic"},"hljs-quote":{color:Ws.AccentCyan,fontStyle:"italic"},"hljs-string":{color:Ws.AccentGreen},"hljs-constant":{color:Ws.AccentCyan},"hljs-number":{color:Ws.AccentPurple},"hljs-keyword":{color:Ws.AccentYellow},"hljs-selector-tag":{color:Ws.AccentYellow},"hljs-attribute":{color:Ws.AccentYellow},"hljs-variable":{color:Ws.Foreground},"hljs-variable.language":{color:Ws.LightBlue,fontStyle:"italic"},"hljs-title":{color:Ws.AccentBlue},"hljs-section":{color:Ws.AccentGreen,fontWeight:"bold"},"hljs-type":{color:Ws.LightBlue},"hljs-class .hljs-title":{color:Ws.AccentBlue},"hljs-tag":{color:Ws.LightBlue},"hljs-name":{color:Ws.AccentBlue},"hljs-builtin-name":{color:Ws.AccentYellow},"hljs-meta":{color:Ws.AccentYellow},"hljs-symbol":{color:Ws.AccentRed},"hljs-bullet":{color:Ws.AccentYellow},"hljs-regexp":{color:Ws.AccentCyan},"hljs-link":{color:Ws.LightBlue},"hljs-deletion":{color:Ws.AccentRed},"hljs-addition":{color:Ws.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-literal":{color:Ws.AccentCyan},"hljs-built_in":{color:Ws.AccentRed},"hljs-doctag":{color:Ws.AccentRed},"hljs-template-variable":{color:Ws.AccentCyan},"hljs-selector-id":{color:Ws.AccentRed}},Ws,H6);var As={type:"dark",Background:"#282c34",Foreground:"#abb2bf",LightBlue:"#61aeee",AccentBlue:"#61aeee",AccentPurple:"#c678dd",AccentCyan:"#56b6c2",AccentGreen:"#98c379",AccentYellow:"#e6c07b",AccentRed:"#e06c75",DiffAdded:"#39544E",DiffRemoved:"#562B2F",Comment:"#5c6370",Gray:"#5c6370",GradientColors:["#61aeee","#98c379"]},Pnr=new oo("Atom One","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:As.Foreground,background:As.Background},"hljs-comment":{color:As.Comment,fontStyle:"italic"},"hljs-quote":{color:As.Comment,fontStyle:"italic"},"hljs-doctag":{color:As.AccentPurple},"hljs-keyword":{color:As.AccentPurple},"hljs-formula":{color:As.AccentPurple},"hljs-section":{color:As.AccentRed},"hljs-name":{color:As.AccentRed},"hljs-selector-tag":{color:As.AccentRed},"hljs-deletion":{color:As.AccentRed},"hljs-subst":{color:As.AccentRed},"hljs-literal":{color:As.AccentCyan},"hljs-string":{color:As.AccentGreen},"hljs-regexp":{color:As.AccentGreen},"hljs-addition":{color:As.AccentGreen},"hljs-attribute":{color:As.AccentGreen},"hljs-meta-string":{color:As.AccentGreen},"hljs-built_in":{color:As.AccentYellow},"hljs-class .hljs-title":{color:As.AccentYellow},"hljs-attr":{color:As.AccentYellow},"hljs-variable":{color:As.AccentYellow},"hljs-template-variable":{color:As.AccentYellow},"hljs-type":{color:As.AccentYellow},"hljs-selector-class":{color:As.AccentYellow},"hljs-selector-attr":{color:As.AccentYellow},"hljs-selector-pseudo":{color:As.AccentYellow},"hljs-number":{color:As.AccentYellow},"hljs-symbol":{color:As.AccentBlue},"hljs-bullet":{color:As.AccentBlue},"hljs-link":{color:As.AccentBlue,textDecoration:"underline"},"hljs-meta":{color:As.AccentBlue},"hljs-selector-id":{color:As.AccentBlue},"hljs-title":{color:As.AccentBlue},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},As,Xh);var Yl={type:"dark",Background:"#282a36",Foreground:"#f8f8f2",LightBlue:"#8be9fd",AccentBlue:"#8be9fd",AccentPurple:"#ff79c6",AccentCyan:"#8be9fd",AccentGreen:"#50fa7b",AccentYellow:"#f1fa8c",AccentRed:"#ff5555",DiffAdded:"#11431d",DiffRemoved:"#6e1818",Comment:"#6272a4",Gray:"#6272a4",GradientColors:["#ff79c6","#8be9fd"]},Qnr=new oo("Dracula","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Yl.Background,color:Yl.Foreground},"hljs-keyword":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-selector-tag":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-literal":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-section":{color:Yl.AccentBlue,fontWeight:"bold"},"hljs-link":{color:Yl.AccentBlue},"hljs-function .hljs-keyword":{color:Yl.AccentPurple},"hljs-subst":{color:Yl.Foreground},"hljs-string":{color:Yl.AccentYellow},"hljs-title":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-name":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-type":{color:Yl.AccentYellow,fontWeight:"bold"},"hljs-attribute":{color:Yl.AccentYellow},"hljs-symbol":{color:Yl.AccentYellow},"hljs-bullet":{color:Yl.AccentYellow},"hljs-addition":{color:Yl.AccentGreen},"hljs-variable":{color:Yl.AccentYellow},"hljs-template-tag":{color:Yl.AccentYellow},"hljs-template-variable":{color:Yl.AccentYellow},"hljs-comment":{color:Yl.Comment},"hljs-quote":{color:Yl.Comment},"hljs-deletion":{color:Yl.AccentRed},"hljs-meta":{color:Yl.Comment},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Yl,Xh);var zs={type:"dark",Background:"#24292e",Foreground:"#d1d5da",LightBlue:"#79B8FF",AccentBlue:"#79B8FF",AccentPurple:"#B392F0",AccentCyan:"#9ECBFF",AccentGreen:"#85E89D",AccentYellow:"#FFAB70",AccentRed:"#F97583",DiffAdded:"#3C4636",DiffRemoved:"#502125",Comment:"#6A737D",Gray:"#6A737D",GradientColors:["#79B8FF","#85E89D"]},knr=new oo("GitHub","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:zs.Foreground,background:zs.Background},"hljs-comment":{color:zs.Comment,fontStyle:"italic"},"hljs-quote":{color:zs.Comment,fontStyle:"italic"},"hljs-keyword":{color:zs.AccentRed,fontWeight:"bold"},"hljs-selector-tag":{color:zs.AccentRed,fontWeight:"bold"},"hljs-subst":{color:zs.Foreground},"hljs-number":{color:zs.LightBlue},"hljs-literal":{color:zs.LightBlue},"hljs-variable":{color:zs.AccentYellow},"hljs-template-variable":{color:zs.AccentYellow},"hljs-tag .hljs-attr":{color:zs.AccentYellow},"hljs-string":{color:zs.AccentCyan},"hljs-doctag":{color:zs.AccentCyan},"hljs-title":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-section":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:zs.AccentPurple,fontWeight:"bold"},"hljs-type":{color:zs.AccentGreen,fontWeight:"bold"},"hljs-class .hljs-title":{color:zs.AccentGreen,fontWeight:"bold"},"hljs-tag":{color:zs.AccentGreen},"hljs-name":{color:zs.AccentGreen},"hljs-attribute":{color:zs.LightBlue},"hljs-regexp":{color:zs.AccentCyan},"hljs-link":{color:zs.AccentCyan},"hljs-symbol":{color:zs.AccentPurple},"hljs-bullet":{color:zs.AccentPurple},"hljs-built_in":{color:zs.LightBlue},"hljs-builtin-name":{color:zs.LightBlue},"hljs-meta":{color:zs.LightBlue,fontWeight:"bold"},"hljs-deletion":{background:"#86181D",color:zs.AccentRed},"hljs-addition":{background:"#144620",color:zs.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},zs,Xh);var yo={type:"light",Background:"#f8f8f8",Foreground:"#24292E",LightBlue:"#0086b3",AccentBlue:"#458",AccentPurple:"#900",AccentCyan:"#009926",AccentGreen:"#008080",AccentYellow:"#990073",AccentRed:"#d14",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#998",Gray:"#999",GradientColors:["#458","#008080"]},Unr=new oo("GitHub Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:yo.Foreground,background:yo.Background},"hljs-comment":{color:yo.Comment,fontStyle:"italic"},"hljs-quote":{color:yo.Comment,fontStyle:"italic"},"hljs-keyword":{color:yo.Foreground,fontWeight:"bold"},"hljs-selector-tag":{color:yo.Foreground,fontWeight:"bold"},"hljs-subst":{color:yo.Foreground,fontWeight:"normal"},"hljs-number":{color:yo.AccentGreen},"hljs-literal":{color:yo.AccentGreen},"hljs-variable":{color:yo.AccentGreen},"hljs-template-variable":{color:yo.AccentGreen},"hljs-tag .hljs-attr":{color:yo.AccentGreen},"hljs-string":{color:yo.AccentRed},"hljs-doctag":{color:yo.AccentRed},"hljs-title":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:yo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:yo.AccentBlue,fontWeight:"bold"},"hljs-class .hljs-title":{color:yo.AccentBlue,fontWeight:"bold"},"hljs-tag":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-name":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-attribute":{color:yo.AccentBlue,fontWeight:"normal"},"hljs-regexp":{color:yo.AccentCyan},"hljs-link":{color:yo.AccentCyan},"hljs-symbol":{color:yo.AccentYellow},"hljs-bullet":{color:yo.AccentYellow},"hljs-built_in":{color:yo.LightBlue},"hljs-builtin-name":{color:yo.LightBlue},"hljs-meta":{color:yo.Gray,fontWeight:"bold"},"hljs-deletion":{background:"#fdd"},"hljs-addition":{background:"#dfd"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},yo,H6);var Ks={type:"light",Background:"white",Foreground:"#444",LightBlue:"#066",AccentBlue:"#008",AccentPurple:"#606",AccentCyan:"#066",AccentGreen:"#080",AccentYellow:"#660",AccentRed:"#800",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#5f6368",Gray:mi.Gray,GradientColors:["#066","#606"]},Hnr=new oo("Google Code","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ks.Background,color:Ks.Foreground},"hljs-comment":{color:Ks.AccentRed},"hljs-quote":{color:Ks.AccentRed},"hljs-keyword":{color:Ks.AccentBlue},"hljs-selector-tag":{color:Ks.AccentBlue},"hljs-section":{color:Ks.AccentBlue},"hljs-title":{color:Ks.AccentPurple},"hljs-name":{color:Ks.AccentBlue},"hljs-variable":{color:Ks.AccentYellow},"hljs-template-variable":{color:Ks.AccentYellow},"hljs-string":{color:Ks.AccentGreen},"hljs-selector-attr":{color:Ks.AccentGreen},"hljs-selector-pseudo":{color:Ks.AccentGreen},"hljs-regexp":{color:Ks.AccentGreen},"hljs-literal":{color:Ks.AccentCyan},"hljs-symbol":{color:Ks.AccentCyan},"hljs-bullet":{color:Ks.AccentCyan},"hljs-meta":{color:Ks.AccentCyan},"hljs-number":{color:Ks.AccentCyan},"hljs-link":{color:Ks.AccentCyan},"hljs-doctag":{color:Ks.AccentPurple,fontWeight:"bold"},"hljs-type":{color:Ks.AccentPurple},"hljs-attr":{color:Ks.AccentPurple},"hljs-built_in":{color:Ks.AccentPurple},"hljs-builtin-name":{color:Ks.AccentPurple},"hljs-params":{color:Ks.AccentPurple},"hljs-attribute":{color:Ks.Foreground},"hljs-subst":{color:Ks.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-selector-id":{color:Ks.AccentYellow},"hljs-selector-class":{color:Ks.AccentYellow},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Ks,H6);var VJ=new oo("Default Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:mi.Background,color:mi.Foreground},"hljs-comment":{color:mi.Comment},"hljs-quote":{color:mi.Comment},"hljs-variable":{color:mi.Foreground},"hljs-keyword":{color:mi.AccentBlue},"hljs-selector-tag":{color:mi.AccentBlue},"hljs-built_in":{color:mi.AccentBlue},"hljs-name":{color:mi.AccentBlue},"hljs-tag":{color:mi.AccentBlue},"hljs-string":{color:mi.AccentRed},"hljs-title":{color:mi.AccentRed},"hljs-section":{color:mi.AccentRed},"hljs-attribute":{color:mi.AccentRed},"hljs-literal":{color:mi.AccentRed},"hljs-template-tag":{color:mi.AccentRed},"hljs-template-variable":{color:mi.AccentRed},"hljs-type":{color:mi.AccentRed},"hljs-addition":{color:mi.AccentGreen},"hljs-deletion":{color:mi.AccentRed},"hljs-selector-attr":{color:mi.AccentCyan},"hljs-selector-pseudo":{color:mi.AccentCyan},"hljs-meta":{color:mi.AccentCyan},"hljs-doctag":{color:mi.Gray},"hljs-attr":{color:mi.AccentRed},"hljs-symbol":{color:mi.AccentCyan},"hljs-bullet":{color:mi.AccentCyan},"hljs-link":{color:mi.AccentCyan},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},mi,H6);var qU=new oo("Default","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Pn.Background,color:Pn.Foreground},"hljs-keyword":{color:Pn.AccentBlue},"hljs-literal":{color:Pn.AccentBlue},"hljs-symbol":{color:Pn.AccentBlue},"hljs-name":{color:Pn.AccentBlue},"hljs-link":{color:Pn.AccentBlue,textDecoration:"underline"},"hljs-built_in":{color:Pn.AccentCyan},"hljs-type":{color:Pn.AccentCyan},"hljs-number":{color:Pn.AccentGreen},"hljs-class":{color:Pn.AccentGreen},"hljs-string":{color:Pn.AccentYellow},"hljs-meta-string":{color:Pn.AccentYellow},"hljs-regexp":{color:Pn.AccentRed},"hljs-template-tag":{color:Pn.AccentRed},"hljs-subst":{color:Pn.Foreground},"hljs-function":{color:Pn.Foreground},"hljs-title":{color:Pn.Foreground},"hljs-params":{color:Pn.Foreground},"hljs-formula":{color:Pn.Foreground},"hljs-comment":{color:Pn.Comment,fontStyle:"italic"},"hljs-quote":{color:Pn.Comment,fontStyle:"italic"},"hljs-doctag":{color:Pn.Comment},"hljs-meta":{color:Pn.Gray},"hljs-meta-keyword":{color:Pn.Gray},"hljs-tag":{color:Pn.Gray},"hljs-variable":{color:Pn.AccentPurple},"hljs-template-variable":{color:Pn.AccentPurple},"hljs-attr":{color:Pn.LightBlue},"hljs-attribute":{color:Pn.LightBlue},"hljs-builtin-name":{color:Pn.LightBlue},"hljs-section":{color:Pn.AccentYellow},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{color:Pn.AccentYellow},"hljs-selector-tag":{color:Pn.AccentYellow},"hljs-selector-id":{color:Pn.AccentYellow},"hljs-selector-class":{color:Pn.AccentYellow},"hljs-selector-attr":{color:Pn.AccentYellow},"hljs-selector-pseudo":{color:Pn.AccentYellow},"hljs-addition":{backgroundColor:"#144212",display:"inline-block",width:"100%"},"hljs-deletion":{backgroundColor:"#600",display:"inline-block",width:"100%"}},Pn,Xh);var Bi={type:"dark",Background:"#2d2b57",Foreground:"#e3dfff",LightBlue:"#847ace",AccentBlue:"#a599e9",AccentPurple:"#ac65ff",AccentCyan:"#a1feff",AccentGreen:"#A5FF90",AccentYellow:"#fad000",AccentRed:"#ff628c",DiffAdded:"#383E45",DiffRemoved:"#572244",Comment:"#B362FF",Gray:"#726c86",GradientColors:["#4d21fc","#847ace","#ff628c"]},Sp={AccentYellowAlt:"#f8d000",AccentOrange:"#fb9e00",AccentPink:"#fa658d",AccentLightPurple:"#c991ff",AccentDarkPurple:"#6943ff",AccentTeal:"#2ee2fa"},Gnr=new oo("Shades Of Purple","dark",{hljs:{display:"block",overflowX:"auto",background:Bi.Background,color:Bi.Foreground},"hljs-title":{color:Bi.AccentYellow,fontWeight:"normal"},"hljs-name":{color:Bi.AccentCyan,fontWeight:"normal"},"hljs-tag":{color:Bi.Foreground},"hljs-attr":{color:Sp.AccentYellowAlt,fontStyle:"italic"},"hljs-built_in":{color:Sp.AccentOrange},"hljs-selector-tag":{color:Sp.AccentOrange,fontWeight:"normal"},"hljs-section":{color:Sp.AccentOrange},"hljs-keyword":{color:Sp.AccentOrange,fontWeight:"normal"},"hljs-subst":{color:Bi.Foreground},"hljs-string":{color:Bi.AccentGreen},"hljs-attribute":{color:Bi.AccentGreen},"hljs-symbol":{color:Bi.AccentGreen},"hljs-bullet":{color:Bi.AccentGreen},"hljs-addition":{color:Bi.AccentGreen},"hljs-code":{color:Bi.AccentGreen},"hljs-regexp":{color:Bi.AccentGreen},"hljs-selector-class":{color:Bi.AccentGreen},"hljs-selector-attr":{color:Bi.AccentGreen},"hljs-selector-pseudo":{color:Bi.AccentGreen},"hljs-template-tag":{color:Bi.AccentGreen},"hljs-quote":{color:Bi.AccentGreen},"hljs-deletion":{color:Bi.AccentRed},"hljs-meta":{color:Sp.AccentOrange},"hljs-meta-string":{color:Sp.AccentOrange},"hljs-comment":{color:Bi.AccentPurple},"hljs-literal":{color:Sp.AccentPink,fontWeight:"normal"},"hljs-number":{color:Sp.AccentPink},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-diff":{color:Bi.Foreground},"hljs-meta.hljs-diff":{color:Bi.AccentBlue},"hljs-ln":{color:Bi.Gray},"hljs-type":{color:Bi.AccentYellow,fontWeight:"normal"},"hljs-variable":{color:Bi.AccentYellow},"hljs-template-variable":{color:Bi.AccentGreen},"hljs-function .hljs-keyword":{color:Sp.AccentOrange},"hljs-link":{color:Bi.LightBlue},"hljs-doctag":{fontWeight:"bold"},"hljs-params":{color:Sp.AccentLightPurple,fontStyle:"italic"},"hljs-class":{color:Bi.AccentCyan,fontWeight:"bold"},"hljs-function":{color:Bi.AccentCyan},"hljs-property":{color:Bi.AccentBlue},"hljs-operator":{color:Sp.AccentDarkPurple},"hljs-punctuation":{color:Bi.Gray},"hljs-selector-id":{color:Bi.AccentYellow,fontWeight:"bold"},"hljs-char":{color:Bi.AccentGreen},"hljs-escape":{color:Sp.AccentPink,fontWeight:"bold"},"hljs-meta-keyword":{color:Sp.AccentOrange,fontWeight:"bold"},"hljs-builtin-name":{color:Sp.AccentTeal},"hljs-module":{color:Bi.AccentCyan},"hljs-namespace":{color:Bi.LightBlue},"hljs-important":{color:Bi.AccentRed,fontWeight:"bold"},"hljs-formula":{color:Bi.AccentCyan,fontStyle:"italic"},"hljs-decorator":{color:Sp.AccentTeal,fontWeight:"bold"},"hljs-symbol.ruby":{color:Sp.AccentPink},"hljs-keyword.sql":{color:Sp.AccentOrange,textTransform:"uppercase"},"hljs-section.markdown":{color:Bi.AccentYellow,fontWeight:"bold"},"hljs-attr.json":{color:Bi.AccentCyan},"hljs-tag .hljs-name":{color:Bi.AccentRed},"hljs-tag .hljs-attr":{color:Sp.AccentYellowAlt},"hljs.hljs-line-numbers":{borderRight:`1px solid ${Bi.Gray}`},"hljs.hljs-line-numbers .hljs-ln-numbers":{color:Bi.Gray,paddingRight:"1em"},"hljs.hljs-line-numbers .hljs-ln-code":{paddingLeft:"1em"},"hljs::selection":{background:Bi.AccentBlue+"40"},"hljs ::-moz-selection":{background:Bi.AccentBlue+"40"},"hljs .hljs-highlight":{background:Bi.AccentPurple+"20",display:"block",width:"100%"}},Bi,Xh);var Is={type:"light",Background:"#fff",Foreground:"#444",LightBlue:"#0E0EFF",AccentBlue:"#1c00cf",AccentPurple:"#aa0d91",AccentCyan:"#3F6E74",AccentGreen:"#007400",AccentYellow:"#836C28",AccentRed:"#c41a16",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#007400",Gray:"#c0c0c0",GradientColors:["#1c00cf","#007400"]},Vnr=new oo("Xcode","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Is.Background,color:Is.Foreground},"xml .hljs-meta":{color:Is.Gray},"hljs-comment":{color:Is.Comment},"hljs-quote":{color:Is.Comment},"hljs-tag":{color:Is.AccentPurple},"hljs-attribute":{color:Is.AccentPurple},"hljs-keyword":{color:Is.AccentPurple},"hljs-selector-tag":{color:Is.AccentPurple},"hljs-literal":{color:Is.AccentPurple},"hljs-name":{color:Is.AccentPurple},"hljs-variable":{color:Is.AccentCyan},"hljs-template-variable":{color:Is.AccentCyan},"hljs-code":{color:Is.AccentRed},"hljs-string":{color:Is.AccentRed},"hljs-meta-string":{color:Is.AccentRed},"hljs-regexp":{color:Is.LightBlue},"hljs-link":{color:Is.LightBlue},"hljs-title":{color:Is.AccentBlue},"hljs-symbol":{color:Is.AccentBlue},"hljs-bullet":{color:Is.AccentBlue},"hljs-number":{color:Is.AccentBlue},"hljs-section":{color:Is.AccentYellow},"hljs-meta":{color:Is.AccentYellow},"hljs-class .hljs-title":{color:Is.AccentPurple},"hljs-type":{color:Is.AccentPurple},"hljs-built_in":{color:Is.AccentPurple},"hljs-builtin-name":{color:Is.AccentPurple},"hljs-params":{color:Is.AccentPurple},"hljs-attr":{color:Is.AccentYellow},"hljs-subst":{color:Is.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-selector-id":{color:Is.AccentYellow},"hljs-selector-class":{color:Is.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Is,H6);var HLn={type:"dark",Background:"black",Foreground:"white",LightBlue:"bluebright",AccentBlue:"blue",AccentPurple:"magenta",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"yellow",AccentRed:"red",DiffAdded:"#003300",DiffRemoved:"#4D0000",Comment:"gray",Gray:"gray",GradientColors:["cyan","green"]},qnr=new oo("ANSI","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"black",color:"white"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"yellow"},"hljs-meta-string":{color:"yellow"},"hljs-regexp":{color:"red"},"hljs-template-tag":{color:"red"},"hljs-subst":{color:"white"},"hljs-function":{color:"white"},"hljs-title":{color:"white"},"hljs-params":{color:"white"},"hljs-formula":{color:"white"},"hljs-comment":{color:"green"},"hljs-quote":{color:"green"},"hljs-doctag":{color:"green"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"magenta"},"hljs-template-variable":{color:"magenta"},"hljs-attr":{color:"bluebright"},"hljs-attribute":{color:"bluebright"},"hljs-builtin-name":{color:"bluebright"},"hljs-section":{color:"yellow"},"hljs-emphasis":{},"hljs-strong":{},"hljs-bullet":{color:"yellow"},"hljs-selector-tag":{color:"yellow"},"hljs-selector-id":{color:"yellow"},"hljs-selector-class":{color:"yellow"},"hljs-selector-attr":{color:"yellow"},"hljs-selector-pseudo":{color:"yellow"}},HLn,Xh);var GLn={type:"light",Background:"white",Foreground:"#444",LightBlue:"blue",AccentBlue:"blue",AccentPurple:"purple",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"orange",AccentRed:"red",DiffAdded:"#E5F2E5",DiffRemoved:"#FFE5E5",Comment:"gray",Gray:"gray",GradientColors:["blue","green"]},$nr=new oo("ANSI Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"white",color:"black"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"red"},"hljs-meta-string":{color:"red"},"hljs-regexp":{color:"magenta"},"hljs-template-tag":{color:"magenta"},"hljs-subst":{color:"black"},"hljs-function":{color:"black"},"hljs-title":{color:"black"},"hljs-params":{color:"black"},"hljs-formula":{color:"black"},"hljs-comment":{color:"gray"},"hljs-quote":{color:"gray"},"hljs-doctag":{color:"gray"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"purple"},"hljs-template-variable":{color:"purple"},"hljs-attr":{color:"blue"},"hljs-attribute":{color:"blue"},"hljs-builtin-name":{color:"blue"},"hljs-section":{color:"orange"},"hljs-bullet":{color:"orange"},"hljs-selector-tag":{color:"orange"},"hljs-selector-id":{color:"orange"},"hljs-selector-class":{color:"orange"},"hljs-selector-attr":{color:"orange"},"hljs-selector-pseudo":{color:"orange"}},GLn,H6);var VLn={type:"ansi",Background:"",Foreground:"",LightBlue:"",AccentBlue:"",AccentPurple:"",AccentCyan:"",AccentGreen:"",AccentYellow:"",AccentRed:"",DiffAdded:"",DiffRemoved:"",Comment:"",Gray:""},qLn={text:{primary:"",secondary:"",link:"",accent:""},background:{primary:"",diff:{added:"",removed:""}},border:{default:"",focused:""},ui:{comment:"",symbol:"",gradient:[]},status:{error:"",success:"",warning:""}},jnr=new oo("NoColor","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em"},"hljs-keyword":{},"hljs-literal":{},"hljs-symbol":{},"hljs-name":{},"hljs-link":{textDecoration:"underline"},"hljs-built_in":{},"hljs-type":{},"hljs-number":{},"hljs-class":{},"hljs-string":{},"hljs-meta-string":{},"hljs-regexp":{},"hljs-template-tag":{},"hljs-subst":{},"hljs-function":{},"hljs-title":{},"hljs-params":{},"hljs-formula":{},"hljs-comment":{fontStyle:"italic"},"hljs-quote":{fontStyle:"italic"},"hljs-doctag":{},"hljs-meta":{},"hljs-meta-keyword":{},"hljs-tag":{},"hljs-variable":{},"hljs-template-variable":{},"hljs-attr":{},"hljs-attribute":{},"hljs-builtin-name":{},"hljs-section":{},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{},"hljs-selector-tag":{},"hljs-selector-id":{},"hljs-selector-class":{},"hljs-selector-attr":{},"hljs-selector-pseudo":{},"hljs-addition":{display:"inline-block",width:"100%"},"hljs-deletion":{display:"inline-block",width:"100%"}},VLn,qLn);import $Ln from"node:process";var H7=qU,Eqe=class{availableThemes;activeTheme;customThemes=new Map;constructor(){this.availableThemes=[Mnr,Lnr,Pnr,Qnr,VJ,qU,knr,Unr,Hnr,Gnr,Vnr,qnr,$nr],this.activeTheme=H7}loadCustomThemes(e){if(this.customThemes.clear(),!!e){for(let[r,n]of Object.entries(e)){let i=Fnr(n);if(i.isValid){i.warning&&console.warn(`Theme "${r}": ${i.warning}`);let a={...H7.colors,...n,name:n.name||r,type:"custom"};try{let s=Onr(a);this.customThemes.set(r,s)}catch(s){console.warn(`Failed to load custom theme "${r}":`,s)}}else console.warn(`Invalid custom theme "${r}": ${i.error}`)}this.activeTheme&&this.activeTheme.type==="custom"&&this.customThemes.has(this.activeTheme.name)&&(this.activeTheme=this.customThemes.get(this.activeTheme.name))}}setActiveTheme(e){let r=this.findThemeByName(e);return r?(this.activeTheme=r,!0):!1}getActiveTheme(){return $Ln.env.NO_COLOR?jnr:((!this.activeTheme||!this.findThemeByName(this.activeTheme.name))&&(this.activeTheme=H7),this.activeTheme)}getSemanticColors(){return this.getActiveTheme().semanticColors}getCustomThemeNames(){return Array.from(this.customThemes.keys())}isCustomTheme(e){return this.customThemes.has(e)}getAvailableThemes(){let e=this.availableThemes.map(a=>({name:a.name,type:a.type,isCustom:!1})),r=Array.from(this.customThemes.values()).map(a=>({name:a.name,type:a.type,isCustom:!0}));return[...e,...r].sort((a,s)=>{let o=u=>{switch(u){case"dark":return 1;case"light":return 2;case"ansi":return 3;case"custom":return 4;default:return 5}},l=o(a.type)-o(s.type);return l!==0?l:a.name.localeCompare(s.name)})}getTheme(e){return this.findThemeByName(e)}findThemeByName(e){if(!e)return H7;let r=this.availableThemes.find(n=>n.name===e);return r||this.customThemes.get(e)}},rs=new Eqe;import jLn from"node:process";var Ynr=(t,e,r)=>{let[n,i]=(0,G7.useState)(!1);(0,G7.useEffect)(()=>{let u=t.merged.theme;u&&!rs.findThemeByName(u)?(i(!0),e(`Theme "${u}" not found.`)):e(null)},[t.merged.theme,e]);let a=(0,G7.useCallback)(()=>{if(jLn.env.NO_COLOR){r({type:"info",text:"Theme configuration unavailable due to NO_COLOR env variable."},Date.now());return}i(!0)},[r]),s=(0,G7.useCallback)(u=>{rs.setActiveTheme(u)?e(null):(i(!0),e(`Theme "${u}" not found.`))},[e]),o=(0,G7.useCallback)(u=>{s(u)},[s]),l=(0,G7.useCallback)((u,c)=>{try{let d={...t.user.settings.customThemes||{},...t.workspace.settings.customThemes||{}},h=rs.findThemeByName(u),f=u&&d[u];if(!h&&!f){e(`Theme "${u}" not found in selected scope.`),i(!0);return}t.setValue(c,"theme",u),t.merged.customThemes&&rs.loadCustomThemes(t.merged.customThemes),s(t.merged.theme),e(null)}finally{i(!1)}},[s,t,e]);return{isThemeDialogOpen:n,openThemeDialog:a,handleThemeSelect:l,handleThemeHighlight:o}};var zl=Ve(lr(),1);Hn();var Sqe=Ve(eir(),1);Hn();var $J=Ve(_qe(),1);import*as Wl from"fs";import*as Im from"path";import{homedir as UAe,platform as nir}from"os";var q7=".kodacli",bqe=Im.join(UAe(),q7),kAe=Im.join(bqe,"settings.json"),fPn=["DEBUG","DEBUG_MODE"];function mPn(){return process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH:nir()==="darwin"?"/Library/Application Support/GeminiCli/settings.json":nir()==="win32"?"C:\\ProgramData\\gemini-cli\\settings.json":"/etc/gemini-cli/settings.json"}function iir(t){return Im.join(t,q7,"settings.json")}var gf=(n=>(n.User="User",n.Workspace="Workspace",n.System="System",n))(gf||{}),Dqe=class{constructor(e,r,n,i){this.system=e,this.user=r,this.workspace=n,this.errors=i,this._merged=this.computeMergedSettings()}system;user;workspace;errors;_merged;get merged(){return this._merged}computeMergedSettings(){let e=this.system.settings,r=this.user.settings,n=this.workspace.settings,{folderTrust:i,...a}=n;return{...r,...a,...e,customThemes:{...r.customThemes||{},...n.customThemes||{},...e.customThemes||{}},mcpServers:{...r.mcpServers||{},...n.mcpServers||{},...e.mcpServers||{}},includeDirectories:[...e.includeDirectories||[],...r.includeDirectories||[],...n.includeDirectories||[]],chatCompression:{...e.chatCompression||{},...r.chatCompression||{},...n.chatCompression||{}}}}forScope(e){switch(e){case"User":return this.user;case"Workspace":return this.workspace;case"System":return this.system;default:throw new Error(`Invalid scope: ${e}`)}}setValue(e,r,n){let i=this.forScope(e);i.settings[r]=n,this._merged=this.computeMergedSettings(),EPn(i)}};function hPn(t){let e=/\$(?:(\w+)|{([^}]+)})/g;return t.replace(e,(r,n,i)=>{let a=n||i;return process&&process.env&&typeof process.env[a]=="string"?process.env[a]:r})}function jU(t){if(t==null||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="string")return hPn(t);if(Array.isArray(t))return t.map(e=>jU(e));if(typeof t=="object"){let e={...t};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=jU(e[r]));return e}return t}function APn(t){let e=Im.resolve(t);for(;;){let r=Im.join(e,Ph,".env");if(Wl.existsSync(r))return r;let n=Im.join(e,".env");if(Wl.existsSync(n))return n;let i=Im.dirname(e);if(i===e||!i){let a=Im.join(UAe(),Ph,".env");if(Wl.existsSync(a))return a;let s=Im.join(UAe(),".env");return Wl.existsSync(s)?s:null}e=i}}function gPn(t){if(t&&Wl.existsSync(t)){let e=Wl.readFileSync(t),r=Sqe.parse(e);r.GOOGLE_CLOUD_PROJECT?process.env.GOOGLE_CLOUD_PROJECT=r.GOOGLE_CLOUD_PROJECT:process.env.GOOGLE_CLOUD_PROJECT="cloudshell-gca"}else process.env.GOOGLE_CLOUD_PROJECT="cloudshell-gca"}function wqe(t){let e=APn(process.cwd());process.env.CLOUD_SHELL==="true"&&gPn(e);let r=t;if(!r){let n=iir(process.cwd());try{if(Wl.existsSync(n)){let i=Wl.readFileSync(n,"utf-8"),a=JSON.parse((0,$J.default)(i));r=jU(a)}}catch{}}if(e)try{let n=Wl.readFileSync(e,"utf-8"),i=Sqe.parse(n),a=r?.excludedProjectEnvVars||fPn,s=!e.includes(Ph);for(let o in i)if(Object.hasOwn(i,o)){if(s&&a.includes(o))continue;Object.hasOwn(process.env,o)||(process.env[o]=i[o])}}catch{}}function D5(t){let e={},r={},n={},i=[],a=mPn(),s=Im.resolve(t),o=Im.resolve(UAe()),l=s;try{l=Wl.realpathSync(s)}catch{}let u=Wl.realpathSync(o),c=iir(t);try{if(Wl.existsSync(a)){let E=Wl.readFileSync(a,"utf-8"),y=JSON.parse((0,$J.default)(E));e=jU(y)}}catch(E){i.push({message:sr(E),path:a})}try{if(Wl.existsSync(kAe)){let E=Wl.readFileSync(kAe,"utf-8"),y=JSON.parse((0,$J.default)(E));r=jU(y),r.theme&&r.theme==="VS"?r.theme=VJ.name:r.theme&&r.theme==="VS2015"&&(r.theme=qU.name)}}catch(E){i.push({message:sr(E),path:kAe})}if(l!==u)try{if(Wl.existsSync(c)){let E=Wl.readFileSync(c,"utf-8"),y=JSON.parse((0,$J.default)(E));n=jU(y),n.theme&&n.theme==="VS"?n.theme=VJ.name:n.theme&&n.theme==="VS2015"&&(n.theme=qU.name)}}catch(E){i.push({message:sr(E),path:c})}let d=new Dqe({path:a,settings:e},{path:kAe,settings:r},{path:c,settings:n},i),f=d.merged.chatCompression?.contextPercentageThreshold;return f!=null&&(typeof f!="number"||f<0||f>1)&&(console.warn(`Invalid value for chatCompression.contextPercentageThreshold: "${f}". Please use a value between 0 and 1. Using default compression settings.`),delete d.merged.chatCompression),wqe(d.merged),d}function EPn(t){try{let e=Im.dirname(t.path);Wl.existsSync(e)||Wl.mkdirSync(e,{recursive:!0}),Wl.writeFileSync(t.path,JSON.stringify(t.settings,null,2),"utf-8")}catch(e){console.error("Error saving user settings file:",e)}}Hn();async function HAe(){try{if(!process.env.KODA_API_KEY){let t=await tqe();t&&(process.env.KODA_API_KEY=t)}}catch{}try{if(!process.env.KODA_GITHUB_TOKEN&&!process.env.GITHUB_TOKEN){let t=await eqe();t&&(process.env.KODA_GITHUB_TOKEN=t,process.env.GITHUB_TOKEN||(process.env.GITHUB_TOKEN=t))}}catch{}}function YU(){return[process.env.KODA_API_KEY,process.env.KODA_GITHUB_TOKEN,process.env.GITHUB_TOKEN].some(e=>typeof e=="string"&&e.trim().length>0)}Hn();var Iqe="https://api.openai.com/v1",gb=null;function yPn(){return"https://api.kodacode.ru/v1"}function Tqe(t){let e=(t||Iqe).trim();if(!/^https?:\/\//i.test(e))throw new Error("Base URL must start with http:// or https://");try{let r=new URL(e);return r.pathname=r.pathname.replace(/\/+$/,""),r.pathname.endsWith("/responses")&&(r.pathname=r.pathname.replace(/\/responses$/,"")),r.toString().replace(/\/+$/,"")}catch{return e.replace(/\/+$/,"")}}async function WU(){let t=await nqe();return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,{model:e,...r}]))}async function air(t){let e=Tqe(t.baseUrl);await rqe(t.model,{apiKey:t.apiKey,baseUrl:e})}async function xqe(t){await iqe(t)}async function sir(t,e){return mU({baseUrl:Tqe(t),apiKey:e,includeDefaults:!1})}async function GAe(t){let r=(await WU())[t];if(!r)return null;gb||(gb={baseUrl:process.env.KODA_API_BASE,apiKey:process.env.KODA_API_KEY,openAiKey:process.env.OPENAI_API_KEY,defaultBaseUrl:process.env.KODA_DEFAULT_API_BASE});let n=gb.baseUrl||gb.defaultBaseUrl||yPn();process.env.KODA_DEFAULT_API_BASE=n;let i=Tqe(r.baseUrl);return process.env.KODA_API_BASE=i,process.env.KODA_API_KEY=r.apiKey,process.env.OPENAI_API_KEY=r.apiKey,{...r,baseUrl:i}}async function VAe(){if(gb){let{baseUrl:t,apiKey:e,openAiKey:r,defaultBaseUrl:n}=gb;gb=null,t?process.env.KODA_API_BASE=t:delete process.env.KODA_API_BASE,e?process.env.KODA_API_KEY=e:delete process.env.KODA_API_KEY,r?process.env.OPENAI_API_KEY=r:delete process.env.OPENAI_API_KEY,n?process.env.KODA_DEFAULT_API_BASE=n:delete process.env.KODA_DEFAULT_API_BASE;return}delete process.env.KODA_API_BASE,delete process.env.KODA_API_KEY,delete process.env.OPENAI_API_KEY,await HAe()}async function oir(t){if(t){let e=await GAe(t);if(e)return e}return gb&&await VAe(),null}var lir="__add_custom_model__";function uir(t,e){let[r,n]=(0,zl.useState)(!1),[i,a]=(0,zl.useState)(!1),[s,o]=(0,zl.useState)([]),[l,u]=(0,zl.useState)([]),[c,d]=(0,zl.useState)(!1),[h,f]=(0,zl.useState)(null),[E,y]=(0,zl.useState)(null),[g,C]=(0,zl.useState)(null),[D,S]=(0,zl.useState)(!1),[w,N]=(0,zl.useState)({}),[M,U]=(0,zl.useState)(null),[k,B]=(0,zl.useState)("add"),[q,W]=(0,zl.useState)(null),[re,$]=(0,zl.useState)(null),R=(0,zl.useCallback)((pe,_e)=>{let Se=new Set,se=[];for(let ve of pe){if(Se.has(ve))continue;Se.add(ve);let X=!!_e[ve];se.push({value:ve,label:X?De.t("app.modelDialog.customModelLabel",{model:ve}):ve,source:X?"custom":"builtin"})}for(let ve of Object.values(_e))Se.has(ve.model)||(Se.add(ve.model),se.push({value:ve.model,label:De.t("app.modelDialog.customModelLabel",{model:ve.model}),source:"custom"}));return se.push({value:lir,label:De.t("app.modelDialog.addCustomModelAction"),source:"action"}),se},[]),Q=(0,zl.useCallback)((pe,_e)=>{o(R(_e??l,pe))},[l,R]),J=(0,zl.useCallback)(()=>{n(!0),a(!1),d(!0),f(null),y(null),C(null);let pe=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU());(async()=>{try{let[_e,Se]=await Promise.all([WU(),pe?mU():Promise.resolve(["KodaAgent"])]);N(_e);let se=t.getModel()||lp,ve=!!_e[se];!pe&&!ve&&se!=="KodaAgent"&&(y(De.t("app.modelDialog.kodaAuthRequired")),t.setModel("KodaAgent"),e.setValue("User","model","KodaAgent"),se="KodaAgent",ve=!1);let X=new Set;se&&!ve&&X.add(se);for(let ie of Se)X.add(ie);let ee=Array.from(X);u(ee),o(R(ee,_e)),U(ve?se:null)}catch(_e){f(_e?.message||De.t("app.modelDialog.loadError"));let Se=t.getModel()||lp,se=await WU().catch(()=>({})),X=!!se[Se]?[]:[Se];u(X),o(R(X,se))}finally{d(!1)}})()},[R,t,e]),ae=(0,zl.useCallback)(()=>n(!1),[]),fe=(0,zl.useCallback)((pe,_e)=>{if(!pe){n(!1);return}if(pe===lir){n(!1),C(null),B("add"),W(null),$(null),a(!0);return}let Se=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU()),se=!!w[pe];(async()=>{try{if(!Se&&!se&&pe!=="KodaAgent"){y(De.t("app.modelDialog.kodaAuthRequired")),e.setValue(_e,"model","KodaAgent"),t.setModel("KodaAgent"),n(!1);return}se?(await GAe(pe),U(pe)):M&&(await VAe(),U(null)),e.setValue(_e,"model",pe),t.setModel(pe),(se||M)&&await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH)}catch(ve){f(ve?.message||De.t("app.modelDialog.switchError"))}finally{n(!1)}})()},[M,t,w,e]),K=(0,zl.useCallback)((pe,_e)=>{let Se=w[pe];Se&&(C(null),f(null),B("edit"),W({model:pe,baseUrl:Se.baseUrl,apiKey:Se.apiKey}),$(pe),n(!1),a(!0))},[w]),ne=(0,zl.useCallback)((pe,_e)=>{if(!w[pe])return;f(null),C(null);let se=!!(e.merged.selectedAuthType&&e.merged.selectedAuthType!==ln.WITHOUT_AUTH&&YU());(async()=>{try{let X=(t.getModel()||lp)===pe,ee=s.findIndex(Ce=>Ce.value===pe);await xqe(pe);let ie=await WU();N(ie);let me=l,ue=null;if(X){if(await VAe(),U(null),ue=se?lp:"KodaAgent",se&&!l.includes(lp)){let Ce=s.slice(ee+1).find(G=>G.source==="builtin"),le=s.slice(0,Math.max(0,ee)).reverse().find(G=>G.source==="builtin");ue=Ce?.value||le?.value||ue}ue&&!me.includes(ue)&&(me=[ue,...me],u(me))}Q(ie,me),X&&ue&&(e.setValue(_e,"model",ue),t.setModel(ue),await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH))}catch(ve){f(ve?.message||De.t("app.modelDialog.deleteError"))}})()},[l,t,w,s,Q,e]),he=(0,zl.useCallback)(pe=>{let _e=re,Se=!!_e;S(!0),C(null),(async()=>{try{let se=pe.model.trim();if(!se)throw new Error(De.t("app.customModel.validationMissingId"));let ve=!Se||t.getModel()===_e,X=null;try{if(X=await sir(pe.baseUrl,pe.apiKey),X.length>0&&!X.includes(se))throw new Error(De.t("app.customModel.modelNotFound",{modelId:se}))}catch(ie){console.warn("[custom model] Unable to verify /models endpoint:",ie?.message||ie)}await air({...pe,model:se}),Se&&_e&&_e!==se&&await xqe(_e);let ee=await WU();N(ee),Q(ee),ve&&(await GAe(se),e.setValue("User","model",se),t.setModel(se),U(se),await t.refreshAuth(e.merged.selectedAuthType??ln.WITHOUT_AUTH)),a(!1),B("add"),W(null),$(null)}catch(se){C(se?.message||(Se?De.t("app.customModel.saveErrorEdit"):De.t("app.customModel.saveErrorAdd")))}finally{S(!1)}})()},[t,re,Q,e]),Ee=(0,zl.useCallback)(()=>{a(!1),C(null),B("add"),W(null),$(null)},[]);return{isModelDialogOpen:r,isCustomModelDialogOpen:i,openModelDialog:J,closeModelDialog:ae,models:s,loading:c,error:h,unauthorizedUserError:E,customModelError:g,customModelBusy:D,customModelDraft:q,customModelDialogMode:k,handleModelSelect:fe,handleCustomModelEdit:K,handleCustomModelDelete:ne,handleCustomModelSubmit:he,handleCustomModelCancel:Ee}}var l3=Ve(lr(),1);Hn();IU();import vPn from"node:os";import Bqe from"node:path";import{promises as Rqe}from"node:fs";async function CPn(t,e){if(!e)try{(await h5(t)).on("error",()=>{})}catch{}}var _Pn="https://github.com/login/device/code",DPn="https://github.com/login/oauth/access_token";async function SPn(t,e){let r=await fetch(_Pn,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,scope:e.join(" ")})});if(!r.ok)throw new Error(`GitHub device code failed: ${r.status} ${r.statusText}`);return await r.json()}async function bPn(t,e,r){let n=Math.max(5,r)*1e3;for(;;){await new Promise(s=>setTimeout(s,n));let i=await fetch(DPn,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(!i.ok)throw new Error(`GitHub token poll failed: ${i.status} ${i.statusText}`);let a=await i.json();if("access_token"in a)return a.access_token;switch(a.error){case"authorization_pending":break;case"slow_down":n+=5e3;break;case"access_denied":throw new Error("User denied access.");case"expired_token":throw new Error("Device code expired. Please retry login.");default:throw new Error(`OAuth error: ${a.error}${a.error_description?` - ${a.error_description}`:""}`)}}}function cir(){let t=process.env.XDG_CONFIG_HOME||Bqe.join(vPn.homedir(),".config");return Bqe.join(t,"koda")}var dir=Bqe.join(cir(),"credentials.json");async function pir(){try{let t=await Rqe.readFile(dir,"utf-8"),e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}async function fir(t){await Rqe.mkdir(cir(),{recursive:!0}),await Rqe.writeFile(dir,JSON.stringify(t,null,2),{mode:384})}async function wPn(t){let e=await pir();e.githubToken=t,await fir(e)}async function IPn(t){let e=await pir();e.kodaApiKey=t,await fir(e)}async function TPn(t){let e=process.env.KODA_GITHUB_EXCHANGE_URL;if(!e)return null;try{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({})});if(!r.ok)throw new Error(`Exchange failed: ${r.status} ${r.statusText}`);let n=await r.json();return typeof n.apiKey=="string"&&n.apiKey.length>0?n.apiKey:null}catch(r){return console.warn("GitHub token exchange failed:",r),null}}async function qAe(t,e){let r="Ov23li5pZhE4aeH5fTSE";if(!r)throw new Error("GITHUB_CLIENT_ID is not set. Create a GitHub OAuth App and set GITHUB_CLIENT_ID.");let n=(process.env.GITHUB_SCOPES||"read:user user:email").split(/\s+/),{device_code:i,user_code:a,verification_uri:s,interval:o=5}=await SPn(r,n);try{e?.(s,a)}catch{}console.log(`
1845
1845
  GitHub Login`),console.log(`Open: ${s}`),console.log(`Code: ${a}
1846
1846
  `),await CPn(s,t.isBrowserLaunchSuppressed());let l=await bPn(i,r,o);await wPn(l),process.env.KODA_GITHUB_TOKEN=l,process.env.GITHUB_TOKEN=process.env.GITHUB_TOKEN||l;let u=await TPn(l);u&&(process.env.KODA_API_KEY=u,await IPn(u)),console.log("GitHub authentication successful.")}var mir=(t,e,r)=>{let[n,i]=(0,l3.useState)(t.merged.selectedAuthType===void 0),a=(0,l3.useCallback)(()=>{i(!0)},[]),[s,o]=(0,l3.useState)(!1),[l,u]=(0,l3.useState)(void 0),[c,d]=(0,l3.useState)(void 0);(0,l3.useEffect)(()=>{(async()=>{let y=t.merged.selectedAuthType;if(!n){if(!y){try{await r.refreshAuth(void 0),console.log("Proceeding without authentication.")}catch(g){e(`Failed to initialize. Message: ${sr(g)}`),a()}return}try{o(!0),await r.refreshAuth(y),console.log(`Authenticated via "${y}".`)}catch(g){e(`Failed to login. Message: ${sr(g)}`),a()}finally{o(!1)}}})()},[n,t,r,e,a]);let h=(0,l3.useCallback)(async(E,y)=>{if(E){if(await SJ(),E===ln.LOGIN_WITH_GITHUB){o(!0),u(void 0),d(void 0);try{await qAe(r,(g,C)=>{u(g),d(C)})}catch(g){o(!1),e(`Failed to login with GitHub. Message: ${sr(g)}`);return}o(!1)}t.setValue(y,"selectedAuthType",E)}else t.setValue(y,"selectedAuthType",void 0);i(!1),e(null)},[t,e,r]),f=(0,l3.useCallback)(()=>{o(!1)},[]);return{isAuthDialogOpen:n,openAuthDialog:a,handleAuthSelect:h,isAuthenticating:s,cancelAuthentication:f,verificationUri:l,userCode:c}};var _R=Ve(lr(),1);var ke={get type(){return rs.getActiveTheme().colors.type},get Foreground(){return rs.getActiveTheme().colors.Foreground},get Background(){return rs.getActiveTheme().colors.Background},get LightBlue(){return rs.getActiveTheme().colors.LightBlue},get AccentBlue(){return rs.getActiveTheme().colors.AccentBlue},get AccentPurple(){return rs.getActiveTheme().colors.AccentPurple},get AccentCyan(){return rs.getActiveTheme().colors.AccentCyan},get AccentGreen(){return rs.getActiveTheme().colors.AccentGreen},get AccentYellow(){return rs.getActiveTheme().colors.AccentYellow},get AccentRed(){return rs.getActiveTheme().colors.AccentRed},get DiffAdded(){return rs.getActiveTheme().colors.DiffAdded},get DiffRemoved(){return rs.getActiveTheme().colors.DiffRemoved},get Comment(){return rs.getActiveTheme().colors.Comment},get Gray(){return rs.getActiveTheme().colors.Gray},get GradientColors(){return rs.getActiveTheme().colors.GradientColors}};var $7=Ve(lr(),1);var g2=Ve(Lt(),1);function Kl({items:t,initialIndex:e=0,onSelect:r,onHighlight:n,isFocused:i=!0,showScrollArrows:a=!1,maxItemsToShow:s=10,showNumbers:o=!0}){let[l,u]=(0,$7.useState)(e),[c,d]=(0,$7.useState)(0),[h,f]=(0,$7.useState)(""),E=(0,$7.useRef)(null);(0,$7.useEffect)(()=>{let g=Math.max(0,Math.min(l-s+1,t.length-s));l<c?d(l):l>=c+s&&d(g)},[l,t.length,c,s]),(0,$7.useEffect)(()=>()=>{E.current&&clearTimeout(E.current)},[]),ts(g=>{let{sequence:C,name:D}=g,S=o&&/^[0-9]$/.test(C);if(!S&&E.current&&(clearTimeout(E.current),f("")),D==="k"||D==="up"){let w=l>0?l-1:t.length-1;u(w),n?.(t[w].value);return}if(D==="j"||D==="down"){let w=l<t.length-1?l+1:0;u(w),n?.(t[w].value);return}if(D==="return"){r(t[l].value);return}if(S){E.current&&clearTimeout(E.current);let w=h+C;f(w);let N=Number.parseInt(w,10)-1;if(w==="0"){E.current=setTimeout(()=>f(""),350);return}if(N>=0&&N<t.length){let M=t[N];u(N),n?.(M.value),Number.parseInt(w+"0",10)>t.length?(r(M.value),f("")):E.current=setTimeout(()=>{r(M.value),f("")},350)}else f("")}},{isActive:!!(i&&t.length>0)});let y=t.slice(c,c+s);return(0,g2.jsxs)(Le,{flexDirection:"column",children:[a&&(0,g2.jsx)(be,{color:c>0?ke.Foreground:ke.Gray,children:"\u25B2"}),y.map((g,C)=>{let D=c+C,S=l===D,w=ke.Foreground,N=ke.Foreground;S?(w=ke.AccentGreen,N=ke.AccentGreen):g.disabled&&(w=ke.Gray,N=ke.Gray),o||(N=ke.Gray);let M=String(t.length).length,U=`${String(D+1).padStart(M)}.`;return(0,g2.jsxs)(Le,{alignItems:"center",children:[(0,g2.jsx)(Le,{minWidth:2,flexShrink:0,children:(0,g2.jsx)(be,{color:S?ke.AccentGreen:ke.Foreground,children:S?"\u25CF":" "})}),(0,g2.jsx)(Le,{marginRight:1,flexShrink:0,minWidth:U.length,children:(0,g2.jsx)(be,{color:N,children:U})}),g.themeNameDisplay&&g.themeTypeDisplay?(0,g2.jsxs)(be,{color:w,wrap:"truncate",children:[g.themeNameDisplay," ",(0,g2.jsx)(be,{color:ke.Gray,children:g.themeTypeDisplay})]}):(0,g2.jsx)(be,{color:w,wrap:"truncate",children:g.label})]},g.label)}),a&&(0,g2.jsx)(be,{color:c+s<t.length?ke.Foreground:ke.Gray,children:"\u25BC"})]})}var CR=Ve(Lt(),1);var hir=({onSelect:t})=>{ts(r=>{r.name==="escape"&&t("do_not_trust")},{isActive:!0});let e=[{label:"Trust folder",value:"trust_folder"},{label:"Trust parent folder",value:"trust_parent"},{label:"Don't trust (esc)",value:"do_not_trust"}];return(0,CR.jsxs)(Le,{flexDirection:"column",borderStyle:"round",borderColor:ke.AccentYellow,padding:1,width:"100%",marginLeft:1,children:[(0,CR.jsxs)(Le,{flexDirection:"column",marginBottom:1,children:[(0,CR.jsx)(be,{bold:!0,children:"Do you trust this folder?"}),(0,CR.jsx)(be,{children:"Trusting a folder allows Gemini to execute commands it suggests. This is a security feature to prevent accidental execution in untrusted directories."})]}),(0,CR.jsx)(Kl,{items:e,onSelect:t,isFocused:!0})]})};Hn();var Air=Ve(_qe(),1);import*as Y7 from"fs";import*as j7 from"path";import{homedir as xPn}from"os";var BPn="trustedFolders.json",RPn=".kodacli",NPn=j7.join(xPn(),RPn),OPn=j7.join(NPn,BPn);var Nqe=class{constructor(e,r){this.user=e;this.errors=r}get rules(){return Object.entries(this.user.config).map(([e,r])=>({path:e,trustLevel:r}))}setValue(e,r){this.user.config[e]=r,FPn(this.user)}};function Oqe(){let t=[],e={},r=OPn;try{if(Y7.existsSync(r)){let n=Y7.readFileSync(r,"utf-8"),i=JSON.parse((0,Air.default)(n));i&&Object.assign(e,i)}}catch(n){t.push({message:sr(n),path:r})}return new Nqe({path:r,config:e},t)}function FPn(t){try{let e=j7.dirname(t.path);Y7.existsSync(e)||Y7.mkdirSync(e,{recursive:!0}),Y7.writeFileSync(t.path,JSON.stringify(t.config,null,2),"utf-8")}catch(e){console.error("Error saving trusted folders file:",e)}}function jJ(t){let e=t.folderTrustFeature??!1,r=t.folderTrust??!0;if(!(e&&r))return!0;let{rules:i,errors:a}=Oqe();if(a.length>0)for(let u of a)console.error(`Error loading trusted folders config from ${u.path}: ${u.message}`);let s=[],o=[];for(let u of i)switch(u.trustLevel){case"TRUST_FOLDER":s.push(u.path);break;case"TRUST_PARENT":s.push(j7.dirname(u.path));break;case"DO_NOT_TRUST":o.push(u.path);break;default:break}let l=process.cwd();for(let u of s)if(WW(l,u))return!0;for(let u of o)if(j7.normalize(l)===j7.normalize(u))return!1}import*as gir from"process";var Eir=(t,e)=>{let[r,n]=(0,_R.useState)(void 0),[i,a]=(0,_R.useState)(!1),{folderTrust:s,folderTrustFeature:o}=t.merged;(0,_R.useEffect)(()=>{let u=jJ({folderTrust:s,folderTrustFeature:o});n(u),a(u===void 0),e(u)},[e,s,o]);let l=(0,_R.useCallback)(u=>{let c=Oqe(),d=gir.cwd(),h;switch(u){case"trust_folder":h="TRUST_FOLDER";break;case"trust_parent":h="TRUST_PARENT";break;case"do_not_trust":h="DO_NOT_TRUST";break;default:return}c.setValue(d,h);let f=jJ({folderTrust:s,folderTrustFeature:o});n(f),a(!1),e(f)},[e,s,o]);return{isTrusted:r,isFolderTrustDialogOpen:i,handleFolderTrustSelect:l}};var zU=Ve(lr(),1);Hn();var yir=(t,e,r)=>{let[n,i]=(0,zU.useState)(!1),a=(0,zU.useCallback)(()=>{i(!0)},[]),s=(0,zU.useCallback)((l,u)=>{if(!(l&&(!gU(l)||!EU(l))))try{t.setValue(u,"preferredEditor",l),r({type:"info",text:`Editor preference ${l?`set to "${l}"`:"cleared"} in ${u} settings.`},Date.now()),e(null),i(!1)}catch(c){e(`Failed to set editor preference: ${c}`)}},[t,e,r]),o=(0,zU.useCallback)(()=>{i(!1)},[]);return{isEditorDialogOpen:n,openEditorDialog:a,handleEditorSelect:s,exitEditorDialog:o}};var y1=Ve(lr(),1);Hn();import BUn from"node:process";Hn();import{promises as MPn}from"fs";import{join as LPn}from"path";var Fqe=[];function KU(t){Fqe.push(t)}async function vir(){for(let t of Fqe)try{await t()}catch{}Fqe.length=0}async function Cir(){let t=cv(process.cwd()),e=LPn(t,"checkpoints");try{await MPn.rm(e,{recursive:!0,force:!0})}catch{}}var $Ae=class t{constructor(e){this.commands=e}static async create(e,r){let n=await Promise.allSettled(e.map(o=>o.loadCommands(r))),i=[];for(let o of n)o.status==="fulfilled"?i.push(...o.value):console.debug("A command loader failed:",o.reason);let a=new Map;for(let o of i){let l=o.name;if(o.extensionName&&a.has(o.name)){let u=`${o.extensionName}.${o.name}`,c=1;for(;a.has(u);)u=`${o.extensionName}.${o.name}${c}`,c++;l=u}a.set(l,{...o,name:l})}let s=Object.freeze(Array.from(a.values()));return new t(s)}getCommands(){return this.commands}};import Pkn from"node:path";import PPn from"node:process";import QPn from"node:fs/promises";import{fileURLToPath as kPn}from"node:url";import JU from"node:path";var _ir=t=>t instanceof URL?kPn(t):t;async function Dir(t,{cwd:e=PPn.cwd(),type:r="file",stopAt:n}={}){let i=JU.resolve(_ir(e)??""),{root:a}=JU.parse(i);n=JU.resolve(i,_ir(n??a));let s=JU.isAbsolute(t);for(;i;){let o=s?t:JU.join(i,t);try{let l=await QPn.stat(o);if(r==="file"&&l.isFile()||r==="directory"&&l.isDirectory())return o}catch{}if(i===n||i===a)break;i=JU.dirname(i)}}import Okn from"node:fs/promises";import Fkn from"node:path";var Wir=Ve(Yir(),1);function sQn(t,e){let r=e===0?-1:t.lastIndexOf(`
1847
1847
  `,e-1);return{line:r===-1?0:t.slice(0,r+1).match(/\n/g).length,column:e-r-1}}function Hqe(t,e,{oneBased:r=!1}={}){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");let n=sQn(t,e);return r?{line:n.line+1,column:n.column+1}:n}var oQn=t=>`\\u{${t.codePointAt(0).toString(16)}}`,Gqe=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#a;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:i}=e;super(void 0,{cause:r}),this.#e=i,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${uQn(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
1848
1848
 
1849
1849
  ${e}
1850
- `:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=lQn(r,this.#t.message);if(n)return(0,Wir.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#a??=this.#i(!1),this.#a}},lQn=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:a}=r.groups;return i&&a?{line:Number(i),column:Number(a)}:Hqe(t,Number(n),{oneBased:!0})},uQn=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${oQn(n)})`);function Vqe(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new Gqe({jsonParseError:n,fileName:r,input:t})}}var dsr=Ve(usr(),1);import{fileURLToPath as Nkn}from"node:url";function csr(t){return t instanceof URL?Nkn(t):t}var Mkn=t=>Fkn.resolve(csr(t)??".","package.json"),Lkn=(t,e)=>{let r=typeof t=="string"?Vqe(t):t;return e&&(0,dsr.default)(r),r};async function psr({cwd:t,normalize:e=!0}={}){let r=await Okn.readFile(Mkn(t),"utf8");return Lkn(r,e)}async function fsr(t){let e=await Dir("package.json",t);if(e)return{packageJson:await psr({...t,cwd:Pkn.dirname(e)}),path:e}}import{fileURLToPath as Qkn}from"url";import kkn from"path";var Ukn=Qkn(import.meta.url),Hkn=kkn.dirname(Ukn),a2e;async function tH(){if(a2e)return a2e;let t=await fsr({cwd:Hkn});if(t)return a2e=t.packageJson,a2e}async function Cb(){let t=await tH();return"0.1.9"}import SR from"node:process";var msr={name:"about",description:()=>De.t("commandDescriptions.about"),kind:"built-in",action:async t=>{let e=SR.platform,r="no sandbox";SR.env.SANDBOX&&SR.env.SANDBOX!=="sandbox-exec"?r=SR.env.SANDBOX:SR.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${SR.env.SEATBELT_PROFILE||"unknown"})`);let n=t.services.config?.getModel()||"Unknown",i=await Cb(),a=t.services.settings.merged.selectedAuthType||"",s=SR.env.GOOGLE_CLOUD_PROJECT||"",o={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:a,gcpProject:s};t.ui.addItem(o,Date.now())}};var hsr={name:"auth",description:()=>De.t("commandDescriptions.auth"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};IU();import _b from"node:process";var rH="d573c51c";Hn();var Asr={name:"bug",description:()=>De.t("commandDescriptions.bug"),kind:"built-in",action:async(t,e)=>{let r=(e||"").trim(),{config:n}=t.services,i=`${_b.platform} ${_b.version}`,a="no sandbox";_b.env.SANDBOX&&_b.env.SANDBOX!=="sandbox-exec"?a=_b.env.SANDBOX.replace(/^gemini-(?:code-)?/,""):_b.env.SANDBOX==="sandbox-exec"&&(a=`sandbox-exec (${_b.env.SEATBELT_PROFILE||"unknown"})`);let s=n?.getModel()||"Unknown",o=await Cb(),l=QU(_b.memoryUsage().rss),u=`* **CLI Version:** ${o}
1850
+ `:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=lQn(r,this.#t.message);if(n)return(0,Wir.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#a??=this.#i(!1),this.#a}},lQn=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:i,column:a}=r.groups;return i&&a?{line:Number(i),column:Number(a)}:Hqe(t,Number(n),{oneBased:!0})},uQn=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${oQn(n)})`);function Vqe(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new Gqe({jsonParseError:n,fileName:r,input:t})}}var dsr=Ve(usr(),1);import{fileURLToPath as Nkn}from"node:url";function csr(t){return t instanceof URL?Nkn(t):t}var Mkn=t=>Fkn.resolve(csr(t)??".","package.json"),Lkn=(t,e)=>{let r=typeof t=="string"?Vqe(t):t;return e&&(0,dsr.default)(r),r};async function psr({cwd:t,normalize:e=!0}={}){let r=await Okn.readFile(Mkn(t),"utf8");return Lkn(r,e)}async function fsr(t){let e=await Dir("package.json",t);if(e)return{packageJson:await psr({...t,cwd:Pkn.dirname(e)}),path:e}}import{fileURLToPath as Qkn}from"url";import kkn from"path";var Ukn=Qkn(import.meta.url),Hkn=kkn.dirname(Ukn),a2e;async function tH(){if(a2e)return a2e;let t=await fsr({cwd:Hkn});if(t)return a2e=t.packageJson,a2e}async function Cb(){let t=await tH();return"0.1.10"}import SR from"node:process";var msr={name:"about",description:()=>De.t("commandDescriptions.about"),kind:"built-in",action:async t=>{let e=SR.platform,r="no sandbox";SR.env.SANDBOX&&SR.env.SANDBOX!=="sandbox-exec"?r=SR.env.SANDBOX:SR.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${SR.env.SEATBELT_PROFILE||"unknown"})`);let n=t.services.config?.getModel()||"Unknown",i=await Cb(),a=t.services.settings.merged.selectedAuthType||"",s=SR.env.GOOGLE_CLOUD_PROJECT||"",o={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:a,gcpProject:s};t.ui.addItem(o,Date.now())}};var hsr={name:"auth",description:()=>De.t("commandDescriptions.auth"),kind:"built-in",action:(t,e)=>({type:"dialog",dialog:"auth"})};IU();import _b from"node:process";var rH="d573c51c";Hn();var Asr={name:"bug",description:()=>De.t("commandDescriptions.bug"),kind:"built-in",action:async(t,e)=>{let r=(e||"").trim(),{config:n}=t.services,i=`${_b.platform} ${_b.version}`,a="no sandbox";_b.env.SANDBOX&&_b.env.SANDBOX!=="sandbox-exec"?a=_b.env.SANDBOX.replace(/^gemini-(?:code-)?/,""):_b.env.SANDBOX==="sandbox-exec"&&(a=`sandbox-exec (${_b.env.SEATBELT_PROFILE||"unknown"})`);let s=n?.getModel()||"Unknown",o=await Cb(),l=QU(_b.memoryUsage().rss),u=`* **CLI Version:** ${o}
1851
1851
  * **Git Commit:** ${rH}
1852
1852
  * **Session ID:** ${C5}
1853
1853
  * **Operating System:** ${i}
@@ -2033,7 +2033,7 @@ Koda CLI - Launch an interactive CLI, use -p/--prompt for non-interactive mode`)
2033
2033
  `),a=/^ *(#{1,4}) +(.*)/,s=/^ *(`{3,}|~{3,}) *(\w*?) *$/,o=/^([ \t]*)([-*+]) +(.*)/,l=/^([ \t]*)(\d+)\. +(.*)/,u=/^ *([-*_] *){3,} *$/,c=/^\s*\|(.+)\|\s*$/,d=/^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/,h=[],f=!1,E=!0,y=[],g=null,C="",D=!1,S=[],w=[];function N(M){M&&(h.push(M),E=!1)}return i.forEach((M,U)=>{let k=`line-${U}`;if(f){let J=M.match(s);J&&J[1].startsWith(C[0])&&J[1].length>=C.length?(N((0,Ai.jsx)(efr,{content:y,lang:g,isPending:e,availableTerminalHeight:r,terminalWidth:n},k)),f=!1,y=[],g=null,C=""):y.push(M);return}let B=M.match(s),q=M.match(a),W=M.match(o),re=M.match(l),$=M.match(u),R=M.match(c),Q=M.match(d);if(B)f=!0,C=B[1],g=B[2]||null;else if(R&&!D)U+1<i.length&&i[U+1].match(d)?(D=!0,w=R[1].split("|").map(J=>J.trim()),S=[]):N((0,Ai.jsx)(Le,{children:(0,Ai.jsx)(be,{wrap:"wrap",children:(0,Ai.jsx)(I2,{text:M})})},k));else if(!(D&&Q))if(D&&R){let J=R[1].split("|").map(ae=>ae.trim());for(;J.length<w.length;)J.push("");J.length>w.length&&(J.length=w.length),S.push(J)}else if(D&&!R)w.length>0&&S.length>0&&N((0,Ai.jsx)(rfr,{headers:w,rows:S,terminalWidth:n},`table-${h.length}`)),D=!1,S=[],w=[],M.trim().length>0&&N((0,Ai.jsx)(Le,{children:(0,Ai.jsx)(be,{wrap:"wrap",children:(0,Ai.jsx)(I2,{text:M})})},k));else if($)N((0,Ai.jsx)(Le,{children:(0,Ai.jsx)(be,{dimColor:!0,children:"---"})},k));else if(q){let J=q[1].length,ae=q[2],fe=null;switch(J){case 1:fe=(0,Ai.jsx)(be,{bold:!0,color:ke.AccentCyan,children:(0,Ai.jsx)(I2,{text:ae})});break;case 2:fe=(0,Ai.jsx)(be,{bold:!0,color:ke.AccentBlue,children:(0,Ai.jsx)(I2,{text:ae})});break;case 3:fe=(0,Ai.jsx)(be,{bold:!0,children:(0,Ai.jsx)(I2,{text:ae})});break;case 4:fe=(0,Ai.jsx)(be,{italic:!0,color:ke.Gray,children:(0,Ai.jsx)(I2,{text:ae})});break;default:fe=(0,Ai.jsx)(be,{children:(0,Ai.jsx)(I2,{text:ae})});break}fe&&N((0,Ai.jsx)(Le,{children:fe},k))}else if(W){let J=W[1],ae=W[2],fe=W[3];N((0,Ai.jsx)(tfr,{itemText:fe,type:"ul",marker:ae,leadingWhitespace:J},k))}else if(re){let J=re[1],ae=re[2],fe=re[3];N((0,Ai.jsx)(tfr,{itemText:fe,type:"ol",marker:ae,leadingWhitespace:J},k))}else M.trim().length===0&&!f?E||(h.push((0,Ai.jsx)(Le,{height:U$n},`spacer-${U}`)),E=!0):N((0,Ai.jsx)(Le,{children:(0,Ai.jsx)(be,{wrap:"wrap",children:(0,Ai.jsx)(I2,{text:M})})},k))}),f&&N((0,Ai.jsx)(efr,{content:y,lang:g,isPending:e,availableTerminalHeight:r,terminalWidth:n},"line-eof")),D&&w.length>0&&S.length>0&&N((0,Ai.jsx)(rfr,{headers:w,rows:S,terminalWidth:n},`table-${h.length}`)),(0,Ai.jsx)(Ai.Fragment,{children:h})},q$n=({content:t,lang:e,isPending:r,availableTerminalHeight:n,terminalWidth:i})=>{let a=Z1r(),s=1,o=2;if(r&&n!==void 0){let c=Math.max(0,n-o);if(t.length>c){if(c<s)return(0,Ai.jsx)(Le,{paddingLeft:PX,children:(0,Ai.jsx)(be,{color:ke.Gray,children:"... code is being written ..."})});let d=t.slice(0,c),h=MR(d.join(`
2034
2034
  `),e,n,i-PX,void 0,a);return(0,Ai.jsxs)(Le,{paddingLeft:PX,flexDirection:"column",children:[h,(0,Ai.jsx)(be,{color:ke.Gray,children:"... generating more ..."})]})}}let l=t.join(`
2035
2035
  `),u=MR(l,e,n,i-PX,void 0,a);return(0,Ai.jsx)(Le,{paddingLeft:PX,flexDirection:"column",width:i,flexShrink:0,children:u})},efr=QX.default.memo(q$n),$$n=({itemText:t,type:e,marker:r,leadingWhitespace:n=""})=>{let i=e==="ol"?`${r}. `:`${r} `,a=i.length,s=n.length;return(0,Ai.jsxs)(Le,{paddingLeft:s+H$n,flexDirection:"row",children:[(0,Ai.jsx)(Le,{width:a,children:(0,Ai.jsx)(be,{children:i})}),(0,Ai.jsx)(Le,{flexGrow:G$n,children:(0,Ai.jsx)(be,{wrap:"wrap",children:(0,Ai.jsx)(I2,{text:t})})})]})},tfr=QX.default.memo($$n),j$n=({headers:t,rows:e,terminalWidth:r})=>(0,Ai.jsx)(X1r,{headers:t,rows:e,terminalWidth:r}),rfr=QX.default.memo(j$n),RH=QX.default.memo(V$n);var zR=Ve(Lt(),1);var nfr=({text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})=>{let i="\u276F ",a=i.length;return(0,zR.jsxs)(Le,{flexDirection:"row",children:[(0,zR.jsx)(Le,{width:a,children:(0,zR.jsx)(be,{color:ke.AccentPurple,children:i})}),(0,zR.jsx)(Le,{flexGrow:1,flexDirection:"column",children:(0,zR.jsx)(RH,{text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})})]})};var KR=Ve(Lt(),1);var ifr=({text:t})=>{let e="\u2139 ",r=e.length;return(0,KR.jsxs)(Le,{flexDirection:"row",marginTop:1,children:[(0,KR.jsx)(Le,{width:r,children:(0,KR.jsx)(be,{color:ke.AccentYellow,children:e})}),(0,KR.jsx)(Le,{flexGrow:1,children:(0,KR.jsx)(be,{wrap:"wrap",color:ke.AccentYellow,children:t})})]})};var JR=Ve(Lt(),1);var afr=({text:t})=>{let e="\u2715 ",r=e.length;return(0,JR.jsxs)(Le,{flexDirection:"row",marginBottom:1,children:[(0,JR.jsx)(Le,{width:r,children:(0,JR.jsx)(be,{color:ke.AccentRed,children:e})}),(0,JR.jsx)(Le,{flexGrow:1,children:(0,JR.jsx)(be,{wrap:"wrap",color:ke.AccentRed,children:t})})]})};var dfr=Ve(lr(),1);var ofr=Ve(lr(),1);var ml=Ve(Lt(),1);var Y$n=1,W$n=5,lfr=3,z$n=2,sfr=1e6,ufr=({name:t,description:e,resultDisplay:r,status:n,availableTerminalHeight:i,terminalWidth:a,emphasis:s="medium",renderOutputAsMarkdown:o=!0})=>{let l=i?Math.max(i-Y$n-W$n,z$n+1):void 0;l&&(o=!1);let u=a-3;return typeof r=="string"&&r.length>sfr&&(r="..."+r.slice(-sfr)),(0,ml.jsxs)(Le,{paddingX:1,paddingY:0,flexDirection:"column",children:[(0,ml.jsxs)(Le,{minHeight:1,children:[(0,ml.jsx)(K$n,{status:n}),(0,ml.jsx)(J$n,{name:t,status:n,description:e,emphasis:s}),s==="high"&&(0,ml.jsx)(X$n,{})]}),r&&(0,ml.jsx)(Le,{paddingLeft:lfr,width:"100%",marginTop:1,children:(0,ml.jsxs)(Le,{flexDirection:"column",children:[typeof r=="string"&&o&&(0,ml.jsx)(Le,{flexDirection:"column",children:(0,ml.jsx)(RH,{text:r,isPending:!1,availableTerminalHeight:l,terminalWidth:u})}),typeof r=="string"&&!o&&(0,ml.jsx)(d3,{maxHeight:l,maxWidth:u,children:(0,ml.jsx)(Le,{children:(0,ml.jsx)(be,{wrap:"wrap",children:r})})}),typeof r!="string"&&(0,ml.jsx)(yH,{diffContent:r.fileDiff,filename:r.fileName,availableTerminalHeight:l,terminalWidth:u})]})})]})},K$n=({status:t})=>(0,ml.jsxs)(Le,{minWidth:lfr,children:[t==="Pending"&&(0,ml.jsx)(be,{color:ke.AccentGreen,children:"o"}),t==="Executing"&&(0,ml.jsx)(Y2e,{spinnerType:"toggle",nonRespondingDisplay:"\u22B7"}),t==="Success"&&(0,ml.jsx)(be,{color:ke.AccentGreen,children:"\u2714"}),t==="Confirming"&&(0,ml.jsx)(be,{color:ke.AccentYellow,children:"?"}),t==="Canceled"&&(0,ml.jsx)(be,{color:ke.AccentYellow,bold:!0,children:"-"}),t==="Error"&&(0,ml.jsx)(be,{color:ke.AccentRed,bold:!0,children:"x"})]}),J$n=({name:t,description:e,status:r,emphasis:n})=>{let i=ofr.default.useMemo(()=>{switch(n){case"high":return ke.Foreground;case"medium":return ke.Foreground;case"low":return ke.Gray;default:return n}},[n]);return(0,ml.jsx)(Le,{children:(0,ml.jsxs)(be,{wrap:"truncate-end",strikethrough:r==="Canceled",children:[(0,ml.jsx)(be,{color:i,bold:!0,children:t})," ",(0,ml.jsx)(be,{color:ke.Gray,children:e})]})})},X$n=()=>(0,ml.jsxs)(be,{color:ke.Foreground,wrap:"truncate",children:[" ","\u2190"]});Hn();var Xl=Ve(Lt(),1);var cfr=({confirmationDetails:t,config:e,isFocused:r=!0,availableTerminalHeight:n,terminalWidth:i})=>{let{onConfirm:a}=t,s=i-2,o=async f=>{if(t.type==="edit"){let E=e?.getIdeClient();if(e?.getIdeMode()){let y=f===Br.Cancel?"rejected":"accepted";await E?.resolveDiffFromCli(t.filePath,y)}}a(f)};ts(f=>{r&&(f.name==="escape"||f.ctrl&&f.name==="c")&&o(Br.Cancel)},{isActive:r});let l=f=>o(f),u=null,c,d=new Array;function h(){if(d.length===0)throw new Error("Options not provided for confirmation message");if(n===void 0)return;let f=2,E=1,y=1,g=1,C=d.length,D=f+E+y+g+C;return Math.max(n-D,1)}if(t.type==="edit"){if(t.isModifying)return(0,Xl.jsxs)(Le,{minWidth:"90%",borderStyle:"round",borderColor:ke.Gray,justifyContent:"space-around",padding:1,overflow:"hidden",children:[(0,Xl.jsx)(be,{children:De.t("app.toolConfirmation.modifyInProgress")}),(0,Xl.jsx)(be,{color:ke.AccentGreen,children:De.t("app.toolConfirmation.saveAndCloseExternalEditor")})]});c=De.t("app.toolConfirmation.applyThisChange"),d.push({label:De.t("app.toolConfirmation.yesAllowOnce"),value:Br.ProceedOnce},{label:De.t("app.toolConfirmation.yesAllowAlways"),value:Br.ProceedAlways}),e?.getIdeMode()?d.push({label:De.t("app.toolConfirmation.noEsc"),value:Br.Cancel}):(d.push({label:De.t("app.toolConfirmation.modifyWithExternalEditor"),value:Br.ModifyWithEditor}),d.push({label:De.t("app.toolConfirmation.noSuggestChanges"),value:Br.Cancel})),u=(0,Xl.jsx)(yH,{diffContent:t.fileDiff,filename:t.fileName,availableTerminalHeight:h(),terminalWidth:s})}else if(t.type==="exec"){let f=t;c=De.t("app.toolConfirmation.allowExecutionOf",{command:f.rootCommand}),d.push({label:De.t("app.toolConfirmation.yesAllowOnce"),value:Br.ProceedOnce},{label:De.t("app.toolConfirmation.yesAllowAlways"),value:Br.ProceedAlways},{label:De.t("app.toolConfirmation.noSuggestChanges"),value:Br.Cancel});let E=h();E!==void 0&&(E-=2),u=(0,Xl.jsx)(Le,{flexDirection:"column",children:(0,Xl.jsx)(Le,{paddingX:1,marginLeft:1,children:(0,Xl.jsx)(d3,{maxHeight:E,maxWidth:Math.max(s-4,1),children:(0,Xl.jsx)(Le,{children:(0,Xl.jsx)(be,{color:ke.AccentCyan,children:f.command})})})})})}else if(t.type==="info"){let f=t,E=f.urls&&!(f.urls.length===1&&f.urls[0]===f.prompt);c=De.t("app.toolConfirmation.doYouWantToProceed"),d.push({label:De.t("app.toolConfirmation.yesAllowOnce"),value:Br.ProceedOnce},{label:De.t("app.toolConfirmation.yesAllowAlways"),value:Br.ProceedAlways},{label:De.t("app.toolConfirmation.noSuggestChanges"),value:Br.Cancel}),u=(0,Xl.jsxs)(Le,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,Xl.jsx)(be,{color:ke.AccentCyan,children:f.prompt}),E&&f.urls&&f.urls.length>0&&(0,Xl.jsxs)(Le,{flexDirection:"column",marginTop:1,children:[(0,Xl.jsxs)(be,{children:[De.t("app.toolConfirmation.urlsToFetch"),":"]}),f.urls.map(y=>(0,Xl.jsxs)(be,{children:[" - ",y]},y))]})]})}else{let f=t;u=(0,Xl.jsxs)(Le,{flexDirection:"column",paddingX:1,marginLeft:1,children:[(0,Xl.jsxs)(be,{color:ke.AccentCyan,children:["MCP Server: ",f.serverName]}),(0,Xl.jsxs)(be,{color:ke.AccentCyan,children:["Tool: ",f.toolName]})]}),c=De.t("app.toolConfirmation.allowExecutionOfMcpTool",{toolName:f.toolName,serverName:f.serverName}),d.push({label:De.t("app.toolConfirmation.yesAllowOnce"),value:Br.ProceedOnce},{label:De.t("app.toolConfirmation.yesAlwaysAllowToolFromServer",{toolName:f.toolName,serverName:f.serverName}),value:Br.ProceedAlwaysTool},{label:De.t("app.toolConfirmation.yesAlwaysAllowAllToolsFromServer",{serverName:f.serverName}),value:Br.ProceedAlwaysServer},{label:De.t("app.toolConfirmation.noSuggestChanges"),value:Br.Cancel})}return(0,Xl.jsxs)(Le,{flexDirection:"column",padding:1,width:s,children:[(0,Xl.jsx)(Le,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:u}),(0,Xl.jsx)(Le,{marginBottom:1,flexShrink:0,children:(0,Xl.jsx)(be,{wrap:"truncate",children:c})}),(0,Xl.jsx)(Le,{flexShrink:0,children:(0,Xl.jsx)(Kl,{items:d,onSelect:l,isFocused:r})})]})};var XR=Ve(Lt(),1);var pfr=({toolCalls:t,availableTerminalHeight:e,terminalWidth:r,config:n,isFocused:i=!0})=>{let a=!t.every(E=>E.status==="Success"),s=t.some(E=>E.name===TAe),o=a||s?ke.AccentYellow:ke.Gray,l=3,u=r-4,c=(0,dfr.useMemo)(()=>t.find(E=>E.status==="Confirming"),[t]),d=0;for(let E of t)E.resultDisplay!==void 0&&E.resultDisplay!==""&&d++;let h=t.length-d,f=e?Math.max(Math.floor((e-l-h)/Math.max(1,d)),1):void 0;return(0,XR.jsx)(Le,{flexDirection:"column",borderStyle:"round",width:"100%",marginLeft:1,borderDimColor:a,borderColor:o,children:t.map(E=>{let y=c?.callId===E.callId;return(0,XR.jsxs)(Le,{flexDirection:"column",minHeight:1,children:[(0,XR.jsx)(Le,{flexDirection:"row",alignItems:"center",children:(0,XR.jsx)(ufr,{callId:E.callId,name:E.name,description:E.description,resultDisplay:E.resultDisplay,status:E.status,confirmationDetails:E.confirmationDetails,availableTerminalHeight:f,terminalWidth:u,emphasis:y?"high":c?"low":"medium",renderOutputAsMarkdown:E.renderOutputAsMarkdown})}),E.status==="Confirming"&&y&&E.confirmationDetails&&(0,XR.jsx)(cfr,{confirmationDetails:E.confirmationDetails,config:n,isFocused:i,availableTerminalHeight:f,terminalWidth:u})]},E.callId)})})};var QYe=Ve(Lt(),1);var ffr=({text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})=>{let a="\u2726 ".length;return(0,QYe.jsx)(Le,{flexDirection:"column",paddingLeft:a,children:(0,QYe.jsx)(RH,{text:t,isPending:e,availableTerminalHeight:r,terminalWidth:n})})};var Mb=Ve(Lt(),1);var mfr=({compression:t})=>{let e=t.isPending?De.t("app.compression.compressing"):De.t("app.compression.compressed",{original:t.originalTokenCount??"unknown",new:t.newTokenCount??"unknown"});return(0,Mb.jsxs)(Le,{flexDirection:"row",children:[(0,Mb.jsx)(Le,{marginRight:1,children:t.isPending?(0,Mb.jsx)(pH,{type:"dots"}):(0,Mb.jsx)(be,{color:ke.AccentPurple,children:"\u2726"})}),(0,Mb.jsx)(Le,{children:(0,Mb.jsx)(be,{color:t.isPending?ke.AccentPurple:ke.AccentGreen,children:e})})]})};var ya=Ve(Lt(),1);var hfr=({cliVersion:t,osVersion:e,sandboxEnv:r,modelVersion:n,selectedAuthType:i,gcpProject:a})=>(0,ya.jsxs)(Le,{borderStyle:"round",borderColor:ke.Gray,flexDirection:"column",padding:1,marginY:1,width:"100%",children:[(0,ya.jsx)(Le,{marginBottom:1,children:(0,ya.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("app.about.title")})}),(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.cliVersion")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:t})})]}),rH&&!["N/A"].includes(rH)&&(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.gitCommit")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:rH})})]}),(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.model")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:n})})]}),(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.sandbox")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:r})})]}),(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.os")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:e})})]}),(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.authMethod")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:i.startsWith("oauth")?"OAuth":i})})]}),a&&(0,ya.jsxs)(Le,{flexDirection:"row",children:[(0,ya.jsx)(Le,{width:"35%",children:(0,ya.jsx)(be,{bold:!0,color:ke.LightBlue,children:De.t("app.about.gcpProject")})}),(0,ya.jsx)(Le,{children:(0,ya.jsx)(be,{children:a})})]})]});var Zge=95,e6e=85,t6e=75,r6e=45;var NH=(t,e,r={})=>t>=e.green?ke.AccentGreen:t>=e.yellow?ke.AccentYellow:r.defaultColor||ke.AccentRed;function Afr(t){return t.api.totalRequests===0?0:t.api.totalErrors/t.api.totalRequests*100}function gfr(t){return t.api.totalRequests===0?0:t.api.totalLatencyMs/t.api.totalRequests}function Efr(t){return t.tokens.prompt===0?0:t.tokens.cached/t.tokens.prompt*100}var yfr=t=>{let{models:e,tools:r}=t,n=Object.values(e).reduce((E,y)=>E+y.api.totalLatencyMs,0),i=r.totalDurationMs,a=n+i,s=a>0?n/a*100:0,o=a>0?i/a*100:0,l=Object.values(e).reduce((E,y)=>E+y.tokens.cached,0),u=Object.values(e).reduce((E,y)=>E+y.tokens.prompt,0),c=u>0?l/u*100:0,d=r.totalDecisions.accept+r.totalDecisions.reject+r.totalDecisions.modify,h=r.totalCalls>0?r.totalSuccess/r.totalCalls*100:0,f=d>0?r.totalDecisions.accept/d*100:0;return{totalApiTime:n,totalToolTime:i,agentActiveTime:a,apiTimePercent:s,toolTimePercent:o,cacheEfficiency:c,totalDecisions:d,successRate:h,agreementRate:f,totalCachedTokens:l,totalPromptTokens:u}};var nn=Ve(Lt(),1);var OH=({title:t,children:e})=>(0,nn.jsxs)(Le,{children:[(0,nn.jsx)(Le,{width:28,children:(0,nn.jsx)(be,{color:ke.LightBlue,children:t})}),e]}),vfr=({title:t,children:e})=>(0,nn.jsxs)(Le,{paddingLeft:2,children:[(0,nn.jsx)(Le,{width:26,children:(0,nn.jsxs)(be,{children:["\xBB ",t]})}),e]}),Cfr=({title:t,children:e})=>(0,nn.jsxs)(Le,{flexDirection:"column",width:"100%",marginBottom:1,children:[(0,nn.jsx)(be,{bold:!0,children:t}),e]}),Z$n=({models:t,totalCachedTokens:e,cacheEfficiency:r})=>(0,nn.jsxs)(Le,{flexDirection:"column",marginTop:1,children:[(0,nn.jsxs)(Le,{children:[(0,nn.jsx)(Le,{width:25,children:(0,nn.jsx)(be,{bold:!0,children:De.t("statsDisplay.modelUsage")})}),(0,nn.jsx)(Le,{width:8,justifyContent:"flex-end",children:(0,nn.jsx)(be,{bold:!0,children:De.t("statsDisplay.requests")})}),(0,nn.jsx)(Le,{width:18,justifyContent:"flex-end",children:(0,nn.jsx)(be,{bold:!0,children:De.t("statsDisplay.inputTokens")})}),(0,nn.jsx)(Le,{width:18,justifyContent:"flex-end",children:(0,nn.jsx)(be,{bold:!0,children:De.t("statsDisplay.outputTokens")})})]}),(0,nn.jsx)(Le,{borderStyle:"round",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:69}),Object.entries(t).map(([o,l])=>(0,nn.jsxs)(Le,{children:[(0,nn.jsx)(Le,{width:25,children:(0,nn.jsx)(be,{children:o.replace("-001","")})}),(0,nn.jsx)(Le,{width:8,justifyContent:"flex-end",children:(0,nn.jsx)(be,{children:l.api.totalRequests})}),(0,nn.jsx)(Le,{width:18,justifyContent:"flex-end",children:(0,nn.jsx)(be,{color:ke.AccentYellow,children:l.tokens.prompt.toLocaleString()})}),(0,nn.jsx)(Le,{width:18,justifyContent:"flex-end",children:(0,nn.jsx)(be,{color:ke.AccentYellow,children:l.tokens.candidates.toLocaleString()})})]},o)),r>0&&(0,nn.jsxs)(Le,{flexDirection:"column",marginTop:1,children:[(0,nn.jsxs)(be,{children:[(0,nn.jsx)(be,{color:ke.AccentGreen,children:De.t("statsDisplay.savingsHighlight")})," ",De.t("statsDisplay.savingsDetail",{tokens:e.toLocaleString(),percent:r.toFixed(1)})]}),(0,nn.jsx)(Le,{height:1}),(0,nn.jsxs)(be,{color:ke.Gray,children:["\xBB"," ",De.t("statsDisplay.tipFullStats",{command:"`/stats model`"})]})]})]}),n6e=({duration:t,title:e})=>{let{stats:r}=U6(),{metrics:n}=r,{models:i,tools:a}=n,s=yfr(n),o={green:Zge,yellow:e6e},l={green:t6e,yellow:r6e},u=NH(s.successRate,o),c=NH(s.agreementRate,l),d=()=>e?ke.GradientColors&&ke.GradientColors.length>0?(0,nn.jsx)(TR,{colors:ke.GradientColors,children:(0,nn.jsx)(be,{bold:!0,children:e})}):(0,nn.jsx)(be,{bold:!0,color:ke.AccentPurple,children:e}):(0,nn.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("statsDisplay.sessionStats")});return(0,nn.jsxs)(Le,{borderStyle:"round",borderColor:ke.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[d(),(0,nn.jsx)(Le,{height:1}),(0,nn.jsxs)(Cfr,{title:De.t("statsDisplay.interactionSummary"),children:[(0,nn.jsx)(OH,{title:De.t("statsDisplay.sessionId"),children:(0,nn.jsx)(be,{children:r.sessionId})}),(0,nn.jsx)(OH,{title:De.t("statsDisplay.toolCalls"),children:(0,nn.jsxs)(be,{children:[a.totalCalls," ("," ",(0,nn.jsxs)(be,{color:ke.AccentGreen,children:["\u2714 ",a.totalSuccess]})," ",(0,nn.jsxs)(be,{color:ke.AccentRed,children:["\u2716 ",a.totalFail]})," )"]})}),(0,nn.jsx)(OH,{title:De.t("statsDisplay.successRate"),children:(0,nn.jsxs)(be,{color:u,children:[s.successRate.toFixed(1),"%"]})}),s.totalDecisions>0&&(0,nn.jsx)(OH,{title:De.t("statsDisplay.userAgreement"),children:(0,nn.jsxs)(be,{color:c,children:[s.agreementRate.toFixed(1),"%"," ",(0,nn.jsx)(be,{color:ke.Gray,children:De.t("statsDisplay.userAgreementReviewed",{count:s.totalDecisions})})]})})]}),(0,nn.jsxs)(Cfr,{title:De.t("statsDisplay.performance"),children:[(0,nn.jsx)(OH,{title:De.t("statsDisplay.wallTime"),children:(0,nn.jsx)(be,{children:t})}),(0,nn.jsx)(OH,{title:De.t("statsDisplay.agentActive"),children:(0,nn.jsx)(be,{children:Jh(s.agentActiveTime)})}),(0,nn.jsx)(vfr,{title:De.t("statsDisplay.apiTime"),children:(0,nn.jsxs)(be,{children:[Jh(s.totalApiTime)," ",(0,nn.jsxs)(be,{color:ke.Gray,children:["(",s.apiTimePercent.toFixed(1),"%)"]})]})}),(0,nn.jsx)(vfr,{title:De.t("statsDisplay.toolTime"),children:(0,nn.jsxs)(be,{children:[Jh(s.totalToolTime)," ",(0,nn.jsxs)(be,{color:ke.Gray,children:["(",s.toolTimePercent.toFixed(1),"%)"]})]})})]}),Object.keys(i).length>0&&(0,nn.jsx)(Z$n,{models:i,totalCachedTokens:s.totalCachedTokens,cacheEfficiency:s.cacheEfficiency})]})};var Ps=Ve(Lt(),1);var _fr=28,Dfr=22,y3=({title:t,values:e,isSubtle:r=!1,isSection:n=!1})=>(0,Ps.jsxs)(Le,{children:[(0,Ps.jsx)(Le,{width:_fr,children:(0,Ps.jsx)(be,{bold:n,color:n?void 0:ke.LightBlue,children:r?` \u21B3 ${t}`:t})}),e.map((i,a)=>(0,Ps.jsx)(Le,{width:Dfr,children:(0,Ps.jsx)(be,{children:i})},a))]}),Sfr=()=>{let{stats:t}=U6(),{models:e}=t.metrics,r=Object.entries(e).filter(([,l])=>l.api.totalRequests>0);if(r.length===0)return(0,Ps.jsx)(Le,{borderStyle:"round",borderColor:ke.Gray,paddingY:1,paddingX:2,children:(0,Ps.jsx)(be,{children:De.t("app.stats.noApiCalls")})});let n=r.map(([l])=>l),i=l=>r.map(([,u])=>l(u)),a=r.some(([,l])=>l.tokens.thoughts>0),s=r.some(([,l])=>l.tokens.tool>0),o=r.some(([,l])=>l.tokens.cached>0);return(0,Ps.jsxs)(Le,{borderStyle:"round",borderColor:ke.Gray,flexDirection:"column",paddingY:1,paddingX:2,children:[(0,Ps.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("app.stats.modelStats")}),(0,Ps.jsx)(Le,{height:1}),(0,Ps.jsxs)(Le,{children:[(0,Ps.jsx)(Le,{width:_fr,children:(0,Ps.jsx)(be,{bold:!0,children:De.t("app.stats.metric")})}),n.map(l=>(0,Ps.jsx)(Le,{width:Dfr,children:(0,Ps.jsx)(be,{bold:!0,children:l})},l))]}),(0,Ps.jsx)(Le,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,Ps.jsx)(y3,{title:De.t("app.stats.api"),values:[],isSection:!0}),(0,Ps.jsx)(y3,{title:De.t("app.stats.requests"),values:i(l=>l.api.totalRequests.toLocaleString())}),(0,Ps.jsx)(y3,{title:De.t("app.stats.errors"),values:i(l=>{let u=Afr(l);return(0,Ps.jsxs)(be,{color:l.api.totalErrors>0?ke.AccentRed:ke.Foreground,children:[l.api.totalErrors.toLocaleString()," (",u.toFixed(1),"%)"]})})}),(0,Ps.jsx)(y3,{title:De.t("app.stats.avgLatency"),values:i(l=>{let u=gfr(l);return Jh(u)})}),(0,Ps.jsx)(Le,{height:1}),(0,Ps.jsx)(y3,{title:De.t("app.stats.tokens"),values:[],isSection:!0}),(0,Ps.jsx)(y3,{title:De.t("app.stats.total"),values:i(l=>(0,Ps.jsx)(be,{color:ke.AccentYellow,children:l.tokens.total.toLocaleString()}))}),(0,Ps.jsx)(y3,{title:De.t("app.stats.prompt"),isSubtle:!0,values:i(l=>l.tokens.prompt.toLocaleString())}),o&&(0,Ps.jsx)(y3,{title:De.t("app.stats.cached"),isSubtle:!0,values:i(l=>{let u=Efr(l);return(0,Ps.jsxs)(be,{color:ke.AccentGreen,children:[l.tokens.cached.toLocaleString()," (",u.toFixed(1),"%)"]})})}),a&&(0,Ps.jsx)(y3,{title:De.t("app.stats.thoughts"),isSubtle:!0,values:i(l=>l.tokens.thoughts.toLocaleString())}),s&&(0,Ps.jsx)(y3,{title:De.t("app.stats.tool"),isSubtle:!0,values:i(l=>l.tokens.tool.toLocaleString())}),(0,Ps.jsx)(y3,{title:De.t("app.stats.output"),isSubtle:!0,values:i(l=>l.tokens.candidates.toLocaleString())})]})};var Gn=Ve(Lt(),1);var ZR=25,eN=8,tN=15,rN=15,ejn=({name:t,stats:e})=>{let r=e.count>0?e.success/e.count*100:0,n=e.count>0?e.durationMs/e.count:0,i=NH(r,{green:Zge,yellow:e6e});return(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR,children:(0,Gn.jsx)(be,{color:ke.LightBlue,children:t})}),(0,Gn.jsx)(Le,{width:eN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{children:e.count})}),(0,Gn.jsx)(Le,{width:tN,justifyContent:"flex-end",children:(0,Gn.jsxs)(be,{color:i,children:[r.toFixed(1),"%"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{children:Jh(n)})})]})},bfr=()=>{let{stats:t}=U6(),{tools:e}=t.metrics,r=Object.entries(e.byName).filter(([,o])=>o.count>0);if(r.length===0)return(0,Gn.jsx)(Le,{borderStyle:"round",borderColor:ke.Gray,paddingY:1,paddingX:2,children:(0,Gn.jsx)(be,{children:De.t("app.stats.noToolCalls")})});let n=Object.values(e.byName).reduce((o,l)=>(o.accept+=l.decisions.accept,o.reject+=l.decisions.reject,o.modify+=l.decisions.modify,o),{accept:0,reject:0,modify:0}),i=n.accept+n.reject+n.modify,a=i>0?n.accept/i*100:0,s=NH(a,{green:t6e,yellow:r6e});return(0,Gn.jsxs)(Le,{borderStyle:"round",borderColor:ke.Gray,flexDirection:"column",paddingY:1,paddingX:2,width:70,children:[(0,Gn.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("app.stats.toolStats")}),(0,Gn.jsx)(Le,{height:1}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR,children:(0,Gn.jsx)(be,{bold:!0,children:De.t("app.stats.toolName")})}),(0,Gn.jsx)(Le,{width:eN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{bold:!0,children:De.t("app.stats.calls")})}),(0,Gn.jsx)(Le,{width:tN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{bold:!0,children:De.t("app.stats.successRate")})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{bold:!0,children:De.t("app.stats.avgDuration")})})]}),(0,Gn.jsx)(Le,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),r.map(([o,l])=>(0,Gn.jsx)(ejn,{name:o,stats:l},o)),(0,Gn.jsx)(Le,{height:1}),(0,Gn.jsx)(be,{bold:!0,children:De.t("app.stats.userDecisionSummary")}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR+eN+tN,children:(0,Gn.jsxs)(be,{color:ke.LightBlue,children:[De.t("app.stats.totalReviewed"),":"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{children:i})})]}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR+eN+tN,children:(0,Gn.jsxs)(be,{children:[" \xBB ",De.t("app.stats.accepted"),":"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{color:ke.AccentGreen,children:n.accept})})]}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR+eN+tN,children:(0,Gn.jsxs)(be,{children:[" \xBB ",De.t("app.stats.rejected"),":"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{color:ke.AccentRed,children:n.reject})})]}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR+eN+tN,children:(0,Gn.jsxs)(be,{children:[" \xBB ",De.t("app.stats.modified"),":"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{color:ke.AccentYellow,children:n.modify})})]}),(0,Gn.jsx)(Le,{borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,width:"100%"}),(0,Gn.jsxs)(Le,{children:[(0,Gn.jsx)(Le,{width:ZR+eN+tN,children:(0,Gn.jsxs)(be,{children:[" ",De.t("app.stats.overallAgreementRate"),":"]})}),(0,Gn.jsx)(Le,{width:rN,justifyContent:"flex-end",children:(0,Gn.jsx)(be,{bold:!0,color:i>0?s:void 0,children:i>0?`${a.toFixed(1)}%`:"--"})})]})]})};var Ifr=Ve(Lt(),1);var wfr=({duration:t})=>(0,Ifr.jsx)(n6e,{title:De.t("sessionSummary.poweringDown"),duration:t});var ca=Ve(Lt(),1);var Tfr=({commands:t})=>(0,ca.jsxs)(Le,{flexDirection:"column",marginBottom:1,borderColor:ke.Gray,borderStyle:"round",padding:1,children:[(0,ca.jsx)(be,{bold:!0,color:ke.Foreground,children:De.t("help.basics")}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("help.addContext")}),": ",De.t("help.addContextDescription",{at:"@",example:"@src/myFile.ts"})]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:De.t("help.shellMode")}),": ",De.t("help.shellModeDescription",{exclamation:"!",example:"!npm run start",naturalLanguage:De.t("help.shellModeNaturalLanguageExample")})]}),(0,ca.jsx)(Le,{height:1}),(0,ca.jsx)(be,{bold:!0,color:ke.Foreground,children:De.t("help.commands")}),t.filter(e=>e.description).map(e=>(0,ca.jsxs)(Le,{flexDirection:"column",children:[(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsxs)(be,{bold:!0,color:ke.AccentPurple,children:[" ","/",e.name]}),e.description&&" - "+(typeof e.description=="function"?e.description():e.description)]}),e.subCommands&&e.subCommands.map(r=>(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsxs)(be,{bold:!0,color:ke.AccentPurple,children:[" ",r.name]}),r.description&&" - "+(typeof r.description=="function"?r.description():r.description)]},r.name))]},e.name)),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsxs)(be,{bold:!0,color:ke.AccentPurple,children:[" ","!"," "]}),"- ",De.t("help.shellCommand")]}),(0,ca.jsx)(Le,{height:1}),(0,ca.jsx)(be,{bold:!0,color:ke.Foreground,children:De.t("help.shortcuts")}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Alt+Left/Right"})," ","- ",De.t("help.jumpWords")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Ctrl+C"})," ","- ",De.t("help.quitApp")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:process.platform==="win32"?"Ctrl+Enter":"Ctrl+J"})," ",process.platform==="linux"?"- "+De.t("help.newLineLinux"):"- "+De.t("help.newLine")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Ctrl+L"})," ","- ",De.t("help.clearScreen")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:process.platform==="darwin"?"Ctrl+X / Meta+Enter":"Ctrl+X"})," ","- ",De.t("help.openEditor")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Ctrl+Y"})," ","- ",De.t("help.toggleYolo")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Enter"})," ","- ",De.t("help.sendMessage")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Esc"})," ","- ",De.t("help.cancelOperation")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Shift+Tab"})," ","- ",De.t("help.autoAcceptEdits")]}),(0,ca.jsxs)(be,{color:ke.Foreground,children:[(0,ca.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Up/Down"})," ","- ",De.t("help.cycleHistory")]}),(0,ca.jsx)(Le,{height:1}),(0,ca.jsx)(be,{color:ke.Foreground,children:De.t("help.fullList",{file:"docs/keyboard-shortcuts.md"})})]});var Cf=Ve(Lt(),1);var i6e=({item:t,availableTerminalHeight:e,terminalWidth:r,isPending:n,config:i,commands:a,isFocused:s=!0})=>(0,Cf.jsxs)(Le,{flexDirection:"column",children:[t.type==="user"&&(0,Cf.jsx)(Y1r,{text:t.text}),t.type==="user_shell"&&(0,Cf.jsx)(W1r,{text:t.text}),t.type==="gemini"&&(0,Cf.jsx)(nfr,{text:t.text,isPending:n,availableTerminalHeight:e,terminalWidth:r}),t.type==="gemini_content"&&(0,Cf.jsx)(ffr,{text:t.text,isPending:n,availableTerminalHeight:e,terminalWidth:r}),t.type==="info"&&(0,Cf.jsx)(ifr,{text:t.text}),t.type==="error"&&(0,Cf.jsx)(afr,{text:t.text}),t.type==="about"&&(0,Cf.jsx)(hfr,{cliVersion:t.cliVersion,osVersion:t.osVersion,sandboxEnv:t.sandboxEnv,modelVersion:t.modelVersion,selectedAuthType:t.selectedAuthType,gcpProject:t.gcpProject}),t.type==="help"&&a&&(0,Cf.jsx)(Tfr,{commands:a}),t.type==="stats"&&(0,Cf.jsx)(n6e,{duration:t.duration}),t.type==="model_stats"&&(0,Cf.jsx)(Sfr,{}),t.type==="tool_stats"&&(0,Cf.jsx)(bfr,{}),t.type==="quit"&&(0,Cf.jsx)(wfr,{duration:t.duration}),t.type==="tool_group"&&(0,Cf.jsx)(pfr,{toolCalls:t.tools,groupId:t.id,availableTerminalHeight:e,terminalWidth:r,config:i,isFocused:s}),t.type==="compression"&&(0,Cf.jsx)(mfr,{compression:t.compression})]},t.id);var Lb=Ve(Lt(),1);var xfr=({geminiMdFileCount:t,contextFileNames:e,mcpServers:r,blockedMcpServers:n,showToolDescriptions:i,ideContext:a})=>{let{columns:s}=gg(),o=Sb(s),l=Object.keys(r||{}).length,u=n?.length||0,c=a?.workspaceState?.openFiles?.length??0;if(t===0&&l===0&&u===0&&c===0)return(0,Lb.jsx)(be,{children:" "});let d=(()=>{if(c===0)return"";let y=c===1?De.t("contextSummary.openFile"):De.t("contextSummary.openFiles");return`${c} ${y} (${De.t("contextSummary.viewOpenFiles")})`})(),h=(()=>{if(t===0)return"";let g=new Set(e).size<2?e[0]:"context",C=t===1?De.t("contextSummary.contextFile"):De.t("contextSummary.contextFiles");return`${t} ${g} ${C}`})(),f=(()=>{if(l===0&&u===0)return"";let y=[];if(l>0){let C=l===1?De.t("contextSummary.mcpServer"):De.t("contextSummary.mcpServers");y.push(`${l} ${C}`)}if(u>0){let C=`${u} ${De.t("contextSummary.blockedMcpServer")}`;if(l===0){let D=u===1?De.t("contextSummary.mcpServer"):De.t("contextSummary.mcpServers");C+=` ${D}`}y.push(C)}let g=y.join(", ");return r&&Object.keys(r).length>0&&(i?g+=` (${De.t("contextSummary.toggleMcp")})`:g+=` (${De.t("contextSummary.viewMcp")})`),g})(),E=[d,h,f].filter(Boolean);return o?(0,Lb.jsxs)(Le,{flexDirection:"column",children:[(0,Lb.jsx)(be,{color:ke.Gray,children:De.t("contextSummary.using")}),E.map((y,g)=>(0,Lb.jsxs)(be,{color:ke.Gray,children:[" ","- ",y]},g))]}):(0,Lb.jsx)(Le,{children:(0,Lb.jsxs)(be,{color:ke.Gray,children:[De.t("contextSummary.using")," ",E.join(" | ")]})})};var P5=Ve(lr(),1);function Bfr(){let[t,e]=(0,P5.useState)([]),r=(0,P5.useRef)(0),n=(0,P5.useCallback)(l=>(r.current+=1,l+r.current),[]),i=(0,P5.useCallback)(l=>{e(l)},[]),a=(0,P5.useCallback)((l,u)=>{let c=n(u),d={...l,id:c};return e(h=>{if(h.length>0){let f=h[h.length-1];if(f.type==="user"&&d.type==="user"&&f.text===d.text)return h}return[...h,d]}),c},[n]),s=(0,P5.useCallback)((l,u)=>{e(c=>c.map(d=>{if(d.id===l){let h=typeof u=="function"?u(d):u;return{...d,...h}}return d}))},[]),o=(0,P5.useCallback)(()=>{e([]),r.current=0},[]);return{history:t,addItem:a,updateItem:s,clearItems:o,loadHistory:i}}Hn();import VYe from"node:process";Hn();var Pb=Ve(Lt(),1);function Rfr({ide:t,onComplete:e}){ts(o=>{o.name==="escape"&&e({userSelection:"no",isExtensionPreInstalled:!1})},{isActive:!0});let{displayName:r}=pv(t),i=!!(process.env.KODA_CLI_IDE_SERVER_PORT??process.env.GEMINI_CLI_IDE_SERVER_PORT)&&!!process.env.GEMINI_CLI_IDE_WORKSPACE_PATH&&!!process.env.KODA_CLI_IDE_WORKSPACE_PATH,a=[{label:"Yes",value:{userSelection:"yes",isExtensionPreInstalled:i}},{label:"No (esc)",value:{userSelection:"no",isExtensionPreInstalled:i}},{label:"No, don't ask again",value:{userSelection:"dismiss",isExtensionPreInstalled:i}}],s=i?`If you select Yes, the CLI will have access to your open files and display diffs directly in ${r??"your editor"}.`:`If you select Yes, we'll install an extension that allows the CLI to access your open files and display diffs directly in ${r??"your editor"}.`;return(0,Pb.jsxs)(Le,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",padding:1,width:"100%",marginLeft:1,children:[(0,Pb.jsxs)(Le,{marginBottom:1,flexDirection:"column",children:[(0,Pb.jsxs)(be,{children:[(0,Pb.jsx)(be,{color:"yellow",children:"> "}),`Do you want to connect ${r??"your"} editor to Koda CLI?`]}),(0,Pb.jsx)(be,{dimColor:!0,children:s})]}),(0,Pb.jsx)(Kl,{items:a,onSelect:e})]})}var FH=Ve(lr(),1);import{exec as Nfr}from"node:child_process";import Ofr from"node:fs";import tjn from"node:fs/promises";import rjn from"path";function Ffr(t){let[e,r]=(0,FH.useState)(void 0),n=(0,FH.useCallback)(()=>Nfr("git rev-parse --abbrev-ref HEAD",{cwd:t},(i,a,s)=>{if(i){r(void 0);return}let o=a.toString().trim();o&&o!=="HEAD"?r(o):Nfr("git rev-parse --short HEAD",{cwd:t},(l,u,c)=>{if(l){r(void 0);return}r(u.toString().trim())})}),[t,r]);return(0,FH.useEffect)(()=>{n();let i=rjn.join(t,".git","logs","HEAD"),a;return(async()=>{try{await tjn.access(i,Ofr.constants.F_OK),a=Ofr.watch(i,o=>{(o==="change"||o==="rename")&&n()})}catch{}})(),()=>{a?.close()}},[t,n]),e}var Mfr=Ve(lr(),1);var njn="\x1B[?2004h",ijn="\x1B[?2004l",Lfr=()=>{let t=()=>{process.stdout.write(ijn)};(0,Mfr.useEffect)(()=>(process.stdout.write(njn),process.on("exit",t),process.on("SIGINT",t),process.on("SIGTERM",t),()=>{t(),process.removeListener("exit",t),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)}),[])};var v3=Ve(lr(),1);var kfr=Ve(Lt(),1);var Pfr=(0,v3.createContext)(void 0),Qfr=({children:t,settings:e})=>{let r=e.merged.vimMode??!1,[n,i]=(0,v3.useState)(r),[a,s]=(0,v3.useState)(r?"NORMAL":"INSERT");(0,v3.useEffect)(()=>{let u=e.merged.vimMode??!1;i(u),u&&s("NORMAL")},[e.merged.vimMode]);let o=(0,v3.useCallback)(async()=>{let u=!n;return i(u),u&&s("NORMAL"),await e.setValue("User","vimMode",u),u},[n,e]),l={vimEnabled:n,vimMode:a,toggleVimEnabled:o,setVimMode:s};return(0,kfr.jsx)(Pfr.Provider,{value:l,children:t})},MH=()=>{let t=(0,v3.useContext)(Pfr);if(t===void 0)throw new Error("useVimMode must be used within a VimModeProvider");return t};var T2=Ve(lr(),1);var ajn=10,sjn=1,ojn=/^[1-9]$/,Oa={DELETE_WORD_FORWARD:"dw",DELETE_WORD_BACKWARD:"db",DELETE_WORD_END:"de",CHANGE_WORD_FORWARD:"cw",CHANGE_WORD_BACKWARD:"cb",CHANGE_WORD_END:"ce",DELETE_CHAR:"x",DELETE_LINE:"dd",CHANGE_LINE:"cc",DELETE_TO_EOL:"D",CHANGE_TO_EOL:"C",CHANGE_MOVEMENT:{LEFT:"ch",DOWN:"cj",UP:"ck",RIGHT:"cl"}},Ufr=()=>({count:0,pendingOperator:null}),ljn={mode:"NORMAL",count:0,pendingOperator:null,lastCommand:null},ujn=(t,e)=>{switch(e.type){case"SET_MODE":return{...t,mode:e.mode};case"SET_COUNT":return{...t,count:e.count};case"INCREMENT_COUNT":return{...t,count:t.count*ajn+e.digit};case"CLEAR_COUNT":return{...t,count:0};case"SET_PENDING_OPERATOR":return{...t,pendingOperator:e.operator};case"SET_LAST_COMMAND":return{...t,lastCommand:e.command};case"CLEAR_PENDING_STATES":return{...t,...Ufr()};case"ESCAPE_TO_NORMAL":return{...t,...Ufr()};default:return t}};function Hfr(t,e){let{vimEnabled:r,vimMode:n,setVimMode:i}=MH(),[a,s]=(0,T2.useReducer)(ujn,ljn);(0,T2.useEffect)(()=>{s({type:"SET_MODE",mode:n})},[n]);let o=(0,T2.useCallback)(y=>{i(y),s({type:"SET_MODE",mode:y})},[i]),l=(0,T2.useCallback)(()=>a.count||sjn,[a.count]),u=(0,T2.useCallback)((y,g)=>{switch(y){case Oa.DELETE_WORD_FORWARD:{t.vimDeleteWordForward(g);break}case Oa.DELETE_WORD_BACKWARD:{t.vimDeleteWordBackward(g);break}case Oa.DELETE_WORD_END:{t.vimDeleteWordEnd(g);break}case Oa.CHANGE_WORD_FORWARD:{t.vimChangeWordForward(g),o("INSERT");break}case Oa.CHANGE_WORD_BACKWARD:{t.vimChangeWordBackward(g),o("INSERT");break}case Oa.CHANGE_WORD_END:{t.vimChangeWordEnd(g),o("INSERT");break}case Oa.DELETE_CHAR:{t.vimDeleteChar(g);break}case Oa.DELETE_LINE:{t.vimDeleteLine(g);break}case Oa.CHANGE_LINE:{t.vimChangeLine(g),o("INSERT");break}case Oa.CHANGE_MOVEMENT.LEFT:case Oa.CHANGE_MOVEMENT.DOWN:case Oa.CHANGE_MOVEMENT.UP:case Oa.CHANGE_MOVEMENT.RIGHT:{let D={[Oa.CHANGE_MOVEMENT.LEFT]:"h",[Oa.CHANGE_MOVEMENT.DOWN]:"j",[Oa.CHANGE_MOVEMENT.UP]:"k",[Oa.CHANGE_MOVEMENT.RIGHT]:"l"}[y];D&&(t.vimChangeMovement(D,g),o("INSERT"));break}case Oa.DELETE_TO_EOL:{t.vimDeleteToEndOfLine();break}case Oa.CHANGE_TO_EOL:{t.vimChangeToEndOfLine(),o("INSERT");break}default:return!1}return!0},[t,o]),c=(0,T2.useCallback)(y=>{if(y.name==="escape")return t.vimEscapeInsertMode(),s({type:"ESCAPE_TO_NORMAL"}),o("NORMAL"),!0;if(y.name==="tab"||y.name==="return"&&!y.ctrl||y.name==="up"||y.name==="down"||y.ctrl&&y.name==="r"||y.ctrl&&y.name==="v"||y.sequence==="!"&&t.text.length===0)return!1;if(y.name==="return"&&!y.ctrl&&!y.meta){if(t.text.trim()&&e){let g=t.text;return t.setText(""),e(g),!0}return!0}return t.handleInput(y),!0},[t,s,o,e]),d=(0,T2.useCallback)(y=>({name:y.name||"",sequence:y.sequence||"",ctrl:y.ctrl||!1,meta:y.meta||!1,shift:y.shift||!1,paste:y.paste||!1}),[]),h=(0,T2.useCallback)(y=>{let g=l();s({type:"CLEAR_COUNT"}),t.vimChangeMovement(y,g),o("INSERT");let C={h:Oa.CHANGE_MOVEMENT.LEFT,j:Oa.CHANGE_MOVEMENT.DOWN,k:Oa.CHANGE_MOVEMENT.UP,l:Oa.CHANGE_MOVEMENT.RIGHT};return s({type:"SET_LAST_COMMAND",command:{type:C[y],count:g}}),s({type:"SET_PENDING_OPERATOR",operator:null}),!0},[l,s,t,o]),f=(0,T2.useCallback)((y,g)=>{let C=l(),S={d:{w:Oa.DELETE_WORD_FORWARD,b:Oa.DELETE_WORD_BACKWARD,e:Oa.DELETE_WORD_END},c:{w:Oa.CHANGE_WORD_FORWARD,b:Oa.CHANGE_WORD_BACKWARD,e:Oa.CHANGE_WORD_END}}[y][g];return u(S,C),s({type:"SET_LAST_COMMAND",command:{type:S,count:C}}),s({type:"CLEAR_COUNT"}),s({type:"SET_PENDING_OPERATOR",operator:null}),!0},[l,u,s]),E=(0,T2.useCallback)(y=>{if(!r)return!1;let g;try{g=d(y)}catch(C){return console.warn("Malformed key input in vim mode:",y,C),!1}if(a.mode==="INSERT")return c(g);if(a.mode==="NORMAL"){if(g.name==="escape")return a.pendingOperator?(s({type:"CLEAR_PENDING_STATES"}),!0):!1;if(ojn.test(g.sequence)||g.sequence==="0"&&a.count>0)return s({type:"INCREMENT_COUNT",digit:parseInt(g.sequence,10)}),!0;let C=l();switch(g.sequence){case"h":return a.pendingOperator==="c"?h("h"):(t.vimMoveLeft(C),s({type:"CLEAR_COUNT"}),!0);case"j":return a.pendingOperator==="c"?h("j"):(t.vimMoveDown(C),s({type:"CLEAR_COUNT"}),!0);case"k":return a.pendingOperator==="c"?h("k"):(t.vimMoveUp(C),s({type:"CLEAR_COUNT"}),!0);case"l":return a.pendingOperator==="c"?h("l"):(t.vimMoveRight(C),s({type:"CLEAR_COUNT"}),!0);case"w":return a.pendingOperator==="d"?f("d","w"):a.pendingOperator==="c"?f("c","w"):(t.vimMoveWordForward(C),s({type:"CLEAR_COUNT"}),!0);case"b":return a.pendingOperator==="d"?f("d","b"):a.pendingOperator==="c"?f("c","b"):(t.vimMoveWordBackward(C),s({type:"CLEAR_COUNT"}),!0);case"e":return a.pendingOperator==="d"?f("d","e"):a.pendingOperator==="c"?f("c","e"):(t.vimMoveWordEnd(C),s({type:"CLEAR_COUNT"}),!0);case"x":return t.vimDeleteChar(C),s({type:"SET_LAST_COMMAND",command:{type:Oa.DELETE_CHAR,count:C}}),s({type:"CLEAR_COUNT"}),!0;case"i":return t.vimInsertAtCursor(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"a":return t.vimAppendAtCursor(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"o":return t.vimOpenLineBelow(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"O":return t.vimOpenLineAbove(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"0":return t.vimMoveToLineStart(),s({type:"CLEAR_COUNT"}),!0;case"$":return t.vimMoveToLineEnd(),s({type:"CLEAR_COUNT"}),!0;case"^":return t.vimMoveToFirstNonWhitespace(),s({type:"CLEAR_COUNT"}),!0;case"g":return a.pendingOperator==="g"?(t.vimMoveToFirstLine(),s({type:"SET_PENDING_OPERATOR",operator:null})):s({type:"SET_PENDING_OPERATOR",operator:"g"}),s({type:"CLEAR_COUNT"}),!0;case"G":return a.count>0?t.vimMoveToLine(a.count):t.vimMoveToLastLine(),s({type:"CLEAR_COUNT"}),!0;case"I":return t.vimInsertAtLineStart(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"A":return t.vimAppendAtLineEnd(),o("INSERT"),s({type:"CLEAR_COUNT"}),!0;case"d":{if(a.pendingOperator==="d"){let D=l();u(Oa.DELETE_LINE,D),s({type:"SET_LAST_COMMAND",command:{type:Oa.DELETE_LINE,count:D}}),s({type:"CLEAR_COUNT"}),s({type:"SET_PENDING_OPERATOR",operator:null})}else s({type:"SET_PENDING_OPERATOR",operator:"d"});return!0}case"c":{if(a.pendingOperator==="c"){let D=l();u(Oa.CHANGE_LINE,D),s({type:"SET_LAST_COMMAND",command:{type:Oa.CHANGE_LINE,count:D}}),s({type:"CLEAR_COUNT"}),s({type:"SET_PENDING_OPERATOR",operator:null})}else s({type:"SET_PENDING_OPERATOR",operator:"c"});return!0}case"D":return u(Oa.DELETE_TO_EOL,1),s({type:"SET_LAST_COMMAND",command:{type:Oa.DELETE_TO_EOL,count:1}}),s({type:"CLEAR_COUNT"}),!0;case"C":return u(Oa.CHANGE_TO_EOL,1),s({type:"SET_LAST_COMMAND",command:{type:Oa.CHANGE_TO_EOL,count:1}}),s({type:"CLEAR_COUNT"}),!0;case".":{if(a.lastCommand){let D=a.lastCommand;u(D.type,D.count)}return s({type:"CLEAR_COUNT"}),!0}default:return g.name==="left"?a.pendingOperator==="c"?h("h"):(t.vimMoveLeft(C),s({type:"CLEAR_COUNT"}),!0):g.name==="down"?a.pendingOperator==="c"?h("j"):(t.vimMoveDown(C),s({type:"CLEAR_COUNT"}),!0):g.name==="up"?a.pendingOperator==="c"?h("k"):(t.vimMoveUp(C),s({type:"CLEAR_COUNT"}),!0):g.name==="right"?a.pendingOperator==="c"?h("l"):(t.vimMoveRight(C),s({type:"CLEAR_COUNT"}),!0):(s({type:"CLEAR_PENDING_STATES"}),!0)}}return!1},[r,d,c,a.mode,a.count,a.pendingOperator,a.lastCommand,s,l,h,f,t,u,o]);return{mode:a.mode,vimModeEnabled:r,handleInput:E}}import*as u6e from"fs";var kYe=Ve(Lt(),1);var Gfr=({message:t})=>(0,kYe.jsx)(Le,{borderStyle:"round",borderColor:ke.AccentYellow,paddingX:1,marginY:1,children:(0,kYe.jsx)(be,{color:ke.AccentYellow,children:t})});Hn();var UYe=Ve(Lt(),1);var a6e=({constrainHeight:t})=>{let e=cdr(),r=cH();return e===void 0||e.overflowingIds.size===0||!t||!(r==="idle"||r==="waiting_for_confirmation")?null:(0,UYe.jsx)(Le,{children:(0,UYe.jsx)(be,{color:ke.Gray,wrap:"truncate",children:"Press ctrl-s to show more lines"})})};Hn();var LH=Ve(lr(),1);Hn();var qfr=t=>{let[e,r]=(0,LH.useState)({isLoading:!0});(0,LH.useEffect)(()=>{(async()=>{r({isLoading:!0});try{let a=Vfr(t);if(await cjn(a)!==zh.FREE){r({isLoading:!1,isFreeTier:!1});return}let o=await djn(a);r({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:o})}catch(a){r({isLoading:!1,error:a instanceof Error?a.message:String(a)})}})()},[t]);let n=(0,LH.useCallback)(async i=>{try{let a=Vfr(t),s=await pjn(a,i);r({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:s})}catch(a){r({isLoading:!1,error:a instanceof Error?a.message:String(a)})}},[t]);return{privacyState:e,updateDataCollectionOptIn:n}};function Vfr(t){let e=t.getGeminiClient().getContentGenerator();if(e instanceof M7){if(!e.projectId)throw new Error("Oauth not being used")}else throw new Error("Oauth not being used");return e}async function cjn(t){let e=await t.loadCodeAssist({cloudaicompanionProject:t.projectId,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:t.projectId}});if(!e.currentTier)throw new Error("User does not have a current tier");return e.currentTier.id}async function djn(t){try{return(await t.getCodeAssistGlobalUserSetting()).freeTierDataCollectionOptin}catch(e){if(e&&typeof e=="object"&&"response"in e&&e.response?.status===404)return!0;throw e}}async function pjn(t,e){return(await t.setCodeAssistGlobalUserSetting({cloudaicompanionProject:t.projectId,freeTierDataCollectionOptin:e})).freeTierDataCollectionOptin}var Rm=Ve(Lt(),1);var $fr=({onExit:t})=>(ts(e=>{e.name==="escape"&&t()},{isActive:!0}),(0,Rm.jsxs)(Le,{flexDirection:"column",marginBottom:1,children:[(0,Rm.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Vertex AI Notice"}),(0,Rm.jsx)(TA,{}),(0,Rm.jsxs)(be,{children:["Service Specific Terms",(0,Rm.jsx)(be,{color:ke.AccentBlue,children:"[1]"})," are incorporated into the agreement under which Google has agreed to provide Google Cloud Platform",(0,Rm.jsx)(be,{color:ke.AccentGreen,children:"[2]"})," to Customer (the \u201CAgreement\u201D). If the Agreement authorizes the resale or supply of Google Cloud Platform under a Google Cloud partner or reseller program, then except for in the section entitled \u201CPartner-Specific Terms\u201D, all references to Customer in the Service Specific Terms mean Partner or Reseller (as applicable), and all references to Customer Data in the Service Specific Terms mean Partner Data. Capitalized terms used but not defined in the Service Specific Terms have the meaning given to them in the Agreement."]}),(0,Rm.jsx)(TA,{}),(0,Rm.jsxs)(be,{children:[(0,Rm.jsx)(be,{color:ke.AccentBlue,children:"[1]"})," ","https://cloud.google.com/terms/service-terms"]}),(0,Rm.jsxs)(be,{children:[(0,Rm.jsx)(be,{color:ke.AccentGreen,children:"[2]"})," ","https://cloud.google.com/terms/services"]}),(0,Rm.jsx)(TA,{}),(0,Rm.jsx)(be,{color:ke.Gray,children:"Press Esc to exit."})]}));var Zl=Ve(Lt(),1);var jfr=({config:t,onExit:e})=>{let{privacyState:r,updateDataCollectionOptIn:n}=qfr(t);if(ts(a=>{r.error&&a.name==="escape"&&e()},{isActive:!0}),r.isLoading)return(0,Zl.jsx)(be,{color:ke.Gray,children:"Loading..."});if(r.error)return(0,Zl.jsxs)(Le,{flexDirection:"column",marginY:1,children:[(0,Zl.jsxs)(be,{color:ke.AccentRed,children:["Error loading Opt-in settings: ",r.error]}),(0,Zl.jsx)(be,{color:ke.Gray,children:"Press Esc to exit."})]});if(r.isFreeTier===!1)return(0,Zl.jsx)($fr,{onExit:e});let i=[{label:"Yes",value:!0},{label:"No",value:!1}];return(0,Zl.jsxs)(Le,{flexDirection:"column",marginY:1,children:[(0,Zl.jsx)(be,{bold:!0,color:ke.AccentPurple,children:"Gemini Code Assist for Individuals Privacy Notice"}),(0,Zl.jsx)(TA,{}),(0,Zl.jsxs)(be,{children:["This notice and our Privacy Policy",(0,Zl.jsx)(be,{color:ke.AccentBlue,children:"[1]"})," describe how Gemini Code Assist handles your data. Please read them carefully."]}),(0,Zl.jsx)(TA,{}),(0,Zl.jsx)(be,{children:"When you use Gemini Code Assist for individuals with Gemini CLI, Google collects your prompts, related code, generated output, code edits, related feature usage information, and your feedback to provide, improve, and develop Google products and services and machine learning technologies."}),(0,Zl.jsx)(TA,{}),(0,Zl.jsx)(be,{children:"To help with quality and improve our products (such as generative machine-learning models), human reviewers may read, annotate, and process the data collected above. We take steps to protect your privacy as part of this process. This includes disconnecting the data from your Google Account before reviewers see or annotate it, and storing those disconnected copies for up to 18 months. Please don't submit confidential information or any data you wouldn't want a reviewer to see or Google to use to improve our products, services and machine-learning technologies."}),(0,Zl.jsx)(TA,{}),(0,Zl.jsxs)(Le,{flexDirection:"column",children:[(0,Zl.jsx)(be,{children:"Allow Google to use this data to develop and improve our products?"}),(0,Zl.jsx)(Kl,{items:i,initialIndex:r.dataCollectionOptIn?0:1,onSelect:a=>{n(a),r.error||e()}})]}),(0,Zl.jsx)(TA,{}),(0,Zl.jsxs)(be,{children:[(0,Zl.jsx)(be,{color:ke.AccentBlue,children:"[1]"})," ","https://policies.google.com/privacy"]}),(0,Zl.jsx)(TA,{}),(0,Zl.jsx)(be,{color:ke.Gray,children:"Press Enter to choose an option and exit."})]})};var s6e=Ve(Lt(),1);var fjn=({config:t,onExit:e})=>{switch(t.getContentGeneratorConfig()?.authType){case ln.LOGIN_WITH_GITHUB:return(0,s6e.jsx)(jfr,{config:t,onExit:e});case ln.WITHOUT_AUTH:default:return null}},Yfr=({onExit:t,config:e})=>(0,s6e.jsx)(Le,{borderStyle:"round",padding:1,flexDirection:"column",children:(0,s6e.jsx)(fjn,{config:e,onExit:t})});var kX=Ve(lr(),1);function Wfr(){let[t,e]=(0,kX.useState)(!1),r=(0,kX.useCallback)(()=>{e(!0)},[]),n=(0,kX.useCallback)(()=>{e(!1)},[]);return{isSettingsDialogOpen:t,openSettingsDialog:r,closeSettingsDialog:n}}var b0=Ve(lr(),1);var HYe=Ve(lr(),1);var Wd=Ve(Lt(),1);function zfr({settings:t,selectedScope:e,onSave:r,isActive:n=!1,onToggle:i}){let a=t.forScope(e).settings.language||"ru",[s,o]=(0,HYe.useState)(!1),[l,u]=(0,HYe.useState)(a||"ru");tV((y,g)=>{s?y==="1"?d("en"):y==="2"?d("ru"):g.escape&&o(!1):n&&(g.return||y===" ")&&c()});let c=()=>{i&&i(),o(!0)},d=y=>{u(y),t.setValue(e,"language",y),De.setLanguage(y),o(!1),r()},h=vH("language"),f=t.forScope(e).settings.language||"ru",E=f==="en"?"English":f==="ru"?"Russian":f;return s?(0,Wd.jsxs)(Le,{flexDirection:"column",children:[(0,Wd.jsx)(be,{bold:!0,color:ke.Foreground,children:De.t("languageSetting.selectLanguage")}),(0,Wd.jsxs)(Le,{flexDirection:"row",alignItems:"center",children:[(0,Wd.jsx)(Le,{minWidth:2,flexShrink:0,children:(0,Wd.jsx)(be,{color:l==="en"?ke.AccentGreen:ke.Gray,children:l==="en"?"\u25CF":"\u25CB"})}),(0,Wd.jsxs)(be,{color:l==="en"?ke.AccentGreen:ke.Foreground,children:[De.t("languageSetting.english")," (",De.t("languageSetting.pressToSelect",{key:"1"}),")"]})]}),(0,Wd.jsxs)(Le,{flexDirection:"row",alignItems:"center",children:[(0,Wd.jsx)(Le,{minWidth:2,flexShrink:0,children:(0,Wd.jsx)(be,{color:l==="ru"?ke.AccentGreen:ke.Gray,children:l==="ru"?"\u25CF":"\u25CB"})}),(0,Wd.jsxs)(be,{color:l==="ru"?ke.AccentGreen:ke.Foreground,children:[De.t("languageSetting.russian")," (",De.t("languageSetting.pressToSelect",{key:"2"}),")"]})]}),(0,Wd.jsx)(be,{color:ke.Gray,children:De.t("languageSetting.pressEscToCancel")})]}):(0,Wd.jsxs)(Le,{flexDirection:"row",alignItems:"center",children:[(0,Wd.jsx)(Le,{minWidth:2,flexShrink:0,children:(0,Wd.jsx)(be,{color:n?ke.AccentGreen:ke.Gray,children:n?"\u25CF":""})}),(0,Wd.jsx)(Le,{minWidth:50,children:(0,Wd.jsxs)(be,{color:n?ke.AccentGreen:ke.Foreground,children:[h?.labelKey?De.t(h.labelKey):De.t(h?.label||"Language")," ","(",De.t("languageSetting.pressEnterToChange"),")"]})}),(0,Wd.jsx)(Le,{minWidth:3}),(0,Wd.jsxs)(be,{color:ke.Foreground,children:[E," \u25BC"]})]})}var Jo=Ve(Lt(),1);var o6e=8;function Kfr({settings:t,onSelect:e,onRestartRequest:r}){let{vimEnabled:n,toggleVimEnabled:i}=MH(),[a,s]=(0,b0.useState)("settings"),[o,l]=(0,b0.useState)("User"),[u,c]=(0,b0.useState)(0),[d,h]=(0,b0.useState)(0),[f,E]=(0,b0.useState)(!1),[y,g]=(0,b0.useState)(()=>structuredClone(t.forScope(o).settings)),[C,D]=(0,b0.useState)(new Set),[S,w]=(0,b0.useState)(new Map),[N,M]=(0,b0.useState)(new Set);(0,b0.useEffect)(()=>{g(structuredClone(t.forScope(o).settings)),N.size===0&&E(!1)},[o,t,N]),(0,b0.useEffect)(()=>{C.size>0&&g(Q=>{let J={...Q};return C.forEach(ae=>{let fe=S.get(ae);fe!==void 0&&(J=xb(ae,fe,J))}),J})},[o,C,S,t]);let k=Edr().map(J=>{let ae=vge(J,y,{}),fe=vH(J);return{label:fe?.labelKey?De.t(fe.labelKey):De.t(fe?.label||J),value:J,checked:ae,toggle:()=>{let K=!ae;if(g(ne=>xb(J,K,ne)),_X(J))w(ne=>{let he=new Map(ne);return he.set(J,K),he}),D(ne=>{let he=new Set(ne).add(J),Ee=Dje(he);return console.log("[DEBUG SettingsDialog] Modified settings:",Array.from(he),"Needs restart:",Ee),Ee&&(E(!0),M(pe=>new Set(pe).add(J))),he});else{let ne=new Set([J]),he=xb(J,K,{});console.log(`[DEBUG SettingsDialog] Saving ${J} immediately with value:`,K),_ge(ne,he,t,o),J==="vimMode"&&K!==n&&i().catch(pe=>{console.error("Failed to toggle vim mode:",pe)});let Ee=new Set(C);D(pe=>{let _e=new Set(pe);return _e.delete(J),_e}),w(pe=>{let _e=new Map(pe);return _e.delete(J),_e}),M(pe=>{let _e=new Set(pe);return _e.delete(J),_e}),g(pe=>{let _e=structuredClone(t.forScope(o).settings);return Ee.forEach(Se=>{if(Se!==J){let se=S.get(Se);se!==void 0&&(_e=xb(Se,se,_e))}}),_e})}}}}),B=CH(),q=Q=>{l(Q)},W=Q=>{q(Q),s("settings")},re=k.slice(d,d+o6e),$=!0,R=!0;return ts(Q=>{let{name:J,ctrl:ae}=Q;if(J==="tab"&&s(fe=>fe==="settings"?"scope":"settings"),a==="settings"){if(J==="up"||J==="k"){let fe=u>0?u-1:k.length-1;c(fe),fe===k.length-1?h(Math.max(0,k.length-o6e)):fe<d&&h(fe)}else if(J==="down"||J==="j"){let fe=u<k.length-1?u+1:0;c(fe),fe===0?h(0):fe>=d+o6e&&h(fe-o6e+1)}else if(J==="return"||J==="space")k[u]?.toggle();else if(ae&&(J==="c"||J==="l")){let fe=k[u];if(fe){let K=vX(fe.value),ne=typeof K=="boolean"?K:!1;if(g(he=>xb(fe.value,ne,he)),D(he=>{let Ee=new Set(he);return Ee.delete(fe.value),Ee}),M(he=>{let Ee=new Set(he);return Ee.delete(fe.value),Ee}),!_X(fe.value)){let he=new Set([fe.value]),Ee=xb(fe.value,ne,{});_ge(he,Ee,t,o)}}}}if(f&&J==="r"){let fe=vdr(C),K=new Set(fe);K.size>0&&_ge(K,y,t,o),E(!1),M(new Set),r&&r()}J==="escape"&&e(void 0,o)},{isActive:!0}),(0,Jo.jsx)(Le,{borderStyle:"round",borderColor:ke.Gray,flexDirection:"row",padding:1,width:"100%",height:"100%",children:(0,Jo.jsxs)(Le,{flexDirection:"column",flexGrow:1,children:[(0,Jo.jsx)(be,{bold:!0,color:ke.AccentBlue,children:De.t("app.settings.title")}),(0,Jo.jsx)(Le,{height:1}),$&&(0,Jo.jsx)(be,{color:ke.Gray,children:"\u25B2"}),re.map((Q,J)=>{let ae=a==="settings"&&u===J+d,fe=t.forScope(o).settings,K=t.merged,ne=Cdr(Q.value,fe,K,C,y),he=_dr(Q.value,fe),Ee=Dge(Q.value,o,t);return Q.value==="language"?(0,Jo.jsxs)(b0.default.Fragment,{children:[(0,Jo.jsx)(zfr,{settings:t,selectedScope:o,isActive:ae,onToggle:Q.toggle,onSave:()=>{D(pe=>{let _e=new Set(pe).add("language");return Dje(_e)&&(E(!0),M(se=>new Set(se).add("language"))),_e})}}),(0,Jo.jsx)(Le,{height:1})]},Q.value):(0,Jo.jsxs)(b0.default.Fragment,{children:[(0,Jo.jsxs)(Le,{flexDirection:"row",alignItems:"center",children:[(0,Jo.jsx)(Le,{minWidth:2,flexShrink:0,children:(0,Jo.jsx)(be,{color:ae?ke.AccentGreen:ke.Gray,children:ae?"\u25CF":""})}),(0,Jo.jsx)(Le,{minWidth:50,children:(0,Jo.jsxs)(be,{color:ae?ke.AccentGreen:ke.Foreground,children:[Q.label,Ee&&(0,Jo.jsxs)(be,{color:ke.Gray,children:[" ",Ee]})]})}),(0,Jo.jsx)(Le,{minWidth:3}),(0,Jo.jsx)(be,{color:ae?ke.AccentGreen:he?ke.Gray:ke.Foreground,children:ne})]}),(0,Jo.jsx)(Le,{height:1})]},Q.value)}),R&&(0,Jo.jsx)(be,{color:ke.Gray,children:"\u25BC"}),(0,Jo.jsx)(Le,{height:1}),(0,Jo.jsxs)(Le,{marginTop:1,flexDirection:"column",children:[(0,Jo.jsxs)(be,{bold:a==="scope",wrap:"truncate",children:[a==="scope"?"> ":" ",De.t("app.settings.applyTo")]}),(0,Jo.jsx)(Kl,{items:B,initialIndex:0,onSelect:W,onHighlight:q,isFocused:a==="scope",showNumbers:a==="scope"})]}),(0,Jo.jsx)(Le,{height:1}),(0,Jo.jsx)(be,{color:ke.Gray,children:De.t("app.settings.enterSelectTabFocus")}),f&&(0,Jo.jsx)(be,{color:ke.AccentYellow,children:De.t("app.settings.restartRequired")})]})})}Hn();import*as PH from"fs";import*as l6e from"path";function Jfr(t,e){let r=process.argv[1];if(!r)return{packageManager:"unknown",isGlobal:!1};try{let n=PH.realpathSync(r).replace(/\\/g,"/"),i=t?.replace(/\\/g,"/");if(Mh(process.cwd())&&i&&n.startsWith(i)&&!n.includes("/node_modules/"))return{packageManager:"unknown",isGlobal:!1,updateMessage:De.t("installationInfo.gitClone")};if(n.includes("/.npm/_npx")||n.includes("/npm/_npx"))return{packageManager:"npx",isGlobal:!1,updateMessage:De.t("installationInfo.npx")};if(n.includes("/.pnpm/_pnpx"))return{packageManager:"pnpx",isGlobal:!1,updateMessage:De.t("installationInfo.pnpx")};if(i&&n.startsWith(`${i}/node_modules`)){let o="npm";return PH.existsSync(l6e.join(t,"yarn.lock"))?o="yarn":PH.existsSync(l6e.join(t,"pnpm-lock.yaml"))?o="pnpm":PH.existsSync(l6e.join(t,"bun.lockb"))&&(o="bun"),{packageManager:o,isGlobal:!1,updateMessage:De.t("installationInfo.local")}}let s="npm install -g @kodadev/koda-cli@latest";return{packageManager:"npm",isGlobal:!0,updateCommand:s,updateMessage:e?De.t("installationInfo.manualUpdate",{command:s}):De.t("installationInfo.autoUpdate",{packageManager:"npm"})}}catch(n){return console.log(n),{packageManager:"unknown",isGlobal:!1}}}import{EventEmitter as mjn}from"events";var x2=new mjn;import{spawn as hjn}from"child_process";var Xfr=hjn;function Zfr(t,e,r,n=Xfr){if(!t||e.merged.disableUpdateNag)return;let i=Jfr(r,e.merged.disableAutoUpdate??!1),a=t.message;if(i.updateMessage&&(a+=`
2036
- ${i.updateMessage}`),x2.emit("update-received",{message:a}),!i.updateCommand||e.merged.disableAutoUpdate)return;let s=t.update.latest.includes("nightly"),o=i.updateCommand.replace("@latest",s?"@nightly":`@${t.update.latest}`),l=n(o,{stdio:"pipe",shell:!0}),u="";return l.stderr.on("data",c=>{u+=c.toString()}),l.on("close",c=>{c===0?x2.emit("update-success",{message:De.t("autoUpdate.success")}):x2.emit("update-failed",{message:De.t("autoUpdate.failedWithCommand",{command:o,stderr:u.trim()})})}),l.on("error",c=>{x2.emit("update-failed",{message:De.t("autoUpdate.failedWithError",{error:c.message})})}),l}function e0r(t,e){let r=!1,n=o=>{e(o);let l=o.message;setTimeout(()=>{r||t({type:"info",text:l},Date.now()),e(null)},6e4)},i=()=>{e(null),t({type:"error",text:De.t("autoUpdate.failedShort")},Date.now())},a=()=>{r=!0,e(null),t({type:"info",text:De.t("autoUpdate.success")},Date.now())},s=o=>{t({type:"info",text:o.message},Date.now())};return x2.on("update-received",n),x2.on("update-failed",i),x2.on("update-success",a),x2.on("update-info",s),()=>{x2.off("update-received",n),x2.off("update-failed",i),x2.off("update-success",a),x2.off("update-info",s)}}import{EventEmitter as Ajn}from"events";var Qb=new Ajn;import gjn from"node:os";import t0r from"node:path";import{promises as Ejn}from"node:fs";async function yjn(){try{let t=process.env.XDG_CONFIG_HOME||t0r.join(gjn.homedir(),".config"),e=t0r.join(t,"koda","credentials.json"),r=await Ejn.readFile(e,"utf-8"),n=JSON.parse(r);return(typeof n.githubToken=="string"?n.githubToken:"")||null}catch{return null}}function vjn(){return`${process.env.KODA_API_BASE||"https://api.kodacode.ru/dev/"}/ftc`}async function GYe(){let t=process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN||null;if(t||(t=await yjn()),!t)return null;let e=vjn(),r={Accept:"application/json","Accept-Encoding":"identity","Content-Type":"application/json",Authorization:`Bearer ${t}`};try{let n=await fetch(e,{method:"POST",headers:r,body:JSON.stringify({ghAuthToken:t})});if(!n.ok)return null;let i=await n.json(),a=Number(i.count??0),s=Number(i.limit??0);if(!Number.isFinite(a)||!Number.isFinite(s))return null;let o=Math.max(0,a);return{count:o,limit:s,remaining:s-o}}catch{return null}}var _r=Ve(Lt(),1);var _jn=1e3,r0r=t=>(0,_r.jsx)(_nr,{children:(0,_r.jsx)(Qfr,{settings:t.settings,children:(0,_r.jsx)(Djn,{...t})})}),Djn=({config:t,settings:e,startupWarnings:r=[],version:n})=>{let i=Snr();Lfr();let[a,s]=(0,Dr.useState)(null),{stdout:o}=rV(),l=n.includes("nightly"),{history:u,addItem:c,clearItems:d,loadHistory:h}=Bfr(),[f,E]=(0,Dr.useState)(!1),y=t.getIdeClient().getCurrentIde();(0,Dr.useEffect)(()=>{KU(()=>t.getIdeClient().disconnect())},[t]);let g=y&&!t.getIdeMode()&&!e.merged.hasSeenIdeIntegrationNudge&&!f;(0,Dr.useEffect)(()=>e0r(c,s),[c]);let{consoleMessages:C,handleNewMessage:D,clearConsoleMessages:S}=xor();(0,Dr.useEffect)(()=>{let Gt=new L5({onNewMessage:D,debugMode:t.getDebugMode()});Gt.patch(),KU(Gt.cleanup)},[D,t]);let{stats:w}=U6(),[N,M]=(0,Dr.useState)(!1),[U,k]=(0,Dr.useState)(0),B=(0,Dr.useCallback)(()=>{o.write(Ry.clearTerminal),k(Gt=>Gt+1)},[k,o]),[q,W]=(0,Dr.useState)(0),[re,$]=(0,Dr.useState)(""),[R,Q]=(0,Dr.useState)(null),[J,ae]=(0,Dr.useState)(null),[fe,K]=(0,Dr.useState)(null),[ne,he]=(0,Dr.useState)(0),[Ee,pe]=(0,Dr.useState)(!1),[_e,Se]=(0,Dr.useState)(t.isTrustedFolder()),[se,ve]=(0,Dr.useState)(t.getModel()),[X,ee]=(0,Dr.useState)(!1),[ie,me]=(0,Dr.useState)(!1),[ue,Ce]=(0,Dr.useState)(!1),[le,G]=(0,Dr.useState)(void 0),[Y,Ae]=(0,Dr.useState)(void 0),[te,H]=(0,Dr.useState)(!1),[ge,xe]=(0,Dr.useState)(null),He=(0,Dr.useRef)(null),[mt,xt]=(0,Dr.useState)(!1),Yt=(0,Dr.useRef)(null),ht=(0,Dr.useRef)(!1),[vt,Ut]=(0,Dr.useState)(!0),[dn,ei]=(0,Dr.useState)(!1),[gi,Di]=(0,Dr.useState)(!1),[Ca,Gi]=(0,Dr.useState)(void 0),[Be,rt]=(0,Dr.useState)(),[nt,Nt]=(0,Dr.useState)(!1),[mr,wr]=(0,Dr.useState)(!1);(0,Dr.useEffect)(()=>{let Gt=JE.subscribeToIdeContext(rt);return rt(JE.getIdeContext()),Gt},[]),(0,Dr.useEffect)(()=>{let Gt=()=>{me(!0),Ut(!1)};Qb.on("open-debug-console",Gt);let yi=ys=>{D({type:"error",content:String(ys),count:1})};return Qb.on("log-error",yi),()=>{Qb.off("open-debug-console",Gt),Qb.off("log-error",yi)}},[D]);let hr=(0,Dr.useCallback)(()=>{ei(!0)},[]),Pr=(0,Dr.useCallback)(Gt=>{if(!Gt){G(void 0),Ae(void 0),ht.current=!1;return}G(Gt.count),Ae(Gt.limit),Gt.limit>0&&Gt.count>=Gt.limit?ht.current||(c({type:"info",text:De.t("app.trial.limitReached")},Date.now()),ht.current=!0):ht.current=!1},[c,G,Ae]),Mr=(0,Dr.useCallback)(Gt=>{Nt(Gt)},[]),lo=(0,Dr.useRef)(!1),xl=(0,Dr.useMemo)(()=>C.filter(Gt=>Gt.type==="error").reduce((Gt,yi)=>Gt+yi.count,0),[C]),{isThemeDialogOpen:wc,openThemeDialog:Ad,handleThemeSelect:gd,handleThemeHighlight:wu}=Ynr(e,Q,c),{isSettingsDialogOpen:uo,openSettingsDialog:x1,closeSettingsDialog:B1}=Wfr(),{isModelDialogOpen:Ke,isCustomModelDialogOpen:$e,openModelDialog:ot,closeModelDialog:Ct,models:st,loading:fr,error:Qr,unauthorizedUserError:Wn,handleModelSelect:li,customModelError:ks,customModelBusy:Ei,customModelDraft:_a,customModelDialogMode:Ts,handleCustomModelEdit:yn,handleCustomModelDelete:Mi,handleCustomModelSubmit:Da,handleCustomModelCancel:da}=uir(t,e),{isFolderTrustDialogOpen:ju,handleFolderTrustSelect:_o}=Eir(e,Se),{isAuthDialogOpen:gs,openAuthDialog:Vn,handleAuthSelect:Xo,isAuthenticating:Li,cancelAuthentication:zn,verificationUri:Iu,userCode:co}=mir(e,ae,t);(0,Dr.useEffect)(()=>{if(e.merged.selectedAuthType&&!e.merged.useExternalAuth){let Gt=Bb(e.merged.selectedAuthType);Gt&&(ae(Gt),Vn())}},[e.merged.selectedAuthType,e.merged.useExternalAuth,Vn,ae]),(0,Dr.useEffect)(()=>{Li||Gi(t.getGeminiClient()?.getUserTier())},[t,Li]);let{isEditorDialogOpen:Ri,openEditorDialog:Tu,handleEditorSelect:Xs,exitEditorDialog:as}=yir(e,K,c),Mo=(0,Dr.useCallback)(()=>{pe(Gt=>!Gt)},[]),Re=(0,Dr.useCallback)(async()=>{c({type:"info",text:De.t("app.memory.refreshing")},Date.now());try{let{memoryContent:Gt,fileCount:yi}=await RYe(VYe.cwd(),e.merged.loadMemoryFromIncludeDirectories?t.getWorkspaceContext().getDirectories():[],t.getDebugMode(),t.getFileService(),e.merged,t.getExtensionContextFilePaths(),e.merged.memoryImportFormat||"tree",t.getFileFilteringOptions());t.setUserMemory(Gt),t.setGeminiMdFileCount(yi),W(yi);let ys=Gt.length>0?De.t("app.memory.refreshSuccess",{charCount:Gt.length,fileCount:yi}):De.t("app.memory.refreshSuccessEmpty");c({type:"info",text:ys},Date.now()),t.getDebugMode()&&console.log(`[DEBUG] Refreshed memory content in config: ${Gt.substring(0,200)}...`)}catch(Gt){let yi=sr(Gt);c({type:"error",text:De.t("app.memory.refreshError",{error:yi})},Date.now()),console.error("Error refreshing memory:",Gt)}},[t,c,e.merged]);(0,Dr.useEffect)(()=>{let Gt=()=>{let ys=t.getModel();ys!==se&&ve(ys)};Gt();let yi=setInterval(Gt,1e3);return()=>clearInterval(yi)},[t,se]),(0,Dr.useEffect)(()=>{(async()=>{try{let Gt=await GYe();Pr(Gt)}catch{Pr(null)}})()},[e.merged.selectedAuthType,se,Pr]),(0,Dr.useEffect)(()=>{let Gt=async(yi,ys,yd)=>{let Al;if(t.getContentGeneratorConfig().authType===ln.LOGIN_WITH_GITHUB){let gl=Ca===zh.LEGACY||Ca===zh.STANDARD;yd&&nb(yd)?gl?Al=De.t("app.flashFallback.proQuotaExceeded",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeQuotaExceeded",{currentModel:yi,fallbackModel:ys}):yd&&nR(yd)?gl?Al=De.t("app.flashFallback.proGenericQuota",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeGenericQuota",{currentModel:yi,fallbackModel:ys}):gl?Al=De.t("app.flashFallback.proDefault",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeDefault",{currentModel:yi,fallbackModel:ys}),c({type:"info",text:Al},Date.now()),Di(!0),t.setQuotaErrorOccurred(!0)}return t.setModel(ys),t.setFallbackMode(!0),Dle(t,new eF(t.getContentGeneratorConfig().authType)),!1};t.setFlashFallbackHandler(Gt)},[t,c,Ca]);let{rows:Fe,columns:Xe}=gg(),lt=Sb(Xe),{stdin:Et,setRawMode:Rt}=v8(),$t=(0,Dr.useRef)(!0),zt=Math.max(20,Math.floor(Xe*.9)-3),Xt=Math.max(20,Math.floor(Xe*.8)),ar=(0,Dr.useCallback)(Gt=>{try{return u6e.existsSync(Gt)&&u6e.statSync(Gt).isFile()}catch{return!1}},[]),tn=(0,Dr.useCallback)(()=>{let Gt=e.merged.preferredEditor;if(!_J(Gt)){Tu();return}return Gt},[e,Tu]),Pi=(0,Dr.useCallback)(()=>{ae(De.t("app.auth.reauthRequired")),Vn()},[Vn,ae]),{vimEnabled:Es,vimMode:ui,toggleVimEnabled:Do}=MH(),{handleSlashCommand:Us,slashCommands:Ic,pendingHistoryItems:hl,commandContext:N2,shellConfirmationRequest:xp,confirmationRequest:Ed}=Ior(t,e,c,d,h,B,$,Ad,Vn,Tu,ot,Mo,xe,hr,x1,Do,wr,W),zd=uur({initialText:"",viewport:{height:10,width:zt},stdin:Et,setRawMode:Rt,isValidPath:ar,shellModeActive:X}),[Pm,Qm]=(0,Dr.useState)([]),xu=(0,Dr.useCallback)(()=>{let Gt=Pm.at(-1);Gt&&zd.setText(Gt)},[zd,Pm]),{streamingState:Yu,submitQuery:Tc,initError:Kd,pendingHistoryItems:Sf,thought:x0,cancelOngoingRequest:xc,activeActivity:Z6}=Inr(t.getGeminiClient(),u,c,t,$,Us,X,tn,Pi,Re,gi,Di,B,xu);(0,Dr.useEffect)(()=>{Yu==="idle"&&(async()=>{try{let Gt=await GYe();Gt&&Pr(Gt)}catch{}})()},[Yu,Pr]);let B0=(0,Dr.useCallback)(Gt=>{let yi=Gt.trim();yi.length>0&&Tc(yi)},[Tc]),e4=(0,Dr.useCallback)(Gt=>{Gt.userSelection==="yes"?(Gt.isExtensionPreInstalled?Us("/ide enable"):Us("/ide install"),e.setValue("User","hasSeenIdeIntegrationNudge",!0)):Gt.userSelection==="dismiss"&&e.setValue("User","hasSeenIdeIntegrationNudge",!0),E(!0)},[Us,e]),{handleInput:t4}=Hfr(zd,B0),Wu=[...hl];Wu.push(...Sf);let{elapsedTime:D3,currentLoadingPhrase:r4}=Bnr(Yu,Z6),O2=Tor({config:t}),S3=ige(),R1=(0,Dr.useCallback)((Gt,yi,ys)=>{Gt?(ys.current&&clearTimeout(ys.current),Us("/quit")):(yi(!0),ys.current=setTimeout(()=>{yi(!1),ys.current=null},_jn))},[Us]),km=(0,Dr.useCallback)(Gt=>{let yi=!1;if(vt||(yi=!0,Ut(!0)),ns.showErrorDetails(Gt))me(ys=>!ys);else if(ns.toggleToolDescriptions(Gt)){let ys=!ue;Ce(ys);let yd=t.getMcpServers();Object.keys(yd||{}).length>0&&Us(ys?"/mcp desc":"/mcp nodesc")}else if(ns.toggleIDEContextDetail(Gt)&&t.getIdeMode()&&Be)Us("/ide status");else if(ns.quit(Gt)){if(Li)return;te||xc?.(),R1(te,H,He)}else if(ns.exit(Gt)){if(zd.text.length>0)return;R1(mt,xt,Yt)}else ns.showMoreLines(Gt)&&!yi&&Ut(!1)},[vt,Ut,me,ue,Ce,t,Be,R1,te,H,He,zd.text.length,mt,xt,Yt,Us,Li,xc]);ts(km,{isActive:!0,kittyProtocolEnabled:S3.enabled,config:t}),(0,Dr.useEffect)(()=>{t&&W(t.getGeminiMdFileCount())},[t,t.getGeminiMdFileCount]);let Bc=RAe();(0,Dr.useEffect)(()=>{(async()=>{let yi=await Bc?.getPreviousUserMessages()||[],yd=[...u.filter(gl=>gl.type==="user"&&typeof gl.text=="string"&&gl.text.trim()!=="").map(gl=>gl.text).reverse(),...yi],Al=[];if(yd.length>0){Al.push(yd[0]);for(let gl=1;gl<yd.length;gl++)yd[gl]!==yd[gl-1]&&Al.push(yd[gl])}Qm(Al.reverse())})()},[u,Bc]);let F2=Yu==="idle"&&!Kd&&!mr,Bp=(0,Dr.useCallback)(()=>{d(),S(),console.clear(),B()},[d,S,B]),bf=(0,Dr.useRef)(null),n4=(0,Dr.useRef)(null);(0,Dr.useEffect)(()=>{if(bf.current){let Gt=P3e(bf.current);he(Gt.height)}},[Fe,C,ie]);let $5=3,b3=(0,Dr.useMemo)(()=>Fe-ne-$5,[Fe,ne]);(0,Dr.useEffect)(()=>{if($t.current){$t.current=!1;return}let Gt=setTimeout(()=>{M(!1),B()},300);return()=>{clearTimeout(Gt)}},[Xe,Fe,B]),(0,Dr.useEffect)(()=>{Yu==="idle"&&N&&(M(!1),B())},[Yu,B,N]);let M2=(0,Dr.useMemo)(()=>t.getDebugMode()?C:C.filter(Gt=>Gt.type!=="debug"),[C,t]),R0=Ffr(t.getTargetDir()),N0=(0,Dr.useMemo)(()=>{let Gt=e.merged.contextFileName;return Gt?Array.isArray(Gt)?Gt:[Gt]:MS()},[e.merged.contextFileName]),ci=(0,Dr.useMemo)(()=>t.getQuestion(),[t]),Kt=t.getGeminiClient();if((0,Dr.useEffect)(()=>{ci&&!lo.current&&!Li&&!gs&&!wc&&!Ri&&!dn&&Kt?.isInitialized?.()&&(Tc(ci),lo.current=!0)},[ci,Tc,Li,gs,wc,Ri,dn,Kt]),ge)return(0,_r.jsx)(Le,{flexDirection:"column",marginBottom:1,children:ge.map(Gt=>(0,_r.jsx)(i6e,{availableTerminalHeight:vt?b3:void 0,terminalWidth:Xe,item:Gt,isPending:!1,config:t},Gt.id))});let Rc=Math.floor(Xe*.9),Um=Math.floor(Math.max(Fe*.2,5)),ss=Math.max(Fe*4,100),Nc=Es?De.t("app.placeholders.vim"):De.t("app.placeholders.default");return(0,_r.jsx)(J$e.Provider,{value:Yu,children:(0,_r.jsxs)(Le,{flexDirection:"column",width:"90%",children:[(0,_r.jsx)(Gee,{items:[(0,_r.jsxs)(Le,{flexDirection:"column",children:[!e.merged.hideBanner&&(0,_r.jsx)(qlr,{version:n,nightly:l}),!e.merged.hideTips&&(0,_r.jsx)(j1r,{config:t})]},"header"),...u.map(Gt=>(0,_r.jsx)(i6e,{terminalWidth:Rc,availableTerminalHeight:ss,item:Gt,isPending:!1,config:t,commands:Ic},Gt.id))],children:Gt=>Gt},U),(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{ref:n4,flexDirection:"column",children:[Wu.map((Gt,yi)=>(0,_r.jsx)(i6e,{availableTerminalHeight:vt?b3:void 0,terminalWidth:Rc,item:{...Gt,id:0},isPending:!0,config:t,isFocused:!Ri},yi)),(0,_r.jsx)(a6e,{constrainHeight:vt})]})}),(0,_r.jsxs)(Le,{flexDirection:"column",ref:bf,children:[a&&(0,_r.jsx)(Gfr,{message:a.message}),r.length>0&&(0,_r.jsx)(Le,{borderStyle:"round",borderColor:ke.AccentYellow,paddingX:1,marginY:1,flexDirection:"column",children:r.map((Gt,yi)=>(0,_r.jsx)(be,{color:ke.AccentYellow,children:Gt},yi))}),g&&y?(0,_r.jsx)(Rfr,{ide:y,onComplete:e4}):ju?(0,_r.jsx)(hir,{onSelect:_o}):xp?(0,_r.jsx)(Rdr,{request:xp}):Ed?(0,_r.jsxs)(Le,{flexDirection:"column",children:[Ed.prompt,(0,_r.jsx)(Le,{paddingY:1,children:(0,_r.jsx)(Kl,{items:[{label:De.t("app.confirmation.yes"),value:!0},{label:De.t("app.confirmation.no"),value:!1}],onSelect:Gt=>{Ed.onConfirm(Gt)}})})]}):wc?(0,_r.jsxs)(Le,{flexDirection:"column",children:[R&&(0,_r.jsx)(Le,{marginBottom:1,children:(0,_r.jsx)(be,{color:ke.AccentRed,children:R})}),(0,_r.jsx)(Ddr,{onSelect:gd,onHighlight:wu,settings:e,availableTerminalHeight:vt?Fe-$5:void 0,terminalWidth:Rc})]}):uo?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Kfr,{settings:e,onSelect:()=>B1(),onRestartRequest:()=>VYe.exit(0)})}):$e?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(bdr,{onSubmit:Da,onCancel:da,error:ks,busy:Ei,initialValues:_a??void 0,mode:Ts})}):Ke?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Sdr,{settings:e,models:st,loading:fr,error:Qr,unauthorizedUserError:Wn,onSelect:li,onEdit:yn,onDelete:Mi,onExit:Ct})}):Li?(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Tdr,{onTimeout:()=>{ae(De.t("app.auth.timeout")),zn(),Vn()},verificationUri:Iu,userCode:co}),ie&&(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{flexDirection:"column",children:[(0,_r.jsx)(NYe,{messages:M2,maxHeight:vt?Um:void 0,width:zt}),(0,_r.jsx)(a6e,{constrainHeight:vt})]})})]}):gs?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Idr,{onSelect:Xo,settings:e,initialErrorMessage:J})}):Ri?(0,_r.jsxs)(Le,{flexDirection:"column",children:[fe&&(0,_r.jsx)(Le,{marginBottom:1,children:(0,_r.jsx)(be,{color:ke.AccentRed,children:fe})}),(0,_r.jsx)(Bdr,{onSelect:Xs,settings:e,onExit:as})]}):dn?(0,_r.jsx)(Yfr,{onExit:()=>ei(!1),config:t}):(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Klr,{thought:Yu==="waiting_for_confirmation"||t.getAccessibility()?.disableLoadingPhrases?void 0:x0,currentLoadingPhrase:t.getAccessibility()?.disableLoadingPhrases?void 0:r4,elapsedTime:D3}),(0,_r.jsxs)(Le,{marginTop:1,justifyContent:"space-between",width:"100%",flexDirection:lt?"column":"row",alignItems:lt?"flex-start":"center",children:[(0,_r.jsxs)(Le,{children:[VYe.env.GEMINI_SYSTEM_MD&&(0,_r.jsx)(be,{color:ke.AccentRed,children:"|\u2310\u25A0_\u25A0| "}),te?(0,_r.jsx)(be,{color:ke.AccentYellow,children:De.t("app.prompts.pressCtrlCAgain")}):mt?(0,_r.jsx)(be,{color:ke.AccentYellow,children:De.t("app.prompts.pressCtrlDAgain")}):nt?(0,_r.jsx)(be,{color:ke.Gray,children:De.t("app.prompts.pressEscAgain")}):(0,_r.jsx)(xfr,{ideContext:Be,geminiMdFileCount:q,contextFileNames:N0,mcpServers:t.getMcpServers(),blockedMcpServers:t.getBlockedMcpServers(),showToolDescriptions:ue})]}),(0,_r.jsxs)(Le,{paddingTop:lt?1:0,children:[O2!==qa.DEFAULT&&!X&&(0,_r.jsx)(Jlr,{approvalMode:O2}),X&&(0,_r.jsx)(Xlr,{})]})]}),ie&&(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{flexDirection:"column",children:[(0,_r.jsx)(NYe,{messages:M2,maxHeight:vt?Um:void 0,width:zt}),(0,_r.jsx)(a6e,{constrainHeight:vt})]})}),F2&&(0,_r.jsx)(wur,{buffer:zd,inputWidth:zt,suggestionsWidth:Xt,onSubmit:B0,userMessages:Pm,onClearScreen:Bp,config:t,slashCommands:Ic,commandContext:N2,shellModeActive:X,setShellModeActive:ee,onEscapePromptChange:Mr,focus:i,vimHandleInput:t4,placeholder:Nc})]}),Kd&&Yu!=="responding"&&(0,_r.jsx)(Le,{borderStyle:"round",borderColor:ke.AccentRed,paddingX:1,marginBottom:1,children:u.find(Gt=>Gt.type==="error"&&Gt.text?.includes(Kd))?.text?(0,_r.jsx)(be,{color:ke.AccentRed,children:u.find(Gt=>Gt.type==="error"&&Gt.text?.includes(Kd))?.text}):(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(be,{color:ke.AccentRed,children:De.t("app.init.error",{error:Kd})}),(0,_r.jsx)(be,{color:ke.AccentRed,children:De.t("app.init.checkConfig")})]})}),(0,_r.jsx)(Our,{model:se,targetDir:t.getTargetDir(),debugMode:t.getDebugMode(),branchName:R0,debugMessage:re,corgiMode:Ee,errorCount:xl,showErrorDetails:ie,showMemoryUsage:t.getDebugMode()||e.merged.showMemoryUsage||!1,promptTokenCount:w.lastPromptTokenCount,nightly:l,vimMode:Es?ui:void 0,isTrustedFolder:_e,trialRequestsUsed:le,trialRequestsLimit:Y})]})]})})};async function n0r(){return new Promise((e,r)=>{let n="",i=0;process.stdin.setEncoding("utf8");let a=()=>{let u;for(;(u=process.stdin.read())!==null;){if(i+u.length>8388608){let c=8388608-i;n+=u.slice(0,c),console.warn("Warning: stdin input truncated to 8388608 bytes."),process.stdin.destroy();break}n+=u,i+=u.length}},s=()=>{l(),e(n)},o=u=>{l(),r(u)},l=()=>{process.stdin.removeListener("readable",a),process.stdin.removeListener("end",s),process.stdin.removeListener("error",o)};process.stdin.on("readable",a),process.stdin.on("end",s),process.stdin.on("error",o)})}import{basename as mei}from"node:path";import hei from"node:v8";import Aei from"node:os";import gei from"node:dns";import{spawn as Eei}from"node:child_process";var UX=Ve(Lpe(),1);import{exec as Sjn,execSync as kb,spawn as QH}from"node:child_process";import C3 from"node:os";import Q5 from"node:path";import I1 from"node:fs";import{readFile as bjn}from"node:fs/promises";import{promisify as wjn}from"util";var qYe=wjn(Sjn);function oA(t){if(C3.platform()!=="win32")return t;let r=t.replace(/\\/g,"/").match(/^([A-Z]):\/(.*)/i);return r?`/${r[1].toLowerCase()}/${r[2]}`:t}var a0r="gemini-cli-sandbox",c6e="gemini-cli-sandbox",nN="gemini-cli-sandbox-proxy",Ijn=["permissive-open","permissive-closed","permissive-proxied","restrictive-open","restrictive-closed","restrictive-proxied"];async function Tjn(){let t=process.env.SANDBOX_SET_UID_GID?.toLowerCase().trim();if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;if(C3.platform()==="linux")try{let e=await bjn("/etc/os-release","utf8");if(e.includes("ID=debian")||e.includes("ID=ubuntu")||e.match(/^ID_LIKE=.*debian.*/m)||e.match(/^ID_LIKE=.*ubuntu.*/m))return console.error("INFO: Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux."),!0}catch{console.warn("Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.")}return!1}function xjn(t){let[e,r]=t.split(":"),n=e.split("/").at(-1)??"unknown-image";return r?`${n}-${r}`:n}function s0r(){return(process.env.SANDBOX_PORTS??"").split(",").filter(t=>t.trim()).map(t=>t.trim())}function Bjn(t){let e=C3.platform()==="win32",r=oA(t),n=[],i=e?";":":",a="";if(process.env.PATH){let d=process.env.PATH.split(i);for(let h of d){let f=oA(h);f.toLowerCase().startsWith(r.toLowerCase())&&(a+=`:${f}`)}}a&&n.push(`export PATH="$PATH${a}";`);let s="";if(process.env.PYTHONPATH){let d=process.env.PYTHONPATH.split(i);for(let h of d){let f=oA(h);f.toLowerCase().startsWith(r.toLowerCase())&&(s+=`:${f}`)}}s&&n.push(`export PYTHONPATH="$PYTHONPATH${s}";`);let o=Q5.join(q7,"sandbox.bashrc");I1.existsSync(o)&&n.push(`source ${oA(o)};`),s0r().forEach(d=>n.push(`socat TCP4-LISTEN:${d},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${d} 2> /dev/null &`));let l=process.argv.slice(2).map(d=>(0,UX.quote)([d])),u=process.env.NODE_ENV==="development"?process.env.DEBUG?"npm run debug --":"npm rebuild && npm run start --":process.env.DEBUG?`node --inspect-brk=0.0.0.0:${process.env.DEBUG_PORT||"9229"} $(which gemini)`:"gemini";return["bash","-c",[...n,u,...l].join(" ")]}async function o0r(t,e=[],r){let n=new L5({debugMode:r?.getDebugMode()||!!process.env.DEBUG,stderr:!0});n.patch();try{if(t.command==="sandbox-exec"){process.env.BUILD_SANDBOX&&(console.error("ERROR: cannot BUILD_SANDBOX when using macOS Seatbelt"),process.exit(1));let B=process.env.SEATBELT_PROFILE??="permissive-open",q=new URL(`sandbox-macos-${B}.sb`,import.meta.url).pathname;Ijn.includes(B)||(q=Q5.join(q7,`sandbox-macos-${B}.sb`)),I1.existsSync(q)||(console.error(`ERROR: missing macos seatbelt profile file '${q}'`),process.exit(1)),console.error(`using macos seatbelt (profile: ${B}) ...`);let W=[...process.env.DEBUG?["--inspect-brk"]:[],...e].join(" "),re=["-D",`TARGET_DIR=${I1.realpathSync(process.cwd())}`,"-D",`TMP_DIR=${I1.realpathSync(C3.tmpdir())}`,"-D",`HOME_DIR=${I1.realpathSync(C3.homedir())}`,"-D",`CACHE_DIR=${I1.realpathSync(kb("getconf DARWIN_USER_CACHE_DIR").toString().trim())}`],$=5,R=I1.realpathSync(r?.getTargetDir()||""),Q=[];if(r){let he=r.getWorkspaceContext().getDirectories();for(let Ee of he){let pe=I1.realpathSync(Ee);pe!==R&&Q.push(pe)}}for(let ne=0;ne<$;ne++){let he="/dev/null";ne<Q.length&&(he=Q[ne]),re.push("-D",`INCLUDE_DIR_${ne}=${he}`)}re.push("-f",q,"sh","-c",["SANDBOX=sandbox-exec",`NODE_OPTIONS="${W}"`,...process.argv.map(ne=>(0,UX.quote)([ne]))].join(" "));let J=process.env.GEMINI_SANDBOX_PROXY_COMMAND,ae,fe,K={...process.env};if(J){let ne=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||"http://localhost:8877";K.HTTPS_PROXY=ne,K.https_proxy=ne,K.HTTP_PROXY=ne,K.http_proxy=ne;let he=process.env.NO_PROXY||process.env.no_proxy;he&&(K.NO_PROXY=he,K.no_proxy=he),ae=QH(J,{stdio:["ignore","pipe","pipe"],shell:!0,detached:!0});let Ee=()=>{console.log("stopping proxy ..."),ae?.pid&&process.kill(-ae.pid,"SIGTERM")};process.on("exit",Ee),process.on("SIGINT",Ee),process.on("SIGTERM",Ee),ae.stderr?.on("data",pe=>{console.error(pe.toString())}),ae.on("close",(pe,_e)=>{console.error(`ERROR: proxy command '${J}' exited with code ${pe}, signal ${_e}`),fe?.pid&&process.kill(-fe.pid,"SIGTERM"),process.exit(1)}),console.log("waiting for proxy to start ..."),await qYe("until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done")}fe=QH(t.command,re,{stdio:"inherit"}),await new Promise(ne=>fe?.on("close",ne));return}console.error(`hopping into sandbox (command: ${t.command}) ...`);let i=I1.realpathSync(process.argv[1]),a=Q5.join(q7,"sandbox.Dockerfile"),s=I1.existsSync(a),o=t.image,l=Q5.resolve(process.cwd()),u=oA(l);if(process.env.BUILD_SANDBOX)if(!i.includes("gemini-cli/packages/"))console.error("ERROR: cannot build sandbox using installed gemini binary; run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary."),process.exit(1);else{console.error("building sandbox ...");let B=i.split("/packages/")[0],q="",W=Q5.join(q7,"sandbox.Dockerfile");s&&(console.error(`using ${W} for sandbox`),q+=`-f ${Q5.resolve(W)} -i ${o}`),kb(`cd ${B} && node scripts/build_sandbox.js -s ${q}`,{stdio:"inherit",env:{...process.env,GEMINI_SANDBOX:t.command}})}await Njn(t.command,o)||(console.error(`ERROR: Sandbox image '${o}' is missing or could not be pulled. ${o===a0r?"Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection.":"Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists."}`),process.exit(1));let c=["run","-i","--rm","--init","--workdir",u];if(process.env.SANDBOX_FLAGS){let B=(0,UX.parse)(process.env.SANDBOX_FLAGS,process.env).filter(q=>typeof q=="string");c.push(...B)}process.stdin.isTTY&&c.push("-t"),c.push("--volume",`${l}:${u}`);let d=bqe,h=oA(`/home/node/${q7}`);I1.existsSync(d)||I1.mkdirSync(d),c.push("--volume",`${d}:${h}`),h!==d&&c.push("--volume",`${d}:${oA(d)}`),c.push("--volume",`${C3.tmpdir()}:${oA(C3.tmpdir())}`);let f=Q5.join(C3.homedir(),".config","gcloud");if(I1.existsSync(f)&&c.push("--volume",`${f}:${oA(f)}:ro`),process.env.GOOGLE_APPLICATION_CREDENTIALS){let B=process.env.GOOGLE_APPLICATION_CREDENTIALS;I1.existsSync(B)&&(c.push("--volume",`${B}:${oA(B)}:ro`),c.push("--env",`GOOGLE_APPLICATION_CREDENTIALS=${oA(B)}`))}if(process.env.SANDBOX_MOUNTS){for(let B of process.env.SANDBOX_MOUNTS.split(","))if(B.trim()){let[q,W,re]=B.trim().split(":");W=W||q,re=re||"ro",B=`${q}:${W}:${re}`,Q5.isAbsolute(q)||(console.error(`ERROR: path '${q}' listed in SANDBOX_MOUNTS must be absolute`),process.exit(1)),I1.existsSync(q)||(console.error(`ERROR: missing mount path '${q}' listed in SANDBOX_MOUNTS`),process.exit(1)),console.error(`SANDBOX_MOUNTS: ${q} -> ${W} (${re})`),c.push("--volume",B)}}if(s0r().forEach(B=>c.push("--publish",`${B}:${B}`)),process.env.DEBUG){let B=process.env.DEBUG_PORT||"9229";c.push("--publish",`${B}:${B}`)}let E=process.env.GEMINI_SANDBOX_PROXY_COMMAND;if(E){let B=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||"http://localhost:8877";B=B.replace("localhost",nN),B&&(c.push("--env",`HTTPS_PROXY=${B}`),c.push("--env",`https_proxy=${B}`),c.push("--env",`HTTP_PROXY=${B}`),c.push("--env",`http_proxy=${B}`));let q=process.env.NO_PROXY||process.env.no_proxy;q&&(c.push("--env",`NO_PROXY=${q}`),c.push("--env",`no_proxy=${q}`)),B&&(kb(`${t.command} network inspect ${c6e} || ${t.command} network create --internal ${c6e}`),c.push("--network",c6e),E&&kb(`${t.command} network inspect ${nN} || ${t.command} network create ${nN}`))}let y=xjn(o),g=0,C=kb(`${t.command} ps -a --format "{{.Names}}"`).toString().trim();for(;C.includes(`${y}-${g}`);)g++;let D=`${y}-${g}`;c.push("--name",D,"--hostname",D),process.env.KODA_API_KEY&&c.push("--env",`KODA_API_KEY=${process.env.KODA_API_KEY}`),process.env.GOOGLE_API_KEY&&c.push("--env",`GOOGLE_API_KEY=${process.env.GOOGLE_API_KEY}`),process.env.GOOGLE_GENAI_USE_VERTEXAI&&c.push("--env",`GOOGLE_GENAI_USE_VERTEXAI=${process.env.GOOGLE_GENAI_USE_VERTEXAI}`),process.env.GOOGLE_GENAI_USE_GCA&&c.push("--env",`GOOGLE_GENAI_USE_GCA=${process.env.GOOGLE_GENAI_USE_GCA}`),process.env.GOOGLE_CLOUD_PROJECT&&c.push("--env",`GOOGLE_CLOUD_PROJECT=${process.env.GOOGLE_CLOUD_PROJECT}`),process.env.GOOGLE_CLOUD_LOCATION&&c.push("--env",`GOOGLE_CLOUD_LOCATION=${process.env.GOOGLE_CLOUD_LOCATION}`),process.env.GEMINI_MODEL&&c.push("--env",`GEMINI_MODEL=${process.env.GEMINI_MODEL}`),process.env.KODA_RESPONSE_LANGUAGE&&c.push("--env",`KODA_RESPONSE_LANGUAGE=${process.env.KODA_RESPONSE_LANGUAGE}`),process.env.TERM&&c.push("--env",`TERM=${process.env.TERM}`),process.env.COLORTERM&&c.push("--env",`COLORTERM=${process.env.COLORTERM}`);for(let B of["KODA_CLI_IDE_SERVER_PORT","GEMINI_CLI_IDE_SERVER_PORT","GEMINI_CLI_IDE_WORKSPACE_PATH","TERM_PROGRAM"])process.env[B]&&c.push("--env",`${B}=${process.env[B]}`);if(process.env.VIRTUAL_ENV?.toLowerCase().startsWith(l.toLowerCase())){let B=Q5.resolve(q7,"sandbox.venv");I1.existsSync(B)||I1.mkdirSync(B,{recursive:!0}),c.push("--volume",`${B}:${oA(process.env.VIRTUAL_ENV)}`),c.push("--env",`VIRTUAL_ENV=${oA(process.env.VIRTUAL_ENV)}`)}if(process.env.SANDBOX_ENV)for(let B of process.env.SANDBOX_ENV.split(","))(B=B.trim())&&(B.includes("=")?(console.error(`SANDBOX_ENV: ${B}`),c.push("--env",B)):(console.error("ERROR: SANDBOX_ENV must be a comma-separated list of key=value pairs"),process.exit(1)));let S=process.env.NODE_OPTIONS||"",w=[...S?[S]:[],...e].join(" ");if(w.length>0&&c.push("--env",`NODE_OPTIONS="${w}"`),c.push("--env",`SANDBOX=${D}`),t.command==="podman"){let B=Q5.join(C3.tmpdir(),"empty_auth.json");I1.writeFileSync(B,"{}","utf-8"),c.push("--authfile",B)}let N="",M=Bjn(l);if(process.env.GEMINI_CLI_INTEGRATION_TEST==="true")c.push("--user","root"),N="--user root";else if(await Tjn()){c.push("--user","root");let B=kb("id -u").toString().trim(),q=kb("id -g").toString().trim(),W="gemini",re=oA(C3.homedir()),$=[`groupadd -f -g ${q} ${W}`,`id -u ${W} &>/dev/null || useradd -o -u ${B} -g ${q} -d ${re} -s /bin/bash ${W}`].join(" && "),Q=M[2].replace(/'/g,"'\\''"),J=`su -p ${W} -c '${Q}'`;M[2]=`${$} && ${J}`,N=`--user ${B}:${q}`,c.push("--env",`HOME=${C3.homedir()}`)}c.push(o),c.push(...M);let U,k;if(E){let B=`${t.command} run --rm --init ${N} --name ${nN} --network ${nN} -p 8877:8877 -v ${process.cwd()}:${l} --workdir ${l} ${o} ${E}`;U=QH(B,{stdio:["ignore","pipe","pipe"],shell:!0,detached:!0});let q=()=>{console.log("stopping proxy container ..."),kb(`${t.command} rm -f ${nN}`)};process.on("exit",q),process.on("SIGINT",q),process.on("SIGTERM",q),U.stderr?.on("data",W=>{console.error(W.toString().trim())}),U.on("close",(W,re)=>{console.error(`ERROR: proxy container command '${B}' exited with code ${W}, signal ${re}`),k?.pid&&process.kill(-k.pid,"SIGTERM"),process.exit(1)}),console.log("waiting for proxy to start ..."),await qYe("until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done"),await qYe(`${t.command} network connect ${c6e} ${nN}`)}k=QH(t.command,c,{stdio:"inherit"}),k.on("error",B=>{console.error("Sandbox process error:",B)}),await new Promise(B=>{k?.on("close",(q,W)=>{q!==0&&console.log(`Sandbox process exited with code: ${q}, signal: ${W}`),B()})})}finally{n.cleanup()}}async function i0r(t,e){return new Promise(r=>{let i=QH(t,["images","-q",e]),a="";i.stdout&&i.stdout.on("data",s=>{a+=s.toString()}),i.on("error",s=>{console.warn(`Failed to start '${t}' command for image check: ${s.message}`),r(!1)}),i.on("close",s=>{r(a.trim()!=="")})})}async function Rjn(t,e){return console.info(`Attempting to pull image ${e} using ${t}...`),new Promise(r=>{let i=QH(t,["pull",e],{stdio:"pipe"}),a="",s=d=>{console.info(d.toString().trim())},o=d=>{a+=d.toString(),console.error(d.toString().trim())},l=d=>{console.warn(`Failed to start '${t} pull ${e}' command: ${d.message}`),c(),r(!1)},u=d=>{d===0?(console.info(`Successfully pulled image ${e}.`),c(),r(!0)):(console.warn(`Failed to pull image ${e}. '${t} pull ${e}' exited with code ${d}.`),a.trim(),c(),r(!1))},c=()=>{i.stdout&&i.stdout.removeListener("data",s),i.stderr&&i.stderr.removeListener("data",o),i.removeListener("error",l),i.removeListener("close",u),i.connected&&i.disconnect()};i.stdout&&i.stdout.on("data",s),i.stderr&&i.stderr.on("data",o),i.on("error",l),i.on("close",u)})}async function Njn(t,e){return console.info(`Checking for sandbox image: ${e}`),await i0r(t,e)?(console.info(`Sandbox image ${e} found locally.`),!0):(console.info(`Sandbox image ${e} not found locally.`),e===a0r?!1:await Rjn(t,e)?await i0r(t,e)?(console.info(`Sandbox image ${e} is now available after pulling.`),!0):(console.warn(`Sandbox image ${e} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`),!1):(console.error(`Failed to obtain sandbox image ${e} after check and pull attempt.`),!1))}Hn();import $Ye from"fs/promises";import Ojn from"os";import{join as Fjn}from"node:path";var jYe=Fjn(Ojn.tmpdir(),"gemini-cli-warnings.txt");async function l0r(){try{await $Ye.access(jYe);let e=(await $Ye.readFile(jYe,"utf-8")).split(`
2036
+ ${i.updateMessage}`),x2.emit("update-received",{message:a}),!i.updateCommand||e.merged.disableAutoUpdate)return;let s=t.update.latest.includes("nightly"),o=i.updateCommand.replace("@latest",s?"@nightly":`@${t.update.latest}`),l=n(o,{stdio:"pipe",shell:!0}),u="";return l.stderr.on("data",c=>{u+=c.toString()}),l.on("close",c=>{c===0?x2.emit("update-success",{message:De.t("autoUpdate.success")}):x2.emit("update-failed",{message:De.t("autoUpdate.failedWithCommand",{command:o,stderr:u.trim()})})}),l.on("error",c=>{x2.emit("update-failed",{message:De.t("autoUpdate.failedWithError",{error:c.message})})}),l}function e0r(t,e){let r=!1,n=o=>{e(o);let l=o.message;setTimeout(()=>{r||t({type:"info",text:l},Date.now()),e(null)},6e4)},i=()=>{e(null),t({type:"error",text:De.t("autoUpdate.failedShort")},Date.now())},a=()=>{r=!0,e(null),t({type:"info",text:De.t("autoUpdate.success")},Date.now())},s=o=>{t({type:"info",text:o.message},Date.now())};return x2.on("update-received",n),x2.on("update-failed",i),x2.on("update-success",a),x2.on("update-info",s),()=>{x2.off("update-received",n),x2.off("update-failed",i),x2.off("update-success",a),x2.off("update-info",s)}}import{EventEmitter as Ajn}from"events";var Qb=new Ajn;import gjn from"node:os";import t0r from"node:path";import{promises as Ejn}from"node:fs";async function yjn(){try{let t=process.env.XDG_CONFIG_HOME||t0r.join(gjn.homedir(),".config"),e=t0r.join(t,"koda","credentials.json"),r=await Ejn.readFile(e,"utf-8"),n=JSON.parse(r);return(typeof n.githubToken=="string"?n.githubToken:"")||null}catch{return null}}function vjn(){return`${process.env.KODA_API_BASE||"https://api.kodacode.ru"}/ftc`}async function GYe(){let t=process.env.KODA_GITHUB_TOKEN||process.env.GITHUB_TOKEN||null;if(t||(t=await yjn()),!t)return null;let e=vjn(),r={Accept:"application/json","Accept-Encoding":"identity","Content-Type":"application/json",Authorization:`Bearer ${t}`};try{let n=await fetch(e,{method:"POST",headers:r,body:JSON.stringify({ghAuthToken:t})});if(!n.ok)return null;let i=await n.json(),a=Number(i.count??0),s=Number(i.limit??0);if(!Number.isFinite(a)||!Number.isFinite(s))return null;let o=Math.max(0,a);return{count:o,limit:s,remaining:s-o}}catch{return null}}var _r=Ve(Lt(),1);var _jn=1e3,r0r=t=>(0,_r.jsx)(_nr,{children:(0,_r.jsx)(Qfr,{settings:t.settings,children:(0,_r.jsx)(Djn,{...t})})}),Djn=({config:t,settings:e,startupWarnings:r=[],version:n})=>{let i=Snr();Lfr();let[a,s]=(0,Dr.useState)(null),{stdout:o}=rV(),l=n.includes("nightly"),{history:u,addItem:c,clearItems:d,loadHistory:h}=Bfr(),[f,E]=(0,Dr.useState)(!1),y=t.getIdeClient().getCurrentIde();(0,Dr.useEffect)(()=>{KU(()=>t.getIdeClient().disconnect())},[t]);let g=y&&!t.getIdeMode()&&!e.merged.hasSeenIdeIntegrationNudge&&!f;(0,Dr.useEffect)(()=>e0r(c,s),[c]);let{consoleMessages:C,handleNewMessage:D,clearConsoleMessages:S}=xor();(0,Dr.useEffect)(()=>{let Gt=new L5({onNewMessage:D,debugMode:t.getDebugMode()});Gt.patch(),KU(Gt.cleanup)},[D,t]);let{stats:w}=U6(),[N,M]=(0,Dr.useState)(!1),[U,k]=(0,Dr.useState)(0),B=(0,Dr.useCallback)(()=>{o.write(Ry.clearTerminal),k(Gt=>Gt+1)},[k,o]),[q,W]=(0,Dr.useState)(0),[re,$]=(0,Dr.useState)(""),[R,Q]=(0,Dr.useState)(null),[J,ae]=(0,Dr.useState)(null),[fe,K]=(0,Dr.useState)(null),[ne,he]=(0,Dr.useState)(0),[Ee,pe]=(0,Dr.useState)(!1),[_e,Se]=(0,Dr.useState)(t.isTrustedFolder()),[se,ve]=(0,Dr.useState)(t.getModel()),[X,ee]=(0,Dr.useState)(!1),[ie,me]=(0,Dr.useState)(!1),[ue,Ce]=(0,Dr.useState)(!1),[le,G]=(0,Dr.useState)(void 0),[Y,Ae]=(0,Dr.useState)(void 0),[te,H]=(0,Dr.useState)(!1),[ge,xe]=(0,Dr.useState)(null),He=(0,Dr.useRef)(null),[mt,xt]=(0,Dr.useState)(!1),Yt=(0,Dr.useRef)(null),ht=(0,Dr.useRef)(!1),[vt,Ut]=(0,Dr.useState)(!0),[dn,ei]=(0,Dr.useState)(!1),[gi,Di]=(0,Dr.useState)(!1),[Ca,Gi]=(0,Dr.useState)(void 0),[Be,rt]=(0,Dr.useState)(),[nt,Nt]=(0,Dr.useState)(!1),[mr,wr]=(0,Dr.useState)(!1);(0,Dr.useEffect)(()=>{let Gt=JE.subscribeToIdeContext(rt);return rt(JE.getIdeContext()),Gt},[]),(0,Dr.useEffect)(()=>{let Gt=()=>{me(!0),Ut(!1)};Qb.on("open-debug-console",Gt);let yi=ys=>{D({type:"error",content:String(ys),count:1})};return Qb.on("log-error",yi),()=>{Qb.off("open-debug-console",Gt),Qb.off("log-error",yi)}},[D]);let hr=(0,Dr.useCallback)(()=>{ei(!0)},[]),Pr=(0,Dr.useCallback)(Gt=>{if(!Gt){G(void 0),Ae(void 0),ht.current=!1;return}G(Gt.count),Ae(Gt.limit),Gt.limit>0&&Gt.count>=Gt.limit?ht.current||(c({type:"info",text:De.t("app.trial.limitReached")},Date.now()),ht.current=!0):ht.current=!1},[c,G,Ae]),Mr=(0,Dr.useCallback)(Gt=>{Nt(Gt)},[]),lo=(0,Dr.useRef)(!1),xl=(0,Dr.useMemo)(()=>C.filter(Gt=>Gt.type==="error").reduce((Gt,yi)=>Gt+yi.count,0),[C]),{isThemeDialogOpen:wc,openThemeDialog:Ad,handleThemeSelect:gd,handleThemeHighlight:wu}=Ynr(e,Q,c),{isSettingsDialogOpen:uo,openSettingsDialog:x1,closeSettingsDialog:B1}=Wfr(),{isModelDialogOpen:Ke,isCustomModelDialogOpen:$e,openModelDialog:ot,closeModelDialog:Ct,models:st,loading:fr,error:Qr,unauthorizedUserError:Wn,handleModelSelect:li,customModelError:ks,customModelBusy:Ei,customModelDraft:_a,customModelDialogMode:Ts,handleCustomModelEdit:yn,handleCustomModelDelete:Mi,handleCustomModelSubmit:Da,handleCustomModelCancel:da}=uir(t,e),{isFolderTrustDialogOpen:ju,handleFolderTrustSelect:_o}=Eir(e,Se),{isAuthDialogOpen:gs,openAuthDialog:Vn,handleAuthSelect:Xo,isAuthenticating:Li,cancelAuthentication:zn,verificationUri:Iu,userCode:co}=mir(e,ae,t);(0,Dr.useEffect)(()=>{if(e.merged.selectedAuthType&&!e.merged.useExternalAuth){let Gt=Bb(e.merged.selectedAuthType);Gt&&(ae(Gt),Vn())}},[e.merged.selectedAuthType,e.merged.useExternalAuth,Vn,ae]),(0,Dr.useEffect)(()=>{Li||Gi(t.getGeminiClient()?.getUserTier())},[t,Li]);let{isEditorDialogOpen:Ri,openEditorDialog:Tu,handleEditorSelect:Xs,exitEditorDialog:as}=yir(e,K,c),Mo=(0,Dr.useCallback)(()=>{pe(Gt=>!Gt)},[]),Re=(0,Dr.useCallback)(async()=>{c({type:"info",text:De.t("app.memory.refreshing")},Date.now());try{let{memoryContent:Gt,fileCount:yi}=await RYe(VYe.cwd(),e.merged.loadMemoryFromIncludeDirectories?t.getWorkspaceContext().getDirectories():[],t.getDebugMode(),t.getFileService(),e.merged,t.getExtensionContextFilePaths(),e.merged.memoryImportFormat||"tree",t.getFileFilteringOptions());t.setUserMemory(Gt),t.setGeminiMdFileCount(yi),W(yi);let ys=Gt.length>0?De.t("app.memory.refreshSuccess",{charCount:Gt.length,fileCount:yi}):De.t("app.memory.refreshSuccessEmpty");c({type:"info",text:ys},Date.now()),t.getDebugMode()&&console.log(`[DEBUG] Refreshed memory content in config: ${Gt.substring(0,200)}...`)}catch(Gt){let yi=sr(Gt);c({type:"error",text:De.t("app.memory.refreshError",{error:yi})},Date.now()),console.error("Error refreshing memory:",Gt)}},[t,c,e.merged]);(0,Dr.useEffect)(()=>{let Gt=()=>{let ys=t.getModel();ys!==se&&ve(ys)};Gt();let yi=setInterval(Gt,1e3);return()=>clearInterval(yi)},[t,se]),(0,Dr.useEffect)(()=>{(async()=>{try{let Gt=await GYe();Pr(Gt)}catch{Pr(null)}})()},[e.merged.selectedAuthType,se,Pr]),(0,Dr.useEffect)(()=>{let Gt=async(yi,ys,yd)=>{let Al;if(t.getContentGeneratorConfig().authType===ln.LOGIN_WITH_GITHUB){let gl=Ca===zh.LEGACY||Ca===zh.STANDARD;yd&&nb(yd)?gl?Al=De.t("app.flashFallback.proQuotaExceeded",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeQuotaExceeded",{currentModel:yi,fallbackModel:ys}):yd&&nR(yd)?gl?Al=De.t("app.flashFallback.proGenericQuota",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeGenericQuota",{currentModel:yi,fallbackModel:ys}):gl?Al=De.t("app.flashFallback.proDefault",{currentModel:yi,fallbackModel:ys}):Al=De.t("app.flashFallback.freeDefault",{currentModel:yi,fallbackModel:ys}),c({type:"info",text:Al},Date.now()),Di(!0),t.setQuotaErrorOccurred(!0)}return t.setModel(ys),t.setFallbackMode(!0),Dle(t,new eF(t.getContentGeneratorConfig().authType)),!1};t.setFlashFallbackHandler(Gt)},[t,c,Ca]);let{rows:Fe,columns:Xe}=gg(),lt=Sb(Xe),{stdin:Et,setRawMode:Rt}=v8(),$t=(0,Dr.useRef)(!0),zt=Math.max(20,Math.floor(Xe*.9)-3),Xt=Math.max(20,Math.floor(Xe*.8)),ar=(0,Dr.useCallback)(Gt=>{try{return u6e.existsSync(Gt)&&u6e.statSync(Gt).isFile()}catch{return!1}},[]),tn=(0,Dr.useCallback)(()=>{let Gt=e.merged.preferredEditor;if(!_J(Gt)){Tu();return}return Gt},[e,Tu]),Pi=(0,Dr.useCallback)(()=>{ae(De.t("app.auth.reauthRequired")),Vn()},[Vn,ae]),{vimEnabled:Es,vimMode:ui,toggleVimEnabled:Do}=MH(),{handleSlashCommand:Us,slashCommands:Ic,pendingHistoryItems:hl,commandContext:N2,shellConfirmationRequest:xp,confirmationRequest:Ed}=Ior(t,e,c,d,h,B,$,Ad,Vn,Tu,ot,Mo,xe,hr,x1,Do,wr,W),zd=uur({initialText:"",viewport:{height:10,width:zt},stdin:Et,setRawMode:Rt,isValidPath:ar,shellModeActive:X}),[Pm,Qm]=(0,Dr.useState)([]),xu=(0,Dr.useCallback)(()=>{let Gt=Pm.at(-1);Gt&&zd.setText(Gt)},[zd,Pm]),{streamingState:Yu,submitQuery:Tc,initError:Kd,pendingHistoryItems:Sf,thought:x0,cancelOngoingRequest:xc,activeActivity:Z6}=Inr(t.getGeminiClient(),u,c,t,$,Us,X,tn,Pi,Re,gi,Di,B,xu);(0,Dr.useEffect)(()=>{Yu==="idle"&&(async()=>{try{let Gt=await GYe();Gt&&Pr(Gt)}catch{}})()},[Yu,Pr]);let B0=(0,Dr.useCallback)(Gt=>{let yi=Gt.trim();yi.length>0&&Tc(yi)},[Tc]),e4=(0,Dr.useCallback)(Gt=>{Gt.userSelection==="yes"?(Gt.isExtensionPreInstalled?Us("/ide enable"):Us("/ide install"),e.setValue("User","hasSeenIdeIntegrationNudge",!0)):Gt.userSelection==="dismiss"&&e.setValue("User","hasSeenIdeIntegrationNudge",!0),E(!0)},[Us,e]),{handleInput:t4}=Hfr(zd,B0),Wu=[...hl];Wu.push(...Sf);let{elapsedTime:D3,currentLoadingPhrase:r4}=Bnr(Yu,Z6),O2=Tor({config:t}),S3=ige(),R1=(0,Dr.useCallback)((Gt,yi,ys)=>{Gt?(ys.current&&clearTimeout(ys.current),Us("/quit")):(yi(!0),ys.current=setTimeout(()=>{yi(!1),ys.current=null},_jn))},[Us]),km=(0,Dr.useCallback)(Gt=>{let yi=!1;if(vt||(yi=!0,Ut(!0)),ns.showErrorDetails(Gt))me(ys=>!ys);else if(ns.toggleToolDescriptions(Gt)){let ys=!ue;Ce(ys);let yd=t.getMcpServers();Object.keys(yd||{}).length>0&&Us(ys?"/mcp desc":"/mcp nodesc")}else if(ns.toggleIDEContextDetail(Gt)&&t.getIdeMode()&&Be)Us("/ide status");else if(ns.quit(Gt)){if(Li)return;te||xc?.(),R1(te,H,He)}else if(ns.exit(Gt)){if(zd.text.length>0)return;R1(mt,xt,Yt)}else ns.showMoreLines(Gt)&&!yi&&Ut(!1)},[vt,Ut,me,ue,Ce,t,Be,R1,te,H,He,zd.text.length,mt,xt,Yt,Us,Li,xc]);ts(km,{isActive:!0,kittyProtocolEnabled:S3.enabled,config:t}),(0,Dr.useEffect)(()=>{t&&W(t.getGeminiMdFileCount())},[t,t.getGeminiMdFileCount]);let Bc=RAe();(0,Dr.useEffect)(()=>{(async()=>{let yi=await Bc?.getPreviousUserMessages()||[],yd=[...u.filter(gl=>gl.type==="user"&&typeof gl.text=="string"&&gl.text.trim()!=="").map(gl=>gl.text).reverse(),...yi],Al=[];if(yd.length>0){Al.push(yd[0]);for(let gl=1;gl<yd.length;gl++)yd[gl]!==yd[gl-1]&&Al.push(yd[gl])}Qm(Al.reverse())})()},[u,Bc]);let F2=Yu==="idle"&&!Kd&&!mr,Bp=(0,Dr.useCallback)(()=>{d(),S(),console.clear(),B()},[d,S,B]),bf=(0,Dr.useRef)(null),n4=(0,Dr.useRef)(null);(0,Dr.useEffect)(()=>{if(bf.current){let Gt=P3e(bf.current);he(Gt.height)}},[Fe,C,ie]);let $5=3,b3=(0,Dr.useMemo)(()=>Fe-ne-$5,[Fe,ne]);(0,Dr.useEffect)(()=>{if($t.current){$t.current=!1;return}let Gt=setTimeout(()=>{M(!1),B()},300);return()=>{clearTimeout(Gt)}},[Xe,Fe,B]),(0,Dr.useEffect)(()=>{Yu==="idle"&&N&&(M(!1),B())},[Yu,B,N]);let M2=(0,Dr.useMemo)(()=>t.getDebugMode()?C:C.filter(Gt=>Gt.type!=="debug"),[C,t]),R0=Ffr(t.getTargetDir()),N0=(0,Dr.useMemo)(()=>{let Gt=e.merged.contextFileName;return Gt?Array.isArray(Gt)?Gt:[Gt]:MS()},[e.merged.contextFileName]),ci=(0,Dr.useMemo)(()=>t.getQuestion(),[t]),Kt=t.getGeminiClient();if((0,Dr.useEffect)(()=>{ci&&!lo.current&&!Li&&!gs&&!wc&&!Ri&&!dn&&Kt?.isInitialized?.()&&(Tc(ci),lo.current=!0)},[ci,Tc,Li,gs,wc,Ri,dn,Kt]),ge)return(0,_r.jsx)(Le,{flexDirection:"column",marginBottom:1,children:ge.map(Gt=>(0,_r.jsx)(i6e,{availableTerminalHeight:vt?b3:void 0,terminalWidth:Xe,item:Gt,isPending:!1,config:t},Gt.id))});let Rc=Math.floor(Xe*.9),Um=Math.floor(Math.max(Fe*.2,5)),ss=Math.max(Fe*4,100),Nc=Es?De.t("app.placeholders.vim"):De.t("app.placeholders.default");return(0,_r.jsx)(J$e.Provider,{value:Yu,children:(0,_r.jsxs)(Le,{flexDirection:"column",width:"90%",children:[(0,_r.jsx)(Gee,{items:[(0,_r.jsxs)(Le,{flexDirection:"column",children:[!e.merged.hideBanner&&(0,_r.jsx)(qlr,{version:n,nightly:l}),!e.merged.hideTips&&(0,_r.jsx)(j1r,{config:t})]},"header"),...u.map(Gt=>(0,_r.jsx)(i6e,{terminalWidth:Rc,availableTerminalHeight:ss,item:Gt,isPending:!1,config:t,commands:Ic},Gt.id))],children:Gt=>Gt},U),(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{ref:n4,flexDirection:"column",children:[Wu.map((Gt,yi)=>(0,_r.jsx)(i6e,{availableTerminalHeight:vt?b3:void 0,terminalWidth:Rc,item:{...Gt,id:0},isPending:!0,config:t,isFocused:!Ri},yi)),(0,_r.jsx)(a6e,{constrainHeight:vt})]})}),(0,_r.jsxs)(Le,{flexDirection:"column",ref:bf,children:[a&&(0,_r.jsx)(Gfr,{message:a.message}),r.length>0&&(0,_r.jsx)(Le,{borderStyle:"round",borderColor:ke.AccentYellow,paddingX:1,marginY:1,flexDirection:"column",children:r.map((Gt,yi)=>(0,_r.jsx)(be,{color:ke.AccentYellow,children:Gt},yi))}),g&&y?(0,_r.jsx)(Rfr,{ide:y,onComplete:e4}):ju?(0,_r.jsx)(hir,{onSelect:_o}):xp?(0,_r.jsx)(Rdr,{request:xp}):Ed?(0,_r.jsxs)(Le,{flexDirection:"column",children:[Ed.prompt,(0,_r.jsx)(Le,{paddingY:1,children:(0,_r.jsx)(Kl,{items:[{label:De.t("app.confirmation.yes"),value:!0},{label:De.t("app.confirmation.no"),value:!1}],onSelect:Gt=>{Ed.onConfirm(Gt)}})})]}):wc?(0,_r.jsxs)(Le,{flexDirection:"column",children:[R&&(0,_r.jsx)(Le,{marginBottom:1,children:(0,_r.jsx)(be,{color:ke.AccentRed,children:R})}),(0,_r.jsx)(Ddr,{onSelect:gd,onHighlight:wu,settings:e,availableTerminalHeight:vt?Fe-$5:void 0,terminalWidth:Rc})]}):uo?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Kfr,{settings:e,onSelect:()=>B1(),onRestartRequest:()=>VYe.exit(0)})}):$e?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(bdr,{onSubmit:Da,onCancel:da,error:ks,busy:Ei,initialValues:_a??void 0,mode:Ts})}):Ke?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Sdr,{settings:e,models:st,loading:fr,error:Qr,unauthorizedUserError:Wn,onSelect:li,onEdit:yn,onDelete:Mi,onExit:Ct})}):Li?(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Tdr,{onTimeout:()=>{ae(De.t("app.auth.timeout")),zn(),Vn()},verificationUri:Iu,userCode:co}),ie&&(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{flexDirection:"column",children:[(0,_r.jsx)(NYe,{messages:M2,maxHeight:vt?Um:void 0,width:zt}),(0,_r.jsx)(a6e,{constrainHeight:vt})]})})]}):gs?(0,_r.jsx)(Le,{flexDirection:"column",children:(0,_r.jsx)(Idr,{onSelect:Xo,settings:e,initialErrorMessage:J})}):Ri?(0,_r.jsxs)(Le,{flexDirection:"column",children:[fe&&(0,_r.jsx)(Le,{marginBottom:1,children:(0,_r.jsx)(be,{color:ke.AccentRed,children:fe})}),(0,_r.jsx)(Bdr,{onSelect:Xs,settings:e,onExit:as})]}):dn?(0,_r.jsx)(Yfr,{onExit:()=>ei(!1),config:t}):(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Klr,{thought:Yu==="waiting_for_confirmation"||t.getAccessibility()?.disableLoadingPhrases?void 0:x0,currentLoadingPhrase:t.getAccessibility()?.disableLoadingPhrases?void 0:r4,elapsedTime:D3}),(0,_r.jsxs)(Le,{marginTop:1,justifyContent:"space-between",width:"100%",flexDirection:lt?"column":"row",alignItems:lt?"flex-start":"center",children:[(0,_r.jsxs)(Le,{children:[VYe.env.GEMINI_SYSTEM_MD&&(0,_r.jsx)(be,{color:ke.AccentRed,children:"|\u2310\u25A0_\u25A0| "}),te?(0,_r.jsx)(be,{color:ke.AccentYellow,children:De.t("app.prompts.pressCtrlCAgain")}):mt?(0,_r.jsx)(be,{color:ke.AccentYellow,children:De.t("app.prompts.pressCtrlDAgain")}):nt?(0,_r.jsx)(be,{color:ke.Gray,children:De.t("app.prompts.pressEscAgain")}):(0,_r.jsx)(xfr,{ideContext:Be,geminiMdFileCount:q,contextFileNames:N0,mcpServers:t.getMcpServers(),blockedMcpServers:t.getBlockedMcpServers(),showToolDescriptions:ue})]}),(0,_r.jsxs)(Le,{paddingTop:lt?1:0,children:[O2!==qa.DEFAULT&&!X&&(0,_r.jsx)(Jlr,{approvalMode:O2}),X&&(0,_r.jsx)(Xlr,{})]})]}),ie&&(0,_r.jsx)(Ege,{children:(0,_r.jsxs)(Le,{flexDirection:"column",children:[(0,_r.jsx)(NYe,{messages:M2,maxHeight:vt?Um:void 0,width:zt}),(0,_r.jsx)(a6e,{constrainHeight:vt})]})}),F2&&(0,_r.jsx)(wur,{buffer:zd,inputWidth:zt,suggestionsWidth:Xt,onSubmit:B0,userMessages:Pm,onClearScreen:Bp,config:t,slashCommands:Ic,commandContext:N2,shellModeActive:X,setShellModeActive:ee,onEscapePromptChange:Mr,focus:i,vimHandleInput:t4,placeholder:Nc})]}),Kd&&Yu!=="responding"&&(0,_r.jsx)(Le,{borderStyle:"round",borderColor:ke.AccentRed,paddingX:1,marginBottom:1,children:u.find(Gt=>Gt.type==="error"&&Gt.text?.includes(Kd))?.text?(0,_r.jsx)(be,{color:ke.AccentRed,children:u.find(Gt=>Gt.type==="error"&&Gt.text?.includes(Kd))?.text}):(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(be,{color:ke.AccentRed,children:De.t("app.init.error",{error:Kd})}),(0,_r.jsx)(be,{color:ke.AccentRed,children:De.t("app.init.checkConfig")})]})}),(0,_r.jsx)(Our,{model:se,targetDir:t.getTargetDir(),debugMode:t.getDebugMode(),branchName:R0,debugMessage:re,corgiMode:Ee,errorCount:xl,showErrorDetails:ie,showMemoryUsage:t.getDebugMode()||e.merged.showMemoryUsage||!1,promptTokenCount:w.lastPromptTokenCount,nightly:l,vimMode:Es?ui:void 0,isTrustedFolder:_e,trialRequestsUsed:le,trialRequestsLimit:Y})]})]})})};async function n0r(){return new Promise((e,r)=>{let n="",i=0;process.stdin.setEncoding("utf8");let a=()=>{let u;for(;(u=process.stdin.read())!==null;){if(i+u.length>8388608){let c=8388608-i;n+=u.slice(0,c),console.warn("Warning: stdin input truncated to 8388608 bytes."),process.stdin.destroy();break}n+=u,i+=u.length}},s=()=>{l(),e(n)},o=u=>{l(),r(u)},l=()=>{process.stdin.removeListener("readable",a),process.stdin.removeListener("end",s),process.stdin.removeListener("error",o)};process.stdin.on("readable",a),process.stdin.on("end",s),process.stdin.on("error",o)})}import{basename as mei}from"node:path";import hei from"node:v8";import Aei from"node:os";import gei from"node:dns";import{spawn as Eei}from"node:child_process";var UX=Ve(Lpe(),1);import{exec as Sjn,execSync as kb,spawn as QH}from"node:child_process";import C3 from"node:os";import Q5 from"node:path";import I1 from"node:fs";import{readFile as bjn}from"node:fs/promises";import{promisify as wjn}from"util";var qYe=wjn(Sjn);function oA(t){if(C3.platform()!=="win32")return t;let r=t.replace(/\\/g,"/").match(/^([A-Z]):\/(.*)/i);return r?`/${r[1].toLowerCase()}/${r[2]}`:t}var a0r="gemini-cli-sandbox",c6e="gemini-cli-sandbox",nN="gemini-cli-sandbox-proxy",Ijn=["permissive-open","permissive-closed","permissive-proxied","restrictive-open","restrictive-closed","restrictive-proxied"];async function Tjn(){let t=process.env.SANDBOX_SET_UID_GID?.toLowerCase().trim();if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;if(C3.platform()==="linux")try{let e=await bjn("/etc/os-release","utf8");if(e.includes("ID=debian")||e.includes("ID=ubuntu")||e.match(/^ID_LIKE=.*debian.*/m)||e.match(/^ID_LIKE=.*ubuntu.*/m))return console.error("INFO: Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux."),!0}catch{console.warn("Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.")}return!1}function xjn(t){let[e,r]=t.split(":"),n=e.split("/").at(-1)??"unknown-image";return r?`${n}-${r}`:n}function s0r(){return(process.env.SANDBOX_PORTS??"").split(",").filter(t=>t.trim()).map(t=>t.trim())}function Bjn(t){let e=C3.platform()==="win32",r=oA(t),n=[],i=e?";":":",a="";if(process.env.PATH){let d=process.env.PATH.split(i);for(let h of d){let f=oA(h);f.toLowerCase().startsWith(r.toLowerCase())&&(a+=`:${f}`)}}a&&n.push(`export PATH="$PATH${a}";`);let s="";if(process.env.PYTHONPATH){let d=process.env.PYTHONPATH.split(i);for(let h of d){let f=oA(h);f.toLowerCase().startsWith(r.toLowerCase())&&(s+=`:${f}`)}}s&&n.push(`export PYTHONPATH="$PYTHONPATH${s}";`);let o=Q5.join(q7,"sandbox.bashrc");I1.existsSync(o)&&n.push(`source ${oA(o)};`),s0r().forEach(d=>n.push(`socat TCP4-LISTEN:${d},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${d} 2> /dev/null &`));let l=process.argv.slice(2).map(d=>(0,UX.quote)([d])),u=process.env.NODE_ENV==="development"?process.env.DEBUG?"npm run debug --":"npm rebuild && npm run start --":process.env.DEBUG?`node --inspect-brk=0.0.0.0:${process.env.DEBUG_PORT||"9229"} $(which gemini)`:"gemini";return["bash","-c",[...n,u,...l].join(" ")]}async function o0r(t,e=[],r){let n=new L5({debugMode:r?.getDebugMode()||!!process.env.DEBUG,stderr:!0});n.patch();try{if(t.command==="sandbox-exec"){process.env.BUILD_SANDBOX&&(console.error("ERROR: cannot BUILD_SANDBOX when using macOS Seatbelt"),process.exit(1));let B=process.env.SEATBELT_PROFILE??="permissive-open",q=new URL(`sandbox-macos-${B}.sb`,import.meta.url).pathname;Ijn.includes(B)||(q=Q5.join(q7,`sandbox-macos-${B}.sb`)),I1.existsSync(q)||(console.error(`ERROR: missing macos seatbelt profile file '${q}'`),process.exit(1)),console.error(`using macos seatbelt (profile: ${B}) ...`);let W=[...process.env.DEBUG?["--inspect-brk"]:[],...e].join(" "),re=["-D",`TARGET_DIR=${I1.realpathSync(process.cwd())}`,"-D",`TMP_DIR=${I1.realpathSync(C3.tmpdir())}`,"-D",`HOME_DIR=${I1.realpathSync(C3.homedir())}`,"-D",`CACHE_DIR=${I1.realpathSync(kb("getconf DARWIN_USER_CACHE_DIR").toString().trim())}`],$=5,R=I1.realpathSync(r?.getTargetDir()||""),Q=[];if(r){let he=r.getWorkspaceContext().getDirectories();for(let Ee of he){let pe=I1.realpathSync(Ee);pe!==R&&Q.push(pe)}}for(let ne=0;ne<$;ne++){let he="/dev/null";ne<Q.length&&(he=Q[ne]),re.push("-D",`INCLUDE_DIR_${ne}=${he}`)}re.push("-f",q,"sh","-c",["SANDBOX=sandbox-exec",`NODE_OPTIONS="${W}"`,...process.argv.map(ne=>(0,UX.quote)([ne]))].join(" "));let J=process.env.GEMINI_SANDBOX_PROXY_COMMAND,ae,fe,K={...process.env};if(J){let ne=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||"http://localhost:8877";K.HTTPS_PROXY=ne,K.https_proxy=ne,K.HTTP_PROXY=ne,K.http_proxy=ne;let he=process.env.NO_PROXY||process.env.no_proxy;he&&(K.NO_PROXY=he,K.no_proxy=he),ae=QH(J,{stdio:["ignore","pipe","pipe"],shell:!0,detached:!0});let Ee=()=>{console.log("stopping proxy ..."),ae?.pid&&process.kill(-ae.pid,"SIGTERM")};process.on("exit",Ee),process.on("SIGINT",Ee),process.on("SIGTERM",Ee),ae.stderr?.on("data",pe=>{console.error(pe.toString())}),ae.on("close",(pe,_e)=>{console.error(`ERROR: proxy command '${J}' exited with code ${pe}, signal ${_e}`),fe?.pid&&process.kill(-fe.pid,"SIGTERM"),process.exit(1)}),console.log("waiting for proxy to start ..."),await qYe("until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done")}fe=QH(t.command,re,{stdio:"inherit"}),await new Promise(ne=>fe?.on("close",ne));return}console.error(`hopping into sandbox (command: ${t.command}) ...`);let i=I1.realpathSync(process.argv[1]),a=Q5.join(q7,"sandbox.Dockerfile"),s=I1.existsSync(a),o=t.image,l=Q5.resolve(process.cwd()),u=oA(l);if(process.env.BUILD_SANDBOX)if(!i.includes("gemini-cli/packages/"))console.error("ERROR: cannot build sandbox using installed gemini binary; run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary."),process.exit(1);else{console.error("building sandbox ...");let B=i.split("/packages/")[0],q="",W=Q5.join(q7,"sandbox.Dockerfile");s&&(console.error(`using ${W} for sandbox`),q+=`-f ${Q5.resolve(W)} -i ${o}`),kb(`cd ${B} && node scripts/build_sandbox.js -s ${q}`,{stdio:"inherit",env:{...process.env,GEMINI_SANDBOX:t.command}})}await Njn(t.command,o)||(console.error(`ERROR: Sandbox image '${o}' is missing or could not be pulled. ${o===a0r?"Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection.":"Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists."}`),process.exit(1));let c=["run","-i","--rm","--init","--workdir",u];if(process.env.SANDBOX_FLAGS){let B=(0,UX.parse)(process.env.SANDBOX_FLAGS,process.env).filter(q=>typeof q=="string");c.push(...B)}process.stdin.isTTY&&c.push("-t"),c.push("--volume",`${l}:${u}`);let d=bqe,h=oA(`/home/node/${q7}`);I1.existsSync(d)||I1.mkdirSync(d),c.push("--volume",`${d}:${h}`),h!==d&&c.push("--volume",`${d}:${oA(d)}`),c.push("--volume",`${C3.tmpdir()}:${oA(C3.tmpdir())}`);let f=Q5.join(C3.homedir(),".config","gcloud");if(I1.existsSync(f)&&c.push("--volume",`${f}:${oA(f)}:ro`),process.env.GOOGLE_APPLICATION_CREDENTIALS){let B=process.env.GOOGLE_APPLICATION_CREDENTIALS;I1.existsSync(B)&&(c.push("--volume",`${B}:${oA(B)}:ro`),c.push("--env",`GOOGLE_APPLICATION_CREDENTIALS=${oA(B)}`))}if(process.env.SANDBOX_MOUNTS){for(let B of process.env.SANDBOX_MOUNTS.split(","))if(B.trim()){let[q,W,re]=B.trim().split(":");W=W||q,re=re||"ro",B=`${q}:${W}:${re}`,Q5.isAbsolute(q)||(console.error(`ERROR: path '${q}' listed in SANDBOX_MOUNTS must be absolute`),process.exit(1)),I1.existsSync(q)||(console.error(`ERROR: missing mount path '${q}' listed in SANDBOX_MOUNTS`),process.exit(1)),console.error(`SANDBOX_MOUNTS: ${q} -> ${W} (${re})`),c.push("--volume",B)}}if(s0r().forEach(B=>c.push("--publish",`${B}:${B}`)),process.env.DEBUG){let B=process.env.DEBUG_PORT||"9229";c.push("--publish",`${B}:${B}`)}let E=process.env.GEMINI_SANDBOX_PROXY_COMMAND;if(E){let B=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy||"http://localhost:8877";B=B.replace("localhost",nN),B&&(c.push("--env",`HTTPS_PROXY=${B}`),c.push("--env",`https_proxy=${B}`),c.push("--env",`HTTP_PROXY=${B}`),c.push("--env",`http_proxy=${B}`));let q=process.env.NO_PROXY||process.env.no_proxy;q&&(c.push("--env",`NO_PROXY=${q}`),c.push("--env",`no_proxy=${q}`)),B&&(kb(`${t.command} network inspect ${c6e} || ${t.command} network create --internal ${c6e}`),c.push("--network",c6e),E&&kb(`${t.command} network inspect ${nN} || ${t.command} network create ${nN}`))}let y=xjn(o),g=0,C=kb(`${t.command} ps -a --format "{{.Names}}"`).toString().trim();for(;C.includes(`${y}-${g}`);)g++;let D=`${y}-${g}`;c.push("--name",D,"--hostname",D),process.env.KODA_API_KEY&&c.push("--env",`KODA_API_KEY=${process.env.KODA_API_KEY}`),process.env.GOOGLE_API_KEY&&c.push("--env",`GOOGLE_API_KEY=${process.env.GOOGLE_API_KEY}`),process.env.GOOGLE_GENAI_USE_VERTEXAI&&c.push("--env",`GOOGLE_GENAI_USE_VERTEXAI=${process.env.GOOGLE_GENAI_USE_VERTEXAI}`),process.env.GOOGLE_GENAI_USE_GCA&&c.push("--env",`GOOGLE_GENAI_USE_GCA=${process.env.GOOGLE_GENAI_USE_GCA}`),process.env.GOOGLE_CLOUD_PROJECT&&c.push("--env",`GOOGLE_CLOUD_PROJECT=${process.env.GOOGLE_CLOUD_PROJECT}`),process.env.GOOGLE_CLOUD_LOCATION&&c.push("--env",`GOOGLE_CLOUD_LOCATION=${process.env.GOOGLE_CLOUD_LOCATION}`),process.env.GEMINI_MODEL&&c.push("--env",`GEMINI_MODEL=${process.env.GEMINI_MODEL}`),process.env.KODA_RESPONSE_LANGUAGE&&c.push("--env",`KODA_RESPONSE_LANGUAGE=${process.env.KODA_RESPONSE_LANGUAGE}`),process.env.TERM&&c.push("--env",`TERM=${process.env.TERM}`),process.env.COLORTERM&&c.push("--env",`COLORTERM=${process.env.COLORTERM}`);for(let B of["KODA_CLI_IDE_SERVER_PORT","GEMINI_CLI_IDE_SERVER_PORT","GEMINI_CLI_IDE_WORKSPACE_PATH","TERM_PROGRAM"])process.env[B]&&c.push("--env",`${B}=${process.env[B]}`);if(process.env.VIRTUAL_ENV?.toLowerCase().startsWith(l.toLowerCase())){let B=Q5.resolve(q7,"sandbox.venv");I1.existsSync(B)||I1.mkdirSync(B,{recursive:!0}),c.push("--volume",`${B}:${oA(process.env.VIRTUAL_ENV)}`),c.push("--env",`VIRTUAL_ENV=${oA(process.env.VIRTUAL_ENV)}`)}if(process.env.SANDBOX_ENV)for(let B of process.env.SANDBOX_ENV.split(","))(B=B.trim())&&(B.includes("=")?(console.error(`SANDBOX_ENV: ${B}`),c.push("--env",B)):(console.error("ERROR: SANDBOX_ENV must be a comma-separated list of key=value pairs"),process.exit(1)));let S=process.env.NODE_OPTIONS||"",w=[...S?[S]:[],...e].join(" ");if(w.length>0&&c.push("--env",`NODE_OPTIONS="${w}"`),c.push("--env",`SANDBOX=${D}`),t.command==="podman"){let B=Q5.join(C3.tmpdir(),"empty_auth.json");I1.writeFileSync(B,"{}","utf-8"),c.push("--authfile",B)}let N="",M=Bjn(l);if(process.env.GEMINI_CLI_INTEGRATION_TEST==="true")c.push("--user","root"),N="--user root";else if(await Tjn()){c.push("--user","root");let B=kb("id -u").toString().trim(),q=kb("id -g").toString().trim(),W="gemini",re=oA(C3.homedir()),$=[`groupadd -f -g ${q} ${W}`,`id -u ${W} &>/dev/null || useradd -o -u ${B} -g ${q} -d ${re} -s /bin/bash ${W}`].join(" && "),Q=M[2].replace(/'/g,"'\\''"),J=`su -p ${W} -c '${Q}'`;M[2]=`${$} && ${J}`,N=`--user ${B}:${q}`,c.push("--env",`HOME=${C3.homedir()}`)}c.push(o),c.push(...M);let U,k;if(E){let B=`${t.command} run --rm --init ${N} --name ${nN} --network ${nN} -p 8877:8877 -v ${process.cwd()}:${l} --workdir ${l} ${o} ${E}`;U=QH(B,{stdio:["ignore","pipe","pipe"],shell:!0,detached:!0});let q=()=>{console.log("stopping proxy container ..."),kb(`${t.command} rm -f ${nN}`)};process.on("exit",q),process.on("SIGINT",q),process.on("SIGTERM",q),U.stderr?.on("data",W=>{console.error(W.toString().trim())}),U.on("close",(W,re)=>{console.error(`ERROR: proxy container command '${B}' exited with code ${W}, signal ${re}`),k?.pid&&process.kill(-k.pid,"SIGTERM"),process.exit(1)}),console.log("waiting for proxy to start ..."),await qYe("until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done"),await qYe(`${t.command} network connect ${c6e} ${nN}`)}k=QH(t.command,c,{stdio:"inherit"}),k.on("error",B=>{console.error("Sandbox process error:",B)}),await new Promise(B=>{k?.on("close",(q,W)=>{q!==0&&console.log(`Sandbox process exited with code: ${q}, signal: ${W}`),B()})})}finally{n.cleanup()}}async function i0r(t,e){return new Promise(r=>{let i=QH(t,["images","-q",e]),a="";i.stdout&&i.stdout.on("data",s=>{a+=s.toString()}),i.on("error",s=>{console.warn(`Failed to start '${t}' command for image check: ${s.message}`),r(!1)}),i.on("close",s=>{r(a.trim()!=="")})})}async function Rjn(t,e){return console.info(`Attempting to pull image ${e} using ${t}...`),new Promise(r=>{let i=QH(t,["pull",e],{stdio:"pipe"}),a="",s=d=>{console.info(d.toString().trim())},o=d=>{a+=d.toString(),console.error(d.toString().trim())},l=d=>{console.warn(`Failed to start '${t} pull ${e}' command: ${d.message}`),c(),r(!1)},u=d=>{d===0?(console.info(`Successfully pulled image ${e}.`),c(),r(!0)):(console.warn(`Failed to pull image ${e}. '${t} pull ${e}' exited with code ${d}.`),a.trim(),c(),r(!1))},c=()=>{i.stdout&&i.stdout.removeListener("data",s),i.stderr&&i.stderr.removeListener("data",o),i.removeListener("error",l),i.removeListener("close",u),i.connected&&i.disconnect()};i.stdout&&i.stdout.on("data",s),i.stderr&&i.stderr.on("data",o),i.on("error",l),i.on("close",u)})}async function Njn(t,e){return console.info(`Checking for sandbox image: ${e}`),await i0r(t,e)?(console.info(`Sandbox image ${e} found locally.`),!0):(console.info(`Sandbox image ${e} not found locally.`),e===a0r?!1:await Rjn(t,e)?await i0r(t,e)?(console.info(`Sandbox image ${e} is now available after pulling.`),!0):(console.warn(`Sandbox image ${e} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`),!1):(console.error(`Failed to obtain sandbox image ${e} after check and pull attempt.`),!1))}Hn();import $Ye from"fs/promises";import Ojn from"os";import{join as Fjn}from"node:path";var jYe=Fjn(Ojn.tmpdir(),"gemini-cli-warnings.txt");async function l0r(){try{await $Ye.access(jYe);let e=(await $Ye.readFile(jYe,"utf-8")).split(`
2037
2037
  `).filter(r=>r.trim()!=="");try{await $Ye.unlink(jYe)}catch{e.push("Warning: Could not delete temporary warnings file.")}return e}catch(t){return t instanceof Error&&"code"in t&&t.code==="ENOENT"?[]:[`Error checking/reading warnings file: ${sr(t)}`]}}import YYe from"fs/promises";import*as u0r from"os";import Mjn from"path";var Ljn={id:"home-directory",check:async t=>{try{let[e,r]=await Promise.all([YYe.realpath(t),YYe.realpath(u0r.homedir())]);return e===r?De.t("startupWarnings.homeDirectory.message"):null}catch{return De.t("startupWarnings.fileSystemError.message")}}},Pjn={id:"root-directory",check:async t=>{try{let e=await YYe.realpath(t);return Mjn.dirname(e)===e?De.t("startupWarnings.rootDirectory.message"):null}catch{return De.t("startupWarnings.fileSystemError.message")}}},Qjn=[Ljn,Pjn];async function c0r(t){return(await Promise.all(Qjn.map(r=>r.check(t)))).filter(r=>r!==null)}Hn();async function d0r(t,e,r){let n=new L5({stderr:!0,debugMode:t.getDebugMode()});try{n.patch(),process.stdout.on("error",d=>{d.code==="EPIPE"&&process.exit(0)});let i=t.getGeminiClient(),a=await t.getToolRegistry(),s={},o=["search_file_content","list_directory","glob","google_web_search","save_memory","run_shell_command"];for(let d of o){let h=`toolDescriptions.${d}`,f=De.t(h);f&&f!==h&&(s[d]=f)}Object.keys(s).length>0&&a.updateToolDescriptions(s);let l=new AbortController,u=[{role:"user",parts:[{text:e}]}],c=0;for(;;){if(c++,t.getMaxSessionTurns()>=0&&c>t.getMaxSessionTurns()){console.error(`
2038
2038
  Reached max session turns for this session. Increase the number of turns by specifying maxSessionTurns in settings.json.`);return}let d=[],h=i.sendMessageStream(u[0]?.parts||[],l.signal,r);for await(let f of h){if(l.signal.aborted){console.error("Operation cancelled.");return}if(f.type===$s.Content)process.stdout.write(f.value);else if(f.type===$s.ToolCallRequest){let E=f.value,y={name:E.name,args:E.args,id:E.callId};d.push(y)}}if(d.length>0){let f=[];for(let y of d){let C={callId:y.id??`${y.name}-${Date.now()}`,name:y.name,args:y.args??{},isClientInitiated:!1,prompt_id:r},D=await GGe(t,C,a,l.signal);if(D.error&&(console.error(`Error executing tool ${y.name}: ${D.resultDisplay||D.error.message}`),D.errorType===ms.UNHANDLED_EXCEPTION&&process.exit(1)),D.responseParts){let S=Array.isArray(D.responseParts)?D.responseParts:[D.responseParts];for(let w of S)typeof w=="string"?f.push({text:w}):w&&f.push(w)}}let E=f.map(y=>({role:"tool",parts:[y]}));u=E.length>0?E:[{role:"user",parts:f}]}else{process.stdout.write(`
2039
2039
  `);return}}}catch(i){console.error(MU(i,t.getContentGeneratorConfig()?.authType)),process.exit(1)}finally{n.cleanup(),tf()&&await mL(t)}}Hn();Hn();function kjn(){return process.env.GOOGLE_GENAI_USE_GCA==="true"?ln.LOGIN_WITH_GITHUB:ln.WITHOUT_AUTH}async function p0r(t,e,r){let n=t||kjn();if(!n)return console.warn("No authentication method configured. Proceeding without authentication. You can authenticate later through the menu."),r;if(!e){let i=Bb(n);i!=null&&(console.error(i),process.exit(1))}return await r.refreshAuth(n),r}import EN from"node:process";import{spawn as jXn}from"node:child_process";import{fileURLToPath as YXn}from"node:url";import Ygr from"node:path";import{format as Sze}from"node:util";var qX=Ve(D0r(),1);import VX from"node:path";import iYn from"node:os";import Kjn from"os";import h6e from"path";var Hb=Kjn.homedir(),{env:aN}=process,S0r=aN.XDG_DATA_HOME||(Hb?h6e.join(Hb,".local","share"):void 0),UH=aN.XDG_CONFIG_HOME||(Hb?h6e.join(Hb,".config"):void 0),cda=aN.XDG_STATE_HOME||(Hb?h6e.join(Hb,".local","state"):void 0),dda=aN.XDG_CACHE_HOME||(Hb?h6e.join(Hb,".cache"):void 0),pda=aN.XDG_RUNTIME_DIR||void 0,Jjn=(aN.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");S0r&&Jjn.unshift(S0r);var Xjn=(aN.XDG_CONFIG_DIRS||"/etc/xdg").split(":");UH&&Xjn.unshift(UH);import rYn from"node:path";import Qs from"node:fs";import{promisify as w0}from"node:util";var J7=(t,e)=>function(...n){return t.apply(void 0,n).catch(e)},k5=(t,e)=>function(...n){try{return t.apply(void 0,n)}catch(i){return e(i)}};import b0r from"node:process";var w0r=b0r.getuid?!b0r.getuid():!1,I0r=1e4,lA=()=>{};var HX={isChangeErrorOk:t=>{if(!HX.isNodeError(t))return!1;let{code:e}=t;return e==="ENOSYS"||!w0r&&(e==="EINVAL"||e==="EPERM")},isNodeError:t=>t instanceof Error,isRetriableError:t=>{if(!HX.isNodeError(t))return!1;let{code:e}=t;return e==="EMFILE"||e==="ENFILE"||e==="EAGAIN"||e==="EBUSY"||e==="EACCESS"||e==="EACCES"||e==="EACCS"||e==="EPERM"},onChangeError:t=>{if(!HX.isNodeError(t))throw t;if(!HX.isChangeErrorOk(t))throw t}},hd=HX;var XYe=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=I0r,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=e=>{this.queueWaiting.add(e),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=e=>{this.queueWaiting.delete(e),this.queueActive.delete(e)},this.schedule=()=>new Promise(e=>{let r=()=>this.remove(n),n=()=>e(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let e of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(e),this.queueActive.add(e),e()}}}}},T0r=new XYe;var X7=(t,e)=>function(n){return function i(...a){return T0r.schedule().then(s=>{let o=u=>(s(),u),l=u=>{if(s(),Date.now()>=n)throw u;if(e(u)){let c=Math.round(100*Math.random());return new Promise(h=>setTimeout(h,c)).then(()=>i.apply(void 0,a))}throw u};return t.apply(void 0,a).then(o,l)})}},Z7=(t,e)=>function(n){return function i(...a){try{return t.apply(void 0,a)}catch(s){if(Date.now()>n)throw s;if(e(s))return i.apply(void 0,a);throw s}}};var Zjn={attempt:{chmod:J7(w0(Qs.chmod),hd.onChangeError),chown:J7(w0(Qs.chown),hd.onChangeError),close:J7(w0(Qs.close),lA),fsync:J7(w0(Qs.fsync),lA),mkdir:J7(w0(Qs.mkdir),lA),realpath:J7(w0(Qs.realpath),lA),stat:J7(w0(Qs.stat),lA),unlink:J7(w0(Qs.unlink),lA),chmodSync:k5(Qs.chmodSync,hd.onChangeError),chownSync:k5(Qs.chownSync,hd.onChangeError),closeSync:k5(Qs.closeSync,lA),existsSync:k5(Qs.existsSync,lA),fsyncSync:k5(Qs.fsync,lA),mkdirSync:k5(Qs.mkdirSync,lA),realpathSync:k5(Qs.realpathSync,lA),statSync:k5(Qs.statSync,lA),unlinkSync:k5(Qs.unlinkSync,lA)},retry:{close:X7(w0(Qs.close),hd.isRetriableError),fsync:X7(w0(Qs.fsync),hd.isRetriableError),open:X7(w0(Qs.open),hd.isRetriableError),readFile:X7(w0(Qs.readFile),hd.isRetriableError),rename:X7(w0(Qs.rename),hd.isRetriableError),stat:X7(w0(Qs.stat),hd.isRetriableError),write:X7(w0(Qs.write),hd.isRetriableError),writeFile:X7(w0(Qs.writeFile),hd.isRetriableError),closeSync:Z7(Qs.closeSync,hd.isRetriableError),fsyncSync:Z7(Qs.fsyncSync,hd.isRetriableError),openSync:Z7(Qs.openSync,hd.isRetriableError),readFileSync:Z7(Qs.readFileSync,hd.isRetriableError),renameSync:Z7(Qs.renameSync,hd.isRetriableError),statSync:Z7(Qs.statSync,hd.isRetriableError),writeSync:Z7(Qs.writeSync,hd.isRetriableError),writeFileSync:Z7(Qs.writeFileSync,hd.isRetriableError)}},T1=Zjn;import x0r from"node:os";import ZYe from"node:process";var B0r="utf8",eWe=438,R0r=511;var N0r={},O0r=x0r.userInfo().uid,F0r=x0r.userInfo().gid;var M0r=1e3,L0r=!!ZYe.getuid,Nda=ZYe.getuid?!ZYe.getuid():!1,tWe=128;var P0r=t=>t instanceof Error&&"code"in t;var rWe=t=>typeof t=="string",A6e=t=>t===void 0;import tYn from"node:path";import HH from"node:process";import Q0r from"node:process";var k0r=Q0r.platform==="linux",g6e=Q0r.platform==="win32";var nWe=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];g6e||nWe.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");k0r&&nWe.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED");var U0r=nWe;var iWe=class{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=e=>{if(!this.exited){this.exited=!0;for(let r of this.callbacks)r();e&&(g6e&&e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"?HH.kill(HH.pid,"SIGTERM"):HH.kill(HH.pid,e))}},this.hook=()=>{HH.once("exit",()=>this.exit());for(let e of U0r)try{HH.once(e,()=>this.exit(e))}catch{}},this.register=e=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}},H0r=new iWe;var eYn=H0r.register,G0r=eYn;var B2={store:{},create:t=>{let e=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),i=`.tmp-${Date.now().toString().slice(-10)}${e}`;return`${t}${i}`},get:(t,e,r=!0)=>{let n=B2.truncate(e(t));return n in B2.store?B2.get(t,e,r):(B2.store[n]=r,[n,()=>delete B2.store[n]])},purge:t=>{B2.store[t]&&(delete B2.store[t],T1.attempt.unlink(t))},purgeSync:t=>{B2.store[t]&&(delete B2.store[t],T1.attempt.unlinkSync(t))},purgeSyncAll:()=>{for(let t in B2.store)B2.purgeSync(t)},truncate:t=>{let e=tYn.basename(t);if(e.length<=tWe)return t;let r=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(e);if(!r)return t;let n=e.length-tWe;return`${t.slice(0,-e.length)}${r[1]}${r[2].slice(0,-n)}${r[3]}`}};G0r(B2.purgeSyncAll);var GX=B2;function E6e(t,e,r=N0r){if(rWe(r))return E6e(t,e,{encoding:r});let n=Date.now()+((r.timeout??M0r)||-1),i=null,a=null,s=null;try{let o=T1.attempt.realpathSync(t),l=!!o;t=o||t,[a,i]=GX.get(t,r.tmpCreate||GX.create,r.tmpPurge!==!1);let u=L0r&&A6e(r.chown),c=A6e(r.mode);if(l&&(u||c)){let d=T1.attempt.statSync(t);d&&(r={...r},u&&(r.chown={uid:d.uid,gid:d.gid}),c&&(r.mode=d.mode))}if(!l){let d=rYn.dirname(t);T1.attempt.mkdirSync(d,{mode:R0r,recursive:!0})}s=T1.retry.openSync(n)(a,"w",r.mode||eWe),r.tmpCreated&&r.tmpCreated(a),rWe(e)?T1.retry.writeSync(n)(s,e,0,r.encoding||B0r):A6e(e)||T1.retry.writeSync(n)(s,e,0,e.length,0),r.fsync!==!1&&(r.fsyncWait!==!1?T1.retry.fsyncSync(n)(s):T1.attempt.fsync(s)),T1.retry.closeSync(n)(s),s=null,r.chown&&(r.chown.uid!==O0r||r.chown.gid!==F0r)&&T1.attempt.chownSync(a,r.chown.uid,r.chown.gid),r.mode&&r.mode!==eWe&&T1.attempt.chmodSync(a,r.mode);try{T1.retry.renameSync(n)(a,t)}catch(d){if(!P0r(d)||d.code!=="ENAMETOOLONG")throw d;T1.retry.renameSync(n)(a,GX.truncate(t))}i(),a=null}finally{s&&T1.attempt.closeSync(s),a&&GX.purge(a)}}var sN=t=>{let e=typeof t;return t!==null&&(e==="object"||e==="function")};var aWe=new Set(["__proto__","prototype","constructor"]),nYn=new Set("0123456789");function y6e(t){let e=[],r="",n="start",i=!1;for(let a of t)switch(a){case"\\":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");i&&(r+=a),n="property",i=!i;break}case".":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="property";break}if(i){i=!1,r+=a;break}if(aWe.has(r))return[];e.push(r),r="",n="property";break}case"[":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="index";break}if(i){i=!1,r+=a;break}if(n==="property"){if(aWe.has(r))return[];e.push(r),r=""}n="index";break}case"]":{if(n==="index"){e.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if(n==="indexEnd")throw new Error("Invalid character after an index")}default:{if(n==="index"&&!nYn.has(a))throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");n==="start"&&(n="property"),i&&(i=!1,r+="\\"),r+=a}}switch(i&&(r+="\\"),n){case"property":{if(aWe.has(r))return[];e.push(r);break}case"index":throw new Error("Index was not closed");case"start":{e.push("");break}}return e}function sWe(t,e){if(typeof e!="number"&&Array.isArray(t)){let r=Number.parseInt(e,10);return Number.isInteger(r)&&t[r]===t[e]}return!1}function V0r(t,e){if(sWe(t,e))throw new Error("Cannot use string index")}function q0r(t,e,r){if(!sN(t)||typeof e!="string")return r===void 0?t:r;let n=y6e(e);if(n.length===0)return r;for(let i=0;i<n.length;i++){let a=n[i];if(sWe(t,a)?t=i===n.length-1?void 0:null:t=t[a],t==null){if(i!==n.length-1)return r;break}}return t===void 0?r:t}function oWe(t,e,r){if(!sN(t)||typeof e!="string")return t;let n=t,i=y6e(e);for(let a=0;a<i.length;a++){let s=i[a];V0r(t,s),a===i.length-1?t[s]=r:sN(t[s])||(t[s]=typeof i[a+1]=="number"?[]:{}),t=t[s]}return n}function $0r(t,e){if(!sN(t)||typeof e!="string")return!1;let r=y6e(e);for(let n=0;n<r.length;n++){let i=r[n];if(V0r(t,i),n===r.length-1)return delete t[i],!0;if(t=t[i],!sN(t))return!1}}function j0r(t,e){if(!sN(t)||typeof e!="string")return!1;let r=y6e(e);if(r.length===0)return!1;for(let n of r){if(!sN(t)||!(n in t)||sWe(t,n))return!1;t=t[n]}return!0}function aYn(t,e){let r=e?VX.join(t,"config.json"):VX.join("configstore",`${t}.json`),n=UH??qX.default.mkdtempSync(qX.default.realpathSync(iYn.tmpdir())+VX.sep);return VX.join(n,r)}var Y0r="You don't have access to this file.",sYn={mode:448,recursive:!0},W0r={mode:384},$X=class{constructor(e,r,n={}){this._path=n.configPath??aYn(e,n.globalConfigPath),r&&(this.all={...r,...this.all})}get all(){try{return JSON.parse(qX.default.readFileSync(this._path,"utf8"))}catch(e){if(e.code==="ENOENT")return{};if(e.code==="EACCES"&&(e.message=`${e.message}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kodadev/koda-cli",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "engines": {
5
5
  "node": ">=20.0.0"
6
6
  },