@sourcegraph/amp 0.0.1764878483-g1dd0b0 → 0.0.1764892237-g17504a

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 +15 -15
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -2917,9 +2917,9 @@ ${J.trim()}
2917
2917
  `);Y.enqueue(V)}catch(X){Y.error(X)}},async cancel(){await Q.return?.()}})}}async function*Nm4(J,Q){if(!J.body)throw Q.abort(),new xQ("Attempted to iterate over a response with no body");let Z=new rh0,Y=new UL,X=sh0(J.body);for await(let G of Dm4(X))for(let V of Y.decode(G)){let K=Z.decode(V);if(K)yield K}for(let G of Y.flush()){let V=Z.decode(G);if(V)yield V}}async function*Dm4(J){let Q=new Uint8Array;for await(let Z of J){if(Z==null)continue;let Y=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?new TextEncoder().encode(Z):Z,X=new Uint8Array(Q.length+Y.length);X.set(Q),X.set(Y,Q.length),Q=X;let G;while((G=Mm4(Q))!==-1)yield Q.slice(0,G),Q=Q.slice(G)}if(Q.length>0)yield Q}function Mm4(J){for(let Y=0;Y<J.length-2;Y++){if(J[Y]===10&&J[Y+1]===10)return Y+2;if(J[Y]===13&&J[Y+1]===13)return Y+2;if(J[Y]===13&&J[Y+1]===10&&Y+3<J.length&&J[Y+2]===13&&J[Y+3]===10)return Y+4}return-1}class rh0{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(J){if(J.endsWith("\r"))J=J.substring(0,J.length-1);if(!J){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
2918
2918
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push(J),J.startsWith(":"))return null;let[Q,Z,Y]=Lm4(J,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Q==="event")this.event=Y;else if(Q==="data")this.data.push(Y);return null}}class UL{constructor(){this.buffer=[],this.trailingCR=!1}decode(J){let Q=this.decodeText(J);if(this.trailingCR)Q="\r"+Q,this.trailingCR=!1;if(Q.endsWith("\r"))this.trailingCR=!0,Q=Q.slice(0,-1);if(!Q)return[];let Z=UL.NEWLINE_CHARS.has(Q[Q.length-1]||""),Y=Q.split(UL.NEWLINE_REGEXP);if(Z)Y.pop();if(Y.length===1&&!Z)return this.buffer.push(Y[0]),[];if(this.buffer.length>0)Y=[this.buffer.join("")+Y[0],...Y.slice(1)],this.buffer=[];if(!Z)this.buffer=[Y.pop()||""];return Y}decodeText(J){if(J==null)return"";if(typeof J==="string")return J;if(typeof Buffer<"u"){if(J instanceof Buffer)return J.toString();if(J instanceof Uint8Array)return Buffer.from(J).toString();throw new xQ(`Unexpected: received non-Uint8Array (${J.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(J instanceof Uint8Array||J instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(J);throw new xQ(`Unexpected: received non-Uint8Array/ArrayBuffer (${J.constructor.name}) in a web platform. Please report this error.`)}throw new xQ("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let J=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,J}}UL.NEWLINE_CHARS=new Set([`
2919
2919
  `,"\r"]);UL.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Lm4(J,Q){let Z=J.indexOf(Q);if(Z!==-1)return[J.substring(0,Z),Q,J.substring(Z+Q.length)];return[J,"",""]}function sh0(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Z=await Q.read();if(Z?.done)Q.releaseLock();return Z}catch(Z){throw Q.releaseLock(),Z}},async return(){let Z=Q.cancel();return Q.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var Am4=(J)=>J!=null&&typeof J==="object"&&typeof J.url==="string"&&typeof J.blob==="function",Om4=(J)=>J!=null&&typeof J==="object"&&typeof J.name==="string"&&typeof J.lastModified==="number"&&tf(J),tf=(J)=>J!=null&&typeof J==="object"&&typeof J.size==="number"&&typeof J.type==="string"&&typeof J.text==="function"&&typeof J.slice==="function"&&typeof J.arrayBuffer==="function";async function th0(J,Q,Z){if(J=await J,Om4(J))return J;if(Am4(J)){let X=await J.blob();Q||(Q=new URL(J.url).pathname.split(/[\\/]/).pop()??"unknown_file");let G=tf(X)?[await X.arrayBuffer()]:[X];return new Ss(G,Q,Z)}let Y=await wm4(J);if(Q||(Q=Im4(J)??"unknown_file"),!Z?.type){let X=Y[0]?.type;if(typeof X==="string")Z={...Z,type:X}}return new Ss(Y,Q,Z)}async function wm4(J){let Q=[];if(typeof J==="string"||ArrayBuffer.isView(J)||J instanceof ArrayBuffer)Q.push(J);else if(tf(J))Q.push(await J.arrayBuffer());else if(Pm4(J))for await(let Z of J)Q.push(Z);else throw Error(`Unexpected data type: ${typeof J}; constructor: ${J?.constructor?.name}; props: ${Em4(J)}`);return Q}function Em4(J){return`[${Object.getOwnPropertyNames(J).map((Z)=>`"${Z}"`).join(", ")}]`}function Im4(J){return fA1(J.name)||fA1(J.filename)||fA1(J.path)?.split(/[\\/]/).pop()}var fA1=(J)=>{if(typeof J==="string")return J;if(typeof Buffer<"u"&&J instanceof Buffer)return String(J);return},Pm4=(J)=>J!=null&&typeof J==="object"&&typeof J[Symbol.asyncIterator]==="function",hA1=(J)=>J&&typeof J==="object"&&J.body&&J[Symbol.toStringTag]==="MultipartBody";var Yb0=function(J,Q,Z,Y,X){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?X.call(J,Z):X?X.value=Z:Q.set(J,Z),Z},Xb0=function(J,Q,Z,Y){if(Z==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!Y:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?Y:Z==="a"?Y.call(J):Y?Y.value:Q.get(J)},at,it;vA1();async function $b0(J){let{response:Q}=J;if(J.options.stream){if(hU("response",Q.status,Q.url,Q.headers,Q.body),J.options.__streamClass)return J.options.__streamClass.fromSSEResponse(Q,J.controller);return FL.fromSSEResponse(Q,J.controller)}if(Q.status===204)return null;if(J.options.__binaryResponse)return Q;let Y=Q.headers.get("content-type")?.split(";")[0]?.trim();if(Y?.includes("application/json")||Y?.endsWith("+json")){let V=await Q.json();return hU("response",Q.status,Q.url,Q.headers,V),V}let G=await Q.text();return hU("response",Q.status,Q.url,Q.headers,G),G}class ot extends Promise{constructor(J,Q=$b0){super((Z)=>{Z(null)});this.responsePromise=J,this.parseResponse=Q}_thenUnwrap(J){return new ot(this.responsePromise,async(Q)=>J(await this.parseResponse(Q),Q))}asResponse(){return this.responsePromise.then((J)=>J.response)}async withResponse(){let[J,Q]=await Promise.all([this.parse(),this.asResponse()]);return{data:J,response:Q}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(J,Q){return this.parse().then(J,Q)}catch(J){return this.parse().catch(J)}finally(J){return this.parse().finally(J)}}class gA1{constructor({baseURL:J,baseURLOverridden:Q,maxRetries:Z=2,timeout:Y=60000,httpAgent:X,fetch:G}){at.set(this,void 0),this.baseURL=J,Yb0(this,at,Q,"f"),this.maxRetries=bA1("maxRetries",Z),this.timeout=bA1("timeout",Y),this.httpAgent=X,this.fetch=G??mM1}authHeaders(J){return{}}defaultHeaders(J){return{Accept:"application/json",...["head","get"].includes(J.method)?{}:{"Content-Type":"application/json"},"User-Agent":this.getUserAgent(),...km4(),...this.authHeaders(J)}}validateHeaders(J,Q){}defaultIdempotencyKey(){return`stainless-node-retry-${hm4()}`}get(J,Q){return this.methodRequest("get",J,Q)}post(J,Q){return this.methodRequest("post",J,Q)}patch(J,Q){return this.methodRequest("patch",J,Q)}put(J,Q){return this.methodRequest("put",J,Q)}delete(J,Q){return this.methodRequest("delete",J,Q)}methodRequest(J,Q,Z){return this.request(Promise.resolve(Z).then(async(Y)=>{let X=Y&&tf(Y?.body)?new DataView(await Y.body.arrayBuffer()):Y?.body instanceof DataView?Y.body:Y?.body instanceof ArrayBuffer?new DataView(Y.body):Y&&ArrayBuffer.isView(Y?.body)?new DataView(Y.body.buffer):Y?.body;return{method:J,path:Q,...Y,body:X}}))}getAPIList(J,Q,Z){return this.requestAPIList(Q,{method:"get",path:J,...Z})}calculateContentLength(J){if(typeof J==="string"){if(typeof Buffer<"u")return Buffer.byteLength(J,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(J).length.toString()}else if(ArrayBuffer.isView(J))return J.byteLength.toString();return null}async buildRequest(J,{retryCount:Q=0}={}){let Z={...J},{method:Y,path:X,query:G,defaultBaseURL:V,headers:K={}}=Z,q=ArrayBuffer.isView(Z.body)||Z.__binaryRequest&&typeof Z.body==="string"?Z.body:hA1(Z.body)?Z.body.body:Z.body?JSON.stringify(Z.body,null,2):null,W=this.calculateContentLength(q),H=this.buildURL(X,G,V);if("timeout"in Z)bA1("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let z=Z.httpAgent??this.httpAgent??pM1(H),U=Z.timeout+1000;if(typeof z?.options?.timeout==="number"&&U>(z.options.timeout??0))z.options.timeout=U;if(this.idempotencyHeader&&Y!=="get"){if(!J.idempotencyKey)J.idempotencyKey=this.defaultIdempotencyKey();K[this.idempotencyHeader]=J.idempotencyKey}let D=this.buildHeaders({options:Z,headers:K,contentLength:W,retryCount:Q});return{req:{method:Y,...q&&{body:q},headers:D,...z&&{agent:z},signal:Z.signal??null},url:H,timeout:Z.timeout}}buildHeaders({options:J,headers:Q,contentLength:Z,retryCount:Y}){let X={};if(Z)X["content-length"]=Z;let G=this.defaultHeaders(J);if(Zb0(X,G),Zb0(X,Q),hA1(J.body)&&iM!=="node")delete X["content-type"];if(nt(G,"x-stainless-retry-count")===void 0&&nt(Q,"x-stainless-retry-count")===void 0)X["x-stainless-retry-count"]=String(Y);if(nt(G,"x-stainless-timeout")===void 0&&nt(Q,"x-stainless-timeout")===void 0&&J.timeout)X["x-stainless-timeout"]=String(Math.trunc(J.timeout/1000));return this.validateHeaders(X,Q),X}async prepareOptions(J){}async prepareRequest(J,{url:Q,options:Z}){}parseHeaders(J){return!J?{}:(Symbol.iterator in J)?Object.fromEntries(Array.from(J).map((Q)=>[...Q])):{...J}}makeStatusError(J,Q,Z,Y){return k3.generate(J,Q,Z,Y)}request(J,Q=null){return new ot(this.makeRequest(J,Q))}async makeRequest(J,Q){let Z=await J,Y=Z.maxRetries??this.maxRetries;if(Q==null)Q=Y;await this.prepareOptions(Z);let{req:X,url:G,timeout:V}=await this.buildRequest(Z,{retryCount:Y-Q});if(await this.prepareRequest(X,{url:G,options:Z}),hU("request",G,Z,X.headers),Z.signal?.aborted)throw new aP;let K=new AbortController,q=await this.fetchWithTimeout(G,X,V,K).catch(lt);if(q instanceof Error){if(Z.signal?.aborted)throw new aP;if(Q)return this.retryRequest(Z,Q);if(q.name==="AbortError")throw new sf;throw new zL({cause:q})}let W=Cm4(q.headers);if(!q.ok){if(Q&&this.shouldRetry(q)){let L=`retrying, ${Q} attempts remaining`;return hU(`response (error; ${L})`,q.status,G,W),this.retryRequest(Z,Q,W)}let H=await q.text().catch((L)=>lt(L).message),z=ym4(H),U=z?void 0:H;throw hU(`response (error; ${Q?"(error; no more retries left)":"(error; not retryable)"})`,q.status,G,W,U),this.makeStatusError(q.status,z,U,W)}return{response:q,options:Z,controller:K}}requestAPIList(J,Q){let Z=this.makeRequest(Q,null);return new Gb0(this,Z,J)}buildURL(J,Q,Z){let Y=!Xb0(this,at,"f")&&Z||this.baseURL,X=vm4(J)?new URL(J):new URL(Y+(Y.endsWith("/")&&J.startsWith("/")?J.slice(1):J)),G=this.defaultQuery();if(!Vb0(G))Q={...G,...Q};if(typeof Q==="object"&&Q&&!Array.isArray(Q))X.search=this.stringifyQuery(Q);return X.toString()}stringifyQuery(J){return Object.entries(J).filter(([Q,Z])=>typeof Z<"u").map(([Q,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(Q)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(Q)}=`;throw new xQ(`Cannot stringify type ${typeof Z}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(J,Q,Z,Y){let{signal:X,...G}=Q||{};if(X)X.addEventListener("abort",()=>Y.abort());let V=setTimeout(()=>Y.abort(),Z),K={signal:Y.signal,...G};if(K.method)K.method=K.method.toUpperCase();return this.fetch.call(void 0,J,K).finally(()=>{clearTimeout(V)})}shouldRetry(J){let Q=J.headers.get("x-should-retry");if(Q==="true")return!0;if(Q==="false")return!1;if(J.status===408)return!0;if(J.status===409)return!0;if(J.status===429)return!0;if(J.status>=500)return!0;return!1}async retryRequest(J,Q,Z){let Y,X=Z?.["retry-after-ms"];if(X){let V=parseFloat(X);if(!Number.isNaN(V))Y=V}let G=Z?.["retry-after"];if(G&&!Y){let V=parseFloat(G);if(!Number.isNaN(V))Y=V*1000;else Y=Date.parse(G)-Date.now()}if(!(Y&&0<=Y&&Y<60000)){let V=J.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(Q,V)}return await fm4(Y),this.makeRequest(J,Q-1)}calculateDefaultRetryTimeoutMillis(J,Q){let X=Q-J,G=Math.min(0.5*Math.pow(2,X),8),V=1-Math.random()*0.25;return G*V*1000}getUserAgent(){return`${this.constructor.name}/JS ${lM}`}}at=new WeakMap;class Rm4{constructor(J,Q,Z,Y){it.set(this,void 0),Yb0(this,it,J,"f"),this.options=Y,this.response=Q,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let J=this.nextPageInfo();if(!J)throw new xQ("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let Q={...this.options};if("params"in J&&typeof Q.query==="object")Q.query={...Q.query,...J.params};else if("url"in J){let Z=[...Object.entries(Q.query||{}),...J.url.searchParams.entries()];for(let[Y,X]of Z)J.url.searchParams.set(Y,X);Q.query=void 0,Q.path=J.url.toString()}return await Xb0(this,it,"f").requestAPIList(this.constructor,Q)}async*iterPages(){let J=this;yield J;while(J.hasNextPage())J=await J.getNextPage(),yield J}async*[(it=new WeakMap,Symbol.asyncIterator)](){for await(let J of this.iterPages())for(let Q of J.getPaginatedItems())yield Q}}class Gb0 extends ot{constructor(J,Q,Z){super(Q,async(Y)=>new Z(J,Y.response,await $b0(Y),Y.options))}async*[Symbol.asyncIterator](){let J=await this;for await(let Q of J)yield Q}}var Cm4=(J)=>{return new Proxy(Object.fromEntries(J.entries()),{get(Q,Z){let Y=Z.toString();return Q[Y.toLowerCase()]||Q[Y]}})},jm4={method:!0,path:!0,query:!0,body:!0,headers:!0,defaultBaseURL:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},mA1=(J)=>{return typeof J==="object"&&J!==null&&!Vb0(J)&&Object.keys(J).every((Q)=>Kb0(jm4,Q))},Sm4=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lM,"X-Stainless-OS":Jb0(Deno.build.os),"X-Stainless-Arch":eh0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lM,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lM,"X-Stainless-OS":Jb0(process.platform),"X-Stainless-Arch":eh0(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let J=_m4();if(J)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lM,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${J.browser}`,"X-Stainless-Runtime-Version":J.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lM,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _m4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Z}of J){let Y=Z.exec(navigator.userAgent);if(Y){let X=Y[1]||0,G=Y[2]||0,V=Y[3]||0;return{browser:Q,version:`${X}.${G}.${V}`}}}return null}var eh0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},Jb0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},Qb0,km4=()=>{return Qb0??(Qb0=Sm4())},ym4=(J)=>{try{return JSON.parse(J)}catch(Q){return}},xm4=/^[a-z][a-z0-9+.-]*:/i,vm4=(J)=>{return xm4.test(J)},fm4=(J)=>new Promise((Q)=>setTimeout(Q,J)),bA1=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new xQ(`${J} must be an integer`);if(Q<0)throw new xQ(`${J} must be a positive integer`);return Q},lt=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null)try{return Error(JSON.stringify(J))}catch{}return Error(J)};var uA1=(J)=>{if(typeof process<"u")return process.env?.[J]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(J)?.trim();return};function Vb0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function Kb0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}function Zb0(J,Q){for(let Z in Q){if(!Kb0(Q,Z))continue;let Y=Z.toLowerCase();if(!Y)continue;let X=Q[Z];if(X===null)delete J[Y];else if(X!==void 0)J[Y]=X}}function hU(J,...Q){if(typeof process<"u"&&process?.env?.DEBUG==="true")console.log(`Cerebras:DEBUG:${J}`,...Q)}var hm4=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(J)=>{let Q=Math.random()*16|0;return(J==="x"?Q:Q&3|8).toString(16)})};var bm4=(J)=>{return typeof J?.get==="function"};var nt=(J,Q)=>{let Z=Q.toLowerCase();if(bm4(J)){let Y=Q[0]?.toUpperCase()+Q.substring(1).replace(/([^\w])(\w)/g,(X,G,V)=>G+V.toUpperCase());for(let X of[Q,Z,Q.toUpperCase(),Y]){let G=J.get(X);if(G)return G}}for(let[Y,X]of Object.entries(J))if(Y.toLowerCase()===Z){if(Array.isArray(X)){if(X.length<=1)return X[0];return console.warn(`Received ${X.length} entries for the ${Q} header, using the first entry.`),X[0]}return X}return};class IH{constructor(J){this._client=J}}class ef extends IH{create(J,Q){let{"CF-RAY":Z,"X-Amz-Cf-Id":Y,"X-delay-time":X,...G}=J;return this._client.post("/v1/chat/completions",{body:G,...Q,stream:G.stream??!1,headers:{...Z!=null?{"CF-RAY":Z}:void 0,...Y!=null?{"X-Amz-Cf-Id":Y}:void 0,...X?.toString()!=null?{"X-delay-time":X?.toString()}:void 0,...Q?.headers}})}}class BL extends IH{constructor(){super(...arguments);this.completions=new ef(this._client)}}BL.Completions=ef;class oP extends IH{create(J,Q){let{"CF-RAY":Z,"X-Amz-Cf-Id":Y,"X-delay-time":X,...G}=J;return this._client.post("/v1/completions",{body:G,...Q,stream:G.stream??!1,headers:{...Z!=null?{"CF-RAY":Z}:void 0,...Y!=null?{"X-Amz-Cf-Id":Y}:void 0,...X?.toString()!=null?{"X-delay-time":X?.toString()}:void 0,...Q?.headers}})}}class rP extends IH{retrieve(J,Q={},Z){if(mA1(Q))return this.retrieve(J,{},Q);let{"CF-RAY":Y,"X-Amz-Cf-Id":X}=Q;return this._client.get(`/v1/models/${J}`,{...Z,headers:{...Y!=null?{"CF-RAY":Y}:void 0,...X!=null?{"X-Amz-Cf-Id":X}:void 0,...Z?.headers}})}list(J={},Q){if(mA1(J))return this.list({},J);let{"CF-RAY":Z,"X-Amz-Cf-Id":Y}=J;return this._client.get("/v1/models",{...Q,headers:{...Z!=null?{"CF-RAY":Z}:void 0,...Y!=null?{"X-Amz-Cf-Id":Y}:void 0,...Q?.headers}})}}var qb0,Wb0,pm4;class E7 extends gA1{constructor({baseURL:J=uA1("CEREBRAS_BASE_URL"),apiKey:Q=uA1("CEREBRAS_API_KEY"),warmTCPConnection:Z=!0,...Y}={}){if(Q===void 0)throw new xQ("The CEREBRAS_API_KEY environment variable is missing or empty; either provide it, or instantiate the Cerebras client with an apiKey option, like new Cerebras({ apiKey: 'My API Key' }).");let X={apiKey:Q,...Y,baseURL:J||"https://api.cerebras.ai"};super({baseURL:X.baseURL,baseURLOverridden:J?J!=="https://api.cerebras.ai":!1,timeout:X.timeout??60000,httpAgent:X.httpAgent,maxRetries:X.maxRetries,fetch:X.fetch});if(qb0.add(this),this.chat=new BL(this),this.completions=new oP(this),this.models=new rP(this),this._options=X,this.apiKey=Q,Z)(async()=>{try{await this.get("/v1/tcp_warming",{timeout:1000,maxRetries:0})}catch(G){hU(`TCP Warming had exception: ${G}`)}})()}defaultQuery(){return this._options.defaultQuery}defaultHeaders(J){return{...super.defaultHeaders(J),...this._options.defaultHeaders}}authHeaders(J){return{Authorization:`Bearer ${this.apiKey}`}}}Wb0=E7,qb0=new WeakSet,pm4=function(){return this.baseURL!=="https://api.cerebras.ai"};E7.Cerebras=Wb0;E7.DEFAULT_TIMEOUT=60000;E7.CerebrasError=xQ;E7.APIError=k3;E7.APIConnectionError=zL;E7.APIConnectionTimeoutError=sf;E7.APIUserAbortError=aP;E7.NotFoundError=mt;E7.ConflictError=ut;E7.RateLimitError=dt;E7.BadRequestError=ht;E7.AuthenticationError=bt;E7.InternalServerError=ct;E7.PermissionDeniedError=gt;E7.UnprocessableEntityError=pt;E7.toFile=th0;E7.fileFromPath=_s;E7.Chat=BL;E7.Completions=oP;E7.Models=rP;var Hb0=E7;o0();NZ();EG();function zb0(J){let Q=[];if("error"in J)throw Error(`Cerebras error: ${J.error}`);else if("object"in J&&J.object==="chat.completion"){let Y=J.choices[0];if(Y?.message?.tool_calls){for(let X of Y.message.tool_calls)if(X.id)Q.push({id:X.id,name:X.function.name,input:X.function.arguments?JSON.parse(X.function.arguments):{}})}}else if("object"in J&&J.object==="chat.completion.chunk"){let Y=J.choices?.[0];if(Y?.delta?.tool_calls){for(let X of Y.delta.tool_calls)if(X.id)Q.push({id:X.id,name:X.function.name??"unknown",input:X.function.arguments?JSON.parse(X.function.arguments):{}})}}return Q}function Fb0(J){if("error"in J)throw Error(`Cerebras error: ${J.error}`);let Q;if("object"in J&&J.object==="chat.completion"){let Y=J.choices[0];if(Y?.message)Q={role:"assistant",content:Y.message.content||"",tool_calls:Y.message.tool_calls}}else if("object"in J&&J.object==="chat.completion.chunk"){let Y=J.choices?.[0];if(Y?.delta)Q={role:"assistant",content:Y.delta.content||"",tool_calls:Y.delta.tool_calls?.filter((X)=>X.id)}}return Q}function dm4(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}function cm4(J,Q,Z){return{...G3(),[hJ]:"amp.chat",...gJ(J),...Q!=null?{[BZ]:String(Q)}:{},...Z!=null?{[bJ]:Z}:{}}}async function Ub0(J,Q,Z,Y,X,G,V,K,q,W){let H=await im4(V,K),z=[{role:"system",content:Z},...J],U={model:X,messages:z,tools:dm4(Q),temperature:G,stream:!1};return{message:await H.chat.completions.create(U,{signal:K,headers:cm4(Y,q,W)})}}function lm4(J){return J.pipe(T4((Q)=>P3((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),N4((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),Q6(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new Hb0({apiKey:Z,baseURL:new URL("/api/provider/cerebras",Q).toString()})}),E8({shouldCountRefs:!0}))}function im4(J,Q){return V6(lm4(J.configService.config),Q)}vL();function jp4(J){let Q=UZ(`cerebras/${J}`);return Q.contextWindow-Q.maxOutputTokens}class hw1{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X,clientRequestId:G}){let{systemPrompt:V,tools:K}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"cerebras",agentMode:X??"smart"},Y),q=V.map((U)=>U.text).join(`
2920
- `),W=Q.id,H=Sp4(Q),z=K.map((U)=>G7(J,U));v.debug("Starting Cerebras inference",{model:J,threadID:W,messageCount:H.length,toolCount:z.length});try{let U=await Ub0(H,z,q,Q,J,0.7,{configService:Z.configService},Y,void 0,G).catch((x)=>{throw yp4(x)}),D=U.message,M=zb0(D),A=Fb0(D)?.content||null;v.debug("Cerebras response parsed",{threadID:W,assistantContent:A?A.slice(0,200)+"...":null,toolUsesCount:M.length,toolUses:M.map((x)=>({name:x.name,id:x.id}))});let E=[];if(A)E.push({type:"text",text:A});if(M.length>0){v.debug("Processing tool uses",{threadID:W,toolUseCount:M.length});for(let x of M)v.debug("Adding tool_use block to message content",{threadID:W,toolUseId:x.id,toolName:x.name,parsedArgs:typeof x.input==="object"&&x.input?Object.keys(x.input):[]}),E.push(gE(x.name,x.input,x.id))}else v.debug("No tool uses to process",{threadID:W});let I=U.message.usage||{},P=I?.prompt_tokens??0,R=I?.completion_tokens??0,k={inputTokens:P,outputTokens:R,cacheCreationInputTokens:0,cacheReadInputTokens:0,maxInputTokens:jp4(J),totalInputTokens:P,credits:0},y={model:J,"~debugParamsUsed":{systemPrompt:q.slice(0,500),messageCount:H.length,toolCount:z.length}};return yield{role:"assistant",content:E,state:{type:"complete",stopReason:M.length>0?"tool_use":null},usage:k},{model:J,"~debugUsage":k,"~debugParamsUsed":y}}catch(U){throw v.error("Cerebras inference error",{error:U,model:J,threadID:W}),U}}}function Sp4(J){let Q=TT(J);return _p4(Q)}function _p4(J){return J.map((Q)=>{if(Q.role==="user")return{role:"user",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")};else if(Q.role==="assistant")return{role:"assistant",content:typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.map((Z)=>Z.type==="text"?Z.text:"").join(""):null,tool_calls:Q.tool_calls};else if(Q.role==="tool")return{role:"tool",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.text).join(""),tool_call_id:Q.tool_call_id};throw Error(`Unsupported message role: ${Q.role}`)})}function kp4(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function yp4(J){if(kp4(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new SQ}return J}o0();wQ();ET();oW();B0();NZ();EG();gK();R8();V7();O7();AY();vL();$b();function rg0(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}async function sg0(J,Q,Z,Y,X,G,V,K,q,W,H){let z=await tg0(G,V),U=[{role:"system",content:Z},...J],D={model:X,messages:U,tools:rg0(Q),temperature:0.1,stream:!1,...H?.reasoning_effort&&{reasoning_effort:H.reasoning_effort},...W&&{tool_choice:W}};try{return{message:await z.chat.completions.create(D,{signal:V,headers:eg0(Y,K,q)})}}catch(M){if(l3(M))throw new DOMException("Aborted","AbortError");throw v.error("Fireworks API call failed",{model:X,error:M instanceof Error?M.message:String(M),status:M?.status,code:M?.code,type:M?.type}),Jm0(M)}}function hp4(J){return J.pipe(T4((Q)=>P3((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),N4((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),Q6(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new p4({apiKey:Z,baseURL:new URL("/api/provider/fireworks/v1",Q).toString()})}),E8({shouldCountRefs:!0}))}function tg0(J,Q){return V6(hp4(J.configService.config),Q)}function eg0(J,Q,Z){return{...G3(),[hJ]:"amp.chat",...Q!=null?{[BZ]:String(Q)}:{},...Z!=null?{[bJ]:Z}:{},...gJ(J)}}function Jm0(J){let Q=J?.message;if(typeof Q==="string"){if(Q.includes("maximum context length")||Q.includes("prompt is too long")||Q.includes("too many tokens"))return new SQ("Token limit exceeded.")}return J}function bp4(J){return{...J,content:J.content.filter((Q)=>Q.type!=="thinking"||Q.thinking.trim()!=="")}}class gw1{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X,clientRequestId:G}){let{systemPrompt:V,tools:K}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"fireworks",agentMode:X??"smart"},Y),q=K.map((A)=>G7(J,A)),W=y8(Xb(Q)),H=await tg0({configService:Z.configService},Y),z=[{role:"system",content:V.map((A)=>A.text).join(`
2920
+ `),W=Q.id,H=Sp4(Q),z=K.map((U)=>G7(J,U));v.debug("Starting Cerebras inference",{model:J,threadID:W,messageCount:H.length,toolCount:z.length});try{let U=await Ub0(H,z,q,Q,J,0.7,{configService:Z.configService},Y,void 0,G).catch((x)=>{throw yp4(x)}),D=U.message,M=zb0(D),A=Fb0(D)?.content||null;v.debug("Cerebras response parsed",{threadID:W,assistantContent:A?A.slice(0,200)+"...":null,toolUsesCount:M.length,toolUses:M.map((x)=>({name:x.name,id:x.id}))});let E=[];if(A)E.push({type:"text",text:A});if(M.length>0){v.debug("Processing tool uses",{threadID:W,toolUseCount:M.length});for(let x of M)v.debug("Adding tool_use block to message content",{threadID:W,toolUseId:x.id,toolName:x.name,parsedArgs:typeof x.input==="object"&&x.input?Object.keys(x.input):[]}),E.push(gE(x.name,x.input,x.id))}else v.debug("No tool uses to process",{threadID:W});let I=U.message.usage||{},P=I?.prompt_tokens??0,R=I?.completion_tokens??0,k={inputTokens:P,outputTokens:R,cacheCreationInputTokens:0,cacheReadInputTokens:0,maxInputTokens:jp4(J),totalInputTokens:P,credits:0},y={model:J,"~debugParamsUsed":{systemPrompt:q.slice(0,500),messageCount:H.length,toolCount:z.length}};return yield{role:"assistant",content:E,state:{type:"complete",stopReason:M.length>0?"tool_use":null},usage:k},{model:J,"~debugUsage":k,"~debugParamsUsed":y}}catch(U){throw v.error("Cerebras inference error",{error:U,model:J,threadID:W}),U}}}function Sp4(J){let Q=TT(J);return _p4(Q)}function _p4(J){return J.map((Q)=>{if(Q.role==="user")return{role:"user",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")};else if(Q.role==="assistant")return{role:"assistant",content:typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.map((Z)=>Z.type==="text"?Z.text:"").join(""):null,tool_calls:Q.tool_calls};else if(Q.role==="tool")return{role:"tool",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.text).join(""),tool_call_id:Q.tool_call_id};throw Error(`Unsupported message role: ${Q.role}`)})}function kp4(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function yp4(J){if(kp4(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new SQ}return J}o0();wQ();ET();oW();B0();NZ();EG();gK();R8();V7();O7();AY();vL();$b();function rg0(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}async function sg0(J,Q,Z,Y,X,G,V,K,q,W,H){let z=await tg0(G,V),U=[{role:"system",content:Z},...J],D={model:X,messages:U,tools:rg0(Q),temperature:0.1,stream:!1,...H?.reasoning_effort&&{reasoning_effort:H.reasoning_effort},...W&&{tool_choice:W}};try{return{message:await z.chat.completions.create(D,{signal:V,headers:eg0(Y,K,q)}),"~debugParamsUsed":D}}catch(M){if(l3(M))throw new DOMException("Aborted","AbortError");throw v.error("Fireworks API call failed",{model:X,error:M instanceof Error?M.message:String(M),status:M?.status,code:M?.code,type:M?.type}),Jm0(M)}}function hp4(J){return J.pipe(T4((Q)=>P3((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),N4((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),Q6(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new p4({apiKey:Z,baseURL:new URL("/api/provider/fireworks/v1",Q).toString()})}),E8({shouldCountRefs:!0}))}function tg0(J,Q){return V6(hp4(J.configService.config),Q)}function eg0(J,Q,Z){return{...G3(),[hJ]:"amp.chat",...Q!=null?{[BZ]:String(Q)}:{},...Z!=null?{[bJ]:Z}:{},...gJ(J)}}function Jm0(J){let Q=J?.message;if(typeof Q==="string"){if(Q.includes("maximum context length")||Q.includes("prompt is too long")||Q.includes("too many tokens"))return new SQ("Token limit exceeded.")}return J}function bp4(J,Q,Z){return{...J,content:J.content.filter((X)=>X.type!=="thinking"||X.thinking.trim()!==""),...Z?{"~debugParamsUsed":Q}:{}}}class gw1{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X,clientRequestId:G}){let{systemPrompt:V,tools:K}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"fireworks",agentMode:X??"smart"},Y),q=K.map((A)=>G7(J,A)),W=y8(Xb(Q)),H=await tg0({configService:Z.configService},Y),z=[{role:"system",content:V.map((A)=>A.text).join(`
2921
2921
 
2922
- `)},...W],D=UZ(`fireworks/${J}`).capabilities?.reasoning??!1,M={model:J,messages:z,tools:rg0(q),temperature:0.1,stream:!0,...D&&{reasoning_effort:"medium"}},L=AG(`fireworks/${J}`,Boolean(X&&P9(X)));try{let A=await H.chat.completions.create(M,{signal:Y,headers:eg0(Q,vX(Q)?.messageId,G)}),E;for await(let I of A)if(E=oU(E,I),E){let P=rU(E,L);yield bp4(P)}}catch(A){if(l3(A))throw new DOMException("Aborted","AbortError");throw v.error("Fireworks streaming API call failed",{model:J,error:A instanceof Error?A.message:String(A),status:A?.status,code:A?.code,type:A?.type}),Jm0(A)}}}QR();o0();wQ();ET();NZ();EG();gK();R8();V7();O7();vL();function o18(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}function r18(J){return J.pipe(T4((Q)=>P3((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),N4((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),Q6(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new p4({apiKey:Z,baseURL:new URL("/api/provider/groq",Q).toString()})}),E8({shouldCountRefs:!0}))}function s18(J,Q){return V6(r18(J.configService.config),Q)}function t18(J,Q,Z){return{...G3(),[hJ]:"amp.chat",...gJ(J),...Q!=null?{[BZ]:String(Q)}:{},...Z!=null?{[bJ]:Z}:{}}}function e18(J){return`toolu_${J.replace(/[^a-zA-Z0-9_-]/g,"_")}`}class xb{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X,clientRequestId:G}){let{systemPrompt:V,tools:K}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"groq",agentMode:X??"smart"},Y),q=K.map((A)=>G7(J,A)),W=y8(TT(Q)),H=J==="kimi-k2-instruct-0905"?"moonshotai/kimi-k2-instruct-0905":J==="gpt-oss-120b"?"openai/gpt-oss-120b":J,z=await s18({configService:Z.configService},Y),U=[{role:"system",content:V},...W],D={model:H,messages:U,tools:o18(q),temperature:0.7,stream:!0},M=await z.chat.completions.create(D,{signal:Y,headers:t18(Q,vX(Q)?.messageId,G)}),L;for await(let A of M)if(L=oU(L,A),L)yield J08(L,Boolean(X&&P9(X)))}}function J08(J,Q){let Y=rU(J,((X)=>{let V=`${J.model.includes("/")?J.model.split("/")[0]:"anthropic"}/${X.replace(/^[^/]+\//,"")}`;return AG(V,Q)})(J.model));return{...Y,content:Y.content.map((X)=>{if(X.type==="tool_use")return{...X,id:e18(X.id)};return X})}}mD();wQ();oW();LU();gK();R8();Ze();pM();V7();me();vL();var Q08=32000;class XP1{async*stream(J){let Q=await IT({configService:J.buildSystemPromptDeps.configService},J.signal),Z=await Z08(J),Y;try{Y=await Q.responses.create(Z,{signal:J.signal,headers:PT(J.thread,void 0,J.clientRequestId)})}catch(G){if(l3(G))throw new DOMException("Aborted","AbortError");throw G}let X;for await(let G of Y)if(X=X08(X,G),X)yield Y08(X)}}async function Z08({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X}){let{systemPrompt:G,tools:V}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"openai",agentMode:X??"smart"},Y),K=V.map((D)=>G7(J,D)),q=$P1(Q),W=xL(J),H="medium",z=[{role:"system",content:G.map((D)=>D.text).join(`
2922
+ `)},...W],D=UZ(`fireworks/${J}`).capabilities?.reasoning??!1,M={model:J,messages:z,tools:rg0(q),temperature:0.1,stream:!0,...D&&{reasoning_effort:"medium"}},L=AG(`fireworks/${J}`,Boolean(X&&P9(X)));try{let A=await H.chat.completions.create(M,{signal:Y,headers:eg0(Q,vX(Q)?.messageId,G)}),E;for await(let I of A)if(E=oU(E,I),E){let P=rU(E,L),R=E.finish_reason!==null;yield bp4(P,z,R)}}catch(A){if(l3(A))throw new DOMException("Aborted","AbortError");throw v.error("Fireworks streaming API call failed",{model:J,error:A instanceof Error?A.message:String(A),status:A?.status,code:A?.code,type:A?.type}),Jm0(A)}}}QR();o0();wQ();ET();NZ();EG();gK();R8();V7();O7();vL();function o18(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}function r18(J){return J.pipe(T4((Q)=>P3((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),N4((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),Q6(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new p4({apiKey:Z,baseURL:new URL("/api/provider/groq",Q).toString()})}),E8({shouldCountRefs:!0}))}function s18(J,Q){return V6(r18(J.configService.config),Q)}function t18(J,Q,Z){return{...G3(),[hJ]:"amp.chat",...gJ(J),...Q!=null?{[BZ]:String(Q)}:{},...Z!=null?{[bJ]:Z}:{}}}function e18(J){return`toolu_${J.replace(/[^a-zA-Z0-9_-]/g,"_")}`}class xb{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X,clientRequestId:G}){let{systemPrompt:V,tools:K}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"groq",agentMode:X??"smart"},Y),q=K.map((A)=>G7(J,A)),W=y8(TT(Q)),H=J==="kimi-k2-instruct-0905"?"moonshotai/kimi-k2-instruct-0905":J==="gpt-oss-120b"?"openai/gpt-oss-120b":J,z=await s18({configService:Z.configService},Y),U=[{role:"system",content:V},...W],D={model:H,messages:U,tools:o18(q),temperature:0.7,stream:!0},M=await z.chat.completions.create(D,{signal:Y,headers:t18(Q,vX(Q)?.messageId,G)}),L;for await(let A of M)if(L=oU(L,A),L)yield J08(L,Boolean(X&&P9(X)))}}function J08(J,Q){let Y=rU(J,((X)=>{let V=`${J.model.includes("/")?J.model.split("/")[0]:"anthropic"}/${X.replace(/^[^/]+\//,"")}`;return AG(V,Q)})(J.model));return{...Y,content:Y.content.map((X)=>{if(X.type==="tool_use")return{...X,id:e18(X.id)};return X})}}mD();wQ();oW();LU();gK();R8();Ze();pM();V7();me();vL();var Q08=32000;class XP1{async*stream(J){let Q=await IT({configService:J.buildSystemPromptDeps.configService},J.signal),Z=await Z08(J),Y;try{Y=await Q.responses.create(Z,{signal:J.signal,headers:PT(J.thread,void 0,J.clientRequestId)})}catch(G){if(l3(G))throw new DOMException("Aborted","AbortError");throw G}let X;for await(let G of Y)if(X=X08(X,G),X)yield Y08(X)}}async function Z08({model:J,thread:Q,buildSystemPromptDeps:Z,signal:Y,agentMode:X}){let{systemPrompt:G,tools:V}=await M2(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"openai",agentMode:X??"smart"},Y),K=V.map((D)=>G7(J,D)),q=$P1(Q),W=xL(J),H="medium",z=[{role:"system",content:G.map((D)=>D.text).join(`
2923
2923
 
2924
2924
  `)},...y8(q)],U=Math.min(Q08,W.maxOutputTokens);return{model:W.name,input:z,store:!1,include:["reasoning.encrypted_content"],tools:K.map(GP1),stream:!0,max_output_tokens:U,prompt_cache_key:Q.id,...W.supportsReasoning?{reasoning:{effort:"medium",summary:"detailed"}}:{temperature:0.1}}}function $P1(J){let Q=[],{summaryBlock:Z,index:Y}=xX(J)??{summaryBlock:void 0,index:0};if(Z&&Z.summary.type==="message")Q.push({type:"message",role:"assistant",content:Z.summary.summary.trimEnd()});for(let X=Y+(Z?1:0);X<J.messages.length;X++){let G=J.messages[X];if(!G)continue;switch(G.role){case"user":{let V=[],K=[];if(G.fileMentions&&G.fileMentions.files.length>0)V.push({type:"input_text",text:eX(G.fileMentions)});if(G.userState)V.push({type:"input_text",text:mK(G.userState)});for(let q of G.content)switch(q.type){case"tool_result":K.push({type:"function_call_output",call_id:q.toolUseID,output:fw1(q.run)});break;case"image":if(q.source.type==="url")V.push({type:"input_image",detail:"auto",image_url:q.source.url});else if(q.source.type==="base64")V.push({type:"input_image",detail:"auto",image_url:`data:${q.source.mediaType};base64,${q.source.data}`});break;case"text":if(q.text.trim())V.push({type:"input_text",text:q.text});break}if(V.length>0)Q.push({type:"message",role:"user",content:V});Q.push(...K);break}case"assistant":{for(let V of G.content)if(V.type==="text")Q.push({type:"message",role:"assistant",content:V.text});else if(V.type==="thinking"){let K=V.thinking.match(/<ENCRYPTED>(.*?)<\/ENCRYPTED><ID>(.*?)<\/ID>/),q=K?.[1]||"",W=K?.[2]||"",H=V.thinking.replace(/<ENCRYPTED>(.*?)<\/ENCRYPTED><ID>(.*?)<\/ID>/g,"");if(W.length>0&&q.length>0)Q.push({type:"reasoning",summary:[{text:H,type:"summary_text"}],encrypted_content:q,id:W})}else if(V.type==="tool_use")Q.push({type:"function_call",name:V.name,call_id:V.id,arguments:JSON.stringify(V.input)});break}}}return GY(Q)}function GP1(J){let Q={...J.inputSchema,type:J.inputSchema?.type??"object",properties:J.inputSchema?.properties??{},required:J.inputSchema?.required??[],additionalProperties:J.inputSchema?.additionalProperties??!1};if(Q.additionalProperties===!0){let Y={...Q,additionalProperties:!1};if(!Y.required)Y.required=[];return{type:"function",name:J.name,description:J.description||"",parameters:Y,strict:!0}}let Z={...Q,additionalProperties:!0};return{type:"function",name:J.name,description:J.description||"",parameters:Z,strict:!1}}function Y08(J){function Q(G){if(G.incomplete_details?.reason==="max_output_tokens")return"max_tokens";if(G.incomplete_details?.reason==="content_filter")return"refusal";if(G.output.some((V)=>V.type==="function_call"))return"tool_use";return"end_turn"}function Z(G){if(!G)return;let V=G.input_tokens_details.cached_tokens,K=G.input_tokens-V,q=xL(J.model);return{maxInputTokens:q.contextWindow-q.maxOutputTokens,inputTokens:0,outputTokens:G.output_tokens,cacheCreationInputTokens:K,cacheReadInputTokens:V,totalInputTokens:G.input_tokens}}function Y(G){let V=[];for(let K of G)switch(K.type){case"message":for(let q of K.content)if(q.type==="refusal")V.push({type:"text",text:q.refusal});else V.push({type:"text",text:q.text});break;case"function_call":try{let q=JSON.parse(K.arguments);V.push({type:"tool_use",complete:!0,id:K.call_id,name:K.name,input:q})}catch{V.push({type:"tool_use",complete:!1,id:K.call_id,name:K.name,inputPartialJSON:{json:K.arguments},input:_X(K.arguments||"{}"),inputIncomplete:Qe(K.arguments||"{}")})}break;case"reasoning":V.push({type:"thinking",thinking:K.summary.map((q)=>q.text).join(`
2925
2925
 
@@ -3862,8 +3862,8 @@ Use load_tool to get the full specification for any of these tools.`}}).pipe(M8(
3862
3862
  `+_4.grey("Debug details:")+`
3863
3863
  `),J.stack)OB.write(J.stack+`
3864
3864
  `);else OB.write(String(J)+`
3865
- `);return jR(),J instanceof I8?J.exitCode:1}function e46(J,Q){let Z=t46(J,Q);process.exit(Z)}async function _g(J,Q){let Z=t46(J,Q);await OA(),process.exit(Z)}B0();OG();function J86(J,Q){let Z=J instanceof Date?J.getTime():J;return I$8(Date.now()-Z,Q)}function I$8(J,{approximate:Q,verbose:Z}={}){if(Q&&J<60000)return Z?"less than 1 minute":"<1m";let Y=Math.floor(J/1000),X=Math.floor(Y/60),G=Math.floor(X/60),V=Math.floor(G/24),K=Math.floor(V/30),W=[{value:Math.floor(K/12),short:"y",long:"year"},{value:K,short:"mo",long:"month"},{value:V,short:"d",long:"day"},{value:G,short:"h",long:"hour"},{value:X,short:"m",long:"minute"},{value:Y,short:"s",long:"second"}];for(let H of W)if(H.value>0){if(Z)return`${H.value} ${m9(H.value,H.long)}`;return`${H.value}${H.short}`}return Z?"0 seconds":"0s"}var Q86="Out of credits";function SR(J){return J.message.includes(Q86)}function _R(J){let Q=["prompt is too long","exceed context limit"],Z=J.error?.type==="invalid_request_error"&&Q.some((X)=>J.error?.message?.toLowerCase().includes(X)),Y=Q.some((X)=>J.message?.includes(X));return Z||Y}function Z86(J){return J.message?.includes("Free tier context limit")??!1}function Y86(J){return J.message?.includes("You've reached the usage limit for 'free' mode")??!1}function X86(J){let Y=(J.message?.includes("You've exceeded your usage quota of")??!1)||(J.message?.includes("You've exceeded your usage limit of")??!1),X=(J.error?.message?.includes("You've exceeded your usage quota of")??!1)||(J.error?.message?.includes("You've exceeded your usage limit of")??!1);return Y||X}function kR(J){let Q=["unauthorized","401"],Z=Q.some((X)=>J.message?.toLowerCase().includes(X.toLowerCase())),Y=Boolean(J.error?.message&&Q.some((X)=>J.error?.message?.toLowerCase().includes(X.toLowerCase())));return Z||Y}function yR(J){let Q=["overloaded","overload"],Z=Q.some((G)=>J.message?.toLowerCase().includes(G.toLowerCase())),Y=Boolean(J.error?.message&&Q.some((G)=>J.error?.message?.toLowerCase().includes(G.toLowerCase()))),X=J.error?.type==="overloaded_error";return Z||Y||X}function k61(J){if(J.error?.message)return J.error.message;let Q=J.message||"";if(Q.includes('{"type":"error"')||Q.includes('{"error":'))try{let Z=JSON.parse(Q.replace(/^\d+\s+/,""));if(Z.error?.message)return Z.error.message}catch{}return Q}R8();j01();z4();var y61=(J)=>{let Q=!1;return{install:()=>{if(!Q)process.on("SIGINT",J),process.on("SIGTERM",J),Q=!0},remove:()=>{if(Q)process.off("SIGINT",J),process.off("SIGTERM",J),Q=!1},get installed(){return Q}}};import{once as S$8}from"node:events";import{createInterface as _$8}from"node:readline";B0();R8();V7();o0();function x61(J,Q){if(kR(J))return{title:"Unauthorized.",description:"Check your API key.",options:["retry","dismiss"]};if(Z86(J))return{title:"Thread context limit reached",description:"This thread has reached the context limit for Amp Free. Edit the thread, or start a new thread, to continue. If you need a larger context window, consider using smart mode.",options:["new-thread","new-smart-thread","dismiss"]};if(Y86(J))return{title:"Free mode usage limit reached",description:k61(J),options:["new-smart-thread","dismiss"]};if(_R(J))return{title:"Context window limit reached.",description:"Start a new thread or use /handoff to continue with relevant context in a fresh thread. If utilizing context >200k tokens, you may be seeing this error because we have failed over to a provider without support for extended context.",options:["new-thread","handoff","dismiss"]};if(yR(J))return{title:"Model provider overloaded.",description:"Try again in a few seconds.",options:["retry","dismiss"]};if(SR(J)){let G=new URL("/pay",Q).toString();return{title:"Insufficient credit balance.",description:"Visit ",link:{text:G,url:G},options:["retry","dismiss"]}}if(X86(J))return{title:"Usage quota exceeded.",description:k61(J),options:["retry","dismiss"]};let Z=200,Y=k61(J);return{title:"Error",description:Y.length>Z?`${Y.substring(0,Z)}...`:Y,options:["retry","dismiss"]}}function $86(J){switch(J){case"retry":return"Retry";case"dismiss":return"Dismiss";case"new-thread":return"New thread";case"new-smart-thread":return"New smart mode thread";case"handoff":return"Handoff";default:throw Error(`Unhandled error action: ${String(J)}`)}}IG();function G86(J){return{type:"text",text:J.text}}function P$8(J){return{type:"tool_use",id:J.id,name:J.name,input:J.input}}function T$8(J){let Q="",Z=!1;switch(J.run.status){case"done":Q=typeof J.run.result==="string"?J.run.result:JSON.stringify(J.run.result),Z=!1;break;case"error":Q=typeof J.run.error==="string"?J.run.error:J.run.error?.message||"Tool execution error",Z=!0;break;case"cancelled":Q=`Tool execution cancelled: ${J.run.reason||"Unknown reason"}`,Z=!0;break;case"rejected-by-user":Q=`Tool execution rejected by user: ${J.run.reason||"User declined permission"}`,Z=!0;break;default:Q=`Tool status: ${J.run.status}`,Z=!1}return{type:"tool_result",tool_use_id:J.toolUseID,content:Q,is_error:Z}}function AC1(J,Q,Z){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(G86(X));else if(X.type==="tool_use")Y.push(P$8(X));return{type:"assistant",message:{type:"message",role:"assistant",content:Y,stop_reason:J.state.type==="complete"?J.state.stopReason:null,usage:J.usage?R$8(J.usage):void 0},parent_tool_use_id:Z??null,session_id:Q}}function V86(J,Q,Z){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(G86(X));else if(X.type==="tool_result")Y.push(T$8(X));return{type:"user",message:{role:"user",content:Y},parent_tool_use_id:Z??null,session_id:Q}}function R$8(J){if(!J)return;return{input_tokens:J.inputTokens||0,cache_creation_input_tokens:J.cacheCreationInputTokens??void 0,cache_read_input_tokens:J.cacheReadInputTokens??void 0,output_tokens:J.outputTokens||0,max_tokens:J.maxInputTokens,service_tier:"standard"}}var C$8=f1.object({type:f1.literal("text"),text:f1.string()}),j$8=f1.object({role:f1.literal("user"),content:f1.array(C$8)}),K86=f1.object({type:f1.literal("user"),message:j$8});var q86=1048576,k$8=1e4;function y$8(J){return J!==void 0}function x$8(J){for(let Q of J)if(Q.type==="tool_result"&&!X3(Q.run))return!1;return!0}async function xR(J){let Q=JSON.stringify(J)+`
3866
- `;try{if(!process.stdout.write(Q))await S$8(process.stdout,"drain")}catch(Z){throw v.error("Failed to emit JSON message",{error:Z,messageType:J.type}),Z}}function kg(J,Q){let Z;if(J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"){if(Z=Error(J.message),"stack"in J&&typeof J.stack==="string")Z.stack=J.stack}else if(J instanceof Error)Z=J;if(Z&&(kR(Z)||_R(Z)||yR(Z)||SR(Z))){let Y=x61(Z,Q),X=Y.title;if(Y.description)X+=` ${Y.description}`;if(Y.link)X+=Y.link.url;return X}if(Z)return Z.message;return String(J)}function W86(J){return J.filter((Q)=>Q.role==="assistant"&&Q.state.type!=="streaming").length}function H86(J){switch(J.role){case"user":return x$8(J.content)?0:2;case"assistant":return J.state.type!=="streaming"?0:2;default:return 1}}async function z86({worker:J,threadID:Q,userInput:Z,stdinInput:Y,dependencies:X,streamJsonInput:G=!1,stdin:V=process.stdin,ampURL:K="https://ampcode.com"}){let q=J.thread.agentMode?J.thread.agentMode:"smart";if(J.thread.messages.length!==0&&q!=="smart")throw new I8(`Stream JSON mode for threads in '${q}' mode.`,1);let H=Q,z=Date.now(),U=0,D=!1,M=null;if(Y&&Y.length>q86)throw Error(`Stdin input too large: ${Y.length} bytes (max ${q86})`);let L,E=y61(()=>{if(!D)L("User cancelled (SIGINT/SIGTERM)")});try{E.install(),J.continueInferenceAfterRejection(!0);let P=(await V6(X.toolService.tools.pipe(FF(1),zF(5000)))).map((p)=>p.spec.name),R=[];try{R=(await V6(X.mcpService.servers.pipe(FF(1),zF(5000)))).map((J1)=>({name:J1.name,status:J1.status.type}))}catch(p){v.warn("Unable to obtain MCP server list for system init message",{err:p})}let k={type:"system",subtype:"init",cwd:process.cwd(),session_id:H,tools:P,mcp_servers:R};await xR(k);let y=W86(J.thread.messages),x=J.thread.messages.length,b=new WeakSet,d=new Map,m=0,o=[],X1=!G,t=!1;return new Promise((p,J1)=>{L=async(l)=>{if(D){v.debug("Complete called multiple times, ignoring",{error:l});return}D=!0,E.remove();try{if(l){let W1={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-z,is_error:!0,num_turns:U,error:l,session_id:H};await xR(W1)}else{let W1=M?g2(M,"assistant"):null,_1=W1?x7(W1.content):"",s={type:"result",subtype:"success",duration_ms:Date.now()-z,is_error:!1,num_turns:U,result:_1,session_id:H};await xR(s)}if(U1.unsubscribe(),r.unsubscribe(),o.forEach((W1)=>W1.unsubscribe()),m=0,await J.asyncDispose(),M){await X.threadService.flushVersion(Q,M.v);let W1=X.threadSyncService.uploadThread(Q),_1=new Promise((s,m1)=>{setTimeout(()=>m1(Error("Thread sync timeout")),k$8)});await Promise.race([W1,_1])}p()}catch(W1){v.error("Error during completion",{error:W1}),J1(W1)}};async function H1(l,W1){try{let _1=d.get(l.id);while(_1.cursor<l.messages.length){let m1=l.messages[_1.cursor],S1=H86(m1);if(S1===2)break;if(S1===1){_1.cursor++;continue}if(!_1.emitted.has(m1)){if(m1.role==="assistant"){if(m1.content.length>0)await xR(AC1(m1,H,W1));U++}_1.emitted.add(m1)}_1.cursor++}let s=g2(l,"assistant");if(s&&s.state.type!=="streaming"&&Fy(s)){if(!_1.done)_1.done=!0,m--}if(X1&&t&&m===0)await L()}catch(_1){v.error("Error in subthread patch handler",{error:_1}),await L(kg(_1,K))}}let U1=J.status.subscribe(async(l)=>{try{if(l.state==="active"&&l.ephemeralError){await L(kg(l.ephemeralError,K));return}if(l.state==="active"&&l.inferenceState==="idle"&&M){let W1=M.messages.flatMap((_1)=>_1.content.map((s)=>{if(s.type==="tool_result"&&s.run.status==="blocked-on-user")return qY(M,s.toolUseID)}).filter(y$8));if(W1.length>0){v.warn("Tools require user consent - exiting stream JSON mode",{blockedTools:W1.map((m1)=>({name:m1.name,id:m1.id}))});let s=`The following tools require user approval, which is not supported in stream JSON mode: ${W1.map((m1)=>m1.name).join(", ")}`;await L(s);return}}}catch(W1){v.error("Error in status subscription",{error:W1}),await L(kg(W1,K))}}),r=X.threadService.observe(Q).subscribe(async(l)=>{try{M=l;while(x<l.messages.length){let s=l.messages[x],m1=H86(s);if(m1===1){x++;continue}if(m1===2)break;if(!b.has(s)){if(s.role==="user")await xR(V86(s,H));else if(s.role==="assistant"){if(s.content.length>0){let S1=AC1(s,H);await xR(S1)}U++}b.add(s)}x++}let W1=W86(l.messages),_1=g2(l,"assistant");if(t=W1>y&&_1!==void 0&&_1.state.type!=="streaming"&&Fy(_1),X1&&t&&m===0)await L()}catch(W1){v.error("Error in thread subscription",{error:W1}),await L(kg(W1,K))}}),n=J.subthreads.subscribe((l)=>{for(let W1 of l){if(d.has(W1.threadID))continue;d.set(W1.threadID,{threadID:W1.threadID,toolUseID:W1.toolUse.id,cursor:0,emitted:new WeakSet,done:!1}),m++;let _1=X.threadService.observePatches(W1.threadID).pipe(rD()).subscribe((s)=>H1(s,W1.toolUse.id));o.push(_1)}});if(o.push(n),G)(async()=>{try{for await(let l of v$8(V))J.handle({type:"user:message",message:{content:l.contentBlocks,agentMode:"smart"}});if(X1=!0,t&&m===0)await L()}catch(l){v.error("Error processing streaming input",{error:l}),await L(kg(l,K))}})();else{let l=[{type:"text",text:Z}];if(Y)l.unshift({type:"text",text:`Input received on stdin:
3865
+ `);return jR(),J instanceof I8?J.exitCode:1}function e46(J,Q){let Z=t46(J,Q);process.exit(Z)}async function _g(J,Q){let Z=t46(J,Q);await OA(),process.exit(Z)}B0();OG();function J86(J,Q){let Z=J instanceof Date?J.getTime():J;return I$8(Date.now()-Z,Q)}function I$8(J,{approximate:Q,verbose:Z}={}){if(Q&&J<60000)return Z?"less than 1 minute":"<1m";let Y=Math.floor(J/1000),X=Math.floor(Y/60),G=Math.floor(X/60),V=Math.floor(G/24),K=Math.floor(V/30),W=[{value:Math.floor(K/12),short:"y",long:"year"},{value:K,short:"mo",long:"month"},{value:V,short:"d",long:"day"},{value:G,short:"h",long:"hour"},{value:X,short:"m",long:"minute"},{value:Y,short:"s",long:"second"}];for(let H of W)if(H.value>0){if(Z)return`${H.value} ${m9(H.value,H.long)}`;return`${H.value}${H.short}`}return Z?"0 seconds":"0s"}var Q86="Out of credits";function SR(J){return J.message.includes(Q86)}function _R(J){let Q=["prompt is too long","exceed context limit"],Z=J.error?.type==="invalid_request_error"&&Q.some((X)=>J.error?.message?.toLowerCase().includes(X)),Y=Q.some((X)=>J.message?.includes(X));return Z||Y}function Z86(J){return J.message?.includes("Free tier context limit")??!1}function Y86(J){return J.message?.includes("You've reached the usage limit for 'free' mode")??!1}function X86(J){let Y=(J.message?.includes("You've exceeded your usage quota of")??!1)||(J.message?.includes("You've exceeded your usage limit of")??!1),X=(J.error?.message?.includes("You've exceeded your usage quota of")??!1)||(J.error?.message?.includes("You've exceeded your usage limit of")??!1);return Y||X}function kR(J){let Q=["unauthorized","401"],Z=Q.some((X)=>J.message?.toLowerCase().includes(X.toLowerCase())),Y=Boolean(J.error?.message&&Q.some((X)=>J.error?.message?.toLowerCase().includes(X.toLowerCase())));return Z||Y}function yR(J){let Q=["overloaded","overload"],Z=Q.some((G)=>J.message?.toLowerCase().includes(G.toLowerCase())),Y=Boolean(J.error?.message&&Q.some((G)=>J.error?.message?.toLowerCase().includes(G.toLowerCase()))),X=J.error?.type==="overloaded_error";return Z||Y||X}function k61(J){if(J.error?.message)return J.error.message;let Q=J.message||"";if(Q.includes('{"type":"error"')||Q.includes('{"error":'))try{let Z=JSON.parse(Q.replace(/^\d+\s+/,""));if(Z.error?.message)return Z.error.message}catch{}return Q}R8();j01();z4();var y61=(J)=>{let Q=!1;return{install:()=>{if(!Q)process.on("SIGINT",J),process.on("SIGTERM",J),Q=!0},remove:()=>{if(Q)process.off("SIGINT",J),process.off("SIGTERM",J),Q=!1},get installed(){return Q}}};import{once as S$8}from"node:events";import{createInterface as _$8}from"node:readline";B0();R8();V7();o0();function x61(J,Q){if(kR(J))return{title:"Unauthorized.",description:"Check your API key.",options:["retry","dismiss"]};if(Z86(J))return{title:"Thread context limit reached",description:"This thread has reached the context limit for Amp Free. Edit the thread, or start a new thread, to continue. If you need a larger context window, consider using smart mode.",options:["new-thread","new-smart-thread","dismiss"]};if(Y86(J))return{title:"Free mode usage limit reached",description:k61(J),options:["new-smart-thread","dismiss"]};if(_R(J))return{title:"Context window limit reached.",description:"Start a new thread or use /handoff to continue with relevant context in a fresh thread. If utilizing context >200k tokens, you may be seeing this error because we have failed over to a provider without support for extended context.",options:["new-thread","handoff","dismiss"]};if(yR(J))return{title:"Model provider overloaded.",description:"Try again in a few seconds.",options:["retry","dismiss"]};if(SR(J))return{title:"Insufficient credit balance.",description:`Visit ${new URL("/pay",Q).toString()} to buy more credits and continue using Amp.`,options:["retry","dismiss"]};if(X86(J))return{title:"Usage quota exceeded.",description:k61(J),options:["retry","dismiss"]};let Z=200,Y=k61(J);return{title:"Error",description:Y.length>Z?`${Y.substring(0,Z)}...`:Y,options:["retry","dismiss"]}}function $86(J){switch(J){case"retry":return"Retry";case"dismiss":return"Dismiss";case"new-thread":return"New thread";case"new-smart-thread":return"New smart mode thread";case"handoff":return"Handoff";default:throw Error(`Unhandled error action: ${String(J)}`)}}IG();function G86(J){return{type:"text",text:J.text}}function P$8(J){return{type:"tool_use",id:J.id,name:J.name,input:J.input}}function T$8(J){let Q="",Z=!1;switch(J.run.status){case"done":Q=typeof J.run.result==="string"?J.run.result:JSON.stringify(J.run.result),Z=!1;break;case"error":Q=typeof J.run.error==="string"?J.run.error:J.run.error?.message||"Tool execution error",Z=!0;break;case"cancelled":Q=`Tool execution cancelled: ${J.run.reason||"Unknown reason"}`,Z=!0;break;case"rejected-by-user":Q=`Tool execution rejected by user: ${J.run.reason||"User declined permission"}`,Z=!0;break;default:Q=`Tool status: ${J.run.status}`,Z=!1}return{type:"tool_result",tool_use_id:J.toolUseID,content:Q,is_error:Z}}function AC1(J,Q,Z){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(G86(X));else if(X.type==="tool_use")Y.push(P$8(X));return{type:"assistant",message:{type:"message",role:"assistant",content:Y,stop_reason:J.state.type==="complete"?J.state.stopReason:null,usage:J.usage?R$8(J.usage):void 0},parent_tool_use_id:Z??null,session_id:Q}}function V86(J,Q,Z){let Y=[];for(let X of J.content)if(X.type==="text")Y.push(G86(X));else if(X.type==="tool_result")Y.push(T$8(X));return{type:"user",message:{role:"user",content:Y},parent_tool_use_id:Z??null,session_id:Q}}function R$8(J){if(!J)return;return{input_tokens:J.inputTokens||0,cache_creation_input_tokens:J.cacheCreationInputTokens??void 0,cache_read_input_tokens:J.cacheReadInputTokens??void 0,output_tokens:J.outputTokens||0,max_tokens:J.maxInputTokens,service_tier:"standard"}}var C$8=f1.object({type:f1.literal("text"),text:f1.string()}),j$8=f1.object({role:f1.literal("user"),content:f1.array(C$8)}),K86=f1.object({type:f1.literal("user"),message:j$8});var q86=1048576,k$8=1e4;function y$8(J){return J!==void 0}function x$8(J){for(let Q of J)if(Q.type==="tool_result"&&!X3(Q.run))return!1;return!0}async function xR(J){let Q=JSON.stringify(J)+`
3866
+ `;try{if(!process.stdout.write(Q))await S$8(process.stdout,"drain")}catch(Z){throw v.error("Failed to emit JSON message",{error:Z,messageType:J.type}),Z}}function kg(J,Q){let Z;if(J&&typeof J==="object"&&"message"in J&&typeof J.message==="string"){if(Z=Error(J.message),"stack"in J&&typeof J.stack==="string")Z.stack=J.stack}else if(J instanceof Error)Z=J;if(Z&&(kR(Z)||_R(Z)||yR(Z)||SR(Z))){let Y=x61(Z,Q);return Y.description?`${Y.title} ${Y.description}`:Y.title}if(Z)return Z.message;return String(J)}function W86(J){return J.filter((Q)=>Q.role==="assistant"&&Q.state.type!=="streaming").length}function H86(J){switch(J.role){case"user":return x$8(J.content)?0:2;case"assistant":return J.state.type!=="streaming"?0:2;default:return 1}}async function z86({worker:J,threadID:Q,userInput:Z,stdinInput:Y,dependencies:X,streamJsonInput:G=!1,stdin:V=process.stdin,ampURL:K="https://ampcode.com"}){let q=J.thread.agentMode?J.thread.agentMode:"smart";if(J.thread.messages.length!==0&&q!=="smart")throw new I8(`Stream JSON mode for threads in '${q}' mode.`,1);let H=Q,z=Date.now(),U=0,D=!1,M=null;if(Y&&Y.length>q86)throw Error(`Stdin input too large: ${Y.length} bytes (max ${q86})`);let L,E=y61(()=>{if(!D)L("User cancelled (SIGINT/SIGTERM)")});try{E.install(),J.continueInferenceAfterRejection(!0);let P=(await V6(X.toolService.tools.pipe(FF(1),zF(5000)))).map((p)=>p.spec.name),R=[];try{R=(await V6(X.mcpService.servers.pipe(FF(1),zF(5000)))).map((J1)=>({name:J1.name,status:J1.status.type}))}catch(p){v.warn("Unable to obtain MCP server list for system init message",{err:p})}let k={type:"system",subtype:"init",cwd:process.cwd(),session_id:H,tools:P,mcp_servers:R};await xR(k);let y=W86(J.thread.messages),x=J.thread.messages.length,b=new WeakSet,d=new Map,m=0,o=[],X1=!G,t=!1;return new Promise((p,J1)=>{L=async(l)=>{if(D){v.debug("Complete called multiple times, ignoring",{error:l});return}D=!0,E.remove();try{if(l){let W1={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-z,is_error:!0,num_turns:U,error:l,session_id:H};await xR(W1)}else{let W1=M?g2(M,"assistant"):null,_1=W1?x7(W1.content):"",s={type:"result",subtype:"success",duration_ms:Date.now()-z,is_error:!1,num_turns:U,result:_1,session_id:H};await xR(s)}if(U1.unsubscribe(),r.unsubscribe(),o.forEach((W1)=>W1.unsubscribe()),m=0,await J.asyncDispose(),M){await X.threadService.flushVersion(Q,M.v);let W1=X.threadSyncService.uploadThread(Q),_1=new Promise((s,m1)=>{setTimeout(()=>m1(Error("Thread sync timeout")),k$8)});await Promise.race([W1,_1])}p()}catch(W1){v.error("Error during completion",{error:W1}),J1(W1)}};async function H1(l,W1){try{let _1=d.get(l.id);while(_1.cursor<l.messages.length){let m1=l.messages[_1.cursor],S1=H86(m1);if(S1===2)break;if(S1===1){_1.cursor++;continue}if(!_1.emitted.has(m1)){if(m1.role==="assistant"){if(m1.content.length>0)await xR(AC1(m1,H,W1));U++}_1.emitted.add(m1)}_1.cursor++}let s=g2(l,"assistant");if(s&&s.state.type!=="streaming"&&Fy(s)){if(!_1.done)_1.done=!0,m--}if(X1&&t&&m===0)await L()}catch(_1){v.error("Error in subthread patch handler",{error:_1}),await L(kg(_1,K))}}let U1=J.status.subscribe(async(l)=>{try{if(l.state==="active"&&l.ephemeralError){await L(kg(l.ephemeralError,K));return}if(l.state==="active"&&l.inferenceState==="idle"&&M){let W1=M.messages.flatMap((_1)=>_1.content.map((s)=>{if(s.type==="tool_result"&&s.run.status==="blocked-on-user")return qY(M,s.toolUseID)}).filter(y$8));if(W1.length>0){v.warn("Tools require user consent - exiting stream JSON mode",{blockedTools:W1.map((m1)=>({name:m1.name,id:m1.id}))});let s=`The following tools require user approval, which is not supported in stream JSON mode: ${W1.map((m1)=>m1.name).join(", ")}`;await L(s);return}}}catch(W1){v.error("Error in status subscription",{error:W1}),await L(kg(W1,K))}}),r=X.threadService.observe(Q).subscribe(async(l)=>{try{M=l;while(x<l.messages.length){let s=l.messages[x],m1=H86(s);if(m1===1){x++;continue}if(m1===2)break;if(!b.has(s)){if(s.role==="user")await xR(V86(s,H));else if(s.role==="assistant"){if(s.content.length>0){let S1=AC1(s,H);await xR(S1)}U++}b.add(s)}x++}let W1=W86(l.messages),_1=g2(l,"assistant");if(t=W1>y&&_1!==void 0&&_1.state.type!=="streaming"&&Fy(_1),X1&&t&&m===0)await L()}catch(W1){v.error("Error in thread subscription",{error:W1}),await L(kg(W1,K))}}),n=J.subthreads.subscribe((l)=>{for(let W1 of l){if(d.has(W1.threadID))continue;d.set(W1.threadID,{threadID:W1.threadID,toolUseID:W1.toolUse.id,cursor:0,emitted:new WeakSet,done:!1}),m++;let _1=X.threadService.observePatches(W1.threadID).pipe(rD()).subscribe((s)=>H1(s,W1.toolUse.id));o.push(_1)}});if(o.push(n),G)(async()=>{try{for await(let l of v$8(V))J.handle({type:"user:message",message:{content:l.contentBlocks,agentMode:"smart"}});if(X1=!0,t&&m===0)await L()}catch(l){v.error("Error processing streaming input",{error:l}),await L(kg(l,K))}})();else{let l=[{type:"text",text:Z}];if(Y)l.unshift({type:"text",text:`Input received on stdin:
3867
3867
  \`\`\`
3868
3868
  ${Y}
3869
3869
  \`\`\``});J.handle({type:"user:message",message:{content:l,agentMode:"smart"}}),X1=!0}})}catch(I){throw E.remove(),I}}async function*v$8(J){let Q=_$8({input:J,crlfDelay:Number.POSITIVE_INFINITY}),Z=0;try{for await(let Y of Q){if(Z++,Y.trim()==="")continue;let X;try{X=JSON.parse(Y)}catch(K){throw new I8(`Invalid JSON on stdin line ${Z}: ${K instanceof Error?K.message:String(K)}`,1,`Line content: ${Y.slice(0,100)}${Y.length>100?"...":""}`)}let G=K86.safeParse(X);if(!G.success){let K=G.error.issues.map((q)=>`${q.path.join(".")}: ${q.message}`).join(", ");throw new I8(`Invalid message format on stdin line ${Z}: ${K}`,1,'Expected format: {"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}')}yield{contentBlocks:G.data.message.content}}}finally{Q.close()}}async function U86(J,Q,Z,Y,X,G,V,K,q){if(J.thread.agentMode&&P9(J.thread.agentMode))throw new I8(`Execute mode is not permitted for threads in '${J.thread.agentMode}' mode.`,1);if(G)return z86({worker:J,threadID:Q,userInput:Z,stdinInput:Y,dependencies:X,streamJsonInput:V,ampURL:q});let W=F86(J.thread.messages),H=[{type:"text",text:Z}];if(Y)H.unshift({type:"text",text:`Input received on stdin:
@@ -3998,15 +3998,15 @@ Actual: ${X}`)}async function QV8(J,Q,Z){let{execSync:Y}=await import("node:ch
3998
3998
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))M+=`
3999
3999
 
4000
4000
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4001
- npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}B0();B0();async function r61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=GV8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function GV8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}o0();function s61(J,Q){let Z=new u4,Y=Z.pipe(E8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new KK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await $R(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=IA(),W=await r61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await o61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}try{await lg(W.latestVersion,z);let U=await EB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Eq}from"node:process";function E96(J){let Q=new qA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await fC1(Y.force||!1,Y.verbose||!1,"0.0.1764878483-g1dd0b0"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new qA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await VV8(Y.targetVersion)});J.addCommand(Z)}async function VV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Eq.write(_4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4001
+ npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}B0();B0();async function r61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=GV8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return v.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return v.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function GV8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}o0();function s61(J,Q){let Z=new u4,Y=Z.pipe(E8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new KK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await $R(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=IA(),W=await r61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await o61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}try{await lg(W.latestVersion,z);let U=await EB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Eq}from"node:process";function E96(J){let Q=new qA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await fC1(Y.force||!1,Y.verbose||!1,"0.0.1764892237-g17504a"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new qA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await VV8(Y.targetVersion)});J.addCommand(Z)}async function VV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Eq.write(_4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4002
4002
 
4003
4003
  `));try{if(!J){Eq.write(_4.blue(`Checking for updates...
4004
- `));let Y=IA(),{hasUpdate:X,latestVersion:G}=await r61("0.0.1764878483-g1dd0b0",Y);if(!X){Eq.write(_4.green(`✓ Amp CLI is already up to date: ${"0.0.1764878483-g1dd0b0"} (${"released"} ${"2025-12-04T20:06:46.152Z"})
4005
- `));let K=await EB("0.0.1764878483-g1dd0b0");if(K.warning)Eq.write(`
4004
+ `));let Y=IA(),{hasUpdate:X,latestVersion:G}=await r61("0.0.1764892237-g17504a",Y);if(!X){Eq.write(_4.green(`✓ Amp CLI is already up to date: ${"0.0.1764892237-g17504a"} (${"released"} ${"2025-12-04T23:55:42.376Z"})
4005
+ `));let K=await EB("0.0.1764892237-g17504a");if(K.warning)Eq.write(`
4006
4006
  `+_4.yellow(K.warning)+`
4007
4007
  `);process.exit(0)}if(!G)Eq.write(_4.yellow("[WARN] could not find latest version")),process.exit(0);J=G}Eq.write(_4.blue(`Updating to version ${J}...
4008
4008
  `)),await lg(J,void 0,(Y)=>{Eq.write(_4.dim(`Running: ${Y}
4009
- `))});let Q="released";Eq.write(_4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-04T20:06:46.152Z"})
4009
+ `))});let Q="released";Eq.write(_4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-04T23:55:42.376Z"})
4010
4010
  `));let Z=await EB(J);if(Z.warning)Eq.write(`
4011
4011
  `+_4.yellow(Z.warning)+`
4012
4012
  `);process.exit(0)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);Eq.write(_4.red.bold("Error: ")+Z+`
@@ -4643,7 +4643,7 @@ Ctrl-X Y Z to unlock`;if(U){let o=W.text.replace(/`([^`]+)`/g,"$1")+`
4643
4643
  `,A)])}),y];if(!q&&!U&&W.url){let m=W.url.replace(/^https?:\/\//,"");b.push(new u5({uri:W.url,text:m,style:new e({color:Z.secondary,underline:!0})}))}if(k&&!U)b.push(k);let d=new X0({width:40,child:new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:b})});return f4.child(new A6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new GS1({width:xk1,height:vk1,agentMode:this.widget.agentMode,glow:this._glow,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:P,...V==="disabled"&&{seed:42}}),new X0({width:2}),d]}))}}B0();R8();z4();V7();R8();o0();function aD8(J,Q){return`${J}:${Q}`}class fk1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Z)=>Q.next(Z),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Z=this.threadService.observePatches(Q).pipe(rD()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Y);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=aD8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(rD()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);let Y=this.subthreadsSubs.get(J);if(Y)Y.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new Q0((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=nL(Z,Y)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function oD8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:Y}=Q,X=J.subagents[Y.threadID];if(!X){if(X={subThreadID:Z.id,parentToolID:Y.toolUse.id,taskDescription:Y.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=fJ(J.mainThread);X.isCompleted=zZ6(W,Y.toolUse.id)}}let G=rD8(Z,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=AC(Z).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Z.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Y.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:Y,workerStatus:X}=Q,G=fJ(Z),V={...J.subagents};for(let z of Y){let U=V[z.threadID];if(!U)continue;let D=zZ6(G,z.toolUse.id);V[z.threadID]={...U,isCompleted:D}}let{items:K}=AC(Z),q=nL(Z,X),W=pE({messages:Z.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=nL(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function AC(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let D of U.content)if(D.type==="tool_result"&&D.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??qY(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function zZ6(J,Q){let Z=J.get(Q);return(Z&&X3(Z.run))??!1}function rD8(J,Q){let Z=J.messages.at(-1);if(Z?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return v.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(AC(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Z&&Z.role==="assistant"&&Z.state.type==="streaming")switch(Z.content.at(-1)?.type){case"text":return v.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return v.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return v.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return v.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return v.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class hk1 extends d0{props;constructor(J){super();this.props=J}createState(){return new FZ6}}class FZ6 extends u0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new fk1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Z=Q.mainThread.subscribe((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Z);let Y=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Y);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=oD8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Z=(G)=>G===B5||G===l8||G===VY,Y=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Z(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Y.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let z of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:gE(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class bk1 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new UZ6}}class UZ6 extends u0{build(J){let Z=Y6.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new X0({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new g0({child:new H6({padding:F0.symmetric(1,0),child:new v0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new k1({text:new i(X,new e({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new e({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new e({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new A6({crossAxisAlignment:"start",children:[new k1({text:new i(Z,X)}),new X0({width:1}),new e6({child:new k1({text:new i(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class gk1 extends T6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y}build(J){let Q=Y6.of(J),Z=Q.colors.primary,Y=Q.colors.foreground;return new g0({decoration:new U8(void 0,new A4(new q4(Z,1,"rounded"),new q4(Z,1,"rounded"),void 0,new q4(Z,1,"rounded"))),child:new H6({padding:F0.horizontal(1),child:new v0({children:[new A6({crossAxisAlignment:"start",children:[new e6({child:new k1({text:new i(this.ad.content,new e({color:Y}))})}),new X0({width:4}),new u5({uri:"https://ampcode.com/free",text:"Ad",style:new e({color:Y,dim:!0})})]}),new A6({crossAxisAlignment:"start",children:[new DS1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:F0.horizontal(1),color:Z,reverse:!0}),new X0({width:2}),new k1({text:new i(this.ad.destinationUrlHostname,new e({color:Y,dim:!0}))})]})]})})})}}class mk1 extends d0{props;constructor(J){super();this.props=J}createState(){return new BZ6(this.props.autofocus??!0)}}class BZ6 extends u0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=v4.sizeOf(J),Y=Math.min(60,Z.width-4),X=Z.height-4,G=[];if(this.widget.props.title)G.push(new k1({text:new i(this.widget.props.title,new e({bold:!0,color:F1.blue}))}),new X0({height:1}));if(this.widget.props.message)G.push(new k1({text:new i(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new X0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new k1({text:new i("Enter to copy",new e({dim:!0}))}));return V.push(new k1({text:new i("Escape to close",new e({dim:!0}))})),G.push(new A6({children:V.flatMap((K,q)=>q<V.length-1?[K,new X0({width:1}),new k1({text:new i("•",new e({dim:!0}))}),new X0({width:1})]:[K]),mainAxisSize:"min"})),new f4({child:new g0({constraints:new I6(Y,Y,0,X),decoration:new U8(F1.default(),new A4(new q4(F1.blue,1,"rounded"),new q4(F1.blue,1,"rounded"),new q4(F1.blue,1,"rounded"),new q4(F1.blue,1,"rounded"))),padding:new F0(2,2,2,2),child:new q8({autofocus:this.autofocus,onKey:Q,child:new v0({children:G,mainAxisSize:"min"})})})})}}class w91 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,w91.prototype)}}class E91 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,E91.prototype)}}function uk1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}oW();B0();import{spawn as sD8}from"node:child_process";import{promises as tD8}from"node:fs";function NZ6(J){return J.kind==="executable"}function DZ6(J){return J.kind==="markdown"}var Xz=50000,MZ6=300000;async function pk1(J,Q,Z,Y={}){let{timeoutMs:X=MZ6,signal:G,source:V}=Y;try{let K=await Z.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(v.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),DZ6(K))return await eD8(K,Q);else if(NZ6(K))return await JM8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return v.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function eD8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await tD8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>Xz?Z.slice(0,Xz)+`
4644
4644
  ... (output truncated at ${Xz} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function JM8(J,Q,Z=MZ6,Y){return new Promise((X)=>{let[G,V]=QM8(J,Q);v.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Z});let K=$T0(Y),q=!1,W=setTimeout(()=>{q=!0,K.abort(),v.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),H=sD8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],U=[],D=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)z.push(L);else{let A=Xz-(D-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)U.push(L);else{let A=Xz-(D-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),I=A;if(!L&&!A.trim()&&E.trim())I=E;else if(E.trim())I+=A?`
4645
4645
  ${E}`:E;if(D>Xz)I+=`
4646
- ... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function QM8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return YM8(Z,Y?[...Y]:null,X,Q);else return ZM8(Z,Y?[...Y]:null,X,Q)}function ZM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function YM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}B0();OG();O7();xW();BY();mG();rW();gK();R8();V7();d_();o0();var iZ6=q6(wP(),1);import{writeFile as dZ6}from"fs/promises";import cZ6 from"path";B0();BY();class dk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764878483-g1dd0b0"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Jr(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class OC extends d0{props;constructor(J){super();this.props=J}createState(){return new LZ6}}class LZ6 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AZ6 extends u0{controller=new R$;focusNode=new F8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=A4.all(new q4(Z.foreground,1,"solid")),q=new mA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new A6({children:[new g0({decoration:{color:F1.default()},child:new k1({text:new i(">",new e({color:Z.foreground}))})}),new e6({child:q})]}),H=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,[new i("Command: ",new e({color:Z.foreground})),new i(this.widget.props.commandName,new e({color:F1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new e({color:Y.keybind}))),z.push(new i(" to submit, ",new e({color:Z.foreground,dim:!0})));z.push(new i("Esc",new e({color:Y.keybind}))),z.push(new i(" to cancel",new e({color:Z.foreground,dim:!0})));let U=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,z)})});return new g0({decoration:{border:K,color:F1.default()},padding:F0.all(1),child:new v0({children:[H,new X0({height:1}),W,new t9,U]})})}}class I91 extends d0{props;constructor(J){super();this.props=J}createState(){return new AZ6}}rW();class OZ6 extends u0{controller=new R$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new F8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=nF)return!1;let Q=XC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,G=v4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new eA({controller:this.controller,triggers:[new dB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:a8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new q8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new I6({maxHeight:V}),padding:F0.symmetric(1,0),child:q}),H=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,[new i("Command: ",new e({color:Z.foreground})),new i(this.widget.props.commandName,new e({color:F1.yellow,bold:!0}))])})}),z=new g0({padding:F0.symmetric(1,0),child:new k1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new e({color:Y.keybind})),new i(" again to clear input",new e({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new e({color:Z.foreground,dim:!0})),new i("Enter",new e({color:Y.keybind})),new i(" to submit, ",new e({color:Z.foreground,dim:!0})),new i("Esc",new e({color:Y.keybind})),new i(" to clear",new e({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new e6({child:W}),new X0({height:1}),z];return new g0({decoration:{border:A4.all(new q4(Z.foreground,1,"solid")),color:F1.default()},padding:F0.all(1),child:new v0({children:U})})}}class wC extends d0{props;constructor(J){super();this.props=J}createState(){return new OZ6}}import{isDeepStrictEqual as VM8}from"node:util";var XM8=/[\\/_ +.#"@[({&]/,$M8=/[\\/_ +.#"@[({&]/g,GM8=/[\s-]/,wZ6=/[\s-]/g;function T91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=T91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GM8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(wZ6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(XM8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match($M8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=T91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function P91(J){return J.toLowerCase().replace(wZ6," ")}function EZ6(J,Q){let Z=T91(J,Q,P91(J),P91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=T91(J,K,P91(J),P91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class EC{}class IC{}class R91{}class C91{}class IZ6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PZ6}}class PZ6 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function KM8(J,Q){if(J==="")return{matches:!0,score:1};let Z=EZ6(Q,J);return{matches:Z>0.15,score:Z}}class dQ extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TZ6}}class TZ6 extends u0{controller=new R$;focusNode;scrollController=new N7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new F8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!VM8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof EC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof R91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof C91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...KM8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;O81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=A4.all(new q4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new mA({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new cY({shortcuts:new Map([[new G4("ArrowDown"),new EC],[new G4("ArrowUp"),new IC],[new G4("Tab"),new EC],[new G4("Tab",{shift:!0}),new IC],[new G4("n",{ctrl:!0}),new EC],[new G4("p",{ctrl:!0}),new IC],[new G4("Enter"),new R91],[new G4("Escape"),new C91]]),focusNode:this.focusNode,child:V}),q=new $J({actions:new Map([[EC,new A8(this.invoke)],[IC,new A8(this.invoke)],[R91,new A8(this.invoke)],[C91,new A8(this.invoke)]]),child:K}),W=new A6({children:[new g0({decoration:{color:F1.default()},child:new k1({text:new i(">",new e({color:Z.foreground}))})}),new e6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new f4({child:new k1({text:new i(L,new e({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new e6({child:new f4({child:new k1({text:new i(this.widget.props.emptyStateText,new e({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let k=I?F1.yellow:void 0,y=I?F1.black:Z.foreground;R=new g0({decoration:k?{color:k}:void 0,padding:F0.symmetric(2,0),child:new k1({text:new i(this.widget.props.getLabel(A),new e({color:y,dim:P}))})})}return new IZ6(new $8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:R}),(k)=>{this.itemContexts[E]=k})});H=new v0({children:L,crossAxisAlignment:"start"})}let z=new e6({child:new $8({onScroll:this.handleScroll,opaque:!1,child:new _5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i(this.widget.props.title,new e({color:F1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:F0.vertical(1),child:new f4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:F1.default()},padding:F0.symmetric(1,0),child:new v0({children:U})})}}class ck1 extends d0{createState(){return new RZ6}}class RZ6 extends u0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new k1({text:new i("●",new e({color:this.isGreen?F1.green:F1.index(8),bold:!0})),maxLines:1})}}function qM8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return iY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function lk1(J,Q,Z){return new k1({text:new i(`${J}${Q}`,new e({color:Z})),maxLines:1})}function WM8(J,Q,Z,Y){return[lk1("+",J,Y.success),t9.horizontal(1),lk1("~",Q,Y.warning),t9.horizontal(1),lk1("-",Z,Y.destructive)]}class j91 extends T6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=qM8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=Y6.of(J),q=new H6({padding:F0.symmetric(0,1),child:new f4({child:new k1({text:new i("",new e({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new e({color:F1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new e({color:K.colors.foreground,dim:!0}))])})})});return new dQ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=Y6.of(D),{colors:L}=M,A=z?F1.yellow:void 0,E=z?F1.black:L.foreground,I=F1.index(8),P=(X1,t)=>new X0({width:t,child:A6.end([new k1({text:new i(X1,new e({color:I}))})])}),R=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",x=new C81;if(H.depth>0){let X1=[],t=H.ancestorsAreLast.slice(1);for(let H1 of t)X1.push(new i(x.getAncestorPrefix(H1),new e({color:x.connectorColor,dim:x.connectorDim})));let p=H.isLast?x.elbow:x.tee,J1=x.getConnectorText(p);X1.push(new i(J1,new e({color:x.connectorColor,dim:x.connectorDim}))),k.push(new k1({text:new i("",void 0,X1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new e({color:F1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new e({color:L.foreground,dim:!0})):null;if(d)b.push(new k1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))b.push(new ck1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let X1=m.match(/^Forked\((\d+)\): /);if(X1)m=m.slice(X1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new k1({text:new i("[fork] ",new e({color:F1.blue}))}))}else if(y)b.push(new k1({text:new i("[handoff] ",new e({color:F1.index(208)}))}));if(b.push(new e6({child:new k1({text:new i(m,new e({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let X1=z?{success:I,warning:I,destructive:I}:L;b.push(...WM8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,X1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new g0({decoration:A?{color:A}:void 0,padding:F0.symmetric(2,0),child:new A6({children:[...k,...b]})})}})}}function CZ6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class ik1 extends T6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CZ6(X.pubDate).length));return new dQ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=Y6.of(K),{colors:W}=q,H=G?F1.yellow:void 0,z=G?F1.black:W.foreground,U=F1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:A6.end([new k1({text:new i(L,new e({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new A6({children:[new e6({child:new k1({text:new i(X.title,new e({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new k1({text:new i(D,new e({color:U})),maxLines:1}),new X0({width:2}),M(CZ6(X.pubDate),Z)]})})}})}}class nk1 extends T6{props;constructor(J){super();this.props=J}build(){return new f4({child:new k1({text:new i("",void 0,[new i(`Forked to new thread:
4646
+ ... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function QM8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return YM8(Z,Y?[...Y]:null,X,Q);else return ZM8(Z,Y?[...Y]:null,X,Q)}function ZM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function YM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}B0();OG();O7();xW();BY();mG();rW();gK();R8();V7();d_();o0();var iZ6=q6(wP(),1);import{writeFile as dZ6}from"fs/promises";import cZ6 from"path";B0();BY();class dk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764892237-g17504a"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Jr(Q,this.configService)}catch(Q){v.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class OC extends d0{props;constructor(J){super();this.props=J}createState(){return new LZ6}}class LZ6 extends u0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AZ6 extends u0{controller=new R$;focusNode=new F8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=A4.all(new q4(Z.foreground,1,"solid")),q=new mA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new A6({children:[new g0({decoration:{color:F1.default()},child:new k1({text:new i(">",new e({color:Z.foreground}))})}),new e6({child:q})]}),H=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,[new i("Command: ",new e({color:Z.foreground})),new i(this.widget.props.commandName,new e({color:F1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new e({color:Y.keybind}))),z.push(new i(" to submit, ",new e({color:Z.foreground,dim:!0})));z.push(new i("Esc",new e({color:Y.keybind}))),z.push(new i(" to cancel",new e({color:Z.foreground,dim:!0})));let U=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,z)})});return new g0({decoration:{border:K,color:F1.default()},padding:F0.all(1),child:new v0({children:[H,new X0({height:1}),W,new t9,U]})})}}class I91 extends d0{props;constructor(J){super();this.props=J}createState(){return new AZ6}}rW();class OZ6 extends u0{controller=new R$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new F8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=nF)return!1;let Q=XC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,G=v4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new eA({controller:this.controller,triggers:[new dB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:a8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new q8({focusNode:this.focusNode,child:K}),W=new g0({constraints:new I6({maxHeight:V}),padding:F0.symmetric(1,0),child:q}),H=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i("",void 0,[new i("Command: ",new e({color:Z.foreground})),new i(this.widget.props.commandName,new e({color:F1.yellow,bold:!0}))])})}),z=new g0({padding:F0.symmetric(1,0),child:new k1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new e({color:Y.keybind})),new i(" again to clear input",new e({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new e({color:Z.foreground,dim:!0})),new i("Enter",new e({color:Y.keybind})),new i(" to submit, ",new e({color:Z.foreground,dim:!0})),new i("Esc",new e({color:Y.keybind})),new i(" to clear",new e({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new e6({child:W}),new X0({height:1}),z];return new g0({decoration:{border:A4.all(new q4(Z.foreground,1,"solid")),color:F1.default()},padding:F0.all(1),child:new v0({children:U})})}}class wC extends d0{props;constructor(J){super();this.props=J}createState(){return new OZ6}}import{isDeepStrictEqual as VM8}from"node:util";var XM8=/[\\/_ +.#"@[({&]/,$M8=/[\\/_ +.#"@[({&]/g,GM8=/[\s-]/,wZ6=/[\s-]/g;function T91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=T91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GM8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(wZ6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(XM8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match($M8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=T91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function P91(J){return J.toLowerCase().replace(wZ6," ")}function EZ6(J,Q){let Z=T91(J,Q,P91(J),P91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=T91(J,K,P91(J),P91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class EC{}class IC{}class R91{}class C91{}class IZ6 extends d0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PZ6}}class PZ6 extends u0{build(J){return this.widget.onContext(J),this.widget.child}}function KM8(J,Q){if(J==="")return{matches:!0,score:1};let Z=EZ6(Q,J);return{matches:Z>0.15,score:Z}}class dQ extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TZ6}}class TZ6 extends u0{controller=new R$;focusNode;scrollController=new N7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new F8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!VM8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof EC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof IC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof R91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof C91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...KM8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;O81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=A4.all(new q4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new mA({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new cY({shortcuts:new Map([[new G4("ArrowDown"),new EC],[new G4("ArrowUp"),new IC],[new G4("Tab"),new EC],[new G4("Tab",{shift:!0}),new IC],[new G4("n",{ctrl:!0}),new EC],[new G4("p",{ctrl:!0}),new IC],[new G4("Enter"),new R91],[new G4("Escape"),new C91]]),focusNode:this.focusNode,child:V}),q=new $J({actions:new Map([[EC,new A8(this.invoke)],[IC,new A8(this.invoke)],[R91,new A8(this.invoke)],[C91,new A8(this.invoke)]]),child:K}),W=new A6({children:[new g0({decoration:{color:F1.default()},child:new k1({text:new i(">",new e({color:Z.foreground}))})}),new e6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new f4({child:new k1({text:new i(L,new e({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new e6({child:new f4({child:new k1({text:new i(this.widget.props.emptyStateText,new e({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,R;if(this.widget.props.renderItem)R=this.widget.props.renderItem(A,I,P,J);else{let k=I?F1.yellow:void 0,y=I?F1.black:Z.foreground;R=new g0({decoration:k?{color:k}:void 0,padding:F0.symmetric(2,0),child:new k1({text:new i(this.widget.props.getLabel(A),new e({color:y,dim:P}))})})}return new IZ6(new $8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:R}),(k)=>{this.itemContexts[E]=k})});H=new v0({children:L,crossAxisAlignment:"start"})}let z=new e6({child:new $8({onScroll:this.handleScroll,opaque:!1,child:new _5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i(this.widget.props.title,new e({color:F1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new g0({padding:F0.vertical(1),child:new f4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new g0({decoration:{border:X,color:F1.default()},padding:F0.symmetric(1,0),child:new v0({children:U})})}}class ck1 extends d0{createState(){return new RZ6}}class RZ6 extends u0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new k1({text:new i("●",new e({color:this.isGreen?F1.green:F1.index(8),bold:!0})),maxLines:1})}}function qM8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return iY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function lk1(J,Q,Z){return new k1({text:new i(`${J}${Q}`,new e({color:Z})),maxLines:1})}function WM8(J,Q,Z,Y){return[lk1("+",J,Y.success),t9.horizontal(1),lk1("~",Q,Y.warning),t9.horizontal(1),lk1("-",Z,Y.destructive)]}class j91 extends T6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=qM8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=Y6.of(J),q=new H6({padding:F0.symmetric(0,1),child:new f4({child:new k1({text:new i("",new e({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new e({color:F1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new e({color:K.colors.foreground,dim:!0}))])})})});return new dQ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=Y6.of(D),{colors:L}=M,A=z?F1.yellow:void 0,E=z?F1.black:L.foreground,I=F1.index(8),P=(X1,t)=>new X0({width:t,child:A6.end([new k1({text:new i(X1,new e({color:I}))})])}),R=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",x=new C81;if(H.depth>0){let X1=[],t=H.ancestorsAreLast.slice(1);for(let H1 of t)X1.push(new i(x.getAncestorPrefix(H1),new e({color:x.connectorColor,dim:x.connectorDim})));let p=H.isLast?x.elbow:x.tee,J1=x.getConnectorText(p);X1.push(new i(J1,new e({color:x.connectorColor,dim:x.connectorDim}))),k.push(new k1({text:new i("",void 0,X1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new e({color:F1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new e({color:L.foreground,dim:!0})):null;if(d)b.push(new k1({text:d}));if(R){if(R.state==="active"&&(R.interactionState==="tool-running"||R.interactionState===!1))b.push(new ck1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let X1=m.match(/^Forked\((\d+)\): /);if(X1)m=m.slice(X1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new k1({text:new i("[fork] ",new e({color:F1.blue}))}))}else if(y)b.push(new k1({text:new i("[handoff] ",new e({color:F1.index(208)}))}));if(b.push(new e6({child:new k1({text:new i(m,new e({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let X1=z?{success:I,warning:I,destructive:I}:L;b.push(...WM8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,X1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new g0({decoration:A?{color:A}:void 0,padding:F0.symmetric(2,0),child:new A6({children:[...k,...b]})})}})}}function CZ6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class ik1 extends T6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CZ6(X.pubDate).length));return new dQ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=Y6.of(K),{colors:W}=q,H=G?F1.yellow:void 0,z=G?F1.black:W.foreground,U=F1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:A6.end([new k1({text:new i(L,new e({color:U}))})])});return new g0({decoration:H?{color:H}:void 0,padding:F0.symmetric(2,0),child:new A6({children:[new e6({child:new k1({text:new i(X.title,new e({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new k1({text:new i(D,new e({color:U})),maxLines:1}),new X0({width:2}),M(CZ6(X.pubDate),Z)]})})}})}}class nk1 extends T6{props;constructor(J){super();this.props=J}build(){return new f4({child:new k1({text:new i("",void 0,[new i(`Forked to new thread:
4647
4647
 
4648
4648
  `,new e({color:F1.white,dim:!0})),new i(`"${this.props.newThreadTitle||"Untitled"}"`,new e({color:F1.white}))]),textAlign:"center"})})}}B0();class jZ6 extends u0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){v.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){v.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null}buildItemsWithCreateOption(){let J=this.widget.props.currentLabels||[],Z=[...this.labels.filter((Y)=>!J.includes(Y.name))];if(this.currentQuery.trim().length>0&&!this.isLoading){let Y=this.currentQuery.trim().toLowerCase(),X=this.labels.some((V)=>V.name===Y),G=J.includes(Y);if(!X&&!G&&this.isValidLabelName(Y))Z.unshift({id:"__create__",name:Y,createdAt:"",__isCreateMarker:!0})}return Z}build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.currentQuery.trim().toLowerCase(),X=Y.length>0?this.getValidationError(Y):null;return new dQ({title:"Add Label",items:this.buildItemsWithCreateOption(),getLabel:(G)=>G.name,onAccept:(G)=>{this.widget.props.onSelect(G.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(G,V,K,q)=>{let W=V?F1.yellow:void 0,H=V?F1.black:Z.foreground;if("__isCreateMarker"in G&&G.__isCreateMarker)return new g0({decoration:W?{color:W}:void 0,padding:F0.symmetric(2,0),child:new k1({text:new i("",void 0,[new i("Create: ",new e({color:H})),new i(G.name,new e({color:H,bold:!0}))])})});return new g0({decoration:W?{color:W}:void 0,padding:F0.symmetric(2,0),child:new k1({text:new i(G.name,new e({color:H}))})})},filterItem:(G,V)=>{let K=this.currentQuery;if(this.currentQuery=V,K!==V)this.setState();if("__isCreateMarker"in G&&G.__isCreateMarker)return!0;let W=V.trim().toLowerCase();return W.length===0||G.name.includes(W)}})}}class ak1 extends d0{props;constructor(J){super();this.props=J}createState(){return new jZ6}}class fq extends d0{props;constructor(J){super();this.props=J}createState(){return new SZ6}}class SZ6 extends u0{_spinner=new C$;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=A4.all(new q4(Z.foreground,1,"solid")),X=this._spinner.toBraille(),G=new k1({textAlign:"center",text:new i("",void 0,[new i(X,new e({color:F1.yellow})),new i(" ",void 0),new i(this.widget.props.message,new e({color:Z.foreground}))])}),K=[new e6({child:new v0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new X0({height:2,child:new g0({padding:F0.symmetric(2,0),child:new k1({text:new i("",new e({dim:!0}),[new i("Press ",new e({color:Z.foreground})),new i("Esc",new e({color:Z.info})),new i(" to cancel",new e({color:Z.foreground}))])})})}));let q=new g0({decoration:new U8(F1.default(),Y),child:new X0({width:60,height:7,child:new v0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new q8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class LV extends d0{props;constructor(J){super();this.props=J}createState(){return new _Z6}}class _Z6 extends u0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof DV}build(J){let Q=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=I81(Q);return{title:W.title,type:W.type,description:W.description}})(),Y=Z.type==="error"?F1.red:F1.yellow,X=A4.all(new q4(F1.default(),1,"solid")),G=new g0({padding:F0.symmetric(1,0),child:new k1({text:new i(Z.title,new e({color:Y,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new k1({text:new i(Z.description,new e({color:F1.default()})),selectable:!0}),K=new e6({child:new hA({child:new g0({padding:F0.symmetric(1,0),child:V})})}),q=new g0({padding:F0.symmetric(1,0),child:new k1({text:this.widget.props.onRetry?new i("",void 0,[new i("Press ",new e({color:F1.default(),dim:!0})),new i("R",new e({color:F1.yellow})),new i(" to retry, ",new e({color:F1.default(),dim:!0})),new i("Esc",new e({color:F1.yellow})),new i(" to cancel",new e({color:F1.default(),dim:!0}))]):new i("Press any key to close",new e({color:F1.default(),dim:!0,italic:!0}))})});return new q8({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new g0({decoration:{border:X,color:F1.default()},padding:F0.all(1),child:new v0({mainAxisAlignment:"center",children:[G,new X0({height:1}),K,q]})})})}}class ok1 extends T6{build(){return new f4({child:new k1({text:new i("",void 0,[new i(`✓ Thread Shared
4649
4649
 
@@ -4719,7 +4719,7 @@ Press ? to view full diff`;else if(J.name===VY)return Q||"The Librarian needs yo
4719
4719
  `,new e({color:Z.accent,bold:!0}))),x.isFreeMode)y.push(new i(" Total: ",L)),y.push(new i(RA(x.totalCostUSD),new e({strikethrough:!0,color:Z.foreground}))),y.push(new i(` free
4720
4720
  `,I));else y.push(new i(` Total: ${RA(x.totalCostUSD)}
4721
4721
  `,A));if(this.widget.onOpenCostBreakdown)y.push(new i(" Press ",E)),y.push(new i("b",R)),y.push(new i(` to view breakdown
4722
- `,E))}let b=new H6({padding:F0.only({left:2,right:2,top:1,bottom:1}),child:new k1({text:new i("Context Details",M)})}),d=new H6({padding:F0.horizontal(1),child:new k1({text:new i("─".repeat(D-4),new e({color:Z.foreground,dim:!0}))})}),m=new H6({padding:F0.only({left:2,right:2,top:1,bottom:1}),child:new k1({text:new i(void 0,k,[new i("Esc",R),new i(": close • ",k),new i("↑↓",R),new i("/",k),new i("j k",R),new i(": scroll",k)])})}),o=new q8({autofocus:!0,onKey:this.handleKeyEvent,child:new $Y6({scrollOffset:this.scrollOffset,onMeasured:(J1,H1)=>{this.updateScrollBounds(J1,H1)},child:new H6({padding:F0.symmetric(2,1),child:new k1({text:new i("",void 0,y)})})})}),X1=new qJ({controller:null,getScrollInfo:this.getScrollbarInfo,thickness:1,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack}),t=new x9({children:[new H6({padding:F0.only({right:1}),child:o}),new S5({right:0,top:0,bottom:0,child:new X0({width:1,child:X1})})]}),p=new v0({crossAxisAlignment:"stretch",children:[b,d,new e6({child:t}),d,m]});return new f4({child:new g0({constraints:new I6(D,D,0,U),decoration:{color:Z.background,border:A4.all(new q4(Z.primary,1,"rounded"))},child:p})})}}class $Y6 extends j5{scrollOffset;onMeasured;constructor({child:J,scrollOffset:Q=0,onMeasured:Z,key:Y}){super(Y?{child:J,key:Y}:{child:J});this.scrollOffset=Q,this.onMeasured=Z}createRenderObject(){return new GY6(this.scrollOffset,this.onMeasured)}updateRenderObject(J){J.updateProperties(this.scrollOffset,this.onMeasured)}}class GY6 extends F4{_scrollOffset;_onMeasured;constructor(J,Q){super();this._scrollOffset=J,this._onMeasured=Q}updateProperties(J,Q){if(this._scrollOffset!==J)this._scrollOffset=J,this.markNeedsPaint();this._onMeasured=Q}performLayout(){let J=this._lastConstraints;if(M4(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(J.minWidth,J.minHeight),super.performLayout();return}let Q=this.children[0],Z=new I6(J.minWidth,J.maxWidth,0,Number.POSITIVE_INFINITY);Q.layout(Z);let Y=-this._scrollOffset;if(Q.setOffset(0,Y),this.setSize(J.maxWidth,J.maxHeight),this._onMeasured)this._onMeasured(Q.size.height,this.size.height);super.performLayout()}paint(J,Q=0,Z=0){for(let Y of this.children)if("offset"in Y&&"paint"in Y){let X=new dY(J,Q,Z,this.size.width,this.size.height);Y.paint(X,Q,Z)}}}class Fy1 extends T6{error;ampURL;onResponse;constructor({key:J,error:Q,ampURL:Z,onResponse:Y}){super({key:J});this.error=Q,this.ampURL=Z,this.onResponse=Y}build(J){let Z=U4.of(J).colorScheme,Y=x61(this.error,this.ampURL),X=Y.options.map((V)=>({value:V,label:$86(V)})),G=Y.description;if(Y.link)G=new A6({children:[new k1({text:new i(Y.description??"")}),new u5({uri:Y.link.url,text:Y.link.text})]});return new bZ({title:Y.title,body:G,options:X,onSelect:(V)=>{this.onResponse(V??"dismiss")},borderColor:Z.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}}var wM8=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]}]},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]}]},{description:"Delete word forward",methods:[{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]}],EM8=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class v91 extends T6{items;renderRow;constructor({items:J,renderRow:Q}){super();this.items=J,this.renderRow=Q}build(J){let Z=v4.of(J).size.width,Y=50,X=Z<50,G=[];for(let V of this.items){let[K,q]=this.renderRow(V),W;if(X)W=new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:[K,new H6({padding:F0.only({left:4}),child:q})]});else W=new A6({crossAxisAlignment:"start",children:[new e6({flex:1,child:K}),new X0({width:1}),new e6({flex:1,child:q})]});G.push(new H6({padding:F0.horizontal(6),child:W}))}return new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:G})}}class Uy1 extends d0{commands;constructor({key:J,commands:Q}){super(J?{key:J}:{});this.commands=Q}createState(){return new VY6}}class VY6 extends u0{scrollController;initState(){this.scrollController=new N7,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(J){let Z=U4.of(J).colorScheme,X=Y6.of(J).app,G=v4.of(J),V=new e({color:Z.primary,bold:!0}),K=new e({color:Z.secondary,bold:!0}),q=new e({color:X.keybind}),W=new e({color:X.command}),H=new e({color:Z.foreground}),z=new e({color:Z.foreground}),U=G.size.width,D=G.size.height,M=U-4,L=D-4,A=Math.max(40,Math.min(80,M)),E=new Map(this.widget.commands.map((x)=>[x.id,x])),P=["help","new","continue","thread-previous","thread-next","thread-parent","handoff","browser","visibility","mention-thread","editor","queue","dequeue","toggle-agent-mode","permissions","settings","generate-agent-file","agent-files","ide","quit"].map((x)=>E.get(x)).filter((x)=>x!==void 0),R=new _5({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new I6(A,A,0,Number.POSITIVE_INFINITY),child:new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new f4({child:new k1({text:new i(`Amp CLI - Help & Keyboard Shortcuts
4722
+ `,E))}let b=new H6({padding:F0.only({left:2,right:2,top:1,bottom:1}),child:new k1({text:new i("Context Details",M)})}),d=new H6({padding:F0.horizontal(1),child:new k1({text:new i("─".repeat(D-4),new e({color:Z.foreground,dim:!0}))})}),m=new H6({padding:F0.only({left:2,right:2,top:1,bottom:1}),child:new k1({text:new i(void 0,k,[new i("Esc",R),new i(": close • ",k),new i("↑↓",R),new i("/",k),new i("j k",R),new i(": scroll",k)])})}),o=new q8({autofocus:!0,onKey:this.handleKeyEvent,child:new $Y6({scrollOffset:this.scrollOffset,onMeasured:(J1,H1)=>{this.updateScrollBounds(J1,H1)},child:new H6({padding:F0.symmetric(2,1),child:new k1({text:new i("",void 0,y)})})})}),X1=new qJ({controller:null,getScrollInfo:this.getScrollbarInfo,thickness:1,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack}),t=new x9({children:[new H6({padding:F0.only({right:1}),child:o}),new S5({right:0,top:0,bottom:0,child:new X0({width:1,child:X1})})]}),p=new v0({crossAxisAlignment:"stretch",children:[b,d,new e6({child:t}),d,m]});return new f4({child:new g0({constraints:new I6(D,D,0,U),decoration:{color:Z.background,border:A4.all(new q4(Z.primary,1,"rounded"))},child:p})})}}class $Y6 extends j5{scrollOffset;onMeasured;constructor({child:J,scrollOffset:Q=0,onMeasured:Z,key:Y}){super(Y?{child:J,key:Y}:{child:J});this.scrollOffset=Q,this.onMeasured=Z}createRenderObject(){return new GY6(this.scrollOffset,this.onMeasured)}updateRenderObject(J){J.updateProperties(this.scrollOffset,this.onMeasured)}}class GY6 extends F4{_scrollOffset;_onMeasured;constructor(J,Q){super();this._scrollOffset=J,this._onMeasured=Q}updateProperties(J,Q){if(this._scrollOffset!==J)this._scrollOffset=J,this.markNeedsPaint();this._onMeasured=Q}performLayout(){let J=this._lastConstraints;if(M4(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(J.minWidth,J.minHeight),super.performLayout();return}let Q=this.children[0],Z=new I6(J.minWidth,J.maxWidth,0,Number.POSITIVE_INFINITY);Q.layout(Z);let Y=-this._scrollOffset;if(Q.setOffset(0,Y),this.setSize(J.maxWidth,J.maxHeight),this._onMeasured)this._onMeasured(Q.size.height,this.size.height);super.performLayout()}paint(J,Q=0,Z=0){for(let Y of this.children)if("offset"in Y&&"paint"in Y){let X=new dY(J,Q,Z,this.size.width,this.size.height);Y.paint(X,Q,Z)}}}class Fy1 extends T6{error;ampURL;onResponse;constructor({key:J,error:Q,ampURL:Z,onResponse:Y}){super({key:J});this.error=Q,this.ampURL=Z,this.onResponse=Y}build(J){let Z=U4.of(J).colorScheme,Y=x61(this.error,this.ampURL),X=Y.options.map((V)=>({value:V,label:$86(V)})),G=this.buildBodyWithLinks(Y.description);return new bZ({title:Y.title,body:G,options:X,onSelect:(V)=>{this.onResponse(V??"dismiss")},borderColor:Z.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}buildBodyWithLinks(J){if(!J)return;let Q=/(https?:\/\/[^\s]+)/g,Z=J.split(Q),Y=J.match(Q);if(!Y||Y.length===0)return J;let X=[],G=0;for(let V of Z){if(V==="")continue;if(Y.includes(V))X.push(new u5({uri:V,text:V})),G++;else X.push(new k1({text:new i(V)}))}return new A6({children:X})}}var wM8=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]}]},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]}]},{description:"Delete word forward",methods:[{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]}],EM8=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class v91 extends T6{items;renderRow;constructor({items:J,renderRow:Q}){super();this.items=J,this.renderRow=Q}build(J){let Z=v4.of(J).size.width,Y=50,X=Z<50,G=[];for(let V of this.items){let[K,q]=this.renderRow(V),W;if(X)W=new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:[K,new H6({padding:F0.only({left:4}),child:q})]});else W=new A6({crossAxisAlignment:"start",children:[new e6({flex:1,child:K}),new X0({width:1}),new e6({flex:1,child:q})]});G.push(new H6({padding:F0.horizontal(6),child:W}))}return new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:G})}}class Uy1 extends d0{commands;constructor({key:J,commands:Q}){super(J?{key:J}:{});this.commands=Q}createState(){return new VY6}}class VY6 extends u0{scrollController;initState(){this.scrollController=new N7,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(J){let Z=U4.of(J).colorScheme,X=Y6.of(J).app,G=v4.of(J),V=new e({color:Z.primary,bold:!0}),K=new e({color:Z.secondary,bold:!0}),q=new e({color:X.keybind}),W=new e({color:X.command}),H=new e({color:Z.foreground}),z=new e({color:Z.foreground}),U=G.size.width,D=G.size.height,M=U-4,L=D-4,A=Math.max(40,Math.min(80,M)),E=new Map(this.widget.commands.map((x)=>[x.id,x])),P=["help","new","continue","thread-previous","thread-next","thread-parent","handoff","browser","visibility","mention-thread","editor","queue","dequeue","toggle-agent-mode","permissions","settings","generate-agent-file","agent-files","ide","quit"].map((x)=>E.get(x)).filter((x)=>x!==void 0),R=new _5({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new I6(A,A,0,Number.POSITIVE_INFINITY),child:new v0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new f4({child:new k1({text:new i(`Amp CLI - Help & Keyboard Shortcuts
4723
4723
  `,V)})}),new X0({height:1}),new H6({padding:F0.horizontal(2),child:new k1({text:new i(`Editor Shortcuts
4724
4724
  `,K)})}),new v91({items:wM8,renderRow:(x)=>{let b=[];for(let m of x.methods){let o=this.buildCleanKeyCombination(m);b.push(o)}let d=b.join(", ");return[new k1({text:new i(d,q)}),new k1({text:new i(x.description,H)})]}}),new X0({height:1}),new H6({padding:F0.horizontal(2),child:new k1({text:new i(`Scrolling & Navigation
4725
4725
  `,K)})}),new v91({items:EM8,renderRow:(x)=>{let b=[];for(let m of x.methods){let o=this.buildCleanKeyCombination(m);b.push(o)}let d=b.join(", ");return[new k1({text:new i(d,q)}),new k1({text:new i(x.description,H)})]}}),new X0({height:1}),new H6({padding:F0.horizontal(2),child:new k1({text:new i(`Command Palette Commands
@@ -4735,7 +4735,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
4735
4735
  `)?`${K}...`:X,W=new e({color:F1.index(8)}),H=[new i(q,W)];if(V>0){let z=new e({color:Z.success});for(let U=1;U<=V;U++)H.push(new i(" ")),H.push(new i(`[${U}]`,z))}return new H6({padding:F0.only({bottom:0}),child:new A6({crossAxisAlignment:"start",children:[new H6({padding:F0.only({right:1}),child:new k1({text:new i("•",new e({color:F1.index(8)}))})}),new e6({child:new k1({text:new i("",void 0,H)})})]})})}}class xy1 extends d0{createState(){return new gY6}}class gY6 extends u0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new e({color:F1.red}),Z=new e({color:this._visible?F1.red:F1.transparent()});return new A6({children:[new k1({text:new i("⏺",Z)}),new X0({width:1}),new k1({text:new i("Replay",Q)})]})}}class vy1 extends T6{entry;width;constructor({key:J,entry:Q,width:Z}){super({key:J});this.entry=Q,this.width=Z}build(J){let Z=Y6.of(J).colors.mutedForeground,Y=this.entry,X=Y.authors[0]?.name||"Community";if(X.includes("@"))X=X.split("@")[0]??X;let G=" · ",V=50,K=this.truncateToWidth(Y.title,V),q=`${G}${K}`,W=Math.max(1,this.width-q.length-2),H=Y.description.replace(/\s+/g," ").trim(),z=`@${X}: ${H}`,U=this.truncateToWidth(z,W),D=new k1({text:new i(U,new e({color:Z,dim:!0}))}),M=new k1({text:new i(q,new e({color:Z,dim:!0}))});return new $8({onClick:()=>GJ(J,Y.link),cursor:"pointer",child:new X0({width:this.width,height:1,child:new H6({padding:F0.horizontal(1),child:new A6({children:[new e6({child:new xB(new X0({width:W,height:1,child:D}))}),M]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}o0();function CL8(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/3600000),X=Math.floor(Y/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class fy1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Z)=>{let Y=this.threadHistoryService.observeThreadList().subscribe((X)=>{Y.unsubscribe(),Z(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Y)=>{if(!Q.trim())return!0;let X=Y.title?.toLowerCase()||"untitled",G=Y.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Y)=>{let X=new Date(Y.userLastInteractedAt),G=CL8(X),V=Y.id.slice(-8),K=Y.env?.initial.trees?.[0]?.uri;return{id:Y.id,title:Y.title||"Untitled",updatedAt:new Date(Y.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Y.title||"Untitled",shortThreadID:V},diffStats:Y.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Y.parentRelationships}})}}B0();R8();class hy1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new N7;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){v.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(rD()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function mY6(J,Q){switch(J){case"update-available":return[new i("A newer Amp is available. Run ",new e({color:Q.foreground,dim:!0})),new i("amp update",new e({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new i("Update complete, run ",new e({color:Q.foreground,dim:!0})),new i("amp update",new e({color:Q.warning})),new i(" to see warnings",new e({color:Q.foreground,dim:!0}))];case"update-error":return[new i("Update failed, run ",new e({color:Q.foreground,dim:!0})),new i("amp update",new e({color:Q.warning})),new i(" to see warnings",new e({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function yL8(J){return new Promise((Q)=>{SL8("git",["branch","--show-current"],{cwd:J},(Z,Y)=>{if(Z){Q(null);return}let X=Y.trim();Q(X||null)})})}class aY6 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new cy1}}class cy1 extends u0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;threadCostInfoLastUsageLedgerLength=0;lastInferenceState=void 0;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new hy1;previewThread=null;planScrollController=(()=>{let J=new N7;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new N7;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new F8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new F8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;mcpServers=[];mcpServersSubscription=null;cacheTimerState=null;cacheTimerSubscription=null;agentModeController=null;freeTierStatus=void 0;agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new PS1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];async initThreadFeed(){let J=await V6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Z=Q.includes("localhost")||Q.includes("127.0.0.1");try{let V=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(V.ok){let K=V.result,q="user"in K?K.user:K;this.currentUserInfo={username:q.username??void 0,displayName:q.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Z&&K.team?.id!==W)return}else return}catch(V){v.debug("Failed to fetch user info for thread feed filtering",V);return}let Y="/threads.rss",X=async(V,K)=>{let q=V instanceof Request?V.url:V.toString();return n2(q,K,this.widget.dependencies.configService)},G=la0();G.get("entries").then((V)=>{if(V){let K=this.filterEntries(V);if(this.threadFeedEntries=K,K.length>0&&!this.currentThreadFeedEntry){let q=[...K].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new uj1(G,X,{url:Y}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let K=this.filterEntries(V);if(K.length>0){this.threadFeedEntries=[...K,...this.threadFeedEntries];let q=[...K].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(K){v.error("Thread feed: error in next handler",K)}},error:(V)=>{v.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Z}=this.currentUserInfo;return J.filter((Y)=>{return!Y.authors.some((X)=>{let G=X.name;if(!G)return!1;return Q&&G===Q||Z&&G===Z||Q&&G.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Z,baseWpm:Y}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Z){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
4736
4736
  `);if(W)await this.replayTypeMessage(W,Y)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let D=J.thread.id;this.getMessageScrollController(D).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),a8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Z=J.split(/(?<=\s)/),Y=60000/Q;for(let X of Z){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Y/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Y=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Z,...Y].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new i(this.submitDisabledHint,new e({color:J.foreground,dim:!0}));if(this.isExiting)return new i("Exiting...",new e({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new i("",void 0,[new i("Ctrl+C",new e({color:Q.keybind})),new i(" again to exit",new e({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new i("",void 0,[new i("Esc",new e({color:Q.keybind})),new i(" again to clear input",new e({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new i("",void 0,[new i("Escape",new e({color:Q.keybind})),new i(" to close help",new e({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),G=dy1(X);return new i("",void 0,[new i("Images aren't supported in ",new e({color:J.warning,dim:!1})),new i(X,new e({color:G})),new i(" mode.",new e({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new i("",void 0,[new i("Esc",new e({color:Q.keybind})),new i(" again to cancel",new e({color:J.foreground,dim:!0}))]);return new i("",void 0,[new i("Esc",new e({color:Q.keybind})),new i(" to cancel",new e({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new i(this.statusMessage,new e({color:J.foreground,dim:!0}));let Z=mY6(this.updateState,J);if(Z)return new i("",void 0,Z);let Y=this.widget.dependencies.worker.thread;if(Y.agentMode==="plan"&&CA(Y))return new i("",void 0,[new i("Ctrl+O",new e({color:Q.keybind})),new i(" → Execute Plan",new e({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){v.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:Y}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await J2.getOrCreateForThread(Z,X),K=await VR(V,Y,G-1);await this.switchToExistingThread(K)}catch(V){v.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:Y}=this.widget.dependencies,X=Z.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),this.widget.dependencies.history.add(Q);let V=fB(Q);if(V)await Y.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){v.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Y.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){v.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(f2)}catch(Z){return v.error("Failed to get affected files:",Z),[]}};textController=new R$;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new N7);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let Y=this.searchElementTreeByKey(J.child,Q);if(Y)return Y}if(J?.children)for(let Y of J.children){let X=this.searchElementTreeByKey(Y,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),Y=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(sC1(Y))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new p7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Z=fB(J)?.visibility;if(Z!==this.currentShellModeStatus)this.currentShellModeStatus=Z,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),m8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new $y1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ky1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Z}=this.widget.dependencies;if(!Q.mainThread)return null;let Y=h0.file(process.cwd()),X=R6(Y);return{recentThreadIDs:Z,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>G.abort(new w91("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W},this.widget.dependencies.configService,G.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw G.signal.reason;throw U}}catch(H){return v.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await ws({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=Q.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let V=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(V)}catch(G){v.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.clustersForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features??[],showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new fy1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.clustersForPicker=pZ6(Q),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await yL8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Z=Date.now(),Y=`bash-${Z}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===vB).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Y))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Y?{...q,toolRun:V}:q);else{let q={id:Y,args:X,toolRun:V,startTime:Z,abortController:G,hidden:Q===vB};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=G76(()=>{let J=this.widget.dependencies.threadID;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(Q.ok)this.setState(()=>{this.threadCostInfo=Q.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J,Q)=>{let Z=J!==this.threadCostInfoLastUsageLedgerLength,Y=Q==="idle"&&this.lastInferenceState==="running";if(this.threadCostInfoLastUsageLedgerLength=J,this.lastInferenceState=Q,Z||Y)this.fetchThreadCostInfo()};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=800,Q=16,Z=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Z),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Ky(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=nF)return!1;let Z=XC(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Z}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)v.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{v.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:Y,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await BV(W);try{let H=await Z(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")v.error("Failed to read temporary file",H)}try{await Y(W),await X(q)}catch(H){v.warn("Failed to clean up temporary file",H)}}catch(q){v.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=fB(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};initState(){if(gY.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();a8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),a8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),a8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{m8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),V6(this.widget.dependencies.configService.config).then((Z)=>{this.paletteConfig=Z,this.agentModeController=new nj1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus?{canUseAmpFree:this.freeTierStatus.canUseAmpFree,eligible:this.freeTierStatus.eligible,workspaceAllowsAmpFree:this.freeTierStatus.workspaceAllowsAmpFree}:void 0,initialSettings:Z.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.adSubscription=Aj1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let Z=this.agentModeController?.getMode();return(Z&&P9(Z)||this.randomAd===null)&&Lj1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let Y=_L8(16).toString("hex");this.lastAdImpressionId=Y,Promise.resolve().then(() => (e91(),t91)).then(({recordAdEvent:X})=>{let G=this.widget.dependencies.worker.thread,V=G.messages[G.messages.length-1];X("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:G.id,messageId:V?.messageId,impressionId:Y,placement:"tui",matchType:Z.metadata?.matchType,matchedPatterns:Z.metadata?.matchedPatterns,candidateAdPoolCount:Z.metadata?.candidateAdPoolCount,clientRegion:Z.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Z}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Z)=>{this.setState(()=>{this.pendingMCPServers=Z})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Z)=>{this.setState(()=>{this.mcpServers=Z})}),this.cacheTimerSubscription=this.widget.dependencies.worker.cacheTimer.subscribe((Z)=>{this.setState(()=>{this.cacheTimerState=Z})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let Y=this.widget.dependencies.getCurrentWorker();if(!Y){v.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),v.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),v.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.mysteriousMessageSubscription=M41(this.widget.dependencies.configService).pipe(f5((Z)=>Z!=="pending"),Q6((Z)=>L41(Z)?Z.mysteriousMessage??null:null),N4((Z,Y)=>Z?.id===Y?.id)).subscribe((Z)=>{this.setState(()=>{if(Z?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Z,Z&&!this.mysterySequenceManager)this.mysterySequenceManager=new F81(new Map([[new z81(cy1.MYSTERY_SEQUENCE),new wm]])),this.mysteryKeyInterceptorUnsubscribe=a8.instance.addKeyInterceptor((Y)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Y);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Z)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener();let Q=this.widget.dependencies.threadID;if(this.threadCostInfoThreadID!==void 0&&this.threadCostInfoThreadID!==Q)this.threadCostInfo=void 0,this.threadCostInfoThreadID=void 0,this.threadCostInfoLastUsageLedgerLength=0,this.fetchThreadCostInfo();let{threadState:Z}=this.widget.dependencies;this.maybeRefetchThreadCostInfo(Z.mainThread?.usageLedger?.events.length??0,Z.viewState.state==="active"?Z.viewState.inferenceState:void 0)}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.cacheTimerSubscription)this.cacheTimerSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(sC1("")),this.shouldUseProgressBar())process.stdout.write(z56())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Y=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Y.length===0)return null;let X=Y[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){v.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){v.error("No tool use block found in confirmation");return}if(J==="allow-all-session")LG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else v.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await GJ(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(VY))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,VY],"global")}let Y=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Z.id,value:{accepted:Y}};if(Q.subthreadID)await(await J2.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){v.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.agentModeController?.setMode("smart"),this.setState(()=>{this.dismissedEphemeralErrorKey=null}),Z41({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette({type:"normal",commandId:"handoff"});break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await BV(Q.getSettingsFilePath())}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await J2.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Z=!0}=Q;if(Z){let Y=this.widget.dependencies.worker.thread.id;if(Y!==J)this.recordNavigation(Y)}try{v.info(`[switchToExistingThread] Switching to thread: ${J}`);let Y=await this.widget.dependencies.switchToThread(J);if(v.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Y.thread.agentMode}`),this.widget.dependencies.worker=Y,this.widget.dependencies.threadID=Y.thread.id,this.widget.dependencies.switchWorker(Y),v.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),Y.thread.draft)if(v.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Y.thread.draft==="string")this.textController.insertText(Y.thread.draft);else{let X=Y.thread.draft.filter((K)=>K.type==="text"),G=Y.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
4737
4737
  `);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Y){throw v.error("Failed to switch to thread:",J,Y),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Z=m2(Q.thread)===0,Y=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&Y!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Z)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Y}}),Z)Z41({agentMode:Y});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((Y)=>Y.type==="handoff"&&Y.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();Z41({agentMode:Q}).catch((Z)=>{v.warn("Failed to save session state on exit:",Z)}).finally(()=>{a8.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=kL8();if(J===Q)return"~";if(J.startsWith(Q+dm.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(dm.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(dm.sep),"…",Q.slice(-2).join(dm.sep)].join(dm.sep)}build(J){let Q=v4.of(J),Z=Y6.of(J),Y=Z.base;this.themeColors=Y;let{colors:X,app:G}=Z;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&P9(V.thread.agentMode),q=K&&this.randomAd!==null,W=!K&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=Boolean(q),{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),D=this.widget.dependencies.replayMode,M=Boolean(D),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,I=z.todosList;if(M){let b6={...D.thread,messages:this.replayDisplayedMessages};L=AC(b6).items,A=b6,E={};let l6=pE({messages:this.replayDisplayedMessages});I=Array.isArray(l6)?l6:[]}let P=A?.id,R=A,k=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(b6)=>new D91({key:new p7(`preview-message-view-${b6.id}`),items:AC(b6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:b6,focusNode:new F8({debugLabel:"PreviewFocus"})}),x=this.previewThread,b=x?x.messages.length>2000?new v0({mainAxisSize:"max",children:[new e6({child:new X0}),new H6({padding:F0.all(2),child:new f4({child:new k1({text:new i("Thread too long for preview",new e({color:X.mutedForeground,dim:!0}))})})})]}):y(x):k?new O91({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal}):new D91({key:P?new p7(`message-view-${P}`):void 0,items:L,subagentToolsByParentID:E,controller:P?this.getMessageScrollController(P):new N7,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:R,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),d=Math.max(Math.floor(Q.size.height*0.4),12),m=this.getCurrentEphemeralError(),o=Q.size.width<40,X1=z.mainThread?SM0(z.mainThread):void 0,t=$91(J),p=this.buildBottomWidget(m,U,X,Z,z,I,d,H,M,X1,this.cacheTimerState??void 0,Q,t),J1=new _81({threadViewState:z.viewState,threadTokenUsage:X1,threadID:P??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:o,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),H1=new j81({bashInvocations:this.bashInvocations}),U1=[];if(W&&this.currentThreadFeedEntry)U1.push(new vy1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let r=this.getEffectiveAgentMode(),n=this.currentShellModeStatus,l=dy1(r),W1=!n?r.length+1:0,_1=Q.capabilities.animationSupport,s=_1==="disabled"?0:_1==="slow"?30:60,m1=NK(r)?.uiHints?.fasterAnimation?3:1,S1=s>0&&this.agentModePulseSeq>0?new x9({children:[p,new S5({top:0,left:1,right:1,height:1,child:new Sy1({color:l,trigger:this.agentModePulseSeq,fps:s,speed:m1,leftOffset:W1})})]}):p;U1.push(new e6({child:b}),H1);let I0=new x9({children:[new v0({mainAxisSize:"min",children:[q?new gk1({ad:this.randomAd,onButtonClick:async()=>{let b6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (e91(),t91)).then(({recordAdEvent:B9})=>{let O4=this.widget.dependencies.worker.thread,UJ=O4.messages[O4.messages.length-1];B9("clicked",{adId:b6.id,advertiserId:b6.advertiserId,threadId:O4.id,messageId:UJ?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:b6.metadata?.matchType,matchedPatterns:b6.metadata?.matchedPatterns,candidateAdPoolCount:b6.metadata?.candidateAdPoolCount,clientRegion:b6.metadata?.clientRegion})});if(!await GJ(this.context,b6.shortDestinationUrl)){let O4=a8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:O4,url:b6.shortDestinationUrl}})}}}):new X0({height:0}),new g0({constraints:new I6(0,Q.size.width,0,d),child:S1})]}),H?new S5({top:0,left:0,right:0,child:new sY6({userHeight:this.bottomGridUserHeight,maxHeight:d,onInitializeHeight:(b6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(b6,d)})},onDrag:(b6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(b6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let l6=Math.floor(b6.localPosition.y)-this.bottomGridDragStartY,B9=Math.max(4,this.bottomGridDragStartHeight-l6),O4=Math.min(B9,d),UJ=Math.floor(O4);if(this.bottomGridUserHeight!==UJ)this.setState(()=>{this.bottomGridUserHeight=UJ})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new X0({height:0})]});U1.push(I0,new X0({height:1,child:new H6({padding:F0.horizontal(1),child:J1})}));let T1=new v0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:U1}),z1=M&&D?.showIndicator!==!1?new x9({children:[T1,new S5({top:0,left:0,child:new xy1})]}):T1,Z1=new A8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((l6)=>{v.error("Failed to mark message as interrupted:",l6)}),this.cancelStreamingMessage().catch((l6)=>{v.error("Failed to cancel streaming message:",l6)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return v.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),O1=new A8(()=>{return this.onExitPressed(),"handled"}),A1=new A8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),R1=new A8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),j1=new A8(()=>{return WJ.instance.toggleAll(),"handled"}),c1=new A8(()=>{return this.widget.dependencies.configService.getLatest().then((b6)=>{LG("internal.showDetailedCosts",!(b6.settings["internal.showDetailedCosts"]??!1))}),"handled"}),g1=new A8(()=>{return a8.instance.toggleFrameStatsOverlay(),"handled"}),s1=new A8(()=>{return a8.instance.tuiInstance.getScreen().markForRefresh(),m8.instance.requestFrame(),"handled"}),K0=new A8(()=>{return this.toggleAgentMode(),"handled"}),q0=new A8(()=>{let l6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(l6){let B9=Math.max(Math.floor(Q.size.height*0.4),10),O4=Q.size.height-B9;l6.animatePageUp(O4,100)}return"handled"}),k0=new A8(()=>{let l6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(l6){let B9=Math.max(Math.floor(Q.size.height*0.4),10),O4=Q.size.height-B9;l6.animatePageDown(O4,100)}return"handled"}),v6=new A8(()=>{let l6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(l6)l6.animateTo(0,100);return"handled"}),u6=new A8(()=>{let l6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(l6)l6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),e4=new A8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:b6}=this.widget.dependencies;if(!b6.mainThread?.messages.some((B9)=>B9.role==="user"||uE(B9)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),r8=new A8((b6)=>{if(b6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),a9=new A8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return E81().then(async(b6)=>{if(b6)try{this.handleInsertImage(b6)}finally{try{let{unlink:l6}=await import("node:fs/promises");await l6(b6)}catch{}}}),"handled"}),E0=new Map([[G4.ctrl("c"),new Bm],[G4.ctrl("l"),new Am],[G4.ctrl("o"),new L81],[G4.ctrl("v"),new Fm],[G4.alt("s"),new VC],[G4.ctrl("s"),new VC],[G4.alt("p"),new Lm],[G4.ctrl("r"),new Dm],[G4.alt("d"),new Mm],[G4.ctrl("t"),new Om],[G4.key("PageUp"),new B81],[G4.key("PageDown"),new N81],[G4.key("Home"),new D81],[G4.key("End"),new M81],[G4.key("Escape"),new Um],[G4.ctrl("p"),new KC("previous")],[G4.ctrl("n"),new KC("next")],[G4.key("Tab"),new Em]]);if(!v3())E0.set(G4.key("ArrowUp"),new Em);if(!1)E0.set(G4.alt("c"),new Nm);let Y4=new A8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),Z8=new A8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),u8=new A8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),Z7=new Map([[Um,Z1],[Am,s1],[VC,K0],[L81,Y4],[Fm,a9],[Nm,A1],[q81,R1],[Dm,j1],[Mm,c1],[Lm,g1],[Om,Z8],[Bm,O1],[B81,q0],[N81,k0],[D81,v6],[M81,u6],[Em,e4],[KC,r8],[wm,u8]]),s8=[z1];if(this.isShowingConsoleOverlay)s8.push(new Hy1);if(this.isShowingHelp&&this.paletteConfig)s8.push(new Uy1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)s8.push(new $k1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)s8.push(new yy1({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)s8.push(new mk1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(b6)=>{let l6=this.adActionModal.url;if(b6==="copy")try{await a8.instance.tuiInstance.clipboard.writeText(l6),this.setState(()=>{this.displayMessage=new lY("Link copied to clipboard")})}catch(B9){v.error("Failed to copy to clipboard",{error:B9}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:b6}=this.widget.dependencies;s8.push(new _y1({servers:this.pendingMCPServers,onAlwaysTrust:b6.trustAlways.bind(b6),onTrustOnce:b6.trustOnce.bind(b6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:b6.deny.bind(b6)}))}if(this.isShowingFileChangesOverlay)s8.push(new fS1({threadData:z}));if(this.isShowingContextDetailOverlay){let b6=this.threadCostInfo?.costBreakdownURL;s8.push(new zy1({thread:z.mainThread??void 0,tokenUsage:X1??void 0,cacheTimerState:this.cacheTimerState??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:b6?()=>{GJ(J,b6)}:void 0}))}if(this.isShowingConfirmationOverlay)s8.push(new qy1({details:this.confirmationOverlayContent}));let Y7=this.getCommandPaletteContext(J);if(Y7&&this.isShowingPalette&&this.paletteConfig)s8.push(new f4({child:new Vy1({commandContext:Y7,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)s8.push(new Ny1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let y5=new x9({children:s8});if(this.isShowingJetBrainsInstaller)return new gA({child:new $J({actions:Z7,child:new cY({shortcuts:E0,debugLabel:"jetbrains-installer-shortcuts",child:new jy1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Jz({controller:this.toastController,child:new gA({child:new TS1({controller:this.toastController,child:new $J({actions:Z7,child:new cY({shortcuts:E0,debugLabel:"main-app-shortcuts",child:y5})})})})})}buildScrollableTodoList(J,Q,Z){return new oY6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Z})}buildBottomWidget(J,Q,Z,Y,X,G,V,K,q,W,H,z,U){if(J)return new Fy1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Wy1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ky1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let D=R81(Y),M=this.agentModeController?.isInRestrictedFreeMode()??!1,L=new eA({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new dB],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Z,placeholder:q?"Press Ctrl+C to exit":M?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!M&&!this.isShowingStandalonePalette(),shellPromptRules:D,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:a8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let n=this.previousThreadIdForHint;if(n)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${n} `},onDoubleAtTrigger:q?void 0:()=>{let n=this.textController.text,l=this.textController.cursorPosition,_1=n.slice(0,l).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(_1!==-1){let s=this.textController.text,m1=s.slice(0,_1)+s.slice(_1+2);this.textController.text=m1,this.textController.cursorPosition=_1}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),A=X.mainThread?.queuedMessages??[],E=Array.isArray(G)&&G.length>0,I=Array.isArray(A)&&A.length>0,P=X.mainThread?.agentMode==="plan"&&CA(X.mainThread),R,k;if(P){if(R=new xB(new M91({thread:X.mainThread,onExecute:async()=>{let n=this.getCommandPaletteContext();if(n)await this.getPaletteCommands().execute("execute-plan",n,void 0,new AbortController)},onEdit:async()=>{try{let n=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:l}=await this.widget.dependencies.planFileManager.ensureSync(X.mainThread.id);a8.instance.tuiInstance.suspend();let{execSync:W1}=await import("child_process");W1(`${n} "${l}"`,{stdio:"inherit"}),a8.instance.tuiInstance.resume()}catch(n){v.error("Failed to edit plan",n),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:Y}),{clipBehavior:"antiAlias"}),I)k=new s91({queuedMessages:A});else if(E)k=this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y)}else R=I?new s91({queuedMessages:A}):void 0,k=E?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y):void 0;let y=[],x=this.currentShellModeStatus;if(x)y.push({child:new k1({text:new i(x==="hidden"?"shell mode (incognito)":"shell mode",new e({color:x==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});let d=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,m=this.agentModeController?.getVisibleModes()??[];if(!x&&m.length>1){let n=this.previewThread,l=n?n.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),W1=dy1(l),_1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,s=n??_1.thread,m1=m2(s)>0,S1=this.agentModeSlideProgress!==null,I0,T1;if(S1){I0="top-left";let z1=z.size.width-l.length-4-d;T1=Math.floor(this.agentModeSlideProgress*z1)}else if(m1)I0="top-right",T1=d;else I0="top-left",T1=void 0;if(n)y.push({child:new k1({text:new i(l,new e({color:W1}))}),position:I0,offsetX:T1});else{let r1=!m1&&!S1,z1=new k1({text:new i(l,new e({color:W1}))});y.push({child:r1?new $8({child:z1,onClick:this.toggleAgentMode,cursor:"pointer"}):z1,position:I0,offsetX:T1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let n=this.connectedClientsStatus,l=n.mode||"disconnected",W1=!!n.errorMessage,_1=n.clientID||"unknown",s,m1;if(W1)s="●",m1=F1.red;else if(l==="presence")s="○",m1=F1.yellow;else if(l==="connected"&&n.connected)s="●",m1=F1.green;else s="○",m1=F1.yellow;let S1=this.connectedClientsStatusExpanded?`${_1} ${s}`:s;y.push({child:new $8({child:new k1({text:new i(S1,new e({color:m1}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let o=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,X1;if(o)X1=h0.parse(o).fsPath;else X1=process.cwd();let t=this.toHomeRelative(X1),p=this.shorten(t),J1=!q&&this.currentGitBranch?`${p} (${this.currentGitBranch})`:p;y.push({child:new k1({text:new i(J1,new e({color:Z.foreground,dim:!0}))}),position:"bottom-right"});let H1=this.previewThread,U1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(m2(U1.thread)>0&&!x&&!H1){let n=[],l=new e({color:Z.foreground,dim:!0}),W1=new i(" · ",l);if(W){let _1=W.totalInputTokens/W.maxInputTokens,s=Math.round(_1*100),m1=Math.max(0,Math.min(s,100)),S1=S81(_1,W.maxInputTokens),I0=l;if(S1==="danger")I0=new e({color:Z.destructive});else if(S1==="warning")I0=new e({color:Z.warning});else if(S1==="recommendation")I0=new e({color:Y.app.recommendation});let T1=Math.round(W.maxInputTokens/1000);n.push(new i(`${m1}% of ${T1}k`,I0))}if(U&&this.threadCostInfo?.totalCostUSD!=null&&this.threadCostInfo.totalCostUSD>0){if(n.length>0)n.push(W1);if(this.threadCostInfo.isFreeMode)n.push(new i(RA(this.threadCostInfo.totalCostUSD),new e({strikethrough:!0,color:Z.foreground,dim:!0}))),n.push(new i(" free",l));else n.push(new i(RA(this.threadCostInfo.totalCostUSD),l))}if(U&&H){let _1=X.viewState.state==="active"&&X.viewState.inferenceState==="idle",s=$76(H,_1);if(s){if(n.length>0)n.push(W1);let m1=l;if(s.urgency==="warning")m1=new e({color:Z.warning});n.push(new i(s.text,m1))}}if(n.length>0){let _1=new k1({text:new i("",void 0,n)});y.push({child:U?new $8({child:_1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):_1,position:"top-left"})}}return new _S1({leftChild:new e6({child:L}),rightChild1:R,rightChild2:k,maxHeight:V,overlayTexts:y,borderColor:M||!this.isTextfieldAndAutocompleteFocused?F1.index(8):void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(n)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(n,V)})},onDrag:(n)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(n.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let l=Math.floor(n.localPosition.y)-this.bottomGridDragStartY,W1=Math.max(4,this.bottomGridDragStartHeight-l),_1=Math.min(W1,V),s=Math.floor(_1);if(this.bottomGridUserHeight!==s)this.setState(()=>{this.bottomGridUserHeight=s})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function ly1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)a8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Y=()=>null,G=!1,V=new aH(G,1000,J.inspectorPort),K=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,q=new hk1({threadService:J.threadService,worker:J.worker,builder:(A,E,I,P,R,k)=>{if(Y=R,J.threadDependencies&&K)lj1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((b)=>{v.error("Failed to start automatic presence:",b)});let y=R(),x={...J,worker:y,threadID:y.thread.id};return new aY6({...x,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:R,recentThreadIDs:k})}}),W=new kS1({configService:J.configService,child:q}),H=new Gk1({configService:J.configService,child:W}),z=new MS1(H),U=new Y6({data:qC.fromBaseTheme(T$.default()),child:z});try{await zj1(U,{onRootElementMounted:(A)=>{if(v.info("TUI input ready for user interaction"),G)V.start(A)}})}finally{if(G)V.stop();if(J.threadDependencies&&K){let{stopGlobalSession:A}=await Promise.resolve().then(() => (ij1(),N36));A()}}let M=Y()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;h36(L,A,J.stdout)}}function dy1(J){let Z=NK(J)?.uiHints?.secondaryColor;if(Z)return F1.rgb(Z.r,Z.g,Z.b);return xL8(J)}class oY6 extends d0{props;constructor(J){super();this.props=J}createState(){return new rY6}}class rY6 extends u0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Z,appTheme:Y}=this.widget.props;return new A6({crossAxisAlignment:"stretch",children:[new e6({child:new _5({controller:Z,autofocus:!1,child:new bk1({todos:Q})})}),new qJ({controller:Z,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Z,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let G=Y.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class sY6 extends T6{props;constructor(J){super();this.props=J}build(J){return new $8({child:new X0({height:1}),cursor:C9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function xL8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Y=Math.abs(Q)%Z.length;return F1.index(Z[Y])}Hj1();try{if(process.platform==="win32")await Promise.resolve().then(() => q6(dC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){g$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
4738
- `)}var Av1=Lv1.join(rF0||Lv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function QI8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function h$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")LG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")LG("model.sonnet",Q.useSonnet)}async function wv1(J){try{await tE8(Lv1.dirname(Av1),{recursive:!0}),await eE8(Av1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function ZI8(){try{return(await IV6(Av1,"utf-8")).trim()}catch(J){return null}}var OV6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??A$,description:`Custom settings file path (overrides the default location ${A$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${MC1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:v3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:vE.SMART.key,description:`Set the agent mode (${kX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:kX().map((J)=>J.mode)}],wV6=(J)=>("deprecated"in J)&&J.deprecated===!0,YI8=(J)=>("hidden"in J)&&J.hidden===!0,XI8=(J)=>("default"in J),$I8=(J)=>("default"in J)?J.default:void 0;function GI8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new I8(L$.unknownCommand(Z),1,V)}}var PV6=null;function pI5(){return PV6}function zu(J){return{...J,getThreadEnvironment:_61,vfs:qC0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new ex(J.fileSystem),generateThreadTitle:ta0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Ev1=h0.file(JI8.homedir()),TV6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(Ev1,".config");async function b$(J,Q){mM0("0.0.1764878483-g1dd0b0");let Z=Kz1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([h0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Ev1,userConfigDir:TV6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (e91(),t91));Y(Z);let X=await Z.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=Qe0({configService:Z}),K=new Map,q=()=>K.clear(),W=new EB1(Z,J.settings.getWorkspaceRootPath()),H=NR0({configService:Z,trustStore:W,createOAuthProvider:async(t,p,J1)=>{let H1=`${t}:${p}`,U1=K.get(H1);if(U1)return v.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),U1;v.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let r=(async()=>{let n=new UM(J.secrets),l=await n.getClientInfo(t,p),W1=J1?.scopes??l?.scopes,_1=new lU1({storage:n,serverName:t,serverUrl:p,clientId:J1?.clientId??l?.clientId,clientSecret:J1?.clientSecret??l?.clientSecret,scopes:W1});return v.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(J1?.clientId??l?.clientId),willUseDCR:!(J1?.clientId??l?.clientId),scopes:W1}),_1})();return K.set(H1,r),r}}),z=k01({configService:Z,filesystem:i8,spawn:JA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (AV6(),LV6)),M;if(J.executeMode){let t=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,J1]of t.initErrors)v.warn(`${p} provider initialization slow or failed:`,J1)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&G96())cE("VS Code");else if(Q.ide&&V96())cE("Neovim");if(J.executeMode)uM0(!0);let L,A=V3.status.pipe(Q6((t)=>Boolean(t.connected&&t.authenticated)),N4()).subscribe((t)=>{if(t){if(!L)L=G.registerTool(sr0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let t=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new p61(process.cwd(),{alwaysIncludePaths:t},!0)}else E=new class extends p61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(D5.write(`No API key found. Starting login flow...
4738
+ `)}var Av1=Lv1.join(rF0||Lv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function QI8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function h$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")LG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")LG("model.sonnet",Q.useSonnet)}async function wv1(J){try{await tE8(Lv1.dirname(Av1),{recursive:!0}),await eE8(Av1,J,"utf-8")}catch(Q){v.debug("Failed to save last thread ID",Q)}}async function ZI8(){try{return(await IV6(Av1,"utf-8")).trim()}catch(J){return null}}var OV6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??A$,description:`Custom settings file path (overrides the default location ${A$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(v).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${MC1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:v3(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:vE.SMART.key,description:`Set the agent mode (${kX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:kX().map((J)=>J.mode)}],wV6=(J)=>("deprecated"in J)&&J.deprecated===!0,YI8=(J)=>("hidden"in J)&&J.hidden===!0,XI8=(J)=>("default"in J),$I8=(J)=>("default"in J)?J.default:void 0;function GI8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new I8(L$.unknownCommand(Z),1,V)}}var PV6=null;function pI5(){return PV6}function zu(J){return{...J,getThreadEnvironment:_61,vfs:qC0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new ex(J.fileSystem),generateThreadTitle:ta0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Ev1=h0.file(JI8.homedir()),TV6=process.env.XDG_CONFIG_HOME?h0.file(process.env.XDG_CONFIG_HOME):i0.joinPath(Ev1,".config");async function b$(J,Q){mM0("0.0.1764892237-g17504a");let Z=Kz1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([h0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Ev1,userConfigDir:TV6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (e91(),t91));Y(Z);let X=await Z.getLatest();v.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=Qe0({configService:Z}),K=new Map,q=()=>K.clear(),W=new EB1(Z,J.settings.getWorkspaceRootPath()),H=NR0({configService:Z,trustStore:W,createOAuthProvider:async(t,p,J1)=>{let H1=`${t}:${p}`,U1=K.get(H1);if(U1)return v.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),U1;v.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let r=(async()=>{let n=new UM(J.secrets),l=await n.getClientInfo(t,p),W1=J1?.scopes??l?.scopes,_1=new lU1({storage:n,serverName:t,serverUrl:p,clientId:J1?.clientId??l?.clientId,clientSecret:J1?.clientSecret??l?.clientSecret,scopes:W1});return v.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(J1?.clientId??l?.clientId),willUseDCR:!(J1?.clientId??l?.clientId),scopes:W1}),_1})();return K.set(H1,r),r}}),z=k01({configService:Z,filesystem:i8,spawn:JA}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (AV6(),LV6)),M;if(J.executeMode){let t=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,J1]of t.initErrors)v.warn(`${p} provider initialization slow or failed:`,J1)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)cE("JetBrains");else if(Q.ide&&G96())cE("VS Code");else if(Q.ide&&V96())cE("Neovim");if(J.executeMode)uM0(!0);let L,A=V3.status.pipe(Q6((t)=>Boolean(t.connected&&t.authenticated)),N4()).subscribe((t)=>{if(t){if(!L)L=G.registerTool(sr0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let t=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new p61(process.cwd(),{alwaysIncludePaths:t},!0)}else E=new class extends p61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(D5.write(`No API key found. Starting login flow...
4739
4739
  `),!await VI8(J))await OA(),process.exit(1)}let I=await mj0({isDevelopment:!1}),P=new AP1(I,Z),R=new NP1(I,{lazy:!0}),k=new yB1(P,(t,p)=>{let J1=J2.get(t);if(J1)J1.handle(p).catch((H1)=>{v.error("Failed to apply artifact delta",H1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,x=Ye0({playNotificationSound:async(t)=>{if(y){Ze0(t);let p=qj1(),J1=Wj1();if((!p||J1)&&X.settings["notifications.system.enabled"]!==!1){if(t==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(t==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:P,configService:Z});v.info("Starting Amp background services");let b=Jo0({threadService:P,threadHistoryService:R,configService:Z,isExtensionDevelopment:!1}),d;V3.status.subscribe((t)=>{d=t});let m=new s$1({workspaceRoots:[h0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return h0.parse(d.openFile)}catch(t){v.warn("Failed to parse current file URI",{uri:d.openFile,error:t});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let t=d.openFile;return d.visibleFiles.filter((p)=>p!==t).map((p)=>{try{return h0.parse(p)}catch(J1){return v.warn("Failed to parse visible file URI",{uri:p,error:J1}),null}}).filter((p)=>p!==null)}}),o=new Fj1,X1={codebaseContextService:m,configService:Z,toolService:G,mcpService:H,trustStore:W,threadService:P,threadHistoryService:R,threadSyncService:b,planFileManager:k,threadStorage:I,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:x,fileSystem:Q.jetbrains||Q.ide?GC0:i8,terminal:o};return{...X1,async asyncDispose(){if(X1.mcpService.hasAuthenticatingClients())v.info("Waiting for OAuth authentication to complete before exit..."),await X1.mcpService.waitForAuthentication();for(let t of M.values())t.dispose();await X1.mcpService.dispose(),q(),await X1.threadService.asyncDispose(),X1.configService.unsubscribe(),V(),X1.fuzzyServer.dispose(),X1.threadSyncService.dispose(),X1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function VI8(J){if(!J.executeMode){if(!await uC1("Would you like to log in to Amp? [(y)es, (n)o]: "))return D5.write(`Login cancelled. Run the command again to retry.
4740
4740
  `),!1}return await RV6(J)}async function RV6(J){let Q=sE8(32).toString("hex"),Z=await mC1(J.ampURL,Q),Y=new AbortController;try{await jW(Z,Y.signal)}catch(G){v.error("Error opening browser",{error:G})}let X=await mC1(J.ampURL,Q,!1);D5.write(`If your browser does not open automatically, visit:
4741
4741
 
@@ -4745,7 +4745,7 @@ ${_4.blue.bold(X)}
4745
4745
  Login successful! You can now use the Amp CLI.
4746
4746
  `),!0}catch(G){return v.error("Login failed",{error:G}),g$.write(`
4747
4747
  Login failed: ${G instanceof Error?G.message:String(G)}
4748
- `),!1}}function KI8(){let J=new qA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)jR(),process.exit(0);let z=H.originalError??H;e46(z)}),J.option("-V, --version","Print the version number and exit",()=>{D5.write(`0.0.1764878483-g1dd0b0 (released 2025-12-04T20:06:46.152Z)
4748
+ `),!1}}function KI8(){let J=new qA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)jR(),process.exit(0);let z=H.originalError??H;e46(z)}),J.option("-V, --version","Print the version number and exit",()=>{D5.write(`0.0.1764892237-g17504a (released 2025-12-04T23:55:42.376Z)
4749
4749
  `),process.exit(0)}),J.addHelpText("after",Y96()),J.configureHelp({formatHelp:X96}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await oQ(U);await zI8(D)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await oQ(U);await HI8(D,await jC1(U,D.settings))});let Q=async(H,z,U)=>{Kz1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:Q0.of([h0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:Ev1,userConfigDir:TV6});let D={...z,executeMode:!1};await Ov1(D,{...H,openThreadSwitcher:!0},U)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await oQ(U);await EV6(U,D,z)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await oQ(U);await LI8(U,D,z)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await oQ(D);if(z.pick)g$.write(`${_4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
4750
4750
  `);if(z.last||H||M.executeMode)await MI8(D,M,H,U);else await Q(D,M,U)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await oQ(D);await DI8(D,M,H,U)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await oQ(U);await EV6(U,D,z)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await oQ(D);await NI8(D,M,H,U,z.support)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,D)=>{let M=D.optsWithGlobals(),L=await oQ(M);await FI8(M,L,H,z,D)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await oQ(D);await UI8(D,M,H,U)}),Z.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await oQ(D);await BI8(D,M,H,z,U)}),i56(J,async(H,z)=>{let U=await oQ(z);h$(H,z);let D=await b$(U,z);return{context:U,mcpService:D.mcpService,toolService:D.toolService,toolServices:D.toolService,configService:D.configService,cleanupTerminal:jR,asyncDispose:D.asyncDispose.bind(D)}}),u96(J,async(H)=>{let z=H.optsWithGlobals();return await oQ(z)}),_96(J,async(H)=>{let z=await oQ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{h$(U,H);let D=await b$(z,H);return{mcpService:D.mcpService,settings:z.settings,asyncDispose:D.asyncDispose.bind(D)}}}});function X(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new Nq(z,M),A=$I8(H);if(A)L.default(A);if(L.hidden=YI8(H)||wV6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of OV6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new Nq("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new Nq("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new Nq("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new Nq("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new Nq("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new Nq("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return e56(J),J.action(async(H,z)=>{let U=H,D=await oQ(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")D5.write(_4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
4751
4751
  `)),process.exit(0);if(Object.keys(U).forEach((L)=>{let A=OV6.find((E)=>E.name===L);if(A&&wV6(A)&&!XI8(A))g$.write(_4.yellow(`Warning: '--${L}' flag is deprecated
@@ -4753,8 +4753,8 @@ Login failed: ${G instanceof Error?G.message:String(G)}
4753
4753
  Or pipe via stdin: echo "your message" | amp --execute`);h$(Z,Q);let V=await b$(J,Q);PV6=V;let K=zu(V),q=async(X1)=>{let t=await IV6(X1,"utf-8"),p=JSON.parse(t);if(!yX(p.id))throw new I8(L$.invalidThreadId);return u51(V,{visibility:Y,agentMode:Q.mode,thread:p})},W=async(X1)=>{if(!yX(X1))throw new I8(L$.invalidThreadId);try{let[p,J1]=await Promise.all([X5.getThreadLinkInfo({thread:X1},{config:V.configService}),X5.getUserInfo({},{config:V.configService})]);if(p.ok&&J1.ok){let H1=p.result.creatorUserID,U1=J1.result.id;if(H1&&H1!==U1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new I8(`Cannot resume thread created by another user.
4754
4754
 
4755
4755
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(p){if(p instanceof I8)throw p;v.warn("Failed to validate thread ownership in CLI, allowing to open",{error:p})}let t=await V.threadService.get(X1)??void 0;return v.info(`[fetchAndStartThread] Loaded thread ${X1}, agentMode: ${t?.agentMode??"undefined"}`),u51(V,{visibility:Y,agentMode:t?void 0:Q.mode,thread:t})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return u51(V,{visibility:Y,agentMode:Q.mode})}catch(X1){if(X1 instanceof I8)throw X1;throw await _g(X1,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return u51(V,{visibility:Y,agentMode:Q.mode})};if(Q.format==="jsonl")g$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
4756
- `),await OA(),process.exit(1);if(J.executeMode&&Q.remote)await p96(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)x96(V.mcpService,J.settings),await U86(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1,L=!1;if(Q.jetbrains||Q.ide){await QL0();let X1=nE({jetbrainsOnly:Q.jetbrains});if(X1.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(X1.length===1){let t=X1[0];if(t)V3.selectConfig(t)}else L=!0}let A=s61("0.0.1764878483-g1dd0b0",V.settingsStorage),E=new G01(V.threadStorage),I=Q0.of([h0.file(process.cwd())]),P=GG1(void 0,I),R=new t61(V.mcpService,J.settings.getWorkspaceRootPath());if(X)U.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let k=(async()=>{try{let X1=await X5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(X1.ok)return v.info("User free tier status:",X1),X1.result}catch(X1){v.error("Failed to fetch free tier status:",X1)}})(),y=(async()=>{try{let X1=await X5.getUserInfo({},{config:V.configService});if(X1.ok)return X1.result}catch(X1){v.debug("Failed to fetch user workspace info:",X1)}})(),[x,b]=await Promise.all([k,y]),d=b?.email,m=d&&(d.endsWith("@sourcegraph.com")||d.endsWith("@ampcode.com")||d==="auth-bypass-user@example.com"),o=await i96();v.info("Loaded session state:",o),await ly1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new v61,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:E,worker:U,workerDeps:K,configService:V.configService,internalAPIClient:X5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:V3,connectedClientsService:new hn,commandRegistry:P,mcpService:V.mcpService,mcpTrustHandler:R,showJetBrainsInstaller:M,showIdePicker:D,showIdePickerHint:L,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:o,freeTierStatus:x,workspace:b?.team??null,features:b?.features??[],isDogfooding:m||!1,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function oQ(J){if(J.interactive)g$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4757
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await u86({...J,workspaceTrust:{current:!0,changes:l_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await k96(J.mcpConfig);Y=y96(Y,G)}let X=await Y.get("url","global");if(!X)X=KZ;if(!BF(X))v.info("Targeting custom Amp server",{ampURL:X});return Y=oU0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:d96(await jC1(J,Y))}}function qI8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function WI8(){let J=qI8(process.argv);if(c46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),QI8(v),v.info("Starting Amp CLI.",{version:"0.0.1764878483-g1dd0b0",buildTimestamp:"2025-12-04T20:06:46.152Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new I8(L$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await KI8().parseAsync(process.argv)}qP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await WI8().catch(_g)});async function HI8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4756
+ `),await OA(),process.exit(1);if(J.executeMode&&Q.remote)await p96(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)x96(V.mcpService,J.settings),await U86(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1,L=!1;if(Q.jetbrains||Q.ide){await QL0();let X1=nE({jetbrainsOnly:Q.jetbrains});if(X1.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(X1.length===1){let t=X1[0];if(t)V3.selectConfig(t)}else L=!0}let A=s61("0.0.1764892237-g17504a",V.settingsStorage),E=new G01(V.threadStorage),I=Q0.of([h0.file(process.cwd())]),P=GG1(void 0,I),R=new t61(V.mcpService,J.settings.getWorkspaceRootPath());if(X)U.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let k=(async()=>{try{let X1=await X5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(X1.ok)return v.info("User free tier status:",X1),X1.result}catch(X1){v.error("Failed to fetch free tier status:",X1)}})(),y=(async()=>{try{let X1=await X5.getUserInfo({},{config:V.configService});if(X1.ok)return X1.result}catch(X1){v.debug("Failed to fetch user workspace info:",X1)}})(),[x,b]=await Promise.all([k,y]),d=b?.email,m=d&&(d.endsWith("@sourcegraph.com")||d.endsWith("@ampcode.com")||d==="auth-bypass-user@example.com"),o=await i96();v.info("Loaded session state:",o),await ly1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new v61,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:E,worker:U,workerDeps:K,configService:V.configService,internalAPIClient:X5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:V3,connectedClientsService:new hn,commandRegistry:P,mcpService:V.mcpService,mcpTrustHandler:R,showJetBrainsInstaller:M,showIdePicker:D,showIdePickerHint:L,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:o,freeTierStatus:x,workspace:b?.team??null,features:b?.features??[],isDogfooding:m||!1,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function oQ(J){if(J.interactive)g$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
4757
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await u86({...J,workspaceTrust:{current:!0,changes:l_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await k96(J.mcpConfig);Y=y96(Y,G)}let X=await Y.get("url","global");if(!X)X=KZ;if(!BF(X))v.info("Targeting custom Amp server",{ampURL:X});return Y=oU0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:d96(await jC1(J,Y))}}function qI8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function WI8(){let J=qI8(process.argv);if(c46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),QI8(v),v.info("Starting Amp CLI.",{version:"0.0.1764892237-g17504a",buildTimestamp:"2025-12-04T23:55:42.376Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new I8(L$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await KI8().parseAsync(process.argv)}qP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await WI8().catch(_g)});async function HI8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
4758
4758
  `);else if(!BF(J.ampURL))D5.write(`Logging in to ${new URL(J.ampURL).hostname}
4759
4759
  `);let Z=process.env.AMP_API_KEY;if(Z)D5.write(`API key found in environment variable, storing...
4760
4760
  `),await Q.set("apiKey",Z,J.ampURL),D5.write(`API key successfully stored.
@@ -4767,7 +4767,7 @@ This thread belongs to a different user and cannot be continued for security rea
4767
4767
  `);else D5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
4768
4768
  `);process.exit(0)}async function FI8(J,Q,Z,Y,X){h$(X,J);let G=await b$(Q,J);try{let V=p51(Z);if(!V)d51(Z);let K=V,q=Y.trim();if(q.length===0)f$("Thread name cannot be empty");if(q.length>256)f$("Thread name cannot exceed 256 characters");if(!(await cC(K,G)).messages.length)f$("Cannot rename an empty thread.");let H=zu(G);await(await J2.getOrCreateForThread(H,K)).handle({type:"title",value:q}),v.info("GOT HERE"),await G.threadSyncService.sync(),v.info("GOT THERE"),D5.write(_4.green(`✓ Thread ${K} renamed to "${q}"
4769
4769
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;f$(K)}}async function UI8(J,Q,Z,Y){h$(Y,J);let X=await b$(Q,J);try{let G=p51(Z);if(!G)d51(Z);let K=await cC(G,X),q=GR(K);D5.write(q+`
4770
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;f$(V)}}async function BI8(J,Q,Z,Y,X){h$(X,J);let G=await b$(Q,J);try{let V=await Iv1(Z),K=await cC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=zu(G),L=K.id;await G.threadStorage.set(L,K);let A=await J2.getOrCreateForThread(M,L);await A.resume();let E=$01.fromWorker(A),I=new G01(G.threadStorage),P=Q0.of([h0.file(process.cwd())]),R=GG1(void 0,P),k=new t61(G.mcpService,Q.settings.getWorkspaceRootPath()),y=s61("0.0.1764878483-g1dd0b0",G.settingsStorage);await ly1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new v61,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:X5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:V3,connectedClientsService:new hn,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D}}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await _g(V,Z)}}async function NI8(J,Q,Z,Y,X){h$(Y,J);let G=await b$(Q,J);try{let V=p51(Z);if(!V)d51(Z);let K=V,q=await X5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=e61(J,W);if(!H&&!X)f$("Must specify either --visibility or --support");if(H&&X)f$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)f$(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,J41(H)),D5.write(_4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4770
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;f$(V)}}async function BI8(J,Q,Z,Y,X){h$(X,J);let G=await b$(Q,J);try{let V=await Iv1(Z),K=await cC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=zu(G),L=K.id;await G.threadStorage.set(L,K);let A=await J2.getOrCreateForThread(M,L);await A.resume();let E=$01.fromWorker(A),I=new G01(G.threadStorage),P=Q0.of([h0.file(process.cwd())]),R=GG1(void 0,P),k=new t61(G.mcpService,Q.settings.getWorkspaceRootPath()),y=s61("0.0.1764892237-g17504a",G.settingsStorage);await ly1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new v61,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:X5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:V3,connectedClientsService:new hn,commandRegistry:R,mcpService:G.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D}}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await _g(V,Z)}}async function NI8(J,Q,Z,Y,X){h$(Y,J);let G=await b$(Q,J);try{let V=p51(Z);if(!V)d51(Z);let K=V,q=await X5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=e61(J,W);if(!H&&!X)f$("Must specify either --visibility or --support");if(H&&X)f$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)f$(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,J41(H)),D5.write(_4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
4771
4771
  `);if(X){await cC(K,G);let z=typeof X==="string"?X:void 0;await xj0(G.threadService,K,G.configService,z),D5.write(_4.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
4772
4772
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),f$(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function DI8(J,Q,Z,Y){h$(Y,J);let X=await b$(Q,J),G=zu(X);try{let V=await Iv1(Z),q=(await cC(V,X)).messages.length-1,W=await J2.getOrCreateForThread(G,V),H=await VR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await wv1(H),D5.write(`${H}
4773
4773
  `),await X.asyncDispose(),process.exit(0)}catch(V){g$.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1764878483-g1dd0b0",
3
+ "version": "0.0.1764892237-g17504a",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {