@sourcegraph/amp 0.0.1753920106-g48ae72 → 0.0.1753948894-g23a9cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +5 -5
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -1337,7 +1337,7 @@ IMPORTANT: Always use the ${i7} tool to plan and track tasks throughout the conv
1337
1337
 
1338
1338
  `),A.id,B);return B?.throwIfAborted(),K}async runOpenAIInference(A,Q,B){let{systemPrompt:J,tools:D}=await Bt({...this.deps,filesystem:this.filesystem,latestConfig:Jt},A,{enableTodos:!0,enableTask:!0,enableOracle:!0},B);B?.throwIfAborted();let z=D.map((K)=>ME(Q,K)),Z=$z0.fromNativeThread(A);return jz0(Z,z,J.map((K)=>K.text).join(`
1339
1339
 
1340
- `),Q,B)}async findAndCancelToolRun(A,Q){if(this.cancelInference(),!EZ(this.thread,A))return;await this.cancelTool(A,Q)}async cancelToolOnly(A,Q){if(!EZ(this.thread,A))return;let J=this.cancelDataForToolRun(A);this.cancelSubthread(A);let D=this.ops.toolMessages[A];if(D)D.complete(),delete this.ops.toolMessages[A];this.abortToolOp(A),j1.debug(`cancelToolOnly(${A})`),await this.handle({type:"tool:data",toolUse:A,data:J},Q)}async sendToolRunMessage(A,Q){if(!EZ(this.thread,A))return;let J=this.ops.toolMessages[A];if(!J){if(this.ops.tools[A])j1.warn("unable to send message to tool, missing toolMessages",{id:A,messageType:Q.type});else j1.debug("tool message sent to completed/cancelled tool",{id:A,messageType:Q.type});return}J.next(Q)}async cleanupThreadBackups(A){try{await this.fileTracker.cleanupBackups(),j1.debug(`Cleaned up backup files for thread ${A}`,{threadID:A})}catch(Q){j1.error("Error cleaning up thread backups",Q,{threadID:A})}}cancelDataForToolRun(A){let B=wZ(this.thread).get(A)?.run;return{status:"cancelled",progress:B?lh1(B):void 0}}async cancelTool(A,Q){let B=this.cancelDataForToolRun(A);this.cancelSubthread(A),this.abortToolOp(A),j1.debug(`cancelToolRun(${A})`),await this.handle({type:"tool:data",toolUse:A,data:B},Q)}async cancel(){j1.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelUnstartedTools(),this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(new Error(Aw1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(j1.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}cancelSubthread(A){let Q=this.registeredSubthreads.get(A);if(Q&&Q.worker)Q.worker.cancel()}abortToolOp(A){this.ops.tools[A]?.abort(),delete this.ops.tools[A]}abortAllTools(){for(let A of Object.keys(this.ops.tools))this.abortToolOp(A)}trackFiles(A){for(let Q of A)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let A=await this.fileTracker.restoreFromBackups();j1.debug(`Restored ${A.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(A){j1.error("Error restoring file changes",A,{threadID:this.threadID})}}createToolUseFileChangeTracker(A){return this.fileTracker.createToolUseTracker(A)}async revertFileChanges(A){for(let Q of this.registeredSubthreads.values()){let B=Q?.worker;if(B)await B.revertFileChanges(A)}await this.fileTracker.revertAll(A),await this.updateFileChanges()}async cleanupForkThreads(A=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:A})}async cleanupFileChanges(A=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,A).forEach((J)=>{if(J.role==="user"){for(let D of J.content)if(D.type==="tool_result")Q.add(D.toolUseID)}else for(let D of J.content)if(D.type==="tool_use")Q.add(D.id)});let B=new Set;for(let[J]of this.fileTracker.records.entries())if(!Q.has(J))B.add(J);if(B.size===0)return;await this.fileTracker.revertChanges(B),await this.updateFileChanges()}async updateFileChanges(){let A=new $Q;for(let[B,J]of this.fileTracker.records.entries())for(let[D,z]of J.entries())if(!A.has(D)||z.timestamp>A.get(D).timestamp)A.set(D,z);let Q=[];for(let[B,J]of A.entries()){let{added:D,removed:z,modified:Z,created:K,reverted:G}=vz0(J);if(!D&&!z&&!Z)continue;Q.push({created:K,uri:j8(B),reverted:G,diffStat:{added:D,removed:z,modified:Z}})}this.cachedFileChanges=Q,this.mergeAndEmit()}mergeAndEmit(){let A=new $Q;for(let B of this.cachedFileChanges)A.set(B.uri,B);for(let B of this.registeredSubthreads.values())for(let J of B.latestFiles??[])A.set(J.uri,J);let Q=A.size;if(Q>50)j1.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...A.values()]})}emitSubthreads(){let A=Array.from(this.registeredSubthreads.values()).sort((Q,B)=>Q.sequenceNumber-B.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(A)}async registerSubthread(A,Q,B){if(this.registeredSubthreads.has(A))return;let J=await xZ.getOrCreateForSubThread(this.deps,Q);await J.resume();let D=J.status.pipe(Fz((z)=>z.state==="active"),E2((z)=>z.fileChanges.files),o$(this.disposed$)).subscribe((z)=>{let Z=this.registeredSubthreads.get(A);if(!Z)return;Z.latestFiles=z,this.mergeAndEmit()});this.registeredSubthreads.set(A,{threadID:Q,worker:J,fileChanges:D,toolUse:B,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}dispose(){if(this.isDisposed)return;j1.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length,fileTrackerRecords:this.fileTracker.records.size}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete();for(let A of this.registeredSubthreads.values())A.fileChanges?.unsubscribe(),A.worker?.dispose();if(this.registeredSubthreads.clear(),this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.summaryState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fileTracker.records.clear(),this.threadReadWriter)this.threadReadWriter.dispose(),this.threadReadWriter=null}}function XZ0(A,Q){let B=CJ(A,"assistant");if(!B||B.state.type!=="complete"||B.state.stopReason!=="tool_use")return!1;let J=B.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id);if(Q&&!J.includes(Q))throw new Error(`(bug) updated tool use ID not found in assistant message: ${Q}`);if(J.length===0)return!1;let D=wZ(A);return J.every((Z)=>{let K=D.get(Z);return K&&a7(K.run)})}var GZ0;var YZ0=$1(()=>{o8();x6();JY();Qw1();R6();K7();rM();MN();Ng();bq();qZ();bz0();mW1();_Q();ez0();OF1();DT();KZ0();GZ0=Td($2)});class qZ0{threadWorkers=Vx1();async getOrCreateForThread(A,Q){if(await A.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(A,Q);return this.getOrCreateForThreadInternal(A,Q)}async getOrCreateForSubThread(A,Q){let B=nL(A.toolService,fs);return this.getOrCreateForThreadInternal({...A,toolService:B},Q)}async getOrCreateForThreadInternal(A,Q){let B=this.threadWorkers.get(Q);if(!B){if(B=new pW1(A,Q),this.threadWorkers.set(Q,B),this.threadWorkers.map.size>10)j1.warn("High number of active thread workers - potential memory leak",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.map.size})}return cW1.record(this.threadWorkers.map.size),B}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(u9((A)=>A.size===0?UA.of({}):l4(...Array.from(A.values()).map((Q)=>Q.status.pipe(E2((B)=>[Q.threadID,Q.threadReadWriter?Cb(Q.thread,B):void 0])))).pipe(E2((Q)=>Object.fromEntries(Q)))),NJ(25),jQ())}get(A){return this.threadWorkers.get(A)}prettyPrintToolRun(A,Q,B){let J=this.threadWorkers.get(A);if(!J)throw new Error(`No worker found for thread ${A}`);for(let D of J.thread.messages)for(let z of D.content)if(z.type==="tool_result"&&z.toolUseID===Q)return zD0(z.run,B);throw new Error(`Tool run not found for thread ${A} and tool use ${Q}`)}async cancelToolRun(A,Q){await this.threadWorkers.get(A)?.findAndCancelToolRun(Q)}async cancelToolOnly(A,Q){await this.threadWorkers.get(A)?.cancelToolOnly(Q)}async sendToolRunMessage(A,Q,B){await this.threadWorkers.get(A)?.sendToolRunMessage(Q,B)}async cancel(A){await this.threadWorkers.get(A)?.cancel()}dispose(A){let Q=this.threadWorkers.get(A);if(Q)Q.dispose(),this.threadWorkers.delete(A),cW1.record(this.threadWorkers.map.size)}async retry(A){let Q=this.threadWorkers.get(A);if(!Q)throw new Error(`No active worker for thread ${A}`);await Q.retry()}async revertFileChanges(A,Q){let B=this.threadWorkers.get(A);if(!B)throw new Error(`No active worker for thread ${A}`);await B.revertFileChanges(Q)}async cleanupThreadBackups(A,Q){let B=this.threadWorkers.get(Q);if(B)await B.fileTracker.cleanupBackups();else{let J=A.createFileSystem({thread:Q,threadService:A.threadService});try{await new iR(J).cleanup(Q),j1.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(D){j1.error("Error cleaning up thread backups",D,{threadID:Q})}}}disposeAll(){for(let A of this.threadWorkers.map.values())A.dispose();this.threadWorkers.map.clear(),cW1.record(0)}}var UZ0,CeA,cW1,xZ;var DT=$1(()=>{UZ0=xA(jL(),1);x6();R6();bs();ZD0();qZ();TX1();YZ0();CeA=UZ0.metrics.getMeter("thread-worker-service"),cW1=CeA.createGauge("thread_worker_count",{description:"Number of active thread workers"});xZ=new qZ0});var HZ0={};t6(HZ0,{readFile:()=>FZ0,nodeChatLLMTool:()=>OeA,createPrompt:()=>dW1});function VeA({dirs:A,filesystem:Q},B,J,D,z){return new UA((Z)=>{(async()=>{try{if(Z.next({status:"in-progress",progress:{statusMessage:`Calling ${B}...`}}),z&&z.length>0)Z.next({status:"in-progress",progress:{statusMessage:`Reading ${z.length} context files...`}});let X=[{role:"user",content:await dW1(Q,A,D,z)}],U=(await uT(X,[],J,B)).message?.choices[0]?.message?.content||"No response received";Z.next({status:"done",result:U})}catch(G){let X=G instanceof Error?G.message:`Error: ${G}`;Z.next({status:"error",error:{message:X}})}Z.complete()})()})}function LeA({dirs:A,filesystem:Q},B,J,D,z){return new UA((Z)=>{(async()=>{try{if(Z.next({status:"in-progress",progress:{statusMessage:`Calling ${B}...`}}),z&&z.length>0)Z.next({status:"in-progress",progress:{statusMessage:`Reading ${z.length} context files...`}});let X=[{role:"user",parts:[{text:await dW1(Q,A,D,z)}]}],Y=Gw("thread"),U="",F=kn(B,X,[],J,Y);for await(let H of F){let E=H.candidates?.[0]?.content?.parts?.filter((w)=>w.text&&!w.thought)?.map((w)=>w.text)?.join("")||"";if(E)U+=E,Z.next({status:"in-progress",progress:{statusMessage:"Generating response...",partialResult:U}})}Z.next({status:"done",result:U||"No response received"})}catch(G){let X=G instanceof Error?G.message:`Error: ${G}`;Z.next({status:"error",error:{message:X}})}Z.complete()})()})}async function FZ0(A,Q,B){let J=await Ta(A,Q,B);return await A.readFile(J)}async function dW1(A,Q,B,J){if(!J||J.length===0)return B;let D=[];for(let Z of J)try{let K=await FZ0(A,Q,Z);D.push(`<file path="${Z}">
1340
+ `),Q,B,"low")}async findAndCancelToolRun(A,Q){if(this.cancelInference(),!EZ(this.thread,A))return;await this.cancelTool(A,Q)}async cancelToolOnly(A,Q){if(!EZ(this.thread,A))return;let J=this.cancelDataForToolRun(A);this.cancelSubthread(A);let D=this.ops.toolMessages[A];if(D){try{D.next({type:"stop-command"})}catch(z){j1.warn("Failed to send stop-command",{id:A,error:z})}D.complete(),delete this.ops.toolMessages[A]}this.abortToolOp(A),j1.debug(`cancelToolOnly(${A})`),await this.handle({type:"tool:data",toolUse:A,data:J},Q)}async sendToolRunMessage(A,Q){if(!EZ(this.thread,A))return;let J=this.ops.toolMessages[A];if(!J){if(this.ops.tools[A])j1.warn("unable to send message to tool, missing toolMessages",{id:A,messageType:Q.type});else j1.debug("tool message sent to completed/cancelled tool",{id:A,messageType:Q.type});return}J.next(Q)}async cleanupThreadBackups(A){try{await this.fileTracker.cleanupBackups(),j1.debug(`Cleaned up backup files for thread ${A}`,{threadID:A})}catch(Q){j1.error("Error cleaning up thread backups",Q,{threadID:A})}}cancelDataForToolRun(A){let B=wZ(this.thread).get(A)?.run;return{status:"cancelled",progress:B?lh1(B):void 0}}async cancelTool(A,Q){let B=this.cancelDataForToolRun(A);this.cancelSubthread(A);let J=this.ops.toolMessages[A];if(J){try{J.next({type:"stop-command"})}catch(D){j1.warn("Failed to send stop-command",{id:A,error:D})}J.complete(),delete this.ops.toolMessages[A]}this.abortToolOp(A),j1.debug(`cancelToolRun(${A})`),await this.handle({type:"tool:data",toolUse:A,data:B},Q)}async cancel(){j1.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelUnstartedTools(),this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(new Error(Aw1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(j1.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}cancelSubthread(A){let Q=this.registeredSubthreads.get(A);if(Q&&Q.worker)Q.worker.cancel()}abortToolOp(A){this.ops.tools[A]?.abort(),delete this.ops.tools[A]}abortAllTools(){for(let A of Object.keys(this.ops.tools)){let Q=A,B=this.ops.toolMessages[Q];if(B)try{B.next({type:"stop-command"}),B.complete(),delete this.ops.toolMessages[Q]}catch(J){j1.warn("Failed to send stop-command during disposal",{id:Q,error:J})}this.abortToolOp(Q)}}trackFiles(A){for(let Q of A)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let A=await this.fileTracker.restoreFromBackups();j1.debug(`Restored ${A.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(A){j1.error("Error restoring file changes",A,{threadID:this.threadID})}}createToolUseFileChangeTracker(A){return this.fileTracker.createToolUseTracker(A)}async revertFileChanges(A){for(let Q of this.registeredSubthreads.values()){let B=Q?.worker;if(B)await B.revertFileChanges(A)}await this.fileTracker.revertAll(A),await this.updateFileChanges()}async cleanupForkThreads(A=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:A})}async cleanupFileChanges(A=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,A).forEach((J)=>{if(J.role==="user"){for(let D of J.content)if(D.type==="tool_result")Q.add(D.toolUseID)}else for(let D of J.content)if(D.type==="tool_use")Q.add(D.id)});let B=new Set;for(let[J]of this.fileTracker.records.entries())if(!Q.has(J))B.add(J);if(B.size===0)return;await this.fileTracker.revertChanges(B),await this.updateFileChanges()}async updateFileChanges(){let A=new $Q;for(let[B,J]of this.fileTracker.records.entries())for(let[D,z]of J.entries())if(!A.has(D)||z.timestamp>A.get(D).timestamp)A.set(D,z);let Q=[];for(let[B,J]of A.entries()){let{added:D,removed:z,modified:Z,created:K,reverted:G}=vz0(J);if(!D&&!z&&!Z)continue;Q.push({created:K,uri:j8(B),reverted:G,diffStat:{added:D,removed:z,modified:Z}})}this.cachedFileChanges=Q,this.mergeAndEmit()}mergeAndEmit(){let A=new $Q;for(let B of this.cachedFileChanges)A.set(B.uri,B);for(let B of this.registeredSubthreads.values())for(let J of B.latestFiles??[])A.set(J.uri,J);let Q=A.size;if(Q>50)j1.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...A.values()]})}emitSubthreads(){let A=Array.from(this.registeredSubthreads.values()).sort((Q,B)=>Q.sequenceNumber-B.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(A)}async registerSubthread(A,Q,B){if(this.registeredSubthreads.has(A))return;let J=await xZ.getOrCreateForSubThread(this.deps,Q);await J.resume();let D=J.status.pipe(Fz((z)=>z.state==="active"),E2((z)=>z.fileChanges.files),o$(this.disposed$)).subscribe((z)=>{let Z=this.registeredSubthreads.get(A);if(!Z)return;Z.latestFiles=z,this.mergeAndEmit()});this.registeredSubthreads.set(A,{threadID:Q,worker:J,fileChanges:D,toolUse:B,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}dispose(){if(this.isDisposed)return;j1.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length,fileTrackerRecords:this.fileTracker.records.size}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete();for(let A of this.registeredSubthreads.values())A.fileChanges?.unsubscribe(),A.worker?.dispose();if(this.registeredSubthreads.clear(),this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.summaryState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fileTracker.records.clear(),this.threadReadWriter)this.threadReadWriter.dispose(),this.threadReadWriter=null}}function XZ0(A,Q){let B=CJ(A,"assistant");if(!B||B.state.type!=="complete"||B.state.stopReason!=="tool_use")return!1;let J=B.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id);if(Q&&!J.includes(Q))throw new Error(`(bug) updated tool use ID not found in assistant message: ${Q}`);if(J.length===0)return!1;let D=wZ(A);return J.every((Z)=>{let K=D.get(Z);return K&&a7(K.run)})}var GZ0;var YZ0=$1(()=>{o8();x6();JY();Qw1();R6();K7();rM();MN();Ng();bq();qZ();bz0();mW1();_Q();ez0();OF1();DT();KZ0();GZ0=Td($2)});class qZ0{threadWorkers=Vx1();async getOrCreateForThread(A,Q){if(await A.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(A,Q);return this.getOrCreateForThreadInternal(A,Q)}async getOrCreateForSubThread(A,Q){let B=nL(A.toolService,fs);return this.getOrCreateForThreadInternal({...A,toolService:B},Q)}async getOrCreateForThreadInternal(A,Q){let B=this.threadWorkers.get(Q);if(!B){if(B=new pW1(A,Q),this.threadWorkers.set(Q,B),this.threadWorkers.map.size>25)j1.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.map.size})}return cW1.record(this.threadWorkers.map.size),B}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(u9((A)=>A.size===0?UA.of({}):l4(...Array.from(A.values()).map((Q)=>Q.status.pipe(E2((B)=>[Q.threadID,Q.threadReadWriter?Cb(Q.thread,B):void 0])))).pipe(E2((Q)=>Object.fromEntries(Q)))),NJ(25),jQ())}get(A){return this.threadWorkers.get(A)}prettyPrintToolRun(A,Q,B){let J=this.threadWorkers.get(A);if(!J)throw new Error(`No worker found for thread ${A}`);for(let D of J.thread.messages)for(let z of D.content)if(z.type==="tool_result"&&z.toolUseID===Q)return zD0(z.run,B);throw new Error(`Tool run not found for thread ${A} and tool use ${Q}`)}async cancelToolRun(A,Q){await this.threadWorkers.get(A)?.findAndCancelToolRun(Q)}async cancelToolOnly(A,Q){await this.threadWorkers.get(A)?.cancelToolOnly(Q)}async sendToolRunMessage(A,Q,B){await this.threadWorkers.get(A)?.sendToolRunMessage(Q,B)}async cancel(A){await this.threadWorkers.get(A)?.cancel()}dispose(A){let Q=this.threadWorkers.get(A);if(Q)Q.dispose(),this.threadWorkers.delete(A),cW1.record(this.threadWorkers.map.size)}async retry(A){let Q=this.threadWorkers.get(A);if(!Q)throw new Error(`No active worker for thread ${A}`);await Q.retry()}async revertFileChanges(A,Q){let B=this.threadWorkers.get(A);if(!B)throw new Error(`No active worker for thread ${A}`);await B.revertFileChanges(Q)}async cleanupThreadBackups(A,Q){let B=this.threadWorkers.get(Q);if(B)await B.fileTracker.cleanupBackups();else{let J=A.createFileSystem({thread:Q,threadService:A.threadService});try{await new iR(J).cleanup(Q),j1.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(D){j1.error("Error cleaning up thread backups",D,{threadID:Q})}}}disposeAll(){for(let A of this.threadWorkers.map.values())A.dispose();this.threadWorkers.map.clear(),cW1.record(0)}}var UZ0,CeA,cW1,xZ;var DT=$1(()=>{UZ0=xA(jL(),1);x6();R6();bs();ZD0();qZ();TX1();YZ0();CeA=UZ0.metrics.getMeter("thread-worker-service"),cW1=CeA.createGauge("thread_worker_count",{description:"Number of active thread workers"});xZ=new qZ0});var HZ0={};t6(HZ0,{readFile:()=>FZ0,nodeChatLLMTool:()=>OeA,createPrompt:()=>dW1});function VeA({dirs:A,filesystem:Q},B,J,D,z){return new UA((Z)=>{(async()=>{try{if(Z.next({status:"in-progress",progress:{statusMessage:`Calling ${B}...`}}),z&&z.length>0)Z.next({status:"in-progress",progress:{statusMessage:`Reading ${z.length} context files...`}});let X=[{role:"user",content:await dW1(Q,A,D,z)}],U=(await uT(X,[],J,B)).message?.choices[0]?.message?.content||"No response received";Z.next({status:"done",result:U})}catch(G){let X=G instanceof Error?G.message:`Error: ${G}`;Z.next({status:"error",error:{message:X}})}Z.complete()})()})}function LeA({dirs:A,filesystem:Q},B,J,D,z){return new UA((Z)=>{(async()=>{try{if(Z.next({status:"in-progress",progress:{statusMessage:`Calling ${B}...`}}),z&&z.length>0)Z.next({status:"in-progress",progress:{statusMessage:`Reading ${z.length} context files...`}});let X=[{role:"user",parts:[{text:await dW1(Q,A,D,z)}]}],Y=Gw("thread"),U="",F=kn(B,X,[],J,Y);for await(let H of F){let E=H.candidates?.[0]?.content?.parts?.filter((w)=>w.text&&!w.thought)?.map((w)=>w.text)?.join("")||"";if(E)U+=E,Z.next({status:"in-progress",progress:{statusMessage:"Generating response...",partialResult:U}})}Z.next({status:"done",result:U||"No response received"})}catch(G){let X=G instanceof Error?G.message:`Error: ${G}`;Z.next({status:"error",error:{message:X}})}Z.complete()})()})}async function FZ0(A,Q,B){let J=await Ta(A,Q,B);return await A.readFile(J)}async function dW1(A,Q,B,J){if(!J||J.length===0)return B;let D=[];for(let Z of J)try{let K=await FZ0(A,Q,Z);D.push(`<file path="${Z}">
1341
1341
  ${K}
1342
1342
  </file>`)}catch(K){D.push(`<file path="${Z}">
1343
1343
  [Error reading file: ${K}]
@@ -4727,7 +4727,7 @@ ${F0.dim('--- Content truncated, use "View diff" for complete file ---')}`:"";re
4727
4727
  `});return}if(U.trim().length>0)P(U.trim());else return;return}if(!S.ctrl&&!S.meta&&!S.tab&&j)z({type:"insert-text",text:j})});let P=async(j)=>{W(null),Q.add(j),Q.reset();try{A(j)}catch(S){j1.error("Failed to submit message",S)}};return V6(DA,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:X,children:[D.imageAttachments.length>0&&V6(DA,{flexDirection:"row",marginBottom:1,children:[M0(FA,{color:"gray",children:"Images: "}),D.imageAttachments.map((j,S)=>V6(FA,{color:"green",children:["[image ",S+1,"]",S<D.imageAttachments.length-1?" ":""]},S))]}),E.lines.map((j,S)=>M0(DA,{flexShrink:0,flexDirection:"row",children:M0(DA,{flexGrow:1,flexShrink:0,width:"100%",children:S===I.line?V6(BZ,{children:[M0(FA,{dimColor:B,children:jS.default.substr(j.content,0,I.column)||""}),M0(FA,{inverse:!B,dimColor:B,children:jS.default(j.content)[I.column]??" "}),M0(FA,{dimColor:B,children:jS.default.substr(j.content,I.column+1)||""})]}):M0(FA,{dimColor:B,children:j.content||" "})})},S))]})}function e12(A,Q){let B=jS.default(A),J=Q,D=Q;while(J>0&&/\S/.test(B[J-1]||""))J--;while(D<B.length&&/\S/.test(B[D]||""))D++;let z=B.slice(J,D).join("");if(!z.trim())return null;return{word:z,start:J,end:D}}var PS=xA(J8(),1);PE();var U51=xA(J8(),1);function v7A(){let[A,Q]=U51.useState(null);return U51.useEffect(()=>{let B=Yi.subscribe(Q);return()=>{B.unsubscribe()}},[]),{jetbrainsState:A}}DB1();var Qy1=xA(J8(),1);function k7A({viewState:A}){let Q=Qy1.useMemo(()=>{return A.state==="active"?A.fileChanges:void 0},[A]),B=Qy1.useMemo(()=>Am1(Q),[Q]);if(!Q||B.totalFiles===0)return null;let J=B.totalFiles-B.revertedFiles;return V6(DA,{gap:1,children:[V6(FA,{dimColor:!0,children:[J," ",J===1?"file":"files"," changed"]}),(B.totalAdded>0||B.totalModified>0||B.totalRemoved>0)&&V6(FA,{children:[V6(FA,{color:"green",children:["+",B.totalAdded]}),V6(FA,{color:"yellow",children:[" ~",B.totalModified]}),V6(FA,{color:"red",children:[" -",B.totalRemoved]})]})]})}import f7A from"node:path";function y7A({jetbrainsStatus:A}){if(!A||!A.enabled)return null;let Q=process.cwd(),B=A.productName&&A.openFile&&A.workspace===Q,J;if(!A.productName)J=" IDE Not Running. To fix this problem, start your JetBrains IDE, exit this session and run `amp threads continue`.";else if(!A.workspace&&!A.openFile)J=" No Open File. To fix this problem, open a project and open a file in your JetBrains IDE.";else if(!A.workspace&&A.openFile){let D=f7A.basename(A.openFile);if(A.openFile.includes("!/"))J=` External File Open. The open file '${A.openFile}' does not belong to your project root. To fix this problem, open a file in your project sources and try again.`;else J=` Project Detection Failed. Failed to map your open file '${D}' to a project root directory. Please note that multi-root projects are not supported at the moment. Please report a bug on https://ampcode.com/discord and include relevant logs from ~/.cache/amp/logs/cli.log`}else if(!A.openFile)J=" No Open File. To fix this problem, open a file in your project.";else if(A.workspace!==Q)J=` Project Mismatch. The currently open project "${A.workspace}" does not match the working directory of Amp CLI ("${Q}").`;return M0(DA,{gap:B?1:2,children:V6(FA,{color:B?"green":"red",children:[B?"✓":"×"," ",A.productName??"JetBrains"," ",B?"• "+f7A.basename(A.openFile??""):J]})})}var q51=xA(J8(),1);function b7A(){let[A,Q]=q51.useState(0);q51.useEffect(()=>{let D=setInterval(()=>{Q((z)=>z+1)},200);return()=>clearInterval(D)},[]);let B=[{char:"∿",dim:!1},{char:"∾",dim:!1},{char:"∽",dim:!1},{char:"≋",dim:!1},{char:"≈",dim:!1},{char:"∼",dim:!1}],J=B[A%B.length];return M0(FA,{dimColor:J.dim,children:J.char})}var A02=0.8,Q02=0.9;function g7A({tokenUsage:A}){let Q=A.totalInputTokens/A.maxInputTokens,B=Math.round(Q*100),D=`${Math.max(0,Math.min(B,100))}%`,z,Z=x7A(Q);if(Z==="danger")z="red";else if(Z==="warning")z="yellow";return M0(FA,{color:z,children:D})}function x7A(A){if(A>=Q02)return"danger";else if(A>=A02)return"warning";return!1}function h7A(A){let Q=A.totalInputTokens/A.maxInputTokens;return x7A(Q)}function m7A({threadViewState:A,tokenUsage:Q,waitingForConfirmation:B,showingEphemeralError:J}){let D=null,z=Q?h7A(Q):!1,Z=!1;if(A&&A.state==="active"){if(A.summaryState==="summarizing")D="Compacting...";else if(A.inferenceState==="running")D="Running inference...";else if(A.interactionState==="tool-running")D="Running tools...";else if(!J&&z==="warning")D="Context window is almost full. Use /compact to trim the thread.",Z=!0;else if(!J&&z==="danger")D="Context window is close to full. Use /compact to trim the thread.",Z=!0}let K=Boolean(A&&A.state==="active"&&A.inferenceState!=="cancelled"&&!Z&&!B);if(!A||A.state!=="active"||!D)return null;let X=()=>{if(A.inferenceState==="running"&&A.interactionState!=="tool-running")return"blueBright";if(A.interactionState==="tool-running")return"greenBright";return"default"},Y=()=>{if(Z&&z==="warning")return"yellow";if(Z&&z==="danger")return"red";if(A.inferenceState==="cancelled")return"dim";return"default"};return V6(DA,{flexDirection:"row",gap:1,children:[K&&M0(FA,{color:X(),children:M0(b7A,{})}),M0(FA,{italic:!Z&&A.inferenceState==="cancelled",color:Y(),children:D})]})}function u7A({view:A,threadViewState:Q,threadTokenUsage:B,hasCompletedMessages:J,width:D}){let{jetbrainsState:z}=v7A(),Z=PS.useRef(null),{stdout:K}=jX(),[G,X]=PS.useState(K.columns);PS.useEffect(()=>{if(Z.current){let{width:E}=LV(Z.current);X(E)}},[K.columns]);let Y=D||G,U=Y&&Y<60,F=A==="confirming"||A==="ephemeral-error",H=Q.state==="active"&&(Q.inferenceState==="running"||Q.interactionState==="tool-running")&&!F;return V6(DA,{gap:2,marginLeft:2,marginRight:2,ref:Z,children:[V6(DA,{flexGrow:1,flexDirection:"row",gap:2,children:[M0(m7A,{threadViewState:Q,tokenUsage:B,waitingForConfirmation:F,showingEphemeralError:A==="ephemeral-error"}),H&&M0(DA,{children:M0(FA,{dimColor:!0,children:"Esc to cancel"})}),V6(DA,{children:[A==="confirming-exit"&&M0(FA,{dimColor:!0,children:"Ctrl+C again to exit"}),A==="confirming-clear-input"&&M0(FA,{dimColor:!0,children:"Esc again to clear input"}),A==="help"&&M0(FA,{dimColor:!0,children:"Escape to close help"}),J&&A==="running"&&!U&&M0(FA,{dimColor:!0,children:"Ctrl+R to expand"})]})]}),V6(DA,{flexGrow:0,gap:2,children:[M0(y7A,{jetbrainsStatus:z}),!U&&M0(k7A,{viewState:Q}),B&&M0(g7A,{tokenUsage:B})]})]})}R6();F0.level=1;var B02={code:F0.white,codespan:F0.white,blockquote:F0.gray.italic,html:F0.gray,heading:F0.bold,firstHeading:F0.bold,hr:F0.reset,table:F0.reset,paragraph:F0.reset,strong:F0.bold,em:F0.italic,del:F0.dim.gray.strikethrough,link:F0.cyan,href:F0.cyan,unescape:!0,emoji:!0,showSectionPrefix:!0,reflowText:!1,tab:4,tableOptions:{wordWrap:!0,wrapOnWordBoundary:!1,style:{head:["bold"],border:["grey"],compact:!1}}},J02={keyword:F0.bold,built_in:F0.dim,type:F0.dim,literal:F0.italic,number:F0.reset,regexp:F0.dim.italic,string:F0.dim,subst:F0.reset,symbol:F0.reset,class:F0.bold,function:F0.reset,title:F0.reset,params:F0.reset,comment:F0.dim.italic,doctag:F0.dim.italic,meta:F0.dim,"meta-keyword":F0.reset,"meta-string":F0.reset,section:F0.reset,tag:F0.dim,name:F0.bold,"builtin-name":F0.reset,attr:F0.dim,attribute:F0.reset,variable:F0.reset,bullet:F0.reset,code:F0.reset,emphasis:F0.italic,strong:F0.bold,formula:F0.reset,link:F0.underline,quote:F0.reset,"selector-tag":F0.reset,"selector-id":F0.reset,"selector-class":F0.reset,"selector-attr":F0.reset,"selector-pseudo":F0.reset,"template-tag":F0.reset,"template-variable":F0.reset,addition:F0.bold.underline,deletion:F0.dim.strikethrough,default:F0.reset};D9.use(u2A({...B02,reflowText:!1},{ignoreIllegals:!0,theme:J02}));function F51({children:A}){let Q;try{Q=D9(A,{async:!1}).trimEnd()}catch(B){j1.error("Markdown rendering failed",B,{input:A}),Q=A}return M0(FA,{children:Q})}function p7A({message:A}){let Q=A.content.filter((B)=>B.type==="thinking"||B.type==="text");if(!Q.length)return null;return M0(DA,{flexDirection:"column",marginBottom:1,children:Q.map((B,J)=>{let D=J>0?1:0;if(B.type==="thinking")return M0(Y51,{thinking:B.thinking},J);else return M0(DA,{marginTop:D,children:M0(F51,{children:B.text})},J);return null})})}function c7A({message:A,marginTop:Q=0}){if(!A.content.some((X)=>X.type==="text"||X.type==="image"||X.type==="thinking"||X.type==="summary"&&X.summary.type==="message"))return null;let J=A.role==="assistant"&&A.state.type==="cancelled",D=A.content.filter((X)=>X.type==="text"),z=A.content.filter((X)=>X.type==="image"),Z=A.content.filter((X)=>X.type==="thinking"),K=A.content.filter((X)=>X.type==="summary"&&("summary"in X)&&X.summary.type==="message"),G=()=>{if(z.length===0)return null;return V6(DA,{flexDirection:"row",gap:1,marginBottom:1,children:[M0(FA,{color:"gray",children:"Images:"}),z.map((X,Y)=>{return V6(FA,{color:"green",children:["[image ",Y+1,"]"]},`img-${Y}`)})]})};return V6(DA,{flexDirection:"column",gap:1,marginTop:Q,children:[Z.map((X,Y)=>M0(Y51,{thinking:X.thinking},`thinking-${Y}`)),D.map((X,Y)=>{switch(A.role){case"assistant":return M0(DA,{flexDirection:"column",children:M0(F51,{children:X.text})},Y);case"user":return V6(DA,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,flexDirection:"column",children:[G(),M0(FA,{color:"green",italic:!0,children:X.text})]},Y);default:return null}}),K.map((X,Y)=>M0(DA,{children:V6(FA,{color:"grey",italic:!0,children:["Summary: ",X.summary.summary]})},`summary-${Y}`)),J&&M0(DA,{children:M0(FA,{italic:!0,dimColor:!0,children:"Cancelled"})})]})}function d7A({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return V6(DA,{borderStyle:"round",borderColor:"dim",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[M0(DA,{children:M0(FA,{dimColor:!0,bold:!0,children:"TODOs"})}),A.map((Q,B)=>M0(DA,{gap:1,children:V6(FA,{dimColor:!0,wrap:"truncate",children:[M0(FA,{children:"• "}),M0(FA,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}var _I=xA(J8(),1);function By1({children:A,dependencies:Q}){let{stdout:B}=jX(),J=_I.useRef(null),[D,z]=_I.useState(B.columns),Z=_I.useCallback(()=>{if(J.current){let{width:K}=LV(J.current);z(K)}},[J,z]);return _I.useLayoutEffect(Z,[Z,B.columns,...Q||[]]),M0(DA,{width:"100%",height:"100%",ref:J,children:A(D)})}R6();x6();var TB=xA(J8(),1),H51=Object.freeze({query:"",options:[]});function l7A(A){let[Q,B]=TB.useState(H51),[J,D]=TB.useState(""),[z,Z]=TB.useState(null),K=TB.useRef(0),[G]=TB.useState(()=>new y8),X=TB.useCallback((E)=>{if(D(E),E!==z)Z(null)},[z]),Y=TB.useCallback(()=>Z(J),[J]),U=TB.useCallback((E)=>{G.next(E)},[G]),F=TB.useMemo(()=>J.startsWith("@")?J.slice(1):null,[J]);TB.useEffect(()=>{if(F!==null&&J!==z){let w=++K.current;(async()=>{try{let I=await A.query(F);if(w===K.current)B({query:F,options:I})}catch(I){if(w===K.current)j1.error("Completion request failed",{query:F,error:I}),B(H51)}})()}else B(H51)},[J,z,A,F]),TB.useEffect(()=>{return()=>{G.complete()}},[G]);let H=TB.useMemo(()=>{if(F===null)return!1;return F.startsWith(Q.query)&&z!==J&&J!==""},[Q,J,z,F]);return{completions:H?Q:H51,hasCompletions:H?Q.options.length>0:!1,selectCompletion:U,completionSelected:G,onWordHighlight:X,ignore:Y}}var E51=xA(J8(),1);function i7A(A){let Q=E51.useMemo(()=>process.cwd().replace(process.env.HOME||"","~"),[]);E51.useEffect(()=>{if(A)process.stdout.write(`\x1B]0;amp - ${A} - ${Q}\x07`);return()=>{process.stdout.write("\x1B]0;\x07")}},[A,Q])}var w51=xA(J8(),1);function a7A(){return M0(DA,{flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:3,marginLeft:4,children:M0(DA,{children:M0(FA,{color:"green",bold:!0,children:"Welcome to Amp"})})})}function r7A(){let[A,Q]=w51.useState(0),B=["Amp","AMP","AmP","amP","aMP","AMp"];return w51.useEffect(()=>{let J=setInterval(()=>{Q((D)=>(D+1)%B.length)},50);return()=>clearInterval(J)},[B.length]),M0(DA,{flexDirection:"column",alignItems:"flex-start",justifyContent:"center",minHeight:3,marginLeft:4,children:M0(DA,{children:V6(FA,{color:"green",bold:!0,children:["Welcome to ",B[A]]})})})}var D02=200;function n7A({threadService:A,history:Q,worker:B,sendToolConfirmation:J,sendUserMessage:D,exit:z,cancel:Z,ampURL:K,commands:G,fuzzyClient:X}){let[Y]=X51(),{viewState:U,subagents:F,subagentActiveTools:H,transcript:E,streamingAssistantMessage:w,todosList:W,mainThread:I}=L5A(A,B),M=I?.title||"Untitled",N=B5.useMemo(()=>I?Fm1(I):void 0,[I]);i7A(I?.title);let O=B5.useRef(new y8),[L,T]=B5.useState({baseView:"running",rerendering:!1,resizeCounter:0,dismissedEphemeralError:null,slashCommandQuery:null,uiError:null}),R=B5.useRef(null),P=B5.useRef(null),j=B5.useRef(null),[S,v]=I7A(),g=B5.useCallback((K1)=>{T((X1)=>({...X1,slashCommandQuery:K1}))},[]),u=B5.useMemo(()=>{if(L.slashCommandQuery===null)return[];return G.query(L.slashCommandQuery)},[L.slashCommandQuery,G]),_=B5.useCallback(()=>{T((K1)=>({...K1,rerendering:!0})),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),O.current.next()},[T,O]),k=B5.useCallback(()=>{if(L.baseView==="confirming-clear-input"){if(P.current)clearTimeout(P.current),P.current=null;v({type:"clear"}),T((K1)=>({...K1,baseView:"running"}))}else{if(T((X1)=>({...X1,baseView:"confirming-clear-input"})),P.current)clearTimeout(P.current);let K1=setTimeout(()=>{T((X1)=>({...X1,baseView:"running"})),P.current=null},1000);P.current=K1}},[L.baseView,v,T]),b=B5.useCallback(async(K1)=>{if(T((E1)=>({...E1,slashCommandQuery:null})),!K1||!I)return;let X1=!1,R1=(E1)=>{X1=!0,v(E1)},I1=()=>{T((E1)=>({...E1,baseView:"help"}))},W1=await G.get(K1).execute({worker:B,thread:I,editorDispatch:R1,exitApp:z,openHelp:I1});if(T((E1)=>({...E1,uiError:W1||null})),!X1)v({type:"clear"})},[G,v,I,B,z]),m=B5.useCallback((K1)=>{let X1=[{type:"text",text:K1}];if(S.imageAttachments.length>0)X1.push(...S.imageAttachments);v({type:"clear"}),D(X1)},[v,S.imageAttachments,D]);B5.useEffect(()=>{return process.stdout.on("resize",_),()=>{process.stdout.off("resize",_)}},[_]),B5.useEffect(()=>{let K1=O.current.pipe(NJ(D02)).subscribe(()=>{T((X1)=>({...X1,rerendering:!1,resizeCounter:X1.resizeCounter+1}))});return()=>{K1.unsubscribe()}},[O,T]),B5.useEffect(()=>{let K1=O.current;return()=>{if(K1.complete(),R.current)clearTimeout(R.current);if(P.current)clearTimeout(P.current)}},[O]);let $=[...E.activeTools,...H],h=$.filter((K1)=>K1.toolRun.status==="blocked-on-user"),d=B5.useMemo(()=>B7A(h),[h]),l=l7A(X),{hasCompletions:B1,completions:n,selectCompletion:z1}=l,Q1=B5.useMemo(()=>{if(U.state!=="active"||!U.ephemeralError)return null;if(L.dismissedEphemeralError===U.ephemeralError)return null;return U.ephemeralError},[U,L.dismissedEphemeralError]),G1=L.uiError!==null?"ui-error":Q1!==null?"ephemeral-error":d!==null?"confirming":L.baseView,D1=(K1)=>{if(!d||d.type!=="tool-use")return;if(K1==="view-diff"){z7A(d).catch((X1)=>{j1.error("failed to handle view-diff action:",X1)});return}if(d.tools.length>0){let X1=d.tools[0],R1=Array.from(K1==="always"?X1.toAllow??[]:[]);J(X1.useBlock.id,K1==="yes"||K1==="always",R1,d.subthreadID)}},L1=(K1)=>{switch(K1){case"compact":T((X1)=>({...X1,dismissedEphemeralError:null})),B.summarizeThread();break;case"dismiss":T((X1)=>({...X1,dismissedEphemeralError:Q1}));break;case"retry":T((X1)=>({...X1,dismissedEphemeralError:null})),B.retry();break;default:j1.warn("action:",{action:K1})}},a=()=>{T((K1)=>({...K1,uiError:null}))};dH((K1,X1)=>{if(X1.ctrlC){if(L.baseView==="confirming-exit"){if(R.current)clearTimeout(R.current),R.current=null;z()}else{if(T((I1)=>({...I1,baseView:"confirming-exit"})),R.current)clearTimeout(R.current);let R1=setTimeout(()=>{T((I1)=>({...I1,baseView:"running"})),R.current=null},1000);R.current=R1}return}if(G1==="help"){if(X1.escape)T((R1)=>({...R1,baseView:"running"}));return}if(G1==="expanded-view"||G1==="confirming"||G1==="ephemeral-error")return;if(G1==="ui-error")return;if(X1.escape){if(B1||u.length>0)return;if(U.state==="active"&&U.inferenceState==="running"){Z();return}if(S.input.trim().length>0){k();return}}else if(X1.ctrl&&K1.toLowerCase()==="r")T((R1)=>({...R1,baseView:"expanded-view"}));else if(X1.ctrlL)_()});let r=Y>100,s=L.rerendering&&E.items.length===0?1:"auto",J1="resize-key"+L.resizeCounter,Z1=[{type:"welcome",id:"welcome"},...E.items];if(L.baseView==="expanded-view")return M0(O7A,{threadName:M,transcriptItems:E.items,onExit:()=>T((K1)=>({...K1,baseView:"running"}))});return V6(DA,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:s,children:[M0(p41,{items:Z1,children:(K1,X1)=>{if(K1.type==="welcome")return M0(a7A,{},"welcome");let R1=X1===0?0:1;return K1.type==="message"?M0(c7A,{message:K1.message,marginTop:R1},K1.id):M0(e5A,{toolUse:K1.toolUse,toolResult:K1.toolResult,marginTop:R1},K1.id)}},J1),V6(DA,{flexDirection:"column",marginTop:Z1.length>1?1:0,children:[w&&M0(p7A,{message:w}),M0(v5A,{activeTools:$,subagents:F}),V6(DA,{flexDirection:r?"row-reverse":"column",children:[W.length>0&&M0(DA,{ref:j,flexGrow:0,flexShrink:0,width:r?"50%":"100%",children:M0(d7A,{todos:W})}),G1==="ui-error"&&L.uiError?M0(K51,{title:gf1(L.uiError).title,description:gf1(L.uiError).description,options:[{value:"dismiss",label:"Dismiss"}],onSelect:a}):G1==="ephemeral-error"&&Q1?M0(N7A,{error:Q1,onResponse:L1,ampURL:K}):G1==="confirming"&&d?M0(K7A,{currentConfirmation:d,onConfirmationResponse:D1}):G1==="help"?M0(By1,{dependencies:[W],children:(K1)=>M0(T7A,{width:K1})}):M0(DA,{flexGrow:1,borderStyle:"round",paddingX:1,children:M0(By1,{dependencies:[W],children:(K1)=>M0($7A,{onSubmit:m,history:Q,disabled:G1==="confirming"||G1==="ephemeral-error"||U.state==="active"&&U.summaryState==="summarizing",viewState:U,editorState:S,editorDispatch:v,onSlashCommandQuery:g,width:K1,completionsState:l})})})]}),M0(u7A,{view:G1,threadViewState:U,threadTokenUsage:N,hasCompletedMessages:E.items.length>0}),M0(z02,{commands:u,onSelect:b}),M0(Z02,{completions:n.options,onSelect:z1})]})]})}function z02({commands:A,onSelect:Q}){let J=B5.useMemo(()=>A.slice(0,10).map((D)=>({value:D.name,label:D.name,description:D.description})),[A]);return M0(DA,{marginBottom:1,children:M0(_V,{title:"Select command:",options:J,onSelect:Q})})}function Z02({completions:A,onSelect:Q}){let B=Math.min(10),J=B5.useMemo(()=>A.slice(0,B).map((z)=>({value:z,label:z})),[A,B]),D=B5.useCallback((z)=>{if(z===null)return;let Z=A.find((K)=>K===z);if(!Z)return;Q(Z)},[A,Q]);if(J.length===0)return null;return M0(DA,{marginBottom:1,children:M0(_V,{title:"Insert file name:",options:J,onSelect:D})})}function s7A(A){let{worker:Q,threadID:B,settingsStorage:J,pipedInput:D,workerDeps:z,configService:Z,fuzzyServer:K}=A,[G,X]=PX.useState(!1);N5A();let Y=PX.useCallback((W,I,M,N)=>{return K02(W,I,M,N,J,Q,z)},[J,Q,z]),U=PX.useCallback(async(W)=>{await Q.handle({type:"user:message",message:{content:W}})},[Q]),{exit:F}=yf1(),H=PX.useCallback(()=>{xZ.cancel(B)},[B]);PX.useEffect(()=>{let W=setTimeout(()=>{X(!0)},500);return()=>clearTimeout(W)},[]);let E=PX.useRef(!1);if(PX.useEffect(()=>{if(E.current)return;if(D)E.current=!0,U([{type:"text",text:D}]),X(!0)},[D,U]),!G)return M0(r7A,{});let w=new xf1;return M0(F5A,{configService:Z,children:M0(n7A,{history:A.history,threadService:A.threadService,worker:Q,sendToolConfirmation:Y,sendUserMessage:U,exit:F,cancel:H,ampURL:A.ampURL,commands:w,fuzzyClient:K})})}async function K02(A,Q,B,J,D,z,Z){let K=B&&B.length>0||!1;if(B&&B.length>0)await C6($2).then((X)=>X.settings["experimental.commandApproval.enabled"]?"experimental.commandApproval.allow":"commands.allowlist").then((X)=>{D.get(X,"global").then((Y)=>{let U=[...Y??[],...B];return D.set(X,U,"global")}).catch((Y)=>{j1.error("Failed to update allowlist",Y)})});let G={type:"user:tool-input",toolUse:A,value:{accepted:Q||K}};if(J)(await xZ.getOrCreateForThread(Z,J)).handle(G);else z.handle(G)}global.React=Jy1.default;function o7A(A){return F0.level=1,ff1(Jy1.default.createElement(s7A,{...A}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout,stdin:A.stdin}).waitUntilExit().then(async()=>{let{threadID:B,ampURL:J,threadService:D}=A;if((await D.get(B))?.messages.length!==0){let Z=`${J.replace(/\/$/,"")}/threads/${B}`;A.stdout.write(`
4728
4728
  `),A.stdout.write(`${F0.dim("Thread:")} ${Z}
4729
4729
  `),A.stdout.write(`${F0.dim("Continue this thread with:")} amp threads continue ${B}
4730
- `)}})}var Ky1=Zy1.join(Np0||Zy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function Gy1(A){try{await E02(Zy1.dirname(Ky1),{recursive:!0}),await W02(Ky1,A,"utf-8")}catch(Q){j1.debug("Failed to save last thread ID",Q)}}async function BQA(){try{return(await w02(Ky1,"utf-8")).trim()}catch(A){return null}}async function I02(A){let Q=await vQ(`/api/threads/${A}`);if(!Q.ok){let B=await Q.text();if(Q.status===404||B.includes("not found"))throw new eD(TK.threadNotFound(A));throw new eD(`Failed to load thread ${A}`,1,`Use 'amp threads share ${A} --support' to share this with the Amp team if this persists.`)}return await Q.json()}var KQA=process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,JQA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??NI,description:`Custom settings file path (overrides the default location ${NI})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{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:KQA,description:(A)=>A?"Enable JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.":"Disable JetBrains integration.",hidden:!0},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0}],DQA=(A)=>("deprecated"in A)&&A.deprecated===!0,M02=(A)=>("hidden"in A)&&A.hidden===!0,N02=(A)=>("default"in A),C02=(A)=>("default"in A)?A.default:void 0;function O02(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((K)=>B.includes(K)||K.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new eD(TK.unknownCommand(B),1,Z)}}async function _S(A,Q){Cm1("0.0.1753920106-g48ae72");let B=j$1(gp()),J=A.settings,D=VB1({storage:J,secretStorage:B,workspaceRoots:UA.of([c6.file(process.cwd())]),defaultAmpURL:A.ampURL,defaultCacheDirectory:V$1}),z=await C6($2);j1.debug("Global configuration initialized",{hasCacheDirectory:!!z.settings.cacheDirectory,settingsKeys:Object.keys(z.settings)});let Z=await wf(Mv()),K=Cr1({configService:D,toolService:Z});try{await K.initialized}catch(O){j1.warn("Failed to wait for MCP servers, continuing anyway:",O)}if(Q.dangerouslyAllowAll)z.settings.dangerouslyAllowAll=!0;if(Q.jetbrains){if(z.settings["jetbrains.enabled"]=!0,Yi.subscribe((L)=>{j1.info("jetbrains-status",L)}),await jE(),!await Cc1())if(KQA)MQ("JetBrains integration failed. Try again with `amp --no-jetbrains` or see setup: https://ampcode.com/manual#jetbrains");else MQ("Cannot connect to JetBrains IDE. Check setup: https://ampcode.com/manual#jetbrains")}let G=z.settings["experimental.reviewTool"]??!1,X=z.settings["experimental.tools"]??[];R_1(Z,!1,G,X);let Y,U;if(!A.executeMode)Y=new Gk1(z.settings,process.cwd()),await Y.start(),U=q8A(Y,process.cwd());else Y=new class{async start(){}async query(){return[]}dispose(){}},U={[Symbol.dispose]:()=>{}};if(!await B.get("apiKey",A.ampURL)){if(A4.write(`No API key found. Starting login flow...
4730
+ `)}})}var Ky1=Zy1.join(Np0||Zy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function Gy1(A){try{await E02(Zy1.dirname(Ky1),{recursive:!0}),await W02(Ky1,A,"utf-8")}catch(Q){j1.debug("Failed to save last thread ID",Q)}}async function BQA(){try{return(await w02(Ky1,"utf-8")).trim()}catch(A){return null}}async function I02(A){let Q=await vQ(`/api/threads/${A}`);if(!Q.ok){let B=await Q.text();if(Q.status===404||B.includes("not found"))throw new eD(TK.threadNotFound(A));throw new eD(`Failed to load thread ${A}`,1,`Use 'amp threads share ${A} --support' to share this with the Amp team if this persists.`)}return await Q.json()}var KQA=process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,JQA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??NI,description:`Custom settings file path (overrides the default location ${NI})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{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:KQA,description:(A)=>A?"Enable JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.":"Disable JetBrains integration.",hidden:!0},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0}],DQA=(A)=>("deprecated"in A)&&A.deprecated===!0,M02=(A)=>("hidden"in A)&&A.hidden===!0,N02=(A)=>("default"in A),C02=(A)=>("default"in A)?A.default:void 0;function O02(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((K)=>B.includes(K)||K.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new eD(TK.unknownCommand(B),1,Z)}}async function _S(A,Q){Cm1("0.0.1753948894-g23a9cc");let B=j$1(gp()),J=A.settings,D=VB1({storage:J,secretStorage:B,workspaceRoots:UA.of([c6.file(process.cwd())]),defaultAmpURL:A.ampURL,defaultCacheDirectory:V$1}),z=await C6($2);j1.debug("Global configuration initialized",{hasCacheDirectory:!!z.settings.cacheDirectory,settingsKeys:Object.keys(z.settings)});let Z=await wf(Mv()),K=Cr1({configService:D,toolService:Z});try{await K.initialized}catch(O){j1.warn("Failed to wait for MCP servers, continuing anyway:",O)}if(Q.dangerouslyAllowAll)z.settings.dangerouslyAllowAll=!0;if(Q.jetbrains){if(z.settings["jetbrains.enabled"]=!0,Yi.subscribe((L)=>{j1.info("jetbrains-status",L)}),await jE(),!await Cc1())if(KQA)MQ("JetBrains integration failed. Try again with `amp --no-jetbrains` or see setup: https://ampcode.com/manual#jetbrains");else MQ("Cannot connect to JetBrains IDE. Check setup: https://ampcode.com/manual#jetbrains")}let G=z.settings["experimental.reviewTool"]??!1,X=z.settings["experimental.tools"]??[];R_1(Z,!1,G,X);let Y,U;if(!A.executeMode)Y=new Gk1(z.settings,process.cwd()),await Y.start(),U=q8A(Y,process.cwd());else Y=new class{async start(){}async query(){return[]}dispose(){}},U={[Symbol.dispose]:()=>{}};if(!await B.get("apiKey",A.ampURL)){if(A4.write(`No API key found. Starting login flow...
4731
4731
  `),!await V02(A,B))process.exit(1)}let F=dr1(),H=new cX1(F),E=new mX1(F),w=new VF1(H),W=Q.notifications!==void 0?Q.notifications:!A.executeMode,I=du0({playNotificationSound:async(O)=>{if(W)cu0(O)},windowFocused:()=>Promise.resolve(!1),threadService:H});j1.info("Starting Amp background services");let M=V90({threadService:H,threadHistoryService:E,isExtensionDevelopment:!1}),N={configService:D,toolService:Z,mcpService:K,threadService:H,threadHistoryService:E,threadSummaryService:w,threadSyncService:M,threadStorage:F,secretStorage:B,settingsStorage:J,fileWatcher:U,fuzzyServer:Y,notificationService:I};return{...N,async dispose(){await N.mcpService.dispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fileWatcher[Symbol.dispose](),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function V02(A,Q){if(!A.executeMode){if(await e91("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return A4.write(`Login cancelled. Run the command again to retry.
4732
4732
  `),!1}return await GQA(A,Q)}async function GQA(A,Q){let B=H02(32).toString("hex"),J=await d8A(A.ampURL,B);A4.write(`If your browser doesn't open automatically, visit:
4733
4733
 
@@ -4741,7 +4741,7 @@ ${F0.blue.bold(J)}
4741
4741
  Login successful! You can now use the Amp CLI.
4742
4742
  `),!0}catch(D){return i9.write(`
4743
4743
  Login failed: ${D instanceof Error?D.message:String(D)}
4744
- `),!1}}function L02(){let A=new yu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, team)").configureOutput({writeErr:()=>{}});A.exitOverride((G)=>{if(G.code==="commander.help"||G.code==="commander.version"||G.exitCode===0)Zp(),process.exit(0);let X=G.originalError??G;Kp(X)}),A.option("-V, --version","output the version number",()=>{A4.write(`0.0.1753920106-g48ae72 (released 2025-07-31T00:06:44.329Z)
4744
+ `),!1}}function L02(){let A=new yu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, team)").configureOutput({writeErr:()=>{}});A.exitOverride((G)=>{if(G.code==="commander.help"||G.code==="commander.version"||G.exitCode===0)Zp(),process.exit(0);let X=G.originalError??G;Kp(X)}),A.option("-V, --version","output the version number",()=>{A4.write(`0.0.1753948894-g23a9cc (released 2025-07-31T08:06:32.233Z)
4745
4745
  `),process.exit(0)}),A.addHelpText("after",m8A()),A.configureHelp({formatHelp:u8A}),A.command("logout").description("Log out by removing stored API key").action(async(G,X)=>{let Y=X.optsWithGlobals(),U=await _X(Y),F=gp();if(process.env.AMP_API_KEY)A4.write(`API key found in environment variable AMP_API_KEY, unset first before running 'amp logout'
4746
4746
  `),process.exit(0);if(!await F.get("apiKey",U.ampURL)){if(Uq(U.ampURL))A4.write(`Already logged out.
4747
4747
  `);else A4.write(`Already logged out from ${new URL(U.ampURL).hostname}.
@@ -4778,10 +4778,10 @@ Summary: ${O}
4778
4778
  `),i9.write(`
4779
4779
  `),i9.write(`Secrets have been automatically redacted, but please review the file before attaching
4780
4780
  `),i9.write(`it to support requests. Learn more at https://ampcode.com/manual/appendix#support-bundles
4781
- `),process.exit(0)}catch(Y){MQ(Y instanceof Error?Y.message:String(Y))}}),A.addCommand(z);let Z=new yu("update").description("Update Amp CLI to the latest version").option("--version <version>","Update to a specific version").allowUnknownOption(!1);Z.action(async(G,X)=>{try{let Y=X.optsWithGlobals(),{update:U}=await Promise.resolve().then(() => (QQA(),AQA)),{checkNpmUpdate:F}=await Promise.resolve().then(() => (NX1(),ir1)),H="0.0.1753920106-g48ae72";if(Y.version)i9.write(F0.blue(`Updating to version ${Y.version}...
4781
+ `),process.exit(0)}catch(Y){MQ(Y instanceof Error?Y.message:String(Y))}}),A.addCommand(z);let Z=new yu("update").description("Update Amp CLI to the latest version").option("--version <version>","Update to a specific version").allowUnknownOption(!1);Z.action(async(G,X)=>{try{let Y=X.optsWithGlobals(),{update:U}=await Promise.resolve().then(() => (QQA(),AQA)),{checkNpmUpdate:F}=await Promise.resolve().then(() => (NX1(),ir1)),H="0.0.1753948894-g23a9cc";if(Y.version)i9.write(F0.blue(`Updating to version ${Y.version}...
4782
4782
  `)),await U(Y.version),i9.write(F0.green(`✓ Successfully updated to version ${Y.version}
4783
4783
  `));else{i9.write(F0.blue(`Checking for updates...
4784
- `));let E=await F("0.0.1753920106-g48ae72");if(!E.hasUpdate)i9.write(F0.green(`✓ Amp CLI is already up to date.
4784
+ `));let E=await F("0.0.1753948894-g23a9cc");if(!E.hasUpdate)i9.write(F0.green(`✓ Amp CLI is already up to date.
4785
4785
  `)),process.exit(0);i9.write(F0.blue(`Updating to version ${E.latestVersion}...
4786
4786
  `)),await U(E.latestVersion),i9.write(F0.green(`✓ Successfully updated to version ${E.latestVersion}
4787
4787
  `))}process.exit(0)}catch(Y){i9.write(F0.red("Error updating: ")+`${Y instanceof Error?Y.message:String(Y)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1753920106-g48ae72",
3
+ "version": "0.0.1753948894-g23a9cc",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {