@sourcegraph/amp 0.0.1751486517-g5cc052 → 0.0.1751515778-gc465ed

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 +5 -5
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6969,7 +6969,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
6969
6969
  `;break;case"id":X=W.includes("\x00")?void 0:W;break;case"retry":/^\d+$/.test(W)?J(parseInt(W,10)):B(new mJ1(`Invalid \`retry\` value: "${W}"`,{type:"invalid-retry",value:W,line:M}));break;default:B(new mJ1(`Unknown field "${H.length>20?`${H.slice(0,20)}…`:H}"`,{type:"unknown-field",field:H,value:W,line:M}));break}}function E(){K.length>0&&Q({id:X,event:G||void 0,data:K.endsWith(`
6970
6970
  `)?K.slice(0,-1):K}),X=void 0,K="",G=""}function w(H={}){z&&H.consume&&Y(z),X=void 0,K="",G="",z=""}return{feed:q,reset:w}}function XYA(A){let Q=[],B="",J=A.length;for(let D=0;D<J;D++){let z=A[D];z==="\r"&&A[D+1]===`
6971
6971
  `?(Q.push(B),B="",D++):z==="\r"||z===`
6972
- `?(Q.push(B),B=""):B+=z}return[Q,B]}class uJ1 extends Event{constructor(A,Q){var B,J;super(A),this.code=(B=Q==null?void 0:Q.code)!=null?B:void 0,this.message=(J=Q==null?void 0:Q.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](A,Q,B){return B(Lc1(this),Q)}[Symbol.for("Deno.customInspect")](A,Q){return A(Lc1(this),Q)}}function KYA(A){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(A,"SyntaxError"):new SyntaxError(A)}function pJ1(A){return A instanceof Error?"errors"in A&&Array.isArray(A.errors)?A.errors.map(pJ1).join(", "):("cause"in A)&&A.cause instanceof Error?`${A}: ${pJ1(A.cause)}`:A.message:`${A}`}function Lc1(A){return{type:A.type,message:A.message,code:A.code,defaultPrevented:A.defaultPrevented,cancelable:A.cancelable,timeStamp:A.timeStamp}}var Tc1=(A)=>{throw TypeError(A)},sJ1=(A,Q,B)=>Q.has(A)||Tc1("Cannot "+B),C9=(A,Q,B)=>(sJ1(A,Q,"read from private field"),B?B.call(A):Q.get(A)),VB=(A,Q,B)=>Q.has(A)?Tc1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(A):Q.set(A,B),E7=(A,Q,B,J)=>(sJ1(A,Q,"write to private field"),Q.set(A,B),B),vw=(A,Q,B)=>(sJ1(A,Q,"access private method"),B),YZ,DO,$T,wa,Ha,My,yT,Iy,rM,fT,gT,kT,Hy,lq,cJ1,lJ1,dJ1,_c1,iJ1,aJ1,Wy,nJ1,rJ1;class bT extends EventTarget{constructor(A,Q){var B,J;super(),VB(this,lq),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,VB(this,YZ),VB(this,DO),VB(this,$T),VB(this,wa),VB(this,Ha),VB(this,My),VB(this,yT),VB(this,Iy,null),VB(this,rM),VB(this,fT),VB(this,gT,null),VB(this,kT,null),VB(this,Hy,null),VB(this,lJ1,async(D)=>{var z;C9(this,fT).reset();let{body:Z,redirected:X,status:K,headers:G}=D;if(K===204){vw(this,lq,Wy).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(X?E7(this,$T,new URL(D.url)):E7(this,$T,void 0),K!==200){vw(this,lq,Wy).call(this,`Non-200 status code (${K})`,K);return}if(!(G.get("content-type")||"").startsWith("text/event-stream")){vw(this,lq,Wy).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(C9(this,YZ)===this.CLOSED)return;E7(this,YZ,this.OPEN);let q=new Event("open");if((z=C9(this,Hy))==null||z.call(this,q),this.dispatchEvent(q),typeof Z!="object"||!Z||!("getReader"in Z)){vw(this,lq,Wy).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let Y=new TextDecoder,F=Z.getReader(),E=!0;do{let{done:w,value:H}=await F.read();H&&C9(this,fT).feed(Y.decode(H,{stream:!w})),w&&(E=!1,C9(this,fT).reset(),vw(this,lq,nJ1).call(this))}while(E)}),VB(this,dJ1,(D)=>{E7(this,rM,void 0),!(D.name==="AbortError"||D.type==="aborted")&&vw(this,lq,nJ1).call(this,pJ1(D))}),VB(this,iJ1,(D)=>{typeof D.id=="string"&&E7(this,Iy,D.id);let z=new MessageEvent(D.event||"message",{data:D.data,origin:C9(this,$T)?C9(this,$T).origin:C9(this,DO).origin,lastEventId:D.id||""});C9(this,kT)&&(!D.event||D.event==="message")&&C9(this,kT).call(this,z),this.dispatchEvent(z)}),VB(this,aJ1,(D)=>{E7(this,My,D)}),VB(this,rJ1,()=>{E7(this,yT,void 0),C9(this,YZ)===this.CONNECTING&&vw(this,lq,cJ1).call(this)});try{if(A instanceof URL)E7(this,DO,A);else if(typeof A=="string")E7(this,DO,new URL(A,GYA()));else throw new Error("Invalid URL")}catch{throw KYA("An invalid or illegal string was specified")}E7(this,fT,Rc1({onEvent:C9(this,iJ1),onRetry:C9(this,aJ1)})),E7(this,YZ,this.CONNECTING),E7(this,My,3000),E7(this,Ha,(B=Q==null?void 0:Q.fetch)!=null?B:globalThis.fetch),E7(this,wa,(J=Q==null?void 0:Q.withCredentials)!=null?J:!1),vw(this,lq,cJ1).call(this)}get readyState(){return C9(this,YZ)}get url(){return C9(this,DO).href}get withCredentials(){return C9(this,wa)}get onerror(){return C9(this,gT)}set onerror(A){E7(this,gT,A)}get onmessage(){return C9(this,kT)}set onmessage(A){E7(this,kT,A)}get onopen(){return C9(this,Hy)}set onopen(A){E7(this,Hy,A)}addEventListener(A,Q,B){let J=Q;super.addEventListener(A,J,B)}removeEventListener(A,Q,B){let J=Q;super.removeEventListener(A,J,B)}close(){C9(this,yT)&&clearTimeout(C9(this,yT)),C9(this,YZ)!==this.CLOSED&&(C9(this,rM)&&C9(this,rM).abort(),E7(this,YZ,this.CLOSED),E7(this,rM,void 0))}}YZ=new WeakMap,DO=new WeakMap,$T=new WeakMap,wa=new WeakMap,Ha=new WeakMap,My=new WeakMap,yT=new WeakMap,Iy=new WeakMap,rM=new WeakMap,fT=new WeakMap,gT=new WeakMap,kT=new WeakMap,Hy=new WeakMap,lq=new WeakSet,cJ1=function(){E7(this,YZ,this.CONNECTING),E7(this,rM,new AbortController),C9(this,Ha)(C9(this,DO),vw(this,lq,_c1).call(this)).then(C9(this,lJ1)).catch(C9(this,dJ1))},lJ1=new WeakMap,dJ1=new WeakMap,_c1=function(){var A;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...C9(this,Iy)?{"Last-Event-ID":C9(this,Iy)}:void 0},cache:"no-store",signal:(A=C9(this,rM))==null?void 0:A.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},iJ1=new WeakMap,aJ1=new WeakMap,Wy=function(A,Q){var B;C9(this,YZ)!==this.CLOSED&&E7(this,YZ,this.CLOSED);let J=new uJ1("error",{code:Q,message:A});(B=C9(this,gT))==null||B.call(this,J),this.dispatchEvent(J)},nJ1=function(A,Q){var B;if(C9(this,YZ)===this.CLOSED)return;E7(this,YZ,this.CONNECTING);let J=new uJ1("error",{code:Q,message:A});(B=C9(this,gT))==null||B.call(this,J),this.dispatchEvent(J),E7(this,yT,setTimeout(C9(this,rJ1),C9(this,My)))},rJ1=new WeakMap,bT.CONNECTING=0,bT.OPEN=1,bT.CLOSED=2;function GYA(){let A="document"in globalThis?globalThis.document:void 0;return A&&typeof A=="object"&&"baseURI"in A&&typeof A.baseURI=="string"?A.baseURI:void 0}QO();var oJ1;oJ1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((A)=>A.webcrypto);async function qYA(A){return(await oJ1).getRandomValues(new Uint8Array(A))}async function YYA(A){let B="",J=await qYA(A);for(let D=0;D<A;D++){let z=J[D]%66;B+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[z]}return B}async function UYA(A){return await YYA(A)}async function FYA(A){let Q=await(await oJ1).subtle.digest("SHA-256",new TextEncoder().encode(A));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function tJ1(A){if(!A)A=43;if(A<43||A>128)throw`Expected a length between 43 and 128. Received ${A}.`;let Q=await UYA(A),B=await FYA(Q);return{code_verifier:Q,code_challenge:B}}QO();gi();var jc1=f1.object({resource:f1.string().url(),authorization_servers:f1.array(f1.string().url()).optional(),jwks_uri:f1.string().url().optional(),scopes_supported:f1.array(f1.string()).optional(),bearer_methods_supported:f1.array(f1.string()).optional(),resource_signing_alg_values_supported:f1.array(f1.string()).optional(),resource_name:f1.string().optional(),resource_documentation:f1.string().optional(),resource_policy_uri:f1.string().url().optional(),resource_tos_uri:f1.string().url().optional(),tls_client_certificate_bound_access_tokens:f1.boolean().optional(),authorization_details_types_supported:f1.array(f1.string()).optional(),dpop_signing_alg_values_supported:f1.array(f1.string()).optional(),dpop_bound_access_tokens_required:f1.boolean().optional()}).passthrough(),Pc1=f1.object({issuer:f1.string(),authorization_endpoint:f1.string(),token_endpoint:f1.string(),registration_endpoint:f1.string().optional(),scopes_supported:f1.array(f1.string()).optional(),response_types_supported:f1.array(f1.string()),response_modes_supported:f1.array(f1.string()).optional(),grant_types_supported:f1.array(f1.string()).optional(),token_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),service_documentation:f1.string().optional(),revocation_endpoint:f1.string().optional(),revocation_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),introspection_endpoint:f1.string().optional(),introspection_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),code_challenge_methods_supported:f1.array(f1.string()).optional()}).passthrough(),eJ1=f1.object({access_token:f1.string(),token_type:f1.string(),expires_in:f1.number().optional(),scope:f1.string().optional(),refresh_token:f1.string().optional()}).strip(),Q92=f1.object({error:f1.string(),error_description:f1.string().optional(),error_uri:f1.string().optional()}),EYA=f1.object({redirect_uris:f1.array(f1.string()).refine((A)=>A.every((Q)=>URL.canParse(Q)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:f1.string().optional(),grant_types:f1.array(f1.string()).optional(),response_types:f1.array(f1.string()).optional(),client_name:f1.string().optional(),client_uri:f1.string().optional(),logo_uri:f1.string().optional(),scope:f1.string().optional(),contacts:f1.array(f1.string()).optional(),tos_uri:f1.string().optional(),policy_uri:f1.string().optional(),jwks_uri:f1.string().optional(),jwks:f1.any().optional(),software_id:f1.string().optional(),software_version:f1.string().optional()}).strip(),wYA=f1.object({client_id:f1.string(),client_secret:f1.string().optional(),client_id_issued_at:f1.number().optional(),client_secret_expires_at:f1.number().optional()}).strip(),Sc1=EYA.merge(wYA),B92=f1.object({error:f1.string(),error_description:f1.string().optional()}).strip(),J92=f1.object({token:f1.string(),token_type_hint:f1.string().optional()}).strip();class zO extends Error{constructor(A){super(A!==null&&A!==void 0?A:"Unauthorized")}}async function Wa(A,{serverUrl:Q,authorizationCode:B,scope:J,resourceMetadataUrl:D}){let z=Q;try{let F=await HYA(D||Q);if(F.authorization_servers&&F.authorization_servers.length>0)z=F.authorization_servers[0]}catch(F){console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server",F)}let Z=await WYA(z),X=await Promise.resolve(A.clientInformation());if(!X){if(B!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!A.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let F=await CYA(z,{metadata:Z,clientMetadata:A.clientMetadata});await A.saveClientInformation(F),X=F}if(B!==void 0){let F=await A.codeVerifier(),E=await IYA(z,{metadata:Z,clientInformation:X,authorizationCode:B,codeVerifier:F,redirectUri:A.redirectUrl});return await A.saveTokens(E),"AUTHORIZED"}let K=await A.tokens();if(K===null||K===void 0?void 0:K.refresh_token)try{let F=await NYA(z,{metadata:Z,clientInformation:X,refreshToken:K.refresh_token});return await A.saveTokens(F),"AUTHORIZED"}catch(F){console.error("Could not refresh OAuth tokens:",F)}let G=A.state?await A.state():void 0,{authorizationUrl:q,codeVerifier:Y}=await MYA(z,{metadata:Z,clientInformation:X,state:G,redirectUrl:A.redirectUrl,scope:J||A.clientMetadata.scope});return await A.saveCodeVerifier(Y),await A.redirectToAuthorization(q),"REDIRECT"}function vc1(A){let Q=A.headers.get("WWW-Authenticate");if(!Q)return;let[B,J]=Q.split(" ");if(B.toLowerCase()!=="bearer"||!J){console.log("Invalid WWW-Authenticate header format, expected 'Bearer'");return}let z=/resource_metadata="([^"]*)"/.exec(Q);if(!z)return;try{return new URL(z[1])}catch(Z){console.log("Invalid resource metadata url: ",z[1]);return}}async function HYA(A,Q){var B;let J;if(Q===null||Q===void 0?void 0:Q.resourceMetadataUrl)J=new URL(Q===null||Q===void 0?void 0:Q.resourceMetadataUrl);else J=new URL("/.well-known/oauth-protected-resource",A);let D;try{D=await fetch(J,{headers:{"MCP-Protocol-Version":(B=Q===null||Q===void 0?void 0:Q.protocolVersion)!==null&&B!==void 0?B:vT}})}catch(z){if(z instanceof TypeError)D=await fetch(J);else throw z}if(D.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!D.ok)throw new Error(`HTTP ${D.status} trying to load well-known OAuth protected resource metadata.`);return jc1.parse(await D.json())}async function WYA(A,Q){var B;let J=new URL("/.well-known/oauth-authorization-server",A),D;try{D=await fetch(J,{headers:{"MCP-Protocol-Version":(B=Q===null||Q===void 0?void 0:Q.protocolVersion)!==null&&B!==void 0?B:vT}})}catch(z){if(z instanceof TypeError)D=await fetch(J);else throw z}if(D.status===404)return;if(!D.ok)throw new Error(`HTTP ${D.status} trying to load well-known OAuth metadata`);return Pc1.parse(await D.json())}async function MYA(A,{metadata:Q,clientInformation:B,redirectUrl:J,scope:D,state:z}){let K;if(Q){if(K=new URL(Q.authorization_endpoint),!Q.response_types_supported.includes("code"))throw new Error("Incompatible auth server: does not support response type code");if(!Q.code_challenge_methods_supported||!Q.code_challenge_methods_supported.includes("S256"))throw new Error("Incompatible auth server: does not support code challenge method S256")}else K=new URL("/authorize",A);let G=await tJ1(),q=G.code_verifier,Y=G.code_challenge;if(K.searchParams.set("response_type","code"),K.searchParams.set("client_id",B.client_id),K.searchParams.set("code_challenge",Y),K.searchParams.set("code_challenge_method","S256"),K.searchParams.set("redirect_uri",String(J)),z)K.searchParams.set("state",z);if(D)K.searchParams.set("scope",D);return{authorizationUrl:K,codeVerifier:q}}async function IYA(A,{metadata:Q,clientInformation:B,authorizationCode:J,codeVerifier:D,redirectUri:z}){let X;if(Q){if(X=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("authorization_code"))throw new Error("Incompatible auth server: does not support grant type authorization_code")}else X=new URL("/token",A);let K=new URLSearchParams({grant_type:"authorization_code",client_id:B.client_id,code:J,code_verifier:D,redirect_uri:String(z)});if(B.client_secret)K.set("client_secret",B.client_secret);let G=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:K});if(!G.ok)throw new Error(`Token exchange failed: HTTP ${G.status}`);return eJ1.parse(await G.json())}async function NYA(A,{metadata:Q,clientInformation:B,refreshToken:J}){let z;if(Q){if(z=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("refresh_token"))throw new Error("Incompatible auth server: does not support grant type refresh_token")}else z=new URL("/token",A);let Z=new URLSearchParams({grant_type:"refresh_token",client_id:B.client_id,refresh_token:J});if(B.client_secret)Z.set("client_secret",B.client_secret);let X=await fetch(z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z});if(!X.ok)throw new Error(`Token refresh failed: HTTP ${X.status}`);return eJ1.parse({refresh_token:J,...await X.json()})}async function CYA(A,{metadata:Q,clientMetadata:B}){let J;if(Q){if(!Q.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");J=new URL(Q.registration_endpoint)}else J=new URL("/register",A);let D=await fetch(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!D.ok)throw new Error(`Dynamic client registration failed: HTTP ${D.status}`);return Sc1.parse(await D.json())}class $c1 extends Error{constructor(A,Q,B){super(`SSE error: ${Q}`);this.code=A,this.event=B}}class AD1{constructor(A,Q){this._url=A,this._resourceMetadataUrl=void 0,this._eventSourceInit=Q===null||Q===void 0?void 0:Q.eventSourceInit,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider}async _authThenStart(){var A;if(!this._authProvider)throw new zO("No auth provider");let Q;try{Q=await Wa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(B){throw(A=this.onerror)===null||A===void 0||A.call(this,B),B}if(Q!=="AUTHORIZED")throw new zO;return await this._startOrAuth()}async _commonHeaders(){let A={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)A.Authorization=`Bearer ${Q.access_token}`}return A}_startOrAuth(){return new Promise((A,Q)=>{var B;this._eventSource=new bT(this._url.href,(B=this._eventSourceInit)!==null&&B!==void 0?B:{fetch:(J,D)=>this._commonHeaders().then((z)=>fetch(J,{...D,headers:{...z,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{var D;if(J.code===401&&this._authProvider){this._authThenStart().then(A,Q);return}let z=new $c1(J.code,J.message,J);Q(z),(D=this.onerror)===null||D===void 0||D.call(this,z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{var D;let z=J;try{if(this._endpoint=new URL(z.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Z){Q(Z),(D=this.onerror)===null||D===void 0||D.call(this,Z),this.close();return}A()}),this._eventSource.onmessage=(J)=>{var D,z;let Z=J,X;try{X=hi.parse(JSON.parse(Z.data))}catch(K){(D=this.onerror)===null||D===void 0||D.call(this,K);return}(z=this.onmessage)===null||z===void 0||z.call(this,X)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(A){if(!this._authProvider)throw new zO("No auth provider");if(await Wa(this._authProvider,{serverUrl:this._url,authorizationCode:A,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new zO("Failed to authorize")}async close(){var A,Q,B;(A=this._abortController)===null||A===void 0||A.abort(),(Q=this._eventSource)===null||Q===void 0||Q.close(),(B=this.onclose)===null||B===void 0||B.call(this)}async send(A){var Q,B,J;if(!this._endpoint)throw new Error("Not connected");try{let D=await this._commonHeaders(),z=new Headers({...D,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers});z.set("content-type","application/json");let Z={...this._requestInit,method:"POST",headers:z,body:JSON.stringify(A),signal:(B=this._abortController)===null||B===void 0?void 0:B.signal},X=await fetch(this._endpoint,Z);if(!X.ok){if(X.status===401&&this._authProvider){if(this._resourceMetadataUrl=vc1(X),await Wa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new zO;return this.send(A)}let K=await X.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${X.status}): ${K}`)}}catch(D){throw(J=this.onerror)===null||J===void 0||J.call(this,D),D}}}QO();v7();F2();y2();var sM=Symbol.for("disabled-client");function vl1(A,Q,B){let J=new Fa({name:"amp-mcp-client",version:"0.0.0-dev"}),D=FA.of(void 0).pipe(Bi(()=>hk(u9(async()=>{if(await J.close(),await new Promise((G)=>setTimeout(G,100)),B)return sM;return ZUA(A,J,Q)}),Rw).pipe(KZ((G)=>{if(G instanceof Fa)G?.close()})),{shouldCountRefs:!1})),z=D.subscribe({}),Z=D.pipe(r6((G)=>{if(G===sM)return{type:"disabled"};if(G===cU)return{type:"connecting"};if(G instanceof Error)return{type:"connection-failed",error:{message:G.message}};return{type:"connected",capabilities:G.getServerCapabilities(),serverInfo:G.getServerVersion()}})),K=D.pipe(W5((G)=>{if(G===cU||G instanceof Error||G===sM)return FA.of(G);let q=new C8;return G.setNotificationHandler(UJ1,()=>{q.next()}),q.pipe(Qi({onUnsubscribe:()=>G.removeNotificationHandler("notifications/tools/list_changed")}),NB(void 0),r6(()=>G))})).pipe(Bi((G)=>{if(G instanceof Error)return FA.of(G);if(G===sM)return FA.of([]);return u9(async(q)=>{return(await G.listTools({signal:q})).tools})}));return{status:Z,tools:K,async callTool(G,q){let Y=await ux1(D);if(Y===sM)throw new Error("cannot call tools for disabled client");let F=await Y.callTool(G,void 0,{signal:q,timeout:999999000});if(!("content"in F))throw new Error("unexpected response");return F.content},async dispose(){z.unsubscribe();try{await J.close()}catch(G){y1.error("Error closing MCP client:",G)}}}}async function ZUA(A,Q,B){let J;if("url"in A)J=new AD1(new URL(A.url));else{let{loadProfileEnvironmentVariables:D}=await Promise.resolve().then(() => (BD1(),kc1)),z=B.loadProfile==="never"||!B.workingDirectory||!yM(B.workingDirectory)?process.env:await B2(D(B.workingDirectory.fsPath,B.loadProfile));J=await Promise.resolve().then(() => (Sl1(),Pl1)).then(({StdioClientTransport:Z})=>{let{AMP_API_KEY:X,...K}=z;return new Z({...A,stderr:"pipe",cwd:B.workingDirectory&&yM(B.workingDirectory)?B.workingDirectory.fsPath:void 0,env:K})})}if("stderr"in J&&J.stderr&&typeof J.stderr==="object"&&J.stderr!==null&&"on"in J.stderr&&typeof J.stderr.on==="function")J.stderr.on("data",(D)=>{let z=D.toString().trim();if(z)y1.info("mcp-server-stderr",{stderr:z,spec:A})});try{let D=Q.connect(J),z=new Promise((Z,X)=>{let K=setTimeout(()=>{clearTimeout(K),X(new Error("Connection timeout: MCP server did not respond within 30 seconds"))},30000)});return await Promise.race([D,z]),Q}catch(D){if(D instanceof Error){if(D.message.includes("Connection closed"))throw new Error("MCP server connection was closed unexpectedly. Check if the server is running and try refreshing the connection.");else if(D.message.includes("Invalid content type"))throw new Error('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in A&&D.message.includes("fetch failed"))throw new Error(`Could not connect to MCP server at ${A.url}. Check that the server is running and accessible.`)}throw D}}function fl1({configService:A,toolService:Q}){let B=new kl1,J=new C8,D=s8.pipe(r6(({settings:{mcpServers:E,"terminal.commands.nodeSpawn.loadProfile":w}})=>({mcpServers:E,loadProfile:w})),Sq()),z=A.workspaceRoots.pipe(r6((E)=>E.at(0))),Z=new Map,X=F7(D,z,J.pipe(NB(void 0))).pipe(vq(300),r6(async([{mcpServers:E,loadProfile:w},H,W])=>{let M=B.consume();for(let[I,N]of Object.entries(E??{})){let V=Z.get(I);if(!M&&V&&XUA(V.spec,N))continue;if(Z.set(I,{spec:N,client:vl1(N,{workingDirectory:H,loadProfile:w},!1)}),V)await V.client.dispose()}for(let[I,{client:N}]of Z.entries())if(!E||!(I in E))await N.dispose(),Z.delete(I);return Array.from(Z.entries())})),K=X.subscribe({}),G=X.pipe(W5((E)=>E.length===0?FA.of([]):F7(...E.map(([w,{spec:H,client:W}])=>W.tools.pipe(r6((M)=>({name:w,spec:H,tools:M===cU||M instanceof Error||M===sM?[]:M,client:W}))))))),q,Y=G.subscribe((E)=>{if(q)for(let w of q)w.dispose();q=[];for(let{name:w,tools:H,client:W}of E)for(let M of H)q.push(Q.registerTool($l1(M,W,w)))},(E)=>{y1.error("MCP toolRegisterer error",E)});return{initialized:(async()=>{try{let E=await B2(s8),w=Object.keys(E.settings.mcpServers||{}).length;if(w===0)return;await B2(X.pipe(W5((H)=>H.length===0?FA.of([]):F7(...H.map(([W,{client:M}])=>M.status.pipe(s7((I)=>I.type==="connected"||I.type==="connection-failed"||I.type==="disabled"),r6(()=>W))))),s7((H)=>H.length>=w),mx1(1)),AbortSignal.timeout(1e4))}catch(E){y1.warn("MCP service initialization failed, but service will continue:",E)}})(),servers:F7(s8,X).pipe(W5(([E,w])=>w.length===0?FA.of([]):F7(...w.map(([H,{spec:W,client:M}])=>F7(M.status,M.tools).pipe(r6(([I,N])=>({name:H,spec:W,status:I,tools:N instanceof Error?N:N===cU||N===sM?[]:N.map((V)=>({spec:{name:V.name,description:V.description,inputSchema:V.inputSchema,source:{mcp:H}},...ik({name:V.name,source:{mcp:H}},E)}))}))))))),restartServers(){B.replenish(),J.next()},async registerToolsWithService(E){return new Promise((w)=>{let H=[],W=!1,M=G.subscribe((I)=>{for(let N of H)N.dispose();H.length=0;for(let{name:N,tools:V,client:_}of I)for(let T of V)H.push(E.registerTool($l1(T,_,N)));if(!W)W=!0,w({dispose:()=>{M.unsubscribe();for(let N of H)N.dispose();H.length=0}})},(I)=>{y1.error("MCP external tool registration error",I)})})},async addServer(E,w){let H=(await B2(s8)).settings.mcpServers;if(H&&E in H)throw new Error(`MCP server already exists with name ${JSON.stringify(E)}`);if("command"in w&&typeof w.command!=="string")throw new Error("Command must be a string");if("url"in w)try{new URL(w.url)}catch(W){throw new Error(`Invalid URL: ${w.url}`)}await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async removeServer(E){let w=(await B2(s8)).settings.mcpServers;if(!w||!(E in w))throw new Error(`MCP server does not exist with name ${JSON.stringify(E)}`);let H={...w};delete H[E],await A.updateSettings("mcpServers",H,"global")},async updateServer(E,w){let H=(await B2(s8)).settings.mcpServers;if(!H||!(E in H))throw new Error(`MCP server does not exist with name ${JSON.stringify(E)}`);await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async dispose(){Y.unsubscribe(),K.unsubscribe();let E=Array.from(Z.values()).map(async({client:w})=>{try{await w.dispose()}catch(H){y1.error("Error disposing MCP client:",H)}});await Promise.all(E),Z.clear()}}}function XUA(A,Q){return JSON.stringify(A)===JSON.stringify(Q)}function $l1(A,Q,B){return{spec:{name:`mcp__${B.replace(/\s+/g,"_")}__${A.name.replace(/\s+/g,"_")}`,description:A.description??"",inputSchema:A.inputSchema,source:{mcp:B}},fn:({args:J},D)=>u9((z)=>Q.callTool({name:A.name,arguments:J??void 0},z).then((Z)=>({status:"done",result:Z.map((X)=>{if(X.type==="text"||X.type==="image")return X;throw new Error(`unsupported content type: ${X.type}`)})})))}}class kl1{forceRestart=!1;consume(){let A=this.forceRestart;return this.forceRestart=!1,A}replenish(){this.forceRestart=!0}}ED1();F2();function pl1(A){let Q={},B=!0;return A.changes.pipe(NB(void 0),uU(async(J,D)=>{if(J===void 0||B){let z=await A.keys();D?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(z.map(async(Z)=>[Z,await A.get(Z)]))),D?.throwIfAborted(),B=!1}else{let z=await A.get(J);if(D?.throwIfAborted(),z===void 0)Q={...Q,[J]:void 0},delete Q[J];else Q={...Q,[J]:z}}return Q}))}function cl1(A){let Q=A??{},B=new C8;return{async get(J){return Promise.resolve(Q[J])},async set(J,D){Q[J]=D,B.next(J)},async delete(J){delete Q[J],B.next(J)},async keys(){return Promise.resolve(Object.keys(Q))},async path(J){return Promise.resolve(void 0)},changes:B.pipe(NB(void 0))}}v7();function ll1(A){let{interval:Q,fn:B,cacheKey:J}=A,D=new Map,z=new Map;return(...Z)=>{let X=J?J(...Z):"default",K=Date.now(),G=z.get(X)||0;if(D.has(X)&&K-G<Q)return D.get(X);z.set(X,K);let q=B(...Z);return D.set(X,q),q}}iq();var Hn1=ll1({interval:20000,fn:mWA,cacheKey:(A,Q)=>A.toString()});async function mWA(A,Q,B){let J=B?.workingDirectory?.fsPath===A.fsPath?" (your working directory)":"",D=[B?.testing?"./":A.fsPath+J],z=0,Z=0,X=await Q.readdir(A),K=await Promise.all(X.filter((F)=>!Ug(e2.basename(F))).map(async(F)=>{try{let E=await Q.stat(F);return{name:e2.basename(F),isDirectory:E.isDirectory}}catch{return{name:e2.basename(F),isDirectory:!1}}}));K.sort((F,E)=>{if(F.isDirectory===E.isDirectory)return F.name.localeCompare(E.name);return F.isDirectory?-1:1});let G=500,q=K.length>G,Y=K.slice(0,G);for(let F=0;F<Y.length;F++){let{name:E,isDirectory:w}=Y[F],W=F===Y.length-1&&!q?"└ ":"├ ";if(w)z++;else Z++;let M=`${W}${E}${w?"/":""}`;D.push(M)}if(q){let F=K.length-G;D.push(`└ ... and ${F} more ${uT(F,"entry","entries")}`)}return D.join(`
6972
+ `?(Q.push(B),B=""):B+=z}return[Q,B]}class uJ1 extends Event{constructor(A,Q){var B,J;super(A),this.code=(B=Q==null?void 0:Q.code)!=null?B:void 0,this.message=(J=Q==null?void 0:Q.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](A,Q,B){return B(Lc1(this),Q)}[Symbol.for("Deno.customInspect")](A,Q){return A(Lc1(this),Q)}}function KYA(A){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(A,"SyntaxError"):new SyntaxError(A)}function pJ1(A){return A instanceof Error?"errors"in A&&Array.isArray(A.errors)?A.errors.map(pJ1).join(", "):("cause"in A)&&A.cause instanceof Error?`${A}: ${pJ1(A.cause)}`:A.message:`${A}`}function Lc1(A){return{type:A.type,message:A.message,code:A.code,defaultPrevented:A.defaultPrevented,cancelable:A.cancelable,timeStamp:A.timeStamp}}var Tc1=(A)=>{throw TypeError(A)},sJ1=(A,Q,B)=>Q.has(A)||Tc1("Cannot "+B),C9=(A,Q,B)=>(sJ1(A,Q,"read from private field"),B?B.call(A):Q.get(A)),VB=(A,Q,B)=>Q.has(A)?Tc1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(A):Q.set(A,B),E7=(A,Q,B,J)=>(sJ1(A,Q,"write to private field"),Q.set(A,B),B),vw=(A,Q,B)=>(sJ1(A,Q,"access private method"),B),YZ,DO,$T,wa,Ha,My,yT,Iy,rM,fT,gT,kT,Hy,lq,cJ1,lJ1,dJ1,_c1,iJ1,aJ1,Wy,nJ1,rJ1;class bT extends EventTarget{constructor(A,Q){var B,J;super(),VB(this,lq),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,VB(this,YZ),VB(this,DO),VB(this,$T),VB(this,wa),VB(this,Ha),VB(this,My),VB(this,yT),VB(this,Iy,null),VB(this,rM),VB(this,fT),VB(this,gT,null),VB(this,kT,null),VB(this,Hy,null),VB(this,lJ1,async(D)=>{var z;C9(this,fT).reset();let{body:Z,redirected:X,status:K,headers:G}=D;if(K===204){vw(this,lq,Wy).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(X?E7(this,$T,new URL(D.url)):E7(this,$T,void 0),K!==200){vw(this,lq,Wy).call(this,`Non-200 status code (${K})`,K);return}if(!(G.get("content-type")||"").startsWith("text/event-stream")){vw(this,lq,Wy).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(C9(this,YZ)===this.CLOSED)return;E7(this,YZ,this.OPEN);let q=new Event("open");if((z=C9(this,Hy))==null||z.call(this,q),this.dispatchEvent(q),typeof Z!="object"||!Z||!("getReader"in Z)){vw(this,lq,Wy).call(this,"Invalid response body, expected a web ReadableStream",K),this.close();return}let Y=new TextDecoder,F=Z.getReader(),E=!0;do{let{done:w,value:H}=await F.read();H&&C9(this,fT).feed(Y.decode(H,{stream:!w})),w&&(E=!1,C9(this,fT).reset(),vw(this,lq,nJ1).call(this))}while(E)}),VB(this,dJ1,(D)=>{E7(this,rM,void 0),!(D.name==="AbortError"||D.type==="aborted")&&vw(this,lq,nJ1).call(this,pJ1(D))}),VB(this,iJ1,(D)=>{typeof D.id=="string"&&E7(this,Iy,D.id);let z=new MessageEvent(D.event||"message",{data:D.data,origin:C9(this,$T)?C9(this,$T).origin:C9(this,DO).origin,lastEventId:D.id||""});C9(this,kT)&&(!D.event||D.event==="message")&&C9(this,kT).call(this,z),this.dispatchEvent(z)}),VB(this,aJ1,(D)=>{E7(this,My,D)}),VB(this,rJ1,()=>{E7(this,yT,void 0),C9(this,YZ)===this.CONNECTING&&vw(this,lq,cJ1).call(this)});try{if(A instanceof URL)E7(this,DO,A);else if(typeof A=="string")E7(this,DO,new URL(A,GYA()));else throw new Error("Invalid URL")}catch{throw KYA("An invalid or illegal string was specified")}E7(this,fT,Rc1({onEvent:C9(this,iJ1),onRetry:C9(this,aJ1)})),E7(this,YZ,this.CONNECTING),E7(this,My,3000),E7(this,Ha,(B=Q==null?void 0:Q.fetch)!=null?B:globalThis.fetch),E7(this,wa,(J=Q==null?void 0:Q.withCredentials)!=null?J:!1),vw(this,lq,cJ1).call(this)}get readyState(){return C9(this,YZ)}get url(){return C9(this,DO).href}get withCredentials(){return C9(this,wa)}get onerror(){return C9(this,gT)}set onerror(A){E7(this,gT,A)}get onmessage(){return C9(this,kT)}set onmessage(A){E7(this,kT,A)}get onopen(){return C9(this,Hy)}set onopen(A){E7(this,Hy,A)}addEventListener(A,Q,B){let J=Q;super.addEventListener(A,J,B)}removeEventListener(A,Q,B){let J=Q;super.removeEventListener(A,J,B)}close(){C9(this,yT)&&clearTimeout(C9(this,yT)),C9(this,YZ)!==this.CLOSED&&(C9(this,rM)&&C9(this,rM).abort(),E7(this,YZ,this.CLOSED),E7(this,rM,void 0))}}YZ=new WeakMap,DO=new WeakMap,$T=new WeakMap,wa=new WeakMap,Ha=new WeakMap,My=new WeakMap,yT=new WeakMap,Iy=new WeakMap,rM=new WeakMap,fT=new WeakMap,gT=new WeakMap,kT=new WeakMap,Hy=new WeakMap,lq=new WeakSet,cJ1=function(){E7(this,YZ,this.CONNECTING),E7(this,rM,new AbortController),C9(this,Ha)(C9(this,DO),vw(this,lq,_c1).call(this)).then(C9(this,lJ1)).catch(C9(this,dJ1))},lJ1=new WeakMap,dJ1=new WeakMap,_c1=function(){var A;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...C9(this,Iy)?{"Last-Event-ID":C9(this,Iy)}:void 0},cache:"no-store",signal:(A=C9(this,rM))==null?void 0:A.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},iJ1=new WeakMap,aJ1=new WeakMap,Wy=function(A,Q){var B;C9(this,YZ)!==this.CLOSED&&E7(this,YZ,this.CLOSED);let J=new uJ1("error",{code:Q,message:A});(B=C9(this,gT))==null||B.call(this,J),this.dispatchEvent(J)},nJ1=function(A,Q){var B;if(C9(this,YZ)===this.CLOSED)return;E7(this,YZ,this.CONNECTING);let J=new uJ1("error",{code:Q,message:A});(B=C9(this,gT))==null||B.call(this,J),this.dispatchEvent(J),E7(this,yT,setTimeout(C9(this,rJ1),C9(this,My)))},rJ1=new WeakMap,bT.CONNECTING=0,bT.OPEN=1,bT.CLOSED=2;function GYA(){let A="document"in globalThis?globalThis.document:void 0;return A&&typeof A=="object"&&"baseURI"in A&&typeof A.baseURI=="string"?A.baseURI:void 0}QO();var oJ1;oJ1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((A)=>A.webcrypto);async function qYA(A){return(await oJ1).getRandomValues(new Uint8Array(A))}async function YYA(A){let B="",J=await qYA(A);for(let D=0;D<A;D++){let z=J[D]%66;B+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[z]}return B}async function UYA(A){return await YYA(A)}async function FYA(A){let Q=await(await oJ1).subtle.digest("SHA-256",new TextEncoder().encode(A));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function tJ1(A){if(!A)A=43;if(A<43||A>128)throw`Expected a length between 43 and 128. Received ${A}.`;let Q=await UYA(A),B=await FYA(Q);return{code_verifier:Q,code_challenge:B}}QO();gi();var jc1=f1.object({resource:f1.string().url(),authorization_servers:f1.array(f1.string().url()).optional(),jwks_uri:f1.string().url().optional(),scopes_supported:f1.array(f1.string()).optional(),bearer_methods_supported:f1.array(f1.string()).optional(),resource_signing_alg_values_supported:f1.array(f1.string()).optional(),resource_name:f1.string().optional(),resource_documentation:f1.string().optional(),resource_policy_uri:f1.string().url().optional(),resource_tos_uri:f1.string().url().optional(),tls_client_certificate_bound_access_tokens:f1.boolean().optional(),authorization_details_types_supported:f1.array(f1.string()).optional(),dpop_signing_alg_values_supported:f1.array(f1.string()).optional(),dpop_bound_access_tokens_required:f1.boolean().optional()}).passthrough(),Pc1=f1.object({issuer:f1.string(),authorization_endpoint:f1.string(),token_endpoint:f1.string(),registration_endpoint:f1.string().optional(),scopes_supported:f1.array(f1.string()).optional(),response_types_supported:f1.array(f1.string()),response_modes_supported:f1.array(f1.string()).optional(),grant_types_supported:f1.array(f1.string()).optional(),token_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),service_documentation:f1.string().optional(),revocation_endpoint:f1.string().optional(),revocation_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),introspection_endpoint:f1.string().optional(),introspection_endpoint_auth_methods_supported:f1.array(f1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f1.array(f1.string()).optional(),code_challenge_methods_supported:f1.array(f1.string()).optional()}).passthrough(),eJ1=f1.object({access_token:f1.string(),token_type:f1.string(),expires_in:f1.number().optional(),scope:f1.string().optional(),refresh_token:f1.string().optional()}).strip(),Q92=f1.object({error:f1.string(),error_description:f1.string().optional(),error_uri:f1.string().optional()}),EYA=f1.object({redirect_uris:f1.array(f1.string()).refine((A)=>A.every((Q)=>URL.canParse(Q)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:f1.string().optional(),grant_types:f1.array(f1.string()).optional(),response_types:f1.array(f1.string()).optional(),client_name:f1.string().optional(),client_uri:f1.string().optional(),logo_uri:f1.string().optional(),scope:f1.string().optional(),contacts:f1.array(f1.string()).optional(),tos_uri:f1.string().optional(),policy_uri:f1.string().optional(),jwks_uri:f1.string().optional(),jwks:f1.any().optional(),software_id:f1.string().optional(),software_version:f1.string().optional()}).strip(),wYA=f1.object({client_id:f1.string(),client_secret:f1.string().optional(),client_id_issued_at:f1.number().optional(),client_secret_expires_at:f1.number().optional()}).strip(),Sc1=EYA.merge(wYA),B92=f1.object({error:f1.string(),error_description:f1.string().optional()}).strip(),J92=f1.object({token:f1.string(),token_type_hint:f1.string().optional()}).strip();class zO extends Error{constructor(A){super(A!==null&&A!==void 0?A:"Unauthorized")}}async function Wa(A,{serverUrl:Q,authorizationCode:B,scope:J,resourceMetadataUrl:D}){let z=Q;try{let F=await HYA(D||Q);if(F.authorization_servers&&F.authorization_servers.length>0)z=F.authorization_servers[0]}catch(F){console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server",F)}let Z=await WYA(z),X=await Promise.resolve(A.clientInformation());if(!X){if(B!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!A.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let F=await CYA(z,{metadata:Z,clientMetadata:A.clientMetadata});await A.saveClientInformation(F),X=F}if(B!==void 0){let F=await A.codeVerifier(),E=await IYA(z,{metadata:Z,clientInformation:X,authorizationCode:B,codeVerifier:F,redirectUri:A.redirectUrl});return await A.saveTokens(E),"AUTHORIZED"}let K=await A.tokens();if(K===null||K===void 0?void 0:K.refresh_token)try{let F=await NYA(z,{metadata:Z,clientInformation:X,refreshToken:K.refresh_token});return await A.saveTokens(F),"AUTHORIZED"}catch(F){console.error("Could not refresh OAuth tokens:",F)}let G=A.state?await A.state():void 0,{authorizationUrl:q,codeVerifier:Y}=await MYA(z,{metadata:Z,clientInformation:X,state:G,redirectUrl:A.redirectUrl,scope:J||A.clientMetadata.scope});return await A.saveCodeVerifier(Y),await A.redirectToAuthorization(q),"REDIRECT"}function vc1(A){let Q=A.headers.get("WWW-Authenticate");if(!Q)return;let[B,J]=Q.split(" ");if(B.toLowerCase()!=="bearer"||!J){console.log("Invalid WWW-Authenticate header format, expected 'Bearer'");return}let z=/resource_metadata="([^"]*)"/.exec(Q);if(!z)return;try{return new URL(z[1])}catch(Z){console.log("Invalid resource metadata url: ",z[1]);return}}async function HYA(A,Q){var B;let J;if(Q===null||Q===void 0?void 0:Q.resourceMetadataUrl)J=new URL(Q===null||Q===void 0?void 0:Q.resourceMetadataUrl);else J=new URL("/.well-known/oauth-protected-resource",A);let D;try{D=await fetch(J,{headers:{"MCP-Protocol-Version":(B=Q===null||Q===void 0?void 0:Q.protocolVersion)!==null&&B!==void 0?B:vT}})}catch(z){if(z instanceof TypeError)D=await fetch(J);else throw z}if(D.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!D.ok)throw new Error(`HTTP ${D.status} trying to load well-known OAuth protected resource metadata.`);return jc1.parse(await D.json())}async function WYA(A,Q){var B;let J=new URL("/.well-known/oauth-authorization-server",A),D;try{D=await fetch(J,{headers:{"MCP-Protocol-Version":(B=Q===null||Q===void 0?void 0:Q.protocolVersion)!==null&&B!==void 0?B:vT}})}catch(z){if(z instanceof TypeError)D=await fetch(J);else throw z}if(D.status===404)return;if(!D.ok)throw new Error(`HTTP ${D.status} trying to load well-known OAuth metadata`);return Pc1.parse(await D.json())}async function MYA(A,{metadata:Q,clientInformation:B,redirectUrl:J,scope:D,state:z}){let K;if(Q){if(K=new URL(Q.authorization_endpoint),!Q.response_types_supported.includes("code"))throw new Error("Incompatible auth server: does not support response type code");if(!Q.code_challenge_methods_supported||!Q.code_challenge_methods_supported.includes("S256"))throw new Error("Incompatible auth server: does not support code challenge method S256")}else K=new URL("/authorize",A);let G=await tJ1(),q=G.code_verifier,Y=G.code_challenge;if(K.searchParams.set("response_type","code"),K.searchParams.set("client_id",B.client_id),K.searchParams.set("code_challenge",Y),K.searchParams.set("code_challenge_method","S256"),K.searchParams.set("redirect_uri",String(J)),z)K.searchParams.set("state",z);if(D)K.searchParams.set("scope",D);return{authorizationUrl:K,codeVerifier:q}}async function IYA(A,{metadata:Q,clientInformation:B,authorizationCode:J,codeVerifier:D,redirectUri:z}){let X;if(Q){if(X=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("authorization_code"))throw new Error("Incompatible auth server: does not support grant type authorization_code")}else X=new URL("/token",A);let K=new URLSearchParams({grant_type:"authorization_code",client_id:B.client_id,code:J,code_verifier:D,redirect_uri:String(z)});if(B.client_secret)K.set("client_secret",B.client_secret);let G=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:K});if(!G.ok)throw new Error(`Token exchange failed: HTTP ${G.status}`);return eJ1.parse(await G.json())}async function NYA(A,{metadata:Q,clientInformation:B,refreshToken:J}){let z;if(Q){if(z=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("refresh_token"))throw new Error("Incompatible auth server: does not support grant type refresh_token")}else z=new URL("/token",A);let Z=new URLSearchParams({grant_type:"refresh_token",client_id:B.client_id,refresh_token:J});if(B.client_secret)Z.set("client_secret",B.client_secret);let X=await fetch(z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z});if(!X.ok)throw new Error(`Token refresh failed: HTTP ${X.status}`);return eJ1.parse({refresh_token:J,...await X.json()})}async function CYA(A,{metadata:Q,clientMetadata:B}){let J;if(Q){if(!Q.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");J=new URL(Q.registration_endpoint)}else J=new URL("/register",A);let D=await fetch(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!D.ok)throw new Error(`Dynamic client registration failed: HTTP ${D.status}`);return Sc1.parse(await D.json())}class $c1 extends Error{constructor(A,Q,B){super(`SSE error: ${Q}`);this.code=A,this.event=B}}class AD1{constructor(A,Q){this._url=A,this._resourceMetadataUrl=void 0,this._eventSourceInit=Q===null||Q===void 0?void 0:Q.eventSourceInit,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider}async _authThenStart(){var A;if(!this._authProvider)throw new zO("No auth provider");let Q;try{Q=await Wa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})}catch(B){throw(A=this.onerror)===null||A===void 0||A.call(this,B),B}if(Q!=="AUTHORIZED")throw new zO;return await this._startOrAuth()}async _commonHeaders(){let A={};if(this._authProvider){let Q=await this._authProvider.tokens();if(Q)A.Authorization=`Bearer ${Q.access_token}`}return A}_startOrAuth(){return new Promise((A,Q)=>{var B;this._eventSource=new bT(this._url.href,(B=this._eventSourceInit)!==null&&B!==void 0?B:{fetch:(J,D)=>this._commonHeaders().then((z)=>fetch(J,{...D,headers:{...z,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{var D;if(J.code===401&&this._authProvider){this._authThenStart().then(A,Q);return}let z=new $c1(J.code,J.message,J);Q(z),(D=this.onerror)===null||D===void 0||D.call(this,z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{var D;let z=J;try{if(this._endpoint=new URL(z.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Z){Q(Z),(D=this.onerror)===null||D===void 0||D.call(this,Z),this.close();return}A()}),this._eventSource.onmessage=(J)=>{var D,z;let Z=J,X;try{X=hi.parse(JSON.parse(Z.data))}catch(K){(D=this.onerror)===null||D===void 0||D.call(this,K);return}(z=this.onmessage)===null||z===void 0||z.call(this,X)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(A){if(!this._authProvider)throw new zO("No auth provider");if(await Wa(this._authProvider,{serverUrl:this._url,authorizationCode:A,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new zO("Failed to authorize")}async close(){var A,Q,B;(A=this._abortController)===null||A===void 0||A.abort(),(Q=this._eventSource)===null||Q===void 0||Q.close(),(B=this.onclose)===null||B===void 0||B.call(this)}async send(A){var Q,B,J;if(!this._endpoint)throw new Error("Not connected");try{let D=await this._commonHeaders(),z=new Headers({...D,...(Q=this._requestInit)===null||Q===void 0?void 0:Q.headers});z.set("content-type","application/json");let Z={...this._requestInit,method:"POST",headers:z,body:JSON.stringify(A),signal:(B=this._abortController)===null||B===void 0?void 0:B.signal},X=await fetch(this._endpoint,Z);if(!X.ok){if(X.status===401&&this._authProvider){if(this._resourceMetadataUrl=vc1(X),await Wa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new zO;return this.send(A)}let K=await X.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${X.status}): ${K}`)}}catch(D){throw(J=this.onerror)===null||J===void 0||J.call(this,D),D}}}QO();v7();F2();y2();var sM=Symbol.for("disabled-client");function vl1(A,Q,B){let J=new Fa({name:"amp-mcp-client",version:"0.0.0-dev"}),D=FA.of(void 0).pipe(Bi(()=>hk(u9(async()=>{if(await J.close(),await new Promise((G)=>setTimeout(G,100)),B)return sM;return ZUA(A,J,Q)}),Rw).pipe(KZ((G)=>{if(G instanceof Fa)G?.close()})),{shouldCountRefs:!1})),z=D.subscribe({}),Z=D.pipe(r6((G)=>{if(G===sM)return{type:"disabled"};if(G===cU)return{type:"connecting"};if(G instanceof Error)return{type:"connection-failed",error:{message:G.message}};return{type:"connected",capabilities:G.getServerCapabilities(),serverInfo:G.getServerVersion()}})),K=D.pipe(W5((G)=>{if(G===cU||G instanceof Error||G===sM)return FA.of(G);let q=new C8;return G.setNotificationHandler(UJ1,()=>{q.next()}),q.pipe(Qi({onUnsubscribe:()=>G.removeNotificationHandler("notifications/tools/list_changed")}),NB(void 0),r6(()=>G))})).pipe(Bi((G)=>{if(G instanceof Error)return FA.of(G);if(G===sM)return FA.of([]);return u9(async(q)=>{return(await G.listTools({signal:q})).tools})}));return{status:Z,tools:K,async callTool(G,q){let Y=await ux1(D);if(Y===sM)throw new Error("cannot call tools for disabled client");let F=await Y.callTool(G,void 0,{signal:q,timeout:999999000});if(!("content"in F))throw new Error("unexpected response");return F.content},async dispose(){z.unsubscribe();try{await J.close()}catch(G){y1.error("Error closing MCP client:",G)}}}}async function ZUA(A,Q,B){let J;if("url"in A)J=new AD1(new URL(A.url));else{let{loadProfileEnvironmentVariables:D}=await Promise.resolve().then(() => (BD1(),kc1)),z=B.loadProfile==="never"||!B.workingDirectory||!yM(B.workingDirectory)?process.env:await B2(D(B.workingDirectory.fsPath,B.loadProfile));J=await Promise.resolve().then(() => (Sl1(),Pl1)).then(({StdioClientTransport:Z})=>{let{AMP_API_KEY:X,...K}=z;return new Z({...A,stderr:"pipe",cwd:B.workingDirectory&&yM(B.workingDirectory)?B.workingDirectory.fsPath:void 0,env:K})})}if("stderr"in J&&J.stderr&&typeof J.stderr==="object"&&J.stderr!==null&&"on"in J.stderr&&typeof J.stderr.on==="function")J.stderr.on("data",(D)=>{let z=D.toString().trim();if(z)y1.info("mcp-server-stderr",{stderr:z,spec:A})});try{let D=Q.connect(J),z=new Promise((Z,X)=>{let K=setTimeout(()=>{clearTimeout(K),X(new Error("Connection timeout: MCP server did not respond within 30 seconds"))},30000)});return await Promise.race([D,z]),Q}catch(D){if(D instanceof Error){if(D.message.includes("Connection closed"))throw new Error("MCP server connection was closed unexpectedly. Check if the server is running and try refreshing the connection.");else if(D.message.includes("Invalid content type"))throw new Error('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in A&&D.message.includes("fetch failed"))throw new Error(`Could not connect to MCP server at ${A.url}. Check that the server is running and accessible.`)}throw D}}function fl1({configService:A,toolService:Q}){let B=new kl1,J=new C8,D=s8.pipe(r6(({settings:{mcpServers:E,"terminal.commands.nodeSpawn.loadProfile":w}})=>({mcpServers:E,loadProfile:w})),Sq()),z=A.workspaceRoots.pipe(r6((E)=>E.at(0))),Z=new Map,X=F7(D,z,J.pipe(NB(void 0))).pipe(vq(300),r6(async([{mcpServers:E,loadProfile:w},H,W])=>{let M=B.consume();for(let[I,N]of Object.entries(E??{})){let V=Z.get(I);if(!M&&V&&XUA(V.spec,N))continue;if(Z.set(I,{spec:N,client:vl1(N,{workingDirectory:H,loadProfile:w},!1)}),V)await V.client.dispose()}for(let[I,{client:N}]of Z.entries())if(!E||!(I in E))await N.dispose(),Z.delete(I);return Array.from(Z.entries())})),K=X.subscribe({}),G=X.pipe(W5((E)=>E.length===0?FA.of([]):F7(...E.map(([w,{spec:H,client:W}])=>W.tools.pipe(r6((M)=>({name:w,spec:H,tools:M===cU||M instanceof Error||M===sM?[]:M,client:W}))))))),q,Y=G.subscribe((E)=>{if(q)for(let w of q)w.dispose();q=[];for(let{name:w,tools:H,client:W}of E)for(let M of H)q.push(Q.registerTool($l1(M,W,w)))},(E)=>{y1.error("MCP toolRegisterer error",E)});return{initialized:(async()=>{try{let E=await B2(s8),w=Object.keys(E.settings.mcpServers||{}).length;if(w===0)return;await B2(X.pipe(W5((H)=>H.length===0?FA.of([]):F7(...H.map(([W,{client:M}])=>M.status.pipe(s7((I)=>I.type==="connected"||I.type==="connection-failed"||I.type==="disabled"),r6(()=>W))))),s7((H)=>H.length>=w),mx1(1)),AbortSignal.timeout(1e4))}catch(E){y1.warn("MCP service initialization failed, but service will continue:",E)}})(),servers:F7(s8,X).pipe(W5(([E,w])=>w.length===0?FA.of([]):F7(...w.map(([H,{spec:W,client:M}])=>F7(M.status,M.tools).pipe(r6(([I,N])=>({name:H,spec:W,status:I,tools:N instanceof Error?N:N===cU||N===sM?[]:N.map((V)=>({spec:{name:V.name,description:V.description,inputSchema:V.inputSchema,source:{mcp:H}},...ik({name:V.name,source:{mcp:H}},E)}))}))))))),restartServers(){B.replenish(),J.next()},async registerToolsWithService(E){return new Promise((w)=>{let H=[],W=!1,M=G.subscribe((I)=>{for(let N of H)N.dispose();H.length=0;for(let{name:N,tools:V,client:_}of I)for(let T of V)H.push(E.registerTool($l1(T,_,N)));if(!W)W=!0,w({dispose:()=>{M.unsubscribe();for(let N of H)N.dispose();H.length=0}})},(I)=>{y1.error("MCP external tool registration error",I)})})},async addServer(E,w){let H=(await B2(s8)).settings.mcpServers;if(H&&E in H)throw new Error(`MCP server already exists with name ${JSON.stringify(E)}`);if("command"in w&&typeof w.command!=="string")throw new Error("Command must be a string");if("url"in w)try{new URL(w.url)}catch(W){throw new Error(`Invalid URL: ${w.url}`)}await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async removeServer(E){let w=(await B2(s8)).settings.mcpServers;if(!w||!(E in w))throw new Error(`MCP server does not exist with name ${JSON.stringify(E)}`);let H={...w};delete H[E],await A.updateSettings("mcpServers",H,"global")},async updateServer(E,w){let H=(await B2(s8)).settings.mcpServers;if(!H||!(E in H))throw new Error(`MCP server does not exist with name ${JSON.stringify(E)}`);await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async dispose(){Y.unsubscribe(),K.unsubscribe();let E=Array.from(Z.values()).map(async({client:w})=>{try{await w.dispose()}catch(H){y1.error("Error disposing MCP client:",H)}});await Promise.all(E),Z.clear()}}}function XUA(A,Q){return JSON.stringify(A)===JSON.stringify(Q)}function $l1(A,Q,B){let J=`mcp__${B.replace(/\s+/g,"_")}__${A.name.replace(/\s+/g,"_")}`;return{spec:{name:J.length>=64?A.name:J,description:A.description??"",inputSchema:A.inputSchema,source:{mcp:B}},fn:({args:z},Z)=>u9((X)=>Q.callTool({name:A.name,arguments:z??void 0},X).then((K)=>({status:"done",result:K.map((G)=>{if(G.type==="text"||G.type==="image")return G;throw new Error(`unsupported content type: ${G.type}`)})})))}}class kl1{forceRestart=!1;consume(){let A=this.forceRestart;return this.forceRestart=!1,A}replenish(){this.forceRestart=!0}}ED1();F2();function pl1(A){let Q={},B=!0;return A.changes.pipe(NB(void 0),uU(async(J,D)=>{if(J===void 0||B){let z=await A.keys();D?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(z.map(async(Z)=>[Z,await A.get(Z)]))),D?.throwIfAborted(),B=!1}else{let z=await A.get(J);if(D?.throwIfAborted(),z===void 0)Q={...Q,[J]:void 0},delete Q[J];else Q={...Q,[J]:z}}return Q}))}function cl1(A){let Q=A??{},B=new C8;return{async get(J){return Promise.resolve(Q[J])},async set(J,D){Q[J]=D,B.next(J)},async delete(J){delete Q[J],B.next(J)},async keys(){return Promise.resolve(Object.keys(Q))},async path(J){return Promise.resolve(void 0)},changes:B.pipe(NB(void 0))}}v7();function ll1(A){let{interval:Q,fn:B,cacheKey:J}=A,D=new Map,z=new Map;return(...Z)=>{let X=J?J(...Z):"default",K=Date.now(),G=z.get(X)||0;if(D.has(X)&&K-G<Q)return D.get(X);z.set(X,K);let q=B(...Z);return D.set(X,q),q}}iq();var Hn1=ll1({interval:20000,fn:mWA,cacheKey:(A,Q)=>A.toString()});async function mWA(A,Q,B){let J=B?.workingDirectory?.fsPath===A.fsPath?" (your working directory)":"",D=[B?.testing?"./":A.fsPath+J],z=0,Z=0,X=await Q.readdir(A),K=await Promise.all(X.filter((F)=>!Ug(e2.basename(F))).map(async(F)=>{try{let E=await Q.stat(F);return{name:e2.basename(F),isDirectory:E.isDirectory}}catch{return{name:e2.basename(F),isDirectory:!1}}}));K.sort((F,E)=>{if(F.isDirectory===E.isDirectory)return F.name.localeCompare(E.name);return F.isDirectory?-1:1});let G=500,q=K.length>G,Y=K.slice(0,G);for(let F=0;F<Y.length;F++){let{name:E,isDirectory:w}=Y[F],W=F===Y.length-1&&!q?"└ ":"├ ";if(w)z++;else Z++;let M=`${W}${E}${w?"/":""}`;D.push(M)}if(q){let F=K.length-G;D.push(`└ ... and ${F} more ${uT(F,"entry","entries")}`)}return D.join(`
6973
6973
  `)}wz();F2();class wG1{storage;constructor(A){this.storage=A;this._observeHistory=kM(pl1(this.storage).pipe(r6((Q)=>{let B=Object.values(Q).filter((D)=>D&&("messages"in D)).toSorted((D,z)=>z.created-D.created),J=[];for(let D of B)if(D.messages.length!==0)J.push(D);return J.map((D)=>({id:D.id,v:D.v,created:D.created,title:D.title??null,userLastInteractedAt:uWA(D),env:D.env,originThreadID:D.originThreadID,mainThreadID:D.mainThreadID})).toSorted((D,z)=>z.userLastInteractedAt-D.userLastInteractedAt)}),mK()))}async delete(A){let Q=await this.storage.keys(),B=[];for(let J of Q){let D=await this.storage.get(J);if(D&&D.mainThreadID===A)B.push(D.id)}for(let J of B)await this.storage.delete(J);await this.storage.delete(A)}observeHistory(){return this._observeHistory.observable}_observeHistory;dispose(){this._observeHistory.subscription.unsubscribe()}}function uWA(A){return Math.max(A.created,...A.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}F2();yq();y2();function Bj(){return new Promise((A)=>setTimeout(A,0))}var Mn1=G6(BT(),1);yq();Oi();class HG1{storage;exclusiveThreads=new Map;exclusiveThreadsChanged=new C8;exclusiveThreadsChanges=this.exclusiveThreadsChanged.pipe(NB(void 0),Lw(()=>lWA.record(this.exclusiveThreads.size)),r6(()=>this.exclusiveThreads));flushRequests=new C8;flusher=this.exclusiveThreadsChanged.pipe(r6(()=>Array.from(this.exclusiveThreads.keys())),W5((A)=>A.length>0?F7(...A.map((Q)=>{let B=this.exclusiveThreads.get(Q);if(!B)return Rw;return F7(B.pipe(vq(0),NB(void 0)),this.flushRequests.pipe(NB(void 0))).pipe(uU(async()=>{let[J]=B.getValue();await this.storage.set(Q,J)}),pU((J)=>{return y1.error("Error flushing thread to storage:",J,{name:"ThreadService",threadID:Q}),Rw}))})):Rw)).subscribe({});constructor(A){this.storage=A}observeRaw(A){return this.exclusiveThreadsChanged.pipe(NB(void 0),r6(()=>this.exclusiveThreads.has(A)),Sq(),W5((Q)=>{if(Q)return this.exclusiveThreads.get(A).pipe(r6(([B,J])=>[B,J]));return u9(async(B)=>{let J=await this.storage.get(A);if(B?.throwIfAborted(),!J)J=Wn1(A),await this.storage.set(A,J),B?.throwIfAborted();return[qT(J,!0),[]]})}))}observe(A){return this.observeRaw(A).pipe(r6(([Q,B])=>Q),GB1(100,{leading:!0,trailing:!0}))}observePatches(A){return this.observeRaw(A).pipe(r6(([Q,B],J)=>J===0?Q:B),pWA(100))}async exclusiveSyncReadWriter(A){if(this.exclusiveThreads.has(A))throw new Error(`Thread ${A} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(A);if(!Q){let D=await this.storage.get(A);if(!D)D=Wn1(A),await this.storage.set(A,D);D=qT(D,!0),Q=new ND([D,[]]),this.exclusiveThreads.set(A,Q),this.exclusiveThreadsChanged.next(),await Bj()}let B=!1;return{read:()=>{if(B)throw new Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(D)=>{if(B)throw new Error("thread exclusive read-writer was disposed");let[z,Z]=iB1(Q.getValue()[0],()=>{return D});Q.next([z,Z])},update:(D)=>{if(B)throw new Error("thread exclusive read-writer was disposed");let[z,Z]=iB1(Q.getValue()[0],D);return Q.next([z,Z]),z},dispose:()=>{if(!B)B=!0,this.exclusiveThreads.delete(A),this.exclusiveThreadsChanged.next()}}}flush(){this.flushRequests.next()}async flushVersion(A,Q,B=5000){this.flush();let J=Date.now();while(!0){if(Date.now()-J>B)throw new Error(`Timed out waiting for thread ${A} to reach version ${Q}`);let D=await this.storage.get(A);if(D&&D.v>=Q)return;await new Promise((z)=>setTimeout(z,10))}}deleteFromExclusiveAccess(A){this.exclusiveThreads.delete(A),this.exclusiveThreadsChanged.next()}dispose(){this.flusher.unsubscribe(),this.exclusiveThreads.clear()}}function Wn1(A){return{v:0,id:A,created:Date.now(),messages:[]}}function pWA(A){return(Q)=>new FA((B)=>{let J=[],D=null,z=()=>{if(D)clearTimeout(D),D=null;if(J.length>0)B.next(J),J=[]};return Q.subscribe({next:(Z)=>{if(!(Z instanceof Array)){z(),B.next(Z);return}J.push(...Z),D=setTimeout(z,A)},error:(Z)=>{z(),B.error(Z)},complete:()=>{z(),B.complete()}})})}var cWA=Mn1.metrics.getMeter("thread-service"),lWA=cWA.createGauge("thread-service.exclusive-thread-count",{description:"Number of exclusive thread handles",unit:"threads"});F2();y2();CD();yk();Fg();pn();function Cn1({threadService:A,threadHistoryService:Q,isExtensionDevelopment:B=!1}){let J=!1,D=[],z=vx1(),Z=new ND(new Map),X=async()=>{if(J)return!1;if(!await B2(In1))return!1;let H=await B2(s8);if(B&&_x1(H.settings.url))return y1.debug(`Skipping sync to ${hK} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;return!0},K=async(H)=>{if(!Y(H))return;let W=await B2(A.observe(H));if(W&&!W.messages.length)return;if(!await X())return;let M=new AbortController;D.push({dispose:()=>M.abort()});let I=!1;try{let N=await wO.uploadThread({thread:W,createdOnServer:!1},{signal:M.signal});if(!N.ok)throw new Error(`Failed to upload thread: ${N.error.code}`);I=!0}catch(N){if(y1.debug("Failed to upload thread (USE_NEW_INTERNAL_API=true)",N),!mw)throw N}if(!I&&mw){let N=await OB(`/api/threads/${H}`,{method:"POST",body:JSON.stringify(W),signal:M.signal});if(!N.ok){let V=await N.text().catch(()=>"Unable to read response body");throw new Error(`Thread sync API (for thread ${H}) responded with status: ${N.status}${V?`: ${V}`:""}`)}}},G=new Map,q=60000,Y=(H)=>{let W=G.get(H);if(!W)return!0;let M=Date.now()-W,I=M>=q;if(!I)y1.debug(`Skipping thread ${H} sync due to backoff (${Math.round(M/1000)}s elapsed of ${q/1000}s backoff)`,{name:"ThreadSyncService"});return I},F=async()=>{for(let H of z.set){if(!Y(H))continue;try{await K(H),z.delete(H),G.delete(H)}catch(W){G.set(H,Date.now()),y1.error(`Error syncing thread ${H} (will retry after backoff)`,W,{name:"ThreadSyncService"})}}},E=async(H,W=!1)=>{if(!await X())return;let M;if(H)M=(await Promise.all(H.map((j)=>B2(A.observe(j).pipe(r6((P)=>P?{id:P.id,v:P.v}:null)))))).filter((j)=>j!==null);else{let j=await B2(Q.observeHistory().pipe(r6(($)=>$.map((f)=>({id:f.id,v:f.v}))))),P=await B2(A.exclusiveThreadsChanges.pipe(r6(($)=>Object.values($).map(([f,m])=>({id:f.id,v:f.v})))));M=j.concat(P)}let I={threadVersions:[],threadMetas:[]},N=new Set;for(let j of M){if(N.has(j.id))continue;if(N.add(j.id),!W)I.threadVersions.push({id:j.id,v:j.v});let P=Z.getValue().get(j.id);I.threadMetas.push({id:j.id,meta:P&&P.status==="synced"?P.info?.meta:void 0})}if(I.threadVersions.length===0&&I.threadMetas.length===0)return;if(!await X())return;let V=new AbortController;D.push({dispose:()=>V.abort()}),y1.debug("Sending threads sync request",{name:"ThreadSyncService"});let _=await OB("/api/threads/sync",{method:"POST",body:JSON.stringify(I),signal:V.signal});if(!_.ok){let j=await _.text().catch(()=>"Unable to read response body");throw y1.warn("Threads sync request failed",{name:"ThreadSyncService",status:_.status,text:j}),new Error(`Threads sync API responded with status: ${_.status}${j?`: ${j}`:""}`)}y1.debug("Got response for threads sync request",{name:"ThreadSyncService",status:_.status});let T=await _.json(),R=0;for(let j of T.threadActions){if(!(("action"in j)&&typeof j.action==="string"))continue;switch(j.action){case"upload":{z.add(j.id),R++;break}case"meta":{Z.getValue().set(j.id,{status:"synced",info:{meta:j.meta}});break}default:continue}}if(H){for(let j of H)if(Z.getValue().get(j)?.status==="unknown")Z.getValue().set(j,{status:"synced",info:null})}Z.next(Z.getValue()),await F(),y1.debug(`Sync completed (${H?H.length:"all"} threads checked, ${R} threads needed sync)`,{name:"ThreadSyncService"})},w=E().catch((H)=>y1.error("Failed to perform initial sync:",H,{name:"ThreadSyncService"}));return D.push(KB1(z.observable.pipe(s7((H)=>H.size>0),vq(3000),uU(()=>F().catch((H)=>y1.error("Error processing sync queue:",H,{name:"ThreadSyncService"})))).subscribe({}))),D.push(KB1(A.exclusiveThreadsChanges.pipe(W5((H)=>mU(...Array.from(H.entries()).map(([,W])=>W.pipe(Lw(([M,I])=>z.add(M.id))))))).subscribe({}))),{async sync(){return E()},initialSyncComplete:w,async updateThreadMeta(H,W){let M=Z.getValue().get(H);try{Z.getValue().set(H,{status:"synced",info:{meta:W}}),Z.next(Z.getValue());let I=new AbortController;D.push({dispose:()=>I.abort()});let N=!1;try{let V=await wO.setThreadMeta({thread:H,meta:W},{signal:I.signal});if(!V.ok)throw new Error(`Failed to update sharing status: ${V.error.code}`);N=!0}catch(V){if(y1.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",V),!mw)throw V}if(!N&&mw){let V=await OB(`/api/threads/${H}/meta`,{method:"PUT",body:JSON.stringify({private:W.private,public:W.public}),signal:I.signal});if(!V.ok)throw new Error(`Failed to update sharing status: ${V.status}`)}}catch(I){if(M)Z.getValue().set(H,M);else Z.getValue().delete(H);throw Z.next(Z.getValue()),I}},threadSyncInfo(H){for(let W of H)if(!Z.getValue().has(W))Z.getValue().set(W,{status:"unknown"});return E(H,!0).catch((W)=>y1.error("Error syncing thread metadata:",W,{name:"ThreadSyncService"})),Z.pipe(r6((W)=>{let M={};for(let I of H)M[I]=W.get(I)??{status:"synced",info:null};return M}))},dispose(){if(J)return;J=!0;for(let H of D)H.dispose()}}}ts();cK();Iw1();r$();F2();y2();dL();F2();Po();y2();dL();pK();cK();class jP1 extends C8{#A=new AbortController;#Q="o3";#B=[];#J=[];constructor(A,Q,B,J){rQ(J.dir);let D=kq();A.forEach((z)=>D.registerTool(z));super();this.start(D,Q,B,J).catch((z)=>{this.error(z)}).finally(()=>{this.complete()})}dispose(){this.#A.abort()}async start(A,Q,B,J){this.#A.signal.throwIfAborted();let D=[{role:"user",content:B}];while(!0){this.#A.signal.throwIfAborted();let{systemPrompt:z,tools:Z}=await n$({...J,toolService:A,getThreadEnvironment:()=>Promise.resolve(J.threadEnvironment)},J.thread,{enableTodos:!1,enableTask:!1,enableOracle:!1},this.#A.signal);this.#A.signal.throwIfAborted();let X=z.map((w)=>w.text).join(`
6974
6974
  `),K=Q?`${Q}
6975
6975
 
@@ -7325,7 +7325,7 @@ ${B.join(`
7325
7325
  `)}function qs6(A,Q){if(A.state!=="active")return{type:"idle"};let B=pC(Q);if(B)return B;if(A.state==="active"){let J=[];for(let D of Q.messages)if(D.role==="user"){for(let z of D.content)if(z.type==="tool_result"&&z.run.status==="in-progress")J.push(z)}if(J.length>0){let D=J[0],z=$7(Q,D.toolUseID);if(z){let Z=J.slice(1).map((X)=>{return $7(Q,X.toolUseID)?.name||"tool"}).filter(Boolean);return T51(z.name,J.length,Date.now(),z.input,Z.length>0?Z:void 0)}}}return{type:"idle"}}class lf1{dependencies;subthreads=new Map;nextAgentNumber=1;events=new C8;constructor(A){this.dependencies=A}get events$(){return this.events}async trackSubthread(A,Q,B){if(this.subthreads.has(A))return;try{let J=await nZ.getOrCreateForThread({configService:this.dependencies.configService,threadService:this.dependencies.threadService,toolService:this.dependencies.toolService,getThreadEnvironment:Hf,systemPromptService:this.dependencies.systemPromptService,threadSummaryService:this.dependencies.threadSummaryService,createFileSystem:await Id,threadHistoryService:this.dependencies.threadHistoryService,mcpService:this.dependencies.mcpService},A);await J.resume();let D=this.nextAgentNumber++,z={threadID:A,worker:J,agentNumber:D,printedMessageIndexes:new Set,printedToolRuns:new Set,requestedToolConfirmations:new Set,taskDescription:Q,isCompleted:!1};if(this.subthreads.set(A,z),Q&&B)this.events.next({type:"subagent-started",subThreadID:A,agentNumber:D,taskDescription:Q,taskPrompt:B});J.status.subscribe(async(X)=>{if(!z.isCompleted){if(X.state==="active"&&X.inferenceState==="cancelled"){z.isCompleted=!0,this.events.next({type:"subagent-cancelled",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task cancelled"});return}if(X.state==="active"&&X.ephemeralError){z.isCompleted=!0,this.events.next({type:"subagent-error",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task failed",error:X.ephemeralError.message||"Unknown error occurred"});return}try{let K=await B2(this.dependencies.threadService.observe(A).pipe(s7((G)=>G!==void 0)));if(K){let G=qs6(X,K);if(this.events.next({type:"subagent-status",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Running task",agentState:G}),X.state==="active"){let q=[];for(let Y of K.messages)if(Y.role==="user"){for(let F of Y.content)if(F.type==="tool_result"&&F.run.status==="in-progress")q.push(F)}for(let Y of q){let F=$7(K,Y.toolUseID);if(F){let E=`${A}-${F.id}`;if(!z.toolStartTimes)z.toolStartTimes=new Map;if(!z.toolStartTimes.has(E))z.toolStartTimes.set(E,Date.now());this.events.next({type:"tool-status",toolUse:F,status:"running",startTime:z.toolStartTimes.get(E),subthreadID:A})}}}}}catch(K){y1.error(`Failed to get thread for status update: ${A}`,K)}}}),kM(this.dependencies.threadService.observe(A).pipe(s7((X)=>X!==void 0))).observable.subscribe((X)=>{if(!X)return;let K=Ez(X,"assistant");if(Li(K)&&!z.isCompleted){z.isCompleted=!0,this.events.next({type:"subagent-cancelled",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task cancelled"});return}if(K?.state?.type==="error"&&!z.isCompleted){z.isCompleted=!0,this.events.next({type:"subagent-error",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task failed",error:K.state.error.message||"Unknown error occurred"});return}for(let F of X.messages)if(F.role==="user"){for(let E of F.content)if(E.type==="tool_result"){let w=$7(X,E.toolUseID);if(w&&!z.printedToolRuns.has(E.toolUseID)){let H=E.run.status==="done"?"completed":E.run.status==="error"?"error":E.run.status==="cancelled"?"cancelled":void 0;if(H){z.printedToolRuns.add(E.toolUseID);let W=`${A}-${w.id}`,M=z.toolStartTimes?.get(W);if(this.events.next({type:"tool-status",toolUse:w,status:H,startTime:M,endTime:Date.now(),subthreadID:A}),z.toolStartTimes)z.toolStartTimes.delete(W)}}}}let q=Ez(X,"user")?.content.filter((F)=>F.type==="tool_result"&&F.run.status==="blocked-on-user")??[];if(q.length>0&&!z.isCompleted){let F=[];for(let E of q){let w=$7(X,E.toolUseID);if(w&&w.name===s4&&E.run.status==="blocked-on-user"&&E.userInput===void 0&&!z.requestedToolConfirmations.has(E.toolUseID))F.push({useBlock:w,toAllow:E.run.toAllow}),z.requestedToolConfirmations.add(E.toolUseID)}if(F.length>0)this.events.next({type:"subthread-tool-request",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Running task",tools:F})}if(K?.state.type==="complete"&&K?.state.stopReason==="end_turn"&&!z.isCompleted){z.isCompleted=!0;let F=K.content.filter((E)=>E.type==="text").map((E)=>E.text).join(`
7326
7326
 
7327
7327
  `);this.events.next({type:"subagent-finished",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task completed",result:F})}if(!z.isCompleted){let F=$f(X,z.printedMessageIndexes,z.printedToolRuns);if(F.blocks.length>0)this.events.next({type:"subthread-message",subThreadID:A,agentNumber:z.agentNumber,blocks:F.blocks})}}),y1.debug(`Started tracking subthread ${A}`)}catch(J){y1.error(`Failed to track subthread ${A}`,J)}}scanForTaskToolSubthreads(A){for(let Q of A.messages)if(Q.role==="user"){for(let B of Q.content)if(B.type==="tool_result"){let J=$7(A,B.toolUseID);if(J?.name===UQ&&(B.run.status==="in-progress"||B.run.status==="done"||B.run.status==="cancelled")){let D="progress"in B.run?B.run.progress:void 0,z=By(D);if(z)this.trackSubthread(z,J.input?.description,J.input?.prompt).catch((Z)=>{y1.error(`Failed to track Task tool subthread ${z}`,Z)})}}}}async handleToolConfirmations(A,Q){let B=this.subthreads.get(A);if(!B){y1.error(`No tracker found for subthread ${A}`);return}y1.info(`Sending tool confirmations to subthread ${A}`,{toolCount:Q.size,responses:Array.from(Q.entries()).map(([J,D])=>({id:J,accepted:D}))});for(let[J,D]of Q)y1.info("Sending tool confirmation to subthread worker",{subThreadID:A,toolUseID:J,accepted:D}),await B.worker.handle({type:"user:tool-input",toolUse:J,value:{accepted:D}})}dispose(){for(let A of this.subthreads.values())A.worker.dispose();this.subthreads.clear(),this.events.complete()}}y2();function D4A(A){let Q=["prompt is too long","exceed context limit"],B=A.error?.type==="invalid_request_error"&&Q.some((D)=>A.error?.message?.includes(D)),J=Q.some((D)=>A.message?.includes(D));return B||J}var z4A="Out of credits";wz();Zl();Wi();F2();j51();AK();c21();dL();import{readdir as Ys6}from"node:fs/promises";import{homedir as Us6}from"node:os";async function Z4A(A,Q){let J=!(await l21(A,Q)).some((z)=>z.type==="project"),D=await Fs6();return{shouldGenerate:J&&D}}async function Fs6(){let A=process.cwd(),Q=Us6();if(A===Q)return!1;try{return(await Ys6(A)).length>0}catch{return!1}}async function X4A(A){await A.handle({type:"user:message",message:{content:[{type:"text",text:Su0}]}})}y2();function d3(A,Q){return(B,J)=>{let D=Q(B,J);if(J.type!=="tick")y1.debug("Transition",{name:A,before:B,event:J,after:D});return D}}y2();import{spawn as G4A}from"node:child_process";import{readlink as Es6,stat as ws6}from"node:fs/promises";import{dirname as K4A,join as Hs6}from"node:path";async function q4A(A){try{let Q=new AbortController,B=setTimeout(()=>Q.abort(),500),J=await fetch("https://registry.npmjs.org/@sourcegraph/amp/latest",{signal:Q.signal});if(clearTimeout(B),!J.ok)return{hasUpdate:!1};let z=(await J.json()).version;if(z===void 0)return{hasUpdate:!1};let Z=Ws6(A,z),X=Z<0;return y1.info("Version comparison",{currentVersion:A,latestVersion:z,compareResult:Z,hasUpdate:X}),{hasUpdate:X,latestVersion:z}}catch(Q){return{hasUpdate:!1}}}function Ws6(A,Q){let B=(Z)=>{let[X,K]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:K}},J=B(A),D=B(Q),z=Math.max(J.parts.length,D.parts.length);for(let Z=0;Z<z;Z++){let X=J.parts[Z]||0,K=D.parts[Z]||0;if(X<K)return-1;if(X>K)return 1}if(J.label===D.label)return 0;if(!J.label&&D.label)return 1;if(J.label&&!D.label)return-1;if(J.label&&D.label)return J.label<D.label?-1:1;return 0}async function Ms6(){try{let A=process.argv[1]||"";y1.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{let z=await Es6(A);if(z)Q=z,y1.debug("Resolved symlink",{from:A,to:Q});else y1.debug("Not a symlink or readlink returned empty")}catch(z){y1.debug("Error reading symlink (probably not a symlink)",{error:z})}if(y1.debug("Resolved installation path",{actualPath:Q}),Q.includes("/.local/share/pnpm/"))return y1.debug("Detected pnpm from path pattern: /.local/share/pnpm/"),"pnpm";if(Q.includes("/.config/yarn/global/"))return y1.debug("Detected yarn from path pattern: /.config/yarn/global/"),"yarn";if(Q.includes("/.bun/install/global/"))return y1.debug("Detected bun from path pattern: /.bun/install/global/"),"bun";if(Q.includes("/node_modules/@sourcegraph/amp/")){if(y1.debug("Found generic node_modules path, checking for specific patterns"),Q.includes("/.local/share/pnpm/"))return y1.debug("Detected pnpm from node_modules with pnpm-specific path"),"pnpm";if(Q.includes("/.config/yarn/"))return y1.debug("Detected yarn from node_modules with yarn-specific path"),"yarn";if(Q.includes("/.bun/"))return y1.debug("Detected bun from node_modules with bun-specific path"),"bun";return y1.debug("Defaulting to npm for generic node_modules path"),"npm"}y1.debug("No path pattern matched, checking installation directory for lockfiles");let B=K4A(K4A(Q));y1.debug("Checking installation directory",{installDir:B});let J=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:z,manager:Z}of J)try{let X=Hs6(B,z);return y1.debug("Checking for lockfile",{filePath:X}),await ws6(X),y1.debug("Found package manager lockfile",{file:z,manager:Z,filePath:X}),Z}catch(X){y1.debug("Lockfile not found",{file:z,error:X})}y1.debug("No lockfiles found, falling back to environment-based detection");let D=await Y4A();return y1.debug("Environment-based detection result",{envDetected:D}),D}catch(A){return y1.debug("Error detecting installed package manager",{error:A}),null}}async function Y4A(){let A=process.env.npm_config_user_agent;if(A){if(A.includes("pnpm"))return"pnpm";if(A.includes("yarn"))return"yarn";if(A.includes("bun"))return"bun";if(A.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Q,B,J,D]=await Promise.allSettled([P51("pnpm"),P51("yarn"),P51("bun"),P51("npm")]);if(Q?.status==="fulfilled"&&Q?.value)return"pnpm";if(B?.status==="fulfilled"&&B?.value)return"yarn";if(J?.status==="fulfilled"&&J?.value)return"bun";if(D?.status==="fulfilled"&&D?.value)return"npm";return null}async function P51(A){return new Promise((Q)=>{try{let B=process.env.HOME||process.env.USERPROFILE||"/",D=`env -i ${process.env.SHELL||"/bin/sh"} -l -c 'cd ${B} && ${A} --version'`;y1.debug("Checking command existence",{command:A,fullCommand:D});let z=G4A("/bin/sh",["-c",D],{stdio:"ignore",cwd:process.env.HOME});z.on("close",(Z)=>{y1.debug("Command check result",{command:A,code:Z}),Q(Z===0)}),z.on("error",(Z)=>{y1.debug("Command check error",{command:A,error:Z}),Q(!1)})}catch(B){y1.debug("Error checking command existencer",{command:A,error:B}),Q(!1)}})}function Is6(A,Q){let B=Q?`@sourcegraph/amp@${Q}`:"@sourcegraph/amp";switch(A){case"pnpm":return["pnpm",["add","-g",B]];case"yarn":return["yarn",["global","add",B]];case"bun":return["bun",["add","-g",B]];case"npm":default:return["npm",["install","-g",B]]}}async function U4A(A){let Q=await Ms6();if(!Q)Q=await Y4A();if(!Q)Q="npm",y1.debug("Falling back to npm for update");y1.debug("Using package manager for update",{packageManager:Q,targetVersion:A});let[B,J]=Is6(Q,A);return new Promise((D,z)=>{let Z=process.env.HOME||process.env.USERPROFILE||"/",X=process.env.SHELL||"/bin/sh",K=`${B} ${J.join(" ")}`,G=`env -i ${X} -l -c 'cd ${Z} && ${K}'`;y1.debug("Running update command",{packageManager:Q,command:B,args:J,fullCommand:G});let q=G4A("/bin/sh",["-c",G],{stdio:"pipe",cwd:process.env.HOME}),Y="",F="";q.stdout?.on("data",(E)=>{Y+=E.toString()}),q.stderr?.on("data",(E)=>{F+=E.toString()}),q.on("close",(E)=>{if(E===0)D();else{let w=F||Y||"No output";z(new Error(`${B} ${J.join(" ")} failed with code ${E}:
7328
- ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function F4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let W=GT(),M=new Set,I=kM(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await B2(I.observable);let _=await Id,T=await nZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Hf,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{y1.error("Initial resume",S)});let R=T.status.pipe(r6((S)=>{return{type:"worker-state",status:S}})),j=I.observable.pipe(r6((S)=>{return{type:"thread-state",thread:S}})),P=new C8,$=new C8,f=H(FA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=W.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=mU(R,j,mU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{y1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await W.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(KZ(()=>{b()})).pipe(zT(d3("threadSession",function(S,y){function d(D1){y1.info(`Processing user message: ${D1.slice(0,50)}${D1.length>50?"...":""}`);let A1="tokenUsage"in S?S.tokenUsage:void 0;if(A1&&A1.used/A1.maxAvailable>S51.CRITICAL)return y1.info("Blocking message at worker boundary - critical token usage"),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:"final",updateState:"updateState"in S?S.updateState:"none",toolConfirmationStatus:"toolConfirmationStatus"in S?S.toolConfirmationStatus:new Map,currentAssistantMessageIndex:("currentAssistantMessageIndex"in S?S.currentAssistantMessageIndex:null)??null,hasBeenIdle:"hasBeenIdle"in S?S.hasBeenIdle:!1,threadTitle:"threadTitle"in S?S.threadTitle:null,confirmationQueue:"confirmationQueue"in S?S.confirmationQueue:[]};T.handle({type:"user:message",message:{content:[{type:"text",text:D1}]}}).then(()=>{if(A)A.sync().catch((X1)=>{y1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{y1.error("Handle user message failed",X1)}),$.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});let K1=I.value.last;if(K1){let X1=pC(K1);if(X1)$.next({type:"state",state:X1})}return{...S,type:"awaiting-agent",displayedError:null}}async function a(){$.next({type:"state",state:{type:"compacting"}});let D1=await X.summarizeThread(E);await T.handle({type:"summary:created",summary:{type:"internal",summary:D1.summary}})}function z1(){if(S.type==="awaiting-user-message")return y1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{y1.error("Thread sync error",A1,{threadID:E})}),D1&&S.type!=="confirming-compaction"&&S.type!=="compacting"){let A1=D1.used/D1.maxAvailable,K1=void 0,X1=S.compactionPromptState;if(A1>S51.CRITICAL)K1="critical",X1="final";else if(A1>S51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>S51.SEVERE&&S.compactionPromptState==="first")K1="severe",X1="final";if(K1)return $.next({type:"confirm",confirmation:{type:"compaction",severity:K1}}),{type:"confirming-compaction",severity:K1,tokenUsage:S.tokenUsage,compactionPromptState:X1,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue}}if($.next({type:"accept-message",initial:!S.hasBeenIdle&&!w}),S.type==="awaiting-agent")S.cancelledWithMessage=void 0;if(D1)$.next({type:"token-usage",tokenUsage:D1});return{...S,type:"awaiting-user-message",hasBeenIdle:!0,tokenUsage:D1??null}}function t(D1){if(D1.length>0)y1.info(`Updating allowlist with ${D1.length} entries`,{entries:D1}),K.get("commands.allowlist","global").then((A1)=>{let K1=[...A1??[],...D1];return K.set("commands.allowlist",K1,"global")}).catch((A1)=>{y1.error("Failed to update allowlist",A1)})}if(S.type==="closing")return S;if(y.type==="thread-state"){let D1=y.thread.title||null;if(S.threadTitle!==D1&&D1!==null)$.next({type:"thread-title",title:D1});if(F.scanForTaskToolSubthreads(y.thread),w&&M.size===0&&y.thread.messages.length>0){let K1=$f(y.thread,M,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Ri(y.thread);if(K1)A1={used:K1.totalInputTokens,maxAvailable:K1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}if(S.type==="awaiting-user-confirmation")if(y.thread.messages.at(-1)?.content.some((K1)=>K1.type==="tool_result"&&(K1.run.status==="in-progress"||K1.run.status==="done"))){let K1=pC(y.thread);if(K1)$.next({type:"state",state:K1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};if(S.type==="awaiting-agent"||S.type==="compacting"){let K1=y.thread.messages.at(-1),X1=$f(y.thread,M,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=pC(y.thread);if(U1)$.next({type:"state",state:U1})}if(N1.length>0){for(let Y1 of N1)if(Y1.type==="toolResult"){let[U1,P1]=Y1.data,R1=P1.run.status==="done"?"completed":P1.run.status==="error"?"error":P1.run.status==="cancelled"?"cancelled":"running";if(R1!=="running")$.next({type:"tool-status",toolUse:U1,status:R1,startTime:V.get(U1.id),endTime:Date.now()}),V.delete(U1.id)}$.next({type:"messages",blocks:N1})}if(y.thread.messages.at(-1)?.content.some((Y1)=>Y1.type==="summary"))return{...z1(),tokenUsage:null,compactionPromptState:"none"};if(K1?.role==="assistant"&&K1?.state.type==="complete"&&K1?.state.stopReason==="end_turn"){$.next({type:"state",state:{type:"idle"}});let Y1=z1();return{...Y1,tokenUsage:A1??Y1.tokenUsage}}if(!I)throw new Error("unexpected: thread is required when waiting for tool input");let r=Ez(y.thread,"assistant"),s=r?y.thread.messages.indexOf(r):null;if(s!==null&&s!==S.currentAssistantMessageIndex)y1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:s,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=s;let e=Ez(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(r?.content.filter((Y1)=>Y1.type==="tool_use").map((Y1)=>Y1.id)??[]),q1=!1;for(let Y1 of e){if(!G1.has(Y1.toolUseID))continue;let U1=$7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===s4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,y1.info("Added new tool to confirmation tracking",{toolUseID:Y1.toolUseID,toolName:U1.name}),!V.has(U1.id))V.set(U1.id,Date.now());$.next({type:"tool-status",toolUse:U1,status:"blocked-on-user",startTime:V.get(U1.id)})}}if(q1){let Y1=Array.from(S.toolConfirmationStatus.entries()).filter(([U1,P1])=>P1==="awaiting");if(Y1.length>0){let[U1]=Y1[0],P1=e.find((T1)=>T1.toolUseID===U1),R1=P1?$7(y.thread,P1.toolUseID):null;if(P1&&R1)return y1.info(`Starting tool confirmation process for ${Y1.length} tools`,{firstToolID:U1,toolName:R1.name}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:R1,toAllow:P1.run.status==="blocked-on-user"?P1.run.toAllow:void 0}]}}),{...S,type:"collecting-tool-confirmations",currentToolID:U1,tokenUsage:A1}}}}}else if(y.type==="worker-state"){if(S.type==="awaiting-user-confirmation"&&y.status.state==="active"&&y.status.ephemeralError)return S;if(S.type==="collecting-tool-confirmations")return y1.info("Already collecting tool confirmations, ignoring worker-state event"),S;let D1=I.value.last?.messages.at(-1),A1=S.tokenUsage;if(y.status.state==="active"){let K1=I.value.last;if(K1){let X1=Ri(K1);if(X1)A1={used:X1.totalInputTokens,maxAvailable:X1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}}if(S.type==="confirming-compaction"||S.type==="compacting")return{...S,tokenUsage:A1};switch(y.status.state){case"initial":if(S.type==="initializing")return S;return z1();case"active":if(y.status.ephemeralError)if(y.status.ephemeralError.message.includes(z4A)){if(S.type==="out-of-credits")return S;return $.next({type:"confirm",confirmation:{type:"out-of-credits"}}),{...S,type:"out-of-credits",tokenUsage:A1}}else if(D4A(y.status.ephemeralError))return y1.info("Context limit error, triggering compaction",{error:y.status.ephemeralError,tokenUsage:A1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:S.compactionPromptState,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue};else if(y.status.ephemeralError.message.includes("401 unauthorized"))return $.next({type:"error",error:{type:"unauthorized"},retryable:!1}),u.unsubscribe(),{...S,type:"closing"};else{let K1=y.status.ephemeralError.message;if(y1.error("Ephemeral error",{error:K1}),S.type==="awaiting-agent"&&S.displayedError!==K1)return $.next({type:"error",error:{type:"other",error:K1},retryable:!1}),{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else return S}switch(y.status.inferenceState){case"running":{let K1=I.value.last;if(K1){let X1=pC(K1);if(X1)$.next({type:"state",state:X1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}if(S.type==="initializing")return{...S,tokenUsage:A1};return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1};case"cancelled":if(S.type==="initializing")return{...S,tokenUsage:A1};if($.next({type:"cancelled"}),$.next({type:"state",state:{type:"idle"}}),S.type==="awaiting-agent"&&S.cancelledWithMessage)return S.cancelledWithMessage=void 0,{...S,tokenUsage:A1};else return{...z1(),tokenUsage:A1};case"idle":if(S.type==="initializing")return{...S,tokenUsage:A1};if(D1?.content.some((K1)=>K1.type==="tool_result"&&K1.run.status==="blocked-on-user"))return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else if(I.value.last?.messages.some((K1)=>K1.role==="user"&&K1.content.some((X1)=>X1.type==="tool_result"&&X1.run.status==="in-progress"))??!1){let K1=I.value.last?.messages.flatMap((N1)=>N1.content).filter((N1)=>N1.type==="tool_result"&&("run"in N1)&&("status"in N1.run)&&N1.run.status==="in-progress"),X1=K1?.length??0;if(X1>0){for(let e of K1||[]){let G1=$7(I.value.last,e.toolUseID);if(G1){if(!V.has(e.toolUseID))V.set(e.toolUseID,Date.now());$.next({type:"tool-status",toolUse:G1,status:"running",startTime:V.get(e.toolUseID)})}}let N1=X1===1&&K1?.[0]&&I.value.last?$7(I.value.last,K1[0].toolUseID):void 0,r=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return $7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,s=N1?T51(N1.name,X1,Date.now(),N1.input,r):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:r};$.next({type:"state",state:s})}else{let N1=I.value.last;if(N1){let r=pC(N1);if(r)$.next({type:"state",state:r});else $.next({type:"state",state:{type:"idle"}})}else $.next({type:"state",state:{type:"idle"}})}return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else if(D1?.role==="assistant"&&D1?.state.type==="complete"&&D1?.state.stopReason==="end_turn")return $.next({type:"state",state:{type:"idle"}}),{...z1(),tokenUsage:A1}}}}else if(y.type==="batch-tool-confirmations-complete")if(S.type==="collecting-tool-confirmations"&&S.subthreadContext)return y1.info("Sending batch tool confirmations to subthread",{subThreadID:S.subthreadContext.subThreadID,toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),F.handleToolConfirmations(S.subthreadContext.subThreadID,y.responses).catch((D1)=>{y1.error("Failed to send subthread tool confirmations",D1)}),y1.info("Transitioning to awaiting-agent after sending subthread confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else return y1.info("Sending batch tool confirmations to worker",{toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),y.responses.forEach((D1,A1)=>{y1.info("Sending individual tool confirmation to worker",{toolUseID:A1,accepted:D1}),T.handle({type:"user:tool-input",toolUse:A1,value:{accepted:D1}}),S.toolConfirmationStatus.set(A1,"sent")}),y1.info("Transitioning to awaiting-agent after sending batch confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else if(y.type==="summary:created"){let D1=I.value.last;if(D1){let A1=Ri(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,r=K1.used,s=N1-r,e=N1>0?s/N1*100:0;if(s<=0)y1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:r,reduction:s,threadID:E});else if(e<10)y1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E});else y1.info("Compaction successful",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E})}else y1.warn("No pre-compaction token usage available for validation",{threadID:E});$.next({type:"token-usage",tokenUsage:K1})}}return z1()}else if(y.type==="compaction-result")if(y.result)return z1();else return $.next({type:"error",error:{type:"other",error:"Compaction failed"},retryable:!1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:y.severity}}),{...S,type:"confirming-compaction",severity:y.severity};else if(y.type==="update-start-updating")return{...S,updateState:"updating"};else if(y.type==="update-result")if(y.success)return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"success"};else return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"error"};else if(y.type==="clear-update-status")return{...S,updateState:"none"};else if(y.type==="agent-file-check-complete"){if(S.type==="checking-agent-file")if(y.shouldGenerate)return $.next({type:"confirm",confirmation:{type:"agent-file-creation"}}),{...S,type:"confirming-agent-file-creation"};else return z1()}else if(y.type==="tool-status")return $.next({type:"tool-status",toolUse:y.toolUse,status:y.status,startTime:y.startTime,endTime:y.endTime,subthreadID:y.subthreadID}),S;else if(y.type==="subagent-started"){if(S.type==="initializing")return S;return $.next({type:"subagent-started",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S}else if(y.type==="subagent-status")return $.next({type:"subagent-status",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,agentState:y.agentState}),S;else if(y.type==="subthread-message"){if(y.blocks.length>0)$.next({type:"subthread-messages",subThreadID:y.subThreadID,blocks:y.blocks});return S}else if(y.type==="historic-thread"){if(S.type!=="initializing")throw new Error(`Historic thread event received in unexpected state: ${S.type}`);if(w&&M.size===0&&y.messages.length>0){let A1=$f({id:E,messages:y.messages},M,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(y1.info(`Received tool confirmation request from subthread ${y.subThreadID}`,{subThreadID:y.subThreadID,agentNumber:y.agentNumber,toolCount:y.tools.length,tools:y.tools.map((D1)=>D1.useBlock.name),queueLength:S.confirmationQueue.length}),S.type==="collecting-tool-confirmations"||S.confirmationQueue.length>0)return y1.info("Queueing tool confirmation request",{subThreadID:y.subThreadID,agentNumber:y.agentNumber,currentQueueLength:S.confirmationQueue.length}),{...S,confirmationQueue:[...S.confirmationQueue,{type:"subthread-tool-request",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,tools:y.tools}]};return $.next({type:"confirm",confirmation:{type:"tool-use",tools:y.tools,subthreadID:y.subThreadID,agentNumber:y.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:y.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}}}return S}else if(y.type==="lsp-status")return $.next({type:"lsp-status",lspState:y.lspState}),S;else if(y.type==="ui-input"){if(y.input.type==="initialized")if(S.type==="initializing"){let D1={...S,hasUI:!0};if(D1.hasUI&&D1.hasThread)if(I.value.last?.messages.length===0)return y1.info("Checking agent file status"),Z4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{y1.error("Agent file check failed",K1),P.next({type:"agent-file-check-complete",shouldGenerate:!1})}),{...S,type:"checking-agent-file"};else return z1();return D1}else throw new Error(`UI initialized event received in unexpected state: ${S.type}`);else if(y.input.type=="message"){let{message:D1}=y.input;return d(D1)}else if(y.input.type==="interrupt")if(S.type==="awaiting-agent"){if($.next({type:"cancelled"}),nZ.cancel(E),y.input.message)S.cancelledWithMessage=y.input.message;return S}else return S;else if(y.input.type==="exit")return u.unsubscribe(),{...S,type:"closing"};else if(y.input.type==="retry")return nZ.retry(E),{...S,type:"awaiting-agent",displayedError:null};else if(y.input.type==="confirmation"){if(S.type==="out-of-credits"&&y.input.confirmation.type==="out-of-credits")nZ.retry(E);else if(S.type==="confirming-compaction"&&y.input.confirmation.type==="compaction")if(y.input.allow){let D1="tokenUsage"in S?S.tokenUsage:void 0;return $.next({type:"state",state:{type:"compacting"}}),a().then(()=>{y1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{y1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return y1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return y1.error("No current tool ID in collecting-tool-confirmations state"),S;if(y1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){y1.info("Sending tool confirmation to subthread",{subThreadID:S.subthreadContext.subThreadID,toolUseID:S.currentToolID,accepted:y.input.allow});let X1=new Map([[S.currentToolID,y.input.allow]]);if(F.handleToolConfirmations(S.subthreadContext.subThreadID,X1).catch((N1)=>{y1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],r=S.confirmationQueue.slice(1);return y1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:r.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:N1.tools,subthreadID:N1.subThreadID,agentNumber:N1.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:N1.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,taskDescription:N1.taskDescription},confirmationQueue:r}}return y1.info("Transitioning to awaiting-agent after sending subthread confirmation"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}S.toolConfirmationStatus.set(S.currentToolID,y.input.allow?"confirmed":"rejected"),t(y.input.confirmation.addToAllowList);let D1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="awaiting");if(D1.length>0){let[X1]=D1[0];if(!I.value.isSet)return y1.error("Thread not available for finding next tool"),S;let s=(I.value.last.messages.at(-1)?.content.filter((G1)=>G1.type==="tool_result"&&G1.run.status==="blocked-on-user")??[]).find((G1)=>G1.toolUseID===X1),e=s?$7(I.value.last,s.toolUseID):null;if(s&&e)return y1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:s.run.status==="blocked-on-user"?s.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");y1.info("All tool confirmations collected, sending batch response",{totalTools:A1.length,responses:A1.map(([X1,N1])=>({id:X1,accepted:N1==="confirmed"}))});let K1=new Map(A1.map(([X1,N1])=>[X1,N1==="confirmed"]));return P.next({type:"batch-tool-confirmations-complete",responses:K1}),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}else if(y.input.confirmation.type==="agent-file-creation"&&S.type==="confirming-agent-file-creation")if(y.input.allow)return X4A(T).catch((D1)=>{y1.error("Agent file generation failed",D1)}),$.next({type:"state",state:{type:"generating-agent-file"}}),{...S,type:"awaiting-agent",displayedError:null};else return z1();return S}}return S}),{type:"initializing",hasUI:!1,hasThread:!1,tokenUsage:null,compactionPromptState:"none",updateState:"none",toolConfirmationStatus:new Map,currentAssistantMessageIndex:null,hasBeenIdle:!1,threadTitle:null,confirmationQueue:[]})).subscribe({error:(S)=>{y1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)y1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else y1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else y1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return Ns6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await B2(g)}async function Ns6(A){try{let Q=await q4A("0.0.1751486517-g5cc052");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await U4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){y1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else y1.info("No update available")}catch(Q){y1.debug("Update check failed",Q)}}var S51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();F2();yq();function E4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7328
+ ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function F4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let W=GT(),M=new Set,I=kM(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await B2(I.observable);let _=await Id,T=await nZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Hf,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{y1.error("Initial resume",S)});let R=T.status.pipe(r6((S)=>{return{type:"worker-state",status:S}})),j=I.observable.pipe(r6((S)=>{return{type:"thread-state",thread:S}})),P=new C8,$=new C8,f=H(FA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=W.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=mU(R,j,mU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{y1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await W.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(KZ(()=>{b()})).pipe(zT(d3("threadSession",function(S,y){function d(D1){y1.info(`Processing user message: ${D1.slice(0,50)}${D1.length>50?"...":""}`);let A1="tokenUsage"in S?S.tokenUsage:void 0;if(A1&&A1.used/A1.maxAvailable>S51.CRITICAL)return y1.info("Blocking message at worker boundary - critical token usage"),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:"final",updateState:"updateState"in S?S.updateState:"none",toolConfirmationStatus:"toolConfirmationStatus"in S?S.toolConfirmationStatus:new Map,currentAssistantMessageIndex:("currentAssistantMessageIndex"in S?S.currentAssistantMessageIndex:null)??null,hasBeenIdle:"hasBeenIdle"in S?S.hasBeenIdle:!1,threadTitle:"threadTitle"in S?S.threadTitle:null,confirmationQueue:"confirmationQueue"in S?S.confirmationQueue:[]};T.handle({type:"user:message",message:{content:[{type:"text",text:D1}]}}).then(()=>{if(A)A.sync().catch((X1)=>{y1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{y1.error("Handle user message failed",X1)}),$.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});let K1=I.value.last;if(K1){let X1=pC(K1);if(X1)$.next({type:"state",state:X1})}return{...S,type:"awaiting-agent",displayedError:null}}async function a(){$.next({type:"state",state:{type:"compacting"}});let D1=await X.summarizeThread(E);await T.handle({type:"summary:created",summary:{type:"internal",summary:D1.summary}})}function z1(){if(S.type==="awaiting-user-message")return y1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{y1.error("Thread sync error",A1,{threadID:E})}),D1&&S.type!=="confirming-compaction"&&S.type!=="compacting"){let A1=D1.used/D1.maxAvailable,K1=void 0,X1=S.compactionPromptState;if(A1>S51.CRITICAL)K1="critical",X1="final";else if(A1>S51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>S51.SEVERE&&S.compactionPromptState==="first")K1="severe",X1="final";if(K1)return $.next({type:"confirm",confirmation:{type:"compaction",severity:K1}}),{type:"confirming-compaction",severity:K1,tokenUsage:S.tokenUsage,compactionPromptState:X1,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue}}if($.next({type:"accept-message",initial:!S.hasBeenIdle&&!w}),S.type==="awaiting-agent")S.cancelledWithMessage=void 0;if(D1)$.next({type:"token-usage",tokenUsage:D1});return{...S,type:"awaiting-user-message",hasBeenIdle:!0,tokenUsage:D1??null}}function t(D1){if(D1.length>0)y1.info(`Updating allowlist with ${D1.length} entries`,{entries:D1}),K.get("commands.allowlist","global").then((A1)=>{let K1=[...A1??[],...D1];return K.set("commands.allowlist",K1,"global")}).catch((A1)=>{y1.error("Failed to update allowlist",A1)})}if(S.type==="closing")return S;if(y.type==="thread-state"){let D1=y.thread.title||null;if(S.threadTitle!==D1&&D1!==null)$.next({type:"thread-title",title:D1});if(F.scanForTaskToolSubthreads(y.thread),w&&M.size===0&&y.thread.messages.length>0){let K1=$f(y.thread,M,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Ri(y.thread);if(K1)A1={used:K1.totalInputTokens,maxAvailable:K1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}if(S.type==="awaiting-user-confirmation")if(y.thread.messages.at(-1)?.content.some((K1)=>K1.type==="tool_result"&&(K1.run.status==="in-progress"||K1.run.status==="done"))){let K1=pC(y.thread);if(K1)$.next({type:"state",state:K1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};if(S.type==="awaiting-agent"||S.type==="compacting"){let K1=y.thread.messages.at(-1),X1=$f(y.thread,M,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=pC(y.thread);if(U1)$.next({type:"state",state:U1})}if(N1.length>0){for(let Y1 of N1)if(Y1.type==="toolResult"){let[U1,P1]=Y1.data,R1=P1.run.status==="done"?"completed":P1.run.status==="error"?"error":P1.run.status==="cancelled"?"cancelled":"running";if(R1!=="running")$.next({type:"tool-status",toolUse:U1,status:R1,startTime:V.get(U1.id),endTime:Date.now()}),V.delete(U1.id)}$.next({type:"messages",blocks:N1})}if(y.thread.messages.at(-1)?.content.some((Y1)=>Y1.type==="summary"))return{...z1(),tokenUsage:null,compactionPromptState:"none"};if(K1?.role==="assistant"&&K1?.state.type==="complete"&&K1?.state.stopReason==="end_turn"){$.next({type:"state",state:{type:"idle"}});let Y1=z1();return{...Y1,tokenUsage:A1??Y1.tokenUsage}}if(!I)throw new Error("unexpected: thread is required when waiting for tool input");let r=Ez(y.thread,"assistant"),s=r?y.thread.messages.indexOf(r):null;if(s!==null&&s!==S.currentAssistantMessageIndex)y1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:s,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=s;let e=Ez(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(r?.content.filter((Y1)=>Y1.type==="tool_use").map((Y1)=>Y1.id)??[]),q1=!1;for(let Y1 of e){if(!G1.has(Y1.toolUseID))continue;let U1=$7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===s4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,y1.info("Added new tool to confirmation tracking",{toolUseID:Y1.toolUseID,toolName:U1.name}),!V.has(U1.id))V.set(U1.id,Date.now());$.next({type:"tool-status",toolUse:U1,status:"blocked-on-user",startTime:V.get(U1.id)})}}if(q1){let Y1=Array.from(S.toolConfirmationStatus.entries()).filter(([U1,P1])=>P1==="awaiting");if(Y1.length>0){let[U1]=Y1[0],P1=e.find((T1)=>T1.toolUseID===U1),R1=P1?$7(y.thread,P1.toolUseID):null;if(P1&&R1)return y1.info(`Starting tool confirmation process for ${Y1.length} tools`,{firstToolID:U1,toolName:R1.name}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:R1,toAllow:P1.run.status==="blocked-on-user"?P1.run.toAllow:void 0}]}}),{...S,type:"collecting-tool-confirmations",currentToolID:U1,tokenUsage:A1}}}}}else if(y.type==="worker-state"){if(S.type==="awaiting-user-confirmation"&&y.status.state==="active"&&y.status.ephemeralError)return S;if(S.type==="collecting-tool-confirmations")return y1.info("Already collecting tool confirmations, ignoring worker-state event"),S;let D1=I.value.last?.messages.at(-1),A1=S.tokenUsage;if(y.status.state==="active"){let K1=I.value.last;if(K1){let X1=Ri(K1);if(X1)A1={used:X1.totalInputTokens,maxAvailable:X1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}}if(S.type==="confirming-compaction"||S.type==="compacting")return{...S,tokenUsage:A1};switch(y.status.state){case"initial":if(S.type==="initializing")return S;return z1();case"active":if(y.status.ephemeralError)if(y.status.ephemeralError.message.includes(z4A)){if(S.type==="out-of-credits")return S;return $.next({type:"confirm",confirmation:{type:"out-of-credits"}}),{...S,type:"out-of-credits",tokenUsage:A1}}else if(D4A(y.status.ephemeralError))return y1.info("Context limit error, triggering compaction",{error:y.status.ephemeralError,tokenUsage:A1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:S.compactionPromptState,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue};else if(y.status.ephemeralError.message.includes("401 unauthorized"))return $.next({type:"error",error:{type:"unauthorized"},retryable:!1}),u.unsubscribe(),{...S,type:"closing"};else{let K1=y.status.ephemeralError.message;if(y1.error("Ephemeral error",{error:K1}),S.type==="awaiting-agent"&&S.displayedError!==K1)return $.next({type:"error",error:{type:"other",error:K1},retryable:!1}),{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else return S}switch(y.status.inferenceState){case"running":{let K1=I.value.last;if(K1){let X1=pC(K1);if(X1)$.next({type:"state",state:X1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}if(S.type==="initializing")return{...S,tokenUsage:A1};return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1};case"cancelled":if(S.type==="initializing")return{...S,tokenUsage:A1};if($.next({type:"cancelled"}),$.next({type:"state",state:{type:"idle"}}),S.type==="awaiting-agent"&&S.cancelledWithMessage)return S.cancelledWithMessage=void 0,{...S,tokenUsage:A1};else return{...z1(),tokenUsage:A1};case"idle":if(S.type==="initializing")return{...S,tokenUsage:A1};if(D1?.content.some((K1)=>K1.type==="tool_result"&&K1.run.status==="blocked-on-user"))return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else if(I.value.last?.messages.some((K1)=>K1.role==="user"&&K1.content.some((X1)=>X1.type==="tool_result"&&X1.run.status==="in-progress"))??!1){let K1=I.value.last?.messages.flatMap((N1)=>N1.content).filter((N1)=>N1.type==="tool_result"&&("run"in N1)&&("status"in N1.run)&&N1.run.status==="in-progress"),X1=K1?.length??0;if(X1>0){for(let e of K1||[]){let G1=$7(I.value.last,e.toolUseID);if(G1){if(!V.has(e.toolUseID))V.set(e.toolUseID,Date.now());$.next({type:"tool-status",toolUse:G1,status:"running",startTime:V.get(e.toolUseID)})}}let N1=X1===1&&K1?.[0]&&I.value.last?$7(I.value.last,K1[0].toolUseID):void 0,r=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return $7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,s=N1?T51(N1.name,X1,Date.now(),N1.input,r):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:r};$.next({type:"state",state:s})}else{let N1=I.value.last;if(N1){let r=pC(N1);if(r)$.next({type:"state",state:r});else $.next({type:"state",state:{type:"idle"}})}else $.next({type:"state",state:{type:"idle"}})}return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else if(D1?.role==="assistant"&&D1?.state.type==="complete"&&D1?.state.stopReason==="end_turn")return $.next({type:"state",state:{type:"idle"}}),{...z1(),tokenUsage:A1}}}}else if(y.type==="batch-tool-confirmations-complete")if(S.type==="collecting-tool-confirmations"&&S.subthreadContext)return y1.info("Sending batch tool confirmations to subthread",{subThreadID:S.subthreadContext.subThreadID,toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),F.handleToolConfirmations(S.subthreadContext.subThreadID,y.responses).catch((D1)=>{y1.error("Failed to send subthread tool confirmations",D1)}),y1.info("Transitioning to awaiting-agent after sending subthread confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else return y1.info("Sending batch tool confirmations to worker",{toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),y.responses.forEach((D1,A1)=>{y1.info("Sending individual tool confirmation to worker",{toolUseID:A1,accepted:D1}),T.handle({type:"user:tool-input",toolUse:A1,value:{accepted:D1}}),S.toolConfirmationStatus.set(A1,"sent")}),y1.info("Transitioning to awaiting-agent after sending batch confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else if(y.type==="summary:created"){let D1=I.value.last;if(D1){let A1=Ri(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,r=K1.used,s=N1-r,e=N1>0?s/N1*100:0;if(s<=0)y1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:r,reduction:s,threadID:E});else if(e<10)y1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E});else y1.info("Compaction successful",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E})}else y1.warn("No pre-compaction token usage available for validation",{threadID:E});$.next({type:"token-usage",tokenUsage:K1})}}return z1()}else if(y.type==="compaction-result")if(y.result)return z1();else return $.next({type:"error",error:{type:"other",error:"Compaction failed"},retryable:!1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:y.severity}}),{...S,type:"confirming-compaction",severity:y.severity};else if(y.type==="update-start-updating")return{...S,updateState:"updating"};else if(y.type==="update-result")if(y.success)return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"success"};else return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"error"};else if(y.type==="clear-update-status")return{...S,updateState:"none"};else if(y.type==="agent-file-check-complete"){if(S.type==="checking-agent-file")if(y.shouldGenerate)return $.next({type:"confirm",confirmation:{type:"agent-file-creation"}}),{...S,type:"confirming-agent-file-creation"};else return z1()}else if(y.type==="tool-status")return $.next({type:"tool-status",toolUse:y.toolUse,status:y.status,startTime:y.startTime,endTime:y.endTime,subthreadID:y.subthreadID}),S;else if(y.type==="subagent-started"){if(S.type==="initializing")return S;return $.next({type:"subagent-started",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S}else if(y.type==="subagent-status")return $.next({type:"subagent-status",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,agentState:y.agentState}),S;else if(y.type==="subthread-message"){if(y.blocks.length>0)$.next({type:"subthread-messages",subThreadID:y.subThreadID,blocks:y.blocks});return S}else if(y.type==="historic-thread"){if(S.type!=="initializing")throw new Error(`Historic thread event received in unexpected state: ${S.type}`);if(w&&M.size===0&&y.messages.length>0){let A1=$f({id:E,messages:y.messages},M,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(y1.info(`Received tool confirmation request from subthread ${y.subThreadID}`,{subThreadID:y.subThreadID,agentNumber:y.agentNumber,toolCount:y.tools.length,tools:y.tools.map((D1)=>D1.useBlock.name),queueLength:S.confirmationQueue.length}),S.type==="collecting-tool-confirmations"||S.confirmationQueue.length>0)return y1.info("Queueing tool confirmation request",{subThreadID:y.subThreadID,agentNumber:y.agentNumber,currentQueueLength:S.confirmationQueue.length}),{...S,confirmationQueue:[...S.confirmationQueue,{type:"subthread-tool-request",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,tools:y.tools}]};return $.next({type:"confirm",confirmation:{type:"tool-use",tools:y.tools,subthreadID:y.subThreadID,agentNumber:y.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:y.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}}}return S}else if(y.type==="lsp-status")return $.next({type:"lsp-status",lspState:y.lspState}),S;else if(y.type==="ui-input"){if(y.input.type==="initialized")if(S.type==="initializing"){let D1={...S,hasUI:!0};if(D1.hasUI&&D1.hasThread)if(I.value.last?.messages.length===0)return y1.info("Checking agent file status"),Z4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{y1.error("Agent file check failed",K1),P.next({type:"agent-file-check-complete",shouldGenerate:!1})}),{...S,type:"checking-agent-file"};else return z1();return D1}else throw new Error(`UI initialized event received in unexpected state: ${S.type}`);else if(y.input.type=="message"){let{message:D1}=y.input;return d(D1)}else if(y.input.type==="interrupt")if(S.type==="awaiting-agent"){if($.next({type:"cancelled"}),nZ.cancel(E),y.input.message)S.cancelledWithMessage=y.input.message;return S}else return S;else if(y.input.type==="exit")return u.unsubscribe(),{...S,type:"closing"};else if(y.input.type==="retry")return nZ.retry(E),{...S,type:"awaiting-agent",displayedError:null};else if(y.input.type==="confirmation"){if(S.type==="out-of-credits"&&y.input.confirmation.type==="out-of-credits")nZ.retry(E);else if(S.type==="confirming-compaction"&&y.input.confirmation.type==="compaction")if(y.input.allow){let D1="tokenUsage"in S?S.tokenUsage:void 0;return $.next({type:"state",state:{type:"compacting"}}),a().then(()=>{y1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{y1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return y1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return y1.error("No current tool ID in collecting-tool-confirmations state"),S;if(y1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){y1.info("Sending tool confirmation to subthread",{subThreadID:S.subthreadContext.subThreadID,toolUseID:S.currentToolID,accepted:y.input.allow});let X1=new Map([[S.currentToolID,y.input.allow]]);if(F.handleToolConfirmations(S.subthreadContext.subThreadID,X1).catch((N1)=>{y1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],r=S.confirmationQueue.slice(1);return y1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:r.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:N1.tools,subthreadID:N1.subThreadID,agentNumber:N1.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:N1.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,taskDescription:N1.taskDescription},confirmationQueue:r}}return y1.info("Transitioning to awaiting-agent after sending subthread confirmation"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}S.toolConfirmationStatus.set(S.currentToolID,y.input.allow?"confirmed":"rejected"),t(y.input.confirmation.addToAllowList);let D1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="awaiting");if(D1.length>0){let[X1]=D1[0];if(!I.value.isSet)return y1.error("Thread not available for finding next tool"),S;let s=(I.value.last.messages.at(-1)?.content.filter((G1)=>G1.type==="tool_result"&&G1.run.status==="blocked-on-user")??[]).find((G1)=>G1.toolUseID===X1),e=s?$7(I.value.last,s.toolUseID):null;if(s&&e)return y1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:s.run.status==="blocked-on-user"?s.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");y1.info("All tool confirmations collected, sending batch response",{totalTools:A1.length,responses:A1.map(([X1,N1])=>({id:X1,accepted:N1==="confirmed"}))});let K1=new Map(A1.map(([X1,N1])=>[X1,N1==="confirmed"]));return P.next({type:"batch-tool-confirmations-complete",responses:K1}),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}else if(y.input.confirmation.type==="agent-file-creation"&&S.type==="confirming-agent-file-creation")if(y.input.allow)return X4A(T).catch((D1)=>{y1.error("Agent file generation failed",D1)}),$.next({type:"state",state:{type:"generating-agent-file"}}),{...S,type:"awaiting-agent",displayedError:null};else return z1();return S}}return S}),{type:"initializing",hasUI:!1,hasThread:!1,tokenUsage:null,compactionPromptState:"none",updateState:"none",toolConfirmationStatus:new Map,currentAssistantMessageIndex:null,hasBeenIdle:!1,threadTitle:null,confirmationQueue:[]})).subscribe({error:(S)=>{y1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)y1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else y1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else y1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return Ns6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await B2(g)}async function Ns6(A){try{let Q=await q4A("0.0.1751515778-gc465ed");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await U4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){y1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else y1.info("No update available")}catch(Q){y1.debug("Update check failed",Q)}}var S51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();F2();yq();function E4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7329
7329
  `)}return(z)=>{let Z=new C8;if(!J)throw new Error("JSONL UI requires piped input (non-interactive mode)");return y1.debug("setting up JSONL UI"),z.pipe(Qi({onSubscribe:()=>{D({type:"initial",threadID:B}),Bj().then(()=>{Z.next({type:"initialized"})})},onUnsubscribe:()=>{y1.debug("JSONL UI stopped")}})).pipe(KZ(()=>{Z.complete()})).pipe(zT(d3("JSONL",(X,K)=>{if(y1.debug("JSONL UI event",{event:K}),X.type==="shutting-down")return X;switch(K.type){case"messages":{let G=(E)=>{return E.map((w)=>{if(w.type==="text"){let{type:H,text:W}=w;return{type:H,text:W}}else if(w.type==="image"){let{type:H,source:W}=w;return{type:H,source:W}}else if(w.type==="tool_result"){let{type:H,toolUseID:W,run:M,userInput:I}=w;return{type:H,toolUseID:W,run:M,userInput:I}}else if(w.type==="thinking"){let{type:H,thinking:W}=w;return{type:H,thinking:W}}else if(w.type==="redacted_thinking"){let{type:H,data:W}=w;return{type:H,data:W}}else if(w.type==="tool_use"){let{type:H,id:W,name:M,input:I}=w,N={type:H,id:W,name:M};if(I!==void 0)N.input=I;return N}else if(w.type==="server_tool_use"){let{type:H,id:W,name:M,input:I}=w;return{type:H,id:W,name:M,input:I}}else if(w.type==="web_search_tool_result"){let{type:H,content:W}=w;return{type:H,content:W}}else if(w.type==="summary"){let{type:H,summary:W}=w;return{type:H,summary:W}}return w})},q=(E)=>{switch(E.status){case"blocked-on-user":case"rejected-by-user":return{status:E.status,toAllow:E.toAllow};case"error":return{status:"error",error:typeof E.error==="object"&&"message"in E.error?E.error:{message:String(E.error)}};case"cancelled":case"in-progress":return{status:E.status,progress:E.progress};case"done":return{status:"done",progress:E.progress,result:E.result,files:E.files};default:return{status:E.status}}},Y=[],F=[];for(let E of K.blocks)if(E.type==="message"){let[w,H]=E.data;if(H.role==="user"){let{role:W,content:M,meta:I}=H,N={role:W,content:G(M),meta:I};Y.push([w,N])}else if(H.role==="assistant"){let{role:W,content:M,state:I}=H,N={role:W,content:G(M),state:I};Y.push([w,N])}else if(H.role==="info"){let{role:W,content:M}=H,I={role:W,content:G(M)};Y.push([w,I])}else Y.push([w,H])}else if(E.type==="toolResult"){let[w,H]=E.data;if(w.input&&H.run!==void 0){let W={type:w.type,id:w.id,name:w.name,input:{}},M={type:H.type,toolUseID:H.toolUseID,run:q(D5(H.run))};F.push([W,M])}else y1.warn("Skipping tool result",{useBlock:w,resultBlock:H})}return D({type:"messages",messages:Y,toolResults:F}),X}case"cancelled":return D({type:"cancelled"}),X;case"tool-status":return D({type:"tool-status",toolUse:{id:K.toolUse.id,name:K.toolUse.name,input:K.toolUse.input},status:K.status,startTime:K.startTime,endTime:K.endTime,subthreadID:K.subthreadID}),X;case"token-usage":return D({type:"token-usage",tokenUsage:K.tokenUsage}),X;case"accept-message":if(X.type==="initializing")return y1.info("Sending piped input",{pipedInput:J}),Z.next({type:"message",message:J}),{type:"running"};else return Z.next({type:"exit"}),X;case"error":return D({type:"error",error:K.error}),Z.next({type:"exit"}),X;case"confirm":{if(K.confirmation.type==="tool-use")for(let{useBlock:G}of K.confirmation.tools){if(G.name===s4&&G.input&&typeof G.input==="object"&&"cmd"in G.input)D({type:"tool-rejected",tool:G.name,command:String(G.input.cmd),message:`Tool call rejected. To allow automatically, add to ${jE}: {"amp.commands.allowlist": [${JSON.stringify(G.input.cmd)}]}`});Z.next({type:"confirmation",confirmation:{type:"tool-use",toolUseID:G.id,addToAllowList:[]},allow:!1})}else if(K.confirmation.type==="compaction")Z.next({type:"confirmation",confirmation:K.confirmation,allow:!0});else if(K.confirmation.type==="agent-file-creation")Z.next({type:"confirmation",confirmation:K.confirmation,allow:!1});else if(K.confirmation.type==="out-of-credits")D({type:"out-of-credits",message:"Insufficient usage balance. Visit https://ampcode.com/pay to buy more usage."}),Z.next({type:"exit"});else Z.next({type:"confirmation",confirmation:K.confirmation,allow:!1});return X}case"subagent-started":return D({type:"subagent-started",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription}),X;case"subagent-finished":return D({type:"subagent-finished",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,result:K.result}),X;case"subagent-cancelled":return D({type:"subagent-cancelled",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription}),X;case"subagent-error":return D({type:"subagent-error",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,error:K.error}),X;case"subagent-status":return D({type:"subagent-status",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,agentState:K.agentState}),X;case"subthread-messages":{let G=K.blocks.filter((Y)=>Y.type==="message").length,q=K.blocks.filter((Y)=>Y.type==="toolResult").length;return D({type:"subthread-activity",subThreadID:K.subThreadID,messageCount:G,toolResultCount:q}),X}case"state":switch(K.state.type){case"shutting-down":return D({type:"shutdown"}),{type:"shutting-down"};default:return D({type:"state",state:K.state.type}),X}case"lsp-status":return D({type:"lsp-status",lspState:K.lspState}),X}return X}),{type:"initializing"})).subscribe({error:(X)=>{y1.error("Error in JSONL UI:",X),D({type:"error",error:{type:"other",error:X.toString()}}),Z.next({type:"exit"})}}),FA.from(Z)}}y2();AK();y2();import{exec as ff}from"node:child_process";function kf(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")ff("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")ff("powershell [console]::beep(800,200)");else if(process.platform==="linux")ff("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="requires-user-input"){if(process.platform==="darwin")ff("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")ff("powershell [console]::beep(1000,300)");else if(process.platform==="linux")ff("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){y1.error(`Failed to play notification sound (${A}):`,Q)}}F2();y2();import{mkdir as w4A,readFile as H4A,writeFile as df1,open as Cs6}from"node:fs/promises";import{homedir as Vs6}from"node:os";import Nd from"node:path";var Os6=Nd.join(Mf||Nd.join(Vs6(),".local/share"),"amp"),Rs6=Nd.join(Os6,"history.jsonl"),Ls6=1000;class Cd{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(A){this.historyFile=A?.historyFile||Rs6,this.maxSize=A?.maxSize||Ls6,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)this.history=await this.readHistoryFromDisk(),this.loaded=!0}async readHistoryFromDisk(){try{let A=await H4A(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return y1.warn("Failed to read history file",{error:A.message}),[];if(this.historyFile.endsWith(".jsonl")){let Q=this.historyFile.replace(".jsonl",".json");try{let B=await H4A(Q,"utf-8");if(B.trim()){let J=JSON.parse(B);y1.info("Migrating from old history.json to history.jsonl",{oldFile:Q,newFile:this.historyFile,size:J.length}),await this.writeHistoryToDisk(J);try{await import("node:fs/promises").then((D)=>D.unlink(Q))}catch{}return J}}catch{}}return[]}}parseJsonlContent(A){let Q=A.trim().split(`
7330
7330
  `),B=[];for(let J of Q)if(J.trim())try{let D=JSON.parse(J);if(typeof D==="string")B.push(D);else y1.warn("Skipping non-string entry in history",{line:J,type:typeof D})}catch(D){y1.warn("Skipping invalid JSONL line in history",{line:J})}return y1.info("Loaded history from JSONL file",{file:this.historyFile,size:B.length}),B}async writeHistoryToDisk(A){await w4A(Nd.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
7331
7331
  `)+`
@@ -7453,7 +7453,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
7453
7453
  `),d=0,a=0;for(let z1=0;z1<y.length;z1++){let t=g6.default(y[z1]).length;if(d+t>=Y){a=d;break}d+=t+1}if(Y>a){let z1=g6.default.substr(G,a,Y-a);N((t)=>[z1,...t.slice(0,9)]),q((t)=>{let D1=g6.default(t);return D1.slice(0,a).join("")+D1.slice(Y).join("")}),F(a)}return}if(u.ctrl&&b==="k"){let y=G.split(`
7454
7454
  `),d=0,a=g6.default(G).length;for(let z1=0;z1<y.length;z1++){let t=g6.default(y[z1]).length;if(d+t>=Y){a=d+t;break}d+=t+1}if(Y<a){let z1=g6.default.substr(G,Y,a-Y);N((t)=>[z1,...t.slice(0,9)]),q((t)=>{let D1=g6.default(t);return D1.slice(0,Y).join("")+D1.slice(a).join("")})}return}if(u.ctrl&&b==="w"||u.alt&&u.backspace||u.ctrl&&u.backspace){if(Y>0){let y=GQA(G,Y),d=g6.default.substr(G,y,Y-y);N((a)=>[d,...a.slice(0,9)]),q((a)=>{let z1=g6.default(a);return z1.slice(0,y).join("")+z1.slice(Y).join("")}),F(y)}return}if(u.ctrl&&b==="d"||u.delete){if(Y<g6.default(G).length){let y=g6.default.substr(G,Y,1);N((d)=>[y,...d.slice(0,9)]),q((d)=>{let a=g6.default(d);return a.slice(0,Y).join("")+a.slice(Y+1).join("")})}return}if(u.alt&&b==="d"){if(Y<g6.default(G).length){let y=qQA(G,Y),d=g6.default.substr(G,Y,y-Y);N((a)=>[d,...a.slice(0,9)]),q((a)=>{let z1=g6.default(a);return z1.slice(0,Y).join("")+z1.slice(y).join("")})}return}if(u.ctrl&&b==="y"){if(I.length>0){let y=I[0];q((d)=>{let a=g6.default(d);return a.slice(0,Y).join("")+y+a.slice(Y).join("")}),F((d)=>d+g6.default(y).length)}return}let S=u.return&&(u.shift||u.meta||u.ctrl)||!u.return&&b==="\r"||u.escape&&u.meta&&!b||b==="\x1B[27;2;13~"||b==="[27;2;13~"||b==="\x1B[13;2u";if(y1.info("Modified Enter detection",{isModifiedEnter:S,"key.return":u.return,"key.shift":u.shift,"key.meta":u.meta,"key.ctrl":u.ctrl,keyInput:JSON.stringify(b),hasContent:G.trim().length>0}),S){if($)return;q((y)=>{let d=g6.default(y);return d.slice(0,Y).join("")+`
7455
7455
  `+d.slice(Y).join("")}),F((y)=>y+1);return}if(u.return&&!u.shift&&!u.meta&&!u.ctrl){if($)return;if(G.trim().length>0)g(G.trim());else return;return}if(!u.ctrl&&!u.meta&&!u.tab&&b)q((y)=>{let d=g6.default(y);return d.slice(0,Y).join("")+b+d.slice(Y).join("")}),F((y)=>y+g6.default(b).length)});let g=async(b)=>{if(K({virtualLine:0,column:0}),F(0),w(!0),q(""),N([]),_(!1),R(null),Q)Q.add(b),Q.reset();try{A(b)}catch(u){y1.error("Failed to submit message",u)}finally{w(!1)}};return fA(y6,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:Z,children:W.map((b,u)=>fA(y6,{flexShrink:0,flexDirection:"row",children:fA(y6,{flexGrow:1,flexShrink:0,width:"100%",children:u===X.virtualLine?T9(Gy1,{children:[fA(h6,{dimColor:B,children:g6.default.substr(b.content,0,X.column)||""}),fA(h6,{inverse:!B,dimColor:B,children:g6.default(b.content)[X.column]??" "}),fA(h6,{dimColor:B,children:g6.default.substr(b.content,X.column+1)||""})]}):fA(h6,{dimColor:B,children:b.content||" "})})},u))})}function J12(A,Q){let B=A.split(`
7456
- `),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),W=g6.default(K),M=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+M.length}),q=G+W.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let W=0;W<H.length;W+=Q){let M=H.slice(W,W+Q).join("");J.push({type:Y?"start":"continuation",content:M,originalLine:D,start:G+W,end:G+W+g6.default(M).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var u71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=u71.useState(0);if(nW((z,Z)=>{if(Z.downArrow||Z.ctrl&&z.toLowerCase()==="n"||Z.tab&&!Z.shift)D((X)=>(X+1)%A.length);else if(Z.upArrow||Z.ctrl&&z.toLowerCase()==="p"||Z.shift&&Z.tab)D((X)=>(X-1+A.length)%A.length);else if(Z.return&&A[J])Q(A[J].value);else if(Z.escape)Q(null);else if(Z.ctrlC)Q(null)}),u71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return T9(y6,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[B&&fA(y6,{marginBottom:1,children:fA(h6,{bold:!0,children:B})}),A.map((z,Z)=>fA(y6,{children:T9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function D12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var UQA=10;function z12({messages:A,agentState:Q}){if(Q.type!=="streaming-thinking"&&Q.type!=="streaming-text")return null;let B=A.findLast((z)=>z.type==="message"&&z.data[1].role==="assistant"&&z.data[1].state?.type==="streaming");if(!B||B.type!=="message")return null;let[,J]=B.data;if(!J.content.some((z)=>z.type==="thinking"||z.type==="text"))return null;return fA(y6,{flexDirection:"column",marginBottom:1,children:J.content.map((z,Z)=>{if(z.type==="thinking"){let X=z.thinking,K=xd(X,!0);return fA(y6,{flexDirection:"column",marginTop:Z>0?1:0,children:K.map((G,q)=>fA(y6,{children:fA(h6,{children:G})},q))},Z)}else if(z.type==="text")return fA(y6,{marginTop:Z>0?1:0,children:fA(Fy1,{children:z.text})},Z);return null})})}function Z12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=X12(J.useBlock);else B="Confirm tool call"}else B=`Confirm ${A.tools.length} tool calls`;break}case"compaction":B=`Compact thread? (${A.severity} token usage)`;break;case"out-of-credits":B="Insufficient usage balance. Retry?";break;case"agent-file-creation":B="Create AGENT.md file for this codebase?";break}if(Q&&Q.total>1)B=`[${Q.current}/${Q.total}] ${B}`;return B}function X12(A){if(A.name===s4){let Q=A.input;return"Run "+pl.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return pl.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function K12(A){switch(A.type){case"tool-use":{let B=A.subthreadID===void 0&&A.tools.some((D)=>D.toAllow),J=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];if(B)J.push({value:"always",label:"Always (add to allowlist)"});return J}case"compaction":return[{value:"yes",label:"Yes"},...A.severity!=="critical"?[{value:"no",label:"No"}]:[]];case"out-of-credits":case"agent-file-creation":return[{value:"yes",label:"Yes"},{value:"no",label:"No"}]}}function G12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return T9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:T9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:T9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function FQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function EQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=ef(),[K]=t3.useState(()=>new C8);t3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=t3.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(W)=>{q((M)=>{if(M.type!=="confirming"||!M.currentConfirmation)return M;let I=M.currentConfirmation,N=M.confirmationQueue.slice(1),V=W===null?"no":W;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...M,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...M,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};t3.useEffect(()=>{let W=A.subscribe((M)=>{switch(M.type){case"state":{switch(M.state.type){case"shutting-down":q({...G,type:"exiting"}),Bj().then(()=>{z.exit()});break;case"idle":if(D)kf("idle");q((I)=>({...I,agentState:M.state}));break;default:q((I)=>({...I,agentState:M.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...M.blocks],V=FQA(N),_=_i({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:M.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:M.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(M.toolUse.name===UQ)return{...I,activeTools:N};if(M.status==="completed"||M.status==="error"||M.status==="cancelled")N.delete(M.toolUse.id);else{let V=M.subthreadID;N.set(M.toolUse.id,{toolUse:M.toolUse,status:M.status,startTime:M.startTime,endTime:M.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(M.subThreadID,{subThreadID:M.subThreadID,agentNumber:M.agentNumber,taskDescription:M.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(M.subThreadID);if(V)N.set(M.subThreadID,{...V,agentState:M.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)kf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,M.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:M.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:M.title}));break}default:y1.info("unhandled ui output",M);break}});return()=>{W.unsubscribe()}},[A,z]);let F=async(W,M)=>{let I=await D12(J,W);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:M}))},E=()=>{q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(W)=>{if(W!==null)K.next(W),q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};t3.useEffect(()=>{let W=null,M=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),W=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA)};return process.stdout.on("resize",M),()=>{if(W)clearTimeout(W);process.stdout.off("resize",M)}},[]),nW((W,M)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(M.escape)Q.next({type:"interrupt"});else if(M.ctrl&&W.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(M.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA);else if(M.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let W=FQA(G.messages);return fA(KQA,{threadName:G.threadTitle,messages:W,onExit:()=>q({...G,type:"running"})})}return T9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(f71,{items:G.messages,children:(W,M)=>fA(y6,{children:fA(q12,{block:W,marginTop:M===0?0:1},M)},M)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(z12,{messages:G.messages,agentState:G.agentState}),fA(s7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(zQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:Z12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:K12(G.currentConfirmation),onSelect:Y})}),T9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(G12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(YQA,{onSubmit:(W)=>{Q.next({type:"message",message:W})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let W=Math.min(10,Math.max(3,Math.floor(X*0.4))),M=G.completions.slice(0,W);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${M.length}${G.completions.length>W?`/${G.completions.length}`:""})`,options:M.map((I)=>({value:I,label:I})),onSelect:w})})})(),T9(y6,{gap:2,children:[T9(y6,{flexGrow:1,children:[G.type==="confirming-exit"&&fA(h6,{dimColor:!0,children:"Ctrl+C again to exit"}),G.type==="confirming"&&fA(h6,{dimColor:!0,children:"Escape to cancel"}),G.type==="running"&&T9(y6,{gap:1,children:[fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Enter to submit,"})}),fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Ctrl+R to expand"})})]})]}),T9(y6,{flexGrow:0,gap:2,children:[fA(U12,{lspState:G.lspState}),G.tokenUsage&&fA(Y12,{tokenUsage:G.tokenUsage})]})]})]})]})}function q12({block:A,marginTop:Q=0}){if(A.type==="message"){let[,B]=A.data;if(B.role==="assistant"&&B.state?.type==="streaming")return null;if(!B.content.some((D)=>D.type==="text"&&B.role!=="info"))return null;return fA(y6,{flexDirection:"column",gap:1,marginTop:Q,children:B.content.map((D,z)=>{if(D.type==="text")switch(B.role){case"assistant":return fA(y6,{children:fA(Fy1,{children:D.text})},z);case"user":return fA(y6,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,children:fA(h6,{color:"green",italic:!0,children:D.text})},z);case"info":return fA(y6,{children:fA(h6,{color:"gray",children:D.text})},z)}else if(D.type==="thinking"){let Z=D.thinking,X=xd(Z,!1);if(X.length===0)return null;return fA(y6,{flexDirection:"column",children:X.map((K,G)=>fA(y6,{children:fA(h6,{children:K})},G))},z)}return null})})}else if(A.type==="toolResult"){let[B,J]=A.data,D=m71(B,J,!1);if(D.length===0)return null;return fA(y6,{marginTop:Q,flexDirection:"column",children:D.map((z,Z)=>fA(y6,{children:fA(h6,{children:z})},Z))})}}function Y12({tokenUsage:A}){let Q=A.used/A.maxAvailable,B=Math.round(Q*100),J=Math.max(0,Math.min(B,100)),D="▁▂▃▄▅▆▇█",z=Math.floor(J*8/100),X="▁▂▃▄▅▆▇█"[Math.max(0,Math.min(z,7))],K=`${J}% ┃${X}┃`,G=0.8,q=0.9,Y;if(Q>=0.9)Y="red";else if(Q>=0.8)Y="yellow";return fA(h6,{color:Y,children:K})}function U12({lspState:A}){if(!A||Object.keys(A.servers).length===0)return null;let Q=Object.values(A.servers).map((B)=>{let J=B.status==="active"?"✓":B.status==="starting"?"⧗":"×",D=B.status==="active"?"green":B.status==="starting"?"yellow":"red";return{symbol:J,serverName:B.serverName,color:D}});return fA(y6,{gap:1,children:Q.map(({symbol:B,serverName:J,color:D},z)=>T9(h6,{color:D,children:[B," ",J]},z))})}global.React=wy1.default;function wQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(EQA,{inputs:B,outputs:Q,history:A.history,fuzzyServer:A.fuzzyServer,useNotifications:A.useNotifications}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout}).waitUntilExit().then(()=>{B.complete()}).catch((D)=>{B.next({type:"exit"})}),FA.from(B)}}var Wy1=Hy1.join(GAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function My1(A){try{await E12(Hy1.dirname(Wy1),{recursive:!0}),await H12(Wy1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function p71(){try{return(await w12(Wy1,"utf-8")).trim()}catch(A){return null}}var W12=[{name:"notifications",long:"notifications",type:"flag",default:!1,description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when interactive)`},{name:"interactive",long:"interactive",type:"switch",default:!1,description:"Force interactive mode"},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",description:`Custom settings file path (overrides the default location ${jE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(y1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",default:"ui",description:"Output format (ui: interactive terminal, jsonl: JSON Lines for scripts)",choices:["ui","jsonl","new-ui"],hidden:!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:process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,description:(A)=>`${A?"Enable":"Disable"} JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp CLI automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.`,hidden:!0}];function M12(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new tZ(Aq.unknownCommand(B),1,Z)}}class WQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=FD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function e3(A,Q){Hd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751486517-g5cc052");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=al(),D=kv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=oB1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new WQA,K=kq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await B2(s8);if(Q.dangerouslyAllowAll)q.settings.dangerouslyAllowAll=!0;if(Q.jetbrains)q.settings["jetbrains.enabled"]=!0;let Y=q.settings["experimental.reviewTool"]??!1,F=q.settings["experimental.tools"]??[];$P1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new N51,await E.start();try{await j9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=P9A(E,process.cwd())}else E=new class extends N51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(Z7.write(`No API key found. Starting login flow...
7456
+ `),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),W=g6.default(K),M=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+M.length}),q=G+W.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let W=0;W<H.length;W+=Q){let M=H.slice(W,W+Q).join("");J.push({type:Y?"start":"continuation",content:M,originalLine:D,start:G+W,end:G+W+g6.default(M).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var u71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=u71.useState(0);if(nW((z,Z)=>{if(Z.downArrow||Z.ctrl&&z.toLowerCase()==="n"||Z.tab&&!Z.shift)D((X)=>(X+1)%A.length);else if(Z.upArrow||Z.ctrl&&z.toLowerCase()==="p"||Z.shift&&Z.tab)D((X)=>(X-1+A.length)%A.length);else if(Z.return&&A[J])Q(A[J].value);else if(Z.escape)Q(null);else if(Z.ctrlC)Q(null)}),u71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return T9(y6,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[B&&fA(y6,{marginBottom:1,children:fA(h6,{bold:!0,children:B})}),A.map((z,Z)=>fA(y6,{children:T9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function D12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var UQA=10;function z12({messages:A,agentState:Q}){if(Q.type!=="streaming-thinking"&&Q.type!=="streaming-text")return null;let B=A.findLast((z)=>z.type==="message"&&z.data[1].role==="assistant"&&z.data[1].state?.type==="streaming");if(!B||B.type!=="message")return null;let[,J]=B.data;if(!J.content.some((z)=>z.type==="thinking"||z.type==="text"))return null;return fA(y6,{flexDirection:"column",marginBottom:1,children:J.content.map((z,Z)=>{if(z.type==="thinking"){let X=z.thinking,K=xd(X,!0);return fA(y6,{flexDirection:"column",marginTop:Z>0?1:0,children:K.map((G,q)=>fA(y6,{children:fA(h6,{children:G})},q))},Z)}else if(z.type==="text")return fA(y6,{marginTop:Z>0?1:0,children:fA(Fy1,{children:z.text})},Z);return null})})}function Z12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=X12(J.useBlock);else B="Confirm tool call"}else B=`Confirm ${A.tools.length} tool calls`;break}case"compaction":B=`Compact thread? (${A.severity} token usage)`;break;case"out-of-credits":B="Insufficient usage balance. Retry?";break;case"agent-file-creation":B="Create AGENT.md file for this codebase?";break}if(Q&&Q.total>1)B=`[${Q.current}/${Q.total}] ${B}`;return B}function X12(A){if(A.name===s4){let Q=A.input;return"Run "+pl.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return pl.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function K12(A){switch(A.type){case"tool-use":{let B=A.subthreadID===void 0&&A.tools.some((D)=>D.toAllow),J=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];if(B)J.push({value:"always",label:"Always (add to allowlist)"});return J}case"compaction":return[{value:"yes",label:"Yes"},...A.severity!=="critical"?[{value:"no",label:"No"}]:[]];case"out-of-credits":case"agent-file-creation":return[{value:"yes",label:"Yes"},{value:"no",label:"No"}]}}function G12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return T9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:T9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:T9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function FQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function EQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=ef(),[K]=t3.useState(()=>new C8);t3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=t3.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(W)=>{q((M)=>{if(M.type!=="confirming"||!M.currentConfirmation)return M;let I=M.currentConfirmation,N=M.confirmationQueue.slice(1),V=W===null?"no":W;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...M,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...M,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};t3.useEffect(()=>{let W=A.subscribe((M)=>{switch(M.type){case"state":{switch(M.state.type){case"shutting-down":q({...G,type:"exiting"}),Bj().then(()=>{z.exit()});break;case"idle":if(D)kf("idle");q((I)=>({...I,agentState:M.state}));break;default:q((I)=>({...I,agentState:M.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...M.blocks],V=FQA(N),_=_i({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:M.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:M.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(M.toolUse.name===UQ)return{...I,activeTools:N};if(M.status==="completed"||M.status==="error"||M.status==="cancelled")N.delete(M.toolUse.id);else{let V=M.subthreadID;N.set(M.toolUse.id,{toolUse:M.toolUse,status:M.status,startTime:M.startTime,endTime:M.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(M.subThreadID,{subThreadID:M.subThreadID,agentNumber:M.agentNumber,taskDescription:M.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(M.subThreadID);if(V)N.set(M.subThreadID,{...V,agentState:M.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)kf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,M.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:M.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:M.title}));break}default:y1.info("unhandled ui output",M);break}});return()=>{W.unsubscribe()}},[A,z]);let F=async(W,M)=>{let I=await D12(J,W);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:M}))},E=()=>{q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(W)=>{if(W!==null)K.next(W),q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};t3.useEffect(()=>{let W=null,M=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),W=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA)};return process.stdout.on("resize",M),()=>{if(W)clearTimeout(W);process.stdout.off("resize",M)}},[]),nW((W,M)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(M.escape)Q.next({type:"interrupt"});else if(M.ctrl&&W.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(M.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA);else if(M.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let W=FQA(G.messages);return fA(KQA,{threadName:G.threadTitle,messages:W,onExit:()=>q({...G,type:"running"})})}return T9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(f71,{items:G.messages,children:(W,M)=>fA(y6,{children:fA(q12,{block:W,marginTop:M===0?0:1},M)},M)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(z12,{messages:G.messages,agentState:G.agentState}),fA(s7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(zQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:Z12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:K12(G.currentConfirmation),onSelect:Y})}),T9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(G12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(YQA,{onSubmit:(W)=>{Q.next({type:"message",message:W})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let W=Math.min(10,Math.max(3,Math.floor(X*0.4))),M=G.completions.slice(0,W);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${M.length}${G.completions.length>W?`/${G.completions.length}`:""})`,options:M.map((I)=>({value:I,label:I})),onSelect:w})})})(),T9(y6,{gap:2,children:[T9(y6,{flexGrow:1,children:[G.type==="confirming-exit"&&fA(h6,{dimColor:!0,children:"Ctrl+C again to exit"}),G.type==="confirming"&&fA(h6,{dimColor:!0,children:"Escape to cancel"}),G.type==="running"&&T9(y6,{gap:1,children:[fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Enter to submit,"})}),fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Ctrl+R to expand"})})]})]}),T9(y6,{flexGrow:0,gap:2,children:[fA(U12,{lspState:G.lspState}),G.tokenUsage&&fA(Y12,{tokenUsage:G.tokenUsage})]})]})]})]})}function q12({block:A,marginTop:Q=0}){if(A.type==="message"){let[,B]=A.data;if(B.role==="assistant"&&B.state?.type==="streaming")return null;if(!B.content.some((D)=>D.type==="text"&&B.role!=="info"))return null;return fA(y6,{flexDirection:"column",gap:1,marginTop:Q,children:B.content.map((D,z)=>{if(D.type==="text")switch(B.role){case"assistant":return fA(y6,{children:fA(Fy1,{children:D.text})},z);case"user":return fA(y6,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,children:fA(h6,{color:"green",italic:!0,children:D.text})},z);case"info":return fA(y6,{children:fA(h6,{color:"gray",children:D.text})},z)}else if(D.type==="thinking"){let Z=D.thinking,X=xd(Z,!1);if(X.length===0)return null;return fA(y6,{flexDirection:"column",children:X.map((K,G)=>fA(y6,{children:fA(h6,{children:K})},G))},z)}return null})})}else if(A.type==="toolResult"){let[B,J]=A.data,D=m71(B,J,!1);if(D.length===0)return null;return fA(y6,{marginTop:Q,flexDirection:"column",children:D.map((z,Z)=>fA(y6,{children:fA(h6,{children:z})},Z))})}}function Y12({tokenUsage:A}){let Q=A.used/A.maxAvailable,B=Math.round(Q*100),J=Math.max(0,Math.min(B,100)),D="▁▂▃▄▅▆▇█",z=Math.floor(J*8/100),X="▁▂▃▄▅▆▇█"[Math.max(0,Math.min(z,7))],K=`${J}% ┃${X}┃`,G=0.8,q=0.9,Y;if(Q>=0.9)Y="red";else if(Q>=0.8)Y="yellow";return fA(h6,{color:Y,children:K})}function U12({lspState:A}){if(!A||Object.keys(A.servers).length===0)return null;let Q=Object.values(A.servers).map((B)=>{let J=B.status==="active"?"✓":B.status==="starting"?"⧗":"×",D=B.status==="active"?"green":B.status==="starting"?"yellow":"red";return{symbol:J,serverName:B.serverName,color:D}});return fA(y6,{gap:1,children:Q.map(({symbol:B,serverName:J,color:D},z)=>T9(h6,{color:D,children:[B," ",J]},z))})}global.React=wy1.default;function wQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(EQA,{inputs:B,outputs:Q,history:A.history,fuzzyServer:A.fuzzyServer,useNotifications:A.useNotifications}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout}).waitUntilExit().then(()=>{B.complete()}).catch((D)=>{B.next({type:"exit"})}),FA.from(B)}}var Wy1=Hy1.join(GAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function My1(A){try{await E12(Hy1.dirname(Wy1),{recursive:!0}),await H12(Wy1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function p71(){try{return(await w12(Wy1,"utf-8")).trim()}catch(A){return null}}var W12=[{name:"notifications",long:"notifications",type:"flag",default:!1,description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when interactive)`},{name:"interactive",long:"interactive",type:"switch",default:!1,description:"Force interactive mode"},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",description:`Custom settings file path (overrides the default location ${jE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(y1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",default:"ui",description:"Output format (ui: interactive terminal, jsonl: JSON Lines for scripts)",choices:["ui","jsonl","new-ui"],hidden:!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:process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,description:(A)=>`${A?"Enable":"Disable"} JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp CLI automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.`,hidden:!0}];function M12(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new tZ(Aq.unknownCommand(B),1,Z)}}class WQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=FD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function e3(A,Q){Hd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751515778-gc465ed");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=al(),D=kv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=oB1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new WQA,K=kq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await B2(s8);if(Q.dangerouslyAllowAll)q.settings.dangerouslyAllowAll=!0;if(Q.jetbrains)q.settings["jetbrains.enabled"]=!0;let Y=q.settings["experimental.reviewTool"]??!1,F=q.settings["experimental.tools"]??[];$P1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new N51,await E.start();try{await j9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=P9A(E,process.cwd())}else E=new class extends N51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(Z7.write(`No API key found. Starting login flow...
7457
7457
  `),!await I12(A,J))process.exit(1)}let H=cl1(),W=new HG1(H),M=new wG1(H),I=new gF1(W),N=new lf1({configService:Z,threadService:W,toolService:K,systemPromptService:X,threadSummaryService:I,threadHistoryService:M,mcpService:G}),V=void 0;return y1.info("Starting Amp background services"),V=Cn1({threadService:W,threadHistoryService:M,isExtensionDevelopment:!1}),{configService:Z,systemPromptService:X,toolService:K,mcpService:G,threadService:W,threadHistoryService:M,summaryService:I,threadSyncService:V,threadStorage:H,secretStorage:J,settingsStorage:D,fileWatcher:w,fuzzyServer:E,subthreadTracker:N}}async function I12(A,Q){if(A.isInteractiveMode){if(await fE("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return Z7.write(`Login cancelled. Run the command again to retry.
7458
7458
  `),!1}return await MQA(A,Q)}async function MQA(A,Q){let B=F12(32).toString("hex"),J=await o9A(A.ampURL,B);Z7.write(`If your browser doesn't open automatically, visit:
7459
7459
 
@@ -7468,8 +7468,8 @@ ${A.printer.print(J,{foreground:"blue",style:"bold"})}
7468
7468
  Login successful! You can now use the Amp CLI.
7469
7469
  `),!0}catch(D){return L8.write(`
7470
7470
  Login failed: ${D instanceof Error?D.message:String(D)}
7471
- `),!1}}var N12=new Set(["fuzzy-server"]);function C12(A){let Q=new h41().name("amp").description("AI-powered coding assistant").option("--thread-id [THREAD_ID]","ID of the thread to continue running",void 0);Q.exitOverride((Z)=>{if(Z.code==="commander.help"||Z.code==="commander.version"||Z.exitCode===0)vC(),process.exit(0);let X=Z.originalError??Z;Wf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.1751486517-g5cc052 ${A.printer.print("(released 2025-07-02T20:10:23.023Z)",{foreground:"gray"})}
7472
- `);else Z7.write(`0.0.1751486517-g5cc052 (released 2025-07-02T20:10:23.023Z)
7471
+ `),!1}}var N12=new Set(["fuzzy-server"]);function C12(A){let Q=new h41().name("amp").description("AI-powered coding assistant").option("--thread-id [THREAD_ID]","ID of the thread to continue running",void 0);Q.exitOverride((Z)=>{if(Z.code==="commander.help"||Z.code==="commander.version"||Z.exitCode===0)vC(),process.exit(0);let X=Z.originalError??Z;Wf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.1751515778-gc465ed ${A.printer.print("(released 2025-07-03T04:18:57.338Z)",{foreground:"gray"})}
7472
+ `);else Z7.write(`0.0.1751515778-gc465ed (released 2025-07-03T04:18:57.338Z)
7473
7473
  `);process.exit(0)}),Q.addHelpText("after",(()=>{let Z="";Z+=A.printer.print("Environment variables:",{style:"bold"})+`
7474
7474
 
7475
7475
  `,Z+=" "+A.printer.print("AMP_API_KEY",{foreground:"green"})+` API key for Amp (see https://ampcode.com/settings)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1751486517-g5cc052",
3
+ "version": "0.0.1751515778-gc465ed",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {