@sourcegraph/amp 0.0.1751542980-g32e18a → 0.0.1751558552-ga58f43

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 +6 -5
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6971,7 +6971,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
6971
6971
  `;break;case"id":X=M.includes("\x00")?void 0:M;break;case"retry":/^\d+$/.test(M)?J(parseInt(M,10)):B(new RK1(`Invalid \`retry\` value: "${M}"`,{type:"invalid-retry",value:M,line:W}));break;default:B(new RK1(`Unknown field "${H.length>20?`${H.slice(0,20)}…`:H}"`,{type:"unknown-field",field:H,value:M,line:W}));break}}function E(){K.length>0&&Q({id:X,event:G||void 0,data:K.endsWith(`
6972
6972
  `)?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 _HA(A){let Q=[],B="",J=A.length;for(let D=0;D<J;D++){let z=A[D];z==="\r"&&A[D+1]===`
6973
6973
  `?(Q.push(B),B="",D++):z==="\r"||z===`
6974
- `?(Q.push(B),B=""):B+=z}return[Q,B]}class LK1 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($i1(this),Q)}[Symbol.for("Deno.customInspect")](A,Q){return A($i1(this),Q)}}function THA(A){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(A,"SyntaxError"):new SyntaxError(A)}function _K1(A){return A instanceof Error?"errors"in A&&Array.isArray(A.errors)?A.errors.map(_K1).join(", "):("cause"in A)&&A.cause instanceof Error?`${A}: ${_K1(A.cause)}`:A.message:`${A}`}function $i1(A){return{type:A.type,message:A.message,code:A.code,defaultPrevented:A.defaultPrevented,cancelable:A.cancelable,timeStamp:A.timeStamp}}var ki1=(A)=>{throw TypeError(A)},kK1=(A,Q,B)=>Q.has(A)||ki1("Cannot "+B),V9=(A,Q,B)=>(kK1(A,Q,"read from private field"),B?B.call(A):Q.get(A)),OB=(A,Q,B)=>Q.has(A)?ki1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(A):Q.set(A,B),H7=(A,Q,B,J)=>(kK1(A,Q,"write to private field"),Q.set(A,B),B),mw=(A,Q,B)=>(kK1(A,Q,"access private method"),B),wZ,FO,dT,jn,Pn,zg,nT,Zg,eW,iT,sT,aT,Jg,dq,TK1,jK1,PK1,fi1,SK1,vK1,Dg,$K1,fK1;class rT extends EventTarget{constructor(A,Q){var B,J;super(),OB(this,dq),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,OB(this,wZ),OB(this,FO),OB(this,dT),OB(this,jn),OB(this,Pn),OB(this,zg),OB(this,nT),OB(this,Zg,null),OB(this,eW),OB(this,iT),OB(this,sT,null),OB(this,aT,null),OB(this,Jg,null),OB(this,jK1,async(D)=>{var z;V9(this,iT).reset();let{body:Z,redirected:X,status:K,headers:G}=D;if(K===204){mw(this,dq,Dg).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(X?H7(this,dT,new URL(D.url)):H7(this,dT,void 0),K!==200){mw(this,dq,Dg).call(this,`Non-200 status code (${K})`,K);return}if(!(G.get("content-type")||"").startsWith("text/event-stream")){mw(this,dq,Dg).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(V9(this,wZ)===this.CLOSED)return;H7(this,wZ,this.OPEN);let q=new Event("open");if((z=V9(this,Jg))==null||z.call(this,q),this.dispatchEvent(q),typeof Z!="object"||!Z||!("getReader"in Z)){mw(this,dq,Dg).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&&V9(this,iT).feed(Y.decode(H,{stream:!w})),w&&(E=!1,V9(this,iT).reset(),mw(this,dq,$K1).call(this))}while(E)}),OB(this,PK1,(D)=>{H7(this,eW,void 0),!(D.name==="AbortError"||D.type==="aborted")&&mw(this,dq,$K1).call(this,_K1(D))}),OB(this,SK1,(D)=>{typeof D.id=="string"&&H7(this,Zg,D.id);let z=new MessageEvent(D.event||"message",{data:D.data,origin:V9(this,dT)?V9(this,dT).origin:V9(this,FO).origin,lastEventId:D.id||""});V9(this,aT)&&(!D.event||D.event==="message")&&V9(this,aT).call(this,z),this.dispatchEvent(z)}),OB(this,vK1,(D)=>{H7(this,zg,D)}),OB(this,fK1,()=>{H7(this,nT,void 0),V9(this,wZ)===this.CONNECTING&&mw(this,dq,TK1).call(this)});try{if(A instanceof URL)H7(this,FO,A);else if(typeof A=="string")H7(this,FO,new URL(A,jHA()));else throw new Error("Invalid URL")}catch{throw THA("An invalid or illegal string was specified")}H7(this,iT,vi1({onEvent:V9(this,SK1),onRetry:V9(this,vK1)})),H7(this,wZ,this.CONNECTING),H7(this,zg,3000),H7(this,Pn,(B=Q==null?void 0:Q.fetch)!=null?B:globalThis.fetch),H7(this,jn,(J=Q==null?void 0:Q.withCredentials)!=null?J:!1),mw(this,dq,TK1).call(this)}get readyState(){return V9(this,wZ)}get url(){return V9(this,FO).href}get withCredentials(){return V9(this,jn)}get onerror(){return V9(this,sT)}set onerror(A){H7(this,sT,A)}get onmessage(){return V9(this,aT)}set onmessage(A){H7(this,aT,A)}get onopen(){return V9(this,Jg)}set onopen(A){H7(this,Jg,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(){V9(this,nT)&&clearTimeout(V9(this,nT)),V9(this,wZ)!==this.CLOSED&&(V9(this,eW)&&V9(this,eW).abort(),H7(this,wZ,this.CLOSED),H7(this,eW,void 0))}}wZ=new WeakMap,FO=new WeakMap,dT=new WeakMap,jn=new WeakMap,Pn=new WeakMap,zg=new WeakMap,nT=new WeakMap,Zg=new WeakMap,eW=new WeakMap,iT=new WeakMap,sT=new WeakMap,aT=new WeakMap,Jg=new WeakMap,dq=new WeakSet,TK1=function(){H7(this,wZ,this.CONNECTING),H7(this,eW,new AbortController),V9(this,Pn)(V9(this,FO),mw(this,dq,fi1).call(this)).then(V9(this,jK1)).catch(V9(this,PK1))},jK1=new WeakMap,PK1=new WeakMap,fi1=function(){var A;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...V9(this,Zg)?{"Last-Event-ID":V9(this,Zg)}:void 0},cache:"no-store",signal:(A=V9(this,eW))==null?void 0:A.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},SK1=new WeakMap,vK1=new WeakMap,Dg=function(A,Q){var B;V9(this,wZ)!==this.CLOSED&&H7(this,wZ,this.CLOSED);let J=new LK1("error",{code:Q,message:A});(B=V9(this,sT))==null||B.call(this,J),this.dispatchEvent(J)},$K1=function(A,Q){var B;if(V9(this,wZ)===this.CLOSED)return;H7(this,wZ,this.CONNECTING);let J=new LK1("error",{code:Q,message:A});(B=V9(this,sT))==null||B.call(this,J),this.dispatchEvent(J),H7(this,nT,setTimeout(V9(this,fK1),V9(this,zg)))},fK1=new WeakMap,rT.CONNECTING=0,rT.OPEN=1,rT.CLOSED=2;function jHA(){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 yK1;yK1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((A)=>A.webcrypto);async function PHA(A){return(await yK1).getRandomValues(new Uint8Array(A))}async function SHA(A){let B="",J=await PHA(A);for(let D=0;D<A;D++){let z=J[D]%66;B+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[z]}return B}async function vHA(A){return await SHA(A)}async function $HA(A){let Q=await(await yK1).subtle.digest("SHA-256",new TextEncoder().encode(A));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function gK1(A){if(!A)A=43;if(A<43||A>128)throw`Expected a length between 43 and 128. Received ${A}.`;let Q=await vHA(A),B=await $HA(Q);return{code_verifier:Q,code_challenge:B}}qO();sa();var yi1=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(),gi1=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(),bK1=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(),s52=f1.object({error:f1.string(),error_description:f1.string().optional(),error_uri:f1.string().optional()}),fHA=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(),kHA=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(),bi1=fHA.merge(kHA),r52=f1.object({error:f1.string(),error_description:f1.string().optional()}).strip(),o52=f1.object({token:f1.string(),token_type_hint:f1.string().optional()}).strip();class EO extends Error{constructor(A){super(A!==null&&A!==void 0?A:"Unauthorized")}}async function Sn(A,{serverUrl:Q,authorizationCode:B,scope:J,resourceMetadataUrl:D}){let z=Q;try{let F=await yHA(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 gHA(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 mHA(z,{metadata:Z,clientMetadata:A.clientMetadata});await A.saveClientInformation(F),X=F}if(B!==void 0){let F=await A.codeVerifier(),E=await xHA(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 hHA(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 bHA(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 xi1(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 yHA(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:lT}})}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 yi1.parse(await D.json())}async function gHA(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:lT}})}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 gi1.parse(await D.json())}async function bHA(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 gK1(),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 xHA(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 bK1.parse(await G.json())}async function hHA(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 bK1.parse({refresh_token:J,...await X.json()})}async function mHA(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 bi1.parse(await D.json())}class hi1 extends Error{constructor(A,Q,B){super(`SSE error: ${Q}`);this.code=A,this.event=B}}class xK1{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 EO("No auth provider");let Q;try{Q=await Sn(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 EO;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 rT(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 hi1(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=ta.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 EO("No auth provider");if(await Sn(this._authProvider,{serverUrl:this._url,authorizationCode:A,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new EO("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=xi1(X),await Sn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new EO;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();f7();D2();y2();var AI=Symbol.for("disabled-client");function xa1(A,Q,B){let J=new _n({name:"amp-mcp-client",version:"0.0.0-dev"}),D=FA.of(void 0).pipe(Xi(()=>pk(J9(async()=>{if(await J.close(),await new Promise((G)=>setTimeout(G,100)),B)return AI;return LMA(A,J,Q)}),Rw).pipe(qZ((G)=>{if(G instanceof _n)G?.close()})),{shouldCountRefs:!1})),z=D.subscribe({}),Z=D.pipe(r6((G)=>{if(G===AI)return{type:"disabled"};if(G===pU)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===pU||G instanceof Error||G===AI)return FA.of(G);let q=new C8;return G.setNotificationHandler(rX1,()=>{q.next()}),q.pipe(Zi({onUnsubscribe:()=>G.removeNotificationHandler("notifications/tools/list_changed")}),CB(void 0),r6(()=>G))})).pipe(Xi((G)=>{if(G instanceof Error)return FA.of(G);if(G===AI)return FA.of([]);return J9(async(q)=>{return(await G.listTools({signal:q})).tools})}));return{status:Z,tools:K,async callTool(G,q){let Y=await sx1(D);if(Y===AI)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){k1.error("Error closing MCP client:",G)}}}}async function LMA(A,Q,B){let J;if("url"in A)J=new xK1(new URL(A.url));else{let{loadProfileEnvironmentVariables:D}=await Promise.resolve().then(() => (mK1(),ui1)),Z={...B.loadProfile==="never"||!B.workingDirectory||!bW(B.workingDirectory)?process.env:await l6(D(B.workingDirectory.fsPath,B.loadProfile)),...A.env};J=await Promise.resolve().then(() => (ba1(),ga1)).then(({StdioClientTransport:X})=>{let{AMP_API_KEY:K,...G}=Z;return new X({...A,stderr:"pipe",cwd:B.workingDirectory&&bW(B.workingDirectory)?B.workingDirectory.fsPath:void 0,env:G})})}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)k1.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 ma1({configService:A,toolService:Q}){let B=new ua1,J=new C8,D=r8.pipe(r6(({settings:{mcpServers:E,"terminal.commands.nodeSpawn.loadProfile":w}})=>({mcpServers:E,loadProfile:w})),vq()),z=A.workspaceRoots.pipe(r6((E)=>E.at(0))),Z=new Map,X=w7(D,z,J.pipe(CB(void 0))).pipe($q(300),r6(async([{mcpServers:E,loadProfile:w},H,M])=>{let W=B.consume();for(let[I,N]of Object.entries(E??{})){let V=Z.get(I);if(!W&&V&&_MA(V.spec,N))continue;if(Z.set(I,{spec:N,client:xa1(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([]):w7(...E.map(([w,{spec:H,client:M}])=>M.tools.pipe(r6((W)=>({name:w,spec:H,tools:W===pU||W instanceof Error||W===AI?[]:W,client:M}))))))),q,Y=G.subscribe((E)=>{if(q)for(let w of q)w.dispose();q=[];for(let{name:w,tools:H,client:M}of E)for(let W of H)q.push(Q.registerTool(ha1(W,M,w)))},(E)=>{k1.error("MCP toolRegisterer error",E)});return{initialized:(async()=>{try{let E=await l6(r8),w=Object.keys(E.settings.mcpServers||{}).length;if(w===0)return;await l6(X.pipe(W5((H)=>H.length===0?FA.of([]):w7(...H.map(([M,{client:W}])=>W.status.pipe(t7((I)=>I.type==="connected"||I.type==="connection-failed"||I.type==="disabled"),r6(()=>M))))),t7((H)=>H.length>=w),nx1(1)),AbortSignal.timeout(1e4))}catch(E){k1.warn("MCP service initialization failed, but service will continue:",E)}})(),servers:w7(r8,X).pipe(W5(([E,w])=>w.length===0?FA.of([]):w7(...w.map(([H,{spec:M,client:W}])=>w7(W.status,W.tools).pipe(r6(([I,N])=>({name:H,spec:M,status:I,tools:N instanceof Error?N:N===pU||N===AI?[]:N.map((V)=>({spec:{name:V.name,description:V.description,inputSchema:V.inputSchema,source:{mcp:H}},...fy({name:V.name,source:{mcp:H}},E)}))}))))))),restartServers(){B.replenish(),J.next()},async registerToolsWithService(E){return new Promise((w)=>{let H=[],M=!1,W=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(ha1(T,_,N)));if(!M)M=!0,w({dispose:()=>{W.unsubscribe();for(let N of H)N.dispose();H.length=0}})},(I)=>{k1.error("MCP external tool registration error",I)})})},async addServer(E,w){let H=(await l6(r8)).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(M){throw new Error(`Invalid URL: ${w.url}`)}await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async removeServer(E){let w=(await l6(r8)).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 l6(r8)).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){k1.error("Error disposing MCP client:",H)}});await Promise.all(E),Z.clear()}}}function _MA(A,Q){return JSON.stringify(A)===JSON.stringify(Q)}function ha1(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)=>J9((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 ua1{forceRestart=!1;consume(){let A=this.forceRestart;return this.forceRestart=!1,A}replenish(){this.forceRestart=!0}}tK1();D2();function sa1(A){let Q={},B=!0;return A.changes.pipe(CB(void 0),mU(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 ra1(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(CB(void 0))}}f7();function oa1(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}}iK();var hn1=oa1({interval:20000,fn:WWA,cacheKey:(A,Q)=>A.toString()});async function WWA(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)=>!Hg(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],M=F===Y.length-1&&!q?"└ ":"├ ";if(w)z++;else Z++;let W=`${M}${E}${w?"/":""}`;D.push(W)}if(q){let F=K.length-G;D.push(`└ ... and ${F} more ${Aj(F,"entry","entries")}`)}return D.join(`
6974
+ `?(Q.push(B),B=""):B+=z}return[Q,B]}class LK1 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($i1(this),Q)}[Symbol.for("Deno.customInspect")](A,Q){return A($i1(this),Q)}}function THA(A){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(A,"SyntaxError"):new SyntaxError(A)}function _K1(A){return A instanceof Error?"errors"in A&&Array.isArray(A.errors)?A.errors.map(_K1).join(", "):("cause"in A)&&A.cause instanceof Error?`${A}: ${_K1(A.cause)}`:A.message:`${A}`}function $i1(A){return{type:A.type,message:A.message,code:A.code,defaultPrevented:A.defaultPrevented,cancelable:A.cancelable,timeStamp:A.timeStamp}}var ki1=(A)=>{throw TypeError(A)},kK1=(A,Q,B)=>Q.has(A)||ki1("Cannot "+B),V9=(A,Q,B)=>(kK1(A,Q,"read from private field"),B?B.call(A):Q.get(A)),OB=(A,Q,B)=>Q.has(A)?ki1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(A):Q.set(A,B),H7=(A,Q,B,J)=>(kK1(A,Q,"write to private field"),Q.set(A,B),B),mw=(A,Q,B)=>(kK1(A,Q,"access private method"),B),wZ,FO,dT,jn,Pn,zg,nT,Zg,eW,iT,sT,aT,Jg,dq,TK1,jK1,PK1,fi1,SK1,vK1,Dg,$K1,fK1;class rT extends EventTarget{constructor(A,Q){var B,J;super(),OB(this,dq),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,OB(this,wZ),OB(this,FO),OB(this,dT),OB(this,jn),OB(this,Pn),OB(this,zg),OB(this,nT),OB(this,Zg,null),OB(this,eW),OB(this,iT),OB(this,sT,null),OB(this,aT,null),OB(this,Jg,null),OB(this,jK1,async(D)=>{var z;V9(this,iT).reset();let{body:Z,redirected:X,status:K,headers:G}=D;if(K===204){mw(this,dq,Dg).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(X?H7(this,dT,new URL(D.url)):H7(this,dT,void 0),K!==200){mw(this,dq,Dg).call(this,`Non-200 status code (${K})`,K);return}if(!(G.get("content-type")||"").startsWith("text/event-stream")){mw(this,dq,Dg).call(this,'Invalid content type, expected "text/event-stream"',K);return}if(V9(this,wZ)===this.CLOSED)return;H7(this,wZ,this.OPEN);let q=new Event("open");if((z=V9(this,Jg))==null||z.call(this,q),this.dispatchEvent(q),typeof Z!="object"||!Z||!("getReader"in Z)){mw(this,dq,Dg).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&&V9(this,iT).feed(Y.decode(H,{stream:!w})),w&&(E=!1,V9(this,iT).reset(),mw(this,dq,$K1).call(this))}while(E)}),OB(this,PK1,(D)=>{H7(this,eW,void 0),!(D.name==="AbortError"||D.type==="aborted")&&mw(this,dq,$K1).call(this,_K1(D))}),OB(this,SK1,(D)=>{typeof D.id=="string"&&H7(this,Zg,D.id);let z=new MessageEvent(D.event||"message",{data:D.data,origin:V9(this,dT)?V9(this,dT).origin:V9(this,FO).origin,lastEventId:D.id||""});V9(this,aT)&&(!D.event||D.event==="message")&&V9(this,aT).call(this,z),this.dispatchEvent(z)}),OB(this,vK1,(D)=>{H7(this,zg,D)}),OB(this,fK1,()=>{H7(this,nT,void 0),V9(this,wZ)===this.CONNECTING&&mw(this,dq,TK1).call(this)});try{if(A instanceof URL)H7(this,FO,A);else if(typeof A=="string")H7(this,FO,new URL(A,jHA()));else throw new Error("Invalid URL")}catch{throw THA("An invalid or illegal string was specified")}H7(this,iT,vi1({onEvent:V9(this,SK1),onRetry:V9(this,vK1)})),H7(this,wZ,this.CONNECTING),H7(this,zg,3000),H7(this,Pn,(B=Q==null?void 0:Q.fetch)!=null?B:globalThis.fetch),H7(this,jn,(J=Q==null?void 0:Q.withCredentials)!=null?J:!1),mw(this,dq,TK1).call(this)}get readyState(){return V9(this,wZ)}get url(){return V9(this,FO).href}get withCredentials(){return V9(this,jn)}get onerror(){return V9(this,sT)}set onerror(A){H7(this,sT,A)}get onmessage(){return V9(this,aT)}set onmessage(A){H7(this,aT,A)}get onopen(){return V9(this,Jg)}set onopen(A){H7(this,Jg,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(){V9(this,nT)&&clearTimeout(V9(this,nT)),V9(this,wZ)!==this.CLOSED&&(V9(this,eW)&&V9(this,eW).abort(),H7(this,wZ,this.CLOSED),H7(this,eW,void 0))}}wZ=new WeakMap,FO=new WeakMap,dT=new WeakMap,jn=new WeakMap,Pn=new WeakMap,zg=new WeakMap,nT=new WeakMap,Zg=new WeakMap,eW=new WeakMap,iT=new WeakMap,sT=new WeakMap,aT=new WeakMap,Jg=new WeakMap,dq=new WeakSet,TK1=function(){H7(this,wZ,this.CONNECTING),H7(this,eW,new AbortController),V9(this,Pn)(V9(this,FO),mw(this,dq,fi1).call(this)).then(V9(this,jK1)).catch(V9(this,PK1))},jK1=new WeakMap,PK1=new WeakMap,fi1=function(){var A;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...V9(this,Zg)?{"Last-Event-ID":V9(this,Zg)}:void 0},cache:"no-store",signal:(A=V9(this,eW))==null?void 0:A.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},SK1=new WeakMap,vK1=new WeakMap,Dg=function(A,Q){var B;V9(this,wZ)!==this.CLOSED&&H7(this,wZ,this.CLOSED);let J=new LK1("error",{code:Q,message:A});(B=V9(this,sT))==null||B.call(this,J),this.dispatchEvent(J)},$K1=function(A,Q){var B;if(V9(this,wZ)===this.CLOSED)return;H7(this,wZ,this.CONNECTING);let J=new LK1("error",{code:Q,message:A});(B=V9(this,sT))==null||B.call(this,J),this.dispatchEvent(J),H7(this,nT,setTimeout(V9(this,fK1),V9(this,zg)))},fK1=new WeakMap,rT.CONNECTING=0,rT.OPEN=1,rT.CLOSED=2;function jHA(){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 yK1;yK1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((A)=>A.webcrypto);async function PHA(A){return(await yK1).getRandomValues(new Uint8Array(A))}async function SHA(A){let B="",J=await PHA(A);for(let D=0;D<A;D++){let z=J[D]%66;B+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[z]}return B}async function vHA(A){return await SHA(A)}async function $HA(A){let Q=await(await yK1).subtle.digest("SHA-256",new TextEncoder().encode(A));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function gK1(A){if(!A)A=43;if(A<43||A>128)throw`Expected a length between 43 and 128. Received ${A}.`;let Q=await vHA(A),B=await $HA(Q);return{code_verifier:Q,code_challenge:B}}qO();sa();var yi1=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(),gi1=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(),bK1=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(),s52=f1.object({error:f1.string(),error_description:f1.string().optional(),error_uri:f1.string().optional()}),fHA=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(),kHA=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(),bi1=fHA.merge(kHA),r52=f1.object({error:f1.string(),error_description:f1.string().optional()}).strip(),o52=f1.object({token:f1.string(),token_type_hint:f1.string().optional()}).strip();class EO extends Error{constructor(A){super(A!==null&&A!==void 0?A:"Unauthorized")}}async function Sn(A,{serverUrl:Q,authorizationCode:B,scope:J,resourceMetadataUrl:D}){let z=Q;try{let F=await yHA(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 gHA(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 mHA(z,{metadata:Z,clientMetadata:A.clientMetadata});await A.saveClientInformation(F),X=F}if(B!==void 0){let F=await A.codeVerifier(),E=await xHA(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 hHA(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 bHA(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 xi1(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 yHA(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:lT}})}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 yi1.parse(await D.json())}async function gHA(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:lT}})}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 gi1.parse(await D.json())}async function bHA(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 gK1(),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 xHA(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 bK1.parse(await G.json())}async function hHA(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 bK1.parse({refresh_token:J,...await X.json()})}async function mHA(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 bi1.parse(await D.json())}class hi1 extends Error{constructor(A,Q,B){super(`SSE error: ${Q}`);this.code=A,this.event=B}}class xK1{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 EO("No auth provider");let Q;try{Q=await Sn(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 EO;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 rT(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 hi1(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=ta.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 EO("No auth provider");if(await Sn(this._authProvider,{serverUrl:this._url,authorizationCode:A,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new EO("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=xi1(X),await Sn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl})!=="AUTHORIZED")throw new EO;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();f7();D2();y2();var AI=Symbol.for("disabled-client");function xa1(A,Q,B){let J=new _n({name:"amp-mcp-client",version:"0.0.0-dev"}),D=FA.of(void 0).pipe(Xi(()=>pk(J9(async()=>{if(await J.close(),await new Promise((G)=>setTimeout(G,100)),B)return AI;return LMA(A,J,Q)}),Rw).pipe(qZ((G)=>{if(G instanceof _n)G?.close()})),{shouldCountRefs:!1})),z=D.subscribe({}),Z=D.pipe(r6((G)=>{if(G===AI)return{type:"disabled"};if(G===pU)return{type:"connecting"};if(G instanceof Error){let q=G;return{type:"connection-failed",error:{message:q.message,stderr:q.stderr}}}return{type:"connected",capabilities:G.getServerCapabilities(),serverInfo:G.getServerVersion()}})),K=D.pipe(W5((G)=>{if(G===pU||G instanceof Error||G===AI)return FA.of(G);let q=new C8;return G.setNotificationHandler(rX1,()=>{q.next()}),q.pipe(Zi({onUnsubscribe:()=>G.removeNotificationHandler("notifications/tools/list_changed")}),CB(void 0),r6(()=>G))})).pipe(Xi((G)=>{if(G instanceof Error)return FA.of(G);if(G===AI)return FA.of([]);return J9(async(q)=>{return(await G.listTools({signal:q})).tools})}));return{status:Z,tools:K,async callTool(G,q){let Y=await sx1(D);if(Y===AI)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){k1.error("Error closing MCP client:",G)}}}}async function LMA(A,Q,B){let J;if("url"in A)J=new xK1(new URL(A.url));else{let{loadProfileEnvironmentVariables:z}=await Promise.resolve().then(() => (mK1(),ui1)),X={...B.loadProfile==="never"||!B.workingDirectory||!bW(B.workingDirectory)?process.env:await l6(z(B.workingDirectory.fsPath,B.loadProfile)),...A.env};J=await Promise.resolve().then(() => (ba1(),ga1)).then(({StdioClientTransport:K})=>{let{AMP_API_KEY:G,...q}=X;return new K({...A,stderr:"pipe",cwd:B.workingDirectory&&bW(B.workingDirectory)?B.workingDirectory.fsPath:void 0,env:q})})}let D=[];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",(z)=>{let Z=z.toString().trim();if(Z){if(D.push(Z),D.length>50)D=["[...]",...D.slice(-49)];k1.info("mcp-server-stderr",{stderr:Z,spec:A})}});try{let z=Q.connect(J),Z=new Promise((X,K)=>{let G=setTimeout(()=>{clearTimeout(G),K(new Error("Connection timeout: MCP server did not respond within 30 seconds"))},30000)});return await Promise.race([z,Z]),Q}catch(z){let Z=(X)=>{let K=new Error(X);if(D.length>0)K.stderr=D.join(`
6975
+ `);return K};if(z instanceof Error){if(z.message.includes("Connection closed"))throw Z("MCP server connection was closed unexpectedly.");else if(z.message.includes("Invalid content type"))throw Z('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&&z.message.includes("fetch failed"))throw Z(`Could not connect to MCP server at ${A.url}. Check that the server is running and accessible.`);else if(D.length>0)throw Z(z.message)}throw z}}function ma1({configService:A,toolService:Q}){let B=new ua1,J=new C8,D=r8.pipe(r6(({settings:{mcpServers:E,"terminal.commands.nodeSpawn.loadProfile":w}})=>({mcpServers:E,loadProfile:w})),vq()),z=A.workspaceRoots.pipe(r6((E)=>E.at(0))),Z=new Map,X=w7(D,z,J.pipe(CB(void 0))).pipe($q(300),r6(async([{mcpServers:E,loadProfile:w},H,M])=>{let W=B.consume();for(let[I,N]of Object.entries(E??{})){let V=Z.get(I);if(!W&&V&&_MA(V.spec,N))continue;if(Z.set(I,{spec:N,client:xa1(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([]):w7(...E.map(([w,{spec:H,client:M}])=>M.tools.pipe(r6((W)=>({name:w,spec:H,tools:W===pU||W instanceof Error||W===AI?[]:W,client:M}))))))),q,Y=G.subscribe((E)=>{if(q)for(let w of q)w.dispose();q=[];for(let{name:w,tools:H,client:M}of E)for(let W of H)q.push(Q.registerTool(ha1(W,M,w)))},(E)=>{k1.error("MCP toolRegisterer error",E)});return{initialized:(async()=>{try{let E=await l6(r8),w=Object.keys(E.settings.mcpServers||{}).length;if(w===0)return;await l6(X.pipe(W5((H)=>H.length===0?FA.of([]):w7(...H.map(([M,{client:W}])=>W.status.pipe(t7((I)=>I.type==="connected"||I.type==="connection-failed"||I.type==="disabled"),r6(()=>M))))),t7((H)=>H.length>=w),nx1(1)),AbortSignal.timeout(1e4))}catch(E){k1.warn("MCP service initialization failed, but service will continue:",E)}})(),servers:w7(r8,X).pipe(W5(([E,w])=>w.length===0?FA.of([]):w7(...w.map(([H,{spec:M,client:W}])=>w7(W.status,W.tools).pipe(r6(([I,N])=>({name:H,spec:M,status:I,tools:N instanceof Error?N:N===pU||N===AI?[]:N.map((V)=>({spec:{name:V.name,description:V.description,inputSchema:V.inputSchema,source:{mcp:H}},...fy({name:V.name,source:{mcp:H}},E)}))}))))))),restartServers(){B.replenish(),J.next()},async registerToolsWithService(E){return new Promise((w)=>{let H=[],M=!1,W=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(ha1(T,_,N)));if(!M)M=!0,w({dispose:()=>{W.unsubscribe();for(let N of H)N.dispose();H.length=0}})},(I)=>{k1.error("MCP external tool registration error",I)})})},async addServer(E,w){let H=(await l6(r8)).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(M){throw new Error(`Invalid URL: ${w.url}`)}await A.updateSettings("mcpServers",{...H,[E]:w},"global")},async removeServer(E){let w=(await l6(r8)).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 l6(r8)).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){k1.error("Error disposing MCP client:",H)}});await Promise.all(E),Z.clear()}}}function _MA(A,Q){return JSON.stringify(A)===JSON.stringify(Q)}function ha1(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)=>J9((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 ua1{forceRestart=!1;consume(){let A=this.forceRestart;return this.forceRestart=!1,A}replenish(){this.forceRestart=!0}}tK1();D2();function sa1(A){let Q={},B=!0;return A.changes.pipe(CB(void 0),mU(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 ra1(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(CB(void 0))}}f7();function oa1(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}}iK();var hn1=oa1({interval:20000,fn:WWA,cacheKey:(A,Q)=>A.toString()});async function WWA(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)=>!Hg(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],M=F===Y.length-1&&!q?"└ ":"├ ";if(w)z++;else Z++;let W=`${M}${E}${w?"/":""}`;D.push(W)}if(q){let F=K.length-G;D.push(`└ ... and ${F} more ${Aj(F,"entry","entries")}`)}return D.join(`
6975
6976
  `)}Hz();D2();class RG1{storage;constructor(A){this.storage=A;this._observeHistory=gW(sa1(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:IWA(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 IWA(A){return Math.max(A.created,...A.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}D2();gq();y2();var un1=G6(DT(),1);gq();ba();class LG1{storage;exclusiveThreads=new Map;exclusiveThreadsChanged=new C8;exclusiveThreadsChanges=this.exclusiveThreadsChanged.pipe(CB(void 0),Lw(()=>VWA.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?w7(...A.map((Q)=>{let B=this.exclusiveThreads.get(Q);if(!B)return Rw;return w7(B.pipe($q(0),CB(void 0)),this.flushRequests.pipe(CB(void 0))).pipe(mU(async()=>{let[J]=B.getValue();await this.storage.set(Q,J)}),uU((J)=>{return k1.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(CB(void 0),r6(()=>this.exclusiveThreads.has(A)),vq(),W5((Q)=>{if(Q)return this.exclusiveThreads.get(A).pipe(r6(([B,J])=>[B,J]));return J9(async(B)=>{let J=await this.storage.get(A);if(B?.throwIfAborted(),!J)J=mn1(A),await this.storage.set(A,J),B?.throwIfAborted();return[OT(J,!0),[]]})}))}observe(A){return this.observeRaw(A).pipe(r6(([Q,B])=>Q),WB1(100,{leading:!0,trailing:!0}))}observePatches(A){return this.observeRaw(A).pipe(r6(([Q,B],J)=>J===0?Q:B),NWA(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=mn1(A),await this.storage.set(A,D);D=OT(D,!0),Q=new CD([D,[]]),this.exclusiveThreads.set(A,Q),this.exclusiveThreadsChanged.next(),await NT()}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]=SX1(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]=SX1(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 mn1(A){return{v:0,id:A,created:Date.now(),messages:[]}}function NWA(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=un1.metrics.getMeter("thread-service"),VWA=CWA.createGauge("thread-service.exclusive-thread-count",{description:"Number of exclusive thread handles",unit:"threads"});D2();y2();VD();xk();Mg();As();function ln1({threadService:A,threadHistoryService:Q,isExtensionDevelopment:B=!1}){let J=!1,D=[],z=hx1(),Z=new CD(new Map),X=async()=>{if(J)return!1;if(!await l6(pn1))return!1;let H=await l6(r8);if(B&&kx1(H.settings.url))return k1.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 M=await l6(A.observe(H));if(M&&!M.messages.length)return;if(!await X())return;let W=new AbortController;D.push({dispose:()=>W.abort()});let I=!1;try{let N=await MO.uploadThread({thread:M,createdOnServer:!1},{signal:W.signal});if(!N.ok)throw new Error(`Failed to upload thread: ${N.error.code}`);I=!0}catch(N){if(k1.debug("Failed to upload thread (USE_NEW_INTERNAL_API=true)",N),!pw)throw N}if(!I&&pw){let N=await RB(`/api/threads/${H}`,{method:"POST",body:JSON.stringify(M),signal:W.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 M=G.get(H);if(!M)return!0;let W=Date.now()-M,I=W>=q;if(!I)k1.debug(`Skipping thread ${H} sync due to backoff (${Math.round(W/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(M){G.set(H,Date.now()),k1.error(`Error syncing thread ${H} (will retry after backoff)`,M,{name:"ThreadSyncService"})}}},E=async(H,M=!1)=>{if(!await X())return;let W;if(H)W=(await Promise.all(H.map((j)=>l6(A.observe(j).pipe(r6((P)=>P?{id:P.id,v:P.v}:null)))))).filter((j)=>j!==null);else{let j=await l6(Q.observeHistory().pipe(r6(($)=>$.map((f)=>({id:f.id,v:f.v}))))),P=await l6(A.exclusiveThreadsChanges.pipe(r6(($)=>Object.values($).map(([f,m])=>({id:f.id,v:f.v})))));W=j.concat(P)}let I={threadVersions:[],threadMetas:[]},N=new Set;for(let j of W){if(N.has(j.id))continue;if(N.add(j.id),!M)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()}),k1.debug("Sending threads sync request",{name:"ThreadSyncService"});let _=await RB("/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 k1.warn("Threads sync request failed",{name:"ThreadSyncService",status:_.status,text:j}),new Error(`Threads sync API responded with status: ${_.status}${j?`: ${j}`:""}`)}k1.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(),k1.debug(`Sync completed (${H?H.length:"all"} threads checked, ${R} threads needed sync)`,{name:"ThreadSyncService"})},w=E().catch((H)=>k1.error("Failed to perform initial sync:",H,{name:"ThreadSyncService"}));return D.push(MB1(z.observable.pipe(t7((H)=>H.size>0),$q(3000),mU(()=>F().catch((H)=>k1.error("Error processing sync queue:",H,{name:"ThreadSyncService"})))).subscribe({}))),D.push(MB1(A.exclusiveThreadsChanges.pipe(W5((H)=>hU(...Array.from(H.entries()).map(([,M])=>M.pipe(Lw(([W,I])=>z.add(W.id))))))).subscribe({}))),{async sync(){return E()},initialSyncComplete:w,async updateThreadMeta(H,M){let W=Z.getValue().get(H);try{Z.getValue().set(H,{status:"synced",info:{meta:M}}),Z.next(Z.getValue());let I=new AbortController;D.push({dispose:()=>I.abort()});let N=!1;try{let V=await MO.setThreadMeta({thread:H,meta:M},{signal:I.signal});if(!V.ok)throw new Error(`Failed to update sharing status: ${V.error.code}`);N=!0}catch(V){if(k1.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",V),!pw)throw V}if(!N&&pw){let V=await RB(`/api/threads/${H}/meta`,{method:"PUT",body:JSON.stringify({private:M.private,public:M.public}),signal:I.signal});if(!V.ok)throw new Error(`Failed to update sharing status: ${V.status}`)}}catch(I){if(W)Z.getValue().set(H,W);else Z.getValue().delete(H);throw Z.next(Z.getValue()),I}},threadSyncInfo(H){for(let M of H)if(!Z.getValue().has(M))Z.getValue().set(M,{status:"unknown"});return E(H,!0).catch((M)=>k1.error("Error syncing thread metadata:",M,{name:"ThreadSyncService"})),Z.pipe(r6((M)=>{let W={};for(let I of H)W[I]=M.get(I)??{status:"synced",info:null};return W}))},dispose(){if(J)return;J=!0;for(let H of D)H.dispose()}}}Go();lK();Tw1();t$();D2();y2();aL();D2();mo();y2();aL();Ez();lK();class kP1 extends C8{#A=new AbortController;#Q="o3";#B=[];#J=[];constructor(A,Q,B,J){y5(J.dir);let D=yq();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 o$({...J,toolService:A,getThreadEnvironment:()=>Promise.resolve(J.threadEnvironment),latestConfig:()=>Promise.resolve(J.config)},J.thread,{enableTodos:!1,enableTask:!1,enableOracle:!1},this.#A.signal);this.#A.signal.throwIfAborted();let X=z.map((w)=>w.text).join(`
6976
6977
  `),K=Q?`${Q}
6977
6978
 
@@ -7352,7 +7353,7 @@ ${B.join(`
7352
7353
  `)}function gr6(A,Q){if(A.state!=="active")return{type:"idle"};let B=cC(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=y7(Q,D.toolUseID);if(z){let Z=J.slice(1).map((X)=>{return y7(Q,X.toolUseID)?.name||"tool"}).filter(Boolean);return g51(z.name,J.length,Date.now(),z.input,Z.length>0?Z:void 0)}}}return{type:"idle"}}class tf1{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 sZ.getOrCreateForThread({configService:this.dependencies.configService,threadService:this.dependencies.threadService,toolService:this.dependencies.toolService,getThreadEnvironment:If,systemPromptService:this.dependencies.systemPromptService,threadSummaryService:this.dependencies.threadSummaryService,createFileSystem:await Rd,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 l6(this.dependencies.threadService.observe(A).pipe(t7((G)=>G!==void 0)));if(K){let G=gr6(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=y7(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){k1.error(`Failed to get thread for status update: ${A}`,K)}}}),gW(this.dependencies.threadService.observe(A).pipe(t7((X)=>X!==void 0))).observable.subscribe((X)=>{if(!X)return;let K=wz(X,"assistant");if(ha(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=y7(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 M=`${A}-${w.id}`,W=z.toolStartTimes?.get(M);if(this.events.next({type:"tool-status",toolUse:w,status:H,startTime:W,endTime:Date.now(),subthreadID:A}),z.toolStartTimes)z.toolStartTimes.delete(M)}}}}let q=wz(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=y7(X,E.toolUseID);if(w&&w.name===o4&&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(`
7353
7354
 
7354
7355
  `);this.events.next({type:"subagent-finished",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task completed",result:F})}if(!z.isCompleted){let F=yf(X,z.printedMessageIndexes,z.printedToolRuns);if(F.blocks.length>0)this.events.next({type:"subthread-message",subThreadID:A,agentNumber:z.agentNumber,blocks:F.blocks})}}),k1.debug(`Started tracking subthread ${A}`)}catch(J){k1.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=y7(A,B.toolUseID);if(J?.name===EQ&&(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=cy(D);if(z)this.trackSubthread(z,J.input?.description,J.input?.prompt).catch((Z)=>{k1.error(`Failed to track Task tool subthread ${z}`,Z)})}}}}async handleToolConfirmations(A,Q){let B=this.subthreads.get(A);if(!B){k1.error(`No tracker found for subthread ${A}`);return}k1.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)k1.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 M4A(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 W4A="Out of credits";Hz();ql();va();D2();b51();AK();A81();aL();import{readdir as br6}from"node:fs/promises";import{homedir as xr6}from"node:os";async function I4A(A,Q){let J=!(await Q81(A,Q)).some((z)=>z.type==="project"),D=await hr6();return{shouldGenerate:J&&D}}async function hr6(){let A=process.cwd(),Q=xr6();if(A===Q)return!1;try{return(await br6(A)).length>0}catch{return!1}}async function N4A(A){await A.handle({type:"user:message",message:{content:[{type:"text",text:mu0}]}})}y2();function a3(A,Q){return(B,J)=>{let D=Q(B,J);if(J.type!=="tick")k1.debug("Transition",{name:A,before:B,event:J,after:D});return D}}y2();import{spawn as V4A}from"node:child_process";import{readlink as mr6,stat as ur6}from"node:fs/promises";import{dirname as C4A,join as pr6}from"node:path";async function O4A(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=cr6(A,z),X=Z<0;return k1.info("Version comparison",{currentVersion:A,latestVersion:z,compareResult:Z,hasUpdate:X}),{hasUpdate:X,latestVersion:z}}catch(Q){return{hasUpdate:!1}}}function cr6(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 lr6(){try{let A=process.argv[1]||"";k1.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{let z=await mr6(A);if(z)Q=z,k1.debug("Resolved symlink",{from:A,to:Q});else k1.debug("Not a symlink or readlink returned empty")}catch(z){k1.debug("Error reading symlink (probably not a symlink)",{error:z})}if(k1.debug("Resolved installation path",{actualPath:Q}),Q.includes("/.local/share/pnpm/"))return k1.debug("Detected pnpm from path pattern: /.local/share/pnpm/"),"pnpm";if(Q.includes("/.config/yarn/global/"))return k1.debug("Detected yarn from path pattern: /.config/yarn/global/"),"yarn";if(Q.includes("/.bun/install/global/"))return k1.debug("Detected bun from path pattern: /.bun/install/global/"),"bun";if(Q.includes("/node_modules/@sourcegraph/amp/")){if(k1.debug("Found generic node_modules path, checking for specific patterns"),Q.includes("/.local/share/pnpm/"))return k1.debug("Detected pnpm from node_modules with pnpm-specific path"),"pnpm";if(Q.includes("/.config/yarn/"))return k1.debug("Detected yarn from node_modules with yarn-specific path"),"yarn";if(Q.includes("/.bun/"))return k1.debug("Detected bun from node_modules with bun-specific path"),"bun";return k1.debug("Defaulting to npm for generic node_modules path"),"npm"}k1.debug("No path pattern matched, checking installation directory for lockfiles");let B=C4A(C4A(Q));k1.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=pr6(B,z);return k1.debug("Checking for lockfile",{filePath:X}),await ur6(X),k1.debug("Found package manager lockfile",{file:z,manager:Z,filePath:X}),Z}catch(X){k1.debug("Lockfile not found",{file:z,error:X})}k1.debug("No lockfiles found, falling back to environment-based detection");let D=await R4A();return k1.debug("Environment-based detection result",{envDetected:D}),D}catch(A){return k1.debug("Error detecting installed package manager",{error:A}),null}}async function R4A(){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([x51("pnpm"),x51("yarn"),x51("bun"),x51("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 x51(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'`;k1.debug("Checking command existence",{command:A,fullCommand:D});let z=V4A("/bin/sh",["-c",D],{stdio:"ignore",cwd:process.env.HOME});z.on("close",(Z)=>{k1.debug("Command check result",{command:A,code:Z}),Q(Z===0)}),z.on("error",(Z)=>{k1.debug("Command check error",{command:A,error:Z}),Q(!1)})}catch(B){k1.debug("Error checking command existencer",{command:A,error:B}),Q(!1)}})}function dr6(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 L4A(A){let Q=await lr6();if(!Q)Q=await R4A();if(!Q)Q="npm",k1.debug("Falling back to npm for update");k1.debug("Using package manager for update",{packageManager:Q,targetVersion:A});let[B,J]=dr6(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}'`;k1.debug("Running update command",{packageManager:Q,command:B,args:J,fullCommand:G});let q=V4A("/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}:
7355
- ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function _4A({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 M=VT(),W=new Set,I=gW(B.observe(E).pipe(t7((S)=>S!==void 0))),N=new Set,V=new Map;await l6(I.observable);let _=await Rd,T=await sZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:If,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{k1.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=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=hU(R,j,hU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{k1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(qZ(()=>{b()})).pipe(XT(a3("threadSession",function(S,y){function d(D1){k1.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>h51.CRITICAL)return k1.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)=>{k1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{k1.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=cC(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 k1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{k1.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>h51.CRITICAL)K1="critical",X1="final";else if(A1>h51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>h51.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)k1.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)=>{k1.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&&W.size===0&&y.thread.messages.length>0){let K1=yf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=xa(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=cC(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=yf(y.thread,W,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=cC(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 s=wz(y.thread,"assistant"),r=s?y.thread.messages.indexOf(s):null;if(r!==null&&r!==S.currentAssistantMessageIndex)k1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:r,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=r;let e=wz(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(s?.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=y7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===o4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,k1.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?y7(y.thread,P1.toolUseID):null;if(P1&&R1)return k1.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 k1.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=xa(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(W4A)){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(M4A(y.status.ephemeralError))return k1.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(k1.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=cC(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=y7(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?y7(I.value.last,K1[0].toolUseID):void 0,s=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return y7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,r=N1?g51(N1.name,X1,Date.now(),N1.input,s):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:s};$.next({type:"state",state:r})}else{let N1=I.value.last;if(N1){let s=cC(N1);if(s)$.next({type:"state",state:s});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 k1.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)=>{k1.error("Failed to send subthread tool confirmations",D1)}),k1.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 k1.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)=>{k1.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")}),k1.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=xa(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,s=K1.used,r=N1-s,e=N1>0?r/N1*100:0;if(r<=0)k1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:s,reduction:r,threadID:E});else if(e<10)k1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E});else k1.info("Compaction successful",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E})}else k1.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&&W.size===0&&y.messages.length>0){let A1=yf({id:E,messages:y.messages},W,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(k1.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 k1.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 k1.info("Checking agent file status"),I4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{k1.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"}),sZ.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 sZ.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")sZ.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(()=>{k1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{k1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return k1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return k1.error("No current tool ID in collecting-tool-confirmations state"),S;if(k1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){k1.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)=>{k1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],s=S.confirmationQueue.slice(1);return k1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:s.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:s}}return k1.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 k1.error("Thread not available for finding next tool"),S;let r=(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=r?y7(I.value.last,r.toolUseID):null;if(r&&e)return k1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:r.run.status==="blocked-on-user"?r.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");k1.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 N4A(T).catch((D1)=>{k1.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)=>{k1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)k1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else k1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else k1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return ir6(P).catch((S)=>{k1.debug("Update check startup failed",S)}),await l6(g)}async function ir6(A){try{let Q=await O4A("0.0.1751542980-g32e18a");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await L4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){k1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else k1.info("No update available")}catch(Q){k1.debug("Update check failed",Q)}}var h51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();D2();gq();function T4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7356
+ ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function _4A({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 M=VT(),W=new Set,I=gW(B.observe(E).pipe(t7((S)=>S!==void 0))),N=new Set,V=new Map;await l6(I.observable);let _=await Rd,T=await sZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:If,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{k1.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=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=hU(R,j,hU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{k1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(qZ(()=>{b()})).pipe(XT(a3("threadSession",function(S,y){function d(D1){k1.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>h51.CRITICAL)return k1.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)=>{k1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{k1.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=cC(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 k1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{k1.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>h51.CRITICAL)K1="critical",X1="final";else if(A1>h51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>h51.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)k1.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)=>{k1.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&&W.size===0&&y.thread.messages.length>0){let K1=yf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=xa(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=cC(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=yf(y.thread,W,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=cC(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 s=wz(y.thread,"assistant"),r=s?y.thread.messages.indexOf(s):null;if(r!==null&&r!==S.currentAssistantMessageIndex)k1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:r,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=r;let e=wz(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(s?.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=y7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===o4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,k1.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?y7(y.thread,P1.toolUseID):null;if(P1&&R1)return k1.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 k1.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=xa(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(W4A)){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(M4A(y.status.ephemeralError))return k1.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(k1.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=cC(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=y7(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?y7(I.value.last,K1[0].toolUseID):void 0,s=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return y7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,r=N1?g51(N1.name,X1,Date.now(),N1.input,s):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:s};$.next({type:"state",state:r})}else{let N1=I.value.last;if(N1){let s=cC(N1);if(s)$.next({type:"state",state:s});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 k1.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)=>{k1.error("Failed to send subthread tool confirmations",D1)}),k1.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 k1.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)=>{k1.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")}),k1.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=xa(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,s=K1.used,r=N1-s,e=N1>0?r/N1*100:0;if(r<=0)k1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:s,reduction:r,threadID:E});else if(e<10)k1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E});else k1.info("Compaction successful",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E})}else k1.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&&W.size===0&&y.messages.length>0){let A1=yf({id:E,messages:y.messages},W,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(k1.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 k1.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 k1.info("Checking agent file status"),I4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{k1.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"}),sZ.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 sZ.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")sZ.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(()=>{k1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{k1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return k1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return k1.error("No current tool ID in collecting-tool-confirmations state"),S;if(k1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){k1.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)=>{k1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],s=S.confirmationQueue.slice(1);return k1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:s.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:s}}return k1.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 k1.error("Thread not available for finding next tool"),S;let r=(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=r?y7(I.value.last,r.toolUseID):null;if(r&&e)return k1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:r.run.status==="blocked-on-user"?r.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");k1.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 N4A(T).catch((D1)=>{k1.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)=>{k1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)k1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else k1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else k1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return ir6(P).catch((S)=>{k1.debug("Update check startup failed",S)}),await l6(g)}async function ir6(A){try{let Q=await O4A("0.0.1751558552-ga58f43");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await L4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){k1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else k1.info("No update available")}catch(Q){k1.debug("Update check failed",Q)}}var h51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();D2();gq();function T4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7356
7357
  `)}return(z)=>{let Z=new C8;if(!J)throw new Error("JSONL UI requires piped input (non-interactive mode)");return k1.debug("setting up JSONL UI"),z.pipe(Zi({onSubscribe:()=>{D({type:"initial",threadID:B}),NT().then(()=>{Z.next({type:"initialized"})})},onUnsubscribe:()=>{k1.debug("JSONL UI stopped")}})).pipe(qZ(()=>{Z.complete()})).pipe(XT(a3("JSONL",(X,K)=>{if(k1.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:M}=w;return{type:H,text:M}}else if(w.type==="image"){let{type:H,source:M}=w;return{type:H,source:M}}else if(w.type==="tool_result"){let{type:H,toolUseID:M,run:W,userInput:I}=w;return{type:H,toolUseID:M,run:W,userInput:I}}else if(w.type==="thinking"){let{type:H,thinking:M}=w;return{type:H,thinking:M}}else if(w.type==="redacted_thinking"){let{type:H,data:M}=w;return{type:H,data:M}}else if(w.type==="tool_use"){let{type:H,id:M,name:W,input:I}=w,N={type:H,id:M,name:W};if(I!==void 0)N.input=I;return N}else if(w.type==="server_tool_use"){let{type:H,id:M,name:W,input:I}=w;return{type:H,id:M,name:W,input:I}}else if(w.type==="web_search_tool_result"){let{type:H,content:M}=w;return{type:H,content:M}}else if(w.type==="summary"){let{type:H,summary:M}=w;return{type:H,summary:M}}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:M,content:W,meta:I}=H,N={role:M,content:G(W),meta:I};Y.push([w,N])}else if(H.role==="assistant"){let{role:M,content:W,state:I}=H,N={role:M,content:G(W),state:I};Y.push([w,N])}else if(H.role==="info"){let{role:M,content:W}=H,I={role:M,content:G(W)};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 M={type:w.type,id:w.id,name:w.name,input:{}},W={type:H.type,toolUseID:H.toolUseID,run:q(z5(H.run))};F.push([M,W])}else k1.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 k1.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===o4&&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)=>{k1.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 gf}from"node:child_process";function bf(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")gf("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")gf("powershell [console]::beep(800,200)");else if(process.platform==="linux")gf("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="requires-user-input"){if(process.platform==="darwin")gf("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")gf("powershell [console]::beep(1000,300)");else if(process.platform==="linux")gf("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){k1.error(`Failed to play notification sound (${A}):`,Q)}}D2();y2();import{mkdir as j4A,readFile as P4A,writeFile as ef1,open as ar6}from"node:fs/promises";import{homedir as nr6}from"node:os";import Ld from"node:path";var sr6=Ld.join(Cf||Ld.join(nr6(),".local/share"),"amp"),rr6=Ld.join(sr6,"history.jsonl"),or6=1000;class _d{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(A){this.historyFile=A?.historyFile||rr6,this.maxSize=A?.maxSize||or6,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)this.history=await this.readHistoryFromDisk(),this.loaded=!0}async readHistoryFromDisk(){try{let A=await P4A(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return k1.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 P4A(Q,"utf-8");if(B.trim()){let J=JSON.parse(B);k1.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(`
7357
7358
  `),B=[];for(let J of Q)if(J.trim())try{let D=JSON.parse(J);if(typeof D==="string")B.push(D);else k1.warn("Skipping non-string entry in history",{line:J,type:typeof D})}catch(D){k1.warn("Skipping invalid JSONL line in history",{line:J})}return k1.info("Loaded history from JSONL file",{file:this.historyFile,size:B.length}),B}async writeHistoryToDisk(A){await j4A(Ld.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
7358
7359
  `)+`
@@ -7480,7 +7481,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
7480
7481
  `),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(`
7481
7482
  `),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=VQA(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=OQA(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(k1.debug("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("")+`
7482
7483
  `+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){k1.error("Failed to submit message",u)}finally{w(!1)}};return fA(y6,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:Z,children:M.map((b,u)=>fA(y6,{flexShrink:0,flexDirection:"row",children:fA(y6,{flexGrow:1,flexShrink:0,width:"100%",children:u===X.virtualLine?j9(My1,{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 P12(A,Q){let B=A.split(`
7483
- `),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(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).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 r71=G6(z4(),1);function Vy1({options:A,onSelect:Q,title:B}){let[J,D]=r71.useState(0);if(rM((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)}),r71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return j9(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:j9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function S12(A,Q){try{return await A.query(Q)}catch(B){return k1.error("Completion failed",B),[]}}var LQA=10;function v12({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=cd(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(Cy1,{children:z.text})},Z);return null})})}function $12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=f12(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 f12(A){if(A.name===o4){let Q=A.input;return"Run "+al.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return al.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 y12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return j9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:j9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:j9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function _QA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function TQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=Fy1(),[Z,X]=Bk(),[K]=A_.useState(()=>new C8);A_.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=A_.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=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;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{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};A_.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),NT().then(()=>{z.exit()});break;case"idle":if(D)bf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=_QA(N),_=ma({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.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(W.toolUse.name===EQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)bf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.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:W.title}));break}default:k1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await S12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};A_.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),rM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.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}))},LQA);else if(W.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 M=_QA(G.messages);return fA(CQA,{threadName:G.threadTitle,messages:M,onExit:()=>q({...G,type:"running"})})}return j9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(p71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(g12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&j9(y6,{flexDirection:"column",marginTop:1,children:[fA(v12,{messages:G.messages,agentState:G.agentState}),fA(GQA,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(WQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Vy1,{title:$12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:k12(G.currentConfirmation),onSelect:Y})}),j9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(y12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(RQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Vy1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.map((I)=>({value:I,label:I})),onSelect:w})})})(),j9(y6,{gap:2,children:[j9(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"&&j9(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"})})]})]}),j9(y6,{flexGrow:0,gap:2,children:[fA(x12,{lspState:G.lspState}),G.tokenUsage&&fA(b12,{tokenUsage:G.tokenUsage})]})]})]})]})}function g12({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(Cy1,{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=cd(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=s71(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 b12({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 x12({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)=>j9(h6,{color:D,children:[B," ",J]},z))})}global.React=Oy1.default;function jQA(A){return JA.level=1,(Q)=>{let B=new C8;return Uy1(Oy1.default.createElement(TQA,{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 Ly1=Ry1.join(CAA||Ry1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function _y1(A){try{await m12(Ry1.dirname(Ly1),{recursive:!0}),await p12(Ly1,A,"utf-8")}catch(Q){k1.debug("Failed to save last thread ID",Q)}}async function o71(){try{return(await u12(Ly1,"utf-8")).trim()}catch(A){return null}}var c12=[{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(k1).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 l12(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 eZ(Qq.unknownCommand(B),1,Z)}}class SQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=oK1(null),J=await hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function Q_(A,Q){Cd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),nc1("0.0.1751542980-g32e18a");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;k1.info("Using settings file",{settingsFile:B});let J=tl(),D=uv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=yX1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new SQA,K=yq(),G=ma1({configService:Z,toolService:K});try{await G.initialized}catch(_){k1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await l6(r8);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"]??[];hP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new P51,await E.start();try{await u9A(E,process.cwd())}catch(_){k1.error("Failed to index files for fuzzy completion",_)}w=p9A(E,process.cwd())}else E=new class extends P51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(K7.write(`No API key found. Starting login flow...
7484
+ `),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(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).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 r71=G6(z4(),1);function Vy1({options:A,onSelect:Q,title:B}){let[J,D]=r71.useState(0);if(rM((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)}),r71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return j9(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:j9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function S12(A,Q){try{return await A.query(Q)}catch(B){return k1.error("Completion failed",B),[]}}var LQA=10;function v12({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=cd(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(Cy1,{children:z.text})},Z);return null})})}function $12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=f12(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 f12(A){if(A.name===o4){let Q=A.input;return"Run "+al.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return al.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 y12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return j9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:j9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:j9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function _QA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function TQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=Fy1(),[Z,X]=Bk(),[K]=A_.useState(()=>new C8);A_.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=A_.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=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;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{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};A_.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),NT().then(()=>{z.exit()});break;case"idle":if(D)bf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=_QA(N),_=ma({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.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(W.toolUse.name===EQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)bf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.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:W.title}));break}default:k1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await S12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};A_.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),rM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.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}))},LQA);else if(W.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 M=_QA(G.messages);return fA(CQA,{threadName:G.threadTitle,messages:M,onExit:()=>q({...G,type:"running"})})}return j9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(p71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(g12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&j9(y6,{flexDirection:"column",marginTop:1,children:[fA(v12,{messages:G.messages,agentState:G.agentState}),fA(GQA,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(WQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Vy1,{title:$12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:k12(G.currentConfirmation),onSelect:Y})}),j9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(y12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(RQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Vy1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.map((I)=>({value:I,label:I})),onSelect:w})})})(),j9(y6,{gap:2,children:[j9(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"&&j9(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"})})]})]}),j9(y6,{flexGrow:0,gap:2,children:[fA(x12,{lspState:G.lspState}),G.tokenUsage&&fA(b12,{tokenUsage:G.tokenUsage})]})]})]})]})}function g12({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(Cy1,{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=cd(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=s71(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 b12({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 x12({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)=>j9(h6,{color:D,children:[B," ",J]},z))})}global.React=Oy1.default;function jQA(A){return JA.level=1,(Q)=>{let B=new C8;return Uy1(Oy1.default.createElement(TQA,{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 Ly1=Ry1.join(CAA||Ry1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function _y1(A){try{await m12(Ry1.dirname(Ly1),{recursive:!0}),await p12(Ly1,A,"utf-8")}catch(Q){k1.debug("Failed to save last thread ID",Q)}}async function o71(){try{return(await u12(Ly1,"utf-8")).trim()}catch(A){return null}}var c12=[{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(k1).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 l12(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 eZ(Qq.unknownCommand(B),1,Z)}}class SQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=oK1(null),J=await hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function Q_(A,Q){Cd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),nc1("0.0.1751558552-ga58f43");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;k1.info("Using settings file",{settingsFile:B});let J=tl(),D=uv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=yX1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new SQA,K=yq(),G=ma1({configService:Z,toolService:K});try{await G.initialized}catch(_){k1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await l6(r8);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"]??[];hP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new P51,await E.start();try{await u9A(E,process.cwd())}catch(_){k1.error("Failed to index files for fuzzy completion",_)}w=p9A(E,process.cwd())}else E=new class extends P51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(K7.write(`No API key found. Starting login flow...
7484
7485
  `),!await d12(A,J))process.exit(1)}let H=ra1(),M=new LG1(H),W=new RG1(H),I=new lF1(M),N=new tf1({configService:Z,threadService:M,toolService:K,systemPromptService:X,threadSummaryService:I,threadHistoryService:W,mcpService:G}),V=void 0;return k1.info("Starting Amp background services"),V=ln1({threadService:M,threadHistoryService:W,isExtensionDevelopment:!1}),{configService:Z,systemPromptService:X,toolService:K,mcpService:G,threadService:M,threadHistoryService:W,summaryService:I,threadSyncService:V,threadStorage:H,secretStorage:J,settingsStorage:D,fileWatcher:w,fuzzyServer:E,subthreadTracker:N}}async function d12(A,Q){if(A.isInteractiveMode){if(await fE("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return K7.write(`Login cancelled. Run the command again to retry.
7485
7486
  `),!1}return await vQA(A,Q)}async function vQA(A,Q){let B=h12(32).toString("hex"),J=await q4A(A.ampURL,B);K7.write(`If your browser doesn't open automatically, visit:
7486
7487
 
@@ -7495,8 +7496,8 @@ ${A.printer.print(J,{foreground:"blue",style:"bold"})}
7495
7496
  Login successful! You can now use the Amp CLI.
7496
7497
  `),!0}catch(D){return L8.write(`
7497
7498
  Login failed: ${D instanceof Error?D.message:String(D)}
7498
- `),!1}}var i12=new Set(["fuzzy-server"]);function a12(A){let Q=new n41().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)$C(),process.exit(0);let X=Z.originalError??Z;Nf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)K7.write(`0.0.1751542980-g32e18a ${A.printer.print("(released 2025-07-03T11:49:38.394Z)",{foreground:"gray"})}
7499
- `);else K7.write(`0.0.1751542980-g32e18a (released 2025-07-03T11:49:38.394Z)
7499
+ `),!1}}var i12=new Set(["fuzzy-server"]);function a12(A){let Q=new n41().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)$C(),process.exit(0);let X=Z.originalError??Z;Nf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)K7.write(`0.0.1751558552-ga58f43 ${A.printer.print("(released 2025-07-03T16:11:58.165Z)",{foreground:"gray"})}
7500
+ `);else K7.write(`0.0.1751558552-ga58f43 (released 2025-07-03T16:11:58.165Z)
7500
7501
  `);process.exit(0)}),Q.addHelpText("after",(()=>{let Z="";Z+=A.printer.print("Environment variables:",{style:"bold"})+`
7501
7502
 
7502
7503
  `,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.1751542980-g32e18a",
3
+ "version": "0.0.1751558552-ga58f43",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {