easycode-ai 1.1.59 → 1.1.60

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.
package/README.md CHANGED
@@ -974,7 +974,7 @@ Easy Code 可以作为 **ACP 编排方**,把编码任务派发给你本机安
974
974
 
975
975
  - 本机已安装并登录 **Claude Code** 和/或 **Codex**(派发会复用其本地登录态,不需要额外配置密钥)。
976
976
  - Easy Code 通过官方 ACP 桥按需拉起(默认 `npx` 运行,不打入安装包;桥版本已固定,避免上游破坏性更新影响已调好的环境):
977
- - Claude Code → `@agentclientprotocol/claude-agent-acp@0.44.0`,可用 `EASYCODE_CLAUDE_CODE_ACP_CMD` 覆盖启动命令(也可借此浮动到 latest)。
977
+ - Claude Code → `@agentclientprotocol/claude-agent-acp@0.62.0`,可用 `EASYCODE_CLAUDE_CODE_ACP_CMD` 覆盖启动命令(也可借此浮动到 latest)。
978
978
  - Codex → `@zed-industries/codex-acp@0.16.0`,可用 `EASYCODE_CODEX_ACP_CMD` 覆盖启动命令。
979
979
 
980
980
  ### 派发方式
@@ -752,7 +752,7 @@ ${I}`)}return t}),gwe=Pca(isr);Hwe=class extends kwe{create(e,r){var a;let{api_v
752
752
  `):[]}};yz.NEWLINE_CHARS=new Set([`
753
753
  `,"\r"]);yz.NEWLINE_REGEXP=/\r\n|[\n\r]/g;Xwe={off:0,error:200,warn:300,info:400,debug:500},qir=(n,e,r)=>{if(n){if(Cca(Xwe,n))return n;Og(r).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Xwe))}`)}};$ca={error:cce,warn:cce,info:cce,debug:cce},Kir=new WeakMap;nJ=n=>(n.options&&(n.options=Object.assign({},n.options),delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);unt=class n{constructor(e,r,a){this.iterator=e,this.controller=r,this.client=a}static fromSSEResponse(e,r,a){let i=!1,o=a?Og(a):console;function t(){return bz(this,arguments,function*(){var d,h,u,I;if(i)throw new E1("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var m=!0,p=aJ(eua(e,r)),b;b=yield wd(p.next()),d=b.done,!d;m=!0){I=b.value,m=!1;let y=I;if(!c)if(y.data.startsWith("[DONE]")){c=!0;continue}else try{yield yield wd(JSON.parse(y.data))}catch(v){throw o.error("Could not parse message into JSON:",y.data),o.error("From chunk:",y.raw),v}}}catch(y){h={error:y}}finally{try{!m&&!d&&(u=p.return)&&(yield wd(u.call(p)))}finally{if(h)throw h.error}}c=!0}catch(y){if(snt(y))return yield wd(void 0);throw y}finally{c||r.abort()}})}return new n(t,r,a)}static fromReadableStream(e,r,a){let i=!1;function o(){return bz(this,arguments,function*(){var d,h,u,I;let c=new yz,m=rsr(e);try{for(var p=!0,b=aJ(m),y;y=yield wd(b.next()),d=y.done,!d;p=!0){I=y.value,p=!1;let v=I;for(let A of c.decode(v))yield yield wd(A)}}catch(v){h={error:v}}finally{try{!p&&!d&&(u=b.return)&&(yield wd(u.call(b)))}finally{if(h)throw h.error}}for(let v of c.flush())yield yield wd(v)})}function t(){return bz(this,arguments,function*(){var d,h,u,I;if(i)throw new E1("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{try{for(var m=!0,p=aJ(o()),b;b=yield wd(p.next()),d=b.done,!d;m=!0){I=b.value,m=!1;let y=I;c||y&&(yield yield wd(JSON.parse(y)))}}catch(y){h={error:y}}finally{try{!m&&!d&&(u=p.return)&&(yield wd(u.call(p)))}finally{if(h)throw h.error}}c=!0}catch(y){if(snt(y))return yield wd(void 0);throw y}finally{c||r.abort()}})}return new n(t,r,a)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],a=this.iterator(),i=o=>({next:()=>{if(o.length===0){let t=a.next();e.push(t),r.push(t)}return o.shift()}});return[new n(()=>i(e),this.controller,this.client),new n(()=>i(r),this.controller,this.client)]}toReadableStream(){let e=this,r;return tsr({async start(){r=e[Symbol.asyncIterator]()},async pull(a){try{let{value:i,done:o}=await r.next();if(o)return a.close();let t=mnt(JSON.stringify(i)+`
754
754
  `);a.enqueue(t)}catch(i){a.error(i)}},async cancel(){var a;await((a=r.return)===null||a===void 0?void 0:a.call(r))}})}};dnt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
755
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,a,i]=rua(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};hnt=class n extends Promise{constructor(e,r,a=nua){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=a,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(r,a)=>e(await this.parseResponse(r,a),a))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ssr=Symbol("brand.privateNullableHeaders");lce=n=>{let e=new Headers,r=new Set;for(let a of n){let i=new Set;for(let[o,t]of aua(a)){let s=o.toLowerCase();i.has(s)||(e.delete(o),i.add(s)),t===null?(e.delete(o),r.add(s)):(e.append(o,t),r.delete(s))}}return{[ssr]:!0,values:e,nulls:r}};int=n=>{var e,r,a,i,o,t;if(typeof globalThis.process<"u")return(a=(r=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||r===void 0?void 0:r.trim())!==null&&a!==void 0?a:void 0;if(typeof globalThis.Deno<"u")return(t=(o=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||o===void 0?void 0:o.call(i,n))===null||t===void 0?void 0:t.trim()};Swe=class n{constructor(e){var r,a,i,o,t,s,d,{baseURL:h=int("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=(r=int("GEMINI_API_KEY"))!==null&&r!==void 0?r:null,apiVersion:I="v1beta"}=e,c=Zwe(e,["baseURL","apiKey","apiVersion"]);let m=Object.assign(Object.assign({apiKey:u,apiVersion:I},c),{baseURL:h||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(a=m.timeout)!==null&&a!==void 0?a:n.DEFAULT_TIMEOUT,this.logger=(i=m.logger)!==null&&i!==void 0?i:console;let p="warn";this.logLevel=p,this.logLevel=(t=(o=qir(m.logLevel,"ClientOptions.logLevel",this))!==null&&o!==void 0?o:qir(int("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&t!==void 0?t:p,this.fetchOptions=m.fetchOptions,this.maxRetries=(s=m.maxRetries)!==null&&s!==void 0?s:2,this.fetch=(d=m.fetch)!==null&&d!==void 0?d:Lca(),this.encoder=Bca,this._options=m,this.apiKey=u,this.apiVersion=I,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!r.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let r=lce([e.headers]);if(!(r.values.has("authorization")||r.values.has("x-goog-api-key"))){if(this.apiKey)return lce([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return lce([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([r,a])=>typeof a<"u").map(([r,a])=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(a)}`;if(a===null)return`${encodeURIComponent(r)}=`;throw new E1(`Cannot stringify type ${typeof a}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${fz}`}defaultIdempotencyKey(){return`stainless-node-retry-${wca()}`}makeStatusError(e,r,a,i){return R1.generate(e,r,a,i)}buildURL(e,r,a){let i=!this.baseURLOverridden()&&a||this.baseURL,o=Eca(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),t=this.defaultQuery();return xca(t)||(r=Object.assign(Object.assign({},t),r)),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let r=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${r}`}}async prepareRequest(e,{url:r,options:a}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,a){return this.request(Promise.resolve(a).then(i=>Object.assign({method:e,path:r},i)))}request(e,r=null){return new hnt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,a){var i,o,t;let s=await e,d=(i=s.maxRetries)!==null&&i!==void 0?i:this.maxRetries;r==null&&(r=d),await this.prepareOptions(s);let{req:h,url:u,timeout:I}=await this.buildRequest(s,{retryCount:d-r});await this.prepareRequest(h,{url:u,options:s});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=a===void 0?"":`, retryOf: ${a}`,p=Date.now();if(Og(this).debug(`[${c}] sending request`,nJ({retryOfRequestLogID:a,method:s.method,url:u,options:s,headers:h.headers})),!((o=s.signal)===null||o===void 0)&&o.aborted)throw new uce;let b=new AbortController,y=await this.fetchWithTimeout(u,h,I,b).catch(ont),v=Date.now();if(y instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(!((t=s.signal)===null||t===void 0)&&t.aborted)throw new uce;let E=snt(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(r)return Og(this).info(`[${c}] connection ${E?"timed out":"failed"} - ${w}`),Og(this).debug(`[${c}] connection ${E?"timed out":"failed"} (${w})`,nJ({retryOfRequestLogID:a,url:u,durationMs:v-p,message:y.message})),this.retryRequest(s,r,a??c);throw Og(this).info(`[${c}] connection ${E?"timed out":"failed"} - error; no more retries left`),Og(this).debug(`[${c}] connection ${E?"timed out":"failed"} (error; no more retries left)`,nJ({retryOfRequestLogID:a,url:u,durationMs:v-p,message:y.message})),E?new wwe:new vz({cause:y})}let A=`[${c}${m}] ${h.method} ${u} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${v-p}ms`;if(!y.ok){let w=await this.shouldRetry(y);if(r&&w){let g=`retrying, ${r} attempts remaining`;return await Jca(y.body),Og(this).info(`${A} - ${g}`),Og(this).debug(`[${c}] response error (${g})`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,durationMs:v-p})),this.retryRequest(s,r,a??c,y.headers)}let E=w?"error; no more retries left":"error; not retryable";Og(this).info(`${A} - ${E}`);let f=await y.text().catch(g=>ont(g).message),Z=Vca(f),W=Z?void 0:f;throw Og(this).debug(`[${c}] response error (${E})`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,message:W,durationMs:Date.now()-p})),this.makeStatusError(y.status,Z,W,y.headers)}return Og(this).info(A),Og(this).debug(`[${c}] response start`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,durationMs:v-p})),{response:y,options:s,controller:b,requestLogID:c,retryOfRequestLogID:a,startTime:p}}async fetchWithTimeout(e,r,a,i){let o=r||{},{signal:t,method:s}=o,d=Zwe(o,["signal","method"]);t&&t.addEventListener("abort",()=>i.abort());let h=setTimeout(()=>i.abort(),a),u=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,I=Object.assign(Object.assign(Object.assign({signal:i.signal},u?{duplex:"half"}:{}),{method:"GET"}),d);s&&(I.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,I)}finally{clearTimeout(h)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,a,i){var o;let t,s=i?.get("retry-after-ms");if(s){let h=parseFloat(s);Number.isNaN(h)||(t=h)}let d=i?.get("retry-after");if(d&&!t){let h=parseFloat(d);Number.isNaN(h)?t=Date.parse(d)-Date.now():t=h*1e3}if(!(t&&0<=t&&t<60*1e3)){let h=(o=e.maxRetries)!==null&&o!==void 0?o:this.maxRetries;t=this.calculateDefaultRetryTimeoutMillis(r,h)}return await kca(t),this.makeRequest(e,r-1,a)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,t=Math.min(.5*Math.pow(2,o),8),s=1-Math.random()*.25;return t*s*1e3}async buildRequest(e,{retryCount:r=0}={}){var a,i,o;let t=Object.assign({},e),{method:s,path:d,query:h,defaultBaseURL:u}=t,I=this.buildURL(d,h,u);"timeout"in t&&Yca("timeout",t.timeout),t.timeout=(a=t.timeout)!==null&&a!==void 0?a:this.timeout;let{bodyHeaders:c,body:m}=this.buildBody({options:t}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:r});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:s,headers:p},t.signal&&{signal:t.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(o=t.fetchOptions)!==null&&o!==void 0?o:{}),url:I,timeout:t.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:a,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let t=await this.authHeaders(e),s=lce([o,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Sca()),this._options.defaultHeaders,a,e.headers,t]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let a=lce([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&a.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Tca(e)}:this.encoder({body:e,headers:a})}};Swe.DEFAULT_TIMEOUT=6e4;R0=class extends Swe{constructor(){super(...arguments),this.interactions=new Qwe(this)}};osr=R0;R0.GeminiNextGenAPIClient=osr;R0.GeminiNextGenAPIClientError=E1;R0.APIError=R1;R0.APIConnectionError=vz;R0.APIConnectionTimeoutError=wwe;R0.APIUserAbortError=uce;R0.NotFoundError=Awe;R0.ConflictError=xwe;R0.RateLimitError=Ywe;R0.BadRequestError=Fwe;R0.AuthenticationError=Ewe;R0.InternalServerError=Vwe;R0.PermissionDeniedError=Rwe;R0.UnprocessableEntityError=Cwe;R0.toFile=Uca;R0.Interactions=Qwe;aDs=1024*1024*8;});function iua(n,e){return{...n,...e}}function lsr(n){let{prompt_id:e,...r}=n;return r}function TH(n){return Array.isArray(n)?n.map(lsr):n}var Lwe=Be(()=>{"use strict";Ua();});var csr={};As(csr,{DEFAULT_PROXY_CONFIG:()=>lua,getActiveProxyServerUrl:()=>rA,getAvailableProxyServers:()=>sua,getProxyServerInfo:()=>oua,getProxyServers:()=>dce,hasAvailableProxyServer:()=>pnt});function dce(){return[{url:"https://api-code.deepvlab.ai",name:"Primary Development Server",region:"default",status:"active"}]}function rA(){let e=dce().find(r=>r.status==="active");if(!e)throw new Error("No active proxy server available. Please contact support.");return e.url}function sua(){return dce().filter(e=>e.status==="active")}function pnt(){return dce().some(e=>e.status==="active")}function oua(n){return dce().find(r=>r.url===n)}var lua,Nz=Be(()=>{"use strict";lua={serverUrl:rA(),timeout:2e5,retryAttempts:3,retryDelay:1e3}});import{randomUUID as cua}from"crypto";function Jy(){return hce||(hce=cua()),hce}function usr(n){hce=n}function dsr(){hce=void 0}var hce,hsr,Twe=Be(()=>{"use strict";hsr=Jy()});function nd(n){let e=n??"1.1.59"??"unknown",r=process.platform,a=process.arch;if(e.startsWith("VSCode-")){let i=e.slice(7)||"unknown";return`${Jwe}/VSCode/${i} (${r}; ${a})`}if(e.startsWith("Desktop-")){let i=e.slice(8)||"unknown";return`${Jwe}/Desktop/${i} (${r}; ${a})`}return`${Jwe}/CLI/${e} (${r}; ${a})`}var Jwe,eY=Be(()=>{"use strict";Jwe="EasyCode"});import*as du from"fs";import*as FF from"path";import*as iJ from"os";function uua(n){el.configure(n)}function dua(n){el.setUserInfo(n)}function hua(n){el.setCliVersion(n)}async function Iua(){return await el.getUserHeaders()}function mua(){return el.getStatus()}var Ice,gs,el,nA=Be(()=>{"use strict";Nz();Twe();eY();Ice=259200,gs=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){return nd(this.cliVersion)}formatTimeRemaining(e){if(e<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(e/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),o=Math.floor(r%3600/60),t=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${o}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${o}\u5206\u949F${t}\u79D2`:o>0?`${o}\u5206\u949F${t}\u79D2`:`${t}\u79D2`}formatAbsoluteTime(e){return new Date(e).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=FF.join(iJ.homedir(),".easycode-user","user-info-dev.json"),this.jwtTokenFilePath=FF.join(iJ.homedir(),".easycode-user","jwt-token-dev.json"),this.usageStatsFilePath=FF.join(iJ.homedir(),".easycode-user","usage-stats-dev.json")):(this.userInfoFilePath=FF.join(iJ.homedir(),".easycode-user","user-info.json"),this.jwtTokenFilePath=FF.join(iJ.homedir(),".easycode-user","jwt-token.json"),this.usageStatsFilePath=FF.join(iJ.homedir(),".easycode-user","usage-stats.json")),this.cliVersion="1.1.59",this.config={proxyServerUrl:rA()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId===null&&(this.periodicStatusCheckIntervalId=setInterval(()=>{this.runPeriodicTokenCheck()},600*1e3))}async runPeriodicTokenCheck(){if(!this.userInfo&&!this.jwtTokenData)return;(!this.jwtTokenData||this.isTokenExpired())&&this.reloadFromDisk();let e=!!this.jwtTokenData&&!this.isTokenExpired();if(this.userInfo&&!e){if(this.jwtTokenData?.refreshToken)try{await this.refreshAccessToken(),console.log("[Login Check] \u2705 Periodic status check - expired access credential renewed via refresh credential");return}catch(r){if(this.jwtTokenData?.refreshToken){console.warn("[Login Check] \u26A0\uFE0F Periodic status check - credential refresh failed transiently, keeping session and retrying next cycle:",r instanceof Error?r.message:String(r));return}}console.log("[Login Check] \u26A0\uFE0F Periodic status check - Credential expired and cannot be renewed, signing out to return to login"),this.clear(),this.triggerLoginSuccessCallbacks();return}if(this.jwtTokenData){let r=Date.now(),a=this.jwtTokenData.expiresAt-r,i=this.formatTimeRemaining(a),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-Ice*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${i} (until ${o}), next renewal: ${t}`)}}static getInstance(){return n.instance||(n.instance=new n),n.instance}chmodOwnerOnly(e){if(process.platform!=="win32")try{du.chmodSync(e,384)}catch(r){console.warn("[Login Check] Failed to chmod credential file:",r)}}loadUserInfo(){try{if(du.existsSync(this.userInfoFilePath)){this.chmodOwnerOnly(this.userInfoFilePath);let e=du.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(e);let r=a=>{if(!a||!a.includes("@"))return a;let[i,o]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${o}`}}else this.userInfo=null}catch(e){console.warn("[Login Check] Failed to load user info from local file:",e),this.userInfo=null}}saveUserInfo(){try{let e=FF.dirname(this.userInfoFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),this.chmodOwnerOnly(this.userInfoFilePath),console.log("[Login Check] User info saved to local file")}catch(e){console.error("[Login Check] Failed to save user info:",e)}}loadJwtToken(){try{if(du.existsSync(this.jwtTokenFilePath)){this.chmodOwnerOnly(this.jwtTokenFilePath);let e=du.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(e),this.isTokenExpired()?this.jwtTokenData?.refreshToken||(this.jwtTokenData=null):this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required"),this.jwtTokenData=null}catch(e){console.warn("[Login Check] Failed to load access credential from local file:",e),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let e=FF.dirname(this.jwtTokenFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),this.chmodOwnerOnly(this.jwtTokenFilePath),console.log("[Login Check] Access credential data saved to local file")}catch(e){console.error("[Login Check] Failed to save access credential:",e)}}loadUsageStats(){try{if(du.existsSync(this.usageStatsFilePath)){let e=du.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(e)}}catch(e){console.warn("[Login Check] Failed to load usage stats from local file:",e),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let e=FF.dirname(this.usageStatsFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),this.chmodOwnerOnly(this.usageStatsFilePath),console.log("[Login Check] Usage stats saved to local file")}catch(e){console.error("[Login Check] Failed to save usage stats:",e)}}updateUsageStats(e){e<=0||(this.usageStats.totalCreditsConsumed+=e,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${e})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(e){this.config={...this.config,...e},e.userInfo&&(this.userInfo=e.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${e.userInfo.name}`)),e.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${e.proxyServerUrl}`),e.cliVersion&&(this.cliVersion=e.cliVersion,console.log(`[Login Check] CLI version set: ${e.cliVersion}`))}setUserInfo(e){this.userInfo=e,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${e.name} (${e.email||e.openId||"N/A"})`),this.startPeriodicStatusCheck(),this.triggerLoginSuccessCallbacks()}onLoginSuccess(e){this.onLoginSuccessCallbacks.push(e)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(e=>{try{e()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(e){this.cliVersion=e,console.log(`[Login Check] CLI version updated: ${e}`)}setJwtToken(e){let r=Date.now();this.jwtTokenData={accessToken:e,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(e){let a=Date.now()+e.expiresIn*1e3;this.jwtTokenData={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(e.expiresIn*1e3),o=this.formatAbsoluteTime(a),t=this.formatAbsoluteTime(a-Ice*1e3),d=!!e.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${o}), next renewal: ${t}${d}`)}reloadFromDisk(){this.loadUserInfo(),this.loadJwtToken()}async getAccessToken(){if(this.jwtTokenData||this.reloadFromDisk(),!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let e=Date.now(),r=this.jwtTokenData.expiresAt-e,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-Ice*1e3,o=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(t){return console.error("[Login Check] Credential renewal failed:",t),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(e=Ice){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=e*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${e}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let e=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":this.getUserAgent()},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!e.ok){if(e.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let d=await e.text();throw new Error(`Credential refresh failed (${e.status}): ${d}`)}let r=await e.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let o=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-Ice*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${o} (until ${t}), next renewal: ${s}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(e){throw console.error("[Login Check] Credential refresh error:",e),e}}clearTokens(){this.jwtTokenData=null;try{du.existsSync(this.jwtTokenFilePath)&&du.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(e){let r=await this.getAccessToken(),a=this.getCliVersion(),i=this.getUserAgent(),o={"Content-Type":"application/json","X-Client-Version":a,"User-Agent":i,"X-Session-ID":Jy()};return r&&(o.Authorization=`Bearer ${r}`),e&&(o["X-DVCode-Scene"]=e),o}getUserHeadersSync(){let e=this.getCliVersion(),r=this.getUserAgent(),a={"Content-Type":"application/json","X-Client-Version":e,"User-Agent":r,"X-Session-ID":Jy()};return this.jwtTokenData?.accessToken&&(a.Authorization=`Bearer ${this.jwtTokenData.accessToken}`),a}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{du.existsSync(this.userInfoFilePath)&&du.unlinkSync(this.userInfoFilePath)}catch(e){console.warn("[Login Check] Failed to delete user info file:",e)}try{du.existsSync(this.jwtTokenFilePath)&&du.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}console.log("[Login Check] Authentication cleared")}},el=gs.getInstance()});import{promises as sJ}from"node:fs";import mce from"node:path";import pua from"os";var By,Bwe,Ur,Oy=Be(()=>{"use strict";(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR"})(By||(By={}));Bwe=class{config;logBuffer=[];constructor(e={}){if(this.config={level:By.INFO,enableConsole:!0,enableFile:!1,maxFileSize:10,maxFiles:5,...e},this.config.enableFile&&!this.config.filePath){let r=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-");this.config.filePath=mce.join(pua.homedir(),".easycode-user","logs",`deepv-${r}.log`)}}formatMessage(e,r,...a){let i=new Date().toISOString(),o=a.map(t=>typeof t=="object"?JSON.stringify(t,null,2):String(t)).join(" ");return`[${i}] [${e}] ${r} ${o}`.trim()}async writeToFile(e){if(!(!this.config.enableFile||!this.config.filePath))try{await sJ.mkdir(mce.dirname(this.config.filePath),{recursive:!0}),await this.rotateLogIfNeeded(),await sJ.appendFile(this.config.filePath,e+`
755
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,a,i]=rua(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};hnt=class n extends Promise{constructor(e,r,a=nua){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=a,this.client=e}_thenUnwrap(e){return new n(this.client,this.responsePromise,async(r,a)=>e(await this.parseResponse(r,a),a))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ssr=Symbol("brand.privateNullableHeaders");lce=n=>{let e=new Headers,r=new Set;for(let a of n){let i=new Set;for(let[o,t]of aua(a)){let s=o.toLowerCase();i.has(s)||(e.delete(o),i.add(s)),t===null?(e.delete(o),r.add(s)):(e.append(o,t),r.delete(s))}}return{[ssr]:!0,values:e,nulls:r}};int=n=>{var e,r,a,i,o,t;if(typeof globalThis.process<"u")return(a=(r=(e=globalThis.process.env)===null||e===void 0?void 0:e[n])===null||r===void 0?void 0:r.trim())!==null&&a!==void 0?a:void 0;if(typeof globalThis.Deno<"u")return(t=(o=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||o===void 0?void 0:o.call(i,n))===null||t===void 0?void 0:t.trim()};Swe=class n{constructor(e){var r,a,i,o,t,s,d,{baseURL:h=int("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=(r=int("GEMINI_API_KEY"))!==null&&r!==void 0?r:null,apiVersion:I="v1beta"}=e,c=Zwe(e,["baseURL","apiKey","apiVersion"]);let m=Object.assign(Object.assign({apiKey:u,apiVersion:I},c),{baseURL:h||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(a=m.timeout)!==null&&a!==void 0?a:n.DEFAULT_TIMEOUT,this.logger=(i=m.logger)!==null&&i!==void 0?i:console;let p="warn";this.logLevel=p,this.logLevel=(t=(o=qir(m.logLevel,"ClientOptions.logLevel",this))!==null&&o!==void 0?o:qir(int("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&t!==void 0?t:p,this.fetchOptions=m.fetchOptions,this.maxRetries=(s=m.maxRetries)!==null&&s!==void 0?s:2,this.fetch=(d=m.fetch)!==null&&d!==void 0?d:Lca(),this.encoder=Bca,this._options=m,this.apiKey=u,this.apiVersion=I,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!r.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let r=lce([e.headers]);if(!(r.values.has("authorization")||r.values.has("x-goog-api-key"))){if(this.apiKey)return lce([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return lce([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([r,a])=>typeof a<"u").map(([r,a])=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(a)}`;if(a===null)return`${encodeURIComponent(r)}=`;throw new E1(`Cannot stringify type ${typeof a}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${fz}`}defaultIdempotencyKey(){return`stainless-node-retry-${wca()}`}makeStatusError(e,r,a,i){return R1.generate(e,r,a,i)}buildURL(e,r,a){let i=!this.baseURLOverridden()&&a||this.baseURL,o=Eca(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),t=this.defaultQuery();return xca(t)||(r=Object.assign(Object.assign({},t),r)),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let r=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${r}`}}async prepareRequest(e,{url:r,options:a}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,a){return this.request(Promise.resolve(a).then(i=>Object.assign({method:e,path:r},i)))}request(e,r=null){return new hnt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,a){var i,o,t;let s=await e,d=(i=s.maxRetries)!==null&&i!==void 0?i:this.maxRetries;r==null&&(r=d),await this.prepareOptions(s);let{req:h,url:u,timeout:I}=await this.buildRequest(s,{retryCount:d-r});await this.prepareRequest(h,{url:u,options:s});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=a===void 0?"":`, retryOf: ${a}`,p=Date.now();if(Og(this).debug(`[${c}] sending request`,nJ({retryOfRequestLogID:a,method:s.method,url:u,options:s,headers:h.headers})),!((o=s.signal)===null||o===void 0)&&o.aborted)throw new uce;let b=new AbortController,y=await this.fetchWithTimeout(u,h,I,b).catch(ont),v=Date.now();if(y instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(!((t=s.signal)===null||t===void 0)&&t.aborted)throw new uce;let E=snt(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(r)return Og(this).info(`[${c}] connection ${E?"timed out":"failed"} - ${w}`),Og(this).debug(`[${c}] connection ${E?"timed out":"failed"} (${w})`,nJ({retryOfRequestLogID:a,url:u,durationMs:v-p,message:y.message})),this.retryRequest(s,r,a??c);throw Og(this).info(`[${c}] connection ${E?"timed out":"failed"} - error; no more retries left`),Og(this).debug(`[${c}] connection ${E?"timed out":"failed"} (error; no more retries left)`,nJ({retryOfRequestLogID:a,url:u,durationMs:v-p,message:y.message})),E?new wwe:new vz({cause:y})}let A=`[${c}${m}] ${h.method} ${u} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${v-p}ms`;if(!y.ok){let w=await this.shouldRetry(y);if(r&&w){let g=`retrying, ${r} attempts remaining`;return await Jca(y.body),Og(this).info(`${A} - ${g}`),Og(this).debug(`[${c}] response error (${g})`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,durationMs:v-p})),this.retryRequest(s,r,a??c,y.headers)}let E=w?"error; no more retries left":"error; not retryable";Og(this).info(`${A} - ${E}`);let f=await y.text().catch(g=>ont(g).message),Z=Vca(f),W=Z?void 0:f;throw Og(this).debug(`[${c}] response error (${E})`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,message:W,durationMs:Date.now()-p})),this.makeStatusError(y.status,Z,W,y.headers)}return Og(this).info(A),Og(this).debug(`[${c}] response start`,nJ({retryOfRequestLogID:a,url:y.url,status:y.status,headers:y.headers,durationMs:v-p})),{response:y,options:s,controller:b,requestLogID:c,retryOfRequestLogID:a,startTime:p}}async fetchWithTimeout(e,r,a,i){let o=r||{},{signal:t,method:s}=o,d=Zwe(o,["signal","method"]);t&&t.addEventListener("abort",()=>i.abort());let h=setTimeout(()=>i.abort(),a),u=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,I=Object.assign(Object.assign(Object.assign({signal:i.signal},u?{duplex:"half"}:{}),{method:"GET"}),d);s&&(I.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,I)}finally{clearTimeout(h)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,a,i){var o;let t,s=i?.get("retry-after-ms");if(s){let h=parseFloat(s);Number.isNaN(h)||(t=h)}let d=i?.get("retry-after");if(d&&!t){let h=parseFloat(d);Number.isNaN(h)?t=Date.parse(d)-Date.now():t=h*1e3}if(!(t&&0<=t&&t<60*1e3)){let h=(o=e.maxRetries)!==null&&o!==void 0?o:this.maxRetries;t=this.calculateDefaultRetryTimeoutMillis(r,h)}return await kca(t),this.makeRequest(e,r-1,a)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,t=Math.min(.5*Math.pow(2,o),8),s=1-Math.random()*.25;return t*s*1e3}async buildRequest(e,{retryCount:r=0}={}){var a,i,o;let t=Object.assign({},e),{method:s,path:d,query:h,defaultBaseURL:u}=t,I=this.buildURL(d,h,u);"timeout"in t&&Yca("timeout",t.timeout),t.timeout=(a=t.timeout)!==null&&a!==void 0?a:this.timeout;let{bodyHeaders:c,body:m}=this.buildBody({options:t}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:r});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:s,headers:p},t.signal&&{signal:t.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(o=t.fetchOptions)!==null&&o!==void 0?o:{}),url:I,timeout:t.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:a,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let t=await this.authHeaders(e),s=lce([o,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),Sca()),this._options.defaultHeaders,a,e.headers,t]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let a=lce([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&a.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Tca(e)}:this.encoder({body:e,headers:a})}};Swe.DEFAULT_TIMEOUT=6e4;R0=class extends Swe{constructor(){super(...arguments),this.interactions=new Qwe(this)}};osr=R0;R0.GeminiNextGenAPIClient=osr;R0.GeminiNextGenAPIClientError=E1;R0.APIError=R1;R0.APIConnectionError=vz;R0.APIConnectionTimeoutError=wwe;R0.APIUserAbortError=uce;R0.NotFoundError=Awe;R0.ConflictError=xwe;R0.RateLimitError=Ywe;R0.BadRequestError=Fwe;R0.AuthenticationError=Ewe;R0.InternalServerError=Vwe;R0.PermissionDeniedError=Rwe;R0.UnprocessableEntityError=Cwe;R0.toFile=Uca;R0.Interactions=Qwe;aDs=1024*1024*8;});function iua(n,e){return{...n,...e}}function lsr(n){let{prompt_id:e,...r}=n;return r}function TH(n){return Array.isArray(n)?n.map(lsr):n}var Lwe=Be(()=>{"use strict";Ua();});var csr={};As(csr,{DEFAULT_PROXY_CONFIG:()=>lua,getActiveProxyServerUrl:()=>rA,getAvailableProxyServers:()=>sua,getProxyServerInfo:()=>oua,getProxyServers:()=>dce,hasAvailableProxyServer:()=>pnt});function dce(){return[{url:"https://api-code.deepvlab.ai",name:"Primary Development Server",region:"default",status:"active"}]}function rA(){let e=dce().find(r=>r.status==="active");if(!e)throw new Error("No active proxy server available. Please contact support.");return e.url}function sua(){return dce().filter(e=>e.status==="active")}function pnt(){return dce().some(e=>e.status==="active")}function oua(n){return dce().find(r=>r.url===n)}var lua,Nz=Be(()=>{"use strict";lua={serverUrl:rA(),timeout:2e5,retryAttempts:3,retryDelay:1e3}});import{randomUUID as cua}from"crypto";function Jy(){return hce||(hce=cua()),hce}function usr(n){hce=n}function dsr(){hce=void 0}var hce,hsr,Twe=Be(()=>{"use strict";hsr=Jy()});function nd(n){let e=n??"1.1.60"??"unknown",r=process.platform,a=process.arch;if(e.startsWith("VSCode-")){let i=e.slice(7)||"unknown";return`${Jwe}/VSCode/${i} (${r}; ${a})`}if(e.startsWith("Desktop-")){let i=e.slice(8)||"unknown";return`${Jwe}/Desktop/${i} (${r}; ${a})`}return`${Jwe}/CLI/${e} (${r}; ${a})`}var Jwe,eY=Be(()=>{"use strict";Jwe="EasyCode"});import*as du from"fs";import*as FF from"path";import*as iJ from"os";function uua(n){el.configure(n)}function dua(n){el.setUserInfo(n)}function hua(n){el.setCliVersion(n)}async function Iua(){return await el.getUserHeaders()}function mua(){return el.getStatus()}var Ice,gs,el,nA=Be(()=>{"use strict";Nz();Twe();eY();Ice=259200,gs=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){return nd(this.cliVersion)}formatTimeRemaining(e){if(e<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(e/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),o=Math.floor(r%3600/60),t=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${o}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${o}\u5206\u949F${t}\u79D2`:o>0?`${o}\u5206\u949F${t}\u79D2`:`${t}\u79D2`}formatAbsoluteTime(e){return new Date(e).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=FF.join(iJ.homedir(),".easycode-user","user-info-dev.json"),this.jwtTokenFilePath=FF.join(iJ.homedir(),".easycode-user","jwt-token-dev.json"),this.usageStatsFilePath=FF.join(iJ.homedir(),".easycode-user","usage-stats-dev.json")):(this.userInfoFilePath=FF.join(iJ.homedir(),".easycode-user","user-info.json"),this.jwtTokenFilePath=FF.join(iJ.homedir(),".easycode-user","jwt-token.json"),this.usageStatsFilePath=FF.join(iJ.homedir(),".easycode-user","usage-stats.json")),this.cliVersion="1.1.60",this.config={proxyServerUrl:rA()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId===null&&(this.periodicStatusCheckIntervalId=setInterval(()=>{this.runPeriodicTokenCheck()},600*1e3))}async runPeriodicTokenCheck(){if(!this.userInfo&&!this.jwtTokenData)return;(!this.jwtTokenData||this.isTokenExpired())&&this.reloadFromDisk();let e=!!this.jwtTokenData&&!this.isTokenExpired();if(this.userInfo&&!e){if(this.jwtTokenData?.refreshToken)try{await this.refreshAccessToken(),console.log("[Login Check] \u2705 Periodic status check - expired access credential renewed via refresh credential");return}catch(r){if(this.jwtTokenData?.refreshToken){console.warn("[Login Check] \u26A0\uFE0F Periodic status check - credential refresh failed transiently, keeping session and retrying next cycle:",r instanceof Error?r.message:String(r));return}}console.log("[Login Check] \u26A0\uFE0F Periodic status check - Credential expired and cannot be renewed, signing out to return to login"),this.clear(),this.triggerLoginSuccessCallbacks();return}if(this.jwtTokenData){let r=Date.now(),a=this.jwtTokenData.expiresAt-r,i=this.formatTimeRemaining(a),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-Ice*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${i} (until ${o}), next renewal: ${t}`)}}static getInstance(){return n.instance||(n.instance=new n),n.instance}chmodOwnerOnly(e){if(process.platform!=="win32")try{du.chmodSync(e,384)}catch(r){console.warn("[Login Check] Failed to chmod credential file:",r)}}loadUserInfo(){try{if(du.existsSync(this.userInfoFilePath)){this.chmodOwnerOnly(this.userInfoFilePath);let e=du.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(e);let r=a=>{if(!a||!a.includes("@"))return a;let[i,o]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${o}`}}else this.userInfo=null}catch(e){console.warn("[Login Check] Failed to load user info from local file:",e),this.userInfo=null}}saveUserInfo(){try{let e=FF.dirname(this.userInfoFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),this.chmodOwnerOnly(this.userInfoFilePath),console.log("[Login Check] User info saved to local file")}catch(e){console.error("[Login Check] Failed to save user info:",e)}}loadJwtToken(){try{if(du.existsSync(this.jwtTokenFilePath)){this.chmodOwnerOnly(this.jwtTokenFilePath);let e=du.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(e),this.isTokenExpired()?this.jwtTokenData?.refreshToken||(this.jwtTokenData=null):this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required"),this.jwtTokenData=null}catch(e){console.warn("[Login Check] Failed to load access credential from local file:",e),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let e=FF.dirname(this.jwtTokenFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),this.chmodOwnerOnly(this.jwtTokenFilePath),console.log("[Login Check] Access credential data saved to local file")}catch(e){console.error("[Login Check] Failed to save access credential:",e)}}loadUsageStats(){try{if(du.existsSync(this.usageStatsFilePath)){let e=du.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(e)}}catch(e){console.warn("[Login Check] Failed to load usage stats from local file:",e),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let e=FF.dirname(this.usageStatsFilePath);du.existsSync(e)||du.mkdirSync(e,{recursive:!0,mode:448}),du.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),this.chmodOwnerOnly(this.usageStatsFilePath),console.log("[Login Check] Usage stats saved to local file")}catch(e){console.error("[Login Check] Failed to save usage stats:",e)}}updateUsageStats(e){e<=0||(this.usageStats.totalCreditsConsumed+=e,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${e})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(e){this.config={...this.config,...e},e.userInfo&&(this.userInfo=e.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${e.userInfo.name}`)),e.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${e.proxyServerUrl}`),e.cliVersion&&(this.cliVersion=e.cliVersion,console.log(`[Login Check] CLI version set: ${e.cliVersion}`))}setUserInfo(e){this.userInfo=e,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${e.name} (${e.email||e.openId||"N/A"})`),this.startPeriodicStatusCheck(),this.triggerLoginSuccessCallbacks()}onLoginSuccess(e){this.onLoginSuccessCallbacks.push(e)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(e=>{try{e()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(e){this.cliVersion=e,console.log(`[Login Check] CLI version updated: ${e}`)}setJwtToken(e){let r=Date.now();this.jwtTokenData={accessToken:e,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(e){let a=Date.now()+e.expiresIn*1e3;this.jwtTokenData={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(e.expiresIn*1e3),o=this.formatAbsoluteTime(a),t=this.formatAbsoluteTime(a-Ice*1e3),d=!!e.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${o}), next renewal: ${t}${d}`)}reloadFromDisk(){this.loadUserInfo(),this.loadJwtToken()}async getAccessToken(){if(this.jwtTokenData||this.reloadFromDisk(),!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let e=Date.now(),r=this.jwtTokenData.expiresAt-e,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-Ice*1e3,o=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(t){return console.error("[Login Check] Credential renewal failed:",t),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(e=Ice){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=e*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${e}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let e=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":this.getUserAgent()},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!e.ok){if(e.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let d=await e.text();throw new Error(`Credential refresh failed (${e.status}): ${d}`)}let r=await e.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let o=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-Ice*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${o} (until ${t}), next renewal: ${s}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(e){throw console.error("[Login Check] Credential refresh error:",e),e}}clearTokens(){this.jwtTokenData=null;try{du.existsSync(this.jwtTokenFilePath)&&du.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(e){let r=await this.getAccessToken(),a=this.getCliVersion(),i=this.getUserAgent(),o={"Content-Type":"application/json","X-Client-Version":a,"User-Agent":i,"X-Session-ID":Jy()};return r&&(o.Authorization=`Bearer ${r}`),e&&(o["X-DVCode-Scene"]=e),o}getUserHeadersSync(){let e=this.getCliVersion(),r=this.getUserAgent(),a={"Content-Type":"application/json","X-Client-Version":e,"User-Agent":r,"X-Session-ID":Jy()};return this.jwtTokenData?.accessToken&&(a.Authorization=`Bearer ${this.jwtTokenData.accessToken}`),a}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{du.existsSync(this.userInfoFilePath)&&du.unlinkSync(this.userInfoFilePath)}catch(e){console.warn("[Login Check] Failed to delete user info file:",e)}try{du.existsSync(this.jwtTokenFilePath)&&du.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}console.log("[Login Check] Authentication cleared")}},el=gs.getInstance()});import{promises as sJ}from"node:fs";import mce from"node:path";import pua from"os";var By,Bwe,Ur,Oy=Be(()=>{"use strict";(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR"})(By||(By={}));Bwe=class{config;logBuffer=[];constructor(e={}){if(this.config={level:By.INFO,enableConsole:!0,enableFile:!1,maxFileSize:10,maxFiles:5,...e},this.config.enableFile&&!this.config.filePath){let r=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-");this.config.filePath=mce.join(pua.homedir(),".easycode-user","logs",`deepv-${r}.log`)}}formatMessage(e,r,...a){let i=new Date().toISOString(),o=a.map(t=>typeof t=="object"?JSON.stringify(t,null,2):String(t)).join(" ");return`[${i}] [${e}] ${r} ${o}`.trim()}async writeToFile(e){if(!(!this.config.enableFile||!this.config.filePath))try{await sJ.mkdir(mce.dirname(this.config.filePath),{recursive:!0}),await this.rotateLogIfNeeded(),await sJ.appendFile(this.config.filePath,e+`
756
756
  `,"utf-8")}catch(r){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",r)}}async rotateLogIfNeeded(){if(this.config.filePath)try{if((await sJ.stat(this.config.filePath)).size/(1024*1024)>(this.config.maxFileSize||10)){let a=new Date().toISOString().slice(0,19).replace(/[:.]/g,"-"),i=this.config.filePath.replace(".log",`-${a}.log`);await sJ.rename(this.config.filePath,i),await this.cleanOldLogs()}}catch(e){e.code!=="ENOENT"&&console.error("\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25:",e)}}async cleanOldLogs(){if(this.config.filePath)try{let e=mce.dirname(this.config.filePath),a=(await sJ.readdir(e)).filter(t=>t.startsWith("deepv-")&&t.endsWith(".log")).map(t=>({name:t,path:mce.join(e,t),time:sJ.stat(mce.join(e,t)).then(s=>s.mtime)})),i=await Promise.all(a.map(async t=>({...t,time:await t.time})));i.sort((t,s)=>s.time.getTime()-t.time.getTime());let o=i.slice(this.config.maxFiles||5);for(let t of o)await sJ.unlink(t.path)}catch(e){console.error("\u6E05\u7406\u65E7\u65E5\u5FD7\u5931\u8D25:",e)}}log(e,r,a,...i){if(e<this.config.level)return;let o=this.formatMessage(r,a,...i);this.config.enableConsole&&(e>=By.ERROR?console.error:e>=By.WARN?console.warn:e>=By.INFO?console.log:console.debug)(o),this.config.enableFile&&this.writeToFile(o)}debug(e,...r){this.log(By.DEBUG,"DEBUG",e,...r)}info(e,...r){this.log(By.INFO,"INFO",e,...r)}warn(e,...r){this.log(By.WARN,"WARN",e,...r)}error(e,...r){this.log(By.ERROR,"ERROR",e,...r)}logApiRequest(e,r){this.debug("API\u8BF7\u6C42",{endpoint:e,timestamp:new Date().toISOString(),requestSize:JSON.stringify(r).length,...process.env.FILE_DEBUG==="1"?{requestData:r}:{}})}logApiResponse(e,r){this.debug("API\u54CD\u5E94",{endpoint:e,timestamp:new Date().toISOString(),responseSize:JSON.stringify(r).length,...process.env.FILE_DEBUG==="1"?{responseData:r}:{}})}},Ur=new Bwe({level:process.env.FILE_DEBUG==="1"?By.DEBUG:By.INFO,enableConsole:!0,enableFile:process.env.LOG_TO_FILE==="true",filePath:process.env.LOG_FILE_PATH})});function Mc(n){return n instanceof Error&&"code"in n}function pn(n){if(n instanceof Error)return n.message;try{return String(n)}catch{return"Failed to get error details"}}function fnt(n){if(n&&typeof n=="object"&&"response"in n){let r=fua(n);if(r.error&&r.error.message&&r.error.code)switch(r.error.code){case 400:return new Dwe(r.error.message);case 401:return new lh(r.error.message);case 403:return new Owe(r.error.message);default:}}return n}function fua(n){return typeof n.response?.data=="string"?JSON.parse(n.response?.data):n.response?.data}function oJ(n){if(!n)return!1;try{let e=JSON.parse(n);return e&&e.error==="Unauthorized"&&e.errorCode==="AUTHENTICATION_FAILED"}catch{return!1}}var Owe,lh,Dwe,Uc=Be(()=>{"use strict";Owe=class extends Error{},lh=class extends Error{},Dwe=class extends Error{}});var ia,Isr,wh,A1=Be(()=>{"use strict";(function(n){n.CHAT_CONVERSATION="chat_conversation",n.WEB_FETCH="web_fetch",n.WEB_SEARCH="web_search",n.CONTENT_SUMMARY="content_summary",n.JSON_GENERATION="json_generation",n.COMPRESSION="compression",n.SUB_AGENT="sub_agent",n.CODE_ASSIST="code_assist",n.EDIT_CORRECTION="edit_correction",n.IMAGE_READER="image_reader",n.GOAL_EVALUATION="goal_evaluation"})(ia||(ia={}));Isr={[ia.CHAT_CONVERSATION]:"auto",[ia.WEB_FETCH]:"gemini-2.5-flash",[ia.WEB_SEARCH]:"gemini-2.5-flash",[ia.CODE_ASSIST]:"auto",[ia.CONTENT_SUMMARY]:"deepseek-v4-flash",[ia.EDIT_CORRECTION]:"deepseek-v4-flash",[ia.JSON_GENERATION]:"gemini-2.5-flash",[ia.COMPRESSION]:"gemini-2.5-flash",[ia.SUB_AGENT]:"auto",[ia.IMAGE_READER]:"gemini-2.5-flash",[ia.GOAL_EVALUATION]:"deepseek-v4-flash"},wh=class{static getModelForScene(e){if(e)return Isr[e]}static isClaudeModel(e){return e.includes("claude")||e.includes("anthropic")}static isGeminiModel(e){return e.includes("gemini")&&!this.isClaudeModel(e)}static getSceneDisplayName(e){return{[ia.CHAT_CONVERSATION]:"\u804A\u5929\u5BF9\u8BDD",[ia.WEB_FETCH]:"Web\u5185\u5BB9\u83B7\u53D6",[ia.WEB_SEARCH]:"Web\u641C\u7D22",[ia.CODE_ASSIST]:"\u4EE3\u7801\u52A9\u624B",[ia.CONTENT_SUMMARY]:"\u5185\u5BB9\u6458\u8981",[ia.EDIT_CORRECTION]:"\u7F16\u8F91\u6821\u6B63",[ia.JSON_GENERATION]:"JSON\u751F\u6210",[ia.COMPRESSION]:"\u5BF9\u8BDD\u538B\u7F29",[ia.SUB_AGENT]:"SubAgent\u5B50\u4EE3\u7406",[ia.IMAGE_READER]:"\u56FE\u7247\u8BC6\u522B",[ia.GOAL_EVALUATION]:"\u76EE\u6807\u8FBE\u6210\u8BC4\u4F30"}[e]||e}}});function y3(n){return typeof n=="object"&&n!==null&&"error"in n&&typeof n.error=="object"&&"message"in n.error}function o2(n){return typeof n=="object"&&n!==null&&"message"in n&&typeof n.message=="string"}function EF(n){let e=r=>r.includes("Quota exceeded for quota metric 'Gemini")&&r.includes("Pro Requests'");if(typeof n=="string")return e(n);if(o2(n))return e(n.message);if(y3(n))return e(n.error.message);if(n&&typeof n=="object"&&"response"in n){let r=n;if(r.response&&r.response.data){if(typeof r.response.data=="string")return e(r.response.data);if(typeof r.response.data=="object"&&r.response.data!==null&&"error"in r.response.data){let a=r.response.data;return e(a.error?.message||"")}}}return!1}function RF(n){return typeof n=="string"?n.includes("Quota exceeded for quota metric"):o2(n)?n.message.includes("Quota exceeded for quota metric"):y3(n)?n.error.message.includes("Quota exceeded for quota metric"):!1}function pce(n){let e=(i,o)=>{if(!i||typeof i!="object")return null;let t=i.error;if(!t||typeof t!="object")return null;let s=t,d=typeof s.code=="string"&&s.code.includes("quota_limit_exceeded"),h=s.type==="rate_limit_error"&&o===400;return(d||h)&&typeof s.message=="string"&&s.message.trim()?s.message:null};if(n&&typeof n=="object"&&"response"in n){let i=n.response;if(i){let o=e(i.data,i.status);if(o)return o}}let r=n instanceof Error||n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:"",a=r.match(/\((\d{3})\):/);if(a&&(r.includes("rate_limit_error")||r.includes("quota_limit_exceeded"))){let i=r.match(/\{[\s\S]*\}$/);if(i)try{let o=e(JSON.parse(i[0]),Number(a[1]));if(o)return o}catch{}}return e(n)}function l2(n){if(pce(n))return!0;if(n&&typeof n=="object"&&"response"in n){let e=n;if(e.response?.status===402&&e.response.data){let r=e.response.data;if(r&&typeof r.error=="string"&&(r.error==="Quota limit exceeded"||r.error==="No quota configuration")&&typeof r.message=="string")return!0}if(e.response?.status===500&&e.response.data){let r=e.response.data;if(r&&typeof r.message=="string"&&r.message.includes("quota exceeded"))return!0}}if(n instanceof Error&&n.message&&(n.message.includes("API request failed (402):")&&(n.message.includes('"error":"Quota limit exceeded"')||n.message.includes('"error":"No quota configuration"'))||n.message.includes("API request failed (500):")&&n.message.includes("quota exceeded")||n.message.includes("Stream API error (500):")&&n.message.includes("quota exceeded")))return!0;if(typeof n=="object"&&n!==null){let e=n;if(e.message&&typeof e.message=="string"&&(e.message.includes("API request failed (402):")&&(e.message.includes('"error":"Quota limit exceeded"')||e.message.includes('"error":"No quota configuration"'))||e.message.includes("API error (402):")&&(e.message.includes('"error":"Quota limit exceeded"')||e.message.includes('"error":"No quota configuration"'))||(e.message.includes("API request failed (500):")||e.message.includes("Stream API error (500):"))&&e.message.includes("quota exceeded"))||(e.error==="Quota limit exceeded"||e.error==="No quota configuration")&&typeof e.message=="string"||e.status===500&&typeof e.message=="string"&&e.message.includes("quota exceeded"))return!0}return typeof n=="string"?n.includes("Quota limit exceeded")||n.includes("No quota configuration")||n.includes("Daily token limit would be exceeded")||n.includes("Daily request limit exceeded")||n.includes("Daily cost limit would be exceeded")||n.includes("500")&&n.includes("quota exceeded"):!1}function fce(n){let e=pce(n);if(e)return e;let r=null;if(n&&typeof n=="object"&&"response"in n){let a=n;if(a.response?.status===402&&a.response.data)r=a.response.data;else if(a.response?.status===500&&a.response.data){let i=a.response.data;i&&typeof i.message=="string"&&i.message.includes("quota exceeded")&&(r=i)}}else if(typeof n=="object"&&n!==null){let a=n;if(a.message&&typeof a.message=="string"&&(a.message.includes("API request failed (402):")||a.message.includes("API request failed (500):")||a.message.includes("Stream API error (500):"))&&(a.message.includes('"error":"Quota limit exceeded"')||a.message.includes('"error":"No quota configuration"')||a.message.includes("quota exceeded")))try{let i=a.message.match(/\{.*\}$/);i&&(r=JSON.parse(i[0]))}catch{}r||(r=n)}if(!r&&n instanceof Error&&n.message&&(n.message.includes("API request failed (402):")||n.message.includes("API request failed (500):")||n.message.includes("Stream API error (500):"))&&(n.message.includes('"error":"Quota limit exceeded"')||n.message.includes('"error":"No quota configuration"')||n.message.includes("quota exceeded")))try{let a=n.message.match(/\{.*\}$/);a&&(r=JSON.parse(a[0]))}catch{}return r?r.message&&r.message.includes("quota exceeded")?bua(r):gua(r):null}function bua(n){let r=(()=>{try{let c=process.env,m=c.LC_ALL||c.LC_CTYPE||c.LANG||"";return m.toLowerCase().includes("zh")||m.toLowerCase().includes("chinese")}catch{return!1}})(),a="",i="",o="",t="",s=n.message||"",d=s.match(/Role:\s*([^,]+)/);d&&(a=d[1].trim());let h=s.match(/Limit:\s*([^,]+)/);h&&(i=h[1].trim());let u=s.match(/Used:\s*([^,]+)/);u&&(o=u[1].trim());let I=s.match(/Cycle:\s*([^,]+)/);if(I&&(t=I[1].trim()),r){let c=`\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
757
757
  `;return c+=`\u{1F6AB} \u5F53\u524D\u6A21\u578B\u7684\u5FAA\u73AF\u914D\u989D\u5DF2\u7528\u5C3D (Cycle Quota Exceeded)
758
758
  `,a&&(c+=`\u{1F464} \u89D2\u8272\u4FE1\u606F: ${a}
@@ -5507,7 +5507,7 @@ ${r}`,o=i.toLowerCase(),t=this.extractErrorCode(e,r);return t==="stale_ref"||o.i
5507
5507
  Hint: ${s}`:t}}catch{}let i=r.match(/^\s*message:\s*(.+)$/m);return i?i[1].trim():r.trim()||e.trim()}hintFor(e){switch(e){case"daemon-not-running":return'\u{1F449} The opencli daemon is not running. Ask me to start it, or run opencli ["doctor"] to diagnose.';case"extension-not-connected":return'\u{1F449} The Browser Bridge Chrome extension is not connected. Make sure Chrome is open and the official extension is installed/enabled from here: https://chromewebstore.google.com/detail/opencli-browser-bridge/ildkmabpimmkaediidaifkhjpohdnifk, then try again. Run opencli ["doctor"] for details.';case"not-logged-in":return"\u{1F511} The target site is not logged in. Ask the user to log in to the site in their Chrome \u2014 opencli reuses that session \u2014 then retry.";case"stale-ref":return'\u{1F449} The numeric ref is stale (the page changed). Re-run ["browser","<session>","state"] and use a fresh [N] ref.';case"selector":return"\u{1F449} The target could not be resolved. Re-run `state`/`find` to get a valid ref or selector; check the error envelope's candidates/available list.";case"cdp-detached":return"\u{1F449} Transient CDP/extension hiccup (the tab navigated or the debugger detached). Re-run `state` and retry the command.";case"timeout":return"\u{1F449} Timed out. For `wait` commands raise the `timeout` param; otherwise re-run `state` and retry.";case"empty":return"\u{1F449} No data returned. The page structure may have changed, or you may need to log in / wait for content.";case"not-installed":return["\u{1F449} OpenCLI is not installed. Install it globally, then simply re-run this command \u2014 the tool re-probes automatically, so NO restart of easycode is needed:",` npm install -g ${Jvn}`," (on macOS/Linux this may require sudo). If it still reports \"not-installed\" after a successful install, the global bin dir is likely not on this process's PATH: run `where opencli` (Windows) or `which opencli` (macOS/Linux) and pass that path via the tool's `binaryPath` parameter."].join(`
5508
5508
  `);default:return""}}}});var s_=Be(()=>{E2t();E2t()});var _u,P0,_ne,jHt=Be(()=>{_u={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_close:"session/close",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},P0={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},_ne=1});var aji,iji,sji,oji,lji,cji,KHt,uji,dji,hji,Iji,mji,pji,Ovn,fji,Dvn,_vn,Mvn,Uvn,bji,gji,zvn,Pvn,Gji,$Ht,vji,yji,Nji,Zji,SOe,eQt,Wji,tQt,jvn,wji,Fji,Eji,Rji,Aji,xji,Cji,qvn,rQt,Yji,Vji,o_,hBo,kji,aGe,Hji,Qji,Xji,Sji,Lji,Tji,Jji,Bji,Oji,Kvn,Dji,nQt,$vn,_ji,Mji,Uji,Mne,zji,Pji,qI,aQt,IBo,iQt,sQt,oQt,lQt,cQt,uQt,dQt,hQt,jji,qji,Kji,$ji,LOe,eqi,tqi,TOe,JOe,rqi,nqi,aqi,iqi,sqi,oqi,lqi,cqi,IQt,uqi,mQt,dqi,pQt,hqi,Iqi,mqi,pqi,fQt,fqi,bqi,gqi,Gqi,vqi,bQt,yqi,qHt,gQt,mBo,eyn,tyn,ryn,nyn,ayn,Nqi,iyn,GQt,Zqi,Wqi,wqi,Fqi,Eqi,Rqi,pBo,Aqi,xqi,vQt,fBo,yQt,Cqi,NQt,bBo,Yqi,gBo,syn=Be(()=>{sHe();aji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),terminal:ot.boolean().optional().default(!1)}),iji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),label:ot.string().nullish(),name:ot.string(),optional:ot.boolean().optional().default(!1),secret:ot.boolean().optional().default(!0)}),sji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string().nullish(),id:ot.string(),name:ot.string()}),oji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string().nullish(),id:ot.string(),link:ot.string().nullish(),name:ot.string(),vars:ot.array(iji)}),lji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),args:ot.array(ot.string()).optional(),description:ot.string().nullish(),env:ot.record(ot.string(),ot.string()).optional(),id:ot.string(),name:ot.string()}),cji=ot.union([oji.and(ot.object({type:ot.literal("env_var")})),lji.and(ot.object({type:ot.literal("terminal")})),sji]),KHt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),methodId:ot.string()}),uji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),dji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),blob:ot.string(),mimeType:ot.string().nullish(),uri:ot.string()}),hji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),Iji=ot.object({amount:ot.number(),currency:ot.string()}),mji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),terminalId:ot.string()}),pji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),newText:ot.string(),oldText:ot.string().nullish(),path:ot.string()}),Ovn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),name:ot.string(),value:ot.string()}),fji=ot.union([ot.literal(-32700),ot.literal(-32600),ot.literal(-32601),ot.literal(-32602),ot.literal(-32603),ot.literal(-32800),ot.literal(-32e3),ot.literal(-32002),ot.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),Dvn=ot.object({code:fji,data:ot.unknown().optional(),message:ot.string()}),_vn=ot.unknown(),Mvn=ot.unknown(),Uvn=ot.unknown(),bji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),readTextFile:ot.boolean().optional().default(!1),writeTextFile:ot.boolean().optional().default(!1)}),gji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),auth:aji.optional().default({terminal:!1}),fs:bji.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:ot.boolean().optional().default(!1)}),zvn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),name:ot.string(),value:ot.string()}),Pvn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),name:ot.string(),title:ot.string().nullish(),version:ot.string()}),Gji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),$Ht=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cursor:ot.string().nullish(),cwd:ot.string().nullish()}),vji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),http:ot.boolean().optional().default(!1),sse:ot.boolean().optional().default(!1)}),yji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),headers:ot.array(zvn),name:ot.string(),url:ot.string()}),Nji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),headers:ot.array(zvn),name:ot.string(),url:ot.string()}),Zji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),args:ot.array(ot.string()),command:ot.string(),env:ot.array(Ovn),name:ot.string()}),SOe=ot.union([yji.and(ot.object({type:ot.literal("http")})),Nji.and(ot.object({type:ot.literal("sse")})),Zji]),eQt=ot.string(),Wji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string().nullish(),modelId:eQt,name:ot.string()}),tQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cwd:ot.string(),mcpServers:ot.array(SOe)}),jvn=ot.string(),wji=ot.union([ot.literal("allow_once"),ot.literal("allow_always"),ot.literal("reject_once"),ot.literal("reject_always")]),Fji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),kind:wji,name:ot.string(),optionId:jvn}),Eji=ot.union([ot.literal("high"),ot.literal("medium"),ot.literal("low")]),Rji=ot.union([ot.literal("pending"),ot.literal("in_progress"),ot.literal("completed")]),Aji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:ot.string(),priority:Eji,status:Rji}),xji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),entries:ot.array(Aji)}),Cji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),audio:ot.boolean().optional().default(!1),embeddedContext:ot.boolean().optional().default(!1),image:ot.boolean().optional().default(!1)}),qvn=ot.number().int().gte(0).lte(65535),rQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),clientCapabilities:gji.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:Pvn.nullish(),protocolVersion:qvn}),Yji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:ot.string()}),Vji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),o_=ot.union([ot.number(),ot.string()]).nullable(),hBo=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),requestId:o_}),kji=ot.enum(["assistant","user"]),aGe=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),audience:ot.array(kji).nullish(),lastModified:ot.string().nullish(),priority:ot.number().nullish()}),Hji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),annotations:aGe.nullish(),data:ot.string(),mimeType:ot.string()}),Qji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),annotations:aGe.nullish(),data:ot.string(),mimeType:ot.string(),uri:ot.string().nullish()}),Xji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),annotations:aGe.nullish(),description:ot.string().nullish(),mimeType:ot.string().nullish(),name:ot.string(),size:ot.number().nullish(),title:ot.string().nullish(),uri:ot.string()}),Sji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),optionId:jvn}),Lji=ot.union([ot.object({outcome:ot.literal("cancelled")}),Sji.and(ot.object({outcome:ot.literal("selected")}))]),Tji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),outcome:Lji}),Jji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),Bji=ot.object({currentValue:ot.boolean()}),Oji=ot.string(),Kvn=ot.string(),Dji=ot.union([ot.literal("mode"),ot.literal("model"),ot.literal("thought_level"),ot.string()]),nQt=ot.string(),$vn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string().nullish(),name:ot.string(),value:nQt}),_ji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),group:Oji,name:ot.string(),options:ot.array($vn)}),Mji=ot.union([ot.array($vn),ot.array(_ji)]),Uji=ot.object({currentValue:nQt,options:Mji}),Mne=ot.intersection(ot.union([Uji.and(ot.object({type:ot.literal("select")})),Bji.and(ot.object({type:ot.literal("boolean")}))]),ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),category:Dji.nullish(),description:ot.string().nullish(),id:Kvn,name:ot.string()})),zji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne)}),Pji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),qI=ot.string(),aQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI}),IBo=ot.object({method:ot.string(),params:ot.union([aQt,_vn]).nullish()}),iQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI}),sQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),args:ot.array(ot.string()).optional(),command:ot.string(),cwd:ot.string().nullish(),env:ot.array(Ovn).optional(),outputByteLimit:ot.number().nullish(),sessionId:qI}),oQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cwd:ot.string(),mcpServers:ot.array(SOe).optional(),sessionId:qI}),lQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI,terminalId:ot.string()}),cQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cwd:ot.string(),mcpServers:ot.array(SOe),sessionId:qI}),uQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),limit:ot.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:ot.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:ot.string(),sessionId:qI}),dQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI,terminalId:ot.string()}),hQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cwd:ot.string(),mcpServers:ot.array(SOe).optional(),sessionId:qI}),jji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cwd:ot.string(),sessionId:qI,title:ot.string().nullish(),updatedAt:ot.string().nullish()}),qji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),nextCursor:ot.string().nullish(),sessions:ot.array(jji)}),Kji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),title:ot.string().nullish(),updatedAt:ot.string().nullish()}),$ji=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),LOe=ot.string(),eqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),currentModeId:LOe}),tqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string().nullish(),id:LOe,name:ot.string()}),TOe=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),availableModes:ot.array(tqi),currentModeId:LOe}),JOe=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),availableModels:ot.array(Wji),currentModelId:eQt}),rqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne).nullish(),models:JOe.nullish(),modes:TOe.nullish(),sessionId:qI}),nqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne).nullish(),models:JOe.nullish(),modes:TOe.nullish()}),aqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne).nullish(),models:JOe.nullish(),modes:TOe.nullish(),sessionId:qI}),iqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne).nullish(),models:JOe.nullish(),modes:TOe.nullish()}),sqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),oqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),close:Jji.nullish(),fork:Pji.nullish(),list:$ji.nullish(),resume:sqi.nullish()}),lqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),loadSession:ot.boolean().optional().default(!1),mcpCapabilities:vji.optional().default({http:!1,sse:!1}),promptCapabilities:Cji.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:oqi.optional().default({})}),cqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),agentCapabilities:lqi.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:Pvn.nullish(),authMethods:ot.array(cji).optional().default([]),protocolVersion:qvn}),IQt=ot.intersection(ot.union([ot.object({type:ot.literal("boolean"),value:ot.boolean()}),ot.object({value:nQt})]),ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configId:Kvn,sessionId:qI})),uqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),configOptions:ot.array(Mne)}),mQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),modeId:LOe,sessionId:qI}),dqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),pQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),modelId:eQt,sessionId:qI}),hqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),Iqi=ot.union([ot.literal("end_turn"),ot.literal("max_tokens"),ot.literal("max_turn_requests"),ot.literal("refusal"),ot.literal("cancelled")]),mqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),terminalId:ot.string()}),pqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),exitCode:ot.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:ot.string().nullish()}),fQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI,terminalId:ot.string()}),fqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),exitStatus:pqi.nullish(),output:ot.string(),truncated:ot.boolean()}),bqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),annotations:aGe.nullish(),text:ot.string()}),gqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),mimeType:ot.string().nullish(),text:ot.string(),uri:ot.string()}),Gqi=ot.union([gqi,dji]),vqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),annotations:aGe.nullish(),resource:Gqi}),bQt=ot.union([bqi.and(ot.object({type:ot.literal("text")})),Qji.and(ot.object({type:ot.literal("image")})),Hji.and(ot.object({type:ot.literal("audio")})),Xji.and(ot.object({type:ot.literal("resource_link")})),vqi.and(ot.object({type:ot.literal("resource")}))]),yqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:bQt}),qHt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:bQt,messageId:ot.string().nullish()}),gQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),messageId:ot.string().nullish(),prompt:ot.array(bQt),sessionId:qI}),mBo=ot.object({id:o_,method:ot.string(),params:ot.union([rQt,KHt,tQt,cQt,$Ht,oQt,hQt,iQt,mQt,IQt,gQt,pQt,Mvn]).nullish()}),eyn=ot.union([yqi.and(ot.object({type:ot.literal("content")})),pji.and(ot.object({type:ot.literal("diff")})),mqi.and(ot.object({type:ot.literal("terminal")}))]),tyn=ot.string(),ryn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),line:ot.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:ot.string()}),nyn=ot.union([ot.literal("pending"),ot.literal("in_progress"),ot.literal("completed"),ot.literal("failed")]),ayn=ot.union([ot.literal("read"),ot.literal("edit"),ot.literal("delete"),ot.literal("move"),ot.literal("search"),ot.literal("execute"),ot.literal("think"),ot.literal("fetch"),ot.literal("switch_mode"),ot.literal("other")]),Nqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:ot.array(eyn).optional(),kind:ayn.optional(),locations:ot.array(ryn).optional(),rawInput:ot.unknown().optional(),rawOutput:ot.unknown().optional(),status:nyn.optional(),title:ot.string(),toolCallId:tyn}),iyn=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:ot.array(eyn).nullish(),kind:ayn.nullish(),locations:ot.array(ryn).nullish(),rawInput:ot.unknown().optional(),rawOutput:ot.unknown().optional(),status:nyn.nullish(),title:ot.string().nullish(),toolCallId:tyn}),GQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),options:ot.array(Fji),sessionId:qI,toolCall:iyn}),Zqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),hint:ot.string()}),Wqi=Zqi,wqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),description:ot.string(),input:Wqi.nullish(),name:ot.string()}),Fqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),availableCommands:ot.array(wqi)}),Eqi=ot.object({cachedReadTokens:ot.number().nullish(),cachedWriteTokens:ot.number().nullish(),inputTokens:ot.number(),outputTokens:ot.number(),thoughtTokens:ot.number().nullish(),totalTokens:ot.number()}),Rqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),stopReason:Iqi,usage:Eqi.nullish(),userMessageId:ot.string().nullish()}),pBo=ot.union([ot.object({id:o_,result:ot.union([cqi,uji,aqi,nqi,qji,rqi,iqi,hji,dqi,uqi,Rqi,hqi,Uvn])}),ot.object({error:Dvn,id:o_})]),Aqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),cost:Iji.nullish(),size:ot.number(),used:ot.number()}),xqi=ot.union([qHt.and(ot.object({sessionUpdate:ot.literal("user_message_chunk")})),qHt.and(ot.object({sessionUpdate:ot.literal("agent_message_chunk")})),qHt.and(ot.object({sessionUpdate:ot.literal("agent_thought_chunk")})),Nqi.and(ot.object({sessionUpdate:ot.literal("tool_call")})),iyn.and(ot.object({sessionUpdate:ot.literal("tool_call_update")})),xji.and(ot.object({sessionUpdate:ot.literal("plan")})),Fqi.and(ot.object({sessionUpdate:ot.literal("available_commands_update")})),eqi.and(ot.object({sessionUpdate:ot.literal("current_mode_update")})),zji.and(ot.object({sessionUpdate:ot.literal("config_option_update")})),Kji.and(ot.object({sessionUpdate:ot.literal("session_info_update")})),Aqi.and(ot.object({sessionUpdate:ot.literal("usage_update")}))]),vQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI,update:xqi}),fBo=ot.object({method:ot.string(),params:ot.union([vQt,_vn]).nullish()}),yQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),sessionId:qI,terminalId:ot.string()}),Cqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),exitCode:ot.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:ot.string().nullish()}),NQt=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish(),content:ot.string(),path:ot.string(),sessionId:qI}),bBo=ot.object({id:o_,method:ot.string(),params:ot.union([NQt,uQt,GQt,sQt,fQt,dQt,yQt,lQt,Mvn]).nullish()}),Yqi=ot.object({_meta:ot.record(ot.string(),ot.unknown()).nullish()}),gBo=ot.union([ot.object({id:o_,result:ot.union([Yqi,Yji,Tji,mji,fqi,Vji,Cqi,Gji,Uvn])}),ot.object({error:Dvn,id:o_})])});function Une(n,e){let r=new TextEncoder,a=new TextDecoder,i=new ReadableStream({async start(t){let s="",d=e.getReader();try{for(;;){let{value:h,done:u}=await d.read();if(u)break;if(!h)continue;s+=a.decode(h,{stream:!0});let I=s.split(`
5509
5509
  `);s=I.pop()||"";for(let c of I){let m=c.trim();if(m)try{let p=JSON.parse(m);t.enqueue(p)}catch(p){console.error("Failed to parse JSON message:",m,p)}}}}finally{d.releaseLock(),t.close()}}}),o=new WritableStream({async write(t){let s=JSON.stringify(t)+`
5510
- `,d=n.getWriter();try{await d.write(r.encode(s))}finally{d.releaseLock()}}});return{readable:i,writable:o}}var oyn=Be(()=>{});var BOe,ZQt,zne,OOe,wa,l_=Be(()=>{s_();jHt();syn();jHt();oyn();BOe=class{#e;constructor(e,r){let a=e(this),i=async(t,s)=>{switch(t){case _u.initialize:{let d=rQt.parse(s);return a.initialize(d)}case _u.session_new:{let d=tQt.parse(s);return a.newSession(d)}case _u.session_load:{if(!a.loadSession)throw wa.methodNotFound(t);let d=cQt.parse(s);return a.loadSession(d)}case _u.session_list:{if(!a.listSessions)throw wa.methodNotFound(t);let d=$Ht.parse(s);return a.listSessions(d)}case _u.session_fork:{if(!a.unstable_forkSession)throw wa.methodNotFound(t);let d=oQt.parse(s);return a.unstable_forkSession(d)}case _u.session_resume:{if(!a.unstable_resumeSession)throw wa.methodNotFound(t);let d=hQt.parse(s);return a.unstable_resumeSession(d)}case _u.session_close:{if(!a.unstable_closeSession)throw wa.methodNotFound(t);let d=iQt.parse(s);return a.unstable_closeSession(d)}case _u.session_set_mode:{if(!a.setSessionMode)throw wa.methodNotFound(t);let d=mQt.parse(s);return await a.setSessionMode(d)??{}}case _u.authenticate:{let d=KHt.parse(s);return await a.authenticate(d)??{}}case _u.session_prompt:{let d=gQt.parse(s);return a.prompt(d)}case _u.session_set_model:{if(!a.unstable_setSessionModel)throw wa.methodNotFound(t);let d=pQt.parse(s);return await a.unstable_setSessionModel(d)??{}}case _u.session_set_config_option:{if(!a.setSessionConfigOption)throw wa.methodNotFound(t);let d=IQt.parse(s);return a.setSessionConfigOption(d)}default:if(a.extMethod)return a.extMethod(t,s);throw wa.methodNotFound(t)}},o=async(t,s)=>{switch(t){case _u.session_cancel:{let d=aQt.parse(s);return a.cancel(d)}default:if(a.extNotification)return a.extNotification(t,s);throw wa.methodNotFound(t)}};this.#e=new OOe(i,o,r)}async sessionUpdate(e){return await this.#e.sendNotification(P0.session_update,e)}async requestPermission(e){return await this.#e.sendRequest(P0.session_request_permission,e)}async readTextFile(e){return await this.#e.sendRequest(P0.fs_read_text_file,e)}async writeTextFile(e){return await this.#e.sendRequest(P0.fs_write_text_file,e)??{}}async createTerminal(e){let r=await this.#e.sendRequest(P0.terminal_create,e);return new ZQt(r.terminalId,e.sessionId,this.#e)}async extMethod(e,r){return await this.#e.sendRequest(e,r)}async extNotification(e,r){return await this.#e.sendNotification(e,r)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},ZQt=class{id;#e;#t;constructor(e,r,a){this.id=e,this.#e=r,this.#t=a}async currentOutput(){return await this.#t.sendRequest(P0.terminal_output,{sessionId:this.#e,terminalId:this.id})}async waitForExit(){return await this.#t.sendRequest(P0.terminal_wait_for_exit,{sessionId:this.#e,terminalId:this.id})}async kill(){return await this.#t.sendRequest(P0.terminal_kill,{sessionId:this.#e,terminalId:this.id})??{}}async release(){return await this.#t.sendRequest(P0.terminal_release,{sessionId:this.#e,terminalId:this.id})??{}}async[Symbol.asyncDispose](){await this.release()}},zne=class{#e;constructor(e,r){let a=e(this),i=async(t,s)=>{switch(t){case P0.fs_write_text_file:{let d=NQt.parse(s);return a.writeTextFile?.(d)}case P0.fs_read_text_file:{let d=uQt.parse(s);return a.readTextFile?.(d)}case P0.session_request_permission:{let d=GQt.parse(s);return a.requestPermission(d)}case P0.terminal_create:{let d=sQt.parse(s);return a.createTerminal?.(d)}case P0.terminal_output:{let d=fQt.parse(s);return a.terminalOutput?.(d)}case P0.terminal_release:{let d=dQt.parse(s);return await a.releaseTerminal?.(d)??{}}case P0.terminal_wait_for_exit:{let d=yQt.parse(s);return a.waitForTerminalExit?.(d)}case P0.terminal_kill:{let d=lQt.parse(s);return await a.killTerminal?.(d)??{}}default:if(a.extMethod)return a.extMethod(t,s);throw wa.methodNotFound(t)}},o=async(t,s)=>{switch(t){case P0.session_update:{let d=vQt.parse(s);return a.sessionUpdate(d)}default:if(a.extNotification)return a.extNotification(t,s);throw wa.methodNotFound(t)}};this.#e=new OOe(i,o,r)}async initialize(e){return await this.#e.sendRequest(_u.initialize,e)}async newSession(e){return await this.#e.sendRequest(_u.session_new,e)}async loadSession(e){return await this.#e.sendRequest(_u.session_load,e)??{}}async unstable_forkSession(e){return await this.#e.sendRequest(_u.session_fork,e)}async listSessions(e){return await this.#e.sendRequest(_u.session_list,e)}async unstable_resumeSession(e){return await this.#e.sendRequest(_u.session_resume,e)}async unstable_closeSession(e){return await this.#e.sendRequest(_u.session_close,e)}async setSessionMode(e){return await this.#e.sendRequest(_u.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.#e.sendRequest(_u.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.#e.sendRequest(_u.session_set_config_option,e)}async authenticate(e){return await this.#e.sendRequest(_u.authenticate,e)??{}}async prompt(e){return await this.#e.sendRequest(_u.session_prompt,e)}async cancel(e){return await this.#e.sendNotification(_u.session_cancel,e)}async extMethod(e,r){return await this.#e.sendRequest(e,r)}async extNotification(e,r){return await this.#e.sendNotification(e,r)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},OOe=class{#e=new Map;#t=0;#r;#n;#i;#a=Promise.resolve();#c=new AbortController;#o;constructor(e,r,a){this.#r=e,this.#n=r,this.#i=a,this.#o=new Promise(i=>{this.#c.signal.addEventListener("abort",()=>i())}),this.#s()}get signal(){return this.#c.signal}get closed(){return this.#o}async#s(){let e=this.#i.readable.getReader();try{for(;;){let{value:r,done:a}=await e.read();if(a)break;if(r)try{this.#h(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.#p({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{e.releaseLock(),this.#c.abort()}}async#h(e){if("method"in e&&"id"in e){let r=await this.#d(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.#p({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.#I(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.#l(e):console.error("Invalid message",{message:e})}async#d(e,r){try{return{result:await this.#r(e,r)??null}}catch(a){if(a instanceof wa)return a.toResult();if(a instanceof On.ZodError)return wa.invalidParams(a.format()).toResult();let i;(a instanceof Error||typeof a=="object"&&a!=null&&"message"in a&&typeof a.message=="string")&&(i=a.message);try{return wa.internalError(i?JSON.parse(i):{}).toResult()}catch{return wa.internalError({details:i}).toResult()}}}async#I(e,r){try{return await this.#n(e,r),{result:null}}catch(a){if(a instanceof wa)return a.toResult();if(a instanceof On.ZodError)return wa.invalidParams(a.format()).toResult();let i;(a instanceof Error||typeof a=="object"&&a!=null&&"message"in a&&typeof a.message=="string")&&(i=a.message);try{return wa.internalError(i?JSON.parse(i):{}).toResult()}catch{return wa.internalError({details:i}).toResult()}}}#l(e){let r=this.#e.get(e.id);r?("result"in e?r.resolve(e.result):"error"in e&&r.reject(e.error),this.#e.delete(e.id)):console.error("Got response to unknown request",e.id)}async sendRequest(e,r){let a=this.#t++,i=new Promise((o,t)=>{this.#e.set(a,{resolve:o,reject:t})});return await this.#p({jsonrpc:"2.0",id:a,method:e,params:r}),i}async sendNotification(e,r){await this.#p({jsonrpc:"2.0",method:e,params:r})}async#p(e){return this.#a=this.#a.then(async()=>{let r=this.#i.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{console.error("ACP write error:",r)}),this.#a}},wa=class n extends Error{code;data;constructor(e,r,a){super(r),this.code=e,this.name="RequestError",this.data=a}static parseError(e,r){return new n(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new n(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new n(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new n(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new n(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new n(-32e3,`Authentication required${r?`: ${r}`:""}`,e)}static resourceNotFound(e){return new n(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}});function jne(n){return Object.prototype.hasOwnProperty.call(lyn,n)}function Dk(n,e=process.env){let r=lyn[n];if(!r)throw new Error(`Unknown external agent type: ${n}`);let a=e[kqi[n]]?.trim();if(a){let i=a.split(/\s+/),[o,...t]=i;if(o)return{...r,command:o,args:t}}return r}var iGe,kqi,lyn,sGe=Be(()=>{"use strict";iGe=["claude-code","codex"],kqi={"claude-code":"EASYCODE_CLAUDE_CODE_ACP_CMD",codex:"EASYCODE_CODEX_ACP_CMD"},lyn={"claude-code":{type:"claude-code",label:"Claude Code",command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.52.0"]},codex:{type:"codex",label:"Codex",command:"npx",args:["-y","@agentclientprotocol/codex-acp@1.0.2"]}}});import{spawn as myn}from"node:child_process";import{Readable as Hqi,Writable as Qqi}from"node:stream";import*as EQt from"node:os";import*as qne from"node:fs/promises";import*as pyn from"node:path";function wQt(n){return n&&typeof n=="object"&&"type"in n&&n.type==="text"&&typeof n.text=="string"?n.text:""}function Tqi(n){return Lqi[n??"other"]??"\u{1F527}"}function Jqi(n){return n.line?`${n.path}:${n.line}`:n.path}function WQt(n,e=500){let r=[];for(let a of n)if(a.type==="content"){let i=wQt(a.content);i&&r.push(i.length>e?i.slice(0,e)+"\u2026":i)}else if(a.type==="diff"){let i=a.oldText?`Edit ${a.path}`:`Write ${a.path}`,o=a.newText.slice(0,e);r.push(`${i}
5510
+ `,d=n.getWriter();try{await d.write(r.encode(s))}finally{d.releaseLock()}}});return{readable:i,writable:o}}var oyn=Be(()=>{});var BOe,ZQt,zne,OOe,wa,l_=Be(()=>{s_();jHt();syn();jHt();oyn();BOe=class{#e;constructor(e,r){let a=e(this),i=async(t,s)=>{switch(t){case _u.initialize:{let d=rQt.parse(s);return a.initialize(d)}case _u.session_new:{let d=tQt.parse(s);return a.newSession(d)}case _u.session_load:{if(!a.loadSession)throw wa.methodNotFound(t);let d=cQt.parse(s);return a.loadSession(d)}case _u.session_list:{if(!a.listSessions)throw wa.methodNotFound(t);let d=$Ht.parse(s);return a.listSessions(d)}case _u.session_fork:{if(!a.unstable_forkSession)throw wa.methodNotFound(t);let d=oQt.parse(s);return a.unstable_forkSession(d)}case _u.session_resume:{if(!a.unstable_resumeSession)throw wa.methodNotFound(t);let d=hQt.parse(s);return a.unstable_resumeSession(d)}case _u.session_close:{if(!a.unstable_closeSession)throw wa.methodNotFound(t);let d=iQt.parse(s);return a.unstable_closeSession(d)}case _u.session_set_mode:{if(!a.setSessionMode)throw wa.methodNotFound(t);let d=mQt.parse(s);return await a.setSessionMode(d)??{}}case _u.authenticate:{let d=KHt.parse(s);return await a.authenticate(d)??{}}case _u.session_prompt:{let d=gQt.parse(s);return a.prompt(d)}case _u.session_set_model:{if(!a.unstable_setSessionModel)throw wa.methodNotFound(t);let d=pQt.parse(s);return await a.unstable_setSessionModel(d)??{}}case _u.session_set_config_option:{if(!a.setSessionConfigOption)throw wa.methodNotFound(t);let d=IQt.parse(s);return a.setSessionConfigOption(d)}default:if(a.extMethod)return a.extMethod(t,s);throw wa.methodNotFound(t)}},o=async(t,s)=>{switch(t){case _u.session_cancel:{let d=aQt.parse(s);return a.cancel(d)}default:if(a.extNotification)return a.extNotification(t,s);throw wa.methodNotFound(t)}};this.#e=new OOe(i,o,r)}async sessionUpdate(e){return await this.#e.sendNotification(P0.session_update,e)}async requestPermission(e){return await this.#e.sendRequest(P0.session_request_permission,e)}async readTextFile(e){return await this.#e.sendRequest(P0.fs_read_text_file,e)}async writeTextFile(e){return await this.#e.sendRequest(P0.fs_write_text_file,e)??{}}async createTerminal(e){let r=await this.#e.sendRequest(P0.terminal_create,e);return new ZQt(r.terminalId,e.sessionId,this.#e)}async extMethod(e,r){return await this.#e.sendRequest(e,r)}async extNotification(e,r){return await this.#e.sendNotification(e,r)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},ZQt=class{id;#e;#t;constructor(e,r,a){this.id=e,this.#e=r,this.#t=a}async currentOutput(){return await this.#t.sendRequest(P0.terminal_output,{sessionId:this.#e,terminalId:this.id})}async waitForExit(){return await this.#t.sendRequest(P0.terminal_wait_for_exit,{sessionId:this.#e,terminalId:this.id})}async kill(){return await this.#t.sendRequest(P0.terminal_kill,{sessionId:this.#e,terminalId:this.id})??{}}async release(){return await this.#t.sendRequest(P0.terminal_release,{sessionId:this.#e,terminalId:this.id})??{}}async[Symbol.asyncDispose](){await this.release()}},zne=class{#e;constructor(e,r){let a=e(this),i=async(t,s)=>{switch(t){case P0.fs_write_text_file:{let d=NQt.parse(s);return a.writeTextFile?.(d)}case P0.fs_read_text_file:{let d=uQt.parse(s);return a.readTextFile?.(d)}case P0.session_request_permission:{let d=GQt.parse(s);return a.requestPermission(d)}case P0.terminal_create:{let d=sQt.parse(s);return a.createTerminal?.(d)}case P0.terminal_output:{let d=fQt.parse(s);return a.terminalOutput?.(d)}case P0.terminal_release:{let d=dQt.parse(s);return await a.releaseTerminal?.(d)??{}}case P0.terminal_wait_for_exit:{let d=yQt.parse(s);return a.waitForTerminalExit?.(d)}case P0.terminal_kill:{let d=lQt.parse(s);return await a.killTerminal?.(d)??{}}default:if(a.extMethod)return a.extMethod(t,s);throw wa.methodNotFound(t)}},o=async(t,s)=>{switch(t){case P0.session_update:{let d=vQt.parse(s);return a.sessionUpdate(d)}default:if(a.extNotification)return a.extNotification(t,s);throw wa.methodNotFound(t)}};this.#e=new OOe(i,o,r)}async initialize(e){return await this.#e.sendRequest(_u.initialize,e)}async newSession(e){return await this.#e.sendRequest(_u.session_new,e)}async loadSession(e){return await this.#e.sendRequest(_u.session_load,e)??{}}async unstable_forkSession(e){return await this.#e.sendRequest(_u.session_fork,e)}async listSessions(e){return await this.#e.sendRequest(_u.session_list,e)}async unstable_resumeSession(e){return await this.#e.sendRequest(_u.session_resume,e)}async unstable_closeSession(e){return await this.#e.sendRequest(_u.session_close,e)}async setSessionMode(e){return await this.#e.sendRequest(_u.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.#e.sendRequest(_u.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.#e.sendRequest(_u.session_set_config_option,e)}async authenticate(e){return await this.#e.sendRequest(_u.authenticate,e)??{}}async prompt(e){return await this.#e.sendRequest(_u.session_prompt,e)}async cancel(e){return await this.#e.sendNotification(_u.session_cancel,e)}async extMethod(e,r){return await this.#e.sendRequest(e,r)}async extNotification(e,r){return await this.#e.sendNotification(e,r)}get signal(){return this.#e.signal}get closed(){return this.#e.closed}},OOe=class{#e=new Map;#t=0;#r;#n;#i;#a=Promise.resolve();#c=new AbortController;#o;constructor(e,r,a){this.#r=e,this.#n=r,this.#i=a,this.#o=new Promise(i=>{this.#c.signal.addEventListener("abort",()=>i())}),this.#s()}get signal(){return this.#c.signal}get closed(){return this.#o}async#s(){let e=this.#i.readable.getReader();try{for(;;){let{value:r,done:a}=await e.read();if(a)break;if(r)try{this.#h(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.#p({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{e.releaseLock(),this.#c.abort()}}async#h(e){if("method"in e&&"id"in e){let r=await this.#d(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.#p({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.#I(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.#l(e):console.error("Invalid message",{message:e})}async#d(e,r){try{return{result:await this.#r(e,r)??null}}catch(a){if(a instanceof wa)return a.toResult();if(a instanceof On.ZodError)return wa.invalidParams(a.format()).toResult();let i;(a instanceof Error||typeof a=="object"&&a!=null&&"message"in a&&typeof a.message=="string")&&(i=a.message);try{return wa.internalError(i?JSON.parse(i):{}).toResult()}catch{return wa.internalError({details:i}).toResult()}}}async#I(e,r){try{return await this.#n(e,r),{result:null}}catch(a){if(a instanceof wa)return a.toResult();if(a instanceof On.ZodError)return wa.invalidParams(a.format()).toResult();let i;(a instanceof Error||typeof a=="object"&&a!=null&&"message"in a&&typeof a.message=="string")&&(i=a.message);try{return wa.internalError(i?JSON.parse(i):{}).toResult()}catch{return wa.internalError({details:i}).toResult()}}}#l(e){let r=this.#e.get(e.id);r?("result"in e?r.resolve(e.result):"error"in e&&r.reject(e.error),this.#e.delete(e.id)):console.error("Got response to unknown request",e.id)}async sendRequest(e,r){let a=this.#t++,i=new Promise((o,t)=>{this.#e.set(a,{resolve:o,reject:t})});return await this.#p({jsonrpc:"2.0",id:a,method:e,params:r}),i}async sendNotification(e,r){await this.#p({jsonrpc:"2.0",method:e,params:r})}async#p(e){return this.#a=this.#a.then(async()=>{let r=this.#i.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{console.error("ACP write error:",r)}),this.#a}},wa=class n extends Error{code;data;constructor(e,r,a){super(r),this.code=e,this.name="RequestError",this.data=a}static parseError(e,r){return new n(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new n(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new n(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new n(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new n(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new n(-32e3,`Authentication required${r?`: ${r}`:""}`,e)}static resourceNotFound(e){return new n(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}});function jne(n){return Object.prototype.hasOwnProperty.call(lyn,n)}function Dk(n,e=process.env){let r=lyn[n];if(!r)throw new Error(`Unknown external agent type: ${n}`);let a=e[kqi[n]]?.trim();if(a){let i=a.split(/\s+/),[o,...t]=i;if(o)return{...r,command:o,args:t}}return r}var iGe,kqi,lyn,sGe=Be(()=>{"use strict";iGe=["claude-code","codex"],kqi={"claude-code":"EASYCODE_CLAUDE_CODE_ACP_CMD",codex:"EASYCODE_CODEX_ACP_CMD"},lyn={"claude-code":{type:"claude-code",label:"Claude Code",command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.62.0"]},codex:{type:"codex",label:"Codex",command:"npx",args:["-y","@agentclientprotocol/codex-acp@1.1.7"]}}});import{spawn as myn}from"node:child_process";import{Readable as Hqi,Writable as Qqi}from"node:stream";import*as EQt from"node:os";import*as qne from"node:fs/promises";import*as pyn from"node:path";function wQt(n){return n&&typeof n=="object"&&"type"in n&&n.type==="text"&&typeof n.text=="string"?n.text:""}function Tqi(n){return Lqi[n??"other"]??"\u{1F527}"}function Jqi(n){return n.line?`${n.path}:${n.line}`:n.path}function WQt(n,e=500){let r=[];for(let a of n)if(a.type==="content"){let i=wQt(a.content);i&&r.push(i.length>e?i.slice(0,e)+"\u2026":i)}else if(a.type==="diff"){let i=a.oldText?`Edit ${a.path}`:`Write ${a.path}`,o=a.newText.slice(0,e);r.push(`${i}
5511
5511
  ${o}${a.newText.length>e?"\u2026":""}`)}else a.type;return r.join(`
5512
5512
  `)}function Bqi(n,e={}){let r=n;if(!r||typeof r!="object")return"";let a=r.terminal_output?.data,i=typeof a=="string"?a:"",o=r.terminal_exit?.exit_code,t=typeof o=="number";if(!i)return t?"```console\n[exit code: "+o+"]\n```":"";let s=e.maxChars??2e3,d=e.maxLines??40,h=i,u=!1,I=h.split(`
5513
5513
  `);I.length>d&&(h=I.slice(-d).join(`
@@ -5798,7 +5798,7 @@ ${a}
5798
5798
  \u{1F50D} Model Diagnostics: ${n}`),console.log(`\u{1F4CA} Reliability: ${r.capabilities.toolCallReliability}`),console.log(`\u{1F527} Format Tolerance: ${r.capabilities.needsFormatTolerance?"Yes":"No"}`),console.log(`\u{1F504} Max Concurrent Tools: ${r.capabilities.maxConcurrentTools}`),r.warnings.length>0&&(console.log(`
5799
5799
  \u26A0\uFE0F Warnings:`),r.warnings.forEach(a=>console.log(` \u2022 ${a}`))),e&&r.recommendations.length>0&&(console.log(`
5800
5800
  \u{1F4A1} Recommendations:`),r.recommendations.forEach(a=>console.log(` \u2022 ${a}`))),e&&(console.log(`
5801
- \u{1F4CB} Full Capabilities:`),console.log(JSON.stringify(r.capabilities,null,2)))}function Gns(n){let e=qDe(n);return e.isSmallModel||e.needsSpecialHandling}function vns(n){let e=qDe(n);return e.capabilities.toolCallReliability==="high"?"\u2705 Excellent tool calling compatibility":e.capabilities.toolCallReliability==="medium"?"\u{1F7E1} Good compatibility with enhanced error handling":"\u{1F7E0} Limited compatibility - enhanced robustness features active"}var $Wn=Be(()=>{"use strict";R0e();});import*as sw from"fs";import*as KDe from"path";var yns,XGe,ewn=Be(()=>{"use strict";Ch();yns="healthy-use-reminder.json",XGe=class{projectRoot;stateFilePath;constructor(e){this.projectRoot=e;let r=vv(e);this.stateFilePath=KDe.join(r,yns)}shouldShowReminder(){let r=new Date().getHours();if(!(r>=22||r<6))return this.clearState(),!1;let i=this.loadState();if(!i||i.lastReminderShownAt===0)return!0;let o=2700*1e3;return Date.now()-i.lastReminderShownAt>=o}markReminderShown(){this.saveState({lastReminderShownAt:Date.now()})}clearState(){try{sw.existsSync(this.stateFilePath)&&sw.unlinkSync(this.stateFilePath)}catch(e){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to clear state:",e)}}loadState(){try{if(!sw.existsSync(this.stateFilePath))return null;let e=sw.readFileSync(this.stateFilePath,"utf-8");return JSON.parse(e)}catch(e){return process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to load state:",e),null}}saveState(e){try{let r=KDe.dirname(this.stateFilePath);sw.existsSync(r)||sw.mkdirSync(r,{recursive:!0}),sw.writeFileSync(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}catch(r){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to save state:",r)}}}});var F6t,E6t,Nns,Zns,Wns,twn=Be(()=>{"use strict";F6t="--- Content from referenced files ---",E6t="--- End of content ---",Nns=2e3,Zns=2e3,Wns=20});function nwn(...n){return wns(...n)}function awn(...n){return Fns(...n)}function rwn(n,e){return n in e}function R6t(){let n={get(i,o){if(o==="write")return nwn;if(rwn(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},e=new Proxy(process.stdout,n),r={get(i,o){if(o==="write")return awn;if(rwn(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},a=new Proxy(process.stderr,r);return{stdout:e,stderr:a}}var wns,Fns,iwn=Be(()=>{"use strict";wns=process.stdout.write.bind(process.stdout),Fns=process.stderr.write.bind(process.stderr)});import{readFile as Ens}from"node:fs/promises";import{fileURLToPath as Rns}from"node:url";import A6t from"node:path";function Ans(){let n=globalThis.import?.meta??void 0;try{let r=typeof import.meta<"u"?import.meta.url:void 0;if(r)return A6t.dirname(Rns(r))}catch{}let e=globalThis.__dirname;return typeof e=="string"?e:process.cwd()}function yx(){return SGe||(SGe=(async()=>"1.1.59")(),SGe)}function xns(){SGe=void 0}var SGe,x6t=Be(()=>{"use strict";});import{EventEmitter as Cns}from"node:events";var LGe,C6t,Y6t,swn=Be(()=>{"use strict";(function(n){n.ApprovalModeChanged="approval_mode_changed"})(LGe||(LGe={}));C6t=class{emitter=new Cns;on(e,r){return this.emitter.on(e,r),()=>this.emitter.off(e,r)}off(e,r){this.emitter.off(e,r)}emit(e,r){this.emitter.emit(e,r)}removeAllListeners(e){e?this.emitter.removeAllListeners(e):this.emitter.removeAllListeners()}},Y6t=new C6t});function $De(n){return Array.isArray(n)?n.map(e=>typeof e=="string"?{text:e}:e):typeof n=="string"?[{text:n}]:[n]}function Yns(n){return n.map(e=>typeof e.text=="string"?e.text:"").join("")}function V6t(n){if(!n||n.length===0)return[];let e=[];for(let r of n){if(r.role&&(r.parts||r.content!==void 0)){let a=r.parts??$De(r.content);e.push({role:r.role,parts:a});continue}if(!(r.type==="info"||r.type==="error"||r.type==="warning")){if(r.type==="user"){let a=r.content!==void 0?$De(r.content):[],i=Yns(a).trim();if(i.startsWith("/")||i.startsWith("?")||a.length===0)continue;e.push({role:"user",parts:a});continue}if(r.type==="gemini"){let a=[];if(r.thoughts&&r.thoughts.length>0)for(let o of r.thoughts){let t=o.subject?`**${o.subject}** ${o.description}`:o.description;a.push({text:t,thought:!0})}let i=!!r.toolCalls&&r.toolCalls.length>0;if(r.content!==void 0&&a.push(...$De(r.content)),i)for(let o of r.toolCalls)a.push({functionCall:{name:o.name,args:o.args,...o.id?{id:o.id}:{}}});if(a.length>0&&e.push({role:"model",parts:a}),i){let o=[];for(let t of r.toolCalls)t.result!==void 0&&(typeof t.result=="string"?o.push({functionResponse:{id:t.id,name:t.name,response:{output:t.result}}}):Array.isArray(t.result)?o.push(...$De(t.result)):o.push(t.result));o.length>0&&e.push({role:"user",parts:o})}}}}return e}var own=Be(()=>{"use strict";});var y_,lwn,TGe,cwn=Be(()=>{"use strict";y_=class n extends Error{constructor(e){super(e),this.name="SessionError"}static noSessionsFound(){return new n("No persisted sessions found.")}static invalidSessionIdentifier(e,r){return new n(`Session '${e}' was not found under ${r}.`)}},lwn="latest",TGe=class{manager;constructor(e){this.manager=e}async sessionExists(e){return(await this.listAllMetadata()).some(a=>a.sessionId===e)}async listSessions(){return(await this.listAllMetadata()).map(r=>({id:r.sessionId,startTime:r.createdAt,title:r.title,messageCount:r.messageCount})).sort((r,a)=>new Date(r.startTime).getTime()-new Date(a.startTime).getTime())}async findSession(e){let r=e.trim(),a=await this.listSessions();if(a.length===0)throw y_.noSessionsFound();let i=a.find(t=>t.id===r);if(i)return i;let o=Number.parseInt(r,10);if(Number.isInteger(o)&&o.toString()===r&&o>0&&o<=a.length)return a[o-1];throw y_.invalidSessionIdentifier(r,"sessions/")}async resolveSession(e){let r=e.trim(),a;if(r===lwn){let o=await this.listSessions();if(o.length===0)throw y_.noSessionsFound();a=o[o.length-1]}else a=await this.findSession(r);let i=await this.manager.loadSession(a.id);if(!i)throw new y_(`Session '${a.id}' exists in index but could not be loaded.`);return{session:a,data:i}}async listAllMetadata(){let e=this.manager;return typeof e.listSessions=="function"?await e.listSessions():typeof e.getSessionIndex=="function"?(await e.getSessionIndex())?.sessions??[]:[]}}});function Vns(n,e,r){return new e_e(n,e,r)}var e_e,t_e,r_e,uwn=Be(()=>{"use strict";y0e();eY();e_e=class n{tokenManager;baseURL;requestQueue=[];isRefreshing=!1;onAuthenticationRequired;constructor(e,r,a){this.baseURL=e.replace(/\/$/,""),this.tokenManager=r,this.onAuthenticationRequired=a}setAuthenticationRequiredCallback(e){this.onAuthenticationRequired=e}async request(e,r={}){let a=`${this.baseURL}${e}`,i=await this.prepareRequestOptions(r),o=await fetch(a,i);return o.status===401&&this.tokenManager&&(o=await this.handleUnauthorized(a,i)),o}async get(e,r={}){return this.request(e,{...r,method:"GET"})}async post(e,r,a={}){let i={...a,method:"POST",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async put(e,r,a={}){let i={...a,method:"PUT",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async delete(e,r={}){return this.request(e,{...r,method:"DELETE"})}async prepareRequestOptions(e){let r={"User-Agent":nd(),...e.headers};if(this.tokenManager)try{let a=await this.tokenManager.getAccessToken();a?r.Authorization=`Bearer ${a}`:bV("warn","\u26A0\uFE0F No access token available")}catch(a){bV("warn","\u26A0\uFE0F Failed to get access token:",a),this.onAuthenticationRequired&&a instanceof Error&&a.message?.includes("authentication required")&&(bV("log","\u{1F504} Triggering authentication flow..."),this.onAuthenticationRequired())}return{...e,headers:r}}async handleUnauthorized(e,r){if(this.isRefreshing)return new Promise((a,i)=>{this.requestQueue.push({resolve:a,reject:i,request:()=>fetch(e,r)})});this.isRefreshing=!0;try{bV("log","\u{1F504} Access token expired, attempting refresh...");let a=await this.tokenManager.refreshAccessToken();if(a){bV("log","\u2705 Token refreshed successfully");let i={...r,headers:{...r.headers,Authorization:`Bearer ${a}`}},o=fetch(e,i);return this.processRequestQueue(a),await o}else throw new Error("Failed to refresh token")}catch(a){throw console.error("\u274C Token refresh failed:",a),this.tokenManager.clearTokens?await this.tokenManager.clearTokens():this.tokenManager.clear&&this.tokenManager.clear(),this.rejectRequestQueue(new Error("Authentication required")),this.onAuthenticationRequired&&(bV("log","\u{1F504} Authentication required, triggering auth flow..."),this.onAuthenticationRequired()),new t_e("Authentication required - please re-authenticate")}finally{this.isRefreshing=!1}}processRequestQueue(e){this.requestQueue.splice(0).forEach(({resolve:a,reject:i,request:o})=>{o().then(t=>a(t)).catch(t=>i(t))})}rejectRequestQueue(e){this.requestQueue.splice(0).forEach(({reject:a})=>{a(e)})}static async checkResponse(e){if(!e.ok){let a=await e.text();throw new r_e(`HTTP ${e.status}: ${e.statusText}`,e.status,a)}let r=e.headers.get("content-type");return r&&r.includes("application/json")?await e.json():await e.text()}async requestJson(e,r={}){let a=await this.request(e,r);return n.checkResponse(a)}async postJson(e,r){let a=await this.post(e,r);return n.checkResponse(a)}async putJson(e,r){let a=await this.put(e,r);return n.checkResponse(a)}async getJson(e){let r=await this.get(e);return n.checkResponse(r)}async deleteJson(e){let r=await this.delete(e);return n.checkResponse(r)}},t_e=class extends Error{constructor(e){super(e),this.name="AuthenticationError"}},r_e=class extends Error{status;response;constructor(e,r,a){super(e),this.name="HttpError",this.status=r,this.response=a}}});function kns(n){return JGe.getInstance(n)}function Hns(n){let e=JGe.getInstance(n);return()=>e.handleAuthenticationRequired()}var JGe,dwn=Be(()=>{"use strict";nA();JGe=class n{static instance=null;config;isAuthenticating=!1;constructor(e={}){this.config={authUrl:"/auth",autoOpenBrowser:!0,...e}}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}updateConfig(e){this.config={...this.config,...e}}async handleAuthenticationRequired(){if(this.isAuthenticating){console.log("[AuthNavigator] Authentication already in progress, skipping...");return}this.isAuthenticating=!0;try{console.log("\u{1F510} [AuthNavigator] Authentication required"),gs.getInstance().clear(),this.config.customAuthHandler?(console.log("[AuthNavigator] Using custom authentication handler"),await this.config.customAuthHandler()):await this.handleDefaultAuthentication()}catch(e){console.error("[AuthNavigator] Authentication handling failed:",e)}finally{this.isAuthenticating=!1}}async handleDefaultAuthentication(){console.log("[AuthNavigator] Starting default authentication flow"),typeof process<"u"&&process.argv?await this.handleCLIAuthentication():await this.handleWebAuthentication()}async handleCLIAuthentication(){console.log(""),console.log("\u{1F510} \u8BA4\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u9700\u8981\u91CD\u65B0\u8BA4\u8BC1"),console.log("\u{1F4A1} \u8BF7\u5728CLI\u4E2D\u8F93\u5165 /auth \u547D\u4EE4\u8FDB\u884C\u91CD\u65B0\u8BA4\u8BC1"),console.log("")}async handleWebAuthentication(){if(typeof window<"u"){let a=`${gs.getInstance().getProxyServerUrl()}${this.config.authUrl}`;console.log(`[AuthNavigator] Redirecting to auth page: ${a}`),window.location.href=a}else console.error("[AuthNavigator] Cannot redirect in non-browser environment")}isInProgress(){return this.isAuthenticating}}});function a_e(n){let r={authUrl:"https://accounts.deepvlab.ai/login",redirectUri:`http://localhost:${n||7863}/callback?plat=deepvlab`};return new n_e(r)}var n_e,k6t=Be(()=>{"use strict";n_e=class{config;constructor(e){this.config=e}buildAuthUrl(){let e=`${this.config.authUrl}?redirect_to=${encodeURIComponent(this.config.redirectUri)}&redirect_mode=same_window`;return console.log("\u{1F517} DeepVlab\u8BA4\u8BC1URL:",e),e}handleCallback(e){console.log("\u{1F504} [DeepVlab Auth] \u5904\u7406DeepVlab\u8BA4\u8BC1\u56DE\u8C03"),console.log("\u{1F504} [DeepVlab Auth] \u56DE\u8C03URL:",e.toString());let r=Object.fromEntries(e.searchParams.entries());console.log("\u{1F504} [DeepVlab Auth] \u56DE\u8C03\u53C2\u6570:",r);let a=e.searchParams.get("token"),i=e.searchParams.get("user_id"),o=e.searchParams.get("error");return o?(console.error("\u274C [DeepVlab Auth] \u8BA4\u8BC1\u9519\u8BEF:",o),{success:!1,error:`DeepVlab\u8BA4\u8BC1\u5931\u8D25: ${o}`}):a?i?(console.log("\u{1F389} [DeepVlab Auth] \u83B7\u53D6\u5230JWT Token:",a),console.log("\u{1F389} [DeepVlab Auth] \u83B7\u53D6\u5230User ID:",i),console.log("\u2705 [DeepVlab Auth] DeepVlab\u8BA4\u8BC1\u6210\u529F"),{success:!0,token:a,user_id:i}):(console.error("\u274C [DeepVlab Auth] \u7F3A\u5C11user_id\u53C2\u6570"),{success:!1,error:"DeepVlab\u8BA4\u8BC1\u56DE\u8C03\u4E2D\u7F3A\u5C11user_id\u53C2\u6570"}):(console.error("\u274C [DeepVlab Auth] \u7F3A\u5C11token\u53C2\u6570"),{success:!1,error:"DeepVlab\u8BA4\u8BC1\u56DE\u8C03\u4E2D\u7F3A\u5C11token\u53C2\u6570"})}}});import*as i_e from"fs";import*as MG from"path";function Qns(){return typeof globalThis.__dirname=="string"?globalThis.__dirname:""}var BGe,xS,H6t=Be(()=>{"use strict";BGe=Qns(),xS=class{static cache=new Map;static customBasePath=null;static setBasePath(e){this.customBasePath=e,console.log(`\u{1F4C1} [AuthTemplates] Custom base path set: ${e}`)}static getAuthSelectPage(){return this.loadTemplate("authSelectPage.html")}static getFeishuSuccessPage(){return this.generateFeishuSuccessTemplate()}static getDeepvlabSuccessPage(){return this.generateDeepvlabSuccessTemplate()}static getErrorPage(e){return this.generateErrorTemplate(e)}static loadTemplate(e){if(this.cache.has(e))return this.cache.get(e);try{let r=[];if(this.customBasePath&&(r.push(MG.join(this.customBasePath,"dist","bundled","auth","login","templates",e)),r.push(MG.join(this.customBasePath,"bundled","auth","login","templates",e)),r.push(MG.join(this.customBasePath,"auth","login","templates",e))),BGe&&r.push(MG.join(BGe,e)),BGe){let o=BGe;for(let t=0;t<10;t++)r.push(MG.join(o,"bundled","auth","login","templates",e)),r.push(MG.join(o,"bundled",e)),r.push(MG.join(o,"bundle","login","templates",e)),r.push(MG.join(o,"auth","login","templates",e)),o=MG.dirname(o)}if(typeof process<"u"&&process.cwd)try{let o=process.cwd();r.push(MG.join(o,"bundle","login","templates",e)),r.push(MG.join(o,"dist","bundled","auth","login","templates",e)),r.push(MG.join(o,"bundled","auth","login","templates",e)),r.push(MG.join(o,"auth","login","templates",e))}catch{}let a=null;for(let o of r)try{if(i_e.existsSync(o)){a=o,console.error(`\u2705 [AuthTemplates] Template loaded: ${e} from ${o}`);break}}catch{continue}if(!a){if(console.warn(`\u26A0\uFE0F [AuthTemplates] Template ${e} not found in any location.`),console.warn(` Tried ${r.length} paths. First 5:`),r.slice(0,5).forEach((o,t)=>console.warn(` ${t+1}. ${o}`)),console.warn(` Current dirname: ${BGe||"(unavailable - cross-platform build)"}`),console.warn(` Custom base path: ${this.customBasePath||"(not set)"}`),typeof process<"u"&&process.cwd)try{console.warn(` Process cwd: ${process.cwd()}`)}catch{console.warn(" Process cwd: unavailable")}return console.log(`\u2139\uFE0F [AuthTemplates] Using fallback template for ${e}`),this.generateBasicAuthSelectTemplate()}let i=i_e.readFileSync(a,"utf-8");return this.cache.set(e,i),i}catch(r){return console.error(`\u274C [AuthTemplates] Failed to load template ${e}:`,r),this.generateBasicAuthSelectTemplate()}}static generateBasicAuthSelectTemplate(){return`
5801
+ \u{1F4CB} Full Capabilities:`),console.log(JSON.stringify(r.capabilities,null,2)))}function Gns(n){let e=qDe(n);return e.isSmallModel||e.needsSpecialHandling}function vns(n){let e=qDe(n);return e.capabilities.toolCallReliability==="high"?"\u2705 Excellent tool calling compatibility":e.capabilities.toolCallReliability==="medium"?"\u{1F7E1} Good compatibility with enhanced error handling":"\u{1F7E0} Limited compatibility - enhanced robustness features active"}var $Wn=Be(()=>{"use strict";R0e();});import*as sw from"fs";import*as KDe from"path";var yns,XGe,ewn=Be(()=>{"use strict";Ch();yns="healthy-use-reminder.json",XGe=class{projectRoot;stateFilePath;constructor(e){this.projectRoot=e;let r=vv(e);this.stateFilePath=KDe.join(r,yns)}shouldShowReminder(){let r=new Date().getHours();if(!(r>=22||r<6))return this.clearState(),!1;let i=this.loadState();if(!i||i.lastReminderShownAt===0)return!0;let o=2700*1e3;return Date.now()-i.lastReminderShownAt>=o}markReminderShown(){this.saveState({lastReminderShownAt:Date.now()})}clearState(){try{sw.existsSync(this.stateFilePath)&&sw.unlinkSync(this.stateFilePath)}catch(e){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to clear state:",e)}}loadState(){try{if(!sw.existsSync(this.stateFilePath))return null;let e=sw.readFileSync(this.stateFilePath,"utf-8");return JSON.parse(e)}catch(e){return process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to load state:",e),null}}saveState(e){try{let r=KDe.dirname(this.stateFilePath);sw.existsSync(r)||sw.mkdirSync(r,{recursive:!0}),sw.writeFileSync(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}catch(r){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to save state:",r)}}}});var F6t,E6t,Nns,Zns,Wns,twn=Be(()=>{"use strict";F6t="--- Content from referenced files ---",E6t="--- End of content ---",Nns=2e3,Zns=2e3,Wns=20});function nwn(...n){return wns(...n)}function awn(...n){return Fns(...n)}function rwn(n,e){return n in e}function R6t(){let n={get(i,o){if(o==="write")return nwn;if(rwn(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},e=new Proxy(process.stdout,n),r={get(i,o){if(o==="write")return awn;if(rwn(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},a=new Proxy(process.stderr,r);return{stdout:e,stderr:a}}var wns,Fns,iwn=Be(()=>{"use strict";wns=process.stdout.write.bind(process.stdout),Fns=process.stderr.write.bind(process.stderr)});import{readFile as Ens}from"node:fs/promises";import{fileURLToPath as Rns}from"node:url";import A6t from"node:path";function Ans(){let n=globalThis.import?.meta??void 0;try{let r=typeof import.meta<"u"?import.meta.url:void 0;if(r)return A6t.dirname(Rns(r))}catch{}let e=globalThis.__dirname;return typeof e=="string"?e:process.cwd()}function yx(){return SGe||(SGe=(async()=>"1.1.60")(),SGe)}function xns(){SGe=void 0}var SGe,x6t=Be(()=>{"use strict";});import{EventEmitter as Cns}from"node:events";var LGe,C6t,Y6t,swn=Be(()=>{"use strict";(function(n){n.ApprovalModeChanged="approval_mode_changed"})(LGe||(LGe={}));C6t=class{emitter=new Cns;on(e,r){return this.emitter.on(e,r),()=>this.emitter.off(e,r)}off(e,r){this.emitter.off(e,r)}emit(e,r){this.emitter.emit(e,r)}removeAllListeners(e){e?this.emitter.removeAllListeners(e):this.emitter.removeAllListeners()}},Y6t=new C6t});function $De(n){return Array.isArray(n)?n.map(e=>typeof e=="string"?{text:e}:e):typeof n=="string"?[{text:n}]:[n]}function Yns(n){return n.map(e=>typeof e.text=="string"?e.text:"").join("")}function V6t(n){if(!n||n.length===0)return[];let e=[];for(let r of n){if(r.role&&(r.parts||r.content!==void 0)){let a=r.parts??$De(r.content);e.push({role:r.role,parts:a});continue}if(!(r.type==="info"||r.type==="error"||r.type==="warning")){if(r.type==="user"){let a=r.content!==void 0?$De(r.content):[],i=Yns(a).trim();if(i.startsWith("/")||i.startsWith("?")||a.length===0)continue;e.push({role:"user",parts:a});continue}if(r.type==="gemini"){let a=[];if(r.thoughts&&r.thoughts.length>0)for(let o of r.thoughts){let t=o.subject?`**${o.subject}** ${o.description}`:o.description;a.push({text:t,thought:!0})}let i=!!r.toolCalls&&r.toolCalls.length>0;if(r.content!==void 0&&a.push(...$De(r.content)),i)for(let o of r.toolCalls)a.push({functionCall:{name:o.name,args:o.args,...o.id?{id:o.id}:{}}});if(a.length>0&&e.push({role:"model",parts:a}),i){let o=[];for(let t of r.toolCalls)t.result!==void 0&&(typeof t.result=="string"?o.push({functionResponse:{id:t.id,name:t.name,response:{output:t.result}}}):Array.isArray(t.result)?o.push(...$De(t.result)):o.push(t.result));o.length>0&&e.push({role:"user",parts:o})}}}}return e}var own=Be(()=>{"use strict";});var y_,lwn,TGe,cwn=Be(()=>{"use strict";y_=class n extends Error{constructor(e){super(e),this.name="SessionError"}static noSessionsFound(){return new n("No persisted sessions found.")}static invalidSessionIdentifier(e,r){return new n(`Session '${e}' was not found under ${r}.`)}},lwn="latest",TGe=class{manager;constructor(e){this.manager=e}async sessionExists(e){return(await this.listAllMetadata()).some(a=>a.sessionId===e)}async listSessions(){return(await this.listAllMetadata()).map(r=>({id:r.sessionId,startTime:r.createdAt,title:r.title,messageCount:r.messageCount})).sort((r,a)=>new Date(r.startTime).getTime()-new Date(a.startTime).getTime())}async findSession(e){let r=e.trim(),a=await this.listSessions();if(a.length===0)throw y_.noSessionsFound();let i=a.find(t=>t.id===r);if(i)return i;let o=Number.parseInt(r,10);if(Number.isInteger(o)&&o.toString()===r&&o>0&&o<=a.length)return a[o-1];throw y_.invalidSessionIdentifier(r,"sessions/")}async resolveSession(e){let r=e.trim(),a;if(r===lwn){let o=await this.listSessions();if(o.length===0)throw y_.noSessionsFound();a=o[o.length-1]}else a=await this.findSession(r);let i=await this.manager.loadSession(a.id);if(!i)throw new y_(`Session '${a.id}' exists in index but could not be loaded.`);return{session:a,data:i}}async listAllMetadata(){let e=this.manager;return typeof e.listSessions=="function"?await e.listSessions():typeof e.getSessionIndex=="function"?(await e.getSessionIndex())?.sessions??[]:[]}}});function Vns(n,e,r){return new e_e(n,e,r)}var e_e,t_e,r_e,uwn=Be(()=>{"use strict";y0e();eY();e_e=class n{tokenManager;baseURL;requestQueue=[];isRefreshing=!1;onAuthenticationRequired;constructor(e,r,a){this.baseURL=e.replace(/\/$/,""),this.tokenManager=r,this.onAuthenticationRequired=a}setAuthenticationRequiredCallback(e){this.onAuthenticationRequired=e}async request(e,r={}){let a=`${this.baseURL}${e}`,i=await this.prepareRequestOptions(r),o=await fetch(a,i);return o.status===401&&this.tokenManager&&(o=await this.handleUnauthorized(a,i)),o}async get(e,r={}){return this.request(e,{...r,method:"GET"})}async post(e,r,a={}){let i={...a,method:"POST",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async put(e,r,a={}){let i={...a,method:"PUT",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async delete(e,r={}){return this.request(e,{...r,method:"DELETE"})}async prepareRequestOptions(e){let r={"User-Agent":nd(),...e.headers};if(this.tokenManager)try{let a=await this.tokenManager.getAccessToken();a?r.Authorization=`Bearer ${a}`:bV("warn","\u26A0\uFE0F No access token available")}catch(a){bV("warn","\u26A0\uFE0F Failed to get access token:",a),this.onAuthenticationRequired&&a instanceof Error&&a.message?.includes("authentication required")&&(bV("log","\u{1F504} Triggering authentication flow..."),this.onAuthenticationRequired())}return{...e,headers:r}}async handleUnauthorized(e,r){if(this.isRefreshing)return new Promise((a,i)=>{this.requestQueue.push({resolve:a,reject:i,request:()=>fetch(e,r)})});this.isRefreshing=!0;try{bV("log","\u{1F504} Access token expired, attempting refresh...");let a=await this.tokenManager.refreshAccessToken();if(a){bV("log","\u2705 Token refreshed successfully");let i={...r,headers:{...r.headers,Authorization:`Bearer ${a}`}},o=fetch(e,i);return this.processRequestQueue(a),await o}else throw new Error("Failed to refresh token")}catch(a){throw console.error("\u274C Token refresh failed:",a),this.tokenManager.clearTokens?await this.tokenManager.clearTokens():this.tokenManager.clear&&this.tokenManager.clear(),this.rejectRequestQueue(new Error("Authentication required")),this.onAuthenticationRequired&&(bV("log","\u{1F504} Authentication required, triggering auth flow..."),this.onAuthenticationRequired()),new t_e("Authentication required - please re-authenticate")}finally{this.isRefreshing=!1}}processRequestQueue(e){this.requestQueue.splice(0).forEach(({resolve:a,reject:i,request:o})=>{o().then(t=>a(t)).catch(t=>i(t))})}rejectRequestQueue(e){this.requestQueue.splice(0).forEach(({reject:a})=>{a(e)})}static async checkResponse(e){if(!e.ok){let a=await e.text();throw new r_e(`HTTP ${e.status}: ${e.statusText}`,e.status,a)}let r=e.headers.get("content-type");return r&&r.includes("application/json")?await e.json():await e.text()}async requestJson(e,r={}){let a=await this.request(e,r);return n.checkResponse(a)}async postJson(e,r){let a=await this.post(e,r);return n.checkResponse(a)}async putJson(e,r){let a=await this.put(e,r);return n.checkResponse(a)}async getJson(e){let r=await this.get(e);return n.checkResponse(r)}async deleteJson(e){let r=await this.delete(e);return n.checkResponse(r)}},t_e=class extends Error{constructor(e){super(e),this.name="AuthenticationError"}},r_e=class extends Error{status;response;constructor(e,r,a){super(e),this.name="HttpError",this.status=r,this.response=a}}});function kns(n){return JGe.getInstance(n)}function Hns(n){let e=JGe.getInstance(n);return()=>e.handleAuthenticationRequired()}var JGe,dwn=Be(()=>{"use strict";nA();JGe=class n{static instance=null;config;isAuthenticating=!1;constructor(e={}){this.config={authUrl:"/auth",autoOpenBrowser:!0,...e}}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}updateConfig(e){this.config={...this.config,...e}}async handleAuthenticationRequired(){if(this.isAuthenticating){console.log("[AuthNavigator] Authentication already in progress, skipping...");return}this.isAuthenticating=!0;try{console.log("\u{1F510} [AuthNavigator] Authentication required"),gs.getInstance().clear(),this.config.customAuthHandler?(console.log("[AuthNavigator] Using custom authentication handler"),await this.config.customAuthHandler()):await this.handleDefaultAuthentication()}catch(e){console.error("[AuthNavigator] Authentication handling failed:",e)}finally{this.isAuthenticating=!1}}async handleDefaultAuthentication(){console.log("[AuthNavigator] Starting default authentication flow"),typeof process<"u"&&process.argv?await this.handleCLIAuthentication():await this.handleWebAuthentication()}async handleCLIAuthentication(){console.log(""),console.log("\u{1F510} \u8BA4\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u9700\u8981\u91CD\u65B0\u8BA4\u8BC1"),console.log("\u{1F4A1} \u8BF7\u5728CLI\u4E2D\u8F93\u5165 /auth \u547D\u4EE4\u8FDB\u884C\u91CD\u65B0\u8BA4\u8BC1"),console.log("")}async handleWebAuthentication(){if(typeof window<"u"){let a=`${gs.getInstance().getProxyServerUrl()}${this.config.authUrl}`;console.log(`[AuthNavigator] Redirecting to auth page: ${a}`),window.location.href=a}else console.error("[AuthNavigator] Cannot redirect in non-browser environment")}isInProgress(){return this.isAuthenticating}}});function a_e(n){let r={authUrl:"https://accounts.deepvlab.ai/login",redirectUri:`http://localhost:${n||7863}/callback?plat=deepvlab`};return new n_e(r)}var n_e,k6t=Be(()=>{"use strict";n_e=class{config;constructor(e){this.config=e}buildAuthUrl(){let e=`${this.config.authUrl}?redirect_to=${encodeURIComponent(this.config.redirectUri)}&redirect_mode=same_window`;return console.log("\u{1F517} DeepVlab\u8BA4\u8BC1URL:",e),e}handleCallback(e){console.log("\u{1F504} [DeepVlab Auth] \u5904\u7406DeepVlab\u8BA4\u8BC1\u56DE\u8C03"),console.log("\u{1F504} [DeepVlab Auth] \u56DE\u8C03URL:",e.toString());let r=Object.fromEntries(e.searchParams.entries());console.log("\u{1F504} [DeepVlab Auth] \u56DE\u8C03\u53C2\u6570:",r);let a=e.searchParams.get("token"),i=e.searchParams.get("user_id"),o=e.searchParams.get("error");return o?(console.error("\u274C [DeepVlab Auth] \u8BA4\u8BC1\u9519\u8BEF:",o),{success:!1,error:`DeepVlab\u8BA4\u8BC1\u5931\u8D25: ${o}`}):a?i?(console.log("\u{1F389} [DeepVlab Auth] \u83B7\u53D6\u5230JWT Token:",a),console.log("\u{1F389} [DeepVlab Auth] \u83B7\u53D6\u5230User ID:",i),console.log("\u2705 [DeepVlab Auth] DeepVlab\u8BA4\u8BC1\u6210\u529F"),{success:!0,token:a,user_id:i}):(console.error("\u274C [DeepVlab Auth] \u7F3A\u5C11user_id\u53C2\u6570"),{success:!1,error:"DeepVlab\u8BA4\u8BC1\u56DE\u8C03\u4E2D\u7F3A\u5C11user_id\u53C2\u6570"}):(console.error("\u274C [DeepVlab Auth] \u7F3A\u5C11token\u53C2\u6570"),{success:!1,error:"DeepVlab\u8BA4\u8BC1\u56DE\u8C03\u4E2D\u7F3A\u5C11token\u53C2\u6570"})}}});import*as i_e from"fs";import*as MG from"path";function Qns(){return typeof globalThis.__dirname=="string"?globalThis.__dirname:""}var BGe,xS,H6t=Be(()=>{"use strict";BGe=Qns(),xS=class{static cache=new Map;static customBasePath=null;static setBasePath(e){this.customBasePath=e,console.log(`\u{1F4C1} [AuthTemplates] Custom base path set: ${e}`)}static getAuthSelectPage(){return this.loadTemplate("authSelectPage.html")}static getFeishuSuccessPage(){return this.generateFeishuSuccessTemplate()}static getDeepvlabSuccessPage(){return this.generateDeepvlabSuccessTemplate()}static getErrorPage(e){return this.generateErrorTemplate(e)}static loadTemplate(e){if(this.cache.has(e))return this.cache.get(e);try{let r=[];if(this.customBasePath&&(r.push(MG.join(this.customBasePath,"dist","bundled","auth","login","templates",e)),r.push(MG.join(this.customBasePath,"bundled","auth","login","templates",e)),r.push(MG.join(this.customBasePath,"auth","login","templates",e))),BGe&&r.push(MG.join(BGe,e)),BGe){let o=BGe;for(let t=0;t<10;t++)r.push(MG.join(o,"bundled","auth","login","templates",e)),r.push(MG.join(o,"bundled",e)),r.push(MG.join(o,"bundle","login","templates",e)),r.push(MG.join(o,"auth","login","templates",e)),o=MG.dirname(o)}if(typeof process<"u"&&process.cwd)try{let o=process.cwd();r.push(MG.join(o,"bundle","login","templates",e)),r.push(MG.join(o,"dist","bundled","auth","login","templates",e)),r.push(MG.join(o,"bundled","auth","login","templates",e)),r.push(MG.join(o,"auth","login","templates",e))}catch{}let a=null;for(let o of r)try{if(i_e.existsSync(o)){a=o,console.error(`\u2705 [AuthTemplates] Template loaded: ${e} from ${o}`);break}}catch{continue}if(!a){if(console.warn(`\u26A0\uFE0F [AuthTemplates] Template ${e} not found in any location.`),console.warn(` Tried ${r.length} paths. First 5:`),r.slice(0,5).forEach((o,t)=>console.warn(` ${t+1}. ${o}`)),console.warn(` Current dirname: ${BGe||"(unavailable - cross-platform build)"}`),console.warn(` Custom base path: ${this.customBasePath||"(not set)"}`),typeof process<"u"&&process.cwd)try{console.warn(` Process cwd: ${process.cwd()}`)}catch{console.warn(" Process cwd: unavailable")}return console.log(`\u2139\uFE0F [AuthTemplates] Using fallback template for ${e}`),this.generateBasicAuthSelectTemplate()}let i=i_e.readFileSync(a,"utf-8");return this.cache.set(e,i),i}catch(r){return console.error(`\u274C [AuthTemplates] Failed to load template ${e}:`,r),this.generateBasicAuthSelectTemplate()}}static generateBasicAuthSelectTemplate(){return`
5802
5802
  <!DOCTYPE html>
5803
5803
  <html>
5804
5804
  <head>
@@ -7187,7 +7187,7 @@ ${c}`),a?i.reset(c):c}function lus(n,e,r,a={}){if(!QAn){QAn=!0;let o="Passing li
7187
7187
 
7188
7188
  ${e}
7189
7189
  `:""}`}set message(e){this.#r=e}#a(e){if(!this.#t)return;let r=this.#e,a=hus(r,this.#t.message);if(a)return(0,_An.codeFrameColumns)(r,{start:a},{highlightCode:e})}get codeFrame(){return this.#n??=this.#a(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#a(!1),this.#i}},hus=(n,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:a,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:_Lt(n,Number(a),{oneBased:!0})},Ius=n=>n.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,a)=>`"${a}"(${dus(a)})`)});var Y1e=Ge((_al,UAn)=>{"use strict";var mus=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};UAn.exports=mus});var V1e=Ge((Mal,zAn)=>{"use strict";var pus="2.0.0",fus=Number.MAX_SAFE_INTEGER||9007199254740991,bus=16,gus=250,Gus=["major","premajor","minor","preminor","patch","prepatch","prerelease"];zAn.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:bus,MAX_SAFE_BUILD_LENGTH:gus,MAX_SAFE_INTEGER:fus,RELEASE_TYPES:Gus,SEMVER_SPEC_VERSION:pus,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var die=Ge((Hx,PAn)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:zLt,MAX_SAFE_BUILD_LENGTH:vus,MAX_LENGTH:yus}=V1e(),Nus=Y1e();Hx=PAn.exports={};var Zus=Hx.re=[],Wus=Hx.safeRe=[],ka=Hx.src=[],wus=Hx.safeSrc=[],Ha=Hx.t={},Fus=0,PLt="[a-zA-Z0-9-]",Eus=[["\\s",1],["\\d",yus],[PLt,vus]],Rus=n=>{for(let[e,r]of Eus)n=n.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return n},Ys=(n,e,r)=>{let a=Rus(e),i=Fus++;Nus(n,i,e),Ha[n]=i,ka[i]=e,wus[i]=a,Zus[i]=new RegExp(e,r?"g":void 0),Wus[i]=new RegExp(a,r?"g":void 0)};Ys("NUMERICIDENTIFIER","0|[1-9]\\d*");Ys("NUMERICIDENTIFIERLOOSE","\\d+");Ys("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${PLt}*`);Ys("MAINVERSION",`(${ka[Ha.NUMERICIDENTIFIER]})\\.(${ka[Ha.NUMERICIDENTIFIER]})\\.(${ka[Ha.NUMERICIDENTIFIER]})`);Ys("MAINVERSIONLOOSE",`(${ka[Ha.NUMERICIDENTIFIERLOOSE]})\\.(${ka[Ha.NUMERICIDENTIFIERLOOSE]})\\.(${ka[Ha.NUMERICIDENTIFIERLOOSE]})`);Ys("PRERELEASEIDENTIFIER",`(?:${ka[Ha.NONNUMERICIDENTIFIER]}|${ka[Ha.NUMERICIDENTIFIER]})`);Ys("PRERELEASEIDENTIFIERLOOSE",`(?:${ka[Ha.NONNUMERICIDENTIFIER]}|${ka[Ha.NUMERICIDENTIFIERLOOSE]})`);Ys("PRERELEASE",`(?:-(${ka[Ha.PRERELEASEIDENTIFIER]}(?:\\.${ka[Ha.PRERELEASEIDENTIFIER]})*))`);Ys("PRERELEASELOOSE",`(?:-?(${ka[Ha.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${ka[Ha.PRERELEASEIDENTIFIERLOOSE]})*))`);Ys("BUILDIDENTIFIER",`${PLt}+`);Ys("BUILD",`(?:\\+(${ka[Ha.BUILDIDENTIFIER]}(?:\\.${ka[Ha.BUILDIDENTIFIER]})*))`);Ys("FULLPLAIN",`v?${ka[Ha.MAINVERSION]}${ka[Ha.PRERELEASE]}?${ka[Ha.BUILD]}?`);Ys("FULL",`^${ka[Ha.FULLPLAIN]}$`);Ys("LOOSEPLAIN",`[v=\\s]*${ka[Ha.MAINVERSIONLOOSE]}${ka[Ha.PRERELEASELOOSE]}?${ka[Ha.BUILD]}?`);Ys("LOOSE",`^${ka[Ha.LOOSEPLAIN]}$`);Ys("GTLT","((?:<|>)?=?)");Ys("XRANGEIDENTIFIERLOOSE",`${ka[Ha.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Ys("XRANGEIDENTIFIER",`${ka[Ha.NUMERICIDENTIFIER]}|x|X|\\*`);Ys("XRANGEPLAIN",`[v=\\s]*(${ka[Ha.XRANGEIDENTIFIER]})(?:\\.(${ka[Ha.XRANGEIDENTIFIER]})(?:\\.(${ka[Ha.XRANGEIDENTIFIER]})(?:${ka[Ha.PRERELEASE]})?${ka[Ha.BUILD]}?)?)?`);Ys("XRANGEPLAINLOOSE",`[v=\\s]*(${ka[Ha.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ka[Ha.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ka[Ha.XRANGEIDENTIFIERLOOSE]})(?:${ka[Ha.PRERELEASELOOSE]})?${ka[Ha.BUILD]}?)?)?`);Ys("XRANGE",`^${ka[Ha.GTLT]}\\s*${ka[Ha.XRANGEPLAIN]}$`);Ys("XRANGELOOSE",`^${ka[Ha.GTLT]}\\s*${ka[Ha.XRANGEPLAINLOOSE]}$`);Ys("COERCEPLAIN",`(^|[^\\d])(\\d{1,${zLt}})(?:\\.(\\d{1,${zLt}}))?(?:\\.(\\d{1,${zLt}}))?`);Ys("COERCE",`${ka[Ha.COERCEPLAIN]}(?:$|[^\\d])`);Ys("COERCEFULL",ka[Ha.COERCEPLAIN]+`(?:${ka[Ha.PRERELEASE]})?(?:${ka[Ha.BUILD]})?(?:$|[^\\d])`);Ys("COERCERTL",ka[Ha.COERCE],!0);Ys("COERCERTLFULL",ka[Ha.COERCEFULL],!0);Ys("LONETILDE","(?:~>?)");Ys("TILDETRIM",`(\\s*)${ka[Ha.LONETILDE]}\\s+`,!0);Hx.tildeTrimReplace="$1~";Ys("TILDE",`^${ka[Ha.LONETILDE]}${ka[Ha.XRANGEPLAIN]}$`);Ys("TILDELOOSE",`^${ka[Ha.LONETILDE]}${ka[Ha.XRANGEPLAINLOOSE]}$`);Ys("LONECARET","(?:\\^)");Ys("CARETTRIM",`(\\s*)${ka[Ha.LONECARET]}\\s+`,!0);Hx.caretTrimReplace="$1^";Ys("CARET",`^${ka[Ha.LONECARET]}${ka[Ha.XRANGEPLAIN]}$`);Ys("CARETLOOSE",`^${ka[Ha.LONECARET]}${ka[Ha.XRANGEPLAINLOOSE]}$`);Ys("COMPARATORLOOSE",`^${ka[Ha.GTLT]}\\s*(${ka[Ha.LOOSEPLAIN]})$|^$`);Ys("COMPARATOR",`^${ka[Ha.GTLT]}\\s*(${ka[Ha.FULLPLAIN]})$|^$`);Ys("COMPARATORTRIM",`(\\s*)${ka[Ha.GTLT]}\\s*(${ka[Ha.LOOSEPLAIN]}|${ka[Ha.XRANGEPLAIN]})`,!0);Hx.comparatorTrimReplace="$1$2$3";Ys("HYPHENRANGE",`^\\s*(${ka[Ha.XRANGEPLAIN]})\\s+-\\s+(${ka[Ha.XRANGEPLAIN]})\\s*$`);Ys("HYPHENRANGELOOSE",`^\\s*(${ka[Ha.XRANGEPLAINLOOSE]})\\s+-\\s+(${ka[Ha.XRANGEPLAINLOOSE]})\\s*$`);Ys("STAR","(<|>)?=?\\s*\\*");Ys("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Ys("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var j7e=Ge((Ual,jAn)=>{"use strict";var Aus=Object.freeze({loose:!0}),xus=Object.freeze({}),Cus=n=>n?typeof n!="object"?Aus:n:xus;jAn.exports=Cus});var jLt=Ge((zal,$An)=>{"use strict";var qAn=/^[0-9]+$/,KAn=(n,e)=>{if(typeof n=="number"&&typeof e=="number")return n===e?0:n<e?-1:1;let r=qAn.test(n),a=qAn.test(e);return r&&a&&(n=+n,e=+e),n===e?0:r&&!a?-1:a&&!r?1:n<e?-1:1},Yus=(n,e)=>KAn(e,n);$An.exports={compareIdentifiers:KAn,rcompareIdentifiers:Yus}});var cg=Ge((Pal,t4n)=>{"use strict";var q7e=Y1e(),{MAX_LENGTH:e4n,MAX_SAFE_INTEGER:K7e}=V1e(),{safeRe:$7e,t:eMe}=die(),Vus=j7e(),{compareIdentifiers:qLt}=jLt(),KLt=class n{constructor(e,r){if(r=Vus(r),e instanceof n){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>e4n)throw new TypeError(`version is longer than ${e4n} characters`);q7e("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let a=e.trim().match(r.loose?$7e[eMe.LOOSE]:$7e[eMe.FULL]);if(!a)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+a[1],this.minor=+a[2],this.patch=+a[3],this.major>K7e||this.major<0)throw new TypeError("Invalid major version");if(this.minor>K7e||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>K7e||this.patch<0)throw new TypeError("Invalid patch version");a[4]?this.prerelease=a[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let o=+i;if(o>=0&&o<K7e)return o}return i}):this.prerelease=[],this.build=a[5]?a[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(q7e("SemVer.compare",this.version,this.options,e),!(e instanceof n)){if(typeof e=="string"&&e===this.version)return 0;e=new n(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof n||(e=new n(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof n||(e=new n(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let a=this.prerelease[r],i=e.prerelease[r];if(q7e("prerelease compare",r,a,i),a===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(a===void 0)return-1;if(a===i)continue;return qLt(a,i)}while(++r)}compareBuild(e){e instanceof n||(e=new n(e,this.options));let r=0;do{let a=this.build[r],i=e.build[r];if(q7e("build compare",r,a,i),a===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(a===void 0)return-1;if(a===i)continue;return qLt(a,i)}while(++r)}inc(e,r,a){if(e.startsWith("pre")){if(!r&&a===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let i=`-${r}`.match(this.options.loose?$7e[eMe.PRERELEASELOOSE]:$7e[eMe.PRERELEASE]);if(!i||i[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,a);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,a);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,a),this.inc("pre",r,a);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,a),this.inc("pre",r,a);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(a)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&a===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let o=[r,i];a===!1&&(o=[r]),qLt(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t4n.exports=KLt});var T_=Ge((jal,n4n)=>{"use strict";var r4n=cg(),kus=(n,e,r=!1)=>{if(n instanceof r4n)return n;try{return new r4n(n,e)}catch(a){if(!r)return null;throw a}};n4n.exports=kus});var $Lt=Ge((qal,a4n)=>{"use strict";var Hus=T_(),Qus=(n,e)=>{let r=Hus(n,e);return r?r.version:null};a4n.exports=Qus});var eTt=Ge((Kal,i4n)=>{"use strict";var Xus=T_(),Sus=(n,e)=>{let r=Xus(n.trim().replace(/^[=v]+/,""),e);return r?r.version:null};i4n.exports=Sus});var tTt=Ge(($al,Lus)=>{Lus.exports=["0BSD","3D-Slicer-1.0","AAL","ADSL","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AGPL-1.0-only","AGPL-1.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","AMD-newlib","AMDPLPA","AML","AML-glslang","AMPAS","ANTLR-PD","ANTLR-PD-fallback","APAFML","APL-1.0","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","ASWF-Digital-Assets-1.0","ASWF-Digital-Assets-1.1","Abstyles","AdaCore-doc","Adobe-2006","Adobe-Display-PostScript","Adobe-Glyph","Adobe-Utopia","Afmparse","Aladdin","Apache-1.0","Apache-1.1","Apache-2.0","App-s2p","Arphic-1999","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","Artistic-dist","Aspell-RU","BSD-1-Clause","BSD-2-Clause","BSD-2-Clause-Darwin","BSD-2-Clause-Patent","BSD-2-Clause-Views","BSD-2-Clause-first-lines","BSD-2-Clause-pkgconf-disclaimer","BSD-3-Clause","BSD-3-Clause-Attribution","BSD-3-Clause-Clear","BSD-3-Clause-HP","BSD-3-Clause-LBNL","BSD-3-Clause-Modification","BSD-3-Clause-No-Military-License","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-Open-MPI","BSD-3-Clause-Sun","BSD-3-Clause-acpica","BSD-3-Clause-flex","BSD-4-Clause","BSD-4-Clause-Shortened","BSD-4-Clause-UC","BSD-4.3RENO","BSD-4.3TAHOE","BSD-Advertising-Acknowledgement","BSD-Attribution-HPND-disclaimer","BSD-Inferno-Nettverk","BSD-Protection","BSD-Source-Code","BSD-Source-beginning-file","BSD-Systemics","BSD-Systemics-W3Works","BSL-1.0","BUSL-1.1","Baekmuk","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","Bitstream-Charter","Bitstream-Vera","BlueOak-1.0.0","Boehm-GC","Boehm-GC-without-fee","Borceux","Brian-Gladman-2-Clause","Brian-Gladman-3-Clause","C-UDA-1.0","CAL-1.0","CAL-1.0-Combined-Work-Exception","CATOSL-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-2.5-AU","CC-BY-3.0","CC-BY-3.0-AT","CC-BY-3.0-AU","CC-BY-3.0-DE","CC-BY-3.0-IGO","CC-BY-3.0-NL","CC-BY-3.0-US","CC-BY-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-3.0-DE","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-3.0-DE","CC-BY-NC-ND-3.0-IGO","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.0-DE","CC-BY-NC-SA-2.0-FR","CC-BY-NC-SA-2.0-UK","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-3.0-DE","CC-BY-NC-SA-3.0-IGO","CC-BY-NC-SA-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-3.0-DE","CC-BY-ND-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.0-UK","CC-BY-SA-2.1-JP","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-3.0-AT","CC-BY-SA-3.0-DE","CC-BY-SA-3.0-IGO","CC-BY-SA-4.0","CC-PDDC","CC-PDM-1.0","CC-SA-1.0","CC0-1.0","CDDL-1.0","CDDL-1.1","CDL-1.0","CDLA-Permissive-1.0","CDLA-Permissive-2.0","CDLA-Sharing-1.0","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","CERN-OHL-1.1","CERN-OHL-1.2","CERN-OHL-P-2.0","CERN-OHL-S-2.0","CERN-OHL-W-2.0","CFITSIO","CMU-Mach","CMU-Mach-nodoc","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","COIL-1.0","CPAL-1.0","CPL-1.0","CPOL-1.02","CUA-OPL-1.0","Caldera","Caldera-no-preamble","Catharon","ClArtistic","Clips","Community-Spec-1.0","Condor-1.1","Cornell-Lossless-JPEG","Cronyx","Crossword","CryptoSwift","CrystalStacker","Cube","D-FSL-1.0","DEC-3-Clause","DL-DE-BY-2.0","DL-DE-ZERO-2.0","DOC","DRL-1.0","DRL-1.1","DSDP","DocBook-DTD","DocBook-Schema","DocBook-Stylesheet","DocBook-XML","Dotseqn","ECL-1.0","ECL-2.0","EFL-1.0","EFL-2.0","EPICS","EPL-1.0","EPL-2.0","EUDatagrid","EUPL-1.0","EUPL-1.1","EUPL-1.2","Elastic-2.0","Entessa","ErlPL-1.1","Eurosym","FBM","FDK-AAC","FSFAP","FSFAP-no-warranty-disclaimer","FSFUL","FSFULLR","FSFULLRSD","FSFULLRWD","FSL-1.1-ALv2","FSL-1.1-MIT","FTL","Fair","Ferguson-Twofish","Frameworx-1.0","FreeBSD-DOC","FreeImage","Furuseth","GCR-docs","GD","GFDL-1.1-invariants-only","GFDL-1.1-invariants-or-later","GFDL-1.1-no-invariants-only","GFDL-1.1-no-invariants-or-later","GFDL-1.1-only","GFDL-1.1-or-later","GFDL-1.2-invariants-only","GFDL-1.2-invariants-or-later","GFDL-1.2-no-invariants-only","GFDL-1.2-no-invariants-or-later","GFDL-1.2-only","GFDL-1.2-or-later","GFDL-1.3-invariants-only","GFDL-1.3-invariants-or-later","GFDL-1.3-no-invariants-only","GFDL-1.3-no-invariants-or-later","GFDL-1.3-only","GFDL-1.3-or-later","GL2PS","GLWTPL","GPL-1.0-only","GPL-1.0-or-later","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","Game-Programming-Gems","Giftware","Glide","Glulxe","Graphics-Gems","Gutmann","HDF5","HIDAPI","HP-1986","HP-1989","HPND","HPND-DEC","HPND-Fenneberg-Livingston","HPND-INRIA-IMAG","HPND-Intel","HPND-Kevlin-Henney","HPND-MIT-disclaimer","HPND-Markus-Kuhn","HPND-Netrek","HPND-Pbmplus","HPND-UC","HPND-UC-export-US","HPND-doc","HPND-doc-sell","HPND-export-US","HPND-export-US-acknowledgement","HPND-export-US-modify","HPND-export2-US","HPND-merchantability-variant","HPND-sell-MIT-disclaimer-xserver","HPND-sell-regexpr","HPND-sell-variant","HPND-sell-variant-MIT-disclaimer","HPND-sell-variant-MIT-disclaimer-rev","HTMLTIDY","HaskellReport","Hippocratic-2.1","IBM-pibs","ICU","IEC-Code-Components-EULA","IJG","IJG-short","IPA","IPL-1.0","ISC","ISC-Veillard","ImageMagick","Imlib2","Info-ZIP","Inner-Net-2.0","InnoSetup","Intel","Intel-ACPI","Interbase-1.0","JPL-image","JPNIC","JSON","Jam","JasPer-2.0","Kastrup","Kazlib","Knuth-CTAN","LAL-1.2","LAL-1.3","LGPL-2.0-only","LGPL-2.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","LGPLLR","LOOP","LPD-document","LPL-1.0","LPL-1.02","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","LZMA-SDK-9.11-to-9.20","LZMA-SDK-9.22","Latex2e","Latex2e-translated-notice","Leptonica","LiLiQ-P-1.1","LiLiQ-R-1.1","LiLiQ-Rplus-1.1","Libpng","Linux-OpenIB","Linux-man-pages-1-para","Linux-man-pages-copyleft","Linux-man-pages-copyleft-2-para","Linux-man-pages-copyleft-var","Lucida-Bitmap-Fonts","MIPS","MIT","MIT-0","MIT-CMU","MIT-Click","MIT-Festival","MIT-Khronos-old","MIT-Modern-Variant","MIT-Wu","MIT-advertising","MIT-enna","MIT-feh","MIT-open-group","MIT-testregex","MITNFA","MMIXware","MPEG-SSG","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","MS-LPL","MS-PL","MS-RL","MTLL","Mackerras-3-Clause","Mackerras-3-Clause-acknowledgment","MakeIndex","Martin-Birgmeier","McPhee-slideshow","Minpack","MirOS","Motosoto","MulanPSL-1.0","MulanPSL-2.0","Multics","Mup","NAIST-2003","NASA-1.3","NBPL-1.0","NCBI-PD","NCGL-UK-2.0","NCL","NCSA","NGPL","NICTA-1.0","NIST-PD","NIST-PD-fallback","NIST-Software","NLOD-1.0","NLOD-2.0","NLPL","NOSL","NPL-1.0","NPL-1.1","NPOSL-3.0","NRL","NTIA-PD","NTP","NTP-0","Naumen","NetCDF","Newsletr","Nokia","Noweb","O-UDA-1.0","OAR","OCCT-PL","OCLC-2.0","ODC-By-1.0","ODbL-1.0","OFFIS","OFL-1.0","OFL-1.0-RFN","OFL-1.0-no-RFN","OFL-1.1","OFL-1.1-RFN","OFL-1.1-no-RFN","OGC-1.0","OGDL-Taiwan-1.0","OGL-Canada-2.0","OGL-UK-1.0","OGL-UK-2.0","OGL-UK-3.0","OGTSL","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.2.2","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OLFL-1.3","OML","OPL-1.0","OPL-UK-3.0","OPUBL-1.0","OSET-PL-2.1","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenPBS-2.3","OpenSSL","OpenSSL-standalone","OpenVision","PADL","PDDL-1.0","PHP-3.0","PHP-3.01","PPL","PSF-2.0","Parity-6.0.0","Parity-7.0.0","Pixar","Plexus","PolyForm-Noncommercial-1.0.0","PolyForm-Small-Business-1.0.0","PostgreSQL","Python-2.0","Python-2.0.1","QPL-1.0","QPL-1.0-INRIA-2004","Qhull","RHeCos-1.1","RPL-1.1","RPL-1.5","RPSL-1.0","RSA-MD","RSCPL","Rdisc","Ruby","Ruby-pty","SAX-PD","SAX-PD-2.0","SCEA","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","SGI-OpenGL","SGP4","SHL-0.5","SHL-0.51","SISSL","SISSL-1.2","SL","SMAIL-GPL","SMLNJ","SMPPL","SNIA","SOFA","SPL-1.0","SSH-OpenSSH","SSH-short","SSLeay-standalone","SSPL-1.0","SUL-1.0","SWL","Saxpath","SchemeReport","Sendmail","Sendmail-8.23","Sendmail-Open-Source-1.1","SimPL-2.0","Sleepycat","Soundex","Spencer-86","Spencer-94","Spencer-99","SugarCRM-1.1.3","Sun-PPP","Sun-PPP-2000","SunPro","Symlinks","TAPR-OHL-1.0","TCL","TCP-wrappers","TGPPL-1.0","TMate","TORQUE-1.1","TOSL","TPDL","TPL-1.0","TTWL","TTYP0","TU-Berlin-1.0","TU-Berlin-2.0","TermReadKey","ThirdEye","TrustedQSL","UCAR","UCL-1.0","UMich-Merit","UPL-1.0","URT-RLE","Ubuntu-font-1.0","Unicode-3.0","Unicode-DFS-2015","Unicode-DFS-2016","Unicode-TOU","UnixCrypt","Unlicense","Unlicense-libtelnet","Unlicense-libwhirlpool","VOSTROM","VSL-1.0","Vim","W3C","W3C-19980720","W3C-20150513","WTFPL","Watcom-1.0","Widget-Workshop","Wsuipa","X11","X11-distribute-modifications-variant","X11-swapped","XFree86-1.1","XSkat","Xdebug-1.03","Xerox","Xfig","Xnet","YPL-1.0","YPL-1.1","ZPL-1.1","ZPL-2.0","ZPL-2.1","Zed","Zeeff","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","any-OSI","any-OSI-perl-modules","bcrypt-Solar-Designer","blessing","bzip2-1.0.6","check-cvs","checkmk","copyleft-next-0.3.0","copyleft-next-0.3.1","curl","cve-tou","diffmark","dtoa","dvipdfm","eGenix","etalab-2.0","fwlw","gSOAP-1.3b","generic-xts","gnuplot","gtkbook","hdparm","iMatix","jove","libpng-1.6.35","libpng-2.0","libselinux-1.0","libtiff","libutil-David-Nugent","lsof","magaz","mailprio","man2html","metamail","mpi-permissive","mpich2","mplus","ngrep","pkgconf","pnmstitch","psfrag","psutils","python-ldap","radvd","snprintf","softSurfer","ssh-keyscan","swrule","threeparttable","ulem","w3m","wwl","xinetd","xkeyboard-config-Zinoviev","xlock","xpp","xzoom","zlib-acknowledgement"]});var s4n=Ge((eil,Tus)=>{Tus.exports=["AGPL-1.0","AGPL-3.0","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-2.0-with-GCC-exception","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-3.0","GPL-3.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","LGPL-2.0","LGPL-2.1","LGPL-3.0","Net-SNMP","Nunit","StandardML-NJ","bzip2-1.0.5","eCos-2.0","wxWindows"]});var o4n=Ge((til,Jus)=>{Jus.exports=["389-exception","Asterisk-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Autoconf-exception-generic","Autoconf-exception-generic-3.0","Autoconf-exception-macro","Bison-exception-1.24","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","cryptsetup-OpenSSL-exception","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","fmt-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-2.0-note","GCC-exception-3.1","Gmsh-exception","GNAT-exception","GNOME-examples-exception","GNU-compiler-exception","gnu-javamail-exception","GPL-3.0-interface-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","GStreamer-exception-2005","GStreamer-exception-2008","i2p-gpl-java-exception","KiCad-libraries-exception","LGPL-3.0-linking-exception","libpri-OpenH323-exception","Libtool-exception","Linux-syscall-note","LLGPL","LLVM-exception","LZMA-exception","mif-exception","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","QPL-1.0-INRIA-2004-exception","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","SANE-exception","SHL-2.0","SHL-2.1","stunnel-exception","SWI-exception","Swift-exception","Texinfo-exception","u-boot-exception-2.0","UBDL-exception","Universal-FOSS-exception-1.0","vsftpd-openssl-exception","WxWindows-exception-3.1","x11vnc-openssl-exception"]});var c4n=Ge((ril,l4n)=>{"use strict";var Bus=[].concat(tTt()).concat(s4n()),Ous=o4n();l4n.exports=function(n){var e=0;function r(){return e<n.length}function a(p){if(p instanceof RegExp){var b=n.slice(e),y=b.match(p);if(y)return e+=y[0].length,y[0]}else if(n.indexOf(p,e)===e)return e+=p.length,p}function i(){a(/[ ]*/)}function o(){for(var p,b=["WITH","AND","OR","(",")",":","+"],y=0;y<b.length&&(p=a(b[y]),!p);y++);if(p==="+"&&e>1&&n[e-2]===" ")throw new Error("Space before `+`");return p&&{type:"OPERATOR",string:p}}function t(){return a(/[A-Za-z0-9-.]+/)}function s(){var p=t();if(!p)throw new Error("Expected idstring at offset "+e);return p}function d(){if(a("DocumentRef-")){var p=s();return{type:"DOCUMENTREF",string:p}}}function h(){if(a("LicenseRef-")){var p=s();return{type:"LICENSEREF",string:p}}}function u(){var p=e,b=t();if(Bus.indexOf(b)!==-1)return{type:"LICENSE",string:b};if(Ous.indexOf(b)!==-1)return{type:"EXCEPTION",string:b};e=p}function I(){return o()||d()||h()||u()}for(var c=[];r()&&(i(),!!r());){var m=I();if(!m)throw new Error("Unexpected `"+n[e]+"` at offset "+e);c.push(m)}return c}});var d4n=Ge((nil,u4n)=>{"use strict";u4n.exports=function(n){var e=0;function r(){return e<n.length}function a(){return r()?n[e]:null}function i(){if(!r())throw new Error;e++}function o(b){var y=a();if(y&&y.type==="OPERATOR"&&b===y.string)return i(),y.string}function t(){if(o("WITH")){var b=a();if(b&&b.type==="EXCEPTION")return i(),b.string;throw new Error("Expected exception after `WITH`")}}function s(){var b=e,y="",v=a();if(v.type==="DOCUMENTREF"&&(i(),y+="DocumentRef-"+v.string+":",!o(":")))throw new Error("Expected `:` after `DocumentRef-...`");if(v=a(),v.type==="LICENSEREF")return i(),y+="LicenseRef-"+v.string,{license:y};e=b}function d(){var b=a();if(b&&b.type==="LICENSE"){i();var y={license:b.string};o("+")&&(y.plus=!0);var v=t();return v&&(y.exception=v),y}}function h(){var b=o("(");if(b){var y=m();if(!o(")"))throw new Error("Expected `)`");return y}}function u(){return h()||s()||d()}function I(b,y){return function v(){var A=y();if(A){if(!o(b))return A;var w=v();if(!w)throw new Error("Expected expression");return{left:A,conjunction:b.toLowerCase(),right:w}}}}var c=I("AND",u),m=I("OR",c),p=m();if(!p||r())throw new Error("Syntax error");return p}});var rTt=Ge((ail,h4n)=>{"use strict";var Dus=c4n(),_us=d4n();h4n.exports=function(n){return _us(Dus(n))}});var y4n=Ge((iil,v4n)=>{var Mus=rTt(),Uus=tTt();function tMe(n){try{return Mus(n),!0}catch{return!1}}function G4n(n,e){var r=e[0].length-n[0].length;return r!==0?r:n[0].toUpperCase().localeCompare(e[0].toUpperCase())}var I4n=[["APGL","AGPL"],["Gpl","GPL"],["GLP","GPL"],["APL","Apache"],["ISD","ISC"],["GLP","GPL"],["IST","ISC"],["Claude","Clause"],[" or later","+"],[" International",""],["GNU","GPL"],["GUN","GPL"],["+",""],["GNU GPL","GPL"],["GNU LGPL","LGPL"],["GNU/GPL","GPL"],["GNU GLP","GPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL"],["GNU Lesser General Public License","LGPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["GNU Lesser General Public License","LGPL-2.1"],["LESSER GENERAL PUBLIC LICENSE","LGPL"],["Lesser General Public License","LGPL"],["LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["Lesser General Public License","LGPL-2.1"],["GNU General Public License","GPL"],["Gnu public license","GPL"],["GNU Public License","GPL"],["GNU GENERAL PUBLIC LICENSE","GPL"],["MTI","MIT"],["Mozilla Public License","MPL"],["Universal Permissive License","UPL"],["WTH","WTF"],["WTFGPL","WTFPL"],["-License",""]].sort(G4n),zus=0,Pus=1,m4n=[function(n){return n.toUpperCase()},function(n){return n.trim()},function(n){return n.replace(/\./g,"")},function(n){return n.replace(/\s+/g,"")},function(n){return n.replace(/\s+/g,"-")},function(n){return n.replace("v","-")},function(n){return n.replace(/,?\s*(\d)/,"-$1")},function(n){return n.replace(/,?\s*(\d)/,"-$1.0")},function(n){return n.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2")},function(n){return n.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2.0")},function(n){return n[0].toUpperCase()+n.slice(1)},function(n){return n.replace("/","-")},function(n){return n.replace(/\s*V\s*(\d)/,"-$1").replace(/(\d)$/,"$1.0")},function(n){return n.indexOf("3.0")!==-1?n+"-or-later":n+"-only"},function(n){return n+"only"},function(n){return n.replace(/(\d)$/,"-$1.0")},function(n){return n.replace(/(-| )?(\d)$/,"-$2-Clause")},function(n){return n.replace(/(-| )clause(-| )(\d)/,"-$3-Clause")},function(n){return n.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i,"BSD-3-Clause")},function(n){return n.replace(/\bSimplified(-| )?BSD((-| )License)?/i,"BSD-2-Clause")},function(n){return n.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i,"BSD-2-Clause-$1BSD")},function(n){return n.replace(/\bClear(-| )?BSD((-| )License)?/i,"BSD-3-Clause-Clear")},function(n){return n.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i,"BSD-4-Clause")},function(n){return"CC-"+n},function(n){return"CC-"+n+"-4.0"},function(n){return n.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")},function(n){return"CC-"+n.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")+"-4.0"}],nTt=Uus.map(function(n){var e=/^(.*)-\d+\.\d+$/.exec(n);return e?[e[0],e[1]]:[n,null]}).reduce(function(n,e){var r=e[1];return n[r]=n[r]||[],n[r].push(e[0]),n},{}),jus=Object.keys(nTt).map(function(e){return[e,nTt[e]]}).filter(function(e){return e[1].length===1&&e[0]!==null&&e[0]!=="APL"}).map(function(e){return[e[0],e[1][0]]});nTt=void 0;var p4n=[["UNLI","Unlicense"],["WTF","WTFPL"],["2 CLAUSE","BSD-2-Clause"],["2-CLAUSE","BSD-2-Clause"],["3 CLAUSE","BSD-3-Clause"],["3-CLAUSE","BSD-3-Clause"],["AFFERO","AGPL-3.0-or-later"],["AGPL","AGPL-3.0-or-later"],["APACHE","Apache-2.0"],["ARTISTIC","Artistic-2.0"],["Affero","AGPL-3.0-or-later"],["BEER","Beerware"],["BOOST","BSL-1.0"],["BSD","BSD-2-Clause"],["CDDL","CDDL-1.1"],["ECLIPSE","EPL-1.0"],["FUCK","WTFPL"],["GNU","GPL-3.0-or-later"],["LGPL","LGPL-3.0-or-later"],["GPLV1","GPL-1.0-only"],["GPL-1","GPL-1.0-only"],["GPLV2","GPL-2.0-only"],["GPL-2","GPL-2.0-only"],["GPL","GPL-3.0-or-later"],["MIT +NO-FALSE-ATTRIBS","MITNFA"],["MIT","MIT"],["MPL","MPL-2.0"],["X11","X11"],["ZLIB","Zlib"]].concat(jus).sort(G4n),qus=0,Kus=1,f4n=function(n){for(var e=0;e<m4n.length;e++){var r=m4n[e](n).trim();if(r!==n&&tMe(r))return r}return null},b4n=function(n){for(var e=n.toUpperCase(),r=0;r<p4n.length;r++){var a=p4n[r];if(e.indexOf(a[qus])>-1)return a[Kus]}return null},g4n=function(n,e){for(var r=0;r<I4n.length;r++){var a=I4n[r],i=a[zus];if(n.indexOf(i)>-1){var o=n.replace(i,a[Pus]),t=e(o);if(t!==null)return t}}return null};v4n.exports=function(n,e){e=e||{};var r=e.upgrade===void 0?!0:!!e.upgrade;function a(s){return r?$us(s):s}var i=typeof n=="string"&&n.trim().length!==0;if(!i)throw Error("Invalid argument. Expected non-empty string.");if(n=n.trim(),tMe(n))return a(n);var o=n.replace(/\+$/,"").trim();if(tMe(o))return a(o);var t=f4n(n);return t!==null||(t=g4n(n,function(s){return tMe(s)?s:f4n(s)}),t!==null)||(t=b4n(n),t!==null)||(t=g4n(n,b4n),t!==null)?a(t):null};function $us(n){return["GPL-1.0","LGPL-1.0","AGPL-1.0","GPL-2.0","LGPL-2.0","AGPL-2.0","LGPL-2.1"].indexOf(n)!==-1?n+"-only":["GPL-1.0+","GPL-2.0+","GPL-3.0+","LGPL-2.0+","LGPL-2.1+","LGPL-3.0+","AGPL-1.0+","AGPL-3.0+"].indexOf(n)!==-1?n.replace(/\+$/,"-or-later"):["GPL-3.0","LGPL-3.0","AGPL-3.0"].indexOf(n)!==-1?n+"-or-later":n}});var w4n=Ge((sil,W4n)=>{var eds=rTt(),tds=y4n(),N4n='license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"',rds=/^SEE LICEN[CS]E IN (.+)$/;function Z4n(n,e){return e.slice(0,n.length)===n}function aTt(n){if(n.hasOwnProperty("license")){var e=n.license;return Z4n("LicenseRef",e)||Z4n("DocumentRef",e)}else return aTt(n.left)||aTt(n.right)}W4n.exports=function(n){var e;try{e=eds(n)}catch{var r;if(n==="UNLICENSED"||n==="UNLICENCED")return{validForOldPackages:!0,validForNewPackages:!0,unlicensed:!0};if(r=rds.exec(n))return{validForOldPackages:!0,validForNewPackages:!0,inFile:r[1]};var a={validForOldPackages:!1,validForNewPackages:!1,warnings:[N4n]};if(n.trim().length!==0){var i=tds(n);i&&a.warnings.push('license is similar to the valid expression "'+i+'"')}return a}return aTt(e)?{validForNewPackages:!1,validForOldPackages:!1,spdx:!0,warnings:[N4n]}:{validForNewPackages:!0,validForOldPackages:!0,spdx:!0}}});var x4n=Ge(nMe=>{"use strict";Object.defineProperty(nMe,"__esModule",{value:!0});nMe.LRUCache=void 0;var hie=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,E4n=new Set,iTt=typeof process=="object"&&process?process:{},R4n=(n,e,r,a)=>{typeof iTt.emitWarning=="function"?iTt.emitWarning(n,e,r,a):console.error(`[${r}] ${e}: ${n}`)},rMe=globalThis.AbortController,F4n=globalThis.AbortSignal;if(typeof rMe>"u"){F4n=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(a,i){this._onabort.push(i)}},rMe=class{constructor(){e()}signal=new F4n;abort(a){if(!this.signal.aborted){this.signal.reason=a,this.signal.aborted=!0;for(let i of this.signal._onabort)i(a);this.signal.onabort?.(a)}}};let n=iTt.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,R4n("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var nds=n=>!E4n.has(n),cil=Symbol("type"),tL=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),A4n=n=>tL(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Iie:null:null,Iie=class extends Array{constructor(e){super(e),this.fill(0)}},sTt=class n{heap;length;static#e=!1;static create(e){let r=A4n(e);if(!r)return[];n.#e=!0;let a=new n(e,r);return n.#e=!1,a}constructor(e,r){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},oTt=class n{#e;#t;#r;#n;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#o;#s;#h;#d;#I;#l;#p;#f;#g;#m;#Z;#y;#W;#w;#v;#G;static unsafeExposeInternals(e){return{starts:e.#y,ttls:e.#W,sizes:e.#Z,keyMap:e.#s,keyList:e.#h,valList:e.#d,next:e.#I,prev:e.#l,get head(){return e.#p},get tail(){return e.#f},free:e.#g,isBackgroundFetch:r=>e.#N(r),backgroundFetch:(r,a,i,o)=>e.#C(r,a,i,o),moveToTail:r=>e.#O(r),indexes:r=>e.#L(r),rindexes:r=>e.#V(r),isStale:r=>e.#A(r)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#o}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#r}get disposeAfter(){return this.#n}constructor(e){let{max:r=0,ttl:a,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:t,updateAgeOnHas:s,allowStale:d,dispose:h,disposeAfter:u,noDisposeOnSet:I,noUpdateTTL:c,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:b,fetchMethod:y,memoMethod:v,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:f,ignoreFetchAbort:Z}=e;if(r!==0&&!tL(r))throw new TypeError("max option must be a nonnegative integer");let W=r?A4n(r):Array;if(!W)throw new Error("invalid max value: "+r);if(this.#e=r,this.#t=m,this.maxEntrySize=p||this.#t,this.sizeCalculation=b,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#a=v,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=y,this.#v=!!y,this.#s=new Map,this.#h=new Array(r).fill(void 0),this.#d=new Array(r).fill(void 0),this.#I=new W(r),this.#l=new W(r),this.#p=0,this.#f=0,this.#g=sTt.create(r),this.#c=0,this.#o=0,typeof h=="function"&&(this.#r=h),typeof u=="function"?(this.#n=u,this.#m=[]):(this.#n=void 0,this.#m=void 0),this.#w=!!this.#r,this.#G=!!this.#n,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!c,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!f,this.ignoreFetchAbort=!!Z,this.maxEntrySize!==0){if(this.#t!==0&&!tL(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!tL(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#x()}if(this.allowStale=!!d,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!t,this.updateAgeOnHas=!!s,this.ttlResolution=tL(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=a||0,this.ttl){if(!tL(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#F()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let R="LRU_CACHE_UNBOUNDED";nds(R)&&(E4n.add(R),R4n("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",R,n))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#F(){let e=new Iie(this.#e),r=new Iie(this.#e);this.#W=e,this.#y=r,this.#H=(o,t,s=hie.now())=>{if(r[o]=t!==0?s:0,e[o]=t,t!==0&&this.ttlAutopurge){let d=setTimeout(()=>{this.#A(o)&&this.#X(this.#h[o],"expire")},t+1);d.unref&&d.unref()}},this.#R=o=>{r[o]=e[o]!==0?hie.now():0},this.#u=(o,t)=>{if(e[t]){let s=e[t],d=r[t];if(!s||!d)return;o.ttl=s,o.start=d,o.now=a||i();let h=o.now-d;o.remainingTTL=s-h}};let a=0,i=()=>{let o=hie.now();if(this.ttlResolution>0){a=o;let t=setTimeout(()=>a=0,this.ttlResolution);t.unref&&t.unref()}return o};this.getRemainingTTL=o=>{let t=this.#s.get(o);if(t===void 0)return 0;let s=e[t],d=r[t];if(!s||!d)return 1/0;let h=(a||i())-d;return s-h},this.#A=o=>{let t=r[o],s=e[o];return!!s&&!!t&&(a||i())-t>s}}#R=()=>{};#u=()=>{};#H=()=>{};#A=()=>!1;#x(){let e=new Iie(this.#e);this.#o=0,this.#Z=e,this.#Y=r=>{this.#o-=e[r],e[r]=0},this.#E=(r,a,i,o)=>{if(this.#N(a))return 0;if(!tL(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(a,r),!tL(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#S=(r,a,i)=>{if(e[r]=a,this.#t){let o=this.#t-e[r];for(;this.#o>o;)this.#T(!0)}this.#o+=e[r],i&&(i.entrySize=a,i.totalCalculatedSize=this.#o)}}#Y=e=>{};#S=(e,r,a)=>{};#E=(e,r,a,i)=>{if(a||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#L({allowStale:e=this.allowStale}={}){if(this.#c)for(let r=this.#f;!(!this.#Q(r)||((e||!this.#A(r))&&(yield r),r===this.#p));)r=this.#l[r]}*#V({allowStale:e=this.allowStale}={}){if(this.#c)for(let r=this.#p;!(!this.#Q(r)||((e||!this.#A(r))&&(yield r),r===this.#f));)r=this.#I[r]}#Q(e){return e!==void 0&&this.#s.get(this.#h[e])===e}*entries(){for(let e of this.#L())this.#d[e]!==void 0&&this.#h[e]!==void 0&&!this.#N(this.#d[e])&&(yield[this.#h[e],this.#d[e]])}*rentries(){for(let e of this.#V())this.#d[e]!==void 0&&this.#h[e]!==void 0&&!this.#N(this.#d[e])&&(yield[this.#h[e],this.#d[e]])}*keys(){for(let e of this.#L()){let r=this.#h[e];r!==void 0&&!this.#N(this.#d[e])&&(yield r)}}*rkeys(){for(let e of this.#V()){let r=this.#h[e];r!==void 0&&!this.#N(this.#d[e])&&(yield r)}}*values(){for(let e of this.#L())this.#d[e]!==void 0&&!this.#N(this.#d[e])&&(yield this.#d[e])}*rvalues(){for(let e of this.#V())this.#d[e]!==void 0&&!this.#N(this.#d[e])&&(yield this.#d[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let a of this.#L()){let i=this.#d[a],o=this.#N(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#h[a],this))return this.get(this.#h[a],r)}}forEach(e,r=this){for(let a of this.#L()){let i=this.#d[a],o=this.#N(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#h[a],this)}}rforEach(e,r=this){for(let a of this.#V()){let i=this.#d[a],o=this.#N(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#h[a],this)}}purgeStale(){let e=!1;for(let r of this.#V({allowStale:!0}))this.#A(r)&&(this.#X(this.#h[r],"expire"),e=!0);return e}info(e){let r=this.#s.get(e);if(r===void 0)return;let a=this.#d[r],i=this.#N(a)?a.__staleWhileFetching:a;if(i===void 0)return;let o={value:i};if(this.#W&&this.#y){let t=this.#W[r],s=this.#y[r];if(t&&s){let d=t-(hie.now()-s);o.ttl=d,o.start=Date.now()}}return this.#Z&&(o.size=this.#Z[r]),o}dump(){let e=[];for(let r of this.#L({allowStale:!0})){let a=this.#h[r],i=this.#d[r],o=this.#N(i)?i.__staleWhileFetching:i;if(o===void 0||a===void 0)continue;let t={value:o};if(this.#W&&this.#y){t.ttl=this.#W[r];let s=hie.now()-this.#y[r];t.start=Math.floor(Date.now()-s)}this.#Z&&(t.size=this.#Z[r]),e.unshift([a,t])}return e}load(e){this.clear();for(let[r,a]of e){if(a.start){let i=Date.now()-a.start;a.start=hie.now()-i}this.set(r,a.value,a)}}set(e,r,a={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:t=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:d}=a,{noUpdateTTL:h=this.noUpdateTTL}=a,u=this.#E(e,r,a.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return d&&(d.set="miss",d.maxEntrySizeExceeded=!0),this.#X(e,"set"),this;let I=this.#c===0?void 0:this.#s.get(e);if(I===void 0)I=this.#c===0?this.#f:this.#g.length!==0?this.#g.pop():this.#c===this.#e?this.#T(!1):this.#c,this.#h[I]=e,this.#d[I]=r,this.#s.set(e,I),this.#I[this.#f]=I,this.#l[I]=this.#f,this.#f=I,this.#c++,this.#S(I,u,d),d&&(d.set="add"),h=!1;else{this.#O(I);let c=this.#d[I];if(r!==c){if(this.#v&&this.#N(c)){c.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=c;m!==void 0&&!t&&(this.#w&&this.#r?.(m,e,"set"),this.#G&&this.#m?.push([m,e,"set"]))}else t||(this.#w&&this.#r?.(c,e,"set"),this.#G&&this.#m?.push([c,e,"set"]));if(this.#Y(I),this.#S(I,u,d),this.#d[I]=r,d){d.set="replace";let m=c&&this.#N(c)?c.__staleWhileFetching:c;m!==void 0&&(d.oldValue=m)}}else d&&(d.set="update")}if(i!==0&&!this.#W&&this.#F(),this.#W&&(h||this.#H(I,i,o),d&&this.#u(d,I)),!t&&this.#G&&this.#m){let c=this.#m,m;for(;m=c?.shift();)this.#n?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#d[this.#p];if(this.#T(!0),this.#N(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#G&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#n?.(...r)}}}#T(e){let r=this.#p,a=this.#h[r],i=this.#d[r];return this.#v&&this.#N(i)?i.__abortController.abort(new Error("evicted")):(this.#w||this.#G)&&(this.#w&&this.#r?.(i,a,"evict"),this.#G&&this.#m?.push([i,a,"evict"])),this.#Y(r),e&&(this.#h[r]=void 0,this.#d[r]=void 0,this.#g.push(r)),this.#c===1?(this.#p=this.#f=0,this.#g.length=0):this.#p=this.#I[r],this.#s.delete(a),this.#c--,r}has(e,r={}){let{updateAgeOnHas:a=this.updateAgeOnHas,status:i}=r,o=this.#s.get(e);if(o!==void 0){let t=this.#d[o];if(this.#N(t)&&t.__staleWhileFetching===void 0)return!1;if(this.#A(o))i&&(i.has="stale",this.#u(i,o));else return a&&this.#R(o),i&&(i.has="hit",this.#u(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:a=this.allowStale}=r,i=this.#s.get(e);if(i===void 0||!a&&this.#A(i))return;let o=this.#d[i];return this.#N(o)?o.__staleWhileFetching:o}#C(e,r,a,i){let o=r===void 0?void 0:this.#d[r];if(this.#N(o))return o;let t=new rMe,{signal:s}=a;s?.addEventListener("abort",()=>t.abort(s.reason),{signal:t.signal});let d={signal:t.signal,options:a,context:i},h=(b,y=!1)=>{let{aborted:v}=t.signal,A=a.ignoreFetchAbort&&b!==void 0;if(a.status&&(v&&!y?(a.status.fetchAborted=!0,a.status.fetchError=t.signal.reason,A&&(a.status.fetchAbortIgnored=!0)):a.status.fetchResolved=!0),v&&!A&&!y)return I(t.signal.reason);let w=m;return this.#d[r]===m&&(b===void 0?w.__staleWhileFetching?this.#d[r]=w.__staleWhileFetching:this.#X(e,"fetch"):(a.status&&(a.status.fetchUpdated=!0),this.set(e,b,d.options))),b},u=b=>(a.status&&(a.status.fetchRejected=!0,a.status.fetchError=b),I(b)),I=b=>{let{aborted:y}=t.signal,v=y&&a.allowStaleOnFetchAbort,A=v||a.allowStaleOnFetchRejection,w=A||a.noDeleteOnFetchRejection,E=m;if(this.#d[r]===m&&(!w||E.__staleWhileFetching===void 0?this.#X(e,"fetch"):v||(this.#d[r]=E.__staleWhileFetching)),A)return a.status&&E.__staleWhileFetching!==void 0&&(a.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw b},c=(b,y)=>{let v=this.#i?.(e,o,d);v&&v instanceof Promise&&v.then(A=>b(A===void 0?void 0:A),y),t.signal.addEventListener("abort",()=>{(!a.ignoreFetchAbort||a.allowStaleOnFetchAbort)&&(b(void 0),a.allowStaleOnFetchAbort&&(b=A=>h(A,!0)))})};a.status&&(a.status.fetchDispatched=!0);let m=new Promise(c).then(h,u),p=Object.assign(m,{__abortController:t,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,p,{...d.options,status:void 0}),r=this.#s.get(e)):this.#d[r]=p,p}#N(e){if(!this.#v)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof rMe}async fetch(e,r={}){let{allowStale:a=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:t=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:d=0,sizeCalculation:h=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:c=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:b,forceRefresh:y=!1,status:v,signal:A}=r;if(!this.#v)return v&&(v.fetch="get"),this.get(e,{allowStale:a,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:v});let w={allowStale:a,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:t,noDisposeOnSet:s,size:d,sizeCalculation:h,noUpdateTTL:u,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:c,allowStaleOnFetchAbort:p,ignoreFetchAbort:m,status:v,signal:A},E=this.#s.get(e);if(E===void 0){v&&(v.fetch="miss");let f=this.#C(e,E,w,b);return f.__returned=f}else{let f=this.#d[E];if(this.#N(f)){let G=a&&f.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",G&&(v.returnedStale=!0)),G?f.__staleWhileFetching:f.__returned=f}let Z=this.#A(E);if(!y&&!Z)return v&&(v.fetch="hit"),this.#O(E),i&&this.#R(E),v&&this.#u(v,E),f;let W=this.#C(e,E,w,b),g=W.__staleWhileFetching!==void 0&&a;return v&&(v.fetch=Z?"stale":"refresh",g&&Z&&(v.returnedStale=!0)),g?W.__staleWhileFetching:W.__returned=W}}async forceFetch(e,r={}){let a=await this.fetch(e,r);if(a===void 0)throw new Error("fetch() returned undefined");return a}memo(e,r={}){let a=this.#a;if(!a)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:o,...t}=r,s=this.get(e,t);if(!o&&s!==void 0)return s;let d=a(e,s,{options:t,context:i});return this.set(e,d,t),d}get(e,r={}){let{allowStale:a=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:t}=r,s=this.#s.get(e);if(s!==void 0){let d=this.#d[s],h=this.#N(d);return t&&this.#u(t,s),this.#A(s)?(t&&(t.get="stale"),h?(t&&a&&d.__staleWhileFetching!==void 0&&(t.returnedStale=!0),a?d.__staleWhileFetching:void 0):(o||this.#X(e,"expire"),t&&a&&(t.returnedStale=!0),a?d:void 0)):(t&&(t.get="hit"),h?d.__staleWhileFetching:(this.#O(s),i&&this.#R(s),d))}else t&&(t.get="miss")}#B(e,r){this.#l[r]=e,this.#I[e]=r}#O(e){e!==this.#f&&(e===this.#p?this.#p=this.#I[e]:this.#B(this.#l[e],this.#I[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#X(e,"delete")}#X(e,r){let a=!1;if(this.#c!==0){let i=this.#s.get(e);if(i!==void 0)if(a=!0,this.#c===1)this.#b(r);else{this.#Y(i);let o=this.#d[i];if(this.#N(o)?o.__abortController.abort(new Error("deleted")):(this.#w||this.#G)&&(this.#w&&this.#r?.(o,e,r),this.#G&&this.#m?.push([o,e,r])),this.#s.delete(e),this.#h[i]=void 0,this.#d[i]=void 0,i===this.#f)this.#f=this.#l[i];else if(i===this.#p)this.#p=this.#I[i];else{let t=this.#l[i];this.#I[t]=this.#I[i];let s=this.#I[i];this.#l[s]=this.#l[i]}this.#c--,this.#g.push(i)}}if(this.#G&&this.#m?.length){let i=this.#m,o;for(;o=i?.shift();)this.#n?.(...o)}return a}clear(){return this.#b("delete")}#b(e){for(let r of this.#V({allowStale:!0})){let a=this.#d[r];if(this.#N(a))a.__abortController.abort(new Error("deleted"));else{let i=this.#h[r];this.#w&&this.#r?.(a,i,e),this.#G&&this.#m?.push([a,i,e])}}if(this.#s.clear(),this.#d.fill(void 0),this.#h.fill(void 0),this.#W&&this.#y&&(this.#W.fill(0),this.#y.fill(0)),this.#Z&&this.#Z.fill(0),this.#p=0,this.#f=0,this.#g.length=0,this.#o=0,this.#c=0,this.#G&&this.#m){let r=this.#m,a;for(;a=r?.shift();)this.#n?.(...a)}}};nMe.LRUCache=oTt});var V4n=Ge((dil,Y4n)=>{"use strict";var nc=(...n)=>n.every(e=>e)?n.join(""):"",c0=n=>n?encodeURIComponent(n):"",C4n=n=>n.toLowerCase().replace(/^\W+|\/|\W+$/g,"").replace(/\W+/g,"-"),ads={sshtemplate:({domain:n,user:e,project:r,committish:a})=>`git@${n}:${e}/${r}.git${nc("#",a)}`,sshurltemplate:({domain:n,user:e,project:r,committish:a})=>`git+ssh://git@${n}/${e}/${r}.git${nc("#",a)}`,edittemplate:({domain:n,user:e,project:r,committish:a,editpath:i,path:o})=>`https://${n}/${e}/${r}${nc("/",i,"/",c0(a||"HEAD"),"/",o)}`,browsetemplate:({domain:n,user:e,project:r,committish:a,treepath:i})=>`https://${n}/${e}/${r}${nc("/",i,"/",c0(a))}`,browsetreetemplate:({domain:n,user:e,project:r,committish:a,treepath:i,path:o,fragment:t,hashformat:s})=>`https://${n}/${e}/${r}/${i}/${c0(a||"HEAD")}/${o}${nc("#",s(t||""))}`,browseblobtemplate:({domain:n,user:e,project:r,committish:a,blobpath:i,path:o,fragment:t,hashformat:s})=>`https://${n}/${e}/${r}/${i}/${c0(a||"HEAD")}/${o}${nc("#",s(t||""))}`,docstemplate:({domain:n,user:e,project:r,treepath:a,committish:i})=>`https://${n}/${e}/${r}${nc("/",a,"/",c0(i))}#readme`,httpstemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git+https://${nc(n,"@")}${e}/${r}/${a}.git${nc("#",i)}`,filetemplate:({domain:n,user:e,project:r,committish:a,path:i})=>`https://${n}/${e}/${r}/raw/${c0(a||"HEAD")}/${i}`,shortcuttemplate:({type:n,user:e,project:r,committish:a})=>`${n}:${e}/${r}${nc("#",a)}`,pathtemplate:({user:n,project:e,committish:r})=>`${n}/${e}${nc("#",r)}`,bugstemplate:({domain:n,user:e,project:r})=>`https://${n}/${e}/${r}/issues`,hashformat:C4n},rL={};rL.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth:n,user:e,project:r,committish:a,path:i})=>`https://${nc(n,"@")}raw.githubusercontent.com/${e}/${r}/${c0(a||"HEAD")}/${i}`,gittemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git://${nc(n,"@")}${e}/${r}/${a}.git${nc("#",i)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://codeload.${n}/${e}/${r}/tar.gz/${c0(a||"HEAD")}`,extract:n=>{let[,e,r,a,i]=n.pathname.split("/",5);if(!(a&&a!=="tree")&&(a||(i=n.hash.slice(1)),r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:i}}};rL.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain:n,user:e,project:r,committish:a,treepath:i,path:o,editpath:t})=>`https://${n}/${e}/${r}${nc("/",i,"/",c0(a||"HEAD"),"/",o,t)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/get/${c0(a||"HEAD")}.tar.gz`,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(!["get"].includes(a)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:n.hash.slice(1)}}};rL.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",httpstemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git+https://${nc(n,"@")}${e}/${r}/${a}.git${nc("#",i)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/repository/archive.tar.gz?ref=${c0(a||"HEAD")}`,extract:n=>{let e=n.pathname.slice(1);if(e.includes("/-/")||e.includes("/archive.tar.gz"))return;let r=e.split("/"),a=r.pop();a.endsWith(".git")&&(a=a.slice(0,-4));let i=r.join("/");if(!(!i||!a))return{user:i,project:a,committish:n.hash.slice(1)}}};rL.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain:n,project:e,committish:r})=>`git@${n}:${e}.git${nc("#",r)}`,sshurltemplate:({domain:n,project:e,committish:r})=>`git+ssh://git@${n}/${e}.git${nc("#",r)}`,edittemplate:({domain:n,user:e,project:r,committish:a,editpath:i})=>`https://${n}/${e}/${r}${nc("/",c0(a))}/${i}`,browsetemplate:({domain:n,project:e,committish:r})=>`https://${n}/${e}${nc("/",c0(r))}`,browsetreetemplate:({domain:n,project:e,committish:r,path:a,hashformat:i})=>`https://${n}/${e}${nc("/",c0(r))}${nc("#",i(a))}`,browseblobtemplate:({domain:n,project:e,committish:r,path:a,hashformat:i})=>`https://${n}/${e}${nc("/",c0(r))}${nc("#",i(a))}`,docstemplate:({domain:n,project:e,committish:r})=>`https://${n}/${e}${nc("/",c0(r))}`,httpstemplate:({domain:n,project:e,committish:r})=>`git+https://${n}/${e}.git${nc("#",r)}`,filetemplate:({user:n,project:e,committish:r,path:a})=>`https://gist.githubusercontent.com/${n}/${e}/raw${nc("/",c0(r))}/${a}`,shortcuttemplate:({type:n,project:e,committish:r})=>`${n}:${e}${nc("#",r)}`,pathtemplate:({project:n,committish:e})=>`${n}${nc("#",e)}`,bugstemplate:({domain:n,project:e})=>`https://${n}/${e}`,gittemplate:({domain:n,project:e,committish:r})=>`git://${n}/${e}.git${nc("#",r)}`,tarballtemplate:({project:n,committish:e})=>`https://codeload.github.com/gist/${n}/tar.gz/${c0(e||"HEAD")}`,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(a!=="raw"){if(!r){if(!e)return;r=e,e=null}return r.endsWith(".git")&&(r=r.slice(0,-4)),{user:e,project:r,committish:n.hash.slice(1)}}},hashformat:function(n){return n&&"file-"+C4n(n)}};rL.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain:n,user:e,project:r,committish:a,path:i})=>`https://${n}/${e}/${r}/blob/${c0(a)||"HEAD"}/${i}`,httpstemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}.git${nc("#",a)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/archive/${c0(a)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(!["archive"].includes(a)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:n.hash.slice(1)}}};for(let[n,e]of Object.entries(rL))rL[n]=Object.assign({},ads,e);Y4n.exports=rL});var cTt=Ge((hil,H4n)=>{var ids=Zt("url"),lTt=(n,e,r)=>{let a=n.indexOf(r);return n.lastIndexOf(e,a>-1?a:1/0)},k4n=n=>{try{return new ids.URL(n)}catch{}},sds=(n,e)=>{let r=n.indexOf(":"),a=n.slice(0,r+1);if(Object.prototype.hasOwnProperty.call(e,a))return n;let i=n.indexOf("@");return i>-1?i>r?`git+ssh://${n}`:n:n.indexOf("//")===r+1?n:`${n.slice(0,r+1)}//${n.slice(r+1)}`},ods=n=>{let e=lTt(n,"@","#"),r=lTt(n,":","#");return r>e&&(n=n.slice(0,r)+"/"+n.slice(r+1)),lTt(n,":","#")===-1&&n.indexOf("//")===-1&&(n=`git+ssh://${n}`),n};H4n.exports=(n,e)=>{let r=e?sds(n,e):n;return k4n(r)||k4n(ods(r))}});var X4n=Ge((Iil,Q4n)=>{"use strict";var lds=cTt(),cds=n=>{let e=n.indexOf("#"),r=n.indexOf("/"),a=n.indexOf("/",r+1),i=n.indexOf(":"),o=/\s/.exec(n),t=n.indexOf("@"),s=!o||e>-1&&o.index>e,d=t===-1||e>-1&&t>e,h=i===-1||e>-1&&i>e,u=a===-1||e>-1&&a>e,I=r>0,c=e>-1?n[e-1]!=="/":!n.endsWith("/"),m=!n.startsWith(".");return s&&I&&c&&m&&d&&h&&u};Q4n.exports=(n,e,{gitHosts:r,protocols:a})=>{if(!n)return;let i=cds(n)?`github:${n}`:n,o=lds(i,a);if(!o)return;let t=r.byShortcut[o.protocol],s=r.byDomain[o.hostname.startsWith("www.")?o.hostname.slice(4):o.hostname],d=t||s;if(!d)return;let h=r[t||s],u=null;a[o.protocol]?.auth&&(o.username||o.password)&&(u=`${o.username}${o.password?":"+o.password:""}`);let I=null,c=null,m=null,p=null;try{if(t){let b=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,y=b.indexOf("@");y>-1&&(b=b.slice(y+1));let v=b.lastIndexOf("/");v>-1?(c=decodeURIComponent(b.slice(0,v)),c||(c=null),m=decodeURIComponent(b.slice(v+1))):m=decodeURIComponent(b),m.endsWith(".git")&&(m=m.slice(0,-4)),o.hash&&(I=decodeURIComponent(o.hash.slice(1))),p="shortcut"}else{if(!h.protocols.includes(o.protocol))return;let b=h.extract(o);if(!b)return;c=b.user&&decodeURIComponent(b.user),m=decodeURIComponent(b.project),I=decodeURIComponent(b.committish),p=a[o.protocol]?.name||o.protocol.slice(0,-1)}}catch(b){if(b instanceof URIError)return;throw b}return[d,c,u,m,I,p,e]}});var L4n=Ge((mil,S4n)=>{"use strict";var{LRUCache:uds}=x4n(),dds=V4n(),hds=X4n(),Ids=cTt(),uTt=new uds({max:1e3}),aMe=class n{constructor(e,r,a,i,o,t,s={}){Object.assign(this,n.#e[e],{type:e,user:r,auth:a,project:i,committish:o,default:t,opts:s})}static#e={byShortcut:{},byDomain:{}};static#t={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(e,r){n.#e[e]=r,n.#e.byDomain[r.domain]=e,n.#e.byShortcut[`${e}:`]=e,n.#t[`${e}:`]={name:e}}static fromUrl(e,r){if(typeof e!="string")return;let a=e+JSON.stringify(r||{});if(!uTt.has(a)){let i=hds(e,r,{gitHosts:n.#e,protocols:n.#t});uTt.set(a,i?new n(...i):void 0)}return uTt.get(a)}static parseUrl(e){return Ids(e)}#r(e,r){if(typeof e!="function")return null;let a={...this,...this.opts,...r};a.path||(a.path=""),a.path.startsWith("/")&&(a.path=a.path.slice(1)),a.noCommittish&&(a.committish=null);let i=e(a);return a.noGitPlus&&i.startsWith("git+")?i.slice(4):i}hash(){return this.committish?`#${this.committish}`:""}ssh(e){return this.#r(this.sshtemplate,e)}sshurl(e){return this.#r(this.sshurltemplate,e)}browse(e,...r){return typeof e!="string"?this.#r(this.browsetemplate,e):typeof r[0]!="string"?this.#r(this.browsetreetemplate,{...r[0],path:e}):this.#r(this.browsetreetemplate,{...r[1],fragment:r[0],path:e})}browseFile(e,...r){return typeof r[0]!="string"?this.#r(this.browseblobtemplate,{...r[0],path:e}):this.#r(this.browseblobtemplate,{...r[1],fragment:r[0],path:e})}docs(e){return this.#r(this.docstemplate,e)}bugs(e){return this.#r(this.bugstemplate,e)}https(e){return this.#r(this.httpstemplate,e)}git(e){return this.#r(this.gittemplate,e)}shortcut(e){return this.#r(this.shortcuttemplate,e)}path(e){return this.#r(this.pathtemplate,e)}tarball(e){return this.#r(this.tarballtemplate,{...e,noCommittish:!1})}file(e,r){return this.#r(this.filetemplate,{...r,path:e})}edit(e,r){return this.#r(this.edittemplate,{...r,path:e})}getDefaultRepresentation(){return this.default}toString(e){return this.default&&typeof this[this.default]=="function"?this[this.default](e):this.sshurl(e)}};for(let[n,e]of Object.entries(dds))aMe.addHost(n,e);S4n.exports=aMe});var J4n=Ge((pil,T4n)=>{T4n.exports=mds;function mds(n){if(!n||n==="ERROR: No README data found!")return;n=n.trim().split(`
7190
- `);let e=0;for(;n[e]&&n[e].trim().match(/^(#|$)/);)e++;let r=n.length,a=e+1;for(;a<r&&n[a].trim();)a++;return n.slice(e,a).join(" ").trim()}});var B4n=Ge((fil,pds)=>{pds.exports={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}}});var M4n=Ge((bil,_4n)=>{var fds=$Lt(),bds=eTt(),gds=w4n(),iMe=L4n(),Gds=Zt("node:module"),vds=["dependencies","devDependencies","optionalDependencies"],yds=J4n(),dTt=Zt("url"),nL=B4n(),O4n=n=>n.includes("@")&&n.indexOf("@")<n.lastIndexOf(".");_4n.exports={warn:function(){},fixRepositoryField:function(n){if(n.repositories&&(this.warn("repositories"),n.repository=n.repositories[0]),!n.repository)return this.warn("missingRepository");typeof n.repository=="string"&&(n.repository={type:"git",url:n.repository});var e=n.repository.url||"";if(e){var r=iMe.fromUrl(e);r&&(e=n.repository.url=r.getDefaultRepresentation()==="shortcut"?r.https():r.toString())}e.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",e)},fixTypos:function(n){Object.keys(nL.topLevel).forEach(function(e){Object.prototype.hasOwnProperty.call(n,e)&&this.warn("typo",e,nL.topLevel[e])},this)},fixScriptsField:function(n){if(n.scripts){if(typeof n.scripts!="object"){this.warn("nonObjectScripts"),delete n.scripts;return}Object.keys(n.scripts).forEach(function(e){typeof n.scripts[e]!="string"?(this.warn("nonStringScript"),delete n.scripts[e]):nL.script[e]&&!n.scripts[nL.script[e]]&&this.warn("typo",e,nL.script[e],"scripts")},this)}},fixFilesField:function(n){var e=n.files;e&&!Array.isArray(e)?(this.warn("nonArrayFiles"),delete n.files):n.files&&(n.files=n.files.filter(function(r){return!r||typeof r!="string"?(this.warn("invalidFilename",r),!1):!0},this))},fixBinField:function(n){if(n.bin&&typeof n.bin=="string"){var e={},r;(r=n.name.match(/^@[^/]+[/](.*)$/))?e[r[1]]=n.bin:e[n.name]=n.bin,n.bin=e}},fixManField:function(n){n.man&&typeof n.man=="string"&&(n.man=[n.man])},fixBundleDependenciesField:function(n){var e="bundledDependencies",r="bundleDependencies";n[e]&&!n[r]&&(n[r]=n[e],delete n[e]),n[r]&&!Array.isArray(n[r])?(this.warn("nonArrayBundleDependencies"),delete n[r]):n[r]&&(n[r]=n[r].filter(function(a){return!a||typeof a!="string"?(this.warn("nonStringBundleDependency",a),!1):(n.dependencies||(n.dependencies={}),Object.prototype.hasOwnProperty.call(n.dependencies,a)||(this.warn("nonDependencyBundleDependency",a),n.dependencies[a]="*"),!0)},this))},fixDependencies:function(n){Ads(n,this.warn),Eds(n,this.warn),this.fixBundleDependenciesField(n),["dependencies","devDependencies"].forEach(function(e){if(e in n){if(!n[e]||typeof n[e]!="object"){this.warn("nonObjectDependencies",e),delete n[e];return}Object.keys(n[e]).forEach(function(r){var a=n[e][r];typeof a!="string"&&(this.warn("nonStringDependency",r,JSON.stringify(a)),delete n[e][r]);var i=iMe.fromUrl(n[e][r]);i&&(n[e][r]=i.toString())},this)}},this)},fixModulesField:function(n){n.modules&&(this.warn("deprecatedModules"),delete n.modules)},fixKeywordsField:function(n){typeof n.keywords=="string"&&(n.keywords=n.keywords.split(/,\s+/)),n.keywords&&!Array.isArray(n.keywords)?(delete n.keywords,this.warn("nonArrayKeywords")):n.keywords&&(n.keywords=n.keywords.filter(function(e){return typeof e!="string"||!e?(this.warn("nonStringKeyword"),!1):!0},this))},fixVersionField:function(n,e){var r=!e;if(!n.version)return n.version="",!0;if(!fds(n.version,r))throw new Error('Invalid version: "'+n.version+'"');return n.version=bds(n.version,r),!0},fixPeople:function(n){D4n(n,wds),D4n(n,Fds)},fixNameField:function(n,e){typeof e=="boolean"?e={strict:e}:typeof e>"u"&&(e={});var r=e.strict;if(!n.name&&!r){n.name="";return}if(typeof n.name!="string")throw new Error("name field must be a string.");r||(n.name=n.name.trim()),Wds(n.name,r,e.allowLegacyCase),Gds.builtinModules.includes(n.name)&&this.warn("conflictingName",n.name)},fixDescriptionField:function(n){n.description&&typeof n.description!="string"&&(this.warn("nonStringDescription"),delete n.description),n.readme&&!n.description&&(n.description=yds(n.readme)),n.description===void 0&&delete n.description,n.description||this.warn("missingDescription")},fixReadmeField:function(n){n.readme||(this.warn("missingReadme"),n.readme="ERROR: No README data found!")},fixBugsField:function(n){if(!n.bugs&&n.repository&&n.repository.url){var e=iMe.fromUrl(n.repository.url);e&&e.bugs()&&(n.bugs={url:e.bugs()})}else if(n.bugs){if(typeof n.bugs=="string")O4n(n.bugs)?n.bugs={email:n.bugs}:dTt.parse(n.bugs).protocol?n.bugs={url:n.bugs}:this.warn("nonEmailUrlBugsString");else{xds(n.bugs,this.warn);var r=n.bugs;n.bugs={},r.url&&(typeof r.url=="string"&&dTt.parse(r.url).protocol?n.bugs.url=r.url:this.warn("nonUrlBugsUrlField")),r.email&&(typeof r.email=="string"&&O4n(r.email)?n.bugs.email=r.email:this.warn("nonEmailBugsEmailField"))}!n.bugs.email&&!n.bugs.url&&(delete n.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(n){if(!n.homepage&&n.repository&&n.repository.url){var e=iMe.fromUrl(n.repository.url);e&&e.docs()&&(n.homepage=e.docs())}if(n.homepage){if(typeof n.homepage!="string")return this.warn("nonUrlHomepage"),delete n.homepage;dTt.parse(n.homepage).protocol||(n.homepage="http://"+n.homepage)}},fixLicenseField:function(n){let e=n.license||n.licence;if(!e)return this.warn("missingLicense");if(typeof e!="string"||e.length<1||e.trim()==="")return this.warn("invalidLicense");if(!gds(e).validForNewPackages)return this.warn("invalidLicense")}};function Nds(n){if(n.charAt(0)!=="@")return!1;var e=n.slice(1).split("/");return e.length!==2?!1:e[0]&&e[1]&&e[0]===encodeURIComponent(e[0])&&e[1]===encodeURIComponent(e[1])}function Zds(n){return!n.match(/[/@\s+%:]/)&&n===encodeURIComponent(n)}function Wds(n,e,r){if(n.charAt(0)==="."||!(Nds(n)||Zds(n))||e&&!r&&n!==n.toLowerCase()||n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico")throw new Error("Invalid name: "+JSON.stringify(n))}function D4n(n,e){return n.author&&(n.author=e(n.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(n[r])&&(n[r]=n[r].map(e))}),n}function wds(n){if(typeof n=="string")return n;var e=n.name||"",r=n.url||n.web,a=r?" ("+r+")":"",i=n.email||n.mail,o=i?" <"+i+">":"";return e+o+a}function Fds(n){if(typeof n!="string")return n;var e=n.match(/^([^(<]+)/),r=n.match(/\(([^()]+)\)/),a=n.match(/<([^<>]+)>/),i={};return e&&e[0].trim()&&(i.name=e[0].trim()),a&&(i.email=a[1]),r&&(i.url=r[1]),i}function Eds(n){var e=n.optionalDependencies;if(e){var r=n.dependencies||{};Object.keys(e).forEach(function(a){r[a]=e[a]}),n.dependencies=r}}function Rds(n,e,r){if(!n)return{};if(typeof n=="string"&&(n=n.trim().split(/[\n\r\s\t ,]+/)),!Array.isArray(n))return n;r("deprecatedArrayDependencies",e);var a={};return n.filter(function(i){return typeof i=="string"}).forEach(function(i){i=i.trim().split(/(:?[@\s><=])/);var o=i.shift(),t=i.join("");t=t.trim(),t=t.replace(/^@/,""),a[o]=t}),a}function Ads(n,e){vds.forEach(function(r){n[r]&&(n[r]=Rds(n[r],r,e))})}function xds(n,e){n&&Object.keys(n).forEach(function(r){nL.bugs[r]&&(e("typo",r,nL.bugs[r],"bugs"),n[nL.bugs[r]]=n[r],delete n[r])})}});var U4n=Ge((gil,Cds)=>{Cds.exports={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."}});var j4n=Ge((Gil,P4n)=>{var z4n=Zt("util"),hTt=U4n();P4n.exports=function(){var n=Array.prototype.slice.call(arguments,0),e=n.shift();if(e==="typo")return Yds.apply(null,n);var r=hTt[e]?hTt[e]:e+": '%s'";return n.unshift(r),z4n.format.apply(null,n)};function Yds(n,e,r){return r&&(n=r+"['"+n+"']",e=r+"['"+e+"']"),z4n.format(hTt.typo,n,e)}});var exn=Ge((vil,$4n)=>{$4n.exports=q4n;var ITt=M4n();q4n.fixer=ITt;var Vds=j4n(),kds=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"],Hds=["dependencies","people","typos"],mTt=kds.map(function(n){return K4n(n)+"Field"});mTt=mTt.concat(Hds);function q4n(n,e,r){e===!0&&(e=null,r=!0),r||(r=!1),(!e||n.private)&&(e=function(){}),n.scripts&&n.scripts.install==="node-gyp rebuild"&&!n.scripts.preinstall&&(n.gypfile=!0),ITt.warn=function(){e(Vds.apply(null,arguments))},mTt.forEach(function(a){ITt["fix"+K4n(a)](n,r)}),n._id=n.name+"@"+n.version}function K4n(n){return n.charAt(0).toUpperCase()+n.slice(1)}});var txn=Be(()=>{});import{fileURLToPath as Qds}from"node:url";function rxn(n){return n instanceof URL?Qds(n):n}var nxn=Be(()=>{txn()});import Xds from"node:fs/promises";import Sds from"node:path";async function ixn({cwd:n,normalize:e=!0}={}){let r=await Xds.readFile(Lds(n),"utf8");return Tds(r,e)}var axn,Lds,Tds,sxn=Be(()=>{MAn();axn=Yt(exn(),1);nxn();Lds=n=>Sds.resolve(rxn(n)??".","package.json"),Tds=(n,e)=>{let r=typeof n=="string"?ULt(n):n;return e&&(0,axn.default)(r),r}});import Jds from"node:path";async function oxn(n){let e=await gAn("package.json",n);if(e)return{packageJson:await ixn({...n,cwd:Jds.dirname(e)}),path:e}}var lxn=Be(()=>{GAn();sxn()});import{fileURLToPath as Bds}from"url";import Ods from"path";async function pie(){if(mie)return mie;let n=await oxn({cwd:_ds});if(!n){let e="easycode-cli",r="1.1.59";return e&&r?(mie={name:e,version:r},mie):void 0}return mie=n.packageJson,mie}var Dds,_ds,mie,sMe=Be(()=>{"use strict";lxn();Dds=Bds(import.meta.url),_ds=Ods.dirname(Dds)});var cxn={};As(cxn,{getCliVersion:()=>SR});async function SR(){let n=await pie();return"1.1.59"}var J_=Be(()=>{"use strict";sMe();});import B_ from"node:process";var uxn,dxn=Be(()=>{"use strict";J_();di();Xs();un();uxn={name:"about",description:we("command.about.description"),kind:"built-in",action:async n=>{let e=B_.platform,r="no sandbox";B_.env.SANDBOX&&B_.env.SANDBOX!=="sandbox-exec"?r=B_.env.SANDBOX:B_.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${B_.env.SEATBELT_PROFILE||"unknown"})`);let a=n.services.config?.getModel()||"Unknown",i=await SR(),o=n.services.settings.merged.selectedAuthType||"",t=B_.env.GOOGLE_CLOUD_PROJECT||"",s={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:a,selectedAuthType:o,gcpProject:t};n.ui.addItem(s,Date.now())}}});var hxn,Ixn=Be(()=>{"use strict";di();un();hxn={name:"auth",description:we("command.auth.description"),kind:"built-in",action:(n,e)=>({type:"dialog",dialog:"auth"})}});var mxn,pxn=Be(()=>{"use strict";di();un();mxn={name:"clear",description:we("command.clear.description"),kind:"built-in",action:async(n,e)=>{n.ui.setDebugMessage("Clearing terminal screen."),n.ui.clear()}}});var fxn,bxn=Be(()=>{"use strict";Xs();di();un();fxn={name:"compress",altNames:["summarize","compact"],description:we("command.compress.description"),kind:"built-in",action:async n=>{let{ui:e}=n,r=n.services.config?.getGeminiClient();if(e.pendingItem){e.addItem({type:"error",text:"Already compressing, wait for previous request to complete"},Date.now());return}if(r?.isCompressionInProgress()){e.addItem({type:"error",text:"Compression already in progress at client level, please wait"},Date.now());return}e.addItem({type:"info",text:we("command.compress.starting")},Date.now());let a={type:"compression",compression:{isPending:!0,originalTokenCount:null,newTokenCount:null}};try{e.setPendingItem(a);let i=`compress-${Date.now()}`,o=await r?.tryCompressChat(i,new AbortController().signal,!0);o?e.addItem({type:"compression",compression:{isPending:!1,originalTokenCount:o.originalTokenCount,newTokenCount:o.newTokenCount}},Date.now()):e.addItem({type:"error",text:"Failed to compress chat history."},Date.now())}catch(i){e.addItem({type:"error",text:`Failed to compress chat history: ${i instanceof Error?i.message:String(i)}`},Date.now())}finally{e.setPendingItem(null)}}}});async function Mds(n){let{config:e,settings:r}=n.services;if(!e||!r)return{type:"message",messageType:"error",content:we("error.config.not.loaded")};let a=r.merged.vimMode||!1,i=e.getAgentStyle(),o=e.getApprovalMode(),t=e.getHealthyUseEnabled(),s=r.merged.preferredLanguage||we("config.value.default"),d=u=>{switch(u){case"codex":return"\u26A1";case"cursor":return"\u2197\uFE0F";case"augment":return"\u{1F680}";case"claude-code":return"\u2733\uFE0F";case"antigravity":return"\u{1F308}";case"windsurf":return"\u{1F30A}";default:return"\u{1D4E5}"}};return{type:"message",messageType:"info",content:`\u2699\uFE0F ${we("command.config.description")}
7190
+ `);let e=0;for(;n[e]&&n[e].trim().match(/^(#|$)/);)e++;let r=n.length,a=e+1;for(;a<r&&n[a].trim();)a++;return n.slice(e,a).join(" ").trim()}});var B4n=Ge((fil,pds)=>{pds.exports={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}}});var M4n=Ge((bil,_4n)=>{var fds=$Lt(),bds=eTt(),gds=w4n(),iMe=L4n(),Gds=Zt("node:module"),vds=["dependencies","devDependencies","optionalDependencies"],yds=J4n(),dTt=Zt("url"),nL=B4n(),O4n=n=>n.includes("@")&&n.indexOf("@")<n.lastIndexOf(".");_4n.exports={warn:function(){},fixRepositoryField:function(n){if(n.repositories&&(this.warn("repositories"),n.repository=n.repositories[0]),!n.repository)return this.warn("missingRepository");typeof n.repository=="string"&&(n.repository={type:"git",url:n.repository});var e=n.repository.url||"";if(e){var r=iMe.fromUrl(e);r&&(e=n.repository.url=r.getDefaultRepresentation()==="shortcut"?r.https():r.toString())}e.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",e)},fixTypos:function(n){Object.keys(nL.topLevel).forEach(function(e){Object.prototype.hasOwnProperty.call(n,e)&&this.warn("typo",e,nL.topLevel[e])},this)},fixScriptsField:function(n){if(n.scripts){if(typeof n.scripts!="object"){this.warn("nonObjectScripts"),delete n.scripts;return}Object.keys(n.scripts).forEach(function(e){typeof n.scripts[e]!="string"?(this.warn("nonStringScript"),delete n.scripts[e]):nL.script[e]&&!n.scripts[nL.script[e]]&&this.warn("typo",e,nL.script[e],"scripts")},this)}},fixFilesField:function(n){var e=n.files;e&&!Array.isArray(e)?(this.warn("nonArrayFiles"),delete n.files):n.files&&(n.files=n.files.filter(function(r){return!r||typeof r!="string"?(this.warn("invalidFilename",r),!1):!0},this))},fixBinField:function(n){if(n.bin&&typeof n.bin=="string"){var e={},r;(r=n.name.match(/^@[^/]+[/](.*)$/))?e[r[1]]=n.bin:e[n.name]=n.bin,n.bin=e}},fixManField:function(n){n.man&&typeof n.man=="string"&&(n.man=[n.man])},fixBundleDependenciesField:function(n){var e="bundledDependencies",r="bundleDependencies";n[e]&&!n[r]&&(n[r]=n[e],delete n[e]),n[r]&&!Array.isArray(n[r])?(this.warn("nonArrayBundleDependencies"),delete n[r]):n[r]&&(n[r]=n[r].filter(function(a){return!a||typeof a!="string"?(this.warn("nonStringBundleDependency",a),!1):(n.dependencies||(n.dependencies={}),Object.prototype.hasOwnProperty.call(n.dependencies,a)||(this.warn("nonDependencyBundleDependency",a),n.dependencies[a]="*"),!0)},this))},fixDependencies:function(n){Ads(n,this.warn),Eds(n,this.warn),this.fixBundleDependenciesField(n),["dependencies","devDependencies"].forEach(function(e){if(e in n){if(!n[e]||typeof n[e]!="object"){this.warn("nonObjectDependencies",e),delete n[e];return}Object.keys(n[e]).forEach(function(r){var a=n[e][r];typeof a!="string"&&(this.warn("nonStringDependency",r,JSON.stringify(a)),delete n[e][r]);var i=iMe.fromUrl(n[e][r]);i&&(n[e][r]=i.toString())},this)}},this)},fixModulesField:function(n){n.modules&&(this.warn("deprecatedModules"),delete n.modules)},fixKeywordsField:function(n){typeof n.keywords=="string"&&(n.keywords=n.keywords.split(/,\s+/)),n.keywords&&!Array.isArray(n.keywords)?(delete n.keywords,this.warn("nonArrayKeywords")):n.keywords&&(n.keywords=n.keywords.filter(function(e){return typeof e!="string"||!e?(this.warn("nonStringKeyword"),!1):!0},this))},fixVersionField:function(n,e){var r=!e;if(!n.version)return n.version="",!0;if(!fds(n.version,r))throw new Error('Invalid version: "'+n.version+'"');return n.version=bds(n.version,r),!0},fixPeople:function(n){D4n(n,wds),D4n(n,Fds)},fixNameField:function(n,e){typeof e=="boolean"?e={strict:e}:typeof e>"u"&&(e={});var r=e.strict;if(!n.name&&!r){n.name="";return}if(typeof n.name!="string")throw new Error("name field must be a string.");r||(n.name=n.name.trim()),Wds(n.name,r,e.allowLegacyCase),Gds.builtinModules.includes(n.name)&&this.warn("conflictingName",n.name)},fixDescriptionField:function(n){n.description&&typeof n.description!="string"&&(this.warn("nonStringDescription"),delete n.description),n.readme&&!n.description&&(n.description=yds(n.readme)),n.description===void 0&&delete n.description,n.description||this.warn("missingDescription")},fixReadmeField:function(n){n.readme||(this.warn("missingReadme"),n.readme="ERROR: No README data found!")},fixBugsField:function(n){if(!n.bugs&&n.repository&&n.repository.url){var e=iMe.fromUrl(n.repository.url);e&&e.bugs()&&(n.bugs={url:e.bugs()})}else if(n.bugs){if(typeof n.bugs=="string")O4n(n.bugs)?n.bugs={email:n.bugs}:dTt.parse(n.bugs).protocol?n.bugs={url:n.bugs}:this.warn("nonEmailUrlBugsString");else{xds(n.bugs,this.warn);var r=n.bugs;n.bugs={},r.url&&(typeof r.url=="string"&&dTt.parse(r.url).protocol?n.bugs.url=r.url:this.warn("nonUrlBugsUrlField")),r.email&&(typeof r.email=="string"&&O4n(r.email)?n.bugs.email=r.email:this.warn("nonEmailBugsEmailField"))}!n.bugs.email&&!n.bugs.url&&(delete n.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(n){if(!n.homepage&&n.repository&&n.repository.url){var e=iMe.fromUrl(n.repository.url);e&&e.docs()&&(n.homepage=e.docs())}if(n.homepage){if(typeof n.homepage!="string")return this.warn("nonUrlHomepage"),delete n.homepage;dTt.parse(n.homepage).protocol||(n.homepage="http://"+n.homepage)}},fixLicenseField:function(n){let e=n.license||n.licence;if(!e)return this.warn("missingLicense");if(typeof e!="string"||e.length<1||e.trim()==="")return this.warn("invalidLicense");if(!gds(e).validForNewPackages)return this.warn("invalidLicense")}};function Nds(n){if(n.charAt(0)!=="@")return!1;var e=n.slice(1).split("/");return e.length!==2?!1:e[0]&&e[1]&&e[0]===encodeURIComponent(e[0])&&e[1]===encodeURIComponent(e[1])}function Zds(n){return!n.match(/[/@\s+%:]/)&&n===encodeURIComponent(n)}function Wds(n,e,r){if(n.charAt(0)==="."||!(Nds(n)||Zds(n))||e&&!r&&n!==n.toLowerCase()||n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico")throw new Error("Invalid name: "+JSON.stringify(n))}function D4n(n,e){return n.author&&(n.author=e(n.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(n[r])&&(n[r]=n[r].map(e))}),n}function wds(n){if(typeof n=="string")return n;var e=n.name||"",r=n.url||n.web,a=r?" ("+r+")":"",i=n.email||n.mail,o=i?" <"+i+">":"";return e+o+a}function Fds(n){if(typeof n!="string")return n;var e=n.match(/^([^(<]+)/),r=n.match(/\(([^()]+)\)/),a=n.match(/<([^<>]+)>/),i={};return e&&e[0].trim()&&(i.name=e[0].trim()),a&&(i.email=a[1]),r&&(i.url=r[1]),i}function Eds(n){var e=n.optionalDependencies;if(e){var r=n.dependencies||{};Object.keys(e).forEach(function(a){r[a]=e[a]}),n.dependencies=r}}function Rds(n,e,r){if(!n)return{};if(typeof n=="string"&&(n=n.trim().split(/[\n\r\s\t ,]+/)),!Array.isArray(n))return n;r("deprecatedArrayDependencies",e);var a={};return n.filter(function(i){return typeof i=="string"}).forEach(function(i){i=i.trim().split(/(:?[@\s><=])/);var o=i.shift(),t=i.join("");t=t.trim(),t=t.replace(/^@/,""),a[o]=t}),a}function Ads(n,e){vds.forEach(function(r){n[r]&&(n[r]=Rds(n[r],r,e))})}function xds(n,e){n&&Object.keys(n).forEach(function(r){nL.bugs[r]&&(e("typo",r,nL.bugs[r],"bugs"),n[nL.bugs[r]]=n[r],delete n[r])})}});var U4n=Ge((gil,Cds)=>{Cds.exports={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."}});var j4n=Ge((Gil,P4n)=>{var z4n=Zt("util"),hTt=U4n();P4n.exports=function(){var n=Array.prototype.slice.call(arguments,0),e=n.shift();if(e==="typo")return Yds.apply(null,n);var r=hTt[e]?hTt[e]:e+": '%s'";return n.unshift(r),z4n.format.apply(null,n)};function Yds(n,e,r){return r&&(n=r+"['"+n+"']",e=r+"['"+e+"']"),z4n.format(hTt.typo,n,e)}});var exn=Ge((vil,$4n)=>{$4n.exports=q4n;var ITt=M4n();q4n.fixer=ITt;var Vds=j4n(),kds=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"],Hds=["dependencies","people","typos"],mTt=kds.map(function(n){return K4n(n)+"Field"});mTt=mTt.concat(Hds);function q4n(n,e,r){e===!0&&(e=null,r=!0),r||(r=!1),(!e||n.private)&&(e=function(){}),n.scripts&&n.scripts.install==="node-gyp rebuild"&&!n.scripts.preinstall&&(n.gypfile=!0),ITt.warn=function(){e(Vds.apply(null,arguments))},mTt.forEach(function(a){ITt["fix"+K4n(a)](n,r)}),n._id=n.name+"@"+n.version}function K4n(n){return n.charAt(0).toUpperCase()+n.slice(1)}});var txn=Be(()=>{});import{fileURLToPath as Qds}from"node:url";function rxn(n){return n instanceof URL?Qds(n):n}var nxn=Be(()=>{txn()});import Xds from"node:fs/promises";import Sds from"node:path";async function ixn({cwd:n,normalize:e=!0}={}){let r=await Xds.readFile(Lds(n),"utf8");return Tds(r,e)}var axn,Lds,Tds,sxn=Be(()=>{MAn();axn=Yt(exn(),1);nxn();Lds=n=>Sds.resolve(rxn(n)??".","package.json"),Tds=(n,e)=>{let r=typeof n=="string"?ULt(n):n;return e&&(0,axn.default)(r),r}});import Jds from"node:path";async function oxn(n){let e=await gAn("package.json",n);if(e)return{packageJson:await ixn({...n,cwd:Jds.dirname(e)}),path:e}}var lxn=Be(()=>{GAn();sxn()});import{fileURLToPath as Bds}from"url";import Ods from"path";async function pie(){if(mie)return mie;let n=await oxn({cwd:_ds});if(!n){let e="easycode-cli",r="1.1.60";return e&&r?(mie={name:e,version:r},mie):void 0}return mie=n.packageJson,mie}var Dds,_ds,mie,sMe=Be(()=>{"use strict";lxn();Dds=Bds(import.meta.url),_ds=Ods.dirname(Dds)});var cxn={};As(cxn,{getCliVersion:()=>SR});async function SR(){let n=await pie();return"1.1.60"}var J_=Be(()=>{"use strict";sMe();});import B_ from"node:process";var uxn,dxn=Be(()=>{"use strict";J_();di();Xs();un();uxn={name:"about",description:we("command.about.description"),kind:"built-in",action:async n=>{let e=B_.platform,r="no sandbox";B_.env.SANDBOX&&B_.env.SANDBOX!=="sandbox-exec"?r=B_.env.SANDBOX:B_.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${B_.env.SEATBELT_PROFILE||"unknown"})`);let a=n.services.config?.getModel()||"Unknown",i=await SR(),o=n.services.settings.merged.selectedAuthType||"",t=B_.env.GOOGLE_CLOUD_PROJECT||"",s={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:a,selectedAuthType:o,gcpProject:t};n.ui.addItem(s,Date.now())}}});var hxn,Ixn=Be(()=>{"use strict";di();un();hxn={name:"auth",description:we("command.auth.description"),kind:"built-in",action:(n,e)=>({type:"dialog",dialog:"auth"})}});var mxn,pxn=Be(()=>{"use strict";di();un();mxn={name:"clear",description:we("command.clear.description"),kind:"built-in",action:async(n,e)=>{n.ui.setDebugMessage("Clearing terminal screen."),n.ui.clear()}}});var fxn,bxn=Be(()=>{"use strict";Xs();di();un();fxn={name:"compress",altNames:["summarize","compact"],description:we("command.compress.description"),kind:"built-in",action:async n=>{let{ui:e}=n,r=n.services.config?.getGeminiClient();if(e.pendingItem){e.addItem({type:"error",text:"Already compressing, wait for previous request to complete"},Date.now());return}if(r?.isCompressionInProgress()){e.addItem({type:"error",text:"Compression already in progress at client level, please wait"},Date.now());return}e.addItem({type:"info",text:we("command.compress.starting")},Date.now());let a={type:"compression",compression:{isPending:!0,originalTokenCount:null,newTokenCount:null}};try{e.setPendingItem(a);let i=`compress-${Date.now()}`,o=await r?.tryCompressChat(i,new AbortController().signal,!0);o?e.addItem({type:"compression",compression:{isPending:!1,originalTokenCount:o.originalTokenCount,newTokenCount:o.newTokenCount}},Date.now()):e.addItem({type:"error",text:"Failed to compress chat history."},Date.now())}catch(i){e.addItem({type:"error",text:`Failed to compress chat history: ${i instanceof Error?i.message:String(i)}`},Date.now())}finally{e.setPendingItem(null)}}}});async function Mds(n){let{config:e,settings:r}=n.services;if(!e||!r)return{type:"message",messageType:"error",content:we("error.config.not.loaded")};let a=r.merged.vimMode||!1,i=e.getAgentStyle(),o=e.getApprovalMode(),t=e.getHealthyUseEnabled(),s=r.merged.preferredLanguage||we("config.value.default"),d=u=>{switch(u){case"codex":return"\u26A1";case"cursor":return"\u2197\uFE0F";case"augment":return"\u{1F680}";case"claude-code":return"\u2733\uFE0F";case"antigravity":return"\u{1F308}";case"windsurf":return"\u{1F30A}";default:return"\u{1D4E5}"}};return{type:"message",messageType:"info",content:`\u2699\uFE0F ${we("command.config.description")}
7191
7191
 
7192
7192
  ${we("command.config.available.options")}:
7193
7193
 
@@ -9107,7 +9107,7 @@ ${e}`}}var lPn=2e5;function cPn(n,e){return n.length<=e?n:`\u2026[earlier output
9107
9107
  `);return`${e}
9108
9108
 
9109
9109
  ${r}`}function qks(n){let e=new Map,r=[];for(let a of n){if(a.id!=null&&e.has(a.id)){r[e.get(a.id)]=a;continue}a.id!=null&&e.set(a.id,r.length),r.push(a)}return r}function Kks(n){let e=(n??"").split(`
9110
- `).map(r=>r.trim()).find(r=>r.length>0)??"";return e=e.replace(/^["'`《》「」“”‘’\[\]]+|["'`《》「」“”‘’\[\]]+$/g,"").trim(),e=e.replace(/[。..!!??,,;;::]+$/u,"").trim(),e.length>60&&(e=e.slice(0,60).trim()),e}function DPn(n,e){if(e<=0)return[];let r=0;for(let a=0;a<n.length;a++){let i=n[a]??{},o=i.parts;if(i.type==="user"||i.role==="user"&&!o?.some(s=>s&&"functionResponse"in s)&&!nNe("user",(o??[]).map(s=>typeof s?.text=="string"?s.text:"").join(""))){if(r===e)return n.slice(0,a);r+=1}}return[...n]}function $Mt(n,e){let r=0,a=n.length;for(let i=0;i<n.length;i++){let o=n[i];if(o.role!==en.USER)continue;let t=o.parts??[];if(t.some(d=>d.functionResponse))continue;let s=t.map(d=>typeof d.text=="string"?d.text:"").join("");if(!nNe(en.USER,s)){if(r===e){a=i;break}r+=1}}return{cutAt:a,userMessageSeen:r}}var aNe=class n{constructor(e,r,a,i,o,t){this.id=e;this.chat=r;this.config=a;this.connection=i;this._settings=o;this.cwd=t;this.approvalModeUnsubscribe=Y6t.on(LGe.ApprovalModeChanged,s=>{s.sessionId&&s.sessionId!==this.id||this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[MODE_UPDATE] ${s.mode}`}})}),this.backgroundTaskUnsubscribe=this.subscribeBackgroundTaskEvents()}pendingAbort;turnCheckpointCreated=!1;turnUserQuery="";approvalModeUnsubscribe;titleGenerated=!1;configValues=new Map;fileOperationQueue=new HX;pendingInjectedText=[];lastIncrementalPersistAt=0;backgroundTaskPushDisabled=!1;backgroundTaskUnsubscribe;dispose(){this.pendingAbort?.abort(),this.pendingAbort=void 0,this.sideQuestionAbort?.abort(),this.sideQuestionAbort=void 0,this.approvalModeUnsubscribe(),this.backgroundTaskUnsubscribe()}subscribeBackgroundTaskEvents(){let e=Do();e.getMaxListeners()<100&&e.setMaxListeners(100);let r=()=>this.pushBackgroundTasksSnapshot(),a=i=>{this.pushBackgroundTasksSnapshot(),this.dispatchBackgroundTaskNotification(i.task)};return e.on("task-started",r),e.on("task-completed",a),e.on("task-failed",a),e.on("task-cancelled",a),e.on("task-killed",a),()=>{e.removeListener("task-started",r),e.removeListener("task-completed",a),e.removeListener("task-failed",a),e.removeListener("task-cancelled",a),e.removeListener("task-killed",a)}}pushBackgroundTasksSnapshot(){let e=Do().getAllTasks().map(Nje);this.callHostBackgroundTaskMethod(uPn,{sessionId:this.id,tasks:e})}dispatchBackgroundTaskNotification(e){let r=hPn(e);if(this.pendingAbort){this.injectMidTurnText(r);return}this.callHostBackgroundTaskMethod(dPn,{sessionId:this.id,taskId:e.id,notificationText:r})}async callHostBackgroundTaskMethod(e,r){if(this.backgroundTaskPushDisabled)return;let a=this.connection.extMethod;if(typeof a!="function"){this.backgroundTaskPushDisabled=!0;return}try{await a.call(this.connection,e,r)}catch(i){this.backgroundTaskPushDisabled=!0,this.debug(`host does not accept ${e} (${Bb(i)}); background-task push disabled for this session`)}}checkpointProjectRoot(){return this.cwd??this.config.getProjectRoot?.()}realUserMessageCount(){let e=this.chat.getHistory(!1);return $Mt(e,Number.MAX_SAFE_INTEGER).userMessageSeen}async maybeCreateTurnCheckpoint(e){if(this.turnCheckpointCreated)return;let r=e.map(t=>({name:t.name??"",args:t.args??void 0}));if(!o_e(r))return;this.turnCheckpointCreated=!0;let a=this.checkpointProjectRoot();if(!a)return;let i=Math.max(0,this.realUserMessageCount()-1),o=await X6t(this.config,{projectRoot:a,sessionId:this.id,userMessageIndex:i,lastUserMessage:this.turnUserQuery});o&&await this.callHostBackgroundTaskMethod("_dvcode/host/checkpointCreated",{sessionId:this.id,checkpoint:o})}async listCheckpoints(){let e=this.checkpointProjectRoot();return e?l_e(e,this.id):[]}async restoreCheckpoint(e){if(this.pendingAbort)return{ok:!1,busy:!0,error:"A turn is in progress \u2014 stop it before restoring a checkpoint."};let r=this.checkpointProjectRoot();if(!r)return{ok:!1,error:"No project root for this session"};let a=await L6t(r,this.id,e);if(!a)return{ok:!1,error:`Checkpoint not found: ${e}`};let i=this.chat.getHistory(!1),o=await this.rewindToBeforeUserMessage(a.userMessageIndex);if(!o.persisted)return this.chat.setHistory(i),{ok:!1,persistFailed:!0,error:"Could not save the rewound conversation (disk/permission/lock). Restore aborted \u2014 nothing changed; retry once it clears.",checkpoint:a};try{await T6t(this.config,a.commitHash)}catch(s){return this.chat.setHistory(i),await this.persistTruncatedHistory(i,this.realUserMessageCount()).catch(()=>{}),{ok:!1,error:`File restore failed: ${Bb(s)}`,checkpoint:a}}let t=await S6t(r,this.id,a.userMessageIndex);return{ok:!0,checkpoint:a,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount,checkpointsPruned:t}}sideQuestionAbort;async askSideQuestion(e){let r=this.config.getGeminiClient();if(!r)return{text:"",status:"failed",error:"Backend client not ready."};let a=null;try{a=this.chat.cacheSafeParams.get()}catch{}this.sideQuestionAbort?.abort();let i=new AbortController;this.sideQuestionAbort=i;try{let o=await OS({contentGenerator:r.getContentGenerator(),model:this.config.getModel()??"auto",question:e,cacheSafeSnapshot:a,signal:i.signal});return{text:o.text,status:o.status,error:o.error}}finally{this.sideQuestionAbort===i&&(this.sideQuestionAbort=void 0)}}async cancelPendingPrompt(){this.pendingAbort?.abort(),this.pendingAbort=void 0}injectMidTurnText(e){let r=e.trim();r&&this.pendingInjectedText.push(r)}drainInjectedText(){if(this.pendingInjectedText.length===0)return"";let e=this.pendingInjectedText.splice(0);return jks(e)}getModeStatus(){let e=null;try{let r=this.config.getGeminiClient()?.getGoalContext();r&&(e={startedAt:r.startedAt,hours:r.hours})}catch{}return{planModeActive:this.config.getPlanModeActive(),goal:e}}async setPlanMode(e){if(this.config.setPlanModeActive(e),!e)if(this.pendingAbort)this.injectMidTurnText(o1e);else try{await this.config.getGeminiClient()?.addHistory({role:en.USER,parts:[{text:o1e}]})}catch{}return{planModeActive:e}}clearGoalMode(){let e;try{e=this.config.getGeminiClient()}catch{e=void 0}if(!e?.getGoalContext())return{wasActive:!1,injected:!1};e.clearGoalContext();let r=uGe();return this.pendingAbort?(this.injectMidTurnText(r),{wasActive:!0,injected:!0}):{wasActive:!0,injected:!1,clearMessage:r}}startGoalMode(e){try{return oie(this.config,e)}catch(r){throw new wa(-32e3,`Failed to start goal mode: ${r instanceof Error?r.message:String(r)}`)}}async rewindToBeforeUserMessage(e){if(!Number.isFinite(e)||e<0)throw new wa(-32602,`Invalid beforeUserMessageIndex: ${e}`);this.pendingAbort?.abort(),this.pendingAbort=void 0;let r=this.chat.getHistory(!1),{cutAt:a,userMessageSeen:i}=$Mt(r,e),o=r.slice(0,a);this.chat.setHistory(o);let t=Math.min(i,e),s=await this.persistTruncatedHistory(o,t);return{keptContentCount:o.length,keptUserMessageCount:t,droppedContentCount:r.length-o.length,persisted:s}}async persistTruncatedHistory(e,r){let a=this.cwd??this.config.getProjectRoot?.();if(!a)return this.debug("persistTruncatedHistory skipped: no projectRoot"),!1;try{let i=new Di(a),o=await i.loadSession(this.id),t=DPn(o?.history??[],r);return await i.saveSessionHistory(this.id,t,e),!0}catch(i){return this.debug(`persistTruncatedHistory failed: ${Bb(i)}`),!1}}async forkAtUserMessage(e){if(!Number.isFinite(e)||e<0)throw new wa(-32602,`Invalid beforeUserMessageIndex: ${e}`);let r=this.cwd??this.config.getProjectRoot?.();if(!r)throw new wa(-32603,"Cannot fork: session has no project root to persist into");let a=this.chat.getHistory(!1),{cutAt:i,userMessageSeen:o}=$Mt(a,e),t=Math.min(o,e),s=a.slice(0,i).filter(d=>{let h=(d.parts??[]).map(u=>typeof u.text=="string"?u.text:"").join("");return!nNe(d.role===en.USER?"user":"model",h)});try{let d=new Di(r),h=await d.loadSession(this.id),u=DPn(h?.history??[],t),I=Dks();return await d.loadSession(I),await d.saveSessionHistory(I,u,s),{newSessionId:I,keptContentCount:s.length,keptUserMessageCount:t,droppedContentCount:a.length-i}}catch(d){throw d instanceof wa?d:new wa(-32603,`Fork failed: ${Bb(d)}`)}}async persistHistory(){let e=this.cwd??this.config.getProjectRoot?.();if(!e){this.debug("persistHistory skipped: no projectRoot");return}try{let r=this.chat.getHistory(!1);if(r.length===0)return;let a=new Di(e);await a.loadSession(this.id),await a.saveSessionHistory(this.id,r,r),this.lastIncrementalPersistAt=Date.now()}catch(r){this.debug(`persistHistory failed: ${Bb(r)}`)}}static INCREMENTAL_PERSIST_INTERVAL_MS=2e3;async maybePersistIncrementally(){Date.now()-this.lastIncrementalPersistAt<n.INCREMENTAL_PERSIST_INTERVAL_MS||await this.persistHistory()}markTitleGenerated(){this.titleGenerated=!0}setMode(e){this.config.setApprovalMode?.(e)}async setModel(e,r){let a=this.config,i=a.getGeminiClient?.(),o=r??new AbortController().signal,t=(()=>{if(!e.startsWith("custom:"))return e;let d=this.config.getCustomModelConfig?.(e);if(!d)return e;let h=qc(d);return h!==e?h:e})();if(i?.switchModel){let d=await i.switchModel(t,o);return d?.success!==!1&&this.persistPreferredModel(t),d}return a.setModel?.(t),this.chat.setSpecifiedModel?.(t),this.persistPreferredModel(t),null}persistPreferredModel(e){try{this._settings.setValue("User","preferredModel",e)}catch(r){process.stderr.write(`[acp] failed to persist preferredModel=${e}: ${r instanceof Error?r.message:String(r)}
9110
+ `).map(r=>r.trim()).find(r=>r.length>0)??"";return e=e.replace(/^["'`《》「」“”‘’\[\]]+|["'`《》「」“”‘’\[\]]+$/g,"").trim(),e=e.replace(/[。..!!??,,;;::]+$/u,"").trim(),e.length>60&&(e=e.slice(0,60).trim()),e}function DPn(n,e){if(e<=0)return[];let r=0;for(let a=0;a<n.length;a++){let i=n[a]??{},o=i.parts;if(i.type==="user"||i.role==="user"&&!o?.some(s=>s&&"functionResponse"in s)&&!nNe("user",(o??[]).map(s=>typeof s?.text=="string"?s.text:"").join(""))){if(r===e)return n.slice(0,a);r+=1}}return[...n]}function $Mt(n,e){let r=0,a=n.length;for(let i=0;i<n.length;i++){let o=n[i];if(o.role!==en.USER)continue;let t=o.parts??[];if(t.some(d=>d.functionResponse))continue;let s=t.map(d=>typeof d.text=="string"?d.text:"").join("");if(!nNe(en.USER,s)){if(r===e){a=i;break}r+=1}}return{cutAt:a,userMessageSeen:r}}var aNe=class n{constructor(e,r,a,i,o,t){this.id=e;this.chat=r;this.config=a;this.connection=i;this._settings=o;this.cwd=t;this.approvalModeUnsubscribe=Y6t.on(LGe.ApprovalModeChanged,s=>{s.sessionId&&s.sessionId!==this.id||this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[MODE_UPDATE] ${s.mode}`}})}),this.backgroundTaskUnsubscribe=this.subscribeBackgroundTaskEvents()}pendingAbort;turnCheckpointCreated=!1;turnUserQuery="";approvalModeUnsubscribe;titleGenerated=!1;configValues=new Map;fileOperationQueue=new HX;pendingInjectedText=[];lastIncrementalPersistAt=0;backgroundTaskPushDisabled=!1;backgroundTaskUnsubscribe;dispose(){this.pendingAbort?.abort(),this.pendingAbort=void 0,this.sideQuestionAbort?.abort(),this.sideQuestionAbort=void 0,this.approvalModeUnsubscribe(),this.backgroundTaskUnsubscribe()}subscribeBackgroundTaskEvents(){let e=Do();e.getMaxListeners()<100&&e.setMaxListeners(100);let r=()=>this.pushBackgroundTasksSnapshot(),a=i=>{this.pushBackgroundTasksSnapshot(),this.dispatchBackgroundTaskNotification(i.task)};return e.on("task-started",r),e.on("task-completed",a),e.on("task-failed",a),e.on("task-cancelled",a),e.on("task-killed",a),()=>{e.removeListener("task-started",r),e.removeListener("task-completed",a),e.removeListener("task-failed",a),e.removeListener("task-cancelled",a),e.removeListener("task-killed",a)}}pushBackgroundTasksSnapshot(){let e=Do().getAllTasks().map(Nje);this.callHostBackgroundTaskMethod(uPn,{sessionId:this.id,tasks:e})}dispatchBackgroundTaskNotification(e){let r=hPn(e);if(this.pendingAbort){this.injectMidTurnText(r);return}this.callHostBackgroundTaskMethod(dPn,{sessionId:this.id,taskId:e.id,notificationText:r})}async callHostBackgroundTaskMethod(e,r){if(this.backgroundTaskPushDisabled)return;let a=this.connection.extMethod;if(typeof a!="function"){this.backgroundTaskPushDisabled=!0;return}try{await a.call(this.connection,e,r)}catch(i){this.backgroundTaskPushDisabled=!0,this.debug(`host does not accept ${e} (${Bb(i)}); background-task push disabled for this session`)}}checkpointProjectRoot(){return this.cwd??this.config.getProjectRoot?.()}realUserMessageCount(){let e=this.chat.getHistory(!1);return $Mt(e,Number.MAX_SAFE_INTEGER).userMessageSeen}async maybeCreateTurnCheckpoint(e){if(this.turnCheckpointCreated)return;let r=e.map(t=>({name:t.name??"",args:t.args??void 0}));if(!o_e(r))return;this.turnCheckpointCreated=!0;let a=this.checkpointProjectRoot();if(!a)return;let i=Math.max(0,this.realUserMessageCount()-1),o=await X6t(this.config,{projectRoot:a,sessionId:this.id,userMessageIndex:i,lastUserMessage:this.turnUserQuery});o&&await this.callHostBackgroundTaskMethod("_dvcode/host/checkpointCreated",{sessionId:this.id,checkpoint:o})}async listCheckpoints(){let e=this.checkpointProjectRoot();return e?l_e(e,this.id):[]}async restoreCheckpoint(e){if(this.pendingAbort)return{ok:!1,busy:!0,error:"A turn is in progress \u2014 stop it before restoring a checkpoint."};let r=this.checkpointProjectRoot();if(!r)return{ok:!1,error:"No project root for this session"};let a=await L6t(r,this.id,e);if(!a)return{ok:!1,error:`Checkpoint not found: ${e}`};let i=this.chat.getHistory(!1),o=await this.rewindToBeforeUserMessage(a.userMessageIndex);if(!o.persisted)return this.chat.setHistory(i),{ok:!1,persistFailed:!0,error:"Could not save the rewound conversation (disk/permission/lock). Restore aborted \u2014 nothing changed; retry once it clears.",checkpoint:a};try{await T6t(this.config,a.commitHash)}catch(s){return this.chat.setHistory(i),await this.persistTruncatedHistory(i,this.realUserMessageCount()).catch(()=>{}),{ok:!1,error:`File restore failed: ${Bb(s)}`,checkpoint:a}}let t=await S6t(r,this.id,a.userMessageIndex);return{ok:!0,checkpoint:a,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount,checkpointsPruned:t}}sideQuestionAbort;async askSideQuestion(e){let r=this.config.getGeminiClient();if(!r)return{text:"",status:"failed",error:"Backend client not ready."};let a=null;try{a=this.chat.cacheSafeParams.get()}catch{}this.sideQuestionAbort?.abort();let i=new AbortController;this.sideQuestionAbort=i;try{let o=await OS({contentGenerator:r.getContentGenerator(),model:this.config.getModel()??"auto",question:e,cacheSafeSnapshot:a,signal:i.signal});return{text:o.text,status:o.status,error:o.error}}finally{this.sideQuestionAbort===i&&(this.sideQuestionAbort=void 0)}}async cancelPendingPrompt(){this.pendingAbort?.abort(),this.pendingAbort=void 0}injectMidTurnText(e){let r=e.trim();r&&this.pendingInjectedText.push(r)}drainInjectedText(){if(this.pendingInjectedText.length===0)return"";let e=this.pendingInjectedText.splice(0);return jks(e)}getModeStatus(){let e=null;try{let r=this.config.getGeminiClient()?.getGoalContext();r&&(e={startedAt:r.startedAt,hours:r.hours})}catch{}return{planModeActive:this.config.getPlanModeActive(),goal:e}}async setPlanMode(e){if(this.config.setPlanModeActive(e),!e)if(this.pendingAbort)this.injectMidTurnText(o1e);else try{await this.config.getGeminiClient()?.addHistory({role:en.USER,parts:[{text:o1e}]})}catch{}return{planModeActive:e}}clearGoalMode(){let e;try{e=this.config.getGeminiClient()}catch{e=void 0}if(!e?.getGoalContext())return{wasActive:!1,injected:!1};e.clearGoalContext();let r=uGe();return this.pendingAbort?(this.injectMidTurnText(r),{wasActive:!0,injected:!0}):{wasActive:!0,injected:!1,clearMessage:r}}startGoalMode(e){try{return oie(this.config,e)}catch(r){throw new wa(-32e3,`Failed to start goal mode: ${r instanceof Error?r.message:String(r)}`)}}async rewindToBeforeUserMessage(e){if(!Number.isFinite(e)||e<0)throw new wa(-32602,`Invalid beforeUserMessageIndex: ${e}`);this.pendingAbort?.abort(),this.pendingAbort=void 0;let r=this.chat.getHistory(!1),{cutAt:a,userMessageSeen:i}=$Mt(r,e),o=r.slice(0,a);this.chat.setHistory(o);let t=Math.min(i,e),s=await this.persistTruncatedHistory(o,t);return{keptContentCount:o.length,keptUserMessageCount:t,droppedContentCount:r.length-o.length,persisted:s}}async persistTruncatedHistory(e,r){let a=this.cwd??this.config.getProjectRoot?.();if(!a)return this.debug("persistTruncatedHistory skipped: no projectRoot"),!1;try{let i=new Di(a),o=await i.loadSession(this.id),t=DPn(o?.history??[],r);return await i.saveSessionHistory(this.id,t,e),!0}catch(i){return this.debug(`persistTruncatedHistory failed: ${Bb(i)}`),!1}}async forkAtUserMessage(e){if(!Number.isFinite(e)||e<0)throw new wa(-32602,`Invalid beforeUserMessageIndex: ${e}`);let r=this.cwd??this.config.getProjectRoot?.();if(!r)throw new wa(-32603,"Cannot fork: session has no project root to persist into");let a=this.chat.getHistory(!1),{cutAt:i,userMessageSeen:o}=$Mt(a,e),t=Math.min(o,e),s=a.slice(0,i).filter(d=>{let h=(d.parts??[]).map(u=>typeof u.text=="string"?u.text:"").join("");return!nNe(d.role===en.USER?"user":"model",h)});try{let d=new Di(r),h=await d.loadSession(this.id),u=DPn(h?.history??[],t),I=Dks();return await d.loadSession(I),await d.saveSessionHistory(I,u,s),{newSessionId:I,keptContentCount:s.length,keptUserMessageCount:t,droppedContentCount:a.length-i}}catch(d){throw d instanceof wa?d:new wa(-32603,`Fork failed: ${Bb(d)}`)}}async persistHistory(){let e=this.cwd??this.config.getProjectRoot?.();if(!e){this.debug("persistHistory skipped: no projectRoot");return}try{let r=this.chat.getHistory(!1);if(r.length===0)return;let a=new Di(e);await a.loadSession(this.id),await a.saveSessionHistory(this.id,r,r),this.lastIncrementalPersistAt=Date.now()}catch(r){this.debug(`persistHistory failed: ${Bb(r)}`)}}static INCREMENTAL_PERSIST_INTERVAL_MS=2e3;async maybePersistIncrementally(){Date.now()-this.lastIncrementalPersistAt<n.INCREMENTAL_PERSIST_INTERVAL_MS||await this.persistHistory()}markTitleGenerated(){this.titleGenerated=!0}setMode(e){this.config.setApprovalMode?.(e)}async setModel(e,r){let a=this.config,i=a.getGeminiClient?.(),o=r??new AbortController().signal,t=this.canonicalizeCustomModelId(e);if(i?.switchModel){let d=await i.switchModel(t,o);return d?.success!==!1&&this.persistPreferredModel(t),d}return a.setModel?.(t),this.chat.setSpecifiedModel?.(t),this.persistPreferredModel(t),null}canonicalizeCustomModelId(e){if(!e.startsWith("custom:"))return e;let r=this.config.getCustomModelConfig?.(e);if(!r)return e;let a=qc(r);return a&&a!==e?a:e}reconcileStartupModelId(){let e=this.config,r=e.getModel?.();if(!r)return;let a=this.canonicalizeCustomModelId(r);a!==r&&(e.setModel?.(a),this.chat.setSpecifiedModel?.(a))}persistPreferredModel(e){try{this._settings.setValue("User","preferredModel",e)}catch(r){process.stderr.write(`[acp] failed to persist preferredModel=${e}: ${r instanceof Error?r.message:String(r)}
9111
9111
  `)}}async applyConfigOption(e,r){if(this.configValues.set(e,r),e==="model"&&typeof r=="string"){let a=await this.setModel(r);return a&&!a.success?(this.configValues.delete(e),{error:a.error}):{compressionInfo:a?.compressionInfo,compressionSkipReason:a?.compressionSkipReason}}else e==="mode"&&typeof r=="string"?this.setMode(r):e==="thinking"&&typeof r=="string"&&this.config.setThinkingConfig(RPn(r));return{}}getConfigValue(e,r){return this.configValues.get(e)??r}getAllConfigValues(){return this.configValues}async streamHistory(e){for(let r of e){let a=r;if(!a)continue;let o=(Array.isArray(a.parts)?a.parts:a.content!==void 0?[].concat(typeof a.content=="string"?[{text:a.content}]:Array.isArray(a.content)?a.content:[a.content]):[]).map(s=>typeof s.text=="string"?s.text:"").join("");if(!o&&typeof a.text=="string"&&(o=a.text),!o)continue;let t;if(a.role)t=a.role==="user"?"user":"assistant";else{let s=a.type;if(s==="user")t="user";else if(s==="gemini"||s==="model"||s==="assistant")t="assistant";else continue}nNe(t==="user"?"user":"model",o)||await this.sendUpdate(t==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}})}}async sendAvailableCommands(){let e=[];try{let{CommandHandler:r}=await KMt().then(()=>qMt);e=await new r().getAvailableCommands(this.config)}catch{e=[{name:"help",description:"List available commands"},{name:"about",description:"Show version / environment info"},{name:"memory show",description:"Show current memory"},{name:"init",description:"Generate a DEEPV.md for this project"}]}await this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:e.map(r=>({name:r.name,description:r.description}))})}async prompt(e){let r=e.prompt.filter(d=>d.type==="text").map(d=>d.text).join("").trim(),a;if(r.startsWith("/")||r.startsWith("$")){let d=zks.test(r);d&&await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Aje}start`}});try{let{CommandHandler:h}=await KMt().then(()=>qMt),I=await new h().handleCommand(r,{config:this.config,settings:this._settings,sendMessage:async c=>{await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}})}});if(I.submitPrompt)a=I.submitPrompt;else if(I.handled)return{stopReason:"end_turn"}}catch{}finally{d&&await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Aje}done`}})}}this.pendingAbort?.abort();let i=new AbortController;this.pendingAbort=i,!this.titleGenerated&&r.length>0&&this.countRealUserMessages()===0&&(this.titleGenerated=!0,this.generateTitle(r));let o=Math.random().toString(16).slice(2),t=a?[{text:a}]:await this.resolvePrompt(e,i.signal);this.config.getPlanModeActive()&&t.unshift({text:rLt});let s={role:en.USER,parts:t};this.turnCheckpointCreated=!1,this.turnUserQuery=r;try{for(;s!==null;){if(i.signal.aborted)return{stopReason:"cancelled"};let d=[],h=[];try{let u=await this.config.getToolRegistry(),I=await this.chat.sendMessageStream({message:s.parts??[],config:{abortSignal:i.signal,tools:[{functionDeclarations:u.getFunctionDeclarations()}]}},o,ia.CHAT_CONVERSATION);s=null;for await(let c of I){if(i.signal.aborted)return{stopReason:"cancelled"};h.push(c);let m=c.candidates?.[0];for(let p of m?.content?.parts??[]){let b=p.reasoning;if(typeof b=="string"&&b.length>0){await this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:b}});continue}p.text&&await this.sendUpdate(p.thought?{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.text}}:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}})}c.functionCalls&&d.push(...c.functionCalls)}}catch(u){if(Zz(u)===429)throw new wa(429,"Rate limit exceeded. Try again later.");if(jDe(u)){let I;try{I=gs.getInstance().getUserInfo()?.email??void 0}catch{I=void 0}let c=QGe(u,{email:I,locale:"zh"})??pn(u);throw new wa(402,c)}throw u}if(await this.emitUsageUpdate(h),await this.maybeAutoCompress(h,o,i.signal),await this.maybePersistIncrementally(),d.length>0){let u=qks(d);await this.maybeCreateTurnCheckpoint(u);let I=[];for(let b of u)I.push(await this.prepareToolRun(i.signal,o,b));let c=await Promise.all(I.map(b=>b())),m=[];for(let b of c){let y=Array.isArray(b)?b:[b];for(let v of y)typeof v=="string"?m.push({text:v}):v&&m.push(v)}let p=this.drainInjectedText();p&&m.push({text:p}),s={role:en.USER,parts:m}}else if(this.pendingInjectedText.length>0){let u=this.drainInjectedText();u&&(s={role:en.USER,parts:[{text:u}]})}}return{stopReason:"end_turn"}}finally{this.pendingAbort===i&&(this.pendingAbort=void 0),await this.persistHistory()}}async sendUpdate(e){try{await this.connection.sessionUpdate({sessionId:this.id,update:e})}catch(r){this.debug(`sessionUpdate failed: ${Bb(r)}`)}}async emitUsageUpdate(e){if(e.length!==0)try{let r=this.chat.getFinalUsageMetadata?.(e),a=gPn(r,this.config);a&&await this.sendUpdate(a)}catch(r){this.debug(`emitUsageUpdate skipped: ${Bb(r)}`)}}static AUTO_COMPRESS_THRESHOLD=.8;async maybeAutoCompress(e,r,a){try{if(e.length===0)return;let i=this.chat.getFinalUsageMetadata?.(e),o=i?.totalTokenCount??(i?.promptTokenCount??0)+(i?.candidatesTokenCount??0);if(!o)return;let t=this.config.getModel?.()??"auto",s=Ah(t,this.config);if(!s)return;let d=n.AUTO_COMPRESS_THRESHOLD*s;if(o<d)return;this.debug(`[auto-compress] used=${o} limit=${s} threshold=${d} \u2014 compressing`),await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Aje}start`}});try{await this.config.getGeminiClient().tryCompressChat(r,a,!0)}finally{await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Aje}done`}})}}catch(i){this.debug(`[auto-compress] skipped: ${Bb(i)}`)}}async prepareToolRun(e,r,a){let i=a.id??`${a.name??"unknown"}-${Date.now()}`,o=a.args??{},t=Date.now(),s=A=>(lv(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),prompt_id:r,function_name:a.name??"",function_args:o,duration_ms:Date.now()-t,success:!1,error:A.message,response_length:A.message.length}),[{functionResponse:{id:i,name:a.name??"",response:{error:A.message}}}]),d=A=>{let w=s(A);return()=>Promise.resolve(w)};if(!a.name)return d(new Error("Missing function name"));let u=(await this.config.getToolRegistry()).getTool(a.name);if(!u)return d(new Error(`Tool "${a.name}" not found in registry.`));let I=i,c=u.kind,m=c?EPn(c):FPn(u.icon);if(this.config.getPlanModeActive()&&!s1e(a.name))return await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:I,title:`${u.getDescription?.(o)??a.name} \u2014 blocked by plan mode`,kind:m,status:"failed",rawInput:o}),d(new Error(DEn(a.name)));a.name==="use_skill"&&gv.notePendingActivation(r);let p=gv.checkToolCall(a.name,r);if(p)return await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:I,title:`${u.getDescription?.(o)??a.name} \u2014 blocked by skill allowedTools`,kind:m,status:"failed",rawInput:o}),d(p);await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:I,title:u.getDescription?.(o)??a.name,kind:m,status:"pending",rawInput:o,locations:u.toolLocations?.(o)??void 0});let b=await u.shouldConfirmExecute(o,e);if(b)if(this.config.getApprovalMode()===An.YOLO?wPn(b):!0){let w=ZPn(b,this.config),E=WPn(b);try{let f=await this.connection.requestPermission({sessionId:this.id,toolCall:{toolCallId:I,title:u.getDescription?.(o)??a.name,kind:m,...E?{_meta:E}:{}},options:w}),Z=vPn.parse(f);if(Z.outcome.outcome==="cancelled")return await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"failed"}),d(new Error(`Tool "${a.name}" was canceled by the user.`));let W=Z.outcome.optionId;if(W===Wn.Cancel)return await b.onConfirm(W),await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"failed"}),d(new Error(`Tool "${a.name}" not allowed to run by the user.`));let R=yPn(Z);await b.onConfirm(W,R)}catch(f){await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"failed"});let Z=f instanceof Error?f.message:String(f);return d(new Error(`Tool "${a.name}" requires approval but the ACP client cannot present one (${Z}). Refusing to run.`))}}else try{await b.onConfirm(Wn.ProceedOnce)}catch{}if(a.name===t_.Name)return async()=>{await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"in_progress"});let A=async Z=>(await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"failed",content:[{type:"content",content:{type:"text",text:Z}}]}),s(new Error(Z))),w=u.validateToolParams(o);if(w)return A(w);let E=this.connection.extMethod;if(typeof E!="function")return A(`The connected host does not support spawning parallel worktree sessions (missing ${nOe}). No session was spawned.`);let f=typeof o.name=="string"&&o.name.length>0?o.name:void 0;try{let W=await E.call(this.connection,nOe,{sessionId:this.id,prompt:String(o.task??""),baseRef:o.base==="head"?"head":"fresh",...f?{name:f,title:f}:{}});if(!W||W.ok!==!0)return A(`Failed to spawn parallel worktree session: ${W?.error??"unknown host error"}`);let R=`\u5DF2\u5728\u5206\u652F ${W.branch??"(unknown)"} \u7684\u9694\u79BB worktree${W.worktreePath?`\uFF08${W.worktreePath}\uFF09`:""} \u542F\u52A8\u5E76\u884C\u4F1A\u8BDD\u3002\u8BE5\u4EFB\u52A1\u5C06\u72EC\u7ACB\u6267\u884C\uFF0C\u7ED3\u679C\u7531\u7528\u6237\u5728\u5B50\u4F1A\u8BDD\u4E2D\u5BA1\u67E5\u5408\u5E76\uFF1B\u672C\u4F1A\u8BDD\u53EF\u7EE7\u7EED\u5904\u7406\u5176\u5B83\u5DE5\u4F5C\u3002`;return await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"completed",content:[{type:"content",content:{type:"text",text:R}}]}),lv(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),prompt_id:r,function_name:a.name,function_args:o,duration_ms:Date.now()-t,success:!0,response_length:R.length}),[{functionResponse:{id:i,name:a.name,response:{ok:!0,sessionId:W.sessionId,branch:W.branch,worktreePath:W.worktreePath,message:R}}}]}catch(Z){return A(`Failed to spawn parallel worktree session: ${Bb(Z)}`)}};let y=async()=>{await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"in_progress"});try{let A=await u.execute(o,e),w=NPn(A);return await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"completed",content:w?[w]:void 0}),lv(this.config,{"event.name":"tool_call","event.timestamp":new Date().toISOString(),prompt_id:r,function_name:a.name,function_args:o,duration_ms:Date.now()-t,success:!0,response_length:typeof A.llmContent=="string"?A.llmContent.length:JSON.stringify(A.llmContent??"").length}),$B(a.name,i,A.llmContent)}catch(A){let w=A instanceof Error?A:new Error(String(A));return await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:I,status:"failed",content:[{type:"content",content:{type:"text",text:w.message}}]}),s(w)}},v=[];try{v=(u.toolLocations?.(o)??[]).map(A=>A.path).filter(A=>!!A)}catch{}return()=>this.fileOperationQueue.enqueueMultiple(v,y)}async resolvePrompt(e,r){let a=e.prompt,i=a.filter(w=>w.type==="resource_link"||w.path!==void 0);if(i.length===0)return a.flatMap(w=>{let E=w.type;if(E==="text"||w.text!==void 0)return[{text:w.text}];if(E==="image"){let f=w;if(f.mimeType&&f.data)return[{inlineData:{mimeType:f.mimeType,data:f.data}}]}return[]});let o=this.config.getFileService(),t=this.config.getFileFilteringRespectGitIgnore(),s=[],d=new Map,h=[],u=[],I=await this.config.getToolRegistry(),c=I.getTool("read_many_files"),m=I.getTool("glob");if(!c)throw new Error("read_many_files tool not found.");let p=w=>{let E=w;if(typeof E.path=="string")return E.path;if(typeof E.uri=="string")return E.uri.replace(/^file:\/\//,"")};for(let w of i){let E=p(w);if(!E)continue;if(o.shouldGitIgnoreFile(E)){u.push(E);continue}let f=E,Z=!1;try{let W=xje.resolve(this.config.getTargetDir(),E);Fu(W,this.config.getTargetDir())&&((await _Pn.stat(W)).isDirectory()&&(f=E.endsWith("/")?`${E}**`:`${E}/**`),Z=!0)}catch(W){if(Mc(W)&&W.code==="ENOENT"&&this.config.getEnableRecursiveFileSearch()&&m)try{let R=await m.execute({pattern:`**/*${E}*`,path:this.config.getTargetDir()},r);if(typeof R.llmContent=="string"&&!R.llmContent.startsWith("No files found")&&!R.llmContent.startsWith("Error:")){let g=R.llmContent.split(`
9112
9112
  `);g.length>1&&g[1]&&(f=xje.relative(this.config.getTargetDir(),g[1].trim()),Z=!0)}}catch{}}Z&&(s.push(f),d.set(E,f),h.push(E))}let b="";for(let w=0;w<a.length;w++){let E=a[w];if(E.text!==void 0){b+=E.text;continue}let f=p(E);if(!f)continue;let Z=d.get(f);w>0&&b.length>0&&!b.endsWith(" ")&&(b+=" "),b+=`@${Z??f}`}b=b.trim(),u.length>0&&this.debug(`Ignored ${u.length} path(s) (${t?"git-ignored":"custom-ignored"}): ${u.join(", ")}`);let y=a.flatMap(w=>{if(w.type!=="image")return[];let E=w;return E.mimeType&&E.data?[{inlineData:{mimeType:E.mimeType,data:E.data}}]:[]});if(s.length===0)return[{text:b},...y];let v=[{text:b},...y],A={paths:s,respectGitIgnore:t};try{let w=await c.execute(A,r);if(Array.isArray(w.llmContent)){let E=/^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;v.push({text:`
9113
9113
  ${F6t}`});for(let f of w.llmContent)if(typeof f=="string"){let Z=E.exec(f);Z?(v.push({text:`
@@ -9116,7 +9116,7 @@ Content from @${Z[1]}:
9116
9116
  ${E6t}`})}}catch(w){this.debug(`Error reading referenced files (${h.join(", ")}): ${pn(w)}`)}return v}countRealUserMessages(){let e=0;for(let r of this.chat.getHistory(!1)){if(r.role!==en.USER)continue;let a=r.parts??[];if(a.some(o=>o.functionResponse))continue;let i=a.map(o=>typeof o.text=="string"?o.text:"").join("");nNe(en.USER,i)||(e+=1)}return e}async generateTitle(e){let r=new AbortController,a=setTimeout(()=>r.abort(),2e4);try{let i=this.config.getGeminiClient?.();if(!i?.createTemporaryChat)return;let o=await i.createTemporaryChat(ia.CONTENT_SUMMARY,wh.getModelForScene(ia.CONTENT_SUMMARY),{type:"sub",agentId:"TitleGen"},{disableSystemPrompt:!0}),t=`Generate a concise title (at most 6 words) summarizing the following user request, so it can label a chat session in a sidebar. Reply with ONLY the title text \u2014 no quotes, no punctuation at the end, and in the same language as the request.
9117
9117
 
9118
9118
  User request:
9119
- `+e.slice(0,2e3),s=await o.sendMessage({message:t,config:{maxOutputTokens:40,abortSignal:r.signal}},`title-${Date.now()}`,ia.CONTENT_SUMMARY),d=Kks(Pks(s));if(!d)return;await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Uks} ${d}`}})}catch(i){this.debug(`generateTitle failed: ${Bb(i)}`)}finally{clearTimeout(a)}}debug(e){this.config.getDebugMode()&&console.error(`[acp:${this.id}] ${e}`)}_authTypeRef=ss};Mr();import $ks from"node:os";import e9s from"node:path";var Cje=class{constructor(e,r,a,i,o){this.connection=e;this.sessionId=r;this.capabilities=a;this.fallback=i;this.root=o}globalDir=e9s.join($ks.homedir(),".dvcode");shouldUseFallback(e){return!Fu(e,this.root)||Fu(e,this.globalDir)}normalizeFileSystemError(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Resource not found")||r.includes("ENOENT")||r.includes("does not exist")||r.includes("No such file")){let a=new Error(r);throw a.code="ENOENT",a}throw e}async readTextFile(e){if(!this.capabilities.readTextFile||this.shouldUseFallback(e))return this.fallback.readTextFile(e);try{return(await this.connection.readTextFile({path:e,sessionId:this.sessionId})).content}catch(r){this.normalizeFileSystemError(r)}}async writeTextFile(e,r){if(!this.capabilities.writeTextFile||this.shouldUseFallback(e))return this.fallback.writeTextFile(e,r);try{await this.connection.writeTextFile({path:e,content:r,sessionId:this.sessionId})}catch(a){this.normalizeFileSystemError(a)}}};var Yje=class{constructor(e,r,a,i){this.config=e;this.settings=r;this.argv=a;this.connection=i;this.policyUnsubscribe=o6t(this.policyEngine,this.messageBus);let o={run:async()=>({status:"failed",error:"ACP mode does not execute cron jobs"})},t=new JS({executor:o});Wx(t,{isOwner:!1})}sessions=new Map;clientCapabilities;policyEngine=new AGe;messageBus=new CGe;policyUnsubscribe;setClientCapabilities(e){this.clientCapabilities=e}getSession(e){return this.sessions.get(e)}dispose(){for(let e of this.sessions.values())e.dispose();this.sessions.clear(),this.policyUnsubscribe?.(),this.messageBus.dispose(),Wx(null)}async newSession(e,r){let a=t9s(),i=e.cwd??process.cwd();await this.authenticate(r),this.installFileSystemServiceIfSupported(a,i);let t=this.config.getGeminiClient().getChat(),s=new aNe(a,t,this.config,this.connection,this.settings,i);this.sessions.set(a,s),setTimeout(()=>{s.sendAvailableCommands()},0);let{availableModels:d,currentModelId:h}=DMt(this.config,this.settings);return{sessionId:a,modes:{availableModes:OMt(),currentModeId:this.config.getApprovalMode()},models:{availableModels:d,currentModelId:h},configOptions:rNe(this.config,s.getAllConfigValues()),_meta:{agentSessionId:a,backendSessionId:a}}}async loadSession(e,r){let a=e.cwd??process.cwd();await this.authenticate(r),this.installFileSystemServiceIfSupported(e.sessionId,a);let i=new TGe(new Di(a)),{data:o}=await i.resolveSession(e.sessionId),t=V6t(o.clientHistory??o.history??[]),s=this.config.getGeminiClient();await s.resumeChat(t);let d=s.getChat(),h=new aNe(e.sessionId,d,this.config,this.connection,this.settings,a);h.markTitleGenerated();let u=this.sessions.get(e.sessionId);u&&u.dispose(),this.sessions.set(e.sessionId,h),h.streamHistory(o.history??[]),setTimeout(()=>{h.sendAvailableCommands()},0);let{availableModels:I,currentModelId:c}=DMt(this.config,this.settings);return{modes:{availableModes:OMt(),currentModeId:this.config.getApprovalMode()},models:{availableModels:I,currentModelId:c},configOptions:rNe(this.config,h.getAllConfigValues()),_meta:{agentSessionId:e.sessionId,backendSessionId:e.sessionId}}}async authenticate(e){try{await this.config.refreshAuth(ss.USE_PROXY_AUTH,{apiKey:e.apiKey,baseUrl:e.baseUrl,customHeaders:e.customHeaders})}catch(i){throw new wa(-32e3,Bb(i)||"Authentication required.")}let r=APn(this.config,this.settings);(this.config.getCloudModels?.()?.length??0)>0||await r}installFileSystemServiceIfSupported(e,r){if(!this.clientCapabilities?.fs)return;let a=new Cje(this.connection,e,this.clientCapabilities.fs,this.config.getFileSystemService(),r);this.config.setFileSystemService(a)}};Mr();async function MPn(n){try{await zD(n.getWorkingDir())}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}let e=n.getGeminiClient();return e?.isInitialized()&&await e.updateSystemPromptWithMcpPrompts(),{ok:!0}}var Vje=class{constructor(e,r,a,i){this.config=e;this.settings=r;this.sessionManager=new Yje(e,r,a,i)}apiKey;baseUrl;customHeaders;sessionManager;dispose(){this.sessionManager.dispose()}async initialize(e){e.clientCapabilities&&this.sessionManager.setClientCapabilities(e.clientCapabilities);let r=await yx().catch(()=>"unknown");return{protocolVersion:_ne,authMethods:[{id:ss.USE_PROXY_AUTH,name:"DeepV proxy auth",description:"Use Easy Code proxy authentication",_meta:{"api-key":{provider:"deepv"},gateway:{protocol:"deepv",restartRequired:"false"}}}],agentInfo:{name:"dvcode",title:"Easy Code",version:r},agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(e){let r=GPn(e)?e._meta:void 0,a=typeof r?.["api-key"]=="string"?r["api-key"]:void 0;a&&(this.apiKey=a);let i=On.object({baseUrl:On.string().optional(),headers:On.record(On.string()).optional()});if(r?.gateway){let o=i.safeParse(r.gateway);if(!o.success)throw new wa(-32602,`Malformed gateway payload: ${o.error.message}`);this.baseUrl=o.data.baseUrl,this.customHeaders=o.data.headers}try{await this.config.refreshAuth(ss.USE_PROXY_AUTH,{apiKey:this.apiKey,baseUrl:this.baseUrl,customHeaders:this.customHeaders})}catch(o){throw new wa(-32e3,Bb(o))}this.settings.setValue("User","selectedAuthType",ss.USE_PROXY_AUTH)}getAuthDetails(){return{apiKey:this.apiKey,baseUrl:this.baseUrl,customHeaders:this.customHeaders}}async newSession(e){return this.sessionManager.newSession(e,this.getAuthDetails())}async loadSession(e){return this.sessionManager.loadSession(e,this.getAuthDetails())}async cancel(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);await r.cancelPendingPrompt()}async prompt(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);return r.prompt(e)}async setSessionMode(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);return r.setMode(e.modeId),{}}async setSessionConfigOption(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);let a=e.value,i=e.configId;if(typeof a!="string"&&typeof a!="boolean")throw new wa(-32602,`Unsupported value shape for config option "${i}"`);try{let o=await r.applyConfigOption(i,a);if(o.error)throw new wa(-32603,`Failed to apply config option "${i}": ${o.error}`)}catch(o){throw o instanceof wa?o:new wa(-32603,Bb(o))}return{configOptions:rNe(this.config,r.getAllConfigValues())}}async unstable_setSessionModel(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);let a=await r.setModel(e.modelId);if(a&&!a.success)throw new wa(-32603,`Failed to switch model to ${e.modelId}: ${a.error??"unknown error"}`);return{}}async extMethod(e,r){switch(e){case"_dvcode/session/rewind":return this.handleRewind(r);case"_dvcode/session/listCheckpoints":return this.handleListCheckpoints(r);case"_dvcode/session/restoreCheckpoint":return this.handleRestoreCheckpoint(r);case"_dvcode/session/fork":return this.handleFork(r);case"_dvcode/session/injectText":return this.handleInjectText(r);case"_dvcode/goal/start":return this.handleGoalStart(r);case"_dvcode/session/status":return this.handleSessionStatus(r);case"_dvcode/plan/set":return this.handlePlanSet(r);case"_dvcode/goal/clear":return this.handleGoalClear(r);case"_dvcode/btw/ask":return this.handleBtwAsk(r);case"_dvcode/tasks/list":return this.handleTasksList(r);case"_dvcode/tasks/stop":return this.handleTasksStop(r);case"_dvcode/tasks/output":return this.handleTasksOutput(r);case"_dvcode/tasks/clear":return this.handleTasksClear(r);case"_dvcode/skills/reload":return this.handleSkillsReload(r);case"_dvcode/auth/reload":return this.handleAuthReload(r);default:throw new wa(-32601,`Method not found: ${e}`)}}async handleTasksList(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/list: ${a.error.message}`);return IPn()}async handleTasksStop(e){let a=On.object({sessionId:On.string().optional(),taskId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/stop: ${a.error.message}`);return mPn(a.data.taskId)}async handleTasksOutput(e){let a=On.object({sessionId:On.string().optional(),taskId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/output: ${a.error.message}`);return fPn(a.data.taskId)}async handleTasksClear(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/clear: ${a.error.message}`);return pPn()}async handleSkillsReload(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/skills/reload: ${a.error.message}`);return MPn(this.config)}async handleAuthReload(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/auth/reload: ${a.error.message}`);try{let i=gs.getInstance();return i.reloadFromDisk(),i.isConfigured()||xPn(this.config,this.settings),{ok:!0}}catch(i){return{ok:!1,error:Bb(i)}}}async handleBtwAsk(e){let a=On.object({sessionId:On.string(),question:On.string().trim().min(1)}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/btw/ask: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.askSideQuestion(a.data.question)}async handlePlanSet(e){let a=On.object({sessionId:On.string(),active:On.boolean()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/plan/set: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.setPlanMode(a.data.active)}async handleGoalClear(e){let a=On.object({sessionId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/goal/clear: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.clearGoalMode()}async handleSessionStatus(e){let a=On.object({sessionId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/status: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.getModeStatus()}async handleGoalStart(e){let a=On.object({sessionId:On.string(),task:On.string().trim().min(1),criteria:On.string().trim().min(1),forbidden:On.string().default(""),hours:On.number().min(.5).max(24),intensity:On.enum(["steady","standard","intense"])}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/goal/start: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let{sessionId:o,...t}=a.data;return i.startGoalMode(t)}async handleInjectText(e){let a=On.object({sessionId:On.string(),text:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/injectText: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.injectMidTurnText(a.data.text),{queued:!0}}async handleFork(e){let a=On.object({sessionId:On.string(),beforeUserMessageIndex:On.number().int().nonnegative()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/fork: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let o=await i.forkAtUserMessage(a.data.beforeUserMessageIndex);return{sessionId:o.newSessionId,keptContentCount:o.keptContentCount,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount}}async handleRewind(e){let a=On.object({sessionId:On.string(),beforeUserMessageIndex:On.number().int().nonnegative()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/rewind: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let o=await i.rewindToBeforeUserMessage(a.data.beforeUserMessageIndex);return{keptContentCount:o.keptContentCount,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount,persisted:o.persisted}}async handleListCheckpoints(e){let r=On.object({sessionId:On.string()}).safeParse(e);if(!r.success)throw new wa(-32602,`Invalid params for _dvcode/session/listCheckpoints: ${r.error.message}`);let a=this.sessionManager.getSession(r.data.sessionId);if(!a)throw new wa(-32602,`Session not found: ${r.data.sessionId}`);return{checkpoints:await a.listCheckpoints()}}async handleRestoreCheckpoint(e){let r=On.object({sessionId:On.string(),checkpointId:On.string()}).safeParse(e);if(!r.success)throw new wa(-32602,`Invalid params for _dvcode/session/restoreCheckpoint: ${r.error.message}`);let a=this.sessionManager.getSession(r.data.sessionId);if(!a)throw new wa(-32602,`Session not found: ${r.data.sessionId}`);return await a.restoreCheckpoint(r.data.checkpointId)}};US();function a9s(){let n=(e,...r)=>{try{let a=r.map(i=>typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})()).join(" ");process.stderr.write(`${e}${a}
9119
+ `+e.slice(0,2e3),s=await o.sendMessage({message:t,config:{maxOutputTokens:40,abortSignal:r.signal}},`title-${Date.now()}`,ia.CONTENT_SUMMARY),d=Kks(Pks(s));if(!d)return;await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${Uks} ${d}`}})}catch(i){this.debug(`generateTitle failed: ${Bb(i)}`)}finally{clearTimeout(a)}}debug(e){this.config.getDebugMode()&&console.error(`[acp:${this.id}] ${e}`)}_authTypeRef=ss};Mr();import $ks from"node:os";import e9s from"node:path";var Cje=class{constructor(e,r,a,i,o){this.connection=e;this.sessionId=r;this.capabilities=a;this.fallback=i;this.root=o}globalDir=e9s.join($ks.homedir(),".dvcode");shouldUseFallback(e){return!Fu(e,this.root)||Fu(e,this.globalDir)}normalizeFileSystemError(e){let r=e instanceof Error?e.message:String(e);if(r.includes("Resource not found")||r.includes("ENOENT")||r.includes("does not exist")||r.includes("No such file")){let a=new Error(r);throw a.code="ENOENT",a}throw e}async readTextFile(e){if(!this.capabilities.readTextFile||this.shouldUseFallback(e))return this.fallback.readTextFile(e);try{return(await this.connection.readTextFile({path:e,sessionId:this.sessionId})).content}catch(r){this.normalizeFileSystemError(r)}}async writeTextFile(e,r){if(!this.capabilities.writeTextFile||this.shouldUseFallback(e))return this.fallback.writeTextFile(e,r);try{await this.connection.writeTextFile({path:e,content:r,sessionId:this.sessionId})}catch(a){this.normalizeFileSystemError(a)}}};var Yje=class{constructor(e,r,a,i){this.config=e;this.settings=r;this.argv=a;this.connection=i;this.policyUnsubscribe=o6t(this.policyEngine,this.messageBus);let o={run:async()=>({status:"failed",error:"ACP mode does not execute cron jobs"})},t=new JS({executor:o});Wx(t,{isOwner:!1})}sessions=new Map;clientCapabilities;policyEngine=new AGe;messageBus=new CGe;policyUnsubscribe;setClientCapabilities(e){this.clientCapabilities=e}getSession(e){return this.sessions.get(e)}dispose(){for(let e of this.sessions.values())e.dispose();this.sessions.clear(),this.policyUnsubscribe?.(),this.messageBus.dispose(),Wx(null)}async newSession(e,r){let a=t9s(),i=e.cwd??process.cwd();await this.authenticate(r),this.installFileSystemServiceIfSupported(a,i);let t=this.config.getGeminiClient().getChat(),s=new aNe(a,t,this.config,this.connection,this.settings,i);this.sessions.set(a,s),s.reconcileStartupModelId(),setTimeout(()=>{s.sendAvailableCommands()},0);let{availableModels:d,currentModelId:h}=DMt(this.config,this.settings);return{sessionId:a,modes:{availableModes:OMt(),currentModeId:this.config.getApprovalMode()},models:{availableModels:d,currentModelId:h},configOptions:rNe(this.config,s.getAllConfigValues()),_meta:{agentSessionId:a,backendSessionId:a}}}async loadSession(e,r){let a=e.cwd??process.cwd();await this.authenticate(r),this.installFileSystemServiceIfSupported(e.sessionId,a);let i=new TGe(new Di(a)),{data:o}=await i.resolveSession(e.sessionId),t=V6t(o.clientHistory??o.history??[]),s=this.config.getGeminiClient();await s.resumeChat(t);let d=s.getChat(),h=new aNe(e.sessionId,d,this.config,this.connection,this.settings,a);h.markTitleGenerated();let u=this.sessions.get(e.sessionId);u&&u.dispose(),this.sessions.set(e.sessionId,h),h.reconcileStartupModelId(),h.streamHistory(o.history??[]),setTimeout(()=>{h.sendAvailableCommands()},0);let{availableModels:I,currentModelId:c}=DMt(this.config,this.settings);return{modes:{availableModes:OMt(),currentModeId:this.config.getApprovalMode()},models:{availableModels:I,currentModelId:c},configOptions:rNe(this.config,h.getAllConfigValues()),_meta:{agentSessionId:e.sessionId,backendSessionId:e.sessionId}}}async authenticate(e){try{await this.config.refreshAuth(ss.USE_PROXY_AUTH,{apiKey:e.apiKey,baseUrl:e.baseUrl,customHeaders:e.customHeaders})}catch(i){throw new wa(-32e3,Bb(i)||"Authentication required.")}let r=APn(this.config,this.settings);(this.config.getCloudModels?.()?.length??0)>0||await r}installFileSystemServiceIfSupported(e,r){if(!this.clientCapabilities?.fs)return;let a=new Cje(this.connection,e,this.clientCapabilities.fs,this.config.getFileSystemService(),r);this.config.setFileSystemService(a)}};Mr();async function MPn(n){try{await zD(n.getWorkingDir())}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}let e=n.getGeminiClient();return e?.isInitialized()&&await e.updateSystemPromptWithMcpPrompts(),{ok:!0}}var Vje=class{constructor(e,r,a,i){this.config=e;this.settings=r;this.sessionManager=new Yje(e,r,a,i)}apiKey;baseUrl;customHeaders;sessionManager;dispose(){this.sessionManager.dispose()}async initialize(e){e.clientCapabilities&&this.sessionManager.setClientCapabilities(e.clientCapabilities);let r=await yx().catch(()=>"unknown");return{protocolVersion:_ne,authMethods:[{id:ss.USE_PROXY_AUTH,name:"DeepV proxy auth",description:"Use Easy Code proxy authentication",_meta:{"api-key":{provider:"deepv"},gateway:{protocol:"deepv",restartRequired:"false"}}}],agentInfo:{name:"dvcode",title:"Easy Code",version:r},agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(e){let r=GPn(e)?e._meta:void 0,a=typeof r?.["api-key"]=="string"?r["api-key"]:void 0;a&&(this.apiKey=a);let i=On.object({baseUrl:On.string().optional(),headers:On.record(On.string()).optional()});if(r?.gateway){let o=i.safeParse(r.gateway);if(!o.success)throw new wa(-32602,`Malformed gateway payload: ${o.error.message}`);this.baseUrl=o.data.baseUrl,this.customHeaders=o.data.headers}try{await this.config.refreshAuth(ss.USE_PROXY_AUTH,{apiKey:this.apiKey,baseUrl:this.baseUrl,customHeaders:this.customHeaders})}catch(o){throw new wa(-32e3,Bb(o))}this.settings.setValue("User","selectedAuthType",ss.USE_PROXY_AUTH)}getAuthDetails(){return{apiKey:this.apiKey,baseUrl:this.baseUrl,customHeaders:this.customHeaders}}async newSession(e){return this.sessionManager.newSession(e,this.getAuthDetails())}async loadSession(e){return this.sessionManager.loadSession(e,this.getAuthDetails())}async cancel(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);await r.cancelPendingPrompt()}async prompt(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);return r.prompt(e)}async setSessionMode(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);return r.setMode(e.modeId),{}}async setSessionConfigOption(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);let a=e.value,i=e.configId;if(typeof a!="string"&&typeof a!="boolean")throw new wa(-32602,`Unsupported value shape for config option "${i}"`);try{let o=await r.applyConfigOption(i,a);if(o.error)throw new wa(-32603,`Failed to apply config option "${i}": ${o.error}`)}catch(o){throw o instanceof wa?o:new wa(-32603,Bb(o))}return{configOptions:rNe(this.config,r.getAllConfigValues())}}async unstable_setSessionModel(e){let r=this.sessionManager.getSession(e.sessionId);if(!r)throw new wa(-32602,`Session not found: ${e.sessionId}`);let a=await r.setModel(e.modelId);if(a&&!a.success)throw new wa(-32603,`Failed to switch model to ${e.modelId}: ${a.error??"unknown error"}`);return{_meta:{dvcode:{currentModelId:this.config.getModel()}}}}async extMethod(e,r){switch(e){case"_dvcode/session/rewind":return this.handleRewind(r);case"_dvcode/session/listCheckpoints":return this.handleListCheckpoints(r);case"_dvcode/session/restoreCheckpoint":return this.handleRestoreCheckpoint(r);case"_dvcode/session/fork":return this.handleFork(r);case"_dvcode/session/injectText":return this.handleInjectText(r);case"_dvcode/goal/start":return this.handleGoalStart(r);case"_dvcode/session/status":return this.handleSessionStatus(r);case"_dvcode/plan/set":return this.handlePlanSet(r);case"_dvcode/goal/clear":return this.handleGoalClear(r);case"_dvcode/btw/ask":return this.handleBtwAsk(r);case"_dvcode/tasks/list":return this.handleTasksList(r);case"_dvcode/tasks/stop":return this.handleTasksStop(r);case"_dvcode/tasks/output":return this.handleTasksOutput(r);case"_dvcode/tasks/clear":return this.handleTasksClear(r);case"_dvcode/skills/reload":return this.handleSkillsReload(r);case"_dvcode/auth/reload":return this.handleAuthReload(r);default:throw new wa(-32601,`Method not found: ${e}`)}}async handleTasksList(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/list: ${a.error.message}`);return IPn()}async handleTasksStop(e){let a=On.object({sessionId:On.string().optional(),taskId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/stop: ${a.error.message}`);return mPn(a.data.taskId)}async handleTasksOutput(e){let a=On.object({sessionId:On.string().optional(),taskId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/output: ${a.error.message}`);return fPn(a.data.taskId)}async handleTasksClear(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/tasks/clear: ${a.error.message}`);return pPn()}async handleSkillsReload(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/skills/reload: ${a.error.message}`);return MPn(this.config)}async handleAuthReload(e){let a=On.object({sessionId:On.string().optional()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/auth/reload: ${a.error.message}`);try{let i=gs.getInstance();return i.reloadFromDisk(),i.isConfigured()||xPn(this.config,this.settings),{ok:!0}}catch(i){return{ok:!1,error:Bb(i)}}}async handleBtwAsk(e){let a=On.object({sessionId:On.string(),question:On.string().trim().min(1)}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/btw/ask: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.askSideQuestion(a.data.question)}async handlePlanSet(e){let a=On.object({sessionId:On.string(),active:On.boolean()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/plan/set: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.setPlanMode(a.data.active)}async handleGoalClear(e){let a=On.object({sessionId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/goal/clear: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.clearGoalMode()}async handleSessionStatus(e){let a=On.object({sessionId:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/status: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.getModeStatus()}async handleGoalStart(e){let a=On.object({sessionId:On.string(),task:On.string().trim().min(1),criteria:On.string().trim().min(1),forbidden:On.string().default(""),hours:On.number().min(.5).max(24),intensity:On.enum(["steady","standard","intense"])}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/goal/start: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let{sessionId:o,...t}=a.data;return i.startGoalMode(t)}async handleInjectText(e){let a=On.object({sessionId:On.string(),text:On.string()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/injectText: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);return i.injectMidTurnText(a.data.text),{queued:!0}}async handleFork(e){let a=On.object({sessionId:On.string(),beforeUserMessageIndex:On.number().int().nonnegative()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/fork: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let o=await i.forkAtUserMessage(a.data.beforeUserMessageIndex);return{sessionId:o.newSessionId,keptContentCount:o.keptContentCount,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount}}async handleRewind(e){let a=On.object({sessionId:On.string(),beforeUserMessageIndex:On.number().int().nonnegative()}).safeParse(e);if(!a.success)throw new wa(-32602,`Invalid params for _dvcode/session/rewind: ${a.error.message}`);let i=this.sessionManager.getSession(a.data.sessionId);if(!i)throw new wa(-32602,`Session not found: ${a.data.sessionId}`);let o=await i.rewindToBeforeUserMessage(a.data.beforeUserMessageIndex);return{keptContentCount:o.keptContentCount,keptUserMessageCount:o.keptUserMessageCount,droppedContentCount:o.droppedContentCount,persisted:o.persisted}}async handleListCheckpoints(e){let r=On.object({sessionId:On.string()}).safeParse(e);if(!r.success)throw new wa(-32602,`Invalid params for _dvcode/session/listCheckpoints: ${r.error.message}`);let a=this.sessionManager.getSession(r.data.sessionId);if(!a)throw new wa(-32602,`Session not found: ${r.data.sessionId}`);return{checkpoints:await a.listCheckpoints()}}async handleRestoreCheckpoint(e){let r=On.object({sessionId:On.string(),checkpointId:On.string()}).safeParse(e);if(!r.success)throw new wa(-32602,`Invalid params for _dvcode/session/restoreCheckpoint: ${r.error.message}`);let a=this.sessionManager.getSession(r.data.sessionId);if(!a)throw new wa(-32602,`Session not found: ${r.data.sessionId}`);return await a.restoreCheckpoint(r.data.checkpointId)}};US();function a9s(){let n=(e,...r)=>{try{let a=r.map(i=>typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})()).join(" ");process.stderr.write(`${e}${a}
9120
9120
  `)}catch{}};console.log=(...e)=>n("",...e),console.info=(...e)=>n("",...e),console.warn=(...e)=>n("",...e),console.debug=(...e)=>n("",...e)}function i9s(){let n=setInterval(()=>{},6e4);return{dispose:()=>clearInterval(n)}}async function PPn(n,e,r){a9s();let{stdout:a}=R6t(),i=n9s.toWeb(a),o=r9s.toWeb(process.stdin),t=Une(i,o),s=new BOe(I=>new Vje(n,e,r,I),t),d=zPn.join(UPn.homedir(),".easycode-user","custom-models.json");kje.watchFile(d,{persistent:!1,interval:500},()=>{try{n.setCustomModels(vf())}catch{}});let h=i9s(),u=I=>{process.stderr.write(`[acp] received ${I}, closing connection gracefully
9121
9121
  `);try{process.stdin.pause(),process.stdin.destroy()}catch{}};process.on("SIGTERM",u),process.on("SIGINT",u);try{await s.closed}finally{h.dispose(),kje.unwatchFile(d),process.off("SIGTERM",u),process.off("SIGINT",u),await X_()}}I7e();bTt();var sUt=Yt(wr(),1);async function N9s(n){try{let r=await new Di(n.getProjectRoot()).listSessions();if(r.length===0){console.log("No available sessions found.");return}console.log("Available sessions:"),console.log("---");let a=r.sort((i,o)=>new Date(o.lastActiveAt).getTime()-new Date(i.lastActiveAt).getTime());for(let i of a){let o=new Date(i.createdAt).toLocaleString(),t=new Date(i.lastActiveAt).toLocaleString(),s=i.hasCheckpoint?" [CP]":"";console.log(`Session ID: ${i.sessionId}${s}`),console.log(` Title: ${i.title||"Untitled"}`),console.log(` Created: ${o}`),console.log(` Last Active: ${t}`),console.log(` Messages: ${i.messageCount}`),console.log(` Tokens: ${i.totalTokens}`),i.model&&console.log(` Model: ${i.model}`),i.firstUserMessage&&console.log(` First Message: ${i.firstUserMessage}${i.firstUserMessage.length>=100?"...":""}`),i.lastAssistantMessage&&console.log(` Last Response: ${i.lastAssistantMessage}${i.lastAssistantMessage.length>=100?"...":""}`),console.log("---")}console.log(`
9122
9122
  Total: ${r.length} sessions`),console.log(`
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "easycode-cli",
3
- "version": "1.1.57",
3
+ "version": "1.1.59",
4
4
  "type": "module"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easycode-ai",
3
- "version": "1.1.59",
3
+ "version": "1.1.60",
4
4
  "engines": {
5
5
  "node": ">=20.0.0"
6
6
  },