@sourcegraph/amp 0.0.1765404020-g2e5656 → 0.0.1765411294-g5611a8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -149,7 +149,7 @@ If you need to replace the entire contents of a file, use \`${j5}\` instead, sin
149
149
  ${H}`)}let W=`${J}.${process.pid}.${Date.now()}.tmp`;try{await hF4(Yo.dirname(J),{recursive:!0});let H=vF4(W),z=uF4.fromWeb(q.body);await pF4(z,H);let U=await lF4(W);if(U!==K)throw Error(`ripgrep checksum validation failed: expected ${K}, got ${U}`);if(process.platform!=="win32")await fF4(W,493);try{await mF4(W,J)}catch(D){if(D instanceof Error&&"code"in D&&D.code==="EEXIST")return;throw D}}finally{await gF4(W).catch(()=>{})}}async function lF4(J){let Q=xF4("sha256"),Z=await bF4(J);return Q.update(Z),Q.digest("hex")}function iF4(){let J=process.env.npm_config_arch||_U1.arch();switch(_U1.platform()){case"darwin":return J==="arm64"?"aarch64-apple-darwin":"x86_64-apple-darwin";case"win32":return J==="x64"?"x86_64-pc-windows-msvc":J==="arm64"?"aarch64-pc-windows-msvc":"i686-pc-windows-msvc";case"linux":return J==="x64"?"x86_64-unknown-linux-musl":J==="arm"?"arm-unknown-linux-gnueabihf":J==="armv7l"?"arm-unknown-linux-gnueabihf":J==="arm64"?"aarch64-unknown-linux-musl":J==="ppc64"?"powerpc64le-unknown-linux-gnu":J==="riscv64"?"riscv64gc-unknown-linux-gnu":J==="s390x"?"s390x-unknown-linux-gnu":"i686-unknown-linux-musl";default:throw Error("Unknown platform: "+_U1.platform())}}async function nF4(){if(Vx!==void 0)return Vx;try{return Vx=(await ME0.promisify(yF4)(`${Kx} --version`)).stdout.includes("ripgrep"),Vx}catch{return Vx=!1,!1}}var Kx,AE0,Vx;var qx=B1(()=>{PW();U0();Kx=process.platform==="win32"?"rg.exe":"rg";AE0=DE0(async(J)=>{if(LE0(J))return J;let Q=3;for(let Z=1;Z<=Q;Z++)try{return await cF4(J),x.info("ripgrep binary downloaded successfully",{path:J}),J}catch(Y){let X=Y instanceof Error?Y.message:String(Y);if(Z===Q){x.error("ripgrep download failed after all attempts",{error:X});return}x.warn(`ripgrep download attempt ${Z}/${Q} failed: ${X}`),await new Promise((G)=>setTimeout(G,500*Math.pow(2,Z-1)))}return})});var IE0={};Q9(IE0,{ripgrepFiles:()=>Xo,nodeGlobTool:()=>oF4,globFilesWithRipgrep:()=>EE0});import{spawn as aF4}from"node:child_process";function EE0(J,Q,Z,Y){return k8(...J.map((X)=>rF4(X,Q,Z,Y))).pipe(Q6((X)=>{let G=[];for(let q of X)if(q.status==="in-progress")G.push(...q?.progress??[]);else if(q.status==="done")G.push(...q.result);else if(q.status==="error")G.push(...q.progress??[]);else if(q.status==="cancelled")G.push(...q.progress??[]);let V=X.filter((q)=>q.status==="error");if(V.length>0)return{status:"error",progress:G,error:{message:V.map((q)=>q?.error?.message??"").join(`
150
150
  `)}};return{status:X.every((q)=>q.status==="done")?"done":X.some((q)=>q.status==="cancelled")?"cancelled":"in-progress",progress:G,result:G}}))}function rF4(J,Q,Z,Y){return new t1((X)=>{X.next({status:"in-progress",progress:[]}),Xo(J,Q?{pattern:Q,caseInsensitive:!0}:null,Z??{},Y).then(({files:G,remaining:V})=>{if(V>0)G.push(`--- ${V} more files not shown ---`);X.next({status:"done",progress:G,result:G})}).catch((G)=>{let V=G instanceof Error?G.message:String(G);X.next({status:"error",progress:[],error:{message:V}})}).finally(()=>X.complete())})}async function Xo(J,Q,Z,Y){let X=Z.limit??kU1,G=["--files","--color","never","--hidden","--glob","!\\.git/","--glob","!\\.jj/"];if(Z.maxDepth!==void 0)G.push("--max-depth",Z.maxDepth.toString());let V;if(Z.basePath)ha(Z.basePath),V=IZ(Z.basePath)?Z.basePath:n0.joinPath(J,Z.basePath).fsPath;else V=J.fsPath;if(G.push(V),Q?.pattern&&Q.pattern==="*")Q.pattern="**";let K=Q?.pattern?wE0.default(Q.pattern,{nocase:Q.caseInsensitive,dot:!0}):void 0,q=aF4(await dI(),G,{stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",env:{...process.env,NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}});return new Promise((W,H)=>{let z=[],U="",D="",M=Z.offset??0,L=!1,A=()=>{if(L)return;if(!D)return;let E=D.startsWith(V)?D.slice(V.length+1):D;if(K&&!K(E))return;let I=D;if(D="",M>0){M--;return}if(z.push(I),z.length>=kU1)x.warn("Glob limit reached. Returning partial results.",{glob:Q?.pattern,limit:kU1,dir:J}),q.kill(),L=!0,W({files:z,remaining:0,aborted:!0})};q.stdout?.on("data",(E)=>{for(let I of String(E)){if(I==="\r")continue;if(I===`
151
151
  `)A(),D="";else D+=I}}),q?.stderr?.on("data",(E)=>{if(U.length>=yU1)return;let I=String(E);if(U.length+I.length>yU1)U+=I.slice(0,yU1-U.length);else U+=I}),q.on("exit",(E)=>{if(E&&E>=2){H(Error(`ripgrep exited with code ${E}:
152
- ${U}`));return}A();let I=z.slice(0,X);W({files:I,remaining:z.length-I.length})})})}var wE0,oF4=({args:J},{dirs:Q,config:Z})=>{if(Q.length===0)return new t1((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Y={};if(J.limit!==void 0)Y.limit=J.limit;if(J.offset!==void 0)Y.offset=J.offset;return EE0(Q,J.filePattern,Y,Z)},kU1=500000,yU1=1e6;var xU1=B1(()=>{i6();i0();U0();AM();qx();CK();wE0=K6(kW(),1)});function nJ(J){return J instanceof e2||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function PE0(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function TE0(J){return{readFile:J.readFile,readBinaryFile:J.readBinaryFile,stat:J.stat,getMtime:J.getMtime,realpath:J.realpath,readdir:J.readdir,findFiles:J.findFiles,access:J.access,watch:J.watch}}function RE0(J){return{...J,writeFile:()=>Promise.reject(Error("Write operations not implemented")),delete:()=>Promise.reject(Error("Write operations not implemented")),mkdirp:()=>Promise.reject(Error("Write operations not implemented")),rename:()=>Promise.reject(Error("Write operations not implemented")),isExclusiveWriterFor:()=>Promise.resolve(!1)}}function bG(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function cI(J,Q,Z){try{return await J.readFile(Q,Z)}catch(Y){if(Y instanceof e2)return null;throw Y}}async function Wx(J,Q,Z){try{return await J.access(Q,Z),!0}catch(Y){if(nJ(Y))return!1;throw Y}}var e2;var jQ=B1(()=>{e2=class e2 extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});function fU1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function Go(J,Q){let Z;if(typeof J==="object"&&J!==null&&"uri"in J&&typeof J.uri==="string")Z=J.uri;else if(typeof J==="string"||h0.isUri(J))Z=J;else throw Error("Invalid base URI");if(J=m4(Z),J.scheme!=="file")throw Error(`Expected file:// scheme, got ${J.scheme}://`);return Q?n0.joinPath(J,Q):J}function vU1(J,Q){Q=m4(Q);let Z,Y;for(let X of J.trees){if(!X.uri)continue;let G=hJ(X.uri);if(n0.hasPrefix(Q,G)){let V=n0.relativePath(G,Q);if(V===null)continue;if(Y===void 0||V.length<Y.length)Y=V,Z=X}}if(!Z||Y===void 0)return null;return{tree:Z,filePath:Y}}function QU4(J){return Array.isArray(J)}function ZU4(J){let Q;if(J===void 0)Q=void 0;else if(QU4(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??JU4}function _E0(J,Q){for(let Y of J.trees){if(!Y.uri)continue;let X=hJ(Y.uri);if(n0.hasPrefix(Q,X))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let Y of J.trees){if(!Y.uri)continue;let X=hJ(Y.uri);if(n0.hasPrefix(X,Q))Z.push(X)}return{isImplied:Z.length>0,childMountPoints:Z}}function Hx(J){return{trees:ZU4(J)}}function yE0(J,Q){let Z={...J.os,mountedTree:kE0},Y=new Map;function X(K){if(!K.fs||K.fs==="os")return Z;if(!K.uri)throw Error("Tree URI is required");if(!K.repository)throw Error(`Tree with FS type ${K.fs} requires repository field`);let q={uri:K.uri,repository:K.repository,fs:K.fs},W=`${K.fs}:${JSON.stringify(K)}`,H=Y.get(W);if(!H){let z=J[K.fs];if(!z)throw Error(`No file system implementation found for: ${K.fs}`);H={...z(q,Q),mountedTree:q},Y.set(W,H)}return H}function G(K){return K.trees.some((q)=>q.fs&&q.fs!=="os")}function V(K,q){let W=K.trees.map((z)=>({mountPoint:z.uri,fs:X(z)}));function H(z){if(!G(K))return q?{...q(Z),mountedTree:Z.mountedTree}:Z;let U=vU1(K,z)?.tree;if(!U)throw new e2(z);let D=W.find((M)=>n0.equalURIs(M.mountPoint,U.uri))?.fs;if(!D)throw Error(`No file system found for URI: ${z}`);return q?{...q(D),mountedTree:D.mountedTree}:D}return{map(z){if(q)throw Error("Cannot use both prepare and prepare2");return V(K,z)},mapReader(z){if(q)throw Error("Cannot use both prepare and prepare2");let U=V(K,z);return{...TE0(U),mountedFileSystemForURI:U.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:U.mapReader,__isFileSystemWithMountedTrees:U.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:U.__isImmutableBaseFileSystem}},mountedFileSystemForURI(z){return H(z)},readFile:async(z,U)=>H(z).readFile(z,U),readBinaryFile:async(z,U)=>H(z).readBinaryFile(z,U),getMtime:async(z,U)=>H(z).getMtime(z,U),realpath:async(z,U)=>H(z).realpath(z,U),access:async(z,U)=>H(z).access(z,U),findFiles:async(z,U)=>H(z.base).findFiles(z,U),stat:async(z,U)=>{let D=m4(z),{isImplied:M}=_E0(K,D);if(M)return{size:0,isDirectory:!0};return H(z).stat(z,U)},rename:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`rename(${z}) is not supported by this file system`);return D.rename(z,U)},writeFile:async(z,U,D)=>{let M=H(z);if(bG(M))throw Error(`writeFile(${z}) is not supported by this file system`);return M.writeFile(z,U,D)},mkdirp:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`mkdirp(${z}) is not supported by this file system`);return D.mkdirp(z,U)},delete:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`delete(${z}) is not supported by this file system`);return D.delete(z,U)},readdir:async(z,U)=>{z=m4(z);let{isImplied:D,childMountPoints:M}=_E0(K,z);if(D){let A=new Set;for(let E of M){let I=n0.relativePath(z,E);if(I){let P=I.split("/")[0];if(P)A.add(P)}}return Array.from(A).map((E)=>({uri:n0.joinPath(z,E),isDirectory:!0}))}return H(z).readdir(z,U)},watch:(z,U)=>{if(!G(K))return Z.watch(z,U);if(!h0.isUri(z))throw Error("Watch with glob is not yet implemented in the file system router");let D=H(z);if(bG(D))return _X;return D.watch(z,U)},isExclusiveWriterFor:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`isExclusiveWriterFor(${z}) is not supported by this file system`);return D.isExclusiveWriterFor(z,U)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:V,fileSystemForURI:(K,q)=>X(vU1(K,q)?.tree??kE0),osFileSystem:Z}}function rF(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let Y=vU1(Hx(Z.thread),Z.dir)?.tree.fs??"os",X=J[Y];if(X)return j3(X()).pipe(B4((G)=>G(Q,Z)));throw Error(`Unsupported file system: ${Y}`)}}var JU4,kE0;var mG=B1(()=>{i6();i0();jQ();JU4=[];kE0={fs:"os",uri:"file:///"}});function rI(J){let Q=J.length;while(--Q>=0)J[Q]=0}function bU1(J,Q,Z,Y,X){this.static_tree=J,this.extra_bits=Q,this.extra_base=Z,this.elems=Y,this.max_length=X,this.has_stree=J&&J.length}function mU1(J,Q){this.dyn_tree=J,this.max_code=0,this.stat_desc=Q}function SK(J,Q,Z,Y,X){this.good_length=J,this.max_lazy=Q,this.nice_length=Z,this.max_chain=Y,this.func=X}function XB4(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=No,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(oU4*2),this.dyn_dtree=new Uint16Array((2*nU4+1)*2),this.bl_tree=new Uint16Array((2*aU4+1)*2),sF(this.dyn_ltree),sF(this.dyn_dtree),sF(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(rU4+1),this.heap=new Uint16Array(2*JB1+1),sF(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*JB1+1),sF(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function TB4(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function Cx(J){this.options=Do.assign({level:kB4,method:xB4,chunkSize:16384,windowBits:15,memLevel:8,strategy:yB4},J||{});let Q=this.options;if(Q.raw&&Q.windowBits>0)Q.windowBits=-Q.windowBits;else if(Q.gzip&&Q.windowBits>0&&Q.windowBits<16)Q.windowBits+=16;this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new mI0,this.strm.avail_out=0;let Z=Nx.deflateInit2(this.strm,Q.level,Q.method,Q.windowBits,Q.memLevel,Q.strategy);if(Z!==Uo)throw Error(TM[Z]);if(Q.header)Nx.deflateSetHeader(this.strm,Q.header);if(Q.dictionary){let Y;if(typeof Q.dictionary==="string")Y=Ix.string2buf(Q.dictionary);else if(gI0.call(Q.dictionary)==="[object ArrayBuffer]")Y=new Uint8Array(Q.dictionary);else Y=Q.dictionary;if(Z=Nx.deflateSetDictionary(this.strm,Y),Z!==Uo)throw Error(TM[Z]);this._dict_set=!0}}function HB1(J,Q){let Z=new Cx(Q);if(Z.push(J,!0),Z.err)throw Z.msg||TM[Z.err];return Z.result}function vB4(J,Q){return Q=Q||{},Q.raw=!0,HB1(J,Q)}function fB4(J,Q){return Q=Q||{},Q.gzip=!0,HB1(J,Q)}function $N4(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function wN4(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}function jx(J){this.options=Do.assign({chunkSize:65536,windowBits:15,to:""},J||{});let Q=this.options;if(Q.raw&&Q.windowBits>=0&&Q.windowBits<16){if(Q.windowBits=-Q.windowBits,Q.windowBits===0)Q.windowBits=-15}if(Q.windowBits>=0&&Q.windowBits<16&&!(J&&J.windowBits))Q.windowBits+=32;if(Q.windowBits>15&&Q.windowBits<48){if((Q.windowBits&15)===0)Q.windowBits|=15}this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new mI0,this.strm.avail_out=0;let Z=QH.inflateInit2(this.strm,Q.windowBits);if(Z!==Px)throw Error(TM[Z]);if(this.header=new EN4,QH.inflateGetHeader(this.strm,this.header),Q.dictionary){if(typeof Q.dictionary==="string")Q.dictionary=Ix.string2buf(Q.dictionary);else if(tI0.call(Q.dictionary)==="[object ArrayBuffer]")Q.dictionary=new Uint8Array(Q.dictionary);if(Q.raw){if(Z=QH.inflateSetDictionary(this.strm,Q.dictionary),Z!==Px)throw Error(TM[Z])}}}function zB1(J,Q){let Z=new jx(Q);if(Z.push(J),Z.err)throw Z.msg||TM[Z.err];return Z.result}function CN4(J,Q){return Q=Q||{},Q.raw=!0,zB1(J,Q)}var YU4=0,MI0=1,XU4=2,$U4=3,GU4=258,GB1=29,Tx=256,Mx,nI=30,VB1=19,LI0,EM=15,hU1=16,VU4=7,KB1=256,AI0=16,OI0=17,wI0=18,sU1,zo,KU4,EI0,qU4=512,JH,Bx,Lx,Ax,qB1,Fo,II0,PI0,TI0,RI0=(J)=>{return J<256?Lx[J]:Lx[256+(J>>>7)]},Ox=(J,Q)=>{J.pending_buf[J.pending++]=Q&255,J.pending_buf[J.pending++]=Q>>>8&255},TZ=(J,Q,Z)=>{if(J.bi_valid>hU1-Z)J.bi_buf|=Q<<J.bi_valid&65535,Ox(J,J.bi_buf),J.bi_buf=Q>>hU1-J.bi_valid,J.bi_valid+=Z-hU1;else J.bi_buf|=Q<<J.bi_valid&65535,J.bi_valid+=Z},_K=(J,Q,Z)=>{TZ(J,Z[Q*2],Z[Q*2+1])},CI0=(J,Q)=>{let Z=0;do Z|=J&1,J>>>=1,Z<<=1;while(--Q>0);return Z>>>1},WU4=(J)=>{if(J.bi_valid===16)Ox(J,J.bi_buf),J.bi_buf=0,J.bi_valid=0;else if(J.bi_valid>=8)J.pending_buf[J.pending++]=J.bi_buf&255,J.bi_buf>>=8,J.bi_valid-=8},HU4=(J,Q)=>{let{dyn_tree:Z,max_code:Y}=Q,X=Q.stat_desc.static_tree,G=Q.stat_desc.has_stree,V=Q.stat_desc.extra_bits,K=Q.stat_desc.extra_base,q=Q.stat_desc.max_length,W,H,z,U,D,M,L=0;for(U=0;U<=EM;U++)J.bl_count[U]=0;Z[J.heap[J.heap_max]*2+1]=0;for(W=J.heap_max+1;W<LI0;W++){if(H=J.heap[W],U=Z[Z[H*2+1]*2+1]+1,U>q)U=q,L++;if(Z[H*2+1]=U,H>Y)continue;if(J.bl_count[U]++,D=0,H>=K)D=V[H-K];if(M=Z[H*2],J.opt_len+=M*(U+D),G)J.static_len+=M*(X[H*2+1]+D)}if(L===0)return;do{U=q-1;while(J.bl_count[U]===0)U--;J.bl_count[U]--,J.bl_count[U+1]+=2,J.bl_count[q]--,L-=2}while(L>0);for(U=q;U!==0;U--){H=J.bl_count[U];while(H!==0){if(z=J.heap[--W],z>Y)continue;if(Z[z*2+1]!==U)J.opt_len+=(U-Z[z*2+1])*Z[z*2],Z[z*2+1]=U;H--}}},jI0=(J,Q,Z)=>{let Y=Array(EM+1),X=0,G,V;for(G=1;G<=EM;G++)X=X+Z[G-1]<<1,Y[G]=X;for(V=0;V<=Q;V++){let K=J[V*2+1];if(K===0)continue;J[V*2]=CI0(Y[K]++,K)}},zU4=()=>{let J,Q,Z,Y,X,G=Array(EM+1);Z=0;for(Y=0;Y<GB1-1;Y++){qB1[Y]=Z;for(J=0;J<1<<sU1[Y];J++)Ax[Z++]=Y}Ax[Z-1]=Y,X=0;for(Y=0;Y<16;Y++){Fo[Y]=X;for(J=0;J<1<<zo[Y];J++)Lx[X++]=Y}X>>=7;for(;Y<nI;Y++){Fo[Y]=X<<7;for(J=0;J<1<<zo[Y]-7;J++)Lx[256+X++]=Y}for(Q=0;Q<=EM;Q++)G[Q]=0;J=0;while(J<=143)JH[J*2+1]=8,J++,G[8]++;while(J<=255)JH[J*2+1]=9,J++,G[9]++;while(J<=279)JH[J*2+1]=7,J++,G[7]++;while(J<=287)JH[J*2+1]=8,J++,G[8]++;jI0(JH,Mx+1,G);for(J=0;J<nI;J++)Bx[J*2+1]=5,Bx[J*2]=CI0(J,5);II0=new bU1(JH,sU1,Tx+1,Mx,EM),PI0=new bU1(Bx,zo,0,nI,EM),TI0=new bU1([],KU4,0,VB1,VU4)},SI0=(J)=>{let Q;for(Q=0;Q<Mx;Q++)J.dyn_ltree[Q*2]=0;for(Q=0;Q<nI;Q++)J.dyn_dtree[Q*2]=0;for(Q=0;Q<VB1;Q++)J.bl_tree[Q*2]=0;J.dyn_ltree[KB1*2]=1,J.opt_len=J.static_len=0,J.sym_next=J.matches=0},_I0=(J)=>{if(J.bi_valid>8)Ox(J,J.bi_buf);else if(J.bi_valid>0)J.pending_buf[J.pending++]=J.bi_buf;J.bi_buf=0,J.bi_valid=0},xE0=(J,Q,Z,Y)=>{let X=Q*2,G=Z*2;return J[X]<J[G]||J[X]===J[G]&&Y[Q]<=Y[Z]},gU1=(J,Q,Z)=>{let Y=J.heap[Z],X=Z<<1;while(X<=J.heap_len){if(X<J.heap_len&&xE0(Q,J.heap[X+1],J.heap[X],J.depth))X++;if(xE0(Q,Y,J.heap[X],J.depth))break;J.heap[Z]=J.heap[X],Z=X,X<<=1}J.heap[Z]=Y},vE0=(J,Q,Z)=>{let Y,X,G=0,V,K;if(J.sym_next!==0)do if(Y=J.pending_buf[J.sym_buf+G++]&255,Y+=(J.pending_buf[J.sym_buf+G++]&255)<<8,X=J.pending_buf[J.sym_buf+G++],Y===0)_K(J,X,Q);else{if(V=Ax[X],_K(J,V+Tx+1,Q),K=sU1[V],K!==0)X-=qB1[V],TZ(J,X,K);if(Y--,V=RI0(Y),_K(J,V,Z),K=zo[V],K!==0)Y-=Fo[V],TZ(J,Y,K)}while(G<J.sym_next);_K(J,KB1,Q)},tU1=(J,Q)=>{let Z=Q.dyn_tree,Y=Q.stat_desc.static_tree,X=Q.stat_desc.has_stree,G=Q.stat_desc.elems,V,K,q=-1,W;J.heap_len=0,J.heap_max=LI0;for(V=0;V<G;V++)if(Z[V*2]!==0)J.heap[++J.heap_len]=q=V,J.depth[V]=0;else Z[V*2+1]=0;while(J.heap_len<2)if(W=J.heap[++J.heap_len]=q<2?++q:0,Z[W*2]=1,J.depth[W]=0,J.opt_len--,X)J.static_len-=Y[W*2+1];Q.max_code=q;for(V=J.heap_len>>1;V>=1;V--)gU1(J,Z,V);W=G;do V=J.heap[1],J.heap[1]=J.heap[J.heap_len--],gU1(J,Z,1),K=J.heap[1],J.heap[--J.heap_max]=V,J.heap[--J.heap_max]=K,Z[W*2]=Z[V*2]+Z[K*2],J.depth[W]=(J.depth[V]>=J.depth[K]?J.depth[V]:J.depth[K])+1,Z[V*2+1]=Z[K*2+1]=W,J.heap[1]=W++,gU1(J,Z,1);while(J.heap_len>=2);J.heap[--J.heap_max]=J.heap[1],HU4(J,Q),jI0(Z,q,J.bl_count)},fE0=(J,Q,Z)=>{let Y,X=-1,G,V=Q[1],K=0,q=7,W=4;if(V===0)q=138,W=3;Q[(Z+1)*2+1]=65535;for(Y=0;Y<=Z;Y++){if(G=V,V=Q[(Y+1)*2+1],++K<q&&G===V)continue;else if(K<W)J.bl_tree[G*2]+=K;else if(G!==0){if(G!==X)J.bl_tree[G*2]++;J.bl_tree[AI0*2]++}else if(K<=10)J.bl_tree[OI0*2]++;else J.bl_tree[wI0*2]++;if(K=0,X=G,V===0)q=138,W=3;else if(G===V)q=6,W=3;else q=7,W=4}},hE0=(J,Q,Z)=>{let Y,X=-1,G,V=Q[1],K=0,q=7,W=4;if(V===0)q=138,W=3;for(Y=0;Y<=Z;Y++){if(G=V,V=Q[(Y+1)*2+1],++K<q&&G===V)continue;else if(K<W)do _K(J,G,J.bl_tree);while(--K!==0);else if(G!==0){if(G!==X)_K(J,G,J.bl_tree),K--;_K(J,AI0,J.bl_tree),TZ(J,K-3,2)}else if(K<=10)_K(J,OI0,J.bl_tree),TZ(J,K-3,3);else _K(J,wI0,J.bl_tree),TZ(J,K-11,7);if(K=0,X=G,V===0)q=138,W=3;else if(G===V)q=6,W=3;else q=7,W=4}},FU4=(J)=>{let Q;fE0(J,J.dyn_ltree,J.l_desc.max_code),fE0(J,J.dyn_dtree,J.d_desc.max_code),tU1(J,J.bl_desc);for(Q=VB1-1;Q>=3;Q--)if(J.bl_tree[EI0[Q]*2+1]!==0)break;return J.opt_len+=3*(Q+1)+5+5+4,Q},UU4=(J,Q,Z,Y)=>{let X;TZ(J,Q-257,5),TZ(J,Z-1,5),TZ(J,Y-4,4);for(X=0;X<Y;X++)TZ(J,J.bl_tree[EI0[X]*2+1],3);hE0(J,J.dyn_ltree,Q-1),hE0(J,J.dyn_dtree,Z-1)},BU4=(J)=>{let Q=4093624447,Z;for(Z=0;Z<=31;Z++,Q>>>=1)if(Q&1&&J.dyn_ltree[Z*2]!==0)return 0;if(J.dyn_ltree[18]!==0||J.dyn_ltree[20]!==0||J.dyn_ltree[26]!==0)return 1;for(Z=32;Z<Tx;Z++)if(J.dyn_ltree[Z*2]!==0)return 1;return 0},bE0=!1,NU4=(J)=>{if(!bE0)zU4(),bE0=!0;J.l_desc=new mU1(J.dyn_ltree,II0),J.d_desc=new mU1(J.dyn_dtree,PI0),J.bl_desc=new mU1(J.bl_tree,TI0),J.bi_buf=0,J.bi_valid=0,SI0(J)},kI0=(J,Q,Z,Y)=>{if(TZ(J,(YU4<<1)+(Y?1:0),3),_I0(J),Ox(J,Z),Ox(J,~Z),Z)J.pending_buf.set(J.window.subarray(Q,Q+Z),J.pending);J.pending+=Z},DU4=(J)=>{TZ(J,MI0<<1,3),_K(J,KB1,JH),WU4(J)},MU4=(J,Q,Z,Y)=>{let X,G,V=0;if(J.level>0){if(J.strm.data_type===2)J.strm.data_type=BU4(J);if(tU1(J,J.l_desc),tU1(J,J.d_desc),V=FU4(J),X=J.opt_len+3+7>>>3,G=J.static_len+3+7>>>3,G<=X)X=G}else X=G=Z+5;if(Z+4<=X&&Q!==-1)kI0(J,Q,Z,Y);else if(J.strategy===4||G===X)TZ(J,(MI0<<1)+(Y?1:0),3),vE0(J,JH,Bx);else TZ(J,(XU4<<1)+(Y?1:0),3),UU4(J,J.l_desc.max_code+1,J.d_desc.max_code+1,V+1),vE0(J,J.dyn_ltree,J.dyn_dtree);if(SI0(J),Y)_I0(J)},LU4=(J,Q,Z)=>{if(J.pending_buf[J.sym_buf+J.sym_next++]=Q,J.pending_buf[J.sym_buf+J.sym_next++]=Q>>8,J.pending_buf[J.sym_buf+J.sym_next++]=Z,Q===0)J.dyn_ltree[Z*2]++;else J.matches++,Q--,J.dyn_ltree[(Ax[Z]+Tx+1)*2]++,J.dyn_dtree[RI0(Q)*2]++;return J.sym_next===J.sym_end},AU4,OU4,wU4,EU4,IU4,PU4,TU4=(J,Q,Z,Y)=>{let X=J&65535|0,G=J>>>16&65535|0,V=0;while(Z!==0){V=Z>2000?2000:Z,Z-=V;do X=X+Q[Y++]|0,G=G+X|0;while(--V);X%=65521,G%=65521}return X|G<<16|0},wx,RU4=()=>{let J,Q=[];for(var Z=0;Z<256;Z++){J=Z;for(var Y=0;Y<8;Y++)J=J&1?3988292384^J>>>1:J>>>1;Q[Z]=J}return Q},CU4,jU4=(J,Q,Z,Y)=>{let X=CU4,G=Y+Z;J^=-1;for(let V=Y;V<G;V++)J=J>>>8^X[(J^Q[V])&255];return J^-1},E2,TM,jM,SU4,eU1,_U4,eF,kU4,JU,yU4,xU4,iX,mE0,JJ,gE0,kK,vU4,uU1,fU4,hU4,Vo,bU4,mU4,gU4,uU4,No,pU4=9,dU4=15,cU4=8,lU4=29,iU4=256,JB1,nU4=30,aU4=19,oU4,rU4=15,D9=3,tF=258,yK,sU4=32,aI=42,WB1=57,QB1=69,ZB1=73,YB1=91,XB1=103,IM=113,Fx=666,SQ=1,sI=2,RM=3,tI=4,tU4=3,PM=(J,Q)=>{return J.msg=TM[Q],Q},uE0=(J)=>{return J*2-(J>4?9:0)},sF=(J)=>{let Q=J.length;while(--Q>=0)J[Q]=0},eU4=(J)=>{let Q,Z,Y,X=J.w_size;Q=J.hash_size,Y=Q;do Z=J.head[--Y],J.head[Y]=Z>=X?Z-X:0;while(--Q);Q=X,Y=Q;do Z=J.prev[--Y],J.prev[Y]=Z>=X?Z-X:0;while(--Q)},JB4=(J,Q,Z)=>(Q<<J.hash_shift^Z)&J.hash_mask,QU,LY=(J)=>{let Q=J.state,Z=Q.pending;if(Z>J.avail_out)Z=J.avail_out;if(Z===0)return;if(J.output.set(Q.pending_buf.subarray(Q.pending_out,Q.pending_out+Z),J.next_out),J.next_out+=Z,Q.pending_out+=Z,J.total_out+=Z,J.avail_out-=Z,Q.pending-=Z,Q.pending===0)Q.pending_out=0},AY=(J,Q)=>{_U4(J,J.block_start>=0?J.block_start:-1,J.strstart-J.block_start,Q),J.block_start=J.strstart,LY(J.strm)},i9=(J,Q)=>{J.pending_buf[J.pending++]=Q},zx=(J,Q)=>{J.pending_buf[J.pending++]=Q>>>8&255,J.pending_buf[J.pending++]=Q&255},$B1=(J,Q,Z,Y)=>{let X=J.avail_in;if(X>Y)X=Y;if(X===0)return 0;if(J.avail_in-=X,Q.set(J.input.subarray(J.next_in,J.next_in+X),Z),J.state.wrap===1)J.adler=wx(J.adler,Q,X,Z);else if(J.state.wrap===2)J.adler=E2(J.adler,Q,X,Z);return J.next_in+=X,J.total_in+=X,X},yI0=(J,Q)=>{let{max_chain_length:Z,strstart:Y}=J,X,G,V=J.prev_length,K=J.nice_match,q=J.strstart>J.w_size-yK?J.strstart-(J.w_size-yK):0,W=J.window,H=J.w_mask,z=J.prev,U=J.strstart+tF,D=W[Y+V-1],M=W[Y+V];if(J.prev_length>=J.good_match)Z>>=2;if(K>J.lookahead)K=J.lookahead;do{if(X=Q,W[X+V]!==M||W[X+V-1]!==D||W[X]!==W[Y]||W[++X]!==W[Y+1])continue;Y+=2,X++;do;while(W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&Y<U);if(G=tF-(U-Y),Y=U-tF,G>V){if(J.match_start=Q,V=G,G>=K)break;D=W[Y+V-1],M=W[Y+V]}}while((Q=z[Q&H])>q&&--Z!==0);if(V<=J.lookahead)return V;return J.lookahead},oI=(J)=>{let Q=J.w_size,Z,Y,X;do{if(Y=J.window_size-J.lookahead-J.strstart,J.strstart>=Q+(Q-yK)){if(J.window.set(J.window.subarray(Q,Q+Q-Y),0),J.match_start-=Q,J.strstart-=Q,J.block_start-=Q,J.insert>J.strstart)J.insert=J.strstart;eU4(J),Y+=Q}if(J.strm.avail_in===0)break;if(Z=$B1(J.strm,J.window,J.strstart+J.lookahead,Y),J.lookahead+=Z,J.lookahead+J.insert>=D9){X=J.strstart-J.insert,J.ins_h=J.window[X],J.ins_h=QU(J,J.ins_h,J.window[X+1]);while(J.insert)if(J.ins_h=QU(J,J.ins_h,J.window[X+D9-1]),J.prev[X&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=X,X++,J.insert--,J.lookahead+J.insert<D9)break}}while(J.lookahead<yK&&J.strm.avail_in!==0)},xI0=(J,Q)=>{let Z=J.pending_buf_size-5>J.w_size?J.w_size:J.pending_buf_size-5,Y,X,G,V=0,K=J.strm.avail_in;do{if(Y=65535,G=J.bi_valid+42>>3,J.strm.avail_out<G)break;if(G=J.strm.avail_out-G,X=J.strstart-J.block_start,Y>X+J.strm.avail_in)Y=X+J.strm.avail_in;if(Y>G)Y=G;if(Y<Z&&(Y===0&&Q!==iX||Q===JU||Y!==X+J.strm.avail_in))break;if(V=Q===iX&&Y===X+J.strm.avail_in?1:0,eU1(J,0,0,V),J.pending_buf[J.pending-4]=Y,J.pending_buf[J.pending-3]=Y>>8,J.pending_buf[J.pending-2]=~Y,J.pending_buf[J.pending-1]=~Y>>8,LY(J.strm),X){if(X>Y)X=Y;J.strm.output.set(J.window.subarray(J.block_start,J.block_start+X),J.strm.next_out),J.strm.next_out+=X,J.strm.avail_out-=X,J.strm.total_out+=X,J.block_start+=X,Y-=X}if(Y)$B1(J.strm,J.strm.output,J.strm.next_out,Y),J.strm.next_out+=Y,J.strm.avail_out-=Y,J.strm.total_out+=Y}while(V===0);if(K-=J.strm.avail_in,K){if(K>=J.w_size)J.matches=2,J.window.set(J.strm.input.subarray(J.strm.next_in-J.w_size,J.strm.next_in),0),J.strstart=J.w_size,J.insert=J.strstart;else{if(J.window_size-J.strstart<=K){if(J.strstart-=J.w_size,J.window.set(J.window.subarray(J.w_size,J.w_size+J.strstart),0),J.matches<2)J.matches++;if(J.insert>J.strstart)J.insert=J.strstart}J.window.set(J.strm.input.subarray(J.strm.next_in-K,J.strm.next_in),J.strstart),J.strstart+=K,J.insert+=K>J.w_size-J.insert?J.w_size-J.insert:K}J.block_start=J.strstart}if(J.high_water<J.strstart)J.high_water=J.strstart;if(V)return tI;if(Q!==JU&&Q!==iX&&J.strm.avail_in===0&&J.strstart===J.block_start)return sI;if(G=J.window_size-J.strstart,J.strm.avail_in>G&&J.block_start>=J.w_size){if(J.block_start-=J.w_size,J.strstart-=J.w_size,J.window.set(J.window.subarray(J.w_size,J.w_size+J.strstart),0),J.matches<2)J.matches++;if(G+=J.w_size,J.insert>J.strstart)J.insert=J.strstart}if(G>J.strm.avail_in)G=J.strm.avail_in;if(G)$B1(J.strm,J.window,J.strstart,G),J.strstart+=G,J.insert+=G>J.w_size-J.insert?J.w_size-J.insert:G;if(J.high_water<J.strstart)J.high_water=J.strstart;if(G=J.bi_valid+42>>3,G=J.pending_buf_size-G>65535?65535:J.pending_buf_size-G,Z=G>J.w_size?J.w_size:G,X=J.strstart-J.block_start,X>=Z||(X||Q===iX)&&Q!==JU&&J.strm.avail_in===0&&X<=G)Y=X>G?G:X,V=Q===iX&&J.strm.avail_in===0&&Y===X?1:0,eU1(J,J.block_start,Y,V),J.block_start+=Y,LY(J.strm);return V?RM:SQ},pU1=(J,Q)=>{let Z,Y;for(;;){if(J.lookahead<yK){if(oI(J),J.lookahead<yK&&Q===JU)return SQ;if(J.lookahead===0)break}if(Z=0,J.lookahead>=D9)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;if(Z!==0&&J.strstart-Z<=J.w_size-yK)J.match_length=yI0(J,Z);if(J.match_length>=D9)if(Y=eF(J,J.strstart-J.match_start,J.match_length-D9),J.lookahead-=J.match_length,J.match_length<=J.max_lazy_match&&J.lookahead>=D9){J.match_length--;do J.strstart++,J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;while(--J.match_length!==0);J.strstart++}else J.strstart+=J.match_length,J.match_length=0,J.ins_h=J.window[J.strstart],J.ins_h=QU(J,J.ins_h,J.window[J.strstart+1]);else Y=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++;if(Y){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=J.strstart<D9-1?J.strstart:D9-1,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},lI=(J,Q)=>{let Z,Y,X;for(;;){if(J.lookahead<yK){if(oI(J),J.lookahead<yK&&Q===JU)return SQ;if(J.lookahead===0)break}if(Z=0,J.lookahead>=D9)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;if(J.prev_length=J.match_length,J.prev_match=J.match_start,J.match_length=D9-1,Z!==0&&J.prev_length<J.max_lazy_match&&J.strstart-Z<=J.w_size-yK){if(J.match_length=yI0(J,Z),J.match_length<=5&&(J.strategy===hU4||J.match_length===D9&&J.strstart-J.match_start>4096))J.match_length=D9-1}if(J.prev_length>=D9&&J.match_length<=J.prev_length){X=J.strstart+J.lookahead-D9,Y=eF(J,J.strstart-1-J.prev_match,J.prev_length-D9),J.lookahead-=J.prev_length-1,J.prev_length-=2;do if(++J.strstart<=X)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;while(--J.prev_length!==0);if(J.match_available=0,J.match_length=D9-1,J.strstart++,Y){if(AY(J,!1),J.strm.avail_out===0)return SQ}}else if(J.match_available){if(Y=eF(J,0,J.window[J.strstart-1]),Y)AY(J,!1);if(J.strstart++,J.lookahead--,J.strm.avail_out===0)return SQ}else J.match_available=1,J.strstart++,J.lookahead--}if(J.match_available)Y=eF(J,0,J.window[J.strstart-1]),J.match_available=0;if(J.insert=J.strstart<D9-1?J.strstart:D9-1,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},QB4=(J,Q)=>{let Z,Y,X,G,V=J.window;for(;;){if(J.lookahead<=tF){if(oI(J),J.lookahead<=tF&&Q===JU)return SQ;if(J.lookahead===0)break}if(J.match_length=0,J.lookahead>=D9&&J.strstart>0){if(X=J.strstart-1,Y=V[X],Y===V[++X]&&Y===V[++X]&&Y===V[++X]){G=J.strstart+tF;do;while(Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&X<G);if(J.match_length=tF-(G-X),J.match_length>J.lookahead)J.match_length=J.lookahead}}if(J.match_length>=D9)Z=eF(J,1,J.match_length-D9),J.lookahead-=J.match_length,J.strstart+=J.match_length,J.match_length=0;else Z=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++;if(Z){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=0,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},ZB4=(J,Q)=>{let Z;for(;;){if(J.lookahead===0){if(oI(J),J.lookahead===0){if(Q===JU)return SQ;break}}if(J.match_length=0,Z=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++,Z){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=0,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},Ux,YB4=(J)=>{J.window_size=2*J.w_size,sF(J.head),J.max_lazy_match=Ux[J.level].max_lazy,J.good_match=Ux[J.level].good_length,J.nice_match=Ux[J.level].nice_length,J.max_chain_length=Ux[J.level].max_chain,J.strstart=0,J.block_start=0,J.lookahead=0,J.insert=0,J.match_length=J.prev_length=D9-1,J.match_available=0,J.ins_h=0},Rx=(J)=>{if(!J)return 1;let Q=J.state;if(!Q||Q.strm!==J||Q.status!==aI&&Q.status!==WB1&&Q.status!==QB1&&Q.status!==ZB1&&Q.status!==YB1&&Q.status!==XB1&&Q.status!==IM&&Q.status!==Fx)return 1;return 0},vI0=(J)=>{if(Rx(J))return PM(J,kK);J.total_in=J.total_out=0,J.data_type=uU4;let Q=J.state;if(Q.pending=0,Q.pending_out=0,Q.wrap<0)Q.wrap=-Q.wrap;return Q.status=Q.wrap===2?WB1:Q.wrap?aI:IM,J.adler=Q.wrap===2?0:1,Q.last_flush=-2,SU4(Q),JJ},fI0=(J)=>{let Q=vI0(J);if(Q===JJ)YB4(J.state);return Q},$B4=(J,Q)=>{if(Rx(J)||J.state.wrap!==2)return kK;return J.state.gzhead=Q,JJ},hI0=(J,Q,Z,Y,X,G)=>{if(!J)return kK;let V=1;if(Q===fU4)Q=6;if(Y<0)V=0,Y=-Y;else if(Y>15)V=2,Y-=16;if(X<1||X>pU4||Z!==No||Y<8||Y>15||Q<0||Q>9||G<0||G>mU4||Y===8&&V!==1)return PM(J,kK);if(Y===8)Y=9;let K=new XB4;return J.state=K,K.strm=J,K.status=aI,K.wrap=V,K.gzhead=null,K.w_bits=Y,K.w_size=1<<K.w_bits,K.w_mask=K.w_size-1,K.hash_bits=X+7,K.hash_size=1<<K.hash_bits,K.hash_mask=K.hash_size-1,K.hash_shift=~~((K.hash_bits+D9-1)/D9),K.window=new Uint8Array(K.w_size*2),K.head=new Uint16Array(K.hash_size),K.prev=new Uint16Array(K.w_size),K.lit_bufsize=1<<X+6,K.pending_buf_size=K.lit_bufsize*4,K.pending_buf=new Uint8Array(K.pending_buf_size),K.sym_buf=K.lit_bufsize,K.sym_end=(K.lit_bufsize-1)*3,K.level=Q,K.strategy=G,K.method=Z,fI0(J)},GB4=(J,Q)=>{return hI0(J,Q,No,dU4,cU4,gU4)},VB4=(J,Q)=>{if(Rx(J)||Q>mE0||Q<0)return J?PM(J,kK):kK;let Z=J.state;if(!J.output||J.avail_in!==0&&!J.input||Z.status===Fx&&Q!==iX)return PM(J,J.avail_out===0?uU1:kK);let Y=Z.last_flush;if(Z.last_flush=Q,Z.pending!==0){if(LY(J),J.avail_out===0)return Z.last_flush=-1,JJ}else if(J.avail_in===0&&uE0(Q)<=uE0(Y)&&Q!==iX)return PM(J,uU1);if(Z.status===Fx&&J.avail_in!==0)return PM(J,uU1);if(Z.status===aI&&Z.wrap===0)Z.status=IM;if(Z.status===aI){let X=No+(Z.w_bits-8<<4)<<8,G=-1;if(Z.strategy>=Vo||Z.level<2)G=0;else if(Z.level<6)G=1;else if(Z.level===6)G=2;else G=3;if(X|=G<<6,Z.strstart!==0)X|=sU4;if(X+=31-X%31,zx(Z,X),Z.strstart!==0)zx(Z,J.adler>>>16),zx(Z,J.adler&65535);if(J.adler=1,Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}if(Z.status===WB1)if(J.adler=0,i9(Z,31),i9(Z,139),i9(Z,8),!Z.gzhead){if(i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,Z.level===9?2:Z.strategy>=Vo||Z.level<2?4:0),i9(Z,tU4),Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}else{if(i9(Z,(Z.gzhead.text?1:0)+(Z.gzhead.hcrc?2:0)+(!Z.gzhead.extra?0:4)+(!Z.gzhead.name?0:8)+(!Z.gzhead.comment?0:16)),i9(Z,Z.gzhead.time&255),i9(Z,Z.gzhead.time>>8&255),i9(Z,Z.gzhead.time>>16&255),i9(Z,Z.gzhead.time>>24&255),i9(Z,Z.level===9?2:Z.strategy>=Vo||Z.level<2?4:0),i9(Z,Z.gzhead.os&255),Z.gzhead.extra&&Z.gzhead.extra.length)i9(Z,Z.gzhead.extra.length&255),i9(Z,Z.gzhead.extra.length>>8&255);if(Z.gzhead.hcrc)J.adler=E2(J.adler,Z.pending_buf,Z.pending,0);Z.gzindex=0,Z.status=QB1}if(Z.status===QB1){if(Z.gzhead.extra){let X=Z.pending,G=(Z.gzhead.extra.length&65535)-Z.gzindex;while(Z.pending+G>Z.pending_buf_size){let K=Z.pending_buf_size-Z.pending;if(Z.pending_buf.set(Z.gzhead.extra.subarray(Z.gzindex,Z.gzindex+K),Z.pending),Z.pending=Z.pending_buf_size,Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(Z.gzindex+=K,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0,G-=K}let V=new Uint8Array(Z.gzhead.extra);if(Z.pending_buf.set(V.subarray(Z.gzindex,Z.gzindex+G),Z.pending),Z.pending+=G,Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);Z.gzindex=0}Z.status=ZB1}if(Z.status===ZB1){if(Z.gzhead.name){let X=Z.pending,G;do{if(Z.pending===Z.pending_buf_size){if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0}if(Z.gzindex<Z.gzhead.name.length)G=Z.gzhead.name.charCodeAt(Z.gzindex++)&255;else G=0;i9(Z,G)}while(G!==0);if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);Z.gzindex=0}Z.status=YB1}if(Z.status===YB1){if(Z.gzhead.comment){let X=Z.pending,G;do{if(Z.pending===Z.pending_buf_size){if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0}if(Z.gzindex<Z.gzhead.comment.length)G=Z.gzhead.comment.charCodeAt(Z.gzindex++)&255;else G=0;i9(Z,G)}while(G!==0);if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X)}Z.status=XB1}if(Z.status===XB1){if(Z.gzhead.hcrc){if(Z.pending+2>Z.pending_buf_size){if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}i9(Z,J.adler&255),i9(Z,J.adler>>8&255),J.adler=0}if(Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}if(J.avail_in!==0||Z.lookahead!==0||Q!==JU&&Z.status!==Fx){let X=Z.level===0?xI0(Z,Q):Z.strategy===Vo?ZB4(Z,Q):Z.strategy===bU4?QB4(Z,Q):Ux[Z.level].func(Z,Q);if(X===RM||X===tI)Z.status=Fx;if(X===SQ||X===RM){if(J.avail_out===0)Z.last_flush=-1;return JJ}if(X===sI){if(Q===yU4)kU4(Z);else if(Q!==mE0){if(eU1(Z,0,0,!1),Q===xU4){if(sF(Z.head),Z.lookahead===0)Z.strstart=0,Z.block_start=0,Z.insert=0}}if(LY(J),J.avail_out===0)return Z.last_flush=-1,JJ}}if(Q!==iX)return JJ;if(Z.wrap<=0)return gE0;if(Z.wrap===2)i9(Z,J.adler&255),i9(Z,J.adler>>8&255),i9(Z,J.adler>>16&255),i9(Z,J.adler>>24&255),i9(Z,J.total_in&255),i9(Z,J.total_in>>8&255),i9(Z,J.total_in>>16&255),i9(Z,J.total_in>>24&255);else zx(Z,J.adler>>>16),zx(Z,J.adler&65535);if(LY(J),Z.wrap>0)Z.wrap=-Z.wrap;return Z.pending!==0?JJ:gE0},KB4=(J)=>{if(Rx(J))return kK;let Q=J.state.status;return J.state=null,Q===IM?PM(J,vU4):JJ},qB4=(J,Q)=>{let Z=Q.length;if(Rx(J))return kK;let Y=J.state,X=Y.wrap;if(X===2||X===1&&Y.status!==aI||Y.lookahead)return kK;if(X===1)J.adler=wx(J.adler,Q,Z,0);if(Y.wrap=0,Z>=Y.w_size){if(X===0)sF(Y.head),Y.strstart=0,Y.block_start=0,Y.insert=0;let q=new Uint8Array(Y.w_size);q.set(Q.subarray(Z-Y.w_size,Z),0),Q=q,Z=Y.w_size}let{avail_in:G,next_in:V,input:K}=J;J.avail_in=Z,J.next_in=0,J.input=Q,oI(Y);while(Y.lookahead>=D9){let q=Y.strstart,W=Y.lookahead-(D9-1);do Y.ins_h=QU(Y,Y.ins_h,Y.window[q+D9-1]),Y.prev[q&Y.w_mask]=Y.head[Y.ins_h],Y.head[Y.ins_h]=q,q++;while(--W);Y.strstart=q,Y.lookahead=D9-1,oI(Y)}return Y.strstart+=Y.lookahead,Y.block_start=Y.strstart,Y.insert=Y.lookahead,Y.lookahead=0,Y.match_length=Y.prev_length=D9-1,Y.match_available=0,J.next_in=V,J.input=K,J.avail_in=G,Y.wrap=X,JJ},WB4,HB4,zB4,FB4,UB4,BB4,NB4,DB4,MB4="pako deflate (from Nodeca project)",Nx,LB4=(J,Q)=>{return Object.prototype.hasOwnProperty.call(J,Q)},AB4=function(J){let Q=Array.prototype.slice.call(arguments,1);while(Q.length){let Z=Q.shift();if(!Z)continue;if(typeof Z!=="object")throw TypeError(Z+"must be non-object");for(let Y in Z)if(LB4(Z,Y))J[Y]=Z[Y]}return J},OB4=(J)=>{let Q=0;for(let Y=0,X=J.length;Y<X;Y++)Q+=J[Y].length;let Z=new Uint8Array(Q);for(let Y=0,X=0,G=J.length;Y<G;Y++){let V=J[Y];Z.set(V,X),X+=V.length}return Z},Do,bI0=!0,Ex,wB4=(J)=>{if(typeof TextEncoder==="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(J);let Q,Z,Y,X,G,V=J.length,K=0;for(X=0;X<V;X++){if(Z=J.charCodeAt(X),(Z&64512)===55296&&X+1<V){if(Y=J.charCodeAt(X+1),(Y&64512)===56320)Z=65536+(Z-55296<<10)+(Y-56320),X++}K+=Z<128?1:Z<2048?2:Z<65536?3:4}Q=new Uint8Array(K);for(G=0,X=0;G<K;X++){if(Z=J.charCodeAt(X),(Z&64512)===55296&&X+1<V){if(Y=J.charCodeAt(X+1),(Y&64512)===56320)Z=65536+(Z-55296<<10)+(Y-56320),X++}if(Z<128)Q[G++]=Z;else if(Z<2048)Q[G++]=192|Z>>>6,Q[G++]=128|Z&63;else if(Z<65536)Q[G++]=224|Z>>>12,Q[G++]=128|Z>>>6&63,Q[G++]=128|Z&63;else Q[G++]=240|Z>>>18,Q[G++]=128|Z>>>12&63,Q[G++]=128|Z>>>6&63,Q[G++]=128|Z&63}return Q},EB4=(J,Q)=>{if(Q<65534){if(J.subarray&&bI0)return String.fromCharCode.apply(null,J.length===Q?J:J.subarray(0,Q))}let Z="";for(let Y=0;Y<Q;Y++)Z+=String.fromCharCode(J[Y]);return Z},IB4=(J,Q)=>{let Z=Q||J.length;if(typeof TextDecoder==="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(J.subarray(0,Q));let Y,X,G=Array(Z*2);for(X=0,Y=0;Y<Z;){let V=J[Y++];if(V<128){G[X++]=V;continue}let K=Ex[V];if(K>4){G[X++]=65533,Y+=K-1;continue}V&=K===2?31:K===3?15:7;while(K>1&&Y<Z)V=V<<6|J[Y++]&63,K--;if(K>1){G[X++]=65533;continue}if(V<65536)G[X++]=V;else V-=65536,G[X++]=55296|V>>10&1023,G[X++]=56320|V&1023}return EB4(G,X)},PB4=(J,Q)=>{if(Q=Q||J.length,Q>J.length)Q=J.length;let Z=Q-1;while(Z>=0&&(J[Z]&192)===128)Z--;if(Z<0)return Q;if(Z===0)return Q;return Z+Ex[J[Z]]>Q?Z:Q},Ix,mI0,gI0,RB4,CB4,jB4,SB4,Uo,_B4,kB4,yB4,xB4,hB4,bB4,mB4,gB4,uB4,pB4,Ko=16209,dB4=16191,cB4=function(Q,Z){let Y,X,G,V,K,q,W,H,z,U,D,M,L,A,E,I,P,R,y,k,v,g,d,b,a=Q.state;Y=Q.next_in,d=Q.input,X=Y+(Q.avail_in-5),G=Q.next_out,b=Q.output,V=G-(Z-Q.avail_out),K=G+(Q.avail_out-257),q=a.dmax,W=a.wsize,H=a.whave,z=a.wnext,U=a.window,D=a.hold,M=a.bits,L=a.lencode,A=a.distcode,E=(1<<a.lenbits)-1,I=(1<<a.distbits)-1;J:do{if(M<15)D+=d[Y++]<<M,M+=8,D+=d[Y++]<<M,M+=8;P=L[D&E];Q:for(;;){if(R=P>>>24,D>>>=R,M-=R,R=P>>>16&255,R===0)b[G++]=P&65535;else if(R&16){if(y=P&65535,R&=15,R){if(M<R)D+=d[Y++]<<M,M+=8;y+=D&(1<<R)-1,D>>>=R,M-=R}if(M<15)D+=d[Y++]<<M,M+=8,D+=d[Y++]<<M,M+=8;P=A[D&I];Z:for(;;){if(R=P>>>24,D>>>=R,M-=R,R=P>>>16&255,R&16){if(k=P&65535,R&=15,M<R){if(D+=d[Y++]<<M,M+=8,M<R)D+=d[Y++]<<M,M+=8}if(k+=D&(1<<R)-1,k>q){Q.msg="invalid distance too far back",a.mode=Ko;break J}if(D>>>=R,M-=R,R=G-V,k>R){if(R=k-R,R>H){if(a.sane){Q.msg="invalid distance too far back",a.mode=Ko;break J}}if(v=0,g=U,z===0){if(v+=W-R,R<y){y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}}else if(z<R){if(v+=W+z-R,R-=z,R<y){y-=R;do b[G++]=U[v++];while(--R);if(v=0,z<y){R=z,y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}}}else if(v+=z-R,R<y){y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}while(y>2)b[G++]=g[v++],b[G++]=g[v++],b[G++]=g[v++],y-=3;if(y){if(b[G++]=g[v++],y>1)b[G++]=g[v++]}}else{v=G-k;do b[G++]=b[v++],b[G++]=b[v++],b[G++]=b[v++],y-=3;while(y>2);if(y){if(b[G++]=b[v++],y>1)b[G++]=b[v++]}}}else if((R&64)===0){P=A[(P&65535)+(D&(1<<R)-1)];continue Z}else{Q.msg="invalid distance code",a.mode=Ko;break J}break}}else if((R&64)===0){P=L[(P&65535)+(D&(1<<R)-1)];continue Q}else if(R&32){a.mode=dB4;break J}else{Q.msg="invalid literal/length code",a.mode=Ko;break J}break}}while(Y<X&&G<K);y=M>>3,Y-=y,M-=y<<3,D&=(1<<M)-1,Q.next_in=Y,Q.next_out=G,Q.avail_in=Y<X?5+(X-Y):5-(Y-X),Q.avail_out=G<K?257+(K-G):257-(G-K),a.hold=D,a.bits=M;return},iI=15,pE0=852,dE0=592,cE0=0,dU1=1,lE0=2,lB4,iB4,nB4,aB4,oB4=(J,Q,Z,Y,X,G,V,K)=>{let q=K.bits,W=0,H=0,z=0,U=0,D=0,M=0,L=0,A=0,E=0,I=0,P,R,y,k,v,g=null,d,b=new Uint16Array(iI+1),a=new Uint16Array(iI+1),G1=null,e,c,J1;for(W=0;W<=iI;W++)b[W]=0;for(H=0;H<Y;H++)b[Q[Z+H]]++;D=q;for(U=iI;U>=1;U--)if(b[U]!==0)break;if(D>U)D=U;if(U===0)return X[G++]=20971520,X[G++]=20971520,K.bits=1,0;for(z=1;z<U;z++)if(b[z]!==0)break;if(D<z)D=z;A=1;for(W=1;W<=iI;W++)if(A<<=1,A-=b[W],A<0)return-1;if(A>0&&(J===cE0||U!==1))return-1;a[1]=0;for(W=1;W<iI;W++)a[W+1]=a[W]+b[W];for(H=0;H<Y;H++)if(Q[Z+H]!==0)V[a[Q[Z+H]]++]=H;if(J===cE0)g=G1=V,d=20;else if(J===dU1)g=lB4,G1=iB4,d=257;else g=nB4,G1=aB4,d=0;if(I=0,H=0,W=z,v=G,M=D,L=0,y=-1,E=1<<D,k=E-1,J===dU1&&E>pE0||J===lE0&&E>dE0)return 1;for(;;){if(e=W-L,V[H]+1<d)c=0,J1=V[H];else if(V[H]>=d)c=G1[V[H]-d],J1=g[V[H]-d];else c=96,J1=0;P=1<<W-L,R=1<<M,z=R;do R-=P,X[v+(I>>L)+R]=e<<24|c<<16|J1|0;while(R!==0);P=1<<W-1;while(I&P)P>>=1;if(P!==0)I&=P-1,I+=P;else I=0;if(H++,--b[W]===0){if(W===U)break;W=Q[Z+V[H]]}if(W>D&&(I&k)!==y){if(L===0)L=D;v+=z,M=W-L,A=1<<M;while(M+L<U){if(A-=b[M+L],A<=0)break;M++,A<<=1}if(E+=1<<M,J===dU1&&E>pE0||J===lE0&&E>dE0)return 1;y=I&k,X[y]=D<<24|M<<16|v-G|0}}if(I!==0)X[v+I]=W-L<<24|4194304|0;return K.bits=D,0},Dx,rB4=0,uI0=1,pI0=2,iE0,sB4,qo,CM,tB4,eB4,nX,dI0,cI0,JN4,nE0,Mo=16180,aE0=16181,oE0=16182,rE0=16183,sE0=16184,tE0=16185,eE0=16186,JI0=16187,QI0=16188,ZI0=16189,Bo=16190,eW=16191,cU1=16192,YI0=16193,lU1=16194,XI0=16195,$I0=16196,GI0=16197,VI0=16198,Wo=16199,Ho=16200,KI0=16201,qI0=16202,WI0=16203,HI0=16204,zI0=16205,iU1=16206,FI0=16207,UI0=16208,F7=16209,lI0=16210,iI0=16211,QN4=852,ZN4=592,YN4=15,XN4,BI0=(J)=>{return(J>>>24&255)+(J>>>8&65280)+((J&65280)<<8)+((J&255)<<24)},SM=(J)=>{if(!J)return 1;let Q=J.state;if(!Q||Q.strm!==J||Q.mode<Mo||Q.mode>iI0)return 1;return 0},nI0=(J)=>{if(SM(J))return nX;let Q=J.state;if(J.total_in=J.total_out=Q.total=0,J.msg="",Q.wrap)J.adler=Q.wrap&1;return Q.mode=Mo,Q.last=0,Q.havedict=0,Q.flags=-1,Q.dmax=32768,Q.head=null,Q.hold=0,Q.bits=0,Q.lencode=Q.lendyn=new Int32Array(QN4),Q.distcode=Q.distdyn=new Int32Array(ZN4),Q.sane=1,Q.back=-1,CM},aI0=(J)=>{if(SM(J))return nX;let Q=J.state;return Q.wsize=0,Q.whave=0,Q.wnext=0,nI0(J)},oI0=(J,Q)=>{let Z;if(SM(J))return nX;let Y=J.state;if(Q<0)Z=0,Q=-Q;else if(Z=(Q>>4)+5,Q<48)Q&=15;if(Q&&(Q<8||Q>15))return nX;if(Y.window!==null&&Y.wbits!==Q)Y.window=null;return Y.wrap=Z,Y.wbits=Q,aI0(J)},rI0=(J,Q)=>{if(!J)return nX;let Z=new $N4;J.state=Z,Z.strm=J,Z.window=null,Z.mode=Mo;let Y=oI0(J,Q);if(Y!==CM)J.state=null;return Y},GN4=(J)=>{return rI0(J,XN4)},NI0=!0,nU1,aU1,VN4=(J)=>{if(NI0){nU1=new Int32Array(512),aU1=new Int32Array(32);let Q=0;while(Q<144)J.lens[Q++]=8;while(Q<256)J.lens[Q++]=9;while(Q<280)J.lens[Q++]=7;while(Q<288)J.lens[Q++]=8;Dx(uI0,J.lens,0,288,nU1,0,J.work,{bits:9}),Q=0;while(Q<32)J.lens[Q++]=5;Dx(pI0,J.lens,0,32,aU1,0,J.work,{bits:5}),NI0=!1}J.lencode=nU1,J.lenbits=9,J.distcode=aU1,J.distbits=5},sI0=(J,Q,Z,Y)=>{let X,G=J.state;if(G.window===null)G.wsize=1<<G.wbits,G.wnext=0,G.whave=0,G.window=new Uint8Array(G.wsize);if(Y>=G.wsize)G.window.set(Q.subarray(Z-G.wsize,Z),0),G.wnext=0,G.whave=G.wsize;else{if(X=G.wsize-G.wnext,X>Y)X=Y;if(G.window.set(Q.subarray(Z-Y,Z-Y+X),G.wnext),Y-=X,Y)G.window.set(Q.subarray(Z-Y,Z),0),G.wnext=Y,G.whave=G.wsize;else{if(G.wnext+=X,G.wnext===G.wsize)G.wnext=0;if(G.whave<G.wsize)G.whave+=X}}return 0},KN4=(J,Q)=>{let Z,Y,X,G,V,K,q,W,H,z,U,D,M,L,A=0,E,I,P,R,y,k,v,g,d=new Uint8Array(4),b,a,G1=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(SM(J)||!J.output||!J.input&&J.avail_in!==0)return nX;if(Z=J.state,Z.mode===eW)Z.mode=cU1;V=J.next_out,X=J.output,q=J.avail_out,G=J.next_in,Y=J.input,K=J.avail_in,W=Z.hold,H=Z.bits,z=K,U=q,g=CM;J:for(;;)switch(Z.mode){case Mo:if(Z.wrap===0){Z.mode=cU1;break}while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&2&&W===35615){if(Z.wbits===0)Z.wbits=15;Z.check=0,d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0),W=0,H=0,Z.mode=aE0;break}if(Z.head)Z.head.done=!1;if(!(Z.wrap&1)||(((W&255)<<8)+(W>>8))%31){J.msg="incorrect header check",Z.mode=F7;break}if((W&15)!==nE0){J.msg="unknown compression method",Z.mode=F7;break}if(W>>>=4,H-=4,v=(W&15)+8,Z.wbits===0)Z.wbits=v;if(v>15||v>Z.wbits){J.msg="invalid window size",Z.mode=F7;break}Z.dmax=1<<Z.wbits,Z.flags=0,J.adler=Z.check=1,Z.mode=W&512?ZI0:eW,W=0,H=0;break;case aE0:while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.flags=W,(Z.flags&255)!==nE0){J.msg="unknown compression method",Z.mode=F7;break}if(Z.flags&57344){J.msg="unknown header flags set",Z.mode=F7;break}if(Z.head)Z.head.text=W>>8&1;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0,Z.mode=oE0;case oE0:while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.head)Z.head.time=W;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,d[2]=W>>>16&255,d[3]=W>>>24&255,Z.check=E2(Z.check,d,4,0);W=0,H=0,Z.mode=rE0;case rE0:while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.head)Z.head.xflags=W&255,Z.head.os=W>>8;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0,Z.mode=sE0;case sE0:if(Z.flags&1024){while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.length=W,Z.head)Z.head.extra_len=W;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0}else if(Z.head)Z.head.extra=null;Z.mode=tE0;case tE0:if(Z.flags&1024){if(D=Z.length,D>K)D=K;if(D){if(Z.head){if(v=Z.head.extra_len-Z.length,!Z.head.extra)Z.head.extra=new Uint8Array(Z.head.extra_len);Z.head.extra.set(Y.subarray(G,G+D),v)}if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);K-=D,G+=D,Z.length-=D}if(Z.length)break J}Z.length=0,Z.mode=eE0;case eE0:if(Z.flags&2048){if(K===0)break J;D=0;do if(v=Y[G+D++],Z.head&&v&&Z.length<65536)Z.head.name+=String.fromCharCode(v);while(v&&D<K);if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);if(K-=D,G+=D,v)break J}else if(Z.head)Z.head.name=null;Z.length=0,Z.mode=JI0;case JI0:if(Z.flags&4096){if(K===0)break J;D=0;do if(v=Y[G+D++],Z.head&&v&&Z.length<65536)Z.head.comment+=String.fromCharCode(v);while(v&&D<K);if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);if(K-=D,G+=D,v)break J}else if(Z.head)Z.head.comment=null;Z.mode=QI0;case QI0:if(Z.flags&512){while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&4&&W!==(Z.check&65535)){J.msg="header crc mismatch",Z.mode=F7;break}W=0,H=0}if(Z.head)Z.head.hcrc=Z.flags>>9&1,Z.head.done=!0;J.adler=Z.check=0,Z.mode=eW;break;case ZI0:while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}J.adler=Z.check=BI0(W),W=0,H=0,Z.mode=Bo;case Bo:if(Z.havedict===0)return J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,eB4;J.adler=Z.check=1,Z.mode=eW;case eW:if(Q===sB4||Q===qo)break J;case cU1:if(Z.last){W>>>=H&7,H-=H&7,Z.mode=iU1;break}while(H<3){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}switch(Z.last=W&1,W>>>=1,H-=1,W&3){case 0:Z.mode=YI0;break;case 1:if(VN4(Z),Z.mode=Wo,Q===qo){W>>>=2,H-=2;break J}break;case 2:Z.mode=$I0;break;case 3:J.msg="invalid block type",Z.mode=F7}W>>>=2,H-=2;break;case YI0:W>>>=H&7,H-=H&7;while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if((W&65535)!==(W>>>16^65535)){J.msg="invalid stored block lengths",Z.mode=F7;break}if(Z.length=W&65535,W=0,H=0,Z.mode=lU1,Q===qo)break J;case lU1:Z.mode=XI0;case XI0:if(D=Z.length,D){if(D>K)D=K;if(D>q)D=q;if(D===0)break J;X.set(Y.subarray(G,G+D),V),K-=D,G+=D,q-=D,V+=D,Z.length-=D;break}Z.mode=eW;break;case $I0:while(H<14){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.nlen=(W&31)+257,W>>>=5,H-=5,Z.ndist=(W&31)+1,W>>>=5,H-=5,Z.ncode=(W&15)+4,W>>>=4,H-=4,Z.nlen>286||Z.ndist>30){J.msg="too many length or distance symbols",Z.mode=F7;break}Z.have=0,Z.mode=GI0;case GI0:while(Z.have<Z.ncode){while(H<3){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.lens[G1[Z.have++]]=W&7,W>>>=3,H-=3}while(Z.have<19)Z.lens[G1[Z.have++]]=0;if(Z.lencode=Z.lendyn,Z.lenbits=7,b={bits:Z.lenbits},g=Dx(rB4,Z.lens,0,19,Z.lencode,0,Z.work,b),Z.lenbits=b.bits,g){J.msg="invalid code lengths set",Z.mode=F7;break}Z.have=0,Z.mode=VI0;case VI0:while(Z.have<Z.nlen+Z.ndist){for(;;){if(A=Z.lencode[W&(1<<Z.lenbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(P<16)W>>>=E,H-=E,Z.lens[Z.have++]=P;else{if(P===16){a=E+2;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(W>>>=E,H-=E,Z.have===0){J.msg="invalid bit length repeat",Z.mode=F7;break}v=Z.lens[Z.have-1],D=3+(W&3),W>>>=2,H-=2}else if(P===17){a=E+3;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=E,H-=E,v=0,D=3+(W&7),W>>>=3,H-=3}else{a=E+7;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=E,H-=E,v=0,D=11+(W&127),W>>>=7,H-=7}if(Z.have+D>Z.nlen+Z.ndist){J.msg="invalid bit length repeat",Z.mode=F7;break}while(D--)Z.lens[Z.have++]=v}}if(Z.mode===F7)break;if(Z.lens[256]===0){J.msg="invalid code -- missing end-of-block",Z.mode=F7;break}if(Z.lenbits=9,b={bits:Z.lenbits},g=Dx(uI0,Z.lens,0,Z.nlen,Z.lencode,0,Z.work,b),Z.lenbits=b.bits,g){J.msg="invalid literal/lengths set",Z.mode=F7;break}if(Z.distbits=6,Z.distcode=Z.distdyn,b={bits:Z.distbits},g=Dx(pI0,Z.lens,Z.nlen,Z.ndist,Z.distcode,0,Z.work,b),Z.distbits=b.bits,g){J.msg="invalid distances set",Z.mode=F7;break}if(Z.mode=Wo,Q===qo)break J;case Wo:Z.mode=Ho;case Ho:if(K>=6&&q>=258){if(J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,cB4(J,U),V=J.next_out,X=J.output,q=J.avail_out,G=J.next_in,Y=J.input,K=J.avail_in,W=Z.hold,H=Z.bits,Z.mode===eW)Z.back=-1;break}Z.back=0;for(;;){if(A=Z.lencode[W&(1<<Z.lenbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(I&&(I&240)===0){R=E,y=I,k=P;for(;;){if(A=Z.lencode[k+((W&(1<<R+y)-1)>>R)],E=A>>>24,I=A>>>16&255,P=A&65535,R+E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=R,H-=R,Z.back+=R}if(W>>>=E,H-=E,Z.back+=E,Z.length=P,I===0){Z.mode=zI0;break}if(I&32){Z.back=-1,Z.mode=eW;break}if(I&64){J.msg="invalid literal/length code",Z.mode=F7;break}Z.extra=I&15,Z.mode=KI0;case KI0:if(Z.extra){a=Z.extra;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.length+=W&(1<<Z.extra)-1,W>>>=Z.extra,H-=Z.extra,Z.back+=Z.extra}Z.was=Z.length,Z.mode=qI0;case qI0:for(;;){if(A=Z.distcode[W&(1<<Z.distbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if((I&240)===0){R=E,y=I,k=P;for(;;){if(A=Z.distcode[k+((W&(1<<R+y)-1)>>R)],E=A>>>24,I=A>>>16&255,P=A&65535,R+E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=R,H-=R,Z.back+=R}if(W>>>=E,H-=E,Z.back+=E,I&64){J.msg="invalid distance code",Z.mode=F7;break}Z.offset=P,Z.extra=I&15,Z.mode=WI0;case WI0:if(Z.extra){a=Z.extra;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.offset+=W&(1<<Z.extra)-1,W>>>=Z.extra,H-=Z.extra,Z.back+=Z.extra}if(Z.offset>Z.dmax){J.msg="invalid distance too far back",Z.mode=F7;break}Z.mode=HI0;case HI0:if(q===0)break J;if(D=U-q,Z.offset>D){if(D=Z.offset-D,D>Z.whave){if(Z.sane){J.msg="invalid distance too far back",Z.mode=F7;break}}if(D>Z.wnext)D-=Z.wnext,M=Z.wsize-D;else M=Z.wnext-D;if(D>Z.length)D=Z.length;L=Z.window}else L=X,M=V-Z.offset,D=Z.length;if(D>q)D=q;q-=D,Z.length-=D;do X[V++]=L[M++];while(--D);if(Z.length===0)Z.mode=Ho;break;case zI0:if(q===0)break J;X[V++]=Z.length,q--,Z.mode=Ho;break;case iU1:if(Z.wrap){while(H<32){if(K===0)break J;K--,W|=Y[G++]<<H,H+=8}if(U-=q,J.total_out+=U,Z.total+=U,Z.wrap&4&&U)J.adler=Z.check=Z.flags?E2(Z.check,X,U,V-U):wx(Z.check,X,U,V-U);if(U=q,Z.wrap&4&&(Z.flags?W:BI0(W))!==Z.check){J.msg="incorrect data check",Z.mode=F7;break}W=0,H=0}Z.mode=FI0;case FI0:if(Z.wrap&&Z.flags){while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&4&&W!==(Z.total&4294967295)){J.msg="incorrect length check",Z.mode=F7;break}W=0,H=0}Z.mode=UI0;case UI0:g=tB4;break J;case F7:g=dI0;break J;case lI0:return cI0;case iI0:default:return nX}if(J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,Z.wsize||U!==J.avail_out&&Z.mode<F7&&(Z.mode<iU1||Q!==iE0)){if(sI0(J,J.output,J.next_out,U-J.avail_out));}if(z-=J.avail_in,U-=J.avail_out,J.total_in+=z,J.total_out+=U,Z.total+=U,Z.wrap&4&&U)J.adler=Z.check=Z.flags?E2(Z.check,X,U,J.next_out-U):wx(Z.check,X,U,J.next_out-U);if(J.data_type=Z.bits+(Z.last?64:0)+(Z.mode===eW?128:0)+(Z.mode===Wo||Z.mode===lU1?256:0),(z===0&&U===0||Q===iE0)&&g===CM)g=JN4;return g},qN4=(J)=>{if(SM(J))return nX;let Q=J.state;if(Q.window)Q.window=null;return J.state=null,CM},WN4=(J,Q)=>{if(SM(J))return nX;let Z=J.state;if((Z.wrap&2)===0)return nX;return Z.head=Q,Q.done=!1,CM},HN4=(J,Q)=>{let Z=Q.length,Y,X,G;if(SM(J))return nX;if(Y=J.state,Y.wrap!==0&&Y.mode!==Bo)return nX;if(Y.mode===Bo){if(X=1,X=wx(X,Q,Z,0),X!==Y.check)return dI0}if(G=sI0(J,Q,Z,Z),G)return Y.mode=lI0,cI0;return Y.havedict=1,CM},zN4,FN4,UN4,BN4,NN4,DN4,MN4,LN4,AN4,ON4="pako inflate (from Nodeca project)",QH,EN4,tI0,IN4,PN4,Px,oU1,rU1,TN4,DI0,RN4,jN4,SN4,_N4,kN4,yN4,xN4,vN4,fN4,hN4,bN4,mN4,gN4,uN4,pN4,dN4,cN4,lN4,iN4,nN4,aN4,oN4,rN4,sN4,eI0;var JP0=B1(()=>{/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */Mx=Tx+1+GB1,LI0=2*Mx+1,sU1=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),zo=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),KU4=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),EI0=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),JH=Array((Mx+2)*2);rI(JH);Bx=Array(nI*2);rI(Bx);Lx=Array(qU4);rI(Lx);Ax=Array(GU4-$U4+1);rI(Ax);qB1=Array(GB1);rI(qB1);Fo=Array(nI);rI(Fo);AU4=NU4,OU4=kI0,wU4=MU4,EU4=LU4,IU4=DU4,PU4={_tr_init:AU4,_tr_stored_block:OU4,_tr_flush_block:wU4,_tr_tally:EU4,_tr_align:IU4},wx=TU4,CU4=new Uint32Array(RU4()),E2=jU4,TM={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},jM={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:SU4,_tr_stored_block:eU1,_tr_flush_block:_U4,_tr_tally:eF,_tr_align:kU4}=PU4,{Z_NO_FLUSH:JU,Z_PARTIAL_FLUSH:yU4,Z_FULL_FLUSH:xU4,Z_FINISH:iX,Z_BLOCK:mE0,Z_OK:JJ,Z_STREAM_END:gE0,Z_STREAM_ERROR:kK,Z_DATA_ERROR:vU4,Z_BUF_ERROR:uU1,Z_DEFAULT_COMPRESSION:fU4,Z_FILTERED:hU4,Z_HUFFMAN_ONLY:Vo,Z_RLE:bU4,Z_FIXED:mU4,Z_DEFAULT_STRATEGY:gU4,Z_UNKNOWN:uU4,Z_DEFLATED:No}=jM,JB1=iU4+1+lU4,oU4=2*JB1+1,yK=tF+D9+1,QU=JB4;Ux=[new SK(0,0,0,0,xI0),new SK(4,4,8,4,pU1),new SK(4,5,16,8,pU1),new SK(4,6,32,32,pU1),new SK(4,4,16,16,lI),new SK(8,16,32,32,lI),new SK(8,16,128,128,lI),new SK(8,32,128,256,lI),new SK(32,128,258,1024,lI),new SK(32,258,258,4096,lI)];WB4=GB4,HB4=hI0,zB4=fI0,FB4=vI0,UB4=$B4,BB4=VB4,NB4=KB4,DB4=qB4,Nx={deflateInit:WB4,deflateInit2:HB4,deflateReset:zB4,deflateResetKeep:FB4,deflateSetHeader:UB4,deflate:BB4,deflateEnd:NB4,deflateSetDictionary:DB4,deflateInfo:MB4},Do={assign:AB4,flattenChunks:OB4};try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(J){bI0=!1}Ex=new Uint8Array(256);for(let J=0;J<256;J++)Ex[J]=J>=252?6:J>=248?5:J>=240?4:J>=224?3:J>=192?2:1;Ex[254]=Ex[254]=1;Ix={string2buf:wB4,buf2string:IB4,utf8border:PB4};mI0=TB4,gI0=Object.prototype.toString,{Z_NO_FLUSH:RB4,Z_SYNC_FLUSH:CB4,Z_FULL_FLUSH:jB4,Z_FINISH:SB4,Z_OK:Uo,Z_STREAM_END:_B4,Z_DEFAULT_COMPRESSION:kB4,Z_DEFAULT_STRATEGY:yB4,Z_DEFLATED:xB4}=jM;Cx.prototype.push=function(J,Q){let Z=this.strm,Y=this.options.chunkSize,X,G;if(this.ended)return!1;if(Q===~~Q)G=Q;else G=Q===!0?SB4:RB4;if(typeof J==="string")Z.input=Ix.string2buf(J);else if(gI0.call(J)==="[object ArrayBuffer]")Z.input=new Uint8Array(J);else Z.input=J;Z.next_in=0,Z.avail_in=Z.input.length;for(;;){if(Z.avail_out===0)Z.output=new Uint8Array(Y),Z.next_out=0,Z.avail_out=Y;if((G===CB4||G===jB4)&&Z.avail_out<=6){this.onData(Z.output.subarray(0,Z.next_out)),Z.avail_out=0;continue}if(X=Nx.deflate(Z,G),X===_B4){if(Z.next_out>0)this.onData(Z.output.subarray(0,Z.next_out));return X=Nx.deflateEnd(this.strm),this.onEnd(X),this.ended=!0,X===Uo}if(Z.avail_out===0){this.onData(Z.output);continue}if(G>0&&Z.next_out>0){this.onData(Z.output.subarray(0,Z.next_out)),Z.avail_out=0;continue}if(Z.avail_in===0)break}return!0};Cx.prototype.onData=function(J){this.chunks.push(J)};Cx.prototype.onEnd=function(J){if(J===Uo)this.result=Do.flattenChunks(this.chunks);this.chunks=[],this.err=J,this.msg=this.strm.msg};hB4=Cx,bB4=HB1,mB4=vB4,gB4=fB4,uB4=jM,pB4={Deflate:hB4,deflate:bB4,deflateRaw:mB4,gzip:gB4,constants:uB4},lB4=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),iB4=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),nB4=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),aB4=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),Dx=oB4,{Z_FINISH:iE0,Z_BLOCK:sB4,Z_TREES:qo,Z_OK:CM,Z_STREAM_END:tB4,Z_NEED_DICT:eB4,Z_STREAM_ERROR:nX,Z_DATA_ERROR:dI0,Z_MEM_ERROR:cI0,Z_BUF_ERROR:JN4,Z_DEFLATED:nE0}=jM,XN4=YN4;zN4=aI0,FN4=oI0,UN4=nI0,BN4=GN4,NN4=rI0,DN4=KN4,MN4=qN4,LN4=WN4,AN4=HN4,QH={inflateReset:zN4,inflateReset2:FN4,inflateResetKeep:UN4,inflateInit:BN4,inflateInit2:NN4,inflate:DN4,inflateEnd:MN4,inflateGetHeader:LN4,inflateSetDictionary:AN4,inflateInfo:ON4};EN4=wN4,tI0=Object.prototype.toString,{Z_NO_FLUSH:IN4,Z_FINISH:PN4,Z_OK:Px,Z_STREAM_END:oU1,Z_NEED_DICT:rU1,Z_STREAM_ERROR:TN4,Z_DATA_ERROR:DI0,Z_MEM_ERROR:RN4}=jM;jx.prototype.push=function(J,Q){let Z=this.strm,Y=this.options.chunkSize,X=this.options.dictionary,G,V,K;if(this.ended)return!1;if(Q===~~Q)V=Q;else V=Q===!0?PN4:IN4;if(tI0.call(J)==="[object ArrayBuffer]")Z.input=new Uint8Array(J);else Z.input=J;Z.next_in=0,Z.avail_in=Z.input.length;for(;;){if(Z.avail_out===0)Z.output=new Uint8Array(Y),Z.next_out=0,Z.avail_out=Y;if(G=QH.inflate(Z,V),G===rU1&&X){if(G=QH.inflateSetDictionary(Z,X),G===Px)G=QH.inflate(Z,V);else if(G===DI0)G=rU1}while(Z.avail_in>0&&G===oU1&&Z.state.wrap>0&&J[Z.next_in]!==0)QH.inflateReset(Z),G=QH.inflate(Z,V);switch(G){case TN4:case DI0:case rU1:case RN4:return this.onEnd(G),this.ended=!0,!1}if(K=Z.avail_out,Z.next_out){if(Z.avail_out===0||G===oU1)if(this.options.to==="string"){let q=Ix.utf8border(Z.output,Z.next_out),W=Z.next_out-q,H=Ix.buf2string(Z.output,q);if(Z.next_out=W,Z.avail_out=Y-W,W)Z.output.set(Z.output.subarray(q,q+W),0);this.onData(H)}else this.onData(Z.output.length===Z.next_out?Z.output:Z.output.subarray(0,Z.next_out))}if(G===Px&&K===0)continue;if(G===oU1)return G=QH.inflateEnd(this.strm),this.onEnd(G),this.ended=!0,!0;if(Z.avail_in===0)break}return!0};jx.prototype.onData=function(J){this.chunks.push(J)};jx.prototype.onEnd=function(J){if(J===Px)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=Do.flattenChunks(this.chunks);this.chunks=[],this.err=J,this.msg=this.strm.msg};jN4=jx,SN4=zB1,_N4=CN4,kN4=zB1,yN4=jM,xN4={Inflate:jN4,inflate:SN4,inflateRaw:_N4,ungzip:kN4,constants:yN4},{Deflate:vN4,deflate:fN4,deflateRaw:hN4,gzip:bN4}=pB4,{Inflate:mN4,inflate:gN4,inflateRaw:uN4,ungzip:pN4}=xN4,dN4=vN4,cN4=fN4,lN4=hN4,iN4=bN4,nN4=mN4,aN4=gN4,oN4=uN4,rN4=pN4,sN4=jM,eI0={Deflate:dN4,deflate:cN4,deflateRaw:lN4,gzip:iN4,Inflate:nN4,inflate:aN4,inflateRaw:oN4,ungzip:rN4,constants:sN4}});var ZP0={};Q9(ZP0,{internalAPIClient:()=>K5,createInternalAPIClient:()=>QP0});function eN4(J){if(new Blob([J]).size<=tN4)return{body:J};return{body:eI0.gzip(J),headers:{"Content-Encoding":"gzip"}}}function QP0(J){return new Proxy({},{get:(Q,Z)=>{return async(...Y)=>{let X=Y.at(1),G=Y.at(0);if(!X?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:V,headers:K={}}=eN4(JSON.stringify({method:Z,params:G})),q=await U3("/api/internal?"+encodeURIComponent(Z),{method:"POST",body:V,headers:K,signal:X?.signal},X.config);if(!q.ok)throw Error(`API request for ${Z} failed: ${q.status}`);return await q.json()}}})}var tN4=10485760,K5;var gG=B1(()=>{JP0();RZ();K5=QP0(fetch)});function JD4(J){if(J.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=J.proxy;if(J.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=J.proxy}function YP0(J){return J.config.pipe(B4(({settings:Q,secrets:Z})=>{return h6(async()=>{return await Z.getToken("apiKey",Q.url)!==void 0})}))}function Sx(J,Q,Z){let Y=Z?`/threads/${Q}/${Z}`:`/threads/${Q}`;return new URL(Y,J)}async function U3(J,Q,Z){let Y=Q?.signal||void 0,X=await Z.getLatest(Y);return FB1(X,J,Q)}async function XP0(J,Q,Z,Y){let X=await J.get(Q);if(!X)throw Error(`Thread not found: ${Q}`);let G=await K5.shareThreadWithOperator({threadData:X,message:Y||void 0},{config:Z});if(!G.ok)throw Error(`Failed to share thread: ${G.error.message}`)}async function Lo(J,Q){let Z=await U3("/api/telemetry",{method:"POST",redirect:"manual",body:J},Q);if(!Z.ok){let Y=await Z.text(),X;try{X=JSON.parse(Y).error||`HTTP ${Z.status}`}catch{X=Y||`HTTP ${Z.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function FB1(J,Q,Z){if(Q.startsWith("http:")||Q.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!Q.startsWith("/"))throw Error("pathAndQuery must start with /");let Y=J.settings.url;if(!Y)throw Error("amp.url is not set");let X=await J.secrets.getToken("apiKey",Y);JD4({proxy:J.settings.proxy});let G=new URL(Q,Y);try{return await fetch(G,{...Z,headers:{...Z?.headers,...W3(),"Content-Type":"application/json",...X?{Authorization:`Bearer ${X}`}:{}}})}catch(V){throw x.error("Amp server fetch failed",V,{name:"fetchFromAmpServer",url:G.toString(),method:Z?.method??"GET",errorMessage:V instanceof Error?V.message:String(V),errorCause:V instanceof Error&&V.cause?String(V.cause):void 0}),V}}var RZ=B1(()=>{i0();U0();DZ();gG()});function ZH(J,Q){if(J=J.replace(/\.git$/,""),!URL.canParse(J))return null;let Z=new URL(J);if(Z.protocol!=="https:"||Z.port||Z.username||Z.password)return null;let Y=Z.pathname.replace(/^\//,"").replace(/\/$/,"");if(!Y)return null;let X=`${Z.protocol}//${Z.host}`;if(Z.hostname==="github.com"){if(Q?.provider&&Q.provider!=="github")return null;return{name:Y,instanceURL:"https://github.com",provider:"github"}}if(!Q?.gitlabInstanceURL)return null;let G=new URL(Q.gitlabInstanceURL);if(Z.protocol===G.protocol&&Z.host===G.host){if(Q?.provider&&Q.provider!=="gitlab")return null;return{name:Y,instanceURL:X,provider:"gitlab"}}return null}async function y3(J,Q={},Z){let Y=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await FB1(Z,Y,{method:V,headers:G,body:X?JSON.stringify(X):void 0,...K});if(q.status===304)return{ok:!0,status:q.status,notModified:!0,headers:{etag:q.headers.get("etag")||void 0}};if(!q.ok)return{ok:!1,status:q.status,statusText:q.statusText};let W=await q.json();return{ok:!0,status:q.status,data:W,headers:{location:q.headers.get("location")||void 0,etag:q.headers.get("etag")||void 0}}}var xK=B1(()=>{RZ()});async function FP0(J,Q,Z,Y,X){let G=ZH(J,{provider:"github"})?.name;if(!G)throw Error("Invalid GitHub repository URL");let{filePattern:V,limit:K,offset:q=0}=Z,W=`repos/${G}/git/trees/${Q??"HEAD"}?recursive=1`,H=await y3(W,{signal:Y},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let U=H.data.tree.filter((A)=>A.type==="blob").map((A)=>A.path),D=zP0.default(V),M=U.filter((A)=>D(A));return{files:K?M.slice(q,q+K):M.slice(q),truncated:H.data.truncated}}var zP0;var UP0=B1(()=>{xK();zP0=K6(uk(),1)});function yx(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function t6(J,Q,Z,Y,X){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?X.call(J,Z):X?X.value=Z:Q.set(J,Z),Z}function P0(J,Q,Z,Y){if(Z==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!Y:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?Y:Z==="a"?Y.call(J):Y?Y.value:Q.get(J)}var YH=()=>{};var MB1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return MB1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Z=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^Z()&15>>+Y/4).toString(16))};function XH(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var vx=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var T4,o3,aJ,_M,fx,hx,bx,mx,gx,ux,px,dx,cx;var aX=B1(()=>{T4=class T4 extends Error{};o3=class o3 extends T4{constructor(J,Q,Z,Y){super(`${o3.makeMessage(J,Q,Z)}`);this.status=J,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Q}static makeMessage(J,Q,Z){let Y=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Z;if(J&&Y)return`${J} ${Y}`;if(J)return`${J} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate(J,Q,Z,Y){if(!J||!Y)return new _M({message:Z,cause:vx(Q)});let X=Q;if(J===400)return new hx(J,X,Z,Y);if(J===401)return new bx(J,X,Z,Y);if(J===403)return new mx(J,X,Z,Y);if(J===404)return new gx(J,X,Z,Y);if(J===409)return new ux(J,X,Z,Y);if(J===422)return new px(J,X,Z,Y);if(J===429)return new dx(J,X,Z,Y);if(J>=500)return new cx(J,X,Z,Y);return new o3(J,X,Z,Y)}};aJ=class aJ extends o3{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};_M=class _M extends o3{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};fx=class fx extends _M{constructor({message:J}={}){super({message:J??"Request timed out."})}};hx=class hx extends o3{};bx=class bx extends o3{};mx=class mx extends o3{};gx=class gx extends o3{};ux=class ux extends o3{};px=class px extends o3{};dx=class dx extends o3{};cx=class cx extends o3{}});function To(J){if(typeof J!=="object")return{};return J??{}}function IP0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function PP0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var LD4,EP0=(J)=>{return LD4.test(J)},LB1=(J)=>(LB1=Array.isArray,LB1(J)),AB1,TP0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new T4(`${J} must be an integer`);if(Q<0)throw new T4(`${J} must be a positive integer`);return Q},Ro=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var kM=B1(()=>{aX();LD4=/^[a-z][a-z0-9+.-]*:/i,AB1=LB1});var RP0=(J)=>new Promise((Q)=>setTimeout(Q,J));var YU="0.71.0";function AD4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function wD4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Z}of J){let Y=Z.exec(navigator.userAgent);if(Y){let X=Y[1]||0,G=Y[2]||0,V=Y[3]||0;return{browser:Q,version:`${X}.${G}.${V}`}}}return null}var _P0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},OD4=()=>{let J=AD4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":jP0(Deno.build.os),"X-Stainless-Arch":CP0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":jP0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":CP0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=wD4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},CP0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},jP0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},SP0,kP0=()=>{return SP0??(SP0=OD4())};var OB1=()=>{};function yP0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function wB1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function Co(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return wB1({start(){},async pull(Z){let{done:Y,value:X}=await Q.next();if(Y)Z.close();else Z.enqueue(X)},async cancel(){await Q.return?.()}})}function lx(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Z=await Q.read();if(Z?.done)Q.releaseLock();return Z}catch(Z){throw Q.releaseLock(),Z}},async return(){let Z=Q.cancel();return Q.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xP0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Z=Q.cancel();Q.releaseLock(),await Z}var vP0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function bP0(J){let Q=0;for(let X of J)Q+=X.length;let Z=new Uint8Array(Q),Y=0;for(let X of J)Z.set(X,Y),Y+=X.length;return Z}function ix(J){let Q;return(fP0??(Q=new globalThis.TextEncoder,fP0=Q.encode.bind(Q)))(J)}function EB1(J){let Q;return(hP0??(Q=new globalThis.TextDecoder,hP0=Q.decode.bind(Q)))(J)}var fP0,hP0;class XU{constructor(){OY.set(this,void 0),wY.set(this,void 0),t6(this,OY,new Uint8Array,"f"),t6(this,wY,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?ix(J):J;t6(this,OY,bP0([P0(this,OY,"f"),Q]),"f");let Z=[],Y;while((Y=PD4(P0(this,OY,"f"),P0(this,wY,"f")))!=null){if(Y.carriage&&P0(this,wY,"f")==null){t6(this,wY,Y.index,"f");continue}if(P0(this,wY,"f")!=null&&(Y.index!==P0(this,wY,"f")+1||Y.carriage)){Z.push(EB1(P0(this,OY,"f").subarray(0,P0(this,wY,"f")-1))),t6(this,OY,P0(this,OY,"f").subarray(P0(this,wY,"f")),"f"),t6(this,wY,null,"f");continue}let X=P0(this,wY,"f")!==null?Y.preceding-1:Y.preceding,G=EB1(P0(this,OY,"f").subarray(0,X));Z.push(G),t6(this,OY,P0(this,OY,"f").subarray(Y.index),"f"),t6(this,wY,null,"f")}return Z}flush(){if(!P0(this,OY,"f").length)return[];return this.decode(`
152
+ ${U}`));return}A();let I=z.slice(0,X);W({files:I,remaining:z.length-I.length})})})}var wE0,oF4=({args:J},{dirs:Q,config:Z})=>{if(Q.length===0)return new t1((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Y={};if(J.limit!==void 0)Y.limit=J.limit;if(J.offset!==void 0)Y.offset=J.offset;return EE0(Q,J.filePattern,Y,Z)},kU1=500000,yU1=1e6;var xU1=B1(()=>{i6();i0();U0();AM();qx();CK();wE0=K6(kW(),1)});function nJ(J){return J instanceof e2||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function PE0(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function TE0(J){return{readFile:J.readFile,readBinaryFile:J.readBinaryFile,stat:J.stat,getMtime:J.getMtime,realpath:J.realpath,readdir:J.readdir,findFiles:J.findFiles,access:J.access,watch:J.watch}}function RE0(J){return{...J,writeFile:()=>Promise.reject(Error("Write operations not implemented")),delete:()=>Promise.reject(Error("Write operations not implemented")),mkdirp:()=>Promise.reject(Error("Write operations not implemented")),rename:()=>Promise.reject(Error("Write operations not implemented")),isExclusiveWriterFor:()=>Promise.resolve(!1)}}function bG(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function cI(J,Q,Z){try{return await J.readFile(Q,Z)}catch(Y){if(Y instanceof e2)return null;throw Y}}async function Wx(J,Q,Z){try{return await J.access(Q,Z),!0}catch(Y){if(nJ(Y))return!1;throw Y}}var e2;var jQ=B1(()=>{e2=class e2 extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});function fU1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function Go(J,Q){let Z;if(typeof J==="object"&&J!==null&&"uri"in J&&typeof J.uri==="string")Z=J.uri;else if(typeof J==="string"||h0.isUri(J))Z=J;else throw Error("Invalid base URI");if(J=m4(Z),J.scheme!=="file")throw Error(`Expected file:// scheme, got ${J.scheme}://`);return Q?n0.joinPath(J,Q):J}function vU1(J,Q){Q=m4(Q);let Z,Y;for(let X of J.trees){if(!X.uri)continue;let G=hJ(X.uri);if(n0.hasPrefix(Q,G)){let V=n0.relativePath(G,Q);if(V===null)continue;if(Y===void 0||V.length<Y.length)Y=V,Z=X}}if(!Z||Y===void 0)return null;return{tree:Z,filePath:Y}}function QU4(J){return Array.isArray(J)}function ZU4(J){let Q;if(J===void 0)Q=void 0;else if(QU4(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??JU4}function _E0(J,Q){for(let Y of J.trees){if(!Y.uri)continue;let X=hJ(Y.uri);if(n0.hasPrefix(Q,X))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let Y of J.trees){if(!Y.uri)continue;let X=hJ(Y.uri);if(n0.hasPrefix(X,Q))Z.push(X)}return{isImplied:Z.length>0,childMountPoints:Z}}function Hx(J){return{trees:ZU4(J)}}function yE0(J,Q){let Z={...J.os,mountedTree:kE0},Y=new Map;function X(K){if(!K.fs||K.fs==="os")return Z;if(!K.uri)throw Error("Tree URI is required");if(!K.repository)throw Error(`Tree with FS type ${K.fs} requires repository field`);let q={uri:K.uri,repository:K.repository,fs:K.fs},W=`${K.fs}:${JSON.stringify(K)}`,H=Y.get(W);if(!H){let z=J[K.fs];if(!z)throw Error(`No file system implementation found for: ${K.fs}`);H={...z(q,Q),mountedTree:q},Y.set(W,H)}return H}function G(K){return K.trees.some((q)=>q.fs&&q.fs!=="os")}function V(K,q){let W=K.trees.map((z)=>({mountPoint:z.uri,fs:X(z)}));function H(z){if(!G(K))return q?{...q(Z),mountedTree:Z.mountedTree}:Z;let U=vU1(K,z)?.tree;if(!U)throw new e2(z);let D=W.find((M)=>n0.equalURIs(M.mountPoint,U.uri))?.fs;if(!D)throw Error(`No file system found for URI: ${z}`);return q?{...q(D),mountedTree:D.mountedTree}:D}return{map(z){if(q)throw Error("Cannot use both prepare and prepare2");return V(K,z)},mapReader(z){if(q)throw Error("Cannot use both prepare and prepare2");let U=V(K,z);return{...TE0(U),mountedFileSystemForURI:U.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:U.mapReader,__isFileSystemWithMountedTrees:U.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:U.__isImmutableBaseFileSystem}},mountedFileSystemForURI(z){return H(z)},readFile:async(z,U)=>H(z).readFile(z,U),readBinaryFile:async(z,U)=>H(z).readBinaryFile(z,U),getMtime:async(z,U)=>H(z).getMtime(z,U),realpath:async(z,U)=>H(z).realpath(z,U),access:async(z,U)=>H(z).access(z,U),findFiles:async(z,U)=>H(z.base).findFiles(z,U),stat:async(z,U)=>{let D=m4(z),{isImplied:M}=_E0(K,D);if(M)return{size:0,isDirectory:!0};return H(z).stat(z,U)},rename:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`rename(${z}) is not supported by this file system`);return D.rename(z,U)},writeFile:async(z,U,D)=>{let M=H(z);if(bG(M))throw Error(`writeFile(${z}) is not supported by this file system`);return M.writeFile(z,U,D)},mkdirp:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`mkdirp(${z}) is not supported by this file system`);return D.mkdirp(z,U)},delete:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`delete(${z}) is not supported by this file system`);return D.delete(z,U)},readdir:async(z,U)=>{z=m4(z);let{isImplied:D,childMountPoints:M}=_E0(K,z);if(D){let A=new Set;for(let E of M){let I=n0.relativePath(z,E);if(I){let P=I.split("/")[0];if(P)A.add(P)}}return Array.from(A).map((E)=>({uri:n0.joinPath(z,E),isDirectory:!0}))}return H(z).readdir(z,U)},watch:(z,U)=>{if(!G(K))return Z.watch(z,U);if(!h0.isUri(z))throw Error("Watch with glob is not yet implemented in the file system router");let D=H(z);if(bG(D))return _X;return D.watch(z,U)},isExclusiveWriterFor:async(z,U)=>{let D=H(z);if(bG(D))throw Error(`isExclusiveWriterFor(${z}) is not supported by this file system`);return D.isExclusiveWriterFor(z,U)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:V,fileSystemForURI:(K,q)=>X(vU1(K,q)?.tree??kE0),osFileSystem:Z}}function rF(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let Y=vU1(Hx(Z.thread),Z.dir)?.tree.fs??"os",X=J[Y];if(X)return j3(X()).pipe(B4((G)=>G(Q,Z)));throw Error(`Unsupported file system: ${Y}`)}}var JU4,kE0;var mG=B1(()=>{i6();i0();jQ();JU4=[];kE0={fs:"os",uri:"file:///"}});function rI(J){let Q=J.length;while(--Q>=0)J[Q]=0}function bU1(J,Q,Z,Y,X){this.static_tree=J,this.extra_bits=Q,this.extra_base=Z,this.elems=Y,this.max_length=X,this.has_stree=J&&J.length}function mU1(J,Q){this.dyn_tree=J,this.max_code=0,this.stat_desc=Q}function SK(J,Q,Z,Y,X){this.good_length=J,this.max_lazy=Q,this.nice_length=Z,this.max_chain=Y,this.func=X}function XB4(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=No,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(oU4*2),this.dyn_dtree=new Uint16Array((2*nU4+1)*2),this.bl_tree=new Uint16Array((2*aU4+1)*2),sF(this.dyn_ltree),sF(this.dyn_dtree),sF(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(rU4+1),this.heap=new Uint16Array(2*JB1+1),sF(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*JB1+1),sF(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function TB4(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function Cx(J){this.options=Do.assign({level:kB4,method:xB4,chunkSize:16384,windowBits:15,memLevel:8,strategy:yB4},J||{});let Q=this.options;if(Q.raw&&Q.windowBits>0)Q.windowBits=-Q.windowBits;else if(Q.gzip&&Q.windowBits>0&&Q.windowBits<16)Q.windowBits+=16;this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new mI0,this.strm.avail_out=0;let Z=Nx.deflateInit2(this.strm,Q.level,Q.method,Q.windowBits,Q.memLevel,Q.strategy);if(Z!==Uo)throw Error(TM[Z]);if(Q.header)Nx.deflateSetHeader(this.strm,Q.header);if(Q.dictionary){let Y;if(typeof Q.dictionary==="string")Y=Ix.string2buf(Q.dictionary);else if(gI0.call(Q.dictionary)==="[object ArrayBuffer]")Y=new Uint8Array(Q.dictionary);else Y=Q.dictionary;if(Z=Nx.deflateSetDictionary(this.strm,Y),Z!==Uo)throw Error(TM[Z]);this._dict_set=!0}}function HB1(J,Q){let Z=new Cx(Q);if(Z.push(J,!0),Z.err)throw Z.msg||TM[Z.err];return Z.result}function vB4(J,Q){return Q=Q||{},Q.raw=!0,HB1(J,Q)}function fB4(J,Q){return Q=Q||{},Q.gzip=!0,HB1(J,Q)}function $N4(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function wN4(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}function jx(J){this.options=Do.assign({chunkSize:65536,windowBits:15,to:""},J||{});let Q=this.options;if(Q.raw&&Q.windowBits>=0&&Q.windowBits<16){if(Q.windowBits=-Q.windowBits,Q.windowBits===0)Q.windowBits=-15}if(Q.windowBits>=0&&Q.windowBits<16&&!(J&&J.windowBits))Q.windowBits+=32;if(Q.windowBits>15&&Q.windowBits<48){if((Q.windowBits&15)===0)Q.windowBits|=15}this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new mI0,this.strm.avail_out=0;let Z=QH.inflateInit2(this.strm,Q.windowBits);if(Z!==Px)throw Error(TM[Z]);if(this.header=new EN4,QH.inflateGetHeader(this.strm,this.header),Q.dictionary){if(typeof Q.dictionary==="string")Q.dictionary=Ix.string2buf(Q.dictionary);else if(tI0.call(Q.dictionary)==="[object ArrayBuffer]")Q.dictionary=new Uint8Array(Q.dictionary);if(Q.raw){if(Z=QH.inflateSetDictionary(this.strm,Q.dictionary),Z!==Px)throw Error(TM[Z])}}}function zB1(J,Q){let Z=new jx(Q);if(Z.push(J),Z.err)throw Z.msg||TM[Z.err];return Z.result}function CN4(J,Q){return Q=Q||{},Q.raw=!0,zB1(J,Q)}var YU4=0,MI0=1,XU4=2,$U4=3,GU4=258,GB1=29,Tx=256,Mx,nI=30,VB1=19,LI0,EM=15,hU1=16,VU4=7,KB1=256,AI0=16,OI0=17,wI0=18,sU1,zo,KU4,EI0,qU4=512,JH,Bx,Lx,Ax,qB1,Fo,II0,PI0,TI0,RI0=(J)=>{return J<256?Lx[J]:Lx[256+(J>>>7)]},Ox=(J,Q)=>{J.pending_buf[J.pending++]=Q&255,J.pending_buf[J.pending++]=Q>>>8&255},TZ=(J,Q,Z)=>{if(J.bi_valid>hU1-Z)J.bi_buf|=Q<<J.bi_valid&65535,Ox(J,J.bi_buf),J.bi_buf=Q>>hU1-J.bi_valid,J.bi_valid+=Z-hU1;else J.bi_buf|=Q<<J.bi_valid&65535,J.bi_valid+=Z},_K=(J,Q,Z)=>{TZ(J,Z[Q*2],Z[Q*2+1])},CI0=(J,Q)=>{let Z=0;do Z|=J&1,J>>>=1,Z<<=1;while(--Q>0);return Z>>>1},WU4=(J)=>{if(J.bi_valid===16)Ox(J,J.bi_buf),J.bi_buf=0,J.bi_valid=0;else if(J.bi_valid>=8)J.pending_buf[J.pending++]=J.bi_buf&255,J.bi_buf>>=8,J.bi_valid-=8},HU4=(J,Q)=>{let{dyn_tree:Z,max_code:Y}=Q,X=Q.stat_desc.static_tree,G=Q.stat_desc.has_stree,V=Q.stat_desc.extra_bits,K=Q.stat_desc.extra_base,q=Q.stat_desc.max_length,W,H,z,U,D,M,L=0;for(U=0;U<=EM;U++)J.bl_count[U]=0;Z[J.heap[J.heap_max]*2+1]=0;for(W=J.heap_max+1;W<LI0;W++){if(H=J.heap[W],U=Z[Z[H*2+1]*2+1]+1,U>q)U=q,L++;if(Z[H*2+1]=U,H>Y)continue;if(J.bl_count[U]++,D=0,H>=K)D=V[H-K];if(M=Z[H*2],J.opt_len+=M*(U+D),G)J.static_len+=M*(X[H*2+1]+D)}if(L===0)return;do{U=q-1;while(J.bl_count[U]===0)U--;J.bl_count[U]--,J.bl_count[U+1]+=2,J.bl_count[q]--,L-=2}while(L>0);for(U=q;U!==0;U--){H=J.bl_count[U];while(H!==0){if(z=J.heap[--W],z>Y)continue;if(Z[z*2+1]!==U)J.opt_len+=(U-Z[z*2+1])*Z[z*2],Z[z*2+1]=U;H--}}},jI0=(J,Q,Z)=>{let Y=Array(EM+1),X=0,G,V;for(G=1;G<=EM;G++)X=X+Z[G-1]<<1,Y[G]=X;for(V=0;V<=Q;V++){let K=J[V*2+1];if(K===0)continue;J[V*2]=CI0(Y[K]++,K)}},zU4=()=>{let J,Q,Z,Y,X,G=Array(EM+1);Z=0;for(Y=0;Y<GB1-1;Y++){qB1[Y]=Z;for(J=0;J<1<<sU1[Y];J++)Ax[Z++]=Y}Ax[Z-1]=Y,X=0;for(Y=0;Y<16;Y++){Fo[Y]=X;for(J=0;J<1<<zo[Y];J++)Lx[X++]=Y}X>>=7;for(;Y<nI;Y++){Fo[Y]=X<<7;for(J=0;J<1<<zo[Y]-7;J++)Lx[256+X++]=Y}for(Q=0;Q<=EM;Q++)G[Q]=0;J=0;while(J<=143)JH[J*2+1]=8,J++,G[8]++;while(J<=255)JH[J*2+1]=9,J++,G[9]++;while(J<=279)JH[J*2+1]=7,J++,G[7]++;while(J<=287)JH[J*2+1]=8,J++,G[8]++;jI0(JH,Mx+1,G);for(J=0;J<nI;J++)Bx[J*2+1]=5,Bx[J*2]=CI0(J,5);II0=new bU1(JH,sU1,Tx+1,Mx,EM),PI0=new bU1(Bx,zo,0,nI,EM),TI0=new bU1([],KU4,0,VB1,VU4)},SI0=(J)=>{let Q;for(Q=0;Q<Mx;Q++)J.dyn_ltree[Q*2]=0;for(Q=0;Q<nI;Q++)J.dyn_dtree[Q*2]=0;for(Q=0;Q<VB1;Q++)J.bl_tree[Q*2]=0;J.dyn_ltree[KB1*2]=1,J.opt_len=J.static_len=0,J.sym_next=J.matches=0},_I0=(J)=>{if(J.bi_valid>8)Ox(J,J.bi_buf);else if(J.bi_valid>0)J.pending_buf[J.pending++]=J.bi_buf;J.bi_buf=0,J.bi_valid=0},xE0=(J,Q,Z,Y)=>{let X=Q*2,G=Z*2;return J[X]<J[G]||J[X]===J[G]&&Y[Q]<=Y[Z]},gU1=(J,Q,Z)=>{let Y=J.heap[Z],X=Z<<1;while(X<=J.heap_len){if(X<J.heap_len&&xE0(Q,J.heap[X+1],J.heap[X],J.depth))X++;if(xE0(Q,Y,J.heap[X],J.depth))break;J.heap[Z]=J.heap[X],Z=X,X<<=1}J.heap[Z]=Y},vE0=(J,Q,Z)=>{let Y,X,G=0,V,K;if(J.sym_next!==0)do if(Y=J.pending_buf[J.sym_buf+G++]&255,Y+=(J.pending_buf[J.sym_buf+G++]&255)<<8,X=J.pending_buf[J.sym_buf+G++],Y===0)_K(J,X,Q);else{if(V=Ax[X],_K(J,V+Tx+1,Q),K=sU1[V],K!==0)X-=qB1[V],TZ(J,X,K);if(Y--,V=RI0(Y),_K(J,V,Z),K=zo[V],K!==0)Y-=Fo[V],TZ(J,Y,K)}while(G<J.sym_next);_K(J,KB1,Q)},tU1=(J,Q)=>{let Z=Q.dyn_tree,Y=Q.stat_desc.static_tree,X=Q.stat_desc.has_stree,G=Q.stat_desc.elems,V,K,q=-1,W;J.heap_len=0,J.heap_max=LI0;for(V=0;V<G;V++)if(Z[V*2]!==0)J.heap[++J.heap_len]=q=V,J.depth[V]=0;else Z[V*2+1]=0;while(J.heap_len<2)if(W=J.heap[++J.heap_len]=q<2?++q:0,Z[W*2]=1,J.depth[W]=0,J.opt_len--,X)J.static_len-=Y[W*2+1];Q.max_code=q;for(V=J.heap_len>>1;V>=1;V--)gU1(J,Z,V);W=G;do V=J.heap[1],J.heap[1]=J.heap[J.heap_len--],gU1(J,Z,1),K=J.heap[1],J.heap[--J.heap_max]=V,J.heap[--J.heap_max]=K,Z[W*2]=Z[V*2]+Z[K*2],J.depth[W]=(J.depth[V]>=J.depth[K]?J.depth[V]:J.depth[K])+1,Z[V*2+1]=Z[K*2+1]=W,J.heap[1]=W++,gU1(J,Z,1);while(J.heap_len>=2);J.heap[--J.heap_max]=J.heap[1],HU4(J,Q),jI0(Z,q,J.bl_count)},fE0=(J,Q,Z)=>{let Y,X=-1,G,V=Q[1],K=0,q=7,W=4;if(V===0)q=138,W=3;Q[(Z+1)*2+1]=65535;for(Y=0;Y<=Z;Y++){if(G=V,V=Q[(Y+1)*2+1],++K<q&&G===V)continue;else if(K<W)J.bl_tree[G*2]+=K;else if(G!==0){if(G!==X)J.bl_tree[G*2]++;J.bl_tree[AI0*2]++}else if(K<=10)J.bl_tree[OI0*2]++;else J.bl_tree[wI0*2]++;if(K=0,X=G,V===0)q=138,W=3;else if(G===V)q=6,W=3;else q=7,W=4}},hE0=(J,Q,Z)=>{let Y,X=-1,G,V=Q[1],K=0,q=7,W=4;if(V===0)q=138,W=3;for(Y=0;Y<=Z;Y++){if(G=V,V=Q[(Y+1)*2+1],++K<q&&G===V)continue;else if(K<W)do _K(J,G,J.bl_tree);while(--K!==0);else if(G!==0){if(G!==X)_K(J,G,J.bl_tree),K--;_K(J,AI0,J.bl_tree),TZ(J,K-3,2)}else if(K<=10)_K(J,OI0,J.bl_tree),TZ(J,K-3,3);else _K(J,wI0,J.bl_tree),TZ(J,K-11,7);if(K=0,X=G,V===0)q=138,W=3;else if(G===V)q=6,W=3;else q=7,W=4}},FU4=(J)=>{let Q;fE0(J,J.dyn_ltree,J.l_desc.max_code),fE0(J,J.dyn_dtree,J.d_desc.max_code),tU1(J,J.bl_desc);for(Q=VB1-1;Q>=3;Q--)if(J.bl_tree[EI0[Q]*2+1]!==0)break;return J.opt_len+=3*(Q+1)+5+5+4,Q},UU4=(J,Q,Z,Y)=>{let X;TZ(J,Q-257,5),TZ(J,Z-1,5),TZ(J,Y-4,4);for(X=0;X<Y;X++)TZ(J,J.bl_tree[EI0[X]*2+1],3);hE0(J,J.dyn_ltree,Q-1),hE0(J,J.dyn_dtree,Z-1)},BU4=(J)=>{let Q=4093624447,Z;for(Z=0;Z<=31;Z++,Q>>>=1)if(Q&1&&J.dyn_ltree[Z*2]!==0)return 0;if(J.dyn_ltree[18]!==0||J.dyn_ltree[20]!==0||J.dyn_ltree[26]!==0)return 1;for(Z=32;Z<Tx;Z++)if(J.dyn_ltree[Z*2]!==0)return 1;return 0},bE0=!1,NU4=(J)=>{if(!bE0)zU4(),bE0=!0;J.l_desc=new mU1(J.dyn_ltree,II0),J.d_desc=new mU1(J.dyn_dtree,PI0),J.bl_desc=new mU1(J.bl_tree,TI0),J.bi_buf=0,J.bi_valid=0,SI0(J)},kI0=(J,Q,Z,Y)=>{if(TZ(J,(YU4<<1)+(Y?1:0),3),_I0(J),Ox(J,Z),Ox(J,~Z),Z)J.pending_buf.set(J.window.subarray(Q,Q+Z),J.pending);J.pending+=Z},DU4=(J)=>{TZ(J,MI0<<1,3),_K(J,KB1,JH),WU4(J)},MU4=(J,Q,Z,Y)=>{let X,G,V=0;if(J.level>0){if(J.strm.data_type===2)J.strm.data_type=BU4(J);if(tU1(J,J.l_desc),tU1(J,J.d_desc),V=FU4(J),X=J.opt_len+3+7>>>3,G=J.static_len+3+7>>>3,G<=X)X=G}else X=G=Z+5;if(Z+4<=X&&Q!==-1)kI0(J,Q,Z,Y);else if(J.strategy===4||G===X)TZ(J,(MI0<<1)+(Y?1:0),3),vE0(J,JH,Bx);else TZ(J,(XU4<<1)+(Y?1:0),3),UU4(J,J.l_desc.max_code+1,J.d_desc.max_code+1,V+1),vE0(J,J.dyn_ltree,J.dyn_dtree);if(SI0(J),Y)_I0(J)},LU4=(J,Q,Z)=>{if(J.pending_buf[J.sym_buf+J.sym_next++]=Q,J.pending_buf[J.sym_buf+J.sym_next++]=Q>>8,J.pending_buf[J.sym_buf+J.sym_next++]=Z,Q===0)J.dyn_ltree[Z*2]++;else J.matches++,Q--,J.dyn_ltree[(Ax[Z]+Tx+1)*2]++,J.dyn_dtree[RI0(Q)*2]++;return J.sym_next===J.sym_end},AU4,OU4,wU4,EU4,IU4,PU4,TU4=(J,Q,Z,Y)=>{let X=J&65535|0,G=J>>>16&65535|0,V=0;while(Z!==0){V=Z>2000?2000:Z,Z-=V;do X=X+Q[Y++]|0,G=G+X|0;while(--V);X%=65521,G%=65521}return X|G<<16|0},wx,RU4=()=>{let J,Q=[];for(var Z=0;Z<256;Z++){J=Z;for(var Y=0;Y<8;Y++)J=J&1?3988292384^J>>>1:J>>>1;Q[Z]=J}return Q},CU4,jU4=(J,Q,Z,Y)=>{let X=CU4,G=Y+Z;J^=-1;for(let V=Y;V<G;V++)J=J>>>8^X[(J^Q[V])&255];return J^-1},E2,TM,jM,SU4,eU1,_U4,eF,kU4,JU,yU4,xU4,iX,mE0,JJ,gE0,kK,vU4,uU1,fU4,hU4,Vo,bU4,mU4,gU4,uU4,No,pU4=9,dU4=15,cU4=8,lU4=29,iU4=256,JB1,nU4=30,aU4=19,oU4,rU4=15,D9=3,tF=258,yK,sU4=32,aI=42,WB1=57,QB1=69,ZB1=73,YB1=91,XB1=103,IM=113,Fx=666,SQ=1,sI=2,RM=3,tI=4,tU4=3,PM=(J,Q)=>{return J.msg=TM[Q],Q},uE0=(J)=>{return J*2-(J>4?9:0)},sF=(J)=>{let Q=J.length;while(--Q>=0)J[Q]=0},eU4=(J)=>{let Q,Z,Y,X=J.w_size;Q=J.hash_size,Y=Q;do Z=J.head[--Y],J.head[Y]=Z>=X?Z-X:0;while(--Q);Q=X,Y=Q;do Z=J.prev[--Y],J.prev[Y]=Z>=X?Z-X:0;while(--Q)},JB4=(J,Q,Z)=>(Q<<J.hash_shift^Z)&J.hash_mask,QU,LY=(J)=>{let Q=J.state,Z=Q.pending;if(Z>J.avail_out)Z=J.avail_out;if(Z===0)return;if(J.output.set(Q.pending_buf.subarray(Q.pending_out,Q.pending_out+Z),J.next_out),J.next_out+=Z,Q.pending_out+=Z,J.total_out+=Z,J.avail_out-=Z,Q.pending-=Z,Q.pending===0)Q.pending_out=0},AY=(J,Q)=>{_U4(J,J.block_start>=0?J.block_start:-1,J.strstart-J.block_start,Q),J.block_start=J.strstart,LY(J.strm)},i9=(J,Q)=>{J.pending_buf[J.pending++]=Q},zx=(J,Q)=>{J.pending_buf[J.pending++]=Q>>>8&255,J.pending_buf[J.pending++]=Q&255},$B1=(J,Q,Z,Y)=>{let X=J.avail_in;if(X>Y)X=Y;if(X===0)return 0;if(J.avail_in-=X,Q.set(J.input.subarray(J.next_in,J.next_in+X),Z),J.state.wrap===1)J.adler=wx(J.adler,Q,X,Z);else if(J.state.wrap===2)J.adler=E2(J.adler,Q,X,Z);return J.next_in+=X,J.total_in+=X,X},yI0=(J,Q)=>{let{max_chain_length:Z,strstart:Y}=J,X,G,V=J.prev_length,K=J.nice_match,q=J.strstart>J.w_size-yK?J.strstart-(J.w_size-yK):0,W=J.window,H=J.w_mask,z=J.prev,U=J.strstart+tF,D=W[Y+V-1],M=W[Y+V];if(J.prev_length>=J.good_match)Z>>=2;if(K>J.lookahead)K=J.lookahead;do{if(X=Q,W[X+V]!==M||W[X+V-1]!==D||W[X]!==W[Y]||W[++X]!==W[Y+1])continue;Y+=2,X++;do;while(W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&W[++Y]===W[++X]&&Y<U);if(G=tF-(U-Y),Y=U-tF,G>V){if(J.match_start=Q,V=G,G>=K)break;D=W[Y+V-1],M=W[Y+V]}}while((Q=z[Q&H])>q&&--Z!==0);if(V<=J.lookahead)return V;return J.lookahead},oI=(J)=>{let Q=J.w_size,Z,Y,X;do{if(Y=J.window_size-J.lookahead-J.strstart,J.strstart>=Q+(Q-yK)){if(J.window.set(J.window.subarray(Q,Q+Q-Y),0),J.match_start-=Q,J.strstart-=Q,J.block_start-=Q,J.insert>J.strstart)J.insert=J.strstart;eU4(J),Y+=Q}if(J.strm.avail_in===0)break;if(Z=$B1(J.strm,J.window,J.strstart+J.lookahead,Y),J.lookahead+=Z,J.lookahead+J.insert>=D9){X=J.strstart-J.insert,J.ins_h=J.window[X],J.ins_h=QU(J,J.ins_h,J.window[X+1]);while(J.insert)if(J.ins_h=QU(J,J.ins_h,J.window[X+D9-1]),J.prev[X&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=X,X++,J.insert--,J.lookahead+J.insert<D9)break}}while(J.lookahead<yK&&J.strm.avail_in!==0)},xI0=(J,Q)=>{let Z=J.pending_buf_size-5>J.w_size?J.w_size:J.pending_buf_size-5,Y,X,G,V=0,K=J.strm.avail_in;do{if(Y=65535,G=J.bi_valid+42>>3,J.strm.avail_out<G)break;if(G=J.strm.avail_out-G,X=J.strstart-J.block_start,Y>X+J.strm.avail_in)Y=X+J.strm.avail_in;if(Y>G)Y=G;if(Y<Z&&(Y===0&&Q!==iX||Q===JU||Y!==X+J.strm.avail_in))break;if(V=Q===iX&&Y===X+J.strm.avail_in?1:0,eU1(J,0,0,V),J.pending_buf[J.pending-4]=Y,J.pending_buf[J.pending-3]=Y>>8,J.pending_buf[J.pending-2]=~Y,J.pending_buf[J.pending-1]=~Y>>8,LY(J.strm),X){if(X>Y)X=Y;J.strm.output.set(J.window.subarray(J.block_start,J.block_start+X),J.strm.next_out),J.strm.next_out+=X,J.strm.avail_out-=X,J.strm.total_out+=X,J.block_start+=X,Y-=X}if(Y)$B1(J.strm,J.strm.output,J.strm.next_out,Y),J.strm.next_out+=Y,J.strm.avail_out-=Y,J.strm.total_out+=Y}while(V===0);if(K-=J.strm.avail_in,K){if(K>=J.w_size)J.matches=2,J.window.set(J.strm.input.subarray(J.strm.next_in-J.w_size,J.strm.next_in),0),J.strstart=J.w_size,J.insert=J.strstart;else{if(J.window_size-J.strstart<=K){if(J.strstart-=J.w_size,J.window.set(J.window.subarray(J.w_size,J.w_size+J.strstart),0),J.matches<2)J.matches++;if(J.insert>J.strstart)J.insert=J.strstart}J.window.set(J.strm.input.subarray(J.strm.next_in-K,J.strm.next_in),J.strstart),J.strstart+=K,J.insert+=K>J.w_size-J.insert?J.w_size-J.insert:K}J.block_start=J.strstart}if(J.high_water<J.strstart)J.high_water=J.strstart;if(V)return tI;if(Q!==JU&&Q!==iX&&J.strm.avail_in===0&&J.strstart===J.block_start)return sI;if(G=J.window_size-J.strstart,J.strm.avail_in>G&&J.block_start>=J.w_size){if(J.block_start-=J.w_size,J.strstart-=J.w_size,J.window.set(J.window.subarray(J.w_size,J.w_size+J.strstart),0),J.matches<2)J.matches++;if(G+=J.w_size,J.insert>J.strstart)J.insert=J.strstart}if(G>J.strm.avail_in)G=J.strm.avail_in;if(G)$B1(J.strm,J.window,J.strstart,G),J.strstart+=G,J.insert+=G>J.w_size-J.insert?J.w_size-J.insert:G;if(J.high_water<J.strstart)J.high_water=J.strstart;if(G=J.bi_valid+42>>3,G=J.pending_buf_size-G>65535?65535:J.pending_buf_size-G,Z=G>J.w_size?J.w_size:G,X=J.strstart-J.block_start,X>=Z||(X||Q===iX)&&Q!==JU&&J.strm.avail_in===0&&X<=G)Y=X>G?G:X,V=Q===iX&&J.strm.avail_in===0&&Y===X?1:0,eU1(J,J.block_start,Y,V),J.block_start+=Y,LY(J.strm);return V?RM:SQ},pU1=(J,Q)=>{let Z,Y;for(;;){if(J.lookahead<yK){if(oI(J),J.lookahead<yK&&Q===JU)return SQ;if(J.lookahead===0)break}if(Z=0,J.lookahead>=D9)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;if(Z!==0&&J.strstart-Z<=J.w_size-yK)J.match_length=yI0(J,Z);if(J.match_length>=D9)if(Y=eF(J,J.strstart-J.match_start,J.match_length-D9),J.lookahead-=J.match_length,J.match_length<=J.max_lazy_match&&J.lookahead>=D9){J.match_length--;do J.strstart++,J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;while(--J.match_length!==0);J.strstart++}else J.strstart+=J.match_length,J.match_length=0,J.ins_h=J.window[J.strstart],J.ins_h=QU(J,J.ins_h,J.window[J.strstart+1]);else Y=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++;if(Y){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=J.strstart<D9-1?J.strstart:D9-1,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},lI=(J,Q)=>{let Z,Y,X;for(;;){if(J.lookahead<yK){if(oI(J),J.lookahead<yK&&Q===JU)return SQ;if(J.lookahead===0)break}if(Z=0,J.lookahead>=D9)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;if(J.prev_length=J.match_length,J.prev_match=J.match_start,J.match_length=D9-1,Z!==0&&J.prev_length<J.max_lazy_match&&J.strstart-Z<=J.w_size-yK){if(J.match_length=yI0(J,Z),J.match_length<=5&&(J.strategy===hU4||J.match_length===D9&&J.strstart-J.match_start>4096))J.match_length=D9-1}if(J.prev_length>=D9&&J.match_length<=J.prev_length){X=J.strstart+J.lookahead-D9,Y=eF(J,J.strstart-1-J.prev_match,J.prev_length-D9),J.lookahead-=J.prev_length-1,J.prev_length-=2;do if(++J.strstart<=X)J.ins_h=QU(J,J.ins_h,J.window[J.strstart+D9-1]),Z=J.prev[J.strstart&J.w_mask]=J.head[J.ins_h],J.head[J.ins_h]=J.strstart;while(--J.prev_length!==0);if(J.match_available=0,J.match_length=D9-1,J.strstart++,Y){if(AY(J,!1),J.strm.avail_out===0)return SQ}}else if(J.match_available){if(Y=eF(J,0,J.window[J.strstart-1]),Y)AY(J,!1);if(J.strstart++,J.lookahead--,J.strm.avail_out===0)return SQ}else J.match_available=1,J.strstart++,J.lookahead--}if(J.match_available)Y=eF(J,0,J.window[J.strstart-1]),J.match_available=0;if(J.insert=J.strstart<D9-1?J.strstart:D9-1,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},QB4=(J,Q)=>{let Z,Y,X,G,V=J.window;for(;;){if(J.lookahead<=tF){if(oI(J),J.lookahead<=tF&&Q===JU)return SQ;if(J.lookahead===0)break}if(J.match_length=0,J.lookahead>=D9&&J.strstart>0){if(X=J.strstart-1,Y=V[X],Y===V[++X]&&Y===V[++X]&&Y===V[++X]){G=J.strstart+tF;do;while(Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&Y===V[++X]&&X<G);if(J.match_length=tF-(G-X),J.match_length>J.lookahead)J.match_length=J.lookahead}}if(J.match_length>=D9)Z=eF(J,1,J.match_length-D9),J.lookahead-=J.match_length,J.strstart+=J.match_length,J.match_length=0;else Z=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++;if(Z){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=0,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},ZB4=(J,Q)=>{let Z;for(;;){if(J.lookahead===0){if(oI(J),J.lookahead===0){if(Q===JU)return SQ;break}}if(J.match_length=0,Z=eF(J,0,J.window[J.strstart]),J.lookahead--,J.strstart++,Z){if(AY(J,!1),J.strm.avail_out===0)return SQ}}if(J.insert=0,Q===iX){if(AY(J,!0),J.strm.avail_out===0)return RM;return tI}if(J.sym_next){if(AY(J,!1),J.strm.avail_out===0)return SQ}return sI},Ux,YB4=(J)=>{J.window_size=2*J.w_size,sF(J.head),J.max_lazy_match=Ux[J.level].max_lazy,J.good_match=Ux[J.level].good_length,J.nice_match=Ux[J.level].nice_length,J.max_chain_length=Ux[J.level].max_chain,J.strstart=0,J.block_start=0,J.lookahead=0,J.insert=0,J.match_length=J.prev_length=D9-1,J.match_available=0,J.ins_h=0},Rx=(J)=>{if(!J)return 1;let Q=J.state;if(!Q||Q.strm!==J||Q.status!==aI&&Q.status!==WB1&&Q.status!==QB1&&Q.status!==ZB1&&Q.status!==YB1&&Q.status!==XB1&&Q.status!==IM&&Q.status!==Fx)return 1;return 0},vI0=(J)=>{if(Rx(J))return PM(J,kK);J.total_in=J.total_out=0,J.data_type=uU4;let Q=J.state;if(Q.pending=0,Q.pending_out=0,Q.wrap<0)Q.wrap=-Q.wrap;return Q.status=Q.wrap===2?WB1:Q.wrap?aI:IM,J.adler=Q.wrap===2?0:1,Q.last_flush=-2,SU4(Q),JJ},fI0=(J)=>{let Q=vI0(J);if(Q===JJ)YB4(J.state);return Q},$B4=(J,Q)=>{if(Rx(J)||J.state.wrap!==2)return kK;return J.state.gzhead=Q,JJ},hI0=(J,Q,Z,Y,X,G)=>{if(!J)return kK;let V=1;if(Q===fU4)Q=6;if(Y<0)V=0,Y=-Y;else if(Y>15)V=2,Y-=16;if(X<1||X>pU4||Z!==No||Y<8||Y>15||Q<0||Q>9||G<0||G>mU4||Y===8&&V!==1)return PM(J,kK);if(Y===8)Y=9;let K=new XB4;return J.state=K,K.strm=J,K.status=aI,K.wrap=V,K.gzhead=null,K.w_bits=Y,K.w_size=1<<K.w_bits,K.w_mask=K.w_size-1,K.hash_bits=X+7,K.hash_size=1<<K.hash_bits,K.hash_mask=K.hash_size-1,K.hash_shift=~~((K.hash_bits+D9-1)/D9),K.window=new Uint8Array(K.w_size*2),K.head=new Uint16Array(K.hash_size),K.prev=new Uint16Array(K.w_size),K.lit_bufsize=1<<X+6,K.pending_buf_size=K.lit_bufsize*4,K.pending_buf=new Uint8Array(K.pending_buf_size),K.sym_buf=K.lit_bufsize,K.sym_end=(K.lit_bufsize-1)*3,K.level=Q,K.strategy=G,K.method=Z,fI0(J)},GB4=(J,Q)=>{return hI0(J,Q,No,dU4,cU4,gU4)},VB4=(J,Q)=>{if(Rx(J)||Q>mE0||Q<0)return J?PM(J,kK):kK;let Z=J.state;if(!J.output||J.avail_in!==0&&!J.input||Z.status===Fx&&Q!==iX)return PM(J,J.avail_out===0?uU1:kK);let Y=Z.last_flush;if(Z.last_flush=Q,Z.pending!==0){if(LY(J),J.avail_out===0)return Z.last_flush=-1,JJ}else if(J.avail_in===0&&uE0(Q)<=uE0(Y)&&Q!==iX)return PM(J,uU1);if(Z.status===Fx&&J.avail_in!==0)return PM(J,uU1);if(Z.status===aI&&Z.wrap===0)Z.status=IM;if(Z.status===aI){let X=No+(Z.w_bits-8<<4)<<8,G=-1;if(Z.strategy>=Vo||Z.level<2)G=0;else if(Z.level<6)G=1;else if(Z.level===6)G=2;else G=3;if(X|=G<<6,Z.strstart!==0)X|=sU4;if(X+=31-X%31,zx(Z,X),Z.strstart!==0)zx(Z,J.adler>>>16),zx(Z,J.adler&65535);if(J.adler=1,Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}if(Z.status===WB1)if(J.adler=0,i9(Z,31),i9(Z,139),i9(Z,8),!Z.gzhead){if(i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,0),i9(Z,Z.level===9?2:Z.strategy>=Vo||Z.level<2?4:0),i9(Z,tU4),Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}else{if(i9(Z,(Z.gzhead.text?1:0)+(Z.gzhead.hcrc?2:0)+(!Z.gzhead.extra?0:4)+(!Z.gzhead.name?0:8)+(!Z.gzhead.comment?0:16)),i9(Z,Z.gzhead.time&255),i9(Z,Z.gzhead.time>>8&255),i9(Z,Z.gzhead.time>>16&255),i9(Z,Z.gzhead.time>>24&255),i9(Z,Z.level===9?2:Z.strategy>=Vo||Z.level<2?4:0),i9(Z,Z.gzhead.os&255),Z.gzhead.extra&&Z.gzhead.extra.length)i9(Z,Z.gzhead.extra.length&255),i9(Z,Z.gzhead.extra.length>>8&255);if(Z.gzhead.hcrc)J.adler=E2(J.adler,Z.pending_buf,Z.pending,0);Z.gzindex=0,Z.status=QB1}if(Z.status===QB1){if(Z.gzhead.extra){let X=Z.pending,G=(Z.gzhead.extra.length&65535)-Z.gzindex;while(Z.pending+G>Z.pending_buf_size){let K=Z.pending_buf_size-Z.pending;if(Z.pending_buf.set(Z.gzhead.extra.subarray(Z.gzindex,Z.gzindex+K),Z.pending),Z.pending=Z.pending_buf_size,Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(Z.gzindex+=K,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0,G-=K}let V=new Uint8Array(Z.gzhead.extra);if(Z.pending_buf.set(V.subarray(Z.gzindex,Z.gzindex+G),Z.pending),Z.pending+=G,Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);Z.gzindex=0}Z.status=ZB1}if(Z.status===ZB1){if(Z.gzhead.name){let X=Z.pending,G;do{if(Z.pending===Z.pending_buf_size){if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0}if(Z.gzindex<Z.gzhead.name.length)G=Z.gzhead.name.charCodeAt(Z.gzindex++)&255;else G=0;i9(Z,G)}while(G!==0);if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);Z.gzindex=0}Z.status=YB1}if(Z.status===YB1){if(Z.gzhead.comment){let X=Z.pending,G;do{if(Z.pending===Z.pending_buf_size){if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X);if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ;X=0}if(Z.gzindex<Z.gzhead.comment.length)G=Z.gzhead.comment.charCodeAt(Z.gzindex++)&255;else G=0;i9(Z,G)}while(G!==0);if(Z.gzhead.hcrc&&Z.pending>X)J.adler=E2(J.adler,Z.pending_buf,Z.pending-X,X)}Z.status=XB1}if(Z.status===XB1){if(Z.gzhead.hcrc){if(Z.pending+2>Z.pending_buf_size){if(LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}i9(Z,J.adler&255),i9(Z,J.adler>>8&255),J.adler=0}if(Z.status=IM,LY(J),Z.pending!==0)return Z.last_flush=-1,JJ}if(J.avail_in!==0||Z.lookahead!==0||Q!==JU&&Z.status!==Fx){let X=Z.level===0?xI0(Z,Q):Z.strategy===Vo?ZB4(Z,Q):Z.strategy===bU4?QB4(Z,Q):Ux[Z.level].func(Z,Q);if(X===RM||X===tI)Z.status=Fx;if(X===SQ||X===RM){if(J.avail_out===0)Z.last_flush=-1;return JJ}if(X===sI){if(Q===yU4)kU4(Z);else if(Q!==mE0){if(eU1(Z,0,0,!1),Q===xU4){if(sF(Z.head),Z.lookahead===0)Z.strstart=0,Z.block_start=0,Z.insert=0}}if(LY(J),J.avail_out===0)return Z.last_flush=-1,JJ}}if(Q!==iX)return JJ;if(Z.wrap<=0)return gE0;if(Z.wrap===2)i9(Z,J.adler&255),i9(Z,J.adler>>8&255),i9(Z,J.adler>>16&255),i9(Z,J.adler>>24&255),i9(Z,J.total_in&255),i9(Z,J.total_in>>8&255),i9(Z,J.total_in>>16&255),i9(Z,J.total_in>>24&255);else zx(Z,J.adler>>>16),zx(Z,J.adler&65535);if(LY(J),Z.wrap>0)Z.wrap=-Z.wrap;return Z.pending!==0?JJ:gE0},KB4=(J)=>{if(Rx(J))return kK;let Q=J.state.status;return J.state=null,Q===IM?PM(J,vU4):JJ},qB4=(J,Q)=>{let Z=Q.length;if(Rx(J))return kK;let Y=J.state,X=Y.wrap;if(X===2||X===1&&Y.status!==aI||Y.lookahead)return kK;if(X===1)J.adler=wx(J.adler,Q,Z,0);if(Y.wrap=0,Z>=Y.w_size){if(X===0)sF(Y.head),Y.strstart=0,Y.block_start=0,Y.insert=0;let q=new Uint8Array(Y.w_size);q.set(Q.subarray(Z-Y.w_size,Z),0),Q=q,Z=Y.w_size}let{avail_in:G,next_in:V,input:K}=J;J.avail_in=Z,J.next_in=0,J.input=Q,oI(Y);while(Y.lookahead>=D9){let q=Y.strstart,W=Y.lookahead-(D9-1);do Y.ins_h=QU(Y,Y.ins_h,Y.window[q+D9-1]),Y.prev[q&Y.w_mask]=Y.head[Y.ins_h],Y.head[Y.ins_h]=q,q++;while(--W);Y.strstart=q,Y.lookahead=D9-1,oI(Y)}return Y.strstart+=Y.lookahead,Y.block_start=Y.strstart,Y.insert=Y.lookahead,Y.lookahead=0,Y.match_length=Y.prev_length=D9-1,Y.match_available=0,J.next_in=V,J.input=K,J.avail_in=G,Y.wrap=X,JJ},WB4,HB4,zB4,FB4,UB4,BB4,NB4,DB4,MB4="pako deflate (from Nodeca project)",Nx,LB4=(J,Q)=>{return Object.prototype.hasOwnProperty.call(J,Q)},AB4=function(J){let Q=Array.prototype.slice.call(arguments,1);while(Q.length){let Z=Q.shift();if(!Z)continue;if(typeof Z!=="object")throw TypeError(Z+"must be non-object");for(let Y in Z)if(LB4(Z,Y))J[Y]=Z[Y]}return J},OB4=(J)=>{let Q=0;for(let Y=0,X=J.length;Y<X;Y++)Q+=J[Y].length;let Z=new Uint8Array(Q);for(let Y=0,X=0,G=J.length;Y<G;Y++){let V=J[Y];Z.set(V,X),X+=V.length}return Z},Do,bI0=!0,Ex,wB4=(J)=>{if(typeof TextEncoder==="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(J);let Q,Z,Y,X,G,V=J.length,K=0;for(X=0;X<V;X++){if(Z=J.charCodeAt(X),(Z&64512)===55296&&X+1<V){if(Y=J.charCodeAt(X+1),(Y&64512)===56320)Z=65536+(Z-55296<<10)+(Y-56320),X++}K+=Z<128?1:Z<2048?2:Z<65536?3:4}Q=new Uint8Array(K);for(G=0,X=0;G<K;X++){if(Z=J.charCodeAt(X),(Z&64512)===55296&&X+1<V){if(Y=J.charCodeAt(X+1),(Y&64512)===56320)Z=65536+(Z-55296<<10)+(Y-56320),X++}if(Z<128)Q[G++]=Z;else if(Z<2048)Q[G++]=192|Z>>>6,Q[G++]=128|Z&63;else if(Z<65536)Q[G++]=224|Z>>>12,Q[G++]=128|Z>>>6&63,Q[G++]=128|Z&63;else Q[G++]=240|Z>>>18,Q[G++]=128|Z>>>12&63,Q[G++]=128|Z>>>6&63,Q[G++]=128|Z&63}return Q},EB4=(J,Q)=>{if(Q<65534){if(J.subarray&&bI0)return String.fromCharCode.apply(null,J.length===Q?J:J.subarray(0,Q))}let Z="";for(let Y=0;Y<Q;Y++)Z+=String.fromCharCode(J[Y]);return Z},IB4=(J,Q)=>{let Z=Q||J.length;if(typeof TextDecoder==="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(J.subarray(0,Q));let Y,X,G=Array(Z*2);for(X=0,Y=0;Y<Z;){let V=J[Y++];if(V<128){G[X++]=V;continue}let K=Ex[V];if(K>4){G[X++]=65533,Y+=K-1;continue}V&=K===2?31:K===3?15:7;while(K>1&&Y<Z)V=V<<6|J[Y++]&63,K--;if(K>1){G[X++]=65533;continue}if(V<65536)G[X++]=V;else V-=65536,G[X++]=55296|V>>10&1023,G[X++]=56320|V&1023}return EB4(G,X)},PB4=(J,Q)=>{if(Q=Q||J.length,Q>J.length)Q=J.length;let Z=Q-1;while(Z>=0&&(J[Z]&192)===128)Z--;if(Z<0)return Q;if(Z===0)return Q;return Z+Ex[J[Z]]>Q?Z:Q},Ix,mI0,gI0,RB4,CB4,jB4,SB4,Uo,_B4,kB4,yB4,xB4,hB4,bB4,mB4,gB4,uB4,pB4,Ko=16209,dB4=16191,cB4=function(Q,Z){let Y,X,G,V,K,q,W,H,z,U,D,M,L,A,E,I,P,R,y,k,v,g,d,b,a=Q.state;Y=Q.next_in,d=Q.input,X=Y+(Q.avail_in-5),G=Q.next_out,b=Q.output,V=G-(Z-Q.avail_out),K=G+(Q.avail_out-257),q=a.dmax,W=a.wsize,H=a.whave,z=a.wnext,U=a.window,D=a.hold,M=a.bits,L=a.lencode,A=a.distcode,E=(1<<a.lenbits)-1,I=(1<<a.distbits)-1;J:do{if(M<15)D+=d[Y++]<<M,M+=8,D+=d[Y++]<<M,M+=8;P=L[D&E];Q:for(;;){if(R=P>>>24,D>>>=R,M-=R,R=P>>>16&255,R===0)b[G++]=P&65535;else if(R&16){if(y=P&65535,R&=15,R){if(M<R)D+=d[Y++]<<M,M+=8;y+=D&(1<<R)-1,D>>>=R,M-=R}if(M<15)D+=d[Y++]<<M,M+=8,D+=d[Y++]<<M,M+=8;P=A[D&I];Z:for(;;){if(R=P>>>24,D>>>=R,M-=R,R=P>>>16&255,R&16){if(k=P&65535,R&=15,M<R){if(D+=d[Y++]<<M,M+=8,M<R)D+=d[Y++]<<M,M+=8}if(k+=D&(1<<R)-1,k>q){Q.msg="invalid distance too far back",a.mode=Ko;break J}if(D>>>=R,M-=R,R=G-V,k>R){if(R=k-R,R>H){if(a.sane){Q.msg="invalid distance too far back",a.mode=Ko;break J}}if(v=0,g=U,z===0){if(v+=W-R,R<y){y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}}else if(z<R){if(v+=W+z-R,R-=z,R<y){y-=R;do b[G++]=U[v++];while(--R);if(v=0,z<y){R=z,y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}}}else if(v+=z-R,R<y){y-=R;do b[G++]=U[v++];while(--R);v=G-k,g=b}while(y>2)b[G++]=g[v++],b[G++]=g[v++],b[G++]=g[v++],y-=3;if(y){if(b[G++]=g[v++],y>1)b[G++]=g[v++]}}else{v=G-k;do b[G++]=b[v++],b[G++]=b[v++],b[G++]=b[v++],y-=3;while(y>2);if(y){if(b[G++]=b[v++],y>1)b[G++]=b[v++]}}}else if((R&64)===0){P=A[(P&65535)+(D&(1<<R)-1)];continue Z}else{Q.msg="invalid distance code",a.mode=Ko;break J}break}}else if((R&64)===0){P=L[(P&65535)+(D&(1<<R)-1)];continue Q}else if(R&32){a.mode=dB4;break J}else{Q.msg="invalid literal/length code",a.mode=Ko;break J}break}}while(Y<X&&G<K);y=M>>3,Y-=y,M-=y<<3,D&=(1<<M)-1,Q.next_in=Y,Q.next_out=G,Q.avail_in=Y<X?5+(X-Y):5-(Y-X),Q.avail_out=G<K?257+(K-G):257-(G-K),a.hold=D,a.bits=M;return},iI=15,pE0=852,dE0=592,cE0=0,dU1=1,lE0=2,lB4,iB4,nB4,aB4,oB4=(J,Q,Z,Y,X,G,V,K)=>{let q=K.bits,W=0,H=0,z=0,U=0,D=0,M=0,L=0,A=0,E=0,I=0,P,R,y,k,v,g=null,d,b=new Uint16Array(iI+1),a=new Uint16Array(iI+1),G1=null,e,c,J1;for(W=0;W<=iI;W++)b[W]=0;for(H=0;H<Y;H++)b[Q[Z+H]]++;D=q;for(U=iI;U>=1;U--)if(b[U]!==0)break;if(D>U)D=U;if(U===0)return X[G++]=20971520,X[G++]=20971520,K.bits=1,0;for(z=1;z<U;z++)if(b[z]!==0)break;if(D<z)D=z;A=1;for(W=1;W<=iI;W++)if(A<<=1,A-=b[W],A<0)return-1;if(A>0&&(J===cE0||U!==1))return-1;a[1]=0;for(W=1;W<iI;W++)a[W+1]=a[W]+b[W];for(H=0;H<Y;H++)if(Q[Z+H]!==0)V[a[Q[Z+H]]++]=H;if(J===cE0)g=G1=V,d=20;else if(J===dU1)g=lB4,G1=iB4,d=257;else g=nB4,G1=aB4,d=0;if(I=0,H=0,W=z,v=G,M=D,L=0,y=-1,E=1<<D,k=E-1,J===dU1&&E>pE0||J===lE0&&E>dE0)return 1;for(;;){if(e=W-L,V[H]+1<d)c=0,J1=V[H];else if(V[H]>=d)c=G1[V[H]-d],J1=g[V[H]-d];else c=96,J1=0;P=1<<W-L,R=1<<M,z=R;do R-=P,X[v+(I>>L)+R]=e<<24|c<<16|J1|0;while(R!==0);P=1<<W-1;while(I&P)P>>=1;if(P!==0)I&=P-1,I+=P;else I=0;if(H++,--b[W]===0){if(W===U)break;W=Q[Z+V[H]]}if(W>D&&(I&k)!==y){if(L===0)L=D;v+=z,M=W-L,A=1<<M;while(M+L<U){if(A-=b[M+L],A<=0)break;M++,A<<=1}if(E+=1<<M,J===dU1&&E>pE0||J===lE0&&E>dE0)return 1;y=I&k,X[y]=D<<24|M<<16|v-G|0}}if(I!==0)X[v+I]=W-L<<24|4194304|0;return K.bits=D,0},Dx,rB4=0,uI0=1,pI0=2,iE0,sB4,qo,CM,tB4,eB4,nX,dI0,cI0,JN4,nE0,Mo=16180,aE0=16181,oE0=16182,rE0=16183,sE0=16184,tE0=16185,eE0=16186,JI0=16187,QI0=16188,ZI0=16189,Bo=16190,eW=16191,cU1=16192,YI0=16193,lU1=16194,XI0=16195,$I0=16196,GI0=16197,VI0=16198,Wo=16199,Ho=16200,KI0=16201,qI0=16202,WI0=16203,HI0=16204,zI0=16205,iU1=16206,FI0=16207,UI0=16208,F7=16209,lI0=16210,iI0=16211,QN4=852,ZN4=592,YN4=15,XN4,BI0=(J)=>{return(J>>>24&255)+(J>>>8&65280)+((J&65280)<<8)+((J&255)<<24)},SM=(J)=>{if(!J)return 1;let Q=J.state;if(!Q||Q.strm!==J||Q.mode<Mo||Q.mode>iI0)return 1;return 0},nI0=(J)=>{if(SM(J))return nX;let Q=J.state;if(J.total_in=J.total_out=Q.total=0,J.msg="",Q.wrap)J.adler=Q.wrap&1;return Q.mode=Mo,Q.last=0,Q.havedict=0,Q.flags=-1,Q.dmax=32768,Q.head=null,Q.hold=0,Q.bits=0,Q.lencode=Q.lendyn=new Int32Array(QN4),Q.distcode=Q.distdyn=new Int32Array(ZN4),Q.sane=1,Q.back=-1,CM},aI0=(J)=>{if(SM(J))return nX;let Q=J.state;return Q.wsize=0,Q.whave=0,Q.wnext=0,nI0(J)},oI0=(J,Q)=>{let Z;if(SM(J))return nX;let Y=J.state;if(Q<0)Z=0,Q=-Q;else if(Z=(Q>>4)+5,Q<48)Q&=15;if(Q&&(Q<8||Q>15))return nX;if(Y.window!==null&&Y.wbits!==Q)Y.window=null;return Y.wrap=Z,Y.wbits=Q,aI0(J)},rI0=(J,Q)=>{if(!J)return nX;let Z=new $N4;J.state=Z,Z.strm=J,Z.window=null,Z.mode=Mo;let Y=oI0(J,Q);if(Y!==CM)J.state=null;return Y},GN4=(J)=>{return rI0(J,XN4)},NI0=!0,nU1,aU1,VN4=(J)=>{if(NI0){nU1=new Int32Array(512),aU1=new Int32Array(32);let Q=0;while(Q<144)J.lens[Q++]=8;while(Q<256)J.lens[Q++]=9;while(Q<280)J.lens[Q++]=7;while(Q<288)J.lens[Q++]=8;Dx(uI0,J.lens,0,288,nU1,0,J.work,{bits:9}),Q=0;while(Q<32)J.lens[Q++]=5;Dx(pI0,J.lens,0,32,aU1,0,J.work,{bits:5}),NI0=!1}J.lencode=nU1,J.lenbits=9,J.distcode=aU1,J.distbits=5},sI0=(J,Q,Z,Y)=>{let X,G=J.state;if(G.window===null)G.wsize=1<<G.wbits,G.wnext=0,G.whave=0,G.window=new Uint8Array(G.wsize);if(Y>=G.wsize)G.window.set(Q.subarray(Z-G.wsize,Z),0),G.wnext=0,G.whave=G.wsize;else{if(X=G.wsize-G.wnext,X>Y)X=Y;if(G.window.set(Q.subarray(Z-Y,Z-Y+X),G.wnext),Y-=X,Y)G.window.set(Q.subarray(Z-Y,Z),0),G.wnext=Y,G.whave=G.wsize;else{if(G.wnext+=X,G.wnext===G.wsize)G.wnext=0;if(G.whave<G.wsize)G.whave+=X}}return 0},KN4=(J,Q)=>{let Z,Y,X,G,V,K,q,W,H,z,U,D,M,L,A=0,E,I,P,R,y,k,v,g,d=new Uint8Array(4),b,a,G1=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(SM(J)||!J.output||!J.input&&J.avail_in!==0)return nX;if(Z=J.state,Z.mode===eW)Z.mode=cU1;V=J.next_out,X=J.output,q=J.avail_out,G=J.next_in,Y=J.input,K=J.avail_in,W=Z.hold,H=Z.bits,z=K,U=q,g=CM;J:for(;;)switch(Z.mode){case Mo:if(Z.wrap===0){Z.mode=cU1;break}while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&2&&W===35615){if(Z.wbits===0)Z.wbits=15;Z.check=0,d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0),W=0,H=0,Z.mode=aE0;break}if(Z.head)Z.head.done=!1;if(!(Z.wrap&1)||(((W&255)<<8)+(W>>8))%31){J.msg="incorrect header check",Z.mode=F7;break}if((W&15)!==nE0){J.msg="unknown compression method",Z.mode=F7;break}if(W>>>=4,H-=4,v=(W&15)+8,Z.wbits===0)Z.wbits=v;if(v>15||v>Z.wbits){J.msg="invalid window size",Z.mode=F7;break}Z.dmax=1<<Z.wbits,Z.flags=0,J.adler=Z.check=1,Z.mode=W&512?ZI0:eW,W=0,H=0;break;case aE0:while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.flags=W,(Z.flags&255)!==nE0){J.msg="unknown compression method",Z.mode=F7;break}if(Z.flags&57344){J.msg="unknown header flags set",Z.mode=F7;break}if(Z.head)Z.head.text=W>>8&1;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0,Z.mode=oE0;case oE0:while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.head)Z.head.time=W;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,d[2]=W>>>16&255,d[3]=W>>>24&255,Z.check=E2(Z.check,d,4,0);W=0,H=0,Z.mode=rE0;case rE0:while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.head)Z.head.xflags=W&255,Z.head.os=W>>8;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0,Z.mode=sE0;case sE0:if(Z.flags&1024){while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.length=W,Z.head)Z.head.extra_len=W;if(Z.flags&512&&Z.wrap&4)d[0]=W&255,d[1]=W>>>8&255,Z.check=E2(Z.check,d,2,0);W=0,H=0}else if(Z.head)Z.head.extra=null;Z.mode=tE0;case tE0:if(Z.flags&1024){if(D=Z.length,D>K)D=K;if(D){if(Z.head){if(v=Z.head.extra_len-Z.length,!Z.head.extra)Z.head.extra=new Uint8Array(Z.head.extra_len);Z.head.extra.set(Y.subarray(G,G+D),v)}if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);K-=D,G+=D,Z.length-=D}if(Z.length)break J}Z.length=0,Z.mode=eE0;case eE0:if(Z.flags&2048){if(K===0)break J;D=0;do if(v=Y[G+D++],Z.head&&v&&Z.length<65536)Z.head.name+=String.fromCharCode(v);while(v&&D<K);if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);if(K-=D,G+=D,v)break J}else if(Z.head)Z.head.name=null;Z.length=0,Z.mode=JI0;case JI0:if(Z.flags&4096){if(K===0)break J;D=0;do if(v=Y[G+D++],Z.head&&v&&Z.length<65536)Z.head.comment+=String.fromCharCode(v);while(v&&D<K);if(Z.flags&512&&Z.wrap&4)Z.check=E2(Z.check,Y,D,G);if(K-=D,G+=D,v)break J}else if(Z.head)Z.head.comment=null;Z.mode=QI0;case QI0:if(Z.flags&512){while(H<16){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&4&&W!==(Z.check&65535)){J.msg="header crc mismatch",Z.mode=F7;break}W=0,H=0}if(Z.head)Z.head.hcrc=Z.flags>>9&1,Z.head.done=!0;J.adler=Z.check=0,Z.mode=eW;break;case ZI0:while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}J.adler=Z.check=BI0(W),W=0,H=0,Z.mode=Bo;case Bo:if(Z.havedict===0)return J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,eB4;J.adler=Z.check=1,Z.mode=eW;case eW:if(Q===sB4||Q===qo)break J;case cU1:if(Z.last){W>>>=H&7,H-=H&7,Z.mode=iU1;break}while(H<3){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}switch(Z.last=W&1,W>>>=1,H-=1,W&3){case 0:Z.mode=YI0;break;case 1:if(VN4(Z),Z.mode=Wo,Q===qo){W>>>=2,H-=2;break J}break;case 2:Z.mode=$I0;break;case 3:J.msg="invalid block type",Z.mode=F7}W>>>=2,H-=2;break;case YI0:W>>>=H&7,H-=H&7;while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if((W&65535)!==(W>>>16^65535)){J.msg="invalid stored block lengths",Z.mode=F7;break}if(Z.length=W&65535,W=0,H=0,Z.mode=lU1,Q===qo)break J;case lU1:Z.mode=XI0;case XI0:if(D=Z.length,D){if(D>K)D=K;if(D>q)D=q;if(D===0)break J;X.set(Y.subarray(G,G+D),V),K-=D,G+=D,q-=D,V+=D,Z.length-=D;break}Z.mode=eW;break;case $I0:while(H<14){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.nlen=(W&31)+257,W>>>=5,H-=5,Z.ndist=(W&31)+1,W>>>=5,H-=5,Z.ncode=(W&15)+4,W>>>=4,H-=4,Z.nlen>286||Z.ndist>30){J.msg="too many length or distance symbols",Z.mode=F7;break}Z.have=0,Z.mode=GI0;case GI0:while(Z.have<Z.ncode){while(H<3){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.lens[G1[Z.have++]]=W&7,W>>>=3,H-=3}while(Z.have<19)Z.lens[G1[Z.have++]]=0;if(Z.lencode=Z.lendyn,Z.lenbits=7,b={bits:Z.lenbits},g=Dx(rB4,Z.lens,0,19,Z.lencode,0,Z.work,b),Z.lenbits=b.bits,g){J.msg="invalid code lengths set",Z.mode=F7;break}Z.have=0,Z.mode=VI0;case VI0:while(Z.have<Z.nlen+Z.ndist){for(;;){if(A=Z.lencode[W&(1<<Z.lenbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(P<16)W>>>=E,H-=E,Z.lens[Z.have++]=P;else{if(P===16){a=E+2;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(W>>>=E,H-=E,Z.have===0){J.msg="invalid bit length repeat",Z.mode=F7;break}v=Z.lens[Z.have-1],D=3+(W&3),W>>>=2,H-=2}else if(P===17){a=E+3;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=E,H-=E,v=0,D=3+(W&7),W>>>=3,H-=3}else{a=E+7;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=E,H-=E,v=0,D=11+(W&127),W>>>=7,H-=7}if(Z.have+D>Z.nlen+Z.ndist){J.msg="invalid bit length repeat",Z.mode=F7;break}while(D--)Z.lens[Z.have++]=v}}if(Z.mode===F7)break;if(Z.lens[256]===0){J.msg="invalid code -- missing end-of-block",Z.mode=F7;break}if(Z.lenbits=9,b={bits:Z.lenbits},g=Dx(uI0,Z.lens,0,Z.nlen,Z.lencode,0,Z.work,b),Z.lenbits=b.bits,g){J.msg="invalid literal/lengths set",Z.mode=F7;break}if(Z.distbits=6,Z.distcode=Z.distdyn,b={bits:Z.distbits},g=Dx(pI0,Z.lens,Z.nlen,Z.ndist,Z.distcode,0,Z.work,b),Z.distbits=b.bits,g){J.msg="invalid distances set",Z.mode=F7;break}if(Z.mode=Wo,Q===qo)break J;case Wo:Z.mode=Ho;case Ho:if(K>=6&&q>=258){if(J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,cB4(J,U),V=J.next_out,X=J.output,q=J.avail_out,G=J.next_in,Y=J.input,K=J.avail_in,W=Z.hold,H=Z.bits,Z.mode===eW)Z.back=-1;break}Z.back=0;for(;;){if(A=Z.lencode[W&(1<<Z.lenbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(I&&(I&240)===0){R=E,y=I,k=P;for(;;){if(A=Z.lencode[k+((W&(1<<R+y)-1)>>R)],E=A>>>24,I=A>>>16&255,P=A&65535,R+E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=R,H-=R,Z.back+=R}if(W>>>=E,H-=E,Z.back+=E,Z.length=P,I===0){Z.mode=zI0;break}if(I&32){Z.back=-1,Z.mode=eW;break}if(I&64){J.msg="invalid literal/length code",Z.mode=F7;break}Z.extra=I&15,Z.mode=KI0;case KI0:if(Z.extra){a=Z.extra;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.length+=W&(1<<Z.extra)-1,W>>>=Z.extra,H-=Z.extra,Z.back+=Z.extra}Z.was=Z.length,Z.mode=qI0;case qI0:for(;;){if(A=Z.distcode[W&(1<<Z.distbits)-1],E=A>>>24,I=A>>>16&255,P=A&65535,E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if((I&240)===0){R=E,y=I,k=P;for(;;){if(A=Z.distcode[k+((W&(1<<R+y)-1)>>R)],E=A>>>24,I=A>>>16&255,P=A&65535,R+E<=H)break;if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}W>>>=R,H-=R,Z.back+=R}if(W>>>=E,H-=E,Z.back+=E,I&64){J.msg="invalid distance code",Z.mode=F7;break}Z.offset=P,Z.extra=I&15,Z.mode=WI0;case WI0:if(Z.extra){a=Z.extra;while(H<a){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}Z.offset+=W&(1<<Z.extra)-1,W>>>=Z.extra,H-=Z.extra,Z.back+=Z.extra}if(Z.offset>Z.dmax){J.msg="invalid distance too far back",Z.mode=F7;break}Z.mode=HI0;case HI0:if(q===0)break J;if(D=U-q,Z.offset>D){if(D=Z.offset-D,D>Z.whave){if(Z.sane){J.msg="invalid distance too far back",Z.mode=F7;break}}if(D>Z.wnext)D-=Z.wnext,M=Z.wsize-D;else M=Z.wnext-D;if(D>Z.length)D=Z.length;L=Z.window}else L=X,M=V-Z.offset,D=Z.length;if(D>q)D=q;q-=D,Z.length-=D;do X[V++]=L[M++];while(--D);if(Z.length===0)Z.mode=Ho;break;case zI0:if(q===0)break J;X[V++]=Z.length,q--,Z.mode=Ho;break;case iU1:if(Z.wrap){while(H<32){if(K===0)break J;K--,W|=Y[G++]<<H,H+=8}if(U-=q,J.total_out+=U,Z.total+=U,Z.wrap&4&&U)J.adler=Z.check=Z.flags?E2(Z.check,X,U,V-U):wx(Z.check,X,U,V-U);if(U=q,Z.wrap&4&&(Z.flags?W:BI0(W))!==Z.check){J.msg="incorrect data check",Z.mode=F7;break}W=0,H=0}Z.mode=FI0;case FI0:if(Z.wrap&&Z.flags){while(H<32){if(K===0)break J;K--,W+=Y[G++]<<H,H+=8}if(Z.wrap&4&&W!==(Z.total&4294967295)){J.msg="incorrect length check",Z.mode=F7;break}W=0,H=0}Z.mode=UI0;case UI0:g=tB4;break J;case F7:g=dI0;break J;case lI0:return cI0;case iI0:default:return nX}if(J.next_out=V,J.avail_out=q,J.next_in=G,J.avail_in=K,Z.hold=W,Z.bits=H,Z.wsize||U!==J.avail_out&&Z.mode<F7&&(Z.mode<iU1||Q!==iE0)){if(sI0(J,J.output,J.next_out,U-J.avail_out));}if(z-=J.avail_in,U-=J.avail_out,J.total_in+=z,J.total_out+=U,Z.total+=U,Z.wrap&4&&U)J.adler=Z.check=Z.flags?E2(Z.check,X,U,J.next_out-U):wx(Z.check,X,U,J.next_out-U);if(J.data_type=Z.bits+(Z.last?64:0)+(Z.mode===eW?128:0)+(Z.mode===Wo||Z.mode===lU1?256:0),(z===0&&U===0||Q===iE0)&&g===CM)g=JN4;return g},qN4=(J)=>{if(SM(J))return nX;let Q=J.state;if(Q.window)Q.window=null;return J.state=null,CM},WN4=(J,Q)=>{if(SM(J))return nX;let Z=J.state;if((Z.wrap&2)===0)return nX;return Z.head=Q,Q.done=!1,CM},HN4=(J,Q)=>{let Z=Q.length,Y,X,G;if(SM(J))return nX;if(Y=J.state,Y.wrap!==0&&Y.mode!==Bo)return nX;if(Y.mode===Bo){if(X=1,X=wx(X,Q,Z,0),X!==Y.check)return dI0}if(G=sI0(J,Q,Z,Z),G)return Y.mode=lI0,cI0;return Y.havedict=1,CM},zN4,FN4,UN4,BN4,NN4,DN4,MN4,LN4,AN4,ON4="pako inflate (from Nodeca project)",QH,EN4,tI0,IN4,PN4,Px,oU1,rU1,TN4,DI0,RN4,jN4,SN4,_N4,kN4,yN4,xN4,vN4,fN4,hN4,bN4,mN4,gN4,uN4,pN4,dN4,cN4,lN4,iN4,nN4,aN4,oN4,rN4,sN4,eI0;var JP0=B1(()=>{/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */Mx=Tx+1+GB1,LI0=2*Mx+1,sU1=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),zo=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),KU4=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),EI0=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),JH=Array((Mx+2)*2);rI(JH);Bx=Array(nI*2);rI(Bx);Lx=Array(qU4);rI(Lx);Ax=Array(GU4-$U4+1);rI(Ax);qB1=Array(GB1);rI(qB1);Fo=Array(nI);rI(Fo);AU4=NU4,OU4=kI0,wU4=MU4,EU4=LU4,IU4=DU4,PU4={_tr_init:AU4,_tr_stored_block:OU4,_tr_flush_block:wU4,_tr_tally:EU4,_tr_align:IU4},wx=TU4,CU4=new Uint32Array(RU4()),E2=jU4,TM={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},jM={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:SU4,_tr_stored_block:eU1,_tr_flush_block:_U4,_tr_tally:eF,_tr_align:kU4}=PU4,{Z_NO_FLUSH:JU,Z_PARTIAL_FLUSH:yU4,Z_FULL_FLUSH:xU4,Z_FINISH:iX,Z_BLOCK:mE0,Z_OK:JJ,Z_STREAM_END:gE0,Z_STREAM_ERROR:kK,Z_DATA_ERROR:vU4,Z_BUF_ERROR:uU1,Z_DEFAULT_COMPRESSION:fU4,Z_FILTERED:hU4,Z_HUFFMAN_ONLY:Vo,Z_RLE:bU4,Z_FIXED:mU4,Z_DEFAULT_STRATEGY:gU4,Z_UNKNOWN:uU4,Z_DEFLATED:No}=jM,JB1=iU4+1+lU4,oU4=2*JB1+1,yK=tF+D9+1,QU=JB4;Ux=[new SK(0,0,0,0,xI0),new SK(4,4,8,4,pU1),new SK(4,5,16,8,pU1),new SK(4,6,32,32,pU1),new SK(4,4,16,16,lI),new SK(8,16,32,32,lI),new SK(8,16,128,128,lI),new SK(8,32,128,256,lI),new SK(32,128,258,1024,lI),new SK(32,258,258,4096,lI)];WB4=GB4,HB4=hI0,zB4=fI0,FB4=vI0,UB4=$B4,BB4=VB4,NB4=KB4,DB4=qB4,Nx={deflateInit:WB4,deflateInit2:HB4,deflateReset:zB4,deflateResetKeep:FB4,deflateSetHeader:UB4,deflate:BB4,deflateEnd:NB4,deflateSetDictionary:DB4,deflateInfo:MB4},Do={assign:AB4,flattenChunks:OB4};try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(J){bI0=!1}Ex=new Uint8Array(256);for(let J=0;J<256;J++)Ex[J]=J>=252?6:J>=248?5:J>=240?4:J>=224?3:J>=192?2:1;Ex[254]=Ex[254]=1;Ix={string2buf:wB4,buf2string:IB4,utf8border:PB4};mI0=TB4,gI0=Object.prototype.toString,{Z_NO_FLUSH:RB4,Z_SYNC_FLUSH:CB4,Z_FULL_FLUSH:jB4,Z_FINISH:SB4,Z_OK:Uo,Z_STREAM_END:_B4,Z_DEFAULT_COMPRESSION:kB4,Z_DEFAULT_STRATEGY:yB4,Z_DEFLATED:xB4}=jM;Cx.prototype.push=function(J,Q){let Z=this.strm,Y=this.options.chunkSize,X,G;if(this.ended)return!1;if(Q===~~Q)G=Q;else G=Q===!0?SB4:RB4;if(typeof J==="string")Z.input=Ix.string2buf(J);else if(gI0.call(J)==="[object ArrayBuffer]")Z.input=new Uint8Array(J);else Z.input=J;Z.next_in=0,Z.avail_in=Z.input.length;for(;;){if(Z.avail_out===0)Z.output=new Uint8Array(Y),Z.next_out=0,Z.avail_out=Y;if((G===CB4||G===jB4)&&Z.avail_out<=6){this.onData(Z.output.subarray(0,Z.next_out)),Z.avail_out=0;continue}if(X=Nx.deflate(Z,G),X===_B4){if(Z.next_out>0)this.onData(Z.output.subarray(0,Z.next_out));return X=Nx.deflateEnd(this.strm),this.onEnd(X),this.ended=!0,X===Uo}if(Z.avail_out===0){this.onData(Z.output);continue}if(G>0&&Z.next_out>0){this.onData(Z.output.subarray(0,Z.next_out)),Z.avail_out=0;continue}if(Z.avail_in===0)break}return!0};Cx.prototype.onData=function(J){this.chunks.push(J)};Cx.prototype.onEnd=function(J){if(J===Uo)this.result=Do.flattenChunks(this.chunks);this.chunks=[],this.err=J,this.msg=this.strm.msg};hB4=Cx,bB4=HB1,mB4=vB4,gB4=fB4,uB4=jM,pB4={Deflate:hB4,deflate:bB4,deflateRaw:mB4,gzip:gB4,constants:uB4},lB4=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),iB4=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),nB4=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),aB4=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),Dx=oB4,{Z_FINISH:iE0,Z_BLOCK:sB4,Z_TREES:qo,Z_OK:CM,Z_STREAM_END:tB4,Z_NEED_DICT:eB4,Z_STREAM_ERROR:nX,Z_DATA_ERROR:dI0,Z_MEM_ERROR:cI0,Z_BUF_ERROR:JN4,Z_DEFLATED:nE0}=jM,XN4=YN4;zN4=aI0,FN4=oI0,UN4=nI0,BN4=GN4,NN4=rI0,DN4=KN4,MN4=qN4,LN4=WN4,AN4=HN4,QH={inflateReset:zN4,inflateReset2:FN4,inflateResetKeep:UN4,inflateInit:BN4,inflateInit2:NN4,inflate:DN4,inflateEnd:MN4,inflateGetHeader:LN4,inflateSetDictionary:AN4,inflateInfo:ON4};EN4=wN4,tI0=Object.prototype.toString,{Z_NO_FLUSH:IN4,Z_FINISH:PN4,Z_OK:Px,Z_STREAM_END:oU1,Z_NEED_DICT:rU1,Z_STREAM_ERROR:TN4,Z_DATA_ERROR:DI0,Z_MEM_ERROR:RN4}=jM;jx.prototype.push=function(J,Q){let Z=this.strm,Y=this.options.chunkSize,X=this.options.dictionary,G,V,K;if(this.ended)return!1;if(Q===~~Q)V=Q;else V=Q===!0?PN4:IN4;if(tI0.call(J)==="[object ArrayBuffer]")Z.input=new Uint8Array(J);else Z.input=J;Z.next_in=0,Z.avail_in=Z.input.length;for(;;){if(Z.avail_out===0)Z.output=new Uint8Array(Y),Z.next_out=0,Z.avail_out=Y;if(G=QH.inflate(Z,V),G===rU1&&X){if(G=QH.inflateSetDictionary(Z,X),G===Px)G=QH.inflate(Z,V);else if(G===DI0)G=rU1}while(Z.avail_in>0&&G===oU1&&Z.state.wrap>0&&J[Z.next_in]!==0)QH.inflateReset(Z),G=QH.inflate(Z,V);switch(G){case TN4:case DI0:case rU1:case RN4:return this.onEnd(G),this.ended=!0,!1}if(K=Z.avail_out,Z.next_out){if(Z.avail_out===0||G===oU1)if(this.options.to==="string"){let q=Ix.utf8border(Z.output,Z.next_out),W=Z.next_out-q,H=Ix.buf2string(Z.output,q);if(Z.next_out=W,Z.avail_out=Y-W,W)Z.output.set(Z.output.subarray(q,q+W),0);this.onData(H)}else this.onData(Z.output.length===Z.next_out?Z.output:Z.output.subarray(0,Z.next_out))}if(G===Px&&K===0)continue;if(G===oU1)return G=QH.inflateEnd(this.strm),this.onEnd(G),this.ended=!0,!0;if(Z.avail_in===0)break}return!0};jx.prototype.onData=function(J){this.chunks.push(J)};jx.prototype.onEnd=function(J){if(J===Px)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=Do.flattenChunks(this.chunks);this.chunks=[],this.err=J,this.msg=this.strm.msg};jN4=jx,SN4=zB1,_N4=CN4,kN4=zB1,yN4=jM,xN4={Inflate:jN4,inflate:SN4,inflateRaw:_N4,ungzip:kN4,constants:yN4},{Deflate:vN4,deflate:fN4,deflateRaw:hN4,gzip:bN4}=pB4,{Inflate:mN4,inflate:gN4,inflateRaw:uN4,ungzip:pN4}=xN4,dN4=vN4,cN4=fN4,lN4=hN4,iN4=bN4,nN4=mN4,aN4=gN4,oN4=uN4,rN4=pN4,sN4=jM,eI0={Deflate:dN4,deflate:cN4,deflateRaw:lN4,gzip:iN4,Inflate:nN4,inflate:aN4,inflateRaw:oN4,ungzip:rN4,constants:sN4}});var ZP0={};Q9(ZP0,{internalAPIClient:()=>K5,createInternalAPIClient:()=>QP0});function eN4(J){if(new Blob([J]).size<=tN4)return{body:J};return{body:eI0.gzip(J),headers:{"Content-Encoding":"gzip"}}}function QP0(J){return new Proxy({},{get:(Q,Z)=>{return async(...Y)=>{let X=Y.at(1),G=Y.at(0);if(!X?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:V,headers:K={}}=eN4(JSON.stringify({method:Z,params:G})),q=await U3("/api/internal?"+encodeURIComponent(Z),{method:"POST",body:V,headers:K,signal:X?.signal},X.config);if(!q.ok)throw Error(`API request for ${Z} failed: ${q.status}`);return await q.json()}}})}var tN4=10485760,K5;var gG=B1(()=>{JP0();RZ();K5=QP0(fetch)});function JD4(J){if(J.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=J.proxy;if(J.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=J.proxy}function YP0(J){return J.config.pipe(B4(({settings:Q,secrets:Z})=>{return h6(async()=>{return await Z.getToken("apiKey",Q.url)!==void 0})}))}function Sx(J,Q,Z){let Y=Z?`/threads/${Q}/${Z}`:`/threads/${Q}`;return new URL(Y,J)}async function U3(J,Q,Z){let Y=Q?.signal||void 0,X=await Z.getLatest(Y);return FB1(X,J,Q)}async function XP0(J,Q,Z,Y){let X=await J.get(Q);if(!X)throw Error(`Thread not found: ${Q}`);let G=await K5.shareThreadWithOperator({threadData:X,message:Y||void 0},{config:Z});if(!G.ok)throw Error(`Failed to share thread: ${G.error.message}`)}async function Lo(J,Q){let Z=await U3("/api/telemetry",{method:"POST",redirect:"manual",body:J},Q);if(!Z.ok){let Y=await Z.text(),X;try{X=JSON.parse(Y).error||`HTTP ${Z.status}`}catch{X=Y||`HTTP ${Z.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function FB1(J,Q,Z){if(Q.startsWith("http:")||Q.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!Q.startsWith("/"))throw Error("pathAndQuery must start with /");let Y=J.settings.url;if(!Y)throw Error("amp.url is not set");let X=await J.secrets.getToken("apiKey",Y);JD4({proxy:J.settings.proxy});let G=new URL(Q,Y);try{return await fetch(G,{...Z,headers:{"Content-Type":"application/json",...Z?.headers,...W3(),...X?{Authorization:`Bearer ${X}`}:{}}})}catch(V){throw x.error("Amp server fetch failed",V,{name:"fetchFromAmpServer",url:G.toString(),method:Z?.method??"GET",errorMessage:V instanceof Error?V.message:String(V),errorCause:V instanceof Error&&V.cause?String(V.cause):void 0}),V}}var RZ=B1(()=>{i0();U0();DZ();gG()});function ZH(J,Q){if(J=J.replace(/\.git$/,""),!URL.canParse(J))return null;let Z=new URL(J);if(Z.protocol!=="https:"||Z.port||Z.username||Z.password)return null;let Y=Z.pathname.replace(/^\//,"").replace(/\/$/,"");if(!Y)return null;let X=`${Z.protocol}//${Z.host}`;if(Z.hostname==="github.com"){if(Q?.provider&&Q.provider!=="github")return null;return{name:Y,instanceURL:"https://github.com",provider:"github"}}if(!Q?.gitlabInstanceURL)return null;let G=new URL(Q.gitlabInstanceURL);if(Z.protocol===G.protocol&&Z.host===G.host){if(Q?.provider&&Q.provider!=="gitlab")return null;return{name:Y,instanceURL:X,provider:"gitlab"}}return null}async function y3(J,Q={},Z){let Y=`/api/internal/github-proxy/${J}`,{body:X,headers:G={},method:V="GET",...K}=Q,q=await FB1(Z,Y,{method:V,headers:G,body:X?JSON.stringify(X):void 0,...K});if(q.status===304)return{ok:!0,status:q.status,notModified:!0,headers:{etag:q.headers.get("etag")||void 0}};if(!q.ok)return{ok:!1,status:q.status,statusText:q.statusText};let W=await q.json();return{ok:!0,status:q.status,data:W,headers:{location:q.headers.get("location")||void 0,etag:q.headers.get("etag")||void 0}}}var xK=B1(()=>{RZ()});async function FP0(J,Q,Z,Y,X){let G=ZH(J,{provider:"github"})?.name;if(!G)throw Error("Invalid GitHub repository URL");let{filePattern:V,limit:K,offset:q=0}=Z,W=`repos/${G}/git/trees/${Q??"HEAD"}?recursive=1`,H=await y3(W,{signal:Y},X);if(!H.ok||!H.data)throw Error(`Failed to fetch files: ${H.status} ${H.statusText||"Unknown error"}`);let U=H.data.tree.filter((A)=>A.type==="blob").map((A)=>A.path),D=zP0.default(V),M=U.filter((A)=>D(A));return{files:K?M.slice(q,q+K):M.slice(q),truncated:H.data.truncated}}var zP0;var UP0=B1(()=>{xK();zP0=K6(uk(),1)});function yx(J){if(!J.startsWith("refs/heads/"))return null;return J.slice(11)}function t6(J,Q,Z,Y,X){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?X.call(J,Z):X?X.value=Z:Q.set(J,Z),Z}function P0(J,Q,Z,Y){if(Z==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!Y:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?Y:Z==="a"?Y.call(J):Y?Y.value:Q.get(J)}var YH=()=>{};var MB1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return MB1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Z=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^Z()&15>>+Y/4).toString(16))};function XH(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var vx=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var T4,o3,aJ,_M,fx,hx,bx,mx,gx,ux,px,dx,cx;var aX=B1(()=>{T4=class T4 extends Error{};o3=class o3 extends T4{constructor(J,Q,Z,Y){super(`${o3.makeMessage(J,Q,Z)}`);this.status=J,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Q}static makeMessage(J,Q,Z){let Y=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Z;if(J&&Y)return`${J} ${Y}`;if(J)return`${J} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate(J,Q,Z,Y){if(!J||!Y)return new _M({message:Z,cause:vx(Q)});let X=Q;if(J===400)return new hx(J,X,Z,Y);if(J===401)return new bx(J,X,Z,Y);if(J===403)return new mx(J,X,Z,Y);if(J===404)return new gx(J,X,Z,Y);if(J===409)return new ux(J,X,Z,Y);if(J===422)return new px(J,X,Z,Y);if(J===429)return new dx(J,X,Z,Y);if(J>=500)return new cx(J,X,Z,Y);return new o3(J,X,Z,Y)}};aJ=class aJ extends o3{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};_M=class _M extends o3{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};fx=class fx extends _M{constructor({message:J}={}){super({message:J??"Request timed out."})}};hx=class hx extends o3{};bx=class bx extends o3{};mx=class mx extends o3{};gx=class gx extends o3{};ux=class ux extends o3{};px=class px extends o3{};dx=class dx extends o3{};cx=class cx extends o3{}});function To(J){if(typeof J!=="object")return{};return J??{}}function IP0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function PP0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}var LD4,EP0=(J)=>{return LD4.test(J)},LB1=(J)=>(LB1=Array.isArray,LB1(J)),AB1,TP0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new T4(`${J} must be an integer`);if(Q<0)throw new T4(`${J} must be a positive integer`);return Q},Ro=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var kM=B1(()=>{aX();LD4=/^[a-z][a-z0-9+.-]*:/i,AB1=LB1});var RP0=(J)=>new Promise((Q)=>setTimeout(Q,J));var YU="0.71.0";function AD4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function wD4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Z}of J){let Y=Z.exec(navigator.userAgent);if(Y){let X=Y[1]||0,G=Y[2]||0,V=Y[3]||0;return{browser:Q,version:`${X}.${G}.${V}`}}}return null}var _P0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},OD4=()=>{let J=AD4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":jP0(Deno.build.os),"X-Stainless-Arch":CP0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":jP0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":CP0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=wD4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":YU,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},CP0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},jP0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},SP0,kP0=()=>{return SP0??(SP0=OD4())};var OB1=()=>{};function yP0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function wB1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function Co(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return wB1({start(){},async pull(Z){let{done:Y,value:X}=await Q.next();if(Y)Z.close();else Z.enqueue(X)},async cancel(){await Q.return?.()}})}function lx(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Z=await Q.read();if(Z?.done)Q.releaseLock();return Z}catch(Z){throw Q.releaseLock(),Z}},async return(){let Z=Q.cancel();return Q.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xP0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Z=Q.cancel();Q.releaseLock(),await Z}var vP0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};function bP0(J){let Q=0;for(let X of J)Q+=X.length;let Z=new Uint8Array(Q),Y=0;for(let X of J)Z.set(X,Y),Y+=X.length;return Z}function ix(J){let Q;return(fP0??(Q=new globalThis.TextEncoder,fP0=Q.encode.bind(Q)))(J)}function EB1(J){let Q;return(hP0??(Q=new globalThis.TextDecoder,hP0=Q.decode.bind(Q)))(J)}var fP0,hP0;class XU{constructor(){OY.set(this,void 0),wY.set(this,void 0),t6(this,OY,new Uint8Array,"f"),t6(this,wY,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?ix(J):J;t6(this,OY,bP0([P0(this,OY,"f"),Q]),"f");let Z=[],Y;while((Y=PD4(P0(this,OY,"f"),P0(this,wY,"f")))!=null){if(Y.carriage&&P0(this,wY,"f")==null){t6(this,wY,Y.index,"f");continue}if(P0(this,wY,"f")!=null&&(Y.index!==P0(this,wY,"f")+1||Y.carriage)){Z.push(EB1(P0(this,OY,"f").subarray(0,P0(this,wY,"f")-1))),t6(this,OY,P0(this,OY,"f").subarray(P0(this,wY,"f")),"f"),t6(this,wY,null,"f");continue}let X=P0(this,wY,"f")!==null?Y.preceding-1:Y.preceding,G=EB1(P0(this,OY,"f").subarray(0,X));Z.push(G),t6(this,OY,P0(this,OY,"f").subarray(Y.index),"f"),t6(this,wY,null,"f")}return Z}flush(){if(!P0(this,OY,"f").length)return[];return this.decode(`
153
153
  `)}}function PD4(J,Q){for(let X=Q??0;X<J.length;X++){if(J[X]===10)return{preceding:X,index:X+1,carriage:!1};if(J[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function mP0(J){for(let Y=0;Y<J.length-1;Y++){if(J[Y]===10&&J[Y+1]===10)return Y+2;if(J[Y]===13&&J[Y+1]===13)return Y+2;if(J[Y]===13&&J[Y+1]===10&&Y+3<J.length&&J[Y+2]===13&&J[Y+3]===10)return Y+4}return-1}var OY,wY;var IB1=B1(()=>{YH();OY=new WeakMap,wY=new WeakMap;XU.NEWLINE_CHARS=new Set([`
154
154
  `,"\r"]);XU.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function nx(){}function jo(J,Q,Z){if(!Q||So[J]>So[Z])return nx;else return Q[J].bind(Q)}function I2(J){let Q=J.logger,Z=J.logLevel??"off";if(!Q)return TD4;let Y=gP0.get(Q);if(Y&&Y[0]===Z)return Y[1];let X={error:jo("error",Q,Z),warn:jo("warn",Q,Z),info:jo("info",Q,Z),debug:jo("debug",Q,Z)};return gP0.set(Q,[Z,X]),X}var So,PB1=(J,Q,Z)=>{if(!J)return;if(PP0(So,J))return J;I2(Z).warn(`${Q} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(So))}`);return},TD4,gP0,$H=(J)=>{if(J.options)J.options={...J.options},delete J.options.headers;if(J.headers)J.headers=Object.fromEntries((J.headers instanceof Headers?[...J.headers]:Object.entries(J.headers)).map(([Q,Z])=>[Q,Q.toLowerCase()==="x-api-key"||Q.toLowerCase()==="authorization"||Q.toLowerCase()==="cookie"||Q.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in J){if(J.retryOfRequestLogID)J.retryOf=J.retryOfRequestLogID;delete J.retryOfRequestLogID}return J};var _o=B1(()=>{kM();So={off:0,error:200,warn:300,info:400,debug:500};TD4={error:nx,warn:nx,info:nx,debug:nx},gP0=new WeakMap});async function*RD4(J,Q){if(!J.body){if(Q.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new T4("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new T4("Attempted to iterate over a response with no body")}let Z=new uP0,Y=new XU,X=lx(J.body);for await(let G of CD4(X))for(let V of Y.decode(G)){let K=Z.decode(V);if(K)yield K}for(let G of Y.flush()){let V=Z.decode(G);if(V)yield V}}async function*CD4(J){let Q=new Uint8Array;for await(let Z of J){if(Z==null)continue;let Y=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?ix(Z):Z,X=new Uint8Array(Q.length+Y.length);X.set(Q),X.set(Y,Q.length),Q=X;let G;while((G=mP0(Q))!==-1)yield Q.slice(0,G),Q=Q.slice(G)}if(Q.length>0)yield Q}class uP0{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(J){if(J.endsWith("\r"))J=J.substring(0,J.length-1);if(!J){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
155
155
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push(J),J.startsWith(":"))return null;let[Q,Z,Y]=jD4(J,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Q==="event")this.event=Y;else if(Q==="data")this.data.push(Y);return null}}function jD4(J,Q){let Z=J.indexOf(Q);if(Z!==-1)return[J.substring(0,Z),Q,J.substring(Z+Q.length)];return[J,"",""]}var ax,EY;var TB1=B1(()=>{YH();aX();IB1();kM();_o();aX();EY=class EY{constructor(J,Q,Z){this.iterator=J,ax.set(this,void 0),this.controller=Q,t6(this,ax,Z,"f")}static fromSSEResponse(J,Q,Z){let Y=!1,X=Z?I2(Z):console;async function*G(){if(Y)throw new T4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let V=!1;try{for await(let K of RD4(J,Q)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(q){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),q}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(q){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),q}if(K.event==="ping")continue;if(K.event==="error")throw new o3(void 0,Ro(K.data)??K.data,void 0,J.headers)}V=!0}catch(K){if(XH(K))return;throw K}finally{if(!V)Q.abort()}}return new EY(G,Q,Z)}static fromReadableStream(J,Q,Z){let Y=!1;async function*X(){let V=new XU,K=lx(J);for await(let q of K)for(let W of V.decode(q))yield W;for(let q of V.flush())yield q}async function*G(){if(Y)throw new T4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let V=!1;try{for await(let K of X()){if(V)continue;if(K)yield JSON.parse(K)}V=!0}catch(K){if(XH(K))return;throw K}finally{if(!V)Q.abort()}}return new EY(G,Q,Z)}[(ax=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let J=[],Q=[],Z=this.iterator(),Y=(X)=>{return{next:()=>{if(X.length===0){let G=Z.next();J.push(G),Q.push(G)}return X.shift()}}};return[new EY(()=>Y(J),this.controller,P0(this,ax,"f")),new EY(()=>Y(Q),this.controller,P0(this,ax,"f"))]}toReadableStream(){let J=this,Q;return wB1({async start(){Q=J[Symbol.asyncIterator]()},async pull(Z){try{let{value:Y,done:X}=await Q.next();if(X)return Z.close();let G=ix(JSON.stringify(Y)+`
@@ -3120,7 +3120,7 @@ Use the create_handoff_context tool to extract relevant information and files.`;
3120
3120
  - Prioritize by importance, up to 12 items
3121
3121
  - Return workspace-relative paths (e.g., "core/src/threads/thread.ts")
3122
3122
  - Do not use absolute paths or invent files
3123
- `}},required:["relevantInformation","relevantFiles"]},source:"builtin",customizedForModel:!1};PY();VV();T7();function Ha4(J){return typeof J==="object"&&J!==null&&"credits"in J}function uc0(J){if(!Ha4(J))return 0;let Q=J.credits,Z=typeof Q==="string"?Number(Q):Q;return typeof Z==="number"&&Number.isFinite(Z)?Z:0}wG();O8();async function pc0(J,Q,Z,Y){let X=h7(J.content);if(!X)return{title:void 0,usage:void 0};let G=await jP({configService:Z},Y),V=crypto.randomUUID(),K=await G.messages.create({model:nr,max_tokens:60,temperature:0.7,system:`You are an assistant that generates short, descriptive titles (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") based on user's message to an agentic coding tool. Your titles should be concise (max 7 words) and capture the essence of the query or topic. DO NOT ASSUME OR GUESS the user's intent beyond what is in their message. Omit generic words like "question", "request", etc. Be professional and precise. Use common software engineering terms and acronyms if they are helpful. Use the set_title tool to provide your answer.`,messages:[{role:"user",content:`<message>${X}</message>`}],tools:[{name:"set_title",input_schema:{type:"object",properties:{title:{type:"string",description:'The short thread title (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") that you generated for the message'}},required:["title"]}}],tool_choice:{type:"tool",name:"set_title",disable_parallel_tool_use:!0}},{stream:!1,signal:Y,headers:{...dJ(Q),[pJ]:V}}),q=`anthropic/${nr.replace(/^[^/]+\//,"")}`,W=mJ(q),H={model:nr,maxInputTokens:W.contextWindow-W.maxOutputTokens,inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens,cacheCreationInputTokens:K.usage.cache_creation_input_tokens,cacheReadInputTokens:K.usage.cache_read_input_tokens,totalInputTokens:K.usage.input_tokens+(K.usage.cache_creation_input_tokens??0)+(K.usage.cache_read_input_tokens??0),credits:uc0(K.usage)},z=await Y2(V,Z);H.credits=z??0;let U=K.content.at(0);if(!U)throw Error("no content in generateThreadTitle response");if(U.type!=="tool_use"||U.name!=="set_title")throw Error("missing or invalid tool_use in generateThreadTitle response");return{title:U.input&&typeof U.input==="object"&&"title"in U.input&&typeof U.input.title==="string"?U.input.title:void 0,usage:H}}function dc0(J){let Q=/^Forked(?:\((\d+)\))?: (.+)$/,Z=J.match(Q);if(!Z)return`Forked: ${J||"Untitled"}`;let Y=Z[1]?Number.parseInt(Z[1],10):1,X=Z[2];return`Forked(${Y+1}): ${X}`}Ti();class _I1{storage;configService;exclusiveThreads=new I_;streamingConnections=new Map;get exclusiveThreadsChanges(){return this.exclusiveThreads.observable}dirtyThreads=new Set;flushRequests=new g4;flusher=this.flushRequests.pipe(L8(void 0),NG(100),B4(()=>{let J=Array.from(this.dirtyThreads);if(this.dirtyThreads=new Set,J.length===0)return P_;let Q=J.slice(0,3).map(async(Z)=>{try{await this.flushThread(Z)}catch(Y){x.error("Error flushing thread to storage:",Y,{name:"ThreadService",threadID:Z}),this.dirtyThreads.add(Z)}});if(J.length>3){for(let Z of J.slice(3))this.dirtyThreads.add(Z);setTimeout(()=>this.flushRequests.next(),100)}return h6(async()=>{await Promise.all(Q)})})).subscribe({});constructor(J,Q){this.storage=J;this.configService=Q}stopStreamingConnection(J){let Q=this.streamingConnections.get(J);if(Q)Q.abortController.abort(),Q.subscription?.unsubscribe(),Q.controller?.close(),this.streamingConnections.delete(J)}async flushThread(J){let Q=this.exclusiveThreads.get(J);if(!Q)return;let[Z]=Q.getValue();await this.storage.set(J,Z)}observeRaw(J){return this.exclusiveThreads.observable.pipe(Q6((Q)=>Q.get(J)),U4(),B4((Q)=>{if(Q!==void 0)return Q;return new t1((Z)=>{this.storage.get(J).then((Y)=>{if(Y)Z.next([zY(Y,!0),[]])})})}))}async getUnfrozen(J,Q){let Z=this.exclusiveThreads.get(J);if(Z)return Z.getValue()[0];let Y=await this.storage.get(J);if(Q?.throwIfAborted(),!Y)return null;return Y}async get(J,Q){let Z=await this.getUnfrozen(J,Q);if(!Z)return null;return zY(Z,!0)}async getPrimitiveProperty(J,Q){let Z=await this.getUnfrozen(J);if(!Z)return null;return Z[Q]}observe(J){return this.observeRaw(J).pipe(Q6(([Q,Z])=>Q),T_(100,{leading:!0,trailing:!0}))}observePatches(J){return this.observeRaw(J).pipe(Q6(([Q,Z],Y)=>Y===0?Q:Z),Ua4(100))}async exclusiveSyncReadWriter(J){if(this.exclusiveThreads.has(J))throw Error(`Thread ${J} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(J);if(!Q){let V=await this.storage.get(J);if(!V)V=Fa4(J),await this.storage.set(J,V);V=zY(V,!0),Q=new e9([V,[]]),this.exclusiveThreads.set(J,Q),await Qc0()}let X=(await this.configService.getLatest())?.settings?.["experimental.liveSync"]?this.startThreadUpdater(J):null,G=!1;return{read:()=>{if(G)throw Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(V)=>{if(G)throw Error("thread exclusive read-writer was disposed");let[K,q]=sD(Q.getValue()[0],()=>{return V});Q.next([K,q]),this.dirtyThreads.add(J),this.flushRequests.next()},update:(V)=>{if(G)throw Error("thread exclusive read-writer was disposed");let[K,q]=sD(Q.getValue()[0],V);return Q.next([K,q]),this.dirtyThreads.add(J),this.flushRequests.next(),K},asyncDispose:async()=>{if(G)return;G=!0,await X?.[Symbol.asyncDispose]();let[V]=Q.getValue();try{await this.storage.set(J,V)}catch(K){x.error("Error flushing thread on dispose:",K,{name:"ThreadService",threadID:J})}this.dirtyThreads.delete(J),this.exclusiveThreads.delete(J)}}}startThreadUpdater(J){let Q=new AbortController,Z;return(async()=>{while(!Q.signal.aborted){let X;try{let V=(await za4(J,this.configService)).getWriter();Z=V,X=this.observePatches(J).subscribe((K)=>{if(K instanceof Array)V.write({type:"thread:patches",patches:fc0(K)});else V.write({type:"thread:snapshot",thread:K})}),await V.closed}catch(G){x.error("Error in thread update stream",{error:G})}finally{X?.unsubscribe(),Z=void 0}if(!Q.signal.aborted)await WB(1000)}})(),{async[Symbol.asyncDispose](){Q.abort(),await Z?.close()}}}flush(){this.flushRequests.next()}async flushVersion(J,Q,Z=5000){this.dirtyThreads.add(J),await this.flushThread(J);let Y=Date.now();while(!0){if(Date.now()-Y>Z)throw Error(`Timed out waiting for thread ${J} to reach version ${Q}`);let X=await this.storage.get(J);if(X&&X.v>=Q)return;await new Promise((G)=>setTimeout(G,10))}}async forkThread(J,Q){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);let Y=Z.messages.slice(0,Q+1);return{threadID:await this.createForkedThread(J,Y,Q)}}async createForkedThread(J,Q,Z){let Y=await this.get(J);if(!Y)throw Error(`Thread ${J} not found`);let X=OG(),G=Date.now(),V=await this.exclusiveSyncReadWriter(X),K=dc0(Y.title||"Untitled"),q=V.update((z)=>{if(z.originThreadID=J,z.forkPointIndex=Z,z.v++,z.title=K,z.relationships=[{threadID:J,type:"fork",role:"child",messageIndex:Z,createdAt:G}],Y.env)z.env=x8(Y.env);for(let U of Q)z.messages.push(x8(U))});await V.asyncDispose();let W=this.exclusiveThreads.get(J);if(W){let[z]=W.getValue(),[U,D]=sD(z,(M)=>{if(M.v++,M.forkThreads??={},M.forkThreads[Z]??=[],!M.forkThreads[Z].includes(X))M.forkThreads[Z].push(X);if(M.relationships??=[],!M.relationships.some((A)=>A.threadID===X&&A.type==="fork"&&A.role==="parent"&&A.messageIndex===Z))M.relationships.push({threadID:X,type:"fork",role:"parent",messageIndex:Z,createdAt:G})});W.next([U,D]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let z=await this.exclusiveSyncReadWriter(J);z.update((U)=>{if(U.v++,U.forkThreads??={},U.forkThreads[Z]??=[],!U.forkThreads[Z].includes(X))U.forkThreads[Z].push(X);if(U.relationships??=[],!U.relationships.some((M)=>M.threadID===X&&M.type==="fork"&&M.role==="child"&&M.messageIndex===Z))U.relationships.push({threadID:X,type:"fork",role:"child",messageIndex:Z,createdAt:G})}),await z.asyncDispose()}let H=q.v;return await this.flushVersion(X,H),X}async generateHandoffPrompt(J,Q,Z,Y,X){let G=await this.get(J);if(!G)throw Error(`Thread ${J} not found`);return SI1(G,Q,Z,Y,X)}async createHandoffThread(J,Q,Z,Y){let{goal:X,generatedPrompt:G,images:V,messageIndex:K}=Q;if(!X&&!G)throw Error("Either goal or generatedPrompt must be provided");let q=await this.get(J);if(!q)throw Error(`Thread ${J} not found`);let H=G!==void 0?G:await SI1(q,X,V,Z,Y);Y.throwIfAborted();let z=OG(),U=K??(q.messages.length?q.messages.length-1:void 0),D=Date.now(),M=await this.exclusiveSyncReadWriter(z);M.update((A)=>{if(A.v++,q.env)A.env=x8(q.env);if(q.agentMode)A.agentMode=q.agentMode==="plan"?"smart":q.agentMode;A.draft=x8(H),A.relationships=[{threadID:J,type:"handoff",role:"child",messageIndex:U,createdAt:D,comment:X}]}),await M.asyncDispose();let L=this.exclusiveThreads.get(J);if(L){let[A]=L.getValue(),[E,I]=sD(A,(P)=>{if(P.v++,P.relationships??=[],!P.relationships.some((y)=>y.threadID===z&&y.type==="handoff"&&y.role==="parent"&&y.messageIndex===U))P.relationships.push({threadID:z,type:"handoff",role:"parent",messageIndex:U,createdAt:D,comment:X})});L.next([E,I]),this.dirtyThreads.add(J),await this.flushThread(J)}else{let A=await this.exclusiveSyncReadWriter(J);A.update((E)=>{if(E.v++,E.relationships??=[],!E.relationships.some((P)=>P.threadID===z&&P.type==="handoff"&&P.role==="parent"&&P.messageIndex===U))E.relationships.push({threadID:z,type:"handoff",role:"parent",messageIndex:U,createdAt:D,comment:X})}),await A.asyncDispose()}return z}async delete(J){let Q=await this.storage.keys(),Z=[];for(let Y of Q){let X=await this.storage.get(Y);if(X&&X.mainThreadID===J)Z.push(X.id)}for(let Y of Z)try{await this.storage.delete(Y)}catch(X){if(!nJ(X))throw X}try{await this.storage.delete(J)}catch(Y){if(!nJ(Y))throw Y}this.exclusiveThreads.delete(J),this.dirtyThreads.delete(J);try{let Y=await K5.deleteThread({thread:J},{config:this.configService});if(!Y.ok&&Y.error.code!=="thread-not-found")throw Error(`Error deleting thread from server: ${Y.error.message??Y.error.code}`)}catch(Y){if(Y instanceof Error&&Y.message.includes("404"))return;throw Y}}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[Y]=Z.getValue();if(S11(Y)>Q)J=Y,Q=S11(Y)}return J}async discardHandoffThread(J){let Q=await this.get(J);if(!Q?.relationships)return null;if(Q.messages.length>0)return null;let Z=Q.relationships.find((X)=>X.type==="handoff"&&X.role==="child");if(!Z)return null;let Y=this.exclusiveThreads.get(Z.threadID);if(Y){let[X]=Y.getValue(),[G,V]=sD(X,(K)=>{K.v++,K.relationships=K.relationships?.filter((q)=>!(q.threadID===J&&q.type==="handoff"&&q.role==="parent"))});Y.next([G,V]),this.dirtyThreads.add(Z.threadID),await this.flushThread(Z.threadID)}else{let X=await this.exclusiveSyncReadWriter(Z.threadID);X.update((G)=>{G.v++,G.relationships=G.relationships?.filter((V)=>!(V.threadID===J&&V.type==="handoff"&&V.role==="parent"))}),await X.asyncDispose(),await this.flushThread(Z.threadID)}return await this.delete(J),Z.threadID}async createPlanExecutionThread(J,Q="smart"){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);Gc0(Z);let Y=aF(Z),X=Kc0(Y,Z),G=OG(),V=Date.now(),K=await this.exclusiveSyncReadWriter(G),q=K.update((z)=>{if(z.v++,z.agentMode=Q,Z.env)z.env=x8(Z.env);z.draft=X});await K.asyncDispose();let W=q.v;await this.flushVersion(G,W);let H=this.exclusiveThreads.get(J);if(H){let[z]=H.getValue(),[U,D]=sD(z,(M)=>{if(M.v++,M.relationships??=[],!M.relationships.some((A)=>A.threadID===G&&A.type==="handoff"&&A.role==="parent"))M.relationships.push({threadID:G,type:"handoff",role:"parent",createdAt:V,comment:"Execution thread created from plan"})});H.next([U,D]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let z=await this.exclusiveSyncReadWriter(J);z.update((U)=>{if(U.v++,U.relationships??=[],!U.relationships.some((M)=>M.threadID===G&&M.type==="handoff"&&M.role==="parent"))U.relationships.push({threadID:G,type:"handoff",role:"parent",createdAt:V,comment:"Execution thread created from plan"})}),await z.asyncDispose()}return G}async asyncDispose(){this.flusher.unsubscribe();for(let J of this.streamingConnections.keys())this.stopStreamingConnection(J);await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}async function za4(J,Q){let{readable:Z,writable:Y}=new TransformStream;return U3(`/api/threads/${J}`,{method:"POST",body:Z.pipeThrough(new CI1).pipeThrough(new MI1).pipeThrough(new TextEncoderStream),headers:{"Content-Type":"text/event-stream"},duplex:"half"},Q).catch((X)=>{x.error("Failed to open stream to server",{error:X})}),Y}function Fa4(J){return{v:0,id:J,created:Date.now(),messages:[]}}function Ua4(J){return(Q)=>new t1((Z)=>{let Y=[],X=null,G=()=>{if(X)clearTimeout(X),X=null;if(Y.length>0)Z.next(Y),Y=[]};return Q.subscribe({next:(V)=>{if(!(V instanceof Array)){G(),Z.next(V);return}Y.push(...V),X=setTimeout(G,J)},error:(V)=>{G(),Z.error(V)},complete:()=>{G(),Z.complete()}})})}i0();U0();NF();RZ();gG();function cc0({threadService:J,threadHistoryService:Q,configService:Z,isExtensionDevelopment:Y=!1,retryIntervalMs:X=30000}){let G=!1,V=[],K=new iX1,q=new e9(new Map),W=async()=>{if(G)return!1;if(!await q6(YP0(Z)))return!1;let P=await Z.getLatest(new AbortController().signal);if(Y&&BF(P.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return x.debug(`Skipping sync to ${WZ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;if(P.settings["experimental.liveSync"])return x.debug("Skipping sync because experimental.liveSync is enabled",{name:"ThreadSyncService"}),!1;return!0},H=async(P)=>{if(!M(P))return;let R=await J.get(P);if(!R){K.delete(P);return}if(R.messages.length===0)return;if(!await W())return;let y=new AbortController,k={dispose:()=>y.abort()};V.push(k);try{try{let v=await K5.uploadThread({thread:R,createdOnServer:!1},{signal:y.signal,config:Z});if(!v.ok)throw Error(`Failed to upload thread: ${v.error.code}`)}catch(v){throw x.warn(`Failed to upload thread ${P}`,{name:"ThreadSyncService",threadID:P,error:v}),v}}finally{let v=V.indexOf(k);if(v!==-1)V.splice(v,1);if(y.abort(),V.length>30)x.debug("[AbortController] High disposables count detected: ",V.length,{name:"ThreadSyncService",operation:"uploadThread"})}},z=new Map,U=new Set,D=60000,M=(P)=>{if(U.has(P))return!1;let R=z.get(P);if(!R)return!0;let y=Date.now()-R,k=y>=D;if(!k)x.debug(`Skipping thread ${P} sync due to backoff (${Math.round(y/1000)}s elapsed of ${D/1000}s backoff)`,{name:"ThreadSyncService"});return k},L=async()=>{for(let P of K){if(!M(P))continue;try{await H(P),K.delete(P),z.delete(P)}catch(R){let y=R instanceof Error?R.message:String(R);if(y.includes("404")&&y.includes("Thread not found"))U.add(P),K.delete(P),z.delete(P),x.warn(`Thread ${P} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else z.set(P,Date.now()),x.warn(`Failed to sync thread ${P}, will retry after backoff`,{name:"ThreadSyncService",error:R})}}},A=async(P,R=!1)=>{if(!await W())return;let y;if(P)y=(await Promise.all(P.map(async(b)=>{let a=await J.get(b);return a?{id:a.id,v:a.v}:{id:b,v:-1}}))).filter((b)=>b!==null);else{let b=await q6(Q.observeHistory().pipe(Q6((G1)=>G1.map((e)=>({id:e.id,v:e.v}))))),a=await q6(J.exclusiveThreadsChanges.pipe(Q6((G1)=>Array.from(G1.values()).map((e)=>{let[c,J1]=e.getValue();return{id:c.id,v:c.v}}))));y=b.concat(a)}let k={threadVersions:[],threadMetas:[]},v=new Set;for(let b of y){if(v.has(b.id))continue;if(v.add(b.id),U.has(b.id))continue;if(!R)k.threadVersions.push({id:b.id,v:b.v});let a=q.getValue().get(b.id);k.threadMetas.push({id:b.id,meta:a?.status==="synced"&&a.info?a.info?.meta.visibility==="private"?{visibility:"private",sharedGroupIDs:a.info.meta.sharedGroupIDs}:{visibility:a.info.meta.visibility}:void 0})}if(k.threadVersions.length===0&&k.threadMetas.length===0)return;if(!await W())return;let g=new AbortController,d={dispose:()=>g.abort()};V.push(d);try{x.debug("Sending threads sync request",{name:"ThreadSyncService",source:R?"metadata":"full",threadCount:k.threadVersions.length+k.threadMetas.length});let b=await U3("/api/threads/sync",{method:"POST",body:JSON.stringify(k),signal:g.signal},Z);if(!b.ok){let e=await b.text().catch(()=>"Unable to read response body");throw x.warn("Threads sync request failed",{name:"ThreadSyncService",status:b.status,text:e}),Error(`Threads sync API responded with status: ${b.status}${e?`: ${e}`:""}`)}x.debug("Got response for threads sync request",{name:"ThreadSyncService",status:b.status});let a=await b.json(),G1=0;for(let e of a.threadActions){if(!(("action"in e)&&typeof e.action==="string"))continue;switch(e.action){case"upload":{if(!U.has(e.id))K.add(e.id),G1++;break}case"meta":{q.getValue().set(e.id,{status:"synced",info:{meta:e.meta}});break}case"download":{x.debug(`Processing download action for thread ${e.id}`,{name:"ThreadSyncService",threadID:e.id,hasThread:!!e.thread,threadV:e.thread?.v,hasEnv:!!e.thread?.env,treeCount:e.thread?.env?.initial?.trees?.length});try{let c=await J.exclusiveSyncReadWriter(e.id);try{let q1=structuredClone(e.thread);if(q1.env?.initial?.trees){let r=q1.env.initial.trees.map((o)=>({repository:o.repository,displayName:o.displayName,uri:void 0,fs:void 0}));q1.env={initial:{...q1.env.initial,trees:r}}}c.write(q1),x.debug(`Successfully wrote thread ${e.id} to storage`,{name:"ThreadSyncService",threadID:e.id}),await J.flushThread(e.id)}finally{await c.asyncDispose()}let J1=new AbortController;try{let q1=await J.get(e.id);if(q1){let L1=await K5.uploadThread({thread:q1,createdOnServer:!1},{signal:J1.signal,config:Z});if(!L1.ok){let r=L1.error.code==="thread-not-found"||L1.error.message?.includes("404"),o=L1.error.code==="permission-denied"||L1.error.message?.includes("403");if(r||o)x.warn(`Permanently failing thread ${e.id} due to unrecoverable error: ${L1.error.code}`,{error:L1.error}),U.add(e.id);else x.warn(`Failed to claim ownership of downloaded thread ${e.id} (will retry with backoff)`,{error:L1.error}),z.set(e.id,Date.now())}}}catch(q1){x.error(`Error claiming thread ${e.id} (will retry with backoff)`,q1,{name:"ThreadSyncService",threadID:e.id}),z.set(e.id,Date.now())}finally{J1.abort()}q.getValue().set(e.id,{status:"synced",info:null}),x.debug(`Thread ${e.id} download complete and flushed to storage`,{name:"ThreadSyncService",threadID:e.id})}catch(c){x.error(`Failed to store downloaded thread ${e.id}`,c,{name:"ThreadSyncService",threadID:e.id})}break}default:continue}}if(P){for(let e of P)if(q.getValue().get(e)?.status==="unknown")q.getValue().set(e,{status:"synced",info:null})}q.next(q.getValue()),await L(),x.debug(`Sync completed (${P?P.length:"all"} threads checked, ${G1} threads needed sync)`,{name:"ThreadSyncService"})}finally{let b=V.indexOf(d);if(b!==-1)V.splice(b,1);if(g.abort(),V.length>30)x.debug("[AbortController] High disposables count detected: ",V.length,{name:"ThreadSyncService",operation:"sync"})}};x.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let E=Promise.resolve();if(X>0){let P=setInterval(()=>{if(K.size>0)L().catch((R)=>x.error("Error in periodic sync retry:",R,{name:"ThreadSyncService"}))},X);V.push({dispose:()=>clearInterval(P)})}V.push(nX1(K.observable.pipe(g5((P)=>P.size>0),NG(3000),UF(()=>L().catch((P)=>x.error("Error processing sync queue:",P,{name:"ThreadSyncService"})))).subscribe({}))),V.push(nX1(J.exclusiveThreadsChanges.pipe(B4((P)=>TW(...Array.from(P.entries()).map(([,R])=>R.pipe(XY(([y,k])=>{if(!U.has(y.id))K.add(y.id)})))))).subscribe({})));let I=async()=>{if(!await W())return[];let P=new AbortController,R={dispose:()=>P.abort()};V.push(R);try{let y=await K5.discoverThreads({},{signal:P.signal,config:Z});if(!y.ok)return x.warn("Thread discovery failed",{name:"ThreadSyncService",error:y.error}),[];let{threadIDs:k}=y.result;if(k.length===0)return[];return x.debug("Discovered available threads from server",{name:"ThreadSyncService",threadCount:k.length}),await A(k,!1),k}finally{let y=V.indexOf(R);if(y!==-1)V.splice(y,1);P.abort()}};return{async sync(){return A()},async uploadThread(P){return H(P)},async discoverThreads(){return I()},initialSyncComplete:E,async updateThreadMeta(P,R){let y=q.getValue().get(P),k=new AbortController,v={dispose:()=>k.abort()};V.push(v);try{q.getValue().set(P,{status:"synced",info:{meta:{visibility:R.visibility,sharedGroupIDs:"sharedGroupIDs"in R?R.sharedGroupIDs:[]}}}),q.next(q.getValue());let g=await K5.setThreadMeta({thread:P,meta:R},{signal:k.signal,config:Z});if(!g.ok)throw x.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",{error:g.error}),Error(`Failed to update sharing status: ${g.error.code}`)}catch(g){if(y)q.getValue().set(P,y);else q.getValue().delete(P);throw q.next(q.getValue()),g}finally{let g=V.indexOf(v);if(g!==-1)V.splice(g,1);k.abort(),x.debug(`[AbortController] Cleaned up for updateThreadMeta ${P}, disposables count: ${V.length}`,{name:"ThreadSyncService",threadID:P,operation:"updateThreadMeta",wasTracked:g!==-1})}},threadSyncInfo(P){let R=[];for(let y of P){if(U.has(y)){if(!q.getValue().has(y))q.getValue().set(y,{status:"synced",info:null});continue}if(!q.getValue().has(y))q.getValue().set(y,{status:"unknown"}),R.push(y)}if(R.length>0)A(R,!0).catch((y)=>x.error("Error syncing thread metadata:",y,{name:"ThreadSyncService"}));return q.pipe(Q6((y)=>{let k={};for(let v of P)k[v]=y.get(v)??{status:"synced",info:null};return k}))},dispose(){if(G)return;G=!0;for(let P of V)P.dispose()}}}i0();U0();async function GR(J,Q,Z,Y){let X=await J.forkThread(Z);return await Ba4(Q,J.threadID,X,Y),X}async function Ba4(J,Q,Z,Y={}){let{originMetaTimeout:X=5000,forkedThreadTimeout:G=1e4,waitForForkedUpload:V=!0}=Y;try{let q=(await q6(J.threadSyncInfo([Q]).pipe(g5((H)=>H[Q]?.status==="synced"),zF(X))))[Q];if(q?.status!=="synced"||!q.info?.meta){x.debug("Origin thread has no metadata to inherit",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z});return}if(V)await q6(J.threadSyncInfo([Z]).pipe(g5((H)=>H[Z]?.status==="synced"),zF(G)));let W=q.info.meta.visibility==="private"?{visibility:q.info.meta.visibility,sharedGroupIDs:q.info.meta.sharedGroupIDs}:{visibility:q.info.meta.visibility};await J.updateThreadMeta(Z,W),x.debug("Successfully inherited thread visibility",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z,metadata:q.info.meta})}catch(K){x.debug("Failed to inherit thread visibility settings",{name:"inheritThreadVisibility",error:K,originThreadID:Q,forkedThreadID:Z})}}Pb();nI1();i0();i0();U0();function di0(J){return{registerTool:J.registerTool.bind(J),tools:J.tools,getTools:J.getTools.bind(J),isToolAllowed:J.isToolAllowed.bind(J),getToolsForMode:J.getToolsForMode.bind(J),preprocessArgs:J.preprocessArgs?.bind(J),getExecutionProfile:J.getExecutionProfile.bind(J),invokeTool(Q,Z,Y){return new t1((X)=>{let G=null,V=!1,K=()=>{if(V)return;G=J.invokeTool(Q,Z,Y).subscribe(X)};if(Z.userInput?.accepted===!0)return x.debug(`Tool ${String(Q)} already approved by user - bypassing permission check`),K(),()=>{V=!0,G?.unsubscribe()};if(Z.userInput?.accepted===!1)return x.debug(`Tool ${String(Q)} rejected by user`),X.next({status:"rejected-by-user",reason:"Tool execution rejected by user"}),X.complete(),()=>{V=!0};x.debug(`Tool ${String(Q)} - checking permissions`);let q=Y.thread.mainThreadID?"subagent":"thread";return L11(Q,Z.args,{configService:Y.configService},q,Y.thread.id,Y.toolUseID).then((W)=>{if(V||!W)return;let{permitted:H,reason:z,action:U,error:D}=W;if(!H){if(x.debug(`Tool ${String(Q)} not permitted - action: ${U}, reason: ${z}`),U==="ask"){X.next({status:"blocked-on-user",reason:z||"Tool requires user approval due to permissions"}),X.complete();return}if(U==="reject"&&D)X.next({status:"error",error:{message:D}});else X.next({status:"rejected-by-user",reason:z||"Tool execution denied by permissions"});X.complete();return}x.debug(`Tool ${String(Q)} permitted - action: ${U}`),K()}).catch((W)=>{if(V)return;x.error(`Permission check failed for tool ${String(Q)}:`,W),X.next({status:"error",error:{message:W.message||"Permission check failed"}}),X.complete()}),()=>{V=!0,G?.unsubscribe()}})},dispose(){J.dispose()}}}Z01();ii0();rL();VV();O8();var ni0={runInference:async(J,Q,Z,Y,X,G,V)=>{let K=crypto.randomUUID(),q=await G.configService.getLatest(V),W=await qB(J,Z.contents,Y,X,q,V,{systemInstruction:Q,tools:U11(Y)},K),H=await Y2(K,G.configService);if(W["~debugUsage"])W["~debugUsage"].credits=H??0;let U=(W.message.candidates?.[0]?.content?.parts?.filter((D)=>D.functionCall)??[]).map((D)=>{let M=D.functionCall;return{id:M.id??`${yW()}__${M.name}`,input:M.args??{},name:M.name??""}});return{result:W.message,toolUses:U,debugUsage:W["~debugUsage"]}},extractMessage:(J)=>{let Z=(J.candidates?.[0]?.content?.parts??[]).filter((Y)=>Y.text&&!Y.thought);if(Z.length===0)return;return Z.map((Y)=>Y.text??"").join("")},updateConversation:(J,Q,Z)=>{let Y=Q.candidates?.[0]?.content;if(!Y)return;if(J.contents.push({role:"model",parts:Y.parts??[]}),Z.length>0){let X=Z.map(({id:G,result:V})=>{let[,K]=G.split("__"),q={};if(V.status==="done")q.output=V.result;else if(V.status==="error")q.error=V.error?.message??"Error executing tool";else q.error=`Tool status: ${V.status}`;return{functionResponse:{name:K??"",response:q}}});J.contents.push({role:"user",parts:X})}}};function ai0(J){return{contents:[{role:"user",parts:[{text:J}]}]}}i0();PY();AG();z4();K01();Tb();CP();zA();var Cs4=({args:J},Q)=>{return new t1((Z)=>{let Y=new WA(q7.finder,aI1,J.query,Q),X=Y.subscribe({next:(G)=>Z.next(G),error:(G)=>{if(G instanceof yQ){let V=new oI1("Search agent reached context window limit. Please try a more specific search query.","Search agent reached context window limit and failed to return result.");Z.error(V)}else Z.error(G)},complete:()=>Z.complete()});return()=>{X.unsubscribe(),Y.dispose()}}).pipe(Q6(js4))};function js4(J){switch(J.status){case"in-progress":return{status:"in-progress",progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]}))};case"done":return{status:"done",result:J.message,progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]})),"~debug":J["~debug"]}}}var Qn0=`Intelligently search your codebase: Use it for complex, multi-step search tasks where you need to find code based on functionality or concepts rather than exact matches. Anytime you want to chain multiple grep calls you should use this tool.
3123
+ `}},required:["relevantInformation","relevantFiles"]},source:"builtin",customizedForModel:!1};PY();VV();T7();function Ha4(J){return typeof J==="object"&&J!==null&&"credits"in J}function uc0(J){if(!Ha4(J))return 0;let Q=J.credits,Z=typeof Q==="string"?Number(Q):Q;return typeof Z==="number"&&Number.isFinite(Z)?Z:0}wG();O8();async function pc0(J,Q,Z,Y){let X=h7(J.content);if(!X)return{title:void 0,usage:void 0};let G=await jP({configService:Z},Y),V=crypto.randomUUID(),K=await G.messages.create({model:nr,max_tokens:60,temperature:0.7,system:`You are an assistant that generates short, descriptive titles (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") based on user's message to an agentic coding tool. Your titles should be concise (max 7 words) and capture the essence of the query or topic. DO NOT ASSUME OR GUESS the user's intent beyond what is in their message. Omit generic words like "question", "request", etc. Be professional and precise. Use common software engineering terms and acronyms if they are helpful. Use the set_title tool to provide your answer.`,messages:[{role:"user",content:`<message>${X}</message>`}],tools:[{name:"set_title",input_schema:{type:"object",properties:{title:{type:"string",description:'The short thread title (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") that you generated for the message'}},required:["title"]}}],tool_choice:{type:"tool",name:"set_title",disable_parallel_tool_use:!0}},{stream:!1,signal:Y,headers:{...dJ(Q),[pJ]:V}}),q=`anthropic/${nr.replace(/^[^/]+\//,"")}`,W=mJ(q),H={model:nr,maxInputTokens:W.contextWindow-W.maxOutputTokens,inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens,cacheCreationInputTokens:K.usage.cache_creation_input_tokens,cacheReadInputTokens:K.usage.cache_read_input_tokens,totalInputTokens:K.usage.input_tokens+(K.usage.cache_creation_input_tokens??0)+(K.usage.cache_read_input_tokens??0),credits:uc0(K.usage)},z=await Y2(V,Z);H.credits=z??0;let U=K.content.at(0);if(!U)throw Error("no content in generateThreadTitle response");if(U.type!=="tool_use"||U.name!=="set_title")throw Error("missing or invalid tool_use in generateThreadTitle response");return{title:U.input&&typeof U.input==="object"&&"title"in U.input&&typeof U.input.title==="string"?U.input.title:void 0,usage:H}}function dc0(J){let Q=/^Forked(?:\((\d+)\))?: (.+)$/,Z=J.match(Q);if(!Z)return`Forked: ${J||"Untitled"}`;let Y=Z[1]?Number.parseInt(Z[1],10):1,X=Z[2];return`Forked(${Y+1}): ${X}`}Ti();class _I1{storage;configService;exclusiveThreads=new I_;get exclusiveThreadsChanges(){return this.exclusiveThreads.observable}dirtyThreads=new Set;flushRequests=new g4;flusher=this.flushRequests.pipe(L8(void 0),NG(100),B4(()=>{let J=Array.from(this.dirtyThreads);if(this.dirtyThreads=new Set,J.length===0)return P_;let Q=J.slice(0,3).map(async(Z)=>{try{await this.flushThread(Z)}catch(Y){x.error("Error flushing thread to storage:",Y,{name:"ThreadService",threadID:Z}),this.dirtyThreads.add(Z)}});if(J.length>3){for(let Z of J.slice(3))this.dirtyThreads.add(Z);setTimeout(()=>this.flushRequests.next(),100)}return h6(async()=>{await Promise.all(Q)})})).subscribe({});constructor(J,Q){this.storage=J;this.configService=Q}async flushThread(J){let Q=this.exclusiveThreads.get(J);if(!Q)return;let[Z]=Q.getValue();await this.storage.set(J,Z)}observeRaw(J){return this.exclusiveThreads.observable.pipe(Q6((Q)=>Q.get(J)),U4(),B4((Q)=>{if(Q!==void 0)return Q;return new t1((Z)=>{this.storage.get(J).then((Y)=>{if(Y)Z.next([zY(Y,!0),[]])})})}))}async getUnfrozen(J,Q){let Z=this.exclusiveThreads.get(J);if(Z)return Z.getValue()[0];let Y=await this.storage.get(J);if(Q?.throwIfAborted(),!Y)return null;return Y}async get(J,Q){let Z=await this.getUnfrozen(J,Q);if(!Z)return null;return zY(Z,!0)}async getPrimitiveProperty(J,Q){let Z=await this.getUnfrozen(J);if(!Z)return null;return Z[Q]}observe(J){return this.observeRaw(J).pipe(Q6(([Q,Z])=>Q),T_(100,{leading:!0,trailing:!0}))}observePatches(J){return this.observeRaw(J).pipe(Q6(([Q,Z],Y)=>Y===0?Q:Z),Ua4(100))}async exclusiveSyncReadWriter(J){if(this.exclusiveThreads.has(J))throw Error(`Thread ${J} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(J);if(!Q){let V=await this.storage.get(J);if(!V)V=Fa4(J),await this.storage.set(J,V);V=zY(V,!0),Q=new e9([V,[]]),this.exclusiveThreads.set(J,Q),await Qc0()}let X=(await this.configService.getLatest())?.settings?.["experimental.liveSync"]?this.startThreadUpdater(J):null,G=!1;return{read:()=>{if(G)throw Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(V)=>{if(G)throw Error("thread exclusive read-writer was disposed");let[K,q]=sD(Q.getValue()[0],()=>{return V});Q.next([K,q]),this.dirtyThreads.add(J),this.flushRequests.next()},update:(V)=>{if(G)throw Error("thread exclusive read-writer was disposed");let[K,q]=sD(Q.getValue()[0],V);return Q.next([K,q]),this.dirtyThreads.add(J),this.flushRequests.next(),K},asyncDispose:async()=>{if(G)return;G=!0,await X?.[Symbol.asyncDispose]();let[V]=Q.getValue();try{await this.storage.set(J,V)}catch(K){x.error("Error flushing thread on dispose:",K,{name:"ThreadService",threadID:J})}this.dirtyThreads.delete(J),this.exclusiveThreads.delete(J)}}}startThreadUpdater(J){let Q=new AbortController,Z;return(async()=>{while(!Q.signal.aborted){let X;try{let V=(await za4(J,this.configService)).getWriter();Z=V,X=this.observePatches(J).subscribe((K)=>{if(K instanceof Array)V.write({type:"thread:patches",patches:fc0(K)});else V.write({type:"thread:snapshot",thread:K})}),await V.closed}catch(G){x.error("Error in thread update stream",{error:G})}finally{X?.unsubscribe(),Z=void 0}if(!Q.signal.aborted)await WB(1000)}})(),{async[Symbol.asyncDispose](){Q.abort(),await Z?.close()}}}flush(){this.flushRequests.next()}async flushVersion(J,Q,Z=5000){this.dirtyThreads.add(J),await this.flushThread(J);let Y=Date.now();while(!0){if(Date.now()-Y>Z)throw Error(`Timed out waiting for thread ${J} to reach version ${Q}`);let X=await this.storage.get(J);if(X&&X.v>=Q)return;await new Promise((G)=>setTimeout(G,10))}}async forkThread(J,Q){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);let Y=Z.messages.slice(0,Q+1);return{threadID:await this.createForkedThread(J,Y,Q)}}async createForkedThread(J,Q,Z){let Y=await this.get(J);if(!Y)throw Error(`Thread ${J} not found`);let X=OG(),G=Date.now(),V=await this.exclusiveSyncReadWriter(X),K=dc0(Y.title||"Untitled"),q=V.update((z)=>{if(z.originThreadID=J,z.forkPointIndex=Z,z.v++,z.title=K,z.relationships=[{threadID:J,type:"fork",role:"child",messageIndex:Z,createdAt:G}],Y.env)z.env=x8(Y.env);for(let U of Q)z.messages.push(x8(U))});await V.asyncDispose();let W=this.exclusiveThreads.get(J);if(W){let[z]=W.getValue(),[U,D]=sD(z,(M)=>{if(M.v++,M.forkThreads??={},M.forkThreads[Z]??=[],!M.forkThreads[Z].includes(X))M.forkThreads[Z].push(X);if(M.relationships??=[],!M.relationships.some((A)=>A.threadID===X&&A.type==="fork"&&A.role==="parent"&&A.messageIndex===Z))M.relationships.push({threadID:X,type:"fork",role:"parent",messageIndex:Z,createdAt:G})});W.next([U,D]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let z=await this.exclusiveSyncReadWriter(J);z.update((U)=>{if(U.v++,U.forkThreads??={},U.forkThreads[Z]??=[],!U.forkThreads[Z].includes(X))U.forkThreads[Z].push(X);if(U.relationships??=[],!U.relationships.some((M)=>M.threadID===X&&M.type==="fork"&&M.role==="child"&&M.messageIndex===Z))U.relationships.push({threadID:X,type:"fork",role:"child",messageIndex:Z,createdAt:G})}),await z.asyncDispose()}let H=q.v;return await this.flushVersion(X,H),X}async generateHandoffPrompt(J,Q,Z,Y,X){let G=await this.get(J);if(!G)throw Error(`Thread ${J} not found`);return SI1(G,Q,Z,Y,X)}async createHandoffThread(J,Q,Z,Y){let{goal:X,generatedPrompt:G,images:V,messageIndex:K}=Q;if(!X&&!G)throw Error("Either goal or generatedPrompt must be provided");let q=await this.get(J);if(!q)throw Error(`Thread ${J} not found`);let H=G!==void 0?G:await SI1(q,X,V,Z,Y);Y.throwIfAborted();let z=OG(),U=K??(q.messages.length?q.messages.length-1:void 0),D=Date.now(),M=await this.exclusiveSyncReadWriter(z);M.update((A)=>{if(A.v++,q.env)A.env=x8(q.env);if(q.agentMode)A.agentMode=q.agentMode==="plan"?"smart":q.agentMode;A.draft=x8(H),A.relationships=[{threadID:J,type:"handoff",role:"child",messageIndex:U,createdAt:D,comment:X}]}),await M.asyncDispose();let L=this.exclusiveThreads.get(J);if(L){let[A]=L.getValue(),[E,I]=sD(A,(P)=>{if(P.v++,P.relationships??=[],!P.relationships.some((y)=>y.threadID===z&&y.type==="handoff"&&y.role==="parent"&&y.messageIndex===U))P.relationships.push({threadID:z,type:"handoff",role:"parent",messageIndex:U,createdAt:D,comment:X})});L.next([E,I]),this.dirtyThreads.add(J),await this.flushThread(J)}else{let A=await this.exclusiveSyncReadWriter(J);A.update((E)=>{if(E.v++,E.relationships??=[],!E.relationships.some((P)=>P.threadID===z&&P.type==="handoff"&&P.role==="parent"&&P.messageIndex===U))E.relationships.push({threadID:z,type:"handoff",role:"parent",messageIndex:U,createdAt:D,comment:X})}),await A.asyncDispose()}return z}async delete(J){let Q=await this.storage.keys(),Z=[];for(let Y of Q){let X=await this.storage.get(Y);if(X&&X.mainThreadID===J)Z.push(X.id)}for(let Y of Z)try{await this.storage.delete(Y)}catch(X){if(!nJ(X))throw X}try{await this.storage.delete(J)}catch(Y){if(!nJ(Y))throw Y}this.exclusiveThreads.delete(J),this.dirtyThreads.delete(J);try{let Y=await K5.deleteThread({thread:J},{config:this.configService});if(!Y.ok&&Y.error.code!=="thread-not-found")throw Error(`Error deleting thread from server: ${Y.error.message??Y.error.code}`)}catch(Y){if(Y instanceof Error&&Y.message.includes("404"))return;throw Y}}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[Y]=Z.getValue();if(S11(Y)>Q)J=Y,Q=S11(Y)}return J}async discardHandoffThread(J){let Q=await this.get(J);if(!Q?.relationships)return null;if(Q.messages.length>0)return null;let Z=Q.relationships.find((X)=>X.type==="handoff"&&X.role==="child");if(!Z)return null;let Y=this.exclusiveThreads.get(Z.threadID);if(Y){let[X]=Y.getValue(),[G,V]=sD(X,(K)=>{K.v++,K.relationships=K.relationships?.filter((q)=>!(q.threadID===J&&q.type==="handoff"&&q.role==="parent"))});Y.next([G,V]),this.dirtyThreads.add(Z.threadID),await this.flushThread(Z.threadID)}else{let X=await this.exclusiveSyncReadWriter(Z.threadID);X.update((G)=>{G.v++,G.relationships=G.relationships?.filter((V)=>!(V.threadID===J&&V.type==="handoff"&&V.role==="parent"))}),await X.asyncDispose(),await this.flushThread(Z.threadID)}return await this.delete(J),Z.threadID}async createPlanExecutionThread(J,Q="smart"){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);Gc0(Z);let Y=aF(Z),X=Kc0(Y,Z),G=OG(),V=Date.now(),K=await this.exclusiveSyncReadWriter(G),q=K.update((z)=>{if(z.v++,z.agentMode=Q,Z.env)z.env=x8(Z.env);z.draft=X});await K.asyncDispose();let W=q.v;await this.flushVersion(G,W);let H=this.exclusiveThreads.get(J);if(H){let[z]=H.getValue(),[U,D]=sD(z,(M)=>{if(M.v++,M.relationships??=[],!M.relationships.some((A)=>A.threadID===G&&A.type==="handoff"&&A.role==="parent"))M.relationships.push({threadID:G,type:"handoff",role:"parent",createdAt:V,comment:"Execution thread created from plan"})});H.next([U,D]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let z=await this.exclusiveSyncReadWriter(J);z.update((U)=>{if(U.v++,U.relationships??=[],!U.relationships.some((M)=>M.threadID===G&&M.type==="handoff"&&M.role==="parent"))U.relationships.push({threadID:G,type:"handoff",role:"parent",createdAt:V,comment:"Execution thread created from plan"})}),await z.asyncDispose()}return G}async asyncDispose(){this.flusher.unsubscribe(),await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}async function za4(J,Q){let{readable:Z,writable:Y}=new TransformStream;return U3(`/api/threads/${J}`,{method:"POST",body:Z.pipeThrough(new CI1).pipeThrough(new MI1).pipeThrough(new TextEncoderStream),headers:{"Content-Type":"text/event-stream"},duplex:"half"},Q).catch((X)=>{x.error("Failed to open stream to server",{error:X})}).then(async(X)=>{if(X&&!X.ok)x.error("Failed to open stream to server",{body:await X.text()})}),Y}function Fa4(J){return{v:0,id:J,created:Date.now(),messages:[]}}function Ua4(J){return(Q)=>new t1((Z)=>{let Y=[],X=null,G=()=>{if(X)clearTimeout(X),X=null;if(Y.length>0)Z.next(Y),Y=[]};return Q.subscribe({next:(V)=>{if(!(V instanceof Array)){G(),Z.next(V);return}Y.push(...V),X=setTimeout(G,J)},error:(V)=>{G(),Z.error(V)},complete:()=>{G(),Z.complete()}})})}i0();U0();NF();RZ();gG();function cc0({threadService:J,threadHistoryService:Q,configService:Z,isExtensionDevelopment:Y=!1,retryIntervalMs:X=30000}){let G=!1,V=[],K=new iX1,q=new e9(new Map),W=async()=>{if(G)return!1;if(!await q6(YP0(Z)))return!1;let P=await Z.getLatest(new AbortController().signal);if(Y&&BF(P.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return x.debug(`Skipping sync to ${WZ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;if(P.settings["experimental.liveSync"])return x.debug("Skipping sync because experimental.liveSync is enabled",{name:"ThreadSyncService"}),!1;return!0},H=async(P)=>{if(!M(P))return;let R=await J.get(P);if(!R){K.delete(P);return}if(R.messages.length===0)return;if(!await W())return;let y=new AbortController,k={dispose:()=>y.abort()};V.push(k);try{try{let v=await K5.uploadThread({thread:R,createdOnServer:!1},{signal:y.signal,config:Z});if(!v.ok)throw Error(`Failed to upload thread: ${v.error.code}`)}catch(v){throw x.warn(`Failed to upload thread ${P}`,{name:"ThreadSyncService",threadID:P,error:v}),v}}finally{let v=V.indexOf(k);if(v!==-1)V.splice(v,1);if(y.abort(),V.length>30)x.debug("[AbortController] High disposables count detected: ",V.length,{name:"ThreadSyncService",operation:"uploadThread"})}},z=new Map,U=new Set,D=60000,M=(P)=>{if(U.has(P))return!1;let R=z.get(P);if(!R)return!0;let y=Date.now()-R,k=y>=D;if(!k)x.debug(`Skipping thread ${P} sync due to backoff (${Math.round(y/1000)}s elapsed of ${D/1000}s backoff)`,{name:"ThreadSyncService"});return k},L=async()=>{for(let P of K){if(!M(P))continue;try{await H(P),K.delete(P),z.delete(P)}catch(R){let y=R instanceof Error?R.message:String(R);if(y.includes("404")&&y.includes("Thread not found"))U.add(P),K.delete(P),z.delete(P),x.warn(`Thread ${P} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else z.set(P,Date.now()),x.warn(`Failed to sync thread ${P}, will retry after backoff`,{name:"ThreadSyncService",error:R})}}},A=async(P,R=!1)=>{if(!await W())return;let y;if(P)y=(await Promise.all(P.map(async(b)=>{let a=await J.get(b);return a?{id:a.id,v:a.v}:{id:b,v:-1}}))).filter((b)=>b!==null);else{let b=await q6(Q.observeHistory().pipe(Q6((G1)=>G1.map((e)=>({id:e.id,v:e.v}))))),a=await q6(J.exclusiveThreadsChanges.pipe(Q6((G1)=>Array.from(G1.values()).map((e)=>{let[c,J1]=e.getValue();return{id:c.id,v:c.v}}))));y=b.concat(a)}let k={threadVersions:[],threadMetas:[]},v=new Set;for(let b of y){if(v.has(b.id))continue;if(v.add(b.id),U.has(b.id))continue;if(!R)k.threadVersions.push({id:b.id,v:b.v});let a=q.getValue().get(b.id);k.threadMetas.push({id:b.id,meta:a?.status==="synced"&&a.info?a.info?.meta.visibility==="private"?{visibility:"private",sharedGroupIDs:a.info.meta.sharedGroupIDs}:{visibility:a.info.meta.visibility}:void 0})}if(k.threadVersions.length===0&&k.threadMetas.length===0)return;if(!await W())return;let g=new AbortController,d={dispose:()=>g.abort()};V.push(d);try{x.debug("Sending threads sync request",{name:"ThreadSyncService",source:R?"metadata":"full",threadCount:k.threadVersions.length+k.threadMetas.length});let b=await U3("/api/threads/sync",{method:"POST",body:JSON.stringify(k),signal:g.signal},Z);if(!b.ok){let e=await b.text().catch(()=>"Unable to read response body");throw x.warn("Threads sync request failed",{name:"ThreadSyncService",status:b.status,text:e}),Error(`Threads sync API responded with status: ${b.status}${e?`: ${e}`:""}`)}x.debug("Got response for threads sync request",{name:"ThreadSyncService",status:b.status});let a=await b.json(),G1=0;for(let e of a.threadActions){if(!(("action"in e)&&typeof e.action==="string"))continue;switch(e.action){case"upload":{if(!U.has(e.id))K.add(e.id),G1++;break}case"meta":{q.getValue().set(e.id,{status:"synced",info:{meta:e.meta}});break}case"download":{x.debug(`Processing download action for thread ${e.id}`,{name:"ThreadSyncService",threadID:e.id,hasThread:!!e.thread,threadV:e.thread?.v,hasEnv:!!e.thread?.env,treeCount:e.thread?.env?.initial?.trees?.length});try{let c=await J.exclusiveSyncReadWriter(e.id);try{let q1=structuredClone(e.thread);if(q1.env?.initial?.trees){let r=q1.env.initial.trees.map((o)=>({repository:o.repository,displayName:o.displayName,uri:void 0,fs:void 0}));q1.env={initial:{...q1.env.initial,trees:r}}}c.write(q1),x.debug(`Successfully wrote thread ${e.id} to storage`,{name:"ThreadSyncService",threadID:e.id}),await J.flushThread(e.id)}finally{await c.asyncDispose()}let J1=new AbortController;try{let q1=await J.get(e.id);if(q1){let L1=await K5.uploadThread({thread:q1,createdOnServer:!1},{signal:J1.signal,config:Z});if(!L1.ok){let r=L1.error.code==="thread-not-found"||L1.error.message?.includes("404"),o=L1.error.code==="permission-denied"||L1.error.message?.includes("403");if(r||o)x.warn(`Permanently failing thread ${e.id} due to unrecoverable error: ${L1.error.code}`,{error:L1.error}),U.add(e.id);else x.warn(`Failed to claim ownership of downloaded thread ${e.id} (will retry with backoff)`,{error:L1.error}),z.set(e.id,Date.now())}}}catch(q1){x.error(`Error claiming thread ${e.id} (will retry with backoff)`,q1,{name:"ThreadSyncService",threadID:e.id}),z.set(e.id,Date.now())}finally{J1.abort()}q.getValue().set(e.id,{status:"synced",info:null}),x.debug(`Thread ${e.id} download complete and flushed to storage`,{name:"ThreadSyncService",threadID:e.id})}catch(c){x.error(`Failed to store downloaded thread ${e.id}`,c,{name:"ThreadSyncService",threadID:e.id})}break}default:continue}}if(P){for(let e of P)if(q.getValue().get(e)?.status==="unknown")q.getValue().set(e,{status:"synced",info:null})}q.next(q.getValue()),await L(),x.debug(`Sync completed (${P?P.length:"all"} threads checked, ${G1} threads needed sync)`,{name:"ThreadSyncService"})}finally{let b=V.indexOf(d);if(b!==-1)V.splice(b,1);if(g.abort(),V.length>30)x.debug("[AbortController] High disposables count detected: ",V.length,{name:"ThreadSyncService",operation:"sync"})}};x.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let E=Promise.resolve();if(X>0){let P=setInterval(()=>{if(K.size>0)L().catch((R)=>x.error("Error in periodic sync retry:",R,{name:"ThreadSyncService"}))},X);V.push({dispose:()=>clearInterval(P)})}V.push(nX1(K.observable.pipe(g5((P)=>P.size>0),NG(3000),UF(()=>L().catch((P)=>x.error("Error processing sync queue:",P,{name:"ThreadSyncService"})))).subscribe({}))),V.push(nX1(J.exclusiveThreadsChanges.pipe(B4((P)=>TW(...Array.from(P.entries()).map(([,R])=>R.pipe(XY(([y,k])=>{if(!U.has(y.id))K.add(y.id)})))))).subscribe({})));let I=async()=>{if(!await W())return[];let P=new AbortController,R={dispose:()=>P.abort()};V.push(R);try{let y=await K5.discoverThreads({},{signal:P.signal,config:Z});if(!y.ok)return x.warn("Thread discovery failed",{name:"ThreadSyncService",error:y.error}),[];let{threadIDs:k}=y.result;if(k.length===0)return[];return x.debug("Discovered available threads from server",{name:"ThreadSyncService",threadCount:k.length}),await A(k,!1),k}finally{let y=V.indexOf(R);if(y!==-1)V.splice(y,1);P.abort()}};return{async sync(){return A()},async uploadThread(P){return H(P)},async discoverThreads(){return I()},initialSyncComplete:E,async updateThreadMeta(P,R){let y=q.getValue().get(P),k=new AbortController,v={dispose:()=>k.abort()};V.push(v);try{q.getValue().set(P,{status:"synced",info:{meta:{visibility:R.visibility,sharedGroupIDs:"sharedGroupIDs"in R?R.sharedGroupIDs:[]}}}),q.next(q.getValue());let g=await K5.setThreadMeta({thread:P,meta:R},{signal:k.signal,config:Z});if(!g.ok)throw x.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",{error:g.error}),Error(`Failed to update sharing status: ${g.error.code}`)}catch(g){if(y)q.getValue().set(P,y);else q.getValue().delete(P);throw q.next(q.getValue()),g}finally{let g=V.indexOf(v);if(g!==-1)V.splice(g,1);k.abort(),x.debug(`[AbortController] Cleaned up for updateThreadMeta ${P}, disposables count: ${V.length}`,{name:"ThreadSyncService",threadID:P,operation:"updateThreadMeta",wasTracked:g!==-1})}},threadSyncInfo(P){let R=[];for(let y of P){if(U.has(y)){if(!q.getValue().has(y))q.getValue().set(y,{status:"synced",info:null});continue}if(!q.getValue().has(y))q.getValue().set(y,{status:"unknown"}),R.push(y)}if(R.length>0)A(R,!0).catch((y)=>x.error("Error syncing thread metadata:",y,{name:"ThreadSyncService"}));return q.pipe(Q6((y)=>{let k={};for(let v of P)k[v]=y.get(v)??{status:"synced",info:null};return k}))},dispose(){if(G)return;G=!0;for(let P of V)P.dispose()}}}i0();U0();async function GR(J,Q,Z,Y){let X=await J.forkThread(Z);return await Ba4(Q,J.threadID,X,Y),X}async function Ba4(J,Q,Z,Y={}){let{originMetaTimeout:X=5000,forkedThreadTimeout:G=1e4,waitForForkedUpload:V=!0}=Y;try{let q=(await q6(J.threadSyncInfo([Q]).pipe(g5((H)=>H[Q]?.status==="synced"),zF(X))))[Q];if(q?.status!=="synced"||!q.info?.meta){x.debug("Origin thread has no metadata to inherit",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z});return}if(V)await q6(J.threadSyncInfo([Z]).pipe(g5((H)=>H[Z]?.status==="synced"),zF(G)));let W=q.info.meta.visibility==="private"?{visibility:q.info.meta.visibility,sharedGroupIDs:q.info.meta.sharedGroupIDs}:{visibility:q.info.meta.visibility};await J.updateThreadMeta(Z,W),x.debug("Successfully inherited thread visibility",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z,metadata:q.info.meta})}catch(K){x.debug("Failed to inherit thread visibility settings",{name:"inheritThreadVisibility",error:K,originThreadID:Q,forkedThreadID:Z})}}Pb();nI1();i0();i0();U0();function di0(J){return{registerTool:J.registerTool.bind(J),tools:J.tools,getTools:J.getTools.bind(J),isToolAllowed:J.isToolAllowed.bind(J),getToolsForMode:J.getToolsForMode.bind(J),preprocessArgs:J.preprocessArgs?.bind(J),getExecutionProfile:J.getExecutionProfile.bind(J),invokeTool(Q,Z,Y){return new t1((X)=>{let G=null,V=!1,K=()=>{if(V)return;G=J.invokeTool(Q,Z,Y).subscribe(X)};if(Z.userInput?.accepted===!0)return x.debug(`Tool ${String(Q)} already approved by user - bypassing permission check`),K(),()=>{V=!0,G?.unsubscribe()};if(Z.userInput?.accepted===!1)return x.debug(`Tool ${String(Q)} rejected by user`),X.next({status:"rejected-by-user",reason:"Tool execution rejected by user"}),X.complete(),()=>{V=!0};x.debug(`Tool ${String(Q)} - checking permissions`);let q=Y.thread.mainThreadID?"subagent":"thread";return L11(Q,Z.args,{configService:Y.configService},q,Y.thread.id,Y.toolUseID).then((W)=>{if(V||!W)return;let{permitted:H,reason:z,action:U,error:D}=W;if(!H){if(x.debug(`Tool ${String(Q)} not permitted - action: ${U}, reason: ${z}`),U==="ask"){X.next({status:"blocked-on-user",reason:z||"Tool requires user approval due to permissions"}),X.complete();return}if(U==="reject"&&D)X.next({status:"error",error:{message:D}});else X.next({status:"rejected-by-user",reason:z||"Tool execution denied by permissions"});X.complete();return}x.debug(`Tool ${String(Q)} permitted - action: ${U}`),K()}).catch((W)=>{if(V)return;x.error(`Permission check failed for tool ${String(Q)}:`,W),X.next({status:"error",error:{message:W.message||"Permission check failed"}}),X.complete()}),()=>{V=!0,G?.unsubscribe()}})},dispose(){J.dispose()}}}Z01();ii0();rL();VV();O8();var ni0={runInference:async(J,Q,Z,Y,X,G,V)=>{let K=crypto.randomUUID(),q=await G.configService.getLatest(V),W=await qB(J,Z.contents,Y,X,q,V,{systemInstruction:Q,tools:U11(Y)},K),H=await Y2(K,G.configService);if(W["~debugUsage"])W["~debugUsage"].credits=H??0;let U=(W.message.candidates?.[0]?.content?.parts?.filter((D)=>D.functionCall)??[]).map((D)=>{let M=D.functionCall;return{id:M.id??`${yW()}__${M.name}`,input:M.args??{},name:M.name??""}});return{result:W.message,toolUses:U,debugUsage:W["~debugUsage"]}},extractMessage:(J)=>{let Z=(J.candidates?.[0]?.content?.parts??[]).filter((Y)=>Y.text&&!Y.thought);if(Z.length===0)return;return Z.map((Y)=>Y.text??"").join("")},updateConversation:(J,Q,Z)=>{let Y=Q.candidates?.[0]?.content;if(!Y)return;if(J.contents.push({role:"model",parts:Y.parts??[]}),Z.length>0){let X=Z.map(({id:G,result:V})=>{let[,K]=G.split("__"),q={};if(V.status==="done")q.output=V.result;else if(V.status==="error")q.error=V.error?.message??"Error executing tool";else q.error=`Tool status: ${V.status}`;return{functionResponse:{name:K??"",response:q}}});J.contents.push({role:"user",parts:X})}}};function ai0(J){return{contents:[{role:"user",parts:[{text:J}]}]}}i0();PY();AG();z4();K01();Tb();CP();zA();var Cs4=({args:J},Q)=>{return new t1((Z)=>{let Y=new WA(q7.finder,aI1,J.query,Q),X=Y.subscribe({next:(G)=>Z.next(G),error:(G)=>{if(G instanceof yQ){let V=new oI1("Search agent reached context window limit. Please try a more specific search query.","Search agent reached context window limit and failed to return result.");Z.error(V)}else Z.error(G)},complete:()=>Z.complete()});return()=>{X.unsubscribe(),Y.dispose()}}).pipe(Q6(js4))};function js4(J){switch(J.status){case"in-progress":return{status:"in-progress",progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]}))};case"done":return{status:"done",result:J.message,progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]})),"~debug":J["~debug"]}}}var Qn0=`Intelligently search your codebase: Use it for complex, multi-step search tasks where you need to find code based on functionality or concepts rather than exact matches. Anytime you want to chain multiple grep calls you should use this tool.
3124
3124
 
3125
3125
  WHEN TO USE THIS TOOL:
3126
3126
  - You must locate code by behavior or concept
@@ -4110,11 +4110,11 @@ Actual: ${X}`)}async function x28(J,Q,Z){let{execSync:Y}=await import("node:ch
4110
4110
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))M+=`
4111
4111
 
4112
4112
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4113
- npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function I61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=m28(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return x.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function m28(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}i0();function P61(J,Q){let Z=new g4,Y=Z.pipe(T8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new HK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await WB(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=xA(),W=await I61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await E61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Z.next("update-available");return}try{await Im(W.latestVersion,z);let U=await TB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await WB(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Eq}from"node:process";function I06(J){let Q=new MA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await aR1(Y.force||!1,Y.verbose||!1,"0.0.1765404020-g2e5656"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new MA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await g28(Y.targetVersion)});J.addCommand(Z)}async function g28(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Eq.write(Y4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4113
+ npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function I61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=m28(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return x.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function m28(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}i0();function P61(J,Q){let Z=new g4,Y=Z.pipe(T8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new HK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await WB(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=xA(),W=await I61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await E61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Z.next("update-available");return}try{await Im(W.latestVersion,z);let U=await TB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await WB(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Eq}from"node:process";function I06(J){let Q=new MA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await aR1(Y.force||!1,Y.verbose||!1,"0.0.1765411294-g5611a8"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new MA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await g28(Y.targetVersion)});J.addCommand(Z)}async function g28(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Eq.write(Y4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4114
4114
 
4115
4115
  `));try{if(!J){Eq.write(Y4.blue(`Checking for updates...
4116
- `));let Z=xA(),{hasUpdate:Y,latestVersion:X}=await I61("0.0.1765404020-g2e5656",Z);if(!Y){Eq.write(Y4.green(`✓ Amp CLI is already up to date: ${"0.0.1765404020-g2e5656"} (${"released"} ${"2025-12-10T22:05:22.702Z"}${`, ${gI(new Date("2025-12-10T22:05:22.702Z"))} ago`})
4117
- `));let V=await TB("0.0.1765404020-g2e5656");if(V.warning)Eq.write(`
4116
+ `));let Z=xA(),{hasUpdate:Y,latestVersion:X}=await I61("0.0.1765411294-g5611a8",Z);if(!Y){Eq.write(Y4.green(`✓ Amp CLI is already up to date: ${"0.0.1765411294-g5611a8"} (${"released"} ${"2025-12-11T00:06:58.334Z"}${`, ${gI(new Date("2025-12-11T00:06:58.334Z"))} ago`})
4117
+ `));let V=await TB("0.0.1765411294-g5611a8");if(V.warning)Eq.write(`
4118
4118
  `+Y4.yellow(V.warning)+`
4119
4119
  `);process.exit(0)}if(!X)Eq.write(Y4.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Eq.write(Y4.blue(`Updating to version ${J}...
4120
4120
  `)),await Im(J,void 0,(Z)=>{Eq.write(Y4.dim(`Running: ${Z}
@@ -4748,7 +4748,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let a=W.text.replace(/`([^`]+)`/g,"$1")+`
4748
4748
  `,A)])}),k];if(!q&&!U&&W.url){let b=W.url.replace(/^https?:\/\//,"");g.push(new i5({uri:W.url,text:b,style:new s({color:Z.secondary,underline:!0})}))}if(y&&!U)g.push(y);let d=new Q0({width:40,child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:g})});return C4.child(new B6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new Oj1({width:o_1,height:r_1,agentMode:this.widget.agentMode,glow:this._glow,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:P,...V==="disabled"&&{seed:42}}),new Q0({width:2}),d]}))}}U0();O8();z4();H7();O8();i0();function dW8(J,Q){return`${J}:${Q}`}class s_1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new t1((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.subthreadObservable=new t1((Q)=>{return this.emitSubthread=(Z)=>Q.next(Z),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new t1((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Z=this.threadService.observePatches(Q).pipe(JM()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Y);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=dW8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(JM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);let Y=this.subthreadsSubs.get(J);if(Y)Y.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new t1((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),subthreads:new t1((Q)=>{return this.subthreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new t1((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=JA(Z,Y)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function cW8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:Y}=Q,X=J.subagents[Y.threadID];if(!X){if(X={subThreadID:Z.id,parentToolID:Y.toolUse.id,taskDescription:Y.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=gJ(J.mainThread);X.isCompleted=L36(W,Y.toolUse.id)}}let G=lW8(Z,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=AC(Z).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Z.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Y.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:Y,workerStatus:X}=Q,G=gJ(Z),V={...J.subagents};for(let z of Y){let U=V[z.threadID];if(!U)continue;let D=L36(G,z.toolUse.id);V[z.threadID]={...U,isCompleted:D}}let{items:K}=AC(Z),q=JA(Z,X),W=pE({messages:Z.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=JA(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function AC(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let D of U.content)if(D.type==="tool_result"&&D.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??UY(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function L36(J,Q){let Z=J.get(Q);return(Z&&K3(Z.run))??!1}function lW8(J,Q){let Z=J.messages.at(-1);if(Z?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return x.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(AC(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Z&&Z.role==="assistant"&&Z.state.type==="streaming")switch(Z.content.at(-1)?.type){case"text":return x.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return x.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return x.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return x.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class t_1 extends p0{props;constructor(J){super();this.props=J}createState(){return new A36}}class A36 extends u0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new s_1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Z=Q.mainThread.subscribe((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Z);let Y=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Y);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=cW8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Z=(G)=>G===A5||G===a8||G===FY,Y=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Z(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Y.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let z of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:mE(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class e_1 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new O36}}class O36 extends u0{build(J){let Z=X6.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new Q0({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new b0({child:new W6({padding:H0.symmetric(1,0),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new S1({text:new l(X,new s({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new s({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new s({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new B6({crossAxisAlignment:"start",children:[new S1({text:new l(Z,X)}),new Q0({width:1}),new d6({child:new S1({text:new l(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Jk1 extends E6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y}build(J){let Q=X6.of(J),Z=Q.colors.primary,Y=Q.colors.foreground;return new b0({decoration:new N8(void 0,new F4(new G4(Z,1,"rounded"),new G4(Z,1,"rounded"),void 0,new G4(Z,1,"rounded"))),child:new W6({padding:H0.horizontal(1),child:new x0({children:[new B6({crossAxisAlignment:"start",children:[new d6({child:new S1({text:new l(this.ad.content,new s({color:Y}))})}),new Q0({width:4}),new i5({uri:"https://ampcode.com/free",text:"Ad",style:new s({color:Y,dim:!0})})]}),new B6({crossAxisAlignment:"start",children:[new kj1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:H0.horizontal(1),color:Z,reverse:!0}),new Q0({width:2}),new S1({text:new l(this.ad.destinationUrlHostname,new s({color:Y,dim:!0}))})]})]})})})}}class Qk1 extends p0{props;constructor(J){super();this.props=J}createState(){return new w36(this.props.autofocus??!0)}}class w36 extends u0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=S4.sizeOf(J),Y=Math.min(60,Z.width-4),X=Z.height-4,G=[];if(this.widget.props.title)G.push(new S1({text:new l(this.widget.props.title,new s({bold:!0,color:H1.blue}))}),new Q0({height:1}));if(this.widget.props.message)G.push(new S1({text:new l(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new Q0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new S1({text:new l("Enter to copy",new s({dim:!0}))}));return V.push(new S1({text:new l("Escape to close",new s({dim:!0}))})),G.push(new B6({children:V.flatMap((K,q)=>q<V.length-1?[K,new Q0({width:1}),new S1({text:new l("•",new s({dim:!0}))}),new Q0({width:1})]:[K]),mainAxisSize:"min"})),new C4({child:new b0({constraints:new L6(Y,Y,0,X),decoration:new N8(H1.default(),new F4(new G4(H1.blue,1,"rounded"),new G4(H1.blue,1,"rounded"),new G4(H1.blue,1,"rounded"),new G4(H1.blue,1,"rounded"))),padding:new H0(2,2,2,2),child:new z8({autofocus:this.autofocus,onKey:Q,child:new x0({children:G,mainAxisSize:"min"})})})})}}class Z91 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,Z91.prototype)}}class Y91 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,Y91.prototype)}}function Zk1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}nW();U0();import{spawn as iW8}from"node:child_process";import{promises as nW8}from"node:fs";function E36(J){return J.kind==="executable"}function I36(J){return J.kind==="markdown"}var Xz=50000,P36=300000;async function Yk1(J,Q,Z,Y={}){let{timeoutMs:X=P36,signal:G,source:V}=Y;try{let K=await Z.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(x.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),I36(K))return await aW8(K,Q);else if(E36(K))return await oW8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return x.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function aW8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await nW8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>Xz?Z.slice(0,Xz)+`
4749
4749
  ... (output truncated at ${Xz} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function oW8(J,Q,Z=P36,Y){return new Promise((X)=>{let[G,V]=rW8(J,Q);x.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Z});let K=SO0(Y),q=!1,W=setTimeout(()=>{q=!0,K.abort(),x.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),H=iW8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],U=[],D=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)z.push(L);else{let A=Xz-(D-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)U.push(L);else{let A=Xz-(D-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),I=A;if(!L&&!A.trim()&&E.trim())I=E;else if(E.trim())I+=A?`
4750
4750
  ${E}`:E;if(D>Xz)I+=`
4751
- ... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function rW8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return tW8(Z,Y?[...Y]:null,X,Q);else return sW8(Z,Y?[...Y]:null,X,Q)}function sW8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function tW8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();LG();T7();BK();RZ();gG();aW();gK();O8();H7();E_();i0();var J26=K6(EP(),1);import{writeFile as s36}from"fs/promises";import t36 from"path";U0();RZ();class Xk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1765404020-g2e5656"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Lo(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class OC extends p0{props;constructor(J){super();this.props=J}createState(){return new T36}}class T36 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class R36 extends u0{controller=new dZ;focusNode=new $8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=F4.all(new G4(Z.foreground,1,"solid")),q=new Jz({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new B6({children:[new b0({decoration:{color:H1.default()},child:new S1({text:new l(">",new s({color:Z.foreground}))})}),new d6({child:q})]}),H=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,[new l("Command: ",new s({color:Z.foreground})),new l(this.widget.props.commandName,new s({color:H1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new l("Enter",new s({color:Y.keybind}))),z.push(new l(" to submit, ",new s({color:Z.foreground,dim:!0})));z.push(new l("Esc",new s({color:Y.keybind}))),z.push(new l(" to cancel",new s({color:Z.foreground,dim:!0})));let U=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,z)})});return new b0({decoration:{border:K,color:H1.default()},padding:H0.all(1),child:new x0({children:[H,new Q0({height:1}),W,new Q5,U]})})}}class X91 extends p0{props;constructor(J){super();this.props=J}createState(){return new R36}}aW();class C36 extends u0{controller=new dZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new $8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=iF)return!1;let Q=XC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,G=S4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new $O({controller:this.controller,triggers:[new rB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:f8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new z8({focusNode:this.focusNode,child:K}),W=new b0({constraints:new L6({maxHeight:V}),padding:H0.symmetric(1,0),child:q}),H=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,[new l("Command: ",new s({color:Z.foreground})),new l(this.widget.props.commandName,new s({color:H1.yellow,bold:!0}))])})}),z=new b0({padding:H0.symmetric(1,0),child:new S1({text:this.isConfirmingClearInput?new l("",void 0,[new l("Esc",new s({color:Y.keybind})),new l(" again to clear input",new s({color:Z.foreground,dim:!0}))]):new l("",void 0,[new l("Press ",new s({color:Z.foreground,dim:!0})),new l("Enter",new s({color:Y.keybind})),new l(" to submit, ",new s({color:Z.foreground,dim:!0})),new l("Esc",new s({color:Y.keybind})),new l(" to clear",new s({color:Z.foreground,dim:!0}))])})}),U=[H,new Q0({height:1}),new d6({child:W}),new Q0({height:1}),z];return new b0({decoration:{border:F4.all(new G4(Z.foreground,1,"solid")),color:H1.default()},padding:H0.all(1),child:new x0({children:U})})}}class wC extends p0{props;constructor(J){super();this.props=J}createState(){return new C36}}import{isDeepStrictEqual as ZH8}from"node:util";var eW8=/[\\/_ +.#"@[({&]/,JH8=/[\\/_ +.#"@[({&]/g,QH8=/[\s-]/,j36=/[\s-]/g;function G91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=G91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(QH8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(j36),M&&X>0)z*=Math.pow(0.999,M.length)}else if(eW8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(JH8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=G91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function $91(J){return J.toLowerCase().replace(j36," ")}function S36(J,Q){let Z=G91(J,Q,$91(J),$91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=G91(J,K,$91(J),$91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class EC{}class IC{}class V91{}class K91{}class _36 extends p0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new k36}}class k36 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function YH8(J,Q){if(J==="")return{matches:!0,score:1};let Z=S36(Q,J);return{matches:Z>0.15,score:Z}}class DJ extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new y36}}class y36 extends u0{controller=new dZ;focusNode;scrollController=new l5;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new $8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),p8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!ZH8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof EC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof V91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof K91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...YH8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;Q81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),p8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=F4.all(new G4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new Jz({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new rY({shortcuts:new Map([[new X4("ArrowDown"),new EC],[new X4("ArrowUp"),new IC],[new X4("Tab"),new EC],[new X4("Tab",{shift:!0}),new IC],[new X4("n",{ctrl:!0}),new EC],[new X4("p",{ctrl:!0}),new IC],[new X4("Enter"),new V91],[new X4("Escape"),new K91]]),focusNode:this.focusNode,child:V}),q=new zJ({actions:new Map([[EC,new E8(this.invoke)],[IC,new E8(this.invoke)],[V91,new E8(this.invoke)],[K91,new E8(this.invoke)]]),child:K}),W=new B6({children:[new b0({decoration:{color:H1.default()},child:new S1({text:new l(">",new s({color:Z.foreground}))})}),new d6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new Q0({height:10,child:new C4({child:new S1({text:new l(L,new s({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new d6({child:new C4({child:new S1({text:new l(this.widget.props.emptyStateText,new s({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let y=I?H1.yellow:void 0,k=I?H1.black:Z.foreground;R=new b0({decoration:y?{color:y}:void 0,padding:H0.symmetric(2,0),child:new S1({text:new l(this.widget.props.getLabel(A),new s({color:k,dim:P}))})})}return new _36(new G8({onClick:(y)=>this.handleItemClick(E,y.clickCount),child:R}),(y)=>{this.itemContexts[E]=y})});H=new x0({children:L,crossAxisAlignment:"start"})}let z=new d6({child:new G8({onScroll:this.handleScroll,opaque:!1,child:new W5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l(this.widget.props.title,new s({color:H1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new Q0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new b0({padding:H0.vertical(1),child:new C4({child:A})}));else U.push(new Q0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new b0({decoration:{border:X,color:H1.default()},padding:H0.symmetric(1,0),child:new x0({children:U})})}}function x36(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class $k1 extends E6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>x36(X.pubDate).length));return new DJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?H1.yellow:void 0,z=G?H1.black:W.foreground,U=H1.index(8),D=(M,L)=>new Q0({width:L,child:B6.end([new S1({text:new l(M,new s({color:U}))})])});return new b0({decoration:H?{color:H}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[new d6({child:new S1({text:new l(X.title,new s({color:z})),overflow:"ellipsis",maxLines:1})}),new Q0({width:2}),D(x36(X.pubDate),Z)]})})}})}}class Gk1 extends p0{createState(){return new v36}}class v36 extends u0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new S1({text:new l("●",new s({color:this.isGreen?H1.green:H1.index(8),bold:!0})),maxLines:1})}}function XH8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return tY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function Vk1(J,Q,Z){return new S1({text:new l(`${J}${Q}`,new s({color:Z})),maxLines:1})}function $H8(J,Q,Z,Y){return[Vk1("+",J,Y.success),Q5.horizontal(1),Vk1("~",Q,Y.warning),Q5.horizontal(1),Vk1("-",Z,Y.destructive)]}class q91 extends E6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=XH8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=X6.of(J),q=new W6({padding:H0.symmetric(0,1),child:new C4({child:new S1({text:new l("",new s({color:K.colors.foreground,dim:!0}),[new l("Ctrl+T",new s({color:H1.blue,dim:!0})),new l(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new s({color:K.colors.foreground,dim:!0}))])})})});return new DJ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=X6.of(D),{colors:L}=M,A=z?H1.yellow:void 0,E=z?H1.black:L.foreground,I=H1.index(8),P=(G1,e)=>new Q0({width:e,child:B6.end([new S1({text:new l(G1,new s({color:I}))})])}),R=this.props.threadViewStates[H.id],y=[],k=H.relationshipType==="handoff",v=new K81;if(H.depth>0){let G1=[],e=H.ancestorsAreLast.slice(1);for(let q1 of e)G1.push(new l(v.getAncestorPrefix(q1),new s({color:v.connectorColor,dim:v.connectorDim})));let c=H.isLast?v.elbow:v.tee,J1=v.getConnectorText(c);G1.push(new l(J1,new s({color:v.connectorColor,dim:v.connectorDim}))),y.push(new S1({text:new l("",void 0,G1)}))}let g=[],d=this.props.currentThreadID===H.id?new l("(current) ",new s({color:H1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new l("(visited) ",new s({color:L.foreground,dim:!0})):null;if(d)g.push(new S1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))g.push(new Gk1),g.push(new Q0({width:1}))}let b=H.title;if(H.relationshipType==="fork"){let G1=b.match(/^Forked\((\d+)\): /);if(G1)b=b.slice(G1[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);g.push(new S1({text:new l("[fork] ",new s({color:H1.blue}))}))}else if(k)g.push(new S1({text:new l("[handoff] ",new s({color:H1.index(208)}))}));if(H.agentMode==="plan"&&H.hasPlan)g.push(new S1({text:new l("[plan] ",new s({color:H1.magenta}))}));if(g.push(new d6({child:new S1({text:new l(b,new s({color:E})),overflow:"ellipsis",maxLines:1})})),g.push(new Q0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let G1=z?{success:I,warning:I,destructive:I}:L;g.push(...$H8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,G1)),g.push(new Q0({width:2}))}return g.push(P(H.description.timeAgo,V)),new b0({decoration:A?{color:A}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[...y,...g]})})}})}}function f36(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Kk1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>f36(X.pubDate).length));return new DJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?H1.yellow:void 0,z=G?H1.black:W.foreground,U=H1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new Q0({width:A,child:B6.end([new S1({text:new l(L,new s({color:U}))})])});return new b0({decoration:H?{color:H}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[new d6({child:new S1({text:new l(X.title,new s({color:z})),overflow:"ellipsis",maxLines:1})}),new Q0({width:2}),new S1({text:new l(D,new s({color:U})),maxLines:1}),new Q0({width:2}),M(f36(X.pubDate),Z)]})})}})}}class qk1 extends E6{props;constructor(J){super();this.props=J}build(){return new C4({child:new S1({text:new l("",void 0,[new l(`Forked to new thread:
4751
+ ... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function rW8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return tW8(Z,Y?[...Y]:null,X,Q);else return sW8(Z,Y?[...Y]:null,X,Q)}function sW8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function tW8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();LG();T7();BK();RZ();gG();aW();gK();O8();H7();E_();i0();var J26=K6(EP(),1);import{writeFile as s36}from"fs/promises";import t36 from"path";U0();RZ();class Xk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1765411294-g5611a8"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Lo(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class OC extends p0{props;constructor(J){super();this.props=J}createState(){return new T36}}class T36 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class R36 extends u0{controller=new dZ;focusNode=new $8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=F4.all(new G4(Z.foreground,1,"solid")),q=new Jz({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new B6({children:[new b0({decoration:{color:H1.default()},child:new S1({text:new l(">",new s({color:Z.foreground}))})}),new d6({child:q})]}),H=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,[new l("Command: ",new s({color:Z.foreground})),new l(this.widget.props.commandName,new s({color:H1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new l("Enter",new s({color:Y.keybind}))),z.push(new l(" to submit, ",new s({color:Z.foreground,dim:!0})));z.push(new l("Esc",new s({color:Y.keybind}))),z.push(new l(" to cancel",new s({color:Z.foreground,dim:!0})));let U=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,z)})});return new b0({decoration:{border:K,color:H1.default()},padding:H0.all(1),child:new x0({children:[H,new Q0({height:1}),W,new Q5,U]})})}}class X91 extends p0{props;constructor(J){super();this.props=J}createState(){return new R36}}aW();class C36 extends u0{controller=new dZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new $8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=iF)return!1;let Q=XC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=X6.of(J),{colors:Z,app:Y}=Q,G=S4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new $O({controller:this.controller,triggers:[new rB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:f8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new z8({focusNode:this.focusNode,child:K}),W=new b0({constraints:new L6({maxHeight:V}),padding:H0.symmetric(1,0),child:q}),H=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l("",void 0,[new l("Command: ",new s({color:Z.foreground})),new l(this.widget.props.commandName,new s({color:H1.yellow,bold:!0}))])})}),z=new b0({padding:H0.symmetric(1,0),child:new S1({text:this.isConfirmingClearInput?new l("",void 0,[new l("Esc",new s({color:Y.keybind})),new l(" again to clear input",new s({color:Z.foreground,dim:!0}))]):new l("",void 0,[new l("Press ",new s({color:Z.foreground,dim:!0})),new l("Enter",new s({color:Y.keybind})),new l(" to submit, ",new s({color:Z.foreground,dim:!0})),new l("Esc",new s({color:Y.keybind})),new l(" to clear",new s({color:Z.foreground,dim:!0}))])})}),U=[H,new Q0({height:1}),new d6({child:W}),new Q0({height:1}),z];return new b0({decoration:{border:F4.all(new G4(Z.foreground,1,"solid")),color:H1.default()},padding:H0.all(1),child:new x0({children:U})})}}class wC extends p0{props;constructor(J){super();this.props=J}createState(){return new C36}}import{isDeepStrictEqual as ZH8}from"node:util";var eW8=/[\\/_ +.#"@[({&]/,JH8=/[\\/_ +.#"@[({&]/g,QH8=/[\s-]/,j36=/[\s-]/g;function G91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=G91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(QH8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(j36),M&&X>0)z*=Math.pow(0.999,M.length)}else if(eW8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(JH8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=G91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function $91(J){return J.toLowerCase().replace(j36," ")}function S36(J,Q){let Z=G91(J,Q,$91(J),$91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=G91(J,K,$91(J),$91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class EC{}class IC{}class V91{}class K91{}class _36 extends p0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new k36}}class k36 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function YH8(J,Q){if(J==="")return{matches:!0,score:1};let Z=S36(Q,J);return{matches:Z>0.15,score:Z}}class DJ extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new y36}}class y36 extends u0{controller=new dZ;focusNode;scrollController=new l5;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new $8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),p8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!ZH8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof EC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof V91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof K91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...YH8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;Q81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),p8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=F4.all(new G4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new Jz({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new rY({shortcuts:new Map([[new X4("ArrowDown"),new EC],[new X4("ArrowUp"),new IC],[new X4("Tab"),new EC],[new X4("Tab",{shift:!0}),new IC],[new X4("n",{ctrl:!0}),new EC],[new X4("p",{ctrl:!0}),new IC],[new X4("Enter"),new V91],[new X4("Escape"),new K91]]),focusNode:this.focusNode,child:V}),q=new zJ({actions:new Map([[EC,new E8(this.invoke)],[IC,new E8(this.invoke)],[V91,new E8(this.invoke)],[K91,new E8(this.invoke)]]),child:K}),W=new B6({children:[new b0({decoration:{color:H1.default()},child:new S1({text:new l(">",new s({color:Z.foreground}))})}),new d6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new Q0({height:10,child:new C4({child:new S1({text:new l(L,new s({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new d6({child:new C4({child:new S1({text:new l(this.widget.props.emptyStateText,new s({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let y=I?H1.yellow:void 0,k=I?H1.black:Z.foreground;R=new b0({decoration:y?{color:y}:void 0,padding:H0.symmetric(2,0),child:new S1({text:new l(this.widget.props.getLabel(A),new s({color:k,dim:P}))})})}return new _36(new G8({onClick:(y)=>this.handleItemClick(E,y.clickCount),child:R}),(y)=>{this.itemContexts[E]=y})});H=new x0({children:L,crossAxisAlignment:"start"})}let z=new d6({child:new G8({onScroll:this.handleScroll,opaque:!1,child:new W5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l(this.widget.props.title,new s({color:H1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new Q0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new b0({padding:H0.vertical(1),child:new C4({child:A})}));else U.push(new Q0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new b0({decoration:{border:X,color:H1.default()},padding:H0.symmetric(1,0),child:new x0({children:U})})}}function x36(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class $k1 extends E6{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>x36(X.pubDate).length));return new DJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?H1.yellow:void 0,z=G?H1.black:W.foreground,U=H1.index(8),D=(M,L)=>new Q0({width:L,child:B6.end([new S1({text:new l(M,new s({color:U}))})])});return new b0({decoration:H?{color:H}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[new d6({child:new S1({text:new l(X.title,new s({color:z})),overflow:"ellipsis",maxLines:1})}),new Q0({width:2}),D(x36(X.pubDate),Z)]})})}})}}class Gk1 extends p0{createState(){return new v36}}class v36 extends u0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new S1({text:new l("●",new s({color:this.isGreen?H1.green:H1.index(8),bold:!0})),maxLines:1})}}function XH8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return tY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function Vk1(J,Q,Z){return new S1({text:new l(`${J}${Q}`,new s({color:Z})),maxLines:1})}function $H8(J,Q,Z,Y){return[Vk1("+",J,Y.success),Q5.horizontal(1),Vk1("~",Q,Y.warning),Q5.horizontal(1),Vk1("-",Z,Y.destructive)]}class q91 extends E6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=XH8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=X6.of(J),q=new W6({padding:H0.symmetric(0,1),child:new C4({child:new S1({text:new l("",new s({color:K.colors.foreground,dim:!0}),[new l("Ctrl+T",new s({color:H1.blue,dim:!0})),new l(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new s({color:K.colors.foreground,dim:!0}))])})})});return new DJ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=X6.of(D),{colors:L}=M,A=z?H1.yellow:void 0,E=z?H1.black:L.foreground,I=H1.index(8),P=(G1,e)=>new Q0({width:e,child:B6.end([new S1({text:new l(G1,new s({color:I}))})])}),R=this.props.threadViewStates[H.id],y=[],k=H.relationshipType==="handoff",v=new K81;if(H.depth>0){let G1=[],e=H.ancestorsAreLast.slice(1);for(let q1 of e)G1.push(new l(v.getAncestorPrefix(q1),new s({color:v.connectorColor,dim:v.connectorDim})));let c=H.isLast?v.elbow:v.tee,J1=v.getConnectorText(c);G1.push(new l(J1,new s({color:v.connectorColor,dim:v.connectorDim}))),y.push(new S1({text:new l("",void 0,G1)}))}let g=[],d=this.props.currentThreadID===H.id?new l("(current) ",new s({color:H1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new l("(visited) ",new s({color:L.foreground,dim:!0})):null;if(d)g.push(new S1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))g.push(new Gk1),g.push(new Q0({width:1}))}let b=H.title;if(H.relationshipType==="fork"){let G1=b.match(/^Forked\((\d+)\): /);if(G1)b=b.slice(G1[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);g.push(new S1({text:new l("[fork] ",new s({color:H1.blue}))}))}else if(k)g.push(new S1({text:new l("[handoff] ",new s({color:H1.index(208)}))}));if(H.agentMode==="plan"&&H.hasPlan)g.push(new S1({text:new l("[plan] ",new s({color:H1.magenta}))}));if(g.push(new d6({child:new S1({text:new l(b,new s({color:E})),overflow:"ellipsis",maxLines:1})})),g.push(new Q0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let G1=z?{success:I,warning:I,destructive:I}:L;g.push(...$H8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,G1)),g.push(new Q0({width:2}))}return g.push(P(H.description.timeAgo,V)),new b0({decoration:A?{color:A}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[...y,...g]})})}})}}function f36(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class Kk1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>f36(X.pubDate).length));return new DJ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=X6.of(K),{colors:W}=q,H=G?H1.yellow:void 0,z=G?H1.black:W.foreground,U=H1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new Q0({width:A,child:B6.end([new S1({text:new l(L,new s({color:U}))})])});return new b0({decoration:H?{color:H}:void 0,padding:H0.symmetric(2,0),child:new B6({children:[new d6({child:new S1({text:new l(X.title,new s({color:z})),overflow:"ellipsis",maxLines:1})}),new Q0({width:2}),new S1({text:new l(D,new s({color:U})),maxLines:1}),new Q0({width:2}),M(f36(X.pubDate),Z)]})})}})}}class qk1 extends E6{props;constructor(J){super();this.props=J}build(){return new C4({child:new S1({text:new l("",void 0,[new l(`Forked to new thread:
4752
4752
 
4753
4753
  `,new s({color:H1.white,dim:!0})),new l(`"${this.props.newThreadTitle||"Untitled"}"`,new s({color:H1.white}))]),textAlign:"center"})})}}U0();class h36 extends u0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){x.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){x.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Z=this.widget.props.currentLabels||[],Y=this.labels.some((G)=>G.name===Q),X=Z.includes(Q);return!Y&&!X}build(J){let Q=X6.of(J),{colors:Z}=Q,Y=this.currentQuery.trim().toLowerCase(),X=Y.length>0?this.getValidationError(Y):null,G=this.getAvailableLabels(),K=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...G];return new DJ({title:"Add Label",items:K,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(q,W,H,z)=>{let U=W?H1.yellow:void 0,D=W?H1.black:Z.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let L=this.currentQuery.trim().toLowerCase();return new b0({decoration:U?{color:U}:void 0,padding:H0.symmetric(2,0),child:new S1({text:new l("",void 0,[new l("Create new label: ",new s({color:D})),new l(L,new s({color:D,bold:!0}))])})})}return new b0({decoration:U?{color:U}:void 0,padding:H0.symmetric(2,0),child:new S1({text:new l(q.name,new s({color:D}))})})},filterItem:(q,W)=>{if(this.currentQuery!==W)this.currentQuery=W,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(W);let z=W.trim().toLowerCase();return z.length===0||q.name.includes(z)},sortItems:(q,W,H)=>{let z="__isCreateMarker"in q.item&&q.item.__isCreateMarker,U="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(z&&!U)return-1;if(!z&&U)return 1;return W.score-q.score}})}}class Wk1 extends p0{props;constructor(J){super();this.props=J}createState(){return new h36}}class hq extends p0{props;constructor(J){super();this.props=J}createState(){return new b36}}class b36 extends u0{_spinner=new S$;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=X6.of(J),{colors:Z}=Q,Y=F4.all(new G4(Z.foreground,1,"solid")),X=this._spinner.toBraille(),G=new S1({textAlign:"center",text:new l("",void 0,[new l(X,new s({color:H1.yellow})),new l(" ",void 0),new l(this.widget.props.message,new s({color:Z.foreground}))])}),K=[new d6({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new Q0({height:2,child:new b0({padding:H0.symmetric(2,0),child:new S1({text:new l("",new s({dim:!0}),[new l("Press ",new s({color:Z.foreground})),new l("Esc",new s({color:Z.info})),new l(" to cancel",new s({color:Z.foreground}))])})})}));let q=new b0({decoration:new N8(H1.default(),Y),child:new Q0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new z8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class wV extends p0{props;constructor(J){super();this.props=J}createState(){return new m36}}class m36 extends u0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof AV}build(J){let Q=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=X81(Q);return{title:W.title,type:W.type,description:W.description}})(),Y=Z.type==="error"?H1.red:H1.yellow,X=F4.all(new G4(H1.default(),1,"solid")),G=new b0({padding:H0.symmetric(1,0),child:new S1({text:new l(Z.title,new s({color:Y,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new S1({text:new l(Z.description,new s({color:H1.default()})),selectable:!0}),K=new d6({child:new tH({child:new b0({padding:H0.symmetric(1,0),child:V})})}),q=new b0({padding:H0.symmetric(1,0),child:new S1({text:this.widget.props.onRetry?new l("",void 0,[new l("Press ",new s({color:H1.default(),dim:!0})),new l("R",new s({color:H1.yellow})),new l(" to retry, ",new s({color:H1.default(),dim:!0})),new l("Esc",new s({color:H1.yellow})),new l(" to cancel",new s({color:H1.default(),dim:!0}))]):new l("Press any key to close",new s({color:H1.default(),dim:!0,italic:!0}))})});return new z8({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new b0({decoration:{border:X,color:H1.default()},padding:H0.all(1),child:new x0({mainAxisAlignment:"center",children:[G,new Q0({height:1}),K,q]})})})}}class Hk1 extends E6{build(){return new C4({child:new S1({text:new l("",void 0,[new l(`✓ Thread Shared
4754
4754
 
@@ -4839,7 +4839,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4839
4839
  `)?`${K}...`:X,W=new s({color:H1.index(8)}),H=[new l(q,W)];if(V>0){let z=new s({color:Z.success});for(let U=1;U<=V;U++)H.push(new l(" ")),H.push(new l(`[${U}]`,z))}return new W6({padding:H0.only({bottom:0}),child:new B6({crossAxisAlignment:"start",children:[new W6({padding:H0.only({right:1}),child:new S1({text:new l("•",new s({color:H1.index(8)}))})}),new d6({child:new S1({text:new l("",void 0,H)})})]})})}}class sk1 extends p0{createState(){return new a26}}class a26 extends u0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new s({color:H1.red}),Z=new s({color:this._visible?H1.red:H1.transparent()});return new B6({children:[new S1({text:new l("⏺",Z)}),new Q0({width:1}),new S1({text:new l("Replay",Q)})]})}}class tk1 extends E6{entry;width;constructor({key:J,entry:Q,width:Z}){super({key:J});this.entry=Q,this.width=Z}build(J){let Z=X6.of(J).colors.mutedForeground,Y=this.entry,X=Y.authors[0]?.name||"Community";if(X.includes("@"))X=X.split("@")[0]??X;let G=" · ",V=50,K=this.truncateToWidth(Y.title,V),q=`${G}${K}`,W=Math.max(1,this.width-q.length-2),H=Y.description.replace(/\s+/g," ").trim(),z=`@${X}: ${H}`,U=this.truncateToWidth(z,W),D=new S1({text:new l(U,new s({color:Z,dim:!0}))}),M=new S1({text:new l(q,new s({color:Z,dim:!0}))});return new G8({onClick:()=>x2(J,Y.link),cursor:"pointer",child:new Q0({width:this.width,height:1,child:new W6({padding:H0.horizontal(1),child:new B6({children:[new d6({child:new gB(new Q0({width:W,height:1,child:D}))}),M]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}i0();function Ez8(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/3600000),X=Math.floor(Y/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class ek1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Z)=>{let Y=this.threadHistoryService.observeThreadList().subscribe((X)=>{Y.unsubscribe(),Z(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Y)=>{if(!Q.trim())return!0;let X=Y.title?.toLowerCase()||"untitled",G=Y.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Y)=>{let X=new Date(Y.userLastInteractedAt),G=Ez8(X),V=Y.id.slice(-8),K=Y.env?.initial.trees?.[0]?.uri;return{id:Y.id,title:Y.title||"Untitled",updatedAt:new Date(Y.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Y.title||"Untitled",shortThreadID:V},diffStats:Y.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Y.parentRelationships,hasPlan:Y.hasPlan,agentMode:Y.agentMode}})}}U0();O8();class Jy1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new l5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(JM()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function o26(J,Q){switch(J){case"update-available":return[new l("A newer Amp is available. Run ",new s({color:Q.foreground,dim:!0})),new l("amp update",new s({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new l("Update complete, run ",new s({color:Q.foreground,dim:!0})),new l("amp update",new s({color:Q.warning})),new l(" to see warnings",new s({color:Q.foreground,dim:!0}))];case"update-error":return[new l("Update failed, run ",new s({color:Q.foreground,dim:!0})),new l("amp update",new s({color:Q.warning})),new l(" to see warnings",new s({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function Cz8(J){return new Promise((Q)=>{Pz8("git",["branch","--show-current"],{cwd:J},(Z,Y)=>{if(Z){Q(null);return}let X=Y.trim();Q(X||null)})})}class YJ6 extends p0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new v91}}class v91 extends u0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;threadCostInfoLastUsageLedgerLength=0;lastInferenceState=void 0;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jy1;previewThread=null;planScrollController=(()=>{let J=new l5;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new l5;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new $8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new $8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;mcpServers=[];mcpServersSubscription=null;cacheTimerState=null;cacheTimerSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1};agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new gj1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];userDisplayBalanceInfo=null;balanceInfoSubscription=null;async initThreadFeed(){let J=await q6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Z=Q.includes("localhost")||Q.includes("127.0.0.1");try{let V=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(V.ok){let K=V.result,q="user"in K?K.user:K;this.currentUserInfo={username:q.username??void 0,displayName:q.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Z&&K.team?.id!==W)return}else return}catch(V){x.debug("Failed to fetch user info for thread feed filtering",V);return}let Y="/threads.rss",X=async(V,K)=>{let q=V instanceof Request?V.url:V.toString();return U3(q,K,this.widget.dependencies.configService)},G=NI1();G.get("entries").then((V)=>{if(V){let K=this.filterEntries(V);if(this.threadFeedEntries=K,K.length>0&&!this.currentThreadFeedEntry){let q=[...K].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new Zj1(G,X,{url:Y}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let K=this.filterEntries(V);if(K.length>0){this.threadFeedEntries=[...K,...this.threadFeedEntries];let q=[...K].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(K){x.error("Thread feed: error in next handler",K)}},error:(V)=>{x.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Z}=this.currentUserInfo;return J.filter((Y)=>{return!Y.authors.some((X)=>{let G=X.name;if(!G)return!1;return Q&&G===Q||Z&&G===Z||Q&&G.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}async initNewsFeed(){let J=async(Z)=>{return U3(Z,void 0,this.widget.dependencies.configService)},Q=NI1();this.newsFeedReader=new Qj1(Q,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Z)=>{if(Z.length>0)this.setState(()=>{this.newsFeedEntries=[...Z,...this.newsFeedEntries]})},error:(Z)=>{x.error("News feed error:",Z)}})}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Z,baseWpm:Y}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Z){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4840
4840
  `);if(W)await this.replayTypeMessage(W,Y)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let D=J.thread.id;this.getMessageScrollController(D).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),f8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Z=J.split(/(?<=\s)/),Y=60000/Q;for(let X of Z){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Y/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Y=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Z,...Y].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new l(this.submitDisabledHint,new s({color:J.foreground,dim:!0}));if(this.isExiting)return new l("Exiting...",new s({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new l("",void 0,[new l("Ctrl+C",new s({color:Q.keybind})),new l(" again to exit",new s({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new l("",void 0,[new l("Esc",new s({color:Q.keybind})),new l(" again to clear input",new s({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new l("",void 0,[new l("Escape",new s({color:Q.keybind})),new l(" to close help",new s({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),G=Gy1(X);return new l("",void 0,[new l("Images aren't supported in ",new s({color:J.warning,dim:!1})),new l(X,new s({color:G})),new l(" mode.",new s({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new l("",void 0,[new l("Esc",new s({color:Q.keybind})),new l(" again to cancel",new s({color:J.foreground,dim:!0}))]);return new l("",void 0,[new l("Esc",new s({color:Q.keybind})),new l(" to cancel",new s({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new l(this.statusMessage,new s({color:J.foreground,dim:!0}));let Z=o26(this.updateState,J);if(Z)return new l("",void 0,Z);let Y=this.widget.dependencies.worker.thread;if(Y.agentMode==="plan"&&tL(Y))return new l("",void 0,[new l("Use command",new s({color:J.foreground})),new l(" plan: execute",new s({color:Q.command}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){x.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:Y}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await X2.getOrCreateForThread(Z,X),K=await GR(V,Y,G-1);await this.switchToExistingThread(K)}catch(V){x.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:Y}=this.widget.dependencies,X=Z.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),this.widget.dependencies.history.add(Q);let V=pB(Q);if(V)await Y.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){x.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Y.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){x.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(c2)}catch(Z){return x.error("Failed to get affected files:",Z),[]}};textController=new dZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new l5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let Y=this.searchElementTreeByKey(J.child,Q);if(Y)return Y}if(J?.children)for(let Y of J.children){let X=this.searchElementTreeByKey(Y,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),Y=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(qC1(Y))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new i7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=pB(J);this.currentShellModeStatus=Q?.visibility,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),p8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),p8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Ok1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ik1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Z}=this.widget.dependencies;if(!Q.mainThread)return null;let Y=h0.file(process.cwd()),X=T6(Y);return{recentThreadIDs:Z,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadService:this.widget.dependencies.threadService,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus.canUseAmpFree,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>G.abort(new Z91("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W},this.widget.dependencies.configService,G.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw G.signal.reason;throw U}}catch(H){return x.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await pr({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=Q.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let V=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(V)}catch(G){x.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.clustersForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,newsFeedEntries:this.newsFeedEntries,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)},showToast:(G,V="success",K)=>{this.toastController.show(G,V,K)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new ek1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.clustersForPicker=r36(Q),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await Cz8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Z=Date.now(),Y=`bash-${Z}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===uB).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Y))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Y?{...q,toolRun:V}:q);else{let q={id:Y,args:X,toolRun:V,startTime:Z,abortController:G,hidden:Q===uB};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=F46(()=>{let J=this.widget.dependencies.threadID;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(Q.ok)this.setState(()=>{this.threadCostInfo=Q.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J,Q)=>{let Z=J!==this.threadCostInfoLastUsageLedgerLength,Y=Q==="idle"&&this.lastInferenceState==="running";if(this.threadCostInfoLastUsageLedgerLength=J,this.lastInferenceState=Q,Z||Y)this.fetchThreadCostInfo()};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=800,Q=16,Z=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Z),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!pk(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=iF)return!1;let Z=XC(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Z}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)x.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{x.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:Y,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await R$(W);try{let H=await Z(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")x.error("Failed to read temporary file",H)}try{await Y(W),await X(q)}catch(H){x.warn("Failed to clean up temporary file",H)}}catch(q){x.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=pB(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};initState(){if(lY.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();f8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),f8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),f8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{p8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),q6(this.widget.dependencies.configService.config).then((Z)=>{this.paletteConfig=Z,this.agentModeController=new Kj1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus,initialSettings:Z.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.balanceInfoSubscription=ae0(async()=>{let Z=await this.widget.dependencies.internalAPIClient.userDisplayBalanceInfo({},{config:this.widget.dependencies.configService});if(!Z.ok)throw Z.error;return Z.result}).subscribe({next:(Z)=>{this.setState(()=>{this.userDisplayBalanceInfo=Z})},error:(Z)=>{x.debug("Failed to fetch user balance info",Z)}}),this.scheduleAdSubscriptionWithIdeReadiness();let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Z)=>{this.setState(()=>{this.pendingMCPServers=Z})}),mR1((Z)=>{this.setState(()=>{this.pendingOAuthRequest=Z})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Z)=>{this.setState(()=>{this.mcpServers=Z})}),this.cacheTimerSubscription=this.widget.dependencies.worker.cacheTimer.subscribe((Z)=>{this.setState(()=>{this.cacheTimerState=Z})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{let Y=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=Z}),!Y&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let Y=this.widget.dependencies.getCurrentWorker();if(!Y){x.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),x.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),x.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.mysteriousMessageSubscription=S41(this.widget.dependencies.configService).pipe(g5((Z)=>Z!=="pending"),Q6((Z)=>_41(Z)?Z.mysteriousMessage??null:null),U4((Z,Y)=>Z?.id===Y?.id)).subscribe((Z)=>{this.setState(()=>{if(Z?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Z,Z&&!this.mysterySequenceManager)this.mysterySequenceManager=new n41(new Map([[new i41(v91.MYSTERY_SEQUENCE),new Gg]])),this.mysteryKeyInterceptorUnsubscribe=f8.instance.addKeyInterceptor((Y)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Y);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Z)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed(),this.initNewsFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener();let Q=this.widget.dependencies.threadID;if(this.threadCostInfoThreadID!==void 0&&this.threadCostInfoThreadID!==Q)this.threadCostInfo=void 0,this.threadCostInfoThreadID=void 0,this.threadCostInfoLastUsageLedgerLength=0,this.fetchThreadCostInfo();let{threadState:Z}=this.widget.dependencies;this.maybeRefetchThreadCostInfo(Z.mainThread?.usageLedger?.events.length??0,Z.viewState.state==="active"?Z.viewState.inferenceState:void 0)}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.balanceInfoSubscription)this.balanceInfoSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(mR1(null),this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.cacheTimerSubscription)this.cacheTimerSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(qC1("")),this.shouldUseProgressBar())process.stdout.write(U66())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Y=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Y.length===0)return null;let X=Y[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},v91.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}subscribeToAds(){if(this.adSubscription)return;this.adSubscription=jC1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let J=this.agentModeController?.getMode();return(J&&P9(J)||this.randomAd===null)&&CC1(this.lastUserInteractionTime)},this.widget.dependencies.codebaseContextService).subscribe({next:(J)=>{if(J){let Q=Tz8(16).toString("hex");this.lastAdImpressionId=Q,Promise.resolve().then(() => (x91(),y91)).then(({recordAdEvent:Z})=>{let Y=this.widget.dependencies.worker.thread,X=Y.messages[Y.messages.length-1];Z("viewed",{adId:J.id,advertiserId:J.advertiserId,threadId:Y.id,messageId:X?.messageId,impressionId:Q,placement:"tui",matchType:J.metadata?.matchType,matchedPatterns:J.metadata?.matchedPatterns,candidateAdPoolCount:J.metadata?.candidateAdPoolCount,clientRegion:J.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=J}),p8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){x.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){x.error("No tool use block found in confirmation");return}if(J==="allow-all-session")DG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else x.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await x2(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(FY))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,FY],"global")}let Y=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Z.id,value:{accepted:Y}};if(Q.subthreadID)await(await X2.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){x.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.agentModeController?.setMode("smart"),this.setState(()=>{this.dismissedEphemeralErrorKey=null}),S61({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette({type:"normal",commandId:"handoff"});break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await R$(Q.getSettingsFilePath())}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await X2.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Z=!0}=Q;if(Z){let Y=this.widget.dependencies.worker.thread.id;if(Y!==J)this.recordNavigation(Y)}try{x.info(`[switchToExistingThread] Switching to thread: ${J}`);let Y=await this.widget.dependencies.switchToThread(J);if(x.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Y.thread.agentMode}`),this.widget.dependencies.worker=Y,this.widget.dependencies.threadID=Y.thread.id,this.widget.dependencies.switchWorker(Y),x.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),Y.thread.draft)if(x.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Y.thread.draft==="string")this.textController.insertText(Y.thread.draft);else{let X=Y.thread.draft.filter((K)=>K.type==="text"),G=Y.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
4841
4841
  `);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Y){throw x.error("Failed to switch to thread:",J,Y),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Z=a2(Q.thread)===0,Y=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&Y!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Z)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Y}}),Z)S61({agentMode:Y});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),p8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((Y)=>Y.type==="handoff"&&Y.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();S61({agentMode:Q}).catch((Z)=>{x.warn("Failed to save session state on exit:",Z)}).finally(()=>{f8.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=Rz8();if(J===Q)return"~";if(J.startsWith(Q+Rg.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Rg.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Rg.sep),"…",Q.slice(-2).join(Rg.sep)].join(Rg.sep)}build(J){let Q=S4.of(J),Z=X6.of(J),Y=Z.base;this.themeColors=Y;let{colors:X,app:G}=Z;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&P9(V.thread.agentMode),q=this.widget.dependencies.features.some((V4)=>V4.name===xm.UBI&&V4.enabled),W=this.widget.dependencies.freeTierStatus.canUseAmpFree&&q,H=(K||W)&&this.randomAd!==null,z=!K&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,U=Boolean(H),{threadState:D}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let M=this.getCurrentConfirmation(),L=this.widget.dependencies.replayMode,A=Boolean(L),E=D.items,I=D.mainThread||void 0,P=D.subagentToolsByParentID,R=D.todosList;if(A){let V4={...L.thread,messages:this.replayDisplayedMessages};E=AC(V4).items,I=V4,P={};let q4=pE({messages:this.replayDisplayedMessages});R=Array.isArray(q4)?q4:[]}let y=I?.id,k=I,v=A?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),g=(V4)=>new s81({key:new i7(`preview-message-view-${V4.id}`),items:AC(V4).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:V4,focusNode:new $8({debugLabel:"PreviewFocus"})}),d=this.previewThread,b=d?d.messages.length>2000?new x0({mainAxisSize:"max",children:[new d6({child:new Q0}),new W6({padding:H0.all(2),child:new C4({child:new S1({text:new l("Thread too long for preview",new s({color:X.mutedForeground,dim:!0}))})})})]}):g(d):v?new Q91({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,userDisplayBalanceInfo:this.userDisplayBalanceInfo}):new s81({key:y?new i7(`message-view-${y}`):void 0,items:E,subagentToolsByParentID:P,controller:y?this.getMessageScrollController(y):new l5,autofocus:!1,onCopy:A?void 0:this._handleTextCopy.bind(this),thread:k,onMessageEditSubmit:A?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:A?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:A?void 0:this.forkMessage,getAffectedFiles:A?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),a=Math.max(Math.floor(Q.size.height*0.4),12),G1=this.getCurrentEphemeralError(),e=Q.size.width<40,c=D.mainThread?ri(D.mainThread):void 0,J1=m81(J),q1=this.buildBottomWidget(G1,M,X,Z,D,R,a,U,A,c,this.cacheTimerState??void 0,Q,J1),L1=new H81({threadViewState:D.viewState,threadTokenUsage:c,threadID:y??null,thread:D.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:e,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!M,showingEphemeralError:Boolean(D.viewState.state==="active"&&D.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),r=new q81({bashInvocations:this.bashInvocations}),o=[];if(z&&this.currentThreadFeedEntry)o.push(new tk1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let i=this.getEffectiveAgentMode(),z1=this.currentShellModeStatus,k1=Gy1(i),t=!z1?i.length+1:0,f1=Q.capabilities.animationSupport,P1=f1==="disabled"?0:f1==="slow"?30:60,I0=LK(i)?.uiHints?.fasterAnimation?3:1,_1=P1>0&&this.agentModePulseSeq>0?new x9({children:[q1,new v5({top:0,left:1,right:1,height:1,child:new ik1({color:k1,trigger:this.agentModePulseSeq,fps:P1,speed:I0,leftOffset:t})})]}):q1;o.push(new d6({child:b}),r);let o1=new x9({children:[new x0({mainAxisSize:"min",children:[H?new Jk1({ad:this.randomAd,onButtonClick:async()=>{let V4=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (x91(),y91)).then(({recordAdEvent:O9})=>{let Y5=this.widget.dependencies.worker.thread,m$=Y5.messages[Y5.messages.length-1];O9("clicked",{adId:V4.id,advertiserId:V4.advertiserId,threadId:Y5.id,messageId:m$?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:V4.metadata?.matchType,matchedPatterns:V4.metadata?.matchedPatterns,candidateAdPoolCount:V4.metadata?.candidateAdPoolCount,clientRegion:V4.metadata?.clientRegion})});if(!await x2(this.context,V4.shortDestinationUrl)){let Y5=f8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:Y5,url:V4.shortDestinationUrl}})}}}):new Q0({height:0}),new b0({constraints:new L6(0,Q.size.width,0,a),child:_1})]}),U?new v5({top:0,left:0,right:0,child:new GJ6({userHeight:this.bottomGridUserHeight,maxHeight:a,onInitializeHeight:(V4)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(V4,a)})},onDrag:(V4)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(V4.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let q4=Math.floor(V4.localPosition.y)-this.bottomGridDragStartY,O9=Math.max(4,this.bottomGridDragStartHeight-q4),Y5=Math.min(O9,a),m$=Math.floor(Y5);if(this.bottomGridUserHeight!==m$)this.setState(()=>{this.bottomGridUserHeight=m$})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new Q0({height:0})]});o.push(o1,new Q0({height:1,child:new W6({padding:H0.horizontal(1),child:L1})}));let F1=new x0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:o}),w1=A&&L?.showIndicator!==!1?new x9({children:[F1,new v5({top:0,left:0,child:new sk1})]}):F1,A1=new E8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((q4)=>{x.error("Failed to mark message as interrupted:",q4)}),this.cancelStreamingMessage().catch((q4)=>{x.error("Failed to cancel streaming message:",q4)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return x.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),R1=new E8(()=>{return this.onExitPressed(),"handled"}),j1=new E8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),d1=new E8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),m1=new E8(()=>{return NJ.instance.toggleAll(),"handled"}),r1=new E8(()=>{return this.widget.dependencies.configService.getLatest().then((V4)=>{DG("internal.showDetailedCosts",!(V4.settings["internal.showDetailedCosts"]??!1))}),"handled"}),K0=new E8(()=>{return f8.instance.toggleFrameStatsOverlay(),"handled"}),q0=new E8(()=>{return f8.instance.tuiInstance.getScreen().markForRefresh(),p8.instance.requestFrame(),"handled"}),k0=new E8(()=>{return this.toggleAgentMode(),"handled"}),v6=new E8(()=>{let q4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O9}=this.widget.dependencies,Y5=O9.mainThread?.id;return Y5?this.getMessageScrollController(Y5):null})();if(q4){let O9=Math.max(Math.floor(Q.size.height*0.4),10),Y5=Q.size.height-O9;q4.animatePageUp(Y5,100)}return"handled"}),p6=new E8(()=>{let q4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O9}=this.widget.dependencies,Y5=O9.mainThread?.id;return Y5?this.getMessageScrollController(Y5):null})();if(q4){let O9=Math.max(Math.floor(Q.size.height*0.4),10),Y5=Q.size.height-O9;q4.animatePageDown(Y5,100)}return"handled"}),e4=new E8(()=>{let q4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O9}=this.widget.dependencies,Y5=O9.mainThread?.id;return Y5?this.getMessageScrollController(Y5):null})();if(q4)q4.animateTo(0,100);return"handled"}),s8=new E8(()=>{let q4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O9}=this.widget.dependencies,Y5=O9.mainThread?.id;return Y5?this.getMessageScrollController(Y5):null})();if(q4)q4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),r9=new E8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:V4}=this.widget.dependencies;if(!V4.mainThread?.messages.some((O9)=>O9.role==="user"||uE(O9)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),E0=new E8((V4)=>{if(V4.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),a0=new E8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return Y81().then(async(V4)=>{if(V4)try{this.handleInsertImage(V4)}finally{try{let{unlink:q4}=await import("node:fs/promises");await q4(V4)}catch{}}}),"handled"}),s6=new Map([[X4.ctrl("c"),new em],[X4.ctrl("l"),new Xg],[X4.ctrl("o"),new e41],[X4.ctrl("v"),new sm],[X4.alt("s"),new KC],[X4.ctrl("s"),new KC],[X4.alt("p"),new Yg],[X4.ctrl("r"),new Qg],[X4.alt("d"),new Zg],[X4.ctrl("t"),new $g],[X4.key("PageUp"),new o41],[X4.key("PageDown"),new r41],[X4.key("Home"),new s41],[X4.key("End"),new t41],[X4.key("Escape"),new tm],[X4.ctrl("p"),new qC("previous")],[X4.ctrl("n"),new qC("next")],[X4.key("Tab"),new Vg]]);if(!m3())s6.set(X4.key("ArrowUp"),new Vg);if(!1)s6.set(X4.alt("c"),new Jg);let d8=new E8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),w7=new E8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),h5=new E8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),G7=new Map([[tm,A1],[Xg,q0],[KC,k0],[e41,d8],[sm,a0],[Jg,j1],[d41,d1],[Qg,m1],[Zg,r1],[Yg,K0],[$g,w7],[em,R1],[o41,v6],[r41,p6],[s41,e4],[t41,s8],[Vg,r9],[qC,E0],[Gg,h5]]),c8=[w1];if(this.isShowingConsoleOverlay)c8.push(new Rk1);if(this.isShowingHelp&&this.paletteConfig)c8.push(new Sk1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)c8.push(new A_1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)c8.push(new ok1({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)c8.push(new Qk1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(V4)=>{let q4=this.adActionModal.url;if(V4==="copy")try{await f8.instance.tuiInstance.clipboard.writeText(q4),this.setState(()=>{this.displayMessage=new sY("Link copied to clipboard")})}catch(O9){x.error("Failed to copy to clipboard",{error:O9}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:V4}=this.widget.dependencies;c8.push(new nk1({servers:this.pendingMCPServers,onAlwaysTrust:V4.trustAlways.bind(V4),onTrustOnce:V4.trustOnce.bind(V4),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:V4.deny.bind(V4)}))}if(this.pendingOAuthRequest)c8.push(new rk1({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.isShowingFileChangesOverlay)c8.push(new sj1({threadData:D}));if(this.isShowingContextDetailOverlay){let V4=this.threadCostInfo?.costBreakdownURL;c8.push(new Ck1({thread:D.mainThread??void 0,tokenUsage:c??void 0,cacheTimerState:this.cacheTimerState??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:V4?()=>{x2(J,V4)}:void 0}))}if(this.isShowingConfirmationOverlay)c8.push(new Pk1({details:this.confirmationOverlayContent}));let d9=this.getCommandPaletteContext(J);if(d9&&this.isShowingPalette&&this.paletteConfig)c8.push(new C4({child:new Ek1({commandContext:d9,mainThread:D.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)c8.push(new kk1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let Z8=new x9({children:c8});if(this.isShowingJetBrainsInstaller)return new iA({child:new zJ({actions:G7,child:new rY({shortcuts:s6,debugLabel:"jetbrains-installer-shortcuts",child:new lk1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new eH({controller:this.toastController,child:new iA({child:new uj1({controller:this.toastController,child:new zJ({actions:G7,child:new rY({shortcuts:s6,debugLabel:"main-app-shortcuts",child:Z8})})})})})}buildScrollableTodoList(J,Q,Z){return new XJ6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Z})}buildBottomWidget(J,Q,Z,Y,X,G,V,K,q,W,H,z,U){if(J)return new jk1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Tk1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ak1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let D=V81(Y),M=this.agentModeController?.isInRestrictedFreeMode()??!1,L=new $O({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new rB],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Z,placeholder:q?"Press Ctrl+C to exit":M?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!M&&!this.isShowingStandalonePalette(),shellPromptRules:D,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:f8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let i=this.previousThreadIdForHint;if(i)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${i} `},onDoubleAtTrigger:q?void 0:()=>{let i=this.textController.text,z1=this.textController.cursorPosition,t=i.slice(0,z1).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"attach-plan",onBeforeExecute:()=>{if(t!==-1){let f1=this.textController.text,P1=f1.slice(0,t)+f1.slice(t+2);this.textController.text=P1,this.textController.cursorPosition=t}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),A=X.mainThread?.queuedMessages??[],E=Array.isArray(G)&&G.length>0,I=Array.isArray(A)&&A.length>0,P=X.mainThread?.agentMode==="plan"&&tL(X.mainThread),R,y;if(P){if(R=new gB(new t81({thread:X.mainThread,onExecute:async()=>{let i=this.getCommandPaletteContext();if(i)await this.getPaletteCommands().execute("execute-plan",i,void 0,new AbortController)},onEdit:async()=>{try{let i=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:z1}=await this.widget.dependencies.planFileManager.ensureSync(X.mainThread.id);f8.instance.tuiInstance.suspend();let{execSync:k1}=await import("child_process");k1(`${i} "${z1}"`,{stdio:"inherit"}),f8.instance.tuiInstance.resume()}catch(i){x.error("Failed to edit plan",i),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:Y}),{clipBehavior:"antiAlias"}),I)y=new k91({queuedMessages:A});else if(E)y=this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y)}else R=I?new k91({queuedMessages:A}):void 0,y=E?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y):void 0;let k=[],v=this.currentShellModeStatus;if(v)k.push({child:new S1({text:new l(v==="hidden"?"shell mode (incognito)":"shell mode",new s({color:v==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});let d=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,b=this.agentModeController?.getVisibleModes()??[];if(!v&&b.length>1){let i=this.previewThread,z1=i?i.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),k1=Gy1(z1),t=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,f1=i??t.thread,P1=a2(f1)>0,I0=this.agentModeSlideProgress!==null,_1,o1;if(I0){_1="top-left";let Y1=z.size.width-z1.length-4-d;o1=Math.floor(this.agentModeSlideProgress*Y1)}else if(P1)_1="top-right",o1=d;else _1="top-left",o1=void 0;if(i)k.push({child:new S1({text:new l(z1,new s({color:k1}))}),position:_1,offsetX:o1});else{let F1=!P1&&!I0,Y1=new S1({text:new l(z1,new s({color:k1}))});k.push({child:F1?new G8({child:Y1,onClick:this.toggleAgentMode,cursor:"pointer"}):Y1,position:_1,offsetX:o1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let i=this.connectedClientsStatus,z1=i.mode||"disconnected",k1=!!i.errorMessage,t=i.clientID||"unknown",f1,P1;if(k1)f1="●",P1=H1.red;else if(z1==="presence")f1="○",P1=H1.yellow;else if(z1==="connected"&&i.connected)f1="●",P1=H1.green;else f1="○",P1=H1.yellow;let I0=this.connectedClientsStatusExpanded?`${t} ${f1}`:f1;k.push({child:new G8({child:new S1({text:new l(I0,new s({color:P1}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let a=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,G1;if(a)G1=h0.parse(a).fsPath;else G1=process.cwd();let e=this.toHomeRelative(G1),c=this.shorten(e),J1=!q&&this.currentGitBranch?`${c} (${this.currentGitBranch})`:c;if(k.push({child:new S1({text:new l(J1,new s({color:Z.foreground,dim:!0}))}),position:"bottom-right"}),this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")k.push({child:new S1({text:new l("",void 0,[new l("press ",new s({color:Z.foreground,dim:!0})),new l("enter",new s({color:Y.app.keybind})),new l(" to reference the previous thread",new s({color:Z.foreground,dim:!0}))])}),position:"bottom-left"});let L1=this.previewThread,r=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(a2(r.thread)>0&&!v&&!L1){let i=[],z1=new s({color:Z.foreground,dim:!0}),k1=new l(" · ",z1);if(W){let t=W.totalInputTokens/W.maxInputTokens,f1=Math.round(t*100),P1=Math.max(0,Math.min(f1,100)),I0=W81(t,W.maxInputTokens),_1=z1;if(I0==="danger")_1=new s({color:Z.destructive});else if(I0==="warning")_1=new s({color:Z.warning});else if(I0==="recommendation")_1=new s({color:Y.app.recommendation});let o1=Math.round(W.maxInputTokens/1000);i.push(new l(`${P1}% of ${o1}k`,_1))}if(U&&this.threadCostInfo){let t=B91(this.threadCostInfo,{colors:{foreground:Z.foreground},dim:!0});if(t.length>0){if(i.length>0)i.push(k1);i.push(...t)}}if(U&&H){let t=X.viewState.state==="active"&&X.viewState.inferenceState==="idle",f1=z46(H,t);if(f1){if(i.length>0)i.push(k1);let P1=z1;if(f1.urgency==="warning")P1=new s({color:Z.warning});i.push(new l(f1.text,P1))}}if(i.length>0){let t=new S1({text:new l("",void 0,i)});k.push({child:U?new G8({child:t,onClick:this.showContextDetailOverlay,cursor:"pointer"}):t,position:"top-left"})}}return new ij1({leftChild:new d6({child:L}),rightChild1:R,rightChild2:y,maxHeight:V,overlayTexts:k,borderColor:M||!this.isTextfieldAndAutocompleteFocused?H1.index(8):void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(i)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(i,V)})},onDrag:(i)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(i.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let z1=Math.floor(i.localPosition.y)-this.bottomGridDragStartY,k1=Math.max(4,this.bottomGridDragStartHeight-z1),t=Math.min(k1,V),f1=Math.floor(t);if(this.bottomGridUserHeight!==f1)this.setState(()=>{this.bottomGridUserHeight=f1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function Vy1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)f8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Y=()=>null,G=!1,V=new lH(G,1000,J.inspectorPort),K=J.features.find((A)=>A.name===xm.AMP_CONNECT)?.enabled??!1,q=new t_1({threadService:J.threadService,worker:J.worker,builder:(A,E,I,P,R,y)=>{if(Y=R,J.threadDependencies&&K)Gj1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((g)=>{x.error("Failed to start automatic presence:",g)});let k=R(),v={...J,worker:k,threadID:k.thread.id};return new YJ6({...v,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:R,recentThreadIDs:y})}}),W=new nj1({configService:J.configService,child:q}),H=new O_1({configService:J.configService,child:W}),z=new yj1(H),U=new X6({data:WC.fromBaseTheme(C$.default()),child:z});try{await IC1(U,{onRootElementMounted:(A)=>{if(x.info("TUI input ready for user interaction"),G)V.start(A)}})}finally{if(G)V.stop();if(J.threadDependencies&&K){let{stopGlobalSession:A}=await Promise.resolve().then(() => (Vj1(),E86));A()}}let M=Y()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;c86(L,A,J.stdout)}}function Gy1(J){let Z=LK(J)?.uiHints?.secondaryColor;if(Z)return H1.rgb(Z.r,Z.g,Z.b);return jz8(J)}class XJ6 extends p0{props;constructor(J){super();this.props=J}createState(){return new $J6}}class $J6 extends u0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Z,appTheme:Y}=this.widget.props;return new B6({crossAxisAlignment:"stretch",children:[new d6({child:new W5({controller:Z,autofocus:!1,child:new e_1({todos:Q})})}),new BJ({controller:Z,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Z,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let G=Y.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class GJ6 extends E6{props;constructor(J){super();this.props=J}build(J){return new G8({child:new Q0({height:1}),cursor:C9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function jz8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Y=Math.abs(Q)%Z.length;return H1.index(Z[Y])}EC1();try{if(process.platform==="win32")await Promise.resolve().then(() => K6(dC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){tQ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4842
- `)}var fx1=vx1.join(Nq0||vx1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function rN8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function TV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")DG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")DG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")DG("model.sonnet",Q.useSonnet)}async function bx1(J){try{await nN8(vx1.dirname(fx1),{recursive:!0}),await aN8(fx1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function sN8(){try{return(await yY6(fx1,"utf-8")).trim()}catch(J){return null}}function tN8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function eN8(J){try{let Q=await K5.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){x.debug("Failed to fetch user info:",Q)}return}var SY6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??O$,description:`Custom settings file path (overrides the default location ${O$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${SA})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:m3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:vE.SMART.key,description:`Set the agent mode (${fX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().map((J)=>J.mode).concat("large")}],_Y6=(J)=>("deprecated"in J)&&J.deprecated===!0,JD8=(J)=>("hidden"in J)&&J.hidden===!0,QD8=(J)=>("default"in J),ZD8=(J)=>("default"in J)?J.default:void 0;function YD8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new R8(A$.unknownCommand(Z),1,V)}}var xY6=null;function WD5(){return xY6}function rg(J){return{...J,getThreadEnvironment:X61,vfs:yE0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new kx(J.fileSystem),generateThreadTitle:pc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var mx1=h0.file(oN8.homedir()),vY6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(mx1,".config");async function b$(J,Q){FU0("0.0.1765404020-g2e5656");let Z=QH1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([h0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:mx1,userConfigDir:vY6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (x91(),y91));Y(Z);let X=await Z.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=oa0({configService:Z}),K=new Map,q=()=>K.clear(),W=new DU1(Z,J.settings.getWorkspaceRootPath()),H=gw0({configService:Z,trustStore:W,createOAuthProvider:async(e,c,J1)=>{let q1=`${e}:${c}`,L1=K.get(q1);if(L1)return x.debug("Reusing existing OAuth provider for server",{serverName:e,serverUrl:c}),L1;x.debug("Creating OAuth provider for server",{serverName:e,serverUrl:c});let r=(async()=>{let o=new MM(J.secrets),i=await o.getClientInfo(e,c),z1=J1?.scopes??i?.scopes,k1=I16();x.info("OAuth headless mode check",{useHeadless:k1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:o9.isTTY});let t=void 0;if(k1)t=J.executeMode?E16():w16(e);let f1=new gF1({storage:o,serverName:e,serverUrl:c,clientId:J1?.clientId??i?.clientId,clientSecret:J1?.clientSecret??i?.clientSecret,authUrl:J1?.authUrl??i?.authUrl,tokenUrl:J1?.tokenUrl??i?.tokenUrl,scopes:z1,headlessAuthHandler:t});return x.debug("OAuth provider created",{serverName:e,serverUrl:c,hasManualClientId:!!(J1?.clientId??i?.clientId),willUseDCR:!(J1?.clientId??i?.clientId),scopes:z1,headlessMode:k1,executeMode:J.executeMode}),f1})();return K.set(q1,r),r}}),z=$01({configService:Z,filesystem:J5,spawn:qA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (jY6(),CY6)),M;if(J.executeMode){let e=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=e.registrations;for(let[c,J1]of e.initErrors)x.warn(`${c} provider initialization slow or failed:`,J1)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&Y06())cE("VS Code");else if(Q.ide&&X06())cE("Neovim");if(J.executeMode)UU0(!0);let L,A=H3.status.pipe(Q6((e)=>Boolean(e.connected&&e.authenticated)),U4()).subscribe((e)=>{if(e){if(!L)L=G.registerTool(pi0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let e=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new B61(process.cwd(),{alwaysIncludePaths:e},!0)}else E=new class extends B61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(o9.write(`No API key found. Starting login flow...
4842
+ `)}var fx1=vx1.join(Nq0||vx1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function rN8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function TV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")DG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")DG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")DG("model.sonnet",Q.useSonnet)}async function bx1(J){try{await nN8(vx1.dirname(fx1),{recursive:!0}),await aN8(fx1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function sN8(){try{return(await yY6(fx1,"utf-8")).trim()}catch(J){return null}}function tN8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}async function eN8(J){try{let Q=await K5.getUserInfo({},{config:J,signal:AbortSignal.timeout(5000)});if(Q.ok)return Q.result}catch(Q){x.debug("Failed to fetch user info:",Q)}return}var SY6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??O$,description:`Custom settings file path (overrides the default location ${O$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${SA})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:m3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:vE.SMART.key,description:`Set the agent mode (${fX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().map((J)=>J.mode).concat("large")}],_Y6=(J)=>("deprecated"in J)&&J.deprecated===!0,JD8=(J)=>("hidden"in J)&&J.hidden===!0,QD8=(J)=>("default"in J),ZD8=(J)=>("default"in J)?J.default:void 0;function YD8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new R8(A$.unknownCommand(Z),1,V)}}var xY6=null;function WD5(){return xY6}function rg(J){return{...J,getThreadEnvironment:X61,vfs:yE0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new kx(J.fileSystem),generateThreadTitle:pc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var mx1=h0.file(oN8.homedir()),vY6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(mx1,".config");async function b$(J,Q){FU0("0.0.1765411294-g5611a8");let Z=QH1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([h0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:mx1,userConfigDir:vY6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (x91(),y91));Y(Z);let X=await Z.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=oa0({configService:Z}),K=new Map,q=()=>K.clear(),W=new DU1(Z,J.settings.getWorkspaceRootPath()),H=gw0({configService:Z,trustStore:W,createOAuthProvider:async(e,c,J1)=>{let q1=`${e}:${c}`,L1=K.get(q1);if(L1)return x.debug("Reusing existing OAuth provider for server",{serverName:e,serverUrl:c}),L1;x.debug("Creating OAuth provider for server",{serverName:e,serverUrl:c});let r=(async()=>{let o=new MM(J.secrets),i=await o.getClientInfo(e,c),z1=J1?.scopes??i?.scopes,k1=I16();x.info("OAuth headless mode check",{useHeadless:k1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:o9.isTTY});let t=void 0;if(k1)t=J.executeMode?E16():w16(e);let f1=new gF1({storage:o,serverName:e,serverUrl:c,clientId:J1?.clientId??i?.clientId,clientSecret:J1?.clientSecret??i?.clientSecret,authUrl:J1?.authUrl??i?.authUrl,tokenUrl:J1?.tokenUrl??i?.tokenUrl,scopes:z1,headlessAuthHandler:t});return x.debug("OAuth provider created",{serverName:e,serverUrl:c,hasManualClientId:!!(J1?.clientId??i?.clientId),willUseDCR:!(J1?.clientId??i?.clientId),scopes:z1,headlessMode:k1,executeMode:J.executeMode}),f1})();return K.set(q1,r),r}}),z=$01({configService:Z,filesystem:J5,spawn:qA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (jY6(),CY6)),M;if(J.executeMode){let e=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=e.registrations;for(let[c,J1]of e.initErrors)x.warn(`${c} provider initialization slow or failed:`,J1)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&Y06())cE("VS Code");else if(Q.ide&&X06())cE("Neovim");if(J.executeMode)UU0(!0);let L,A=H3.status.pipe(Q6((e)=>Boolean(e.connected&&e.authenticated)),U4()).subscribe((e)=>{if(e){if(!L)L=G.registerTool(pi0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let e=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new B61(process.cwd(),{alwaysIncludePaths:e},!0)}else E=new class extends B61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(o9.write(`No API key found. Starting login flow...
4843
4843
  `),!await XD8(J))await _A(),process.exit(1)}let I=await WP0({isDevelopment:!1}),P=new _I1(I,Z),R=new DI1(I,{lazy:!0}),y=new RU1(P,(e,c)=>{let J1=X2.get(e);if(J1)J1.handle(c).catch((q1)=>{x.error("Failed to apply artifact delta",q1)})}),k=Q.notifications!==void 0?Q.notifications:!J.executeMode,v=sa0({playNotificationSound:async(e)=>{if(k){ra0(e);let c=OC1(),J1=wC1();if((!c||J1)&&X.settings["notifications.system.enabled"]!==!1){if(e==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(e==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:P,configService:Z});x.info("Starting Amp background services");let g=cc0({threadService:P,threadHistoryService:R,configService:Z,isExtensionDevelopment:!1}),d;H3.status.subscribe((e)=>{d=e});let b=new uX1({workspaceRoots:[h0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return h0.parse(d.openFile)}catch(e){x.warn("Failed to parse current file URI",{uri:d.openFile,error:e});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let e=d.openFile;return d.visibleFiles.filter((c)=>c!==e).map((c)=>{try{return h0.parse(c)}catch(J1){return x.warn("Failed to parse visible file URI",{uri:c,error:J1}),null}}).filter((c)=>c!==null)}}),a=new PC1,G1={codebaseContextService:b,configService:Z,toolService:G,mcpService:H,trustStore:W,threadService:P,threadHistoryService:R,threadSyncService:g,planFileManager:y,threadStorage:I,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:v,fileSystem:Q.jetbrains||Q.ide?SE0:J5,terminal:a};return{...G1,async asyncDispose(){if(G1.mcpService.hasAuthenticatingClients())x.info("Waiting for OAuth authentication to complete before exit..."),await G1.mcpService.waitForAuthentication();for(let e of M.values())e.dispose();await G1.mcpService.dispose(),q(),await G1.threadService.asyncDispose(),G1.configService.unsubscribe(),V(),G1.fuzzyServer.dispose(),G1.threadSyncService.dispose(),G1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function XD8(J){if(!J.executeMode){if(!await eR1("Would you like to log in to Amp? [(y)es, (n)o]: "))return o9.write(`Login cancelled. Run the command again to retry.
4844
4844
  `),!1}return await fY6(J)}async function fY6(J){let Q=iN8(32).toString("hex"),Z=await tR1(J.ampURL,Q),Y=new AbortController;try{await hD(Z,Y.signal)}catch(G){x.error("Error opening browser",{error:G})}let X=await tR1(J.ampURL,Q,!1);o9.write(`If your browser does not open automatically, visit:
4845
4845
 
@@ -4849,7 +4849,7 @@ ${Y4.blue.bold(X)}
4849
4849
  Login successful! You can now use the Amp CLI.
4850
4850
  `),!0}catch(G){return x.error("Login failed",{error:G}),tQ.write(`
4851
4851
  Login failed: ${G instanceof Error?G.message:String(G)}
4852
- `),!1}}function $D8(){let J=new MA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)RR(),process.exit(0);let z=H.originalError??H;ne0(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${gI(new Date("2025-12-10T22:05:22.702Z"))} ago`}catch{}o9.write(`0.0.1765404020-g2e5656 (released 2025-12-10T22:05:22.702Z${z??""})
4852
+ `),!1}}function $D8(){let J=new MA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)RR(),process.exit(0);let z=H.originalError??H;ne0(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${gI(new Date("2025-12-11T00:06:58.334Z"))} ago`}catch{}o9.write(`0.0.1765411294-g5611a8 (released 2025-12-11T00:06:58.334Z${z??""})
4853
4853
  `),process.exit(0)}),J.addHelpText("after",J06()),J.configureHelp({formatHelp:Q06}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await HQ(U);await qD8(D)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await HQ(U);await KD8(D,await uR1(U,D.settings))});let Q=async(H,z,U)=>{QH1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:t1.of([h0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:mx1,userConfigDir:vY6});let D={...z,executeMode:!1};await hx1(D,{...H,openThreadSwitcher:!0},U)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await HQ(U);await kY6(U,D,z)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await HQ(U);await ND8(U,D,z)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await HQ(D);if(z.pick)tQ.write(`${Y4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4854
4854
  `);if(z.last||H||M.executeMode)await BD8(D,M,H,U);else await Q(D,M,U)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await HQ(D);await UD8(D,M,H,U)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await HQ(U);await kY6(U,D,z)}),Z.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
4855
4855
 
@@ -4865,8 +4865,8 @@ All matching is case-insensitive. File paths use partial matching.`).option("-n,
4865
4865
  Or pipe via stdin: echo "your message" | amp --execute`);TV(Z,Q);let V=await b$(J,Q);xY6=V;let K=rg(V),q=await eN8(V.configService),W=tN8(q?.email);if((J.executeMode||Q.streamJson)&&P9(Q.mode)&&!W)throw new R8(`Execute mode is not permitted with --mode '${Q.mode}'`,1);let H=async(b)=>{let a=await yY6(b,"utf-8"),G1=JSON.parse(a);if(!hX(G1.id))throw new R8(A$.invalidThreadId);return E51(V,{visibility:Y,agentMode:Q.mode,thread:G1})},z=async(b)=>{if(!hX(b))throw new R8(A$.invalidThreadId);try{let[G1,e]=await Promise.all([K5.getThreadLinkInfo({thread:b},{config:V.configService}),K5.getUserInfo({},{config:V.configService})]);if(G1.ok&&e.ok){let c=G1.result.creatorUserID,J1=e.result.id;if(c&&c!==J1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new R8(`Cannot resume thread created by another user.
4866
4866
 
4867
4867
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(G1){if(G1 instanceof R8)throw G1;x.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G1})}let a=await V.threadService.get(b)??void 0;return x.info(`[fetchAndStartThread] Loaded thread ${b}, agentMode: ${a?.agentMode??"undefined"}`),E51(V,{visibility:Y,agentMode:a?void 0:Q.mode,thread:a})},U=async()=>{try{if(Q.threadId)return z(Q.threadId);else return E51(V,{visibility:Y,agentMode:Q.mode})}catch(b){if(b instanceof R8)throw b;throw await qm(b,Q.threadId),Error("handleError should have called process.exit()")}},D=async()=>{return E51(V,{visibility:Y,agentMode:Q.mode})};if(Q.format==="jsonl")tQ.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4868
- `),await _A(),process.exit(1);if(J.executeMode&&Q.remote)await c06(X,G,V.configService),await V.asyncDispose(),process.exit(0);let M=await U();if(J.executeMode)f06(V.mcpService,J.settings),await K16(M,M.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,E=!1;if(Q.jetbrains||Q.ide){await CU0();let b=nE({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let a=b[0];if(a)H3.selectConfig(a)}else E=!0}let I=P61("0.0.1765404020-g2e5656",V.settingsStorage),P=new j11(V.threadStorage),R=t1.of([h0.file(process.cwd())]),y=rX1(void 0,R),k=new T61(V.mcpService,J.settings.getWorkspaceRootPath());if(X)M.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let g=await(async()=>{try{let b=await K5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return x.info("User free tier status:",b),b.result}catch(b){throw x.error("Failed to fetch free tier status:",b),b}})(),d=await a06();x.info("Loaded session state:",d),await Vy1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new K61,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:M.threadID,threadFuzzyIndexer:P,worker:M,workerDeps:K,configService:V.configService,internalAPIClient:K5,ampURL:J.ampURL,startNewThread:D,switchToThread:z,ideClient:H3,connectedClientsService:new Zn,commandRegistry:y,mcpService:V.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:E,openThreadSwitcher:Q.openThreadSwitcher,updateService:I,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:d,freeTierStatus:{canUseAmpFree:g.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function HQ(J){if(J.interactive)tQ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4869
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await b16({...J,workspaceTrust:{current:!0,changes:P_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await x06(J.mcpConfig);Y=v06(Y,G)}let X=await Y.get("url","global");if(!X)X=WZ;if(!BF(X))x.info("Targeting custom Amp server",{ampURL:X});return Y=BW0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:l06(await uR1(J,Y))}}function GD8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function VD8(){let J=GD8(process.argv);if(be0({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),rN8(x),x.info("Starting Amp CLI.",{version:"0.0.1765404020-g2e5656",buildTimestamp:"2025-12-10T22:05:22.702Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new R8(A$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await $D8().parseAsync(process.argv)}GI1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await VD8().catch(qm)});async function KD8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),o9.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4868
+ `),await _A(),process.exit(1);if(J.executeMode&&Q.remote)await c06(X,G,V.configService),await V.asyncDispose(),process.exit(0);let M=await U();if(J.executeMode)f06(V.mcpService,J.settings),await K16(M,M.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,W,Q.mode),await V.asyncDispose(),process.exit(0);let L=!1,A=!1,E=!1;if(Q.jetbrains||Q.ide){await CU0();let b=nE({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)A=!await V.configService.get("jetbrains.skipInstall")}else if(b.length===1){let a=b[0];if(a)H3.selectConfig(a)}else E=!0}let I=P61("0.0.1765411294-g5611a8",V.settingsStorage),P=new j11(V.threadStorage),R=t1.of([h0.file(process.cwd())]),y=rX1(void 0,R),k=new T61(V.mcpService,J.settings.getWorkspaceRootPath());if(X)M.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let g=await(async()=>{try{let b=await K5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(b.ok)return x.info("User free tier status:",b),b.result}catch(b){throw x.error("Failed to fetch free tier status:",b),b}})(),d=await a06();x.info("Loaded session state:",d),await Vy1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new K61,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:M.threadID,threadFuzzyIndexer:P,worker:M,workerDeps:K,configService:V.configService,internalAPIClient:K5,ampURL:J.ampURL,startNewThread:D,switchToThread:z,ideClient:H3,connectedClientsService:new Zn,commandRegistry:y,mcpService:V.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:A,showIdePicker:L,showIdePickerHint:E,openThreadSwitcher:Q.openThreadSwitcher,updateService:I,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:d,freeTierStatus:{canUseAmpFree:g.canUseAmpFree},workspace:q?.team??null,features:q?.features??[],isDogfooding:W,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function HQ(J){if(J.interactive)tQ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4869
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await b16({...J,workspaceTrust:{current:!0,changes:P_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await x06(J.mcpConfig);Y=v06(Y,G)}let X=await Y.get("url","global");if(!X)X=WZ;if(!BF(X))x.info("Targeting custom Amp server",{ampURL:X});return Y=BW0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:l06(await uR1(J,Y))}}function GD8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function VD8(){let J=GD8(process.argv);if(be0({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),rN8(x),x.info("Starting Amp CLI.",{version:"0.0.1765411294-g5611a8",buildTimestamp:"2025-12-11T00:06:58.334Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new R8(A$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await $D8().parseAsync(process.argv)}GI1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await VD8().catch(qm)});async function KD8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),o9.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4870
4870
  `);else if(!BF(J.ampURL))o9.write(`Logging in to ${new URL(J.ampURL).hostname}
4871
4871
  `);let Z=process.env.AMP_API_KEY;if(Z)o9.write(`API key found in environment variable, storing...
4872
4872
  `),await Q.set("apiKey",Z,J.ampURL),o9.write(`API key successfully stored.
@@ -4879,7 +4879,7 @@ This thread belongs to a different user and cannot be continued for security rea
4879
4879
  `);else o9.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4880
4880
  `);process.exit(0)}async function WD8(J,Q,Z,Y,X){TV(X,J);let G=await b$(Q,J);try{let V=I51(Z);if(!V)P51(Z);let K=V,q=Y.trim();if(q.length===0)ZX("Thread name cannot be empty");if(q.length>256)ZX("Thread name cannot exceed 256 characters");if(!(await cC(K,G)).messages.length)ZX("Cannot rename an empty thread.");let H=rg(G);await(await X2.getOrCreateForThread(H,K)).handle({type:"title",value:q}),x.info("GOT HERE"),await G.threadSyncService.sync(),x.info("GOT THERE"),o9.write(Y4.green(`✓ Thread ${K} renamed to "${q}"
4881
4881
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;ZX(K)}}async function HD8(J,Q,Z,Y){TV(Y,J);let X=await b$(Q,J);try{let G=I51(Z);if(!G)P51(Z);let K=await cC(G,X),q=YR(K);o9.write(q+`
4882
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;ZX(V)}}async function zD8(J,Q,Z,Y,X){TV(X,J);let G=await b$(Q,J);try{let V=await gx1(Z),K=await cC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=rg(G),L=K.id;await G.threadStorage.set(L,K);let A=await X2.getOrCreateForThread(M,L);await A.resume();let E=C11.fromWorker(A),I=new j11(G.threadStorage),P=t1.of([h0.file(process.cwd())]),R=rX1(void 0,P),y=new T61(G.mcpService,Q.settings.getWorkspaceRootPath()),k=P61("0.0.1765404020-g2e5656",G.settingsStorage);await Vy1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new K61,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:K5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:H3,connectedClientsService:new Zn,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:y,showJetBrainsInstaller:!1,updateService:k,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await qm(V,Z)}}async function FD8(J,Q,Z,Y,X){TV(Y,J);let G=await b$(Q,J);try{let V=I51(Z);if(!V)P51(Z);let K=V,q=await K5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=R61(J,W);if(!H&&!X)ZX("Must specify either --visibility or --support");if(H&&X)ZX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)ZX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,C61(H)),o9.write(Y4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4882
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;ZX(V)}}async function zD8(J,Q,Z,Y,X){TV(X,J);let G=await b$(Q,J);try{let V=await gx1(Z),K=await cC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=rg(G),L=K.id;await G.threadStorage.set(L,K);let A=await X2.getOrCreateForThread(M,L);await A.resume();let E=C11.fromWorker(A),I=new j11(G.threadStorage),P=t1.of([h0.file(process.cwd())]),R=rX1(void 0,P),y=new T61(G.mcpService,Q.settings.getWorkspaceRootPath()),k=P61("0.0.1765411294-g5611a8",G.settingsStorage);await Vy1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new K61,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:K5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:H3,connectedClientsService:new Zn,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:y,showJetBrainsInstaller:!1,updateService:k,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D},freeTierStatus:{canUseAmpFree:!0},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await qm(V,Z)}}async function FD8(J,Q,Z,Y,X){TV(Y,J);let G=await b$(Q,J);try{let V=I51(Z);if(!V)P51(Z);let K=V,q=await K5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=R61(J,W);if(!H&&!X)ZX("Must specify either --visibility or --support");if(H&&X)ZX("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)ZX(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,C61(H)),o9.write(Y4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4883
4883
  `);if(X){await cC(K,G);let z=typeof X==="string"?X:void 0;await XP0(G.threadService,K,G.configService,z),o9.write(Y4.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
4884
4884
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),ZX(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function UD8(J,Q,Z,Y){TV(Y,J);let X=await b$(Q,J),G=rg(X);try{let V=await gx1(Z),q=(await cC(V,X)).messages.length-1,W=await X2.getOrCreateForThread(G,V),H=await GR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await bx1(H),o9.write(`${H}
4885
4885
  `),await X.asyncDispose(),process.exit(0)}catch(V){tQ.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1765404020-g2e5656",
3
+ "version": "0.0.1765411294-g5611a8",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {