@sourcegraph/amp 0.0.1759276921-gbfbfa1 → 0.0.1759294726-g7c064a

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 +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -136,7 +136,7 @@ ${ew6(Q.progress)}
136
136
  ${W}`)}let U=`${J}.${process.pid}.${Date.now()}.tmp`;try{await UE6(sl.dirname(J),{recursive:!0});let W=GE6(U),F=BE6.fromWeb(z.body);await DE6(F,W);let H=await NE6(U);if(H!==G)throw Error(`ripgrep checksum validation failed: expected ${G}, got ${H}`);if(process.platform!=="win32")await zE6(U,493);try{await FE6(U,J)}catch(D){if(D instanceof Error&&"code"in D&&D.code==="EEXIST")return;throw D}}finally{await HE6(U).catch(()=>{})}}async function NE6(J){let Q=qE6("sha256"),Z=await WE6(J);return Q.update(Z),Q.digest("hex")}function LE6(){let J=process.env.npm_config_arch||xU1.arch();switch(xU1.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: "+xU1.platform())}}async function AE6(){if(rv!==void 0)return rv;try{return rv=(await M10.promisify(KE6)("rg --version")).stdout.includes("ripgrep"),rv}catch{return rv=!1,!1}}var N10,rv;var gR=p(()=>{D0();D4();N10=D10(async(J)=>{if(V10(J))return J;let Q=3;for(let Z=1;Z<=Q;Z++)try{return await VE6(J),a.info("ripgrep binary downloaded successfully",{path:J}),J}catch(X){let Y=X instanceof Error?X.message:String(X);if(Z===Q){a.error("ripgrep download failed after all attempts",{error:Y});return}a.warn(`ripgrep download attempt ${Z}/${Q} failed: ${Y}`),await new Promise((K)=>setTimeout(K,500*Math.pow(2,Z-1)))}return})});var j10={};L6(j10,{ripgrepFiles:()=>ol,nodeGlobTool:()=>jE6,globFilesWithRipgrep:()=>O10});import{spawn as OE6}from"node:child_process";function O10(J,Q,Z){return J4(...J.map((X)=>RE6(X,Q,Z))).pipe(g0((X)=>{let Y=[];for(let G of X)if(G.status==="in-progress")Y.push(...G?.progress??[]);else if(G.status==="done")Y.push(...G.result);else if(G.status==="error")Y.push(...G.progress??[]);else if(G.status==="cancelled")Y.push(...G.progress??[]);let K=X.filter((G)=>G.status==="error");if(K.length>0)return{status:"error",progress:Y,error:{message:K.map((G)=>G?.error?.message??"").join(`
137
137
  `)}};return{status:X.every((G)=>G.status==="done")?"done":X.some((G)=>G.status==="cancelled")?"cancelled":"in-progress",progress:Y,result:Y}}))}function RE6(J,Q,Z){return new K0((X)=>{X.next({status:"in-progress",progress:[]}),ol(J,Q?{pattern:Q,caseInsensitive:!0}:null,Z??{}).then(({files:Y,remaining:K})=>{if(K>0)Y.push(`--- ${K} more files not shown ---`);X.next({status:"done",progress:Y,result:Y})}).catch((Y)=>{let K=Y instanceof Error?Y.message:String(Y);X.next({status:"error",progress:[],error:{message:K}})}).finally(()=>X.complete())})}async function ol(J,Q,Z){let X=Z.limit??fU1,Y=["--files","--color","never","--no-require-git","--hidden","--glob","!\\.git/","--glob","!\\.jj/"];if(Z.maxDepth!==void 0)Y.push("--max-depth",Z.maxDepth.toString());let K;if(Z.basePath)Ql(Z.basePath),K=FW(Z.basePath)?Z.basePath:u0.joinPath(J,Z.basePath).fsPath;else K=J.fsPath;if(Y.push(K),Q?.pattern&&Q.pattern==="*")Q.pattern="**";let q=Q?.pattern?A10.default(Q.pattern,{nocase:Q.caseInsensitive,dot:!0}):void 0,G=OE6(await mN(),Y,{stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",env:{...process.env,NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}});return new Promise((z,U)=>{let W=[],F="",H="",D=Z.offset??0,M=!1,V=()=>{if(M)return;if(!H)return;let N=H.startsWith(K)?H.slice(K.length+1):H;if(q&&!q(N))return;let L=H;if(H="",D>0){D--;return}if(W.push(L),W.length>=fU1)a.warn("Glob limit reached. Returning partial results.",{glob:Q?.pattern,limit:fU1,dir:J}),G.kill(),M=!0,z({files:W,remaining:0,aborted:!0})};G.stdout?.on("data",(N)=>{for(let L of String(N)){if(L==="\r")continue;if(L===`
138
138
  `)V(),H="";else H+=L}}),G?.stderr?.on("data",(N)=>{F+=String(N)}),G.on("exit",(N)=>{if(N&&N>=2){U(Error(`ripgrep exited with code ${N}:
139
- ${F}`));return}V();let L=W.slice(0,X);z({files:L,remaining:W.length-L.length})})})}var A10,jE6=({args:J},{dirs:Q})=>{if(Q.length===0)return new K0((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Z={};if(J.limit!==void 0)Z.limit=J.limit;if(J.offset!==void 0)Z.offset=J.offset;return O10(Q,J.filePattern,Z)},fU1=500000;var hU1=p(()=>{Y8();n0();A10=u6(_j(),1);D0();oS();gR();sG()});function RQ(J){return J instanceof KJ||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function R10(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function w10(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 I10(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 Jq(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function sv(J,Q,Z){try{return await J.readFile(Q,Z)}catch(X){if(X instanceof KJ)return null;throw X}}async function ov(J,Q,Z){try{return await J.access(Q,Z),!0}catch(X){if(RQ(X))return!1;throw X}}var KJ;var hJ=p(()=>{KJ=class KJ extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});import*as vX from"node:fs";import*as tl from"node:path";function wE6(J){if(!iH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function IW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function IE6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return S0.file(await vX.promises.realpath(J.fsPath))}catch(Q){if(IW(Q))throw new KJ(J);throw Q}}var R8;var uN=p(()=>{Y8();n0();D0();hU1();hJ();oS();R8={readFile:async(J,Q)=>{try{return await vX.promises.readFile(X8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await vX.promises.readFile(X8(J).fsPath,{signal:Q?.signal})}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await vX.promises.stat(X8(J).fsPath)).mtimeMs}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},stat:async(J,Q)=>{J=X8(J);try{let Z=await vX.promises.stat(J.fsPath);return{name:tl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},realpath:async(J,Q)=>{return IE6(X8(J))},rename:async(J,Q)=>{try{await vX.promises.rename(X8(J).fsPath,X8(Q).fsPath)}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await vX.promises.writeFile(X8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=X8(J);try{if(Q?.recursive)await vX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await vX.promises.unlink(J.fsPath)}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},mkdirp:async(J)=>{await vX.promises.mkdir(X8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=X8(J);try{return(await vX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:S0.file(tl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await ol(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>FW(X)?S0.file(X):u0.joinPath(J.base,X))}catch(Z){return a.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=X8(J);wE6(Z);try{await vX.promises.access(Z.fsPath)}catch(X){if(IW(X))throw new KJ(Z);throw X}}}});async function EE6(J,Q){let Z=X8(J).fsPath;if(!Z.startsWith(process.cwd()))return;if(a.debug("ide-fs",{method:"readFile",path:Z}),await jQ.isConnected())try{let X=await jQ.sendRequest("readFile",{path:Z});if(X?.content)return Q(X.content);throw Error(`Failed to readFile via IDE ${Z}: ${X?.message??"unknown cause"}`)}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;a.warn("IDE readFile failed, falling back to Node.js filesystem",{path:Z,error:X});return}else return}async function $E6(J,Q){let Z=X8(J).fsPath;if(!Z.startsWith(process.cwd()))return!1;if(a.debug("ide-fs",{method:"writeFile",path:Z}),await jQ.isConnected())try{let X=await jQ.sendRequest("editFile",{path:X8(J).fsPath,fullContent:Q});if(!X?.success)throw Error(`Failed to writeFile via IDE ${Z}: ${X?.message??"unknown cause"}`);return!0}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;return a.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:Z,error:X}),!1}else return!1}var E10;var $10=p(()=>{Y8();n0();D0();XR();uN();E10={readFile:async(J,Q)=>{return await EE6(J,(Z)=>Z)??await R8.readFile(J,Q).finally(()=>{a.debug("ide-fs",{fallback:"readFile"})})},readBinaryFile:async(J,Q)=>{return a.debug("ide-fs",{fallback:"readBinaryFile"}),R8.readBinaryFile(J,Q)},getMtime:async(J,Q)=>{return R8.getMtime(J,Q)},stat:async(J,Q)=>{return R8.stat(J,Q)},realpath:async(J,Q)=>{return R8.realpath(J,Q)},rename:async(J,Q)=>{return R8.rename(J,Q)},writeFile:async(J,Q,Z)=>{if(await $E6(J,Q))return;return await R8.writeFile(J,Q,Z).finally(()=>{a.debug("ide-fs",{fallback:"writeFile"})})},delete:async(J,Q)=>{return R8.delete(J,Q)},mkdirp:async(J)=>{return R8.mkdirp(J)},readdir:async(J,Q)=>{return R8.readdir(J,Q)},findFiles:async(J,Q)=>{return R8.findFiles(J,Q)},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return R8.access(J,Q)}}});function mU1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function gU1(J,Q){Q=X8(Q);let Z,X;for(let Y of J.trees){if(!Y.uri)continue;let K=MX(Y.uri);if(u0.hasPrefix(Q,K)){let q=u0.relativePath(K,Q);if(q===null)continue;if(X===void 0||q.length<X.length)X=q,Z=Y}}if(!Z||X===void 0)return null;return{tree:Z,filePath:X}}function TE6(J){return Array.isArray(J)}function CE6(J){let Q;if(J===void 0)Q=void 0;else if(TE6(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??PE6}function P10(J,Q){for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Q,Y))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Y,Q))Z.push(Y)}return{isImplied:Z.length>0,childMountPoints:Z}}function tv(J){return{trees:CE6(J)}}function C10(J){let Q={...J.os,mountedTree:T10},Z=new Map;function X(q){if(!q.fs||q.fs==="os")return Q;if(!q.uri)throw Error("Tree URI is required");if(!q.repository)throw Error(`Tree with FS type ${q.fs} requires repository field`);let G={uri:q.uri,repository:q.repository,fs:q.fs},z=`${q.fs}:${JSON.stringify(q)}`,U=Z.get(z);if(!U){let W=J[q.fs];if(!W)throw Error(`No file system implementation found for: ${q.fs}`);U={...W(G),mountedTree:G},Z.set(z,U)}return U}function Y(q){return q.trees.some((G)=>G.fs&&G.fs!=="os")}function K(q,G){let z=q.trees.map((W)=>({mountPoint:W.uri,fs:X(W)}));function U(W){if(!Y(q))return G?{...G(Q),mountedTree:Q.mountedTree}:Q;let F=gU1(q,W)?.tree;if(!F)throw new KJ(W);let H=z.find((D)=>u0.equalURIs(D.mountPoint,F.uri))?.fs;if(!H)throw Error(`No file system found for URI: ${W}`);return G?{...G(H),mountedTree:H.mountedTree}:H}return{map(W){if(G)throw Error("Cannot use both prepare and prepare2");return K(q,W)},mapReader(W){if(G)throw Error("Cannot use both prepare and prepare2");let F=K(q,W);return{...w10(F),mountedFileSystemForURI:F.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:F.mapReader,__isFileSystemWithMountedTrees:F.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:F.__isImmutableBaseFileSystem}},mountedFileSystemForURI(W){return U(W)},readFile:async(W,F)=>U(W).readFile(W,F),readBinaryFile:async(W,F)=>U(W).readBinaryFile(W,F),getMtime:async(W,F)=>U(W).getMtime(W,F),realpath:async(W,F)=>U(W).realpath(W,F),access:async(W,F)=>U(W).access(W,F),findFiles:async(W,F)=>U(W.base).findFiles(W,F),stat:async(W,F)=>{let H=X8(W),{isImplied:D}=P10(q,H);if(D)return{size:0,isDirectory:!0};return U(W).stat(W,F)},rename:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`rename(${W}) is not supported by this file system`);return H.rename(W,F)},writeFile:async(W,F,H)=>{let D=U(W);if(Jq(D))throw Error(`writeFile(${W}) is not supported by this file system`);return D.writeFile(W,F,H)},mkdirp:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`mkdirp(${W}) is not supported by this file system`);return H.mkdirp(W,F)},delete:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`delete(${W}) is not supported by this file system`);return H.delete(W,F)},readdir:async(W,F)=>{W=X8(W);let{isImplied:H,childMountPoints:D}=P10(q,W);if(H){let V=new Set;for(let N of D){let L=u0.relativePath(W,N);if(L){let A=L.split("/")[0];if(A)V.add(A)}}return Array.from(V).map((N)=>({uri:u0.joinPath(W,N),isDirectory:!0}))}return U(W).readdir(W,F)},watch:(W,F)=>{if(!Y(q))return Q.watch(W,F);if(!S0.isUri(W))throw Error("Watch with glob is not yet implemented in the file system router");let H=U(W);if(Jq(H))return DY;return H.watch(W,F)},isExclusiveWriterFor:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`isExclusiveWriterFor(${W}) is not supported by this file system`);return H.isExclusiveWriterFor(W,F)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:K,fileSystemForURI:(q,G)=>X(gU1(q,G)?.tree??T10),osFileSystem:Q}}function SB(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let X=gU1(tv(Z.thread),Z.dir)?.tree.fs??"os",Y=J[X];if(Y)return lH(Y()).pipe(S9((K)=>K(Q,Z)));throw Error(`Unsupported file system: ${X}`)}}var PE6,T10;var EW=p(()=>{Y8();n0();hJ();PE6=[];T10={fs:"os",uri:"file:///"}});function SE6(){return new Proxy({},{get:(J,Q)=>{return async(...Z)=>{let X=Z.at(1),Y=Z.at(0),K=await LZ("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:JSON.stringify({method:Q,params:Y}),signal:X?.signal});if(!K.ok)throw Error(`API request failed: ${K.status}`);return await K.json()}}})}var NZ;var pN=p(()=>{vB();NZ=SE6()});function vE6(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 ev(J,Q){return new URL(`/threads/${Q}`,J)}async function LZ(J,Q){let Z=await O9(Q?.signal??void 0);return kE6(Z,J,Q)}async function v10(J,Q){let Z=await J.get(Q);if(!Z)throw Error(`Thread not found: ${Q}`);let X=await NZ.shareThreadWithOperator({threadData:Z});if(!X.ok)throw Error(`Failed to share thread: ${X.error.message}`)}async function k10(J){let Q=await LZ("/api/telemetry",{method:"POST",headers:{"Content-Type":"application/json"},body:J});if(!Q.ok){let Z=await Q.text(),X;try{X=JSON.parse(Z).error||`HTTP ${Q.status}`}catch{X=Z||`HTTP ${Q.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function kE6(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 X=J.settings.url;if(!X)throw Error("amp.url is not set");let Y=await J.secrets.getToken("apiKey",X);if(!Y||Y.trim()===""){let K=Error("Amp API key is not set");throw K.name="MissingApiKeyError",K}return vE6({proxy:J.settings.proxy}),fetch(new URL(Q,X),{...Z,headers:{...Z?.headers,...pG(),"Content-Type":"application/json",Authorization:`Bearer ${Y}`}})}var S10;var vB=p(()=>{n0();D4();sU();pN();S10=Z2.pipe(S9(({settings:J,secrets:Q})=>{return p8(async()=>{return await Q.getToken("apiKey",J.url)!==void 0})}))});class uR{heap;length;static#J=!1;static create(J){let Q=y10(J);if(!Q)return[];uR.#J=!0;let Z=new uR(J,Q);return uR.#J=!1,Z}constructor(J,Q){if(!uR.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}var mR,b10,uU1,x10=(J,Q,Z,X)=>{typeof uU1.emitWarning==="function"?uU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},el,_10,_E6=(J)=>!b10.has(J),TA9,kB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),y10=(J)=>!kB(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?Jk:null,Jk,Ji;var f10=p(()=>{mR=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,b10=new Set,uU1=typeof process==="object"&&!!process?process:{},el=globalThis.AbortController,_10=globalThis.AbortSignal;if(typeof el>"u"){_10=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},el=class{constructor(){Q()}signal=new _10;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=uU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,x10("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}TA9=Symbol("type");Jk=class Jk extends Array{constructor(J){super(J);this.fill(0)}};Ji=class Ji{#J;#Z;#Y;#X;#G;#$;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#W;#A;#F;#O;#j;#V;#R;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#j,ttls:J.#V,sizes:J.#O,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#w(Q),rindexes:(Q)=>J.#I(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Z}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#$}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#G}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:q,allowStale:G,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:F,noUpdateTTL:H,maxSize:D=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:O,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:R,ignoreFetchAbort:I}=J;if(Q!==0&&!kB(Q))throw TypeError("max option must be a nonnegative integer");let w=Q?y10(Q):Array;if(!w)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=D,this.maxEntrySize=M||this.#Z,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Z&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#$=N,this.#C=!!N,this.#z=new Map,this.#q=Array(Q).fill(void 0),this.#Q=Array(Q).fill(void 0),this.#B=new w(Q),this.#M=new w(Q),this.#H=0,this.#W=0,this.#A=uR.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#G=W,this.#F=[];else this.#G=void 0,this.#F=void 0;if(this.#R=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#Z!==0){if(!kB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!kB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!O,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=kB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!kB(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Z===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Z){if(_E6("LRU_CACHE_UNBOUNDED"))b10.add("LRU_CACHE_UNBOUNDED"),x10("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",Ji)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new Jk(this.#J),Q=new Jk(this.#J);this.#V=J,this.#j=Q,this.#h=(Y,K,q=mR.now())=>{if(Q[Y]=K!==0?q:0,J[Y]=K,K!==0&&this.ttlAutopurge){let G=setTimeout(()=>{if(this.#N(Y))this.#E(this.#q[Y],"expire")},K+1);if(G.unref)G.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?mR.now():0},this.#P=(Y,K)=>{if(J[K]){let q=J[K],G=Q[K];if(!q||!G)return;Y.ttl=q,Y.start=G,Y.now=Z||X();let z=Y.now-G;Y.remainingTTL=q-z}};let Z=0,X=()=>{let Y=mR.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let q=J[K],G=Q[K];if(!q||!G)return 1/0;let z=(Z||X())-G;return q-z},this.#N=(Y)=>{let K=Q[Y],q=J[Y];return!!q&&!!K&&(Z||X())-K>q}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new Jk(this.#J);this.#L=0,this.#O=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!kB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!kB(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#b=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#x(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#b=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#w({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#I({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#H;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#q[J])===J}*entries(){for(let J of this.#w())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*rentries(){for(let J of this.#I())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*keys(){for(let J of this.#w()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#I()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#w())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#I())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#w()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#q[Z],this))return this.get(this.#q[Z],Q)}}forEach(J,Q=this){for(let Z of this.#w()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}rforEach(J,Q=this){for(let Z of this.#I()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#I({allowStale:!0}))if(this.#N(Q))this.#E(this.#q[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Q[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#j){let K=this.#V[Q],q=this.#j[Q];if(K&&q){let G=K-(mR.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#O)Y.size=this.#O[Q];return Y}dump(){let J=[];for(let Q of this.#w({allowStale:!0})){let Z=this.#q[Q],X=this.#Q[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#j){K.ttl=this.#V[Q];let q=mR.now()-this.#j[Q];K.start=Math.floor(Date.now()-q)}if(this.#O)K.size=this.#O[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=mR.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:q=this.sizeCalculation,status:G}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,q);if(this.maxEntrySize&&U>this.maxEntrySize){if(G)G.set="miss",G.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#x(!1):this.#U,this.#q[W]=J,this.#Q[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#b(W,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let F=this.#Q[W];if(Q!==F){if(this.#C&&this.#K(F)){F.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!K){if(this.#R)this.#Y?.(H,J,"set");if(this.#D)this.#F?.push([H,J,"set"])}}else if(!K){if(this.#R)this.#Y?.(F,J,"set");if(this.#D)this.#F?.push([F,J,"set"])}if(this.#v(W),this.#b(W,U,G),this.#Q[W]=Q,G){G.set="replace";let H=F&&this.#K(F)?F.__staleWhileFetching:F;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===F?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(G)this.#P(G,W)}if(!K&&this.#D&&this.#F){let F=this.#F,H;while(H=F?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#x(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#F){let J=this.#F,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#x(J){let Q=this.#H,Z=this.#q[Q],X=this.#Q[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#R||this.#D){if(this.#R)this.#Y?.(X,Z,"evict");if(this.#D)this.#F?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#H=this.#W=0,this.#A.length=0;else this.#H=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Q[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Q[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Q[Q];if(this.#K(Y))return Y;let K=new el,{signal:q}=Z;q?.addEventListener("abort",()=>K.abort(q.reason),{signal:K.signal});let G={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=H;if(this.#Q[Q]===H)if(M===void 0)if(A.__staleWhileFetching)this.#Q[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,G.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,O=H;if(this.#Q[Q]===H){if(!A||O.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=O.__staleWhileFetching}if(L){if(Z.status&&O.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return O.__staleWhileFetching}else if(O.__returned===O)throw M},F=(M,V)=>{let N=this.#$?.(J,Y,G);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let H=new Promise(F).then(z,U),D=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,D,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=D;return D}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof el}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:q=this.noDisposeOnSet,size:G=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:D=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:D,ignoreFetchAbort:H,status:N,signal:L},O=this.#z.get(J);if(O===void 0){if(N)N.fetch="miss";let j=this.#y(J,O,A,M);return j.__returned=j}else{let j=this.#Q[O];if(this.#K(j)){let $=Z&&j.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",$)N.returnedStale=!0}return $?j.__staleWhileFetching:j.__returned=j}let R=this.#N(O);if(!V&&!R){if(N)N.fetch="hit";if(this.#k(O),X)this.#S(O);if(N)this.#P(N,O);return j}let I=this.#y(J,O,A,M),E=I.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=R?"stale":"refresh",E&&R)N.returnedStale=!0}return E?I.__staleWhileFetching:I.__returned=I}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,q=this.get(J,K);if(!Y&&q!==void 0)return q;let G=Z(J,q,{options:K,context:X});return this.set(J,G,K),G}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,q=this.#z.get(J);if(q!==void 0){let G=this.#Q[q],z=this.#K(G);if(K)this.#P(K,q);if(this.#N(q)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?G:void 0}else{if(K&&Z&&G.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?G.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return G.__staleWhileFetching;if(this.#k(q),X)this.#S(q);return G}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Q[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#R||this.#D){if(this.#R)this.#Y?.(Y,J,Q);if(this.#D)this.#F?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#H)this.#H=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let q=this.#B[X];this.#M[q]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#F?.length){let X=this.#F,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#I({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#R)this.#Y?.(Z,X,J);if(this.#D)this.#F?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#j)this.#V.fill(0),this.#j.fill(0);if(this.#O)this.#O.fill(0);if(this.#H=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#F){let Q=this.#F,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}});function pU1(J,Q,Z){let X=new b8,K=(()=>{let D=new Map;return(M,V)=>{let L=(D.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(D.get(M)===L)D.delete(M)});return D.set(M,L),L}})(),q=Z?u0.joinPath(Q,Z):Q;function G(D){return u0.joinPath(q,`${D.toString()}.json`)}async function z(D){let M=G(D);try{let V=await J.readBinaryFile(M),N=20971520;if(V.length>20971520){let L=Math.round(V.length/1048576);a.warn(`File too large to load safely: ${String(D)} (${L}MB)`,{key:String(D),size:V.length,maxSize:20971520});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:O,contentPreview:j}=bE6(V);a.warn("Corrupted JSON detected.",{key:String(D),storageUri:q.toString(),error:A.message,contentLength:O,contentPreview:j});return}}catch(V){if(RQ(V))return;throw V}}async function U(D,M){let V=G(D),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(u0.joinPath(V,"..")),await K(D,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(D)}async function W(D){let M=G(D);await K(D,async()=>{await J.delete(M)}),X.next(D)}async function F(){let D;try{D=await J.readdir(q)}catch(M){if(RQ(M))return[];throw M}return D.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function H(D){return G(D).fsPath}return{get:z,set:U,delete:W,keys:F,path:H,changes:X}}function bE6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}var h10=p(()=>{Y8();n0();D0();hJ()});var cE6={};import _B from"node:path";import{parentPort as dU1,workerData as xE6}from"node:worker_threads";function fE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}async function hE6(J,Q,Z,X,Y){try{await R8.mkdirp(Z),await u10(Z)}catch(K){throw a.error("Cannot create migration directory, aborting migration:",K),K}if(await ov(R8,Y)){a.debug("Migration already completed by another process");return}try{await m10(X),a.info("Starting thread migration")}catch(K){if(pE6(K))if(await dE6(X))a.info("Removing stale migration lock and retrying"),await R8.delete(X),await m10(X),a.info("Starting thread migration (after stale lock cleanup)");else{a.debug("Another process is running migration");return}else throw a.error("Failed to acquire migration lock:",K),K}try{await gE6(J,Q),await(await import("node:fs/promises")).rename(X.fsPath,Y.fsPath),a.info("Thread migration completed")}catch(K){try{await R8.delete(X)}catch{}throw K}}async function gE6(J,Q){await R8.mkdirp(Q),await u10(Q);try{let X=(await R8.readdir(J)).filter((K)=>_B.basename(K.uri.path).endsWith(".json"));a.info(`Migrating ${X.length} threads to centralized storage`);let Y=0;for(let K=0;K<X.length;K+=g10){let q=X.slice(K,K+g10);await Promise.all(q.map(async(G)=>{let z=_B.basename(G.uri.path),U=G.uri,W=S0.file(_B.join(Q.path,z));if(await ov(R8,W))return;await mE6(U,W),Y++}))}a.info(`Migration completed: ${Y} threads migrated`)}catch(Z){a.debug("No legacy threads to migrate:",Z)}}async function mE6(J,Q){let Z=await import("node:fs/promises");try{await Z.rename(J.fsPath,Q.fsPath)}catch(X){if(X.code==="EXDEV")await uE6(J,Q),await R8.delete(J);else throw X}}async function uE6(J,Q){let Z=await R8.readFile(J);await R8.writeFile(Q,Z);try{let X=await import("node:fs/promises"),Y=await X.stat(J.fsPath);await X.utimes(Q.fsPath,Y.atime,Y.mtime)}catch(X){a.debug(`Could not preserve timestamp for ${_B.basename(Q.path)}:`,X)}}async function m10(J){let Q=await import("node:fs/promises");try{let Z=JSON.stringify({pid:process.pid,startTime:Date.now()});await Q.writeFile(J.fsPath,Z,{flag:"wx"})}catch(Z){if(Z.code==="EEXIST"){let X=Error(`File already exists: ${J.toString()}`);throw X.code="EEXIST",X}throw Z}}function pE6(J){return J instanceof Error&&(("code"in J)&&J.code==="EEXIST"||J.message.includes("already exists"))}async function u10(J){try{await(await import("node:fs/promises")).chmod(J.fsPath,448)}catch(Q){a.debug("Could not set secure permissions:",Q)}}async function dE6(J){try{let Q=await R8.readFile(J),Z=JSON.parse(Q),X=Date.now()-Z.startTime;if(X>yE6)return a.debug(`Migration lock is stale (${Math.round(X/1000/60)}min old)`),!0;return!1}catch(Q){return a.debug("Could not read migration lock file, considering stale:",Q),!0}}var g10=25,yE6=300000;var p10=p(()=>{Y8();D0();hJ();uN();if(dU1){let{legacyDir:J,centralizedDir:Q,isDevelopment:Z}=xE6,X=S0.parse(J),Y=S0.parse(Q),K=S0.file(_B.join(Y.path,"..","migration")),q=fE6(Z),G=S0.file(_B.join(K.path,q.progress)),z=S0.file(_B.join(K.path,q.done));hE6(X,Y,K,G,z).then(async()=>{try{let W=(await R8.readdir(Y)).filter((F)=>_B.basename(F.uri.path).endsWith(".json")).length;dU1?.postMessage({migratedCount:W})}catch{dU1?.postMessage({migratedCount:0})}}).catch((U)=>{throw U})}});import{homedir as lE6}from"node:os";import bB from"node:path";import{Worker as iE6}from"node:worker_threads";async function d10(J){let Q=J.isDevelopment||!1,Z=aE6(),X=Q?"threads-development":"threads",Y=pU1(R8,Z,X),K=new c10(Y);if(!J.vscodeMigrationContext)return a.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=S0.file(bB.join(Z.path,X)),U=Q?"threads3-development":"threads3",W=S0.file(bB.join(G.globalStorageUri.path,U));if(await rE6(z,Q,W))return a.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{a.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),sE6(W,z,Q);let H=pU1(q,G.globalStorageUri,U);return nE6(K,H)}}class c10{delegate;cache=new Ji({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){await this.delegate.set(J,Q),this.cache.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function nE6(J,Q){return{async get(Z){let X=await J.get(Z);if(X!==void 0)return X;return Q.get(Z)},async set(Z,X){await J.set(Z,X)},async delete(Z){await J.delete(Z).catch(()=>{}),await Q.delete(Z).catch(()=>{})},async keys(){let[Z,X]=await Promise.all([J.keys(),Q.keys()]);return[...new Set([...Z,...X])]},async path(Z){let X=await J.path(Z);if(X)return X;return Q.path(Z)},get changes(){return J.changes}}}function aE6(){let J=process.env.XDG_DATA_HOME||bB.join(lE6(),".local","share"),Q=bB.resolve(J,"amp");return S0.file(Q)}async function rE6(J,Q,Z){let X=S0.file(bB.join(J.path,"..","migration")),Y=oE6(Q),K=S0.file(bB.join(X.path,Y.done));if(await ov(R8,K))return!0;if(Z)try{if((await R8.readdir(Z)).filter((z)=>bB.basename(z.uri.path).endsWith(".json")).length===0){if((await R8.readdir(J)).filter((W)=>bB.basename(W.uri.path).endsWith(".json")).length>0){a.info("Detected completed migration without marker, creating completion marker");try{await R8.mkdirp(X),await R8.writeFile(K,"completed")}catch(W){a.debug("Could not create migration completion marker:",W)}return!0}}}catch(q){a.debug("Could not check legacy directory for completion detection:",q)}return!1}function sE6(J,Q,Z){try{let X=new iE6(o1.resolve("/home/runner/work/amp/amp/core/src/storage/migration-worker.node.ts"),{workerData:{legacyDir:J.toString(),centralizedDir:Q.toString(),isDevelopment:Z}});X.on("message",(Y)=>{a.info("Background migration completed:",Y)}),X.on("error",(Y)=>{a.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)a.warn(`Migration worker exited with code ${Y}`)})}catch(X){let Y=X instanceof Error?X.message:String(X);if(Y.includes("Worker is not supported")||Y.includes("Cannot resolve module")||Y.includes("ENOENT")&&Y.includes("migration-worker"))a.debug("Migration worker could not be started (expected in tests):",X);else a.warn("Migration worker failed to start, migration will be skipped:",X)}}function oE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}var l10=p(()=>{Y8();f10();D0();hJ();uN();h10()});async function pR(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=tE6(J,q),z=G<0,U,W;if(K.time){let F=K.time[J],H=K.time[q],D=Date.now();if(F)U=Math.floor((D-new Date(F).getTime())/3600000);if(H)W=Math.floor((D-new Date(H).getTime())/3600000)}return a.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return a.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function tE6(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}var Qi=p(()=>{D0()});import{execFile as eE6}from"node:child_process";import{promises as xB}from"node:fs";import{homedir as cU1}from"node:os";import{join as Qq}from"node:path";import{promisify as J$6}from"node:util";class lU1{async collect(){let[J,Q,Z,X,Y]=await Promise.all([this.collectInstallationInfo(),this.collectEnvironmentInfo(),this.collectConfigInfo(),this.collectCliTestInfo(),this.collectLogsInfo()]);return{cliTest:X,config:Z,environment:Q,installation:J,logs:Y}}async collectInstallationInfo(){let J={installMethod:"unknown",packageManager:"unknown"};try{if(J.version=await this.getCliVersion(),J.version)J.versionAge=await this.getCliAge(J.version)}catch{}try{J.installMethod=await this.detectInstallMethod()}catch{}try{J.packageManager=await this.detectPackageManager()}catch{}try{J.executablePath=process.execPath}catch{}return J}async collectEnvironmentInfo(){let J={};for(let[Q,Z]of Object.entries(process.env))if(Q.startsWith("AMP_")&&Z!==void 0)J[Q]=Z;return{variables:J}}async collectConfigInfo(){let J={};try{let Q=this.getSettingsPath(),Z=await xB.readFile(Q,"utf8");J.settings=JSON.parse(Z)}catch(Q){J.configError=Q instanceof Error?Q.message:String(Q)}try{let Q=this.getSecretsPath(),Z=await xB.readFile(Q,"utf8");J.secrets=JSON.parse(Z)}catch(Q){J.secretsError=Q instanceof Error?Q.message:String(Q)}return J}async collectCliTestInfo(){let J=new Date().toISOString();try{await dR("which",["amp"],{timeout:5000})}catch{return{additionalTests:[],executedAt:J,initialTest:{command:`echo "what is today's date" | amp`,error:"amp command not found in PATH",exitCode:127,stderr:"",stdout:""}}}let Q=await this.runCliCommand(`echo "what is today's date" | amp`),Z=[];if(Q.exitCode===0){let X=["amp threads list","amp tools show"];for(let Y of X){let K=await this.runCliCommand(Y);Z.push(K)}}return{additionalTests:Z,executedAt:J,initialTest:Q}}async runCliCommand(J){let Q={command:J,exitCode:-1,stderr:"",stdout:""};try{let{spawn:Z}=await import("node:child_process");return new Promise((X)=>{let Y=Z("sh",["-c",J],{stdio:["pipe","pipe","pipe"],timeout:30000}),K="",q="";Y.stdout?.on("data",(G)=>{K+=G.toString()}),Y.stderr?.on("data",(G)=>{q+=G.toString()}),Y.on("close",(G)=>{Q.stdout=K,Q.stderr=q,Q.exitCode=G??-1,X(Q)}),Y.on("error",(G)=>{Q.error=G.message,Q.exitCode=-1,X(Q)}),setTimeout(()=>{Y.kill("SIGTERM"),Q.error="Command timed out after 30 seconds",Q.exitCode=-1,X(Q)},30000)})}catch(Z){return Q.error=Z instanceof Error?Z.message:String(Z),Q.exitCode=-1,Q}}async collectLogsInfo(){let J={recentLogs:[]};try{let Q=this.getLogPath(),X=(await xB.readFile(Q,"utf8")).split(`
139
+ ${F}`));return}V();let L=W.slice(0,X);z({files:L,remaining:W.length-L.length})})})}var A10,jE6=({args:J},{dirs:Q})=>{if(Q.length===0)return new K0((X)=>{X.next({status:"error",error:{message:"No directory provided"}}),X.complete()});let Z={};if(J.limit!==void 0)Z.limit=J.limit;if(J.offset!==void 0)Z.offset=J.offset;return O10(Q,J.filePattern,Z)},fU1=500000;var hU1=p(()=>{Y8();n0();A10=u6(_j(),1);D0();oS();gR();sG()});function RQ(J){return J instanceof KJ||J instanceof Error&&J.name==="FileNotExistError"||typeof J==="object"&&J!==null&&"code"in J&&typeof J.code==="string"&&["ENOENT","FileNotFound"].includes(J.code)}function R10(J){return typeof J==="object"&&J!==null&&"base"in J&&"pattern"in J&&typeof J.pattern==="string"}function w10(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 I10(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 Jq(J){return"__isImmutableBaseFileSystem"in J&&J.__isImmutableBaseFileSystem===!0}async function sv(J,Q,Z){try{return await J.readFile(Q,Z)}catch(X){if(X instanceof KJ)return null;throw X}}async function ov(J,Q,Z){try{return await J.access(Q,Z),!0}catch(X){if(RQ(X))return!1;throw X}}var KJ;var hJ=p(()=>{KJ=class KJ extends Error{constructor(J){let Q=typeof J==="string"?J:J.toString();super(`File not found: ${Q}`);this.name="FileNotExistError"}}});import*as vX from"node:fs";import*as tl from"node:path";function wE6(J){if(!iH(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function IW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function IE6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return S0.file(await vX.promises.realpath(J.fsPath))}catch(Q){if(IW(Q))throw new KJ(J);throw Q}}var R8;var uN=p(()=>{Y8();n0();D0();hU1();hJ();oS();R8={readFile:async(J,Q)=>{try{return await vX.promises.readFile(X8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await vX.promises.readFile(X8(J).fsPath,{signal:Q?.signal})}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await vX.promises.stat(X8(J).fsPath)).mtimeMs}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},stat:async(J,Q)=>{J=X8(J);try{let Z=await vX.promises.stat(J.fsPath);return{name:tl.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},realpath:async(J,Q)=>{return IE6(X8(J))},rename:async(J,Q)=>{try{await vX.promises.rename(X8(J).fsPath,X8(Q).fsPath)}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await vX.promises.writeFile(X8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=X8(J);try{if(Q?.recursive)await vX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await vX.promises.unlink(J.fsPath)}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},mkdirp:async(J)=>{await vX.promises.mkdir(X8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=X8(J);try{return(await vX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:S0.file(tl.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(IW(Z))throw new KJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await ol(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>FW(X)?S0.file(X):u0.joinPath(J.base,X))}catch(Z){return a.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=X8(J);wE6(Z);try{await vX.promises.access(Z.fsPath)}catch(X){if(IW(X))throw new KJ(Z);throw X}}}});async function EE6(J,Q){let Z=X8(J).fsPath;if(!Z.startsWith(process.cwd()))return;if(a.debug("ide-fs",{method:"readFile",path:Z}),await jQ.isConnected())try{let X=await jQ.sendRequest("readFile",{path:Z});if(X?.content)return Q(X.content);throw Error(`Failed to readFile via IDE ${Z}: ${X?.message??"unknown cause"}`)}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;a.warn("IDE readFile failed, falling back to Node.js filesystem",{path:Z,error:X});return}else return}async function $E6(J,Q){let Z=X8(J).fsPath;if(!Z.startsWith(process.cwd()))return!1;if(a.debug("ide-fs",{method:"writeFile",path:Z}),await jQ.isConnected())try{let X=await jQ.sendRequest("editFile",{path:X8(J).fsPath,fullContent:Q});if(!X?.success)throw Error(`Failed to writeFile via IDE ${Z}: ${X?.message??"unknown cause"}`);return!0}catch(X){if(process.env.IDE_FS_NO_FALLBACK)throw X;return a.warn("IDE writeFile failed, falling back to Node.js filesystem",{path:Z,error:X}),!1}else return!1}var E10;var $10=p(()=>{Y8();n0();D0();XR();uN();E10={readFile:async(J,Q)=>{return await EE6(J,(Z)=>Z)??await R8.readFile(J,Q).finally(()=>{a.debug("ide-fs",{fallback:"readFile"})})},readBinaryFile:async(J,Q)=>{return a.debug("ide-fs",{fallback:"readBinaryFile"}),R8.readBinaryFile(J,Q)},getMtime:async(J,Q)=>{return R8.getMtime(J,Q)},stat:async(J,Q)=>{return R8.stat(J,Q)},realpath:async(J,Q)=>{return R8.realpath(J,Q)},rename:async(J,Q)=>{return R8.rename(J,Q)},writeFile:async(J,Q,Z)=>{if(await $E6(J,Q))return;return await R8.writeFile(J,Q,Z).finally(()=>{a.debug("ide-fs",{fallback:"writeFile"})})},delete:async(J,Q)=>{return R8.delete(J,Q)},mkdirp:async(J)=>{return R8.mkdirp(J)},readdir:async(J,Q)=>{return R8.readdir(J,Q)},findFiles:async(J,Q)=>{return R8.findFiles(J,Q)},watch:()=>DY,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return R8.access(J,Q)}}});function mU1(J){return"__isFileSystemWithMountedTrees"in J&&J.__isFileSystemWithMountedTrees===!0}function gU1(J,Q){Q=X8(Q);let Z,X;for(let Y of J.trees){if(!Y.uri)continue;let K=MX(Y.uri);if(u0.hasPrefix(Q,K)){let q=u0.relativePath(K,Q);if(q===null)continue;if(X===void 0||q.length<X.length)X=q,Z=Y}}if(!Z||X===void 0)return null;return{tree:Z,filePath:X}}function TE6(J){return Array.isArray(J)}function CE6(J){let Q;if(J===void 0)Q=void 0;else if(TE6(J))Q=J;else Q=J?.env?.initial?.trees;return Q?.filter((Z)=>Z.uri!==void 0)??PE6}function P10(J,Q){for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Q,Y))return{isImplied:!1,childMountPoints:[]}}let Z=[];for(let X of J.trees){if(!X.uri)continue;let Y=MX(X.uri);if(u0.hasPrefix(Y,Q))Z.push(Y)}return{isImplied:Z.length>0,childMountPoints:Z}}function tv(J){return{trees:CE6(J)}}function C10(J){let Q={...J.os,mountedTree:T10},Z=new Map;function X(q){if(!q.fs||q.fs==="os")return Q;if(!q.uri)throw Error("Tree URI is required");if(!q.repository)throw Error(`Tree with FS type ${q.fs} requires repository field`);let G={uri:q.uri,repository:q.repository,fs:q.fs},z=`${q.fs}:${JSON.stringify(q)}`,U=Z.get(z);if(!U){let W=J[q.fs];if(!W)throw Error(`No file system implementation found for: ${q.fs}`);U={...W(G),mountedTree:G},Z.set(z,U)}return U}function Y(q){return q.trees.some((G)=>G.fs&&G.fs!=="os")}function K(q,G){let z=q.trees.map((W)=>({mountPoint:W.uri,fs:X(W)}));function U(W){if(!Y(q))return G?{...G(Q),mountedTree:Q.mountedTree}:Q;let F=gU1(q,W)?.tree;if(!F)throw new KJ(W);let H=z.find((D)=>u0.equalURIs(D.mountPoint,F.uri))?.fs;if(!H)throw Error(`No file system found for URI: ${W}`);return G?{...G(H),mountedTree:H.mountedTree}:H}return{map(W){if(G)throw Error("Cannot use both prepare and prepare2");return K(q,W)},mapReader(W){if(G)throw Error("Cannot use both prepare and prepare2");let F=K(q,W);return{...w10(F),mountedFileSystemForURI:F.mountedFileSystemForURI,map:()=>{throw Error("not implemented")},mapReader:F.mapReader,__isFileSystemWithMountedTrees:F.__isFileSystemWithMountedTrees,__isImmutableBaseFileSystem:F.__isImmutableBaseFileSystem}},mountedFileSystemForURI(W){return U(W)},readFile:async(W,F)=>U(W).readFile(W,F),readBinaryFile:async(W,F)=>U(W).readBinaryFile(W,F),getMtime:async(W,F)=>U(W).getMtime(W,F),realpath:async(W,F)=>U(W).realpath(W,F),access:async(W,F)=>U(W).access(W,F),findFiles:async(W,F)=>U(W.base).findFiles(W,F),stat:async(W,F)=>{let H=X8(W),{isImplied:D}=P10(q,H);if(D)return{size:0,isDirectory:!0};return U(W).stat(W,F)},rename:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`rename(${W}) is not supported by this file system`);return H.rename(W,F)},writeFile:async(W,F,H)=>{let D=U(W);if(Jq(D))throw Error(`writeFile(${W}) is not supported by this file system`);return D.writeFile(W,F,H)},mkdirp:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`mkdirp(${W}) is not supported by this file system`);return H.mkdirp(W,F)},delete:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`delete(${W}) is not supported by this file system`);return H.delete(W,F)},readdir:async(W,F)=>{W=X8(W);let{isImplied:H,childMountPoints:D}=P10(q,W);if(H){let V=new Set;for(let N of D){let L=u0.relativePath(W,N);if(L){let A=L.split("/")[0];if(A)V.add(A)}}return Array.from(V).map((N)=>({uri:u0.joinPath(W,N),isDirectory:!0}))}return U(W).readdir(W,F)},watch:(W,F)=>{if(!Y(q))return Q.watch(W,F);if(!S0.isUri(W))throw Error("Watch with glob is not yet implemented in the file system router");let H=U(W);if(Jq(H))return DY;return H.watch(W,F)},isExclusiveWriterFor:async(W,F)=>{let H=U(W);if(Jq(H))throw Error(`isExclusiveWriterFor(${W}) is not supported by this file system`);return H.isExclusiveWriterFor(W,F)},__isImmutableBaseFileSystem:!1,__isFileSystemWithMountedTrees:!0}}return{fileSystemWithMountedTrees:K,fileSystemForURI:(q,G)=>X(gU1(q,G)?.tree??T10),osFileSystem:Q}}function SB(J){if(!Object.values(J).some((Q)=>!!Q))return null;return(Q,Z)=>{if(!Z.dir)throw Error("No directory provided");let X=gU1(tv(Z.thread),Z.dir)?.tree.fs??"os",Y=J[X];if(Y)return lH(Y()).pipe(S9((K)=>K(Q,Z)));throw Error(`Unsupported file system: ${X}`)}}var PE6,T10;var EW=p(()=>{Y8();n0();hJ();PE6=[];T10={fs:"os",uri:"file:///"}});function SE6(){return new Proxy({},{get:(J,Q)=>{return async(...Z)=>{let X=Z.at(1),Y=Z.at(0),K=await LZ("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:JSON.stringify({method:Q,params:Y}),signal:X?.signal});if(!K.ok)throw Error(`API request failed: ${K.status}`);return await K.json()}}})}var NZ;var pN=p(()=>{vB();NZ=SE6()});function vE6(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 ev(J,Q){return new URL(`/threads/${Q}`,J)}async function LZ(J,Q){let Z=await O9(Q?.signal??void 0);return kE6(Z,J,Q)}async function v10(J,Q){let Z=await J.get(Q);if(!Z)throw Error(`Thread not found: ${Q}`);let X=await NZ.shareThreadWithOperator({threadData:Z});if(!X.ok)throw Error(`Failed to share thread: ${X.error.message}`)}async function k10(J){let Q=await LZ("/api/telemetry",{method:"POST",headers:{"Content-Type":"application/json"},body:J});if(!Q.ok){let Z=await Q.text(),X;try{X=JSON.parse(Z).error||`HTTP ${Q.status}`}catch{X=Z||`HTTP ${Q.status}`}throw Error(`Failed to submit telemetry: ${X}`)}}async function kE6(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 X=J.settings.url;if(!X)throw Error("amp.url is not set");let Y=await J.secrets.getToken("apiKey",X);if(!Y||Y.trim()===""){let K=Error("Amp API key is not set");throw K.name="MissingApiKeyError",K}return vE6({proxy:J.settings.proxy}),fetch(new URL(Q,X),{...Z,headers:{...Z?.headers,...pG(),"Content-Type":"application/json",Authorization:`Bearer ${Y}`}})}var S10;var vB=p(()=>{n0();D4();sU();pN();S10=Z2.pipe(S9(({settings:J,secrets:Q})=>{return p8(async()=>{return await Q.getToken("apiKey",J.url)!==void 0})}))});class uR{heap;length;static#J=!1;static create(J){let Q=y10(J);if(!Q)return[];uR.#J=!0;let Z=new uR(J,Q);return uR.#J=!1,Z}constructor(J,Q){if(!uR.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}var mR,b10,uU1,x10=(J,Q,Z,X)=>{typeof uU1.emitWarning==="function"?uU1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},el,_10,_E6=(J)=>!b10.has(J),TA9,kB=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),y10=(J)=>!kB(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?Jk:null,Jk,Ji;var f10=p(()=>{mR=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,b10=new Set,uU1=typeof process==="object"&&!!process?process:{},el=globalThis.AbortController,_10=globalThis.AbortSignal;if(typeof el>"u"){_10=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},el=class{constructor(){Q()}signal=new _10;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=uU1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,x10("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}TA9=Symbol("type");Jk=class Jk extends Array{constructor(J){super(J);this.fill(0)}};Ji=class Ji{#J;#Z;#Y;#X;#G;#$;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#q;#Q;#B;#M;#H;#W;#A;#F;#O;#j;#V;#R;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#j,ttls:J.#V,sizes:J.#O,keyMap:J.#z,keyList:J.#q,valList:J.#Q,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#w(Q),rindexes:(Q)=>J.#I(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Z}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#$}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#G}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:q,allowStale:G,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:F,noUpdateTTL:H,maxSize:D=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:O,allowStaleOnFetchRejection:j,allowStaleOnFetchAbort:R,ignoreFetchAbort:I}=J;if(Q!==0&&!kB(Q))throw TypeError("max option must be a nonnegative integer");let w=Q?y10(Q):Array;if(!w)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Z=D,this.maxEntrySize=M||this.#Z,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Z&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#$=N,this.#C=!!N,this.#z=new Map,this.#q=Array(Q).fill(void 0),this.#Q=Array(Q).fill(void 0),this.#B=new w(Q),this.#M=new w(Q),this.#H=0,this.#W=0,this.#A=uR.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#G=W,this.#F=[];else this.#G=void 0,this.#F=void 0;if(this.#R=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#G,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!j,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(this.#Z!==0){if(!kB(this.#Z))throw TypeError("maxSize must be a positive integer if specified")}if(!kB(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!G,this.noDeleteOnStaleGet=!!O,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!q,this.ttlResolution=kB(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!kB(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Z===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Z){if(_E6("LRU_CACHE_UNBOUNDED"))b10.add("LRU_CACHE_UNBOUNDED"),x10("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",Ji)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new Jk(this.#J),Q=new Jk(this.#J);this.#V=J,this.#j=Q,this.#h=(Y,K,q=mR.now())=>{if(Q[Y]=K!==0?q:0,J[Y]=K,K!==0&&this.ttlAutopurge){let G=setTimeout(()=>{if(this.#N(Y))this.#E(this.#q[Y],"expire")},K+1);if(G.unref)G.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?mR.now():0},this.#P=(Y,K)=>{if(J[K]){let q=J[K],G=Q[K];if(!q||!G)return;Y.ttl=q,Y.start=G,Y.now=Z||X();let z=Y.now-G;Y.remainingTTL=q-z}};let Z=0,X=()=>{let Y=mR.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let q=J[K],G=Q[K];if(!q||!G)return 1/0;let z=(Z||X())-G;return q-z},this.#N=(Y)=>{let K=Q[Y],q=J[Y];return!!q&&!!K&&(Z||X())-K>q}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new Jk(this.#J);this.#L=0,this.#O=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!kB(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!kB(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#b=(Q,Z,X)=>{if(J[Q]=Z,this.#Z){let Y=this.#Z-J[Q];while(this.#L>Y)this.#x(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#b=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#w({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#I({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#H;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#q[J])===J}*entries(){for(let J of this.#w())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*rentries(){for(let J of this.#I())if(this.#Q[J]!==void 0&&this.#q[J]!==void 0&&!this.#K(this.#Q[J]))yield[this.#q[J],this.#Q[J]]}*keys(){for(let J of this.#w()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*rkeys(){for(let J of this.#I()){let Q=this.#q[J];if(Q!==void 0&&!this.#K(this.#Q[J]))yield Q}}*values(){for(let J of this.#w())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}*rvalues(){for(let J of this.#I())if(this.#Q[J]!==void 0&&!this.#K(this.#Q[J]))yield this.#Q[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#w()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#q[Z],this))return this.get(this.#q[Z],Q)}}forEach(J,Q=this){for(let Z of this.#w()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}rforEach(J,Q=this){for(let Z of this.#I()){let X=this.#Q[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#q[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#I({allowStale:!0}))if(this.#N(Q))this.#E(this.#q[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Q[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#j){let K=this.#V[Q],q=this.#j[Q];if(K&&q){let G=K-(mR.now()-q);Y.ttl=G,Y.start=Date.now()}}if(this.#O)Y.size=this.#O[Q];return Y}dump(){let J=[];for(let Q of this.#w({allowStale:!0})){let Z=this.#q[Q],X=this.#Q[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#j){K.ttl=this.#V[Q];let q=mR.now()-this.#j[Q];K.start=Math.floor(Date.now()-q)}if(this.#O)K.size=this.#O[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=mR.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:q=this.sizeCalculation,status:G}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,q);if(this.maxEntrySize&&U>this.maxEntrySize){if(G)G.set="miss",G.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#x(!1):this.#U,this.#q[W]=J,this.#Q[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#b(W,U,G),G)G.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let F=this.#Q[W];if(Q!==F){if(this.#C&&this.#K(F)){F.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!K){if(this.#R)this.#Y?.(H,J,"set");if(this.#D)this.#F?.push([H,J,"set"])}}else if(!K){if(this.#R)this.#Y?.(F,J,"set");if(this.#D)this.#F?.push([F,J,"set"])}if(this.#v(W),this.#b(W,U,G),this.#Q[W]=Q,G){G.set="replace";let H=F&&this.#K(F)?F.__staleWhileFetching:F;if(H!==void 0)G.oldValue=H}}else if(G)G.set="update";if(this.#_)this.onInsert?.(Q,J,Q===F?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(G)this.#P(G,W)}if(!K&&this.#D&&this.#F){let F=this.#F,H;while(H=F?.shift())this.#G?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Q[this.#H];if(this.#x(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#F){let J=this.#F,Q;while(Q=J?.shift())this.#G?.(...Q)}}}#x(J){let Q=this.#H,Z=this.#q[Q],X=this.#Q[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#R||this.#D){if(this.#R)this.#Y?.(X,Z,"evict");if(this.#D)this.#F?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#q[Q]=void 0,this.#Q[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#H=this.#W=0,this.#A.length=0;else this.#H=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Q[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Q[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Q[Q];if(this.#K(Y))return Y;let K=new el,{signal:q}=Z;q?.addEventListener("abort",()=>K.abort(q.reason),{signal:K.signal});let G={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=H;if(this.#Q[Q]===H)if(M===void 0)if(A.__staleWhileFetching)this.#Q[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,G.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,O=H;if(this.#Q[Q]===H){if(!A||O.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Q[Q]=O.__staleWhileFetching}if(L){if(Z.status&&O.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return O.__staleWhileFetching}else if(O.__returned===O)throw M},F=(M,V)=>{let N=this.#$?.(J,Y,G);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let H=new Promise(F).then(z,U),D=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,D,{...G.options,status:void 0}),Q=this.#z.get(J);else this.#Q[Q]=D;return D}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof el}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:q=this.noDisposeOnSet,size:G=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:D=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:q,size:G,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:D,ignoreFetchAbort:H,status:N,signal:L},O=this.#z.get(J);if(O===void 0){if(N)N.fetch="miss";let j=this.#y(J,O,A,M);return j.__returned=j}else{let j=this.#Q[O];if(this.#K(j)){let $=Z&&j.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",$)N.returnedStale=!0}return $?j.__staleWhileFetching:j.__returned=j}let R=this.#N(O);if(!V&&!R){if(N)N.fetch="hit";if(this.#k(O),X)this.#S(O);if(N)this.#P(N,O);return j}let I=this.#y(J,O,A,M),E=I.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=R?"stale":"refresh",E&&R)N.returnedStale=!0}return E?I.__staleWhileFetching:I.__returned=I}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,q=this.get(J,K);if(!Y&&q!==void 0)return q;let G=Z(J,q,{options:K,context:X});return this.set(J,G,K),G}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,q=this.#z.get(J);if(q!==void 0){let G=this.#Q[q],z=this.#K(G);if(K)this.#P(K,q);if(this.#N(q)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?G:void 0}else{if(K&&Z&&G.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?G.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return G.__staleWhileFetching;if(this.#k(q),X)this.#S(q);return G}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Q[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#R||this.#D){if(this.#R)this.#Y?.(Y,J,Q);if(this.#D)this.#F?.push([Y,J,Q])}if(this.#z.delete(J),this.#q[X]=void 0,this.#Q[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#H)this.#H=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let q=this.#B[X];this.#M[q]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#F?.length){let X=this.#F,Y;while(Y=X?.shift())this.#G?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#I({allowStale:!0})){let Z=this.#Q[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#q[Q];if(this.#R)this.#Y?.(Z,X,J);if(this.#D)this.#F?.push([Z,X,J])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#q.fill(void 0),this.#V&&this.#j)this.#V.fill(0),this.#j.fill(0);if(this.#O)this.#O.fill(0);if(this.#H=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#F){let Q=this.#F,Z;while(Z=Q?.shift())this.#G?.(...Z)}}}});function pU1(J,Q,Z){let X=new b8,K=(()=>{let D=new Map;return(M,V)=>{let L=(D.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(D.get(M)===L)D.delete(M)});return D.set(M,L),L}})(),q=Z?u0.joinPath(Q,Z):Q;function G(D){return u0.joinPath(q,`${D.toString()}.json`)}async function z(D){let M=G(D);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);a.warn(`File too large to load safely: ${String(D)} (${L}MB)`,{key:String(D),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:O,contentPreview:j}=bE6(V);a.warn("Corrupted JSON detected.",{key:String(D),storageUri:q.toString(),error:A.message,contentLength:O,contentPreview:j});return}}catch(V){if(RQ(V))return;throw V}}async function U(D,M){let V=G(D),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(u0.joinPath(V,"..")),await K(D,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(D)}async function W(D){let M=G(D);await K(D,async()=>{await J.delete(M)}),X.next(D)}async function F(){let D;try{D=await J.readdir(q)}catch(M){if(RQ(M))return[];throw M}return D.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function H(D){return G(D).fsPath}return{get:z,set:U,delete:W,keys:F,path:H,changes:X}}function bE6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}var h10=p(()=>{Y8();n0();D0();hJ()});var cE6={};import _B from"node:path";import{parentPort as dU1,workerData as xE6}from"node:worker_threads";function fE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}async function hE6(J,Q,Z,X,Y){try{await R8.mkdirp(Z),await u10(Z)}catch(K){throw a.error("Cannot create migration directory, aborting migration:",K),K}if(await ov(R8,Y)){a.debug("Migration already completed by another process");return}try{await m10(X),a.info("Starting thread migration")}catch(K){if(pE6(K))if(await dE6(X))a.info("Removing stale migration lock and retrying"),await R8.delete(X),await m10(X),a.info("Starting thread migration (after stale lock cleanup)");else{a.debug("Another process is running migration");return}else throw a.error("Failed to acquire migration lock:",K),K}try{await gE6(J,Q),await(await import("node:fs/promises")).rename(X.fsPath,Y.fsPath),a.info("Thread migration completed")}catch(K){try{await R8.delete(X)}catch{}throw K}}async function gE6(J,Q){await R8.mkdirp(Q),await u10(Q);try{let X=(await R8.readdir(J)).filter((K)=>_B.basename(K.uri.path).endsWith(".json"));a.info(`Migrating ${X.length} threads to centralized storage`);let Y=0;for(let K=0;K<X.length;K+=g10){let q=X.slice(K,K+g10);await Promise.all(q.map(async(G)=>{let z=_B.basename(G.uri.path),U=G.uri,W=S0.file(_B.join(Q.path,z));if(await ov(R8,W))return;await mE6(U,W),Y++}))}a.info(`Migration completed: ${Y} threads migrated`)}catch(Z){a.debug("No legacy threads to migrate:",Z)}}async function mE6(J,Q){let Z=await import("node:fs/promises");try{await Z.rename(J.fsPath,Q.fsPath)}catch(X){if(X.code==="EXDEV")await uE6(J,Q),await R8.delete(J);else throw X}}async function uE6(J,Q){let Z=await R8.readFile(J);await R8.writeFile(Q,Z);try{let X=await import("node:fs/promises"),Y=await X.stat(J.fsPath);await X.utimes(Q.fsPath,Y.atime,Y.mtime)}catch(X){a.debug(`Could not preserve timestamp for ${_B.basename(Q.path)}:`,X)}}async function m10(J){let Q=await import("node:fs/promises");try{let Z=JSON.stringify({pid:process.pid,startTime:Date.now()});await Q.writeFile(J.fsPath,Z,{flag:"wx"})}catch(Z){if(Z.code==="EEXIST"){let X=Error(`File already exists: ${J.toString()}`);throw X.code="EEXIST",X}throw Z}}function pE6(J){return J instanceof Error&&(("code"in J)&&J.code==="EEXIST"||J.message.includes("already exists"))}async function u10(J){try{await(await import("node:fs/promises")).chmod(J.fsPath,448)}catch(Q){a.debug("Could not set secure permissions:",Q)}}async function dE6(J){try{let Q=await R8.readFile(J),Z=JSON.parse(Q),X=Date.now()-Z.startTime;if(X>yE6)return a.debug(`Migration lock is stale (${Math.round(X/1000/60)}min old)`),!0;return!1}catch(Q){return a.debug("Could not read migration lock file, considering stale:",Q),!0}}var g10=25,yE6=300000;var p10=p(()=>{Y8();D0();hJ();uN();if(dU1){let{legacyDir:J,centralizedDir:Q,isDevelopment:Z}=xE6,X=S0.parse(J),Y=S0.parse(Q),K=S0.file(_B.join(Y.path,"..","migration")),q=fE6(Z),G=S0.file(_B.join(K.path,q.progress)),z=S0.file(_B.join(K.path,q.done));hE6(X,Y,K,G,z).then(async()=>{try{let W=(await R8.readdir(Y)).filter((F)=>_B.basename(F.uri.path).endsWith(".json")).length;dU1?.postMessage({migratedCount:W})}catch{dU1?.postMessage({migratedCount:0})}}).catch((U)=>{throw U})}});import{homedir as lE6}from"node:os";import bB from"node:path";import{Worker as iE6}from"node:worker_threads";async function d10(J){let Q=J.isDevelopment||!1,Z=aE6(),X=Q?"threads-development":"threads",Y=pU1(R8,Z,X),K=new c10(Y);if(!J.vscodeMigrationContext)return a.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:q,vscodeContext:G}=J.vscodeMigrationContext,z=S0.file(bB.join(Z.path,X)),U=Q?"threads3-development":"threads3",W=S0.file(bB.join(G.globalStorageUri.path,U));if(await rE6(z,Q,W))return a.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{a.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:G.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),sE6(W,z,Q);let H=pU1(q,G.globalStorageUri,U);return nE6(K,H)}}class c10{delegate;cache=new Ji({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){await this.delegate.set(J,Q),this.cache.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function nE6(J,Q){return{async get(Z){let X=await J.get(Z);if(X!==void 0)return X;return Q.get(Z)},async set(Z,X){await J.set(Z,X)},async delete(Z){await J.delete(Z).catch(()=>{}),await Q.delete(Z).catch(()=>{})},async keys(){let[Z,X]=await Promise.all([J.keys(),Q.keys()]);return[...new Set([...Z,...X])]},async path(Z){let X=await J.path(Z);if(X)return X;return Q.path(Z)},get changes(){return J.changes}}}function aE6(){let J=process.env.XDG_DATA_HOME||bB.join(lE6(),".local","share"),Q=bB.resolve(J,"amp");return S0.file(Q)}async function rE6(J,Q,Z){let X=S0.file(bB.join(J.path,"..","migration")),Y=oE6(Q),K=S0.file(bB.join(X.path,Y.done));if(await ov(R8,K))return!0;if(Z)try{if((await R8.readdir(Z)).filter((z)=>bB.basename(z.uri.path).endsWith(".json")).length===0){if((await R8.readdir(J)).filter((W)=>bB.basename(W.uri.path).endsWith(".json")).length>0){a.info("Detected completed migration without marker, creating completion marker");try{await R8.mkdirp(X),await R8.writeFile(K,"completed")}catch(W){a.debug("Could not create migration completion marker:",W)}return!0}}}catch(q){a.debug("Could not check legacy directory for completion detection:",q)}return!1}function sE6(J,Q,Z){try{let X=new iE6(o1.resolve("/home/runner/work/amp/amp/core/src/storage/migration-worker.node.ts"),{workerData:{legacyDir:J.toString(),centralizedDir:Q.toString(),isDevelopment:Z}});X.on("message",(Y)=>{a.info("Background migration completed:",Y)}),X.on("error",(Y)=>{a.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)a.warn(`Migration worker exited with code ${Y}`)})}catch(X){let Y=X instanceof Error?X.message:String(X);if(Y.includes("Worker is not supported")||Y.includes("Cannot resolve module")||Y.includes("ENOENT")&&Y.includes("migration-worker"))a.debug("Migration worker could not be started (expected in tests):",X);else a.warn("Migration worker failed to start, migration will be skipped:",X)}}function oE6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}var l10=p(()=>{Y8();f10();D0();hJ();uN();h10()});async function pR(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=tE6(J,q),z=G<0,U,W;if(K.time){let F=K.time[J],H=K.time[q],D=Date.now();if(F)U=Math.floor((D-new Date(F).getTime())/3600000);if(H)W=Math.floor((D-new Date(H).getTime())/3600000)}return a.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return a.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function tE6(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}var Qi=p(()=>{D0()});import{execFile as eE6}from"node:child_process";import{promises as xB}from"node:fs";import{homedir as cU1}from"node:os";import{join as Qq}from"node:path";import{promisify as J$6}from"node:util";class lU1{async collect(){let[J,Q,Z,X,Y]=await Promise.all([this.collectInstallationInfo(),this.collectEnvironmentInfo(),this.collectConfigInfo(),this.collectCliTestInfo(),this.collectLogsInfo()]);return{cliTest:X,config:Z,environment:Q,installation:J,logs:Y}}async collectInstallationInfo(){let J={installMethod:"unknown",packageManager:"unknown"};try{if(J.version=await this.getCliVersion(),J.version)J.versionAge=await this.getCliAge(J.version)}catch{}try{J.installMethod=await this.detectInstallMethod()}catch{}try{J.packageManager=await this.detectPackageManager()}catch{}try{J.executablePath=process.execPath}catch{}return J}async collectEnvironmentInfo(){let J={};for(let[Q,Z]of Object.entries(process.env))if(Q.startsWith("AMP_")&&Z!==void 0)J[Q]=Z;return{variables:J}}async collectConfigInfo(){let J={};try{let Q=this.getSettingsPath(),Z=await xB.readFile(Q,"utf8");J.settings=JSON.parse(Z)}catch(Q){J.configError=Q instanceof Error?Q.message:String(Q)}try{let Q=this.getSecretsPath(),Z=await xB.readFile(Q,"utf8");J.secrets=JSON.parse(Z)}catch(Q){J.secretsError=Q instanceof Error?Q.message:String(Q)}return J}async collectCliTestInfo(){let J=new Date().toISOString();try{await dR("which",["amp"],{timeout:5000})}catch{return{additionalTests:[],executedAt:J,initialTest:{command:`echo "what is today's date" | amp`,error:"amp command not found in PATH",exitCode:127,stderr:"",stdout:""}}}let Q=await this.runCliCommand(`echo "what is today's date" | amp`),Z=[];if(Q.exitCode===0){let X=["amp threads list","amp tools show"];for(let Y of X){let K=await this.runCliCommand(Y);Z.push(K)}}return{additionalTests:Z,executedAt:J,initialTest:Q}}async runCliCommand(J){let Q={command:J,exitCode:-1,stderr:"",stdout:""};try{let{spawn:Z}=await import("node:child_process");return new Promise((X)=>{let Y=Z("sh",["-c",J],{stdio:["pipe","pipe","pipe"],timeout:30000}),K="",q="";Y.stdout?.on("data",(G)=>{K+=G.toString()}),Y.stderr?.on("data",(G)=>{q+=G.toString()}),Y.on("close",(G)=>{Q.stdout=K,Q.stderr=q,Q.exitCode=G??-1,X(Q)}),Y.on("error",(G)=>{Q.error=G.message,Q.exitCode=-1,X(Q)}),setTimeout(()=>{Y.kill("SIGTERM"),Q.error="Command timed out after 30 seconds",Q.exitCode=-1,X(Q)},30000)})}catch(Z){return Q.error=Z instanceof Error?Z.message:String(Z),Q.exitCode=-1,Q}}async collectLogsInfo(){let J={recentLogs:[]};try{let Q=this.getLogPath(),X=(await xB.readFile(Q,"utf8")).split(`
140
140
  `).filter((Y)=>Y.trim());J.recentLogs=X.slice(-1000)}catch(Q){J.logError=Q instanceof Error?Q.message:String(Q)}return J}async getCliVersion(){try{let{stdout:J}=await dR("npm",["list","-g","@sourcegraph/amp","--depth=0","--json"],{timeout:5000}),Z=JSON.parse(J).dependencies?.["@sourcegraph/amp"];if(Z?.version)return Z.version}catch{}try{let J=Qq(process.cwd(),"node_modules","@sourcegraph","amp","package.json"),Q=await xB.readFile(J,"utf8"),Z=JSON.parse(Q);if(Z.version)return Z.version}catch{}try{let{stdout:J}=await dR("pnpm",["list","-g","@sourcegraph/amp","--depth=0","--json"],{timeout:5000}),Q=JSON.parse(J),Z=Array.isArray(Q)?Q:[Q];for(let X of Z){let Y=X.dependencies?.["@sourcegraph/amp"];if(Y?.version)return Y.version}}catch{}try{let{stdout:J}=await dR("yarn",["global","list","--pattern","@sourcegraph/amp","--json"],{timeout:5000}),Q=J.split(`
141
141
  `).filter((Z)=>Z.trim());for(let Z of Q)try{let X=JSON.parse(Z);if(X.type==="info"&&X.data&&typeof X.data==="string"){let Y=X.data.match(/"@sourcegraph\/amp@(.+?)"/);if(Y?.[1])return Y[1]}}catch{}}catch{}try{let{stdout:J}=await dR("amp",["--version"],{timeout:5000}),Q=J.trim().match(/(\d+\.\d+\.\d+[\w\-.]*)/g);if(Q?.[0])return Q[0]}catch{}return}async getCliAge(J){try{let Q=await pR(J);if(Q.currentVersionAge!==void 0)return this.formatAge(Q.currentVersionAge);return}catch{return}}formatAge(J){let Q=Math.floor(J/24),Z=J%24;if(J<24)return`${J} hours`;else if(Z===0)return`${J} hours (${Q} ${Q===1?"day":"days"})`;else return`${J} hours (${Q} ${Q===1?"day":"days"}, ${Z}h)`}async detectInstallMethod(){try{return await dR("npm",["list","-g","@sourcegraph/amp"],{timeout:5000}),"global"}catch{}try{let J=Qq(process.cwd(),"node_modules","@sourcegraph","amp");return await xB.access(J),"local"}catch{}if(process.argv[0]?.includes("npx")||process.env.npm_execpath?.includes("npx"))return"npx";return"unknown"}async detectPackageManager(){try{return await xB.access(Qq(process.cwd(),"pnpm-lock.yaml")),"pnpm"}catch{}try{return await xB.access(Qq(process.cwd(),"yarn.lock")),"yarn"}catch{}try{return await xB.access(Qq(process.cwd(),"package-lock.json")),"npm"}catch{}return"unknown"}getSettingsPath(){let J=process.env.XDG_CONFIG_HOME||Qq(cU1(),".config");return Qq(J,"amp","settings.json")}getSecretsPath(){let J=process.env.XDG_DATA_HOME||Qq(cU1(),".local","share");return Qq(J,"amp","secrets.json")}getLogPath(){let J=process.env.XDG_CACHE_HOME||Qq(cU1(),".cache");return Qq(J,"amp","logs","cli.log")}}var dR;var i10=p(()=>{Qi();dR=J$6(eE6)});import{lookup as Q$6}from"node:dns";import{promisify as Z$6}from"node:util";class iU1{testUrls=["https://ampcode.com","https://sourcegraph.com","https://ampcodestatus.com"];testDomains=["ampcode.com","sourcegraph.com","ampcodestatus.com","github.com"];async collect(){let[J,Q]=await Promise.all([this.runConnectivityTests(),this.runDnsTests()]);return{connectivity:J,dns:Q,proxy:this.detectProxy(),timestamp:new Date().toISOString()}}async runConnectivityTests(){return(await Promise.allSettled(this.testUrls.map((Q)=>this.testConnectivity(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{error:Q.reason instanceof Error?Q.reason.message:String(Q.reason),responseTime:0,success:!1,url:this.testUrls[Z]}})}async runDnsTests(){return(await Promise.allSettled(this.testDomains.map((Q)=>this.testDnsResolution(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{domain:this.testDomains[Z],error:Q.reason instanceof Error?Q.reason.message:String(Q.reason),responseTime:0,success:!1}})}async testConnectivity(J){let Q=Date.now();try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),1e4),Y=await fetch(J,{method:"HEAD",signal:Z.signal});clearTimeout(X);let K=Date.now()-Q,q={};return Y.headers.forEach((G,z)=>{q[z]=G}),{headers:q,responseTime:K,status:Y.status,statusText:Y.statusText,success:Y.ok,url:J}}catch(Z){let X=Date.now()-Q;return{error:Z instanceof Error?Z.message:String(Z),responseTime:X,success:!1,url:J}}}async testDnsResolution(J){let Q=Date.now();try{let Z=await X$6(J,{all:!0}),X=Date.now()-Q;return{addresses:Z.map((Y)=>Y.address),domain:J,responseTime:X,success:!0}}catch(Z){let X=Date.now()-Q;return{domain:J,error:Z instanceof Error?Z.message:String(Z),responseTime:X,success:!1}}}detectProxy(){let J={detected:!1},Q=process.env.HTTP_PROXY||process.env.http_proxy,Z=process.env.HTTPS_PROXY||process.env.https_proxy,X=process.env.NO_PROXY||process.env.no_proxy,Y=process.env.NODE_EXTRA_CA_CERTS;if(Q||Z||Y)J.detected=!0,J.httpProxy=Q,J.httpsProxy=Z,J.nodeExtraCaCerts=Y,J.noProxy=X;return J}}var X$6;var n10=p(()=>{X$6=Z$6(Q$6)});import{execFile as Y$6}from"node:child_process";import{promises as Zi}from"node:fs";import{platform as a10}from"node:os";import{promisify as K$6}from"node:util";class aU1{testUrls=["https://ampcode.com","https://sourcegraph.com"];async collect(){let[J,Q]=await Promise.all([this.collectTrustedCertificates(),this.testCertificateChains()]);return{trustedCertificates:J,certificateTests:Q,platform:a10(),timestamp:new Date().toISOString()}}async collectTrustedCertificates(){let J={count:0,sources:[],sampleCertificates:[]};try{let Q=a10();switch(Q){case"darwin":await this.collectMacOSCertificates(J);break;case"win32":await this.collectWindowsCertificates(J);break;case"linux":await this.collectLinuxCertificates(J);break;default:J.error=`Unsupported platform: ${Q}`}}catch(Q){J.error=Q instanceof Error?Q.message:String(Q)}return J}async testCertificateChains(){return(await Promise.allSettled(this.testUrls.map((Q)=>this.testCertificateChain(Q)))).map((Q,Z)=>{if(Q.status==="fulfilled")return Q.value;else return{url:this.testUrls[Z],success:!1,error:Q.reason instanceof Error?Q.reason.message:String(Q.reason)}})}async collectMacOSCertificates(J){try{let{stdout:Q}=await nU1("security",["find-certificate","-a","-p","/System/Library/Keychains/SystemRootCertificates.keychain"],{timeout:1e4}),Z=this.parsePEMCertificates(Q);J.count=Z.length,J.sources.push("/System/Library/Keychains/SystemRootCertificates.keychain"),J.sampleCertificates=Z.slice(0,3);try{let{stdout:X}=await nU1("security",["find-certificate","-a","-p","login.keychain"],{timeout:5000}),Y=this.parsePEMCertificates(X);if(Y.length>0)J.count+=Y.length,J.sources.push("login.keychain"),J.sampleCertificates.push(...Y.slice(0,2))}catch{}}catch(Q){throw Error(`Failed to collect macOS certificates: ${Q instanceof Error?Q.message:String(Q)}`)}}async collectWindowsCertificates(J){try{let{stdout:Q}=await nU1("powershell",["-Command","Get-ChildItem -Path Cert:\\LocalMachine\\Root | Select-Object Subject, Issuer, SerialNumber, NotBefore, NotAfter, Thumbprint | ConvertTo-Json"],{timeout:1e4}),Z=JSON.parse(Q),X=Array.isArray(Z)?Z:[Z];J.count=X.length,J.sources.push("Cert:\\LocalMachine\\Root"),J.sampleCertificates=X.slice(0,3).map((Y)=>({subject:Y.Subject,issuer:Y.Issuer,serialNumber:Y.SerialNumber,notBefore:Y.NotBefore,notAfter:Y.NotAfter,fingerprint:Y.Thumbprint}))}catch(Q){throw Error(`Failed to collect Windows certificates: ${Q instanceof Error?Q.message:String(Q)}`)}}async collectLinuxCertificates(J){let Q=["/etc/ssl/certs","/usr/local/share/ca-certificates","/etc/pki/tls/certs","/etc/ssl/ca-bundle.pem"],Z=0,X=[],Y=[];for(let K of Q)try{let q=await Zi.stat(K);if(q.isDirectory()){let z=(await Zi.readdir(K)).filter((U)=>U.endsWith(".crt")||U.endsWith(".pem"));if(z.length>0){if(Z+=z.length,X.push(K),Y.length<3)try{let U=await Zi.readFile(`${K}/${z[0]}`,"utf8"),W=this.parsePEMCertificates(U);Y.push(...W.slice(0,1))}catch{}}}else if(q.isFile()){let G=await Zi.readFile(K,"utf8"),z=this.parsePEMCertificates(G);if(z.length>0)Z+=z.length,X.push(K),Y.push(...z.slice(0,2))}}catch{}if(J.count=Z,J.sources=X,J.sampleCertificates=Y.slice(0,3),Z===0)throw Error("No certificate sources found")}async testCertificateChain(J){try{let Q=new URL(J),Z=await import("node:https");return new Promise((X,Y)=>{let K=Z.request({hostname:Q.hostname,port:Q.port||443,method:"HEAD",timeout:1e4},(q)=>{if(process.versions.bun)return X({url:J,success:!1,error:"The binary version of Amp does not support certificate testing"});let G=q.socket,z=G.getPeerCertificate(!0),U=G.getCipher();if(z&&Object.keys(z).length>0){let W=this.extractCertificateChain(z);X({url:J,success:!0,certificates:W,tlsVersion:G.getProtocol(),cipherSuite:U?`${U.name} (${U.version})`:void 0})}else X({url:J,success:!1,error:"No certificate information available"})});K.on("error",(q)=>{X({url:J,success:!1,error:q.message})}),K.on("timeout",()=>{K.destroy(),X({url:J,success:!1,error:"Connection timeout"})}),K.end()})}catch(Q){return{url:J,success:!1,error:Q instanceof Error?Q.message:String(Q)}}}parsePEMCertificates(J){let Q=[],Z=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,X=J.match(Z);if(X)for(let Y of X.slice(0,5))try{let K=Y.split(`
142
142
  `),q={subject:"Unknown",issuer:"Unknown"};for(let G of K){if(G.includes("Subject:"))q.subject=G.split("Subject:")[1]?.trim()||"Unknown";if(G.includes("Issuer:"))q.issuer=G.split("Issuer:")[1]?.trim()||"Unknown"}Q.push(q)}catch{}return Q}extractCertificateChain(J){let Q=[],Z=J;while(Z&&Q.length<10)if(Q.push({subject:Z.subject?.CN||Z.subject?.O||"Unknown",issuer:Z.issuer?.CN||Z.issuer?.O||"Unknown",serialNumber:Z.serialNumber,notBefore:Z.valid_from,notAfter:Z.valid_to,fingerprint:Z.fingerprint}),Z=Z.issuerCertificate,Z===J)break;return Q}}var nU1;var r10=p(()=>{nU1=K$6(Y$6)});function s10(J){if(!J._regex)try{J._regex=new RegExp(J.pattern,J.caseInsensitive?"gi":"g")}catch(Q){a.warn("Error compiling regex",{pattern:J.id,error:Q}),J._regex=new RegExp("$^")}return J._regex}var o10;var t10=p(()=>{D0();o10=[{id:"sourcegraph-access-token-v3",category:"sourcegraph",title:"Sourcegraph Access Token (v3)",pattern:String.raw`(sgp_(?:[a-fA-F0-9]{16}|local)_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-access-token-v2",category:"sourcegraph",title:"Sourcegraph Access Token (v2, deprecated)",pattern:String.raw`(sgp_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-dotcom-user-gateway",category:"sourcegraph",title:"Sourcegraph Dotcom User Gateway Access Token",pattern:String.raw`(sgd_[a-fA-F0-9]{64})`,keywords:["sgd_"]},{id:"sourcegraph-license-key",category:"sourcegraph",title:"Sourcegraph License Key Token",pattern:String.raw`(slk_[a-fA-F0-9]{64})`,keywords:["slk_"]},{id:"sourcegraph-enterprise-subscription",category:"sourcegraph",title:"Sourcegraph Enterprise subscription Token",pattern:String.raw`(sgs_[a-fA-F0-9]{64})`,keywords:["sgs_"]},{id:"sourcegraph-amp",category:"sourcegraph",title:"Sourcegraph Amp Access Token",pattern:String.raw`(sgamp_user_[A-Z0-9]{26}_[a-f0-9]{64})`,keywords:["sgamp_user_"]},{id:"sourcegraph-amp-auth-bypass",category:"sourcegraph",title:"Sourcegraph Amp Auth Bypass Token",pattern:String.raw`(sgamp_user_auth-bypass_[a-zA-Z0-9_-]+)`,keywords:["sgamp_user_auth-bypass_"]},{id:"sourcegraph-workspace-token",category:"sourcegraph",title:"Sourcegraph Workspace Access Token",pattern:String.raw`(sgp_ws[a-fA-F0-9]{32}_[a-fA-F0-9]{40})`,keywords:["sgp_ws"]},{id:"github-pat",category:"github",title:"GitHub Personal Access Token",pattern:String.raw`(ghp_[0-9a-zA-Z]{36})`,keywords:["ghp_"]},{id:"github-oauth",category:"github",title:"GitHub OAuth Access Token",pattern:String.raw`(gho_[0-9a-zA-Z]{36})`,keywords:["gho_"]},{id:"github-app-token",category:"github",title:"GitHub App Token",pattern:String.raw`((ghu|ghs)_[0-9a-zA-Z]{36})`,keywords:["ghu_","ghs_"]},{id:"github-refresh-token",category:"github",title:"GitHub Refresh Token",pattern:String.raw`(ghr_[0-9a-zA-Z]{76})`,keywords:["ghr_"]},{id:"github-fine-grained-pat",category:"github",title:"GitHub Fine-grained personal access tokens",pattern:String.raw`(github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})`,keywords:["github_pat_"]},{id:"gitlab-pat",category:"gitlab",title:"GitLab Personal Access Token",pattern:String.raw`(glpat-[0-9a-zA-Z_-]{20})`,keywords:["glpat-"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})`,keywords:["AKIA","AGPA","AIDA","AROA","AIPA","ANPA","ANVA","ASIA"]},{id:"hugging-face-access-token",category:"huggingface",title:"Hugging Face Access Token",pattern:String.raw`(hf_[A-Za-z0-9]{34,40})`,keywords:["hf_"]},{id:"private-key",category:"asymmetric-private-key",title:"Asymmetric Private Key",pattern:String.raw`-----\s*?BEGIN[ A-Z0-9_-]*?PRIVATE KEY( BLOCK)?\s*?-----[\s]*?([A-Za-z0-9=+/\\\\r\n][A-Za-z0-9=+/\\\\s]+)[\s]*?-----\s*?END[ A-Z0-9_-]*? PRIVATE KEY( BLOCK)?\s*?-----`,keywords:["-----"],caseInsensitive:!0},{id:"shopify-token",category:"shopify",title:"Shopify token",pattern:String.raw`(shp(ss|at|ca|pa)_[a-fA-F0-9]{32})`,keywords:["shpss_","shpat_","shpca_","shppa_"]},{id:"slack-access-token",category:"slack",title:"Slack token",pattern:String.raw`((xox[baoprs]-|xapp-|xwfp-)([0-9a-zA-Z-]{10,100}))`,keywords:["xoxb-","xoxa-","xoxp-","xoxr-","xoxs-","xoxo-","xapp-","xwfp-"]},{id:"slack-config-refresh-token",category:"slack",title:"Slack config refresh token",pattern:String.raw`(xoxe-\d-[a-zA-Z0-9]{146})`,caseInsensitive:!0,keywords:["xoxe-"]},{id:"slack-config-access-token",category:"slack",title:"Slack config access token",pattern:String.raw`(xoxe.xox[bp]-\d-[A-Z0-9]{163,166})`,caseInsensitive:!0,keywords:["xoxe.xoxb-","xoxe.xoxp-"]},{id:"slack-web-hook",category:"slack",title:"Slack Webhook",pattern:String.raw`(https:\/\/hooks\.slack\.com\/(services|triggers|workflows)\/[A-Za-z0-9+\/]{43,56})`,caseInsensitive:!0,keywords:["hooks.slack.com"]},{id:"stripe-secret-token",category:"stripe",title:"Stripe Secret Key",pattern:String.raw`(sk_(test|live)_[0-9a-z]{10,99})`,keywords:["sk_test_","sk_live_"],caseInsensitive:!0},{id:"supabase-service-key",category:"supabase",title:"Supabase Service Key",pattern:String.raw`(sbp_[a-fA-F0-9]{40})`,keywords:["sbp_"]},{id:"pypi-upload-token",category:"pypi",title:"PyPI upload token",pattern:String.raw`(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000})`,keywords:["pypi-AgEIcHlwaS5vcmc"]},{id:"gcp-service-account",category:"google",title:"Google (GCP) Service-account",pattern:String.raw`("type": "service_account")`,keywords:['"type": "service_account"']},{id:"heroku-api-key",category:"heroku",title:"Heroku API Key",pattern:String.raw`(?:heroku[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](\d[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})['"]`,keywords:["heroku"],caseInsensitive:!0},{id:"twilio-api-key",category:"twilio",title:"Twilio API Key",pattern:String.raw`(SK[0-9a-fA-F]{32})`,keywords:["SK"]},{id:"age-secret-key",category:"age",title:"Age secret key",pattern:String.raw`(AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58})`,keywords:["AGE-SECRET-KEY-1"]},{id:"jwt-token",category:"jwt",title:"JWT token",pattern:String.raw`(ey[a-zA-Z0-9]{17,}\.ey[a-zA-Z0-9/\\_-]{17,}\.(?:[a-zA-Z0-9/\\_-]{10,}={0,2})?)`,keywords:[".eyJ"]},{id:"npm-access-token",category:"npm",title:"npm access token",pattern:String.raw`(npm_[a-z0-9]{36})`,keywords:["npm_"],caseInsensitive:!0},{id:"sendgrid-api-token",category:"sendgrid",title:"SendGrid API token",pattern:String.raw`(SG\.[a-z0-9_.-]{66})`,keywords:["SG."],caseInsensitive:!0},{id:"aws-secret-access-key",category:"aws",title:"AWS Secret Access Key",pattern:String.raw`(aws[_-]secret[_-]access[_-]key[_-][A-Za-z0-9/+=]{40})`,keywords:["key"],caseInsensitive:!0},{id:"dockerconfig-secret",category:"docker",title:"Dockerconfig secret exposed",pattern:String.raw`((\.dockerconfigjson|dockercfg):\s*\|*\s*((ey|ew)+[A-Za-z0-9/+=]+))`,keywords:["dockerc"],caseInsensitive:!0},{id:"linear-api-token",category:"linear",title:"Linear API token",pattern:String.raw`(lin_api_[a-z0-9]{40})`,keywords:["lin_api_"],caseInsensitive:!0},{id:"sendinblue-api-token",category:"sendinblue",title:"Sendinblue API token",pattern:String.raw`(xkeysib-[a-f0-9]{64}-[a-z0-9]{16})`,keywords:["xkeysib-"],caseInsensitive:!0},{id:"planetscale-api-token",category:"planetscale",title:"PlanetScale API token",pattern:String.raw`(pscale_tkn_[a-z0-9_.-]{43})`,keywords:["pscale_tkn_"],caseInsensitive:!0},{id:"doppler-api-token",category:"doppler",title:"Doppler API token",pattern:String.raw`(dp\.pt\.[a-z0-9]{43})`,keywords:["dp.pt."],caseInsensitive:!0},{id:"discord-api-token",category:"discord",title:"Discord API key",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{64})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"pulumi-api-token",category:"pulumi",title:"Pulumi API token",pattern:String.raw`(pul-[a-f0-9]{40})`,keywords:["pul-"]},{id:"postman-api-token",category:"postman",title:"Postman API token",pattern:String.raw`(PMAK-[a-f0-9]{24}-[a-f0-9]{34})`,keywords:["PMAK-"],caseInsensitive:!0},{id:"facebook-token",category:"facebook",title:"Facebook token",pattern:String.raw`(?:facebook[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["facebook"],caseInsensitive:!0},{id:"twitter-token",category:"twitter",title:"Twitter token",pattern:String.raw`(?:twitter[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{35,44})['"]`,keywords:["twitter"],caseInsensitive:!0},{id:"adobe-client-id",category:"adobe",title:"Adobe Client ID (Oauth Web)",pattern:String.raw`(?:adobe[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["adobe"],caseInsensitive:!0},{id:"adobe-client-secret",category:"adobe",title:"Adobe Client Secret",pattern:String.raw`(p8e-[a-z0-9]{32})`,keywords:["p8e-"],caseInsensitive:!0},{id:"alibaba-access-key-id",category:"alibaba",title:"Alibaba AccessKey ID",pattern:String.raw`((LTAI)[a-z0-9]{20})`,keywords:["LTAI"],caseInsensitive:!0},{id:"alibaba-secret-key",category:"alibaba",title:"Alibaba Secret Key",pattern:String.raw`(?:alibaba[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["alibaba"],caseInsensitive:!0},{id:"asana-client-id",category:"asana",title:"Asana Client ID",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{16})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"asana-client-secret",category:"asana",title:"Asana Client Secret",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"atlassian-api-token",category:"atlassian",title:"Atlassian API token",pattern:String.raw`(?:atlassian[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{24})['"]`,keywords:["atlassian"],caseInsensitive:!0},{id:"bitbucket-client-id",category:"bitbucket",title:"Bitbucket client ID",pattern:String.raw`(?:bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["bitbucket"],caseInsensitive:!0},{id:"bitbucket-client-secret",category:"bitbucket",title:"Bitbucket client secret",pattern:String.raw`(?:bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9_-]{64})['"]`,keywords:["bitbucket"],caseInsensitive:!0},{id:"beamer-api-token",category:"beamer",title:"Beamer API token",pattern:String.raw`(?:beamer[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](b_[a-z0-9=_-]{44})['"]`,keywords:["beamer"],caseInsensitive:!0},{id:"buildkite-agent-token",category:"buildkite",title:"Buildkite API Token V2",pattern:String.raw`(bkua_[a-fA-F0-9]{40})`,keywords:["bkua_"]},{id:"clojars-api-token",category:"clojars",title:"Clojars API token",pattern:String.raw`(CLOJARS_[a-z0-9]{60})`,keywords:["CLOJARS_"],caseInsensitive:!0},{id:"contentful-delivery-api-token",category:"contentful-delivery",title:"Contentful delivery API token",pattern:String.raw`(?:contentful[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{43})['"]`,keywords:["contentful"],caseInsensitive:!0},{id:"databricks-api-token",category:"databricks",title:"Databricks API token",pattern:String.raw`(dapi[a-h0-9]{32})`,keywords:["dapi"]},{id:"discord-client-id",category:"discord",title:"Discord client ID",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{18})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"discord-client-secret",category:"discord",title:"Discord client secret",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"dropbox-api-secret",category:"dropbox",title:"Dropbox API secret/key",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{15})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-short-lived-api-token",category:"dropbox",title:"Dropbox short lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](sl\.[a-z0-9=_-]{135})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-long-lived-api-token",category:"dropbox",title:"Dropbox long lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9_=-]{43})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"duffel-api-token",category:"duffel",title:"Duffel API token",pattern:String.raw`(duffel_(test|live)_[a-z0-9_-]{43})`,keywords:["duffel_test_","duffel_live_"],caseInsensitive:!0},{id:"dynatrace-api-token",category:"dynatrace",title:"Dynatrace API token",pattern:String.raw`(dt0c01\.[a-z0-9]{24}\.[a-z0-9]{64})`,keywords:["dt0c01."],caseInsensitive:!0},{id:"easypost-api-token",category:"easypost",title:"EasyPost API token",pattern:String.raw`(EZ[AT]K[a-z0-9]{54})`,keywords:["EZAK","EZAT"],caseInsensitive:!0},{id:"fastly-api-token",category:"fastly",title:"Fastly API token",pattern:String.raw`(?:fastly[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["fastly"],caseInsensitive:!0},{id:"finicity-client-secret",category:"finicity",title:"Finicity client secret",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{20})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"finicity-api-token",category:"finicity",title:"Finicity API token",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"flutterwave-public-key",category:"flutterwave",title:"Flutterwave public/secret key",pattern:String.raw`(FLW(PUB|SEC)K_TEST-[a-h0-9]{32}-X)`,keywords:["FLWSECK_TEST-","FLWPUBK_TEST-"],caseInsensitive:!0},{id:"flutterwave-enc-key",category:"flutterwave",title:"Flutterwave encrypted key",pattern:String.raw`(FLWSECK_TEST[a-h0-9]{12})`,keywords:["FLWSECK_TEST"]},{id:"frameio-api-token",category:"frameio",title:"Frame.io API token",pattern:String.raw`(fio-u-[a-z0-9_=-]{64})`,keywords:["fio-u-"],caseInsensitive:!0},{id:"gocardless-api-token",category:"gocardless",title:"GoCardless API token",pattern:String.raw`(live_[a-z0-9_=-]{40})`,keywords:["live_"],caseInsensitive:!0},{id:"grafana-api-token",category:"grafana",title:"Grafana API token",pattern:String.raw`(eyJrIjoi[a-z0-9_=-]{72,92})`,keywords:["eyJrIjoi"],caseInsensitive:!0},{id:"hashicorp-tf-api-token",category:"hashicorp",title:"HashiCorp Terraform user/org API token",pattern:String.raw`([a-z0-9]{14}\.atlasv1\.[a-z0-9_=-]{60,70})`,keywords:["atlasv1."],caseInsensitive:!0},{id:"hubspot-api-token",category:"hubspot",title:"HubSpot API token",pattern:String.raw`(?:hubspot[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["hubspot"],caseInsensitive:!0},{id:"intercom-api-token",category:"intercom",title:"Intercom API token",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_]{60})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"intercom-client-secret",category:"intercom",title:"Intercom client secret/ID",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"ionic-api-token",category:"ionic",title:"Ionic API token",pattern:String.raw`(?:ionic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](ion_[a-z0-9]{42})['"]`,keywords:["ionic"],caseInsensitive:!0},{id:"linear-client-secret",category:"linear",title:"Linear client secret/ID",pattern:String.raw`(?:linear[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["linear"],caseInsensitive:!0},{id:"lob-api-key",category:"lob",title:"Lob API Key",pattern:String.raw`(?:lob[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((live|test)_[a-f0-9]{35})['"]`,keywords:["lob"],caseInsensitive:!0},{id:"mailchimp-api-key",category:"mailchimp",title:"Mailchimp API key",pattern:String.raw`(?:mailchimp[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32}-us20)['"]`,keywords:["mailchimp"],caseInsensitive:!0},{id:"mailgun-token",category:"mailgun",title:"Mailgun private API token",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((pub)?key-[a-f0-9]{32})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mailgun-signing-key",category:"mailgun",title:"Mailgun webhook signing key",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mapbox-api-token",category:"mapbox",title:"Mapbox API token",pattern:String.raw`(pk\.[a-z0-9]{60}\.[a-z0-9]{22})`,keywords:["pk."],caseInsensitive:!0},{id:"messagebird-api-token",category:"messagebird",title:"MessageBird API token",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{25})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"messagebird-client-id",category:"messagebird",title:"MessageBird API client ID",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"new-relic-user-api-key",category:"newrelic",title:"New Relic user API Key",pattern:String.raw`(NRAK-[A-Z0-9]{27})`,keywords:["NRAK-"]},{id:"new-relic-user-api-id",category:"newrelic",title:"New Relic user API ID",pattern:String.raw`(?:newrelic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Z0-9]{64})['"]`,keywords:["newrelic"],caseInsensitive:!0},{id:"new-relic-browser-api-token",category:"newrelic",title:"New Relic ingest browser API token",pattern:String.raw`(NRJS-[a-f0-9]{19})`,keywords:["NRJS-"]},{id:"planetscale-password",category:"planetscale",title:"PlanetScale password",pattern:String.raw`(pscale_pw_[a-z0-9_.-]{43})`,keywords:["pscale_pw_"],caseInsensitive:!0},{id:"private-packagist-token",category:"private-packagist",title:"Private Packagist token",pattern:String.raw`(packagist_[ou][ru]t_[a-f0-9]{68})`,keywords:["packagist_uut_","packagist_ort_","packagist_out_"],caseInsensitive:!0},{id:"rubygems-api-token",category:"rubygems",title:"Rubygem API token",pattern:String.raw`(rubygems_[a-f0-9]{48})`,keywords:["rubygems_"]},{id:"shippo-api-token",category:"shippo",title:"Shippo API token",pattern:String.raw`(shippo_(live|test)_[a-f0-9]{40})`,keywords:["shippo_live_","shippo_test_"]},{id:"linkedin-client-secret",category:"linkedin",title:"LinkedIn Client secret",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z]{16})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"linkedin-client-id",category:"linkedin",title:"LinkedIn Client ID",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{14})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"twitch-api-token",category:"twitch",title:"Twitch API token",pattern:String.raw`(?:twitch[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["twitch"],caseInsensitive:!0},{id:"typeform-api-token",category:"typeform",title:"Typeform API token",pattern:String.raw`(?:typeform[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9_.=-]{59})`,keywords:["typeform"],caseInsensitive:!0},{id:"todoist-api-token",category:"todoist",title:"Todoist API token",pattern:String.raw`(?:todoist[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:)[\s'"]{0,3}([0-9a-f]{40})`,keywords:["todoist"],caseInsensitive:!0},{id:"openai-api-key",category:"openai",title:"OpenAI API Key",pattern:String.raw`(sk-[a-zA-Z0-9]{50})`,caseInsensitive:!1,keywords:["sk-"]},{id:"openai-api-key-project",category:"openai",title:"OpenAI Project-scoped API Key",pattern:String.raw`(sk-proj-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-proj-"]},{id:"openai-api-key-env",category:"openai",title:"OpenAI Environment-scoped API Key",pattern:String.raw`(sk-(?:live|test)-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-live-","sk-test-"]},{id:"anthropic-api-key",category:"anthropic",title:"Anthropic API Key",pattern:String.raw`(sk-ant-([a-zA-Z0-9]{1,10}-)?[a-zA-Z0-9_-]{32,128})`,caseInsensitive:!1,keywords:["sk-ant-"]},{id:"canva-token",category:"canva",title:"Canva Token",pattern:String.raw`\b(cnv[a-z0-9]{2}[A-Za-z0-9_=-]+[a-f0-9]{8})\b`,caseInsensitive:!1,keywords:["cnv"]},{id:"api-key",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}api[-_](?:key|token)(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["api-key","api_key","api-token","api_token"],caseInsensitive:!0},{id:"webhook-secret",category:"unknown",title:"Unknown Webhook Secret",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}webhook[-_]secret(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|webhook))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["webhook-secret","webhook_secret"],caseInsensitive:!0},{id:"password",category:"unknown",title:"Unknown Password",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}password(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|password|pass|pwd))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["password"],caseInsensitive:!0},{id:"sk-secret",category:"unknown",title:"Unknown SK Secret",pattern:String.raw`(?:^|['"\s])(sk(?:[-_][a-z0-9]{1,10})?[-_][a-z0-9]{10,99})(?:$|['"\s])`,caseInsensitive:!0,keywords:["sk-","sk_"]}]});function G$6(J){if(!J||typeof J!=="string")return J;let Q=J.replace(q$6,"");if(Q.length!==J.length){let Z=J.length-Q.length;a.info("Invisible Unicode tag characters removed during sanitization",{removedCount:Z})}return Q}function z$6(J){if(!J||typeof J!=="string")return J;let Q=G$6(J);for(let Z of o10){if(!Z.keywords.some((Y)=>Z.caseInsensitive?Q.toLowerCase().includes(Y.toLowerCase()):Q.includes(Y)))continue;let X=s10(Z);Q=Q.replace(X,(Y,K)=>{return Y.replace(K,`[REDACTED:${Z.id}]`)})}return Q}function Xi(J,Q){if(!J||typeof J==="number"||typeof J==="boolean")return J;if(typeof J==="string")return Q(J);if(Array.isArray(J))return J.map((Z)=>{if(typeof Z==="string")return Q(Z);else if(Z&&typeof Z==="object")return Xi(Z,Q);return Z});if(J&&typeof J==="object"){if("type"in J&&(J.type==="base64"||J.type==="image")&&"data"in J)return{...J};if("isImage"in J&&J.isImage===!0&&"content"in J&&typeof J.content==="string"){let Z={};for(let[X,Y]of Object.entries(J))if(X==="content")Z[X]=Y;else Z[X]=Xi(Y,Q);return Z}}return Object.fromEntries(Object.entries(J).map(([Z,X])=>[Z,Xi(X,Q)]))}function cR(J){return Xi(J,z$6)}var q$6;var rU1=p(()=>{D0();t10();q$6=/[\uDB40][\uDC00-\uDC7F]/g});import{execFile as U$6}from"node:child_process";import{promises as W$6}from"node:fs";import{arch as F$6,cpus as H$6,freemem as B$6,platform as Yi,release as D$6,totalmem as M$6}from"node:os";import{promisify as V$6}from"node:util";class oU1{async collect(){let J=H$6(),Q=M$6(),Z=B$6(),X={architecture:F$6(),cpu:{cores:J.length,model:J[0]?.model||"Unknown",speed:J[0]?.speed||0},environment:await(async()=>{let[Y,K,q,G,z,U,W,F,H]=await Promise.all([this.collectBrewInfo(),this.collectChocolateyInfo(),this.collectNixInfo(),this.collectNpmInfo(),this.collectNvmInfo(),this.collectPnpmInfo(),this.collectRipgrepBundledInfo(),this.collectRipgrepInfo(),this.collectYarnInfo()]);return{brew:Y,chocolatey:K,nix:q,node:{executablePath:process.execPath,version:process.version},npm:G,nvm:z,pnpm:U,rgBundled:W,rgSystem:F,yarn:H}})(),memory:{free:Z,total:Q,used:Q-Z},platform:Yi(),version:D$6()};try{let Y=await this.getDiskSpace();if(Y)X.diskSpace=Y}catch{}return X}async findExecutablePath(J){try{if(Yi()==="win32"){let{stdout:Z}=await sU1("where",[J],{timeout:5000});return Z.trim().split(`
@@ -5434,7 +5434,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||KR}function zQ6(J,Q){let
5434
5434
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(KQ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await XQ6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}var UQ6=p(()=>{gS();MV();pJ6();iJ6();aJ6();qQ6()});function WQ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}import f29 from"node:fs";import FQ6 from"node:path";function HQ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!FQ6.isAbsolute(Q))return null;return a.debug("Extracted image path",{original:J,extracted:Q}),Q}function BQ6(J){try{let Q=FQ6.extname(J).toLowerCase(),Z=go1(Q);if(!Z)return a.warn("Unsupported image file extension",{ext:Q}),null;try{let X=f29.readFileSync(J);return h29(X,Z)}catch(X){a.error(`Failed to read image file ${J}:`,X)}}catch(Q){a.error("Error handling image file path",{imagePath:J,error:Q})}return null}function h29(J,Q){if(J.length>jR)return a.warn(`Image file too large: ${J.length} bytes (max: ${jR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}var DQ6=p(()=>{D0();vN()});function MQ6(J){return J.kind==="executable"}function VQ6(J){return J.kind==="markdown"}import{spawn as g29}from"node:child_process";import{promises as m29}from"node:fs";async function Hx1(J,Q,Z,X={}){let{timeoutMs:Y=NQ6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(a.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),VQ6(q))return await u29(q,Q);else if(MQ6(q))return await p29(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return a.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function u29(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await m29.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>wH?Z.slice(0,wH)+`
5435
5435
  ... (output truncated at ${wH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function p29(J,Q,Z=NQ6,X){return new Promise((Y)=>{let[K,q]=d29(J,Q);a.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=xo1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),a.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=g29(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],D=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=wH)F.push(V);else{let N=wH-(D-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=wH)H.push(V);else{let N=wH-(D-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
5436
5436
  ${L}`:L;if(D>wH)A+=`
5437
- ... (output truncated at ${wH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function d29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return l29(Z,X?[...X]:null,Y,Q);else return c29(Z,X?[...X]:null,Y,Q)}function c29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function l29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var wH=50000,NQ6=300000;var LQ6=p(()=>{AR();D0()});var AQ6=p(()=>{LQ6();oJ1()});var m41,DU2,MU2,VU2,NU2,LU2,AU2,OU2,jU2,RU2,am,wU2,IU2,EU2,$U2,PU2;var OQ6=p(()=>{m41=globalThis.window?.document!==void 0,DU2=globalThis.process?.versions?.node!==void 0,MU2=globalThis.process?.versions?.bun!==void 0,VU2=globalThis.Deno?.version?.deno!==void 0,NU2=globalThis.process?.versions?.electron!==void 0,LU2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,AU2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,OU2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,jU2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,RU2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,am=globalThis.navigator?.userAgentData?.platform,wU2=am==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",IU2=am==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",EU2=am==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",$U2=am==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),PU2=am==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var u41={};L6(u41,{scrollUp:()=>F49,scrollDown:()=>H49,link:()=>L49,image:()=>A49,iTerm:()=>O49,exitAlternativeScreen:()=>V49,eraseUp:()=>W49,eraseStartLine:()=>z49,eraseScreen:()=>Bx1,eraseLines:()=>q49,eraseLine:()=>IQ6,eraseEndLine:()=>G49,eraseDown:()=>U49,enterAlternativeScreen:()=>M49,cursorUp:()=>RQ6,cursorTo:()=>a29,cursorShow:()=>K49,cursorSavePosition:()=>e29,cursorRestorePosition:()=>J49,cursorPrevLine:()=>X49,cursorNextLine:()=>Z49,cursorMove:()=>r29,cursorLeft:()=>wQ6,cursorHide:()=>Y49,cursorGetPosition:()=>Q49,cursorForward:()=>o29,cursorDown:()=>s29,cursorBackward:()=>t29,clearTerminal:()=>D49,clearScreen:()=>B49,beep:()=>N49});import Dx1 from"node:process";var U2="\x1B[",sm="\x1B]",bT="\x07",rm=";",jQ6,i29,n29,a29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+rm+(J+1)+"H"},r29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},RQ6=(J=1)=>U2+J+"A",s29=(J=1)=>U2+J+"B",o29=(J=1)=>U2+J+"C",t29=(J=1)=>U2+J+"D",wQ6,e29,J49,Q49,Z49,X49,Y49,K49,q49=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=IQ6+(Z<J-1?RQ6():"");if(J)Q+=wQ6;return Q},G49,z49,IQ6,U49,W49,Bx1,F49,H49,B49="\x1Bc",D49,M49,V49,N49,L49=(J,Q)=>[sm,"8",rm,rm,Q,bT,J,sm,"8",rm,rm,bT].join(""),A49=(J,Q={})=>{let Z=`${sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+bT},O49;var Mx1=p(()=>{OQ6();jQ6=!m41&&Dx1.env.TERM_PROGRAM==="Apple_Terminal",i29=!m41&&Dx1.platform==="win32",n29=m41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Dx1.cwd,wQ6=U2+"G",e29=jQ6?"\x1B7":U2+"s",J49=jQ6?"\x1B8":U2+"u",Q49=U2+"6n",Z49=U2+"E",X49=U2+"F",Y49=U2+"?25l",K49=U2+"?25h",G49=U2+"K",z49=U2+"1K",IQ6=U2+"2K",U49=U2+"J",W49=U2+"1J",Bx1=U2+"2J",F49=U2+"S",H49=U2+"T",D49=i29?`${Bx1}${U2}0f`:`${Bx1}${U2}3J${U2}H`,M49=U2+"?1049h",V49=U2+"?1049l",N49=bT,O49={setCwd:(J=n29())=>`${sm}50;CurrentDir=${J}${bT}`,annotation(J,Q={}){let Z=`${sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+bT}}});var EQ6=p(()=>{Mx1();Mx1()});var Vx1=e((_U2,$Q6)=>{$Q6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var CQ6=e((bU2,TQ6)=>{var j49=o1("os"),PQ6=o1("tty"),_K=Vx1(),{env:r5}=process,EV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))EV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))EV=1;if("FORCE_COLOR"in r5)if(r5.FORCE_COLOR==="true")EV=1;else if(r5.FORCE_COLOR==="false")EV=0;else EV=r5.FORCE_COLOR.length===0?1:Math.min(parseInt(r5.FORCE_COLOR,10),3);function Nx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Lx1(J,Q){if(EV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&EV===void 0)return 0;let Z=EV||0;if(r5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=j49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in r5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in r5))||r5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in r5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r5.TEAMCITY_VERSION)?1:0;if(r5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r5){let X=parseInt((r5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(r5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r5.TERM))return 1;if("COLORTERM"in r5)return 1;return Z}function R49(J){let Q=Lx1(J,J&&J.isTTY);return Nx1(Q)}TQ6.exports={supportsColor:R49,stdout:Nx1(Lx1(!0,PQ6.isatty(1))),stderr:Nx1(Lx1(!0,PQ6.isatty(2)))}});var kQ6=e((xU2,vQ6)=>{var w49=CQ6(),xT=Vx1();function SQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Ax1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(xT("no-hyperlink")||xT("no-hyperlinks")||xT("hyperlink=false")||xT("hyperlink=never"))return!1;if(xT("hyperlink=true")||xT("hyperlink=always"))return!0;if(X)return!0;if(!w49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=SQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=SQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}vQ6.exports={supportsHyperlink:Ax1,stdout:Ax1(process.stdout),stderr:Ax1(process.stderr)}});function $V(J,Q,{target:Z="stdout",...X}={}){if(!p41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return u41.link(J,Q)}var p41;var _Q6=p(()=>{EQ6();p41=u6(kQ6(),1);$V.isSupported=p41.default.stdout;$V.stderr=(J,Q,Z={})=>$V(J,Q,{target:"stderr",...Z});$V.stderr.isSupported=p41.default.stderr});class Ox1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;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.1759276921-gbfbfa1"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await k10(Q)}catch(Q){a.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}}var bQ6=p(()=>{D0();vB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function xQ6(J){if(J instanceof d41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var d41;var jx1=p(()=>{D0();d41=class d41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as yQ6}from"node:child_process";import{rmdir as I49}from"node:fs/promises";import{tmpdir as E49}from"node:os";import fQ6 from"node:path";import{mkdtemp as $49,readFile as P49,unlink as T49,writeFile as GW2}from"fs/promises";class Rx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=VC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new Ox1(async()=>{try{return(await O9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Z2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...C49},J)Object.assign(this.commands,S49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Hx1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var C49,S49;var hQ6=p(()=>{AQ6();D0();D4();NC();nw();u4();iU();Gx1();vB();WD();Y8();n0();_Q6();b41();zx1();bQ6();jx1();C49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${FJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:tY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new d41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await $49(fQ6.join(E49(),"amp-edit-")),Y=fQ6.join(X,"message.amp.md");yQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await P49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await T49(Y),await I49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return pU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return pU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await kT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:kT};await h41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5437
+ ... (output truncated at ${wH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function d29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return l29(Z,X?[...X]:null,Y,Q);else return c29(Z,X?[...X]:null,Y,Q)}function c29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function l29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var wH=50000,NQ6=300000;var LQ6=p(()=>{AR();D0()});var AQ6=p(()=>{LQ6();oJ1()});var m41,DU2,MU2,VU2,NU2,LU2,AU2,OU2,jU2,RU2,am,wU2,IU2,EU2,$U2,PU2;var OQ6=p(()=>{m41=globalThis.window?.document!==void 0,DU2=globalThis.process?.versions?.node!==void 0,MU2=globalThis.process?.versions?.bun!==void 0,VU2=globalThis.Deno?.version?.deno!==void 0,NU2=globalThis.process?.versions?.electron!==void 0,LU2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,AU2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,OU2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,jU2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,RU2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,am=globalThis.navigator?.userAgentData?.platform,wU2=am==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",IU2=am==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",EU2=am==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",$U2=am==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),PU2=am==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var u41={};L6(u41,{scrollUp:()=>F49,scrollDown:()=>H49,link:()=>L49,image:()=>A49,iTerm:()=>O49,exitAlternativeScreen:()=>V49,eraseUp:()=>W49,eraseStartLine:()=>z49,eraseScreen:()=>Bx1,eraseLines:()=>q49,eraseLine:()=>IQ6,eraseEndLine:()=>G49,eraseDown:()=>U49,enterAlternativeScreen:()=>M49,cursorUp:()=>RQ6,cursorTo:()=>a29,cursorShow:()=>K49,cursorSavePosition:()=>e29,cursorRestorePosition:()=>J49,cursorPrevLine:()=>X49,cursorNextLine:()=>Z49,cursorMove:()=>r29,cursorLeft:()=>wQ6,cursorHide:()=>Y49,cursorGetPosition:()=>Q49,cursorForward:()=>o29,cursorDown:()=>s29,cursorBackward:()=>t29,clearTerminal:()=>D49,clearScreen:()=>B49,beep:()=>N49});import Dx1 from"node:process";var U2="\x1B[",sm="\x1B]",bT="\x07",rm=";",jQ6,i29,n29,a29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+rm+(J+1)+"H"},r29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},RQ6=(J=1)=>U2+J+"A",s29=(J=1)=>U2+J+"B",o29=(J=1)=>U2+J+"C",t29=(J=1)=>U2+J+"D",wQ6,e29,J49,Q49,Z49,X49,Y49,K49,q49=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=IQ6+(Z<J-1?RQ6():"");if(J)Q+=wQ6;return Q},G49,z49,IQ6,U49,W49,Bx1,F49,H49,B49="\x1Bc",D49,M49,V49,N49,L49=(J,Q)=>[sm,"8",rm,rm,Q,bT,J,sm,"8",rm,rm,bT].join(""),A49=(J,Q={})=>{let Z=`${sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+bT},O49;var Mx1=p(()=>{OQ6();jQ6=!m41&&Dx1.env.TERM_PROGRAM==="Apple_Terminal",i29=!m41&&Dx1.platform==="win32",n29=m41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Dx1.cwd,wQ6=U2+"G",e29=jQ6?"\x1B7":U2+"s",J49=jQ6?"\x1B8":U2+"u",Q49=U2+"6n",Z49=U2+"E",X49=U2+"F",Y49=U2+"?25l",K49=U2+"?25h",G49=U2+"K",z49=U2+"1K",IQ6=U2+"2K",U49=U2+"J",W49=U2+"1J",Bx1=U2+"2J",F49=U2+"S",H49=U2+"T",D49=i29?`${Bx1}${U2}0f`:`${Bx1}${U2}3J${U2}H`,M49=U2+"?1049h",V49=U2+"?1049l",N49=bT,O49={setCwd:(J=n29())=>`${sm}50;CurrentDir=${J}${bT}`,annotation(J,Q={}){let Z=`${sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+bT}}});var EQ6=p(()=>{Mx1();Mx1()});var Vx1=e((_U2,$Q6)=>{$Q6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var CQ6=e((bU2,TQ6)=>{var j49=o1("os"),PQ6=o1("tty"),_K=Vx1(),{env:r5}=process,EV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))EV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))EV=1;if("FORCE_COLOR"in r5)if(r5.FORCE_COLOR==="true")EV=1;else if(r5.FORCE_COLOR==="false")EV=0;else EV=r5.FORCE_COLOR.length===0?1:Math.min(parseInt(r5.FORCE_COLOR,10),3);function Nx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Lx1(J,Q){if(EV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&EV===void 0)return 0;let Z=EV||0;if(r5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=j49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in r5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in r5))||r5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in r5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r5.TEAMCITY_VERSION)?1:0;if(r5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r5){let X=parseInt((r5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(r5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r5.TERM))return 1;if("COLORTERM"in r5)return 1;return Z}function R49(J){let Q=Lx1(J,J&&J.isTTY);return Nx1(Q)}TQ6.exports={supportsColor:R49,stdout:Nx1(Lx1(!0,PQ6.isatty(1))),stderr:Nx1(Lx1(!0,PQ6.isatty(2)))}});var kQ6=e((xU2,vQ6)=>{var w49=CQ6(),xT=Vx1();function SQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Ax1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(xT("no-hyperlink")||xT("no-hyperlinks")||xT("hyperlink=false")||xT("hyperlink=never"))return!1;if(xT("hyperlink=true")||xT("hyperlink=always"))return!0;if(X)return!0;if(!w49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=SQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=SQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}vQ6.exports={supportsHyperlink:Ax1,stdout:Ax1(process.stdout),stderr:Ax1(process.stderr)}});function $V(J,Q,{target:Z="stdout",...X}={}){if(!p41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return u41.link(J,Q)}var p41;var _Q6=p(()=>{EQ6();p41=u6(kQ6(),1);$V.isSupported=p41.default.stdout;$V.stderr=(J,Q,Z={})=>$V(J,Q,{target:"stderr",...Z});$V.stderr.isSupported=p41.default.stderr});class Ox1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;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.1759294726-g7c064a"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await k10(Q)}catch(Q){a.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}}var bQ6=p(()=>{D0();vB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function xQ6(J){if(J instanceof d41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var d41;var jx1=p(()=>{D0();d41=class d41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as yQ6}from"node:child_process";import{rmdir as I49}from"node:fs/promises";import{tmpdir as E49}from"node:os";import fQ6 from"node:path";import{mkdtemp as $49,readFile as P49,unlink as T49,writeFile as GW2}from"fs/promises";class Rx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=VC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new Ox1(async()=>{try{return(await O9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Z2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...C49},J)Object.assign(this.commands,S49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Hx1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var C49,S49;var hQ6=p(()=>{AQ6();D0();D4();NC();nw();u4();iU();Gx1();vB();WD();Y8();n0();_Q6();b41();zx1();bQ6();jx1();C49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${FJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:tY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new d41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await $49(fQ6.join(E49(),"amp-edit-")),Y=fQ6.join(X,"message.amp.md");yQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await P49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await T49(Y),await I49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return pU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return pU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await kT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:kT};await h41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5438
5438
  `).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=ev(new URL(Y),Z.id).toString(),G=`Thread URL: ${$V(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new zY(`${G}
5439
5439
 
5440
5440
  This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof Error?W.message:String(W);if(F.includes("no-workspace"))return Error("You are not a member of any workspace.");if(F.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(F.includes("no-groups"))return Error("You are not a member of any groups.");return a.error("Unexpected failure to update thread visibility",W),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=ev(new URL(X),Z.id).toString();try{return await vT(Y),new zY("Thread opened in browser")}catch(K){a.error("Failed to open browser",{error:K});let q=$V(Y,Y,{fallback:()=>Y});return new zY(`Could not open browser automatically. Thread URL: ${q}`)}},isVisible:(J)=>J.messages.length!==0},settings:{name:"settings",description:"Open CLI settings file in $EDITOR",launchesWindow:!0,execute:async(J)=>{let Q=await kT();if(Q===null)return Error("No editor found, please set $EDITOR to edit settings");try{yQ6(`${Q} "${J.settingsFilePath}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");return}catch(Z){return a.error("Failed to open settings in editor",Z),Error(`Failed to open ${Q}`)}}},"agent-files":{name:"agent-files",description:"List AGENTS.md guidance files in use for the current thread",execute:async(J)=>{try{let Q=await J.getGuidanceFiles();if(Q.length===0)return new zY("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${NX(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${JJ(MX(K.uri))} (${K.type})`).join(`
@@ -5444,9 +5444,9 @@ ${Y}`)}catch(Q){return a.error("Failed to get guidance files",Q),Error("Failed t
5444
5444
  Available modes: ${U}`)}let Y=Q[0]?.trim();if(!Y)return Error("Mode value cannot be empty");let K=Y,q=lC.map((z)=>z.mode);if(!oU.includes(K))return Error(`Invalid mode: ${K}. Valid modes: ${q.join(", ")}`);await J.settingsStorage.set("experimental.agentMode",K);let G=mQ1(K);return new zY(`Mode set to: ${K}${G?` - ${G}`:""}`)}catch(Z){return a.error("Failed to access agent mode setting",Z),Error("Failed to access agent mode setting")}}}}});import v49 from"node:http";class wx1{enabled;interval;server=null;latestSnapshot=null;timer=null;rootElement=null;port=9876;elementToIdMap=new Map;renderObjectToIdMap=new Map;constructor(J=!1,Q=1e4){this.enabled=J;this.interval=Q}start(J){if(!this.enabled)return;this.rootElement=J,this.startServer(),this.startPeriodicScan()}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;if(this.server)this.server.close(),this.server=null}startServer(){this.server=v49.createServer((J,Q)=>{if(Q.setHeader("Access-Control-Allow-Origin","*"),Q.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),Q.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),J.method==="OPTIONS"){Q.writeHead(200),Q.end();return}if(J.url==="/widget-tree"&&J.method==="GET"){Q.setHeader("Content-Type","application/json"),Q.writeHead(200),Q.end(JSON.stringify(this.latestSnapshot||{timestamp:Date.now(),rootWidget:null}));return}if(J.url==="/health"&&J.method==="GET"){Q.setHeader("Content-Type","application/json"),Q.writeHead(200),Q.end(JSON.stringify({status:"ok",enabled:this.enabled}));return}Q.writeHead(404),Q.end("Not Found")}),this.server.listen(this.port,"localhost",()=>{a.info(`Widget Tree Debugger running on http://localhost:${this.port}`),a.info(`Widget Tree Data: http://localhost:${this.port}/widget-tree`)}),this.server.on("error",(J)=>{a.error("Widget Tree Debugger server error:",J)})}startPeriodicScan(){this.scanTree(),this.timer=setInterval(()=>{this.scanTree()},this.interval)}scanTree(){if(!this.rootElement)return;try{this.elementToIdMap.clear(),this.renderObjectToIdMap.clear(),this.buildElementIdMap(this.rootElement),this.buildRenderObjectIdMap(this.rootElement);let J=this.elementToDebugInfo(this.rootElement),Q=this.elementToElementDebugInfo(this.rootElement),Z=this.rootElement.renderObject?this.renderObjectToRenderTreeDebugInfo(this.rootElement.renderObject):null;this.latestSnapshot={timestamp:Date.now(),rootWidget:J,rootElement:Q,rootRenderObject:Z}}catch(J){a.error("Error scanning trees:",J)}}elementToDebugInfo(J){let Q=this.elementToIdMap.get(J)||"unknown",Z=J.widget.constructor.name,X=J.widget.key?String(J.widget.key):void 0,Y=J.depth,K;if(J.renderObject)K=this.renderObjectToDebugInfo(J.renderObject);let q=J.children.map((G)=>this.elementToDebugInfo(G));return{id:Q,type:Z,key:X,depth:Y,renderObject:K,children:q}}elementToElementDebugInfo(J){let Q=this.elementToIdMap.get(J)||"unknown",Z=J.constructor.name,X=J.depth,Y=J.dirty,K=!0,q=this.elementToDebugInfo(J),G;if(J.renderObject)G=this.renderObjectToDebugInfo(J.renderObject);let z=J.children.map((U)=>this.elementToElementDebugInfo(U));return{id:Q,type:Z,depth:X,dirty:Y,mounted:!0,widget:q,renderObject:G,children:z}}renderObjectToRenderTreeDebugInfo(J){let Q=this.renderObjectToIdMap.get(J)||this.generateRenderObjectId(J),Z=J.constructor.name,X={},Y=!1,K=!1,q=void 0,G=void 0,z=void 0;try{if("needsLayout"in J)Y=J.needsLayout;if("needsPaint"in J)K=J.needsPaint;if("size"in J)G=J.size;if("_lastConstraints"in J)q=J._lastConstraints;if("offset"in J){let F=J.offset;if(F&&typeof F==="object"&&"x"in F&&"y"in F)z={x:F.x,y:F.y}}let W=Object.getOwnPropertyNames(J);for(let F of W)if(!F.startsWith("_")&&F!=="constructor"&&!["needsLayout","needsPaint","size","constraints","offset"].includes(F))try{let H=J[F];if(typeof H!=="function"&&typeof H!=="object")X[F]=H}catch{}}catch(W){X.error=`Failed to extract properties: ${W}`}let U=[];try{if("children"in J&&Array.isArray(J.children)){let W=J.children;for(let F of W){if(!this.renderObjectToIdMap.has(F))this.renderObjectToIdMap.set(F,this.generateRenderObjectId(F));U.push(this.renderObjectToRenderTreeDebugInfo(F))}}}catch{}return{id:Q,type:Z,constraints:q,size:G,offset:z,needsLayout:Y,needsPaint:K,properties:X,children:U}}renderObjectToDebugInfo(J){let Q=J.constructor.name,Z={};try{if("size"in J)Z.size=J.size;if("constraints"in J)Z.constraints=J.constraints;if("offset"in J)Z.offset=J.offset;let X=Object.getOwnPropertyNames(J);for(let Y of X)if(!Y.startsWith("_")&&Y!=="constructor")try{let K=J[Y];if(typeof K!=="function")Z[Y]=K}catch{}}catch(X){Z.error=`Failed to extract properties: ${X}`}return{type:Q,properties:Z}}getLatestSnapshot(){return this.latestSnapshot}forceScan(){this.scanTree()}buildElementIdMap(J){let Q=this.generateNodeId(J);this.elementToIdMap.set(J,Q);for(let Z of J.children)this.buildElementIdMap(Z)}buildRenderObjectIdMap(J){let Q=this.elementToIdMap.get(J);if(J.renderObject&&Q)this.renderObjectToIdMap.set(J.renderObject,Q);for(let Z of J.children)this.buildRenderObjectIdMap(Z)}generateNodeId(J){let Q=J.widget.constructor.name,Z=J.constructor.name,X=J.widget.key?String(J.widget.key):"no-key",Y=J.depth,K=0,q=`${Z}-${Q}-${X}-${Y}`;for(let G=0;G<q.length;G++){let z=q.charCodeAt(G);K=(K<<5)-K+z,K=K&K}return`elem-${Math.abs(K).toString(36)}`}generateRenderObjectId(J){let Z=J.constructor.name;if("size"in J&&J.size)Z+=`-${JSON.stringify(J.size)}`;if("offset"in J&&J.offset)Z+=`-${JSON.stringify(J.offset)}`;let X=0;for(let Y=0;Y<Z.length;Y++){let K=Z.charCodeAt(Y);X=(X<<5)-X+K,X=X&X}return`render-${Math.abs(X).toString(36)}`}}var gQ6=p(()=>{D0()});import{execFile as l41}from"node:child_process";import{platform as mQ6}from"node:os";import{promisify as k49}from"node:util";class uQ6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await c41("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l41("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=l41("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=l41("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52(){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Q)=>{this.readResolve=Q,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Q(null)},2000),process.stdout.write(b49)});let J=await this.pendingReadPromise;return this.pendingReadPromise=null,J}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await c41("pbpaste");return J}catch{return null}}async readFromWlPaste(){try{let{stdout:J}=await c41("wl-paste",["--no-newline"]);return J}catch{return null}}async readFromXclip(){try{let{stdout:J}=await c41("xclip",["-selection","clipboard","-o"]);return J}catch{return null}}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(mQ6()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste();if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip();if(Q!==null)return Q}}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=_49(Z);process.stdout.write(X);return}if(mQ6()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var c41,_49=(J)=>`\x1B]52;c;${J}\x1B\\`,b49="\x1B]52;c;?\x1B\\",OG;var yT=p(()=>{c41=k49(l41);OG=new uQ6});function x49(J){let Q=(J&4)!==0,Z=(J&8)!==0,X=(J&16)!==0,Y=(J&32)!==0,K=J&-61,q="unknown";switch(K){case 0:q="left";break;case 1:q="middle";break;case 2:q="right";break;case 64:q="wheel_up";break;case 65:q="wheel_down";break;default:q="unknown";break}return{button:q,modifiers:{shift:Q,ctrl:X,alt:Z,meta:!1},motion:Y}}function om(J,Q,Z,X){let Y=x49(J.button),K;if(Y.button==="wheel_up"||Y.button==="wheel_down")K="scroll";else if(Y.motion)K="move";else if(J.pressed)K="press";else K="release";let q,G;if(Q&&Z&&X)q=(J.x-1)/Z,G=(J.y-1)/X;else q=J.x-1,G=J.y-1;return{type:"mouse",action:K,button:Y.button,x:q,y:G,modifiers:Y.modifiers,drag:Y.motion&&J.pressed}}var j5;var fT=p(()=>{j5={DEFAULT:"default",POINTER:"pointer",TEXT:"text",WAIT:"wait",CROSSHAIR:"crosshair",HELP:"help",MOVE:"move",NOT_ALLOWED:"not-allowed",PROGRESS:"progress",CELL:"cell",CONTEXT_MENU:"context-menu",COPY:"copy",ALIAS:"alias",ZOOM_IN:"zoom-in",ZOOM_OUT:"zoom-out",GRAB:"grab",GRABBING:"grabbing",N_RESIZE:"n-resize",S_RESIZE:"s-resize",E_RESIZE:"e-resize",W_RESIZE:"w-resize",NE_RESIZE:"ne-resize",NW_RESIZE:"nw-resize",SE_RESIZE:"se-resize",SW_RESIZE:"sw-resize",COL_RESIZE:"col-resize",ROW_RESIZE:"row-resize"}});function m9(J=" ",Q={},Z=1,X){return{char:J,style:{...Q},width:Z,hyperlink:X}}function y49(J,Q){return J.char===Q.char&&J.width===Q.width&&f49(J.style,Q.style)&&i41(J.hyperlink,Q.hyperlink)}function f49(J,Q){return pQ6(J.fg,Q.fg)&&pQ6(J.bg,Q.bg)&&J.bold===Q.bold&&J.italic===Q.italic&&J.underline===Q.underline&&J.strikethrough===Q.strikethrough&&J.reverse===Q.reverse&&J.dim===Q.dim}function i41(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;return J.uri===Q.uri&&J.id===Q.id}function pQ6(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;if(J.type!==Q.type)return!1;if(J.alpha!==Q.alpha)return!1;switch(J.type){case"default":return!0;case"index":return Q.value===J.value;case"rgb":{let Z=Q.value;return Z.r===J.value.r&&Z.g===J.value.g&&Z.b===J.value.b}default:return!1}}function dQ6(J){switch(J.type){case"rgb":return J.value;case"index":return{0:{r:0,g:0,b:0},1:{r:128,g:0,b:0},2:{r:0,g:128,b:0},3:{r:128,g:128,b:0},4:{r:0,g:0,b:128},5:{r:128,g:0,b:128},6:{r:0,g:128,b:128},7:{r:192,g:192,b:192},8:{r:128,g:128,b:128},9:{r:255,g:0,b:0},10:{r:0,g:255,b:0},11:{r:255,g:255,b:0},12:{r:0,g:0,b:255},13:{r:255,g:0,b:255},14:{r:0,g:255,b:255},15:{r:255,g:255,b:255}}[J.value]||{r:128,g:128,b:128};case"default":return null;default:return null}}function cQ6(J,Q){let Z=J.alpha??1;if(Z>=1)return J;if(Z<=0)return Q;let X=dQ6(J),Y=dQ6(Q);if(!X||!Y)return Z>0.5?J:Q;let K=Math.round(X.r*Z+Y.r*(1-Z)),q=Math.round(X.g*Z+Y.g*(1-Z)),G=Math.round(X.b*Z+Y.b*(1-Z));return{type:"rgb",value:{r:Math.max(0,Math.min(255,K)),g:Math.max(0,Math.min(255,q)),b:Math.max(0,Math.min(255,G))}}}function h49(J,Q){let Z={...Q};if(J.fg)if(Q.fg)Z.fg=cQ6(J.fg,Q.fg);else Z.fg=J.fg;if(J.bg)if(J.bg.alpha===0){if(Q.bg)Z.bg=Q.bg}else if(Q.bg)Z.bg=cQ6(J.bg,Q.bg);else Z.bg=J.bg;if(J.bold!==void 0)Z.bold=J.bold;if(J.italic!==void 0)Z.italic=J.italic;if(J.underline!==void 0)Z.underline=J.underline;if(J.strikethrough!==void 0)Z.strikethrough=J.strikethrough;if(J.reverse!==void 0)Z.reverse=J.reverse;if(J.dim!==void 0)Z.dim=J.dim;return Z}class Ix1{cells;width;height;constructor(J,Q){this.width=J,this.height=Q,this.cells=[],this.resize(J,Q)}getSize(){return{width:this.width,height:this.height}}resize(J,Q){this.width=J,this.height=Q,this.cells=Array(Q).fill(null).map(()=>Array(J).fill(null).map(()=>IH))}getCell(J,Q){if(J<0||J>=this.width||Q<0||Q>=this.height)return null;return this.cells[Q]?.[J]||null}setCell(J,Q,Z){if(J<0||J>=this.width||Q<0||Q>=this.height)return;if(Z.style.fg&&Z.style.fg.alpha!==void 0&&Z.style.fg.alpha<1||Z.style.bg&&Z.style.bg.alpha!==void 0&&Z.style.bg.alpha<1){let Y=this.cells[Q]?.[J]||IH,K=h49(Z.style,Y.style);if(this.cells[Q])this.cells[Q][J]={char:Z.char,style:K,width:Z.width}}else if(this.cells[Q])this.cells[Q][J]={...Z,style:{...Z.style}};if(Z.width>1){for(let Y=1;Y<Z.width;Y++)if(J+Y<this.width&&this.cells[Q])this.cells[Q][J+Y]=IH}}setChar(J,Q,Z,X,Y){this.setCell(J,Q,m9(Z,X,Y))}clear(){for(let J=0;J<this.height;J++)for(let Q=0;Q<this.width;Q++){let Z=this.cells[J];if(Z)Z[Q]=IH}}fill(J,Q,Z,X,Y=" ",K={}){let q=m9(Y,K);for(let G=0;G<X;G++)for(let z=0;z<Z;z++)this.setCell(J+z,Q+G,q)}copyTo(J){let{width:Q,height:Z}=J.getSize();for(let X=0;X<Math.min(this.height,Z);X++)for(let Y=0;Y<Math.min(this.width,Q);Y++){let K=this.getCell(Y,X);if(K)J.setCell(Y,X,K)}}getCells(){return this.cells.map((J)=>J.map((Q)=>({...Q,style:{...Q.style}})))}setCursor(J,Q){}clearCursor(){}setCursorShape(J){}markForRefresh(){}}class em{frontBuffer;backBuffer;width;height;needsFullRefresh=!1;cursorPosition=null;cursorVisible=!1;cursorShape=0;constructor(J=80,Q=24){this.width=J,this.height=Q,this.frontBuffer=new Ix1(J,Q),this.backBuffer=new Ix1(J,Q)}getSize(){return{width:this.width,height:this.height}}resize(J,Q){this.width=J,this.height=Q,this.frontBuffer.resize(J,Q),this.backBuffer.resize(J,Q)}getBuffer(){return this.backBuffer}getCell(J,Q){return this.backBuffer.getCell(J,Q)}setCell(J,Q,Z){this.backBuffer.setCell(J,Q,Z)}setChar(J,Q,Z,X,Y){this.backBuffer.setChar(J,Q,Z,X,Y)}clear(){this.backBuffer.clear()}fill(J,Q,Z,X,Y=" ",K={}){this.backBuffer.fill(J,Q,Z,X,Y,K)}present(){let J=this.frontBuffer;this.frontBuffer=this.backBuffer,this.backBuffer=J,this.processWideCharacters()}processWideCharacters(){for(let J=0;J<this.height;J++)for(let Q=0;Q<this.width;Q++){let Z=this.frontBuffer.getCell(Q,J);if(Z&&Z.width>1){for(let X=1;X<Z.width;X++)if(Q+X<this.width)this.frontBuffer.setCell(Q+X,J,IH)}}}getDiff(){let J=[];if(this.needsFullRefresh){for(let Q=0;Q<this.height;Q++)for(let Z=0;Z<this.width;Z++){let X=this.backBuffer.getCell(Z,Q);if(J.push({x:Z,y:Q,cell:X||IH}),X&&X.width>1)Z+=X.width-1}return this.needsFullRefresh=!1,J}for(let Q=0;Q<this.height;Q++)for(let Z=0;Z<this.width;Z++){let X=this.frontBuffer.getCell(Z,Q),Y=this.backBuffer.getCell(Z,Q);if(X===IH&&Y===IH)continue;if(!X||!Y||!y49(X,Y)){if(J.push({x:Z,y:Q,cell:Y||IH}),Y&&(Y.char.length>1||/[\u{1F000}-\u{1FFFF}]/u.test(Y.char)));if(Y&&Y.width>1)Z+=Y.width-1}else if(Y.char.length>1||/[\u{1F000}-\u{1FFFF}]/u.test(Y.char)){if(Y.width>1)Z+=Y.width-1}}return J}getFrontBuffer(){return this.frontBuffer}getBackBuffer(){return this.backBuffer}markForRefresh(){this.needsFullRefresh=!0}setCursor(J,Q){this.cursorPosition={x:J,y:Q},this.cursorVisible=!0}clearCursor(){this.cursorPosition=null,this.cursorVisible=!1}getCursor(){return this.cursorPosition}isCursorVisible(){return this.cursorVisible}setCursorShape(J){this.cursorShape=J}getCursorShape(){return this.cursorShape}}function m49(){return`amp-${++g49}`}function lQ6(J,Q){return{uri:J,id:Q??m49()}}function iQ6(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function n41(){return"\x1B]8;;\x1B\\"}var tm=4,d1,IH,g49=0;var z9=p(()=>{d1={default(J){return J!==void 0?{type:"default",alpha:J}:{type:"default"}},index(J,Q){return Q!==void 0?{type:"index",value:J,alpha:Q}:{type:"index",value:J}},rgb(J,Q,Z,X){return X!==void 0?{type:"rgb",value:{r:J,g:Q,b:Z},alpha:X}:{type:"rgb",value:{r:J,g:Q,b:Z}}},transparent(){return{type:"default",alpha:0}},black:{type:"index",value:0},red:{type:"index",value:1},green:{type:"index",value:2},yellow:{type:"index",value:3},blue:{type:"index",value:4},magenta:{type:"index",value:5},cyan:{type:"index",value:6},white:{type:"index",value:7},brightWhite:{type:"index",value:15}};IH=m9(" ",{})});function u49(J){return/\p{Extended_Pictographic}/u.test(J)}function p49(J){return J>=9632&&J<=9727||J>=9728&&J<=9983&&!(J>=9728&&J<=9983&&(J===9728||J===9729||J===9889||J===10052||J===9924||J===9925))||J>=8592&&J<=8703||J===10006}function d49(J){return/\p{M}/u.test(J)}function c49(J,Q=!0){if(!J)return 0;let Z=Array.from(J);if(Q){let X=0;for(let Y=0;Y<Z.length;Y++){let K=Z[Y];if(!K)continue;let q=K.codePointAt(0);if(!q)continue;let G=aQ6(q);if(G!==0){if(Y+1<Z.length){let U=Z[Y+1]?.codePointAt(0);if(U===65038)G=1;else if(U===65039)G=2}if(X===0){X=G;break}}}return X}else{let X=0;for(let Y of Z){if(!Y)continue;let K=Y.codePointAt(0);if(!K)continue;X+=aQ6(K)}return X}}function aQ6(J){if(J===9)return tm;if(d49(String.fromCodePoint(J))||J===8205||J>=65024&&J<=65039||J>=917760&&J<=917999||J>=127995&&J<=127999)return 0;if(l49(J)){if(p49(J))return 1;return 2}if(i49(J))return 2;return 1}function l49(J){let Q=String.fromCodePoint(J);return u49(Q)}function i49(J){return J>=19968&&J<=40959||J>=13312&&J<=19903||J>=131072&&J<=173791||J>=173824&&J<=177983||J>=177984&&J<=178207||J>=178208&&J<=183983||J>=183984&&J<=191471||J>=44032&&J<=55215||J>=12352&&J<=12447||J>=12448&&J<=12543||J>=12784&&J<=12799||J>=65280&&J<=65519||J>=12288&&J<=12351||J>=65281&&J<=65376||J===9001||J===9002||J>=127462&&J<=127487}function f4(J,Q=!0){let Z=nQ6.get(J);if(Z!==void 0)return Z;let X=c49(J,Q);return nQ6.set(J,X),X}function D2(J){try{if(!Ex1)Ex1=new Intl.Segmenter("en",{granularity:"grapheme"});return Array.from(Ex1.segment(J),(Q)=>Q.segment)}catch(Q){return Array.from(J)}}function UY(J,Q=!0){let Z=0,X=D2(J);for(let Y of X)Z+=f4(Y,Q);return Z}function $x1(J,Q,Z=!0,X="…"){if(Q<=0)return"";let Y=0,K="",q=D2(J);for(let G of q){let z=f4(G,Z);if(Y+z>Q){let U=UY(X,Z);if(Y+U<=Q)K+=X;break}K+=G,Y+=z}return K}var nQ6,Ex1=null;var EH=p(()=>{z9();nQ6=new Map});var rQ6=()=>{};var hT,sQ6;var Px1=p(()=>{hT={ground:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"ground",action:"execute"}])),...Object.fromEntries(Array.from({length:95},(J,Q)=>[Q+32,{nextState:"ground",action:"print"}])),127:{nextState:"ground",action:"execute"},...Object.fromEntries(Array.from({length:128},(J,Q)=>[Q+128,{nextState:"ground",action:"print"}])),27:{nextState:"escape",action:"clear"}},escape:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"escape",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"esc_dispatch"}])),91:{nextState:"csi_entry",action:"clear"},80:{nextState:"dcs_entry",action:"clear"},93:{nextState:"osc_string",action:"osc_start"},88:{nextState:"sos_pm_apc_string",action:"ignore"},94:{nextState:"sos_pm_apc_string",action:"ignore"},95:{nextState:"sos_pm_apc_string",action:"ignore"},79:{nextState:"escape_intermediate",action:"collect"},127:{nextState:"ground",action:"esc_dispatch"}},escape_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"escape_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"esc_dispatch"}])),127:{nextState:"escape_intermediate",action:"ignore"}},csi_entry:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_entry",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"csi_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_entry",action:"ignore"}},csi_param:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_param",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_param",action:"param"}])),58:{nextState:"csi_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_param",action:"ignore"}},csi_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_intermediate",action:"ignore"}},csi_ignore:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_ignore",action:"execute"}])),...Object.fromEntries(Array.from({length:64},(J,Q)=>[Q+32,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"ignore"}])),127:{nextState:"csi_ignore",action:"ignore"}},dcs_entry:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_entry",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"dcs_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_entry",action:"ignore"}},dcs_param:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_param",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_param",action:"param"}])),58:{nextState:"dcs_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_param",action:"ignore"}},dcs_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_intermediate",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_intermediate",action:"ignore"}},dcs_passthrough:{156:{nextState:"ground",action:"unhook"},27:{nextState:"ground",action:"unhook"},...Object.fromEntries(Array.from({length:256},(J,Q)=>{if(Q===156||Q===27)return[Q,void 0];return[Q,{nextState:"dcs_passthrough",action:"put"}]}).filter(([,J])=>J!==void 0))},dcs_ignore:{...Object.fromEntries(Array.from({length:256},(J,Q)=>[Q,{nextState:"dcs_ignore",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}},osc_string:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"osc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Q)=>[Q+32,{nextState:"osc_string",action:"osc_put"}])),7:{nextState:"ground",action:"osc_end"},156:{nextState:"ground",action:"osc_end"},27:{nextState:"escape",action:"clear"}},sos_pm_apc_string:{...Object.fromEntries(Array.from({length:256},(J,Q)=>[Q,{nextState:"sos_pm_apc_string",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}}},sQ6={24:{nextState:"ground",action:"execute"},26:{nextState:"ground",action:"execute"},27:{nextState:"escape",action:"clear"}};Object.keys(hT).forEach((J)=>{let Q=J;if(Q==="dcs_passthrough"){let{27:Z,...X}=sQ6;Object.assign(hT[Q],X)}else Object.assign(hT[Q],sQ6)})});class Ju{context;eventHandlers=[];constructor(){this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,dcsEscSeen:!1}}onEvent(J){this.eventHandlers.push(J)}offEvent(J){let Q=this.eventHandlers.indexOf(J);if(Q!==-1)this.eventHandlers.splice(Q,1)}parse(J){let Q=typeof J==="string"?this.stringToBytes(J):J;for(let Z of Q)this.processByte(Z)}flush(){this.flushPrintBuffer(),this.flushTextBuffer()}stringToBytes(J){return new TextEncoder().encode(J)}processByte(J){if(this.context.state==="osc_string"&&J===27){this.context.oscEscSeen=!0;return}if(this.context.oscEscSeen&&J===92){this.context.oscEscSeen=!1,this.performAction("osc_end",J),this.context.state="ground";return}if(this.context.oscEscSeen){this.context.oscEscSeen=!1,this.performAction("clear",27),this.context.state="escape";let Z=hT["escape"][J];if(Z)this.performAction(Z.action,J),this.context.state=Z.nextState;return}let Q=hT[this.context.state][J];if(!Q)return;if(this.performAction(Q.action,J),this.context.state==="ground"&&Q.nextState!=="ground")this.flushTextBuffer();this.context.state=Q.nextState}performAction(J,Q){if(this.context.dcsEscSeen&&Q===92){this.context.dcsEscSeen=!1;return}if(this.context.dcsEscSeen)this.context.dcsEscSeen=!1;switch(J){case"ignore":break;case"print":this.addToPrintBuffer(Q);break;case"execute":this.flushTextBuffer(),this.emitEvent({type:"execute",code:Q});break;case"clear":this.flushTextBuffer(),this.context.private.length=0,this.context.intermediates.length=0,this.context.final="",this.context.params=[],this.context.oscEscSeen=!1,this.context.paramBuffer.length=0,this.context.subparamBuffer.length=0,this.context.currentSubparams=[],this.context.oscData.length=0,this.context.dcsData.length=0;break;case"collect":if(Q>=60&&Q<=63)this.context.private.push(String.fromCharCode(Q));else this.context.intermediates.push(String.fromCharCode(Q));break;case"param":if(Q>=48&&Q<=57)if(this.context.currentSubparams.length>0)this.context.subparamBuffer.push(String.fromCharCode(Q));else this.context.paramBuffer.push(String.fromCharCode(Q));else if(Q===59)this.finishParameter();else if(Q===58)this.finishSubparameter();break;case"esc_dispatch":this.emitEvent({type:"escape",intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Q)});break;case"csi_dispatch":this.finishParameter(),this.emitEvent({type:"csi",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Q),params:[...this.context.params]});break;case"hook":this.finishParameter(),this.context.dcsData.length=0,this.context.final=String.fromCharCode(Q);break;case"put":this.context.dcsData.push(String.fromCharCode(Q));break;case"unhook":this.emitEvent({type:"dcs",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:this.context.final,params:[...this.context.params],data:this.context.dcsData.join("")}),this.context.dcsEscSeen=Q===27;break;case"osc_start":this.context.oscData.length=0,this.context.oscEscSeen=!1;break;case"osc_put":this.context.oscData.push(String.fromCharCode(Q));break;case"osc_end":this.emitEvent({type:"osc",data:this.context.oscData.join("")});break}}finishSubparameter(){if(this.context.currentSubparams.length===0)if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.paramBuffer.length=0}else this.context.currentSubparams.push(0);else if(this.context.subparamBuffer.length>0){let J=parseInt(this.context.subparamBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.subparamBuffer.length=0}else this.context.currentSubparams.push(0)}finishParameter(){if(this.context.currentSubparams.length>0){this.finishSubparameter();let[J,...Q]=this.context.currentSubparams,Z={value:J??0};if(Q.length>0)Z.subparams=Q;this.context.params.push(Z),this.context.currentSubparams=[]}else if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.params.push({value:isNaN(J)?0:J}),this.context.paramBuffer.length=0}else this.context.params.push({value:0})}addToPrintBuffer(J){this.context.printBuffer.push(J),this.tryEmitGraphemes()}tryEmitAccumulatedGraphemes(){if(this.context.textBuffer.length>1000){this.flushTextBuffer();return}if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout);this.context.flushTimeout=setTimeout(()=>{if(this.context.textBuffer.length>0)this.flushTextBuffer()},1)}tryEmitGraphemes(){if(this.context.printBuffer.length===0)return;let J=0,Q=this.context.printBuffer;for(let Z=0;Z<Q.length;Z++){let X=Q[Z];if(X===void 0)continue;if(X<128)J=Z+1;else if((X&224)===192){let Y=Q[Z+1];if(Z+1<Q.length&&Y!==void 0&&(Y&192)===128)J=Z+2,Z++;else break}else if((X&240)===224){let Y=Q[Z+1],K=Q[Z+2];if(Z+2<Q.length&&Y!==void 0&&(Y&192)===128&&K!==void 0&&(K&192)===128)J=Z+3,Z+=2;else break}else if((X&248)===240){let Y=Q[Z+1],K=Q[Z+2],q=Q[Z+3];if(Z+3<Q.length&&Y!==void 0&&(Y&192)===128&&K!==void 0&&(K&192)===128&&q!==void 0&&(q&192)===128)J=Z+4,Z+=3;else break}else if((X&192)===128){this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Z+1),this.tryEmitGraphemes();return}else{this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Z+1),this.tryEmitGraphemes();return}}if(J>0){let Z=new Uint8Array(Q.slice(0,J)),Y=new TextDecoder("utf-8",{fatal:!1}).decode(Z);if(this.context.textBuffer+=Y,this.tryEmitAccumulatedGraphemes(),this.context.printBuffer.splice(0,J),this.context.printBuffer.length>0)this.tryEmitGraphemes()}}flushPrintBuffer(){if(this.context.printBuffer.length>0){let J=new Uint8Array(this.context.printBuffer),Z=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(Z.length>0)this.context.textBuffer+=Z}this.context.printBuffer=[]}flushTextBuffer(){if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout),delete this.context.flushTimeout;if(this.context.textBuffer.length>0){let J=D2(this.context.textBuffer);for(let Q of J)this.emitEvent({type:"print",grapheme:Q});this.context.textBuffer=""}}emitEvent(J){for(let Q of this.eventHandlers)Q(J)}reset(){this.flushPrintBuffer(),this.flushTextBuffer(),this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,dcsEscSeen:!1}}getState(){return this.context.state}}var Tx1=p(()=>{EH();Px1()});var oQ6,Qu;var tQ6=p(()=>{Tx1();oQ6={57348:"Insert",57349:"Delete",57350:"ArrowLeft",57351:"ArrowRight",57352:"ArrowUp",57353:"ArrowDown",57354:"PageUp",57355:"PageDown",57356:"Home",57357:"End",57358:"CapsLock",57359:"ScrollLock",57360:"NumLock",57361:"PrintScreen",57362:"Pause",57363:"ContextMenu",57364:"F1",57365:"F2",57366:"F3",57367:"F4",57368:"F5",57369:"F6",57370:"F7",57371:"F8",57372:"F9",57373:"F10",57374:"F11",57375:"F12",57376:"F13",57377:"F14",57378:"F15",57379:"F16",57380:"F17",57381:"F18",57382:"F19",57383:"F20",57384:"F21",57385:"F22",57386:"F23",57387:"F24",57388:"F25",57389:"F26",57390:"F27",57391:"F28",57392:"F29",57393:"F30",57394:"F31",57395:"F32",57396:"F33",57397:"F34",57398:"F35",57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57414:"Enter",57415:"=",57416:",",57417:"ArrowLeft",57418:"ArrowRight",57419:"ArrowUp",57420:"ArrowDown",57421:"PageUp",57422:"PageDown",57423:"Home",57424:"End",57425:"Insert",57426:"Delete",57427:"Clear",57428:"MediaPlay",57429:"MediaPause",57430:"MediaPlayPause",57431:"MediaReverse",57432:"MediaStop",57433:"MediaFastForward",57434:"MediaRewind",57435:"MediaTrackNext",57436:"MediaTrackPrevious",57437:"MediaRecord",57438:"AudioVolumeDown",57439:"AudioVolumeUp",57440:"AudioVolumeMute",57441:"ShiftLeft",57442:"ControlLeft",57443:"AltLeft",57444:"MetaLeft",57445:"HyperLeft",57446:"MetaLeft",57447:"ShiftRight",57448:"ControlRight",57449:"AltRight",57450:"MetaRight",57451:"HyperRight",57452:"MetaRight",57453:"AltGraph",57454:"ISOLevel5Shift"};Qu=class Qu{lexer;keyHandlers=[];deviceAttributesHandlers=[];decrqssHandlers=[];dcsHandlers=[];oscHandlers=[];pasteHandlers=[];sgrMouseHandlers=[];mouseHandlers=[];focusHandlers=[];resizeHandlers=[];escapeTimeout=null;ESCAPE_TIMEOUT_MS=25;pendingEscape=!1;sgrToMouseConverter=om;inPaste=!1;pasteBuffer="";constructor(){this.lexer=new Ju,this.lexer.onEvent(this.handleLexicalEvent.bind(this))}onEvent(J){this.lexer.onEvent(J)}offEvent(J){this.lexer.offEvent(J)}onKey(J){this.keyHandlers.push(J)}offKey(J){let Q=this.keyHandlers.indexOf(J);if(Q!==-1)this.keyHandlers.splice(Q,1)}onDeviceAttributes(J){this.deviceAttributesHandlers.push(J)}onDecrqss(J){this.decrqssHandlers.push(J)}onDcs(J){this.dcsHandlers.push(J)}onOsc(J){this.oscHandlers.push(J)}onPaste(J){this.pasteHandlers.push(J)}onSgrMouse(J){this.sgrMouseHandlers.push(J)}onMouse(J){this.mouseHandlers.push(J)}onFocus(J){this.focusHandlers.push(J)}onResize(J){this.resizeHandlers.push(J)}setSgrToMouseConverter(J){this.sgrToMouseConverter=J}parse(J){if(this.isStandaloneEscape(J)){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.scheduleEscapeTimeout(),this.lexer.parse(J);return}if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null,this.pendingEscape=!1;this.lexer.parse(J)}isStandaloneEscape(J){if(typeof J==="string")return J.length===1&&J.charCodeAt(0)===27;else return J.length===1&&J[0]===27}scheduleEscapeTimeout(){this.pendingEscape=!0,this.escapeTimeout=setTimeout(()=>{this.pendingEscape=!1,this.lexer.reset();let J={type:"key",key:"Escape",shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(J),this.escapeTimeout=null},this.ESCAPE_TIMEOUT_MS)}clearEscapeTimeout(){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.pendingEscape=!1}flush(){this.lexer.flush()}reset(){this.clearEscapeTimeout(),this.lexer.reset()}handleLexicalEvent(J){switch(J.type){case"print":this.handlePrintEvent(J);break;case"execute":this.handleExecuteEvent(J);break;case"csi":this.handleCsiEvent(J);break;case"dcs":this.handleDcsEvent(J);break;case"osc":this.handleOscEvent(J);break;case"escape":this.handleEscapeEvent(J);break}}handlePrintEvent(J){if(this.inPaste){this.pasteBuffer+=J.grapheme;return}if(this.pendingEscape){this.clearEscapeTimeout();let Z={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Z);return}let Q={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Q)}handleExecuteEvent(J){if(this.inPaste)switch(J.code){case 10:this.pasteBuffer+=`
5445
5445
  `;return;case 13:this.pasteBuffer+="\r";return;case 9:this.pasteBuffer+="\t";return}if(J.code===10){let Z={type:"key",key:"Enter",shiftKey:!0,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Z);return}let Q=this.controlCharacterToGrapheme(J.code);if(Q){let Z={type:"key",key:Q,shiftKey:!1,ctrlKey:this.isControlCharacter(J.code)&&J.code!==127&&J.code!==8&&J.code!==9&&J.code!==10&&J.code!==13&&J.code!==27,altKey:!1,metaKey:!1};this.emitKeyEvent(Z)}}controlCharacterToGrapheme(J){switch(J){case 8:return"Backspace";case 9:return"Tab";case 10:return"Enter";case 13:return"Enter";case 27:return"Escape";case 127:return"Backspace";case 0:return"@";case 1:return"a";case 2:return"b";case 3:return"c";case 4:return"d";case 5:return"e";case 6:return"f";case 7:return"g";case 11:return"k";case 12:return"l";case 14:return"n";case 15:return"o";case 16:return"p";case 17:return"q";case 18:return"r";case 19:return"s";case 20:return"t";case 21:return"u";case 22:return"v";case 23:return"w";case 24:return"x";case 25:return"y";case 26:return"z";default:return null}}isControlCharacter(J){return J>=0&&J<=26||J===27||J===127}handleEscapeEvent(J){this.clearEscapeTimeout();let Q=this.escapeToKey(J);if(Q)this.emitKeyEvent(Q)}handleDcsEvent(J){for(let Q of this.dcsHandlers)Q(J)}handleOscEvent(J){for(let Q of this.oscHandlers)Q(J)}handleCsiEvent(J){if(this.clearEscapeTimeout(),this.handleBracketedPaste(J))return;let Q=this.csiToFocus(J);if(Q){this.emitFocusEvent(Q);return}let Z=this.csiToDeviceAttributes(J);if(Z){this.emitDeviceAttributesEvent(Z);return}let X=this.csiToDecrqss(J);if(X){this.emitDecrqssEvent(X);return}let Y=this.csiToKittyKeyboardResponse(J);if(Y){this.emitDecrqssEvent(Y);return}let K=this.csiToInBandResize(J);if(K){this.emitResizeEvent(K);return}let q=this.csiToSgrMouse(J);if(q){this.emitSgrMouseEvent(q);let z=this.sgrToMouseConverter(q);this.emitMouseEvent(z);return}let G=this.csiToKey(J);if(G)this.emitKeyEvent(G)}escapeToKey(J){if(J.intermediates==="O"){if(J.final==="P")return this.createKeyEvent("F1");if(J.final==="Q")return this.createKeyEvent("F2");if(J.final==="R")return this.createKeyEvent("F3");if(J.final==="S")return this.createKeyEvent("F4")}if(J.intermediates===""&&J.final.length===1){let Q=J.final.charCodeAt(0);if(Q>=32&&Q<=126)return{type:"key",key:J.final,shiftKey:this.isShifted(J.final),ctrlKey:!1,altKey:!0,metaKey:!1};else if(Q==127)return{type:"key",key:"Backspace",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1}}return null}csiToKey(J){let{final:Q,params:Z}=J;if(Z.length===0||Z.length===1&&Z[0]?.value===0)Z=[{value:1}];let X=null,Y={shift:!1,ctrl:!1,alt:!1,meta:!1},K=1,q="";if(Z.length>=1){let G=Z[0]?.value??1;if(G===1&&Q==="Z")X="Tab",Y.shift=!0;else X=this.getSpecialKey(G,Q)??this.unicodeToKey(G)}if(Z.length>=2){let G=Z[1]?.value??1;Y=this.parseModifiers(G)}if(Z.length>=3){let G=Z[2]?.value??1;if(Q==="u")K=G-1;else if(Q==="~"&&Z[0]?.value===27)X=this.unicodeToKey(G)}if(K!==1&&K!==0)return null;if(!X)return null;if(q===""&&Y.shift&&!Y.ctrl&&!Y.alt&&!Y.meta){let G=this.keyToUnicode(X);if(G&&G>=32&&G<=126)q=X.toUpperCase()}return this.createKeyEventWithModifiers(X,Y,q)}parseModifiers(J){if(J===0||J===1)return{shift:!1,ctrl:!1,alt:!1,meta:!1};let Q=J-1;return{shift:(Q&1)!==0,alt:(Q&2)!==0,ctrl:(Q&4)!==0,meta:(Q&8)!==0}}unicodeToKey(J){if(J===13)return"Enter";if(J===9)return"Tab";if(J===27)return"Escape";if(J===127)return"Backspace";if(J===32)return" ";if(J>=1&&J<=26)return String.fromCharCode(J+96);if(oQ6[J])return oQ6[J];if(J>=32&&J<=126)return String.fromCharCode(J);if(J>126)try{return String.fromCharCode(J)}catch{return null}return null}createKeyEvent(J){return{type:"key",key:J,shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1}}createKeyEventWithModifiers(J,Q,Z){return{type:"key",key:J,shiftKey:Q.shift,ctrlKey:Q.ctrl,altKey:Q.alt,metaKey:Q.meta}}static SPECIAL_KEYS=new Map([["1:A","ArrowUp"],["1:B","ArrowDown"],["1:C","ArrowRight"],["1:D","ArrowLeft"],["1:H","Home"],["1:F","End"],["1:P","F1"],["1:Q","F2"],["1:R","F3"],["1:S","F4"],["1:~","Home"],["2:~","Insert"],["3:~","Delete"],["4:~","End"],["5:~","PageUp"],["6:~","PageDown"],["7:~","Home"],["8:~","End"],["9:~","Tab"],["11:~","F1"],["12:~","F2"],["13:~","F3"],["14:~","F4"],["15:~","F5"],["17:~","F6"],["18:~","F7"],["19:~","F8"],["20:~","F9"],["21:~","F10"],["23:~","F11"],["24:~","F12"]]);getSpecialKey(J,Q){let Z=`${J}:${Q}`;return Qu.SPECIAL_KEYS.get(Z)||null}keyToUnicode(J){if(J.length===1)return J.charCodeAt(0);switch(J){case"Enter":return 13;case"Tab":return 9;case"Escape":return 27;case"Backspace":return 127;case" ":return 32}return null}isShifted(J){return J!==J.toLowerCase()}emitKeyEvent(J){for(let Q of this.keyHandlers)Q(J)}csiToDeviceAttributes(J){if(J.final==="c"&&J.private==="?"){let Q=0,Z=[];if(J.params.length>0){Q=J.params[0]?.value||0;let X=J.params.slice(1);if(X.length>0&&X[X.length-1]?.value===0)X=X.slice(0,-1);Z=X.map((Y)=>Y.value)}return{type:"device_attributes_primary",primary:Q,secondary:Z}}return null}csiToDecrqss(J){if(J.final==="y"&&J.intermediates.includes("$")){if(J.params.length>=2){let Q=`?${J.params[0]?.value||0}`,Z=String(J.params[1]?.value||0);return{type:"decrqss_response",request:Q,response:Z}}}return null}csiToKittyKeyboardResponse(J){if(J.final==="u"&&J.private==="?"){if(J.params.length>=1)return{type:"decrqss_response",request:"u",response:(J.params[0]?.value||0)>0?"1":"0"}}return null}emitDeviceAttributesEvent(J){for(let Q of this.deviceAttributesHandlers)Q(J)}csiToSgrMouse(J){if((J.final==="M"||J.final==="m")&&J.private==="<"){if(J.params.length>=3){let Q=J.params[0]?.value||0,Z=J.params[1]?.value||1,X=J.params[2]?.value||1,Y=Q&-61,K=J.final==="M"&&Y!==3;return{type:"sgr_mouse",button:Q,x:Z,y:X,pressed:K}}}return null}emitDecrqssEvent(J){for(let Q of this.decrqssHandlers)Q(J)}emitSgrMouseEvent(J){for(let Q of this.sgrMouseHandlers)Q(J)}emitMouseEvent(J){for(let Q of this.mouseHandlers)Q(J)}csiToFocus(J){if(J.intermediates===""&&(J.final==="I"||J.final==="O"))return{type:"focus",focused:J.final==="I"};return null}csiToInBandResize(J){if(J.final==="t"&&J.params.length>=5&&J.params[0]?.value===48){let Q=J.params[1]?.value||0,Z=J.params[2]?.value||0,X=J.params[3]?.value||0,Y=J.params[4]?.value||0;return{type:"resize",width:Z,height:Q,pixelWidth:Y,pixelHeight:X}}return null}emitFocusEvent(J){for(let Q of this.focusHandlers)Q(J)}emitResizeEvent(J){for(let Q of this.resizeHandlers)Q(J)}handleBracketedPaste(J){if(J.final==="~"&&J.params.length===1){let Q=J.params[0]?.value;if(Q===200)return this.inPaste=!0,this.pasteBuffer="",!0;else if(Q===201){if(this.inPaste)this.inPaste=!1,this.emitPasteEvent({type:"paste",text:this.pasteBuffer}),this.pasteBuffer="";return!0}}return!1}emitPasteEvent(J){for(let Q of this.pasteHandlers)Q(J)}}});var Cx1=p(()=>{tQ6();Px1();rQ6()});function n49(J){return J.replace(/\r\n|\r/g,`
5446
5446
  `)}function a49(J){return J.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function eQ6(J){let Q=J;return Q=n49(Q),Q=a49(Q),Q}class Sx1{parts=[];append(...J){this.parts.push(...J)}toString(){return this.parts.join("")}reset(){this.parts.length=0}get length(){return this.parts.length}get isEmpty(){return this.parts.length===0}}function Y79(J,Q,Z){let X=`${J},${Q},${Z}`,Y=XZ6.get(X);if(Y!==void 0)return Y;let K=16,q=1/0;for(let G=0;G<ZZ6.length;G++){let[z,U,W]=ZZ6[G],F=(J-z)**2+(Q-U)**2+(Z-W)**2;if(F<q)q=F,K=G+16}return XZ6.set(X,K),K}function O79(J){return G79+(J?U79:"")}function j79(){return z79+W79}function kx1(J){return L79(J)}function UZ6(){return qZ6}function _x1(){return GZ6}function WZ6(){return zZ6}function YZ6(J,Q,Z){if(!J)return"";switch(J.type){case"default":return O8+(Q?"39":"49")+"m";case"index":return O8+`${Q?"38":"48"};5;${J.value}m`;case"rgb":{if(Z&&!Z.canRgb){let{r:G,g:z,b:U}=J.value,W=Y79(G,z,U);return O8+`${Q?"38":"48"};5;${W}m`}let X=Q?"38":"48",{r:Y,g:K,b:q}=J.value;return O8+`${X};2;${Y};${K};${q}m`}default:return""}}function R79(J,Q,Z){let X="";if(J.fg!==Q.fg){if(J.fg===void 0&&Q.fg!==void 0)X+=O8+"39m";else X+=YZ6(J.fg,!0,Z);Q.fg=J.fg}if(J.bg!==Q.bg){if(J.bg===void 0&&Q.bg!==void 0)X+=O8+"49m";else X+=YZ6(J.bg,!1,Z);Q.bg=J.bg}if(J.bold!==Q.bold)X+=J.bold?O8+"1m":O8+"22m",Q.bold=J.bold;if(J.italic!==Q.italic)X+=J.italic?O8+"3m":O8+"23m",Q.italic=J.italic;if(J.underline!==Q.underline)X+=J.underline?O8+"4m":O8+"24m",Q.underline=J.underline;if(J.strikethrough!==Q.strikethrough)X+=J.strikethrough?O8+"9m":O8+"29m",Q.strikethrough=J.strikethrough;if(J.reverse!==Q.reverse)X+=J.reverse?O8+"7m":O8+"27m",Q.reverse=J.reverse;if(J.dim!==Q.dim)X+=J.dim?O8+"2m":O8+"22m",Q.dim=J.dim;return X}function w79(J,Q){let Z="";if(!i41(J,Q.hyperlink)){if(Q.hyperlink)Z+=n41();if(J)Z+=iQ6(J);Q.hyperlink=J}return Z}function KZ6(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;if(J.type!==Q.type)return!1;switch(J.type){case"default":return!0;case"index":return Q.value===J.value;case"rgb":{let Z=Q.value;return Z.r===J.value.r&&Z.g===J.value.g&&Z.b===J.value.b}default:return!1}}function I79(J,Q){return KZ6(J.fg,Q.fg)&&KZ6(J.bg,Q.bg)&&J.bold===Q.bold&&J.italic===Q.italic&&J.underline===Q.underline&&J.strikethrough===Q.strikethrough&&J.reverse===Q.reverse&&J.dim===Q.dim}class bx1{capabilities;currentStyle={};currentX=0;currentY=0;constructor(J){this.capabilities=J}updateCapabilities(J){this.capabilities=J}render(J){if(J.length===0)return"";let Q=this.batchDiffs(J),Z=new Sx1;for(let X of Q){if(this.currentX!==X.x||this.currentY!==X.y)Z.append(QZ6(X.y,X.x)),this.currentX=X.x,this.currentY=X.y;Z.append(R79(X.style,this.currentStyle,this.capabilities)),Z.append(w79(X.hyperlink,this.currentStyle)),Z.append(X.chars.join("")),this.currentX+=X.totalWidth}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},JZ6+n41()+e49+s49}hideCursor(){return o49}showCursor(){return t49}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return A79(J)}reset(){return this.currentStyle={},JZ6+n41()}moveTo(J,Q){return this.currentX=J,this.currentY=Q,QZ6(Q,J)}batchDiffs(J){if(J.length===0)return[];let Q=[],Z=null;for(let X of J)if(Z&&Z.y===X.y&&Z.x+Z.totalWidth===X.x&&I79(Z.style,X.cell.style)&&i41(Z.hyperlink,X.cell.hyperlink)){let K=X.cell.char==="\t"?" ".repeat(tm):X.cell.char;Z.chars.push(K),Z.totalWidth+=X.cell.width}else{let K=X.cell.char==="\t"?" ".repeat(tm):X.cell.char;Z={x:X.x,y:X.y,chars:[K],style:X.cell.style,hyperlink:X.cell.hyperlink,totalWidth:X.cell.width},Q.push(Z)}return Q}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return J79}endSync(){return Q79}enterAltScreen(){return K79}exitAltScreen(){return q79}resetCursor(){return r49}enableMouse(J=!1){return O79(J)}disableMouse(){return j79()}enableEmojiWidth(){return F79}disableEmojiWidth(){return H79}enableInBandResize(){return B79}disableInBandResize(){return D79}enableBracketedPaste(){return Z79}disableBracketedPaste(){return X79}enableKittyKeyboard(){return M79}disableKittyKeyboard(){return V79}setMouseShape(J){return N79(J)}setProgressBarIndeterminate(){return qZ6}setProgressBarOff(){return GZ6}setProgressBarPaused(){return zZ6}}var $H="\x1B",O8="\x1B[",JZ6,r49,QZ6=(J,Q)=>O8+`${J+1};${Q+1}H`,s49,o49,t49,e49,J79,Q79,Z79,X79,ZZ6,XZ6,K79,q79,G79,z79,U79,W79,F79,H79,B79,D79,M79,V79,N79=(J)=>$H+`]22;${J}`+$H+"\\",L79=(J)=>$H+`]0;${J}\x07`,qZ6,GZ6,zZ6,A79=(J)=>O8+`${J} q`,vx1;var Zu=p(()=>{z9();JZ6=O8+"0m",r49=O8+"m",s49=O8+"H",o49=O8+"?25l",t49=O8+"?25h",e49=O8+"2J",J79=O8+"?2026h",Q79=O8+"?2026l",Z79=O8+"?2004h",X79=O8+"?2004l",ZZ6=[...Array.from({length:216},(J,Q)=>{let Z=Math.floor(Q/36),X=Math.floor(Q%36/6),Y=Q%6,K=(q)=>q===0?0:55+q*40;return[K(Z),K(X),K(Y)]}),...Array.from({length:24},(J,Q)=>{let Z=8+Q*10;return[Z,Z,Z]})],XZ6=new Map;K79=O8+"?1049h",q79=O8+"?1049l",G79=O8+"?1002h"+O8+"?1003h"+O8+"?1004h"+O8+"?1006h",z79=O8+"?1002l"+O8+"?1003l"+O8+"?1004l"+O8+"?1006l",U79=O8+"?1016h",W79=O8+"?1016l",F79=O8+"?2027h",H79=O8+"?2027l",B79=O8+"?2048h",D79=O8+"?2048l",M79=O8+">1u",V79=O8+"<u",qZ6=$H+"]9;4;3"+$H+"\\",GZ6=$H+"]9;4;0"+$H+"\\",zZ6=$H+"]9;4;4"+$H+"\\",vx1={DEFAULT:0,BLINKING_BLOCK:1,STEADY_BLOCK:2,BLINKING_UNDERLINE:3,STEADY_UNDERLINE:4,BLINKING_BAR:5,STEADY_BAR:6}});function xx1(){let J=E79();if(J)return J;let Q=$79();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function E79(){try{let J=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),X=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),Y=J.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),K=process.platform==="darwin"?1074295912:21523,q=new X;if(Y.ioctl(process.stdout.fd,K,q.ref())===0)return{rows:q.ws_row,columns:q.ws_col,pixelWidth:q.ws_xpixel,pixelHeight:q.ws_ypixel};return null}catch(J){return null}}function $79(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let J=process.stdin;if(process.stdin.isTTY&&J.columns&&J.rows)return{columns:J.columns,rows:J.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let Z=Q.getWindowSize();if(Z[0]>0&&Z[1]>0)return{columns:Z[0],rows:Z[1]}}return null}catch(J){return null}}class a41{capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,scrollStep:()=>this.getScrollStep()};complete=!1;inbandPixelData=null;processDecrqss(J,Q){if(J==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(J==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(J==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(J==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(J,Q){if(this.checkPixelDimensions(),this.detectJetBrains())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(J){return this.capabilities.xtversion=J,!1}processXtgettcap(J,Q){if(J.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}updateInbandPixelData(J,Q,Z,X){if(Z&&X&&Z>0&&X>0)this.inbandPixelData={pixelWidth:Z,pixelHeight:X,columns:J,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let J=xx1();this.capabilities.pixelDimensions=!!(J&&J.pixelWidth>0&&J.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let J=xx1();if(J&&J.pixelWidth>0&&J.pixelHeight>0)return{pixelWidth:J.pixelWidth,pixelHeight:J.pixelHeight,columns:J.columns,rows:J.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.detectEmacs())return"disabled";if(this.detectSSH()||this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(LG())return 1;return 3}}var FZ6;var yx1=p(()=>{FZ6=[{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}]});class HZ6{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(J){this.onEmitEvent=J}handleWheelEvent(J){if(J.button!=="wheel_up"&&J.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>T79)this.filterDirection=null;else return this.lastEventTime=Q,J.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(J),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},P79);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class fx1{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;stdin=process.stdin;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;constructor(){this.screen=new em(80,24),this.renderer=new bx1,this.jetBrainsWheelFilter=new HZ6((J)=>{for(let Q of this.mouseHandlers)Q(J)})}setStdin(J){if(this.initialized)throw Error("Cannot change stdin after TUI is initialized");this.stdin=J}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(gT(this.stdin))this.stdin.setRawMode(!0);else if(process.env.AMP_DEBUG)a.warn("Warning: stdin is not a TTY or using custom stdin");this.parser=new Qu,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new a41,this.parser.onDeviceAttributes((J)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(J.primary,J.secondary))this.finishInitialization()}}),this.parser.onDecrqss((J)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(J.request,J.response)}),this.parser.onDcs((J)=>{if(this.queryParser&&this.initialized){if(J.final==="|"&&J.private===">")this.queryParser.processXtversion(J.data);if(J.final==="r"&&J.intermediates==="+"&&J.params.length>0&&J.params[0]?.value===1)this.parseXtgettcapResponse(J.data)}}),this.parser.onMouse((J)=>{if(LG()&&!this.jetBrainsWheelFilter.handleWheelEvent(J))return;for(let Q of this.mouseHandlers)Q(J)}),this.parser.onFocus((J)=>{for(let Q of this.focusHandlers)Q(J)}),this.parser.onResize((J)=>{this.handleInbandResize(J)}),this.stdin.on("data",(J)=>{this.parser?.parse(J)}),this.stdin.resume(),process.on("SIGWINCH",this.boundHandleResize),this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(J){throw this.deinit(),J}}deinit(){if(this.initialized){let J="";if(J+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+this.renderer.disableKittyKeyboard()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.xtversion?.startsWith("ghostty"))J+=this.renderer.setProgressBarOff();if(this.inAltScreen)J+=this.renderer.exitAltScreen(),this.inAltScreen=!1;process.stdout.write(J)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;if(this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.stdin.removeAllListeners("data"),this.stdin.pause(),gT(this.stdin))try{this.stdin.setRawMode(!1)}catch(J){}this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}onKey(J){this.keyHandlers.push(J)}offKey(J){let Q=this.keyHandlers.indexOf(J);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(J){this.mouseHandlers.push(J)}offMouse(J){let Q=this.mouseHandlers.indexOf(J);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(J){this.resizeHandlers.push(J)}offResize(J){let Q=this.resizeHandlers.indexOf(J);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(J){this.focusHandlers.push(J)}offFocus(J){let Q=this.focusHandlers.indexOf(J);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(J){this.pasteHandlers.push(J)}offPaste(J){let Q=this.pasteHandlers.indexOf(J);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(J){this.capabilityHandlers.push(J)}offCapabilities(J){let Q=this.capabilityHandlers.indexOf(J);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}async waitForCapabilities(J=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let J=this.screen.getDiff(),Q=this.screen.getCursor();if(J.length>0||Q!==null){let X="";X+=this.renderer.startSync(),X+=this.renderer.hideCursor(),X+=this.renderer.reset(),X+=this.renderer.moveTo(0,0);let Y=this.renderer.render(J);if(X+=Y,Q&&this.screen.isCursorVisible())X+=this.renderer.moveTo(Q.x,Q.y),X+=this.renderer.setCursorShape(this.screen.getCursorShape()),X+=this.renderer.showCursor();else X+=this.renderer.hideCursor();X+=this.renderer.endSync(),process.stdout.write(X),this.screen.present()}}clearScreen(){let J=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(J),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(J,Q){this.screen.setCursor(J,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(J){this.screen.setCursorShape(J)}setMouseCursor(J){let Q=`\x1B]22;${J}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(j5.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(){process.stdout.write(this.renderer.enableKittyKeyboard())}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}async writeClipboard(J){return OG.writeText(J)}get clipboard(){return OG}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let J=this.queryParser?.shouldUsePixelMouse()??!1,Q=this.renderer.enableMouse(J);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let J=this.renderer.enableEmojiWidth();process.stdout.write(J)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let J=this.renderer.enableInBandResize();process.stdout.write(J)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}setMouseShape(J){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(J))}suspend(){if(!this.initialized||this.suspended)return;if(this.disableMouse(),this.disableEmojiWidth(),this.disableInBandResize(),this.disableBracketedPaste(),this.disableKittyKeyboard(),this.exitAltScreen(),this.stdin.pause(),gT(this.stdin))this.stdin.setRawMode(!1);if(this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(gT(this.stdin))this.stdin.setRawMode(!0);if(this.stdin.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),a.debug(`Successfully suspended process ${process.pid}`)}catch(J){a.debug(`Failed to suspend process ${process.pid}: ${J}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!gT(this.stdin)){this.terminalSize={width:80,height:24};return}try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows){this.terminalSize={width:process.stdout.columns,height:process.stdout.rows};return}let J=process.stdout.getWindowSize();if(J[0]>0&&J[1]>0){this.terminalSize={width:J[0],height:J[1]};return}}catch(J){}}handleKeyEvent(J){for(let Q of this.keyHandlers)Q(J)}handlePasteEvent(J){let Q={type:"paste",text:eQ6(J.text)};for(let Z of this.pasteHandlers)Z(Q)}handleOscEvent(J){if(J.data.startsWith("52;c;")){let Q=J.data.slice(5);if(Q&&Q!=="?")OG.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((J)=>{this.capabilityResolve=J})}startCapabilityDetection(){if(!gT(this.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new a41,process.env.TERM_PROGRAM==="Apple_Terminal"){let J={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!1,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3};this.capabilities=J;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Z of this.capabilityHandlers)Z(Q);if(this.capabilityResolve)this.capabilityResolve(J),this.capabilityResolve=null;return}for(let J of FZ6)process.stdout.write(J.sequence);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}finishInitialization(){if(!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let J={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Q of this.capabilityHandlers)Q(J);if(this.capabilityResolve)a.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let Z=Q.pixelWidth/Q.columns,X=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((Y)=>om(Y,!0,Z,X))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),OG.setCapabilities(this.capabilities)}parseXtgettcapResponse(J){if(!this.queryParser)return;let Q=J.indexOf("=");if(Q!==-1){let Z=J.slice(0,Q),X=J.slice(Q+1);if(this.queryParser.processXtgettcap(Z,X))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(J){if(this.terminalSize={width:J.width,height:J.height},this.queryParser&&J.pixelWidth&&J.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(J.width,J.height,J.pixelWidth,J.pixelHeight);let Z=this.queryParser.shouldUsePixelMouse();if(!Q&&Z)this.disableMouse(),this.enableMouse();if(Z){let X=J.pixelWidth/J.width,Y=J.pixelHeight/J.height;this.parser?.setSgrToMouseConverter((K)=>om(K,!0,X,Y))}}this.screen.resize(J.width,J.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){a.error("Error in resize handler:",Z)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let J={...this.terminalSize};if(this.updateTerminalSize(),J.width===this.terminalSize.width&&J.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let J={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){a.error("Error in resize handler:",Z)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundCleanup),process.on("SIGCONT",this.boundHandleResume)}cleanup(){try{this.deinit()}catch{}}}function gT(J){return"isTTY"in J&&J.isTTY===!0&&typeof J.setRawMode==="function"}var P79=50,T79=200;var BZ6=p(()=>{D0();yT();fT();Cx1();Zu();z9();yx1()});function DZ6(){try{if(process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1016l"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?2031l"),process.stdout.write("\x1B[?2048l"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[0 q"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[999;1H"),process.stdout.write("\x1B[0m"),!process.env.TERM_PROGRAM?.startsWith("iTerm"))process.stdout.write("\x1B]9;4;0\x1B\\")}catch(J){}}function q8(J,...Q){if(!J){let Z=Q.join(" "),X=Error(Z);a.error("TUI Assert failed",{assertion:Z,stackTrace:X.stack,meta:Q});let Y=process.env.AMP_DEBUG,K=process.env.VITEST;if(Y||K)DZ6(),console.error("FATAL TUI ERROR:",Z),console.error("Stack trace:",X.stack),console.error("Context:",{meta:Q}),process.exit(1)}}var I4=p(()=>{D0()});class XZ{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_lastFrameTime=0;TARGET_FPS=60;FRAME_TIME=1000/this.TARGET_FPS;_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return this._instance??=new XZ}requestFrame(){if(this._frameScheduled)return;this._frameScheduled=!0;let Q=performance.now()-this._lastFrameTime;if(Q>=this.FRAME_TIME)setImmediate(()=>this.executeFrame());else{let Z=this.FRAME_TIME-Q;setTimeout(()=>this.executeFrame(),Z)}}addFrameCallback(J,Q,Z,X=0,Y){this._frameCallbacks.set(J,{callback:Q,phase:Z,priority:X,name:Y||J})}removeFrameCallback(J){this._frameCallbacks.delete(J)}addPostFrameCallback(J,Q){if(this._postFrameCallbacks.push({callback:J,name:Q}),!this._frameScheduled&&!this._frameInProgress)this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let J=performance.now();this._frameScheduled=!1,this._frameInProgress=!0,this._lastFrameTime=J;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){a.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{this.recordFrameStats(performance.now()-J),this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1}}executePhase(J){let Q=performance.now();try{let Z=Array.from(this._frameCallbacks.values()).filter((X)=>X.phase===J).sort((X,Y)=>X.priority-Y.priority);for(let X of Z)try{X.callback()}catch(Y){a.error(`Frame callback error in ${J} phase (${X.name})`,{errorMessage:Y instanceof Error?Y.message:String(Y),errorType:Y?.constructor?.name,stackTrace:Y instanceof Error?Y.stack:void 0}),q8(!1,`FATAL: ${J} error in ${X.name}: ${Y}`)}}finally{let Z=performance.now()-Q;this.recordPhaseStats(J,Z)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let J=this._postFrameCallbacks.splice(0);for(let{callback:Q,name:Z}of J)try{Q()}catch(X){a.error(`Post-frame callback error (${Z||"anonymous"}):`,X instanceof Error?X.message:String(X))}}recordFrameStats(J){this._stats.lastFrameTime=J}recordPhaseStats(J,Q){this._stats.phaseStats[J].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(J){return{...J,phaseStats:{["build"]:{...J.phaseStats.build},["layout"]:{...J.phaseStats.layout},["paint"]:{...J.phaseStats.paint},["render"]:{...J.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}dispose(){this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this.resetStats()}}var Xu,C79=60,hx1;var TO=p(()=>{D0();I4();((Y)=>{Y.BUILD="build";Y.LAYOUT="layout";Y.PAINT="paint";Y.RENDER="render"})(Xu||={});hx1=1000/C79});class gx1{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(J){if(this._dirtyElements.has(J))return;this._dirtyElements.add(J),XZ.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let J=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let Z=Array.from(this._dirtyElements);this._dirtyElements.clear(),Z.sort((X,Y)=>X.depth-Y.depth);for(let X of Z)if(X.dirty)try{X.performRebuild(),X._dirty=!1,Q++}catch(Y){a.error("Element rebuild error:",Y instanceof Error?Y.message:String(Y)),X._dirty=!1}}}finally{this.recordBuildStats(performance.now()-J,Q)}}recordBuildStats(J,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=J,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,J),this._buildTimes.push(J),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((Z,X)=>Z+X,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((Z,X)=>Z+X,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}var MZ6=p(()=>{D0();TO()});function VZ6(J,Q){mx1=J,ux1=Q}function NZ6(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function LZ6(){if(!mx1){if(NZ6())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return mx1}function r41(){if(!ux1){if(NZ6())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return ux1}var mx1=null,ux1=null;class O2{_parent=null;_children=new Set;_hasFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_focusChangeListeners=new Set;_debugLabel=null;static _requestFocusCallback=null;constructor(J={}){if(this._debugLabel=J.debugLabel??null,this._canRequestFocus=J.canRequestFocus??!0,this._skipTraversal=J.skipTraversal??!1,J.onKey)this._keyHandlers.push(J.onKey);this._onPasteCallback=J.onPaste??null}get hasFocus(){return this._hasFocus}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(J){if(this._canRequestFocus!==J){if(this._canRequestFocus=J,!J&&this._hasFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(J){this._skipTraversal=J}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(J){this._onPasteCallback=J}static setRequestFocusCallback(J){O2._requestFocusCallback=J}requestFocus(){if(!this._canRequestFocus)return!1;if(O2._requestFocusCallback)return O2._requestFocusCallback(this);return!1}unfocus(){if(this._hasFocus){if(O2._requestFocusCallback)O2._requestFocusCallback(null)}}_attach(J){if(this._parent===J)return;if(this._parent)this._parent._children.delete(this);if(this._parent=J,J)J._children.add(this);if(O2._requestFocusCallback){let Q=O2._requestFocusCallback.__focusManager;if(Q&&Q._invalidateFocusableNodesCache)Q._invalidateFocusableNodesCache()}}_detach(){if(this._parent)this._parent._children.delete(this),this._parent=null;if(O2._requestFocusCallback){let J=O2._requestFocusCallback.__focusManager;if(J&&J._invalidateFocusableNodesCache)J._invalidateFocusableNodesCache()}if(this._hasFocus)this.unfocus()}_setFocus(J){if(this._hasFocus===J)return;this._hasFocus=J,this._notifyListeners()}addFocusChangeListener(J){this._focusChangeListeners.add(J)}removeFocusChangeListener(J){this._focusChangeListeners.delete(J)}_notifyListeners(){for(let J of this._focusChangeListeners)J(this._hasFocus)}_handleKeyEvent(J){return this.handleKeyEvent(J)}_handlePasteEvent(J){if(this._onPasteCallback)return this._onPasteCallback(J);return"ignored"}toStringShort(){let J=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasFocus?" FOCUSED":"",Z=this._canRequestFocus?"":" (can't focus)";return`FocusNode${J}${Q}${Z}`}toStringDeep(J="",Q=!0){let Z=J+this.toStringShort();if(Q&&this._children.size>0){let X=J+" ";for(let Y of this._children)Z+=`
5447
- `+Y.toStringDeep(X,!0)}return Z}addKeyHandler(J){this._keyHandlers.push(J)}removeKeyHandler(J){let Q=this._keyHandlers.indexOf(J);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(J){for(let Q of this._keyHandlers)if(Q(J)==="handled")return"handled";return"ignored"}dispose(){this._detach(),this._children.clear(),this._keyHandlers=[]}}var CU=()=>{};class PV{static _instance=null;_rootScope;_primaryFocus=null;_cachedFocusableNodes=null;constructor(){this._rootScope=new O2({debugLabel:"Root Focus Scope",canRequestFocus:!1});let J=(Q)=>this.requestFocus(Q);J.__focusManager=this,O2.setRequestFocusCallback(J)}static get instance(){if(!this._instance)this._instance=new PV;return this._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(J){if(this._primaryFocus===J)return!0;if(J&&!J.canRequestFocus)return!1;if(this._primaryFocus)this._primaryFocus._setFocus(!1);if(this._primaryFocus=J,J)J._setFocus(!0);return!0}handleKeyEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handleKeyEvent(J)==="handled")return!0;Q=Q.parent}return!1}handlePasteEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(J)==="handled")return!0;Q=Q.parent}return!1}registerNode(J,Q=null){this._invalidateFocusableNodesCache();let Z=Q??this._rootScope;J._attach(Z)}unregisterNode(J){if(this._invalidateFocusableNodesCache(),this._primaryFocus===J)this.requestFocus(null);J._detach()}findNearestFocusableAncestor(J){let Q=J.parent;while(Q){if(Q.canRequestFocus&&!Q.skipTraversal)return Q;Q=Q.parent}return null}findAllFocusableNodes(){if(this._cachedFocusableNodes!==null)return this._cachedFocusableNodes;let J=[],Q=(Z)=>{if(Z.canRequestFocus&&!Z.skipTraversal)J.push(Z);for(let X of Z.children)Q(X)};return Q(this._rootScope),this._cachedFocusableNodes=J,J}_invalidateFocusableNodesCache(){this._cachedFocusableNodes=null}focusNext(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[0]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[0]??null);let Z=(Q+1)%J.length;return this.requestFocus(J[Z]??null)}focusPrevious(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[J.length-1]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[J.length-1]??null);let Z=Q===0?J.length-1:Q-1;return this.requestFocus(J[Z]??null)}dispose(){this._primaryFocus=null,this._cachedFocusableNodes=null,this._rootScope.dispose(),PV._instance=null}}var px1=p(()=>{CU()});function s41(J){if(J.length===0)return 0;let Q=[...J].sort((X,Y)=>X-Y),Z=Math.ceil(Q.length*0.99)-1;return Q[Math.max(0,Z)]||0}class AZ6{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];lastKeyEventTime=0;lastMouseEventTime=0;MAX_SAMPLES=1024;recordFrame(J){if(this.frameTimes.push(J),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(J,Q){let Z=this.phaseTimes[J];if(Z.push(Q),Z.length>this.MAX_SAMPLES)Z.shift()}recordKeyEvent(J){if(this.lastKeyEventTime=J,this.keyEventTimes.push(J),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(J){if(this.lastMouseEventTime=J,this.mouseEventTimes.push(J),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}getFrameP99(){return s41(this.frameTimes)}getPhaseP99(J){return s41(this.phaseTimes[J])}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return s41(this.keyEventTimes)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return s41(this.mouseEventTimes)}reset(){this.frameTimes=[];for(let J of Object.values(Xu))this.phaseTimes[J]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0}}class dx1{enabled=!1;tracker=new AZ6;setEnabled(J){this.enabled=J}isEnabled(){return this.enabled}recordKeyEvent(J){this.tracker.recordKeyEvent(J)}recordMouseEvent(J){this.tracker.recordMouseEvent(J)}recordStats(J){this.tracker.recordFrame(J.lastFrameTime);for(let Q of Object.values(Xu))this.tracker.recordPhase(Q,J.phaseStats[Q].lastTime)}draw(J,Q){if(!this.enabled)return;let{width:Z,height:X}=J.getSize(),Y=26,K=12,q=Z-Y-2,G=1;if(q<0||G+K>=X)return;let z=d1.white,U=d1.brightWhite,W=d1.yellow,F=" Gotta Go Fast ",H=Math.floor((Y-F.length)/2);J.setCell(q,G,m9("╭",{fg:U}));for(let b=1;b<Y-1;b++)if(b>=H&&b<H+F.length)J.setCell(q+b,G,m9(F[b-H]||"─",{fg:W}));else J.setCell(q+b,G,m9("─",{fg:U}));J.setCell(q+Y-1,G,m9("╮",{fg:U}));for(let b=1;b<K-1;b++){J.setCell(q,G+b,m9("│",{fg:U})),J.setCell(q+Y-1,G+b,m9("│",{fg:U}));for(let m=1;m<Y-1;m++)J.setCell(q+m,G+b,m9(" ",{fg:U}))}J.setCell(q,G+K-1,m9("╰",{fg:U}));for(let b=1;b<Y-1;b++)J.setCell(q+b,G+K-1,m9("─",{fg:U}));J.setCell(q+Y-1,G+K-1,m9("╯",{fg:U}));let D=q+1,M=G+1;this.drawText(J,D,M++," Last P99",z);let V=this.tracker.getLastKeyEventTime(),N=this.tracker.getKeyEventP99(),L=V.toFixed(2).padStart(5," "),A=N.toFixed(2).padStart(5," "),O=this.getTimingColor(V),j=this.getTimingColor(N),R=` ${"Key".padStart(6," ")} `;this.drawText(J,D,M,R,z),this.drawText(J,D+R.length,M,L,O),this.drawText(J,D+R.length+L.length,M," ",z),this.drawText(J,D+R.length+L.length+3,M++,A,j);let I=this.tracker.getLastMouseEventTime(),w=this.tracker.getMouseEventP99(),E=I.toFixed(2).padStart(5," "),$=w.toFixed(2).padStart(5," "),P=this.getTimingColor(I),C=this.getTimingColor(w),k=` ${"Mouse".padStart(6," ")} `;this.drawText(J,D,M,k,z),this.drawText(J,D+k.length,M,E,P),this.drawText(J,D+k.length+E.length,M," ",z),this.drawText(J,D+k.length+E.length+3,M++,$,C),M++;for(let b of["build","layout","paint","render"]){let m=Q.phaseStats[b].lastTime,n=this.tracker.getPhaseP99(b),u=m.toFixed(2).padStart(5," "),Q1=n.toFixed(2).padStart(5," "),z1=this.getTimingColor(m),F1=this.getTimingColor(n),H1=` ${(b.charAt(0).toUpperCase()+b.slice(1)).padStart(6," ")} `;this.drawText(J,D,M,H1,z),this.drawText(J,D+H1.length,M,u,z1),this.drawText(J,D+H1.length+u.length,M," ",z),this.drawText(J,D+H1.length+u.length+3,M++,Q1,F1)}M++;let g=Q.lastFrameTime,T=this.tracker.getFrameP99(),v=g.toFixed(2).padStart(5," "),f=T.toFixed(2).padStart(5," "),h=this.getTimingColor(g),S=this.getTimingColor(T),x=` ${"Frame".padStart(6," ")} `;this.drawText(J,D,M,x,U),this.drawText(J,D+x.length,M,v,h),this.drawText(J,D+x.length+v.length,M," ",U),this.drawText(J,D+x.length+v.length+3,M++,f,S)}getTimingColor(J){let Q=hx1,Z=hx1*0.7;if(J>=Q)return d1.red;if(J>=Z)return d1.yellow;return d1.white}drawText(J,Q,Z,X,Y){for(let K=0;K<X.length;K++)J.setCell(Q+K,Z,m9(X[K]||" ",{fg:Y}))}}var OZ6=p(()=>{z9();TO()});class BQ{key;constructor({key:J}={}){if(this.constructor===BQ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}static canUpdate(J,Q){return J.canUpdate(Q)}}class WY{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this.parent;while(Q)J++,Q=Q.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Q=this._children.indexOf(J);if(Q!==-1)this._children.splice(Q,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){this._mounted=!0}unmount(){this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,LZ6().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Q=this.parent;while(Q){if(Q.widget.constructor===J){if("addDependent"in Q)Q.addDependent(this),this._inheritedDependencies.add(Q);return Q}Q=Q.parent}return null}findAncestorElementOfType(J){let Q=this.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){let Q=this.parent;while(Q){if(Q.widget instanceof J)return Q.widget;Q=Q.parent}return null}}var PH=()=>{};var jG,jZ6;var SO=p(()=>{PH();jG=class jG extends BQ{child;constructor({key:J,child:Q}){super(J!==void 0?{key:J}:{});this.child=Q}createElement(){return new jZ6(this)}};jZ6=class jZ6 extends WY{_child;_dependents=new Set;constructor(J){super(J)}get inheritedWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.inheritedWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._dependents.clear(),super.unmount()}update(J){let Q=this.inheritedWidget;super.update(J);let Z=this.inheritedWidget;if(Z.updateShouldNotify(Q))this.notifyDependents();if(this._child&&this._child.widget.canUpdate(Z.child))this._child.update(Z.child);else{if(this._child)this._child.unmount(),this.removeChild(this._child);this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount()}}addDependent(J){this._dependents.add(J)}removeDependent(J){this._dependents.delete(J)}notifyDependents(){for(let J of this._dependents)J.markNeedsRebuild()}performRebuild(){}}});class mT{size;capabilities;constructor(J,Q){this.size=J;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}var m8;var RG=p(()=>{SO();m8=class m8 extends jG{data;constructor({key:J,data:Q,child:Z}){super(J!==void 0?{key:J,child:Z}:{child:Z});this.data=Q}updateShouldNotify(J){return this.data!==J.data||this.data.size.width!==J.data.size.width||this.data.size.height!==J.data.size.height||this.data.capabilities!==J.data.capabilities}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(m8);if(Q)return Q.widget.data;throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.")}static sizeOf(J){return m8.of(J).size}static capabilitiesOf(J){return m8.of(J).capabilities}}});class TV{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;allowHitTestOutsideBounds=!1;parentData;get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this._parent;while(Q)J++,Q=Q._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),"setupParentData"in this&&typeof this.setupParentData==="function")this.setupParentData(J);if(this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Q=this._children.indexOf(J);if(Q!==-1){if(J._attached)J.detach();this._children.splice(Q,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Q of J)Q._parent=this,Q._invalidateDepth();this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else r41().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,r41().requestPaint(this)}performLayout(){}paint(J,Q=0,Z=0){this._needsPaint=!1;for(let X of this.children)if("offset"in X){let Y=X,K=Q+Y.offset.x,q=Z+Y.offset.y;X.paint(J,K,q)}else X.paint(J,Q,Z)}visitChildren(J){for(let Q of this._children)J(Q)}dispose(){r41().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}function CV(J,Q=0){return Number.isFinite(J)?J:Q}class d6{minWidth;maxWidth;minHeight;maxHeight;constructor(J=0,Q=1/0,Z=0,X=1/0){this.minWidth=J;this.maxWidth=Q;this.minHeight=Z;this.maxHeight=X}static tight(J,Q){return new d6(J,J,Q,Q)}static loose(J,Q){return new d6(0,J,0,Q)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Q){return q8(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),q8(isFinite(Q),`BoxConstraints.constrain received infinite height: ${Q}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Q))}}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}var H8;var r9=p(()=>{I4();H8=class H8 extends TV{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Q){q8(Number.isFinite(J)&&Number.isFinite(Q),`RenderBox.setSize received non-finite dimension: ${J}x${Q}`),this._size.width=J,this._size.height=Q}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Q){let Z=Number.isFinite(J)?Math.round(J):0,X=Number.isFinite(Q)?Math.round(Q):0;this._offset.x=Z,this._offset.y=X}localToGlobal(J){let{x:Q,y:Z}=J,X=this;while(X)if(Q+=X._offset.x,Z+=X._offset.y,X=X.parent,X&&!("_offset"in X))break;return{x:Q,y:Z}}globalToLocal(J){let Q=this.localToGlobal({x:0,y:0});return{x:J.x-Q.x,y:J.y-Q.y}}_lastConstraints;layout(J){let Q=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Q)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicWidth(J));return Z}getMaxIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicWidth(J));return Z}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicHeight(J));return Z}getMaxIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicHeight(J));return Z}paint(J,Q=0,Z=0){let X=J.getSize(),Y=X.width,K=X.height;for(let q of this.children)if(q instanceof H8){let G=Q+this.offset.x+q.offset.x,z=Z+this.offset.y+q.offset.y,U=G+q.size.width,W=z+q.size.height;if(!(G>=Y||z>=K||U<=0||W<=0))q.paint(J,Q+this.offset.x,Z+this.offset.y)}}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){J.addWithPaintOffset(this,{x:Y,y:K},Q);let z=!0;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}if(this.allowHitTestOutsideBounds){let z=!1;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}return!1}}});var uT,h4,wG,vO,Yu,SV,o41,pT;var Y7=p(()=>{PH();uT=class uT extends BQ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new Yu(this)}updateRenderObject(J){}};h4=class h4 extends uT{child;constructor({key:J,child:Q}={}){super(J?{key:J}:{});this.child=Q}createElement(){return new SV(this)}};wG=class wG extends uT{children;constructor({key:J,children:Q=[]}={}){super(J?{key:J}:{});this.children=[...Q]}createElement(){return new o41(this)}};vO=class vO extends uT{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new pT(this)}};Yu=class Yu extends WY{_renderObject;constructor(J){super(J)}get renderObjectWidget(){return this.widget}get renderObject(){return this._renderObject}mount(){this._renderObject=this.renderObjectWidget.createRenderObject(),this._renderObject.attach(),this.markMounted()}unmount(){if(this._renderObject)this._renderObject.detach(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Q=this.renderObjectWidget;if(this._renderObject)Q.updateRenderObject(this._renderObject)}performRebuild(){}};SV=class SV extends Yu{_child;constructor(J){super(J)}get singleChildWidget(){return this.widget}get child(){return this._child}mount(){if(super.mount(),this.singleChildWidget.child){if(this._child=this.singleChildWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject&&this.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Q=this.singleChildWidget;if(Q.child&&this._child){if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject){if(this.renderObject.removeAllChildren(),this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}else if(Q.child&&!this._child){if(this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject&&this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}else if(!Q.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this.renderObject)this.renderObject.removeAllChildren()}}performRebuild(){}};o41=class o41 extends Yu{_childElements=[];constructor(J){super(J)}get multiChildWidget(){return this.widget}get children(){return this._childElements}mount(){super.mount();for(let J of this.multiChildWidget.children){let Q=J.createElement();if(this._childElements.push(Q),this.addChild(Q),Q.mount(),Q.renderObject&&this.renderObject)this.renderObject.adoptChild(Q.renderObject)}}unmount(){for(let J of this._childElements)J.unmount(),this.removeChild(J);this._childElements.length=0,super.unmount()}update(J){super.update(J);let Q=this.multiChildWidget;this.updateChildren(this._childElements,[...Q.children])}updateChildren(J,Q){let Z=[],X=0,Y=0,K=J.length-1,q=Q.length-1;while(X<=K&&Y<=q){let U=J[X],W=Q[Y];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);Z.push(U),X++,Y++}let G=[];while(X<=K&&Y<=q){let U=J[K],W=Q[q];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);G.unshift(U),K--,q--}if(X>K)for(let U=Y;U<=q;U++){let W=Q[U];if(W){let F=this.createChildElement(W);Z.push(F)}}else if(Y>q)for(let U=X;U<=K;U++){let W=J[U];if(W)this.deactivateChild(W)}else{let U=new Map,W=new Map;for(let F=X;F<=K;F++){let H=J[F];if(H.widget.key){let D=H.widget.key.toString();U.set(D,H),W.set(D,F)}}for(let F=Y;F<=q;F++){let H=Q[F];if(!H)continue;let D;if(H.key){let M=H.key.toString();if(D=U.get(M),D){U.delete(M);let V=W.get(M);if(V!==void 0)J[V]=null;if(D.widget===H);else if(D.widget.canUpdate(H))D.update(H);else this.deactivateChild(D),D=this.createChildElement(H)}else D=this.createChildElement(H)}else{let M=!1;for(let V=X;V<=K;V++){let N=J[V];if(N&&!N.widget.key){if(N.widget===H){D=N,J[V]=null,M=!0;break}else if(N.widget.canUpdate(H)){D=N,J[V]=null,D.update(H),M=!0;break}}}if(!M)D=this.createChildElement(H)}if(D)Z.push(D)}for(let F=X;F<=K;F++){let H=J[F];if(H)this.deactivateChild(H)}for(let F of U.values())this.deactivateChild(F)}Z.push(...G);let z=this._childElements;if(this._childElements=Z,this.renderObject){let U=[];for(let H of Z)if(H.renderObject)U.push(H.renderObject);let W=this.renderObject.children;if(W.length!==U.length||W.some((H,D)=>H!==U[D]))this.renderObject.replaceChildren(U)}}createChildElement(J){let Q=J.createElement();return this.addChild(Q),Q.mount(),Q}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}};pT=class pT extends Yu{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}});var R5,RZ6,IG;var SU=p(()=>{I4();r9();Y7();Ku();R5=class R5 extends h4{child;onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;constructor({key:J,child:Q,onClick:Z,onEnter:X,onExit:Y,onHover:K,onScroll:q,onRelease:G,onDrag:z,cursor:U,opaque:W=!0}){super({key:J});this.child=Q,this.onClick=Z??null,this.onEnter=X??null,this.onExit=Y??null,this.onHover=K??null,this.onScroll=q??null,this.onRelease=G??null,this.onDrag=z??null,this.cursor=U??null,this.opaque=W}createElement(){return new RZ6(this)}createRenderObject(){return new IG({onClick:this.onClick,onEnter:this.onEnter,onExit:this.onExit,onHover:this.onHover,onScroll:this.onScroll,onRelease:this.onRelease,onDrag:this.onDrag,cursor:this.cursor,opaque:this.opaque})}updateRenderObject(J){J.onClick=this.onClick,J.onEnter=this.onEnter,J.onExit=this.onExit,J.onHover=this.onHover,J.onScroll=this.onScroll,J.onRelease=this.onRelease,J.onDrag=this.onDrag,J.cursor=this.cursor,J.opaque=this.opaque}};RZ6=class RZ6 extends SV{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}};IG=class IG extends H8{onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;_isHovered=!1;constructor({onClick:J,onEnter:Q,onExit:Z,onHover:X,onScroll:Y,onRelease:K,onDrag:q,cursor:G,opaque:z}){super();this.onClick=J,this.onEnter=Q,this.onExit=Z,this.onHover=X,this.onScroll=Y,this.onRelease=K,this.onDrag=q,this.cursor=G,this.opaque=z}get hasMouseListeners(){return!!(this.onClick||this.onEnter||this.onExit||this.onHover||this.onScroll||this.onRelease||this.onDrag)}get isHovered(){return this._isHovered}handleMouseEvent(J){switch(J.type){case"click":this.onClick?.(J);break;case"enter":this._isHovered=!0,this.onEnter?.(J);break;case"exit":this._isHovered=!1,this.onExit?.(J);break;case"hover":this.onHover?.(J);break;case"scroll":this.onScroll?.(J);break}}handleMouseRelease(J){this.onRelease?.(J)}handleMouseDrag(J){this.onDrag?.(J)}performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height),Q.setOffset(0,0)}else this.setSize(0,0);super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}getMinIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}paint(J,Q=0,Z=0){if(this.children.length>0)this.children[0].paint(J,Q+this.offset.x,Z+this.offset.y)}hitTest(J,Q,Z=0,X=0){let Y=super.hitTest(J,Q,Z,X);if(Y&&this.hasMouseListeners)J.addMouseTarget(this,Q);return Y}getDebugProperties(){return{hasMouseListeners:this.hasMouseListeners,isHovered:this.isHovered,cursor:this.cursor,opaque:this.opaque}}dispose(){DQ.instance.removeRegion(this),this.onClick=null,this.onEnter=null,this.onExit=null,this.onHover=null,this.onScroll=null,this.onRelease=null,this.onDrag=null,this.cursor=null,super.dispose()}}});class cx1{static hitTest(J,Q){let Z=new wZ6;return J.hitTest(Z,Q),Z}}class wZ6{_hits=[];get hits(){return this._hits}add(J){this._hits.push(J)}addWithPaintOffset(J,Q,Z){let X={x:Z.x-Q.x,y:Z.y-Q.y};this.add({target:J,localPosition:X})}addMouseTarget(J,Q){}}function S79(){if(!TV.prototype.hitTest)TV.prototype.hitTest=function(J,Q,Z=0,X=0){if("size"in this&&"offset"in this){let K=this,q=K.size,G=K.offset;if(q&&G){let z=Z+G.x,U=X+G.y,W=Q.x>=z&&Q.x<z+q.width,F=Q.y>=U&&Q.y<U+q.height;if(W&&F){let H={x:Q.x-z,y:Q.y-U};J.add({target:this,localPosition:H});let D=this.children,M=!0;for(let V=D.length-1;V>=0;V--)if(D[V].hitTest(J,Q,z,U))M=!0;return M}if(this.allowHitTestOutsideBounds){let H=!1,D=this.children;for(let M=D.length-1;M>=0;M--)if(D[M].hitTest(J,Q,z,U))H=!0;return H}return!1}}let Y=!1;for(let K of this.children)if(K.hitTest(J,Q,Z,X))Y=!0;return Y}}var lx1=p(()=>{r9();S79()});function IZ6(J,Q,Z){return{position:Q,localPosition:Z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}}}function EZ6(J,Q,Z,X=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:X,...IZ6(J,Q,Z)}}function $Z6(J,Q,Z){return{type:"scroll",direction:J.button==="wheel_up"?"up":"down",...IZ6(J,Q,Z)}}var DQ;var Ku=p(()=>{fT();SU();lx1();DQ=class DQ{static _instance=null;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=j5.DEFAULT;_lastMousePosition=null;_dragTargets=[];_globalReleaseCallbacks=new Set;_globalClickCallbacks=new Set;_lastClickTime=new Map;_lastClickPosition=new Map;_currentClickCount=new Map;static DOUBLE_CLICK_TIME=500;static DOUBLE_CLICK_DISTANCE=2;static DOUBLE_CLICK_DISTANCE_SQUARED=DQ.DOUBLE_CLICK_DISTANCE*DQ.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!this._instance)this._instance=new DQ;return this._instance}setRootRenderObject(J){this._rootRenderObject=J}setTui(J){this._vaxis=J}handleMouseEvent(J){if(!this._rootRenderObject)return;let Q={x:J.x,y:J.y},Z=cx1.hitTest(this._rootRenderObject,Q),X=this._findMouseTargets(Z.hits);switch(J.action){case"press":if(J.button==="left"||J.button==="middle"||J.button==="right"){if(this._handleClick(J,Q,X),J.button==="left")this._dragTargets=X.map(({target:Y,localPosition:K})=>{let q={x:Q.x-K.x,y:Q.y-K.y};return{target:Y,localPosition:K,globalOffset:q}})}break;case"release":this._handleRelease(J,Q,X),this._dragTargets=[];break;case"scroll":if(J.button==="wheel_up"||J.button==="wheel_down")this._handleScroll(J,Q,X);break;case"move":if(this._handleMove(J,Q,X),J.drag)this._handleDrag(J,Q,X);break}this._lastMousePosition=Q}addGlobalReleaseCallback(J){this._globalReleaseCallbacks.add(J)}removeGlobalReleaseCallback(J){this._globalReleaseCallbacks.delete(J)}addGlobalClickCallback(J){this._globalClickCallbacks.add(J)}removeGlobalClickCallback(J){this._globalClickCallbacks.delete(J)}requestCursorChange(J){if(this._vaxis&&J!==this._currentCursor)this._currentCursor=J,this._vaxis.setMouseCursor(J)}_handleRelease(J,Q,Z){for(let X of this._globalReleaseCallbacks)X();for(let{target:X,localPosition:Y}of Z){if(typeof X.handleMouseRelease==="function")X.handleMouseRelease({type:"release",position:Q,localPosition:Y,button:J.button,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}});if(X instanceof IG&&X.opaque)break}}_handleDrag(J,Q,Z){for(let{target:X,globalOffset:Y}of this._dragTargets)if(typeof X.handleMouseDrag==="function"){let K={x:Q.x-Y.x,y:Q.y-Y.y};X.handleMouseDrag({type:"drag",position:Q,localPosition:K,button:J.button,drag:J.drag,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}})}}_handleClick(J,Q,Z){let X=this._calculateClickCount(Q,J.button);for(let Y of this._globalClickCallbacks)Y({event:J,globalPosition:Q,mouseTargets:Z,clickCount:X});for(let{target:Y,localPosition:K}of Z){let q=EZ6(J,Q,K,X);if(Y.handleMouseEvent(q),Y instanceof IG&&Y.opaque)break}}_handleScroll(J,Q,Z){for(let{target:X,localPosition:Y}of Z){let K=$Z6(J,Q,Y);if(X.handleMouseEvent(K),X instanceof IG&&X.opaque)break}}_handleMove(J,Q,Z){let X=Z.filter((G)=>G.target instanceof IG),Y=this._scratchCurrentRegions,K=this._scratchExitedRegions,q=this._scratchEnteredRegions;Y.clear();for(let{target:G}of X)Y.add(G);K.clear();for(let G of this._hoveredRegions)if(!Y.has(G))K.add(G);q.clear();for(let G of Y)if(!this._hoveredRegions.has(G))q.add(G);for(let G of K)if(G.onExit){let z={type:"exit",position:Q,localPosition:Q,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(z)}for(let{target:G,localPosition:z}of X)if(q.has(G)&&G.onEnter){let U={type:"enter",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}for(let{target:G,localPosition:z}of X)if(G.onHover&&this._hoveredRegions.has(G)){let U={type:"hover",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}this._hoveredRegions.clear();for(let G of Y)this._hoveredRegions.add(G);this._updateCursor(X)}_updateCursor(J){if(!this._vaxis)return;let Q=j5.DEFAULT;for(let{target:Z}of J)if(Z.cursor!==null)Q=Z.cursor;if(Q!==this._currentCursor)this._currentCursor=Q,this._vaxis.setMouseCursor(Q)}_findMouseTargets(J){let Q=[];for(let Z of J)if(this._canHandleMouseEvents(Z.target))Q.push({target:Z.target,localPosition:Z.localPosition});return Q}_canHandleMouseEvents(J){if(J instanceof IG)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==j5.DEFAULT)this._currentCursor=j5.DEFAULT,this._vaxis.setMouseCursor(j5.DEFAULT)}removeRegion(J){this._hoveredRegions.delete(J)}reestablishHoverState(){if(!this._lastMousePosition||!this._rootRenderObject)return;let J={type:"mouse",action:"move",x:this._lastMousePosition.x,y:this._lastMousePosition.y,button:"unknown",drag:!1,modifiers:{shift:!1,ctrl:!1,alt:!1,meta:!1}};this.handleMouseEvent(J)}_calculateClickCount(J,Q="left"){let Z=Date.now(),X=this._lastClickTime.get(Q)??0,Y=Z-X,K=1,q=this._lastClickPosition.get(Q);if(q&&Y<=DQ.DOUBLE_CLICK_TIME&&this._isWithinDoubleClickDistance(J,q))K=(this._currentClickCount.get(Q)??0)+1;else K=1;return this._lastClickTime.set(Q,Z),this._lastClickPosition.set(Q,J),this._currentClickCount.set(Q,K),K}_isWithinDoubleClickDistance(J,Q){let Z=J.x-Q.x,X=J.y-Q.y;return Z*Z+X*X<=DQ.DOUBLE_CLICK_DISTANCE_SQUARED}dispose(){this.clearHoverState(),this._lastMousePosition=null,this._rootRenderObject=null,this._lastClickTime.clear(),this._lastClickPosition.clear(),this._currentClickCount.clear(),this._globalReleaseCallbacks.clear(),this._globalClickCallbacks.clear(),DQ._instance=null}}});class ix1{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(J){if(!XZ.instance.isFrameInProgress)XZ.instance.requestFrame()}requestPaint(J){if(this._nodesNeedingPaint.has(J))return;if(this._nodesNeedingPaint.add(J),!XZ.instance.isFrameInProgress)XZ.instance.requestFrame()}setRootRenderObject(J){this._rootRenderObject=J}updateRootConstraints(J){let Q=new d6(0,J.width,0,J.height),Z=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,Z&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints)}}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let J of this._nodesNeedingPaint)if(J.needsPaint)J._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return!1}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(J){this._nodesNeedingPaint.delete(J)}}var PZ6=p(()=>{TO();r9()});var TZ6={};L6(TZ6,{setTerminalFocused:()=>k79,initFocusTracking:()=>v79,getTerminalFocused:()=>ax1});function v79(J){let Q=(Z)=>{if(Z.type==="focus")nx1=Z.focused};J.onFocus(Q)}function ax1(){return nx1}function k79(J){nx1=J}var nx1=!0;var SZ6={};L6(SZ6,{initIdleTracking:()=>_79,getIsIdle:()=>rx1});function _79(J,Q=300000){CZ6=Q,t41=Date.now(),J.onKey(()=>{t41=Date.now()}),J.onMouse(()=>{t41=Date.now()})}function rx1(){return Date.now()-t41>=CZ6}var t41,CZ6=300000;var sx1=p(()=>{t41=Date.now()});class EG{static _instance;frameScheduler=XZ.instance;buildOwner;pipelineOwner;focusManager=PV.instance;mouseManager=DQ.instance;frameStatsOverlay=new dx1;tui=new fx1;rootElement;isRunning=!1;rootElementMountedCallback;static get instance(){return this._instance??=new EG}pendingResizeEvent=null;constructor(){this.buildOwner=new gx1,this.pipelineOwner=new ix1,this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>this.buildOwner.buildScopes(),"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{this.updateRootConstraints(),this.pipelineOwner.flushLayout()},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),VZ6({scheduleBuildFor:(J)=>this.buildOwner.scheduleBuildFor(J)},{requestLayout:(J)=>this.pipelineOwner.requestLayout(J),requestPaint:(J)=>this.pipelineOwner.requestPaint(J),removeFromQueues:(J)=>this.pipelineOwner.removeFromQueues(J)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(J)=>{a.error("Framework uncaught exception",J)})}async runApp(J){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => TZ6);Q(this.tui);let{initIdleTracking:Z}=await Promise.resolve().then(() => (sx1(),SZ6));Z(this.tui),await this.tui.waitForCapabilities(1000);let X=this.createMediaQueryWrapper(J);if(this.rootElement=X.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let Y=this.rootElement.renderObject;if(!Y&&this.rootElement.children.length>0)Y=this.rootElement.children[0]?.renderObject;if(Y)this.pipelineOwner.setRootRenderObject(Y),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),a.debug("Setting up event handlers..."),this.setupEventHandlers(),a.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),a.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),a.debug("waitForExit completed")}finally{a.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let J=this.tui.getSize();this.pipelineOwner.updateRootConstraints(J)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let J=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:J.width,height:J.height},Z=this.tui.getCapabilities()||{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3},X=new mT(Q,Z),Y=this.rootElement;if(Y.widget instanceof m8){let q=new m8({data:X,child:Y.widget.child});Y.update(q)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}paint(){if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let J=this.rootElement.renderObject;if(!J&&this.rootElement.children.length>0)J=this.rootElement.children[0]?.renderObject;if(!J)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(J,Q,0,0);let Z=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(Z),this.frameStatsOverlay.draw(Q,Z)}catch(Q){a.error("Paint error:",Q)}}render(){try{this.tui.render()}catch(J){a.error("Render error:",J)}}renderRenderObject(J,Q,Z,X){if("paint"in J&&typeof J.paint==="function")J.paint(Q,Z,X)}createMediaQueryWrapper(J){let Q=this.tui.getCapabilities()||{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3},Z=this.tui.getSize(),X=new mT(Z,Q);return new m8({data:X,child:J})}setupEventHandlers(){this.tui.onResize((J)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=J,this.frameScheduler.requestFrame()}),this.tui.onKey((J)=>{let Q=performance.now();if(this.focusManager.handleKeyEvent(J)){let Y=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(Y);return}this.handleGlobalKeyEvent(J);let X=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(X)}),this.tui.onMouse((J)=>{let Q=performance.now();this.mouseManager.handleMouseEvent(J);let Z=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(Z)}),this.tui.onPaste((J)=>{this.focusManager.handlePasteEvent(J)}),this.tui.onCapabilities((J)=>{if(this.rootElement){let Q=this.tui.getSize(),Z=new mT(Q,J.capabilities),X=this.rootElement;if(X.widget instanceof m8){let Y=new m8({data:Z,child:X.widget.child});X.update(Y)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(J){if(J.ctrlKey&&J.key==="z"&&!J.shiftKey&&!J.altKey&&!J.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let J=!this.frameStatsOverlay.isEnabled();this.frameStatsOverlay.setEnabled(J),this.frameScheduler.requestFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise)return this.exitPromise;return this.exitPromise=new Promise((J)=>{if(this.exitResolve=J,!this.isRunning)J()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(J){this.rootElementMountedCallback=J}}async function ox1(J,Q){let Z=EG.instance;if(Q?.stdin)Z.tuiInstance.setStdin(Q.stdin);if(Q?.onRootElementMounted)Z.setRootElementMountedCallback(Q.onRootElementMounted);await Z.runApp(J)}var tx1=p(()=>{D0();BZ6();MZ6();px1();TO();OZ6();RG();Ku();PZ6()});class TH{element;widget;mediaQuery;parent;constructor(J,Q,Z=void 0,X=null){this.element=J;this.widget=Q;this.mediaQuery=Z;this.parent=X}findAncestorElementOfType(J){let Q=this.element.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Q=this.element.parent;while(Q){if("state"in Q&&Q.state instanceof J)return Q.state;Q=Q.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof TV?J:void 0}return}}var qu=p(()=>{r9()});var vZ6=()=>{};class kZ6{constructor(){}}var s5;var Gu=p(()=>{s5=class s5 extends kZ6{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof s5))return!1;return this.value===J.value}get hashCode(){if(this.value===null||this.value===void 0)return 0;if(typeof this.value==="string")return this.stringHash(this.value);if(typeof this.value==="number")return this.value;if(typeof this.value==="boolean")return this.value?1:0;return this.stringHash(String(this.value))}stringHash(J){let Q=0;for(let Z=0;Z<J.length;Z++){let X=J.charCodeAt(Z);Q=(Q<<5)-Q+X,Q=Q&Q}return Q}toString(){return`ValueKey(${this.value})`}}});var w5,_Z6;var kO=p(()=>{I4();r9();Y7();w5=class w5 extends h4{constructor({key:J,child:Q}={}){super({key:J,child:Q})}createRenderObject(){return new _Z6}updateRenderObject(J){}static child(J){return new w5({child:J})}};_Z6=class _Z6 extends H8{constructor(){super()}performLayout(){let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this.children[0];if(!Q){let G=CV(J.maxWidth,J.minWidth),z=CV(J.maxHeight,J.minHeight);this.setSize(G,z),super.performLayout();return}Q.layout(d6.loose(J.maxWidth,J.maxHeight));let Z=J.maxWidth===1/0?Q.size.width:J.maxWidth,X=J.maxHeight===1/0?Q.size.height:J.maxHeight,Y=J.constrain(Z,X);this.setSize(Y.width,Y.height);let K=(this.size.width-Q.size.width)/2,q=(this.size.height-Q.size.height)/2;Q.setOffset(K,q),super.performLayout()}}});var CH;var zu=p(()=>{z9();CH=class CH extends em{_screen;_clipX;_clipY;_clipWidth;_clipHeight;constructor(J,Q,Z,X,Y){super(X,Y);this._screen=J,this._clipX=Q,this._clipY=Z,this._clipWidth=X,this._clipHeight=Y}setChar(J,Q,Z,X,Y=1){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setChar(J,Q,Z,X||{},Y)}setCell(J,Q,Z){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setCell(J,Q,Z)}fill(J,Q,Z,X,Y=" ",K){let q=Math.max(J,this._clipX),G=Math.max(Q,this._clipY),z=Math.min(J+Z,this._clipX+this._clipWidth),U=Math.min(Q+X,this._clipY+this._clipHeight);if(q<z&&G<U)this._screen.fill(q,G,z-q,U-G,Y,K)}getSize(){return this._screen.getSize()}resize(J,Q){return this._screen.resize(J,Q)}getBuffer(){return this._screen.getBuffer()}getFrontBuffer(){return this._screen.getFrontBuffer()}getBackBuffer(){return this._screen.getBackBuffer()}getCell(J,Q){return this._screen.getCell(J,Q)}clear(){return this._screen.clear()}present(){return this._screen.present()}getDiff(){return this._screen.getDiff()}markForRefresh(){return this._screen.markForRefresh()}setCursor(J,Q){return this._screen.setCursor(J,Q)}clearCursor(){return this._screen.clearCursor()}getCursor(){return this._screen.getCursor()}isCursorVisible(){return this._screen.isCursorVisible()}}});var ex1,bZ6;var Jy1=p(()=>{I4();zu();r9();Y7();ex1=class ex1 extends h4{clipBehavior;constructor(J,{key:Q,clipBehavior:Z="antiAlias"}={}){super(Q?{child:J,key:Q}:{child:J});this.clipBehavior=Z}createRenderObject(){return new bZ6(this.clipBehavior)}updateRenderObject(J){J.updateClipBehavior(this.clipBehavior)}};bZ6=class bZ6 extends H8{_clipBehavior;constructor(J){super();this._clipBehavior=J}updateClipBehavior(J){if(this._clipBehavior!==J)this._clipBehavior=J,this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(J.minWidth,J.minHeight),super.performLayout();return}this.children[0].layout(J),this.setSize(J.maxWidth,J.maxHeight),super.performLayout()}paint(J,Q=0,Z=0){if(this.children.length===0||this._clipBehavior==="none"){super.paint(J,Q,Z);return}let X=this.children[0],Y=Q+this.offset.x,K=Z+this.offset.y,q=this.size.width,G=this.size.height,z=new CH(J,Y,K,q,G);X.paint(z,Q+this.offset.x,Z+this.offset.y)}}});class Uu{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}var Wu;var e41=p(()=>{Wu=class Wu extends Uu{flex;fit;constructor(J=0,Q="tight"){super();this.flex=J,this.fit=Q}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}});var Fu,xZ6,yZ6;var J71=p(()=>{I4();r9();Y7();e41();Fu=class Fu extends wG{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Q,children:Z=[],mainAxisAlignment:X="start",crossAxisAlignment:Y="center",mainAxisSize:K="min"}){super({...J?{key:J}:{},children:Z});this.direction=Q,this.mainAxisAlignment=X,this.crossAxisAlignment=Y,this.mainAxisSize=K}createRenderObject(){return new yZ6(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new xZ6(this)}};xZ6=class xZ6 extends o41{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Q=J.renderObject;if(Q&&!Q.parentData)Q.parentData=new Wu(0,"tight")}}};yZ6=class yZ6 extends H8{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Q,Z,X){super();this._direction=J;this._mainAxisAlignment=Q;this._crossAxisAlignment=Z;this._mainAxisSize=X}updateProperties(J,Q,Z,X){this._direction=J,this._mainAxisAlignment=Q,this._crossAxisAlignment=Z,this._mainAxisSize=X,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this._direction==="horizontal",Z=[],X=[];for(let D of this.children){let M=D.parentData;if(M&&M.flex>0)Z.push({child:D,flex:M.flex,fit:M.fit});else X.push(D)}let Y=0,K=0,q,G=Q?J.maxHeight:J.maxWidth;if(isFinite(G))q=G;else{let D=0;for(let M of X){let V=Q?M.getMaxIntrinsicHeight(1/0):M.getMaxIntrinsicWidth(1/0);D=Math.max(D,V)}q=D}for(let D of X){let M=Q?new d6(0,1/0,0,q):new d6(0,q,0,1/0);if(D.layout(M),Q)Y+=D.size.width,K=Math.max(K,D.size.height);else Y+=D.size.height,K=Math.max(K,D.size.width)}let z=Q?J.maxWidth:J.maxHeight,U=Number.isFinite(z)?Math.max(0,z-Y):0,W=Z.reduce((D,M)=>D+M.flex,0);if(W>0){let D=U/W,M=0;for(let V=0;V<Z.length;V++){let{child:N,flex:L,fit:A}=Z[V],O;if(V===Z.length-1)O=U-M;else O=Math.floor(D*L),M+=O;let j=Q?J.maxHeight:J.maxWidth,R=Q?A==="tight"?new d6(O,O,0,j):d6.loose(O,j):A==="tight"?new d6(0,j,O,O):d6.loose(j,O);if(N.layout(R),Q)K=Math.max(K,N.size.height);else K=Math.max(K,N.size.width)}}let F=Y+(W>0?U:0);if(Q){q8(!(Z.length>0&&J.maxWidth===1/0&&this._mainAxisSize!=="min"),"RenderFlex children have non-zero flex but incoming width constraints are unbounded. Consider using MainAxisSize.min instead, or providing bounded width constraints.");let D=this._mainAxisSize==="min"||J.maxWidth===1/0?F:Math.max(J.minWidth,J.maxWidth);this.setSize(CV(D,J.minWidth),CV(K,J.minHeight))}else{q8(!(Z.length>0&&J.maxHeight===1/0&&this._mainAxisSize!=="min"),"RenderFlex children have non-zero flex but incoming height constraints are unbounded. Consider using MainAxisSize.min instead, or providing bounded height constraints.");let D=this._mainAxisSize==="min"||J.maxHeight===1/0?Math.min(Math.max(F,J.minHeight),J.maxHeight):Math.max(J.minHeight,J.maxHeight),M=this._mainAxisSize==="min"||J.maxHeight===1/0?Math.min(Math.max(K,J.minWidth),J.maxWidth):J.maxWidth;this.setSize(CV(M,J.minWidth),CV(D,J.minHeight))}if(this._crossAxisAlignment==="stretch"){let D=Q?this.size.height:this.size.width;for(let M of X){let V=Q?new d6(0,1/0,D,D):new d6(D,D,0,1/0);M.layout(V)}for(let{child:M}of Z){let V=Q?M.size.width:M.size.height,N=Q?new d6(V,V,D,D):new d6(D,D,V,V);M.layout(N)}}let H=Q?this.size.height:this.size.width;this.positionChildren(Q,H,J)}positionChildren(J,Q,Z){let X=this.children;if(X.length===0)return;let Y=0;for(let W of X)Y+=J?W.size.width:W.size.height;let K=J?this.size.width:this.size.height,q=Math.max(0,K-Y),G=0,z=0;switch(this._mainAxisAlignment){case"start":G=0;break;case"end":G=q;break;case"center":G=q/2;break;case"spaceBetween":z=X.length>1?Math.floor(q/(X.length-1)):0;break;case"spaceAround":z=X.length>0?q/X.length:0,G=z/2;break;case"spaceEvenly":z=X.length>0?Math.floor(q/(X.length+1)):0,G=z;break}let U=G;for(let W=0;W<X.length;W++){let F=X[W],H=J?F.size.width:F.size.height,D=J?F.size.height:F.size.width,M=0;switch(this._crossAxisAlignment){case"start":M=0;break;case"end":M=Q-D;break;case"center":M=(Q-D)/2;break;case"stretch":M=0;break;case"baseline":if(!J)throw Error("CrossAxisAlignment.baseline is only supported for horizontal flex (Row)");M=0;break}if(J)F.setOffset(U,M);else F.setOffset(M,U);if(U+=H,W<X.length-1)U+=z}}getMinIntrinsicWidth(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMinIntrinsicWidth(J)}return X}else{let X=0;for(let Y of Z)X=Math.max(X,Y.getMinIntrinsicWidth(J));return X}}getMaxIntrinsicWidth(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMaxIntrinsicWidth(J)}return X}else{let X=0;for(let Y of Z)X=Math.max(X,Y.getMaxIntrinsicWidth(J));return X}}getMaxIntrinsicHeight(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0,Y=0,K=[],q=[];for(let U of Z){let W=U.parentData;if(W&&W.flex>0)Y+=W.flex,q.push({child:U,flex:W.flex});else K.push(U)}let G=0;for(let U of K)G+=U.getMaxIntrinsicWidth(0);let z=Math.max(0,J-G);for(let U of Z){let W=U.parentData,F=J;if(W&&W.flex>0&&Y>0)F=z/Y*W.flex;X=Math.max(X,U.getMaxIntrinsicHeight(F))}return X}else{let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMaxIntrinsicHeight(J)}return X}}getMinIntrinsicHeight(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0,Y=0,K=[],q=[];for(let U of Z){let W=U.parentData;if(W&&W.flex>0)Y+=W.flex,q.push(U);else K.push(U)}let G=0;for(let U of K)G+=U.getMinIntrinsicWidth(0);let z=Math.max(0,J-G);for(let U of Z){let W=U.parentData,F=J;if(W&&W.flex>0&&Y>0)F=z/Y*W.flex;X=Math.max(X,U.getMinIntrinsicHeight(F))}return X}else{let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMinIntrinsicHeight(J)}return X}}dispose(){this._direction="vertical",this._mainAxisAlignment="start",this._crossAxisAlignment="start",this._mainAxisSize="min",super.dispose()}}});var O6;var zX=p(()=>{J71();O6=class O6 extends Fu{constructor({key:J,children:Q=[],mainAxisAlignment:Z="start",crossAxisAlignment:X="center",mainAxisSize:Y="max"}={}){super({...J?{key:J}:{},direction:"vertical",children:Q,mainAxisAlignment:Z,crossAxisAlignment:X,mainAxisSize:Y})}static start(J){return new O6({children:J,mainAxisAlignment:"start"})}static center(J){return new O6({children:J,mainAxisAlignment:"center"})}static end(J){return new O6({children:J,mainAxisAlignment:"end"})}static spaceBetween(J){return new O6({children:J,mainAxisAlignment:"spaceBetween"})}static spaceAround(J){return new O6({children:J,mainAxisAlignment:"spaceAround"})}static spaceEvenly(J){return new O6({children:J,mainAxisAlignment:"spaceEvenly"})}}});class g2{color;border;constructor(J,Q){this.color=J;this.border=Q}}class H4{top;right;bottom;left;constructor(J,Q,Z,X){this.top=J;this.right=Q;this.bottom=Z;this.left=X}static all(J){return new H4(J,J,J,J)}static symmetric(J,Q){return new H4(Q,J,Q,J)}}class g4{color;width;style;constructor(J=d1.black,Q=1,Z="rounded"){this.color=J;this.width=Q;this.style=Z}}var t6,Q71;var PJ=p(()=>{I4();z9();r9();Y7();t6=class t6 extends h4{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Q,width:Z,height:X,padding:Y,margin:K,decoration:q,constraints:G}={}){super({...J?{key:J}:{},...Q?{child:Q}:{}});this.width=Z,this.height=X,this.padding=Y,this.margin=K,this.decoration=q,this.constraints=G}createRenderObject(){return new Q71(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof Q71))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}};Q71=class Q71 extends H8{_width;_height;_padding;_margin;_decoration;_constraints;constructor(J,Q,Z,X,Y,K){super();this._width=J;this._height=Q;this._padding=Z;this._margin=X;this._decoration=Y;this._constraints=K}updateProperties(J,Q,Z,X,Y,K){this._width=J,this._height=Q,this._padding=Z,this._margin=X,this._decoration=Y,this._constraints=K,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=J;if(this._constraints)Q=new d6(Math.max(J.minWidth,this._constraints.minWidth),Math.min(J.maxWidth,this._constraints.maxWidth),Math.max(J.minHeight,this._constraints.minHeight),Math.min(J.maxHeight,this._constraints.maxHeight));let Z=this._margin?.horizontal??0,X=this._margin?.vertical??0,Y=this._padding?.horizontal??0,K=this._padding?.vertical??0,q=this._decoration?.border,G=(q?.left?1:0)+(q?.right?1:0),z=(q?.top?1:0)+(q?.bottom?1:0),U,W;if(this._width!==void 0)U=this._width;if(this._height!==void 0)W=this._height;let F,H;if(U!==void 0)F=Math.max(0,U-Z-Y-G);else F=Q.maxWidth-Z-Y-G;if(W!==void 0)H=Math.max(0,W-X-K-z);else H=Q.maxHeight-X-K-z;let D=new d6(Math.max(0,Q.minWidth-Z-Y-G),Math.max(0,F),Math.max(0,Q.minHeight-X-K-z),Math.max(0,H)),M,V;if(this.children.length>0){let A=this.children[0];if(!(A instanceof H8))throw Error("Child must be a RenderBox");A.layout(D),M=A.size.width,V=A.size.height;let O=q?.left?1:0,j=q?.top?1:0,R=(this._margin?.left??0)+O+(this._padding?.left??0),I=(this._margin?.top??0)+j+(this._padding?.top??0);A.setOffset(R,I)}else M=0,V=0;let N,L;if(U!==void 0)N=U;else N=M+Y+G+Z;if(W!==void 0)L=W;else L=V+K+z+X;if(Q.minWidth===Q.maxWidth&&isFinite(Q.maxWidth))N=Q.maxWidth;if(Q.minHeight===Q.maxHeight&&isFinite(Q.maxHeight))L=Q.maxHeight;this.setSize(Q.constrain(N,L).width,Q.constrain(N,L).height)}getMinIntrinsicWidth(J){let Q=this._margin?.horizontal??0,Z=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),K=0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));K=q.getMinIntrinsicWidth(G)}return K+Q+Z+Y}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.maxWidth!==1/0)return this._constraints.maxWidth;let Q=this._margin?.horizontal??0,Z=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),K=1/0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));K=q.getMaxIntrinsicWidth(G)}if(K===1/0)return 1/0;return K+Q+Z+Y}getMinIntrinsicHeight(J){let Q=this._margin?.vertical??0,Z=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),K=0;if(this.children.length>0){let G=this.children[0],z=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));K=G.getMinIntrinsicHeight(z)}let q=K+Q+Z+Y;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(q,this._constraints.maxHeight);return q}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.maxHeight!==1/0)return this._constraints.maxHeight;let Q=this._margin?.vertical??0,Z=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),K=0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));K=q.getMaxIntrinsicHeight(G)}if(K===1/0)return 1/0;return K+Q+Z+Y}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y);if(this._decoration?.color){let K={bg:this._decoration.color};J.fill(X,Y,this.size.width,this.size.height," ",K)}if(this._decoration?.border)this._paintBorder(J,X,Y);super.paint(J,Q,Z)}_paintBorder(J,Q,Z){let X=this._decoration.border,Y=this.size.width,K=this.size.height,q=(H)=>{switch(H){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},G=(H)=>{switch(H){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},z=(H,D)=>{if(H===1)return D?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"};else return D?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┏",tr:"┓",bl:"┗",br:"┛"}};if(X.top){let H={fg:X.top.color},D=q(X.top.width);for(let M=0;M<Y;M++)J.setChar(Q+M,Z,D,H,1)}if(X.bottom){let H={fg:X.bottom.color},D=q(X.bottom.width);for(let M=0;M<Y;M++)J.setChar(Q+M,Z+K-1,D,H,1)}if(X.left){let H={fg:X.left.color},D=G(X.left.width);for(let M=0;M<K;M++)J.setChar(Q,Z+M,D,H,1)}if(X.right){let H={fg:X.right.color},D=G(X.right.width);for(let M=0;M<K;M++)J.setChar(Q+Y-1,Z+M,D,H,1)}let U=X.top?.style==="rounded",W=Math.max(X.top?.width??1,X.right?.width??1,X.bottom?.width??1,X.left?.width??1),F=z(W,U);if(X.top&&X.left){let H={fg:X.top.color};J.setChar(Q,Z,F.tl,H,1)}if(X.top&&X.right){let H={fg:X.top.color};J.setChar(Q+Y-1,Z,F.tr,H,1)}if(X.bottom&&X.left){let H={fg:X.bottom.color};J.setChar(Q,Z+K-1,F.bl,H,1)}if(X.bottom&&X.right){let H={fg:X.bottom.color};J.setChar(Q+Y-1,Z+K-1,F.br,H,1)}}hitTest(J,Q,Z=0,X=0){return super.hitTest(J,Q,Z,X)}_getBorderWidth(){let J=this._decoration?.border;if(!J)return 0;let Q=[J.top,J.right,J.bottom,J.left].filter((Z)=>Z!==void 0);return Q.length>0?Math.max(...Q.map((Z)=>Z.width)):0}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}});var Hu,fZ6;var Z71=p(()=>{PH();Hu=class Hu extends BQ{child;constructor(J,Q){super(Q);this.child=J}createElement(){return new fZ6(this)}};fZ6=class fZ6 extends WY{_child;constructor(J){super(J)}get parentDataWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.parentDataWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._applyParentData()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Q=J;if(this._child)if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount();else this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount();this._applyParentData()}performRebuild(){this._applyParentData()}_applyParentData(){let J=this._child;if(!J)return;let Q=J.renderObject;if(!Q)return;if(!this.parentDataWidget.debugIsValidRenderObject(Q))throw Error(`ParentDataWidget ${this.parentDataWidget.constructor.name} provided parent data to ${Q.constructor.name}, but ${Q.constructor.name} doesn't support this type of parent data.`);if(!Q.parentData||Q.parentData.constructor!==this.parentDataWidget.createParentData().constructor)Q.parentData=this.parentDataWidget.createParentData();this.parentDataWidget.applyParentData(Q)}}});var $2;var vU=p(()=>{Z71();e41();$2=class $2 extends Hu{flex;constructor({child:J,flex:Q=1,key:Z}){super(J,Z);this.flex=Q}createParentData(){return new Wu(this.flex,"tight")}applyParentData(J){let Q=J.parentData;if(Q)Q.flex=this.flex,Q.fit="tight"}debugIsValidRenderObject(J){return!0}toString(){return`Expanded(flex: ${this.flex}, child: ${this.child})`}}});var hZ6=()=>{};class B6{left;top;right;bottom;constructor(J,Q,Z,X){this.left=J;this.top=Q;this.right=Z;this.bottom=X}static all(J){return new B6(J,J,J,J)}static symmetric(J=0,Q=0){return new B6(J,Q,J,Q)}static horizontal(J){return new B6(J,0,J,0)}static vertical(J){return new B6(0,J,0,J)}static only(J){return new B6(J.left??0,J.top??0,J.right??0,J.bottom??0)}get horizontal(){return this.left+this.right}get vertical(){return this.top+this.bottom}}var S8,Zy1,Xy1;var FY=p(()=>{I4();r9();PH();S8=class S8 extends BQ{padding;child;constructor({key:J,padding:Q,child:Z}){super(J?{key:J}:{});this.padding=Q,this.child=Z}createElement(){return new Zy1(this)}};Zy1=class Zy1 extends WY{_child;_renderObject;constructor(J){super(J)}get paddingWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._renderObject}mount(){if(this._renderObject=new Xy1(this.paddingWidget.padding),this._renderObject.attach(),this.paddingWidget.child){if(this._child=this.paddingWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject)this._renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._renderObject)this._renderObject.detach(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Q=this.paddingWidget;if(this._renderObject)this._renderObject.updatePadding(Q.padding);if(Q.child&&this._child){if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this._renderObject&&this._child.renderObject)this._renderObject.removeAllChildren(),this._renderObject.adoptChild(this._child.renderObject)}else if(Q.child&&!this._child){if(this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this._renderObject&&this._child.renderObject)this._renderObject.adoptChild(this._child.renderObject)}else if(!Q.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this._renderObject)this._renderObject.removeAllChildren()}}performRebuild(){}};Xy1=class Xy1 extends H8{_padding;constructor(J){super();this._padding=J}updatePadding(J){this._padding=J,this.markNeedsLayout()}get padding(){return this._padding}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this._padding.horizontal,Z=this._padding.vertical,X=new d6(Math.max(0,J.minWidth-Q),Math.max(0,J.maxWidth-Q),Math.max(0,J.minHeight-Z),Math.max(0,J.maxHeight-Z));if(this.children.length>0){let Y=this.children[0];Y.layout(X),Y.setOffset(this._padding.left,this._padding.top),this.setSize(Y.size.width+Q,Y.size.height+Z)}else this.setSize(J.minWidth+Q,J.minHeight+Z)}getMinIntrinsicWidth(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Z);return X.getMinIntrinsicWidth(Y)+Q}return Q}getMinIntrinsicHeight(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Q);return X.getMinIntrinsicHeight(Y)+Z}return Z}getMaxIntrinsicWidth(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Z);return X.getMaxIntrinsicWidth(Y)+Q}return Q}getMaxIntrinsicHeight(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Q);return X.getMaxIntrinsicHeight(Y)+Z}return Z}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){let W={x:Q.x-Y,y:Q.y-K};J.add({target:this,localPosition:W});for(let F=this.children.length-1;F>=0;F--){let H=this.children[F];if(H&&"hitTest"in H&&typeof H.hitTest==="function")H.hitTest(J,Q,Y,K)}return!0}let z=Z+this.offset.x,U=X+this.offset.y;for(let W of this.children)if("hitTest"in W&&typeof W.hitTest==="function")W.hitTest(J,Q,z,U);return!1}}});var bK,X71,gZ6;var _O=p(()=>{I4();r9();Y7();bK=class bK extends wG{constructor({key:J,children:Q=[]}={}){super({...J?{key:J}:{},children:Q})}createRenderObject(){return new gZ6}updateRenderObject(J){}};X71=class X71 extends Uu{left;top;right;bottom;width;height;constructor(J,Q,Z,X,Y,K){super();this.left=J,this.top=Q,this.right=Z,this.bottom=X,this.width=Y,this.height=K}};gZ6=class gZ6 extends H8{constructor(){super();this.allowHitTestOutsideBounds=!0}setupParentData(J){if(!J.parentData)J.parentData=new X71}performLayout(){let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=0,Z=0,X=this.children;for(let q of X){let G=q.parentData;if(!G||!G.left&&!G.top&&!G.right&&!G.bottom)q.layout(J),Q=Math.max(Q,q.size.width),Z=Math.max(Z,q.size.height)}let Y=Math.max(Q,J.minWidth),K=Math.max(Z,J.minHeight);this.setSize(Y,K);for(let q of X){let G=q.parentData;if(G&&(G.left!==void 0||G.top!==void 0||G.right!==void 0||G.bottom!==void 0))this.layoutPositionedChild(q,G);else q.setOffset(0,0)}super.performLayout()}layoutPositionedChild(J,Q){let{width:Z,height:X}=Q;if(Z===void 0&&Q.left!==void 0&&Q.right!==void 0)Z=this.size.width-Q.left-Q.right;if(X===void 0&&Q.top!==void 0&&Q.bottom!==void 0)X=this.size.height-Q.top-Q.bottom;let Y=new d6(Z??0,Z??this.size.width,X??0,X??this.size.height);J.layout(Y);let K=0,q=0;if(Q.left!==void 0)K=Q.left;else if(Q.right!==void 0)K=this.size.width-Q.right-J.size.width;if(Q.top!==void 0)q=Q.top;else if(Q.bottom!==void 0)q=this.size.height-Q.bottom-J.size.height;J.setOffset(K,q)}}});var bO;var Bu=p(()=>{Z71();_O();bO=class bO extends Hu{left;top;right;bottom;width;height;constructor({key:J,left:Q,top:Z,right:X,bottom:Y,width:K,height:q,child:G}){super(G,J);this.left=Q,this.top=Z,this.right=X,this.bottom=Y,this.width=K,this.height=q}createParentData(){return new X71(this.left,this.top,this.right,this.bottom,this.width,this.height)}applyParentData(J){let Q=J.parentData;if(Q)Q.left=this.left,Q.top=this.top,Q.right=this.right,Q.bottom=this.bottom,Q.width=this.width,Q.height=this.height}debugIsValidRenderObject(J){return!0}updateParentData(J){let Q=J.parentData,Z=!1;if(Q.left!==this.left)Q.left=this.left,Z=!0;if(Q.top!==this.top)Q.top=this.top,Z=!0;if(Q.right!==this.right)Q.right=this.right,Z=!0;if(Q.bottom!==this.bottom)Q.bottom=this.bottom,Z=!0;if(Q.width!==this.width)Q.width=this.width,Z=!0;if(Q.height!==this.height)Q.height=this.height,Z=!0;if(Z){let X=J.parent;if(X&&"markNeedsLayout"in X)X.markNeedsLayout()}}}});var N9;var $G=p(()=>{J71();N9=class N9 extends Fu{constructor({key:J,children:Q=[],mainAxisAlignment:Z="start",crossAxisAlignment:X="center",mainAxisSize:Y="max"}={}){super({...J?{key:J}:{},direction:"horizontal",children:Q,mainAxisAlignment:Z,crossAxisAlignment:X,mainAxisSize:Y})}static start(J){return new N9({children:J,mainAxisAlignment:"start"})}static center(J){return new N9({children:J,mainAxisAlignment:"center"})}static end(J){return new N9({children:J,mainAxisAlignment:"end"})}static spaceBetween(J){return new N9({children:J,mainAxisAlignment:"spaceBetween"})}static spaceAround(J){return new N9({children:J,mainAxisAlignment:"spaceAround"})}static spaceEvenly(J){return new N9({children:J,mainAxisAlignment:"spaceEvenly"})}}});var i0,Yy1;var u7=p(()=>{I4();r9();Y7();i0=class i0 extends h4{width;height;constructor({key:J,width:Q,height:Z,child:X}={}){super({key:J,child:X});this.width=Q,this.height=Z}createRenderObject(){return new Yy1(this.width,this.height)}updateRenderObject(J){J.updateDimensions(this.width,this.height)}static fromSize(J,Q,Z){return Z?new i0({width:J,height:Q,child:Z}):new i0({width:J,height:Q})}static expand(J){return J?new i0({width:1/0,height:1/0,child:J}):new i0({width:1/0,height:1/0})}static shrink(J){return J?new i0({width:0,height:0,child:J}):new i0({width:0,height:0})}static height(J,Q){return Q?new i0({height:J,child:Q}):new i0({height:J})}static width(J,Q){return Q?new i0({width:J,child:Q}):new i0({width:J})}};Yy1=class Yy1 extends H8{_width;_height;constructor(J,Q){super();this._width=J;this._height=Q}updateDimensions(J,Q){let Z=this._width,X=this._height;if(this._width=J,this._height=Q,Z!==J||X!==Q)this.markNeedsLayout()}getMinIntrinsicWidth(J){if(this._width!==void 0)return this._width===1/0?0:this._width;if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width===1/0?1/0:this._width;if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}getMinIntrinsicHeight(J){if(this._height!==void 0)return this._height===1/0?0:this._height;if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height===1/0?1/0:this._height;if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q,Z;if(this._width!==void 0)if(this._width===1/0)Q=J.maxWidth;else Q=this._width;else if(this.children.length>0){let Y=this.children[0];Y.layout(J),Q=Y.size.width}else Q=0;if(this._height!==void 0)if(this._height===1/0)Z=J.maxHeight;else Z=this._height;else if(this.children.length>0){let Y=this.children[0];Y.layout(J),Z=Y.size.height}else Z=0;let X=J.constrain(Q,Z);if(this.setSize(X.width,X.height),this.children.length>0){let Y=this.children[0],K=d6.tight(X.width,X.height);Y.layout(K),Y.setOffset(0,0)}}}});var o5;var Du=p(()=>{PH();PJ();vU();u7();o5=class o5 extends BQ{flex;width;height;constructor({key:J,flex:Q=1,width:Z,height:X}={}){super(J?{key:J}:{});this.flex=Q,this.width=Z,this.height=X}createElement(){if(this.width!==void 0||this.height!==void 0){let J={child:new t6};if(this.width!==void 0)J.width=this.width;if(this.height!==void 0)J.height=this.height;return new i0(J).createElement()}else return new $2({flex:this.flex,child:i0.shrink()}).createElement()}static horizontal(J){return new o5({width:J})}static vertical(J){return new o5({height:J})}static flexible(J=1){return new o5({flex:J})}}});var Ky1,mZ6;var uZ6=p(()=>{I4();r9();r9();Y7();Ky1=class Ky1 extends h4{constructor(J){super({child:J.child})}createRenderObject(){return new mZ6}updateRenderObject(J){}};mZ6=class mZ6 extends H8{performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(0,0),super.performLayout();return}let Q=this.children[0],Z=Math.min(Q.getMaxIntrinsicWidth(J.maxHeight),J.maxWidth),X=Q.getMinIntrinsicHeight(Z),Y=new d6(Math.min(Z,J.minWidth),Math.min(Z,J.maxWidth),Math.min(X,J.maxHeight),Math.max(X,J.minHeight));Q.layout(Y),Q.setOffset(0,0);let q=J.minHeight===J.maxHeight?J.maxHeight:Math.min(X,J.maxHeight);this.setSize(Q.size.width,q),super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length===0)return 0;return this.children[0].getMinIntrinsicHeight(J)}getMaxIntrinsicHeight(J){if(this.children.length===0)return 0;return this.children[0].getMaxIntrinsicHeight(J)}getMinIntrinsicWidth(J){if(this.children.length===0)return 0;return this.children[0].getMinIntrinsicWidth(J)}getMaxIntrinsicWidth(J){if(this.children.length===0)return 0;return this.children[0].getMaxIntrinsicWidth(J)}}});var kU=p(()=>{kO();Jy1();zX();PJ();vU();J71();e41();hZ6();FY();Bu();$G();u7();Du();_O();z9();r9();kO();zX();PJ();vU();FY();$G();u7()});var pZ6=p(()=>{lx1();Ku()});class $6{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Q){this.widget=J,this.context=Q,this._mounted=!0,this.initState()}_update(J){let Q=this.widget;this.widget=J,this.didUpdateWidget(Q)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}var P6,qy1;var j2=p(()=>{qu();PH();P6=class P6 extends BQ{createElement(){return new qy1(this)}};qy1=class qy1 extends WY{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new TH(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Q=this._child,Z=this.findNearestRenderObjectAncestor();if(Z&&Q.renderObject)Z.dropChild(Q.renderObject);else if(!Z&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Z&&this._child.renderObject)Z.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Z&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}});var e6,Gy1;var m4=p(()=>{qu();PH();e6=class e6 extends BQ{createElement(){return new Gy1(this)}};Gy1=class Gy1 extends WY{_child;_context;constructor(J){super(J)}get statelessWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new TH(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let J=this.statelessWidget.build(this._context);if(this._child){if(this._child.widget===J)return;if(this._child.widget.canUpdate(J))this._child.update(J);else this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}}});var xO;var Y71=p(()=>{SO();xO=class xO extends jG{controller;constructor({key:J,controller:Q,child:Z}){super({key:J,child:Z});this.controller=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(xO);if(Q)return Q.widget.controller;return null}static require(J){let Q=xO.of(J);if(!Q)throw Error(`InheritedSelectionArea.require() called with a context that does not contain an InheritedSelectionArea.
5447
+ `+Y.toStringDeep(X,!0)}return Z}addKeyHandler(J){this._keyHandlers.push(J)}removeKeyHandler(J){let Q=this._keyHandlers.indexOf(J);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(J){for(let Q of this._keyHandlers)if(Q(J)==="handled")return"handled";return"ignored"}dispose(){this._detach(),this._children.clear(),this._keyHandlers=[]}}var CU=()=>{};class PV{static _instance=null;_rootScope;_primaryFocus=null;_cachedFocusableNodes=null;constructor(){this._rootScope=new O2({debugLabel:"Root Focus Scope",canRequestFocus:!1});let J=(Q)=>this.requestFocus(Q);J.__focusManager=this,O2.setRequestFocusCallback(J)}static get instance(){if(!this._instance)this._instance=new PV;return this._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(J){if(this._primaryFocus===J)return!0;if(J&&!J.canRequestFocus)return!1;if(this._primaryFocus)this._primaryFocus._setFocus(!1);if(this._primaryFocus=J,J)J._setFocus(!0);return!0}handleKeyEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handleKeyEvent(J)==="handled")return!0;Q=Q.parent}return!1}handlePasteEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(J)==="handled")return!0;Q=Q.parent}return!1}registerNode(J,Q=null){this._invalidateFocusableNodesCache();let Z=Q??this._rootScope;J._attach(Z)}unregisterNode(J){if(this._invalidateFocusableNodesCache(),this._primaryFocus===J)this.requestFocus(null);J._detach()}findNearestFocusableAncestor(J){let Q=J.parent;while(Q){if(Q.canRequestFocus&&!Q.skipTraversal)return Q;Q=Q.parent}return null}findAllFocusableNodes(){if(this._cachedFocusableNodes!==null)return this._cachedFocusableNodes;let J=[],Q=(Z)=>{if(Z.canRequestFocus&&!Z.skipTraversal)J.push(Z);for(let X of Z.children)Q(X)};return Q(this._rootScope),this._cachedFocusableNodes=J,J}_invalidateFocusableNodesCache(){this._cachedFocusableNodes=null}focusNext(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[0]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[0]??null);let Z=(Q+1)%J.length;return this.requestFocus(J[Z]??null)}focusPrevious(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[J.length-1]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[J.length-1]??null);let Z=Q===0?J.length-1:Q-1;return this.requestFocus(J[Z]??null)}dispose(){this._primaryFocus=null,this._cachedFocusableNodes=null,this._rootScope.dispose(),PV._instance=null}}var px1=p(()=>{CU()});function s41(J){if(J.length===0)return 0;let Q=[...J].sort((X,Y)=>X-Y),Z=Math.ceil(Q.length*0.99)-1;return Q[Math.max(0,Z)]||0}class AZ6{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];lastKeyEventTime=0;lastMouseEventTime=0;MAX_SAMPLES=1024;recordFrame(J){if(this.frameTimes.push(J),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(J,Q){let Z=this.phaseTimes[J];if(Z.push(Q),Z.length>this.MAX_SAMPLES)Z.shift()}recordKeyEvent(J){if(this.lastKeyEventTime=J,this.keyEventTimes.push(J),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(J){if(this.lastMouseEventTime=J,this.mouseEventTimes.push(J),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}getFrameP99(){return s41(this.frameTimes)}getPhaseP99(J){return s41(this.phaseTimes[J])}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return s41(this.keyEventTimes)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return s41(this.mouseEventTimes)}reset(){this.frameTimes=[];for(let J of Object.values(Xu))this.phaseTimes[J]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0}}class dx1{enabled=!1;tracker=new AZ6;setEnabled(J){this.enabled=J}isEnabled(){return this.enabled}recordKeyEvent(J){this.tracker.recordKeyEvent(J)}recordMouseEvent(J){this.tracker.recordMouseEvent(J)}recordStats(J){this.tracker.recordFrame(J.lastFrameTime);for(let Q of Object.values(Xu))this.tracker.recordPhase(Q,J.phaseStats[Q].lastTime)}draw(J,Q){if(!this.enabled)return;let{width:Z,height:X}=J.getSize(),Y=26,K=12,q=Z-Y-2,G=1;if(q<0||G+K>=X)return;let z=d1.white,U=d1.brightWhite,W=d1.yellow,F=" Gotta Go Fast ",H=Math.floor((Y-F.length)/2);J.setCell(q,G,m9("╭",{fg:U}));for(let b=1;b<Y-1;b++)if(b>=H&&b<H+F.length)J.setCell(q+b,G,m9(F[b-H]||"─",{fg:W}));else J.setCell(q+b,G,m9("─",{fg:U}));J.setCell(q+Y-1,G,m9("╮",{fg:U}));for(let b=1;b<K-1;b++){J.setCell(q,G+b,m9("│",{fg:U})),J.setCell(q+Y-1,G+b,m9("│",{fg:U}));for(let m=1;m<Y-1;m++)J.setCell(q+m,G+b,m9(" ",{fg:U}))}J.setCell(q,G+K-1,m9("╰",{fg:U}));for(let b=1;b<Y-1;b++)J.setCell(q+b,G+K-1,m9("─",{fg:U}));J.setCell(q+Y-1,G+K-1,m9("╯",{fg:U}));let D=q+1,M=G+1;this.drawText(J,D,M++," Last P99",z);let V=this.tracker.getLastKeyEventTime(),N=this.tracker.getKeyEventP99(),L=V.toFixed(2).padStart(5," "),A=N.toFixed(2).padStart(5," "),O=this.getTimingColor(V),j=this.getTimingColor(N),R=` ${"Key".padStart(6," ")} `;this.drawText(J,D,M,R,z),this.drawText(J,D+R.length,M,L,O),this.drawText(J,D+R.length+L.length,M," ",z),this.drawText(J,D+R.length+L.length+3,M++,A,j);let I=this.tracker.getLastMouseEventTime(),w=this.tracker.getMouseEventP99(),E=I.toFixed(2).padStart(5," "),$=w.toFixed(2).padStart(5," "),P=this.getTimingColor(I),C=this.getTimingColor(w),k=` ${"Mouse".padStart(6," ")} `;this.drawText(J,D,M,k,z),this.drawText(J,D+k.length,M,E,P),this.drawText(J,D+k.length+E.length,M," ",z),this.drawText(J,D+k.length+E.length+3,M++,$,C),M++;for(let b of["build","layout","paint","render"]){let m=Q.phaseStats[b].lastTime,n=this.tracker.getPhaseP99(b),u=m.toFixed(2).padStart(5," "),Q1=n.toFixed(2).padStart(5," "),z1=this.getTimingColor(m),F1=this.getTimingColor(n),H1=` ${(b.charAt(0).toUpperCase()+b.slice(1)).padStart(6," ")} `;this.drawText(J,D,M,H1,z),this.drawText(J,D+H1.length,M,u,z1),this.drawText(J,D+H1.length+u.length,M," ",z),this.drawText(J,D+H1.length+u.length+3,M++,Q1,F1)}M++;let g=Q.lastFrameTime,T=this.tracker.getFrameP99(),v=g.toFixed(2).padStart(5," "),f=T.toFixed(2).padStart(5," "),h=this.getTimingColor(g),S=this.getTimingColor(T),x=` ${"Frame".padStart(6," ")} `;this.drawText(J,D,M,x,U),this.drawText(J,D+x.length,M,v,h),this.drawText(J,D+x.length+v.length,M," ",U),this.drawText(J,D+x.length+v.length+3,M++,f,S)}getTimingColor(J){let Q=hx1,Z=hx1*0.7;if(J>=Q)return d1.red;if(J>=Z)return d1.yellow;return d1.white}drawText(J,Q,Z,X,Y){for(let K=0;K<X.length;K++)J.setCell(Q+K,Z,m9(X[K]||" ",{fg:Y}))}}var OZ6=p(()=>{z9();TO()});class BQ{key;constructor({key:J}={}){if(this.constructor===BQ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}}class WY{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this.parent;while(Q)J++,Q=Q.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Q=this._children.indexOf(J);if(Q!==-1)this._children.splice(Q,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){this._mounted=!0}unmount(){this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,LZ6().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Q=this.parent;while(Q){if(Q.widget.constructor===J){if("addDependent"in Q)Q.addDependent(this),this._inheritedDependencies.add(Q);return Q}Q=Q.parent}return null}findAncestorElementOfType(J){let Q=this.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){let Q=this.parent;while(Q){if(Q.widget instanceof J)return Q.widget;Q=Q.parent}return null}}var PH=()=>{};var jG,jZ6;var SO=p(()=>{PH();jG=class jG extends BQ{child;constructor({key:J,child:Q}){super(J!==void 0?{key:J}:{});this.child=Q}createElement(){return new jZ6(this)}};jZ6=class jZ6 extends WY{_child;_dependents=new Set;constructor(J){super(J)}get inheritedWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.inheritedWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._dependents.clear(),super.unmount()}update(J){let Q=this.inheritedWidget;super.update(J);let Z=this.inheritedWidget;if(Z.updateShouldNotify(Q))this.notifyDependents();if(this._child&&this._child.widget.canUpdate(Z.child))this._child.update(Z.child);else{if(this._child)this._child.unmount(),this.removeChild(this._child);this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount()}}addDependent(J){this._dependents.add(J)}removeDependent(J){this._dependents.delete(J)}notifyDependents(){for(let J of this._dependents)J.markNeedsRebuild()}performRebuild(){}}});class mT{size;capabilities;constructor(J,Q){this.size=J;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}var m8;var RG=p(()=>{SO();m8=class m8 extends jG{data;constructor({key:J,data:Q,child:Z}){super(J!==void 0?{key:J,child:Z}:{child:Z});this.data=Q}updateShouldNotify(J){return this.data!==J.data||this.data.size.width!==J.data.size.width||this.data.size.height!==J.data.size.height||this.data.capabilities!==J.data.capabilities}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(m8);if(Q)return Q.widget.data;throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.")}static sizeOf(J){return m8.of(J).size}static capabilitiesOf(J){return m8.of(J).capabilities}}});class TV{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;allowHitTestOutsideBounds=!1;parentData;get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this._parent;while(Q)J++,Q=Q._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),"setupParentData"in this&&typeof this.setupParentData==="function")this.setupParentData(J);if(this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Q=this._children.indexOf(J);if(Q!==-1){if(J._attached)J.detach();this._children.splice(Q,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Q of J)Q._parent=this,Q._invalidateDepth();this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else r41().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,r41().requestPaint(this)}performLayout(){}paint(J,Q=0,Z=0){this._needsPaint=!1;for(let X of this.children)if("offset"in X){let Y=X,K=Q+Y.offset.x,q=Z+Y.offset.y;X.paint(J,K,q)}else X.paint(J,Q,Z)}visitChildren(J){for(let Q of this._children)J(Q)}dispose(){r41().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}function CV(J,Q=0){return Number.isFinite(J)?J:Q}class d6{minWidth;maxWidth;minHeight;maxHeight;constructor(J=0,Q=1/0,Z=0,X=1/0){this.minWidth=J;this.maxWidth=Q;this.minHeight=Z;this.maxHeight=X}static tight(J,Q){return new d6(J,J,Q,Q)}static loose(J,Q){return new d6(0,J,0,Q)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Q){return q8(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),q8(isFinite(Q),`BoxConstraints.constrain received infinite height: ${Q}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Q))}}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}var H8;var r9=p(()=>{I4();H8=class H8 extends TV{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Q){q8(Number.isFinite(J)&&Number.isFinite(Q),`RenderBox.setSize received non-finite dimension: ${J}x${Q}`),this._size.width=J,this._size.height=Q}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Q){let Z=Number.isFinite(J)?Math.round(J):0,X=Number.isFinite(Q)?Math.round(Q):0;this._offset.x=Z,this._offset.y=X}localToGlobal(J){let{x:Q,y:Z}=J,X=this;while(X)if(Q+=X._offset.x,Z+=X._offset.y,X=X.parent,X&&!("_offset"in X))break;return{x:Q,y:Z}}globalToLocal(J){let Q=this.localToGlobal({x:0,y:0});return{x:J.x-Q.x,y:J.y-Q.y}}_lastConstraints;layout(J){let Q=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Q)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicWidth(J));return Z}getMaxIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicWidth(J));return Z}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicHeight(J));return Z}getMaxIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicHeight(J));return Z}paint(J,Q=0,Z=0){let X=J.getSize(),Y=X.width,K=X.height;for(let q of this.children)if(q instanceof H8){let G=Q+this.offset.x+q.offset.x,z=Z+this.offset.y+q.offset.y,U=G+q.size.width,W=z+q.size.height;if(!(G>=Y||z>=K||U<=0||W<=0))q.paint(J,Q+this.offset.x,Z+this.offset.y)}}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){J.addWithPaintOffset(this,{x:Y,y:K},Q);let z=!0;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}if(this.allowHitTestOutsideBounds){let z=!1;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}return!1}}});var uT,h4,wG,vO,Yu,SV,o41,pT;var Y7=p(()=>{PH();uT=class uT extends BQ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new Yu(this)}updateRenderObject(J){}};h4=class h4 extends uT{child;constructor({key:J,child:Q}={}){super(J?{key:J}:{});this.child=Q}createElement(){return new SV(this)}};wG=class wG extends uT{children;constructor({key:J,children:Q=[]}={}){super(J?{key:J}:{});this.children=[...Q]}createElement(){return new o41(this)}};vO=class vO extends uT{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new pT(this)}};Yu=class Yu extends WY{_renderObject;constructor(J){super(J)}get renderObjectWidget(){return this.widget}get renderObject(){return this._renderObject}mount(){this._renderObject=this.renderObjectWidget.createRenderObject(),this._renderObject.attach(),this.markMounted()}unmount(){if(this._renderObject)this._renderObject.detach(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Q=this.renderObjectWidget;if(this._renderObject)Q.updateRenderObject(this._renderObject)}performRebuild(){}};SV=class SV extends Yu{_child;constructor(J){super(J)}get singleChildWidget(){return this.widget}get child(){return this._child}mount(){if(super.mount(),this.singleChildWidget.child){if(this._child=this.singleChildWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject&&this.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Q=this.singleChildWidget;if(Q.child&&this._child){if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject){if(this.renderObject.removeAllChildren(),this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}else if(Q.child&&!this._child){if(this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject&&this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}else if(!Q.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this.renderObject)this.renderObject.removeAllChildren()}}performRebuild(){}};o41=class o41 extends Yu{_childElements=[];constructor(J){super(J)}get multiChildWidget(){return this.widget}get children(){return this._childElements}mount(){super.mount();for(let J of this.multiChildWidget.children){let Q=J.createElement();if(this._childElements.push(Q),this.addChild(Q),Q.mount(),Q.renderObject&&this.renderObject)this.renderObject.adoptChild(Q.renderObject)}}unmount(){for(let J of this._childElements)J.unmount(),this.removeChild(J);this._childElements.length=0,super.unmount()}update(J){super.update(J);let Q=this.multiChildWidget;this.updateChildren(this._childElements,[...Q.children])}updateChildren(J,Q){let Z=[],X=0,Y=0,K=J.length-1,q=Q.length-1;while(X<=K&&Y<=q){let U=J[X],W=Q[Y];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);Z.push(U),X++,Y++}let G=[];while(X<=K&&Y<=q){let U=J[K],W=Q[q];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);G.unshift(U),K--,q--}if(X>K)for(let U=Y;U<=q;U++){let W=Q[U];if(W){let F=this.createChildElement(W);Z.push(F)}}else if(Y>q)for(let U=X;U<=K;U++){let W=J[U];if(W)this.deactivateChild(W)}else{let U=new Map,W=new Map;for(let F=X;F<=K;F++){let H=J[F];if(H.widget.key){let D=H.widget.key.toString();U.set(D,H),W.set(D,F)}}for(let F=Y;F<=q;F++){let H=Q[F];if(!H)continue;let D;if(H.key){let M=H.key.toString();if(D=U.get(M),D){U.delete(M);let V=W.get(M);if(V!==void 0)J[V]=null;if(D.widget===H);else if(D.widget.canUpdate(H))D.update(H);else this.deactivateChild(D),D=this.createChildElement(H)}else D=this.createChildElement(H)}else{let M=!1;for(let V=X;V<=K;V++){let N=J[V];if(N&&!N.widget.key){if(N.widget===H){D=N,J[V]=null,M=!0;break}else if(N.widget.canUpdate(H)){D=N,J[V]=null,D.update(H),M=!0;break}}}if(!M)D=this.createChildElement(H)}if(D)Z.push(D)}for(let F=X;F<=K;F++){let H=J[F];if(H)this.deactivateChild(H)}for(let F of U.values())this.deactivateChild(F)}Z.push(...G);let z=this._childElements;if(this._childElements=Z,this.renderObject){let U=[];for(let H of Z)if(H.renderObject)U.push(H.renderObject);let W=this.renderObject.children;if(W.length!==U.length||W.some((H,D)=>H!==U[D]))this.renderObject.replaceChildren(U)}}createChildElement(J){let Q=J.createElement();return this.addChild(Q),Q.mount(),Q}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}};pT=class pT extends Yu{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}});var R5,RZ6,IG;var SU=p(()=>{I4();r9();Y7();Ku();R5=class R5 extends h4{child;onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;constructor({key:J,child:Q,onClick:Z,onEnter:X,onExit:Y,onHover:K,onScroll:q,onRelease:G,onDrag:z,cursor:U,opaque:W=!0}){super({key:J});this.child=Q,this.onClick=Z??null,this.onEnter=X??null,this.onExit=Y??null,this.onHover=K??null,this.onScroll=q??null,this.onRelease=G??null,this.onDrag=z??null,this.cursor=U??null,this.opaque=W}createElement(){return new RZ6(this)}createRenderObject(){return new IG({onClick:this.onClick,onEnter:this.onEnter,onExit:this.onExit,onHover:this.onHover,onScroll:this.onScroll,onRelease:this.onRelease,onDrag:this.onDrag,cursor:this.cursor,opaque:this.opaque})}updateRenderObject(J){J.onClick=this.onClick,J.onEnter=this.onEnter,J.onExit=this.onExit,J.onHover=this.onHover,J.onScroll=this.onScroll,J.onRelease=this.onRelease,J.onDrag=this.onDrag,J.cursor=this.cursor,J.opaque=this.opaque}};RZ6=class RZ6 extends SV{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}};IG=class IG extends H8{onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;_isHovered=!1;constructor({onClick:J,onEnter:Q,onExit:Z,onHover:X,onScroll:Y,onRelease:K,onDrag:q,cursor:G,opaque:z}){super();this.onClick=J,this.onEnter=Q,this.onExit=Z,this.onHover=X,this.onScroll=Y,this.onRelease=K,this.onDrag=q,this.cursor=G,this.opaque=z}get hasMouseListeners(){return!!(this.onClick||this.onEnter||this.onExit||this.onHover||this.onScroll||this.onRelease||this.onDrag)}get isHovered(){return this._isHovered}handleMouseEvent(J){switch(J.type){case"click":this.onClick?.(J);break;case"enter":this._isHovered=!0,this.onEnter?.(J);break;case"exit":this._isHovered=!1,this.onExit?.(J);break;case"hover":this.onHover?.(J);break;case"scroll":this.onScroll?.(J);break}}handleMouseRelease(J){this.onRelease?.(J)}handleMouseDrag(J){this.onDrag?.(J)}performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height),Q.setOffset(0,0)}else this.setSize(0,0);super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}getMinIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}paint(J,Q=0,Z=0){if(this.children.length>0)this.children[0].paint(J,Q+this.offset.x,Z+this.offset.y)}hitTest(J,Q,Z=0,X=0){let Y=super.hitTest(J,Q,Z,X);if(Y&&this.hasMouseListeners)J.addMouseTarget(this,Q);return Y}getDebugProperties(){return{hasMouseListeners:this.hasMouseListeners,isHovered:this.isHovered,cursor:this.cursor,opaque:this.opaque}}dispose(){DQ.instance.removeRegion(this),this.onClick=null,this.onEnter=null,this.onExit=null,this.onHover=null,this.onScroll=null,this.onRelease=null,this.onDrag=null,this.cursor=null,super.dispose()}}});class cx1{static hitTest(J,Q){let Z=new wZ6;return J.hitTest(Z,Q),Z}}class wZ6{_hits=[];get hits(){return this._hits}add(J){this._hits.push(J)}addWithPaintOffset(J,Q,Z){let X={x:Z.x-Q.x,y:Z.y-Q.y};this.add({target:J,localPosition:X})}addMouseTarget(J,Q){}}function S79(){if(!TV.prototype.hitTest)TV.prototype.hitTest=function(J,Q,Z=0,X=0){if("size"in this&&"offset"in this){let K=this,q=K.size,G=K.offset;if(q&&G){let z=Z+G.x,U=X+G.y,W=Q.x>=z&&Q.x<z+q.width,F=Q.y>=U&&Q.y<U+q.height;if(W&&F){let H={x:Q.x-z,y:Q.y-U};J.add({target:this,localPosition:H});let D=this.children,M=!0;for(let V=D.length-1;V>=0;V--)if(D[V].hitTest(J,Q,z,U))M=!0;return M}if(this.allowHitTestOutsideBounds){let H=!1,D=this.children;for(let M=D.length-1;M>=0;M--)if(D[M].hitTest(J,Q,z,U))H=!0;return H}return!1}}let Y=!1;for(let K of this.children)if(K.hitTest(J,Q,Z,X))Y=!0;return Y}}var lx1=p(()=>{r9();S79()});function IZ6(J,Q,Z){return{position:Q,localPosition:Z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}}}function EZ6(J,Q,Z,X=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:X,...IZ6(J,Q,Z)}}function $Z6(J,Q,Z){return{type:"scroll",direction:J.button==="wheel_up"?"up":"down",...IZ6(J,Q,Z)}}var DQ;var Ku=p(()=>{fT();SU();lx1();DQ=class DQ{static _instance=null;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=j5.DEFAULT;_lastMousePosition=null;_dragTargets=[];_globalReleaseCallbacks=new Set;_globalClickCallbacks=new Set;_lastClickTime=new Map;_lastClickPosition=new Map;_currentClickCount=new Map;static DOUBLE_CLICK_TIME=500;static DOUBLE_CLICK_DISTANCE=2;static DOUBLE_CLICK_DISTANCE_SQUARED=DQ.DOUBLE_CLICK_DISTANCE*DQ.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!this._instance)this._instance=new DQ;return this._instance}setRootRenderObject(J){this._rootRenderObject=J}setTui(J){this._vaxis=J}handleMouseEvent(J){if(!this._rootRenderObject)return;let Q={x:J.x,y:J.y},Z=cx1.hitTest(this._rootRenderObject,Q),X=this._findMouseTargets(Z.hits);switch(J.action){case"press":if(J.button==="left"||J.button==="middle"||J.button==="right"){if(this._handleClick(J,Q,X),J.button==="left")this._dragTargets=X.map(({target:Y,localPosition:K})=>{let q={x:Q.x-K.x,y:Q.y-K.y};return{target:Y,localPosition:K,globalOffset:q}})}break;case"release":this._handleRelease(J,Q,X),this._dragTargets=[];break;case"scroll":if(J.button==="wheel_up"||J.button==="wheel_down")this._handleScroll(J,Q,X);break;case"move":if(this._handleMove(J,Q,X),J.drag)this._handleDrag(J,Q,X);break}this._lastMousePosition=Q}addGlobalReleaseCallback(J){this._globalReleaseCallbacks.add(J)}removeGlobalReleaseCallback(J){this._globalReleaseCallbacks.delete(J)}addGlobalClickCallback(J){this._globalClickCallbacks.add(J)}removeGlobalClickCallback(J){this._globalClickCallbacks.delete(J)}requestCursorChange(J){if(this._vaxis&&J!==this._currentCursor)this._currentCursor=J,this._vaxis.setMouseCursor(J)}_handleRelease(J,Q,Z){for(let X of this._globalReleaseCallbacks)X();for(let{target:X,localPosition:Y}of Z){if(typeof X.handleMouseRelease==="function")X.handleMouseRelease({type:"release",position:Q,localPosition:Y,button:J.button,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}});if(X instanceof IG&&X.opaque)break}}_handleDrag(J,Q,Z){for(let{target:X,globalOffset:Y}of this._dragTargets)if(typeof X.handleMouseDrag==="function"){let K={x:Q.x-Y.x,y:Q.y-Y.y};X.handleMouseDrag({type:"drag",position:Q,localPosition:K,button:J.button,drag:J.drag,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}})}}_handleClick(J,Q,Z){let X=this._calculateClickCount(Q,J.button);for(let Y of this._globalClickCallbacks)Y({event:J,globalPosition:Q,mouseTargets:Z,clickCount:X});for(let{target:Y,localPosition:K}of Z){let q=EZ6(J,Q,K,X);if(Y.handleMouseEvent(q),Y instanceof IG&&Y.opaque)break}}_handleScroll(J,Q,Z){for(let{target:X,localPosition:Y}of Z){let K=$Z6(J,Q,Y);if(X.handleMouseEvent(K),X instanceof IG&&X.opaque)break}}_handleMove(J,Q,Z){let X=Z.filter((G)=>G.target instanceof IG),Y=this._scratchCurrentRegions,K=this._scratchExitedRegions,q=this._scratchEnteredRegions;Y.clear();for(let{target:G}of X)Y.add(G);K.clear();for(let G of this._hoveredRegions)if(!Y.has(G))K.add(G);q.clear();for(let G of Y)if(!this._hoveredRegions.has(G))q.add(G);for(let G of K)if(G.onExit){let z={type:"exit",position:Q,localPosition:Q,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(z)}for(let{target:G,localPosition:z}of X)if(q.has(G)&&G.onEnter){let U={type:"enter",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}for(let{target:G,localPosition:z}of X)if(G.onHover&&this._hoveredRegions.has(G)){let U={type:"hover",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}this._hoveredRegions.clear();for(let G of Y)this._hoveredRegions.add(G);this._updateCursor(X)}_updateCursor(J){if(!this._vaxis)return;let Q=j5.DEFAULT;for(let{target:Z}of J)if(Z.cursor!==null)Q=Z.cursor;if(Q!==this._currentCursor)this._currentCursor=Q,this._vaxis.setMouseCursor(Q)}_findMouseTargets(J){let Q=[];for(let Z of J)if(this._canHandleMouseEvents(Z.target))Q.push({target:Z.target,localPosition:Z.localPosition});return Q}_canHandleMouseEvents(J){if(J instanceof IG)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==j5.DEFAULT)this._currentCursor=j5.DEFAULT,this._vaxis.setMouseCursor(j5.DEFAULT)}removeRegion(J){this._hoveredRegions.delete(J)}reestablishHoverState(){if(!this._lastMousePosition||!this._rootRenderObject)return;let J={type:"mouse",action:"move",x:this._lastMousePosition.x,y:this._lastMousePosition.y,button:"unknown",drag:!1,modifiers:{shift:!1,ctrl:!1,alt:!1,meta:!1}};this.handleMouseEvent(J)}_calculateClickCount(J,Q="left"){let Z=Date.now(),X=this._lastClickTime.get(Q)??0,Y=Z-X,K=1,q=this._lastClickPosition.get(Q);if(q&&Y<=DQ.DOUBLE_CLICK_TIME&&this._isWithinDoubleClickDistance(J,q))K=(this._currentClickCount.get(Q)??0)+1;else K=1;return this._lastClickTime.set(Q,Z),this._lastClickPosition.set(Q,J),this._currentClickCount.set(Q,K),K}_isWithinDoubleClickDistance(J,Q){let Z=J.x-Q.x,X=J.y-Q.y;return Z*Z+X*X<=DQ.DOUBLE_CLICK_DISTANCE_SQUARED}dispose(){this.clearHoverState(),this._lastMousePosition=null,this._rootRenderObject=null,this._lastClickTime.clear(),this._lastClickPosition.clear(),this._currentClickCount.clear(),this._globalReleaseCallbacks.clear(),this._globalClickCallbacks.clear(),DQ._instance=null}}});class ix1{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(J){if(!XZ.instance.isFrameInProgress)XZ.instance.requestFrame()}requestPaint(J){if(this._nodesNeedingPaint.has(J))return;if(this._nodesNeedingPaint.add(J),!XZ.instance.isFrameInProgress)XZ.instance.requestFrame()}setRootRenderObject(J){this._rootRenderObject=J}updateRootConstraints(J){let Q=new d6(0,J.width,0,J.height),Z=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,Z&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints)}}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let J of this._nodesNeedingPaint)if(J.needsPaint)J._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return!1}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(J){this._nodesNeedingPaint.delete(J)}}var PZ6=p(()=>{TO();r9()});var TZ6={};L6(TZ6,{setTerminalFocused:()=>k79,initFocusTracking:()=>v79,getTerminalFocused:()=>ax1});function v79(J){let Q=(Z)=>{if(Z.type==="focus")nx1=Z.focused};J.onFocus(Q)}function ax1(){return nx1}function k79(J){nx1=J}var nx1=!0;var SZ6={};L6(SZ6,{initIdleTracking:()=>_79,getIsIdle:()=>rx1});function _79(J,Q=300000){CZ6=Q,t41=Date.now(),J.onKey(()=>{t41=Date.now()}),J.onMouse(()=>{t41=Date.now()})}function rx1(){return Date.now()-t41>=CZ6}var t41,CZ6=300000;var sx1=p(()=>{t41=Date.now()});class EG{static _instance;frameScheduler=XZ.instance;buildOwner;pipelineOwner;focusManager=PV.instance;mouseManager=DQ.instance;frameStatsOverlay=new dx1;tui=new fx1;rootElement;isRunning=!1;rootElementMountedCallback;static get instance(){return this._instance??=new EG}pendingResizeEvent=null;constructor(){this.buildOwner=new gx1,this.pipelineOwner=new ix1,this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>this.buildOwner.buildScopes(),"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{this.updateRootConstraints(),this.pipelineOwner.flushLayout()},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),VZ6({scheduleBuildFor:(J)=>this.buildOwner.scheduleBuildFor(J)},{requestLayout:(J)=>this.pipelineOwner.requestLayout(J),requestPaint:(J)=>this.pipelineOwner.requestPaint(J),removeFromQueues:(J)=>this.pipelineOwner.removeFromQueues(J)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(J)=>{a.error("Framework uncaught exception",J)})}async runApp(J){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => TZ6);Q(this.tui);let{initIdleTracking:Z}=await Promise.resolve().then(() => (sx1(),SZ6));Z(this.tui),await this.tui.waitForCapabilities(1000);let X=this.createMediaQueryWrapper(J);if(this.rootElement=X.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let Y=this.rootElement.renderObject;if(!Y&&this.rootElement.children.length>0)Y=this.rootElement.children[0]?.renderObject;if(Y)this.pipelineOwner.setRootRenderObject(Y),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),a.debug("Setting up event handlers..."),this.setupEventHandlers(),a.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),a.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),a.debug("waitForExit completed")}finally{a.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let J=this.tui.getSize();this.pipelineOwner.updateRootConstraints(J)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let J=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:J.width,height:J.height},Z=this.tui.getCapabilities()||{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3},X=new mT(Q,Z),Y=this.rootElement;if(Y.widget instanceof m8){let q=new m8({data:X,child:Y.widget.child});Y.update(q)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}paint(){if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let J=this.rootElement.renderObject;if(!J&&this.rootElement.children.length>0)J=this.rootElement.children[0]?.renderObject;if(!J)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(J,Q,0,0);let Z=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(Z),this.frameStatsOverlay.draw(Q,Z)}catch(Q){a.error("Paint error:",Q)}}render(){try{this.tui.render()}catch(J){a.error("Render error:",J)}}renderRenderObject(J,Q,Z,X){if("paint"in J&&typeof J.paint==="function")J.paint(Q,Z,X)}createMediaQueryWrapper(J){let Q=this.tui.getCapabilities()||{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3},Z=this.tui.getSize(),X=new mT(Z,Q);return new m8({data:X,child:J})}setupEventHandlers(){this.tui.onResize((J)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=J,this.frameScheduler.requestFrame()}),this.tui.onKey((J)=>{let Q=performance.now();if(this.focusManager.handleKeyEvent(J)){let Y=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(Y);return}this.handleGlobalKeyEvent(J);let X=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(X)}),this.tui.onMouse((J)=>{let Q=performance.now();this.mouseManager.handleMouseEvent(J);let Z=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(Z)}),this.tui.onPaste((J)=>{this.focusManager.handlePasteEvent(J)}),this.tui.onCapabilities((J)=>{if(this.rootElement){let Q=this.tui.getSize(),Z=new mT(Q,J.capabilities),X=this.rootElement;if(X.widget instanceof m8){let Y=new m8({data:Z,child:X.widget.child});X.update(Y)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(J){if(J.ctrlKey&&J.key==="z"&&!J.shiftKey&&!J.altKey&&!J.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let J=!this.frameStatsOverlay.isEnabled();this.frameStatsOverlay.setEnabled(J),this.frameScheduler.requestFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise)return this.exitPromise;return this.exitPromise=new Promise((J)=>{if(this.exitResolve=J,!this.isRunning)J()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(J){this.rootElementMountedCallback=J}}async function ox1(J,Q){let Z=EG.instance;if(Q?.stdin)Z.tuiInstance.setStdin(Q.stdin);if(Q?.onRootElementMounted)Z.setRootElementMountedCallback(Q.onRootElementMounted);await Z.runApp(J)}var tx1=p(()=>{D0();BZ6();MZ6();px1();TO();OZ6();RG();Ku();PZ6()});class TH{element;widget;mediaQuery;parent;constructor(J,Q,Z=void 0,X=null){this.element=J;this.widget=Q;this.mediaQuery=Z;this.parent=X}findAncestorElementOfType(J){let Q=this.element.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Q=this.element.parent;while(Q){if("state"in Q&&Q.state instanceof J)return Q.state;Q=Q.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof TV?J:void 0}return}}var qu=p(()=>{r9()});var vZ6=()=>{};class kZ6{constructor(){}}var s5;var Gu=p(()=>{s5=class s5 extends kZ6{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof s5))return!1;return this.value===J.value}get hashCode(){if(this.value===null||this.value===void 0)return 0;if(typeof this.value==="string")return this.stringHash(this.value);if(typeof this.value==="number")return this.value;if(typeof this.value==="boolean")return this.value?1:0;return this.stringHash(String(this.value))}stringHash(J){let Q=0;for(let Z=0;Z<J.length;Z++){let X=J.charCodeAt(Z);Q=(Q<<5)-Q+X,Q=Q&Q}return Q}toString(){return`ValueKey(${this.value})`}}});var w5,_Z6;var kO=p(()=>{I4();r9();Y7();w5=class w5 extends h4{constructor({key:J,child:Q}={}){super({key:J,child:Q})}createRenderObject(){return new _Z6}updateRenderObject(J){}static child(J){return new w5({child:J})}};_Z6=class _Z6 extends H8{constructor(){super()}performLayout(){let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this.children[0];if(!Q){let G=CV(J.maxWidth,J.minWidth),z=CV(J.maxHeight,J.minHeight);this.setSize(G,z),super.performLayout();return}Q.layout(d6.loose(J.maxWidth,J.maxHeight));let Z=J.maxWidth===1/0?Q.size.width:J.maxWidth,X=J.maxHeight===1/0?Q.size.height:J.maxHeight,Y=J.constrain(Z,X);this.setSize(Y.width,Y.height);let K=(this.size.width-Q.size.width)/2,q=(this.size.height-Q.size.height)/2;Q.setOffset(K,q),super.performLayout()}}});var CH;var zu=p(()=>{z9();CH=class CH extends em{_screen;_clipX;_clipY;_clipWidth;_clipHeight;constructor(J,Q,Z,X,Y){super(X,Y);this._screen=J,this._clipX=Q,this._clipY=Z,this._clipWidth=X,this._clipHeight=Y}setChar(J,Q,Z,X,Y=1){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setChar(J,Q,Z,X||{},Y)}setCell(J,Q,Z){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setCell(J,Q,Z)}fill(J,Q,Z,X,Y=" ",K){let q=Math.max(J,this._clipX),G=Math.max(Q,this._clipY),z=Math.min(J+Z,this._clipX+this._clipWidth),U=Math.min(Q+X,this._clipY+this._clipHeight);if(q<z&&G<U)this._screen.fill(q,G,z-q,U-G,Y,K)}getSize(){return this._screen.getSize()}resize(J,Q){return this._screen.resize(J,Q)}getBuffer(){return this._screen.getBuffer()}getFrontBuffer(){return this._screen.getFrontBuffer()}getBackBuffer(){return this._screen.getBackBuffer()}getCell(J,Q){return this._screen.getCell(J,Q)}clear(){return this._screen.clear()}present(){return this._screen.present()}getDiff(){return this._screen.getDiff()}markForRefresh(){return this._screen.markForRefresh()}setCursor(J,Q){return this._screen.setCursor(J,Q)}clearCursor(){return this._screen.clearCursor()}getCursor(){return this._screen.getCursor()}isCursorVisible(){return this._screen.isCursorVisible()}}});var ex1,bZ6;var Jy1=p(()=>{I4();zu();r9();Y7();ex1=class ex1 extends h4{clipBehavior;constructor(J,{key:Q,clipBehavior:Z="antiAlias"}={}){super(Q?{child:J,key:Q}:{child:J});this.clipBehavior=Z}createRenderObject(){return new bZ6(this.clipBehavior)}updateRenderObject(J){J.updateClipBehavior(this.clipBehavior)}};bZ6=class bZ6 extends H8{_clipBehavior;constructor(J){super();this._clipBehavior=J}updateClipBehavior(J){if(this._clipBehavior!==J)this._clipBehavior=J,this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(J.minWidth,J.minHeight),super.performLayout();return}this.children[0].layout(J),this.setSize(J.maxWidth,J.maxHeight),super.performLayout()}paint(J,Q=0,Z=0){if(this.children.length===0||this._clipBehavior==="none"){super.paint(J,Q,Z);return}let X=this.children[0],Y=Q+this.offset.x,K=Z+this.offset.y,q=this.size.width,G=this.size.height,z=new CH(J,Y,K,q,G);X.paint(z,Q+this.offset.x,Z+this.offset.y)}}});class Uu{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}var Wu;var e41=p(()=>{Wu=class Wu extends Uu{flex;fit;constructor(J=0,Q="tight"){super();this.flex=J,this.fit=Q}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}});var Fu,xZ6,yZ6;var J71=p(()=>{I4();r9();Y7();e41();Fu=class Fu extends wG{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Q,children:Z=[],mainAxisAlignment:X="start",crossAxisAlignment:Y="center",mainAxisSize:K="min"}){super({...J?{key:J}:{},children:Z});this.direction=Q,this.mainAxisAlignment=X,this.crossAxisAlignment=Y,this.mainAxisSize=K}createRenderObject(){return new yZ6(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new xZ6(this)}};xZ6=class xZ6 extends o41{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Q=J.renderObject;if(Q&&!Q.parentData)Q.parentData=new Wu(0,"tight")}}};yZ6=class yZ6 extends H8{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Q,Z,X){super();this._direction=J;this._mainAxisAlignment=Q;this._crossAxisAlignment=Z;this._mainAxisSize=X}updateProperties(J,Q,Z,X){this._direction=J,this._mainAxisAlignment=Q,this._crossAxisAlignment=Z,this._mainAxisSize=X,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this._direction==="horizontal",Z=[],X=[];for(let D of this.children){let M=D.parentData;if(M&&M.flex>0)Z.push({child:D,flex:M.flex,fit:M.fit});else X.push(D)}let Y=0,K=0,q,G=Q?J.maxHeight:J.maxWidth;if(isFinite(G))q=G;else{let D=0;for(let M of X){let V=Q?M.getMaxIntrinsicHeight(1/0):M.getMaxIntrinsicWidth(1/0);D=Math.max(D,V)}q=D}for(let D of X){let M=Q?new d6(0,1/0,0,q):new d6(0,q,0,1/0);if(D.layout(M),Q)Y+=D.size.width,K=Math.max(K,D.size.height);else Y+=D.size.height,K=Math.max(K,D.size.width)}let z=Q?J.maxWidth:J.maxHeight,U=Number.isFinite(z)?Math.max(0,z-Y):0,W=Z.reduce((D,M)=>D+M.flex,0);if(W>0){let D=U/W,M=0;for(let V=0;V<Z.length;V++){let{child:N,flex:L,fit:A}=Z[V],O;if(V===Z.length-1)O=U-M;else O=Math.floor(D*L),M+=O;let j=Q?J.maxHeight:J.maxWidth,R=Q?A==="tight"?new d6(O,O,0,j):d6.loose(O,j):A==="tight"?new d6(0,j,O,O):d6.loose(j,O);if(N.layout(R),Q)K=Math.max(K,N.size.height);else K=Math.max(K,N.size.width)}}let F=Y+(W>0?U:0);if(Q){q8(!(Z.length>0&&J.maxWidth===1/0&&this._mainAxisSize!=="min"),"RenderFlex children have non-zero flex but incoming width constraints are unbounded. Consider using MainAxisSize.min instead, or providing bounded width constraints.");let D=this._mainAxisSize==="min"||J.maxWidth===1/0?F:Math.max(J.minWidth,J.maxWidth);this.setSize(CV(D,J.minWidth),CV(K,J.minHeight))}else{q8(!(Z.length>0&&J.maxHeight===1/0&&this._mainAxisSize!=="min"),"RenderFlex children have non-zero flex but incoming height constraints are unbounded. Consider using MainAxisSize.min instead, or providing bounded height constraints.");let D=this._mainAxisSize==="min"||J.maxHeight===1/0?Math.min(Math.max(F,J.minHeight),J.maxHeight):Math.max(J.minHeight,J.maxHeight),M=this._mainAxisSize==="min"||J.maxHeight===1/0?Math.min(Math.max(K,J.minWidth),J.maxWidth):J.maxWidth;this.setSize(CV(M,J.minWidth),CV(D,J.minHeight))}if(this._crossAxisAlignment==="stretch"){let D=Q?this.size.height:this.size.width;for(let M of X){let V=Q?new d6(0,1/0,D,D):new d6(D,D,0,1/0);M.layout(V)}for(let{child:M}of Z){let V=Q?M.size.width:M.size.height,N=Q?new d6(V,V,D,D):new d6(D,D,V,V);M.layout(N)}}let H=Q?this.size.height:this.size.width;this.positionChildren(Q,H,J)}positionChildren(J,Q,Z){let X=this.children;if(X.length===0)return;let Y=0;for(let W of X)Y+=J?W.size.width:W.size.height;let K=J?this.size.width:this.size.height,q=Math.max(0,K-Y),G=0,z=0;switch(this._mainAxisAlignment){case"start":G=0;break;case"end":G=q;break;case"center":G=q/2;break;case"spaceBetween":z=X.length>1?Math.floor(q/(X.length-1)):0;break;case"spaceAround":z=X.length>0?q/X.length:0,G=z/2;break;case"spaceEvenly":z=X.length>0?Math.floor(q/(X.length+1)):0,G=z;break}let U=G;for(let W=0;W<X.length;W++){let F=X[W],H=J?F.size.width:F.size.height,D=J?F.size.height:F.size.width,M=0;switch(this._crossAxisAlignment){case"start":M=0;break;case"end":M=Q-D;break;case"center":M=(Q-D)/2;break;case"stretch":M=0;break;case"baseline":if(!J)throw Error("CrossAxisAlignment.baseline is only supported for horizontal flex (Row)");M=0;break}if(J)F.setOffset(U,M);else F.setOffset(M,U);if(U+=H,W<X.length-1)U+=z}}getMinIntrinsicWidth(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMinIntrinsicWidth(J)}return X}else{let X=0;for(let Y of Z)X=Math.max(X,Y.getMinIntrinsicWidth(J));return X}}getMaxIntrinsicWidth(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMaxIntrinsicWidth(J)}return X}else{let X=0;for(let Y of Z)X=Math.max(X,Y.getMaxIntrinsicWidth(J));return X}}getMaxIntrinsicHeight(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0,Y=0,K=[],q=[];for(let U of Z){let W=U.parentData;if(W&&W.flex>0)Y+=W.flex,q.push({child:U,flex:W.flex});else K.push(U)}let G=0;for(let U of K)G+=U.getMaxIntrinsicWidth(0);let z=Math.max(0,J-G);for(let U of Z){let W=U.parentData,F=J;if(W&&W.flex>0&&Y>0)F=z/Y*W.flex;X=Math.max(X,U.getMaxIntrinsicHeight(F))}return X}else{let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMaxIntrinsicHeight(J)}return X}}getMinIntrinsicHeight(J){let Q=this._direction==="horizontal",Z=this.children;if(Q){let X=0,Y=0,K=[],q=[];for(let U of Z){let W=U.parentData;if(W&&W.flex>0)Y+=W.flex,q.push(U);else K.push(U)}let G=0;for(let U of K)G+=U.getMinIntrinsicWidth(0);let z=Math.max(0,J-G);for(let U of Z){let W=U.parentData,F=J;if(W&&W.flex>0&&Y>0)F=z/Y*W.flex;X=Math.max(X,U.getMinIntrinsicHeight(F))}return X}else{let X=0;for(let Y of Z){let K=Y.parentData;if(!K||K.flex===0)X+=Y.getMinIntrinsicHeight(J)}return X}}dispose(){this._direction="vertical",this._mainAxisAlignment="start",this._crossAxisAlignment="start",this._mainAxisSize="min",super.dispose()}}});var O6;var zX=p(()=>{J71();O6=class O6 extends Fu{constructor({key:J,children:Q=[],mainAxisAlignment:Z="start",crossAxisAlignment:X="center",mainAxisSize:Y="max"}={}){super({...J?{key:J}:{},direction:"vertical",children:Q,mainAxisAlignment:Z,crossAxisAlignment:X,mainAxisSize:Y})}static start(J){return new O6({children:J,mainAxisAlignment:"start"})}static center(J){return new O6({children:J,mainAxisAlignment:"center"})}static end(J){return new O6({children:J,mainAxisAlignment:"end"})}static spaceBetween(J){return new O6({children:J,mainAxisAlignment:"spaceBetween"})}static spaceAround(J){return new O6({children:J,mainAxisAlignment:"spaceAround"})}static spaceEvenly(J){return new O6({children:J,mainAxisAlignment:"spaceEvenly"})}}});class g2{color;border;constructor(J,Q){this.color=J;this.border=Q}}class H4{top;right;bottom;left;constructor(J,Q,Z,X){this.top=J;this.right=Q;this.bottom=Z;this.left=X}static all(J){return new H4(J,J,J,J)}static symmetric(J,Q){return new H4(Q,J,Q,J)}}class g4{color;width;style;constructor(J=d1.black,Q=1,Z="rounded"){this.color=J;this.width=Q;this.style=Z}}var t6,Q71;var PJ=p(()=>{I4();z9();r9();Y7();t6=class t6 extends h4{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Q,width:Z,height:X,padding:Y,margin:K,decoration:q,constraints:G}={}){super({...J?{key:J}:{},...Q?{child:Q}:{}});this.width=Z,this.height=X,this.padding=Y,this.margin=K,this.decoration=q,this.constraints=G}createRenderObject(){return new Q71(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof Q71))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}};Q71=class Q71 extends H8{_width;_height;_padding;_margin;_decoration;_constraints;constructor(J,Q,Z,X,Y,K){super();this._width=J;this._height=Q;this._padding=Z;this._margin=X;this._decoration=Y;this._constraints=K}updateProperties(J,Q,Z,X,Y,K){this._width=J,this._height=Q,this._padding=Z,this._margin=X,this._decoration=Y,this._constraints=K,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=J;if(this._constraints)Q=new d6(Math.max(J.minWidth,this._constraints.minWidth),Math.min(J.maxWidth,this._constraints.maxWidth),Math.max(J.minHeight,this._constraints.minHeight),Math.min(J.maxHeight,this._constraints.maxHeight));let Z=this._margin?.horizontal??0,X=this._margin?.vertical??0,Y=this._padding?.horizontal??0,K=this._padding?.vertical??0,q=this._decoration?.border,G=(q?.left?1:0)+(q?.right?1:0),z=(q?.top?1:0)+(q?.bottom?1:0),U,W;if(this._width!==void 0)U=this._width;if(this._height!==void 0)W=this._height;let F,H;if(U!==void 0)F=Math.max(0,U-Z-Y-G);else F=Q.maxWidth-Z-Y-G;if(W!==void 0)H=Math.max(0,W-X-K-z);else H=Q.maxHeight-X-K-z;let D=new d6(Math.max(0,Q.minWidth-Z-Y-G),Math.max(0,F),Math.max(0,Q.minHeight-X-K-z),Math.max(0,H)),M,V;if(this.children.length>0){let A=this.children[0];if(!(A instanceof H8))throw Error("Child must be a RenderBox");A.layout(D),M=A.size.width,V=A.size.height;let O=q?.left?1:0,j=q?.top?1:0,R=(this._margin?.left??0)+O+(this._padding?.left??0),I=(this._margin?.top??0)+j+(this._padding?.top??0);A.setOffset(R,I)}else M=0,V=0;let N,L;if(U!==void 0)N=U;else N=M+Y+G+Z;if(W!==void 0)L=W;else L=V+K+z+X;if(Q.minWidth===Q.maxWidth&&isFinite(Q.maxWidth))N=Q.maxWidth;if(Q.minHeight===Q.maxHeight&&isFinite(Q.maxHeight))L=Q.maxHeight;this.setSize(Q.constrain(N,L).width,Q.constrain(N,L).height)}getMinIntrinsicWidth(J){let Q=this._margin?.horizontal??0,Z=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),K=0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));K=q.getMinIntrinsicWidth(G)}return K+Q+Z+Y}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.maxWidth!==1/0)return this._constraints.maxWidth;let Q=this._margin?.horizontal??0,Z=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),K=1/0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));K=q.getMaxIntrinsicWidth(G)}if(K===1/0)return 1/0;return K+Q+Z+Y}getMinIntrinsicHeight(J){let Q=this._margin?.vertical??0,Z=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),K=0;if(this.children.length>0){let G=this.children[0],z=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));K=G.getMinIntrinsicHeight(z)}let q=K+Q+Z+Y;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(q,this._constraints.maxHeight);return q}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.maxHeight!==1/0)return this._constraints.maxHeight;let Q=this._margin?.vertical??0,Z=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),K=0;if(this.children.length>0){let q=this.children[0],G=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));K=q.getMaxIntrinsicHeight(G)}if(K===1/0)return 1/0;return K+Q+Z+Y}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y);if(this._decoration?.color){let K={bg:this._decoration.color};J.fill(X,Y,this.size.width,this.size.height," ",K)}if(this._decoration?.border)this._paintBorder(J,X,Y);super.paint(J,Q,Z)}_paintBorder(J,Q,Z){let X=this._decoration.border,Y=this.size.width,K=this.size.height,q=(H)=>{switch(H){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},G=(H)=>{switch(H){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},z=(H,D)=>{if(H===1)return D?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"};else return D?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┏",tr:"┓",bl:"┗",br:"┛"}};if(X.top){let H={fg:X.top.color},D=q(X.top.width);for(let M=0;M<Y;M++)J.setChar(Q+M,Z,D,H,1)}if(X.bottom){let H={fg:X.bottom.color},D=q(X.bottom.width);for(let M=0;M<Y;M++)J.setChar(Q+M,Z+K-1,D,H,1)}if(X.left){let H={fg:X.left.color},D=G(X.left.width);for(let M=0;M<K;M++)J.setChar(Q,Z+M,D,H,1)}if(X.right){let H={fg:X.right.color},D=G(X.right.width);for(let M=0;M<K;M++)J.setChar(Q+Y-1,Z+M,D,H,1)}let U=X.top?.style==="rounded",W=Math.max(X.top?.width??1,X.right?.width??1,X.bottom?.width??1,X.left?.width??1),F=z(W,U);if(X.top&&X.left){let H={fg:X.top.color};J.setChar(Q,Z,F.tl,H,1)}if(X.top&&X.right){let H={fg:X.top.color};J.setChar(Q+Y-1,Z,F.tr,H,1)}if(X.bottom&&X.left){let H={fg:X.bottom.color};J.setChar(Q,Z+K-1,F.bl,H,1)}if(X.bottom&&X.right){let H={fg:X.bottom.color};J.setChar(Q+Y-1,Z+K-1,F.br,H,1)}}hitTest(J,Q,Z=0,X=0){return super.hitTest(J,Q,Z,X)}_getBorderWidth(){let J=this._decoration?.border;if(!J)return 0;let Q=[J.top,J.right,J.bottom,J.left].filter((Z)=>Z!==void 0);return Q.length>0?Math.max(...Q.map((Z)=>Z.width)):0}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}});var Hu,fZ6;var Z71=p(()=>{PH();Hu=class Hu extends BQ{child;constructor(J,Q){super(Q);this.child=J}createElement(){return new fZ6(this)}};fZ6=class fZ6 extends WY{_child;constructor(J){super(J)}get parentDataWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.parentDataWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._applyParentData()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Q=J;if(this._child)if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount();else this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount();this._applyParentData()}performRebuild(){this._applyParentData()}_applyParentData(){let J=this._child;if(!J)return;let Q=J.renderObject;if(!Q)return;if(!this.parentDataWidget.debugIsValidRenderObject(Q))throw Error(`ParentDataWidget ${this.parentDataWidget.constructor.name} provided parent data to ${Q.constructor.name}, but ${Q.constructor.name} doesn't support this type of parent data.`);if(!Q.parentData||Q.parentData.constructor!==this.parentDataWidget.createParentData().constructor)Q.parentData=this.parentDataWidget.createParentData();this.parentDataWidget.applyParentData(Q)}}});var $2;var vU=p(()=>{Z71();e41();$2=class $2 extends Hu{flex;constructor({child:J,flex:Q=1,key:Z}){super(J,Z);this.flex=Q}createParentData(){return new Wu(this.flex,"tight")}applyParentData(J){let Q=J.parentData;if(Q)Q.flex=this.flex,Q.fit="tight"}debugIsValidRenderObject(J){return!0}toString(){return`Expanded(flex: ${this.flex}, child: ${this.child})`}}});var hZ6=()=>{};class B6{left;top;right;bottom;constructor(J,Q,Z,X){this.left=J;this.top=Q;this.right=Z;this.bottom=X}static all(J){return new B6(J,J,J,J)}static symmetric(J=0,Q=0){return new B6(J,Q,J,Q)}static horizontal(J){return new B6(J,0,J,0)}static vertical(J){return new B6(0,J,0,J)}static only(J){return new B6(J.left??0,J.top??0,J.right??0,J.bottom??0)}get horizontal(){return this.left+this.right}get vertical(){return this.top+this.bottom}}var S8,Zy1,Xy1;var FY=p(()=>{I4();r9();PH();S8=class S8 extends BQ{padding;child;constructor({key:J,padding:Q,child:Z}){super(J?{key:J}:{});this.padding=Q,this.child=Z}createElement(){return new Zy1(this)}};Zy1=class Zy1 extends WY{_child;_renderObject;constructor(J){super(J)}get paddingWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._renderObject}mount(){if(this._renderObject=new Xy1(this.paddingWidget.padding),this._renderObject.attach(),this.paddingWidget.child){if(this._child=this.paddingWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject)this._renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._renderObject)this._renderObject.detach(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Q=this.paddingWidget;if(this._renderObject)this._renderObject.updatePadding(Q.padding);if(Q.child&&this._child){if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this._renderObject&&this._child.renderObject)this._renderObject.removeAllChildren(),this._renderObject.adoptChild(this._child.renderObject)}else if(Q.child&&!this._child){if(this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this._renderObject&&this._child.renderObject)this._renderObject.adoptChild(this._child.renderObject)}else if(!Q.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this._renderObject)this._renderObject.removeAllChildren()}}performRebuild(){}};Xy1=class Xy1 extends H8{_padding;constructor(J){super();this._padding=J}updatePadding(J){this._padding=J,this.markNeedsLayout()}get padding(){return this._padding}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this._padding.horizontal,Z=this._padding.vertical,X=new d6(Math.max(0,J.minWidth-Q),Math.max(0,J.maxWidth-Q),Math.max(0,J.minHeight-Z),Math.max(0,J.maxHeight-Z));if(this.children.length>0){let Y=this.children[0];Y.layout(X),Y.setOffset(this._padding.left,this._padding.top),this.setSize(Y.size.width+Q,Y.size.height+Z)}else this.setSize(J.minWidth+Q,J.minHeight+Z)}getMinIntrinsicWidth(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Z);return X.getMinIntrinsicWidth(Y)+Q}return Q}getMinIntrinsicHeight(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Q);return X.getMinIntrinsicHeight(Y)+Z}return Z}getMaxIntrinsicWidth(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Z);return X.getMaxIntrinsicWidth(Y)+Q}return Q}getMaxIntrinsicHeight(J){let Q=this._padding.horizontal,Z=this._padding.vertical;if(this.children.length>0){let X=this.children[0],Y=Math.max(0,J-Q);return X.getMaxIntrinsicHeight(Y)+Z}return Z}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){let W={x:Q.x-Y,y:Q.y-K};J.add({target:this,localPosition:W});for(let F=this.children.length-1;F>=0;F--){let H=this.children[F];if(H&&"hitTest"in H&&typeof H.hitTest==="function")H.hitTest(J,Q,Y,K)}return!0}let z=Z+this.offset.x,U=X+this.offset.y;for(let W of this.children)if("hitTest"in W&&typeof W.hitTest==="function")W.hitTest(J,Q,z,U);return!1}}});var bK,X71,gZ6;var _O=p(()=>{I4();r9();Y7();bK=class bK extends wG{constructor({key:J,children:Q=[]}={}){super({...J?{key:J}:{},children:Q})}createRenderObject(){return new gZ6}updateRenderObject(J){}};X71=class X71 extends Uu{left;top;right;bottom;width;height;constructor(J,Q,Z,X,Y,K){super();this.left=J,this.top=Q,this.right=Z,this.bottom=X,this.width=Y,this.height=K}};gZ6=class gZ6 extends H8{constructor(){super();this.allowHitTestOutsideBounds=!0}setupParentData(J){if(!J.parentData)J.parentData=new X71}performLayout(){let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=0,Z=0,X=this.children;for(let q of X){let G=q.parentData;if(!G||!G.left&&!G.top&&!G.right&&!G.bottom)q.layout(J),Q=Math.max(Q,q.size.width),Z=Math.max(Z,q.size.height)}let Y=Math.max(Q,J.minWidth),K=Math.max(Z,J.minHeight);this.setSize(Y,K);for(let q of X){let G=q.parentData;if(G&&(G.left!==void 0||G.top!==void 0||G.right!==void 0||G.bottom!==void 0))this.layoutPositionedChild(q,G);else q.setOffset(0,0)}super.performLayout()}layoutPositionedChild(J,Q){let{width:Z,height:X}=Q;if(Z===void 0&&Q.left!==void 0&&Q.right!==void 0)Z=this.size.width-Q.left-Q.right;if(X===void 0&&Q.top!==void 0&&Q.bottom!==void 0)X=this.size.height-Q.top-Q.bottom;let Y=new d6(Z??0,Z??this.size.width,X??0,X??this.size.height);J.layout(Y);let K=0,q=0;if(Q.left!==void 0)K=Q.left;else if(Q.right!==void 0)K=this.size.width-Q.right-J.size.width;if(Q.top!==void 0)q=Q.top;else if(Q.bottom!==void 0)q=this.size.height-Q.bottom-J.size.height;J.setOffset(K,q)}}});var bO;var Bu=p(()=>{Z71();_O();bO=class bO extends Hu{left;top;right;bottom;width;height;constructor({key:J,left:Q,top:Z,right:X,bottom:Y,width:K,height:q,child:G}){super(G,J);this.left=Q,this.top=Z,this.right=X,this.bottom=Y,this.width=K,this.height=q}createParentData(){return new X71(this.left,this.top,this.right,this.bottom,this.width,this.height)}applyParentData(J){let Q=J.parentData;if(Q)Q.left=this.left,Q.top=this.top,Q.right=this.right,Q.bottom=this.bottom,Q.width=this.width,Q.height=this.height}debugIsValidRenderObject(J){return!0}updateParentData(J){let Q=J.parentData,Z=!1;if(Q.left!==this.left)Q.left=this.left,Z=!0;if(Q.top!==this.top)Q.top=this.top,Z=!0;if(Q.right!==this.right)Q.right=this.right,Z=!0;if(Q.bottom!==this.bottom)Q.bottom=this.bottom,Z=!0;if(Q.width!==this.width)Q.width=this.width,Z=!0;if(Q.height!==this.height)Q.height=this.height,Z=!0;if(Z){let X=J.parent;if(X&&"markNeedsLayout"in X)X.markNeedsLayout()}}}});var N9;var $G=p(()=>{J71();N9=class N9 extends Fu{constructor({key:J,children:Q=[],mainAxisAlignment:Z="start",crossAxisAlignment:X="center",mainAxisSize:Y="max"}={}){super({...J?{key:J}:{},direction:"horizontal",children:Q,mainAxisAlignment:Z,crossAxisAlignment:X,mainAxisSize:Y})}static start(J){return new N9({children:J,mainAxisAlignment:"start"})}static center(J){return new N9({children:J,mainAxisAlignment:"center"})}static end(J){return new N9({children:J,mainAxisAlignment:"end"})}static spaceBetween(J){return new N9({children:J,mainAxisAlignment:"spaceBetween"})}static spaceAround(J){return new N9({children:J,mainAxisAlignment:"spaceAround"})}static spaceEvenly(J){return new N9({children:J,mainAxisAlignment:"spaceEvenly"})}}});var i0,Yy1;var u7=p(()=>{I4();r9();Y7();i0=class i0 extends h4{width;height;constructor({key:J,width:Q,height:Z,child:X}={}){super({key:J,child:X});this.width=Q,this.height=Z}createRenderObject(){return new Yy1(this.width,this.height)}updateRenderObject(J){J.updateDimensions(this.width,this.height)}static fromSize(J,Q,Z){return Z?new i0({width:J,height:Q,child:Z}):new i0({width:J,height:Q})}static expand(J){return J?new i0({width:1/0,height:1/0,child:J}):new i0({width:1/0,height:1/0})}static shrink(J){return J?new i0({width:0,height:0,child:J}):new i0({width:0,height:0})}static height(J,Q){return Q?new i0({height:J,child:Q}):new i0({height:J})}static width(J,Q){return Q?new i0({width:J,child:Q}):new i0({width:J})}};Yy1=class Yy1 extends H8{_width;_height;constructor(J,Q){super();this._width=J;this._height=Q}updateDimensions(J,Q){let Z=this._width,X=this._height;if(this._width=J,this._height=Q,Z!==J||X!==Q)this.markNeedsLayout()}getMinIntrinsicWidth(J){if(this._width!==void 0)return this._width===1/0?0:this._width;if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width===1/0?1/0:this._width;if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}getMinIntrinsicHeight(J){if(this._height!==void 0)return this._height===1/0?0:this._height;if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height===1/0?1/0:this._height;if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}performLayout(){super.performLayout();let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q,Z;if(this._width!==void 0)if(this._width===1/0)Q=J.maxWidth;else Q=this._width;else if(this.children.length>0){let Y=this.children[0];Y.layout(J),Q=Y.size.width}else Q=0;if(this._height!==void 0)if(this._height===1/0)Z=J.maxHeight;else Z=this._height;else if(this.children.length>0){let Y=this.children[0];Y.layout(J),Z=Y.size.height}else Z=0;let X=J.constrain(Q,Z);if(this.setSize(X.width,X.height),this.children.length>0){let Y=this.children[0],K=d6.tight(X.width,X.height);Y.layout(K),Y.setOffset(0,0)}}}});var o5;var Du=p(()=>{PH();PJ();vU();u7();o5=class o5 extends BQ{flex;width;height;constructor({key:J,flex:Q=1,width:Z,height:X}={}){super(J?{key:J}:{});this.flex=Q,this.width=Z,this.height=X}createElement(){if(this.width!==void 0||this.height!==void 0){let J={child:new t6};if(this.width!==void 0)J.width=this.width;if(this.height!==void 0)J.height=this.height;return new i0(J).createElement()}else return new $2({flex:this.flex,child:i0.shrink()}).createElement()}static horizontal(J){return new o5({width:J})}static vertical(J){return new o5({height:J})}static flexible(J=1){return new o5({flex:J})}}});var Ky1,mZ6;var uZ6=p(()=>{I4();r9();r9();Y7();Ky1=class Ky1 extends h4{constructor(J){super({child:J.child})}createRenderObject(){return new mZ6}updateRenderObject(J){}};mZ6=class mZ6 extends H8{performLayout(){let J=this._lastConstraints;if(q8(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(0,0),super.performLayout();return}let Q=this.children[0],Z=Math.min(Q.getMaxIntrinsicWidth(J.maxHeight),J.maxWidth),X=Q.getMinIntrinsicHeight(Z),Y=new d6(Math.min(Z,J.minWidth),Math.min(Z,J.maxWidth),Math.min(X,J.maxHeight),Math.max(X,J.minHeight));Q.layout(Y),Q.setOffset(0,0);let q=J.minHeight===J.maxHeight?J.maxHeight:Math.min(X,J.maxHeight);this.setSize(Q.size.width,q),super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length===0)return 0;return this.children[0].getMinIntrinsicHeight(J)}getMaxIntrinsicHeight(J){if(this.children.length===0)return 0;return this.children[0].getMaxIntrinsicHeight(J)}getMinIntrinsicWidth(J){if(this.children.length===0)return 0;return this.children[0].getMinIntrinsicWidth(J)}getMaxIntrinsicWidth(J){if(this.children.length===0)return 0;return this.children[0].getMaxIntrinsicWidth(J)}}});var kU=p(()=>{kO();Jy1();zX();PJ();vU();J71();e41();hZ6();FY();Bu();$G();u7();Du();_O();z9();r9();kO();zX();PJ();vU();FY();$G();u7()});var pZ6=p(()=>{lx1();Ku()});class $6{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Q){this.widget=J,this.context=Q,this._mounted=!0,this.initState()}_update(J){let Q=this.widget;this.widget=J,this.didUpdateWidget(Q)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}var P6,qy1;var j2=p(()=>{qu();PH();P6=class P6 extends BQ{createElement(){return new qy1(this)}};qy1=class qy1 extends WY{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new TH(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Q=this._child,Z=this.findNearestRenderObjectAncestor();if(Z&&Q.renderObject)Z.dropChild(Q.renderObject);else if(!Z&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Z&&this._child.renderObject)Z.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Z&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}});var e6,Gy1;var m4=p(()=>{qu();PH();e6=class e6 extends BQ{createElement(){return new Gy1(this)}};Gy1=class Gy1 extends WY{_child;_context;constructor(J){super(J)}get statelessWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new TH(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let J=this.statelessWidget.build(this._context);if(this._child){if(this._child.widget===J)return;if(this._child.widget.canUpdate(J))this._child.update(J);else this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}}});var xO;var Y71=p(()=>{SO();xO=class xO extends jG{controller;constructor({key:J,controller:Q,child:Z}){super({key:J,child:Z});this.controller=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(xO);if(Q)return Q.widget.controller;return null}static require(J){let Q=xO.of(J);if(!Q)throw Error(`InheritedSelectionArea.require() called with a context that does not contain an InheritedSelectionArea.
5448
5448
  No InheritedSelectionArea ancestor could be found starting from the given context. This can happen if the context comes from a widget above the SelectionArea.
5449
- The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J){return this.controller!==J.controller}}});function cZ6(J,Q,Z){if(J.selectableId===Q.selectableId)return J.offset-Q.offset;return Z(J.selectableId,Q.selectableId)}var dZ6;var K71=p(()=>{dZ6={left:1,top:1,right:0,bottom:0}});class q71{foreground;mutedForeground;background;primary;secondary;accent;border;success;warning;info;destructive;selection;copyHighlight;tableBorder;constructor({foreground:J,mutedForeground:Q,background:Z,primary:X,secondary:Y,accent:K,border:q,success:G,warning:z,info:U,destructive:W,selection:F,copyHighlight:H,tableBorder:D}){this.foreground=J,this.mutedForeground=Q,this.background=Z,this.primary=X,this.secondary=Y,this.accent=K,this.border=q,this.success=G,this.warning=z,this.info=U,this.destructive=W,this.selection=F,this.copyHighlight=H,this.tableBorder=D}static default(){return new q71({foreground:d1.default(),mutedForeground:d1.index(7),background:d1.default(),primary:d1.blue,secondary:d1.cyan,accent:d1.magenta,border:d1.index(7),success:d1.green,warning:d1.yellow,info:d1.index(12),destructive:d1.red,selection:d1.index(8),copyHighlight:d1.yellow,tableBorder:d1.index(7)})}}class kH{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new kH({colorScheme:q71.default()})}}var j8;var p7=p(()=>{z9();SO();j8=class j8 extends jG{data;constructor({key:J,data:Q,child:Z}){super({key:J,child:Z});this.data=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(j8);if(Q)return Q.widget.data;return kH.default()}static maybeOf(J){let Q=J.dependOnInheritedWidgetOfExactType(j8);if(Q)return Q.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}});class v1{color;backgroundColor;bold;italic;underline;strikethrough;dim;constructor({color:J,backgroundColor:Q,bold:Z,italic:X,underline:Y,strikethrough:K,dim:q}={}){if(J!==void 0)this.color=J;if(Q!==void 0)this.backgroundColor=Q;if(Z!==void 0)this.bold=Z;if(X!==void 0)this.italic=X;if(Y!==void 0)this.underline=Y;if(K!==void 0)this.strikethrough=K;if(q!==void 0)this.dim=q}copyWith({color:J,backgroundColor:Q,bold:Z,italic:X,underline:Y,strikethrough:K,dim:q}){let G={};if(J!==void 0||this.color!==void 0)G.color=J??this.color;if(Q!==void 0||this.backgroundColor!==void 0)G.backgroundColor=Q??this.backgroundColor;if(Z!==void 0||this.bold!==void 0)G.bold=Z??this.bold;if(X!==void 0||this.italic!==void 0)G.italic=X??this.italic;if(Y!==void 0||this.underline!==void 0)G.underline=Y??this.underline;if(K!==void 0||this.strikethrough!==void 0)G.strikethrough=K??this.strikethrough;if(q!==void 0||this.dim!==void 0)G.dim=q??this.dim;return new v1(G)}merge(J){if(!J)return this;let Q={};if(J.color!==void 0||this.color!==void 0)Q.color=J.color??this.color;if(J.backgroundColor!==void 0||this.backgroundColor!==void 0)Q.backgroundColor=J.backgroundColor??this.backgroundColor;if(J.bold!==void 0||this.bold!==void 0)Q.bold=J.bold??this.bold;if(J.italic!==void 0||this.italic!==void 0)Q.italic=J.italic??this.italic;if(J.underline!==void 0||this.underline!==void 0)Q.underline=J.underline??this.underline;if(J.strikethrough!==void 0||this.strikethrough!==void 0)Q.strikethrough=J.strikethrough??this.strikethrough;if(J.dim!==void 0||this.dim!==void 0)Q.dim=J.dim??this.dim;return new v1(Q)}static normal(J){return J?new v1({color:J}):new v1}static bold(J){return J?new v1({color:J,bold:!0}):new v1({bold:!0})}static italic(J){return J?new v1({color:J,italic:!0}):new v1({italic:!0})}static underline(J){return J?new v1({color:J,underline:!0}):new v1({underline:!0})}static colored(J){return new v1({color:J})}static background(J){return new v1({backgroundColor:J})}}class I1{text;style;children;hyperlink;constructor(J,Q,Z,X){this.text=J;this.style=Q;this.children=Z;this.hyperlink=X}toPlainText(){let J=this.text??"";if(this.children)for(let Q of this.children)J+=Q.toPlainText();return String(J)}equals(J){if(!J)return!1;if(this.text!==J.text)return!1;if(this.hyperlink?.uri!==J.hyperlink?.uri)return!1;if(this.style!==J.style){if(!this.style||!J.style)return!1;if(this.style.color!==J.style.color)return!1;if(this.style.backgroundColor!==J.style.backgroundColor)return!1;if(this.style.bold!==J.style.bold)return!1;if(this.style.italic!==J.style.italic)return!1;if(this.style.underline!==J.style.underline)return!1}if(this.children?.length!==J.children?.length)return!1;if(this.children&&J.children)for(let Q=0;Q<this.children.length;Q++){let Z=this.children[Q],X=J.children[Q];if(!Z||!X||!Z.equals(X))return!1}return!0}visitTextSpan(J){if(!J(this))return;if(this.children)for(let Q of this.children)Q.visitTextSpan(J)}}var q0,lZ6,iZ6;var u9=p(()=>{I4();z9();EH();qu();RG();r9();Y7();Y71();K71();p7();q0=class q0 extends vO{text;textAlign;maxLines;overflow;selectable;constructor({key:J,text:Q,textAlign:Z="left",maxLines:X,overflow:Y="clip",selectable:K=!1}){super(J?{key:J}:{});this.text=Q,this.textAlign=Z,this.maxLines=X,this.overflow=Y,this.selectable=K}createElement(){return new lZ6(this)}createRenderObject(){return new iZ6(this.text,this.textAlign,this.maxLines,this.overflow,!1,d1.index(8),d1.yellow,this.selectable)}updateRenderObject(J){}};lZ6=class lZ6 extends pT{constructor(J){super(J)}get richTextWidget(){return this.widget}mount(){super.mount(),this._updateRenderObjectWithMediaQuery()}performRebuild(){super.performRebuild(),setTimeout(()=>this._ensureRenderObjectContext(),0)}_ensureRenderObjectContext(){if(!this.renderObject)return;let J=this.renderObject,Q=new TH(this,this.widget);J.setContext(Q)}update(J){let Q=this.richTextWidget;super.update(J),this._updateRenderObjectWithMediaQuery()}_updateRenderObjectWithMediaQuery(){if(!this.renderObject)return;let J=this.renderObject;try{let Q=new TH(this,this.widget),Z=m8.of(Q),X=j8.maybeOf(Q),Y=X?.colorScheme.selection??d1.index(8),K=X?.colorScheme.copyHighlight??d1.yellow,q=this.renderObject;q.setContext(Q),q.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,Z.supportsEmojiWidth,Y,K,this.richTextWidget.selectable)}catch(Q){let Z=new TH(this,this.widget),X=this.renderObject;X.setContext(Z),X.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,!1,d1.index(8),d1.yellow,this.richTextWidget.selectable)}}};iZ6=class iZ6 extends H8{_text;_textAlign;_maxLines;_overflow;_emojiWidthSupported;_selectable;selectableId=0;_selectionArea;_selectedRanges=[];set selectionArea(J){this._selectionArea=J}get selectionArea(){return this._selectionArea}_cachedStyledCells;_selectionStart=null;_selectionEnd=null;_characterPositions=[];_visualLines=[];_selectionColor=d1.index(8);_copyHighlightColor=d1.yellow;_highlightMode="selection";constructor(J,Q,Z,X="clip",Y=!1,K=d1.index(8),q=d1.yellow,G=!1){super();this._text=J;this._textAlign=Q;this._maxLines=Z;this._overflow=X;this._emojiWidthSupported=Y;this._selectable=G;this._selectionColor=K,this._copyHighlightColor=q}get text(){return this._text}get textAlign(){return this._textAlign}get maxLines(){return this._maxLines}get overflow(){return this._overflow}updateSelection(J,Q,Z="selection"){if(this._selectionStart!==J||this._selectionEnd!==Q||this._highlightMode!==Z)this._selectionStart=J,this._selectionEnd=Q,this._highlightMode=Z,this.markNeedsPaint()}setHighlightMode(J){if(this._highlightMode!==J)this._highlightMode=J,this.markNeedsPaint()}get plainText(){return this._text.toPlainText()}getCharacterRect(J){if(J<0||J>=this._characterPositions.length)return null;let Q=this._characterPositions[J];if(!Q)return null;return{x:Q.x,y:Q.y,width:Q.width,height:1}}getOffsetForPosition(J,Q){if(this._characterPositions.length===0)return null;let Z=Math.round(J),X=Math.floor(Q),Y=1/0,K=1/0,q=-1/0,G=-1/0;for(let W of this._characterPositions)Y=Math.min(Y,W.x),K=Math.min(K,W.y),q=Math.max(q,W.x+W.width),G=Math.max(G,W.y+1);if(Z<Y||Z>=q||X<K||X>=G)return null;for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;if(Z>=F.x&&Z<F.x+F.width&&X>=F.y&&X<F.y+1)return W}for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;if(X>=F.y&&X<F.y+1){if(Z<F.x)return W;if(W===this._characterPositions.length-1||this._characterPositions[W+1]&&this._characterPositions[W+1].y>F.y){if(Z>=F.x+F.width)return W+1}}}let z=0,U=1/0;for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;let H=Math.abs(X-F.y)+Math.abs(Z-F.x);if(H<U)U=H,z=W}return z}getVisualLines(){return this._visualLines}getRenderableCharacterCount(){return this._characterPositions.length}updateText(J,Q,Z,X="clip",Y=!1,K=d1.index(8),q=d1.yellow,G=!1){this._text=J,this._textAlign=Q,this._maxLines=Z,this._overflow=X,this._emojiWidthSupported=Y,this._selectionColor=K,this._copyHighlightColor=q,this._selectable=G,this._cachedStyledCells=void 0,this._characterPositions=[],this._visualLines=[],this._cachedStyledCells=this.getStyledCells(),this.markNeedsLayout(),this.markNeedsPaint()}getStyledCells(){let J=[],Q=this.getStyledSegments(this._text,new v1({color:d1.white}));for(let Z of Q){let X=D2(Z.text);for(let Y of X){let K=f4(Y,this._emojiWidthSupported),q={};if(Z.style.color)q.fg=Z.style.color;if(Z.style.backgroundColor)q.bg=Z.style.backgroundColor;if(Z.style.bold)q.bold=Z.style.bold;if(Z.style.italic)q.italic=Z.style.italic;if(Z.style.underline)q.underline=Z.style.underline;if(Z.style.strikethrough)q.strikethrough=Z.style.strikethrough;if(Z.style.dim)q.dim=Z.style.dim;J.push(m9(Y,q,K,Z.hyperlink))}}return J}getCachedStyledCells(){return this._cachedStyledCells??this.getStyledCells()}getTotalCellsWidth(J){let Q=0;for(let Z of J)Q+=Z.width;return Q}wrapCells(J,Q){if(Q===1/0)return this.handleExplicitLineBreaksInCells(J);let Z=[],X=[],Y=0,K=0;while(K<J.length){let q=J[K];if(!q){K++;continue}if(q.char===`
5449
+ The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J){return this.controller!==J.controller}}});function cZ6(J,Q,Z){if(J.selectableId===Q.selectableId)return J.offset-Q.offset;return Z(J.selectableId,Q.selectableId)}var dZ6;var K71=p(()=>{dZ6={left:1,top:1,right:0,bottom:0}});class q71{foreground;mutedForeground;background;primary;secondary;accent;border;success;warning;info;destructive;selection;copyHighlight;tableBorder;constructor({foreground:J,mutedForeground:Q,background:Z,primary:X,secondary:Y,accent:K,border:q,success:G,warning:z,info:U,destructive:W,selection:F,copyHighlight:H,tableBorder:D}){this.foreground=J,this.mutedForeground=Q,this.background=Z,this.primary=X,this.secondary=Y,this.accent=K,this.border=q,this.success=G,this.warning=z,this.info=U,this.destructive=W,this.selection=F,this.copyHighlight=H,this.tableBorder=D}static default(){return new q71({foreground:d1.default(),mutedForeground:d1.index(7),background:d1.default(),primary:d1.blue,secondary:d1.cyan,accent:d1.magenta,border:d1.index(7),success:d1.green,warning:d1.yellow,info:d1.index(12),destructive:d1.red,selection:d1.index(8),copyHighlight:d1.yellow,tableBorder:d1.index(7)})}}class kH{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new kH({colorScheme:q71.default()})}}var j8;var p7=p(()=>{z9();SO();j8=class j8 extends jG{data;constructor({key:J,data:Q,child:Z}){super({key:J,child:Z});this.data=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(j8);if(Q)return Q.widget.data;return kH.default()}static maybeOf(J){let Q=J.dependOnInheritedWidgetOfExactType(j8);if(Q)return Q.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}});class v1{color;backgroundColor;bold;italic;underline;strikethrough;dim;constructor({color:J,backgroundColor:Q,bold:Z,italic:X,underline:Y,strikethrough:K,dim:q}={}){if(J!==void 0)this.color=J;if(Q!==void 0)this.backgroundColor=Q;if(Z!==void 0)this.bold=Z;if(X!==void 0)this.italic=X;if(Y!==void 0)this.underline=Y;if(K!==void 0)this.strikethrough=K;if(q!==void 0)this.dim=q}copyWith({color:J,backgroundColor:Q,bold:Z,italic:X,underline:Y,strikethrough:K,dim:q}){let G={};if(J!==void 0||this.color!==void 0)G.color=J??this.color;if(Q!==void 0||this.backgroundColor!==void 0)G.backgroundColor=Q??this.backgroundColor;if(Z!==void 0||this.bold!==void 0)G.bold=Z??this.bold;if(X!==void 0||this.italic!==void 0)G.italic=X??this.italic;if(Y!==void 0||this.underline!==void 0)G.underline=Y??this.underline;if(K!==void 0||this.strikethrough!==void 0)G.strikethrough=K??this.strikethrough;if(q!==void 0||this.dim!==void 0)G.dim=q??this.dim;return new v1(G)}merge(J){if(!J)return this;let Q={};if(J.color!==void 0||this.color!==void 0)Q.color=J.color??this.color;if(J.backgroundColor!==void 0||this.backgroundColor!==void 0)Q.backgroundColor=J.backgroundColor??this.backgroundColor;if(J.bold!==void 0||this.bold!==void 0)Q.bold=J.bold??this.bold;if(J.italic!==void 0||this.italic!==void 0)Q.italic=J.italic??this.italic;if(J.underline!==void 0||this.underline!==void 0)Q.underline=J.underline??this.underline;if(J.strikethrough!==void 0||this.strikethrough!==void 0)Q.strikethrough=J.strikethrough??this.strikethrough;if(J.dim!==void 0||this.dim!==void 0)Q.dim=J.dim??this.dim;return new v1(Q)}static normal(J){return J?new v1({color:J}):new v1}static bold(J){return J?new v1({color:J,bold:!0}):new v1({bold:!0})}static italic(J){return J?new v1({color:J,italic:!0}):new v1({italic:!0})}static underline(J){return J?new v1({color:J,underline:!0}):new v1({underline:!0})}static colored(J){return new v1({color:J})}static background(J){return new v1({backgroundColor:J})}}class I1{text;style;children;hyperlink;constructor(J,Q,Z,X){this.text=J;this.style=Q;this.children=Z;this.hyperlink=X}toPlainText(){let J=this.text??"";if(this.children)for(let Q of this.children)J+=Q.toPlainText();return String(J)}equals(J){if(!J)return!1;if(this.text!==J.text)return!1;if(this.hyperlink?.uri!==J.hyperlink?.uri)return!1;if(this.style!==J.style){if(!this.style||!J.style)return!1;if(this.style.color!==J.style.color)return!1;if(this.style.backgroundColor!==J.style.backgroundColor)return!1;if(this.style.bold!==J.style.bold)return!1;if(this.style.italic!==J.style.italic)return!1;if(this.style.underline!==J.style.underline)return!1}if(this.children?.length!==J.children?.length)return!1;if(this.children&&J.children)for(let Q=0;Q<this.children.length;Q++){let Z=this.children[Q],X=J.children[Q];if(!Z||!X||!Z.equals(X))return!1}return!0}visitTextSpan(J){if(!J(this))return;if(this.children)for(let Q of this.children)Q.visitTextSpan(J)}}var q0,lZ6,iZ6;var u9=p(()=>{I4();z9();EH();qu();RG();r9();Y7();Y71();K71();p7();q0=class q0 extends vO{text;textAlign;maxLines;overflow;selectable;constructor({key:J,text:Q,textAlign:Z="left",maxLines:X,overflow:Y="clip",selectable:K=!1}){super(J?{key:J}:{});this.text=Q,this.textAlign=Z,this.maxLines=X,this.overflow=Y,this.selectable=K}createElement(){return new lZ6(this)}createRenderObject(){return new iZ6(this.text,this.textAlign,this.maxLines,this.overflow,!1,d1.index(8),d1.yellow,this.selectable)}updateRenderObject(J){}};lZ6=class lZ6 extends pT{constructor(J){super(J)}get richTextWidget(){return this.widget}mount(){super.mount(),this._updateRenderObjectWithMediaQuery()}performRebuild(){super.performRebuild(),setTimeout(()=>this._ensureRenderObjectContext(),0)}_ensureRenderObjectContext(){if(!this.renderObject)return;let J=this.renderObject,Q=new TH(this,this.widget);J.setContext(Q)}update(J){super.update(J),this._updateRenderObjectWithMediaQuery()}_updateRenderObjectWithMediaQuery(){if(!this.renderObject)return;try{let J=new TH(this,this.widget),Q=m8.of(J),Z=j8.maybeOf(J),X=Z?.colorScheme.selection??d1.index(8),Y=Z?.colorScheme.copyHighlight??d1.yellow,K=this.renderObject;K.setContext(J),K.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,Q.supportsEmojiWidth,X,Y,this.richTextWidget.selectable)}catch(J){let Q=new TH(this,this.widget),Z=this.renderObject;Z.setContext(Q),Z.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,!1,d1.index(8),d1.yellow,this.richTextWidget.selectable)}}};iZ6=class iZ6 extends H8{_text;_textAlign;_maxLines;_overflow;_emojiWidthSupported;_selectable;selectableId=0;_selectionArea;_selectedRanges=[];set selectionArea(J){this._selectionArea=J}get selectionArea(){return this._selectionArea}_cachedStyledCells;_selectionStart=null;_selectionEnd=null;_characterPositions=[];_visualLines=[];_selectionColor=d1.index(8);_copyHighlightColor=d1.yellow;_highlightMode="selection";constructor(J,Q,Z,X="clip",Y=!1,K=d1.index(8),q=d1.yellow,G=!1){super();this._text=J;this._textAlign=Q;this._maxLines=Z;this._overflow=X;this._emojiWidthSupported=Y;this._selectable=G;this._selectionColor=K,this._copyHighlightColor=q}get text(){return this._text}get textAlign(){return this._textAlign}get maxLines(){return this._maxLines}get overflow(){return this._overflow}updateSelection(J,Q,Z="selection"){if(this._selectionStart!==J||this._selectionEnd!==Q||this._highlightMode!==Z)this._selectionStart=J,this._selectionEnd=Q,this._highlightMode=Z,this.markNeedsPaint()}setHighlightMode(J){if(this._highlightMode!==J)this._highlightMode=J,this.markNeedsPaint()}get plainText(){return this._text.toPlainText()}getCharacterRect(J){if(J<0||J>=this._characterPositions.length)return null;let Q=this._characterPositions[J];if(!Q)return null;return{x:Q.x,y:Q.y,width:Q.width,height:1}}getOffsetForPosition(J,Q){if(this._characterPositions.length===0)return null;let Z=Math.round(J),X=Math.floor(Q),Y=1/0,K=1/0,q=-1/0,G=-1/0;for(let W of this._characterPositions)Y=Math.min(Y,W.x),K=Math.min(K,W.y),q=Math.max(q,W.x+W.width),G=Math.max(G,W.y+1);if(Z<Y||Z>=q||X<K||X>=G)return null;for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;if(Z>=F.x&&Z<F.x+F.width&&X>=F.y&&X<F.y+1)return W}for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;if(X>=F.y&&X<F.y+1){if(Z<F.x)return W;if(W===this._characterPositions.length-1||this._characterPositions[W+1]&&this._characterPositions[W+1].y>F.y){if(Z>=F.x+F.width)return W+1}}}let z=0,U=1/0;for(let W=0;W<this._characterPositions.length;W++){let F=this._characterPositions[W];if(!F)continue;let H=Math.abs(X-F.y)+Math.abs(Z-F.x);if(H<U)U=H,z=W}return z}getVisualLines(){return this._visualLines}getRenderableCharacterCount(){return this._characterPositions.length}updateText(J,Q,Z,X="clip",Y=!1,K=d1.index(8),q=d1.yellow,G=!1){this._text=J,this._textAlign=Q,this._maxLines=Z,this._overflow=X,this._emojiWidthSupported=Y,this._selectionColor=K,this._copyHighlightColor=q,this._selectable=G,this._cachedStyledCells=void 0,this._characterPositions=[],this._visualLines=[],this._cachedStyledCells=this.getStyledCells(),this.markNeedsLayout(),this.markNeedsPaint()}getStyledCells(){let J=[],Q=this.getStyledSegments(this._text,new v1({color:d1.white}));for(let Z of Q){let X=D2(Z.text);for(let Y of X){let K=f4(Y,this._emojiWidthSupported),q={};if(Z.style.color)q.fg=Z.style.color;if(Z.style.backgroundColor)q.bg=Z.style.backgroundColor;if(Z.style.bold)q.bold=Z.style.bold;if(Z.style.italic)q.italic=Z.style.italic;if(Z.style.underline)q.underline=Z.style.underline;if(Z.style.strikethrough)q.strikethrough=Z.style.strikethrough;if(Z.style.dim)q.dim=Z.style.dim;J.push(m9(Y,q,K,Z.hyperlink))}}return J}getCachedStyledCells(){return this._cachedStyledCells??this.getStyledCells()}getTotalCellsWidth(J){let Q=0;for(let Z of J)Q+=Z.width;return Q}wrapCells(J,Q){if(Q===1/0)return this.handleExplicitLineBreaksInCells(J);let Z=[],X=[],Y=0,K=0;while(K<J.length){let q=J[K];if(!q){K++;continue}if(q.char===`
5450
5450
  `){X.push(q),Z.push(X),X=[],Y=0,K++;continue}if(Y+q.width>Q&&X.length>0){let G=X.length-1;while(G>=0&&!/\s/.test(X[G].char))G--;if(G>=0){let z=X.slice(G+1);X=X.slice(0,G+1),Z.push(X),X=z,Y=0;for(let U of z)Y+=U.width}else Z.push(X),X=[],Y=0}X.push(q),Y+=q.width,K++}if(X.length>0)Z.push(X);return Z.length>0?Z:[[]]}handleExplicitLineBreaksInCells(J){let Q=[],Z=[];for(let X of J)if(X.char===`
5451
5451
  `)Z.push(X),Q.push(Z),Z=[];else Z.push(X);if(Z.length>0)Q.push(Z);return Q.length>0?Q:[[]]}performLayout(){let J=this._lastConstraints;q8(!!J,"performLayout called without constraints");let Q=this.getCachedStyledCells(),Z=isFinite(J.maxWidth)?J.maxWidth:this.getTotalCellsWidth(Q),X=this.wrapCells(Q,Z),Y=this._maxLines?X.slice(0,this._maxLines):X,K=0;for(let W of Y){let F=0;for(let H of W)F+=H.width;K=Math.max(K,F)}let q=Y.length,G=Y.length>1,z,U;if(!isFinite(J.maxWidth))z=K;else{let W;if(this._textAlign==="center"||this._textAlign==="right")W=J.maxWidth;else W=G?J.maxWidth:K;z=Math.max(J.minWidth,Math.min(J.maxWidth,W))}if(!isFinite(J.maxHeight))U=q;else{let W=G?q:Math.min(q,J.maxHeight);U=Math.max(J.minHeight,W)}z=Math.max(0,z),U=Math.max(0,U),this.setSize(z,U),super.performLayout()}getMinIntrinsicWidth(J){let Q=this.getCachedStyledCells();if(this._maxLines===1)return Math.max(this.getTotalCellsWidth(Q),1);let Z=0,X=0,Y=!1;for(let K of Q){if(K.char===`
5452
5452
  `){if(Y)Z=Math.max(Z,X),X=0,Y=!1;continue}if(/\s/.test(K.char)){if(Y)Z=Math.max(Z,X),X=0,Y=!1}else{if(!Y)X=0,Y=!0;X+=K.width}}if(Y)Z=Math.max(Z,X);return Math.max(Z,1)}getMaxIntrinsicWidth(J){let Q=this.getCachedStyledCells();return Math.max(this.getTotalCellsWidth(Q),1)}getMinIntrinsicHeight(J){let Q=this.getCachedStyledCells(),Z=this.wrapCells(Q,J),X=this._maxLines?Z.slice(0,this._maxLines):Z;return Math.max(X.length,1)}getMaxIntrinsicHeight(J){return this.getMinIntrinsicHeight(J)}paint(J,Q=0,Z=0){let X=Q+this.offset.x,Y=Z+this.offset.y,K=this.getCachedStyledCells(),q=this.wrapCells(K,this.size.width),G=this._maxLines?q.slice(0,this._maxLines):q;if(this._maxLines&&q.length>this._maxLines)G=this.applyCellOverflow(G,this.size.width);if(G.length>this.size.height)G=G.slice(0,this.size.height);this._characterPositions=[],this._visualLines=[];let z=0;for(let U=0;U<G.length;U++){let W=G[U];if(!W)continue;let F=Y+U;if(F>=0&&F<J.getSize().height){let H=X;if(this._textAlign==="center"||this._textAlign==="right"){let V=0,N=W.length-1;while(N>=0&&W[N]&&/\s/.test(W[N]?.char||""))N--;for(let L=0;L<=N;L++){let A=W[L];if(A)V+=A.width}if(this._textAlign==="center")H=Math.max(X,X+Math.floor((this.size.width-V)/2));else H=Math.max(X,X+this.size.width-V)}let D=Math.floor(H),M=X+this.size.width;for(let V of W){if(V.char===`
@@ -5612,7 +5612,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5612
5612
  `),J.stdout.write(`Continue this thread with: amp threads continue ${U}
5613
5613
  `)}}function MY9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return d1.index(Z[X])}var RW6,wW6;var EW6=p(()=>{D0();D4();NC();nw();u4();vN();Q4();k3();Y8();n0();DQ6();hQ6();gQ6();d7();U71();TO();FX6();Gu();kU();Jy1();PJ();_O();DX6();r9();W71();j2();SX6();UX();u9();Ty1();p7();Zu();z9();KU6();GU6();MQ();KY6();BU6();DU6();OU6();IU6();nT();EU6();ry1();$U6();SU6();XW6();YW6();tz6();qW6();xh1();UW6();FW6();b71();YU6();NW6();jW6();RW6=class RW6 extends P6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new wW6}};wW6=class wW6 extends $6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;updateState=null;updateServiceSubscription=null;isFreeTierEnabled=!1;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;return Boolean(J.viewState.state==="active"&&(J.viewState.interactionState==="tool-running"||J.viewState.inferenceState==="running"))}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!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 I1(this.submitDisabledHint,new v1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new I1("",void 0,[new I1("Ctrl+C",new v1({color:Q.keybind})),new I1(" again to exit",new v1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new I1("",void 0,[new I1("Esc",new v1({color:Q.keybind})),new I1(" again to clear input",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new I1("",void 0,[new I1("Escape",new v1({color:Q.keybind})),new I1(" to close help",new v1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new I1("",void 0,[new I1("Esc",new v1({color:Q.keybind})),new I1(" to cancel",new v1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new I1("Selection copied to clipboard",new v1({color:J.foreground,dim:!0}));return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new O71;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new kV);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 X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}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=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},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||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(kx1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new s5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Rx1(this.widget.dependencies.commandRegistry);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new ch1(this.getCommands(),this.widget.dependencies.fuzzyServer,new f51);return this.completionBuilder}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.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J)=>{try{await this.connectToSelectedIde(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}this.widget.dependencies.lockfileManager.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J){await this.widget.dependencies.ideClient.start(J)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};handleHistoryNavigation=(J)=>{if(J.key==="p"&&J.ctrlKey)return this.navigateHistoryPrevious(),"handled";if(J.key==="n"&&J.ctrlKey)return this.navigateHistoryNext(),"handled";return"ignored"};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=WQ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();_71(z);return}if(J.launchesWindow)EG.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await Na({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))}},Q,X.signal);if(J.launchesWindow)EG.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){a.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Lg1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(PG.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;this.checkFreeTierStatus(),_71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Q)=>{this.setState(()=>{this.ideStatus=Q})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Q)=>{let Z=aT();if(!Z){a.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Q}]}}),a.debug("Message sent from IDE to agent",{message:Q.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Q)=>{this.textController.insertText(Q),a.debug("Appended text to CLI prompt from IDE",{text:Q.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Q)=>{this.setState(()=>{this.updateState=Q})}),this.agentModeSubscription=Z2.pipe(g0((Q)=>Q.settings["experimental.agentMode"]),d8()).subscribe((Q)=>{this.setState(()=>{this.currentAgentMode=Q})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Q,Z)=>{if(Q.length<=3)return!0;let X=HQ6(Q);if(!X)return!0;if(this.imageAttachments.length>=mo1)return!1;let Y=BQ6(X);if(Y)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return!0},this.updateTerminalTitle();let J=this.widget.dependencies.lockfileManager.getSelectedConfig();if(J)this.connectToSelectedIde(J).catch((Q)=>{let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{a.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(kx1("")),this.shouldUseProgressBar())process.stdout.write(_x1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.activeTools,...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],Y=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],K=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:Y}],subthreadID:X.subthreadID,reason:K}}shouldUseProgressBar(){return m8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let{threadState:J}=this.widget.dependencies,Q=this.getCurrentConfirmation(),Z="off";if(Q)Z="paused";else if(this.isProcessing())Z="indeterminate";if(Z!==this.currentProgressBarState)this.currentProgressBarState=Z,this.sendProgressReport(Z);this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(UZ6());break;case"paused":process.stdout.write(WZ6());break;case"off":process.stdout.write(_x1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.currentProgressBarState!=="off")this.progressReportTimer=setTimeout(()=>{if(this.currentProgressBarState!=="off")this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){a.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){a.error("No tool use block found in confirmation");return}if(J==="allow-all-session")pU("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else a.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await dJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){a.error("Failed to send tool confirmation:",Y)}};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"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await dJ.cancel(this.widget.dependencies.threadID)};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,_71(Q),k71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw a.error("Failed to switch to thread:",J,Q),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=aT()||this.widget.dependencies.worker,Z=[{type:"text",text:J}];if(this.imageAttachments.length>0)Z.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Z}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};onTrainingModeDialogResponse=async(J)=>{if(this.setState(()=>{this.isShowingTrainingModeDialog=!1}),J&&this.pendingTrainingMode)try{let Q=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0});if(!Q.ok){let Z=Q.error.message||"Failed to enable training mode";await this.showErrorMessage(Z),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else await this.proceedWithUserMessage(this.pendingTrainingMode)}catch(Q){await this.showErrorMessage(`Failed to enable training mode:
5614
5614
 
5615
- ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;EG.instance.stop()}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=BY9();if(J===Q)return"~";if(J.startsWith(Q+cu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(cu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(cu.sep),"…",Q.slice(-2).join(cu.sep)].join(cu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new yH({child:new Dg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new f51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new O51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new mh1({key:U?new s5(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new kV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?vc1(q.mainThread):void 0,L=new x71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),A=new ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),O=new v71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new t6({decoration:new g2(Y.secondary),child:new S8({padding:B6.horizontal(1),child:new q0({text:new I1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:d1.black})),textAlign:"center"})})}));j.push(new $2({child:F}),A,O,new t6({constraints:new d6(0,Q.size.width,0,H),child:M}),new i0({height:1,child:new S8({padding:B6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new I5(()=>{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.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.clearActiveSelection())return"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.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"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"}),w=new I5(()=>{return this.onExitPressed(),"handled"}),E=new I5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),$=new I5(()=>{return gV.instance.toggleAll(),"handled"}),P=new I5(()=>{return EG.instance.toggleFrameStatsOverlay(),"handled"}),C=new I5(()=>{return EG.instance.tuiInstance.getScreen().markForRefresh(),XZ.instance.requestFrame(),"handled"}),k=new I5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Mu],[m2.ctrl("c"),new cT],[m2.ctrl("l"),new Au],[m2.alt("c"),new Vu],[m2.alt("p"),new Lu],[m2.ctrl("r"),new Nu],[m2.key("PageUp"),new H71],[m2.key("PageDown"),new B71],[m2.key("Home"),new D71],[m2.key("End"),new M71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new cT);let S=new Map([[Mu,I],[G71,w],[Au,C],[Vu,E],[Nu,$],[Lu,P],[cT,k],[H71,g],[B71,T],[D71,v],[M71,f]]),x=R;if(this.isShowingConsoleOverlay)x=new bK({children:[x,new ah1]});if(this.isShowingHelp)x=new bK({children:[x,new sh1]});if(this.isShowingFileChangesOverlay)x=new bK({children:[x,new ay1]});if(this.isShowingConfirmationOverlay)x=new bK({children:[x,new lh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new th1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new Fg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"main-app-shortcuts",child:x})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new rh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Mg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new nh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Hg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=DY9(X),U=new R71({key:this.textFieldKey,controller:this.textController,triggers:[Lg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>dh1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:EG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=dh1(C);break}let x=HU6(C),b=new I1(h,new v1({color:T})),m=new I1(S,new v1({color:v})),n=[b,m];if(x){let u=new I1(" - ",new v1({color:f,dim:!0})),Q1=new I1(x,new v1({color:f,dim:!0}));n.push(u,Q1)}return new t6({decoration:new g2(g),child:new q0({text:new I1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new Q2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new t6({padding:B6.only({bottom:1,left:1}),child:new q0({text:new I1("",void 0,[new I1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new I1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new I1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,F]}):F,L=V?new Bg1({queuedMessages:W}):void 0,A=M?new ex1(new uh1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new I1("",void 0,[new I1("Enter",new v1({color:G.keybind})),new I1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new I1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",oU[0]].includes(R)&&!H){let P=MY9(R);O.push({text:new I1("",void 0,[new I1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new I1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new I1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new my1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as VY9}from"node:crypto";import{mkdir as NY9,readFile as CW6,writeFile as LY9}from"node:fs/promises";import AY9 from"node:os";import Ag1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function OY9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function sO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")pU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")pU("experimental.agentMode",Q.agentMode)}async function Rg1(J){try{await NY9(Ag1.dirname(Og1),{recursive:!0}),await LY9(Og1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function wY9(){try{return(await CW6(Og1,"utf-8")).trim()}catch(J){return null}}async function IY9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return RY9.parse(Q)}catch(Z){if(Z instanceof T0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function EY9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function CY9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new E2(vK.unknownCommand(Z),1,q)}}function zf2(){return SW6}function g51(J){return{...J,getThreadEnvironment:H41,vfs:C10({os:J.fileSystem}),fileChangeTrackerStorage:new Qk(J.fileSystem),generateThreadTitle:Oa,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function oO(J,Q){dc1("0.0.1759276921-gbfbfa1");let Z=uQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:Ob1,homeDir:wg1,userConfigDir:vW6}),X=await O9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=rl(xp()),K=z10({configService:Z,toolService:Y}),q=zA0(Y,R8,Rt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)cc1(!0);if(Q.ide&&ob1())lc1(!0);if(O66(Y,X.settings),Q.jetbrains)Y.registerTool(la);else if(Q.ide)Y.registerTool(Jq0);let z;if(!J.executeMode)z=new R41(process.cwd(),{},!0);else z=new class extends R41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
5615
+ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;EG.instance.stop()}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=BY9();if(J===Q)return"~";if(J.startsWith(Q+cu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(cu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(cu.sep),"…",Q.slice(-2).join(cu.sep)].join(cu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new yH({child:new Dg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new f51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new O51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new mh1({key:U?new s5(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new kV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?vc1(q.mainThread):void 0,L=new x71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),A=new ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),O=new v71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new t6({decoration:new g2(Y.secondary),child:new S8({padding:B6.horizontal(1),child:new q0({text:new I1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:d1.black})),textAlign:"center"})})}));j.push(new $2({child:F}),A,O,new t6({constraints:new d6(0,Q.size.width,0,H),child:M}),new i0({height:1,child:new S8({padding:B6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new I5(()=>{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.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.clearActiveSelection())return"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.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"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"}),w=new I5(()=>{return this.onExitPressed(),"handled"}),E=new I5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),$=new I5(()=>{return gV.instance.toggleAll(),"handled"}),P=new I5(()=>{return EG.instance.toggleFrameStatsOverlay(),"handled"}),C=new I5(()=>{return EG.instance.tuiInstance.getScreen().markForRefresh(),XZ.instance.requestFrame(),"handled"}),k=new I5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new I5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Mu],[m2.ctrl("c"),new cT],[m2.ctrl("l"),new Au],[m2.alt("c"),new Vu],[m2.alt("p"),new Lu],[m2.ctrl("r"),new Nu],[m2.key("PageUp"),new H71],[m2.key("PageDown"),new B71],[m2.key("Home"),new D71],[m2.key("End"),new M71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new cT);let S=new Map([[Mu,I],[G71,w],[Au,C],[Vu,E],[Nu,$],[Lu,P],[cT,k],[H71,g],[B71,T],[D71,v],[M71,f]]),x=R;if(this.isShowingConsoleOverlay)x=new bK({children:[x,new ah1]});if(this.isShowingHelp)x=new bK({children:[x,new sh1]});if(this.isShowingFileChangesOverlay)x=new bK({children:[x,new ay1]});if(this.isShowingConfirmationOverlay)x=new bK({children:[x,new lh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new th1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new Fg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new yH({child:new xK({actions:S,child:new vV({shortcuts:h,debugLabel:"main-app-shortcuts",child:x})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new rh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Mg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new nh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Hg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=DY9(X),U=new R71({key:this.textFieldKey,controller:this.textController,triggers:[Lg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>dh1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:EG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=dh1(C);break}let x=HU6(C),b=new I1(h,new v1({color:T})),m=new I1(S,new v1({color:v})),n=[b,m];if(x){let u=new I1(" - ",new v1({color:f,dim:!0})),Q1=new I1(x,new v1({color:f,dim:!0}));n.push(u,Q1)}return new t6({decoration:new g2(g),child:new q0({text:new I1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new Q2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new t6({padding:B6.only({bottom:1,left:1}),child:new q0({text:new I1("",void 0,[new I1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new I1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new I1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,F]}):F,L=V?new Bg1({queuedMessages:W}):void 0,A=M?new ex1(new uh1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new I1("",void 0,[new I1("Enter",new v1({color:G.keybind})),new I1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new I1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",oU[0]].includes(R)&&!H){let P=MY9(R);O.push({text:new I1("",void 0,[new I1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new I1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new I1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new my1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as VY9}from"node:crypto";import{mkdir as NY9,readFile as CW6,writeFile as LY9}from"node:fs/promises";import AY9 from"node:os";import Ag1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function OY9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function sO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")pU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")pU("experimental.agentMode",Q.agentMode)}async function Rg1(J){try{await NY9(Ag1.dirname(Og1),{recursive:!0}),await LY9(Og1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function wY9(){try{return(await CW6(Og1,"utf-8")).trim()}catch(J){return null}}async function IY9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return RY9.parse(Q)}catch(Z){if(Z instanceof T0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function EY9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function CY9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new E2(vK.unknownCommand(Z),1,q)}}function zf2(){return SW6}function g51(J){return{...J,getThreadEnvironment:H41,vfs:C10({os:J.fileSystem}),fileChangeTrackerStorage:new Qk(J.fileSystem),generateThreadTitle:Oa,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function oO(J,Q){dc1("0.0.1759294726-g7c064a");let Z=uQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:Ob1,homeDir:wg1,userConfigDir:vW6}),X=await O9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=rl(xp()),K=z10({configService:Z,toolService:Y}),q=zA0(Y,R8,Rt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)cc1(!0);if(Q.ide&&ob1())lc1(!0);if(O66(Y,X.settings),Q.jetbrains)Y.registerTool(la);else if(Q.ide)Y.registerTool(Jq0);let z;if(!J.executeMode)z=new R41(process.cwd(),{},!0);else z=new class extends R41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
5616
5616
  `),!await SY9(J))await jO(),process.exit(1)}let U=await d10({isDevelopment:!1}),W=new QW1(U),F=new eU1(U,{lazy:!0}),H=new cD1(W),D=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=I66({playNotificationSound:async(L)=>{if(D){R66(L);let A=ax1(),O=rx1();if((!A||O)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:W});a.info("Starting Amp background services");let V=qK0({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?E10:R8};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function SY9(J){if(!J.executeMode){if(!await qx1("Would you like to log in to Amp? [(y)es, (n)o]: "))return u2.write(`Login cancelled. Run the command again to retry.
5617
5617
  `),!1}return await kW6(J)}async function kW6(J){let Q=VY9(32).toString("hex"),Z=await Kx1(J.ampURL,Q);try{await vT(Z)}catch(Y){a.error("Failed to open browser",{error:Y})}let X=await Kx1(J.ampURL,Q,!1);u2.write(`If your browser did not open automatically, visit:
5618
5618
 
@@ -5622,12 +5622,12 @@ ${Q8.blue.bold(X)}
5622
5622
  Login successful! You can now use the Amp CLI.
5623
5623
  `),!0}catch(Y){return a.error("Login failed",{error:Y}),o2.write(`
5624
5624
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
5625
- `),!1}}function vY9(){let J=new Xm().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)VT(),process.exit(0);let H=F.originalError??F;R76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759276921-gbfbfa1 (released 2025-10-01T00:06:50.062Z)
5626
- `),process.exit(0)}),J.addHelpText("after",l56()),J.configureHelp({formatHelp:i56}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await xY9(M)}),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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await bY9(M,await lb1(D,M.settings))});let Q=async(F,H,D)=>{uQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:wg1,userConfigDir:vW6});let M={...H,executeMode:!1};await jg1(M,{...F,startWithPicker:!0},D)},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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await TW6(D,M,H)});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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await pY9(D,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);if(H.pick)await Q(M,V,D);else await uY9(M,V,F,D)}),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(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await mY9(M,V,F,D)}),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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await TW6(D,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await gY9(M,V,F,D,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await hY9(M,V,F,D)}),zQ6(J,async(F,H)=>{let D=await fK(H);sO(F,H);let M=await oO(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:VT,asyncDispose:M.asyncDispose.bind(M)}}),PJ6(J),MJ6(J,async(F)=>{return(await fK(F)).settings});let X=new Xm().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(F)=>{await eb1(F.force||!1,F.verbose||!1,"0.0.1759276921-gbfbfa1"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,D){let V=typeof F.description==="string"?F.description:D===void 0?F.description(!0):F.description(D),N=new WO(H,V),L=TY9(F);if(L)N.default(L);if(N.hidden=$Y9(F)||PW6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of $W6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new WO("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new WO("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new WO("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new WO("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new WO("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(F,H)=>{let D=F,M=await fK(D);if(Object.keys(D).forEach((V)=>{let N=$W6.find((L)=>L.name===V);if(N&&PW6(N)&&!PY9(N))o2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
5625
+ `),!1}}function vY9(){let J=new Xm().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)VT(),process.exit(0);let H=F.originalError??F;R76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759294726-g7c064a (released 2025-10-01T05:04:08.500Z)
5626
+ `),process.exit(0)}),J.addHelpText("after",l56()),J.configureHelp({formatHelp:i56}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await xY9(M)}),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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await bY9(M,await lb1(D,M.settings))});let Q=async(F,H,D)=>{uQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:wg1,userConfigDir:vW6});let M={...H,executeMode:!1};await jg1(M,{...F,startWithPicker:!0},D)},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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await TW6(D,M,H)});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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await pY9(D,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);if(H.pick)await Q(M,V,D);else await uY9(M,V,F,D)}),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(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await mY9(M,V,F,D)}),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(F,H)=>{let D=H.optsWithGlobals(),M=await fK(D);await TW6(D,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await gY9(M,V,F,D,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,D)=>{let M=D.optsWithGlobals(),V=await fK(M);await hY9(M,V,F,D)}),zQ6(J,async(F,H)=>{let D=await fK(H);sO(F,H);let M=await oO(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:VT,asyncDispose:M.asyncDispose.bind(M)}}),PJ6(J),MJ6(J,async(F)=>{return(await fK(F)).settings});let X=new Xm().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(F)=>{await eb1(F.force||!1,F.verbose||!1,"0.0.1759294726-g7c064a"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,D){let V=typeof F.description==="string"?F.description:D===void 0?F.description(!0):F.description(D),N=new WO(H,V),L=TY9(F);if(L)N.default(L);if(N.hidden=$Y9(F)||PW6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of $W6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new WO("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new WO("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new WO("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new WO("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new WO("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(F,H)=>{let D=F,M=await fK(D);if(Object.keys(D).forEach((V)=>{let N=$W6.find((L)=>L.name===V);if(N&&PW6(N)&&!PY9(N))o2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
5627
5627
  `))}),H.args.length>0)CY9(M,H);await jg1(M,D,H)});let U=new Xm("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await fY9(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new Xm("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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await yY9(F.version)});return J.addCommand(W),J}async function h51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??aK(),K=g51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await dJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,y41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(q7(z,"assistant"))await Rg1(Y),G.unsubscribe()});return await q.resume(),q}async function jg1(J,Q,Z){let X=process.stdin,Y=x41(Q);if(Y instanceof Error)WX(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let R=(await Ux1()).trimEnd();if(R)q=R}else K=(await Ux1()).trimEnd();if(Q.remote&&!J.executeMode)throw new E2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new E2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new E2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new E2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new E2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new E2("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&K===""&&!Q.streamJsonInput)throw new E2("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
5628
5628
  Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await fJ6();sO(Z,Q);let G=await oO(J,Q);SW6=G;let z=g51(G),U=async(R)=>{let I=await CW6(R,"utf-8"),w=JSON.parse(I);if(!rU(w.id))throw new E2(vK.invalidThreadId);return h51(G,{visibility:Y,thread:w})},W=async(R)=>{if(!rU(R))throw new E2(vK.invalidThreadId);let I=await G.threadService.get(R)??void 0;return h51(G,{visibility:Y,thread:I})},F=async()=>{try{if(Q.threadId)return W(Q.threadId);else return h51(G,{visibility:Y})}catch(R){if(R instanceof E2)throw R;throw await B41(R,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return h51(G,{visibility:Y})};if(Q.format==="jsonl")o2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5629
- `),await jO(),process.exit(1);if(J.executeMode&&Q.remote)await CJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await F();if(J.executeMode)await x76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new JG1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=Xx1("0.0.1759276921-gbfbfa1",G.settingsStorage),A=K0.of([S0.file(process.cwd())]),O=VC(void 0,A);if(K)D.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let j=await O9();await IW6({stdin:X,stdout:process.stdout,history:new Pb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:D.threadID,worker:D,workerDeps:z,configService:G.configService,internalAPIClient:NZ,ampURL:J.ampURL,useGpt5:j.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:jQ,commandRegistry:O,showJetBrainsInstaller:V,showIdePicker:M,lockfileManager:N,startWithPicker:Q.startWithPicker,updateService:L,debugWidgetTree:Q.debugWidgetTree}),await G.asyncDispose(),process.exit(0)}async function fK(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5630
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=TU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await _J6(Y),await bJ6(Y),J.mcpConfig){let q=await IY9(J.mcpConfig);Y=EY9(Y,q)}let K=await Y.get("url","global");if(!K)K=qZ;if(!sH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=Wd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:vJ6(await lb1(J,Y))}}function kY9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function _Y9(){let J=kY9(process.argv);if(F76({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),OY9(a),a.info("Starting Amp CLI.",{version:"0.0.1759276921-gbfbfa1",buildTimestamp:"2025-10-01T00:06:50.062Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E2(vK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await vY9().parseAsync(process.argv)}async function bY9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5629
+ `),await jO(),process.exit(1);if(J.executeMode&&Q.remote)await CJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await F();if(J.executeMode)await x76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new JG1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=Xx1("0.0.1759294726-g7c064a",G.settingsStorage),A=K0.of([S0.file(process.cwd())]),O=VC(void 0,A);if(K)D.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let j=await O9();await IW6({stdin:X,stdout:process.stdout,history:new Pb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:D.threadID,worker:D,workerDeps:z,configService:G.configService,internalAPIClient:NZ,ampURL:J.ampURL,useGpt5:j.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:jQ,commandRegistry:O,showJetBrainsInstaller:V,showIdePicker:M,lockfileManager:N,startWithPicker:Q.startWithPicker,updateService:L,debugWidgetTree:Q.debugWidgetTree}),await G.asyncDispose(),process.exit(0)}async function fK(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5630
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=TU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await _J6(Y),await bJ6(Y),J.mcpConfig){let q=await IY9(J.mcpConfig);Y=EY9(Y,q)}let K=await Y.get("url","global");if(!K)K=qZ;if(!sH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=Wd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:vJ6(await lb1(J,Y))}}function kY9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function _Y9(){let J=kY9(process.argv);if(F76({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),OY9(a),a.info("Starting Amp CLI.",{version:"0.0.1759294726-g7c064a",buildTimestamp:"2025-10-01T05:04:08.500Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E2(vK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await vY9().parseAsync(process.argv)}async function bY9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5631
5631
  `);else if(!sH(J.ampURL))u2.write(`Logging in to ${new URL(J.ampURL).hostname}
5632
5632
  `);let Z=process.env.AMP_API_KEY;if(Z)u2.write(`API key found in environment variable, storing...
5633
5633
  `),await Q.set("apiKey",Z,J.ampURL),u2.write(`API key successfully stored.
@@ -5643,7 +5643,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
5643
5643
  `));try{let Q;if(J)Q=J,o2.write(Q8.blue(`Updating to version ${J}...
5644
5644
  `)),await CT(J),o2.write(Q8.green(`✓ Successfully updated to version ${J}
5645
5645
  `));else{o2.write(Q8.blue(`Checking for updates...
5646
- `));let{hasUpdate:X,latestVersion:Y}=await pR("0.0.1759276921-gbfbfa1");if(!X)o2.write(Q8.green(`✓ Amp CLI is already up to date.
5646
+ `));let{hasUpdate:X,latestVersion:Y}=await pR("0.0.1759294726-g7c064a");if(!X)o2.write(Q8.green(`✓ Amp CLI is already up to date.
5647
5647
  `)),process.exit(0);if(!Y)o2.write(Q8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,o2.write(Q8.blue(`Updating to version ${Y}...
5648
5648
  `)),await CT(Y),o2.write(Q8.green(`✓ Successfully updated to version ${Y}
5649
5649
  `))}let Z=await PO(Q);if(Z.warning)o2.write(`