@sourcegraph/amp 0.0.1774866438-g7cb400 → 0.0.1774873738-gc73620

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 +13 -13
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -101,7 +101,7 @@ Expected format:
101
101
  `),K.newLines.join(`
102
102
  `))));Q.push({path:Y.movePath??Y.path,diffStat:X})}return Q}function s00(J){let Z=0,Q=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((K)=>{let V=Dx1(K);if(!V)return;let{name:z,input:G}=V,F=null;if(z==="edit_file"){if("old_str"in G&&"new_str"in G){let{old_str:q,new_str:W}=G;F=vD(q,W)}}else if(z==="apply_patch"){let q=Bx1(G);F=gA0(q.map((W)=>W.diffStat))}else if((z==="write_file"||z==="create_file")&&"content"in G&&typeof G.content==="string")F=yD(G.content);if(F)Z+=F.added,Y+=F.deleted,Q+=F.changed})}),{added:Z,changed:Q,deleted:Y}}function Nx1(J){let Z=new Map;return J.messages.forEach((Q)=>{if(Q.role!=="assistant")return;Q.content.forEach((Y)=>{let X=Dx1(Y);if(!X)return;let{name:K,input:V}=X,z,G=null;if(K==="edit_file"){if("path"in V&&typeof V.path==="string"&&"old_str"in V&&"new_str"in V){z=V.path;let{old_str:F,new_str:q}=V;G=vD(F,q)}}else if(K==="apply_patch"){for(let F of Bx1(V)){let q=Fx1(F.path,J.env?.initial?.trees);if(q){let W=Z.get(q)??{added:0,changed:0,deleted:0};W.added+=F.diffStat.added,W.changed+=F.diffStat.changed,W.deleted+=F.diffStat.deleted,Z.set(q,W)}}return}else if((K==="write_file"||K==="create_file")&&"path"in V&&typeof V.path==="string"&&"content"in V&&typeof V.content==="string")z=V.path,G=yD(V.content);if(z&&G){let F=Fx1(z,J.env?.initial?.trees);if(F){let q=Z.get(F)??{added:0,changed:0,deleted:0};q.added+=G.added,q.changed+=G.changed,q.deleted+=G.deleted,Z.set(F,q)}}})}),Z}function Fx1(J,Z){let Q=J.startsWith("/"),Y=/^[a-zA-Z]:[\\/]/.test(J);if(!Q&&!Y)return J;let X=J.replace(/\\/g,"/");if(Z&&Z.length>0)for(let z of Z){if(!z.uri)continue;let G=z.uri.match(/^file:\/\/(.+)$/);if(!G?.[1])continue;let F=decodeURIComponent(G[1]).replace(/\\/g,"/"),q=F.startsWith("/")&&/^\/[a-zA-Z]:/.test(F)?F.slice(1):F;if(X.startsWith(q)){let W=X.slice(q.length);return W.startsWith("/")?W.slice(1):W}}let K=X.match(/\/(?:Users|home)\/[^/]+\/[^/]+\/(.+)/);if(K?.[1])return K[1];let V=X.match(/^[a-zA-Z]:\/Users\/[^/]+\/[^/]+\/(.+)/);if(V?.[1])return V[1];return null}function cP(J,Z){let Q=J.relationships?.filter((K)=>K.role==="child")??[],Y=nu(J),X=[...Q,...Y];return Z?X.filter((K)=>K.type===Z):X}function t00(J,Z){return cP(J,Z)[0]}function iZ(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user")return Q}return}function wx1(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user"&&Q.agentMode)return Q.agentMode}return}function nu(J){let Z=[],Q=new Set;if(!J.messages)return Z;return J.messages.forEach((Y,X)=>{if(Y.role!=="assistant")return;Y.content.forEach((K)=>{if(K.type!=="tool_use")return;if(K.name!==EW)return;if(!S8(K))return;let V=K.input,z=typeof V.threadID==="string"?H$(V.threadID):null;if(z&&!Q.has(z))Q.add(z),Z.push({threadID:z,type:"mention",role:"parent",messageIndex:X,createdAt:Date.now()})})}),Z}var d4=Q0(()=>{xA0();m0();_4();aO();hP()});var N4=Q0(()=>{SP();C00();cO()});import PS6 from"os";import e00 from"path";var fD,rO,uD,lP,Ex1,de3,ce3,CS6,TS6;var au=Q0(()=>{fD=PS6.homedir(),{env:rO}=process,uD=rO.XDG_DATA_HOME||(fD?e00.join(fD,".local","share"):void 0),lP=rO.XDG_CONFIG_HOME||(fD?e00.join(fD,".config"):void 0),Ex1=rO.XDG_STATE_HOME||(fD?e00.join(fD,".local","state"):void 0),de3=rO.XDG_CACHE_HOME||(fD?e00.join(fD,".cache"):void 0),ce3=rO.XDG_RUNTIME_DIR||void 0,CS6=(rO.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");if(uD)CS6.unshift(uD);TS6=(rO.XDG_CONFIG_DIRS||"/etc/xdg").split(":");if(lP)TS6.unshift(lP)});import{homedir as $10}from"node:os";import AW from"node:path";var Mx1,_S6,Ax1,SS6,iP,kS6,nP,vS6,nZ;var PX=Q0(()=>{au();Mx1=AW.join($10(),".local/share"),_S6=process.platform==="win32"||process.platform==="darwin"?Mx1:uD??Mx1,Ax1=AW.join($10(),".config"),SS6=process.platform==="win32"||process.platform==="darwin"?Ax1:lP??Ax1,iP=AW.join(_S6,"amp"),kS6=AW.join(SS6,"amp"),nP=AW.join(kS6,"tools"),vS6=process.platform==="win32"?AW.join(process.env.LOCALAPPDATA??AW.join($10(),"AppData","Local"),"amp"):AW.join(process.env.XDG_CACHE_HOME??AW.join($10(),".cache"),"amp"),nZ=vS6});function xS6(){return!1}function jx1(J){return J.trim().toLowerCase()}function fS6(J){if(!J.endsWith("@sourcegraph.com"))return!1;if(xS6())return!0;return yS6.has(J)}function J10(J){let Z=jx1(J);if(Z.length===0)return!1;return Z.endsWith("@sourcegraph.com")||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}function dJ(J){let Z=jx1(J);if(Z.length===0)return!1;return fS6(Z)||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}var yS6;var sO=Q0(()=>{yS6=new Set(["alex.kemper@sourcegraph.com","beyang@sourcegraph.com","brady.jeong@sourcegraph.com","brett.jones@sourcegraph.com","camden@sourcegraph.com","connor.obrien@sourcegraph.com","dario.hamidi@sourcegraph.com","hamish.bultitude@sourcegraph.com","harry.charlesworth@sourcegraph.com","hitesh.sagtani@sourcegraph.com","isuru.fonseka@sourcegraph.com","jesse.edelstein@sourcegraph.com","jim.espelico@sourcegraph.com","karl.clement@sourcegraph.com","lewis.metcalf@sourcegraph.com","nicolay.gerold@sourcegraph.com","sqs@sourcegraph.com","thorsten@sourcegraph.com","tim.culverhouse@sourcegraph.com","tim.lucas@sourcegraph.com","will.dollman@sourcegraph.com","devsqs@sourcegraph.com"])});function i4(J,Z,Q=Z+"s"){return J===1?Z:Q}var _7=()=>{};function aA0(J){return Z10[J]??0}function uS6(J){return typeof J==="number"&&Number.isInteger(J)&&J>=1&&J<=3600}function Ix1(J){let Z=J.settings["tools.inactivityTimeout"],Q=J.settings["tools.stopTimeout"],Y=Z;if(Y===void 0&&Q!==void 0)Y=Q;if(Y===void 0)Y=aA0("amp.tools.inactivityTimeout");if(!uS6(Y))return null;return Y*1000}function Px1(J){let Z=J.settings["tools.stopTimeout"],Q=aA0("amp.tools.stopTimeout");return(Z??Q)*1000}function ou(J){let Z=J.settings["network.timeout"],Q=aA0("amp.network.timeout");return(Z??Q)*1000}var Z10,Rx1;var aP=Q0(()=>{Z10={"amp.tools.inactivityTimeout":300,"amp.tools.stopTimeout":300,"amp.network.timeout":30},Rx1={"amp.tools.inactivityTimeout":{default:Z10["amp.tools.inactivityTimeout"]},"amp.tools.stopTimeout":{default:Z10["amp.tools.stopTimeout"]},"amp.network.timeout":{default:Z10["amp.network.timeout"]}}});function Q10(J){Promise.resolve().then(()=>{try{J()}catch(Z){console.error(Z)}})}function Cx1(J){let Z=J._cleanup;if(Z===void 0)return;if(J._cleanup=void 0,!Z)return;try{if(typeof Z==="function")Z();else if(Z&&typeof Z.unsubscribe==="function")Z.unsubscribe()}catch(Q){console.error("cleanupSubscription",Q)}}function rA0(J){J._observer=void 0,J._queue=void 0,J._state="closed"}function bS6(J){let Z=J._queue;if(!Z)return;J._queue=void 0,J._state="ready";for(let Q of Z)if(Tx1(J,Q.type,Q.value),J._state==="closed")break}function Tx1(J,Z,Q){J._state="running";let Y=J._observer;try{switch(Z){case"next":if(Y&&typeof Y.next==="function")Y.next(Q);break;case"error":if(rA0(J),Y&&typeof Y.error==="function")Y.error(Q);else throw Q;break;case"complete":if(rA0(J),Y&&typeof Y.complete==="function")Y.complete();break}}catch(X){console.error("notifySubscription",X)}if(J._state==="closed")Cx1(J);else if(J._state==="running")J._state="ready"}function oA0(J,Z,Q){if(J._state==="closed")return;if(J._state==="buffering"){J._queue=J._queue||[],J._queue.push({type:Z,value:Q});return}if(J._state!=="ready"){J._state="buffering",J._queue=[{type:Z,value:Q}],Q10(()=>bS6(J));return}Tx1(J,Z,Q)}class _x1{_cleanup;_observer;_queue;_state;constructor(J,Z){this._cleanup=void 0,this._observer=J,this._queue=void 0,this._state="initializing";let Q=new Sx1(this);try{this._cleanup=Z.call(void 0,Q)}catch(Y){Q.error(Y)}if(this._state==="initializing")this._state="ready"}get closed(){return this._state==="closed"}unsubscribe(){if(this._state!=="closed")rA0(this),Cx1(this)}}class Sx1{_subscription;constructor(J){this._subscription=J}get closed(){return this._subscription._state==="closed"}next(J){oA0(this._subscription,"next",J)}error(J){oA0(this._subscription,"error",J)}complete(){oA0(this._subscription,"complete")}}function l8(J){if(typeof J==="function")J();else if(J&&typeof J.unsubscribe==="function")J.unsubscribe()}class oP{_baseObserver;_pendingPromises;constructor(J){this._baseObserver=J,this._pendingPromises=new Set}complete(){Promise.all(this._pendingPromises).then(()=>this._baseObserver.complete()).catch((J)=>this._baseObserver.error(J))}error(J){this._baseObserver.error(J)}schedule(J){let Z=Promise.all(this._pendingPromises),Q=[],Y=(K)=>Q.push(K),X=Promise.resolve().then(async()=>{await Z,await J(Y),this._pendingPromises.delete(X);for(let K of Q)this._baseObserver.next(K)}).catch((K)=>{this._pendingPromises.delete(X),this._baseObserver.error(K)});this._pendingPromises.add(X)}}function sA0(J){return J&&typeof J.subscribe==="function"&&typeof J[Symbol.observable]==="function"}function tA0(J){if(sA0(J))return J;return k0.of(J)}var k0;var rP=Q0(()=>{if(!Symbol.observable)Symbol.observable=Symbol("observable");k0=class k0{_subscriber;constructor(J){if(!(this instanceof k0))throw TypeError("Observable cannot be called as a function");if(typeof J!=="function")throw TypeError("Observable initializer must be a function");this._subscriber=J}subscribe(J,Z,Q){if(typeof J!=="object"||J===null)J={next:J,error:Z,complete:Q};return new _x1(J,this._subscriber)}pipe(J,...Z){let Q=this;for(let Y of[J,...Z])Q=Y(Q);return Q}[Symbol.observable](){return this}static from(J){let Z=typeof k0==="function"?k0:k0;if(J==null)throw TypeError(J+" is not an object");let Q=J[Symbol.observable];if(typeof Q==="function"){let X=Q.call(J);if(Object(X)!==X)throw TypeError(X+" is not an object");if(X instanceof k0)return X;return new Z((K)=>X.subscribe(K))}let Y=J[Symbol.iterator];if(typeof Y==="function")return new Z((X)=>{Q10(()=>{if(X.closed)return;for(let K of Y.call(J))if(X.next(K),X.closed)return;X.complete()})});if(Array.isArray(J))return new Z((X)=>{Q10(()=>{if(X.closed)return;for(let K of J)if(X.next(K),X.closed)return;X.complete()})});throw TypeError(J+" is not observable")}static of(...J){return new(typeof k0==="function"?k0:k0)((Q)=>{Q10(()=>{if(Q.closed)return;for(let Y of J)if(Q.next(Y),Q.closed)return;Q.complete()})})}static get[Symbol.species](){return k0}}});var Y4,K4;var Y10=Q0(()=>{rP();Y4=class Y4 extends k0{_observers=new Set;constructor(){super((J)=>{return this._observers.add(J),()=>this._observers.delete(J)})}next(J){for(let Z of this._observers)Z.next(J)}error(J){for(let Z of this._observers)Z.error(J)}complete(){for(let J of this._observers)J.complete()}};K4=class K4 extends Y4{currentValue;constructor(J){super();this.currentValue=J}next(J){this.currentValue=J,super.next(J)}subscribe(J,Z,Q){if(typeof J!=="object"||J===null){let Y={};if(J)Y.next=J;if(Z)Y.error=Z;if(Q)Y.complete=Q;J=Y}return J.next?.(this.currentValue),super.subscribe(J)}getValue(){return this.currentValue}}});var eA0,ru;var kx1=Q0(()=>{rP();Y10();eA0=class eA0 extends Set{subject=new K4(this);add(J){return super.add(J),this.subject.next(this),this}delete(J){let Z=super.delete(J);if(Z)this.subject.next(this);return Z}clear(){super.clear(),this.subject.next(this)}get observable(){return k0.from(this.subject)}dispose(){this.subject.complete()}};ru=class ru extends Map{subject=new K4(this);set(J,Z){return super.set(J,Z),this.subject.next(this),this}delete(J){let Z=super.delete(J);if(Z)this.subject.next(this);return Z}clear(){super.clear(),this.subject.next(this)}get observable(){return k0.from(this.subject)}dispose(){this.subject.complete()}}});function X10(J,Z){if(J===Z)return!0;if(J==null||Z==null||typeof J!=="object"||typeof Z!=="object")return!1;let Q=Array.isArray(J),Y=Array.isArray(Z);if(Q!==Y)return!1;if(Q&&Y)return J.length===Z.length&&J.every((K,V)=>X10(K,Z[V]));let X=new Set([...Object.keys(J),...Object.keys(Z)]);for(let K of X)if(!X10(J[K],Z[K]))return!1;return!0}var K10;var $j0=Q0(()=>{K10={now:()=>Date.now(),schedule:(J,Z)=>{let Q=setTimeout(J,Z);return()=>clearTimeout(Q)}}});function Jj0(J){return{dispose:J.unsubscribe.bind(J)}}async function j1(J,Z){return new Promise((Q,Y)=>{let X,K=()=>{X?.unsubscribe(),Y(new DOMException("Aborted","AbortError"))};Z?.addEventListener("abort",K,{once:!0}),X=J.subscribe({next:(V)=>{X?.unsubscribe(),Z?.removeEventListener("abort",K),Q(V)},error:(V)=>{Z?.removeEventListener("abort",K),Y(V)},complete:()=>{Z?.removeEventListener("abort",K),Y("Observable completed without emitting a value")}})})}async function bD(J,Z){return new Promise((Q,Y)=>{let X,K=!1,V,z=()=>{V?.unsubscribe(),Y(new DOMException("Aborted","AbortError"))};Z?.addEventListener("abort",z,{once:!0}),V=J.subscribe({next:(G)=>{X=G,K=!0},error:(G)=>{Z?.removeEventListener("abort",z),Y(G)},complete:()=>{if(Z?.removeEventListener("abort",z),K)Q(X);else Y("Observable completed without emitting a value")}})})}async function yx1(J,Z){return new Promise((Q,Y)=>{let X=J.subscribe({error:Y,complete:()=>Q()});Z?.addEventListener("abort",()=>{X.unsubscribe(),Y(new DOMException("Aborted","AbortError"))},{once:!0})})}function J9(J){return new k0((Z)=>{J.then((Q)=>{Z.next(Q),Z.complete()}).catch((Q)=>{Z.error(Q)})})}function k4(J){return new k0((Z)=>{let Q=!1,Y=new AbortController,X=Y.signal;return(async()=>{try{X?.throwIfAborted();let V=await J(X);if(X?.throwIfAborted(),!Q)Z.next(V),Z.complete()}catch(V){if(!Q)if(X.aborted)Z.complete();else Z.error(V)}})(),()=>{Q=!0,Y.abort()}})}function D1(J){return(Z)=>{return new k0((Q)=>{let Y=new oP(Q),X=0,K=Z.subscribe({complete(){Y.complete()},error(V){Y.error(V)},next(V){Y.schedule(async(z)=>{let G=await J(V,X);X++,z(G)})}});return()=>l8(K)})}}function sP(J,Z=K10){return new k0((Q)=>{let Y=0,X=null,K=()=>{Q.next(Y++),X=Z.schedule(K,J)};return X=Z.schedule(K,J),()=>{if(X)X()}})}function aZ(...J){return new k0((Z)=>{let Q=0,Y=J.map((X)=>X.subscribe({next:(K)=>Z.next(K),error:(K)=>Z.error(K),complete:()=>{if(Q++,Q===J.length)Z.complete()}}));return()=>{xx1(Y)}})}function D5(...J){if(J.length===0)return su;return new k0((Z)=>{let Q=Array(J.length),Y=Array(J.length).fill(0),X=Array(J.length).fill(!1),K=0,V=[],z=new oP(Z);for(let G=0;G<J.length;G++){let F=J[G];V.push(F.subscribe({next(q){Q[G]=q,X[G]=!0;let W=++Y[G];if(X.every(Boolean))z.schedule(async(U)=>{if(Y[G]===W)U([...Q])})},error(q){z.error(q)},complete(){if(K++,K===J.length)z.complete()}}))}return()=>{xx1(V)}})}function c6(J){let Q=J?.shouldCountRefs??!0,Y=hS6++,X=(K,...V)=>{};return(K)=>{let V=new Y4,z=null,G=!1,F,q=0;return new k0((W)=>{if(q++,G)X("new subscriber, emitting buffered value",F),W.next(F);else X("new subscriber, no buffered value to emit");if(!z)z=K.subscribe({next:(H)=>{G=!0,F=H,V.next(H)},error:(H)=>V.error(H),complete:()=>V.complete()});let U=V.subscribe(W);return()=>{if(q--,U.unsubscribe(),Q&&q===0){if(z)l8(z),z=null;G=!1}}})}}function xx1(J){for(let Z of J)if(Z)l8(Z)}function jW(J){return(Z)=>{return new k0((Q)=>{let Y=Z.subscribe({next:(K)=>Q.next(K),error:(K)=>Q.error(K),complete:()=>Q.complete()}),X=J.subscribe({next:()=>{Q.complete(),Y.unsubscribe(),X.unsubscribe()},error:(K)=>{Q.error(K),Y.unsubscribe()}});return()=>{Y.unsubscribe(),X.unsubscribe()}})}}function hD(J){return(Z)=>{return new k0((Q)=>{let Y,X=Z.subscribe({next(K){Y=K,Q.next(K)},error(K){Q.error(K)},complete(){Q.complete()}});return()=>{l8(X),J(Y)}})}}function b4(J=X10){return(Z)=>{return new k0((Q)=>{let Y=vx1,X=new oP(Q),K=Z.subscribe({complete(){X.complete()},error(V){X.error(V)},next(V){X.schedule(async(z)=>{if(Y===vx1||!J(Y,V))Y=V,z(V)})}});return()=>l8(K)})}}function tP(J){return gS6(typeof J==="function"?{next:J}:J)}function gS6(J){return(Z)=>new k0((Q)=>{let Y=typeof J==="function"?J():J,X=Z.subscribe({next(K){if(Y.next)try{Y.next(K)}catch(V){Q.error(V);return}Q.next(K)},error(K){if(Y.error)try{Y.error(K)}catch(V){Q.error(V);return}Q.error(K)},complete(){if(Y.complete)try{Y.complete()}catch(K){Q.error(K);return}Q.complete()}});return()=>l8(X)})}function cJ(J){return(Z)=>{return new k0((Q)=>{let Y=!1,X=Z.subscribe({next:(V)=>{Y=!0,clearTimeout(K),Q.next(V)},error:(V)=>{clearTimeout(K),Q.error(V)},complete:()=>{clearTimeout(K),Q.complete()}}),K=setTimeout(()=>{if(!Y)X.unsubscribe(),Q.error(new V10(`Operation timed out after ${J}ms`))},J);return()=>{clearTimeout(K),X.unsubscribe()}})}}function K5(J){return(Z)=>new k0((Q)=>{let Y;try{Q.next(J),Y=Z.subscribe({next(X){Q.next(X)},error(X){Q.error(X)},complete(){Q.complete()}})}catch(X){Q.error(X)}return()=>{if(Y)l8(Y)}})}function lJ(J){return(Z)=>new k0((Q)=>{let Y=0,X=Z.subscribe({next(K){if(Y<J){if(Q.next(K),Y++,Y===J)Q.complete(),l8(X)}},error(K){Q.error(K)},complete(){Q.complete()}});return()=>{l8(X)}})}function fx1(J){return(Z)=>new k0((Q)=>{let Y=0,X=Z.subscribe({next(K){if(Y>=J)Q.next(K);else Y++},error(K){Q.error(K)},complete(){Q.complete()}});return()=>{l8(X)}})}function H4(J){return(Z)=>{return new k0((Q)=>{let Y=0,X=null,K=!1,V=()=>{if(K&&!X)Q.complete()},z=Z.subscribe({next(G){if(X)l8(X),X=null;let F;try{F=J(G,Y++)}catch(q){Q.error(q);return}X=F.subscribe({next(q){Q.next(q)},error(q){Q.error(q)},complete(){X=null,V()}})},error(G){Q.error(G)},complete(){K=!0,V()}});return()=>{if(l8(z),X)l8(X)}})}}function iJ(J,Z){let Q=Z?.scheduler??K10;return(Y)=>new k0((X)=>{let K=null,V=null,z=!1,G=Y.subscribe({next:(F)=>{if(V=F,z=!0,K===null)K=Q.schedule(()=>{if(z)X.next(V),z=!1;K=null},J)},error:(F)=>X.error(F),complete:()=>{if(K!==null)K();if(z)X.next(V);X.complete()}});return()=>{if(l8(G),K!==null)K()}})}function Zj0(J,Z){if(!Z.leading||!Z.trailing)throw Error("leading and trailing must be true");let Q=Z.scheduler??K10;return(Y)=>new k0((X)=>{let K=0,V=null,z=null,G=!1,F=Y.subscribe({next:(q)=>{let W=Q.now();if(z=q,G=!0,W-K>=J)X.next(q),K=W,G=!1;else if(V===null)V=Q.schedule(()=>{if(G)X.next(z),K=Q.now(),G=!1;V=null},J-(W-K));if(K===0)X.next(q),K=W,G=!1},error:(q)=>X.error(q),complete:()=>{if(V!==null)V();if(G)X.next(z);X.complete()}});return()=>{if(l8(F),V!==null)V()}})}function eu(...J){return new k0((Z)=>{let Q=0,Y=null;function X(){if(Q>=J.length){Z.complete();return}Y=J[Q].subscribe({next:(V)=>Z.next(V),error:(V)=>Z.error(V),complete:()=>{Q++,X()}})}return X(),()=>{if(Y)l8(Y)}})}function gD(J){return(Z)=>new k0((Q)=>{let Y=0,X=!1,K=null,V=Z.subscribe({next(z){try{let G=J(z,Y++);if(K)l8(K);K=G.subscribe({next(F){Q.next(F)},error(F){Q.error(F)},complete(){if(K=null,X&&!K)Q.complete()}})}catch(G){Q.error(G)}},error(z){Q.error(z)},complete(){if(X=!0,!K)Q.complete()}});return()=>{if(l8(V),K)l8(K)}})}function $b({onSubscribe:J,onUnsubscribe:Z}){return(Q)=>new k0((Y)=>{J?.();let X=Q.subscribe(Y);return()=>{l8(X),Z?.()}})}function mD(J){return(Z)=>k0.from(Z).pipe(H4((Q)=>k4((Y)=>J(Q,Y))))}function nJ(J){return(Z)=>new k0((Q)=>{let Y,X=Z.subscribe({next(K){Q.next(K)},error(K){try{Y=J(K).subscribe({next(z){Q.next(z)},error(z){Q.error(z)},complete(){Q.complete()}})}catch(V){Q.error(V)}},complete(){Q.complete()}});return()=>{if(l8(X),Y)l8(Y)}})}function T5(J){return(Z)=>{return new k0((Q)=>{let Y=Z.subscribe({next(X){if(J(X))Q.next(X)},error(X){Q.error(X)},complete(){Q.complete()}});return()=>l8(Y)})}}function ux1(J,Z){return(Q)=>{return new k0((Y)=>{let X,K=0,V=new oP(Y),z=Q.subscribe({complete(){V.complete()},error(G){V.error(G)},next(G){V.schedule(async(F)=>{X=await J(K===0?typeof Z>"u"?G:Z:X,G,K++),F(X)})}});return()=>l8(z)})}}var su,tu,H08,hS6=0,vx1,V10;var Qj0=Q0(()=>{rP();$j0();Y10();su=new k0((J)=>{J.complete()}),tu=new k0(()=>{});H08=Symbol("noInitialValue");vx1={};V10=class V10 extends Error{constructor(J="Timeout has occurred"){super(J);this.name="TimeoutError"}}});function eP(J,Z){return(Q)=>{return k0.from(Q).pipe(H4((Y)=>Y===kG?k0.of(kG):J(Y).pipe(nJ((X)=>k0.of(X instanceof Error?X:Error(X))),K5(kG))),c6(Z))}}function Yj0(){return(J)=>k0.from(J).pipe(T5((Z)=>Z!==kG))}async function bx1(J,Z){let Q=await j1(k0.from(J).pipe(Yj0()),Z);if(Q instanceof Error)throw Q;return Q}var kG;var hx1=Q0(()=>{rP();Qj0();kG=Symbol.for("@@pendingOperation")});var gx1=()=>{};var O1=Q0(()=>{kx1();rP();hx1();Qj0();$j0();Y10();gx1()});function Jk6(J){return rx1.safeParse(J)}function pD(J){return $k6.safeParse(J)}function ZC(J){if(!J||!Array.isArray(J))return[];let Z=[];for(let[Q,Y]of J.entries()){let X=Jk6(Y);if(X.success)Z.push(X.data);else{let K=typeof Y==="object"&&Y!==null&&"tool"in Y?String(Y.tool):`entry at index ${Q}`;P.warn(`Permission entry for tool "${K}" is invalid: ${X.error.issues.map((V)=>`${V.path.join(".")}: ${V.message}`).join(", ")}`)}}return Z}var Uj0,rx1,$k6;var eO=Q0(()=>{t$();m0();Uj0=v.lazy(()=>v.union([v.string().describe('Pattern match where "*" matches any number of any characters'),v.array(Uj0).min(1).describe("OR match of each entry"),v.boolean().describe("A literal boolean match"),v.number().describe("A literal number match"),v.null().describe("A literal null match"),v.undefined().describe("A literal undefined match"),v.record(v.string(),Uj0).describe("Matching individual keys of an object")])),rx1=v.object({tool:v.string().min(1).describe("The name of the tool to which this entry applies"),matches:v.record(v.string(),Uj0).optional().describe("Maps tool inputs to conditions"),action:v.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:v.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:v.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:v.string().optional().describe('Message to return to the model when action is "reject". If set, the rejection is returned as an error so the model can continue.')}).superRefine((J,Z)=>{if(J.action==="delegate"&&!J.to)Z.addIssue({code:"custom",message:'delegate action requires "to" field',path:["to"]});if(J.action!=="delegate"&&J.to)Z.addIssue({code:"custom",message:'"to" field only allowed with delegate action',path:["to"]});if(J.message&&J.action!=="reject")Z.addIssue({code:"custom",message:'"message" field only allowed with reject action',path:["message"]})}),$k6=v.array(rx1).describe("Entries checked in sequence to configure tool permissions")});function Z9(J,Z){let Q=Zk6(J,Z);return typeof Q==="string"?Q:Q.toString()}function Zk6(J,Z,Q=!0){if(!Z)Z=Qk6();let{workspaceFolders:Y,isWindows:X,homeDir:K}=Z,V=typeof J==="string"?V1.parse(J):V1.from(J);if(Y)for(let z of Y){let G=_6(z);if(Y1.hasPrefix(V,G)){let F=G.path.endsWith("/")?G.path.slice(0,-1):G.path,W=Q&&Y&&Y.length>=2?OW(G.path)+(X?"\\":"/"):"";return Hj0(W+V.path.slice(F.length+1),X,V.scheme)}}if(V?.scheme==="file"){if(K){let z=_6(K);if(Y1.hasPrefix(V,z)){let G=z.path.endsWith("/")?z.path.slice(0,-1):z.path,F=V.path.slice(G.length+1);return Hj0("~"+(X?"\\":"/")+F,X,V.scheme)}}return Hj0(V.fsPath,X,V.scheme)}return V}function Hj0(J,Z,Q){return Z&&Q==="file"?J.replaceAll("/","\\"):J}function U10(J){let Z=W10;return W10=J,Z}function Qk6(){if(W10)return W10;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var W10=null;var CX=Q0(()=>{N4();cO();C00()});function S7(J){if(!J)return{};return{[Dj0]:J.id,[Yk6]:J.agentMode??""}}var F7="x-amp-feature",Dj0="x-amp-thread-id",e$="x-amp-message-id",Yk6="x-amp-mode",sx1="X-Amp-Client-Application",Xb="X-Amp-Client-Type",tx1="X-Amp-Client-Version",ex1="X-Amp-Installation-ID",$f1="X-Amp-Device-Fingerprint";var oZ=()=>{};function Qf1(J){Jf1=J}function $E(J){Kb=J}function Yf1(J){Zf1=J}function Xf1(J){Vb=J.installationID,zb=J.deviceFingerprint}function Kf1(){if(!Vb||!zb)return;return{installationID:Vb,deviceFingerprint:zb}}function JE(){let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Z;if(!Kb)Z="CLI";else if(["Neovim","JetBrains","Zed"].includes(Kb))Z=Kb;else Z=`${Kb} CLI`;return{type:"cli",name:Zf1?`${Z} Execute Mode`:Z,version:Jf1}}function k7(){let J=JE(),Z={};if(Z[sx1]=J.name,Z[Xb]=J.type,Vb)Z[ex1]=Vb;if(zb)Z[$f1]=zb;if(J.version)Z[tx1]=J.version;return Z}var Jf1=null,Kb=null,Zf1=!1,Vb=null,zb=null;var $J=Q0(()=>{oZ()});function Xk6(J){if(typeof process>"u"||!process.versions?.node)return"unknown";try{switch(J){case"darwin":{try{let{execSync:Q}=I0("node:child_process"),X=Q("/usr/bin/sw_vers -productVersion",{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}).trim();if(X&&/^\d+\.\d+/.test(X))return X}catch{}return I0("node:os").release()}case"linux":try{let Y=I0("node:fs").readFileSync("/etc/os-release","utf8").split(`
103
103
  `);for(let K of Y)if(K.startsWith("PRETTY_NAME=")){let V=K.match(/PRETTY_NAME="?([^"]*)"?/);if(V?.[1])return V[1]}return I0("node:os").release()}catch{return I0("node:os").release()}case"windows":try{let{execSync:Z}=I0("node:child_process"),Y=Z('systeminfo | findstr /B /C:"OS Name" /C:"OS Version"',{encoding:"utf8",timeout:5000}).split(`
104
- `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),G=K.split(":")[1]?.trim();return`${z} ${G}`}return I0("node:os").release()}catch{return I0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function vG(){if(!Bj0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=Xk6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}Bj0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:JE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return Bj0}var Bj0;var QC=Q0(()=>{$J()});function c3(J){let Z=G5[J];return`${Z.provider}/${Z.name}`}function yG(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function D$(J){let{provider:Z,model:Q}=yG(J);for(let Y of Object.values(G5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return G5.CLAUDE_SONNET_4_5;case"openai":return G5.GPT_5;case"xai":return G5.GROK_CODE_FAST_1;case"cerebras":return G5.Z_AI_GLM_4_7;case"fireworks":return G5.FIREWORKS_GLM_4P6;case"baseten":return G5.BASETEN_KIMI_K2P5;case"moonshotai":return G5.KIMI_K2_INSTRUCT;case"openrouter":return G5.SONOMA_SKY_ALPHA;case"groq":return G5.GPT_OSS_120B;case"vertexai":return G5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function Gb(J){for(let Q of Object.values(G5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(G5))if(Y.name===Q)return Y}return}function Y8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function JJ(J){let Z=D$(J);return Z.contextWindow-Z.maxOutputTokens}function H10(J){return D$(J).maxOutputTokens}var h6,G5,Nj0;var _2=Q0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},G5={CLAUDE_SONNET_4:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:h6.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:h6.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:h6.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:h6.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:h6.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:h6.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:h6.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:h6.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:h6.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:h6.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:h6.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:h6.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:h6.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:h6.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:h6.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:h6.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:h6.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:h6.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};Nj0={FINDER:"finder"}});function B10(J){return J===D10}function YY(J){return J==="deep"||J===D10}function ZE(J,Z){if(!B10(J))return!0;return Boolean(Z&&dJ(Z))}function wj0(J,Z){let Q=B$(Z);if(!Q)return!1;if(Kk6.has(J)){let Y=Q.finder??Nj0.FINDER,X=Vk6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function Wf1(J,Z){let Q=B$(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function fG(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(xG).filter((z)=>{if(!ZE(z.key,Q?.userEmail))return!1;if(z.key===N10)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&N8(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let F="visible"in z?z.visible:!1,q=K.includes(z.key);return F||q}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,G)=>z.mode.localeCompare(G.mode))}function Lj0(J,Z,Q){let Y=fG(J,Z,Q),X=new Set(J?.disabledAgentModes??[]),K=w10.filter((V)=>{if(!B$(V))return!1;if(X.has(V))return!1;if(Z===!1&&N8(V))return!1;if(!ZE(V,Q?.userEmail))return!1;return!0}).sort((V,z)=>V.localeCompare(z));return{visibleAgentModes:Y,allowedAgentModes:K}}function B$(J){return Object.values(xG).find((Z)=>Z.key===J)}function TX(J){return B$(J)?.primaryModel??c3("CLAUDE_SONNET_4_5")}function Fb(J){let Z=B$(J);if(!Z)return!1;return D$(Z.primaryModel).capabilities?.vision??!1}function N8(J){return J==="free"||J.startsWith("free-")}function Oj0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function Ej0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var Kk6,Vk6,Ff1,qf1,D10="internal",zk6,Gk6,Vf1,zf1,Gf1,Fk6,qk6,Wk6,xG,N10,w10;var N$=Q0(()=>{sO();_2();Kk6=new Set(["finder"]),Vk6={finder:"finder"},Ff1={r:0,g:55,b:0},qf1={r:0,g:255,b:136};zk6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Gk6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],Vf1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot"],zf1=["code_tour","code_review","walkthrough","walkthrough_diagram"],Gf1=["code_tour","code_review"],Fk6=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],qk6=["shell_command","apply_patch","web_search","read_web_page","mermaid","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Wk6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","Task","send_message_to_aggman"],xG={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Vf1,deferredTools:zf1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:c3("CLAUDE_HAIKU_4_5"),includeTools:zk6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:c3("CLAUDE_HAIKU_4_5"),includeTools:Gk6,visible:!0,uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Fk6,visible:!1,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Vf1,deferredTools:zf1,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.4",primaryModel:c3("GPT_5_4"),includeTools:qk6,deferredTools:Gf1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:D10,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:c3("GPT_5_4"),includeTools:Wk6,deferredTools:Gf1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},N10=xG.AGG.key,w10=Object.values(xG).map((J)=>J.key)});var y3=Q0(()=>{N$();_2()});function qb(J){return J["agent.deepReasoningEffort"]??"high"}function Mj0(J){let Z=Uk6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function Aj0(J){return Hk6.includes(J)}function Hf1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return G5.GPT_5_4.name}function Df1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var Uk6,Hk6,L10,Uf1;var RW=Q0(()=>{y3();Uk6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];Hk6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];L10=["mcpServers","mcpPermissions","url"],Uf1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var S2;var QE=Q0(()=>{S2={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",CODEMIRROR_DIFFS:"codemirror-diffs",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var Nf1;var jj0=Q0(()=>{du();du();Nf1=v});var _X;var j9=Q0(()=>{jj0();jj0();_X=Nf1});function E10(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function IW(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var YE=Q0(()=>{m0()});import{execFile as Dk6,spawnSync as Ub}from"node:child_process";import YC from"node:fs";import Rj0 from"node:os";import rZ from"node:path";import{promisify as Bk6}from"node:util";async function Rk6(J){try{if(!await nk6())return[];let Z=await ck6(J);if(!Z)return[];let Q=await If1(J);return(await Rf1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Ik6(J,Z){if(!Z.pid||!IW(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await If1(J),K=(await Rf1(J,Y)).find((z)=>A10(z.workspaceFolder)===A10(Q));if(!K)return null;let V=await Sk6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function Pk6(J,Z){let{filePath:Q,line:Y,column:X}=Tk6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=ak6(J);if(!V)return Lf1(J,Q,Y,X);if(Ub(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return Lf1(J,Q,Y,X)}function Lf1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",G=`${J.urlScheme}://file${V}${z}`,F=Ck6(G);if(F.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:G,status:F.status,stderr:F.stderr?.toString().trim()}),!1}function Ck6(J){if(process.platform==="darwin")return Ub("open",[J],{stdio:"ignore"});if(process.platform==="win32")return Ub("cmd.exe",["/c","start","",J],{stdio:"ignore"});return Ub("xdg-open",[J],{stdio:"ignore"})}function Tk6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return{};let Q=_k6(Z.fragment);return{filePath:Z.fsPath,line:Q?.line,column:Q?.column}}catch{return{}}}function _k6(J){let Z=J.match(wk6),Q=Z?.groups?.line;if(!Q)return null;return{line:Number.parseInt(Q,10),column:Z.groups?.column?Number.parseInt(Z.groups.column,10):void 0}}async function Sk6(J){let Z=await pk6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=kk6(Z.find((G)=>G.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((G)=>G.editors),X=Q.leaves.find((G)=>G.id===Q.activeGroup)??Q.leaves[0],K=X?yk6(X):void 0,V=xk6(Z.find((G)=>G.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await fk6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function kk6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=jf1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function jf1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>vk6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>jf1(Y));return[]}function vk6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return n1(V1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return n1(V1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function yk6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function xk6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function fk6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await uk6(J);if(V===void 0)return;let z=Of1(K.selectionStart.lineNumber,K.selectionStart.column),G=Of1(K.position.lineNumber,K.position.column),F=Ef1(z,G)<=0?z:G,q=Ef1(z,G)<=0?G:z,U=F.line===q.line&&F.character===q.character?bk6(V,F.line):hk6(V,F.line,F.character,q.line,q.character);return{range:{startLine:F.line,startCharacter:F.character,endLine:q.line,endCharacter:q.character},content:U}}async function uk6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return;return await YC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function Of1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function Ef1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function bk6(J,Z){return J.split(`
104
+ `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),G=K.split(":")[1]?.trim();return`${z} ${G}`}return I0("node:os").release()}catch{return I0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function vG(){if(!Bj0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=Xk6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}Bj0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:JE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return Bj0}var Bj0;var QC=Q0(()=>{$J()});function c3(J){let Z=G5[J];return`${Z.provider}/${Z.name}`}function yG(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function D$(J){let{provider:Z,model:Q}=yG(J);for(let Y of Object.values(G5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return G5.CLAUDE_SONNET_4_5;case"openai":return G5.GPT_5;case"xai":return G5.GROK_CODE_FAST_1;case"cerebras":return G5.Z_AI_GLM_4_7;case"fireworks":return G5.FIREWORKS_GLM_4P6;case"baseten":return G5.BASETEN_KIMI_K2P5;case"moonshotai":return G5.KIMI_K2_INSTRUCT;case"openrouter":return G5.SONOMA_SKY_ALPHA;case"groq":return G5.GPT_OSS_120B;case"vertexai":return G5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function Gb(J){for(let Q of Object.values(G5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(G5))if(Y.name===Q)return Y}return}function Y8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function JJ(J){let Z=D$(J);return Z.contextWindow-Z.maxOutputTokens}function H10(J){return D$(J).maxOutputTokens}var h6,G5,Nj0;var _2=Q0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},G5={CLAUDE_SONNET_4:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:h6.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:h6.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:h6.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:h6.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:h6.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:h6.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:h6.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:h6.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:h6.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:h6.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:h6.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:h6.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:h6.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:h6.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:h6.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:h6.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:h6.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:h6.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};Nj0={FINDER:"finder"}});function B10(J){return J===D10}function YY(J){return J==="deep"||J===D10}function ZE(J,Z){if(!B10(J))return!0;return Boolean(Z&&dJ(Z))}function wj0(J,Z){let Q=B$(Z);if(!Q)return!1;if(Kk6.has(J)){let Y=Q.finder??Nj0.FINDER,X=Vk6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function Wf1(J,Z){let Q=B$(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function fG(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(xG).filter((z)=>{if(!ZE(z.key,Q?.userEmail))return!1;if(z.key===N10)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&N8(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let F="visible"in z?z.visible:!1,q=K.includes(z.key);return F||q}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,G)=>z.mode.localeCompare(G.mode))}function Lj0(J,Z,Q){let Y=fG(J,Z,Q),X=new Set(J?.disabledAgentModes??[]),K=w10.filter((V)=>{if(!B$(V))return!1;if(X.has(V))return!1;if(Z===!1&&N8(V))return!1;if(!ZE(V,Q?.userEmail))return!1;return!0}).sort((V,z)=>V.localeCompare(z));return{visibleAgentModes:Y,allowedAgentModes:K}}function B$(J){return Object.values(xG).find((Z)=>Z.key===J)}function TX(J){return B$(J)?.primaryModel??c3("CLAUDE_SONNET_4_5")}function Fb(J){let Z=B$(J);if(!Z)return!1;return D$(Z.primaryModel).capabilities?.vision??!1}function N8(J){return J==="free"||J.startsWith("free-")}function Oj0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function Ej0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var Kk6,Vk6,Ff1,qf1,D10="internal",zk6,Gk6,Vf1,zf1,Gf1,Fk6,qk6,Wk6,xG,N10,w10;var N$=Q0(()=>{sO();_2();Kk6=new Set(["finder"]),Vk6={finder:"finder"},Ff1={r:0,g:55,b:0},qf1={r:0,g:255,b:136};zk6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Gk6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],Vf1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot"],zf1=["code_tour","code_review","walkthrough","walkthrough_diagram"],Gf1=["code_tour","code_review","walkthrough","walkthrough_diagram"],Fk6=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],qk6=["shell_command","apply_patch","web_search","read_web_page","mermaid","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Wk6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","Task","send_message_to_aggman"],xG={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Vf1,deferredTools:zf1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:c3("CLAUDE_HAIKU_4_5"),includeTools:zk6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:c3("CLAUDE_HAIKU_4_5"),includeTools:Gk6,visible:!0,uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Fk6,visible:!1,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:c3("CLAUDE_OPUS_4_6"),includeTools:Vf1,deferredTools:zf1,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.4",primaryModel:c3("GPT_5_4"),includeTools:qk6,deferredTools:Gf1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:D10,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:c3("GPT_5_4"),includeTools:Wk6,deferredTools:Gf1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},N10=xG.AGG.key,w10=Object.values(xG).map((J)=>J.key)});var y3=Q0(()=>{N$();_2()});function qb(J){return J["agent.deepReasoningEffort"]??"high"}function Mj0(J){let Z=Uk6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function Aj0(J){return Hk6.includes(J)}function Hf1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return G5.GPT_5_4.name}function Df1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var Uk6,Hk6,L10,Uf1;var RW=Q0(()=>{y3();Uk6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];Hk6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];L10=["mcpServers","mcpPermissions","url"],Uf1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var S2;var QE=Q0(()=>{S2={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",CODEMIRROR_DIFFS:"codemirror-diffs",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var Nf1;var jj0=Q0(()=>{du();du();Nf1=v});var _X;var j9=Q0(()=>{jj0();jj0();_X=Nf1});function E10(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function IW(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var YE=Q0(()=>{m0()});import{execFile as Dk6,spawnSync as Ub}from"node:child_process";import YC from"node:fs";import Rj0 from"node:os";import rZ from"node:path";import{promisify as Bk6}from"node:util";async function Rk6(J){try{if(!await nk6())return[];let Z=await ck6(J);if(!Z)return[];let Q=await If1(J);return(await Rf1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Ik6(J,Z){if(!Z.pid||!IW(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await If1(J),K=(await Rf1(J,Y)).find((z)=>A10(z.workspaceFolder)===A10(Q));if(!K)return null;let V=await Sk6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function Pk6(J,Z){let{filePath:Q,line:Y,column:X}=Tk6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=ak6(J);if(!V)return Lf1(J,Q,Y,X);if(Ub(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return Lf1(J,Q,Y,X)}function Lf1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",G=`${J.urlScheme}://file${V}${z}`,F=Ck6(G);if(F.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:G,status:F.status,stderr:F.stderr?.toString().trim()}),!1}function Ck6(J){if(process.platform==="darwin")return Ub("open",[J],{stdio:"ignore"});if(process.platform==="win32")return Ub("cmd.exe",["/c","start","",J],{stdio:"ignore"});return Ub("xdg-open",[J],{stdio:"ignore"})}function Tk6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return{};let Q=_k6(Z.fragment);return{filePath:Z.fsPath,line:Q?.line,column:Q?.column}}catch{return{}}}function _k6(J){let Z=J.match(wk6),Q=Z?.groups?.line;if(!Q)return null;return{line:Number.parseInt(Q,10),column:Z.groups?.column?Number.parseInt(Z.groups.column,10):void 0}}async function Sk6(J){let Z=await pk6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=kk6(Z.find((G)=>G.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((G)=>G.editors),X=Q.leaves.find((G)=>G.id===Q.activeGroup)??Q.leaves[0],K=X?yk6(X):void 0,V=xk6(Z.find((G)=>G.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await fk6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function kk6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=jf1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function jf1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>vk6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>jf1(Y));return[]}function vk6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return n1(V1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return n1(V1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function yk6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function xk6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function fk6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await uk6(J);if(V===void 0)return;let z=Of1(K.selectionStart.lineNumber,K.selectionStart.column),G=Of1(K.position.lineNumber,K.position.column),F=Ef1(z,G)<=0?z:G,q=Ef1(z,G)<=0?G:z,U=F.line===q.line&&F.character===q.character?bk6(V,F.line):hk6(V,F.line,F.character,q.line,q.character);return{range:{startLine:F.line,startCharacter:F.character,endLine:q.line,endCharacter:q.character},content:U}}async function uk6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return;return await YC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function Of1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function Ef1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function bk6(J,Z){return J.split(`
105
105
  `)[Z]??""}function hk6(J,Z,Q,Y,X){let K=Mf1(J,Z,Q),V=Mf1(J,Y,X);if(V<=K)return"";return J.slice(K,V)}function Mf1(J,Z,Q){let Y=0,X=0;for(let K=0;K<J.length;K+=1){if(Y===Z&&X===Q)return K;if(J[K]===`
106
106
  `)Y+=1,X=0;else X+=1}return J.length}async function Rf1(J,Z){if(Z?.size===0)return[];let Q=rZ.join(Pf1(J),"workspaceStorage");if(!await Wb(Q))return[];let Y=await YC.promises.readdir(Q,{withFileTypes:!0});return(await Promise.all(Y.filter((V)=>V.isDirectory()).map(async(V)=>{let z=V.name,G=rZ.join(Q,z),F=rZ.join(G,"state.vscdb"),q=rZ.join(G,"workspace.json");if(!await Wb(F)||!await Wb(q))return null;let W=await mk6(q);if(!W||!await Wb(W))return null;if(Z&&!Z.has(A10(W)))return null;let U=await YC.promises.stat(F);return{storageID:z,workspaceFolder:W,stateDBPath:F,mtime:U.mtimeMs}}))).filter((V)=>V!==null).sort((V,z)=>z.mtime-V.mtime).slice(0,Nk6)}async function If1(J){let Z=rZ.join(Pf1(J),"globalStorage","storage.json");if(!await Wb(Z))return null;try{let Q=await YC.promises.readFile(Z,"utf-8"),X=JSON.parse(Q).windowsState,K=Array.isArray(X?.openedWindows)?X.openedWindows:[],V=K.length>0?K:[X?.lastActiveWindow],z=new Set;for(let G of V){if(!G)continue;let F=gk6(G);if(!F)continue;z.add(A10(F))}return z}catch(Q){return P.debug(`Failed to parse ${J.ideName} windowsState`,{storageFilePath:Z,error:Q instanceof Error?Q.message:String(Q)}),null}}function gk6(J){if(J.folder)return Af1(J.folder);let Z=J.workspaceIdentifier?.configURIPath;if(!Z)return null;let Q=Af1(Z);return Q?rZ.dirname(Q):null}function Af1(J){try{return V1.parse(J).fsPath}catch{if(rZ.isAbsolute(J))return J;return null}}async function mk6(J){try{let Z=await YC.promises.readFile(J,"utf-8"),Q=JSON.parse(Z);if(Q.folder)return V1.parse(Q.folder).fsPath;if(Q.configuration)return rZ.dirname(V1.parse(Q.configuration).fsPath)}catch(Z){P.debug("Failed to parse VS Code workspace metadata",{workspaceMetadataPath:J,error:Z instanceof Error?Z.message:String(Z)})}return null}async function Wb(J){try{return await YC.promises.access(J),!0}catch{return!1}}async function pk6(J,Z){let Q=await M10("sqlite3",["-readonly","-json",dk6(J),Z],{timeout:Ak6});if(Q.status!==0)return P.debug("sqlite3 query failed for VS Code database",{status:Q.status,stderr:Q.stderr?.trim()}),[];let Y=Q.stdout?.trim();if(!Y)return[];try{return JSON.parse(Y).filter((K)=>typeof K.key==="string"&&typeof K.value==="string")}catch(X){return P.debug("Failed to parse sqlite3 JSON output for VS Code database",{error:X instanceof Error?X.message:String(X)}),[]}}function dk6(J){let Q=J.replaceAll("\\","/").split("/").map((X)=>encodeURIComponent(X)).join("/");return`file:${Q.startsWith("/")?Q:`/${Q}`}?immutable=1`}async function ck6(J){return(await lk6()).find((Y)=>ik6(J,Y.command))?.pid??null}async function lk6(){if(process.platform==="win32"){let Z=await M10("tasklist",["/FO","CSV"]);if(Z.status!==0)return[];return Z.stdout.split(`
107
107
  `).slice(1).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{let[Y,X]=Q.replaceAll('"',"").split(",");return{pid:Number.parseInt(X??"",10),command:Y??""}}).filter((Q)=>Number.isFinite(Q.pid)&&Q.command)}let J=await M10("ps",["-ax","-o","pid=","-o","command="]);if(J.status!==0)return[];return J.stdout.split(`
@@ -6019,7 +6019,7 @@ Trace directory: ${J.traceDir}
6019
6019
  `+o0.grey("Debug details:")+`
6020
6020
  `),J.stack)Uw.write(J.stack+`
6021
6021
  `);else Uw.write(String(J)+`
6022
- `);return Uj(),J instanceof T1?J.exitCode:1}function QR4(J,Z){let Q=ZR4(J,Z);process.exit(Q)}async function zH(J,Z){let Q=ZR4(J,Z);await VH(),process.exit(Q)}m0();N$();DN();d4();_4();O1();var YY0=(J)=>{let Z=!1;return{install:()=>{if(!Z)process.on("SIGINT",J),process.on("SIGTERM",J),Z=!0},remove:()=>{if(Z)process.off("SIGINT",J),process.off("SIGTERM",J),Z=!1},get installed(){return Z}}};import{once as I23}from"node:events";import{createInterface as P23}from"node:readline";m0();N$();DN();ZQ();d4();O1();m0();rJ();async function XY0(J,Z,Q){if(Z.length===0)return;let Y=await g6.getThreadLabels({thread:J},{config:Q});if(!Y.ok){P.error("Failed to get thread labels",{error:Y.error});return}if(Y.result.length>0)return;let X=await g6.setThreadLabels({thread:J,labels:Z},{config:Q});if(!X.ok)P.error("Failed to set thread labels",{error:X.error})}j9();function YR4(J){return{type:"text",text:J.text}}function B23(J){return{type:"tool_use",id:J.id,name:J.name,input:J.input}}function N23(J){let Z="",Q=!1;switch(J.run.status){case"done":Z=typeof J.run.result==="string"?J.run.result:JSON.stringify(J.run.result),Q=!1;break;case"error":Z=typeof J.run.error==="string"?J.run.error:J.run.error?.message||"Tool execution error",Q=!0;break;case"cancelled":Z=`Tool execution cancelled: ${J.run.reason||"Unknown reason"}`,Q=!0;break;case"rejected-by-user":Z=`Tool execution rejected by user: ${J.run.reason||"User declined permission"}`,Q=!0;break;default:Z=`Tool status: ${J.run.status}`,Q=!1}return{type:"tool_result",tool_use_id:J.toolUseID,content:Z,is_error:Q}}function w23(J){return{type:"thinking",thinking:J.thinking}}function L23(J){return{type:"redacted_thinking",data:J.data}}function XR4(J,Z,Q,Y){let X=[],K=Y?.includeThinking??!1;for(let V of J.content)if(V.type==="text")X.push(YR4(V));else if(V.type==="tool_use")X.push(B23(V));else if(K&&V.type==="thinking")X.push(w23(V));else if(K&&V.type==="redacted_thinking")X.push(L23(V));return{type:"assistant",message:{type:"message",role:"assistant",content:X,stop_reason:J.state.type==="complete"?J.state.stopReason:null,usage:J.usage?O23(J.usage):void 0},parent_tool_use_id:Q??null,session_id:Z}}function KR4(J,Z,Q){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(YR4(X));else if(X.type==="tool_result")Y.push(N23(X));return{type:"user",message:{role:"user",content:Y},parent_tool_use_id:Q??null,session_id:Z}}function O23(J){if(!J)return;return{input_tokens:J.inputTokens||0,cache_creation_input_tokens:J.cacheCreationInputTokens??void 0,cache_read_input_tokens:J.cacheReadInputTokens??void 0,output_tokens:J.outputTokens||0,max_tokens:J.maxInputTokens,service_tier:"standard"}}var E23=v.object({type:v.literal("text"),text:v.string()}),M23=v.object({type:v.literal("base64"),media_type:v.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),A23=v.object({type:v.literal("image"),source:M23,source_path:v.string().optional()}),j23=v.union([E23,A23]),R23=v.object({role:v.literal("user"),content:v.array(j23)}),VR4=v.object({type:v.literal("user"),message:R23});var zR4=1048576;function C23(J){return J!==void 0}function T23(J){for(let Z of J)if(Z.type==="tool_result"&&!M9(Z.run.status))return!1;return!0}async function Gi(J){let Z=JSON.stringify(J)+`
6022
+ `);return Uj(),J instanceof T1?J.exitCode:1}function QR4(J,Z){let Q=ZR4(J,Z);process.exit(Q)}async function zH(J,Z){let Q=ZR4(J,Z);await VH(),process.exit(Q)}m0();N$();DN();d4();_4();O1();var YY0=(J)=>{let Z=!1;return{install:()=>{if(!Z)process.on("SIGINT",J),process.on("SIGTERM",J),Z=!0},remove:()=>{if(Z)process.off("SIGINT",J),process.off("SIGTERM",J),Z=!1},get installed(){return Z}}};import{once as I23}from"node:events";import{createInterface as P23}from"node:readline";m0();N$();DN();ZQ();d4();O1();m0();rJ();async function XY0(J,Z,Q){if(Z.length===0)return;try{let Y=await g6.getThreadLabels({thread:J},{config:Q});if(!Y.ok){P.error("Failed to get thread labels",{error:Y.error});return}if(Y.result.length>0)return;let X=await g6.setThreadLabels({thread:J,labels:Z},{config:Q});if(!X.ok)P.error("Failed to set thread labels",{error:X.error})}catch(Y){P.error("Failed to label thread",{error:Y})}}j9();function YR4(J){return{type:"text",text:J.text}}function B23(J){return{type:"tool_use",id:J.id,name:J.name,input:J.input}}function N23(J){let Z="",Q=!1;switch(J.run.status){case"done":Z=typeof J.run.result==="string"?J.run.result:JSON.stringify(J.run.result),Q=!1;break;case"error":Z=typeof J.run.error==="string"?J.run.error:J.run.error?.message||"Tool execution error",Q=!0;break;case"cancelled":Z=`Tool execution cancelled: ${J.run.reason||"Unknown reason"}`,Q=!0;break;case"rejected-by-user":Z=`Tool execution rejected by user: ${J.run.reason||"User declined permission"}`,Q=!0;break;default:Z=`Tool status: ${J.run.status}`,Q=!1}return{type:"tool_result",tool_use_id:J.toolUseID,content:Z,is_error:Q}}function w23(J){return{type:"thinking",thinking:J.thinking}}function L23(J){return{type:"redacted_thinking",data:J.data}}function XR4(J,Z,Q,Y){let X=[],K=Y?.includeThinking??!1;for(let V of J.content)if(V.type==="text")X.push(YR4(V));else if(V.type==="tool_use")X.push(B23(V));else if(K&&V.type==="thinking")X.push(w23(V));else if(K&&V.type==="redacted_thinking")X.push(L23(V));return{type:"assistant",message:{type:"message",role:"assistant",content:X,stop_reason:J.state.type==="complete"?J.state.stopReason:null,usage:J.usage?O23(J.usage):void 0},parent_tool_use_id:Q??null,session_id:Z}}function KR4(J,Z,Q){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(YR4(X));else if(X.type==="tool_result")Y.push(N23(X));return{type:"user",message:{role:"user",content:Y},parent_tool_use_id:Q??null,session_id:Z}}function O23(J){if(!J)return;return{input_tokens:J.inputTokens||0,cache_creation_input_tokens:J.cacheCreationInputTokens??void 0,cache_read_input_tokens:J.cacheReadInputTokens??void 0,output_tokens:J.outputTokens||0,max_tokens:J.maxInputTokens,service_tier:"standard"}}var E23=v.object({type:v.literal("text"),text:v.string()}),M23=v.object({type:v.literal("base64"),media_type:v.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),A23=v.object({type:v.literal("image"),source:M23,source_path:v.string().optional()}),j23=v.union([E23,A23]),R23=v.object({role:v.literal("user"),content:v.array(j23)}),VR4=v.object({type:v.literal("user"),message:R23});var zR4=1048576;function C23(J){return J!==void 0}function T23(J){for(let Z of J)if(Z.type==="tool_result"&&!M9(Z.run.status))return!1;return!0}async function Gi(J){let Z=JSON.stringify(J)+`
6023
6023
  `;try{if(!process.stdout.write(Z))await I23(process.stdout,"drain")}catch(Q){throw P.error("Failed to emit JSON message",{error:Q,messageType:J.type}),Q}}function ok(J,Z){let Q;if(J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"){if(Q=Error(J.message),"stack"in J&&typeof J.stack==="string")Q.stack=J.stack}else if(J instanceof Error)Q=J;if(Q&&(VS(Q)||MF(Q)||gM(Q)||mM(Q)||KS(Q))){let Y=xS(Q,{freeTierEnabled:!1});return Y.description?`${Y.title} ${Y.description}`:Y.title}if(Q)return Q.message;return String(J)}function GR4(J){return J.filter((Z)=>Z.role==="assistant"&&Z.state.type!=="streaming").length}function _23(J){switch(J.role){case"user":return T23(J.content)?0:2;case"assistant":return J.state.type!=="streaming"?0:2;default:return 1}}async function FR4({handle:J,threadID:Z,initialThread:Q,userInput:Y,stdinInput:X,dependencies:K,streamJsonInput:V=!1,streamJsonThinking:z=!1,stdin:G=process.stdin,ampURL:F="https://ampcode.com",isDogfooding:q=!1,agentMode:W,labels:U}){let H=Q??await j1(J.thread$.pipe(lJ(1),cJ(5000))),D=W??H.agentMode??"smart";if(N8(D)&&!q)throw new T1(`Stream JSON mode is not permitted with '${D}' mode.`,1);let B=Z,N=Date.now(),w=0,L=!1,O=H,E=null;if(X&&X.length>zR4)throw Error(`Stdin input too large: ${X.length} bytes (max ${zR4})`);let M,j=YY0(()=>{if(!L)M("User cancelled (SIGINT/SIGTERM)")});try{j.install();let _=(await j1(K.toolService.getTools(D).pipe(lJ(1),cJ(5000)))).map((c)=>c.spec.name),T=[];try{T=(await j1(K.mcpService.servers.pipe(lJ(1),cJ(5000)))).map((a)=>({name:a.name,status:a.status.type}))}catch(c){P.warn("Unable to obtain MCP server list for system init message",{err:c})}let u={type:"system",subtype:"init",cwd:process.cwd(),session_id:B,tools:_,mcp_servers:T};await Gi(u);let m=GR4(H.messages),y=H.messages.length,k=new WeakSet,f=[],d=!V,p=!1,h=[],n=async(c)=>{while(y<c.messages.length){let a=c.messages[y],W0=_23(a);if(W0===1){y++;continue}if(W0===2)break;if(!k.has(a)){if(a.role==="user")await Gi(KR4(a,B,a.parentToolUseId??null));else if(a.role==="assistant"){if(a.content.length>0){let r=XR4(a,B,a.parentToolUseId??null,{includeThinking:z});await Gi(r)}w++}k.add(a)}y++}};return new Promise((c,a)=>{M=async(z0)=>{if(L){P.debug("Complete called multiple times, ignoring",{error:z0});return}L=!0,j.remove();try{try{let J0=await j1(J.thread$.pipe(lJ(1),cJ(1000)));O=J0,await n(J0)}catch(J0){P.debug("Unable to flush pending thread messages before completion",{error:J0})}if(z0){let J0={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-N,is_error:!0,num_turns:w,error:z0,session_id:B};await Gi(J0)}else{let J0=O?A9(O,"assistant"):null,G0=J0?d3(J0.content):"",i={type:"result",subtype:"success",duration_ms:Date.now()-N,is_error:!1,num_turns:w,result:G0,session_id:B};await Gi(i)}if(W0.unsubscribe(),r.unsubscribe(),f.forEach((J0)=>J0.unsubscribe()),await J.postExecuteMode?.(),U&&U.length>0)await XY0(Z,U,K.configService);c()}catch(J0){P.error("Error during completion",{error:J0}),a(J0)}};let W0=J.threadViewState$.subscribe(async(z0)=>{try{if(E=z0,z0.state==="active"&&z0.ephemeralError){await M(ok(z0.ephemeralError,F));return}if(h.length>0){let J0=[...new Set(h.map((i)=>i.toolName))],G0=J0.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J0.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";await M(G0);return}if(z0.state==="active"&&z0.inferenceState==="idle"&&O){let J0=O.messages.flatMap((G0)=>G0.content.map((i)=>{if(i.type==="tool_result"&&i.run.status==="blocked-on-user")return pJ(O,i.toolUseID)}).filter(C23));if(J0.length>0){P.warn("Tools require user consent - exiting stream JSON mode",{blockedTools:J0.map((o)=>({name:o.name,id:o.id}))});let i=`The following tools require user approval, which is not supported in stream JSON mode: ${J0.map((o)=>o.name).join(", ")}`;await M(i);return}}if(d&&p&&z0.state==="active"&&z0.inferenceState==="idle")await M()}catch(J0){P.error("Error in status subscription",{error:J0}),await M(ok(J0,F))}}),r=J.thread$.subscribe(async(z0)=>{try{O=z0,await n(z0);let J0=GR4(z0.messages),G0=A9(z0,"assistant");if(p=J0>m&&G0!==void 0&&G0.state.type!=="streaming"&&r00(G0)&&!G0.content.some((i)=>i.type==="tool_use"),d&&p&&E?.state==="active"&&E.inferenceState==="idle")await M()}catch(J0){P.error("Error in thread subscription",{error:J0}),await M(ok(J0,F))}}),H0=J.pendingApprovals$.subscribe((z0)=>{if(h=z0,z0.length>0){let J0=[...new Set(z0.map((i)=>i.toolName))],G0=J0.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J0.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";M(G0)}});f.push(H0);let L0=J.inferenceErrors$?.subscribe((z0)=>{M(ok(z0,F))});if(L0)f.push(L0);if(V)(async()=>{try{for await(let z0 of S23(G)){if(L)break;await J.sendMessage({content:z0.contentBlocks,agentMode:D})}if(d=!0,p&&E?.state==="active"&&E.inferenceState==="idle")await M()}catch(z0){P.error("Error processing streaming input",{error:z0}),await M(ok(z0,F))}})();else(async()=>{try{let z0=[{type:"text",text:Y}];if(X)z0.unshift({type:"text",text:`Input received on stdin:
6024
6024
  \`\`\`
6025
6025
  ${X}
@@ -6085,7 +6085,7 @@ password=${K}
6085
6085
  `).length-1});throw new T1(`Invalid JSON in settings file ${Z}`,1,`Fix the JSON syntax errors. Errors found on lines [${R.join(", ")}].`)}P.debug("readSettings",{settingsPath:Z,rawConfig:A});let j={};for(let[R,_]of Object.entries(A))if(R.startsWith("amp.")){let T=R.substring(4);j[T]=_}return z=j,j}catch(E){if(E.code==="ENOENT")return z={},z;throw P.error(`Failed to read settings: ${E}`),E}}async function D(O){await TY0.acquire();try{await U(),await Oi(Z,(E)=>{let M=E;for(let[A,j]of Object.entries(O)){let R=Fj0(M,[`amp.${A}`],j,{formattingOptions:{tabSize:2,insertSpaces:!0}});if(R.length>0)M=qj0(M,R)}return{newContent:M}},{mode:384}),z=O}catch(E){throw P.error(`Failed to write settings: ${E}`),E}finally{TY0.release()}}function B(){if(q)return;if(process.versions.bun){try{W=Y(Z,(O,E)=>{P.debug("Settings file change detected (fallback watcher)",{settingsPath:Z,curr:O,prev:E}),N()}),q=!0,P.debug("Started watching settings file with fallback watcher (Bun)",{settingsPath:Z})}catch(O){P.error("Failed to start fallback file watcher",{settingsPath:Z,error:O})}return}try{let O=cY.dirname(Z),E=cY.basename(Z);G=Q(O,(M,A)=>{if(A!==E)return;P.debug("Settings file change detected",{eventType:M,filename:A,settingsPath:Z}),N()}),G.on("error",(M)=>{P.debug("transient file watcher error",{error:M}),N()}),P.debug("Started watching settings directory",{dir:O,targetFilename:E})}catch(O){if(O.code==="ENOENT"){if(!W)W=Y(Z,(E,M)=>{if(E.ino===0)return;P.debug("Settings file created, starting file watcher",{settingsPath:Z}),B(),W?.close(),W=void 0})}else P.warn("Failed to start watching settings directory",{settingsPath:Z,error:O})}q=!0}function N(){if(F)clearTimeout(F);F=setTimeout(w,X)}async function w(){try{let O=z;z=void 0,await new Promise((A)=>setTimeout(A,K));let E=await H(!0),M=qI4(O,E);if(M.length>0)z=void 0,V.next(M),P.info("Settings reloaded",{changedKeys:M})}catch(O){P.warn("Failed to handle settings file change",{settingsPath:Z,error:O})}}function L(){if(G)G.close(),G=void 0;if(W)W.close(),W=void 0;if(F)clearTimeout(F),F=void 0;q=!1,P.debug("Stopped watching settings directory",{settingsPath:Z})}return{async get(O){return(await H())[O]},async set(O,E,M){let A=await H();A[O]=E,await D(A),V.next([O])},async delete(O,E){await TY0.acquire();try{await Oi(Z,(A)=>{let j=`amp.${O}`,R=Fj0(A,[j],void 0,{formattingOptions:{tabSize:2,insertSpaces:!0}});return{newContent:R.length>0?qj0(A,R):A}},{mode:384});let M=await H();delete M[O],z=M,V.next([O])}catch(M){throw P.error(`Failed to delete setting: ${M}`),M}finally{TY0.release()}},async keys(){let O=await H();return Object.keys(O)},getSettingsFilePath(){return Z},changes:V,[Symbol.dispose](){L()}}}async function qJ3(J){let Z=await FI4(J.settingsFile??yK,yK),Q=await WI4({...J,settingsFile:Z});return{...Q,async set(Y,X){return Zv(Y,"global"),Q.set(Y,X)},async delete(Y){return Zv(Y,"global"),Q.delete(Y)}}}async function WJ3(J){let{workspaceRootPath:Z,workspaceSettingsPath:Q}=await zJ3(J.cwd),Y=await WI4({...J,settingsFile:Q}),X=new Y4,K=Y.changes.subscribe((G)=>X.next(G)),V=J.workspaceTrust?.current??!1,z=J.workspaceTrust?.changes?.subscribe(async(G)=>{let F=V;if(V=G,!F&&G){let W=(await Y.keys()).filter((U)=>L10.includes(U));if(W.length>0)X.next(W)}});return{...Y,changes:X,getWorkspaceRootPath(){return Z},async get(G){if(!V&&L10.includes(G))return;return Y.get(G)},async set(G,F){return Zv(G,"workspace"),Y.set(G,F)},async delete(G){return Zv(G,"workspace"),Y.delete(G)},async keys(){let G=await Y.keys();if(!V)return G.filter((F)=>!L10.includes(F));return G},[Symbol.dispose](){K.unsubscribe(),z?.unsubscribe(),Y[Symbol.dispose]()}}}async function UI4(J){let Z=J.getHook,Q=new Y4,Y=await qJ3(J),X=await WJ3({...J,cwd:J.cwd||process.cwd()});P.info("Using settings file",{settingsPath:Y.getSettingsFilePath(),workspaceSettingsPath:X.getSettingsFilePath(),workspaceRootPath:X.getWorkspaceRootPath()});let K=Y.changes.subscribe((z)=>Q.next(z)),V=X.changes.subscribe((z)=>Q.next(z));return{async get(z,G){let F=async()=>{switch(G){case"global":return Y.get(z);case"workspace":return X.get(z);case"admin":throw Error("Cannot get admin settings from file storage");case void 0:break}let[q,W]=await Promise.all([Y.get(z),X.get(z)]);return VI4(z,{global:q,workspace:W})};return Z?Z(z,F):F()},async set(z,G,F="workspace"){switch(Zv(z,F),F){case"workspace":await X.set(z,G);break;case"global":await Y.set(z,G);break;default:}Q.next([z])},async delete(z,G="workspace"){switch(Zv(z,G),G){case"workspace":await X.delete(z);break;case"global":await Y.delete(z);break;default:}Q.next([z])},async keys(){let z=await Y.keys(),G=await X.keys(),F=new Set([...z,...G]);return Array.from(F)},getSettingsFilePath(){return Y.getSettingsFilePath()},getWorkspaceRootPath(){return X.getWorkspaceRootPath()},getWorkspaceSettingsPath(){return X.getSettingsFilePath()},changes:Q,[Symbol.dispose](){K.unsubscribe(),V.unsubscribe(),Y[Symbol.dispose](),X[Symbol.dispose]()}}}m0();IX();import UJ3,{promises as _Y0}from"node:fs";import HJ3 from"node:path";import{stderr as HI4,stdout as DJ3}from"node:process";O1();var BJ3="secrets.json";function DI4(J){return HJ3.join(J.dataDir,BJ3)}function BI4(J){let Z=new CG(P).scoped("secrets.file"),Q=new Y4,Y,X=DI4(J),K=new yY;async function V(){try{await _Y0.mkdir(J.dataDir,{recursive:!0})}catch(F){throw Z.error(`Failed to create data directory: ${F}`),F}}async function z(){if(Y)return Y;try{await V();let F=await _Y0.readFile(X,"utf-8");return Y=JSON.parse(F),Y}catch(F){if(F.code==="ENOENT")return Y={},Y;throw Z.error("Failed to read secrets",{secretsPath:X,error:F}),F}}async function G(F){await K.acquire();try{await V(),await Oi(X,()=>({newContent:JSON.stringify(F,null,2)}),{mode:384}),Y=F}catch(q){throw Z.error("Failed to write secrets",{secretsPath:X,error:q}),q}finally{K.release()}}return{async get(F,q){let W=await z(),U=bP(q);return W[`${F}@${U}`]},async set(F,q,W){let U=bP(W),H=`${F}@${U}`,D=await z();D[H]=q,await G(D),Q.next(H)},changes:Q}}async function NI4(J,Z){let Q=new CG(P).scoped("secrets.file.migrate"),Y=DI4(J);if(!UJ3.existsSync(Y))return;let X=await _Y0.readFile(Y,"utf-8"),K=JSON.parse(X);if(Object.keys(K).length===0)return;if(!J.quiet)DJ3.write(`Migrating secrets from file storage to native secret storage...
6086
6086
  `);let V=[];for(let[z,G]of Object.entries(K))if(typeof G==="string"){let F=z.match(/^(.+)@(.+)$/);if(F){let[,q,W]=F;if(q&&W)try{await Z.set(q,G,W),V.push(z),Q.debug(`Successfully migrated secret: ${z}`)}catch(U){throw HI4.write(`Failed to migrate secret ${z} to native secret storage
6087
6087
  `),U}}}if(V.length>0)try{await _Y0.rm(Y),Q.info("Successfully migrated secrets and removed file storage",{migratedKeys:V,removed:Y})}catch(z){throw HI4.write(`Failed to remove file storage after migration
6088
- `),z}}m0();IX();O1();function NJ3(J){return typeof J==="function"}async function wJ3(){let J=Reflect.get(globalThis,"__AMP_KEYRING_ENTRY_CLASS__");if(NJ3(J))return J;return(await import("@napi-rs/keyring")).Entry}async function wI4(){let J=new CG(P).scoped("secrets.native"),Z=new Y4,Q={},Y=await wJ3();async function X(K,V){let z;try{z=new URL(V).hostname}catch{z=V}return new Y(`amp.cli.${K}`,z)}return{async get(K,V){let z=bP(V),G=`${K}@${z}`;if(G in Q)return Q[G];let F=await X(K,z);try{let W=F.getPassword()||void 0;return Q[G]=W,W}catch(q){J.warn("failed to get secret",{name:K,url:V,error:q}),Q[G]=void 0;return}},async set(K,V,z){let G=bP(z),F=await X(K,G);if(V)F.setPassword(V);else F.deleteCredential();let q=`${K}@${G}`;Q[q]=V,Z.next(q)},changes:Z}}async function Ea0(J,Z){let Q={dataDir:J.dataDir||Qv};if(!await Z.get("experimental.cli.nativeSecretsStorage.enabled","global"))return P.info("using file-based secrets storage",Q),BI4(Q);P.info("using native secrets storage");let Y;try{Y=await wI4()}catch(X){throw P.error("failed to initialize native secrets storage",{error:X,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await NI4(Q,Y),Y}async function LI4(J){return UI4(J)}var OI4={"agent.deepReasoningEffort":{value:"high",visible:!0,description:"Default reasoning effort for new deep-mode threads (medium, high, xhigh)."},"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.effort":{value:"high",visible:!1,description:"Effort level for Anthropic models that support auto-thinking (low, medium, high, max). Higher effort means more thinking and better performance."},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.speed":{value:void 0,visible:!1,description:"Fast speed toggle for smart mode (Anthropic fast mode)"},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable system sound notifications when agent completes tasks"},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.commands.nodeSpawn.loadProfile":{value:"daily",visible:!1,description:"How often to load shell profile in node-spawn mode (always, daily, never)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},"windowsPasteHook.enabled":{value:!0,visible:!0,description:"Enable the Windows Ctrl+V clipboard hook integration for reliable text and image paste."},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},LJ3=Object.fromEntries(Object.entries(OI4).filter(([,J])=>J.visible).map(([J,Z])=>[`amp.${J}`,Z.value])),Mi={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
6088
+ `),z}}m0();IX();O1();function NJ3(J){return typeof J==="function"}async function wJ3(){let J=Reflect.get(globalThis,"__AMP_KEYRING_ENTRY_CLASS__");if(NJ3(J))return J;return(await import("@napi-rs/keyring")).Entry}async function wI4(){let J=new CG(P).scoped("secrets.native"),Z=new Y4,Q={},Y=await wJ3();async function X(K,V){let z;try{z=new URL(V).hostname}catch{z=V}return new Y(`amp.cli.${K}`,z)}return{async get(K,V){let z=bP(V),G=`${K}@${z}`;if(G in Q)return Q[G];let F=await X(K,z);try{let W=F.getPassword()||void 0;return Q[G]=W,W}catch(q){J.warn("failed to get secret",{name:K,url:V,error:q}),Q[G]=void 0;return}},async set(K,V,z){let G=bP(z),F=await X(K,G);if(V)F.setPassword(V);else F.deleteCredential();let q=`${K}@${G}`;Q[q]=V,Z.next(q)},changes:Z}}async function Ea0(J,Z){let Q={dataDir:J.dataDir||Qv};if(!await Z.get("experimental.cli.nativeSecretsStorage.enabled","global"))return P.info("using file-based secrets storage",Q),BI4(Q);P.info("using native secrets storage");let Y;try{Y=await wI4()}catch(X){throw P.error("failed to initialize native secrets storage",{error:X,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await NI4(Q,Y),Y}async function LI4(J){return UI4(J)}var OI4={"agent.deepReasoningEffort":{value:"high",visible:!0,description:"Default reasoning effort for new deep-mode threads (medium, high, xhigh)."},"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.effort":{value:"high",visible:!1,description:"Effort level for Anthropic models that support auto-thinking (low, medium, high, max). Higher effort means more thinking and better performance."},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.speed":{value:void 0,visible:!1,description:"Fast speed toggle for smart mode (Anthropic fast mode)"},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable system sound notifications when agent completes tasks"},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.commands.nodeSpawn.loadProfile":{value:"daily",visible:!1,description:"How often to load shell profile in node-spawn mode (always, daily, never)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},"windowsPasteHook.enabled":{value:!1,visible:!0,description:"Enable the Windows Ctrl+V clipboard hook integration for reliable text and image paste."},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},LJ3=Object.fromEntries(Object.entries(OI4).filter(([,J])=>J.visible).map(([J,Z])=>[`amp.${J}`,Z.value])),Mi={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
6089
6089
 
6090
6090
  - README.md (root)
6091
6091
  - AGENT.md (root)
@@ -6196,11 +6196,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
6196
6196
  ${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
6197
6197
 
6198
6198
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6199
- npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function fY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=NP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pZ3="https://static.ampcode.com/cli/cli-version.txt";async function uY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=NP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dZ3=604800000;function BP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>dZ3)return{ageMs:Q};return null}function NP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await $F(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await xY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await uY0(J):await fY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await $F(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Uq}from"node:process";function wP4(J){let Z=new fN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await _a0(Y.force||!1,Y.verbose||!1,"0.0.1774866438-g7cb400"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new fN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await cZ3(Y.targetVersion)});J.addCommand(Q)}async function cZ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Uq.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6199
+ npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function fY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=NP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pZ3="https://static.ampcode.com/cli/cli-version.txt";async function uY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=NP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dZ3=604800000;function BP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>dZ3)return{ageMs:Q};return null}function NP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await $F(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await xY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await uY0(J):await fY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await $F(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Uq}from"node:process";function wP4(J){let Z=new fN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await _a0(Y.force||!1,Y.verbose||!1,"0.0.1774873738-gc73620"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new fN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await cZ3(Y.targetVersion)});J.addCommand(Q)}async function cZ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Uq.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6200
6200
 
6201
6201
  `));try{if(!J){Uq.write(o0.blue(`Checking for updates...
6202
- `));let{hasUpdate:Y,latestVersion:X}=ka0()?await uY0("0.0.1774866438-g7cb400"):await fY0("0.0.1774866438-g7cb400",Oj());if(!Y){let K=ma0("0.0.1774866438-g7cb400"),V=K?.age?`released ${K.age} ago`:`built ${EF(new Date("2026-03-30T10:31:14.209Z"))} ago`;Uq.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774866438-g7cb400"} (${V})
6203
- `));let z=await Nw("0.0.1774866438-g7cb400");if(z.warning)Uq.write(`
6202
+ `));let{hasUpdate:Y,latestVersion:X}=ka0()?await uY0("0.0.1774873738-gc73620"):await fY0("0.0.1774873738-gc73620",Oj());if(!Y){let K=ma0("0.0.1774873738-gc73620"),V=K?.age?`released ${K.age} ago`:`built ${EF(new Date("2026-03-30T12:32:50.624Z"))} ago`;Uq.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774873738-gc73620"} (${V})
6203
+ `));let z=await Nw("0.0.1774873738-gc73620");if(z.warning)Uq.write(`
6204
6204
  `+o0.yellow(z.warning)+`
6205
6205
  `);process.exit(0)}if(!X)Uq.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Uq.write(o0.blue(`Updating to version ${J}...
6206
6206
  `)),await Ti(J,void 0,(Y)=>{Uq.write(o0.dim(`Running: ${Y}
@@ -6675,7 +6675,7 @@ Or install from GitHub: amp skill add <owner/repo>
6675
6675
  `)}}finally{await V.asyncDispose(),process.exit(0)}});return Q}m0();import{fstatSync as AV3,readlinkSync as jV3}from"node:fs";class LX0 extends Error{cause;constructor(J,Z){super(J);this.cause=Z;this.name="StdinReadError"}}async function RV3(J={}){let{maxSizeBytes:Z=1048576,timeoutMs:Q=30000}=J;if(process.stdin.isTTY)return{content:"",truncated:!1,timedOut:!1,bytesRead:0};try{if(AV3(process.stdin.fd).isCharacterDevice()){let X=`/proc/self/fd/${process.stdin.fd}`;try{let K=jV3(X);if(K==="/dev/zero")return P.warn("Detected /dev/zero input, returning empty content to avoid infinite read"),{content:"",truncated:!1,timedOut:!1,bytesRead:0};if(K==="/dev/random"||K==="/dev/urandom")throw new LX0(`Refusing to read from special device: ${K}. This would cause infinite data consumption.`)}catch{}}}catch{}return new Promise((Y,X)=>{let K="",V=0,z=!1,G=!1,F=null,q=()=>{if(F)clearTimeout(F),F=null;process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),process.stdin.removeAllListeners("error")},W=()=>{q(),Y({content:K,truncated:z,timedOut:G,bytesRead:V})};F=setTimeout(()=>{G=!0,W()},Q),process.stdin.once("error",(U)=>{q(),X(new LX0("Failed to read from stdin",U))}),process.stdin.once("end",()=>{W()}),process.stdin.on("data",(U)=>{let H=U.length;if(V+H>Z){let D=Z-V;if(D>0)K+=U.subarray(0,D).toString("utf8"),V=Z;z=!0,W();return}K+=U.toString("utf8"),V+=H}),process.stdin.resume()})}async function Bv(){let J=await RV3();if(J.timedOut)throw new LX0("Timeout while reading from stdin");if(J.truncated)P.warn(`Warning: stdin input was truncated at ${J.bytesRead} bytes`);return J.content}RT0();m0();O$();$J();function Po0(J){let Z={},Q={};for(let Y in J){if(!Object.hasOwn(J,Y))continue;let X=J[Y];switch(typeof X){case"number":Z[Y]=X;break;case"boolean":Z[Y]=X?1:0;break;case"object":{if(X===null||X===void 0){Q[Y]=X;break}let{metadata:K}=Po0(X);for(let[V,z]of Object.entries(K))Z[`${Y}.${V}`]=z;Q[Y]=X;break}default:Q[Y]=X}}return{metadata:Z,sensitiveMetadata:Q}}function Co0(J,Z){let{metadata:Q,sensitiveMetadata:Y}=Po0(J.metadata||{}),X=JE().version;return{feature:J.feature,action:J.action,timestamp:Date.now()*1000,source:{client:Z,...X&&{clientVersion:X}},parameters:{...Object.keys(Q).length>0&&{metadata:Q},...Object.keys(Y).length>0&&{sensitiveMetadata:Y}}}}var IV3="Failed to submit telemetry: Telemetry service not configured";function PV3(J){return!1}class To0{configService;constructor(J){this.configService=J}recordEvent(J){let Z=Co0(J,"cli"),Q=JSON.stringify([Z]);H40(Q,this.configService).catch((Y)=>{if(PV3(Y))return;P.error("Failed to send telemetry",{error:Y,feature:J.feature,action:J.action})})}}var jT4=!1;function RT4(J){if(jT4)return;let Z=new To0(J);bn1(Z),jT4=!0}import{spawn as Wz3}from"node:child_process";m0();m0();import{execSync as PT4}from"node:child_process";function _o0(){let J=CV3();if(J)return J;let Z=TV3();if(Z)return{...Z,pixelWidth:0,pixelHeight:0};return null}function CV3(){try{let J=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Z=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),Y=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Z)({ws_row:Z.types.ushort,ws_col:Z.types.ushort,ws_xpixel:Z.types.ushort,ws_ypixel:Z.types.ushort}),X=J.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),K=process.platform==="darwin"?1074295912:21523,V=new Y;if(X.ioctl(process.stdout.fd,K,V.ref())===0)return{rows:V.ws_row,columns:V.ws_col,pixelWidth:V.ws_xpixel,pixelHeight:V.ws_ypixel};return null}catch(J){return null}}function TV3(){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 Z=process.stdout;if(typeof Z.getWindowSize==="function"){let Q=Z.getWindowSize();if(Q[0]>0&&Q[1]>0)return{columns:Q[0],rows:Q[1]}}return null}catch(J){return null}}import{exec as _V3,execSync as SV3}from"node:child_process";function NH(){if(process.env.TMUX||process.env.TMUX_PANE)return!0;return process.env.TERM?.toLowerCase()?.includes("tmux")??!1}var So0=!1;if(process.env.TMUX)_V3("tmux show-options -g extended-keys 2>/dev/null",{timeout:1000},(J,Z)=>{if(!J&&Z.trim()==="extended-keys on")So0=!0});function IT4(){if(!NH())return!1;try{return SV3('tmux display-message -p "#{pane_active}"',{timeout:500,encoding:"utf8"}).trim()!=="1"}catch{return!1}}function wH(J){if(!NH())return J;return`\x1BPtmux;${J.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`}function ii(J){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:a7()?"none":"standard",scrollStep:()=>3,...J}}var CT4=[{sequence:"\x1B[?1049h\x1B[H\x1B]66;w=1; \x1B\\\x1B[6n\x1B[?1049l",description:"Query Kitty explicit width support"},{sequence:"\x1B]10;?\x07",description:"Query terminal foreground color (OSC 10)"},{sequence:"\x1B]11;?\x07",description:"Query terminal background color (OSC 11)"},{sequence:"\x1B]12;?\x07",description:"Query terminal cursor color (OSC 12)"},{sequence:"\x1B]4;0;?\x07",description:"Query terminal color 0 (OSC 4)"},{sequence:"\x1B]4;1;?\x07",description:"Query terminal color 1 (OSC 4)"},{sequence:"\x1B]4;2;?\x07",description:"Query terminal color 2 (OSC 4)"},{sequence:"\x1B]4;3;?\x07",description:"Query terminal color 3 (OSC 4)"},{sequence:"\x1B]4;4;?\x07",description:"Query terminal color 4 (OSC 4)"},{sequence:"\x1B]4;5;?\x07",description:"Query terminal color 5 (OSC 4)"},{sequence:"\x1B]4;6;?\x07",description:"Query terminal color 6 (OSC 4)"},{sequence:"\x1B]4;7;?\x07",description:"Query terminal color 7 (OSC 4)"},{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[?2031$p",description:"Query color palette change notifications support (mode 2031)"},{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:wH("\x1B_Gi=1,a=q\x1B\\"),description:"Query Kitty graphics protocol support",shouldSend:()=>!a7()&&process.env.TERM_PROGRAM!=="Apple_Terminal"},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];class OX0{options;capabilities;constructor(J={}){this.options=J;this.capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,kittyGraphics:this.detectKittyGraphicsFromEnv(),background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:a7()?"none":"standard",scrollStep:()=>this.getScrollStep()}}complete=!1;colorUpdateTimer=null;onColorPaletteChange;inbandPixelData=null;kittyWidthQuerySent=!1;rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]};processDecrqss(J,Z){if(J==="?2026")this.capabilities.syncOutput=Z==="1"||Z==="2";if(J==="?2027")this.capabilities.emojiWidth=Z==="1"||Z==="2";if(J==="?1016")this.capabilities.pixelMouse=Z==="1"||Z==="2";if(J==="?2031")this.capabilities.colorPaletteNotifications=Z==="1"||Z==="2";if(J==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(J,Z){if(this.checkPixelDimensions(),this.detectJetBrains()||this.detectTmux())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(J){this.capabilities.xtversion=J;let Z=["ghostty","kitty","wezterm","foot","alacritty","iterm2","tmux"],Q=J.toLowerCase();if(Z.some((Y)=>Q.includes(Y)))this.capabilities.osc52=!0;return!1}processXtgettcap(J,Z){if(J.toLowerCase()==="4d73")this.capabilities.osc52=Z.length>0;return!1}processKittyGraphics(){if(this.isITerm2())return this.capabilities.kittyGraphics=!1,!1;return this.capabilities.kittyGraphics=!0,!1}processCursorPositionReport(J,Z){if(this.kittyWidthQuerySent){if(J===1&&Z===2)this.capabilities.kittyExplicitWidth=!0,P.info("Kitty explicit width support detected");this.kittyWidthQuerySent=!1}return!1}markKittyWidthQuerySent(){this.kittyWidthQuerySent=!0}processOsc10(J){let Z=J.match(/^10;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Z||!Z[1]||!Z[2]||!Z[3])return!1;let Q=Z[1],Y=Z[2],X=Z[3],K=(F)=>{let q=Number.parseInt(F,16),W=F.length*4;return q/(2**W-1)*255},V=Math.round(K(Q)),z=Math.round(K(Y)),G=Math.round(K(X));return this.rgbColors.foreground={r:V,g:z,b:G},!1}processOsc11(J){let Z=J.match(/^11;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Z||!Z[1]||!Z[2]||!Z[3])return!1;let Q=Z[1],Y=Z[2],X=Z[3],K=(q)=>{let W=Number.parseInt(q,16),U=q.length*4;return W/(2**U-1)*255},V=Math.round(K(Q)),z=Math.round(K(Y)),G=Math.round(K(X));this.rgbColors.background={r:V,g:z,b:G};let F=0.299*V+0.587*z+0.114*G;return this.capabilities.background=F<128?"dark":"light",!1}processOsc12(J){let Z=J.match(/^12;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Z||!Z[1]||!Z[2]||!Z[3])return!1;let Q=Z[1],Y=Z[2],X=Z[3],K=(F)=>{let q=Number.parseInt(F,16),W=F.length*4;return q/(2**W-1)*255},V=Math.round(K(Q)),z=Math.round(K(Y)),G=Math.round(K(X));return this.rgbColors.cursor={r:V,g:z,b:G},!1}processOsc4(J){let Z=J.match(/^4;(\d+);rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Z||!Z[1]||!Z[2]||!Z[3]||!Z[4])return!1;let Q=Number.parseInt(Z[1],10),Y=Z[2],X=Z[3],K=Z[4],V=(q)=>{let W=Number.parseInt(q,16),U=q.length*4;return W/(2**U-1)*255},z=Math.round(V(Y)),G=Math.round(V(X)),F=Math.round(V(K));if(Q>=0&&Q<=7)this.rgbColors.indices[Q]={r:z,g:G,b:F};return!1}setColorPaletteChangeCallback(J){this.onColorPaletteChange=J}handleColorPaletteChangeNotification(){if(P.info("Color palette changed, re-querying colors..."),this.rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]},this.colorUpdateTimer)clearTimeout(this.colorUpdateTimer);this.colorUpdateTimer=setTimeout(()=>{let J=this.getRgbColors();if(this.onColorPaletteChange&&J)P.info("Color re-query complete, notifying callback"),this.onColorPaletteChange();this.colorUpdateTimer=null},200)}getColorQuerySequences(){return["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]4;0;?\x07","\x1B]4;1;?\x07","\x1B]4;2;?\x07","\x1B]4;3;?\x07","\x1B]4;4;?\x07","\x1B]4;5;?\x07","\x1B]4;6;?\x07","\x1B]4;7;?\x07"]}updateInbandPixelData(J,Z,Q,Y){if(Q&&Y&&Q>0&&Y>0)this.inbandPixelData={pixelWidth:Q,pixelHeight:Y,columns:J,rows:Z},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let J=_o0();this.capabilities.pixelDimensions=!!(J&&J.pixelWidth>0&&J.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}getRgbColors(){if(!this.rgbColors.foreground||!this.rgbColors.background||!this.rgbColors.cursor)return P.info("Missing fg, bg, or cursor color",{fg:!!this.rgbColors.foreground,bg:!!this.rgbColors.background,cursor:!!this.rgbColors.cursor}),null;for(let J=0;J<8;J++)if(!this.rgbColors.indices[J])return P.info(`Missing palette color ${J}`),null;return P.info("All RGB colors available",{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indicesCount:this.rgbColors.indices.filter((J)=>J!==null).length}),{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indices:this.rgbColors.indices}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let J=_o0();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"]}detectKittyGraphicsFromEnv(){let J=["kitty","ghostty","wezterm"];if(NH())try{let Z="",Q="";try{Z=PT4("tmux show-environment -g TERM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM=/,"").toLowerCase()}catch{}try{Q=PT4("tmux show-environment -g TERM_PROGRAM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM_PROGRAM=/,"").toLowerCase()}catch{}for(let Y of J)if(Z.includes(Y)||Q.includes(Y))return P.debug("Detected Kitty graphics support from tmux environment",{term:Z,termProgram:Q}),!0}catch{}return!1}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.options.animationDisabled)return"disabled";if(process.env.NO_ANIMATION==="1"||process.env.NO_ANIMATIONS==="1")return"disabled";if(this.detectEmacs()||this.detectSSH())return"disabled";if(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)}detectTmux(){return!!process.env.TMUX}isITerm2(){if(this.capabilities.xtversion?.toLowerCase().includes("iterm2"))return!0;return process.env.TERM_PROGRAM==="iTerm.app"}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(a7())return 1;return 3}}m0();import{execFile as Pj}from"node:child_process";import{existsSync as kV3}from"node:fs";import{platform as EX0}from"node:os";import{promisify as vV3}from"node:util";var ni=vV3(Pj);function TT4(){if(EX0()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||kV3("/proc/sys/fs/binfmt_misc/WSLInterop")}var yV3=(J)=>`\x1B]52;c;${J}\x1B\\`,xV3="\x1B]52;c;?\x1B\\",fV3="\x1B]52;p;?\x1B\\";class _T4{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;tmuxSetClipboard="unknown";setCapabilities(J){if(this.capabilities=J,NH())this.detectTmuxSetClipboard()}detectTmuxSetClipboard(){Pj("tmux",["show-options","-s","-v","set-clipboard"],{timeout:1000},(J,Z)=>{if(!J){let Q=Z.trim();if(Q==="on"||Q==="external"||Q==="off")this.tmuxSetClipboard=Q}})}isTmuxOsc52Allowed(){return this.tmuxSetClipboard==="on"||this.tmuxSetClipboard==="unknown"}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await ni("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Z=Pj("pbcopy");return Z.stdin?.write(J),Z.stdin?.end(),await new Promise((Q,Y)=>{Z.on("close",(X)=>{if(X===0)Q();else Y(Error(`pbcopy exited with code ${X}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Z=Pj("wl-copy");return Z.stdin?.write(J),Z.stdin?.end(),await new Promise((Q,Y)=>{Z.on("close",(X)=>{if(X===0)Q();else Y(Error(`wl-copy exited with code ${X}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Z=Pj("xclip",["-selection","clipboard"]);return Z.stdin?.write(J),Z.stdin?.end(),await new Promise((Q,Y)=>{Z.on("close",(X)=>{if(X===0)Q();else Y(Error(`xclip exited with code ${X}`))})}),!0}catch{return!1}}async writeToClipExe(J){try{let Z=Pj("clip.exe");return Z.stdin?.write(J),Z.stdin?.end(),await new Promise((Q,Y)=>{Z.on("close",(X)=>{if(X===0)Q();else Y(Error(`clip.exe exited with code ${X}`))})}),!0}catch{return!1}}async writeToPowerShell(J){try{let Z=Pj("powershell.exe",["-NoProfile","-Command","$Input | Set-Clipboard"]);return Z.stdin?.write(J),Z.stdin?.end(),await new Promise((Q,Y)=>{Z.on("close",(X)=>{if(X===0)Q();else Y(Error(`powershell.exe exited with code ${X}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise!==void 0)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(J)});let Z=await this.pendingReadPromise;return this.pendingReadPromise=null,Z}async readFromOSC52(){return this.readFromOSC52WithQuery(xV3)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Z=Buffer.from(J,"base64").toString("utf8");this.readResolve(Z)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await ni("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Z=["--no-newline"];if(J==="primary")Z.push("--primary");let{stdout:Q}=await ni("wl-paste",Z);return Q}catch{return null}}async readFromXclip(J){try{let{stdout:Z}=await ni("xclip",["-selection",J,"-o"]);return Z}catch{return null}}async readFromPowerShell(){try{let{stdout:J}=await ni("powershell.exe",["-NoProfile","-Command","Get-Clipboard"]);return J}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(fV3)}async readText(){if(this.isOsc52Supported()){let Z=await this.readFromOSC52();if(Z!==null)return Z}let J=EX0();if(J==="darwin"){let Z=await this.readFromPbpaste();if(Z!==null)return Z}else if(J==="win32"){let Z=await this.readFromPowerShell();if(Z!==null)return Z}else{if(await this.commandExists("wl-paste")){let Z=await this.readFromWlPaste("clipboard");if(Z!==null)return Z}if(await this.commandExists("xclip")){let Z=await this.readFromXclip("clipboard");if(Z!==null)return Z}if(TT4()){let Z=await this.readFromPowerShell();if(Z!==null)return Z}}return null}async readPrimarySelection(){let J=EX0();if(J==="darwin"||J==="win32")return this.readText();if(this.isOsc52Supported()){let Z=await this.readFromOSC52Primary();if(Z!==null)return Z}if(await this.commandExists("wl-paste")){let Z=await this.readFromWlPaste("primary");if(Z!==null)return Z}if(await this.commandExists("xclip")){let Z=await this.readFromXclip("primary");if(Z!==null)return Z}return null}async writeText(J){let Z=NH(),Q=!1;if(this.isOsc52Supported()&&(!Z||this.isTmuxOsc52Allowed())){let X=Buffer.from(J).toString("base64"),K=yV3(X);if(process.stdout.write(K),Q=!0,!Z)return!0}let Y=EX0();if(Y==="darwin"){if(await this.writeToPbcopy(J))return!0}else if(Y==="win32"){if(await this.writeToPowerShell(J))return!0;if(await this.writeToClipExe(J))return!0}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return!0;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return!0;if(TT4()){if(await this.writeToPowerShell(J))return!0}}if(Q)return!0;return!1}}var yz=new _T4;function uV3(J){let Z=(J&4)!==0,Q=(J&8)!==0,Y=(J&16)!==0,X=(J&32)!==0,K=J&-61,V="unknown";switch(K){case 0:V="left";break;case 1:V="middle";break;case 2:V="right";break;case 64:V="wheel_up";break;case 65:V="wheel_down";break;case 66:V="wheel_left";break;case 67:V="wheel_right";break;default:V="unknown";break}return{button:V,modifiers:{shift:Z,ctrl:Y,alt:Q,meta:!1},motion:X}}function ai(J,Z,Q,Y){let X=uV3(J.button),K;if(X.button==="wheel_up"||X.button==="wheel_down"||X.button==="wheel_left"||X.button==="wheel_right")K="scroll";else if(X.motion)K="move";else if(J.pressed)K="press";else K="release";let V,z;if(Z&&Q&&Y)V=(J.x-1)/Q,z=(J.y-1)/Y;else V=J.x-1,z=J.y-1;return{type:"mouse",action:K,button:X.button,x:V,y:z,modifiers:X.modifiers,drag:X.motion&&J.pressed}}m0();var ST4=new Map;function bV3(J){return/\p{Extended_Pictographic}/u.test(J)}function hV3(J){let Z=String.fromCodePoint(J);return!/\p{Emoji_Presentation}/u.test(Z)}function gV3(J){return/\p{M}/u.test(J)}function mV3(J,Z=!0){if(!J)return 0;let Q=Array.from(J);if(Z){let Y=0;for(let X=0;X<Q.length;X++){let K=Q[X];if(!K)continue;let V=K.codePointAt(0);if(!V)continue;let z=kT4(V);if(z!==0){if(X+1<Q.length){let F=Q[X+1]?.codePointAt(0);if(F===65038)z=1;else if(F===65039)z=2}if(Y===0){Y=z;break}}}return Y}else{let Y=0;for(let X of Q){if(!X)continue;let K=X.codePointAt(0);if(!K)continue;Y+=kT4(K)}return Y}}function kT4(J){if(J===9)return fi;if(gV3(String.fromCodePoint(J))||J>=8203&&J<=8205||J===8206||J===8207||J===8288||J===65279||J>=65024&&J<=65039||J>=917760&&J<=917999||J>=127995&&J<=127999)return 0;if(pV3(J)){if(a7()&&(J>=9728&&J<=10175||J===8986||J===8987||J===9203||J>=9193&&J<=9196||J===9200))return 1;if(hV3(J))return 1;return 2}if(dV3(J))return 2;return 1}function pV3(J){let Z=String.fromCodePoint(J);return bV3(Z)}function dV3(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>=65040&&J<=65049||J>=65072&&J<=65103||J>=127462&&J<=127487}function z3(J,Z=!0){let Q=ST4.get(J);if(Q!==void 0)return Q;let Y=mV3(J,Z);return ST4.set(J,Y),Y}var ko0=null;function f6(J){try{if(!ko0)ko0=new Intl.Segmenter("en",{granularity:"grapheme"});return Array.from(ko0.segment(J),(Z)=>Z.segment)}catch(Z){return Array.from(J)}}function x5(J,Z=!0){let Q=0,Y=f6(J);for(let X of Y)Q+=z3(X,Z);return Q}function Cj(J,Z,Q=!0,Y="…"){if(Z<=0)return"";let X=0,K="",V=f6(J);for(let z of V){let G=z3(z,Q);if(X+G>Z){let F=x5(Y,Q);if(X+F<=Z)K+=Y;break}K+=z,X+=G}return K}function oi(J,Z,Q=!0,Y="left",X=" "){let K=x5(J,Q);if(K>=Z)return J;let V=Z-K,z=z3(X,Q),G=Math.floor(V/z);switch(Y){case"center":{let F=Math.floor(G/2),q=G-F;return X.repeat(F)+J+X.repeat(q)}case"right":return X.repeat(G)+J;default:return J+X.repeat(G)}}var Nv={ground:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"ground",action:"execute"}])),...Object.fromEntries(Array.from({length:95},(J,Z)=>[Z+32,{nextState:"ground",action:"print"}])),127:{nextState:"ground",action:"execute"},...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+128,{nextState:"ground",action:"print"}])),27:{nextState:"escape",action:"clear"}},escape:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"escape",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:79},(J,Z)=>[Z+48,{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:"apc_start"},79:{nextState:"escape_intermediate",action:"collect"},127:{nextState:"ground",action:"esc_dispatch"}},escape_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"escape_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:79},(J,Z)=>[Z+48,{nextState:"ground",action:"esc_dispatch"}])),127:{nextState:"escape_intermediate",action:"ignore"}},csi_entry:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_entry",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"csi_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_entry",action:"ignore"}},csi_param:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_param",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_param",action:"param"}])),58:{nextState:"csi_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_param",action:"ignore"}},csi_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_intermediate",action:"ignore"}},csi_ignore:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"csi_ignore",action:"execute"}])),...Object.fromEntries(Array.from({length:64},(J,Z)=>[Z+32,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"ground",action:"ignore"}])),127:{nextState:"csi_ignore",action:"ignore"}},dcs_entry:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_entry",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"dcs_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_entry",action:"ignore"}},dcs_param:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_param",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_param",action:"param"}])),58:{nextState:"dcs_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Z)=>[Z+60,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_param",action:"ignore"}},dcs_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"dcs_intermediate",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Z)=>[Z+48,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Z)=>[Z+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,Z)=>{if(Z===156||Z===27)return[Z,void 0];return[Z,{nextState:"dcs_passthrough",action:"put"}]}).filter(([,J])=>J!==void 0))},dcs_ignore:{...Object.fromEntries(Array.from({length:256},(J,Z)=>[Z,{nextState:"dcs_ignore",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}},osc_string:{...Object.fromEntries(Array.from({length:32},(J,Z)=>[Z,{nextState:"osc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+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:32},(J,Z)=>[Z,{nextState:"sos_pm_apc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Z)=>[Z+32,{nextState:"sos_pm_apc_string",action:"apc_put"}])),156:{nextState:"ground",action:"apc_end"},27:{nextState:"escape",action:"clear"}}},vT4={24:{nextState:"ground",action:"execute"},26:{nextState:"ground",action:"execute"},27:{nextState:"escape",action:"clear"}};Object.keys(Nv).forEach((J)=>{let Z=J;if(Z==="dcs_passthrough"){let{27:Q,...Y}=vT4;Object.assign(Nv[Z],Y)}else Object.assign(Nv[Z],vT4)});class ri{context;eventHandlers=[];constructor(){this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],apcData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,apcEscSeen:!1,dcsEscSeen:!1}}onEvent(J){this.eventHandlers.push(J)}offEvent(J){let Z=this.eventHandlers.indexOf(J);if(Z!==-1)this.eventHandlers.splice(Z,1)}parse(J){let Z=typeof J==="string"?this.stringToBytes(J):J;for(let Q of Z)this.processByte(Q)}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;if(this.context.state==="sos_pm_apc_string"&&J===27){this.context.apcEscSeen=!0;return}if(this.context.apcEscSeen&&J===92){this.context.apcEscSeen=!1,this.performAction("apc_end",J),this.context.state="ground";return}if(this.context.apcEscSeen){this.context.apcEscSeen=!1,this.performAction("clear",27),this.context.state="escape";let Y=Nv["escape"][J];if(Y)this.performAction(Y.action,J),this.context.state=Y.nextState;return}let Z=Nv[this.context.state][J];if(!Z)return;let Q=this.context.state;if(this.performAction(Z.action,J),this.context.state==="ground"&&Z.nextState!=="ground")this.flushTextBuffer();if(this.context.state===Q)this.context.state=Z.nextState}performAction(J,Z){if(this.context.dcsEscSeen&&Z===92){this.context.dcsEscSeen=!1;return}if(this.context.dcsEscSeen)this.context.dcsEscSeen=!1;switch(J){case"ignore":break;case"print":this.addToPrintBuffer(Z);break;case"execute":this.flushTextBuffer(),this.emitEvent({type:"execute",code:Z});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(Z>=60&&Z<=63)this.context.private.push(String.fromCharCode(Z));else this.context.intermediates.push(String.fromCharCode(Z));break;case"param":if(Z>=48&&Z<=57)if(this.context.currentSubparams.length>0)this.context.subparamBuffer.push(String.fromCharCode(Z));else this.context.paramBuffer.push(String.fromCharCode(Z));else if(Z===59)this.finishParameter();else if(Z===58)this.finishSubparameter();break;case"esc_dispatch":this.emitEvent({type:"escape",intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Z)});break;case"csi_dispatch":this.finishParameter(),this.emitEvent({type:"csi",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Z),params:[...this.context.params]});break;case"hook":this.finishParameter(),this.context.dcsData.length=0,this.context.final=String.fromCharCode(Z);break;case"put":this.context.dcsData.push(String.fromCharCode(Z));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=Z===27;break;case"osc_start":this.context.oscData.length=0,this.context.oscEscSeen=!1;break;case"osc_put":this.context.oscData.push(String.fromCharCode(Z));break;case"osc_end":this.emitEvent({type:"osc",data:this.context.oscData.join("")});break;case"apc_start":this.context.apcData.length=0;break;case"apc_put":this.context.apcData.push(String.fromCharCode(Z));break;case"apc_end":this.emitEvent({type:"apc",data:this.context.apcData.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,...Z]=this.context.currentSubparams,Q={value:J??0};if(Z.length>0)Q.subparams=Z;this.context.params.push(Q),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,Z=this.context.printBuffer;for(let Q=0;Q<Z.length;Q++){let Y=Z[Q];if(Y===void 0)continue;if(Y<128)J=Q+1;else if((Y&224)===192){let X=Z[Q+1];if(Q+1<Z.length&&X!==void 0&&(X&192)===128)J=Q+2,Q++;else break}else if((Y&240)===224){let X=Z[Q+1],K=Z[Q+2];if(Q+2<Z.length&&X!==void 0&&(X&192)===128&&K!==void 0&&(K&192)===128)J=Q+3,Q+=2;else break}else if((Y&248)===240){let X=Z[Q+1],K=Z[Q+2],V=Z[Q+3];if(Q+3<Z.length&&X!==void 0&&(X&192)===128&&K!==void 0&&(K&192)===128&&V!==void 0&&(V&192)===128)J=Q+4,Q+=3;else break}else if((Y&192)===128){this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Q+1),this.tryEmitGraphemes();return}else{this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Q+1),this.tryEmitGraphemes();return}}if(J>0){let Q=new Uint8Array(Z.slice(0,J)),X=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(this.context.textBuffer+=X,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),Q=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(Q.length>0)this.context.textBuffer+=Q}this.context.printBuffer=[]}flushTextBuffer(){if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout),delete this.context.flushTimeout;if(this.context.textBuffer.length>0){let J=f6(this.context.textBuffer);for(let Z of J)this.emitEvent({type:"print",grapheme:Z});this.context.textBuffer=""}}emitEvent(J){for(let Z of this.eventHandlers)Z(J)}reset(){this.flushPrintBuffer(),this.flushTextBuffer(),this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],apcData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,apcEscSeen:!1,dcsEscSeen:!1}}getState(){return this.context.state}}var yT4={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"};class si{lexer;keyHandlers=[];deviceAttributesHandlers=[];decrqssHandlers=[];dcsHandlers=[];oscHandlers=[];apcHandlers=[];pasteHandlers=[];sgrMouseHandlers=[];mouseHandlers=[];focusHandlers=[];resizeHandlers=[];colorPaletteChangeHandlers=[];cursorPositionReportHandlers=[];escapeTimeout=null;ESCAPE_TIMEOUT_MS=25;pendingEscape=!1;sgrToMouseConverter=ai;inPaste=!1;pasteBuffer="";constructor(){this.lexer=new ri,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 Z=this.keyHandlers.indexOf(J);if(Z!==-1)this.keyHandlers.splice(Z,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)}onApc(J){this.apcHandlers.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)}onColorPaletteChange(J){this.colorPaletteChangeHandlers.push(J)}onCursorPositionReport(J){this.cursorPositionReportHandlers.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"apc":this.handleApcEvent(J);break;case"escape":this.handleEscapeEvent(J);break}}handlePrintEvent(J){if(this.inPaste){this.pasteBuffer+=J.grapheme;return}if(this.pendingEscape){this.clearEscapeTimeout();let Q={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Q);return}let Z={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Z)}handleExecuteEvent(J){if(this.inPaste)switch(J.code){case 10:this.pasteBuffer+=`
6676
6676
  `;return;case 13:this.pasteBuffer+="\r";return;case 9:this.pasteBuffer+="\t";return;default:return}if(J.code===10){let Q={type:"key",key:"Enter",shiftKey:!0,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Q);return}if(J.code===13&&this.lexer.getState()==="escape"){let Q={type:"key",key:"Enter",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Q),this.lexer.reset();return}if(this.lexer.getState()==="escape"&&this.isControlCharacter(J.code)){let Q=this.controlCharacterToGrapheme(J.code);if(Q&&J.code!==27){let Y={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:!0,metaKey:!1};this.emitKeyEvent(Y),this.lexer.reset();return}}let Z=this.controlCharacterToGrapheme(J.code);if(Z){let Q={type:"key",key:Z,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(Q)}}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 Z=this.escapeToKey(J);if(Z)this.emitKeyEvent(Z)}handleDcsEvent(J){for(let Z of this.dcsHandlers)Z(J)}handleOscEvent(J){for(let Z of this.oscHandlers)Z(J)}handleApcEvent(J){for(let Z of this.apcHandlers)Z(J)}handleCsiEvent(J){if(this.clearEscapeTimeout(),this.handleBracketedPaste(J))return;let Z=this.csiToFocus(J);if(Z){this.emitFocusEvent(Z);return}let Q=this.csiToCursorPositionReport(J);if(Q){this.emitCursorPositionReportEvent(Q);return}let Y=this.csiToDeviceAttributes(J);if(Y){this.emitDeviceAttributesEvent(Y);return}let X=this.csiToDecrqss(J);if(X){this.emitDecrqssEvent(X);return}let K=this.csiToKittyKeyboardResponse(J);if(K){this.emitDecrqssEvent(K);return}let V=this.csiToInBandResize(J);if(V){this.emitResizeEvent(V);return}if(J.final==="n"&&J.private==="?"&&J.params[0]?.value===997){let F=J.params[1]?.value??0;P.info("Received color palette change notification (mode 2031)",{mode:F}),this.emitColorPaletteChangeEvent({type:"colorPaletteChange",colorIndex:-1,value:""});return}let z=this.csiToSgrMouse(J);if(z){this.emitSgrMouseEvent(z);let F=this.sgrToMouseConverter(z);this.emitMouseEvent(F);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 Z=J.final.charCodeAt(0);if(Z>=32&&Z<=126)return{type:"key",key:J.final,shiftKey:this.isShifted(J.final),ctrlKey:!1,altKey:!0,metaKey:!1};else if(Z==127)return{type:"key",key:"Backspace",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1}}return null}csiToKey(J){let{final:Z,params:Q}=J;if(Q.length===0||Q.length===1&&Q[0]?.value===0)Q=[{value:1}];let Y=null,X,K={shift:!1,ctrl:!1,alt:!1,meta:!1},V=1,z="";if(Q.length>=1){let G=Q[0]?.value??1,q=Q[0]?.subparams?.[1];if(G===1&&Z==="Z")Y="Tab",K.shift=!0;else Y=this.getSpecialKey(G,Z)??this.unicodeToKey(G);if(q!==void 0)X=this.unicodeToKey(q)??void 0}if(Q.length>=2){let G=Q[1]?.value??1;K=this.parseModifiers(G)}if(Q.length>=3){let G=Q[2]?.value??1;if(Z==="u")V=G-1;else if(Z==="~"&&Q[0]?.value===27)Y=this.unicodeToKey(G)}if(V!==1&&V!==0)return null;if(!Y)return null;if(z===""&&K.shift&&!K.ctrl&&!K.alt&&!K.meta){let G=this.keyToUnicode(Y);if(G&&G>=32&&G<=126)z=Y.toUpperCase()}return this.createKeyEventWithModifiers(Y,K,z,X)}parseModifiers(J){if(J===0||J===1)return{shift:!1,ctrl:!1,alt:!1,meta:!1};let Z=J-1;return{shift:(Z&1)!==0,alt:(Z&2)!==0,ctrl:(Z&4)!==0,meta:(Z&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(yT4[J])return yT4[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,Z,Q,Y){let X={type:"key",key:J,shiftKey:Z.shift,ctrlKey:Z.ctrl,altKey:Z.alt,metaKey:Z.meta};if(Y!==void 0)X.code=Y;return X}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,Z){let Q=`${J}:${Z}`;return si.SPECIAL_KEYS.get(Q)||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 Z of this.keyHandlers)Z(J)}csiToDeviceAttributes(J){if(J.final==="c"&&J.private==="?"){let Z=0,Q=[];if(J.params.length>0){Z=J.params[0]?.value||0;let Y=J.params.slice(1);if(Y.length>0&&Y[Y.length-1]?.value===0)Y=Y.slice(0,-1);Q=Y.map((X)=>X.value)}return{type:"device_attributes_primary",primary:Z,secondary:Q}}return null}csiToDecrqss(J){if(J.final==="y"&&J.intermediates.includes("$")){if(J.params.length>=2){let Z=`?${J.params[0]?.value||0}`,Q=String(J.params[1]?.value||0);return{type:"decrqss_response",request:Z,response:Q}}}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 Z of this.deviceAttributesHandlers)Z(J)}csiToSgrMouse(J){if((J.final==="M"||J.final==="m")&&J.private==="<"){if(J.params.length>=3){let Z=J.params[0]?.value||0,Q=J.params[1]?.value||1,Y=J.params[2]?.value||1,X=Z&-61,K=J.final==="M"&&X!==3;return{type:"sgr_mouse",button:Z,x:Q,y:Y,pressed:K}}}return null}emitDecrqssEvent(J){for(let Z of this.decrqssHandlers)Z(J)}emitSgrMouseEvent(J){for(let Z of this.sgrMouseHandlers)Z(J)}emitMouseEvent(J){for(let Z of this.mouseHandlers)Z(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 Z=J.params[1]?.value||0,Q=J.params[2]?.value||0,Y=J.params[3]?.value||0,X=J.params[4]?.value||0;return{type:"resize",width:Q,height:Z,pixelWidth:X,pixelHeight:Y}}return null}csiToCursorPositionReport(J){if(J.final==="R"&&J.params.length===2){let Z=J.params[0]?.value||0,Q=J.params[1]?.value||0;return{type:"cursor_position_report",row:Z,col:Q}}return null}emitFocusEvent(J){for(let Z of this.focusHandlers)Z(J)}emitColorPaletteChangeEvent(J){for(let Z of this.colorPaletteChangeHandlers)Z({...J,type:"colorPaletteChange"})}emitCursorPositionReportEvent(J){for(let Z of this.cursorPositionReportHandlers)Z(J)}emitResizeEvent(J){for(let Z of this.resizeHandlers)Z(J)}handleBracketedPaste(J){if(J.final==="~"&&J.params.length===1){let Z=J.params[0]?.value;if(Z===200)return this.inPaste=!0,this.pasteBuffer="",!0;else if(Z===201){if(this.inPaste)this.inPaste=!1,this.emitPasteEvent({type:"paste",text:this.pasteBuffer}),this.pasteBuffer="";return!0}}return!1}emitPasteEvent(J){for(let Z of this.pasteHandlers)Z(J)}}function cV3(J){return J.replace(/\r\n|\r/g,`
6677
6677
  `)}function lV3(J){return J.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function xT4(J){let Z=J;return Z=cV3(Z),Z=lV3(Z),Z}m0();import{openSync as iV3}from"node:fs";import fT4 from"node:tty";function nV3(){let J=process.versions.bun;if(!J)return!1;let Z=J.split(".").map(Number),Q=Z[0]??0,Y=Z[1]??0,X=Z[2]??0;if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(X))return!1;if(Q!==1||Y!==2)return!1;return X<22}function bT4(J){let Z="",Q=0;while(Q<J.length){let Y=J.charCodeAt(Q);if(Y===27){if(Q++,Q>=J.length)break;let X=J.charCodeAt(Q);if(X===91){Q++;while(Q<J.length){let K=J.charCodeAt(Q);if(Q++,K>=64&&K<=126)break}continue}if(X===93){Q++;while(Q<J.length){let K=J.charCodeAt(Q);if(K===7){Q++;break}if(K===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===80){Q++;while(Q<J.length){if(J.charCodeAt(Q)===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===95||X===88||X===94){Q++;while(Q<J.length){if(J.charCodeAt(Q)===27&&Q+1<J.length&&J.charCodeAt(Q+1)===92){Q+=2;break}Q++}continue}if(X===78||X===79){Q+=2;continue}if(X>=64&&X<=126){Q++;continue}continue}if(Y===127||Y===8){Z=Z.slice(0,-1),Q++;continue}if(Y<32){Q++;continue}Z+=J[Q],Q++}return Z}function aV3(){let J=!1,Z={stdin:null,dataCallback:null,earlyInputBuffer:[],init(){if(this.stdin!==null)return;if(l5.stream){if(P.info("[tty] taking over early stdin stream"),this.stdin=l5.stream,this.stdin.removeAllListeners("data"),l5.takenOver=!0,l5.buffer.length>0)this.earlyInputBuffer.push(...l5.buffer),l5.buffer=[];this.stdin.on("data",(X)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(X));if(this.dataCallback)this.dataCallback(X)}),l5.stream=null;return}let Q=iV3("/dev/tty","r");if(!fT4.isatty(Q))throw Error("/dev/tty is not a TTY device");let Y=new fT4.ReadStream(Q);this.stdin=Y,Y.setRawMode(!0),Y.on("data",(X)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(X));if(this.dataCallback)this.dataCallback(X)})},on(Q,Y){this.dataCallback=Y},pause(){if(this.stdin)this.stdin.setRawMode(!1),this.stdin.removeAllListeners("data"),this.stdin.destroy();this.stdin=null},resume(){this.init()},dispose(){if(this.stdin)this.stdin.setRawMode(!1),this.stdin.removeAllListeners("data"),this.stdin.destroy();this.stdin=null,this.dataCallback=null,this.earlyInputBuffer=[]},getEarlyInputText(){if(J=!0,this.earlyInputBuffer.length===0)return"";let Y=Buffer.concat(this.earlyInputBuffer).toString("utf8");return this.earlyInputBuffer=[],bT4(Y)}};return Z.init(),Z}function uT4(){let J=!1,Z={stdin:null,dataCallback:null,earlyInputBuffer:[],init(){if(this.stdin!==null)return;if(this.stdin=process.stdin,this.stdin.isTTY)this.stdin.setRawMode(!0);if(l5.buffer.length>0)this.earlyInputBuffer.push(...l5.buffer),l5.buffer=[];if(l5.stream)l5.stream.removeAllListeners("data"),l5.stream=null,l5.takenOver=!0;this.stdin.on("data",(Q)=>{if(!J)this.earlyInputBuffer.push(Buffer.from(Q));if(this.dataCallback)this.dataCallback(Q)})},on(Q,Y){this.dataCallback=Y},pause(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);this.stdin?.pause()},resume(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!0);this.stdin?.resume()},dispose(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);if(this.stdin)this.stdin.removeAllListeners("data");this.stdin=null,this.dataCallback=null,this.earlyInputBuffer=[]},getEarlyInputText(){if(J=!0,this.earlyInputBuffer.length===0)return"";let Y=Buffer.concat(this.earlyInputBuffer).toString("utf8");return this.earlyInputBuffer=[],bT4(Y)}};return Z.init(),Z}function hT4(){if(process.platform==="win32")return uT4();if(nV3())return P.warn("Detected Bun <1.2.22 which has known /dev/tty issues. Please upgrade to Bun 1.2.22 or later for proper TTY support. Using process.stdin instead."),uT4();return aV3()}m0();import{mkdir as $z3}from"node:fs/promises";import{tmpdir as Jz3}from"node:os";import{join as Zz3}from"node:path";m0();import{spawn as oV3}from"node:child_process";import{createInterface as rV3}from"node:readline";var sV3=1048576,tV3=2000,eV3=500;class vo0{child=null;isStopping=!1;nextRequestID=1;options;pendingRequests=new Map;readline=null;constructor(J){this.options=J}start(){if(this.child)throw Error("win-paste-hook client already started");let J=["--parent-pid",String(this.options.parentPID),"--temp-dir",this.options.tempDir,"--text-priority","false","--enabled","true","--max-text-chars",String(this.options.maxTextChars??sV3)],Z=oV3(this.options.executablePath,J,{stdio:["pipe","pipe","pipe"],windowsHide:!0});this.child=Z,this.readline=rV3({input:Z.stdout}),this.readline.on("line",(Q)=>{this.handleLine(Q)}),Z.stderr.on("data",(Q)=>{let Y=Q.toString().trim();if(Y.length>0)P.debug("[win-paste-hook] stderr",{text:Y})}),Z.on("error",(Q)=>{P.error("[win-paste-hook] child process error",{error:Q}),this.rejectAllPending(Q)}),Z.on("exit",(Q,Y)=>{this.disposeReaders(),this.rejectAllPending(Error("win-paste-hook exited")),this.child=null,this.options.onExit({code:Q,signal:Y,unexpected:!this.isStopping})})}isRunning(){if(!this.child)return!1;return this.child.exitCode===null&&this.child.signalCode===null}async getState(){return this.request("hook/getState")}async readClipboard(){let J=await this.request("clipboard/read");if(!J||typeof J!=="object")return null;return J}async request(J,Z,Q=tV3){let Y=this.nextRequestID++,X={id:Y,jsonrpc:"2.0",method:J,...Z!==void 0?{params:Z}:{}};return this.writeMessage(X),new Promise((K,V)=>{let z=setTimeout(()=>{this.pendingRequests.delete(Y),V(Error(`[win-paste-hook] request timed out: ${J}`))},Q);this.pendingRequests.set(Y,{method:J,reject:V,resolve:(G)=>{K(G)},timeout:z})})}async setEnabled(J){await this.request("hook/setEnabled",{enabled:J})}async shutdown(){if(this.isStopping=!0,!this.child)return;try{await this.request("system/shutdown",void 0,eV3)}catch{this.forceKill()}}forceKill(){if(this.isStopping=!0,this.child&&this.isRunning())this.child.kill()}disposeReaders(){if(this.readline)this.readline.removeAllListeners(),this.readline.close(),this.readline=null}handleLine(J){let Z=J.trim();if(Z.length===0)return;let Q;try{Q=JSON.parse(Z)}catch{P.warn("[win-paste-hook] failed to parse NDJSON line",{line:Z});return}if(!Q||typeof Q!=="object")return;if("method"in Q&&typeof Q.method==="string"){let Y=Q.method;if(Y==="hook/ready"||Y==="clipboard/paste"||Y==="hook/error")this.options.onNotification(Q);return}if("id"in Q&&typeof Q.id==="number")this.handleResponse(Q)}handleResponse(J){let Z=this.pendingRequests.get(J.id);if(!Z)return;if(clearTimeout(Z.timeout),this.pendingRequests.delete(J.id),J.error){Z.reject(Error(`[win-paste-hook] RPC error for ${Z.method}: ${J.error.message}`));return}Z.resolve(J.result)}rejectAllPending(J){for(let Z of this.pendingRequests.values())clearTimeout(Z.timeout),Z.reject(J);this.pendingRequests.clear()}writeMessage(J){if(!this.child||!this.child.stdin.writable)throw Error("win-paste-hook stdin is not writable");this.child.stdin.write(`${JSON.stringify(J)}
6678
- `)}}var Qz3=30000,gT4=2000;class yo0{client=null;clientFactory;desiredEnabled=!0;isStopping=!1;onErrorCallbacks=new Set;onPasteCallbacks=new Set;onStateChangeCallbacks=new Set;restartAttempted=!1;restartTimer=null;restartWindowStartedAtMs=null;state="idle";tempDir;constructor(J={}){this.clientFactory=J.clientFactory??((Z)=>new vo0(Z)),this.tempDir=J.tempDir??Zz3(Jz3(),"amp-win-paste-hook")}getState(){return this.state}isReady(){return this.state==="ready"}onError(J){return this.onErrorCallbacks.add(J),()=>{this.onErrorCallbacks.delete(J)}}onPaste(J){return this.onPasteCallbacks.add(J),()=>{this.onPasteCallbacks.delete(J)}}onStateChange(J){return this.onStateChangeCallbacks.add(J),()=>{this.onStateChangeCallbacks.delete(J)}}async readClipboard(){if(!this.client||!this.isReady())return null;try{return await this.client.readClipboard()}catch(J){return P.warn("[win-paste-hook] clipboard/read failed",{error:J}),null}}async setEnabled(J){if(this.desiredEnabled=J,!this.client||!this.isReady())return;try{await this.client.setEnabled(J)}catch(Z){P.warn("[win-paste-hook] hook/setEnabled failed",{error:Z,enabled:J})}}async start(){this.isStopping=!1,this.restartAttempted=!1,this.restartWindowStartedAtMs=null,await this.launchClient(!1)}async stop(){this.isStopping=!0,this.clearRestartTimer();let J=this.client;if(this.client=null,this.setState("stopped"),!J)return;try{await J.shutdown()}catch(Z){P.debug("[win-paste-hook] shutdown error",{error:Z}),J.forceKill()}}clearRestartTimer(){if(this.restartTimer)clearTimeout(this.restartTimer),this.restartTimer=null}emitError(J){for(let Z of this.onErrorCallbacks)Z(J)}handleHookError(J){let Z=J.message??"Unknown hook error";this.emitError(Error(`[win-paste-hook] ${Z}`))}async handleReady(){let J=this.client;if(!J)return;this.setState("ready");try{let Z=await J.getState();P.debug("[win-paste-hook] hook/getState",{enabled:Z.enabled===!0})}catch(Z){P.warn("[win-paste-hook] hook/getState failed",{error:Z})}await this.setEnabled(this.desiredEnabled)}handleNotification(J){switch(J.method){case"hook/ready":{this.handleReady();return}case"clipboard/paste":{let Z=J.params,Q=Boolean(Z.image),Y=Boolean(Z.text?.value),X=Q&&Y?"both":Q?"image":Y?"text":"none";P.debug("[win-paste-hook] clipboard/paste",{category:X,imageTempFile:Z.image?.tempFile,preferred:Z.preferred,textLength:Z.text?.value.length});for(let K of this.onPasteCallbacks)K(Z);return}case"hook/error":this.handleHookError(J.params)}}async launchClient(J){if(this.isStopping)return;this.setState("starting");let Z;try{Z=await sI4()}catch(Y){P.warn("[win-paste-hook] failed to ensure binary",{error:Y})}if(!Z){this.setState("disabled_session"),this.emitError(Error("win-paste-hook binary unavailable for this session"));return}if(await $z3(this.tempDir,{recursive:!0}),J)this.restartWindowStartedAtMs=Date.now();let Q=this.clientFactory({executablePath:Z,onExit:(Y)=>{this.onClientExit(Y.unexpected,Y.code,Y.signal)},onNotification:(Y)=>{this.handleNotification(Y)},parentPID:process.pid,tempDir:this.tempDir});this.client=Q,Q.start(),P.debug("[win-paste-hook] started")}async onClientExit(J,Z,Q){if(this.client=null,!J||this.isStopping)return;if(P.warn("[win-paste-hook] exited unexpectedly",{code:Z,signal:Q}),this.setState("degraded"),!this.restartAttempted){this.restartAttempted=!0,this.clearRestartTimer(),this.restartTimer=setTimeout(()=>{this.restartTimer=null,this.launchClient(!0)},gT4),P.debug("[win-paste-hook] scheduling restart",{delayMs:gT4});return}let Y=this.restartWindowStartedAtMs!==null&&Date.now()-this.restartWindowStartedAtMs<=Qz3;this.setState("disabled_session"),this.emitError(Error(Y?"win-paste-hook restart failed quickly; disabling for this session":"win-paste-hook restart failed; disabling for this session"))}setState(J){if(this.state===J)return;let Z=this.state;this.state=J,P.debug("[win-paste-hook] state",{current:J,previous:Z});for(let Q of this.onStateChangeCallbacks)Q({current:J,previous:Z})}}var Yz3=50,Xz3=200;function Kz3(J){if(!J)return null;if(J==="1"||J.toLowerCase()==="true")return!0;if(J==="0"||J.toLowerCase()==="false")return!1;return null}class pT4{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 Z=Date.now();if(this.filterDirection!==null)if(Z-this.lastEventTime>Xz3)this.filterDirection=null;else return this.lastEventTime=Z,J.button===this.filterDirection;if(this.lastEventTime=Z,this.eventBuffer.push(J),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},Yz3);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Z)=>Z.button==="wheel_down")){this.filterDirection="wheel_down";for(let Z of this.eventBuffer)if(Z.button==="wheel_down")this.onEmitEvent(Z)}else{this.filterDirection="wheel_up";for(let Z of this.eventBuffer)this.onEmitEvent(Z)}this.eventBuffer=[]}}class xo0{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];winPasteHookImagePasteHandlers=[];winPasteHookStateHandlers=[];winPasteHookSupervisor=null;winPasteHookSupervisorState="idle";boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;lastRenderDiffStats={repaintedCellCount:0,totalCellCount:1920,repaintedPercent:0,bytesWritten:0};options={};constructor(){this.screen=new HH(80,24),this.renderer=new $o0,this.tty=hT4(),this.jetBrainsWheelFilter=new pT4((J)=>{for(let Z of this.mouseHandlers)Z(J)})}setOptions(J){this.options={...this.options,...J}}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(this.parser=new si,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new OX0(this.options.queryOptions),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.onApc((J)=>{if(this.queryParser&&this.initialized){if(J.data.startsWith("G"))this.queryParser.processKittyGraphics()}}),this.parser.onCursorPositionReport((J)=>{if(this.queryParser&&this.initialized)this.queryParser.processCursorPositionReport(J.row,J.col)}),this.parser.onColorPaletteChange((J)=>{if(this.queryParser&&this.initialized){P.info("Color palette change detected, re-querying colors");let Z=this.queryParser.getColorQuerySequences();for(let Q of Z)process.stdout.write(Q);this.queryParser.handleColorPaletteChangeNotification()}}),this.parser.onMouse((J)=>{if(a7()&&!this.jetBrainsWheelFilter.handleWheelEvent(J))return;for(let Z of this.mouseHandlers)Z(J)}),this.parser.onFocus((J)=>{this.winPasteHookSupervisor?.setEnabled(J.focused);for(let Z of this.focusHandlers)Z(J)}),this.parser.onResize((J)=>{this.handleInbandResize(J)}),this.tty.on("data",(J)=>{this.parser?.parse(J)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.isWindowsPasteHookEnabled())this.startWinPasteHookSupervisor();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.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)J+="\x1B[?2031l";if(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,this.winPasteHookImagePasteHandlers.length=0,this.winPasteHookStateHandlers.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.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1,this.winPasteHookSupervisor)this.stopWinPasteHookSupervisor()}getEarlyInputText(){return this.tty.getEarlyInputText()}onKey(J){this.keyHandlers.push(J)}offKey(J){let Z=this.keyHandlers.indexOf(J);if(Z!==-1)this.keyHandlers.splice(Z,1)}onMouse(J){this.mouseHandlers.push(J)}offMouse(J){let Z=this.mouseHandlers.indexOf(J);if(Z!==-1)this.mouseHandlers.splice(Z,1)}onResize(J){this.resizeHandlers.push(J)}offResize(J){let Z=this.resizeHandlers.indexOf(J);if(Z!==-1)this.resizeHandlers.splice(Z,1)}onFocus(J){this.focusHandlers.push(J)}offFocus(J){let Z=this.focusHandlers.indexOf(J);if(Z!==-1)this.focusHandlers.splice(Z,1)}onPaste(J){this.pasteHandlers.push(J)}offPaste(J){let Z=this.pasteHandlers.indexOf(J);if(Z!==-1)this.pasteHandlers.splice(Z,1)}onWinPasteHookImagePaste(J){return this.winPasteHookImagePasteHandlers.push(J),()=>{let Z=this.winPasteHookImagePasteHandlers.indexOf(J);if(Z!==-1)this.winPasteHookImagePasteHandlers.splice(Z,1)}}onWinPasteHookStateChange(J){return this.winPasteHookStateHandlers.push(J),()=>{let Z=this.winPasteHookStateHandlers.indexOf(J);if(Z!==-1)this.winPasteHookStateHandlers.splice(Z,1)}}async readWinPasteHookClipboard(){return this.winPasteHookSupervisor?.readClipboard()??null}isWinPasteHookReady(){return this.winPasteHookSupervisorState==="ready"}onCapabilities(J){this.capabilityHandlers.push(J)}offCapabilities(J){let Z=this.capabilityHandlers.indexOf(J);if(Z!==-1)this.capabilityHandlers.splice(Z,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}getQueryParser(){return this.queryParser}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}getLastRenderDiffStats(){return this.lastRenderDiffStats}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let J=this.screen.getDiff(),Z=this.screen.getSize(),Q=Z.width*Z.height,Y=J.length,X=Q>0?Y/Q*100:0;this.lastRenderDiffStats={repaintedCellCount:Y,totalCellCount:Q,repaintedPercent:X,bytesWritten:0};let K=this.screen.getCursor();if(J.length>0||K!==null){let z=new bi;z.append(this.renderer.startSync()),z.append(this.renderer.hideCursor()),z.append(this.renderer.reset()),z.append(this.renderer.moveTo(0,0));let G=this.renderer.render(J);if(z.append(G),K)if(z.append(this.renderer.moveTo(K.x,K.y)),this.screen.isCursorVisible())z.append(this.renderer.setCursorShape(this.screen.getCursorShape())),z.append(this.renderer.showCursor());else z.append(this.renderer.hideCursor());else z.append(this.renderer.hideCursor());z.append(this.renderer.endSync());let F=z.toString();this.lastRenderDiffStats={...this.lastRenderDiffStats,bytesWritten:Buffer.byteLength(F,"utf8")},process.stdout.write(F),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,Z){this.screen.setCursor(J,Z)}clearCursor(){this.screen.clearCursor()}setCursorShape(J){this.screen.setCursorShape(J)}setMouseCursor(J){let Z=`\x1B]22;${J}\x07`;process.stdout.write(Z)}resetMouseCursor(){this.setMouseCursor(p5.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())}enableModifyOtherKeys(){process.stdout.write(this.renderer.enableModifyOtherKeys())}disableModifyOtherKeys(){process.stdout.write(this.renderer.disableModifyOtherKeys())}async writeClipboard(J){return yz.writeText(J)}get clipboard(){return yz}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&&this.isMouseReportingEnabled()){let J=this.queryParser?.shouldUsePixelMouse()??!1,Z=this.renderer.enableMouse(J);process.stdout.write(Z)}}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())}enableColorPaletteNotifications(){if(this.initialized)P.info("Enabling mode 2031 (color palette change notifications)"),process.stdout.write("\x1B[?2031h")}disableColorPaletteNotifications(){if(this.initialized)process.stdout.write("\x1B[?2031l")}setMouseShape(J){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(J))}suspend(){if(!this.initialized||this.suspended)return;let J="";if(J+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+this.renderer.disableKittyKeyboard()+this.renderer.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)J+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))J+=this.renderer.setProgressBarOff();if(this.inAltScreen)J+=this.renderer.exitAltScreen(),this.inAltScreen=!1;if(process.stdout.write(J),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.hideCursor(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableModifyOtherKeys(),this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1,this.winPasteHookSupervisor?.setEnabled(!0)}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend(),this.winPasteHookSupervisor?.setEnabled(!1);try{process.kill(0,"SIGTSTP"),P.debug(`Successfully suspended process ${process.pid}`)}catch(J){P.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(!this.tty.stdin||!mT4(this.tty.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 Z of this.keyHandlers)Z(J)}handlePasteEvent(J){this.dispatchSyntheticPaste(J.text)}dispatchSyntheticPaste(J){let Z={type:"paste",text:xT4(J)};for(let Q of this.pasteHandlers)Q(Z)}emitWinPasteHookImage(J){for(let Z of this.winPasteHookImagePasteHandlers)Z(J)}emitWinPasteHookState(J){for(let Z of this.winPasteHookStateHandlers)Z(J)}async handleWinPasteHookPaste(J){let Z=Boolean(J.image),Q=Boolean(J.text?.value);if(J.image&&(J.preferred==="image"||!Q)){this.emitWinPasteHookImage({image:J.image,preferred:J.preferred});return}if(J.text&&Q){this.dispatchSyntheticPaste(J.text.value);return}if(!Z&&!Q)P.debug("[win-paste-hook] ignored empty clipboard/paste notification")}isWindowsPasteHookEnabled(){if(!qH())return!1;let J=Kz3(process.env.AMP_WIN_PASTE_HOOK_ENABLED);if(J!==null)return J;return this.options.windowsPasteHookEnabled??!0}isMouseReportingEnabled(){return process.platform!=="win32"}async startWinPasteHookSupervisor(){if(this.winPasteHookSupervisor)return;let J=new yo0;this.winPasteHookSupervisor=J,J.onPaste((Z)=>{this.handleWinPasteHookPaste(Z)}),J.onError((Z)=>{P.warn("[win-paste-hook] supervisor error",{error:Z})}),J.onStateChange((Z)=>{this.winPasteHookSupervisorState=Z.current,this.emitWinPasteHookState(Z)});try{await J.start()}catch(Z){P.warn("[win-paste-hook] failed to start supervisor",{error:Z}),this.winPasteHookSupervisor=null}}async stopWinPasteHookSupervisor(){let J=this.winPasteHookSupervisor;if(!J)return;this.winPasteHookSupervisor=null,await J.stop()}handleOscEvent(J){if(J.data.startsWith("10;")&&this.queryParser){this.queryParser.processOsc10(J.data);return}if(J.data.startsWith("11;")&&this.queryParser){this.queryParser.processOsc11(J.data);return}if(J.data.startsWith("12;")&&this.queryParser){this.queryParser.processOsc12(J.data);return}if(J.data.startsWith("4;")&&this.queryParser){this.queryParser.processOsc4(J.data);return}if(J.data.startsWith("52;c;")){let Z=J.data.slice(5);if(Z&&Z!=="?")yz.handleOSC52Response(Z)}}createCapabilityPromise(){this.capabilityPromise=new Promise((J)=>{this.capabilityResolve=J})}startCapabilityDetection(){if(!this.tty.stdin||!mT4(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new OX0(this.options.queryOptions),process.env.TERM_PROGRAM==="Apple_Terminal"){let J=ii({canRgb:!1});this.capabilities=J;let Z={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Q of this.capabilityHandlers)Q(Z);if(this.capabilityResolve)this.capabilityResolve(J),this.capabilityResolve=null;return}for(let J of CT4){if(J.shouldSend&&!J.shouldSend())continue;if(process.stdout.write(J.sequence),J.description==="Query Kitty explicit width support")this.queryParser.markKittyWidthQuerySent()}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),cY0(this.capabilities.background);for(let Z of this.capabilityHandlers)Z(J);if(this.capabilityResolve)P.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Z=this.queryParser.getPixelDimensions();if(Z){let Q=Z.pixelWidth/Z.columns,Y=Z.pixelHeight/Z.rows;this.parser?.setSgrToMouseConverter((X)=>ai(X,!0,Q,Y))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();if(this.enableModifyOtherKeys(),this.enableInBandResize(),this.capabilities.colorPaletteNotifications)this.enableColorPaletteNotifications();yz.setCapabilities(this.capabilities)}parseXtgettcapResponse(J){if(!this.queryParser)return;let Z=J.indexOf("=");if(Z!==-1){let Q=J.slice(0,Z),Y=J.slice(Z+1);if(this.queryParser.processXtgettcap(Q,Y))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 Z=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(J.width,J.height,J.pixelWidth,J.pixelHeight);let Q=this.queryParser.shouldUsePixelMouse();if(this.isMouseReportingEnabled()&&!Z&&Q)this.disableMouse(),this.enableMouse();if(Q){let Y=J.pixelWidth/J.width,X=J.pixelHeight/J.height;this.parser?.setSgrToMouseConverter((K)=>ai(K,!0,Y,X))}}this.screen.resize(J.width,J.height),setImmediate(()=>{for(let Z of this.resizeHandlers)try{Z(J)}catch(Q){P.error("Error in resize handler:",Q)}})}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 Z of this.resizeHandlers)try{Z(J)}catch(Q){P.error("Error in resize handler:",Q)}})}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 mT4(J){return"isTTY"in J&&J.isTTY===!0&&typeof J.setRawMode==="function"}m0();m0();var ti;((X)=>{X.BUILD="build";X.LAYOUT="layout";X.PAINT="paint";X.RENDER="render"})(ti||={});var Vz3=60,Tj=1000/Vz3;function zz3(){if(typeof process>"u")return!1;return process.env.BUN_TEST==="1"||process.env.VITEST==="true"||process.env.NODE_TEST_CONTEXT==="1"}class C6{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_executingPostFrameCallbacks=!1;_pendingFrameTimer=null;_lastFrameTimestamp=0;_useFramePacing=!zz3();_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 C6._instance??=new C6}requestFrame(){if(this._frameScheduled)return;if(this._frameInProgress){this._frameScheduled=!0;return}if(!this._useFramePacing){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let J=performance.now(),Z=this._lastFrameTimestamp,Q=J-Z;if(Z===0||Q>=Tj){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let Y=Math.max(0,Tj-Q);this._frameScheduled=!0,this.scheduleFrameExecution(Y)}scheduleFrameExecution(J){if(J<=0){setImmediate(()=>this.runScheduledFrame());return}this._pendingFrameTimer=setTimeout(()=>this.runScheduledFrame(),J)}runScheduledFrame(){if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;if(this._frameInProgress)return;this.executeFrame()}addFrameCallback(J,Z,Q,Y=0,X){this._frameCallbacks.set(J,{callback:Z,phase:Q,priority:Y,name:X||J})}removeFrameCallback(J){this._frameCallbacks.delete(J)}addPostFrameCallback(J,Z){if(this._postFrameCallbacks.push({callback:J,name:Z}),!this._frameScheduled&&(!this._frameInProgress||this._executingPostFrameCallbacks))this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let J=performance.now();this._frameScheduled=!1,this._frameInProgress=!0;try{for(let Z of["build","layout","paint","render"])this.executePhase(Z);this.executePostFrameCallbacks()}catch(Z){P.error("Frame execution error:",Z instanceof Error?Z.message:String(Z))}finally{if(this.recordFrameStats(performance.now()-J),this._lastFrameTimestamp=J,this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1,this._frameScheduled){let Q=performance.now()-this._lastFrameTimestamp,Y=Q>=Tj?0:Math.max(0,Tj-Q);this.scheduleFrameExecution(Y)}}}executePhase(J){let Z=performance.now();try{let Q=Array.from(this._frameCallbacks.values()).filter((Y)=>Y.phase===J).sort((Y,X)=>Y.priority-X.priority);for(let Y of Q)try{Y.callback()}catch(X){P.error(`Frame callback error in ${J} phase (${Y.name})`,{errorMessage:X instanceof Error?X.message:String(X),errorType:X?.constructor?.name,stackTrace:X instanceof Error?X.stack:void 0}),Z6(!1,`FATAL: ${J} error in ${Y.name}: ${X}`)}}finally{let Q=performance.now()-Z;this.recordPhaseStats(J,Q)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let J=this._postFrameCallbacks.splice(0);this._executingPostFrameCallbacks=!0;try{for(let{callback:Z,name:Q}of J)try{Z()}catch(Y){P.error(`Post-frame callback error (${Q||"anonymous"}):`,Y instanceof Error?Y.message:String(Y))}}finally{this._executingPostFrameCallbacks=!1}}recordFrameStats(J){this._stats.lastFrameTime=J}recordPhaseStats(J,Z){this._stats.phaseStats[J].lastTime=Z}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(){if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this._lastFrameTimestamp=0,this.resetStats()}}class fo0{_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),C6.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let J=performance.now(),Z=0;try{while(this._dirtyElements.size>0){let Q=Array.from(this._dirtyElements);this._dirtyElements.clear(),Q.sort((Y,X)=>Y.depth-X.depth);for(let Y of Q)if(Y.dirty)try{Y.performRebuild(),Y._dirty=!1,Z++}catch(X){P.error("Element rebuild error:",{error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0,elementType:Y.widget.constructor.name,elementDebugLabel:Y.widget.debugLabel}),Y._dirty=!1}}}finally{this.recordBuildStats(performance.now()-J,Z)}}recordBuildStats(J,Z){if(this._stats.totalRebuilds+=Z,this._stats.elementsRebuiltThisFrame=Z,this._stats.lastBuildTime=J,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Z),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,J),this._buildTimes.push(J),this._elementsPerFrame.push(Z),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((Q,Y)=>Q+Y,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((Q,Y)=>Q+Y,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()}}m0();import Gz3 from"node:http";class wq{enabled;interval;static _instance=null;server=null;latestSnapshot=null;timer=null;rootElement=null;port;objectToId=new WeakMap;nextId=0;renderObjectToElementMap=new Map;keystrokeHistory=[];MAX_KEYSTROKE_HISTORY=50;constructor(J=!1,Z=1000,Q){this.enabled=J;this.interval=Z;this.port=Q??9876,wq._instance=this}static get instance(){return wq._instance}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;wq._instance=null}static recordKeystroke(J,Z,Q){let Y=wq._instance;if(!Y||!Y.enabled)return;let X={timestamp:Date.now(),key:J,focusPath:Z,handled:Q};if(Y.keystrokeHistory.push(X),Y.keystrokeHistory.length>Y.MAX_KEYSTROKE_HISTORY)Y.keystrokeHistory.shift()}startServer(){this.server=Gz3.createServer((J,Z)=>{if(Z.setHeader("Access-Control-Allow-Origin","*"),Z.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),Z.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),J.method==="OPTIONS"){Z.writeHead(200),Z.end();return}if(J.url==="/widget-tree"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200),Z.end(JSON.stringify(this.latestSnapshot||{timestamp:Date.now(),rootWidget:null}));return}if(J.url==="/focus-tree"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200);let Q=OZ.instance.debugDumpFocusTree();Z.end(JSON.stringify(Q||{timestamp:Date.now(),rootScope:null}));return}if(J.url==="/health"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200),Z.end(JSON.stringify({status:"ok",enabled:this.enabled}));return}Z.writeHead(404),Z.end("Not Found")}),this.server.listen(this.port,"localhost",()=>{P.info(`Widget Tree Debugger running on http://localhost:${this.port}`),P.info(`Widget Tree Data: http://localhost:${this.port}/widget-tree`)}),this.server.on("error",(J)=>{P.error("Widget Tree Debugger server error:",J)})}startPeriodicScan(){this.scanTree(),this.timer=setInterval(()=>{this.scanTree()},this.interval)}scanTree(){if(!this.rootElement)return;try{this.renderObjectToElementMap.clear(),this.buildRenderObjectElementMap(this.rootElement);let J=this.elementToDebugInfo(this.rootElement),Z=this.elementToElementDebugInfo(this.rootElement),Q=this.rootElement.renderObject?this.renderObjectToRenderTreeDebugInfo(this.rootElement.renderObject,this.rootElement):null;this.latestSnapshot={timestamp:Date.now(),rootWidget:J,rootElement:Z,rootRenderObject:Q,recentKeystrokes:[...this.keystrokeHistory]}}catch(J){P.error("Error scanning trees:",J)}}elementToDebugInfo(J){let Z=this.toId(J),Q=J.widget.constructor.name,Y=J.widget.key?String(J.widget.key):void 0,X=J.depth,K;if(J.renderObject)K=this.renderObjectToDebugInfo(J.renderObject);let V=J.children.map((z)=>this.elementToDebugInfo(z));return{id:Z,type:Q,key:Y,depth:X,renderObject:K,children:V}}elementToElementDebugInfo(J){let Z=this.toId(J),Q=J.constructor.name,Y=J.depth,X=J.dirty,K=J.mounted,V=this.elementToDebugInfo(J),z;if(J.renderObject)z=this.renderObjectToDebugInfo(J.renderObject);let G=J.children.map((F)=>this.elementToElementDebugInfo(F));return{id:Z,type:Q,depth:Y,dirty:X,mounted:K,widget:V,renderObject:z,children:G}}renderObjectToRenderTreeDebugInfo(J,Z){let Q=this.toId(J),Y=this.renderObjectToElementMap.get(J),X=Y?this.toId(Y):void 0,K=J.constructor.name,V={},z=!1,G=!1,F,q,W,U;if(Z)U=this.getDebugData(Z,J);else{let D=this.renderObjectToElementMap.get(J);if(D)U=this.getDebugData(D,J);else if("debugData"in J){let B=J.debugData;if(B&&Object.keys(B).length>0)U=B}}try{if("needsLayout"in J)z=J.needsLayout;if("needsPaint"in J)G=J.needsPaint;if("size"in J)q=J.size;if("_lastConstraints"in J)F=J._lastConstraints;if("offset"in J){let B=J.offset;if(B&&typeof B==="object"&&"x"in B&&"y"in B)W={x:B.x,y:B.y}}let D=Object.getOwnPropertyNames(J);for(let B of D)if(!B.startsWith("_")&&B!=="constructor"&&!["needsLayout","needsPaint","size","constraints","offset"].includes(B))try{let N=J[B];if(typeof N!=="function"&&typeof N!=="object")V[B]=N}catch{}}catch(D){V.error=`Failed to extract properties: ${D}`}let H=[];try{let D=J;if("children"in J&&Array.isArray(D.children))for(let B of D.children)H.push(this.renderObjectToRenderTreeDebugInfo(B))}catch{}return{id:Q,type:K,constraints:F,size:q,offset:W,needsLayout:z,needsPaint:G,properties:V,debugData:U,elementId:X,children:H}}renderObjectToDebugInfo(J){let Z=J.constructor.name,Q={};try{if("size"in J)Q.size=J.size;if("constraints"in J)Q.constraints=J.constraints;if("offset"in J)Q.offset=J.offset;let Y=Object.getOwnPropertyNames(J);for(let X of Y)if(!X.startsWith("_")&&X!=="constructor")try{let K=J[X];if(typeof K!=="function")Q[X]=K}catch{}}catch(Y){Q.error=`Failed to extract properties: ${Y}`}return{type:Z,properties:Q}}getLatestSnapshot(){return this.latestSnapshot}forceScan(){this.scanTree()}buildRenderObjectElementMap(J){if(J.renderObject)this.renderObjectToElementMap.set(J.renderObject,J);for(let Z of J.children)this.buildRenderObjectElementMap(Z)}toId(J){let Z=this.objectToId.get(J);if(Z===void 0)Z=`inspector-${this.nextId++}`,this.objectToId.set(J,Z);return Z}getDebugData(J,Z){let Q={};if("debugData"in J.widget){let X=J.widget.debugData;if(X&&Object.keys(X).length>0)Q={...Q,...X}}let Y=Z||J.renderObject;if(Y&&"debugData"in Y){let X=Y.debugData;if(X&&Object.keys(X).length>0)Q={...Q,...X}}return Object.keys(Q).length>0?Q:void 0}}class G6{static _nextDebugId=0;_debugId;_parent=null;_children=new Set;_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;static _requestFocusCallback=null;constructor(J={}){if(this._debugId=`focus-${G6._nextDebugId++}`,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 debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let J=OZ.instance.primaryFocus;return this._hasPrimaryFocus||(J?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(J){if(this._canRequestFocus!==J){if(this._canRequestFocus=J,!J&&this._hasPrimaryFocus)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){G6._requestFocusCallback=J}requestFocus(){if(!this._canRequestFocus)return!1;if(G6._requestFocusCallback)return G6._requestFocusCallback(this);return!1}unfocus(){if(this._hasPrimaryFocus){if(G6._requestFocusCallback)G6._requestFocusCallback(null)}}_isDecendantOf(J){if(J===null)return!1;if(this._parent===J)return!0;return this._parent?._isDecendantOf(J)??!1}_isAncestorTo(J){return J?._isDecendantOf(this)??!1}_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(G6._requestFocusCallback){let Z=G6._requestFocusCallback.__focusManager;if(Z&&Z._invalidateFocusableNodesCache)Z._invalidateFocusableNodesCache()}}_detach(){if(this._parent)this._parent._children.delete(this),this._parent=null;if(G6._requestFocusCallback){let J=G6._requestFocusCallback.__focusManager;if(J&&J._invalidateFocusableNodesCache)J._invalidateFocusableNodesCache()}if(this._hasPrimaryFocus)this.unfocus()}_setFocus(J){if(this._hasPrimaryFocus===J)return;let Z=this.hasFocus;this._hasPrimaryFocus=J;let Q=this.hasFocus;if(this._notifyListeners(),Z!==Q)this._notifyAncestorListeners()}addListener(J){this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J(this)}_notifyAncestorListeners(){let J=this._parent;while(J)J._notifyListeners(),J=J._parent}_handleKeyEvent(J){return this.handleKeyEvent(J)}_handlePasteEvent(J){if(this._onPasteCallback)return this._onPasteCallback(J);return"ignored"}toStringShort(){let J=this._debugLabel?`"${this._debugLabel}"`:"",Z=this._hasPrimaryFocus?" FOCUSED":"",Q=this._canRequestFocus?"":" (can't focus)";return`FocusNode${J}${Z}${Q}`}toStringDeep(J="",Z=!0){let Q=J+this.toStringShort();if(Z&&this._children.size>0){let Y=J+" ";for(let X of this._children)Q+=`
6678
+ `)}}var Qz3=30000,gT4=2000;class yo0{client=null;clientFactory;desiredEnabled=!0;isStopping=!1;onErrorCallbacks=new Set;onPasteCallbacks=new Set;onStateChangeCallbacks=new Set;restartAttempted=!1;restartTimer=null;restartWindowStartedAtMs=null;state="idle";tempDir;constructor(J={}){this.clientFactory=J.clientFactory??((Z)=>new vo0(Z)),this.tempDir=J.tempDir??Zz3(Jz3(),"amp-win-paste-hook")}getState(){return this.state}isReady(){return this.state==="ready"}onError(J){return this.onErrorCallbacks.add(J),()=>{this.onErrorCallbacks.delete(J)}}onPaste(J){return this.onPasteCallbacks.add(J),()=>{this.onPasteCallbacks.delete(J)}}onStateChange(J){return this.onStateChangeCallbacks.add(J),()=>{this.onStateChangeCallbacks.delete(J)}}async readClipboard(){if(!this.client||!this.isReady())return null;try{return await this.client.readClipboard()}catch(J){return P.warn("[win-paste-hook] clipboard/read failed",{error:J}),null}}async setEnabled(J){if(this.desiredEnabled=J,!this.client||!this.isReady())return;try{await this.client.setEnabled(J)}catch(Z){P.warn("[win-paste-hook] hook/setEnabled failed",{error:Z,enabled:J})}}async start(){this.isStopping=!1,this.restartAttempted=!1,this.restartWindowStartedAtMs=null,await this.launchClient(!1)}async stop(){this.isStopping=!0,this.clearRestartTimer();let J=this.client;if(this.client=null,this.setState("stopped"),!J)return;try{await J.shutdown()}catch(Z){P.debug("[win-paste-hook] shutdown error",{error:Z}),J.forceKill()}}clearRestartTimer(){if(this.restartTimer)clearTimeout(this.restartTimer),this.restartTimer=null}emitError(J){for(let Z of this.onErrorCallbacks)Z(J)}handleHookError(J){let Z=J.message??"Unknown hook error";this.emitError(Error(`[win-paste-hook] ${Z}`))}async handleReady(){let J=this.client;if(!J)return;this.setState("ready");try{let Z=await J.getState();P.debug("[win-paste-hook] hook/getState",{enabled:Z.enabled===!0})}catch(Z){P.warn("[win-paste-hook] hook/getState failed",{error:Z})}await this.setEnabled(this.desiredEnabled)}handleNotification(J){switch(J.method){case"hook/ready":{this.handleReady();return}case"clipboard/paste":{let Z=J.params,Q=Boolean(Z.image),Y=Boolean(Z.text?.value),X=Q&&Y?"both":Q?"image":Y?"text":"none";P.debug("[win-paste-hook] clipboard/paste",{category:X,imageTempFile:Z.image?.tempFile,preferred:Z.preferred,textLength:Z.text?.value.length});for(let K of this.onPasteCallbacks)K(Z);return}case"hook/error":this.handleHookError(J.params)}}async launchClient(J){if(this.isStopping)return;this.setState("starting");let Z;try{Z=await sI4()}catch(Y){P.warn("[win-paste-hook] failed to ensure binary",{error:Y})}if(!Z){this.setState("disabled_session"),this.emitError(Error("win-paste-hook binary unavailable for this session"));return}if(await $z3(this.tempDir,{recursive:!0}),J)this.restartWindowStartedAtMs=Date.now();let Q=this.clientFactory({executablePath:Z,onExit:(Y)=>{this.onClientExit(Y.unexpected,Y.code,Y.signal)},onNotification:(Y)=>{this.handleNotification(Y)},parentPID:process.pid,tempDir:this.tempDir});this.client=Q,Q.start(),P.debug("[win-paste-hook] started")}async onClientExit(J,Z,Q){if(this.client=null,!J||this.isStopping)return;if(P.warn("[win-paste-hook] exited unexpectedly",{code:Z,signal:Q}),this.setState("degraded"),!this.restartAttempted){this.restartAttempted=!0,this.clearRestartTimer(),this.restartTimer=setTimeout(()=>{this.restartTimer=null,this.launchClient(!0)},gT4),P.debug("[win-paste-hook] scheduling restart",{delayMs:gT4});return}let Y=this.restartWindowStartedAtMs!==null&&Date.now()-this.restartWindowStartedAtMs<=Qz3;this.setState("disabled_session"),this.emitError(Error(Y?"win-paste-hook restart failed quickly; disabling for this session":"win-paste-hook restart failed; disabling for this session"))}setState(J){if(this.state===J)return;let Z=this.state;this.state=J,P.debug("[win-paste-hook] state",{current:J,previous:Z});for(let Q of this.onStateChangeCallbacks)Q({current:J,previous:Z})}}var Yz3=50,Xz3=200;function Kz3(J){if(!J)return null;if(J==="1"||J.toLowerCase()==="true")return!0;if(J==="0"||J.toLowerCase()==="false")return!1;return null}class pT4{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 Z=Date.now();if(this.filterDirection!==null)if(Z-this.lastEventTime>Xz3)this.filterDirection=null;else return this.lastEventTime=Z,J.button===this.filterDirection;if(this.lastEventTime=Z,this.eventBuffer.push(J),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},Yz3);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Z)=>Z.button==="wheel_down")){this.filterDirection="wheel_down";for(let Z of this.eventBuffer)if(Z.button==="wheel_down")this.onEmitEvent(Z)}else{this.filterDirection="wheel_up";for(let Z of this.eventBuffer)this.onEmitEvent(Z)}this.eventBuffer=[]}}class xo0{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];winPasteHookImagePasteHandlers=[];winPasteHookStateHandlers=[];winPasteHookSupervisor=null;winPasteHookSupervisorState="idle";boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;lastRenderDiffStats={repaintedCellCount:0,totalCellCount:1920,repaintedPercent:0,bytesWritten:0};options={};constructor(){this.screen=new HH(80,24),this.renderer=new $o0,this.tty=hT4(),this.jetBrainsWheelFilter=new pT4((J)=>{for(let Z of this.mouseHandlers)Z(J)})}setOptions(J){this.options={...this.options,...J}}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(this.parser=new si,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new OX0(this.options.queryOptions),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.onApc((J)=>{if(this.queryParser&&this.initialized){if(J.data.startsWith("G"))this.queryParser.processKittyGraphics()}}),this.parser.onCursorPositionReport((J)=>{if(this.queryParser&&this.initialized)this.queryParser.processCursorPositionReport(J.row,J.col)}),this.parser.onColorPaletteChange((J)=>{if(this.queryParser&&this.initialized){P.info("Color palette change detected, re-querying colors");let Z=this.queryParser.getColorQuerySequences();for(let Q of Z)process.stdout.write(Q);this.queryParser.handleColorPaletteChangeNotification()}}),this.parser.onMouse((J)=>{if(a7()&&!this.jetBrainsWheelFilter.handleWheelEvent(J))return;for(let Z of this.mouseHandlers)Z(J)}),this.parser.onFocus((J)=>{this.winPasteHookSupervisor?.setEnabled(J.focused);for(let Z of this.focusHandlers)Z(J)}),this.parser.onResize((J)=>{this.handleInbandResize(J)}),this.tty.on("data",(J)=>{this.parser?.parse(J)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.isWindowsPasteHookEnabled())this.startWinPasteHookSupervisor();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.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)J+="\x1B[?2031l";if(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,this.winPasteHookImagePasteHandlers.length=0,this.winPasteHookStateHandlers.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.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1,this.winPasteHookSupervisor)this.stopWinPasteHookSupervisor()}getEarlyInputText(){return this.tty.getEarlyInputText()}onKey(J){this.keyHandlers.push(J)}offKey(J){let Z=this.keyHandlers.indexOf(J);if(Z!==-1)this.keyHandlers.splice(Z,1)}onMouse(J){this.mouseHandlers.push(J)}offMouse(J){let Z=this.mouseHandlers.indexOf(J);if(Z!==-1)this.mouseHandlers.splice(Z,1)}onResize(J){this.resizeHandlers.push(J)}offResize(J){let Z=this.resizeHandlers.indexOf(J);if(Z!==-1)this.resizeHandlers.splice(Z,1)}onFocus(J){this.focusHandlers.push(J)}offFocus(J){let Z=this.focusHandlers.indexOf(J);if(Z!==-1)this.focusHandlers.splice(Z,1)}onPaste(J){this.pasteHandlers.push(J)}offPaste(J){let Z=this.pasteHandlers.indexOf(J);if(Z!==-1)this.pasteHandlers.splice(Z,1)}onWinPasteHookImagePaste(J){return this.winPasteHookImagePasteHandlers.push(J),()=>{let Z=this.winPasteHookImagePasteHandlers.indexOf(J);if(Z!==-1)this.winPasteHookImagePasteHandlers.splice(Z,1)}}onWinPasteHookStateChange(J){return this.winPasteHookStateHandlers.push(J),()=>{let Z=this.winPasteHookStateHandlers.indexOf(J);if(Z!==-1)this.winPasteHookStateHandlers.splice(Z,1)}}async readWinPasteHookClipboard(){return this.winPasteHookSupervisor?.readClipboard()??null}isWinPasteHookReady(){return this.winPasteHookSupervisorState==="ready"}onCapabilities(J){this.capabilityHandlers.push(J)}offCapabilities(J){let Z=this.capabilityHandlers.indexOf(J);if(Z!==-1)this.capabilityHandlers.splice(Z,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}getQueryParser(){return this.queryParser}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}getLastRenderDiffStats(){return this.lastRenderDiffStats}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let J=this.screen.getDiff(),Z=this.screen.getSize(),Q=Z.width*Z.height,Y=J.length,X=Q>0?Y/Q*100:0;this.lastRenderDiffStats={repaintedCellCount:Y,totalCellCount:Q,repaintedPercent:X,bytesWritten:0};let K=this.screen.getCursor();if(J.length>0||K!==null){let z=new bi;z.append(this.renderer.startSync()),z.append(this.renderer.hideCursor()),z.append(this.renderer.reset()),z.append(this.renderer.moveTo(0,0));let G=this.renderer.render(J);if(z.append(G),K)if(z.append(this.renderer.moveTo(K.x,K.y)),this.screen.isCursorVisible())z.append(this.renderer.setCursorShape(this.screen.getCursorShape())),z.append(this.renderer.showCursor());else z.append(this.renderer.hideCursor());else z.append(this.renderer.hideCursor());z.append(this.renderer.endSync());let F=z.toString();this.lastRenderDiffStats={...this.lastRenderDiffStats,bytesWritten:Buffer.byteLength(F,"utf8")},process.stdout.write(F),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,Z){this.screen.setCursor(J,Z)}clearCursor(){this.screen.clearCursor()}setCursorShape(J){this.screen.setCursorShape(J)}setMouseCursor(J){let Z=`\x1B]22;${J}\x07`;process.stdout.write(Z)}resetMouseCursor(){this.setMouseCursor(p5.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())}enableModifyOtherKeys(){process.stdout.write(this.renderer.enableModifyOtherKeys())}disableModifyOtherKeys(){process.stdout.write(this.renderer.disableModifyOtherKeys())}async writeClipboard(J){return yz.writeText(J)}get clipboard(){return yz}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&&this.isMouseReportingEnabled()){let J=this.queryParser?.shouldUsePixelMouse()??!1,Z=this.renderer.enableMouse(J);process.stdout.write(Z)}}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())}enableColorPaletteNotifications(){if(this.initialized)P.info("Enabling mode 2031 (color palette change notifications)"),process.stdout.write("\x1B[?2031h")}disableColorPaletteNotifications(){if(this.initialized)process.stdout.write("\x1B[?2031l")}setMouseShape(J){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(J))}suspend(){if(!this.initialized||this.suspended)return;let J="";if(J+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+this.renderer.disableKittyKeyboard()+this.renderer.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)J+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))J+=this.renderer.setProgressBarOff();if(this.inAltScreen)J+=this.renderer.exitAltScreen(),this.inAltScreen=!1;if(process.stdout.write(J),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.hideCursor(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableModifyOtherKeys(),this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1,this.winPasteHookSupervisor?.setEnabled(!0)}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend(),this.winPasteHookSupervisor?.setEnabled(!1);try{process.kill(0,"SIGTSTP"),P.debug(`Successfully suspended process ${process.pid}`)}catch(J){P.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(!this.tty.stdin||!mT4(this.tty.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 Z of this.keyHandlers)Z(J)}handlePasteEvent(J){this.dispatchSyntheticPaste(J.text)}dispatchSyntheticPaste(J){let Z={type:"paste",text:xT4(J)};for(let Q of this.pasteHandlers)Q(Z)}emitWinPasteHookImage(J){for(let Z of this.winPasteHookImagePasteHandlers)Z(J)}emitWinPasteHookState(J){for(let Z of this.winPasteHookStateHandlers)Z(J)}async handleWinPasteHookPaste(J){let Z=Boolean(J.image),Q=Boolean(J.text?.value);if(J.image&&(J.preferred==="image"||!Q)){this.emitWinPasteHookImage({image:J.image,preferred:J.preferred});return}if(J.text&&Q){this.dispatchSyntheticPaste(J.text.value);return}if(!Z&&!Q)P.debug("[win-paste-hook] ignored empty clipboard/paste notification")}isWindowsPasteHookEnabled(){if(!qH())return!1;let J=Kz3(process.env.AMP_WIN_PASTE_HOOK_ENABLED);if(J!==null)return J;return this.options.windowsPasteHookEnabled??!1}isMouseReportingEnabled(){return process.platform!=="win32"}async startWinPasteHookSupervisor(){if(this.winPasteHookSupervisor)return;let J=new yo0;this.winPasteHookSupervisor=J,J.onPaste((Z)=>{this.handleWinPasteHookPaste(Z)}),J.onError((Z)=>{P.warn("[win-paste-hook] supervisor error",{error:Z})}),J.onStateChange((Z)=>{this.winPasteHookSupervisorState=Z.current,this.emitWinPasteHookState(Z)});try{await J.start()}catch(Z){P.warn("[win-paste-hook] failed to start supervisor",{error:Z}),this.winPasteHookSupervisor=null}}async stopWinPasteHookSupervisor(){let J=this.winPasteHookSupervisor;if(!J)return;this.winPasteHookSupervisor=null,await J.stop()}handleOscEvent(J){if(J.data.startsWith("10;")&&this.queryParser){this.queryParser.processOsc10(J.data);return}if(J.data.startsWith("11;")&&this.queryParser){this.queryParser.processOsc11(J.data);return}if(J.data.startsWith("12;")&&this.queryParser){this.queryParser.processOsc12(J.data);return}if(J.data.startsWith("4;")&&this.queryParser){this.queryParser.processOsc4(J.data);return}if(J.data.startsWith("52;c;")){let Z=J.data.slice(5);if(Z&&Z!=="?")yz.handleOSC52Response(Z)}}createCapabilityPromise(){this.capabilityPromise=new Promise((J)=>{this.capabilityResolve=J})}startCapabilityDetection(){if(!this.tty.stdin||!mT4(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new OX0(this.options.queryOptions),process.env.TERM_PROGRAM==="Apple_Terminal"){let J=ii({canRgb:!1});this.capabilities=J;let Z={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Q of this.capabilityHandlers)Q(Z);if(this.capabilityResolve)this.capabilityResolve(J),this.capabilityResolve=null;return}for(let J of CT4){if(J.shouldSend&&!J.shouldSend())continue;if(process.stdout.write(J.sequence),J.description==="Query Kitty explicit width support")this.queryParser.markKittyWidthQuerySent()}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),cY0(this.capabilities.background);for(let Z of this.capabilityHandlers)Z(J);if(this.capabilityResolve)P.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Z=this.queryParser.getPixelDimensions();if(Z){let Q=Z.pixelWidth/Z.columns,Y=Z.pixelHeight/Z.rows;this.parser?.setSgrToMouseConverter((X)=>ai(X,!0,Q,Y))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();if(this.enableModifyOtherKeys(),this.enableInBandResize(),this.capabilities.colorPaletteNotifications)this.enableColorPaletteNotifications();yz.setCapabilities(this.capabilities)}parseXtgettcapResponse(J){if(!this.queryParser)return;let Z=J.indexOf("=");if(Z!==-1){let Q=J.slice(0,Z),Y=J.slice(Z+1);if(this.queryParser.processXtgettcap(Q,Y))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 Z=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(J.width,J.height,J.pixelWidth,J.pixelHeight);let Q=this.queryParser.shouldUsePixelMouse();if(this.isMouseReportingEnabled()&&!Z&&Q)this.disableMouse(),this.enableMouse();if(Q){let Y=J.pixelWidth/J.width,X=J.pixelHeight/J.height;this.parser?.setSgrToMouseConverter((K)=>ai(K,!0,Y,X))}}this.screen.resize(J.width,J.height),setImmediate(()=>{for(let Z of this.resizeHandlers)try{Z(J)}catch(Q){P.error("Error in resize handler:",Q)}})}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 Z of this.resizeHandlers)try{Z(J)}catch(Q){P.error("Error in resize handler:",Q)}})}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 mT4(J){return"isTTY"in J&&J.isTTY===!0&&typeof J.setRawMode==="function"}m0();m0();var ti;((X)=>{X.BUILD="build";X.LAYOUT="layout";X.PAINT="paint";X.RENDER="render"})(ti||={});var Vz3=60,Tj=1000/Vz3;function zz3(){if(typeof process>"u")return!1;return process.env.BUN_TEST==="1"||process.env.VITEST==="true"||process.env.NODE_TEST_CONTEXT==="1"}class C6{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_executingPostFrameCallbacks=!1;_pendingFrameTimer=null;_lastFrameTimestamp=0;_useFramePacing=!zz3();_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 C6._instance??=new C6}requestFrame(){if(this._frameScheduled)return;if(this._frameInProgress){this._frameScheduled=!0;return}if(!this._useFramePacing){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let J=performance.now(),Z=this._lastFrameTimestamp,Q=J-Z;if(Z===0||Q>=Tj){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let Y=Math.max(0,Tj-Q);this._frameScheduled=!0,this.scheduleFrameExecution(Y)}scheduleFrameExecution(J){if(J<=0){setImmediate(()=>this.runScheduledFrame());return}this._pendingFrameTimer=setTimeout(()=>this.runScheduledFrame(),J)}runScheduledFrame(){if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;if(this._frameInProgress)return;this.executeFrame()}addFrameCallback(J,Z,Q,Y=0,X){this._frameCallbacks.set(J,{callback:Z,phase:Q,priority:Y,name:X||J})}removeFrameCallback(J){this._frameCallbacks.delete(J)}addPostFrameCallback(J,Z){if(this._postFrameCallbacks.push({callback:J,name:Z}),!this._frameScheduled&&(!this._frameInProgress||this._executingPostFrameCallbacks))this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let J=performance.now();this._frameScheduled=!1,this._frameInProgress=!0;try{for(let Z of["build","layout","paint","render"])this.executePhase(Z);this.executePostFrameCallbacks()}catch(Z){P.error("Frame execution error:",Z instanceof Error?Z.message:String(Z))}finally{if(this.recordFrameStats(performance.now()-J),this._lastFrameTimestamp=J,this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1,this._frameScheduled){let Q=performance.now()-this._lastFrameTimestamp,Y=Q>=Tj?0:Math.max(0,Tj-Q);this.scheduleFrameExecution(Y)}}}executePhase(J){let Z=performance.now();try{let Q=Array.from(this._frameCallbacks.values()).filter((Y)=>Y.phase===J).sort((Y,X)=>Y.priority-X.priority);for(let Y of Q)try{Y.callback()}catch(X){P.error(`Frame callback error in ${J} phase (${Y.name})`,{errorMessage:X instanceof Error?X.message:String(X),errorType:X?.constructor?.name,stackTrace:X instanceof Error?X.stack:void 0}),Z6(!1,`FATAL: ${J} error in ${Y.name}: ${X}`)}}finally{let Q=performance.now()-Z;this.recordPhaseStats(J,Q)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let J=this._postFrameCallbacks.splice(0);this._executingPostFrameCallbacks=!0;try{for(let{callback:Z,name:Q}of J)try{Z()}catch(Y){P.error(`Post-frame callback error (${Q||"anonymous"}):`,Y instanceof Error?Y.message:String(Y))}}finally{this._executingPostFrameCallbacks=!1}}recordFrameStats(J){this._stats.lastFrameTime=J}recordPhaseStats(J,Z){this._stats.phaseStats[J].lastTime=Z}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(){if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this._lastFrameTimestamp=0,this.resetStats()}}class fo0{_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),C6.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let J=performance.now(),Z=0;try{while(this._dirtyElements.size>0){let Q=Array.from(this._dirtyElements);this._dirtyElements.clear(),Q.sort((Y,X)=>Y.depth-X.depth);for(let Y of Q)if(Y.dirty)try{Y.performRebuild(),Y._dirty=!1,Z++}catch(X){P.error("Element rebuild error:",{error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0,elementType:Y.widget.constructor.name,elementDebugLabel:Y.widget.debugLabel}),Y._dirty=!1}}}finally{this.recordBuildStats(performance.now()-J,Z)}}recordBuildStats(J,Z){if(this._stats.totalRebuilds+=Z,this._stats.elementsRebuiltThisFrame=Z,this._stats.lastBuildTime=J,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Z),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,J),this._buildTimes.push(J),this._elementsPerFrame.push(Z),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((Q,Y)=>Q+Y,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((Q,Y)=>Q+Y,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()}}m0();import Gz3 from"node:http";class wq{enabled;interval;static _instance=null;server=null;latestSnapshot=null;timer=null;rootElement=null;port;objectToId=new WeakMap;nextId=0;renderObjectToElementMap=new Map;keystrokeHistory=[];MAX_KEYSTROKE_HISTORY=50;constructor(J=!1,Z=1000,Q){this.enabled=J;this.interval=Z;this.port=Q??9876,wq._instance=this}static get instance(){return wq._instance}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;wq._instance=null}static recordKeystroke(J,Z,Q){let Y=wq._instance;if(!Y||!Y.enabled)return;let X={timestamp:Date.now(),key:J,focusPath:Z,handled:Q};if(Y.keystrokeHistory.push(X),Y.keystrokeHistory.length>Y.MAX_KEYSTROKE_HISTORY)Y.keystrokeHistory.shift()}startServer(){this.server=Gz3.createServer((J,Z)=>{if(Z.setHeader("Access-Control-Allow-Origin","*"),Z.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),Z.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),J.method==="OPTIONS"){Z.writeHead(200),Z.end();return}if(J.url==="/widget-tree"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200),Z.end(JSON.stringify(this.latestSnapshot||{timestamp:Date.now(),rootWidget:null}));return}if(J.url==="/focus-tree"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200);let Q=OZ.instance.debugDumpFocusTree();Z.end(JSON.stringify(Q||{timestamp:Date.now(),rootScope:null}));return}if(J.url==="/health"&&J.method==="GET"){Z.setHeader("Content-Type","application/json"),Z.writeHead(200),Z.end(JSON.stringify({status:"ok",enabled:this.enabled}));return}Z.writeHead(404),Z.end("Not Found")}),this.server.listen(this.port,"localhost",()=>{P.info(`Widget Tree Debugger running on http://localhost:${this.port}`),P.info(`Widget Tree Data: http://localhost:${this.port}/widget-tree`)}),this.server.on("error",(J)=>{P.error("Widget Tree Debugger server error:",J)})}startPeriodicScan(){this.scanTree(),this.timer=setInterval(()=>{this.scanTree()},this.interval)}scanTree(){if(!this.rootElement)return;try{this.renderObjectToElementMap.clear(),this.buildRenderObjectElementMap(this.rootElement);let J=this.elementToDebugInfo(this.rootElement),Z=this.elementToElementDebugInfo(this.rootElement),Q=this.rootElement.renderObject?this.renderObjectToRenderTreeDebugInfo(this.rootElement.renderObject,this.rootElement):null;this.latestSnapshot={timestamp:Date.now(),rootWidget:J,rootElement:Z,rootRenderObject:Q,recentKeystrokes:[...this.keystrokeHistory]}}catch(J){P.error("Error scanning trees:",J)}}elementToDebugInfo(J){let Z=this.toId(J),Q=J.widget.constructor.name,Y=J.widget.key?String(J.widget.key):void 0,X=J.depth,K;if(J.renderObject)K=this.renderObjectToDebugInfo(J.renderObject);let V=J.children.map((z)=>this.elementToDebugInfo(z));return{id:Z,type:Q,key:Y,depth:X,renderObject:K,children:V}}elementToElementDebugInfo(J){let Z=this.toId(J),Q=J.constructor.name,Y=J.depth,X=J.dirty,K=J.mounted,V=this.elementToDebugInfo(J),z;if(J.renderObject)z=this.renderObjectToDebugInfo(J.renderObject);let G=J.children.map((F)=>this.elementToElementDebugInfo(F));return{id:Z,type:Q,depth:Y,dirty:X,mounted:K,widget:V,renderObject:z,children:G}}renderObjectToRenderTreeDebugInfo(J,Z){let Q=this.toId(J),Y=this.renderObjectToElementMap.get(J),X=Y?this.toId(Y):void 0,K=J.constructor.name,V={},z=!1,G=!1,F,q,W,U;if(Z)U=this.getDebugData(Z,J);else{let D=this.renderObjectToElementMap.get(J);if(D)U=this.getDebugData(D,J);else if("debugData"in J){let B=J.debugData;if(B&&Object.keys(B).length>0)U=B}}try{if("needsLayout"in J)z=J.needsLayout;if("needsPaint"in J)G=J.needsPaint;if("size"in J)q=J.size;if("_lastConstraints"in J)F=J._lastConstraints;if("offset"in J){let B=J.offset;if(B&&typeof B==="object"&&"x"in B&&"y"in B)W={x:B.x,y:B.y}}let D=Object.getOwnPropertyNames(J);for(let B of D)if(!B.startsWith("_")&&B!=="constructor"&&!["needsLayout","needsPaint","size","constraints","offset"].includes(B))try{let N=J[B];if(typeof N!=="function"&&typeof N!=="object")V[B]=N}catch{}}catch(D){V.error=`Failed to extract properties: ${D}`}let H=[];try{let D=J;if("children"in J&&Array.isArray(D.children))for(let B of D.children)H.push(this.renderObjectToRenderTreeDebugInfo(B))}catch{}return{id:Q,type:K,constraints:F,size:q,offset:W,needsLayout:z,needsPaint:G,properties:V,debugData:U,elementId:X,children:H}}renderObjectToDebugInfo(J){let Z=J.constructor.name,Q={};try{if("size"in J)Q.size=J.size;if("constraints"in J)Q.constraints=J.constraints;if("offset"in J)Q.offset=J.offset;let Y=Object.getOwnPropertyNames(J);for(let X of Y)if(!X.startsWith("_")&&X!=="constructor")try{let K=J[X];if(typeof K!=="function")Q[X]=K}catch{}}catch(Y){Q.error=`Failed to extract properties: ${Y}`}return{type:Z,properties:Q}}getLatestSnapshot(){return this.latestSnapshot}forceScan(){this.scanTree()}buildRenderObjectElementMap(J){if(J.renderObject)this.renderObjectToElementMap.set(J.renderObject,J);for(let Z of J.children)this.buildRenderObjectElementMap(Z)}toId(J){let Z=this.objectToId.get(J);if(Z===void 0)Z=`inspector-${this.nextId++}`,this.objectToId.set(J,Z);return Z}getDebugData(J,Z){let Q={};if("debugData"in J.widget){let X=J.widget.debugData;if(X&&Object.keys(X).length>0)Q={...Q,...X}}let Y=Z||J.renderObject;if(Y&&"debugData"in Y){let X=Y.debugData;if(X&&Object.keys(X).length>0)Q={...Q,...X}}return Object.keys(Q).length>0?Q:void 0}}class G6{static _nextDebugId=0;_debugId;_parent=null;_children=new Set;_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;static _requestFocusCallback=null;constructor(J={}){if(this._debugId=`focus-${G6._nextDebugId++}`,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 debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let J=OZ.instance.primaryFocus;return this._hasPrimaryFocus||(J?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(J){if(this._canRequestFocus!==J){if(this._canRequestFocus=J,!J&&this._hasPrimaryFocus)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){G6._requestFocusCallback=J}requestFocus(){if(!this._canRequestFocus)return!1;if(G6._requestFocusCallback)return G6._requestFocusCallback(this);return!1}unfocus(){if(this._hasPrimaryFocus){if(G6._requestFocusCallback)G6._requestFocusCallback(null)}}_isDecendantOf(J){if(J===null)return!1;if(this._parent===J)return!0;return this._parent?._isDecendantOf(J)??!1}_isAncestorTo(J){return J?._isDecendantOf(this)??!1}_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(G6._requestFocusCallback){let Z=G6._requestFocusCallback.__focusManager;if(Z&&Z._invalidateFocusableNodesCache)Z._invalidateFocusableNodesCache()}}_detach(){if(this._parent)this._parent._children.delete(this),this._parent=null;if(G6._requestFocusCallback){let J=G6._requestFocusCallback.__focusManager;if(J&&J._invalidateFocusableNodesCache)J._invalidateFocusableNodesCache()}if(this._hasPrimaryFocus)this.unfocus()}_setFocus(J){if(this._hasPrimaryFocus===J)return;let Z=this.hasFocus;this._hasPrimaryFocus=J;let Q=this.hasFocus;if(this._notifyListeners(),Z!==Q)this._notifyAncestorListeners()}addListener(J){this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J(this)}_notifyAncestorListeners(){let J=this._parent;while(J)J._notifyListeners(),J=J._parent}_handleKeyEvent(J){return this.handleKeyEvent(J)}_handlePasteEvent(J){if(this._onPasteCallback)return this._onPasteCallback(J);return"ignored"}toStringShort(){let J=this._debugLabel?`"${this._debugLabel}"`:"",Z=this._hasPrimaryFocus?" FOCUSED":"",Q=this._canRequestFocus?"":" (can't focus)";return`FocusNode${J}${Z}${Q}`}toStringDeep(J="",Z=!0){let Q=J+this.toStringShort();if(Z&&this._children.size>0){let Y=J+" ";for(let X of this._children)Q+=`
6679
6679
  `+X.toStringDeep(Y,!0)}return Q}addKeyHandler(J){this._keyHandlers.push(J)}removeKeyHandler(J){let Z=this._keyHandlers.indexOf(J);if(Z!==-1)this._keyHandlers.splice(Z,1)}handleKeyEvent(J){for(let Z of this._keyHandlers)if(Z(J)==="handled")return"handled";return"ignored"}dispose(){this._detach(),this._children.clear(),this._keyHandlers=[]}}class OZ{static _instance=null;_rootScope;_primaryFocus=null;_cachedFocusableNodes=null;_primaryFocusStack=[];constructor(){this._rootScope=new G6({debugLabel:"Root Focus Scope",canRequestFocus:!1});let J=(Z)=>this.requestFocus(Z);J.__focusManager=this,G6.setRequestFocusCallback(J)}static get instance(){if(!OZ._instance)OZ._instance=new OZ;return OZ._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(J&&!J.parent)return!1;if(this._primaryFocus)this._primaryFocus._setFocus(!1);if(J===null){let Z=this._primaryFocus;if(Z)this._popFromFocusStack(Z);let Q=this._findPreviousFocusableNode();if(this._primaryFocus=Q,Q)Q._setFocus(!0);return!0}return this._primaryFocus=J,J._setFocus(!0),this._pushToFocusStack(J),!0}handleKeyEvent(J){if(!this._primaryFocus)return!1;let Z=void 0,Q=this._primaryFocus;while(Q){let X=Q._handleKeyEvent(J)==="handled";if(Z)Z.push({id:Q.debugId,debugLabel:Q.debugLabel,handled:X});if(X){if(Z)wq.recordKeystroke(this.formatKeyEvent(J),Z,!0);return!0}Q=Q.parent}if(Z)wq.recordKeystroke(this.formatKeyEvent(J),Z,!1);return!1}formatKeyEvent(J){let Z=[];if(J.ctrlKey)Z.push("Ctrl");if(J.altKey)Z.push("Alt");if(J.shiftKey)Z.push("Shift");if(J.metaKey)Z.push("Meta");if(J.key)Z.push(J.key);return Z.join("+")}handlePasteEvent(J){if(!this._primaryFocus)return!1;let Z=this._primaryFocus;while(Z){if(Z._handlePasteEvent(J)==="handled")return!0;Z=Z.parent}return!1}registerNode(J,Z=null){Z6(J!==Z,"Focus node cannot be its own parent"),this._invalidateFocusableNodesCache();let Q=Z??this._rootScope;J._attach(Q)}unregisterNode(J){if(this._invalidateFocusableNodesCache(),this._popFromFocusStack(J),this._primaryFocus===J)this.requestFocus(null);J._detach()}findNearestFocusableAncestor(J){let Z=J.parent;while(Z){if(Z.canRequestFocus&&!Z.skipTraversal)return Z;Z=Z.parent}return null}findAllFocusableNodes(){if(this._cachedFocusableNodes!==null)return this._cachedFocusableNodes;let J=[],Z=(Q)=>{if(Q.canRequestFocus&&!Q.skipTraversal)J.push(Q);for(let Y of Q.children)Z(Y)};return Z(this._rootScope),this._cachedFocusableNodes=J,J}_invalidateFocusableNodesCache(){this._cachedFocusableNodes=null}_pushToFocusStack(J){let Z=this._primaryFocusStack.indexOf(J);if(Z!==-1)this._primaryFocusStack.splice(Z,1);this._primaryFocusStack.push(J)}_popFromFocusStack(J){let Z=this._primaryFocusStack.indexOf(J);while(Z!==-1)this._primaryFocusStack.splice(Z,1),Z=this._primaryFocusStack.indexOf(J)}_findPreviousFocusableNode(){while(this._primaryFocusStack.length>0){let J=this._primaryFocusStack[this._primaryFocusStack.length-1];if(J.parent&&J.canRequestFocus&&!J.skipTraversal)return J;else this._primaryFocusStack.pop()}return null}focusNext(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[0]??null);let Z=J.indexOf(this._primaryFocus);if(Z===-1)return this.requestFocus(J[0]??null);let Q=(Z+1)%J.length;return this.requestFocus(J[Q]??null)}focusPrevious(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[J.length-1]??null);let Z=J.indexOf(this._primaryFocus);if(Z===-1)return this.requestFocus(J[J.length-1]??null);let Q=Z===0?J.length-1:Z-1;return this.requestFocus(J[Q]??null)}_focusNodeToDebugInfo(J){return{id:J.debugId,debugLabel:J.debugLabel,hasPrimaryFocus:J.hasPrimaryFocus,hasFocus:J.hasFocus,canRequestFocus:J.canRequestFocus,skipTraversal:J.skipTraversal,isPrimaryFocus:this._primaryFocus===J,children:Array.from(J.children).map((Z)=>this._focusNodeToDebugInfo(Z))}}debugDumpFocusTree(){return null}dispose(){this._primaryFocus=null,this._cachedFocusableNodes=null,this._primaryFocusStack=[],this._rootScope.dispose(),OZ._instance=null}}function fK(J,Z){if(J.length===0)return 0;let Q=[...J].sort((K,V)=>K-V),Y=Math.max(0,Math.min(Z,1)),X=Math.ceil(Q.length*Y)-1;return Q[Math.max(0,X)]||0}class dT4{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];repaintPercents=[];bytesWritten=[];lastKeyEventTime=0;lastMouseEventTime=0;lastRepaintPercent=0;lastBytesWritten=0;MAX_SAMPLES=1024;recordFrame(J){if(this.frameTimes.push(J),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(J,Z){let Q=this.phaseTimes[J];if(Q.push(Z),Q.length>this.MAX_SAMPLES)Q.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()}recordRepaintPercent(J){if(this.lastRepaintPercent=J,this.repaintPercents.push(J),this.repaintPercents.length>this.MAX_SAMPLES)this.repaintPercents.shift()}recordBytesWritten(J){if(this.lastBytesWritten=J,this.bytesWritten.push(J),this.bytesWritten.length>this.MAX_SAMPLES)this.bytesWritten.shift()}getFrameP99(){return fK(this.frameTimes,0.99)}getFrameP95(){return fK(this.frameTimes,0.95)}getPhaseP99(J){return fK(this.phaseTimes[J],0.99)}getPhaseP95(J){return fK(this.phaseTimes[J],0.95)}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return fK(this.keyEventTimes,0.99)}getKeyEventP95(){return fK(this.keyEventTimes,0.95)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return fK(this.mouseEventTimes,0.99)}getMouseEventP95(){return fK(this.mouseEventTimes,0.95)}getLastRepaintPercent(){return this.lastRepaintPercent}getRepaintPercentP99(){return fK(this.repaintPercents,0.99)}getRepaintPercentP95(){return fK(this.repaintPercents,0.95)}getLastBytesWritten(){return this.lastBytesWritten}getBytesWrittenP99(){return fK(this.bytesWritten,0.99)}getBytesWrittenP95(){return fK(this.bytesWritten,0.95)}reset(){this.frameTimes=[];for(let J of Object.values(ti))this.phaseTimes[J]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.repaintPercents=[],this.bytesWritten=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0,this.lastRepaintPercent=0,this.lastBytesWritten=0}}class uo0{enabled=!1;tracker=new dT4;setEnabled(J){this.enabled=J}isEnabled(){return this.enabled}recordKeyEvent(J){this.tracker.recordKeyEvent(J)}recordMouseEvent(J){this.tracker.recordMouseEvent(J)}recordStats(J,Z){this.tracker.recordFrame(J.lastFrameTime);for(let Q of Object.values(ti))this.tracker.recordPhase(Q,J.phaseStats[Q].lastTime);if(Z)this.tracker.recordRepaintPercent(Z.repaintedPercent),this.tracker.recordBytesWritten(Z.bytesWritten)}draw(J,Z){if(!this.enabled)return;let{width:Q,height:Y}=J.getSize(),X=34,K=14,V=Q-X-2,z=1;if(V<0||z+K>=Y)return;let G=r9.default().colorScheme,F=G.border,q=G.foreground,W=G.warning,U=" Gotta Go Fast ",H=Math.floor((X-U.length)/2);J.setCell(V,z,q6("╭",{fg:q}));for(let B0=1;B0<X-1;B0++)if(B0>=H&&B0<H+U.length)J.setCell(V+B0,z,q6(U[B0-H]||"─",{fg:W}));else J.setCell(V+B0,z,q6("─",{fg:q}));J.setCell(V+X-1,z,q6("╮",{fg:q}));for(let B0=1;B0<K-1;B0++){J.setCell(V,z+B0,q6("│",{fg:q})),J.setCell(V+X-1,z+B0,q6("│",{fg:q}));for(let T0=1;T0<X-1;T0++)J.setCell(V+T0,z+B0,q6(" ",{fg:q}))}J.setCell(V,z+K-1,q6("╰",{fg:q}));for(let B0=1;B0<X-1;B0++)J.setCell(V+B0,z+K-1,q6("─",{fg:q}));J.setCell(V+X-1,z+K-1,q6("╯",{fg:q}));let D=V+1,B=z+1;this.drawText(J,D,B++," Last P95 P99",F);let N=this.tracker.getLastKeyEventTime(),w=this.tracker.getKeyEventP95(),L=this.tracker.getKeyEventP99(),O=N.toFixed(2).padStart(5," "),E=w.toFixed(2).padStart(5," "),M=L.toFixed(2).padStart(5," "),A=this.getTimingColor(N),j=this.getTimingColor(w),R=this.getTimingColor(L);this.drawLastP95P99Row(J,D,B++,{label:"Key",labelColor:F,last:{text:O,color:A},p95:{text:E,color:j},p99:{text:M,color:R}});let _=this.tracker.getLastMouseEventTime(),T=this.tracker.getMouseEventP95(),u=this.tracker.getMouseEventP99(),m=_.toFixed(2).padStart(5," "),y=T.toFixed(2).padStart(5," "),k=u.toFixed(2).padStart(5," "),f=this.getTimingColor(_),d=this.getTimingColor(T),p=this.getTimingColor(u);this.drawLastP95P99Row(J,D,B++,{label:"Mouse",labelColor:F,last:{text:m,color:f},p95:{text:y,color:d},p99:{text:k,color:p}}),B++;for(let B0 of["build","layout","paint","render"]){let T0=Z.phaseStats[B0].lastTime,e0=this.tracker.getPhaseP95(B0),Q1=this.tracker.getPhaseP99(B0),F1=T0.toFixed(2).padStart(5," "),e1=e0.toFixed(2).padStart(5," "),m1=Q1.toFixed(2).padStart(5," "),g0=this.getTimingColor(T0),G1=this.getTimingColor(e0),t0=this.getTimingColor(Q1),P1=B0.charAt(0).toUpperCase()+B0.slice(1);this.drawLastP95P99Row(J,D,B++,{label:P1,labelColor:F,last:{text:F1,color:g0},p95:{text:e1,color:G1},p99:{text:m1,color:t0}})}B++;let h=Z.lastFrameTime,n=this.tracker.getFrameP95(),c=this.tracker.getFrameP99(),a=h.toFixed(2).padStart(5," "),W0=n.toFixed(2).padStart(5," "),r=c.toFixed(2).padStart(5," "),H0=this.getTimingColor(h),L0=this.getTimingColor(n),z0=this.getTimingColor(c);this.drawLastP95P99Row(J,D,B++,{label:"Frame",labelColor:q,last:{text:a,color:H0},p95:{text:W0,color:L0},p99:{text:r,color:z0}});let J0=this.tracker.getLastRepaintPercent(),G0=this.tracker.getRepaintPercentP95(),i=this.tracker.getRepaintPercentP99(),o=`${J0.toFixed(1)}%`.padStart(5," "),t=`${G0.toFixed(1)}%`.padStart(5," "),$0=`${i.toFixed(1)}%`.padStart(5," "),F0=this.getPercentColor(J0),K0=this.getPercentColor(G0),Z0=this.getPercentColor(i);this.drawLastP95P99Row(J,D,B++,{label:"Repaint",labelColor:q,last:{text:o,color:F0},p95:{text:t,color:K0},p99:{text:$0,color:Z0}});let Y0=this.formatBytes(this.tracker.getLastBytesWritten()).padStart(5," "),w0=this.formatBytes(this.tracker.getBytesWrittenP95()).padStart(5," "),X0=this.formatBytes(this.tracker.getBytesWrittenP99()).padStart(5," ");this.drawLastP95P99Row(J,D,B,{label:"Bytes",labelColor:q,last:{text:Y0,color:q},p95:{text:w0,color:q},p99:{text:X0,color:q}})}drawLastP95P99Row(J,Z,Q,Y){let X=` ${Y.label.padStart(7," ")} `,K=Z;this.drawText(J,K,Q,X,Y.labelColor),K+=X.length,this.drawText(J,K,Q,Y.last.text,Y.last.color),K+=Y.last.text.length,this.drawText(J,K,Q," ",Y.labelColor),K+=3,this.drawText(J,K,Q,Y.p95.text,Y.p95.color),K+=Y.p95.text.length,this.drawText(J,K,Q," ",Y.labelColor),K+=3,this.drawText(J,K,Q,Y.p99.text,Y.p99.color)}getTimingColor(J){let Z=r9.default().colorScheme,Q=Tj,Y=Tj*0.7;if(J>=Q)return Z.destructive;if(J>=Y)return Z.warning;return Z.foreground}getPercentColor(J){let Z=r9.default().colorScheme;if(J>=50)return Z.destructive;if(J>=20)return Z.warning;return Z.foreground}drawText(J,Z,Q,Y,X){for(let K=0;K<Y.length;K++)J.setCell(Z+K,Q,q6(Y[K]||" ",{fg:X}))}formatBytes(J){if(J>=1e4)return`${Math.round(J/1000)}k`;if(J>=1000)return`${(J/1000).toFixed(1)}k`;return`${Math.round(J)}`}}class wv{size;capabilities;constructor(J,Z){this.size=J;this.capabilities=Z}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}class V4 extends s5{data;constructor({key:J,data:Z,child:Q}){super(J!==void 0?{key:J,child:Q}:{child:Q});this.data=Z}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 Z=J.dependOnInheritedWidgetOfExactType(V4);if(Z)return Z.widget.data;throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.")}static sizeOf(J){return V4.of(J).size}static capabilitiesOf(J){return V4.of(J).capabilities}}class bo0{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(J){if(!C6.instance.isFrameInProgress)C6.instance.requestFrame()}requestPaint(J){if(this._nodesNeedingPaint.has(J))return;if(this._nodesNeedingPaint.add(J),!C6.instance.isFrameInProgress)C6.instance.requestFrame()}setRootRenderObject(J){this._rootRenderObject=J}updateRootConstraints(J){let Z=new I1(0,J.width,0,J.height),Q=!this._rootConstraints||this._rootConstraints.maxWidth!==Z.maxWidth||this._rootConstraints.maxHeight!==Z.maxHeight;if(this._rootConstraints=Z,Q&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){let J=!1;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),J=!0}return J}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 Boolean(this._rootRenderObject&&this._rootRenderObject.needsLayout)}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(J){this._nodesNeedingPaint.delete(J)}}class t4{static _instance;frameScheduler=C6.instance;buildOwner;pipelineOwner;focusManager=OZ.instance;mouseManager=A8.instance;frameStatsOverlay=new uo0;tui=new xo0;rootElement;isRunning=!1;rootElementMountedCallback;forcePaintOnNextFrame=!1;shouldPaintCurrentFrame=!1;didPaintCurrentFrame=!1;eventCallbacks={key:[],mouse:[],paste:[]};keyInterceptors=[];rgbColorChangeCallbacks=[];cachedRgbColors=null;static get instance(){return t4._instance??=new t4}pendingResizeEvent=null;constructor(){this.buildOwner=new fo0,this.pipelineOwner=new bo0,this.frameScheduler.addFrameCallback("frame-start",()=>this.beginFrame(),"build",-2000,"WidgetsBinding.beginFrame"),this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>{this.buildOwner.buildScopes(),this.updateRootRenderObject()},"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{if(this.updateRootConstraints(),this.pipelineOwner.flushLayout())this.shouldPaintCurrentFrame=!0},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),yP4({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)=>{P.error("Framework uncaught exception",J)})}getRgbColors(){return this.cachedRgbColors}onRgbColorsChanged(J){return this.rgbColorChangeCallbacks.push(J),()=>{let Z=this.rgbColorChangeCallbacks.indexOf(J);if(Z!==-1)this.rgbColorChangeCallbacks.splice(Z,1)}}notifyRgbColorsChanged(){for(let J of this.rgbColorChangeCallbacks)J()}updateRgbColors(J){this.cachedRgbColors=J;let Z=this.tui.getScreen();Z.setDefaultColors({type:"rgb",value:J.bg},{type:"rgb",value:J.fg}),Z.setIndexRgbMapping(J.indices),cY0(Lw(),J.bg),this.notifyRgbColorsChanged(),this.requestForcedPaintFrame()}async runApp(J){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Z}=await Promise.resolve().then(() => lT4);Z(this.tui);let{initIdleTracking:Q}=await Promise.resolve().then(() => (go0(),nT4));Q(this.tui),await this.tui.waitForCapabilities(1000);let Y=this.tui.getQueryParser(),X=Y?.getRgbColors();if(P.info("Initial RGB colors from terminal",{available:!!X}),X)this.updateRgbColors(X);if(Y)Y.setColorPaletteChangeCallback(()=>{let z=Y.getRgbColors();if(z)this.updateRgbColors(z)});let K=this.createMediaQueryWrapper(J);if(this.rootElement=K.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let V=this.rootElement.renderObject;if(!V&&this.rootElement.children.length>0)V=this.rootElement.children[0]?.renderObject;if(V)this.pipelineOwner.setRootRenderObject(V),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),P.debug("Setting up event handlers..."),this.setupEventHandlers(),P.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),P.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),P.debug("waitForExit completed")}finally{P.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)}updateRootRenderObject(){if(!this.rootElement)return;let J=this.rootElement.renderObject;if(!J&&this.rootElement.children.length>0)J=this.rootElement.children[0]?.renderObject;if(J)this.pipelineOwner.setRootRenderObject(J),this.mouseManager.setRootRenderObject(J)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let J=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Z={width:J.width,height:J.height},Q=this.tui.getCapabilities()||ii(),Y=new wv(Z,Q),X=this.rootElement;if(X.widget instanceof V4){let V=new V4({data:Y,child:X.widget.child});X.update(V)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Z),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}beginFrame(){this.didPaintCurrentFrame=!1,this.shouldPaintCurrentFrame=this.forcePaintOnNextFrame||this.buildOwner.hasDirtyElements||this.pipelineOwner.hasNodesNeedingLayout||this.pipelineOwner.hasNodesNeedingPaint||this.tui.getScreen().requiresFullRefresh,this.forcePaintOnNextFrame=!1}requestForcedPaintFrame(){this.forcePaintOnNextFrame=!0,this.frameScheduler.requestFrame()}paint(){if(!this.shouldPaintCurrentFrame)return;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 Z=this.tui.getScreen();Z.clear(),Z.clearCursor(),this.renderRenderObject(J,Z,0,0);let Q=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(Q,this.tui.getLastRenderDiffStats()),this.frameStatsOverlay.draw(Z,Q),this.didPaintCurrentFrame=!0}catch(Z){P.error("Paint error:",Z)}}render(){if(!this.didPaintCurrentFrame)return;try{this.tui.render()}catch(J){P.error("Render error:",J)}}renderRenderObject(J,Z,Q,Y){if("paint"in J&&typeof J.paint==="function")J.paint(Z,Q,Y)}createMediaQueryWrapper(J){let Z=this.tui.getCapabilities()||ii(),Q=this.tui.getSize(),Y=new wv(Q,Z);return new V4({data:Y,child:J})}setupEventHandlers(){this.tui.onResize((J)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=J,this.frameScheduler.requestFrame()}),this.tui.onKey((J)=>{let Z=performance.now();for(let X of this.eventCallbacks.key)X(J);for(let X of this.keyInterceptors)if(X(J)){let K=performance.now()-Z;this.frameStatsOverlay.recordKeyEvent(K);return}if(this.focusManager.handleKeyEvent(J)){let X=performance.now()-Z;this.frameStatsOverlay.recordKeyEvent(X);return}this.handleGlobalKeyEvent(J);let Y=performance.now()-Z;this.frameStatsOverlay.recordKeyEvent(Y)}),this.tui.onMouse((J)=>{let Z=performance.now();for(let Y of this.eventCallbacks.mouse)Y(J);this.mouseManager.handleMouseEvent(J);let Q=performance.now()-Z;this.frameStatsOverlay.recordMouseEvent(Q)}),this.tui.onPaste((J)=>{for(let Z of this.eventCallbacks.paste)Z(J);this.focusManager.handlePasteEvent(J)}),this.tui.onCapabilities((J)=>{if(this.rootElement){let Z=this.tui.getSize(),Q=new wv(Z,J.capabilities),Y=this.rootElement;if(Y.widget instanceof V4){let X=new V4({data:Q,child:Y.widget.child});Y.update(X)}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.requestForcedPaintFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise!==null)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("frame-start"),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}on(J,Z){let Q=this.eventCallbacks[J];return Q.push(Z),()=>{let Y=Q.indexOf(Z);if(Y!==-1)Q.splice(Y,1)}}dispatchSyntheticPaste(J){this.tui.dispatchSyntheticPaste(J)}addKeyInterceptor(J){return this.keyInterceptors.push(J),()=>{let Z=this.keyInterceptors.indexOf(J);if(Z!==-1)this.keyInterceptors.splice(Z,1)}}}async function mo0(J,Z){let Q=t4.instance;if(Z?.onRootElementMounted)Q.setRootElementMountedCallback(Z.onRootElementMounted);await Q.runApp(J)}class po0{async runInTerminal(J,Z){let Y=t4.instance.tuiInstance;if(Y.isInitialized()&&!Y.isSuspended())Y.suspend();try{await new Promise((X,K)=>{let V=Wz3(J,{shell:!0,cwd:Z,stdio:"inherit"});V.on("exit",(z)=>{if(z===0)X();else K(Error(`Command failed with exit code ${z}`))}),V.on("error",(z)=>{K(z)})})}finally{if(Y.isInitialized())Y.resume()}}}rJ();hP();import{stdout as kX0}from"node:process";/*!
6680
6680
  * decimal.js v10.5.0
6681
6681
  * An arbitrary-precision Decimal type for JavaScript.
@@ -7311,7 +7311,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
7311
7311
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
7312
7312
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7313
7313
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7314
- */function FE3(){let J=process.env.XDG_CONFIG_HOME||EV0.join(Yu4.homedir(),".config");return EV0.join(J,"amp","themes")}async function Xu4(){let J=FE3();if(!av.existsSync(J))return[];let Z=[],Q;try{Q=await av.promises.readdir(J,{withFileTypes:!0})}catch(Y){return P.warn("Failed to read custom themes directory",{themesDir:J,error:Y}),[]}for(let Y of Q){if(!Y.isDirectory())continue;let X=EV0.join(J,Y.name,"colors.toml");if(!av.existsSync(X))continue;try{let K=await qE3(X,Y.name);Z.push(K)}catch(K){P.warn("Failed to load custom theme",{dir:Y.name,error:K})}}return Z}async function qE3(J,Z){let Q=await av.promises.readFile(J,"utf-8"),Y=He0(Q);WE3(Y,Z);let X=HE3(Y);return{name:Y.name||Z,dirName:Z,palette:X,path:J}}function WE3(J,Z){let Q=[];if(!J.colors)Q.push("[colors]");else{let Y=["background","foreground","primary","success","warning","destructive"];for(let X of Y)if(!(X in J.colors))Q.push(`colors.${X}`)}if(Q.length>0)throw Error(`Theme "${Z}" missing required fields: ${Q.join(", ")}`)}function Ku4(J){if(!J.startsWith("#")||J.length!==7&&J.length!==9)throw Error(`Invalid hex color: ${J}`);let Z=parseInt(J.slice(1,3),16),Q=parseInt(J.slice(3,5),16),Y=parseInt(J.slice(5,7),16),X=J.length===9?parseInt(J.slice(7,9),16)/255:void 0;return{r:Z,g:Q,b:Y,a:X}}function D9(J){let{r:Z,g:Q,b:Y,a:X}=Ku4(J);return M0.rgb(Z,Q,Y,X)}function OV0(J,Z){if(J.type==="none")return J;return{...J,alpha:Z}}function UE3(J){let{r:Z,g:Q,b:Y}=Ku4(J);return(0.299*Z+0.587*Q+0.114*Y)/255}function HE3(J){let Z=J.colors,Q=J.ui||{},Y=J.syntax||{},X=Z.background==="none",K=J.mode==="light"||J.mode===void 0&&!X&&UE3(Z.background)>0.5,V=D9(Z.foreground),z=D9(Z.primary),G=D9(Z.warning),F=Q.muted_foreground?D9(Q.muted_foreground):OV0(V,0.6),q=Q.border?D9(Q.border):OV0(V,0.4);return{background:X?M0.none():D9(Z.background),foreground:V,cursor:Q.cursor?D9(Q.cursor):V,mutedForeground:F,border:q,selection:Q.selection?D9(Q.selection):OV0(q,0.3),primary:z,secondary:Z.secondary?D9(Z.secondary):z,accent:Z.accent?D9(Z.accent):z,success:D9(Z.success),warning:G,info:Z.info?D9(Z.info):z,destructive:D9(Z.destructive),copyHighlight:Q.copy_highlight?D9(Q.copy_highlight):G,tableBorder:Q.table_border?D9(Q.table_border):OV0(q,0.4),isLight:K,syntaxHighlight:{keyword:Y.keyword?D9(Y.keyword):z,string:Y.string?D9(Y.string):D9(Z.success),number:Y.number?D9(Y.number):G,comment:Y.comment?D9(Y.comment):F,function:Y.function?D9(Y.function):z,variable:Y.variable?D9(Y.variable):V,type:Y.type?D9(Y.type):G,operator:Y.operator?D9(Y.operator):V}}}class fQ extends s5{value;constructor({value:J,child:Z}){super({child:Z});this.value=Object.freeze(J)}updateShouldNotify(J){return!1}static maybeOf(J){return J.dependOnInheritedWidgetOfExactType(fQ)?.widget?.value}static require(J){let Z=fQ.maybeOf(J);if(!Z)throw Error("TuiContextProvider.require() called with a context that does not contain a TuiContextProvider.");return Z}}class De0 extends l0{dependencies;childBuilder;constructor(J,Z){super();this.dependencies=J;this.childBuilder=Z}createState(){return new Vu4}}class Vu4 extends p0{debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";threadHandleSubscription=null;activeThreadStateSubscription=null;activeToolProgressSubscription=null;recentThreadIDsSubscription=null;activeThreadState=nw();activeToolProgressByToolUseID=new Map;recentThreadIDs=[];activeThreadHandle=null;initState(){this.threadHandleSubscription=this.widget.dependencies.threadPool.threadHandles$.subscribe((J)=>{if(this.activeThreadStateSubscription?.unsubscribe(),this.activeThreadStateSubscription=null,this.activeToolProgressSubscription?.unsubscribe(),this.activeToolProgressSubscription=null,this.activeToolProgressByToolUseID=new Map,J)this.activeThreadStateSubscription=J.threadState$.subscribe((Z)=>{if(this.setState(()=>{this.activeThreadState=Z}),this.debugThreadViewState&&Z.mainThread){let Q=Z.mainThread.messages.at(-1);P.info("[tui-application] active thread state update",{threadID:Z.mainThread.id,messageCount:Z.mainThread.messages.length,lastMessageRole:Q?.role,lastMessageState:Q?.role==="assistant"?Q.state?.type:void 0,state:Z.viewState.state,inferenceState:Z.viewState.state==="active"?Z.viewState.inferenceState:void 0,interactionState:Z.viewState.interactionState,itemCount:Z.items.length})}}),this.activeToolProgressSubscription=J.toolProgressByToolUseID$.subscribe((Z)=>{this.setState(()=>{this.activeToolProgressByToolUseID=Z})});else this.activeThreadState=nw();this.setState(()=>{this.activeThreadHandle=J})}),this.recentThreadIDsSubscription=this.widget.dependencies.threadPool.recentThreadIDs$.subscribe((J)=>{this.setState(()=>{this.recentThreadIDs=J})})}dispose(){this.threadHandleSubscription?.unsubscribe(),this.activeThreadStateSubscription?.unsubscribe(),this.activeToolProgressSubscription?.unsubscribe(),this.recentThreadIDsSubscription?.unsubscribe()}build(){if(!this.activeThreadHandle||!this.activeThreadState.mainThread)return new d0;return this.widget.childBuilder({...this.widget.dependencies,activeThreadHandle:this.activeThreadHandle,threadState:this.activeThreadState,toolProgressByToolUseID:this.activeToolProgressByToolUseID,recentThreadIDs:this.recentThreadIDs})}}async function zu4(J,Z,Q){let Y=null,X={...J,setExitNotice:(M)=>{Y=M}},K=await X.configService.getLatest(),V=K.settings["terminal.animation"]===!1,z={windowsPasteHookEnabled:K.settings["windowsPasteHook.enabled"]??!0};if(V)z.queryOptions={animationDisabled:!0};t4.instance.tuiInstance.setOptions(z);let G=await Xu4();for(let M of G)af4(M.dirName,M.name,M.palette,M.path);let F=K.settings["terminal.theme"]??"terminal",q=X.threadPool,U=!1;if(U)process.env.AMP_INSPECTOR_ENABLED="1";let H=new wq(U,1000,Z.inspectorPort),D=Q(X),B=new fQ({value:Z,child:D}),N=new ze0({configService:X.configService,child:B}),w=new Ve0({configService:X.configService,child:N}),L=new We0(F),O=X.configService.config.pipe(D1((M)=>M.settings["terminal.theme"]),b4()).subscribe((M)=>{L.setThemeName(M??"terminal")}),E=new Ue0({controller:L,child:w});try{await mo0(E,{onRootElementMounted:(M)=>{let A=Number(process.hrtime.bigint()-QO4)/1e6;if(P.info(`Boot complete: ${A.toFixed(0)}ms to interactive`),U)H.start(M),yf4(M)}})}finally{if(O.unsubscribe(),U)H.stop(),xf4();let M=await j1(q.threadHandles$).catch(()=>null),j=(M?await j1(M.thread$).catch(()=>null):null)?.id;if(j){let R=await X.threadService.get(j);if(R&&R.messages.length>0){let _=`${Z.ampURL.replace(/\/$/,"")}/threads/${j}`;Rf4(R,_,Z.stdout,Y)}}if(Y)Z.stdout.write(`${Y}
7314
+ */function FE3(){let J=process.env.XDG_CONFIG_HOME||EV0.join(Yu4.homedir(),".config");return EV0.join(J,"amp","themes")}async function Xu4(){let J=FE3();if(!av.existsSync(J))return[];let Z=[],Q;try{Q=await av.promises.readdir(J,{withFileTypes:!0})}catch(Y){return P.warn("Failed to read custom themes directory",{themesDir:J,error:Y}),[]}for(let Y of Q){if(!Y.isDirectory())continue;let X=EV0.join(J,Y.name,"colors.toml");if(!av.existsSync(X))continue;try{let K=await qE3(X,Y.name);Z.push(K)}catch(K){P.warn("Failed to load custom theme",{dir:Y.name,error:K})}}return Z}async function qE3(J,Z){let Q=await av.promises.readFile(J,"utf-8"),Y=He0(Q);WE3(Y,Z);let X=HE3(Y);return{name:Y.name||Z,dirName:Z,palette:X,path:J}}function WE3(J,Z){let Q=[];if(!J.colors)Q.push("[colors]");else{let Y=["background","foreground","primary","success","warning","destructive"];for(let X of Y)if(!(X in J.colors))Q.push(`colors.${X}`)}if(Q.length>0)throw Error(`Theme "${Z}" missing required fields: ${Q.join(", ")}`)}function Ku4(J){if(!J.startsWith("#")||J.length!==7&&J.length!==9)throw Error(`Invalid hex color: ${J}`);let Z=parseInt(J.slice(1,3),16),Q=parseInt(J.slice(3,5),16),Y=parseInt(J.slice(5,7),16),X=J.length===9?parseInt(J.slice(7,9),16)/255:void 0;return{r:Z,g:Q,b:Y,a:X}}function D9(J){let{r:Z,g:Q,b:Y,a:X}=Ku4(J);return M0.rgb(Z,Q,Y,X)}function OV0(J,Z){if(J.type==="none")return J;return{...J,alpha:Z}}function UE3(J){let{r:Z,g:Q,b:Y}=Ku4(J);return(0.299*Z+0.587*Q+0.114*Y)/255}function HE3(J){let Z=J.colors,Q=J.ui||{},Y=J.syntax||{},X=Z.background==="none",K=J.mode==="light"||J.mode===void 0&&!X&&UE3(Z.background)>0.5,V=D9(Z.foreground),z=D9(Z.primary),G=D9(Z.warning),F=Q.muted_foreground?D9(Q.muted_foreground):OV0(V,0.6),q=Q.border?D9(Q.border):OV0(V,0.4);return{background:X?M0.none():D9(Z.background),foreground:V,cursor:Q.cursor?D9(Q.cursor):V,mutedForeground:F,border:q,selection:Q.selection?D9(Q.selection):OV0(q,0.3),primary:z,secondary:Z.secondary?D9(Z.secondary):z,accent:Z.accent?D9(Z.accent):z,success:D9(Z.success),warning:G,info:Z.info?D9(Z.info):z,destructive:D9(Z.destructive),copyHighlight:Q.copy_highlight?D9(Q.copy_highlight):G,tableBorder:Q.table_border?D9(Q.table_border):OV0(q,0.4),isLight:K,syntaxHighlight:{keyword:Y.keyword?D9(Y.keyword):z,string:Y.string?D9(Y.string):D9(Z.success),number:Y.number?D9(Y.number):G,comment:Y.comment?D9(Y.comment):F,function:Y.function?D9(Y.function):z,variable:Y.variable?D9(Y.variable):V,type:Y.type?D9(Y.type):G,operator:Y.operator?D9(Y.operator):V}}}class fQ extends s5{value;constructor({value:J,child:Z}){super({child:Z});this.value=Object.freeze(J)}updateShouldNotify(J){return!1}static maybeOf(J){return J.dependOnInheritedWidgetOfExactType(fQ)?.widget?.value}static require(J){let Z=fQ.maybeOf(J);if(!Z)throw Error("TuiContextProvider.require() called with a context that does not contain a TuiContextProvider.");return Z}}class De0 extends l0{dependencies;childBuilder;constructor(J,Z){super();this.dependencies=J;this.childBuilder=Z}createState(){return new Vu4}}class Vu4 extends p0{debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";threadHandleSubscription=null;activeThreadStateSubscription=null;activeToolProgressSubscription=null;recentThreadIDsSubscription=null;activeThreadState=nw();activeToolProgressByToolUseID=new Map;recentThreadIDs=[];activeThreadHandle=null;initState(){this.threadHandleSubscription=this.widget.dependencies.threadPool.threadHandles$.subscribe((J)=>{if(this.activeThreadStateSubscription?.unsubscribe(),this.activeThreadStateSubscription=null,this.activeToolProgressSubscription?.unsubscribe(),this.activeToolProgressSubscription=null,this.activeToolProgressByToolUseID=new Map,J)this.activeThreadStateSubscription=J.threadState$.subscribe((Z)=>{if(this.setState(()=>{this.activeThreadState=Z}),this.debugThreadViewState&&Z.mainThread){let Q=Z.mainThread.messages.at(-1);P.info("[tui-application] active thread state update",{threadID:Z.mainThread.id,messageCount:Z.mainThread.messages.length,lastMessageRole:Q?.role,lastMessageState:Q?.role==="assistant"?Q.state?.type:void 0,state:Z.viewState.state,inferenceState:Z.viewState.state==="active"?Z.viewState.inferenceState:void 0,interactionState:Z.viewState.interactionState,itemCount:Z.items.length})}}),this.activeToolProgressSubscription=J.toolProgressByToolUseID$.subscribe((Z)=>{this.setState(()=>{this.activeToolProgressByToolUseID=Z})});else this.activeThreadState=nw();this.setState(()=>{this.activeThreadHandle=J})}),this.recentThreadIDsSubscription=this.widget.dependencies.threadPool.recentThreadIDs$.subscribe((J)=>{this.setState(()=>{this.recentThreadIDs=J})})}dispose(){this.threadHandleSubscription?.unsubscribe(),this.activeThreadStateSubscription?.unsubscribe(),this.activeToolProgressSubscription?.unsubscribe(),this.recentThreadIDsSubscription?.unsubscribe()}build(){if(!this.activeThreadHandle||!this.activeThreadState.mainThread)return new d0;return this.widget.childBuilder({...this.widget.dependencies,activeThreadHandle:this.activeThreadHandle,threadState:this.activeThreadState,toolProgressByToolUseID:this.activeToolProgressByToolUseID,recentThreadIDs:this.recentThreadIDs})}}async function zu4(J,Z,Q){let Y=null,X={...J,setExitNotice:(M)=>{Y=M}},K=await X.configService.getLatest(),V=K.settings["terminal.animation"]===!1,z={windowsPasteHookEnabled:K.settings["windowsPasteHook.enabled"]??!1};if(V)z.queryOptions={animationDisabled:!0};t4.instance.tuiInstance.setOptions(z);let G=await Xu4();for(let M of G)af4(M.dirName,M.name,M.palette,M.path);let F=K.settings["terminal.theme"]??"terminal",q=X.threadPool,U=!1;if(U)process.env.AMP_INSPECTOR_ENABLED="1";let H=new wq(U,1000,Z.inspectorPort),D=Q(X),B=new fQ({value:Z,child:D}),N=new ze0({configService:X.configService,child:B}),w=new Ve0({configService:X.configService,child:N}),L=new We0(F),O=X.configService.config.pipe(D1((M)=>M.settings["terminal.theme"]),b4()).subscribe((M)=>{L.setThemeName(M??"terminal")}),E=new Ue0({controller:L,child:w});try{await mo0(E,{onRootElementMounted:(M)=>{let A=Number(process.hrtime.bigint()-QO4)/1e6;if(P.info(`Boot complete: ${A.toFixed(0)}ms to interactive`),U)H.start(M),yf4(M)}})}finally{if(O.unsubscribe(),U)H.stop(),xf4();let M=await j1(q.threadHandles$).catch(()=>null),j=(M?await j1(M.thread$).catch(()=>null):null)?.id;if(j){let R=await X.threadService.get(j);if(R&&R.messages.length>0){let _=`${Z.ampURL.replace(/\/$/,"")}/threads/${j}`;Rf4(R,_,Z.stdout,Y)}}if(Y)Z.stdout.write(`${Y}
7315
7315
  `);if(Z.stdout.write(oY0("")),DE3())Z.stdout.write(rP4())}}function DE3(){return!1}import{execFile as b_3}from"node:child_process";import{randomBytes as vd4}from"node:crypto";import{mkdtemp as h_3,readFile as g_3,rmdir as m_3,unlink as yd4,writeFile as p_3}from"node:fs/promises";import{homedir as d_3,tmpdir as c_3}from"node:os";import bq from"node:path";O1();m0();var Gu4=30000,Fu4=180000;function Be0(J,Z=Date.now()){return Z-J<Fu4}function Ne0(J,Z,Q=()=>!0,Y,X){let K=null,V=[],z=5;return aZ(k0.of(void 0),sP(Gu4).pipe(T5(()=>Q()))).pipe(H4(()=>k4(async(G)=>{let F=X?.(),q=await Y?.getContext(F);P.debug("[Ads] Fetching ad from server",{hasContext:!!q});let W=await J.getCurrentAd({context:q,excludeAdIds:V},{config:Z,signal:G});if(!W.ok)throw P.error("[Ads] Failed to fetch ad",{error:W.error.message}),Error(W.error.message);if(W.result){if(K=W.result,V.length>=z)V.shift();V.push(K.id),P.debug("[Ads] Received ad from server",{adTitle:K.title,matchType:K.metadata?.matchType,matchedPatterns:K.metadata?.matchedPatterns,candidateAdPoolCount:K.metadata?.candidateAdPoolCount,recentlyShownCount:V.length})}else P.debug("[Ads] No ad available from server");return K})),b4((G,F)=>G?.id===F?.id&&G?.impressionId===F?.impressionId))}m0();_7();aP();RW();N$();y3();Nd();hM();function qu4(J,Z){let Q;return function(...X){let K=()=>{clearTimeout(Q),J(...X)};clearTimeout(Q),Q=setTimeout(K,Z)}}O1();var we0,BE3=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),Wu4=(we0=String.fromCodePoint)!==null&&we0!==void 0?we0:(J)=>{let Z="";if(J>65535)J-=65536,Z+=String.fromCharCode(J>>>10&1023|55296),J=56320|J&1023;return Z+=String.fromCharCode(J),Z};function Uu4(J){var Z;if(J>=55296&&J<=57343||J>1114111)return 65533;return(Z=BE3.get(J))!==null&&Z!==void 0?Z:J}function MV0(J){let Z=typeof atob==="function"?atob(J):typeof Buffer.from==="function"?Buffer.from(J,"base64").toString("binary"):new Buffer(J,"base64").toString("binary"),Q=Z.length&-2,Y=new Uint16Array(Q/2);for(let X=0,K=0;X<Q;X+=2){let V=Z.charCodeAt(X),z=Z.charCodeAt(X+1);Y[K++]=V|z<<8}return Y}var Hu4=MV0("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1x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5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var Du4=MV0("AAJhZ2xxBwARABMAFQBtAg0AAAAAAA8AcAAmYG8AcwAnYHQAPmB0ADxg9SFvdCJg");var TJ;(function(J){J[J.VALUE_LENGTH=49152]="VALUE_LENGTH",J[J.FLAG13=8192]="FLAG13",J[J.BRANCH_LENGTH=8064]="BRANCH_LENGTH",J[J.JUMP_TABLE=127]="JUMP_TABLE"})(TJ||(TJ={}));var k9;(function(J){J[J.NUM=35]="NUM",J[J.SEMI=59]="SEMI",J[J.EQUALS=61]="EQUALS",J[J.ZERO=48]="ZERO",J[J.NINE=57]="NINE",J[J.LOWER_A=97]="LOWER_A",J[J.LOWER_F=102]="LOWER_F",J[J.LOWER_X=120]="LOWER_X",J[J.LOWER_Z=122]="LOWER_Z",J[J.UPPER_A=65]="UPPER_A",J[J.UPPER_F=70]="UPPER_F",J[J.UPPER_Z=90]="UPPER_Z"})(k9||(k9={}));var Bu4=32;function Le0(J){return J>=k9.ZERO&&J<=k9.NINE}function NE3(J){return J>=k9.UPPER_A&&J<=k9.UPPER_F||J>=k9.LOWER_A&&J<=k9.LOWER_F}function wE3(J){return J>=k9.UPPER_A&&J<=k9.UPPER_Z||J>=k9.LOWER_A&&J<=k9.LOWER_Z||Le0(J)}function LE3(J){return J===k9.EQUALS||wE3(J)}var J$;(function(J){J[J.EntityStart=0]="EntityStart",J[J.NumericStart=1]="NumericStart",J[J.NumericDecimal=2]="NumericDecimal",J[J.NumericHex=3]="NumericHex",J[J.NamedEntity=4]="NamedEntity"})(J$||(J$={}));var Sq;(function(J){J[J.Legacy=0]="Legacy",J[J.Strict=1]="Strict",J[J.Attribute=2]="Attribute"})(Sq||(Sq={}));class Oe0{constructor(J,Z,Q){this.decodeTree=J,this.emitCodePoint=Z,this.errors=Q,this.state=J$.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Sq.Strict}startEntity(J){this.decodeMode=J,this.state=J$.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(J,Z){switch(this.state){case J$.EntityStart:{if(J.charCodeAt(Z)===k9.NUM)return this.state=J$.NumericStart,this.consumed+=1,this.stateNumericStart(J,Z+1);return this.state=J$.NamedEntity,this.stateNamedEntity(J,Z)}case J$.NumericStart:return this.stateNumericStart(J,Z);case J$.NumericDecimal:return this.stateNumericDecimal(J,Z);case J$.NumericHex:return this.stateNumericHex(J,Z);case J$.NamedEntity:return this.stateNamedEntity(J,Z)}}stateNumericStart(J,Z){if(Z>=J.length)return-1;if((J.charCodeAt(Z)|Bu4)===k9.LOWER_X)return this.state=J$.NumericHex,this.consumed+=1,this.stateNumericHex(J,Z+1);return this.state=J$.NumericDecimal,this.stateNumericDecimal(J,Z)}stateNumericHex(J,Z){while(Z<J.length){let Q=J.charCodeAt(Z);if(Le0(Q)||NE3(Q)){let Y=Q<=k9.NINE?Q-k9.ZERO:(Q|Bu4)-k9.LOWER_A+10;this.result=this.result*16+Y,this.consumed++,Z++}else return this.emitNumericEntity(Q,3)}return-1}stateNumericDecimal(J,Z){while(Z<J.length){let Q=J.charCodeAt(Z);if(Le0(Q))this.result=this.result*10+(Q-k9.ZERO),this.consumed++,Z++;else return this.emitNumericEntity(Q,2)}return-1}emitNumericEntity(J,Z){var Q;if(this.consumed<=Z)return(Q=this.errors)===null||Q===void 0||Q.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(J===k9.SEMI)this.consumed+=1;else if(this.decodeMode===Sq.Strict)return 0;if(this.emitCodePoint(Uu4(this.result),this.consumed),this.errors){if(J!==k9.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}stateNamedEntity(J,Z){let{decodeTree:Q}=this,Y=Q[this.treeIndex],X=(Y&TJ.VALUE_LENGTH)>>14;while(Z<J.length){if(X===0&&(Y&TJ.FLAG13)!==0){let V=(Y&TJ.BRANCH_LENGTH)>>7,z=Y&TJ.JUMP_TABLE;if(Z+V>J.length)return-1;if(J.charCodeAt(Z)!==z)return this.result===0?0:this.emitNotTerminatedNamedEntity();Z++,this.excess++;let G=V-1;for(let F=1;F<V;F+=2){let q=Q[this.treeIndex+1+(F-1>>1)],W=q&255;if(J.charCodeAt(Z)!==W)return this.result===0?0:this.emitNotTerminatedNamedEntity();Z++,this.excess++;let U=q>>8&255;if(F+1<V){if(J.charCodeAt(Z)!==U)return this.result===0?0:this.emitNotTerminatedNamedEntity();Z++,this.excess++}}this.treeIndex+=1+(G+1>>1),Y=Q[this.treeIndex],X=(Y&TJ.VALUE_LENGTH)>>14}if(Z>=J.length)break;let K=J.charCodeAt(Z);if(K===k9.SEMI&&X!==0&&(Y&TJ.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,X,this.consumed+this.excess);if(this.treeIndex=OE3(Q,Y,this.treeIndex+Math.max(1,X),K),this.treeIndex<0)return this.result===0||this.decodeMode===Sq.Attribute&&(X===0||LE3(K))?0:this.emitNotTerminatedNamedEntity();if(Y=Q[this.treeIndex],X=(Y&TJ.VALUE_LENGTH)>>14,X!==0){if(K===k9.SEMI)return this.emitNamedEntityData(this.treeIndex,X,this.consumed+this.excess);if(this.decodeMode!==Sq.Strict&&(Y&TJ.FLAG13)===0)this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0}Z++,this.excess++}return-1}emitNotTerminatedNamedEntity(){var J;let{result:Z,decodeTree:Q}=this,Y=(Q[Z]&TJ.VALUE_LENGTH)>>14;return this.emitNamedEntityData(Z,Y,this.consumed),(J=this.errors)===null||J===void 0||J.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(J,Z,Q){let{decodeTree:Y}=this;if(this.emitCodePoint(Z===1?Y[J]&~(TJ.VALUE_LENGTH|TJ.FLAG13):Y[J+1],Q),Z===3)this.emitCodePoint(Y[J+2],Q);return Q}end(){var J;switch(this.state){case J$.NamedEntity:return this.result!==0&&(this.decodeMode!==Sq.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case J$.NumericDecimal:return this.emitNumericEntity(0,2);case J$.NumericHex:return this.emitNumericEntity(0,3);case J$.NumericStart:return(J=this.errors)===null||J===void 0||J.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case J$.EntityStart:return 0}}}function Nu4(J){let Z="",Q=new Oe0(J,(Y)=>Z+=Wu4(Y));return function(X,K){let V=0,z=0;while((z=X.indexOf("&",z))>=0){Z+=X.slice(V,z),Q.startEntity(K);let F=Q.write(X,z+1);if(F<0){V=z+Q.end();break}V=z+F,z=F===0?V+1:V}let G=Z+X.slice(V);return Z="",G}}function OE3(J,Z,Q,Y){let X=(Z&TJ.BRANCH_LENGTH)>>7,K=Z&TJ.JUMP_TABLE;if(X===0)return K!==0&&Y===K?Q:-1;if(K){let F=Y-K;return F<0||F>=X?-1:J[Q+F]-1}let V=X+1>>1,z=0,G=X-1;while(z<=G){let F=z+G>>>1,q=F>>1,U=J[Q+q]>>(F&1)*8&255;if(U<Y)z=F+1;else if(U>Y)G=F-1;else return J[Q+V+F]}return-1}var EE3=Nu4(Hu4),ME3=Nu4(Du4);function Wa(J,Z=Sq.Legacy){return EE3(J,Z)}function AV0(J){return ME3(J,Sq.Strict)}var wu4;(function(J){J[J.XML=0]="XML",J[J.HTML=1]="HTML"})(wu4||(wu4={}));var Lu4;(function(J){J[J.UTF8=0]="UTF8",J[J.ASCII=1]="ASCII",J[J.Extensive=2]="Extensive",J[J.Attribute=3]="Attribute",J[J.Text=4]="Text"})(Lu4||(Lu4={}));var $X=(J)=>{return J!=null},$1=(J)=>{return J!=null&&typeof J==="object"&&!Array.isArray(J)&&J.constructor===Object},AE3=/^\p{White_Space}*$/u,_J=(J)=>{return typeof J==="string"&&J!==""&&!AE3.test(J)},GR=(J)=>{return typeof J==="number"||_J(J)},j0=(J)=>{return J?.["#text"]??J},e9=(J,Z)=>{if($1(J)){let Q=Z(J["@rdf:resource"]);if($X(Q))return Q;let Y=Z(J["@resource"]);if($X(Y))return Y}return Z(j0(J))},s0=(J)=>{let Z;for(let Q in J){let Y=J[Q];if($X(Y)){if(!Z)Z={};Z[Q]=Y}}return Z},Ua=(J,Z)=>{if(!Array.isArray(J)||J.length===0)return;if(!Z){let Y=!1;for(let X=0;X<J.length;X++)if(!$X(J[X])){Y=!0;break}if(!Y)return J}let Q=[];for(let Y=0;Y<J.length;Y++){let X=Z?Z(J[Y]):J[Y];if($X(X))Q.push(X)}return Q.length>0?Q:void 0};var Ee0="<![CDATA[",jE3="]]>",RE3=(J)=>{if(typeof J!=="string")return J;let Z=J.indexOf(Ee0);if(Z===-1)return J;let Q="",Y=0;while(Z!==-1){if(Q+=J.substring(Y,Z),Y=J.indexOf(jE3,Z+9),Y===-1)return J;Q+=J.substring(Z+9,Y),Y+=3,Z=J.indexOf(Ee0,Y)}return Q+=J.substring(Y),Q},Eu4=(J)=>{let Z=J.indexOf("&");return Z!==-1&&J.indexOf(";",Z)!==-1},V0=(J)=>{if(typeof J==="string"){if(J==="")return;let Z=J;if(J.indexOf(Ee0)!==-1)Z=RE3(J);if(Z=Z.trim(),Z==="")return;if(Eu4(Z)){if(Z=AV0(Z),Eu4(Z))Z=Wa(Z)}return Z||void 0}if(typeof J==="number")return J.toString()},F4=(J)=>{if(typeof J==="number")return J;if(_J(J)){let Z=+J;return Number.isNaN(Z)?void 0:Z}},IE3=/^\p{White_Space}*true\p{White_Space}*$/iu,PE3=/^\p{White_Space}*false\p{White_Space}*$/iu,CE3=/^\p{White_Space}*yes\p{White_Space}*$/iu,d$=(J)=>{if(typeof J==="boolean")return J;if(_J(J)){if(IE3.test(J))return!0;if(PE3.test(J))return!1}},SJ=(J)=>{let Z=d$(J);if(Z!==void 0)return Z;if(_J(J))return CE3.test(J)},L5=(J)=>{return V0(J)},TE3=(J)=>{if(Array.isArray(J))return J;if(!$1(J))return;if(J.length)return Array.from(J);let Z=Object.keys(J);if(Z.length===0)return;for(let Q=0;Q<Z.length;Q++){let Y=Z[Q],X=Number(Y);if(!Number.isInteger(X)||X!==Q)return}return Object.values(J)},q1=(J,Z,Q)=>{let Y=TE3(J);if(!Y&&$X(J))Y=[J];if(Y)return Ua(_E3(Y,Q),Z)},_E3=(J,Z)=>{if(Z===void 0||Z<0)return J;if(Z===0)return[];return J.slice(0,Z)},Me0=(J)=>{return Array.isArray(J)?J[0]:J},N0=(J,Z)=>{return Z(Me0(J))},tw=(J,Z)=>{if(!GR(J))return;let Q=V0(J)?.split(",");if(Q)return Ua(Q,Z)};var dz=(J,Z=!1)=>{let Q=new Set,Y=new Set,X=(K)=>{if(Array.isArray(K)){for(let V of K)X(V);return}if($1(K))for(let V in K){if(Y.has(V))continue;Y.add(V);let z=V.charCodeAt(0)===64?V.slice(1):V,G=z.indexOf(":");if(G>0)Q.add(z.slice(0,G));if(Z)X(K[V])}};return X(J),Q};var ov=(J,Z,Q)=>{let Y=(W)=>{return typeof W==="string"?W.trim().toLowerCase():W},X=Q&&J[Q]?J[Q].map(Y):void 0,K=(W,U,H)=>{let D=Y(W);if(X?.includes(D))return U;let B=Z[D];if(B)return`${B}:${U}`;return H},V=(W)=>{let U={};if($1(W)){for(let H in W)if(H==="@xmlns")U[""]=Y(W[H]);else if(H.indexOf("@xmlns:")===0){let D=H.substring(7);U[D]=Y(W[H])}}return U},z=(W,U,H=!1)=>{let D=W.indexOf(":");if(D===-1){if(H&&U[""])return K(U[""],W,W);return W}let B=W.substring(0,D),N=W.substring(D+1),w=U[B];if(w)return K(w,N,W);return W},G=(W,U)=>{if(W.charCodeAt(0)===64)return`@${z(W.substring(1),U,!1)}`;return z(W,U,!0)},F=(W,U={})=>{if(!$1(W))return W;if(Array.isArray(W))return W.map((w)=>F(w,U));let H={},D=new Map,B=V(W),N={...U,...B};for(let w in W){let L=W[w];if(w.indexOf("@xmlns")===0){H[w]=L;continue}let O=G(w,N),E=F(L,N);if(!D.has(O))D.set(O,[]);let M=D.get(O);if(M)M.push(E)}for(let[w,L]of D)H[w]=L.length===1?L[0]:L;return H},q=(W)=>{if(!$1(W))return W;if(Array.isArray(W))return W.map(q);let U={};for(let H in W){let D=W[H],B=V(D),N=Object.keys(B).length?G(H,B):H;U[N]=F(D)}return U};return q},rv=(J)=>{if($1(J))return J;if(!_J(J)||J.length<2)return;let Z=J.charAt(0)==="{"||/^\s*\{/.test(J),Q=J.charAt(J.length-1)==="}"||/\}\s*$/.test(J);if(!Z||!Q)return;try{return JSON.parse(J)}catch{}};var jV0=(J)=>{if(!_J(J))return!1;if(!/(?:^|[\s>])<(?:\w+:)?feed[\s>]/im.test(J))return!1;let Z=J.includes("http://www.w3.org/2005/Atom"),Q=/(<(?:\w+:)?(entry|title|link|id|updated|summary)[\s>])/i.test(J);return Z||Q};var sv={trimValues:!1,processEntities:!1,htmlEntities:!1,parseTagValue:!1,parseAttributeValue:!1,alwaysCreateTextNode:!1,ignoreAttributes:!1,ignorePiTags:!0,ignoreDeclaration:!0,attributeNamePrefix:"@",transformTagName:(J)=>J.toLowerCase(),transformAttributeName:(J)=>J.toLowerCase()};var uQ={unrecognizedFeedFormat:"Unrecognized feed format",invalidFeedFormat:"Invalid feed format",invalidOpmlFormat:"Invalid OPML format",invalidInputOpml:"Invalid input OPML",invalidInputAtom:"Invalid input Atom",invalidInputRss:"Invalid input RSS"},FR={admin:["http://webns.net/mvcb/","https://webns.net/mvcb/","http://webns.net/mvcb","https://webns.net/mvcb"],atom:["http://www.w3.org/2005/Atom","https://www.w3.org/2005/Atom","http://www.w3.org/2005/Atom/","https://www.w3.org/2005/Atom/","http://purl.org/atom/ns#","https://purl.org/atom/ns#"],app:["http://www.w3.org/2007/app","https://www.w3.org/2007/app","http://www.w3.org/2007/app/","https://www.w3.org/2007/app/"],dc:["http://purl.org/dc/elements/1.1/","https://purl.org/dc/elements/1.1/","http://purl.org/dc/elements/1.1","https://purl.org/dc/elements/1.1","http://dublincore.org/documents/dcmi-namespace/","https://dublincore.org/documents/dcmi-namespace/","http://dublincore.org/documents/dcmi-namespace","https://dublincore.org/documents/dcmi-namespace","http://purl.org/dc/elements/1.0/","https://purl.org/dc/elements/1.0/","http://purl.org/dc/elements/1.0","https://purl.org/dc/elements/1.0"],sy:["http://purl.org/rss/1.0/modules/syndication/","https://purl.org/rss/1.0/modules/syndication/","http://purl.org/rss/1.0/modules/syndication","https://purl.org/rss/1.0/modules/syndication"],content:["http://purl.org/rss/1.0/modules/content/","https://purl.org/rss/1.0/modules/content/","http://purl.org/rss/1.0/modules/content","https://purl.org/rss/1.0/modules/content"],creativeCommons:["http://backend.userland.com/creativeCommonsRssModule","https://backend.userland.com/creativeCommonsRssModule","http://backend.userland.com/creativeCommonsRssModule/","https://backend.userland.com/creativeCommonsRssModule/","http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html","https://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html","http://cyber.law.harvard.edu/rss/creativeCommonsRssModule","https://cyber.law.harvard.edu/rss/creativeCommonsRssModule"],slash:["http://purl.org/rss/1.0/modules/slash/","https://purl.org/rss/1.0/modules/slash/","http://purl.org/rss/1.0/modules/slash","https://purl.org/rss/1.0/modules/slash"],itunes:["http://www.itunes.com/dtds/podcast-1.0.dtd","https://www.itunes.com/dtds/podcast-1.0.dtd"],podcast:["https://podcastindex.org/namespace/1.0","http://podcastindex.org/namespace/1.0","https://podcastindex.org/namespace/1.0/","http://podcastindex.org/namespace/1.0/","https://github.com/Podcastindex-org/podcast-namespace/blob/main/docs/1.0.md"],psc:["http://podlove.org/simple-chapters","https://podlove.org/simple-chapters","http://podlove.org/simple-chapters/","https://podlove.org/simple-chapters/"],media:["http://search.yahoo.com/mrss/","https://search.yahoo.com/mrss/","http://search.yahoo.com/mrss","https://search.yahoo.com/mrss","http://video.search.yahoo.com/mrss","http://video.search.yahoo.com/mrss/","https://video.search.yahoo.com/mrss","https://video.search.yahoo.com/mrss/","http://www.rssboard.org/media-rss","http://www.rssboard.org/media-rss/","https://www.rssboard.org/media-rss","https://www.rssboard.org/media-rss/","http://search.yahoo.com/searchmonkey/media/","https://search.yahoo.com/searchmonkey/media/","http://search.yahoo.com/searchmonkey/media","https://search.yahoo.com/searchmonkey/media","http://tools.search.yahoo.com/mrss/","https://tools.search.yahoo.com/mrss/","http://tools.search.yahoo.com/mrss","https://tools.search.yahoo.com/mrss"],georss:["http://www.georss.org/georss","http://www.georss.org/georss/","https://www.georss.org/georss","https://www.georss.org/georss/"],geo:["http://www.w3.org/2003/01/geo/wgs84_pos#","https://www.w3.org/2003/01/geo/wgs84_pos#"],thr:["http://purl.org/syndication/thread/1.0","https://purl.org/syndication/thread/1.0","http://purl.org/syndication/thread/1.0/","https://purl.org/syndication/thread/1.0/","http://purl.org/rss/1.0/modules/threading/","https://purl.org/rss/1.0/modules/threading/","http://purl.org/rss/1.0/modules/threading","https://purl.org/rss/1.0/modules/threading"],dcterms:["http://purl.org/dc/terms/","https://purl.org/dc/terms/","http://purl.org/dc/terms","https://purl.org/dc/terms","http://dublincore.org/documents/dcmi-terms/","https://dublincore.org/documents/dcmi-terms/","http://dublincore.org/documents/dcmi-terms","https://dublincore.org/documents/dcmi-terms","http://dublincore.org/specifications/dublin-core/dcmi-terms/","https://dublincore.org/specifications/dublin-core/dcmi-terms/","http://dublincore.org/specifications/dublin-core/dcmi-terms","https://dublincore.org/specifications/dublin-core/dcmi-terms"],wfw:["http://wellformedweb.org/CommentAPI/","https://wellformedweb.org/CommentAPI/","http://wellformedweb.org/CommentAPI","https://wellformedweb.org/CommentAPI"],source:["http://source.scripting.com/","https://source.scripting.com/","http://source.scripting.com","https://source.scripting.com"],feedpress:["https://feed.press/xmlns","http://feed.press/xmlns","https://feed.press/xmlns/","http://feed.press/xmlns/","https://feedpress.com/xmlns","http://feedpress.com/xmlns","https://feedpress.com/xmlns/","http://feedpress.com/xmlns/","http://feedpress.it/xmlns","https://feedpress.it/xmlns","http://feedpress.it/xmlns/","https://feedpress.it/xmlns/"],yt:["http://www.youtube.com/xml/schemas/2015","https://www.youtube.com/xml/schemas/2015","http://www.youtube.com/xml/schemas/2015/","https://www.youtube.com/xml/schemas/2015/"],googleplay:["https://www.google.com/schemas/play-podcasts/1.0/","http://www.google.com/schemas/play-podcasts/1.0/","https://www.google.com/schemas/play-podcasts/1.0","http://www.google.com/schemas/play-podcasts/1.0","https://www.google.com/schemas/play-podcasts/1.0/play-podcasts.xsd","http://www.google.com/schemas/play-podcasts/1.0/play-podcasts.xsd"],spotify:["http://www.spotify.com/ns/rss","https://www.spotify.com/ns/rss","http://www.spotify.com/ns/rss/","https://www.spotify.com/ns/rss/"],rdf:["http://www.w3.org/1999/02/22-rdf-syntax-ns#","https://www.w3.org/1999/02/22-rdf-syntax-ns#"],rawvoice:["http://www.rawvoice.com/rawvoiceRssModule/","https://www.rawvoice.com/rawvoiceRssModule/","http://www.rawvoice.com/rawvoiceRssModule","https://www.rawvoice.com/rawvoiceRssModule","https://blubrry.com/developer/rawvoice-rss","http://blubrry.com/developer/rawvoice-rss","https://blubrry.com/developer/rawvoice-rss/","http://blubrry.com/developer/rawvoice-rss/"],cc:["http://creativecommons.org/ns#","https://creativecommons.org/ns#","http://web.resource.org/cc/","https://web.resource.org/cc/","http://web.resource.org/cc","https://web.resource.org/cc"],opensearch:["http://a9.com/-/spec/opensearch/1.1/","https://a9.com/-/spec/opensearch/1.1/","http://a9.com/-/spec/opensearch/1.0/","https://a9.com/-/spec/opensearch/1.0/","http://a9.com/-/spec/opensearchrss/1.0/","https://a9.com/-/spec/opensearchrss/1.0/"],arxiv:["http://arxiv.org/schemas/atom","https://arxiv.org/schemas/atom","http://arxiv.org/schemas/atom/","https://arxiv.org/schemas/atom/"],pingback:["http://madskills.com/public/xml/rss/module/pingback/","https://madskills.com/public/xml/rss/module/pingback/","http://madskills.com/public/xml/rss/module/pingback","https://madskills.com/public/xml/rss/module/pingback"],trackback:["http://madskills.com/public/xml/rss/module/trackback/","https://madskills.com/public/xml/rss/module/trackback/","http://madskills.com/public/xml/rss/module/trackback","https://madskills.com/public/xml/rss/module/trackback"]},tv=Object.entries(FR).reduce((J,[Z,Q])=>{for(let Y of Q){let X=Y.toLowerCase();J[X]=Z.toLowerCase()}return J},{});var SE3=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",kE3="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+SE3+"]*",vE3=new RegExp("^"+kE3+"$");function RV0(J,Z){let Q=[],Y=Z.exec(J);while(Y){let X=[];X.startIndex=Z.lastIndex-Y[0].length;let K=Y.length;for(let V=0;V<K;V++)X.push(Y[V]);Q.push(X),Y=Z.exec(J)}return Q}var ev=function(J){let Z=vE3.exec(J);return!(Z===null||typeof Z>"u")};function Mu4(J){return typeof J<"u"}var yE3={allowBooleanAttributes:!1,unpairedTags:[]};function Pu4(J,Z){Z=Object.assign({},yE3,Z);let Q=[],Y=!1,X=!1;if(J[0]==="\uFEFF")J=J.substr(1);for(let K=0;K<J.length;K++)if(J[K]==="<"&&J[K+1]==="?"){if(K+=2,K=ju4(J,K),K.err)return K}else if(J[K]==="<"){let V=K;if(K++,J[K]==="!"){K=Ru4(J,K);continue}else{let z=!1;if(J[K]==="/")z=!0,K++;let G="";for(;K<J.length&&J[K]!==">"&&J[K]!==" "&&J[K]!=="\t"&&J[K]!==`
7316
7316
  `&&J[K]!=="\r";K++)G+=J[K];if(G=G.trim(),G[G.length-1]==="/")G=G.substring(0,G.length-1),K--;if(!pE3(G)){let W;if(G.trim().length===0)W="Invalid space after '<'.";else W="Tag '"+G+"' is an invalid name.";return A7("InvalidTag",W,RZ(J,K))}let F=uE3(J,K);if(F===!1)return A7("InvalidAttr","Attributes for '"+G+"' have open quote.",RZ(J,K));let q=F.value;if(K=F.index,q[q.length-1]==="/"){let W=K-q.length;q=q.substring(0,q.length-1);let U=Iu4(q,Z);if(U===!0)Y=!0;else return A7(U.err.code,U.err.msg,RZ(J,W+U.err.line))}else if(z)if(!F.tagClosed)return A7("InvalidTag","Closing tag '"+G+"' doesn't have proper closing.",RZ(J,K));else if(q.trim().length>0)return A7("InvalidTag","Closing tag '"+G+"' can't have attributes or invalid starting.",RZ(J,V));else if(Q.length===0)return A7("InvalidTag","Closing tag '"+G+"' has not been opened.",RZ(J,V));else{let W=Q.pop();if(G!==W.tagName){let U=RZ(J,W.tagStartPos);return A7("InvalidTag","Expected closing tag '"+W.tagName+"' (opened in line "+U.line+", col "+U.col+") instead of closing tag '"+G+"'.",RZ(J,V))}if(Q.length==0)X=!0}else{let W=Iu4(q,Z);if(W!==!0)return A7(W.err.code,W.err.msg,RZ(J,K-q.length+W.err.line));if(X===!0)return A7("InvalidXml","Multiple possible root nodes found.",RZ(J,K));else if(Z.unpairedTags.indexOf(G)!==-1);else Q.push({tagName:G,tagStartPos:V});Y=!0}for(K++;K<J.length;K++)if(J[K]==="<")if(J[K+1]==="!"){K++,K=Ru4(J,K);continue}else if(J[K+1]==="?"){if(K=ju4(J,++K),K.err)return K}else break;else if(J[K]==="&"){let W=gE3(J,K);if(W==-1)return A7("InvalidChar","char '&' is not expected.",RZ(J,K));K=W}else if(X===!0&&!Au4(J[K]))return A7("InvalidXml","Extra text at the end",RZ(J,K));if(J[K]==="<")K--}}else{if(Au4(J[K]))continue;return A7("InvalidChar","char '"+J[K]+"' is not expected.",RZ(J,K))}if(!Y)return A7("InvalidXml","Start tag expected.",1);else if(Q.length==1)return A7("InvalidTag","Unclosed tag '"+Q[0].tagName+"'.",RZ(J,Q[0].tagStartPos));else if(Q.length>0)return A7("InvalidXml","Invalid '"+JSON.stringify(Q.map((K)=>K.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function Au4(J){return J===" "||J==="\t"||J===`
7317
7317
  `||J==="\r"}function ju4(J,Z){let Q=Z;for(;Z<J.length;Z++)if(J[Z]=="?"||J[Z]==" "){let Y=J.substr(Q,Z-Q);if(Z>5&&Y==="xml")return A7("InvalidXml","XML declaration allowed only at the start of the document.",RZ(J,Z));else if(J[Z]=="?"&&J[Z+1]==">"){Z++;break}else continue}return Z}function Ru4(J,Z){if(J.length>Z+5&&J[Z+1]==="-"&&J[Z+2]==="-"){for(Z+=3;Z<J.length;Z++)if(J[Z]==="-"&&J[Z+1]==="-"&&J[Z+2]===">"){Z+=2;break}}else if(J.length>Z+8&&J[Z+1]==="D"&&J[Z+2]==="O"&&J[Z+3]==="C"&&J[Z+4]==="T"&&J[Z+5]==="Y"&&J[Z+6]==="P"&&J[Z+7]==="E"){let Q=1;for(Z+=8;Z<J.length;Z++)if(J[Z]==="<")Q++;else if(J[Z]===">"){if(Q--,Q===0)break}}else if(J.length>Z+9&&J[Z+1]==="["&&J[Z+2]==="C"&&J[Z+3]==="D"&&J[Z+4]==="A"&&J[Z+5]==="T"&&J[Z+6]==="A"&&J[Z+7]==="["){for(Z+=8;Z<J.length;Z++)if(J[Z]==="]"&&J[Z+1]==="]"&&J[Z+2]===">"){Z+=2;break}}return Z}var xE3='"',fE3="'";function uE3(J,Z){let Q="",Y="",X=!1;for(;Z<J.length;Z++){if(J[Z]===xE3||J[Z]===fE3)if(Y==="")Y=J[Z];else if(Y!==J[Z]);else Y="";else if(J[Z]===">"){if(Y===""){X=!0;break}}Q+=J[Z]}if(Y!=="")return!1;return{value:Q,index:Z,tagClosed:X}}var bE3=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Iu4(J,Z){let Q=RV0(J,bE3),Y={};for(let X=0;X<Q.length;X++){if(Q[X][1].length===0)return A7("InvalidAttr","Attribute '"+Q[X][2]+"' has no space in starting.",Ha(Q[X]));else if(Q[X][3]!==void 0&&Q[X][4]===void 0)return A7("InvalidAttr","Attribute '"+Q[X][2]+"' is without value.",Ha(Q[X]));else if(Q[X][3]===void 0&&!Z.allowBooleanAttributes)return A7("InvalidAttr","boolean attribute '"+Q[X][2]+"' is not allowed.",Ha(Q[X]));let K=Q[X][2];if(!mE3(K))return A7("InvalidAttr","Attribute '"+K+"' is an invalid name.",Ha(Q[X]));if(!Y.hasOwnProperty(K))Y[K]=1;else return A7("InvalidAttr","Attribute '"+K+"' is repeated.",Ha(Q[X]))}return!0}function hE3(J,Z){let Q=/\d/;if(J[Z]==="x")Z++,Q=/[\da-fA-F]/;for(;Z<J.length;Z++){if(J[Z]===";")return Z;if(!J[Z].match(Q))break}return-1}function gE3(J,Z){if(Z++,J[Z]===";")return-1;if(J[Z]==="#")return Z++,hE3(J,Z);let Q=0;for(;Z<J.length;Z++,Q++){if(J[Z].match(/\w/)&&Q<20)continue;if(J[Z]===";")break;return-1}return Z}function A7(J,Z,Q){return{err:{code:J,msg:Z,line:Q.line||Q,col:Q.col}}}function mE3(J){return ev(J)}function pE3(J){return ev(J)}function RZ(J,Z){let Q=J.substring(0,Z).split(/\r?\n/);return{line:Q.length,col:Q[Q.length-1].length+1}}function Ha(J){return J.startIndex+J[1].length}var dE3={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(J,Z){return Z},attributeValueProcessor:function(J,Z){return Z},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(J,Z,Q){return J},captureMetaData:!1},Cu4=function(J){return Object.assign({},dE3,J)};var IV0;if(typeof Symbol!=="function")IV0="@@xmlMetadata";else IV0=Symbol("XML Node Metadata");class lK{constructor(J){this.tagname=J,this.child=[],this[":@"]={}}add(J,Z){if(J==="__proto__")J="#__proto__";this.child.push({[J]:Z})}addChild(J,Z){if(J.tagname==="__proto__")J.tagname="#__proto__";if(J[":@"]&&Object.keys(J[":@"]).length>0)this.child.push({[J.tagname]:J.child,[":@"]:J[":@"]});else this.child.push({[J.tagname]:J.child});if(Z!==void 0)this.child[this.child.length-1][IV0]={startIndex:Z}}static getMetaDataSymbol(){return IV0}}class PV0{constructor(J){this.suppressValidationErr=!J}readDocType(J,Z){let Q={};if(J[Z+3]==="O"&&J[Z+4]==="C"&&J[Z+5]==="T"&&J[Z+6]==="Y"&&J[Z+7]==="P"&&J[Z+8]==="E"){Z=Z+9;let Y=1,X=!1,K=!1,V="";for(;Z<J.length;Z++)if(J[Z]==="<"&&!K){if(X&&qR(J,"!ENTITY",Z)){Z+=7;let z,G;if([z,G,Z]=this.readEntityExp(J,Z+1,this.suppressValidationErr),G.indexOf("&")===-1)Q[z]={regx:RegExp(`&${z};`,"g"),val:G}}else if(X&&qR(J,"!ELEMENT",Z)){Z+=8;let{index:z}=this.readElementExp(J,Z+1);Z=z}else if(X&&qR(J,"!ATTLIST",Z))Z+=8;else if(X&&qR(J,"!NOTATION",Z)){Z+=9;let{index:z}=this.readNotationExp(J,Z+1,this.suppressValidationErr);Z=z}else if(qR(J,"!--",Z))K=!0;else throw Error("Invalid DOCTYPE");Y++,V=""}else if(J[Z]===">"){if(K){if(J[Z-1]==="-"&&J[Z-2]==="-")K=!1,Y--}else Y--;if(Y===0)break}else if(J[Z]==="[")X=!0;else V+=J[Z];if(Y!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Q,i:Z}}readEntityExp(J,Z){Z=bQ(J,Z);let Q="";while(Z<J.length&&!/\s/.test(J[Z])&&J[Z]!=='"'&&J[Z]!=="'")Q+=J[Z],Z++;if(Da(Q),Z=bQ(J,Z),!this.suppressValidationErr){if(J.substring(Z,Z+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if(J[Z]==="%")throw Error("Parameter entities are not supported")}let Y="";return[Z,Y]=this.readIdentifierVal(J,Z,"entity"),Z--,[Q,Y,Z]}readNotationExp(J,Z){Z=bQ(J,Z);let Q="";while(Z<J.length&&!/\s/.test(J[Z]))Q+=J[Z],Z++;!this.suppressValidationErr&&Da(Q),Z=bQ(J,Z);let Y=J.substring(Z,Z+6).toUpperCase();if(!this.suppressValidationErr&&Y!=="SYSTEM"&&Y!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${Y}"`);Z+=Y.length,Z=bQ(J,Z);let X=null,K=null;if(Y==="PUBLIC"){if([Z,X]=this.readIdentifierVal(J,Z,"publicIdentifier"),Z=bQ(J,Z),J[Z]==='"'||J[Z]==="'")[Z,K]=this.readIdentifierVal(J,Z,"systemIdentifier")}else if(Y==="SYSTEM"){if([Z,K]=this.readIdentifierVal(J,Z,"systemIdentifier"),!this.suppressValidationErr&&!K)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Q,publicIdentifier:X,systemIdentifier:K,index:--Z}}readIdentifierVal(J,Z,Q){let Y="",X=J[Z];if(X!=='"'&&X!=="'")throw Error(`Expected quoted string, found "${X}"`);Z++;while(Z<J.length&&J[Z]!==X)Y+=J[Z],Z++;if(J[Z]!==X)throw Error(`Unterminated ${Q} value`);return Z++,[Z,Y]}readElementExp(J,Z){Z=bQ(J,Z);let Q="";while(Z<J.length&&!/\s/.test(J[Z]))Q+=J[Z],Z++;if(!this.suppressValidationErr&&!ev(Q))throw Error(`Invalid element name: "${Q}"`);Z=bQ(J,Z);let Y="";if(J[Z]==="E"&&qR(J,"MPTY",Z))Z+=4;else if(J[Z]==="A"&&qR(J,"NY",Z))Z+=2;else if(J[Z]==="("){Z++;while(Z<J.length&&J[Z]!==")")Y+=J[Z],Z++;if(J[Z]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${J[Z]}"`);return{elementName:Q,contentModel:Y.trim(),index:Z}}readAttlistExp(J,Z){Z=bQ(J,Z);let Q="";while(Z<J.length&&!/\s/.test(J[Z]))Q+=J[Z],Z++;Da(Q),Z=bQ(J,Z);let Y="";while(Z<J.length&&!/\s/.test(J[Z]))Y+=J[Z],Z++;if(!Da(Y))throw Error(`Invalid attribute name: "${Y}"`);Z=bQ(J,Z);let X="";if(J.substring(Z,Z+8).toUpperCase()==="NOTATION"){if(X="NOTATION",Z+=8,Z=bQ(J,Z),J[Z]!=="(")throw Error(`Expected '(', found "${J[Z]}"`);Z++;let V=[];while(Z<J.length&&J[Z]!==")"){let z="";while(Z<J.length&&J[Z]!=="|"&&J[Z]!==")")z+=J[Z],Z++;if(z=z.trim(),!Da(z))throw Error(`Invalid notation name: "${z}"`);if(V.push(z),J[Z]==="|")Z++,Z=bQ(J,Z)}if(J[Z]!==")")throw Error("Unterminated list of notations");Z++,X+=" ("+V.join("|")+")"}else{while(Z<J.length&&!/\s/.test(J[Z]))X+=J[Z],Z++;let V=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!V.includes(X.toUpperCase()))throw Error(`Invalid attribute type: "${X}"`)}Z=bQ(J,Z);let K="";if(J.substring(Z,Z+8).toUpperCase()==="#REQUIRED")K="#REQUIRED",Z+=8;else if(J.substring(Z,Z+7).toUpperCase()==="#IMPLIED")K="#IMPLIED",Z+=7;else[Z,K]=this.readIdentifierVal(J,Z,"ATTLIST");return{elementName:Q,attributeName:Y,attributeType:X,defaultValue:K,index:Z}}}var bQ=(J,Z)=>{while(Z<J.length&&/\s/.test(J[Z]))Z++;return Z};function qR(J,Z,Q){for(let Y=0;Y<Z.length;Y++)if(Z[Y]!==J[Q+Y+1])return!1;return!0}function Da(J){if(ev(J))return J;else throw Error(`Invalid entity name ${J}`)}var cE3=/^[-+]?0x[a-fA-F0-9]+$/,lE3=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,iE3={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ae0(J,Z={}){if(Z=Object.assign({},iE3,Z),!J||typeof J!=="string")return J;let Q=J.trim();if(Z.skipLike!==void 0&&Z.skipLike.test(Q))return J;else if(J==="0")return 0;else if(Z.hex&&cE3.test(Q))return rE3(Q,16);else if(Q.search(/.+[eE].+/)!==-1)return aE3(J,Q,Z);else{let Y=lE3.exec(Q);if(Y){let X=Y[1]||"",K=Y[2],V=oE3(Y[3]),z=X?J[K.length+1]===".":J[K.length]===".";if(!Z.leadingZeros&&(K.length>1||K.length===1&&!z))return J;else{let G=Number(Q),F=String(G);if(G===0)return G;if(F.search(/[eE]/)!==-1)if(Z.eNotation)return G;else return J;else if(Q.indexOf(".")!==-1)if(F==="0")return G;else if(F===V)return G;else if(F===`${X}${V}`)return G;else return J;let q=K?V:Q;if(K)return q===F||X+q===F?G:J;else return q===F||q===X+F?G:J}}else return J}}var nE3=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function aE3(J,Z,Q){if(!Q.eNotation)return J;let Y=Z.match(nE3);if(Y){let X=Y[1]||"",K=Y[3].indexOf("e")===-1?"E":"e",V=Y[2],z=X?J[V.length+1]===K:J[V.length]===K;if(V.length>1&&z)return J;else if(V.length===1&&(Y[3].startsWith(`.${K}`)||Y[3][0]===K))return Number(Z);else if(Q.leadingZeros&&!z)return Z=(Y[1]||"")+Y[3],Number(Z);else return J}else return J}function oE3(J){if(J&&J.indexOf(".")!==-1){if(J=J.replace(/0+$/,""),J===".")J="0";else if(J[0]===".")J="0"+J;else if(J[J.length-1]===".")J=J.substring(0,J.length-1);return J}return J}function rE3(J,Z){if(parseInt)return parseInt(J,Z);else if(Number.parseInt)return Number.parseInt(J,Z);else if(window&&window.parseInt)return window.parseInt(J,Z);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}function je0(J){if(typeof J==="function")return J;if(Array.isArray(J))return(Z)=>{for(let Q of J){if(typeof Q==="string"&&Z===Q)return!0;if(Q instanceof RegExp&&Q.test(Z))return!0}};return()=>!1}class CV0{constructor(J){if(this.options=J,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(Z,Q)=>String.fromCodePoint(Number.parseInt(Q,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(Z,Q)=>String.fromCodePoint(Number.parseInt(Q,16))}},this.addExternalEntities=sE3,this.parseXml=ZM3,this.parseTextData=tE3,this.resolveNameSpace=eE3,this.buildAttributesMap=JM3,this.isItStopNode=KM3,this.replaceEntitiesValue=YM3,this.readStopNodeData=zM3,this.saveTextToParentTag=XM3,this.addChild=QM3,this.ignoreAttributesFn=je0(this.options.ignoreAttributes),this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let Z=0;Z<this.options.stopNodes.length;Z++){let Q=this.options.stopNodes[Z];if(typeof Q!=="string")continue;if(Q.startsWith("*."))this.stopNodesWildcard.add(Q.substring(2));else this.stopNodesExact.add(Q)}}}}function sE3(J){let Z=Object.keys(J);for(let Q=0;Q<Z.length;Q++){let Y=Z[Q];this.lastEntities[Y]={regex:new RegExp("&"+Y+";","g"),val:J[Y]}}}function tE3(J,Z,Q,Y,X,K,V){if(J!==void 0){if(this.options.trimValues&&!Y)J=J.trim();if(J.length>0){if(!V)J=this.replaceEntitiesValue(J);let z=this.options.tagValueProcessor(Z,J,Q,X,K);if(z===null||z===void 0)return J;else if(typeof z!==typeof J||z!==J)return z;else if(this.options.trimValues)return Ie0(J,this.options.parseTagValue,this.options.numberParseOptions);else if(J.trim()===J)return Ie0(J,this.options.parseTagValue,this.options.numberParseOptions);else return J}}}function eE3(J){if(this.options.removeNSPrefix){let Z=J.split(":"),Q=J.charAt(0)==="/"?"/":"";if(Z[0]==="xmlns")return"";if(Z.length===2)J=Q+Z[1]}return J}var $M3=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function JM3(J,Z,Q){if(this.options.ignoreAttributes!==!0&&typeof J==="string"){let Y=RV0(J,$M3),X=Y.length,K={};for(let V=0;V<X;V++){let z=this.resolveNameSpace(Y[V][1]);if(this.ignoreAttributesFn(z,Z))continue;let G=Y[V][4],F=this.options.attributeNamePrefix+z;if(z.length){if(this.options.transformAttributeName)F=this.options.transformAttributeName(F);if(F==="__proto__")F="#__proto__";if(G!==void 0){if(this.options.trimValues)G=G.trim();G=this.replaceEntitiesValue(G);let q=this.options.attributeValueProcessor(z,G,Z);if(q===null||q===void 0)K[F]=G;else if(typeof q!==typeof G||q!==G)K[F]=q;else K[F]=Ie0(G,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)K[F]=!0}}if(!Object.keys(K).length)return;if(this.options.attributesGroupName){let V={};return V[this.options.attributesGroupName]=K,V}return K}}var ZM3=function(J){J=J.replace(/\r\n?/g,`
@@ -7371,7 +7371,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7371
7371
  `),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7372
7372
  `))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class K01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=jz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Y01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function wh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function fR3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=z>0?V/z:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=z>0?V/z:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function uR3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function bR3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function hR3(J,Z,Q,Y,X,K,V){let z;try{let D=x1.of(J),B=f0.of(J);z={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,iY0(D),()=>{u3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
7373
7373
  `,G));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??z.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
7374
- `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774866438-g7cb400"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Lh4}}class Lh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Oh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}ZQ();import{mkdtemp as pR3,readFile as dR3,rmdir as cR3,unlink as lR3,writeFile as iR3}from"node:fs/promises";import{tmpdir as nR3}from"node:os";import Ch4 from"node:path";m0();m0();class Eh4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Eh4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Mh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Ah4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ah4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var gR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},gR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Iz0{}class Pz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new jh4(this.props)}}class jh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Mh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Iz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Iz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Iz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Rh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ih4(J){switch(J.type){case"file":return J.path;case"hint":return`${mR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ph4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function mR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7374
+ `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}sO();m0();_7();QE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();NA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774873738-gc73620"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Lh4}}class Lh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Oh4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}ZQ();import{mkdtemp as pR3,readFile as dR3,rmdir as cR3,unlink as lR3,writeFile as iR3}from"node:fs/promises";import{tmpdir as nR3}from"node:os";import Ch4 from"node:path";m0();m0();class Eh4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Eh4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Mh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class G01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Dq(this)}createRenderObject(){return new Ah4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ah4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var gR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},gR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class Iz0{}class Pz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new jh4(this.props)}}class jh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Mh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof Iz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new Iz0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Iz0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.of(this.context).insert(this.overlayEntry)}catch(J){P.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new G01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Rh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function Ih4(J){switch(J.type){case"file":return J.path;case"hint":return`${mR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ph4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function mR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7375
7375
  `))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class NR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Th4(this.props)}}var aR3=":";class Th4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new vq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let z=X.query.toLowerCase().startsWith(aR3);if(z!==this._isCommitMode)this._isCommitMode=z,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=J.kind==="commit"?"@:":"@@",G=K+z+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=`git-commit(${J.hash})`,G=K+z+" "+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Lb4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await pR3(Ch4.join(nR3(),"amp-edit-")),Q=Ch4.join(Z,"message.amp.md");await iR3(Q,J,"utf-8"),await hK(Q);try{let Y=await dR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await lR3(Q),await cR3(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((G,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new C(G.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((G,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new C(" ")}),new e({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new Pz0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(G)=>Ih4(G),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(G,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new C("",void 0,[new C(F.shortHash,new g({color:Z.secondary})),new C(" ",new g({})),new C(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new C(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new C("@",new g({color:U}))),N.push(new C(F.path,new g({color:H})));break;case"hint":N.push(new C(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new C(" ",new g({}))),N.push(new C(F.message,new g({color:B})));break}let w=Ph4(F);if(w)N.push(new C(" - ",new g({color:D,dim:!0}))),N.push(new C(w,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new C("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),z=[];if(this.props.topWidget)z.push(this.props.topWidget);if(X||K){let G=[];if(X)G.push(X);if(X&&K)G.push(new e({text:new C(" ")}));if(K)G.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:G})});z.push(F)}if(z.push(new y1({child:V})),this.props.bottomWidget)z.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:z})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class _h4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=PV)return!1;let Z=await JL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),z=new NR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),G=new s4({focusNode:this.focusNode,child:z}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:G}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class q01 extends l0{props;constructor(J){super();this.props=J}createState(){return new _h4}}import{isDeepStrictEqual as W01}from"node:util";var oR3=/[\\/_ +.#"@[({&]/,rR3=/[\\/_ +.#"@[({&]/g,sR3=/[\s-]/,Sh4=/[\s-]/g;function Tz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,H,D;while(F>=0){if(W=Tz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(sR3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(Sh4),D&&X>0)W*=0.999**D.length}else if(oR3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(rR3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Tz0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function Cz0(J){return J.toLowerCase().replace(Sh4," ")}function kh4(J,Z){let Q=Tz0(J,Z,Cz0(J),Cz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=Tz0(J,z,Cz0(J),Cz0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class Dy{}class _z0{}class Sz0{}class vh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new yh4}}class yh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function tR3(J,Z){if(J==="")return{matches:!0,score:1};let Q=kh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xh4}}class xh4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new G6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>W01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!W01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>W01(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Hy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Dy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _z0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Sz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...tR3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Hy],[new D4("ArrowUp"),new Dy],[new D4("Tab"),new Hy],[new D4("Tab",{shift:!0}),new Dy],[new D4("n",{ctrl:!0}),new Hy],[new D4("p",{ctrl:!0}),new Dy],[new D4("Enter"),new _z0],[new D4("Escape"),new Sz0]]),focusNode:this.focusNode,child:z}),F=new M7({actions:new Map([[Hy,new D6(this.invoke)],[Dy,new D6(this.invoke)],[_z0,new D6(this.invoke)],[Sz0,new D6(this.invoke)]]),child:G}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new vh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function fh4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class U01 extends J4{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>fh4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new R0({width:N,child:W1.end([new e({text:new C(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(fh4(X.pubDate),Q)]})})}})}}hP();class H01 extends l0{createState(){return new uh4}}class uh4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function eR3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return ZV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function D01(J,Z,Q){return new e({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function $I3(J,Z,Q,Y){return[D01("+",J,Y.success),f3.horizontal(1),D01("~",Z,Y.warning),f3.horizontal(1),D01("-",Q,Y.destructive)]}function JI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class kz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new bh4}}class bh4 extends p0{spinner=new V3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((L,O)=>{if(G){if(L.id===G)return-1;if(O.id===G)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=eR3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=H$(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!JI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new C(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new C(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new C("",void 0,a)}))}let p=[],h=G===L.id?new C("(current) ",new g({color:R.success})):z.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(HN(y))p.push(new H01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new C("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...$I3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function hh4(J){return 1-(1-J)**3}function gh4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=hh4(Y),V=hh4(X);return{x:gh4(J.startOffset.x,J.targetOffset.x,K),y:gh4(J.startOffset.y,J.targetOffset.y,V)}}var ZI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...ZI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:G}}),D};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var QI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...QI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var YI3={nodeWidth:3,nodeHeight:2},XI3={x:0,y:0};class yz0{options;constructor(J={}){this.options={...YI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=XI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new g({color:G,bold:F}))}),new e({text:new C(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new C(z,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new e({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+z;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new C(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+z,B=H.map((L)=>L.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new C(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+z;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new C(W.join(""),new g({color:G}))})),V}}var KI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},VI3={x:0,y:0};class B01{options;constructor(J={}){this.options={...KI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=VI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,H=W.map((N)=>N.position.x+z),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new C(F.join(""),new g({color:G}))})),V}}class Pa extends n3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new mh4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class mh4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class wR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new ch4}}var ph4=400,dh4=300,zI3=16;class ch4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new B01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:ph4,durationY:dh4};let Z=Math.max(ph4,dh4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},zI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ih4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nh4}}class nh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var lh4=30,GI3=30;class wy{}class Ly{}class xz0{}class fz0{}class N01 extends l0{props;constructor(J){super();this.props=J}createState(){return new ah4}}class ah4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new G6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof fz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=V4.of(J).size.width>=GI3+lh4,G=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ly],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ly],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ly],[new D4("Enter"),new xz0],[new D4("Escape"),new fz0]]),focusNode:this.focusNode,child:W}),H=new M7({actions:new Map([[wy,new D6(this.invoke)],[Ly,new D6(this.invoke)],[xz0,new D6(this.invoke)],[fz0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new C(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new ih4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new wR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(z){let M=O?new y1({child:O}):new R0({width:lh4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();IX();hM();CX();O$();d4();N4();SP();var L01=B4(tW(),1);import{execSync as LR}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import FI3 from"node:os";import yq from"node:path";var oh4="c446b2e9b16cdc06df2ec285894d6421",qI3="5ea19563777f4ade8707fc56f7e7a388",WI3="amp-thread-worker",rh4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function UI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function zL(J){if(!J||!UI3(J.meta))return!1;return J.meta.usesDtw===!0}function O01(J){let Z=new URL(`https://dash.cloudflare.com/${oh4}/workers/durable-objects/view/${qI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function E01(J){let Z=new URL(`https://dash.cloudflare.com/${oh4}/workers/services/view/${WI3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function HI3(J,Z){if(OV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function M01(J,Z){let Q=HI3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function sh4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function th4(J,Z){return M01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
7376
7376
  ${Y}`).join(`
7377
7377
 
@@ -7600,7 +7600,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?MG0(t.b
7600
7600
  `),process.exit(1)}process.stdout.write(await s_3(G.result.displayText)+`
7601
7601
  `),process.exit(0)})}hM();import{stdout as t_3}from"node:process";function e_3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${EF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function dd4(J){t_3.write(`${e_3(J)}
7602
7602
  `)}function cd4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{dd4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{dd4(Z),process.exit(0)})}var Lx3=lH.join(nZ,"logs","headless.log"),r61=lH.join(Qv,"device-id.json"),Wn4=`cli-tui-${En4(16).toString("hex")}`;async function Ox3(){for(let J of XE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7603
- `)}function Ex3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Mx3(J){try{return await An4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Mx3(Y))}function In4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Un4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ax3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function WF0(J){let Y=Ax3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Hn4(J){if(!Y5.write(J))await Dx3(Y5,"drain")}var Dn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],Bn4=(J)=>("deprecated"in J)&&J.deprecated===!0,jx3=(J)=>("hidden"in J)&&J.hidden===!0,Rx3=(J)=>("default"in J),Ix3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:jo0}];function Px3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var UF0=V1.file(jn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(UF0,".config");function Cx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=MX0(),Y=ho0();if((!Q||Y||IT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(MX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Tx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774866438-g7cb400");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:UF0,userConfigDir:J51});RT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
7603
+ `)}function Ex3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Mx3(J){try{return await An4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await Mx3(Y))}function In4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function Un4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ax3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function WF0(J){let Y=Ax3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Hn4(J){if(!Y5.write(J))await Dx3(Y5,"drain")}var Dn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],Bn4=(J)=>("deprecated"in J)&&J.deprecated===!0,jx3=(J)=>("hidden"in J)&&J.hidden===!0,Rx3=(J)=>("default"in J),Ix3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:jo0}];function Px3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var UF0=V1.file(jn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(UF0,".config");function Cx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=MX0(),Y=ho0();if((!Q||Y||IT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(MX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Tx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774873738-gc73620");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:UF0,userConfigDir:J51});RT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
7604
7604
  `);let W0=await _x3(J),r=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await VH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];P.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let z=j1(xX(X).pipe(T5((a)=>a!=="pending"))),G=Y?"pending":await z;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:o6(G),isError:bW(G),errorMessage:bW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=Xq4({configService:X}),W=new Map,U=()=>W.clear(),H=new fT0(X,J.settings.getWorkspaceRootPath()),D=zt1({configService:X,filesystem:n8}),B=Qa1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return P.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;P.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let z0=(async()=>{let J0=new HE(J.secrets),G0=await J0.getClientInfo(a,W0),i=r?.scopes??G0?.scopes,o=ZI4();P.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Y5.isTTY});let t;if(o)t=J.executeMode?JI4():$I4(a);let $0=new BR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??G0?.clientId,clientSecret:r?.clientSecret??G0?.clientSecret,authUrl:r?.authUrl??G0?.authUrl,tokenUrl:r?.tokenUrl??G0?.tokenUrl,scopes:i,headlessAuthHandler:t});return P.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??G0?.clientId),willUseDCR:!(r?.clientId??G0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,z0),z0}}),N=ug0({configService:X,filesystem:n8,spawn:P$0}),w;if(J.executeMode){let a=await Gz4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)P.warn(`${W0} provider initialization slow or failed:`,r)}else w=bg0({toolService:F,providers:[B,N]});if(Z.jetbrains)$E("JetBrains");else if(Z.ide&&gI4())$E("VS Code");else if(Z.ide&&mI4())$E("Neovim");else if(Z.ide){let a=await Ox3();if(a){let W0=_10(a.ideName);if(W0)$E(W0)}}if(J.executeMode)Yf1(!0);let L,O=w$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&if1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(zz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new WY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends WY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Dt1({isDevelopment:!1}),A=new bS0(M,X,{maxThreads:200});P.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=e61(j,G),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let T=_?Tx3():yt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new lA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){P.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return P.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new po0,k=process.env.PLUGINS??"off",f=Z.headless?GT4():void 0,d=f??new BX0({configService:X}),p=d instanceof BX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=tT0({configService:X,fileSystem:n8,platform:d,internalPlugins:Pn4,pluginFilter:k}),n=sa1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:n8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function _x3(J){if(!J.executeMode){if(!await UX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Y5.write(`Login cancelled. Run the command again to retry.
7605
7605
  `),!1}return await Tn4(J)}async function Tn4(J){let Z=En4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await EV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);Y5.write(`If your browser does not open automatically, visit:
7606
7606
 
@@ -7608,7 +7608,7 @@ ${o0.blue.bold(X)}
7608
7608
 
7609
7609
  `);try{return await pC4(J.ampURL,Z,J.secrets,Y),Y5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),j2.write(`
7610
7610
  Login failed: ${K instanceof Error?K.message:String(K)}
7611
- `),!1}}function Nn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Sx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function kx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!kx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function yx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function xx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function fx3(J){let Z=new fN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),cd4(Z,{version:"0.0.1774866438-g7cb400",buildTimestamp:"2026-03-30T10:31:14.209Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await cx3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await dx3(L,await Ea0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await r3(L);await SR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await kR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7611
+ `),!1}}function Nn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Sx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function kx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!kx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function yx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function xx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function fx3(J){let Z=new fN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;QR4(N)}),cd4(Z,{version:"0.0.1774873738-gc73620",buildTimestamp:"2026-03-30T12:32:50.624Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await cx3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await dx3(L,await Ea0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await r3(L);await SR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await kR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7612
7612
  Actions:
7613
7613
  create Create a new DTW thread and print its ID
7614
7614
  add-message <message> Send a user message and wait for message_added
@@ -7672,8 +7672,8 @@ ${M}
7672
7672
 
7673
7673
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function ux3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new hV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function bx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function hx3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("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"
7674
7674
  Or pipe via stdin: echo "your message" | amp --execute`)}async function HF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(z0,J0)=>{let G0=Number(process.hrtime.bigint()-J0)/1e6,i=XO4();P.info("Startup phase",{phase:z0,phaseMs:Math.round(G0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:z}=await bx3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;hx3({...Z,streamJson:G},J.executeMode,V),A2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;P.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await R7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await Q51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&bW(D)){let z0=ak(Error(D.error.message));if(z0.message===E3.networkOffline||z0.message===E3.networkTimeout)throw WF0(J.ampURL);throw new T1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,N=B?.user.email,w=In4(N),L=t61({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&e61(O,B);if(!W)await s61(Q,Z,D);let M=$51(D),A=M?.features??[],j=M?.team??null,R=HX0(Z,M);if(R instanceof Error)s3(R.message);if((J.executeMode||G)&&N8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!ZE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await WT4(V,z,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new T1("Headless DTW mode is only available for Amp employees",1);let z0=await U.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new T1(`Invalid thread ID: ${J0}`,1);let G0=J0?void 0:await tx3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??G0?.threadId;if(!i)throw new T1("Failed to resolve headless thread ID",1);let o=await KI4(i);if(o.status==="already-running")await U.asyncDispose(),await VH(),process.exit(0);try{await eR4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:G0?.ownerUserId,threadVersion:G0?.threadVersion,agentMode:G0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await VH(),process.exit(0)}let _=J.executeMode?void 0:async(z0)=>Lo(z0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let z0=W?await U.serverStatusPromise:D,J0=await sQ0(J.settings,process.cwd(),$51(z0),R);if(J0 instanceof Error)s3(J0.message);return Ze0(H,{threadMeta:J0?vz(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(z0,J0)=>{if(J0?.nonBlockingOwnershipCheck){wn4(z0,U.configService).catch((G0)=>{if(G0 instanceof T1){if(J0.onOwnershipError){J0.onOwnershipError(G0,z0);return}zH(G0,z0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await wn4(z0,U.configService)}catch(G0){if(G0 instanceof T1)throw G0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zH},u=async(z0)=>{try{if(z0==="dtw")return ux3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Wn4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Lf4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof T1)throw J0;throw await zH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7675
- `),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Un4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Un4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Cx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){$T4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774866438-g7cb400",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let z0=await j1(f.threadHandles$);if(!z0)throw new T1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await wX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((z0)=>({...z0,launchCount:z0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await zu4({codebaseContextService:U.codebaseContextService,history:new Qa0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>Cn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Wn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T10:31:14.209Z"},(z0)=>new De0({...z0,threadPool:z0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7676
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await An4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await Mn4(lH.dirname(r61),{recursive:!0}),await Bx3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await tC4(J.mcpConfig);X=eC4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:NT4(await Ea0(J,X))}}function gx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function mx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Lx3:Pn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function px3(){YO4();let J=gx3(process.argv),Z=mx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Ex3(P),P.info("Starting Amp CLI.",{version:"0.0.1774866438-g7cb400",buildTimestamp:"2026-03-30T10:31:14.209Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await fx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await px3().catch(zH)});async function dx3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7675
+ `),await VH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return P.info("User free tier status:",G0),G0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,z0);let J0=process.hrtime.bigint(),G0=e61(O,z0),i=o6(z0)?t61({userEmail:z0.user.email,features:z0.features}):!1;Un4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await zH(z0,Z.threadId)});else F=process.hrtime.bigint(),Un4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Cx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){$T4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...z0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774873738-gc73620",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let z0=await j1(f.threadHandles$);if(!z0)throw new T1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await wX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((z0)=>({...z0,launchCount:z0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await zu4({codebaseContextService:U.codebaseContextService,history:new Qa0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>Cn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Wn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T12:32:50.624Z"},(z0)=>new De0({...z0,threadPool:z0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7676
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(z)=>{if(z!==rh)return;try{let G=await An4(r61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==rh)return;await Mn4(lH.dirname(r61),{recursive:!0}),await Bx3(r61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await tC4(J.mcpConfig);X=eC4(X,z)}let K=lH.dirname(X.getSettingsFilePath());Gq4(Qv,K);let V=await X.get("url","global");if(!V)V=G7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:NT4(await Ea0(J,X))}}function gx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function mx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Lx3:Pn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function px3(){YO4();let J=gx3(process.argv),Z=mx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Ex3(P),P.info("Starting Amp CLI.",{version:"0.0.1774873738-gc73620",buildTimestamp:"2026-03-30T12:32:50.624Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await fx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await px3().catch(zH)});async function dx3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7677
7677
  `);else if(!OV(J.ampURL))Y5.write(`Logging in to ${new URL(J.ampURL).hostname}
7678
7678
  `);let Y=process.env.AMP_API_KEY;if(Y)Y5.write(`API key found in environment variable, storing...
7679
7679
  `),await Z.set("apiKey",Y,J.ampURL),Y5.write(`API key successfully stored.