@sourcegraph/amp 0.0.1761537996-gd958b0 → 0.0.1761540104-g4e1704
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.
- package/dist/main.js +14 -14
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4823,7 +4823,7 @@ Minimum version required to store current data is: `+K+`.
|
|
|
4823
4823
|
`;async function cq0(J,Q,Z,X){let Y=performance.now(),K=[...SV1(uq0(J)),{role:"user",parts:[{text:Z98.replace("{USER_GOAL}",Q)}]}],G=await Fs(bq0,K,[],J,Z,X,{responseMimeType:"application/json",responseJsonSchema:R0.toJSONSchema(dq0)}),q=dq0.parse(JSON.parse(G.message.text??"")),z=performance.now()-Y;return u.debug("Thread handoff prepared",{threadId:J.id,goalLength:Q.length,instructionsLength:q.instructions.length,fileCount:q.relevantFiles.length,durationMs:Math.round(z)}),{instructions:q.instructions,relevantFiles:q.relevantFiles}}x5();W2();hB();M2();async function Bs(J,Q,Z,X){let Y=s7(J.content);if(!Y)return{title:void 0,usage:void 0};let G=await(await Ca({configService:Z},X)).messages.create({model:Sa,max_tokens:60,temperature:0.7,system:`You are an assistant that generates short, descriptive titles (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") based on user's message to an agentic coding tool. Your titles should be concise (max 7 words) and capture the essence of the query or topic. DO NOT ASSUME OR GUESS the user's intent beyond what is in their message. Omit generic words like "question", "request", etc. Be professional and precise. Use common software engineering terms and acronyms if they are helpful. Use the set_title tool to provide your answer.`,messages:[{role:"user",content:`<message>${Y}</message>`}],tools:[{name:"set_title",input_schema:{type:"object",properties:{title:{type:"string",description:'The short thread title (maximum 7 words, "Sentence case" with the first word capitalized not "Title Case") that you generated for the message'}},required:["title"]}}],tool_choice:{type:"tool",name:"set_title",disable_parallel_tool_use:!0}},{stream:!1,signal:X,headers:{...zz(Q)}}),q=`anthropic/${Sa.replace(/^[^/]+\//,"")}`,z=jX(q),U={model:Sa,maxInputTokens:z.contextWindow-z.maxOutputTokens,inputTokens:G.usage.input_tokens,outputTokens:G.usage.output_tokens,cacheCreationInputTokens:G.usage.cache_creation_input_tokens,cacheReadInputTokens:G.usage.cache_read_input_tokens,totalInputTokens:G.usage.input_tokens+(G.usage.cache_creation_input_tokens??0)+(G.usage.cache_read_input_tokens??0),credits:f2(G.usage)},W=G.content.at(0);if(!W)throw Error("no content in generateThreadTitle response");if(W.type!=="tool_use"||W.name!=="set_title")throw Error("missing or invalid tool_use in generateThreadTitle response");return{title:W.input&&typeof W.input==="object"&&"title"in W.input&&typeof W.input.title==="string"?W.input.title:void 0,usage:U}}Lc();class kV1{storage;exclusiveThreads=new MS;get exclusiveThreadsChanges(){return this.exclusiveThreads.observable}dirtyThreads=new Set;flushRequests=new b8;flusher=this.flushRequests.pipe(v2(void 0),KG(100),q8(()=>{let J=Array.from(this.dirtyThreads);if(this.dirtyThreads=new Set,J.length===0)return cZ1;let Q=J.slice(0,3).map(async(Z)=>{try{this.flushThread(Z)}catch(X){u.error("Error flushing thread to storage:",X,{name:"ThreadService",threadID:Z}),this.dirtyThreads.add(Z)}});if(J.length>3){for(let Z of J.slice(3))this.dirtyThreads.add(Z);setTimeout(()=>this.flushRequests.next(),100)}return d6(async()=>{await Promise.all(Q)})})).subscribe({});constructor(J){this.storage=J}async flushThread(J){let Q=this.exclusiveThreads.get(J);if(!Q)return;let[Z]=Q.getValue();await this.storage.set(J,Z)}observeRaw(J){return this.exclusiveThreads.observable.pipe(k0((Q)=>Q.get(J)),J8(),q8((Q)=>{if(Q!==void 0)return Q;return new e1((Z)=>{this.storage.get(J).then((X)=>{if(X)Z.next([RQ(X,!0),[]])})})}))}async getUnfrozen(J,Q){let Z=this.exclusiveThreads.get(J);if(Z)return Z.getValue()[0];let X=await this.storage.get(J);if(Q?.throwIfAborted(),!X)return null;return X}async get(J,Q){let Z=await this.getUnfrozen(J,Q);if(!Z)return null;return RQ(Z,!0)}async getPrimitiveProperty(J,Q){let Z=await this.getUnfrozen(J);if(!Z)return null;return Z[Q]}observe(J){return this.observeRaw(J).pipe(k0(([Q,Z])=>Q),lZ1(100,{leading:!0,trailing:!0}))}observePatches(J){return this.observeRaw(J).pipe(k0(([Q,Z],X)=>X===0?Q:Z),Y98(100))}async exclusiveSyncReadWriter(J){if(this.exclusiveThreads.has(J))throw Error(`Thread ${J} already has an exclusive read-writer`);let Q=this.exclusiveThreads.get(J);if(!Q){let X=await this.storage.get(J);if(!X)X=X98(J),await this.storage.set(J,X);X=RQ(X,!0),Q=new W4([X,[]]),this.exclusiveThreads.set(J,Q),await r90()}let Z=!1;return{read:()=>{if(Z)throw Error("thread exclusive read-writer was disposed");return Q.getValue()[0]},write:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=dS(Q.getValue()[0],()=>{return X});Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next()},update:(X)=>{if(Z)throw Error("thread exclusive read-writer was disposed");let[Y,K]=dS(Q.getValue()[0],X);return Q.next([Y,K]),this.dirtyThreads.add(J),this.flushRequests.next(),Y},asyncDispose:async()=>{if(Z)return;if(Z=!0,this.dirtyThreads.has(J)){let[X]=Q.getValue();try{await this.storage.set(J,X)}catch(Y){u.error("Error flushing thread on dispose:",Y,{name:"ThreadService",threadID:J})}this.dirtyThreads.delete(J)}this.exclusiveThreads.delete(J)}}}flush(){this.flushRequests.next()}async flushVersion(J,Q,Z=5000){this.flush();let X=Date.now();while(!0){if(Date.now()-X>Z)throw Error(`Timed out waiting for thread ${J} to reach version ${Q}`);let Y=await this.storage.get(J);if(Y&&Y.v>=Q)return;await new Promise((K)=>setTimeout(K,10))}}async forkThread(J,Q){let Z=await this.get(J);if(!Z)throw Error(`Thread ${J} not found`);let X=Z.messages.slice(0,Q+1);return{threadID:await this.createForkedThread(J,X,Q)}}async createForkedThread(J,Q,Z){let X=await this.get(J);if(!X)throw Error(`Thread ${J} not found`);let Y=Kz(),K=Date.now(),G=await this.exclusiveSyncReadWriter(Y),q=`Forked: ${X.title||"Untitled"}`,z=G.update((F)=>{if(F.originThreadID=J,F.forkPointIndex=Z,F.v++,F.title=q,F.relationships=[{threadID:J,type:"fork",role:"child",messageIndex:Z,createdAt:K}],X.env)F.env=t8(X.env);for(let H of Q)F.messages.push(t8(H))});await G.asyncDispose();let U=this.exclusiveThreads.get(J);if(U){let[F]=U.getValue(),[H,B]=dS(F,(M)=>{if(M.v++,M.forkThreads??={},M.forkThreads[Z]??=[],!M.forkThreads[Z].includes(Y))M.forkThreads[Z].push(Y);if(M.relationships??=[],!M.relationships.some((N)=>N.threadID===Y&&N.type==="fork"&&N.role==="parent"&&N.messageIndex===Z))M.relationships.push({threadID:Y,type:"fork",role:"parent",messageIndex:Z,createdAt:K})});U.next([H,B]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let F=await this.exclusiveSyncReadWriter(J);F.update((H)=>{if(H.v++,H.forkThreads??={},H.forkThreads[Z]??=[],!H.forkThreads[Z].includes(Y))H.forkThreads[Z].push(Y);if(H.relationships??=[],!H.relationships.some((M)=>M.threadID===Y&&M.type==="fork"&&M.role==="child"&&M.messageIndex===Z))H.relationships.push({threadID:Y,type:"fork",role:"child",messageIndex:Z,createdAt:K})}),await F.asyncDispose()}let W=z.v;return await this.flushVersion(Y,W),Y}async createHandoffThread(J,Q,Z,X,Y){let K=await this.get(J);if(!K)throw Error(`Thread ${J} not found`);let G=await Z.getLatest(X),{instructions:q,relevantFiles:z}=await cq0(K,Q,G,X),U=z.map((w)=>`@${w}`).join(" "),W=U?`${U}
|
|
4824
4824
|
|
|
4825
4825
|
${q}
|
|
4826
|
-
`:q,{title:F}=await Bs({role:"user",content:[{type:"text",text:q}]},{id:J,agentMode:K.agentMode},Z,X),H=Kz(),B=Y??(K.messages.length?K.messages.length-1:void 0),M=Date.now(),V=await this.exclusiveSyncReadWriter(H),N=V.update((w)=>{if(w.v++,w.title=F||`Handoff: ${K.title||"Untitled"}`,K.env)w.env=t8(K.env);if(w.draft=W,K.agentMode)w.agentMode=K.agentMode;w.relationships=[{threadID:J,type:"handoff",role:"child",messageIndex:B,createdAt:M,comment:Q}]});await V.asyncDispose();let L=N.v;await this.flushVersion(H,L);let A=this.exclusiveThreads.get(J);if(A){let[w]=A.getValue(),[R,O]=dS(w,(j)=>{if(j.v++,j.relationships??=[],!j.relationships.some((E)=>E.threadID===H&&E.type==="handoff"&&E.role==="parent"&&E.messageIndex===B))j.relationships.push({threadID:H,type:"handoff",role:"parent",messageIndex:B,createdAt:M,comment:Q})});A.next([R,O]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let w=await this.exclusiveSyncReadWriter(J);w.update((R)=>{if(R.v++,R.relationships??=[],!R.relationships.some((j)=>j.threadID===H&&j.type==="handoff"&&j.role==="parent"&&j.messageIndex===B))R.relationships.push({threadID:H,type:"handoff",role:"parent",messageIndex:B,createdAt:M,comment:Q})}),await w.asyncDispose()}return H}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[X]=Z.getValue();if(oa(X)>Q)J=X,Q=oa(X)}return J}async asyncDispose(){this.flusher.unsubscribe(),await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}function X98(J){return{v:0,id:J,created:Date.now(),messages:[]}}function Y98(J){return(Q)=>new e1((Z)=>{let X=[],Y=null,K=()=>{if(Y)clearTimeout(Y),Y=null;if(X.length>0)Z.next(X),X=[]};return Q.subscribe({next:(G)=>{if(!(G instanceof Array)){K(),Z.next(G);return}X.push(...G),Y=setTimeout(K,J)},error:(G)=>{K(),Z.error(G)},complete:()=>{K(),Z.complete()}})})}C0();G0();TB();fY();AD();function lq0({threadService:J,threadHistoryService:Q,configService:Z,isExtensionDevelopment:X=!1}){let Y=!1,K=[],G=new pZ1,q=new W4(new Map),z=async()=>{if(Y)return!1;if(!await G6(k90(Z)))return!1;let L=await Z.getLatest(new AbortController().signal);if(X&&PB(L.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return u.debug(`Skipping sync to ${DZ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;return!0},U=async(L)=>{if(!B(L))return;let A=await J.get(L);if(!A){G.delete(L);return}if(A.messages.length===0)return;if(!await z())return;let w=new AbortController,R={dispose:()=>w.abort()};K.push(R);try{try{let O=await YJ.uploadThread({thread:A,createdOnServer:!1},{signal:w.signal,config:Z});if(!O.ok)throw Error(`Failed to upload thread: ${O.error.code}`)}catch(O){throw u.debug("Failed to upload thread",{error:O}),O}}finally{let O=K.indexOf(R);if(O!==-1)K.splice(O,1);if(w.abort(),K.length>30)u.debug("[AbortController] High disposables count detected: ",K.length,{name:"ThreadSyncService",operation:"uploadThread"})}},W=new Map,F=new Set,H=60000,B=(L)=>{if(F.has(L))return!1;let A=W.get(L);if(!A)return!0;let w=Date.now()-A,R=w>=H;if(!R)u.debug(`Skipping thread ${L} sync due to backoff (${Math.round(w/1000)}s elapsed of ${H/1000}s backoff)`,{name:"ThreadSyncService"});return R},M=async()=>{for(let L of G){if(!B(L))continue;try{await U(L),G.delete(L),W.delete(L)}catch(A){let w=A instanceof Error?A.message:String(A);if(w.includes("404")&&w.includes("Thread not found"))F.add(L),G.delete(L),W.delete(L),u.warn(`Thread ${L} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else W.set(L,Date.now()),u.error(`Error syncing thread ${L} (will retry after backoff)`,A,{name:"ThreadSyncService"})}}},V=async(L,A=!1)=>{if(!await z())return;let w;if(L)w=(await Promise.all(L.map((E)=>G6(J.observe(E).pipe(k0((I)=>I?{id:I.id,v:I.v}:null)))))).filter((E)=>E!==null);else{let E=await G6(Q.observeHistory().pipe(k0((T)=>T.map((S)=>({id:S.id,v:S.v}))))),I=await G6(J.exclusiveThreadsChanges.pipe(k0((T)=>Array.from(T.values()).map((S)=>{let[x,h]=S.getValue();return{id:x.id,v:x.v}}))));w=E.concat(I)}let R={threadVersions:[],threadMetas:[]},O=new Set;for(let E of w){if(O.has(E.id))continue;if(O.add(E.id),F.has(E.id))continue;if(!A)R.threadVersions.push({id:E.id,v:E.v});let I=q.getValue().get(E.id);R.threadMetas.push({id:E.id,meta:I?.status==="synced"?I.info?.meta:void 0})}if(R.threadVersions.length===0&&R.threadMetas.length===0)return;if(!await z())return;let j=new AbortController,$={dispose:()=>j.abort()};K.push($);try{u.debug("Sending threads sync request",{name:"ThreadSyncService",source:A?"metadata":"full",threadCount:R.threadVersions.length+R.threadMetas.length,specificThreads:L?.length??"all"});let E=await PZ("/api/threads/sync",{method:"POST",body:JSON.stringify(R),signal:j.signal},Z);if(!E.ok){let S=await E.text().catch(()=>"Unable to read response body");throw u.warn("Threads sync request failed",{name:"ThreadSyncService",status:E.status,text:S}),Error(`Threads sync API responded with status: ${E.status}${S?`: ${S}`:""}`)}u.debug("Got response for threads sync request",{name:"ThreadSyncService",status:E.status});let I=await E.json(),T=0;for(let S of I.threadActions){if(!(("action"in S)&&typeof S.action==="string"))continue;switch(S.action){case"upload":{if(!F.has(S.id))G.add(S.id),T++;break}case"meta":{q.getValue().set(S.id,{status:"synced",info:{meta:S.meta}});break}default:continue}}if(L){for(let S of L)if(q.getValue().get(S)?.status==="unknown")q.getValue().set(S,{status:"synced",info:null})}q.next(q.getValue()),await M(),u.debug(`Sync completed (${L?L.length:"all"} threads checked, ${T} threads needed sync)`,{name:"ThreadSyncService"})}finally{let E=K.indexOf($);if(E!==-1)K.splice(E,1);if(j.abort(),K.length>30)u.debug("[AbortController] High disposables count detected: ",K.length,{name:"ThreadSyncService",operation:"sync"})}};u.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let N=Promise.resolve();return K.push(dZ1(G.observable.pipe(T5((L)=>L.size>0),KG(3000),BW(()=>M().catch((L)=>u.error("Error processing sync queue:",L,{name:"ThreadSyncService"})))).subscribe({}))),K.push(dZ1(J.exclusiveThreadsChanges.pipe(q8((L)=>VS(...Array.from(L.entries()).map(([,A])=>A.pipe(_N(([w,R])=>{if(!F.has(w.id))G.add(w.id)})))))).subscribe({}))),{async sync(){return V()},async uploadThread(L){return U(L)},initialSyncComplete:N,async updateThreadMeta(L,A){let w=q.getValue().get(L),R=new AbortController,O={dispose:()=>R.abort()};K.push(O);try{q.getValue().set(L,{status:"synced",info:{meta:{visibility:A.visibility,sharedGroupIDs:"sharedGroupIDs"in A?A.sharedGroupIDs:[]
|
|
4826
|
+
`:q,{title:F}=await Bs({role:"user",content:[{type:"text",text:q}]},{id:J,agentMode:K.agentMode},Z,X),H=Kz(),B=Y??(K.messages.length?K.messages.length-1:void 0),M=Date.now(),V=await this.exclusiveSyncReadWriter(H),N=V.update((w)=>{if(w.v++,w.title=F||`Handoff: ${K.title||"Untitled"}`,K.env)w.env=t8(K.env);if(w.draft=W,K.agentMode)w.agentMode=K.agentMode;w.relationships=[{threadID:J,type:"handoff",role:"child",messageIndex:B,createdAt:M,comment:Q}]});await V.asyncDispose();let L=N.v;await this.flushVersion(H,L);let A=this.exclusiveThreads.get(J);if(A){let[w]=A.getValue(),[R,O]=dS(w,(j)=>{if(j.v++,j.relationships??=[],!j.relationships.some((E)=>E.threadID===H&&E.type==="handoff"&&E.role==="parent"&&E.messageIndex===B))j.relationships.push({threadID:H,type:"handoff",role:"parent",messageIndex:B,createdAt:M,comment:Q})});A.next([R,O]),this.dirtyThreads.add(J),this.flushRequests.next()}else{let w=await this.exclusiveSyncReadWriter(J);w.update((R)=>{if(R.v++,R.relationships??=[],!R.relationships.some((j)=>j.threadID===H&&j.type==="handoff"&&j.role==="parent"&&j.messageIndex===B))R.relationships.push({threadID:H,type:"handoff",role:"parent",messageIndex:B,createdAt:M,comment:Q})}),await w.asyncDispose()}return H}getRecentlyActiveThread(){let J=null,Q=0;for(let[,Z]of this.exclusiveThreads.entries()){let[X]=Z.getValue();if(oa(X)>Q)J=X,Q=oa(X)}return J}async asyncDispose(){this.flusher.unsubscribe(),await Promise.all(Array.from(this.dirtyThreads).map((J)=>this.flushThread(J))),this.exclusiveThreads.dispose()}}function X98(J){return{v:0,id:J,created:Date.now(),messages:[]}}function Y98(J){return(Q)=>new e1((Z)=>{let X=[],Y=null,K=()=>{if(Y)clearTimeout(Y),Y=null;if(X.length>0)Z.next(X),X=[]};return Q.subscribe({next:(G)=>{if(!(G instanceof Array)){K(),Z.next(G);return}X.push(...G),Y=setTimeout(K,J)},error:(G)=>{K(),Z.error(G)},complete:()=>{K(),Z.complete()}})})}C0();G0();TB();fY();AD();function lq0({threadService:J,threadHistoryService:Q,configService:Z,isExtensionDevelopment:X=!1}){let Y=!1,K=[],G=new pZ1,q=new W4(new Map),z=async()=>{if(Y)return!1;if(!await G6(k90(Z)))return!1;let L=await Z.getLatest(new AbortController().signal);if(X&&PB(L.settings.url)&&process.env.FORCE_ENABLE_SYNC!=="1")return u.debug(`Skipping sync to ${DZ} in extension development mode to avoid polluting the production server`,{name:"ThreadSyncService"}),!1;return!0},U=async(L)=>{if(!B(L))return;let A=await J.get(L);if(!A){G.delete(L);return}if(A.messages.length===0)return;if(!await z())return;let w=new AbortController,R={dispose:()=>w.abort()};K.push(R);try{try{let O=await YJ.uploadThread({thread:A,createdOnServer:!1},{signal:w.signal,config:Z});if(!O.ok)throw Error(`Failed to upload thread: ${O.error.code}`)}catch(O){throw u.debug("Failed to upload thread",{error:O}),O}}finally{let O=K.indexOf(R);if(O!==-1)K.splice(O,1);if(w.abort(),K.length>30)u.debug("[AbortController] High disposables count detected: ",K.length,{name:"ThreadSyncService",operation:"uploadThread"})}},W=new Map,F=new Set,H=60000,B=(L)=>{if(F.has(L))return!1;let A=W.get(L);if(!A)return!0;let w=Date.now()-A,R=w>=H;if(!R)u.debug(`Skipping thread ${L} sync due to backoff (${Math.round(w/1000)}s elapsed of ${H/1000}s backoff)`,{name:"ThreadSyncService"});return R},M=async()=>{for(let L of G){if(!B(L))continue;try{await U(L),G.delete(L),W.delete(L)}catch(A){let w=A instanceof Error?A.message:String(A);if(w.includes("404")&&w.includes("Thread not found"))F.add(L),G.delete(L),W.delete(L),u.warn(`Thread ${L} not found on server, stopping sync attempts`,{name:"ThreadSyncService"});else W.set(L,Date.now()),u.error(`Error syncing thread ${L} (will retry after backoff)`,A,{name:"ThreadSyncService"})}}},V=async(L,A=!1)=>{if(!await z())return;let w;if(L)w=(await Promise.all(L.map((E)=>G6(J.observe(E).pipe(k0((I)=>I?{id:I.id,v:I.v}:null)))))).filter((E)=>E!==null);else{let E=await G6(Q.observeHistory().pipe(k0((T)=>T.map((S)=>({id:S.id,v:S.v}))))),I=await G6(J.exclusiveThreadsChanges.pipe(k0((T)=>Array.from(T.values()).map((S)=>{let[x,h]=S.getValue();return{id:x.id,v:x.v}}))));w=E.concat(I)}let R={threadVersions:[],threadMetas:[]},O=new Set;for(let E of w){if(O.has(E.id))continue;if(O.add(E.id),F.has(E.id))continue;if(!A)R.threadVersions.push({id:E.id,v:E.v});let I=q.getValue().get(E.id);R.threadMetas.push({id:E.id,meta:I?.status==="synced"&&I.info?I.info?.meta.visibility==="private"?{visibility:"private",sharedGroupIDs:I.info.meta.sharedGroupIDs}:{visibility:I.info.meta.visibility}:void 0})}if(R.threadVersions.length===0&&R.threadMetas.length===0)return;if(!await z())return;let j=new AbortController,$={dispose:()=>j.abort()};K.push($);try{u.debug("Sending threads sync request",{name:"ThreadSyncService",source:A?"metadata":"full",threadCount:R.threadVersions.length+R.threadMetas.length,specificThreads:L?.length??"all"});let E=await PZ("/api/threads/sync",{method:"POST",body:JSON.stringify(R),signal:j.signal},Z);if(!E.ok){let S=await E.text().catch(()=>"Unable to read response body");throw u.warn("Threads sync request failed",{name:"ThreadSyncService",status:E.status,text:S}),Error(`Threads sync API responded with status: ${E.status}${S?`: ${S}`:""}`)}u.debug("Got response for threads sync request",{name:"ThreadSyncService",status:E.status});let I=await E.json(),T=0;for(let S of I.threadActions){if(!(("action"in S)&&typeof S.action==="string"))continue;switch(S.action){case"upload":{if(!F.has(S.id))G.add(S.id),T++;break}case"meta":{q.getValue().set(S.id,{status:"synced",info:{meta:S.meta}});break}default:continue}}if(L){for(let S of L)if(q.getValue().get(S)?.status==="unknown")q.getValue().set(S,{status:"synced",info:null})}q.next(q.getValue()),await M(),u.debug(`Sync completed (${L?L.length:"all"} threads checked, ${T} threads needed sync)`,{name:"ThreadSyncService"})}finally{let E=K.indexOf($);if(E!==-1)K.splice(E,1);if(j.abort(),K.length>30)u.debug("[AbortController] High disposables count detected: ",K.length,{name:"ThreadSyncService",operation:"sync"})}};u.debug("Thread sync service initialized (on-demand sync mode)",{name:"ThreadSyncService"});let N=Promise.resolve();return K.push(dZ1(G.observable.pipe(T5((L)=>L.size>0),KG(3000),BW(()=>M().catch((L)=>u.error("Error processing sync queue:",L,{name:"ThreadSyncService"})))).subscribe({}))),K.push(dZ1(J.exclusiveThreadsChanges.pipe(q8((L)=>VS(...Array.from(L.entries()).map(([,A])=>A.pipe(_N(([w,R])=>{if(!F.has(w.id))G.add(w.id)})))))).subscribe({}))),{async sync(){return V()},async uploadThread(L){return U(L)},initialSyncComplete:N,async updateThreadMeta(L,A){let w=q.getValue().get(L),R=new AbortController,O={dispose:()=>R.abort()};K.push(O);try{q.getValue().set(L,{status:"synced",info:{meta:{visibility:A.visibility,sharedGroupIDs:"sharedGroupIDs"in A?A.sharedGroupIDs:[]}}}),q.next(q.getValue());let j=await YJ.setThreadMeta({thread:L,meta:A},{signal:R.signal,config:Z});if(!j.ok)throw u.debug("Failed to update sharing status (USE_NEW_INTERNAL_API=true)",{error:j.error}),Error(`Failed to update sharing status: ${j.error.code}`)}catch(j){if(w)q.getValue().set(L,w);else q.getValue().delete(L);throw q.next(q.getValue()),j}finally{let j=K.indexOf(O);if(j!==-1)K.splice(j,1);R.abort(),u.debug(`[AbortController] Cleaned up for updateThreadMeta ${L}, disposables count: ${K.length}`,{name:"ThreadSyncService",threadID:L,operation:"updateThreadMeta",wasTracked:j!==-1})}},threadSyncInfo(L){let A=[];for(let w of L){if(F.has(w)){if(!q.getValue().has(w))q.getValue().set(w,{status:"synced",info:null});continue}if(!q.getValue().has(w))q.getValue().set(w,{status:"unknown"}),A.push(w)}if(A.length>0)V(A,!0).catch((w)=>u.error("Error syncing thread metadata:",w,{name:"ThreadSyncService"}));return q.pipe(k0((w)=>{let R={};for(let O of L)R[O]=w.get(O)??{status:"synced",info:null};return R}))},dispose(){if(Y)return;Y=!0;for(let L of K)L.dispose()}}}C0();G0();async function Ds(J,Q,Z,X){let Y=await J.forkThread(Z);return await K98(Q,J.threadID,Y,X),Y}async function K98(J,Q,Z,X={}){let{originMetaTimeout:Y=5000,forkedThreadTimeout:K=1e4,waitForForkedUpload:G=!0}=X;try{let z=(await G6(J.threadSyncInfo([Q]).pipe(T5((W)=>W[Q]?.status==="synced"),QO(Y))))[Q];if(z?.status!=="synced"||!z.info?.meta){u.debug("Origin thread has no metadata to inherit",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z});return}if(G)await G6(J.threadSyncInfo([Z]).pipe(T5((W)=>W[Z]?.status==="synced"),QO(K)));let U=z.info.meta.visibility==="private"?{visibility:z.info.meta.visibility,sharedGroupIDs:z.info.meta.sharedGroupIDs}:{visibility:z.info.meta.visibility};await J.updateThreadMeta(Z,U),u.debug("Successfully inherited thread visibility",{name:"inheritThreadVisibility",originThreadID:Q,forkedThreadID:Z,metadata:z.info.meta})}catch(q){u.debug("Failed to inherit thread visibility settings",{name:"inheritThreadVisibility",error:q,originThreadID:Q,forkedThreadID:Z})}}$L();b6();C0();DW();G0();EQ();hV1();Dz();var MO0=C6(UO0(),1);function WO0(J){let Q=J.trim().split(`
|
|
4827
4827
|
`).map((K)=>K.trim()).filter((K)=>K);if(Q.length===0)return null;let Z="",X=[],Y={};for(let K of Q){let G=K.indexOf(":");if(G===-1)continue;let q=K.substring(0,G).trim(),z=K.substring(G+1).trim();if(!q||!z)continue;if(q==="name"&&!Z)Z=z;else if(q==="description")X.push(z);else{let U=z.indexOf(" ");if(U===-1)Y[q]={type:"string",description:z,optional:!1};else{let W=z.substring(0,U),F=z.substring(U+1).trim(),H=["string","boolean","number","integer","array","object"],B=W,M=F,V=!1;if(B.endsWith("?"))V=!0,B=B.slice(0,-1);if(H.includes(B.toLowerCase())){if(/^(\()?optional(\))?(\s|$)/i.test(M))V=!0;Y[q]={type:B,description:M,optional:V}}else{if(/^(\()?optional(\))?(\s|$)/i.test(z))V=!0;Y[q]={type:"string",description:z,optional:V}}}}}if(!Z)return null;return{name:Z,description:X.join(`
|
|
4828
4828
|
`),parameters:Y}}function FO0(J,Q){let Z={},X=[];for(let[K,G]of Object.entries(J.parameters)){let q;switch(G.type.toLowerCase()){case"boolean":q="boolean";break;case"number":case"integer":q=G.type.toLowerCase();break;case"array":q="array";break;case"object":q="object";break;default:q="string"}if(Z[K]={type:q,description:G.description},!G.optional)X.push(K)}let Y={type:"object",properties:Z,required:X,additionalProperties:!1};return{name:J.name,description:J.description,inputSchema:Y,source:{toolbox:Q}}}function HO0(J){let Q=[];function Z(X,Y){if(Y===null||Y===void 0)Q.push(`${X}: ${String(Y)}`);else if(typeof Y==="boolean")Q.push(`${X}: ${Y?"true":"false"}`);else if(typeof Y==="number"||typeof Y==="string")Q.push(`${X}: ${String(Y)}`);else if(Array.isArray(Y))for(let K=0;K<Y.length;K++)Z(`${X}_${K}`,Y[K]);else if(typeof Y==="object")for(let[K,G]of Object.entries(Y))Z(`${X}_${K}`,G);else Q.push(`${X}: ${String(Y)}`)}for(let[X,Y]of Object.entries(J))Z(X,Y);return Q.join(`
|
|
4829
4829
|
`)+`
|
|
@@ -5906,11 +5906,11 @@ Actual: ${Y}`)}async function t79(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
5906
5906
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
5907
5907
|
|
|
5908
5908
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
5909
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function b51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=X59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function X59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}C0();function Zf1(J,Q){let Z=new b8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await $_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Qp(z.latestVersion,U);let W=await eV(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await $_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Hu().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(X)=>{await ey1(X.force||!1,X.verbose||!1,"0.0.
|
|
5909
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function b51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=X59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function X59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}C0();function Zf1(J,Q){let Z=new b8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await $_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Qp(z.latestVersion,U);let W=await eV(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await $_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Hu().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(X)=>{await ey1(X.force||!1,X.verbose||!1,"0.0.1761540104-g4e1704"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new Hu("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await Y59(X.version)});J.addCommand(Z)}async function Y59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")JW.write(z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
5910
5910
|
|
|
5911
5911
|
`));try{if(!J){JW.write(z8.blue(`Checking for updates...
|
|
5912
|
-
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.
|
|
5913
|
-
`));let Y=await eV("0.0.
|
|
5912
|
+
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.1761540104-g4e1704");if(!Z){JW.write(z8.green(`✓ Amp CLI is already up to date.
|
|
5913
|
+
`));let Y=await eV("0.0.1761540104-g4e1704");if(Y.warning)JW.write(`
|
|
5914
5914
|
`+z8.yellow(Y.warning)+`
|
|
5915
5915
|
`);process.exit(0)}if(!X)JW.write(z8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}JW.write(z8.blue(`Updating to version ${J}...
|
|
5916
5916
|
`)),await Qp(J,void 0,(Z)=>{JW.write(z8.dim(`Running: ${Z}
|
|
@@ -5977,7 +5977,7 @@ Examples:
|
|
|
5977
5977
|
`),process.exit(1)}}),Z.command("doctor [name]").summary("Check MCP server status").description(`Wait for MCP service initialization and display the status of configured servers.
|
|
5978
5978
|
|
|
5979
5979
|
If [name] is provided, only show status for that specific server.`).action(async(X,Y,K)=>{let{mcpDoctor:G}=await Promise.resolve().then(() => sZ6),q=await Q(K.optsWithGlobals());if(!q.getThreadDeps)throw Error("Internal error: getThreadDeps not available for doctor command");await G(K,q.getThreadDeps,X)})}function D59(J,Q){if(Q.header&&Q.header.length>0)throw Error("HTTP headers cannot be used with command-based MCP servers. Use --env instead");let Z,X,Y=J.indexOf("--");if(Y!==-1){let q=J.slice(Y+1);if(q.length===0)throw Error("No command provided after -- separator");Z=q[0],X=q.length>1?q.slice(1):void 0}else{if(Q.env&&Q.env.length>0&&J.length===0)throw Error("Environment variables provided but no command specified. Use: amp mcp add <name> --env KEY=VAL -- <command>");Z=J[0],X=J.length>1?J.slice(1):void 0}let G=M59(Q.env||[]);return{command:Z,args:X,env:Object.keys(G).length>0?G:void 0}}function oZ6(J,Q){return Q.concat(J)}function M59(J){let Q={};for(let Z of J){let X=Z.indexOf("=");if(X<=0)throw Error(`Invalid --env format: ${Z}. Expected KEY=VALUE`);let Y=Z.slice(0,X),K=Z.slice(X+1);if(Y.trim()==="")throw Error(`Invalid --env format: ${Z}. Expected KEY=VALUE`);if(K==="")throw Error(`Invalid --env format: ${Z}. Expected KEY=VALUE`);Q[Y]=K}return Q}function V59(J){let Q={};for(let Z of J){let X=Z.indexOf("=");if(X<=0)throw Error(`Invalid --header format: ${Z}. Expected KEY=VALUE`);let Y=Z.slice(0,X),K=Z.slice(X+1);if(K==="")throw Error(`Invalid --header format: ${Z}. Expected KEY=VALUE`);Q[Y]=K}return Q}U3();var N59=R0.union([R0.object({command:R0.string(),args:R0.array(R0.string()).optional(),env:R0.record(R0.string(),R0.string()).optional()}).strict(),R0.object({url:R0.string()}).strict()]),L59=R0.record(R0.string(),N59);async function eZ6(J){let Q;if(J.trim().startsWith("{"))Q=J;else{let{readFile:Y}=await import("node:fs/promises");try{Q=await Y(J,"utf-8")}catch(K){throw Error(`Failed to read --mcp-config file: ${K instanceof Error?K.message:String(K)}`)}}let X;try{X=JSON.parse(Q)}catch(Y){throw Error(`Failed to parse --mcp-config as JSON: ${Y instanceof Error?Y.message:String(Y)}`)}try{return L59.parse(X)}catch(Y){if(Y instanceof R0.ZodError){let K=Y.issues.map((G)=>`${G.path.join(".")}: ${G.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${K}`)}throw Error(`Failed to validate MCP server configuration: ${String(Y)}`)}}var A59=["public","private","workspace","group"];function y51(J){let Q=J?.visibility;if(!Q)return;if(A59.includes(Q))return Q;return Error(`Invalid visibility. Must be one of: private, public, workspace, group
|
|
5980
|
-
`)}function f51(J){switch(J){case"public":return{visibility:"
|
|
5980
|
+
`)}function f51(J){switch(J){case"public":return{visibility:"public_unlisted"};case"workspace":return{visibility:"thread_workspace_shared"};case"private":return{visibility:"private",sharedGroupIDs:[]};case"group":return{visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0}}}import{execSync as w59}from"node:child_process";var R59={getEnv(J){return process.env[J]},getPlatform(){return process.platform},execSync:w59};async function QW(J=R59){let Q=[J.getEnv("EDITOR"),J.getEnv("VISUAL"),"vi","nano","edit"].filter((Z)=>typeof Z==="string");for(let Z of Q)if(await O59(J,Z))return Z;return null}async function O59(J,Q){try{let Z=Q.split(" ").at(0);if(Z===void 0)return!1;let X=J.getPlatform()==="win32"?`where "${Z}"`:`which "${Z}"`;return J.execSync(X,{stdio:"ignore",timeout:3000}),!0}catch{return!1}}C_();nN();async function j59(J,Q){let Z=ga(J);if(!Z.success)throw Error(`Invalid permission format: ${Z.error.message}`);if(Z.data.length===0)throw Error("No permission entry provided");let X=xB(Z.data);if(!X.success){let z=X.error.errors.map((U)=>U.message).join(", ");throw Error(`Invalid permission entry: ${z}`)}let Y=await tU({settingsFile:Q}),K=await Y.get("permissions")??[],q=[Z.data[0],...K];await Y.set("permissions",q)}async function JX6(J){try{let Q=J.args.map((Z)=>{if(/[\s/\\*?[\]{}()"]/.test(Z))return`"${Z}"`;return Z}).join(" ");await j59(Q,J.settingsFile),J.exit(0)}catch(Q){let Z=Q instanceof Error?Q.message:"Unknown error";J.stderr.write(`Error: ${Z}
|
|
5981
5981
|
`),J.exit(1)}}C_();nN();import{execSync as $59}from"node:child_process";import{mkdtemp as E59,readFile as I59,rmdir as P59,unlink as T59,writeFile as C59}from"node:fs/promises";import Zp from"node:fs/promises";import{tmpdir as S59}from"node:os";import{join as h51}from"node:path";import{dirname as v59}from"node:path";var k59=`# Permission Rules
|
|
5982
5982
|
# First matching rule wins.
|
|
5983
5983
|
#
|
|
@@ -6282,10 +6282,10 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||XO}function vX6(J,Q){let
|
|
|
6282
6282
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let G=K.optsWithGlobals(),q=await Q(K,G),z=0;await q.mcpService.initialized;let U=K.args.slice(1),W;if(CX6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await PX6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:q,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await q.asyncDispose(),q.cleanupTerminal(),process.exit(z)})}import{randomBytes as IH9}from"node:crypto";import{homedir as PH9}from"node:os";import Dd from"node:path";C0();G0();var kX6=120000,_X6=180000;function Uf1(J,Q=Date.now()){return Q-J<_X6}function Wf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return fd(kX6).pipe(v2(void 0),q8(()=>d6(async(q)=>{if(!Z())return u.debug("[Ads] Skipping ad fetch (user inactive or ad already fetched)"),Y;let z=await X?.getContext();u.debug("[Ads] Fetching ad from server",{hasContext:!!z});let U=await J.getCurrentAd({context:z,excludeAdIds:K},{config:Q,signal:q});if(!U.ok)throw u.error("[Ads] Failed to fetch ad",{error:U.error.message}),Error(U.error.message);if(U.result){if(Y=U.result,K.length>=G)K.shift();K.push(Y.id),u.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else u.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();ij();W2();JD();M2();$L();N8();b6();function xX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function bX6(J,Q,Z){if(J.agentMode)return J.agentMode;if(Q?.agentMode){let X=Q.agentMode;if(X==="free"){if(Z?.canUseAmpFree??!1)return"free";return"smart"}return X}return"smart"}G0();JD();import vJ9 from"node:fs";import yX6 from"node:path";function fX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!yX6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function hX6(J){try{let Q=yX6.extname(J).toLowerCase(),Z=M10(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=vJ9.readFileSync(J);return kJ9(X,Z)}catch(X){u.error(`Failed to read image file ${J}:`,X)}}catch(Q){u.error("Error handling image file path",{imagePath:J,error:Q})}return null}function kJ9(J,Q){if(J.length>_W)return u.warn(`Image file too large: ${J.length} bytes (max: ${_W})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as IK9}from"node:child_process";Hj();G0();import{spawn as _J9}from"node:child_process";import{promises as xJ9}from"node:fs";function gX6(J){return J.kind==="executable"}function mX6(J){return J.kind==="markdown"}var JB=50000,uX6=300000;async function Kp(J,Q,Z,X={}){let{timeoutMs:Y=uX6,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(u.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),mX6(G))return await bJ9(G,Q);else if(gX6(G))return await yJ9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return u.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function bJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await xJ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>JB?Z.slice(0,JB)+`
|
|
6283
6283
|
... (output truncated at ${JB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function yJ9(J,Q,Z=uX6,X){return new Promise((Y)=>{let[K,G]=fJ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=z10(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=_J9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)F.push(V);else{let N=JB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)H.push(V);else{let N=JB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(q.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6284
6284
|
${L}`:L;if(B>JB)A+=`
|
|
6285
|
-
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function fJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return gJ9(Z,X?[...X]:null,Y,Q);else return hJ9(Z,X?[...X]:null,Y,Q)}function hJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();ij();W2();bB();fY();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>KQ9,scrollDown:()=>GQ9,link:()=>HQ9,image:()=>BQ9,iTerm:()=>DQ9,exitAlternativeScreen:()=>WQ9,eraseUp:()=>YQ9,eraseStartLine:()=>ZQ9,eraseScreen:()=>Ff1,eraseLines:()=>JQ9,eraseLine:()=>lX6,eraseEndLine:()=>QQ9,eraseDown:()=>XQ9,enterAlternativeScreen:()=>UQ9,cursorUp:()=>dX6,cursorTo:()=>pJ9,cursorShow:()=>eJ9,cursorSavePosition:()=>nJ9,cursorRestorePosition:()=>aJ9,cursorPrevLine:()=>oJ9,cursorNextLine:()=>sJ9,cursorMove:()=>dJ9,cursorLeft:()=>cX6,cursorHide:()=>tJ9,cursorGetPosition:()=>rJ9,cursorForward:()=>lJ9,cursorDown:()=>cJ9,cursorBackward:()=>iJ9,clearTerminal:()=>zQ9,clearScreen:()=>qQ9,beep:()=>FQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,hw2=globalThis.process?.versions?.node!==void 0,gw2=globalThis.process?.versions?.bun!==void 0,mw2=globalThis.Deno?.version?.deno!==void 0,uw2=globalThis.process?.versions?.electron!==void 0,pw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,dw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,cw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,lw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,iw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,nw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",aw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",rw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",sw2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ow2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",PC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",mJ9=!u51&&Hf1.platform==="win32",uJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,pJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",cJ9=(J=1)=>j2+J+"B",lJ9=(J=1)=>j2+J+"C",iJ9=(J=1)=>j2+J+"D",cX6=j2+"G",nJ9=pX6?"\x1B7":j2+"s",aJ9=pX6?"\x1B8":j2+"u",rJ9=j2+"6n",sJ9=j2+"E",oJ9=j2+"F",tJ9=j2+"?25l",eJ9=j2+"?25h",JQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},QQ9=j2+"K",ZQ9=j2+"1K",lX6=j2+"2K",XQ9=j2+"J",YQ9=j2+"1J",Ff1=j2+"2J",KQ9=j2+"S",GQ9=j2+"T",qQ9="\x1Bc",zQ9=mJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,UQ9=j2+"?1049h",WQ9=j2+"?1049l",FQ9=PC,HQ9=(J,Q)=>[zp,"8",qp,qp,Q,PC,J,zp,"8",qp,qp,PC].join(""),BQ9=(J,Q={})=>{let Z=`${zp}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+PC},DQ9={setCwd:(J=uJ9())=>`${zp}50;CurrentDir=${J}${PC}`,annotation(J,Q={}){let Z=`${zp}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+PC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fY();class Up{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.1761537996-gd958b0"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(Q,this.configService)}catch(Q){u.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}}import{execFile as l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as LQ9}from"node:util";var c51=LQ9(l51),AQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,wQ9="\x1B]52;c;?\x1B\\",RQ9="\x1B]52;p;?\x1B\\";class eX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=l51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=l51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(wQ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(RQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Nf1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=AQ9(Z);process.stdout.write(X);return}if(Nf1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var VY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,PK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Ty1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6285
|
+
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function fJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return gJ9(Z,X?[...X]:null,Y,Q);else return hJ9(Z,X?[...X]:null,Y,Q)}function hJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();ij();W2();bB();fY();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>KQ9,scrollDown:()=>GQ9,link:()=>HQ9,image:()=>BQ9,iTerm:()=>DQ9,exitAlternativeScreen:()=>WQ9,eraseUp:()=>YQ9,eraseStartLine:()=>ZQ9,eraseScreen:()=>Ff1,eraseLines:()=>JQ9,eraseLine:()=>lX6,eraseEndLine:()=>QQ9,eraseDown:()=>XQ9,enterAlternativeScreen:()=>UQ9,cursorUp:()=>dX6,cursorTo:()=>pJ9,cursorShow:()=>eJ9,cursorSavePosition:()=>nJ9,cursorRestorePosition:()=>aJ9,cursorPrevLine:()=>oJ9,cursorNextLine:()=>sJ9,cursorMove:()=>dJ9,cursorLeft:()=>cX6,cursorHide:()=>tJ9,cursorGetPosition:()=>rJ9,cursorForward:()=>lJ9,cursorDown:()=>cJ9,cursorBackward:()=>iJ9,clearTerminal:()=>zQ9,clearScreen:()=>qQ9,beep:()=>FQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,hw2=globalThis.process?.versions?.node!==void 0,gw2=globalThis.process?.versions?.bun!==void 0,mw2=globalThis.Deno?.version?.deno!==void 0,uw2=globalThis.process?.versions?.electron!==void 0,pw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,dw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,cw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,lw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,iw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,nw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",aw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",rw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",sw2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ow2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",PC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",mJ9=!u51&&Hf1.platform==="win32",uJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,pJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",cJ9=(J=1)=>j2+J+"B",lJ9=(J=1)=>j2+J+"C",iJ9=(J=1)=>j2+J+"D",cX6=j2+"G",nJ9=pX6?"\x1B7":j2+"s",aJ9=pX6?"\x1B8":j2+"u",rJ9=j2+"6n",sJ9=j2+"E",oJ9=j2+"F",tJ9=j2+"?25l",eJ9=j2+"?25h",JQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},QQ9=j2+"K",ZQ9=j2+"1K",lX6=j2+"2K",XQ9=j2+"J",YQ9=j2+"1J",Ff1=j2+"2J",KQ9=j2+"S",GQ9=j2+"T",qQ9="\x1Bc",zQ9=mJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,UQ9=j2+"?1049h",WQ9=j2+"?1049l",FQ9=PC,HQ9=(J,Q)=>[zp,"8",qp,qp,Q,PC,J,zp,"8",qp,qp,PC].join(""),BQ9=(J,Q={})=>{let Z=`${zp}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+PC},DQ9={setCwd:(J=uJ9())=>`${zp}50;CurrentDir=${J}${PC}`,annotation(J,Q={}){let Z=`${zp}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+PC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fY();class Up{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.1761540104-g4e1704"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(Q,this.configService)}catch(Q){u.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}}import{execFile as l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as LQ9}from"node:util";var c51=LQ9(l51),AQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,wQ9="\x1B]52;c;?\x1B\\",RQ9="\x1B]52;p;?\x1B\\";class eX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=l51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=l51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(wQ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(RQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Nf1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=AQ9(Z);process.stdout.write(X);return}if(Nf1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var VY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,PK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Ty1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6286
6286
|
Client ID: ${Z}
|
|
6287
6287
|
Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Fh1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=AS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Up(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(k0((Z)=>$Y(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...TK9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,PK9);if(J)Object.assign(this.commands,CK9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((q)=>{u.debug("Failed to submit command telemetry",q)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((q)=>q.name===J),G=await Kp(J,Z,this.customRegistry,{signal:X});if(G.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:G.output});return}else{Q.submitMessage(G.output);return}return Error(G.error??`Command '${J}' failed`)}query(J,Q,Z){let X=Object.values(this.commands).filter((K)=>{if(!Q||!K.isVisible)return!0;return K.isVisible(Q,Z)}),Y=this.latestCustom.filter((K)=>K.available).map((K)=>({name:K.name,description:"Custom command",requiresArgs:K.kind==="executable",execute:(G,q)=>this.execute(K.name,G,q??[])}));return[...X,...Y]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}getCustomCommand(J){return this.latestCustom.find((Q)=>Q.name===J)}}var TK9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${_5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=kQ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Ia}],agentMode:K}});return}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{return J.openInEditor("")}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return BZ("dangerouslyAllowAll",!1),new e9("Amp is now following permissions rules for this session")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return BZ("dangerouslyAllowAll",!0),new e9("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await QW();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw u.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:QW};await EC(Y);return}catch(Y){u.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return u.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Draft a new thread with relevant context from current thread: /handoff <your goal>",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new e9(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return u.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim()}).filter(Boolean).join(`
|
|
6288
|
-
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=nW(new URL(Y),Z.id).toString(),q=`Thread URL: ${ZN(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"
|
|
6288
|
+
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=nW(new URL(Y),Z.id).toString(),q=`Thread URL: ${ZN(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public_unlisted"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new e9(`${q}
|
|
6289
6289
|
|
|
6290
6290
|
This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof Error?W.message:String(W);if(F.includes("no-workspace"))return Error("You are not a member of any workspace.");if(F.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(F.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",W),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=nW(new URL(X),Z.id).toString();try{return await MY(Y),new e9("Thread opened in browser")}catch(K){u.error("Failed to open browser",{error:K});let G=ZN(Y,Y,{fallback:()=>Y});return new e9(`Could not open browser automatically. Thread URL: ${G}`)}},isVisible:(J)=>J.messages.length!==0},url:{name:"url",description:"Display thread URL and copy to clipboard",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=nW(new URL(X),Z.id).toString();try{return await VY.writeText(Y),new e9(`Thread URL: ${Y}
|
|
6291
6291
|
|
|
@@ -6437,7 +6437,7 @@ exit code: ${q}`,new $1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
|
|
|
6437
6437
|
|
|
6438
6438
|
(Copied to clipboard)`)}catch(Z){return u.error("Failed to copy URL to clipboard",{error:Z}),Error(`Thread URL: ${Q}
|
|
6439
6439
|
|
|
6440
|
-
(Could not copy to clipboard)`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-private",noun:"Thread",verb:"Set visibility to private",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"private",sharedGroupIDs:[]};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to private")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-workspace",noun:"Thread",verb:"Set visibility to workspace",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"thread_workspace_shared"};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to workspace")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-group",noun:"Thread",verb:"Set visibility to group",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to group")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-public",noun:"Thread",verb:"Set visibility to public",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"
|
|
6440
|
+
(Could not copy to clipboard)`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-private",noun:"Thread",verb:"Set visibility to private",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"private",sharedGroupIDs:[]};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to private")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-workspace",noun:"Thread",verb:"Set visibility to workspace",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"thread_workspace_shared"};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to workspace")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-group",noun:"Thread",verb:"Set visibility to group",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to group")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"share-public",noun:"Thread",verb:"Set visibility to public",execute:async(J)=>{let{thread:Q,threadSyncService:Z}=J,X={visibility:"public_unlisted"};try{return await Z.updateThreadMeta(Q.id,X),new e9("This thread's visibility has been updated to public")}catch(Y){let K=Y instanceof Error?Y.message:String(Y);if(K.includes("no-workspace"))return Error("You are not a member of any workspace.");if(K.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(K.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",Y),Error(`Failed to update thread visibility for ${Q.id}`)}},isVisible:(J)=>!this.isThreadEmpty(J)}),this.register({id:"expand-thinking-blocks",noun:"Thread",verb:"Expand Thinking Blocks",shortcut:x6.ctrl("r"),execute:async(J)=>{NQ.instance.toggleAll(),U2.instance.requestFrame()},isVisible:(J)=>!this.isThreadEmpty(J)&&!NQ.instance.allExpanded}),this.register({id:"collapse-thinking-blocks",noun:"Thread",verb:"Collapse Thinking Blocks",shortcut:x6.ctrl("r"),execute:async(J)=>{NQ.instance.toggleAll(),U2.instance.requestFrame()},isVisible:(J)=>!this.isThreadEmpty(J)&&NQ.instance.allExpanded}),this.register({id:"editor",noun:"Prompt",verb:"Open in editor",shortcut:new x6("g",{ctrl:!0}),execute:async(J)=>{await J.openInEditor(J.editorState.text.trim())},isVisible:()=>!0,getPromptText:(J)=>{let Q=J.editorState.text.trim().replace(/\n/g," ");if(Q.length===0)return;return Q.length>20?`${Q.slice(0,20)}...`:Q}}),this.register({id:"queue-current-prompt",noun:"Prompt",verb:"Queue",execute:async(J)=>{let Z=[{type:"text",text:J.editorState.text.trim()}],X=J.takeImageAttachments?.()??[];if(X.length>0)Z.push(...X);J.worker.handle({type:"user:message-queue:enqueue",message:{content:Z}}),J.editorDispatch({type:"clear"})},isVisible:(J)=>{return J.editorState.text.trim().length>0&&J.isProcessing},getPromptText:(J)=>{let Q=J.editorState.text.trim().replace(/\n/g," ");return Q.length>20?`${Q.slice(0,20)}...`:Q}}),this.register({id:"queue-argument",noun:"Prompt",verb:"Queue",gatherArguments:(J,Q)=>{return Q.launchArgumentPrompt("Enter the prompt to queue:")},execute:async(J,Q)=>{let Z=[{type:"text",text:Q}],X=J.takeImageAttachments?.()??[];if(X.length>0)Z.push(...X);J.worker.handle({type:"user:message-queue:enqueue",message:{content:Z}})},isVisible:(J)=>{return J.isProcessing}}),this.register({id:"dequeue",noun:"Prompt",verb:"Dequeue All Queued Prompts",execute:async(J)=>{let Q=this.getQueuedMessages(J);if(Q.length===0)return;let X=Q.map((Y)=>{return Y.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
|
|
6441
6441
|
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:X})},isVisible:(J)=>this.getQueuedMessages(J).length>0,getPromptText:(J)=>`${this.getQueuedMessages(J).length} queued`}),this.register({id:"clear",noun:"Prompt",verb:"Clear",execute:async(J)=>{J.editorDispatch({type:"clear"})},isVisible:(J)=>J.editorState.text.trim().length>0}),this.register({id:"mode",noun:"Agent",verb:"Toggle Mode",shortcut:new x6("s",{ctrl:!0}),execute:async(J)=>{J.toggleAgentMode()},isVisible:()=>!0}),this.register({id:"generate-agent-file",noun:"Agent",verb:"Generate AGENTS.md File",execute:async(J)=>{let Q=await J.configService.getLatest(),Z=kQ(Q.settings),Y=J.getInMemoryAgentModeOverride()??Z;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Ia}],agentMode:Y}})},isVisible:()=>!0}),this.register({id:"agent-files",noun:"Agent",verb:"List AGENTS.md Files",execute:async(J)=>{try{let Q=await J.getGuidanceFiles();if(Q.length===0)return new e9("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${kJ(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${VZ(LQ(K.uri))} (${K.type})`).join(`
|
|
6442
6442
|
`);return new e9(`${X}
|
|
6443
6443
|
|
|
@@ -6492,12 +6492,12 @@ ${J.helpMessage}`);return}if(!J.requiresManualInstall&&J.products.length===0){th
|
|
|
6492
6492
|
${this.stateNotifier.value.getDownloadPath()}.`,new $1({color:Q.colorScheme.foreground}))}),new F0({height:1}),new r1({text:new N1(`Go to Settings > Plugins > Cogwheel > Install Plugin from Disk or see
|
|
6493
6493
|
https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_disk`,new $1({color:Q.colorScheme.foreground}))}),new F0({height:1}),new r1({text:new N1(`Finally restart your JetBrains IDE${!nK()&&" and Amp"}.`,new $1({color:Q.colorScheme.foreground}))}),new F0({height:1}),new r1({text:new N1("Press any key to exit...",new $1({color:Q.colorScheme.foreground,dim:!0}))})]})})});return new Y9({autofocus:!0,onKey:(U)=>{return this.widget.onExit(),"handled"},child:z})}return new i0({decoration:new l8(Q.colorScheme.background),child:new p6({padding:O0.all(2),child:new r1({text:new N1("Discovering JetBrains IDEs...",new $1({color:Q.colorScheme.foreground}))})})})}}function AH9(J){let Q=J.reduce((Z,X)=>{return(Z[X.name]??=[]).push(X),Z},{});return Object.entries(Q).map(([Z,X])=>({name:Z,versions:X.map((Y)=>Y.version).sort()}))}function wH9(J){if(J.length<=1)return"";if(J.length>=3)return` (${J[0]}-${J.at(-1)})`;return` (${J.join(", ")})`}H9();s8();class du1 extends l0{color;trigger;trail;fps;speed;leftOffset;constructor({key:J,color:Q,trigger:Z,trail:X=5,fps:Y=60,speed:K=1,leftOffset:G=0}){super(J?{key:J}:{});this.color=Q,this.trigger=Z,this.trail=X,this.fps=Y,this.speed=K,this.leftOffset=G}createState(){return new YF6}}class YF6 extends c0{progress=0;timer=null;initState(){this.restart()}didUpdateWidget(J){if(J.trigger!==this.widget.trigger)this.restart()}dispose(){this.stop()}restart(){this.stop(),this.progress=-this.widget.trail,this.start()}start(){if(this.timer)return;let J=Math.max(16,Math.round(1000/Math.max(1,this.widget.fps)));this.timer=setInterval(()=>{this.setState(()=>{this.progress+=this.widget.speed})},J)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}build(J){return new KF6({color:this.widget.color,trail:this.widget.trail,head:this.progress,leftOffset:this.widget.leftOffset},this.widget.key)}}class KF6 extends XB{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new HN(this)}createRenderObject(){return new GF6(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}updateRenderObject(J){J.update(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}}class GF6 extends Z8{_color;_trail;_head;_leftOffset;constructor(J,Q,Z,X){super();this._color=J;this._trail=Q;this._head=Z;this._leftOffset=X}update(J,Q,Z,X){let Y=!1;if(Q!==this._trail)this._trail=Q,Y=!0;if(this._color=J,this._head=Z,this._leftOffset=X,Y)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Q=J.constrain(J.biggest.width,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y),K=Math.floor(this.size.width),G=[1,0.7,0.5,0.35,0.25,0.15];for(let q=0;q<=this._trail&&q<G.length;q++){let z=Math.floor(this._head)-q+this._leftOffset;if(z<this._leftOffset||z>=K)continue;let U=RH9(this._color,G[q]);J.setChar(X+z,Y,"━",{fg:U},1)}super.paint(J,Q,Z)}}function RH9(J,Q){if(J.type==="rgb")return E1.rgb(J.value.r,J.value.g,J.value.b,Q);if(J.type==="index")return E1.index(J.value,Q);return E1.default(Q)}class cu1 extends I6{message;onDismiss;constructor({key:J,message:Q,onDismiss:Z}){super({key:J});this.message=Q,this.onDismiss=Z}build(J){let Z=e6.of(J).colorScheme,X=i51(this.message),Y=[{value:"dismiss",label:"Dismiss"}],K=X.type==="error"?Z.destructive:Z.primary,G=new ER({child:new r1({text:new N1(X.description),selectable:!0})});return new WB({title:X.title,body:G,options:Y,onSelect:(q)=>{this.onDismiss()},borderColor:K,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})}}H9();class lu1 extends I6{url;qrCode;constructor({key:J,url:Q,qrCode:Z}){super(J?{key:J}:{});this.url=Q,this.qrCode=Z}build(J){let Z=e6.of(J).colorScheme,X=h8.of(J),Y=new $1({color:E1.rgb(0,0,0)}),K=new $1({color:Z.foreground}),G=new $1({color:Z.foreground}),q=new $1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,W=z-4,F=Math.min(U-4,Math.floor(U*0.8)),H=Math.min(60,W),B=new wY({autofocus:!0,child:new p6({padding:O0.only({left:2,right:2}),child:new r0({crossAxisAlignment:"center",children:[new C9({child:new i0({decoration:new l8(E1.rgb(255,255,255)),padding:O0.all(2),child:new r1({text:new N1(this.qrCode,Y),textAlign:"left"})})}),new F0({height:1}),new C9({child:new r1({text:new N1(`Continue at ${this.url}`,K)})}),new F0({height:1})]})})}),M=new C9({child:new r1({text:new N1("",G,[new N1("Press ",G),new N1("Escape",q),new N1(" to close",G)])})}),V=new r0({crossAxisAlignment:"stretch",children:[new v8({child:B}),M]});return new C9({child:new i0({constraints:new w6(H,H,0,F),decoration:new l8(Z.background,g8.all(new S8(Z.primary,1,"rounded"))),child:V})})}}s8();class iu1 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new qF6}}class qF6 extends c0{build(J){let{queuedMessages:Q,title:Z="Queue"}=this.widget.props;if(!Array.isArray(Q)||Q.length===0)return new F0({width:0,height:0});let X=Q.map((Y)=>this.buildQueueItem(Y));return new i0({child:new p6({padding:O0.symmetric(1,0),child:new r0({crossAxisAlignment:"stretch",children:[new r1({text:new N1(Z,new $1({bold:!0}))}),...X]})})})}buildQueueItem(J){let Z=J.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join(" ").trim(),X=Z.split(`
|
|
6494
6494
|
`)[0],Y=Z.includes(`
|
|
6495
|
-
`)?`${X}...`:Z,K=new $1({color:E1.index(8)});return new p6({padding:O0.only({bottom:0}),child:new X8({crossAxisAlignment:"start",children:[new p6({padding:O0.only({right:1}),child:new r1({text:new N1("•",new $1({color:E1.index(8)}))})}),new v8({child:new r1({text:new N1(Y,K)})})]})})}}LW();var OH9=Q1.string(),zF6=Q1.object({id:OH9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","
|
|
6495
|
+
`)?`${X}...`:Z,K=new $1({color:E1.index(8)});return new p6({padding:O0.only({bottom:0}),child:new X8({crossAxisAlignment:"start",children:[new p6({padding:O0.only({right:1}),child:new r1({text:new N1("•",new $1({color:E1.index(8)}))})}),new v8({child:new r1({text:new N1(Y,K)})})]})})}}LW();var OH9=Q1.string(),zF6=Q1.object({id:OH9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public_unlisted","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});G0();fY();LW();var jH9=Q1.object({id:Q1.string()});function $H9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),G=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${G}mo ago`}class Bd{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await PZ("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=jH9.parse(await X.json())}catch(W){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),G=await PZ(`/api/threads?${K}`,void 0,this.configService);if(!G.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${G.status})`};let q;try{q=Q1.array(zF6).parse(await G.json())}catch(W){return u.error("failed to parse thread data from server",{error:W}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:q.filter((W)=>W.messageCount>0).filter((W)=>{if(!J.trim())return!0;let F=W.title?.toLowerCase()||"untitled",H=W.id.toLowerCase(),B=J.toLowerCase();return F.includes(B)||H.includes(B)}).slice(0,Z).map((W)=>{let F=W.title||"Untitled",H=new Date(W.updatedAt),B=$H9(H),M=W.id.slice(-8);return{id:W.id,title:F,messageCount:W.messageCount,updatedAt:W.updatedAt,description:{timeAgo:B,title:F,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}s8();class nu1 extends l0{props;constructor(J){super();this.props=J}createState(){return new UF6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class UF6 extends c0{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(G)=>{if(G.ctrlKey&&G.key==="c"||G.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new Y9({autofocus:this.autofocus,onKey:Q,child:new r1({text:new N1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new Y9({autofocus:this.autofocus,onKey:Q,child:new r1({text:new N1("Loading threads...")})});let Z=h8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new Y9({autofocus:this.autofocus,onKey:Q,child:new r1({text:new N1("No threads found.")})});let X=this.allThreads.map((G)=>({value:G.id,label:G.title,description:this.formatThreadDescription(G)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new Y9({autofocus:this.autofocus,onKey:Q,child:new zd({title:"Select a thread to continue:",options:X,onSelect:(G)=>{this.widget.props.onSelect(G)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}B51();class au1{detect(J,Q){if(!J||Q<1)return null;let Z=z2(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
|
|
6496
6496
|
`))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class ru1{detect(J,Q){if(!J||Q<1)return null;let Z=z2(J);if(Q>Z.length)return null;if(Z[0]!=="/")return null;let X=Z.slice(1,Q).join("");return{start:0,end:Q,query:X,trigger:"/"}}}class WF6{triggers;constructor(J){this.triggers=J}detect(J,Q){for(let Z of this.triggers){let X=Z.detect(J,Q);if(X)return X}return null}}function su1(){return new WF6([new au1,new ru1])}function FF6(J,Q){switch(J){case"update-available":return[new N1("A newer Amp is available. Run ",new $1({color:Q.foreground,dim:!0})),new N1("amp update",new $1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new N1("Update complete, run ",new $1({color:Q.foreground,dim:!0})),new N1("amp update",new $1({color:Q.warning})),new N1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"update-error":return[new N1("Update failed, run ",new $1({color:Q.foreground,dim:!0})),new N1("amp update",new $1({color:Q.warning})),new N1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function TH9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new $1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new $1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class MF6 extends l0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new VF6}}class VF6 extends c0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;processingHandoff=!1;threadsForPicker=[];isLoadingThreads=!1;previewThread=null;previewCache=new Map;previewScrollController=new AY;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new B9({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new B9({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=$Y();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}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((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new N1(this.submitDisabledHint,new $1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new N1("",void 0,[new N1("Ctrl+C",new $1({color:Q.keybind})),new N1(" again to exit",new $1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new N1("",void 0,[new N1("Esc",new $1({color:Q.keybind})),new N1(" again to clear input",new $1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new N1("",void 0,[new N1("Escape",new $1({color:Q.keybind})),new N1(" to close help",new $1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=Jp1(X);return new N1("",void 0,[new N1("Images aren't supported in ",new $1({color:J.warning,dim:!1})),new N1(X,new $1({color:Y})),new N1(" mode.",new $1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new N1("",void 0,[new N1("Esc",new $1({color:Q.keybind})),new N1(" to cancel",new $1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new N1("Selection copied to clipboard",new $1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new N1(this.showingCannotToggleMessage,new $1({color:J.warning,dim:!1}));let Z=FF6(this.updateState,J);if(Z)return new N1("",void 0,Z);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 Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){u.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let G=Q.mainThread?.messages.findIndex((q)=>q===J);if(G===void 0||G<=0)return;try{let q=await WJ.getOrCreateForThread(Z,K),z=await Ds(q,X,G),U=await Y(z);oV(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let W=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=W})}catch(q){u.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((G)=>G===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let G=[{type:"text",text:Q}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);let q={content:G,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&q.agentMode!==Y.agentMode){u.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:q,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){u.error("Failed to edit message:",G)}};textController=new YW;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new AY);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(Lh1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new i7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;commands=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Fh1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ou1(this.getCommands(),this.widget.dependencies.fuzzyServer,new Bd(this.widget.dependencies.configService),this.widget.dependencies.configService);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.setState(()=>{this.isShowingIdePicker=!1});return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}showCommandPalette(){if(!this.isShowingPalette)this.loadThreadsForPicker();this.setState(()=>{this.isShowingPalette=!this.isShowingPalette})}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Du1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})});return this.paletteCommands}dismissPalette=()=>{this.isShowingPalette=!1,this.setState(()=>{this.previewThread=null})};handleThreadPreview=async(J)=>{if(J===null){this.setState(()=>{this.previewThread=null});return}if(this.previewCache.has(J)){this.setState(()=>{this.previewThread=this.previewCache.get(J)??null});return}let Q=await this.widget.dependencies.threadService.get(J);if(Q)this.previewCache.set(J,Q),this.setState(()=>{this.previewThread=Q})};getCommandPaletteContext=(J)=>{let{threadState:Q}=this.widget.dependencies;if(!Q.mainThread)return null;return{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.onOpenInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},editorDispatch:(Z)=>{if(Z.type==="set-input")this.textController.clear(),this.textController.insertText(Z.input);else if(Z.type==="clear")this.textController.clear()},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:()=>{let Z=this.getEffectiveAgentMode();Xp({agentMode:Z}).catch((X)=>{u.warn("Failed to save session state on exit:",X)}).finally(()=>{process.exit(0)})},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{let Z=await this.widget.dependencies.startNewThread();oV(Z)},switchToThread:async(Z)=>{await this.switchToExistingThread(Z)},handleHandoff:async(Z)=>{let X=Z.trim();if(!X){this.setState(()=>{this.displayMessage=Error("Cannot handoff with empty prompt text")});return}try{let Y=this.widget.dependencies.threadState.mainThread?.id;if(!Y){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let K=new AbortController,G=setTimeout(()=>K.abort(),20000),q=await this.widget.dependencies.threadService.createHandoffThread(Y,X,this.widget.dependencies.configService,K.signal);clearTimeout(G),await this.switchToExistingThread(q)}catch(Y){u.error("Failed to create handoff thread",Y),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${Y instanceof Error?Y.message:String(Y)}`)})}},getGuidanceFiles:async()=>{if(!Q.mainThread)return[];return(await O_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,J.signal)).map((X)=>({uri:X.uri,type:X.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode}};getThreadsForPicker(){return this.threadsForPicker}async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.isLoadingThreads=!0;try{let Q=await new Bd(this.widget.dependencies.configService).fetchThreadSummaries("",0,50);if(Q.ok)this.setState(()=>{this.threadsForPicker=Q.threads.map((Z)=>({id:Z.id,title:Z.title,messageCount:Z.messageCount,timeAgo:Z.description.timeAgo,shortThreadID:Z.description.shortThreadID}))})}finally{this.isLoadingThreads=!1}}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(G)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:G}:z);else{let z={id:X,args:Y,toolRun:G,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleAgentMode=()=>{if((lK()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=Kc(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=Kc(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:G}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{$2.instance.tuiInstance.suspend();let W=await Z(z.join(q(),"amp-edit-")),F=z.join(W,"message.amp.md");await G(F,J,"utf-8"),Q(`${U} "${F}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(F,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")u.error("Failed to read temporary file",H)}try{await Y(F),await K(W)}catch(H){u.warn("Failed to clean up temporary file",H)}$2.instance.tuiInstance.resume()}catch(W){try{$2.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=this.parseShellModeInput(J);if(Q){if(Q.cmd&&!this.isProcessing())this.invokeBashCommand(Q.cmd,{hidden:Q.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let Z=xX6(J),{threadState:X}=this.widget.dependencies;if(this.isSlashCommand(Z)&&X.mainThread){let Y=Z.slice(1).split(" "),K=Y[0],G=Y.slice(1).filter((q)=>q.trim()!=="");if(K){let q=X.viewState,z=this.getCommands().query(K,X.mainThread,q).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&G.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,G)}else if(K==="compact")this.setState(()=>{this.displayMessage=Error("The /compact command has been removed. Use /handoff to draft a new thread with relevant context instead.")}),this.textController.clear();return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(Z)};onOptionSelected=(J)=>{switch(J.type){case"hint":return;case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),G=Q.slice(Z),q=K+`@${J.path} `+G;this.textController.clear(),this.textController.insertText(q),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),G={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,statusMessage:J.statusMessage,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=G});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();oV(z);return}if(J.name==="handoff"){let z=Q?.join(" ").trim()||"";if(!z){this.setState(()=>{this.displayMessage=Error("Usage: /handoff <describe your goal>")});return}try{let U=this.widget.dependencies.threadState.mainThread?.id;if(!U){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let W=new AbortController,F=setTimeout(()=>W.abort(),20000),H=await this.widget.dependencies.threadService.createHandoffThread(U,z,this.widget.dependencies.configService,W.signal);clearTimeout(F),await this.switchToExistingThread(H)}catch(U){u.error("Failed to create handoff thread",U),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${U instanceof Error?U.message:String(U)}`)})}return}if(J.launchesWindow)$2.instance.tuiInstance.suspend();let q=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},submitMessage:(z)=>{return this.proceedWithUserMessage(z)},exitApp:()=>{let z=this.getEffectiveAgentMode();Xp({agentMode:z}).catch((U)=>{u.warn("Failed to save session state on exit:",U)}).finally(()=>{process.exit(0)})},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},openInEditor:this.onOpenInEditor,getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await O_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode},Q,X.signal);if(J.launchesWindow)$2.instance.tuiInstance.resume();if(q)this.setState(()=>{this.displayMessage=q})}catch(q){u.error("Error executing command:",q)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=su1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(HY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;$2.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),$2.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),$2.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{U2.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=bX6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);u.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.adSubscription=Wf1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&Uf1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=IH9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (xQ1(),_Q1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,G=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:G?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}}),oV(this.widget.dependencies.worker),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 X=lK();if(!X){u.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),u.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),u.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.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=$Y(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Z,X)=>{if(Z.length<=3)return!0;let Y=fX6(Z);if(!Y)return!0;let K=this.getEffectiveAgentMode();if(!Yc(K)){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>=V10)return!1;let G=hX6(Y);if(G)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,G]}),!1;return!0},this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{u.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Lh1("")),this.shouldUseProgressBar())process.stdout.write(EG6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:q.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],G=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:G}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){u.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){u.error("No tool use block found in confirmation");return}if(J==="allow-all-session")BZ("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else u.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],G=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",G)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await MY(Y)}catch(K){u.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(eq))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,eq])}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await WJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){u.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=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});let X=await this.widget.dependencies.startNewThread();oV(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),Xp({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();oV(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await WJ.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)=>{try{u.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;if(u.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,oV(Q),H51()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{u.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z}),Q.thread.draft)u.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),this.textController.insertText(Q.thread.draft)}catch(Q){throw u.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=lK()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==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 Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;let J=this.getEffectiveAgentMode();Xp({agentMode:J}).catch((Q)=>{u.warn("Failed to save session state on exit:",Q)}).finally(()=>{$2.instance.stop()})}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=PH9();if(J===Q)return"~";if(J.startsWith(Q+Dd.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Dd.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Dd.sep),"…",Q.slice(-2).join(Dd.sep)].join(Dd.sep)}build(J){let Q=h8.of(J),Z=a6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let q=(lK()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new DN({child:new nu1({onSelect:async(w1)=>{if(w1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(w1);else process.exit(0)},pageSize:50,threadFetcher:new Bd(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,F=z.mainThread?.id,H=z.mainThread||void 0,B=this.isTranscriptEmpty(),M=(w1)=>new DQ1({key:new i7(`preview-message-view-${w1.id}`),items:uu(w1).items,controller:this.previewScrollController,autofocus:!1,thread:w1,focusNode:new B9({debugLabel:"PreviewFocus"})}),V=this.previewThread?M(this.previewThread):B?new MQ1({agentMode:this.getEffectiveAgentMode()}):new DQ1({key:F?new i7(`message-view-${F}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:F?this.getMessageScrollController(F):new AY,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:H,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(!this.getCurrentConfirmation())this.autocompleteFocusNode.requestFocus()}}),N=Math.max(Math.floor(Q.size.height*0.4),12),L=this.getCurrentEphemeralError(),A=this.buildBottomWidget(L,U,Y,Z,z,W,N,q?this.randomAd:null),w=Q.size.width<40,R=z.mainThread?An1(z.mainThread):void 0,O=new bJ1({threadViewState:z.viewState,threadTokenUsage:R,threadID:F??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:w,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}),j=new xJ1({bashInvocations:this.bashInvocations}),$=[],E=this.getEffectiveAgentMode(),I=this.currentShellModeStatus,T=Jp1(E),S=!I?E.length+1:0,x=Q.capabilities.animationSupport,h=x==="disabled"?0:x==="slow"?30:60,v=1,_=h>0&&this.agentModePulseSeq>0?new IJ({children:[A,new VX({top:0,left:1,right:1,height:1,child:new du1({color:T,trigger:this.agentModePulseSeq,fps:h,speed:v,leftOffset:S})})]}):A;if($.push(new v8({child:V}),j),q)$.push(new Hu1({ad:this.randomAd,onButtonClick:async()=>{let w1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (xQ1(),_Q1)).then(({recordAdEvent:D1})=>{let y1=this.widget.dependencies.worker.thread,l1=y1.messages[y1.messages.length-1];D1("clicked",{adId:w1.id,advertiserId:w1.advertiserId,threadId:y1.id,messageId:l1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await MY(w1.shortDestinationUrl)}catch(D1){let l1=$2.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:l1,url:w1.shortDestinationUrl}})}}}));$.push(new i0({constraints:new w6(0,Q.size.width,0,N),child:_}),new F0({height:1,child:new p6({padding:O0.horizontal(1),child:O})}));let b=new r0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:$}),g=new S9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"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.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!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.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return u.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((D1)=>{u.error("Failed to mark message as interrupted:",D1)}),this.cancelStreamingMessage().catch((D1)=>{u.error("Failed to cancel streaming message:",D1)}),"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"}),k=new S9(()=>{return this.onExitPressed(),"handled"}),y=new S9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),f=new S9(()=>{return NQ.instance.toggleAll(),"handled"}),m=new S9(()=>{return this.widget.dependencies.configService.getLatest().then((w1)=>{BZ("internal.showCost",!(w1.settings["internal.showCost"]??!0))}),"handled"}),n=new S9(()=>{return $2.instance.toggleFrameStatsOverlay(),"handled"}),p=new S9(()=>{return $2.instance.tuiInstance.getScreen().markForRefresh(),U2.instance.requestFrame(),"handled"}),e=new S9(()=>{return this.toggleAgentMode(),"handled"}),G1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageUp(l1,100)}return"handled"}),U1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageDown(l1,100)}return"handled"}),Z1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(0,100);return"handled"}),F1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new S9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:w1}=this.widget.dependencies;if(!w1.mainThread?.messages.some((y1)=>y1.role==="user"))return"ignored";return this.messageViewFocusNode.requestFocus(),"handled"}),d=new S9((w1)=>{if(w1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[x6.ctrl("c"),new yp],[x6.ctrl("l"),new up],[x6.alt("s"),new pC],[x6.ctrl("s"),new pC],[x6.alt("p"),new mp],[x6.ctrl("r"),new hp],[x6.alt("d"),new gp],[x6.key("PageUp"),new DJ1],[x6.key("PageDown"),new MJ1],[x6.key("Home"),new VJ1],[x6.key("End"),new NJ1],[x6.key("Escape"),new bp],[x6.ctrl("p"),new dC("previous")],[x6.ctrl("n"),new dC("next")],[x6.key("Tab"),new LJ1]]);if(!1)i.set(x6.alt("c"),new fp),i.set(x6.ctrl("o"),new AJ1);let o=new S9(()=>{return this.showCommandPalette(),"handled"}),Y1=new Map([[bp,g],[up,p],[pC,e],[AJ1,o],[fp,y],[hp,f],[gp,m],[mp,n],[yp,k],[DJ1,G1],[MJ1,U1],[VJ1,Z1],[NJ1,F1],[LJ1,l],[dC,d]]),J1=[b];if(this.isShowingConsoleOverlay)J1.push(new Eu1);if(this.isShowingHelp)J1.push(new Tu1);if(this.adActionModal)J1.push(new Bu1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(w1)=>{let D1=this.adActionModal.url;if(w1==="copy")try{await $2.instance.tuiInstance.clipboard.writeText(D1),this.setState(()=>{this.displayMessage=new e9("Link copied to clipboard")})}catch(y1){u.error("Failed to copy to clipboard",{error:y1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)J1.push(new Og1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)J1.push(new Iu1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)J1.push(new ju1({details:this.confirmationOverlayContent}));if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)J1.push(new lu1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode}));let H1=this.getCommandPaletteContext(new AbortController);if(H1&&this.isShowingPalette){let w1=this.getThreadsForPicker();J1.push(new C9({child:new i0({constraints:w6.loose(80,20),child:new wu1({commandContext:H1,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,threads:w1,onThreadPreview:this.handleThreadPreview})})}))}if(this.isShowingIdePicker)J1.push(new Cu1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let z1=new IJ({children:J1});if(this.isShowingJetBrainsInstaller)return new DN({child:new UZ({actions:Y1,child:new pq({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new pu1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let W1=new MN({onError:(w1)=>{this.showErrorMessage(w1.message)},child:z1});return new DN({child:new UZ({actions:Y1,child:new pq({shortcuts:i,debugLabel:"main-app-shortcuts",child:W1})})})}buildBottomWidget(J,Q,Z,X,Y,K,G,q){if(J)return new Pu1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new $u1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new cu1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=TH9(X),W=this.isInRestrictedFreeMode(),F=new $J1({key:this.textFieldKey,controller:this.textController,triggers:[su1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(S)=>Ru1(S),overlayBorderColor:Z.border,focusNode:this.autocompleteFocusNode,textFieldProps:{placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.isTextfieldAndAutocompleteFocused&&!W,onSubmitted:this.onTextSubmitted,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:U,style:{border:null},clipboard:$2.instance.tuiInstance.clipboard},optionViewBuilder:(S,x,h)=>{let v=h?Z.selection:void 0,_=x.type==="command"?Z.warning:Z.secondary,b=Z.foreground,g=Z.foreground,k,y;switch(x.type){case"command":k="/",y=x.name;break;case"file":k="@",y=x.path;break;case"thread":k="",y=x.title;break;case"hint":k="",y=x.message;break;default:k="",y=Ru1(x);break}let f=RW6(x),m=new N1(k,new $1({color:_})),n=new N1(y,new $1({color:b})),p=[m,n];if(f){let e=new N1(" - ",new $1({color:g,dim:!0})),G1=new N1(f,new $1({color:g,dim:!0}));p.push(e,G1)}return new i0({decoration:new l8(v),child:new r1({text:new N1("",void 0,p),maxLines:1,overflow:"ellipsis"})})}}),H=Y.mainThread?.queuedMessages??[],B=this.currentShellModeStatus,M=this.imageAttachments.length>0?new i0({padding:O0.only({bottom:1,left:1}),child:new r1({text:new N1("",void 0,[new N1("Images: ",new $1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((S,x)=>[new N1(`[image ${x+1}]`,new $1({color:Z.success})),...x<this.imageAttachments.length-1?[new N1(" ")]:[]])])})}):null,V=Array.isArray(K)&&K.length>0,N=Array.isArray(H)&&H.length>0,L=[];if(M)L.push(M);L.push(new v8({child:F}));let A=new r0({crossAxisAlignment:"start",children:L}),w=N?new iu1({queuedMessages:H}):void 0,R=V?new _h1(new Fu1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,O=[];if(B)O.push({text:new N1(B==="hidden"?"shell mode (incognito)":"shell mode",new $1({color:B==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:M?1:0});let j=this.getEffectiveAgentMode();if(!B&&this.cachedVisibleModes.length>1){let S=Jp1(j),h=Kc(j,this.cachedVisibleModes)!==j,_=(lK()||this.widget.dependencies.worker).thread.messages.length===0,g=W||!this.hasToggledAgentMode&&h&&_?new N1("",void 0,[new N1(j,new $1({color:S})),new N1(" (click or ",new $1({color:Z.foreground,dim:!0})),new N1("Ctrl+S",new $1({color:z.keybind})),new N1(" to switch)",new $1({color:Z.foreground,dim:!0}))]):new N1(j,new $1({color:S}));O.push({text:g,position:"top-left",offsetY:0,onClick:_?this.toggleAgentMode:void 0})}let $=Y.mainThread?.metadata?.treeInfo?.uri,E;if($)E=w0.isUri($)?$.fsPath:$;else E=process.cwd();let I=this.toHomeRelative(E),T=this.shorten(I);return O.push({text:new N1(T,new $1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Hg1({leftChild:A,rightChild1:w,rightChild2:R,maxHeight:G,overlayTexts:O,borderColor:W||!this.isTextfieldAndAutocompleteFocused?E1.index(8):void 0,hasBanner:q!==null})}}async function NF6(J){let X=new QB(!1,1000,J.inspectorPort),Y=new $y1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=lK(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new MF6({...N,threadState:B})}}),K=new Lg1({configService:J.configService,child:Y}),G=new Mg1({configService:J.configService,child:K}),q=new lh1(G),z=new a6({data:lC.fromBaseTheme(tK.default()),child:q});try{await vh1(z,{onRootElementMounted:void 0})}finally{}let W=lK()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6497
6497
|
`),J.stdout.write(`Thread: ${H}
|
|
6498
6498
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6499
6499
|
`)}}function Jp1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):CH9(J)}function CH9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return E1.index(Z[X])}Sh1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){QG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6500
|
-
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function xH9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await vH9(Qp1.dirname(Zp1),{recursive:!0}),await kH9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function bH9(){try{return(await RF6(Zp1,"utf-8")).trim()}catch(J){return null}}function yH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var LF6=[{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??DX,description:`Custom settings file path (overrides the default location ${DX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ly1})`},{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:nK(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:qO}],AF6=(J)=>("deprecated"in J)&&J.deprecated===!0,fH9=(J)=>("hidden"in J)&&J.hidden===!0,hH9=(J)=>("default"in J),gH9=(J)=>("default"in J)?J.default:void 0;function mH9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new c9(iK.unknownCommand(Z),1,G)}}var OF6=null;function Z64(){return OF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new y_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(_H9.homedir()),jF6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.
|
|
6500
|
+
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function xH9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await vH9(Qp1.dirname(Zp1),{recursive:!0}),await kH9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function bH9(){try{return(await RF6(Zp1,"utf-8")).trim()}catch(J){return null}}function yH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var LF6=[{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??DX,description:`Custom settings file path (overrides the default location ${DX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ly1})`},{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:nK(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:qO}],AF6=(J)=>("deprecated"in J)&&J.deprecated===!0,fH9=(J)=>("hidden"in J)&&J.hidden===!0,hH9=(J)=>("default"in J),gH9=(J)=>("default"in J)?J.default:void 0;function mH9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new c9(iK.unknownCommand(Z),1,G)}}var OF6=null;function Z64(){return OF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new y_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(_H9.homedir()),jF6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.1761540104-g4e1704");let Z=hX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Kp1,userConfigDir:jF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (xQ1(),_Q1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=pa(PO({configService:Z})),G=F40({configService:Z,toolService:K}),q=VO0(K,k9,A11).catch((O)=>{u.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{u.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)SO("JetBrains");else if(Q.ide&&SZ6())SO("VS Code");else if(Q.ide&&vZ6())SO("Neovim");if(J.executeMode)kn1(!0);O26(K,{configService:Z});let U,W=T7.status.pipe(k0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(ms)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new $51(process.cwd(),{},!0);else F=new class extends $51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
|
|
6501
6501
|
`),!await uH9(J))await BR(),process.exit(1)}let H=await m40({isDevelopment:!1}),B=new kV1(H),M=new AB1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=$26({playNotificationSound:async(O)=>{if(V){j26(O);let j=Th1(),$=Ch1();if((!j||$)&&Y.settings["notifications.system.enabled"]!==!1){if(O==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(O==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});u.info("Starting Amp background services");let L=lq0({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;T7.status.subscribe((O)=>{A=O});let R={codebaseContextService:new fZ1({workspaceRoots:[w0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return w0.parse(A.openFile)}catch(O){u.warn("Failed to parse current file URI",{uri:A.openFile,error:O});return}},getOpenFiles:()=>{if(!A?.visibleFiles?.length)return[];let O=A.openFile;return A.visibleFiles.filter((j)=>j!==O).map((j)=>{try{return w0.parse(j)}catch($){return u.warn("Failed to parse visible file URI",{uri:j,error:$}),null}}).filter((j)=>j!==null)}}),configService:Z,toolService:K,mcpService:G,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?k40:k9};return{...R,async asyncDispose(){await R.mcpService.dispose(),await R.threadService.asyncDispose(),R.configService.unsubscribe(),R.toolService.dispose(),R.fuzzyServer.dispose(),R.threadSyncService.dispose(),R.settingsStorage[Symbol.dispose](),W.unsubscribe(),U?.dispose()}}}async function uH9(J){if(!J.executeMode){if(!await Kf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
|
|
6502
6502
|
`),!1}return await $F6(J)}async function $F6(J){let Q=SH9(32).toString("hex"),Z=await Yf1(J.ampURL,Q);try{await MY(Z)}catch(Y){u.error("Failed to open browser",{error:Y})}let X=await Yf1(J.ampURL,Q,!1);e2.write(`If your browser did not open automatically, visit:
|
|
6503
6503
|
|
|
@@ -6507,13 +6507,13 @@ ${z8.blue.bold(X)}
|
|
|
6507
6507
|
Login successful! You can now use the Amp CLI.
|
|
6508
6508
|
`),!0}catch(Y){return u.error("Login failed",{error:Y}),QG.write(`
|
|
6509
6509
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6510
|
-
`),!1}}function pH9(){let J=new Hu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.
|
|
6510
|
+
`),!1}}function pH9(){let J=new Hu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761540104-g4e1704 (released 2025-10-27T04:46:54.903Z)
|
|
6511
6511
|
`),process.exit(0)}),J.addHelpText("after",PZ6()),J.configureHelp({formatHelp:TZ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await iH9(H)}),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(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await lH9(H,await iy1(F,H.settings))});let Q=async(U,W,F)=>{hX1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:Kp1,userConfigDir:jF6});let H={...W,executeMode:!1};await Xp1(H,{...U,startWithPicker:!0},F)},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(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await wF6(F,H,W)});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(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await tH9(F,H,W)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);if(W.pick)QG.write(`${z8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6512
6512
|
`);if(W.last||U||B.executeMode)await oH9(H,B,U,F);else await Q(H,B,F)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await sH9(H,B,U,F)}),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(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await wF6(F,H,W)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await rH9(H,B,U,F,W.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(U,W,F,H)=>{let B=H.optsWithGlobals(),M=await NX(B);await nH9(B,M,U,W,H)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await aH9(H,B,U,F)}),vX6(J,async(U,W)=>{let F=await NX(W);cq(U,W);let H=await lq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:VR,asyncDispose:H.asyncDispose.bind(H)}}),GX6(J),tZ6(J,async(U)=>{let W=await NX(U);return{settings:W.settings,getThreadDeps:async(F)=>{cq(F,U);let H=await lq(W,U);return{mcpService:H.mcpService,asyncDispose:H.asyncDispose.bind(H)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);cq(W,F);let B=await lq(H,F);try{await Py1(B,B.configService,{})}finally{await B.asyncDispose(),await VR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new dV(W,B),V=gH9(U);if(V)M.default(V);if(M.hidden=fH9(U)||AF6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of LF6)switch(U.type){case"flag":{J.addOption(X(U,`--${U.long}`)),J.addOption(X(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(X(U,`--${U.long}`,!0));break}default:{J.addOption(X(U,`--${U.long} <value>`));break}}let Y=new dV("-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(Y);let K=new dV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let G=new dV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let q=new dV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new dV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let U=new dV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,W)=>{let F=U,H=await NX(F);if(Object.keys(F).forEach((B)=>{let M=LF6.find((V)=>V.name===B);if(M&&AF6(M)&&!hH9(M))QG.write(z8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6513
6513
|
`))}),W.args.length>0)mH9(H,W);await Xp1(H,F,W)}),iZ6(J),J}async function bQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Kz(),K=yQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await WJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,f51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(o7(z,"assistant"))await Yp1(Y),q.unsubscribe()});return await G.resume(),G}async function Xp1(J,Q,Z){let X=y51(Q);if(X instanceof Error)JG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Gf1()).trimEnd();if(R)K=R}else Y=(await Gf1()).trimEnd();if(Q.remote&&!J.executeMode)throw new c9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new c9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new c9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new c9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new c9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new c9("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new c9("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new c9("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
6514
6514
|
Or pipe via stdin: echo "your message" | amp --execute`);cq(Z,Q);let G=await lq(J,Q);OF6=G;let q=yQ1(G),z=async(R)=>{let O=await RF6(R,"utf-8"),j=JSON.parse(O);if(!AW(j.id))throw new c9(iK.invalidThreadId);return bQ1(G,{visibility:X,thread:j})},U=async(R)=>{if(!AW(R))throw new c9(iK.invalidThreadId);let O=await G.threadService.get(R)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),BZ("experimental.agentMode",O.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return bQ1(G,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return bQ1(G,{visibility:X})}catch(R){if(R instanceof c9)throw R;throw await V51(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return bQ1(G,{visibility:X})};if(Q.format==="jsonl")QG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6515
|
-
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await nr1();let R=await uB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)T7.selectConfig(O)}else B=!0}let V=Zf1("0.0.
|
|
6516
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eZ6(J.mcpConfig);X=yH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await iy1(J,X))}}function dH9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function cH9(){let J=dH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),xH9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6515
|
+
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await nr1();let R=await uB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)T7.selectConfig(O)}else B=!0}let V=Zf1("0.0.1761540104-g4e1704",G.settingsStorage),N=e1.of([w0.file(process.cwd())]),L=AS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await YJ.getUserFreeTierStatus({},{config:G.configService})}catch(R){A={ok:!1,error:R}}u.info("User free tier status:",A);let w=await FX6();u.info("Loaded session state:",w),await NF6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new ky1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:YJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:T7,connectedClientsService:new vc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await G.asyncDispose(),process.exit(0)}async function NX(J){if(J.interactive)QG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6516
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eZ6(J.mcpConfig);X=yH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await iy1(J,X))}}function dH9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function cH9(){let J=dH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),xH9(u),u.info("Starting Amp CLI.",{version:"0.0.1761540104-g4e1704",buildTimestamp:"2025-10-27T04:46:54.903Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c9(iK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await pH9().parseAsync(process.argv)}cH9().catch(V51);async function lH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6517
6517
|
`);else if(!PB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6518
6518
|
`);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
|
|
6519
6519
|
`),await Q.set("apiKey",Z,J.ampURL),e2.write(`API key successfully stored.
|
|
@@ -6536,7 +6536,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);cq(Z,Q);let G=await lq(
|
|
|
6536
6536
|
`),await X.asyncDispose(),process.exit(1)}}async function wF6(J,Q,Z){cq(Z,J);let X=await lq(Q,J);try{let Y=await PZ("/api/user",void 0,X.configService);if(!Y.ok)QG.write(`Failed to get user info: ${Y.status} ${await Y.text()}
|
|
6537
6537
|
`),process.exit(1);let G=(await Y.json()).id,q=await PZ(`/api/threads?createdByUserID=${G}`,void 0,X.configService);if(!q.ok)QG.write(`Failed to load threads: ${q.status} ${await q.text()}
|
|
6538
6538
|
`),process.exit(1);let z=await q.json();if(z.length===0)e2.write(`No threads found.
|
|
6539
|
-
`),process.exit(0);let U=["Title","Last Updated","Visibility","Messages","Thread ID"],W=z.map((F)=>{let H=F.title||"Untitled",B;switch(F.meta.visibility){case"
|
|
6539
|
+
`),process.exit(0);let U=["Title","Last Updated","Visibility","Messages","Thread ID"],W=z.map((F)=>{let H=F.title||"Untitled",B;switch(F.meta.visibility){case"public_unlisted":B="Unlisted";break;case"thread_workspace_shared":B="Workspace";break;case"private":default:if(F.meta.sharedGroupIDs.length>0)B=kJ(F.meta.sharedGroupIDs.length,"Group");else B="Private";break}let M=eH9(new Date(F.updatedAt||F.firstSyncAt));return[H,M,B,F.messageCount.toString(),F.id]});JB9(U,W,{columnFormatters:[(F,H)=>{return(F.length>H?F.substring(0,H-3)+"...":F).padEnd(H)},void 0,void 0,(F,H)=>F.padStart(H),(F,H)=>z8.green(F.padEnd(H))],truncateColumnIndex:0}),await X.asyncDispose(),process.exit(0)}catch(Y){await X.asyncDispose(),JG(`Error listing threads: ${Y instanceof Error?Y.message:String(Y)}
|
|
6540
6540
|
`)}}function eH9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/1000),Y=Math.floor(X/60),K=Math.floor(Y/60),G=Math.floor(K/24),q=Math.floor(G/7),z=Math.floor(G/30),U=Math.floor(G/365);if(X<60)return X<=1?"now":`${X}s ago`;else if(Y<60)return`${Y}m ago`;else if(K<24)return`${K}h ago`;else if(G<7)return`${G}d ago`;else if(q<4)return`${q}w ago`;else if(z<12)return`${z}mo ago`;else return`${U}y ago`}function JB9(J,Q,Z={}){let{columnFormatters:X=[],minimumTruncatedColumnWidth:Y=20,truncateColumnIndex:K}=Z;for(let N=0;N<Q.length;N++)if(Q[N].length!==J.length)throw Error(`Row ${N} has ${Q[N].length} columns, but headers have ${J.length} columns`);let G=e2.columns||120,q=" ",z=J.length-1,U=K??J.length-1,W=[];for(let N=0;N<J.length;N++)if(N===U)W.push(0);else W.push(Math.max(J[N].length,...Q.map((L)=>L[N].length)));let F=W.reduce((N,L)=>N+L,0)+z*q.length,H=Math.max(Y,G-F);W[U]=H;let B=W,M=J.map((N,L)=>N.padEnd(B[L])).join(q);e2.write(M+`
|
|
6541
6541
|
`);let V=B.map((N)=>"─".repeat(N)).join(q);e2.write(V+`
|
|
6542
6542
|
`);for(let N of Q){let L=N.map((A,w)=>{let R=B[w],O=X[w];if(O)return O(A,R);return(A.length>R?A.substring(0,R-3)+"...":A).padEnd(R)});e2.write(L.join(q)+`
|