@sourcegraph/amp 0.0.1762358483-gc3a3b8 → 0.0.1762361985-g1ec0ff

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 +13 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -5849,7 +5849,7 @@ src/api/auth/login.ts, src/api/auth/authentication.ts, and src/api/auth/session.
5849
5849
  `)Z+=W,K++;else Z+=W}let q=Z.trim();if(q)Q.push({content:q,lineNumber:G});return Q}function oq1(J){let Q=KV4(J),Z=[];for(let X=0;X<Q.length;X++){let Y=Q[X];if(Y.content.startsWith("#"))continue;let K=YV4(Y.content);if(!K.success)return K.error.line=Y.lineNumber,K;Z.push(K.data)}return{success:!0,data:Z}}function GV4(J){if(typeof J!=="string")return!1;if(/[\s*"'\\]/.test(J)||J.includes("/")||J===""||!/^[a-zA-Z0-9_*.-]+$/.test(J))return!0;if(qV4(J))return!0;return!1}function qV4(J){return/^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(J)}function OE(J){if(typeof J!=="string")return String(J);if(!GV4(J))return J;return`'${J.replace(/'/g,"\\'")}'`}function sq1(J,Q=""){let Z=[];for(let[X,Y]of Object.entries(J)){let K=Q?`${Q}.${X}`:X;if(Array.isArray(Y))for(let G=0;G<Y.length;G++){let q=`${K}.${G}`;if(typeof Y[G]==="object"&&Y[G]!==null)Z.push(...sq1(Y[G],q));else Z.push({path:q,value:Y[G]})}else if(typeof Y==="object"&&Y!==null)Z.push(...sq1(Y,K));else Z.push({path:K,value:Y})}return Z}function zV4(J,Q){let Z=[];if(typeof Q==="string"||typeof Q==="boolean"||typeof Q==="number"||Q===null)Z.push(`--${J} ${OE(Q)}`);else if(Array.isArray(Q)){let X=Q.every((K)=>typeof K==="string"||typeof K==="boolean"||typeof K==="number"||K===null);if(!J.includes(".")&&X)for(let K of Q)Z.push(`--${J} ${OE(K)}`);else for(let K=0;K<Q.length;K++)if(typeof Q[K]==="object"&&Q[K]!==null){let G=sq1({[`${J}.${K}`]:Q[K]});for(let{path:q,value:z}of G)Z.push(`--${q} ${OE(z)}`)}else Z.push(`--${J}.${K} ${OE(Q[K])}`)}else if(typeof Q==="object"&&Q!==null){let X=sq1({[J]:Q});for(let{path:Y,value:K}of X)Z.push(`--${Y} ${OE(K)}`)}return Z}function tq1(J){let Q=[];if(Q.push(J.action),J.action==="delegate"&&J.to)Q.push(`--to ${OE(J.to)}`);if(J.context)Q.push(`--context ${J.context}`);if(Q.push(OE(J.tool)),J.matches)for(let[Z,X]of Object.entries(J.matches)){let Y=zV4(Z,X);Q.push(...Y)}return Q.join(" ")}function ka(J){return J.map(tq1).join(`
5850
5850
  `)}var va=()=>{};function WV4(J){return J.configService.config.pipe(h0((Q)=>{if(Q.settings?.dangerouslyAllowAll===!0)return[{tool:"*",action:"allow"}];return QT(Q.settings?.permissions)}),M8())}async function eq1(J,Q,Z,X="thread",Y,K){let G=await Y6(WV4(Z));try{let q=await Mx(J,Q,G,X,Sa,Y,"user",K);if(!q.matchedEntry)q=await Mx(J,Q,Vx,X,void 0,Y,"built-in",K);if(!q.matchedEntry)return{permitted:!1,action:null,reason:"No matching entry found, denying by default"};let W=q.matchedEntry?.action==="delegate"&&q.action!=="reject"?"delegate":q.action;switch(q.action){case"allow":return{permitted:!0,action:W,matchedEntry:q.matchedEntry,error:q.error,source:q.source};case"reject":return{permitted:!1,action:W,matchedEntry:q.matchedEntry,reason:`Rejected by ${q.source==="built-in"?"built-in":q.source||"unknown"} permissions rule ${q.matchIndex}: ${tq1(q.matchedEntry)}`,error:q.error,source:q.source};case"ask":return{permitted:!1,action:W,matchedEntry:q.matchedEntry,reason:`Matches ${q.source==="built-in"?"built-in":q.source||"unknown"} permissions rule ${q.matchIndex}: ${tq1(q.matchedEntry)}`,error:q.error,source:q.source};case null:if(q.error)return{permitted:!1,action:null,reason:q.error,error:q.error};return{permitted:!0,action:null};default:return{permitted:!1,action:null,reason:"Unknown permission result"}}}catch(q){return{permitted:!1,action:null,reason:q instanceof Error?q.message:"Permission evaluation failed",error:q instanceof Error?q.message:"Permission evaluation failed"}}}var Ts1=W1(()=>{C0();nq1();rq1();va();RO()});function vp6(J){return{registerTool:J.registerTool.bind(J),tools:J.tools,preprocessArgs:J.preprocessArgs?.bind(J),getExecutionProfile:J.getExecutionProfile.bind(J),invokeTool(Q,Z,X){return new J0((Y)=>{let K=null,G=!1,q=()=>{if(G)return;K=J.invokeTool(Q,Z,X).subscribe(Y)};if(Z.userInput?.accepted===!0)return p.debug(`Tool ${String(Q)} already approved by user - bypassing permission check`),q(),()=>{G=!0,K?.unsubscribe()};if(Z.userInput?.accepted===!1)return p.debug(`Tool ${String(Q)} rejected by user`),Y.next({status:"rejected-by-user",reason:"Tool execution rejected by user"}),Y.complete(),()=>{G=!0};p.debug(`Tool ${String(Q)} - checking permissions`);let z=X.thread.mainThreadID?"subagent":"thread";return eq1(Q,Z.args,{configService:X.configService},z,X.thread.id,X.toolUseID).then((W)=>{if(G||!W)return;let{permitted:U,reason:F,action:H,error:B}=W;if(!U){if(p.debug(`Tool ${String(Q)} not permitted - action: ${H}, reason: ${F}`),H==="ask"){Y.next({status:"blocked-on-user",reason:F||"Tool requires user approval due to permissions"}),Y.complete();return}if(H==="reject"&&B)Y.next({status:"error",error:{message:B}});else Y.next({status:"rejected-by-user",reason:F||"Tool execution denied by permissions"});Y.complete();return}p.debug(`Tool ${String(Q)} permitted - action: ${H}`),q()}).catch((W)=>{if(G)return;p.error(`Permission check failed for tool ${String(Q)}:`,W),Y.next({status:"error",error:{message:W.message||"Permission check failed"}}),Y.complete()}),()=>{G=!0,K?.unsubscribe()}})},dispose(){J.dispose()}}}var _p6=W1(()=>{C0();q0();Ts1()});class RE{services;registrationDisposables=[];constructor(J){let Q={};for(let Z of $E){let X=_a(Z);if(!X)throw Error(`Unknown agent mode: ${Z}`);let Y=vp6(UT({configService:J.configService}));Q[Z]=Y;let K,G=J.configService.config.pipe(h0(({settings:q})=>({"experimental.tools":q["experimental.tools"],"experimental.fastSearchAgentConfig":q["experimental.fastSearchAgentConfig"],"experimental.kimiK2SearchAgentConfig":q["experimental.kimiK2SearchAgentConfig"],"experimental.agentMode":q["experimental.agentMode"],"internal.visibleModes":q["internal.visibleModes"]})),M8()).subscribe((q)=>{if(K)K.dispose();K=X.registerTools(Y,q)});this.registrationDisposables.push({dispose(){if(G.unsubscribe(),K)K.dispose()}})}this.services=Q}getForAgent(J){return this.services[J]}registerTool(J){let Q=[];for(let Z of $E){let Y=this.services[Z].registerTool(J);Q.push(Y)}return{dispose(){for(let Z of Q)Z.dispose()}}}get tools(){return $9(...$E.map((J)=>this.services[J].tools)).pipe(h0((J)=>{let Q=new Set,Z=[];for(let X of J)for(let Y of X)if(!Q.has(Y.spec.name))Q.add(Y.spec.name),Z.push(Y);return Z}))}get toolService(){return this.services.default}dispose(){for(let J of this.registrationDisposables)J.dispose();for(let J of Object.values(this.services))J.dispose()}static createSingleToolServices(J){return{getForAgent:()=>J,registerTool:(Q)=>J.registerTool(Q),get tools(){return J.tools},get toolService(){return J},dispose:()=>{}}}}var Jz1=W1(()=>{C0();iq1();_p6();K5()});function yp6(J){if(J.status==="done"){if(J.result!==null&&typeof J.result==="object"&&"output"in J.result&&typeof J.result.output==="string"){if("truncation"in J.result&&typeof J.result.truncation==="object"&&J.result.truncation!==null&&"prefixLinesOmitted"in J.result.truncation&&typeof J.result.truncation.prefixLinesOmitted==="number"){let Q=J.result.truncation.prefixLinesOmitted;return`--- Truncated ${Q} ${jZ(Q,"line")} above this ---
5851
5851
  `+J.result.output}return J.result.output}}return xp6.default.stringify(J)}var xp6;var bp6=W1(()=>{xp6=G6(jk1(),1)});function UV4(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(J)}class xa{fs;constructor(J){this.fs=J}async store(J,Q,Z){let X=this.backupDirForThread(J);if(!X)return;await this.fs.mkdirp(X);let Y=d0.joinPath(X,this.filename(Q));await this.fs.writeFile(Y,JSON.stringify(Z,null,2))}async load(J,Q){let Z=this.backupDirForThread(J);if(!Z)return null;try{let X=await this.fs.readFile(d0.joinPath(Z,this.filename(Q)));return JSON.parse(X)}catch(X){return p.error(`Error loading backup file ${this.filename(Q)}:`,X),null}}async list(J){let Q=this.backupDirForThread(J);if(!Q)return[];await this.fs.mkdirp(Q);try{let Z=await this.fs.readdir(Q),X=[];for(let Y of Z){let K=d0.relativePath(Q,Y.uri);if(!K)continue;let G=K.split(".");if(G.length===2){let q=G[0],z=G[1];if(zg0(q)&&UV4(z))X.push({toolUseID:q,fileChangeID:z})}}return X}catch(Z){return p.error("Error listing backup files:",Z),[]}}async cleanup(J){let Q=this.backupDirForThread(J);if(!Q)return;try{await this.fs.delete(Q,{recursive:!0})}catch(Z){if(!CZ(Z))p.error(`Error cleaning up backup files in ${Q}:`,Z)}}filename(J){return`${J.toolUseID}.${J.fileChangeID}`}backupDirForThread(J){let Q=typeof process<"u"?process.env.HOME:null;if(!Q)return null;return d0.joinPath(E0.file(Q),".amp","file-changes",J)}}var Cs1;var Qz1=W1(()=>{u6();q0();fX();A4();Cs1={async store(){},async load(){return null},async list(){return[]},async cleanup(){}}});function ya(J,Q){let Z=J&&Q?.state==="active"&&Q.inferenceState!=="running"?FV4(J):{running:0,blocked:0};return{...Q,interactionState:J&&Q?.state==="active"?Ss1(J,Q.inferenceState):!1,toolState:Z}}function FV4(J){let Q=J.messages.at(-1);if(!Q||Q.role==="assistant")return{running:0,blocked:0};let Z=0,X=0;for(let Y of Q.content){if(Y.type!=="tool_result")continue;let K=Y.run.status;if(K==="in-progress")Z++;else if(K==="blocked-on-user")X++}return{running:Z,blocked:X}}function Ss1(J,Q){if(Q==="running")return!1;let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;if(Z.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return"user-tool-approval";if(Z.content.some((X)=>X.type==="tool_result"&&X.run.status==="in-progress"))return"tool-running";return!1}class qX{bits;constructor(J){this.bits=J}static empty(){return new qX(0n)}static fromString(J){let Q=0n;for(let Z=0;Z<J.length;Z++){let X=J.charCodeAt(Z),Y=qX.charToBitIndex(X);if(Y>=0)Q|=1n<<BigInt(Y)}return new qX(Q)}static fromPath(J){let Q=0n,Z=J.split(/[/\\]/);for(let X of Z){if(X===""||X==="."||X==="..")continue;for(let Y=0;Y<X.length;Y++){let K=X.charCodeAt(Y),G=qX.charToBitIndex(K);if(G>=0)Q|=1n<<BigInt(G)}}return new qX(Q)}hasChars(J){return(this.bits&J.bits)===J.bits}union(J){return new qX(this.bits|J.bits)}intersection(J){return new qX(this.bits&J.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((J)=>J==="1").length}toString(){let J=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let Z=qX.bitIndexToChar(Q);if(Z)J.push(Z)}return`CharBag{${J.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(J){return new qX(BigInt(J.bits))}equals(J){return this.bits===J.bits}static charToBitIndex(J){if(J>=65&&J<=90)J+=32;if(J>=48&&J<=57)return J-48;if(J>=97&&J<=122)return J-97+10;return-1}static bitIndexToChar(J){if(J>=0&&J<=9)return String.fromCharCode(48+J);if(J>=10&&J<=35)return String.fromCharCode(97+J-10);return null}}class EY{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(J){this.id=J.id,this.kind=J.kind,this.path=J.path,this.uri=J.uri,this.metadata=J.metadata,this.isIgnored=J.isIgnored??!1,this.isExternal=J.isExternal??!1,this.isPrivate=J.isPrivate??!1,this.isAlwaysIncluded=J.isAlwaysIncluded??!1,this.charBag=qX.fromPath(this.path)}withUpdates(J){return new EY({id:this.id,kind:J.kind??this.kind,path:this.path,uri:this.uri,metadata:J.metadata??this.metadata,isIgnored:J.isIgnored??this.isIgnored,isExternal:J.isExternal??this.isExternal,isPrivate:J.isPrivate??this.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let J=this.getFilename(),Q=J.lastIndexOf(".");return Q>0?J.slice(Q+1):""}getDirectory(){let J=this.path.split(/[/\\]/);return J.length>1?J.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(J,Q){return new EY({id:J.id,kind:J.kind,path:J.path,uri:Q(J.uri),metadata:J.metadata,isIgnored:J.isIgnored,isExternal:J.isExternal,isPrivate:J.isPrivate,isAlwaysIncluded:J.isAlwaysIncluded})}equals(J){return this.id===J.id&&this.kind===J.kind&&this.path===J.path&&this.metadata.mtime===J.metadata.mtime&&this.metadata.size===J.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}var Nx=()=>{};class Zz1{config;queryChars;queryLower;constructor(J,Q={}){this.config={...HV4,...Q};let Z=J.replace(/^[@#]+/,"");if(this.queryChars=Array.from(Z),this.queryLower=Array.from(Z.toLowerCase()),this.config.smartCase)this.config.caseSensitive=Z!==Z.toLowerCase()}match(J){if(this.queryChars.length===0)return J.filter((Z)=>Z.shouldIncludeInResults()).map((Z)=>{let X=this.config.openFiles?.includes(Z.path)?300:0,Y=Z.getImportanceBoost()+X;return{entry:Z,score:Y,matchPositions:[],highlightedPath:Z.path}}).sort((Z,X)=>X.score-Z.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(J);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(J)}matchWithSemanticScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],G=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000,q=(U,F)=>{if(!U.shouldIncludeInResults())return!1;if(X.length>5&&!this.passesCharBagFilter(X,U))return!1;let H=this.matchEntrySemantic(U);if(H&&H.score>=this.config.minScore)Q.push(H);if(Z++,Z>=G)return!0;if(F&&Q.length>=this.config.maxResults*5)return!0;return!1},z=(U,F)=>{for(let H of J){if(!U(H))continue;if(q(H,F))return!0}return!1};if(!z((U)=>U.isDirectory(),!1))z((U)=>!U.isDirectory(),!0);return Q.sort((U,F)=>{let H=F.score-U.score;if(Math.abs(H)>0.001)return H;return U.entry.path.length-F.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(J){let Q=[],Z=0,X=this.queryChars.join(""),Y=this.queryChars[0],G=this.queryChars.length===1&&Y!==void 0&&/[a-z]/i.test(Y)?1e4:20000,q=(U,F)=>{if(!U.shouldIncludeInResults())return!1;if(X.length>5&&!this.passesCharBagFilter(X,U))return!1;let H=this.matchEntryFuzzy(U);if(H)Q.push(H);if(Z++,Z>=G)return!0;if(F&&Q.length>=this.config.maxResults*5)return!0;return!1},z=(U,F)=>{for(let H of J){if(!U(H))continue;if(q(H,F))return!0}return!1};if(!z((U)=>U.isDirectory(),!1))z((U)=>!U.isDirectory(),!0);return Q.sort((U,F)=>{let H=F.score-U.score;if(Math.abs(H)>0.001)return H;return U.entry.path.length-F.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateSemanticScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),G=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:G}}matchEntryFuzzy(J){let Q=J.path,Z=this.queryLower.join(""),X=this.calculateFuzzyScore(Z,J);if(X===0)return null;let Y=this.applyTieBreakers(X,Z,J),K=this.findMatchPositions(Z,Q),G=this.createHighlightedPath(Q,K);return{entry:J,score:Y,matchPositions:K,highlightedPath:G}}calculateSemanticScore(J,Q){let Z=J.toLowerCase(),X=Q.path,Y=X.toLowerCase(),K=this.getFilename(X),G=this.removeExtension(K).toLowerCase(),q=Y.split(/[/\\.\s-_]/).filter((F)=>F.length>0);if(J.endsWith("/")&&Q.isDirectory()){let F=Z.slice(0,-1);if(Y===F||Y.endsWith("/"+F))return zX.EXACT_FILENAME+100;if(Y.includes(F))return zX.SUBSTRING_FILENAME+50}if(G===Z||K.toLowerCase()===Z)return zX.EXACT_FILENAME;if(G.startsWith(Z))return zX.PREFIX_FILENAME;if(G.endsWith(Z))return zX.SUFFIX_FILENAME;if(G.includes(Z))return zX.SUBSTRING_FILENAME;let z=this.simpleTokens(Z);if(z.length>1){let F=this.matchTokensToSegments(z,q);if(F)return F}if(z.length===1&&Z.length>6){let F=this.progressiveSegmentMatch(Z,q);if(F)return F}if(q.includes(Z))return zX.SEGMENT_EXACT;if(q.some((F)=>F.includes(Z)))return zX.SEGMENT_SUBSTRING;if(q.join("").includes(Z))return zX.SEGMENT_SUBSTRING;if(Y.replace(/[\s-_]/g,"").includes(Z))return zX.PATH_SUBSTRING;return 0}calculateFuzzyScore(J,Q){let Z=J.toLowerCase(),X=Q.path.toLowerCase();if(this.fuzzyIn(Z,X))return zX.FUZZY;return 0}applyTieBreakers(J,Q,Z){let X=J,Y=Math.abs(Z.path.length-Q.length);X-=0.01*Y;let K=Z.path.split(/[/\\]/).length-1;X-=0.1*K;let G=this.getFilename(Z.path),q=this.removeExtension(G).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(q)&&K===1)X-=200;if(Z.metadata.mtime){let W=(Date.now()-Z.metadata.mtime)/86400000;if(W<30){let U=Math.max(0,1-W/30);X+=50*U}}if(this.config.openFiles?.includes(Z.path))X+=300;return X}simpleTokens(J){return J.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}progressiveSegmentMatch(J,Q){let Z=0,X=0,Y=0;for(let G of Q){if(Z>=J.length)break;let q="",z="none";if(Z+G.length<=J.length){if(J.slice(Z,Z+G.length)===G)q=G,z="exact"}if(!q&&G.length>=3){if(J.slice(Z).startsWith(G))q=G,z="prefix"}if(!q&&G.length>=3){let W=J.slice(Z);if(W.includes(G)&&W.indexOf(G)===0)q=G,z="substring"}if(!q){let W=J.slice(Z);if(W.length>=3&&G.includes(W))q=W,z="substring"}if(q){if(Z+=q.length,X++,z==="exact")Y++}}if(Z/J.length>=0.8&&X>=2)return Y>=2?zX.SEGMENT_ORDERED_EXACT:zX.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(J,Q){let Z=this.findTokenMatches(J,Q),X=this.getWorstMatchType(Z);return this.scoreFromMatchType(X)}findTokenMatches(J,Q){let Z=0,X=[];for(let Y of J){let K=!1;for(let G=Z;G<Q.length;G++){let q=Q[G];if(!q)continue;if(Y===q){X.push("exact"),Z=G+1,K=!0;break}else if(q.startsWith(Y)||Y.startsWith(q)||q.endsWith(Y)||q.includes(Y)||Y.includes(q)){X.push("partial"),Z=G+1,K=!0;break}}if(!K)return[]}return X}getWorstMatchType(J){if(J.length===0)return"none";if(J.includes("partial"))return"partial";return"exact"}scoreFromMatchType(J){switch(J){case"exact":return zX.SEGMENT_ORDERED_EXACT;case"partial":return zX.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(J,Q){let Z=0;for(let X=0;X<Q.length&&Z<J.length;X++)if(Q[X]===J[Z])Z++;return Z===J.length}getFilename(J){return J.split(/[/\\]/).pop()||J}removeExtension(J){let Q=J.lastIndexOf(".");return Q>0?J.substring(0,Q):J}findMatchPositions(J,Q){let Z=[],X=Q.toLowerCase(),Y=J.toLowerCase();if(X.includes(Y)){let G=X.indexOf(Y);for(let q=0;q<Y.length;q++)Z.push(G+q);return Z}let K=0;for(let G of Y){let q=X.indexOf(G,K);if(q!==-1)Z.push(q),K=q+1}return Z}passesCharBagFilter(J,Q){if(J.includes("/")||J.includes("\\")){let Z=J.split(/[/\\]/);for(let X of Z){if(X.trim()==="")continue;let Y=qX.fromString(X);if(!Q.charBag.hasChars(Y))return!1}return!0}else{let Z=qX.fromString(J);return Q.charBag.hasChars(Z)}}createHighlightedPath(J,Q){if(Q.length===0)return J;let Z="",X=0;for(let Y of Q){if(Y>=J.length)continue;Z+=J.slice(X,Y),Z+=`**${J[Y]}**`,X=Y+1}return Z+=J.slice(X),Z}}function Lx(J,Q,Z){return new Zz1(J,Z).match(Q)}var HV4,zX;var ba=W1(()=>{HV4={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},zX={EXACT_FILENAME:1000,SEGMENT_ORDERED_EXACT:950,PREFIX_FILENAME:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250}});function TH(J){return J.replace(/ /g,"\\ ")}var HA=100;var Ax=()=>{};function fp6(J,Q,Z,X){let Y=new Map,K=async()=>{try{let U;if(X)U=await J.get(X);else U=J.getRecentlyActiveThread();if(U){let F=U.id,H=U.env?.initial.trees||[];if(p.info("Found thread:",F,"trees:",H.length),H.length>0)return p.info("Using trees from thread:",F),{trees:H,threadId:F};else p.info("Thread has no trees")}else p.info("No thread found");return null}catch(U){return p.error("Error getting thread:",U),null}},G=async(U)=>{if(!U.repository||!U.repository.url||!U.repository.sha)return[];let F=U.repository,H=F.sha,B=Date.now(),V=`${F.url}:${H}`,M=Y.get(V);if(M&&B-M.timestamp<300000)return M.entries;try{let N=await i76(F.url,H,{filePattern:"**/*",limit:1e4},void 0,Z),L=N.files.map((w)=>{let O={mtime:Date.now(),size:0,inode:0,isSymlink:!1},$=E0.file(`/${w}`);return new EY({id:`github:${F.url}:${H}:${w}`,kind:"file",path:w,uri:$,metadata:O})}),A={entries:L,timestamp:B,repoUrl:F.url,sha:H};if(Y.set(V,A),N.truncated)p.warn("GitHub repository file listing was truncated",{repo:F.url,indexedFiles:L.length});return L}catch(N){return p.error("Failed to fetch files from GitHub API",N),[]}},q=async(U)=>{try{return(await Q.searchResources(U)).map(({resource:H,serverName:B})=>BV4(H,B)).slice(0,Math.min(5,HA))}catch(F){return p.warn("Failed to search MCP resources",F),[]}},z=(U)=>{return Q.searchPrompts(U)},W=(U)=>{return U.map((F)=>{let H=F.path,B=`@${TH(H)}`,V=H.split("/"),M=V[V.length-1]||H,N=V.length>1?V.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:M,detail:N,insertText:B,filterText:H.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(U){let F=z(U),H=y6(async()=>{let B=await K();if(!B)return p.info("No thread with trees found, using MCP resources only"),await q(U);let{trees:V,threadId:M}=B,N=V.find(($)=>$.repository?.url!=null&&$.repository?.sha!=null);if(!N)return p.info("No GitHub repository found in thread trees, using MCP resources only"),await q(U);p.info("Found GitHub repository",{threadId:M,uri:N.uri,repoUrl:N.repository.url,sha:N.repository.sha});let[L,A]=await Promise.all([G(N),q(U)]);if(L.length===0)return A;let w;if(!U)p.info("Empty query, returning first 10 files"),w=L.slice(0,10);else try{w=Lx(U,L,{maxResults:50,minScore:400}).map((I)=>I.entry)}catch($){return p.error("Fuzzy search failed",$),A}return[...W(w),...A]});return $9(F,H).pipe(h0(([B,V])=>{return[...B,...V].slice(0,HA)}))},dispose(){Y.clear()}}}function BV4(J,Q){let Z=J.title||J.name,X=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,Y=`${Q}:${J.uri}`,K="@"+TH(Y);return{uri:sf(Y),label:Z,detail:X,insertText:K,filterText:`${Z} ${X} ${J.uri}`.toLowerCase()}}var hp6=W1(()=>{u6();C0();q0();Nx();ba();Ax();n76()});function Yz1(J){let Q=u01(J);if(Object.values(Q).reduce((Z,X)=>Z+X,0)>0)return!0;for(let Z of J.messages){if(Z.role!=="assistant")continue;for(let X of Z.content){if(X.type==="tool_use"&&X.name==="delete_file"){if(FM(J,X.id)?.run.status==="done")return!0}if(X.type==="tool_use"&&X.name==="Bash"&&X.input&&"cmd"in X.input){if(String(X.input.cmd).match(/^\s*(rm|mv)\s+/)){if(FM(J,X.id)?.run.status==="done")return!0}}}}return!1}var ks1=W1(()=>{A4()});function DV4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((Y)=>Y.repository?.url):J;if(!Q?.repository?.url)return null;let Z=ID(Q.repository.url,{provider:"github"});if(!Z||Z.provider!=="github")return null;let X=Q.repository.headRef?Hd(Q.repository.headRef):null;return{repo:Z.name,branch:X,provider:"github"}}async function VV4({repo:J,branch:Q},Z,X){if(!Q)return null;try{let Y=J.split("/")[0],K=`repos/${J}/pulls?head=${encodeURIComponent(Y)}:${encodeURIComponent(Q)}&state=all&sort=created&direction=desc&per_page=1&page=1`,G=await O2(K,{signal:X,cache:"no-cache"},Z);if(!G.ok||!G.data)return null;let q=G.data;if(q.length>0){let z=q[0],W=z.state==="closed"&&z.merged_at!==null;return{url:v6(E0.parse(z.html_url)),number:z.number.toString(),merged:W}}return null}catch(Y){return p.debug("Failed to check GitHub pull request status:",Y),null}}function gp6(J,Q,Z,X){let Y=J.observe(Q).pipe(h0((K)=>[{id:K.id,env:K.env},K.messages.length>=2&&Yz1(K)]),M8());return $9(Y,X.pipe(t4(void 0),f2((K)=>{return p.error("pullRequestChanges subject error, continuing with undefined",{error:K,threadID:Q}),J0.of(void 0)}))).pipe(rY(([[K,G]])=>{if(!K||!G)return J0.of([]);let q=DV4(K);if(!q)return J0.of([]);let W=K.env?.initial?.trees?.find((U)=>U.repository?.url)?.repository?.pullRequestURL;return y6(async(U)=>{if(W&&!q.branch){let H=W.split("/").pop()||"";try{let B=`repos/${q.repo}/pulls/${H}`,V=await O2(B,{signal:U,cache:"no-cache"},Z);if(V.ok&&V.data){let M=V.data;return[{type:M.state==="closed"&&M.merged_at!==null?"view-merged-pull-request":"view-pull-request",url:v6(E0.parse(M.html_url)),number:M.number.toString()}]}}catch(B){p.debug("Failed to fetch specific PR:",B)}}let F=await VV4(q,Z,U);if(F)return[{type:F.merged?"view-merged-pull-request":"view-pull-request",url:F.url,number:F.number}];return[{type:"create-pull-request"}]})}),S9({shouldCountRefs:!0}))}var up6=W1(()=>{u6();C0();q0();ks1();IF()});async function fa(J,Q){let Z=Q.config.settings.url;if(!Z)throw Error("amp.url is not set");let X=await Q.config.secrets.getToken("gitlab-access-token",Z);if(!X)return{ok:!1,status:401,statusText:"GitLab access token is not set"};let Y=await Q.config.secrets.getToken("gitlab-instance-url",Z)??MV4;return NV4(J,{...Q,auth:{instanceURL:Y,accessToken:X}})}async function NV4(J,{auth:Q,...Z}){let X=`${Q.instanceURL.replace(/\/+$/,"")}/api/v4`,Y=J.startsWith("http")?J:`${X}${J}`,{body:K,headers:G={}}=Z,q={"Content-Type":"application/json",Authorization:`Bearer ${Q.accessToken}`,...G};try{let z=await fetch(Y,{...Z,body:K?JSON.stringify(K):void 0,headers:q}),W=void 0,U=void 0;if(Z.method!=="HEAD"&&z.status!==204)try{U=await z.text(),W=JSON.parse(U)}catch(F){p.info("GitLab API response not JSON:",{url:Y,status:z.status,responseText:U?.substring(0,200)})}return p.debug("GitLab API response:",{url:Y,ok:z.ok,status:z.status,statusText:z.statusText,hasData:!!W,dataKeys:W&&typeof W==="object"?Object.keys(W):void 0,responseTextLength:U?.length}),{data:W,ok:z.ok,status:z.status,statusText:z.statusText}}catch(z){return p.error(`GitLab API request error (${Y}):`,z),{ok:!1,status:0,statusText:z instanceof Error?z.message:String(z)}}}var MV4="https://gitlab.com";var vs1=W1(()=>{q0()});function mp6(J){let Q=J.replace(/\.git$/,"");try{return new URL(Q).pathname.replace(/^\//,"")}catch{return Q.match(/https?:\/\/[^/]+\/(.+)/)?.[1]??Q}}function LV4(J){if(J.includes("**")){let Q=J.replace(/\*\*\//g,"");if(Q.includes("*"))return Q}if(J.includes("*")&&!J.includes("/"))return J;return null}async function AV4(J,Q,Z,X){let{filePattern:Y,limit:K=100,offset:G=0}=Z,q=LV4(Y);if(!q)return null;let z=encodeURIComponent(J),W=Math.floor(G/K)+1,U=`/projects/${z}/search?scope=blobs&search=path:${encodeURIComponent(q)}&per_page=${K}&page=${W}&ref=${Q}`;try{let F=await fa(U,{config:X});if(!F.ok||!F.data)return null;let H=new Set(F.data.map((N)=>N.path)),B=Array.from(H),V=_s1.default(Y);return{files:B.filter((N)=>V(N)),truncated:F.data.length===K}}catch(F){return null}}async function wV4(J,Q,Z,X){let{filePattern:Y,limit:K,offset:G=0}=Z,z=`/projects/${encodeURIComponent(J)}/repository/tree?recursive=true&ref=${Q}&per_page=1000&pagination=keyset`,W=await fa(z,{config:X});if(!W.ok||!W.data)throw Error(`Failed to fetch files: ${W.status} ${W.statusText||"Unknown error"}`);let F=W.data.filter((M)=>M.type==="blob").map((M)=>M.path),H=_s1.default(Y),B=F.filter((M)=>H(M));return{files:K?B.slice(G,G+K):B.slice(G),truncated:W.data.length===1000}}async function pp6(J,Q,Z,X){let Y=mp6(J);if(!Y)throw Error(`Invalid GitLab repository URL: ${J}`);let K=await AV4(Y,Q,Z,X);if(K)return K;return wV4(Y,Q,Z,X)}var _s1;var dp6=W1(()=>{vs1();_s1=G6(Ph(),1)});function cp6(J,Q,Z,X){let Y=new Map,K=async()=>{try{let U;if(X)U=await J.get(X);else U=J.getRecentlyActiveThread();if(U){let F=U.id,H=U.env?.initial.trees||[];if(p.info("Found thread:",F,"trees:",H.length),H.length>0)return p.info("Using trees from thread:",F),{trees:H,threadId:F};else p.info("Thread has no trees")}else p.info("No thread found");return null}catch(U){return p.error("Error getting thread:",U),null}},G=async(U)=>{if(!U.repository||!U.repository.url||!U.repository.sha)return[];let F=U.repository,H=F.sha,B=Date.now(),V=`${F.url}:${H}`,M=Y.get(V);if(M&&B-M.timestamp<300000)return M.entries;try{let N=await pp6(F.url,H,{filePattern:"**/*",limit:1e4},Z),L=N.files.map((w)=>{let O={mtime:Date.now(),size:0,inode:0,isSymlink:!1},$=E0.file(`/${w}`);return new EY({id:`gitlab:${F.url}:${H}:${w}`,kind:"file",path:w,uri:$,metadata:O})}),A={entries:L,timestamp:B,repoUrl:F.url,sha:H};if(Y.set(V,A),N.truncated)p.warn("GitLab repository file listing was truncated",{repo:F.url,indexedFiles:L.length});return L}catch(N){return p.error("Failed to fetch files from GitLab API",N),[]}},q=async(U)=>{try{return(await Q.searchResources(U)).map(({resource:H,serverName:B})=>OV4(H,B)).slice(0,Math.min(5,HA))}catch(F){return p.warn("Failed to search MCP resources",F),[]}},z=(U)=>{return Q.searchPrompts(U)},W=(U)=>{return U.map((F)=>{let H=F.path,B=`@${TH(H)}`,V=H.split("/"),M=V[V.length-1]||H,N=V.length>1?V.slice(0,-1).join("/"):"";return{uri:v6(F.uri),label:M,detail:N,insertText:B,filterText:H.toLowerCase(),kind:F.isDirectory()?"folder":"file"}})};return{search(U){let F=z(U),H=y6(async()=>{let B=await K();if(!B)return p.info("No thread with trees found, using MCP resources only"),await q(U);let{trees:V,threadId:M}=B,N=V.find(($)=>$.repository?.url!=null&&$.repository?.sha!=null&&$.fs==="gitlab");if(!N)return p.info("No GitLab repository found in thread trees, using MCP resources only"),await q(U);p.info("Found GitLab repository",{threadId:M,uri:N.uri,repoUrl:N.repository.url,sha:N.repository.sha});let[L,A]=await Promise.all([G(N),q(U)]);if(L.length===0)return A;let w;if(!U)p.info("Empty query, returning first 10 files"),w=L.slice(0,10);else try{w=Lx(U,L,{maxResults:50,minScore:400}).map((I)=>I.entry)}catch($){return p.error("Fuzzy search failed",$),A}return[...W(w),...A]});return $9(F,H).pipe(h0(([B,V])=>{return[...B,...V].slice(0,HA)}))},dispose(){Y.clear()}}}function OV4(J,Q){let Z=J.title||J.name,X=J.description?`${J.description} (${Q})`:`MCP Resource from ${Q}`,Y=`${Q}:${J.uri}`,K="@"+TH(Y);return{uri:sf(Y),label:Z,detail:X,insertText:K,filterText:`${Z} ${X} ${J.uri}`.toLowerCase()}}var lp6=W1(()=>{u6();C0();q0();Nx();ba();Ax();dp6()});function $V4(J){let Q="id"in J&&typeof J.id==="string"?J.env?.initial?.trees?.find((K)=>K.repository?.url):J;if(!Q?.repository?.url)return null;let Z=new URL(Q.repository.url).origin,X=ID(Q.repository.url,{gitlabInstanceURL:Z});if(!X||X.provider!=="gitlab")return null;let Y=Q.repository.headRef?Hd(Q.repository.headRef):Q.repository.ref?Hd(Q.repository.ref):null;return{repo:X.name,branch:Y,provider:"gitlab",instanceURL:X.instanceURL}}async function RV4({repo:J,branch:Q,instanceURL:Z},X,Y){if(!Q||!Z)return p.info("GitLab MR check: missing branch or instanceURL",{repo:J,branch:Q,instanceURL:Z}),null;try{let K=encodeURIComponent(J),G=`/projects/${K}/merge_requests?source_branch=${encodeURIComponent(Q)}&state=all&per_page=1&page=1`;p.info("GitLab MR check: making API request",{repo:J,branch:Q,instanceURL:Z,apiEndpoint:G,projectPath:K});let q=await fa(G,{config:X,signal:Y,cache:"no-cache"});if(!q.ok||!q.data)return p.info("GitLab MR check: API response not ok or no data",{repo:J,branch:Q,response:q}),null;let z=q.data;if(z.length>0){let W=z[0];return{url:v6(E0.parse(W.web_url)),number:W.iid.toString(),merged:W.state==="merged"}}return null}catch(K){return null}}function ip6(J,Q,Z,X){p.info("GitLab thread actions: setting up observable for thread",{threadID:Q});let Y=J.observe(Q).pipe(h0((K)=>{let G=K.messages.length>=2&&Yz1(K);return[{id:K.id,env:K.env},G]}),M8());return $9(Y,X.pipe(t4(void 0),f2((K)=>{return p.error("mergeRequestChanges subject error, continuing with undefined",{error:K,threadID:Q}),J0.of(void 0)}))).pipe(rY(([[K,G],q])=>{if(!K||!G)return p.info("GitLab thread actions: no thread or no messages, returning empty",{threadID:Q}),J0.of([]);let z=$V4(K);if(!z)return p.info("GitLab thread actions: not a GitLab repository, returning empty",{threadID:Q}),J0.of([]);return y6(async(W)=>{let U=await RV4(z,Z,W);if(U)return[{type:U.merged?"view-merged-pull-request":"view-pull-request",url:U.url,number:U.number}];return[{type:"create-pull-request"}]})}),S9({shouldCountRefs:!0}))}var np6=W1(()=>{u6();C0();q0();ks1();vs1()});class xs1{threadService;config;name="github";mentions;pullRequestChanges=new S8;constructor(J,Q,Z,X){this.threadService=J;this.config=Z;this.mentions=fp6(J,Q,Z,X)}getThreadActions(J){return gp6(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;return ID(J,{provider:"github"})?.provider==="github"}dispose(){this.mentions.dispose()}}class ap6{threadService;config;name="gitlab";mentions;pullRequestChanges=new S8;constructor(J,Q,Z,X){this.threadService=J;this.config=Z;this.mentions=cp6(J,Q,Z,X)}getThreadActions(J){return ip6(this.threadService,J,this.config,this.pullRequestChanges)}canHandle(J){if(!J)return!1;let Q=new URL(J).origin;return ID(J,{gitlabInstanceURL:Q})?.provider==="gitlab"}dispose(){this.mentions.dispose()}}function rp6(J,Q,Z,X,Y){let K=J.find((z)=>z.repository?.url);if(!K?.repository?.url)return new xs1(Q,Z,X,Y);if(K.repository.url.includes("gitlab.")||K.fs==="gitlab")return new ap6(Q,Z,X,Y);else return new xs1(Q,Z,X,Y)}var sp6=W1(()=>{C0();hp6();up6();lp6();np6()});function IV4(J){let Q=RG(`cerebras/${J}`);return Q.contextWindow-Q.maxOutputTokens}class ys1{async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:X,agentMode:Y,clientRequestId:K}){let{systemPrompt:G,tools:q}=await cX(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"cerebras",agentMode:Y},X),z=G.map((H)=>H.text).join(`
5852
- `),W=Q.id,U=EV4(Q),F=q.map((H)=>V2(J,H));p.debug("Starting Cerebras inference",{model:J,threadID:W,messageCount:U.length,toolCount:F.length});try{let H=await t21(U,F,z,Q,J,0.7,{configService:Z.configService},X,void 0,K).catch((R)=>{throw TV4(R)}),B=H.message,V=s21(B),N=o21(B)?.content||null;p.debug("Cerebras response parsed",{threadID:W,assistantContent:N?N.slice(0,200)+"...":null,toolUsesCount:V.length,toolUses:V.map((R)=>({name:R.name,id:R.id}))});let L=[];if(N)L.push({type:"text",text:N});if(V.length>0){p.debug("Processing tool uses",{threadID:W,toolUseCount:V.length});for(let R of V)p.debug("Adding tool_use block to message content",{threadID:W,toolUseId:R.id,toolName:R.name,parsedArgs:typeof R.input==="object"&&R.input?Object.keys(R.input):[]}),L.push({type:"tool_use",id:R.id,name:R.name,input:R.input})}else p.debug("No tool uses to process",{threadID:W});let A=H.message.usage||{},w=A?.prompt_tokens??0,O=A?.completion_tokens??0,$={inputTokens:w,outputTokens:O,cacheCreationInputTokens:0,cacheReadInputTokens:0,maxInputTokens:IV4(J),totalInputTokens:w,credits:0},I={model:J,"~debugParamsUsed":{systemPrompt:z.slice(0,500),messageCount:U.length,toolCount:F.length}};return yield{role:"assistant",content:L,state:{type:"complete",stopReason:V.length>0?"tool_use":null},usage:$},{model:J,"~debugUsage":$,"~debugParamsUsed":I}}catch(H){throw p.error("Cerebras inference error",{error:H,model:J,threadID:W}),H}}}function EV4(J){let Q=nS(J);return PV4(Q)}function PV4(J){return J.map((Q)=>{if(Q.role==="user")return{role:"user",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")};else if(Q.role==="assistant")return{role:"assistant",content:typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.map((Z)=>Z.type==="text"?Z.text:"").join(""):null,tool_calls:Q.tool_calls};else if(Q.role==="tool")return{role:"tool",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.text).join(""),tool_call_id:Q.tool_call_id};throw Error(`Unsupported message role: ${Q.role}`)})}function jV4(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function TV4(J){if(jV4(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new a7}return J}var op6=W1(()=>{q0();HD();K5();q5();PJ();Cb1();JR()});function CV4(J){return J.pipe(N8((Q)=>H2((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),M8((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),h0(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new L8({apiKey:Z,baseURL:new URL("/api/provider/supernova/v1",Q).toString()})}),S9({shouldCountRefs:!0}))}function bs1(J,Q){return Y6(CV4(J.configService.config),Q)}var tp6=W1(()=>{C0();lS()});function ep6(J){return J.filter((Q)=>Q.type!=="thinking"&&Q.type!=="redacted_thinking")}function Jd6(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}async function Kz1(J,Q,Z,X,Y,K,G,q=!1,z,W){let U=await(q?bs1(K,G):Qd6(K,G)),F=[{role:"system",content:Z},...J],H={model:Y,messages:F,tools:Jd6(Q),temperature:0.7,top_p:0.95,stream:!1};try{return{message:await U.chat.completions.create(H,{signal:G,headers:Zd6(X,z,W)})}}catch(B){if(EG(B))throw new DOMException("Aborted","AbortError");throw p.error("xAI API call failed",{model:Y,error:B instanceof Error?B.message:String(B),status:B?.status,code:B?.code,type:B?.type}),p.error("xAI API call failed",{model:Y,error:B instanceof Error?B.message:String(B),params:{...H,messages:H.messages.map((V)=>({...V,content:typeof V.content==="string"?V.content.substring(0,100)+"...":V.content}))}}),Xd6(B)}}async function*SV4(J,Q,Z,X,Y,K,G,q=!1,z,W){let U=await(q?bs1(K,G):Qd6(K,G)),F=[{role:"system",content:Z},...J],H={model:Y,messages:F,tools:Jd6(Q),stream:!0,stream_options:{include_usage:!0}};try{yield*await U.chat.completions.create(H,{signal:G,headers:Zd6(X,z,W)})}catch(B){if(EG(B))throw new DOMException("Aborted","AbortError");throw Xd6(B)}}function kV4(J){if(J.status==="done")return typeof J.result==="string"?J.result:JSON.stringify(J.result);else if(J.status==="error")return`<tool_execution_error>${J.error?.message||"Unknown error"}</tool_execution_error>`;else if(J.status==="cancelled")return"<tool_call_cancelled>Tool call was cancelled by the user</tool_call_cancelled>";else if(J.status==="rejected-by-user")return"<tool_rejection>User rejected the tool call, disallowing it from running</tool_rejection>";else return`<tool_status>${J.status}</tool_status>`}function fs1(J){let Q=[],{summaryBlock:Z,index:X}=kX(J)??{summaryBlock:void 0,index:0};if(Z&&Z.summary.type==="message")Q.push({role:"assistant",content:[{type:"text",text:Z.summary.summary.trimEnd()}]});for(let Y=X+(Z?1:0);Y<J.messages.length;Y++){let K=J.messages[Y];if(!K)continue;switch(K.role){case"user":{let G=[],q=[];if(K.fileMentions&&K.fileMentions.files.length>0)G.push({type:"text",text:gG(K.fileMentions)});if(K.userState)G.push({type:"text",text:HF(K.userState)});for(let z of K.content)switch(z.type){case"tool_result":q.push({role:"tool",content:kV4(z.run),tool_call_id:z.toolUseID.replace(/^toolu_/,"")});break;case"image":break;case"text":if(z.text.trim())G.push({type:"text",text:z.text});break}if(G.length>0)Q.push({role:"user",content:G});Q.push(...q);break}case"assistant":{let q=ep6(K.content).filter((W)=>W.type==="text").map((W)=>({type:"text",text:W.text})),z=K.content.filter((W)=>W.type==="tool_use").map((W)=>({id:W.id.replace(/^toolu_/,""),type:"function",function:{name:W.name,arguments:JSON.stringify(W.input)}}));if(q.length>0||z.length>0)Q.push({role:"assistant",content:q.length>0?q:null,tool_calls:z.length>0?z:void 0});break}case"info":{for(let G of K.content)if(G.type==="manual_bash_invocation"){let q=GS(G);if(q.length>0)Q.push({role:"user",content:q})}break}}}return QK(Q)}function vV4(J){return J.pipe(N8((Q)=>H2((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),M8((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),h0(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new L8({apiKey:Z,baseURL:new URL("/api/provider/xai/v1",Q).toString()})}),S9({shouldCountRefs:!0}))}function Qd6(J,Q){return Y6(vV4(J.configService.config),Q)}function Zd6(J,Q,Z){return{...oJ(),[vX]:"amp.chat",...Q!=null?{[$G]:String(Q)}:{},...Z!=null?{[yQ]:Z}:{},"x-grok-conv-id":J.id,..._X(J)}}function Xd6(J){let Q=J?.message;if(typeof Q==="string"){if(Q.includes("This model's maximum prompt length is")&&Q.includes("but the request contains")&&Q.includes("tokens."))return new a7("Token limit exceeded.")}return J}class Gz1{useSupernova;constructor(J=!1){this.useSupernova=J}async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:X,agentMode:Y,clientRequestId:K}){let{systemPrompt:G,tools:q}=await cX(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:this.useSupernova?"supernova":"xai",agentMode:Y},X),z=q.map((V)=>V2(J,V)),W=fs1(Q),U=SV4(W,z,G.map((V)=>V.text).join(`
5852
+ `),W=Q.id,U=EV4(Q),F=q.map((H)=>V2(J,H));p.debug("Starting Cerebras inference",{model:J,threadID:W,messageCount:U.length,toolCount:F.length});try{let H=await t21(U,F,z,Q,J,0.7,{configService:Z.configService},X,void 0,K).catch((R)=>{throw TV4(R)}),B=H.message,V=s21(B),N=o21(B)?.content||null;p.debug("Cerebras response parsed",{threadID:W,assistantContent:N?N.slice(0,200)+"...":null,toolUsesCount:V.length,toolUses:V.map((R)=>({name:R.name,id:R.id}))});let L=[];if(N)L.push({type:"text",text:N});if(V.length>0){p.debug("Processing tool uses",{threadID:W,toolUseCount:V.length});for(let R of V)p.debug("Adding tool_use block to message content",{threadID:W,toolUseId:R.id,toolName:R.name,parsedArgs:typeof R.input==="object"&&R.input?Object.keys(R.input):[]}),L.push({type:"tool_use",id:R.id,name:R.name,input:R.input})}else p.debug("No tool uses to process",{threadID:W});let A=H.message.usage||{},w=A?.prompt_tokens??0,O=A?.completion_tokens??0,$={inputTokens:w,outputTokens:O,cacheCreationInputTokens:0,cacheReadInputTokens:0,maxInputTokens:IV4(J),totalInputTokens:w,credits:0},I={model:J,"~debugParamsUsed":{systemPrompt:z.slice(0,500),messageCount:U.length,toolCount:F.length}};return yield{role:"assistant",content:L,state:{type:"complete",stopReason:V.length>0?"tool_use":null},usage:$},{model:J,"~debugUsage":$,"~debugParamsUsed":I}}catch(H){throw p.error("Cerebras inference error",{error:H,model:J,threadID:W}),H}}}function EV4(J){let Q=nS(J);return PV4(Q)}function PV4(J){return J.map((Q)=>{if(Q.role==="user")return{role:"user",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.type==="text"?Z.text:"").join("")};else if(Q.role==="assistant")return{role:"assistant",content:typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.map((Z)=>Z.type==="text"?Z.text:"").join(""):null,tool_calls:Q.tool_calls};else if(Q.role==="tool")return{role:"tool",content:typeof Q.content==="string"?Q.content:Q.content.map((Z)=>Z.text).join(""),tool_call_id:Q.tool_call_id};throw Error(`Unsupported message role: ${Q.role}`)})}function jV4(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function TV4(J){if(jV4(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new a7}return J}var op6=W1(()=>{q0();HD();K5();q5();PJ();Cb1();JR()});function CV4(J){return J.pipe(N8((Q)=>H2((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),M8((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),h0(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new L8({apiKey:Z,baseURL:new URL("/api/provider/supernova/v1",Q).toString()})}),S9({shouldCountRefs:!0}))}function bs1(J,Q){return Y6(CV4(J.configService.config),Q)}var tp6=W1(()=>{C0();lS()});function ep6(J){return J.filter((Q)=>Q.type!=="thinking"&&Q.type!=="redacted_thinking")}function Jd6(J){let Q=new Set;return J.filter((Z)=>{if(Q.has(Z.name))return!1;return Q.add(Z.name),!0}).map((Z)=>({type:"function",function:{name:Z.name,description:Z.description??"",parameters:Z.inputSchema}}))}async function Kz1(J,Q,Z,X,Y,K,G,q=!1,z,W,U){let F=await(q?bs1(K,G):Qd6(K,G)),H=[{role:"system",content:Z},...J],B={model:Y,messages:H,tools:Jd6(Q),temperature:0.7,top_p:0.95,stream:!1,...U&&{tool_choice:U}};try{return{message:await F.chat.completions.create(B,{signal:G,headers:Zd6(X,z,W)})}}catch(V){if(EG(V))throw new DOMException("Aborted","AbortError");throw p.error("xAI API call failed",{model:Y,error:V instanceof Error?V.message:String(V),status:V?.status,code:V?.code,type:V?.type}),p.error("xAI API call failed",{model:Y,error:V instanceof Error?V.message:String(V),params:{...B,messages:B.messages.map((M)=>({...M,content:typeof M.content==="string"?M.content.substring(0,100)+"...":M.content}))}}),Xd6(V)}}async function*SV4(J,Q,Z,X,Y,K,G,q=!1,z,W){let U=await(q?bs1(K,G):Qd6(K,G)),F=[{role:"system",content:Z},...J],H={model:Y,messages:F,tools:Jd6(Q),stream:!0,stream_options:{include_usage:!0}};try{yield*await U.chat.completions.create(H,{signal:G,headers:Zd6(X,z,W)})}catch(B){if(EG(B))throw new DOMException("Aborted","AbortError");throw Xd6(B)}}function kV4(J){if(J.status==="done")return typeof J.result==="string"?J.result:JSON.stringify(J.result);else if(J.status==="error")return`<tool_execution_error>${J.error?.message||"Unknown error"}</tool_execution_error>`;else if(J.status==="cancelled")return"<tool_call_cancelled>Tool call was cancelled by the user</tool_call_cancelled>";else if(J.status==="rejected-by-user")return"<tool_rejection>User rejected the tool call, disallowing it from running</tool_rejection>";else return`<tool_status>${J.status}</tool_status>`}function fs1(J){let Q=[],{summaryBlock:Z,index:X}=kX(J)??{summaryBlock:void 0,index:0};if(Z&&Z.summary.type==="message")Q.push({role:"assistant",content:[{type:"text",text:Z.summary.summary.trimEnd()}]});for(let Y=X+(Z?1:0);Y<J.messages.length;Y++){let K=J.messages[Y];if(!K)continue;switch(K.role){case"user":{let G=[],q=[];if(K.fileMentions&&K.fileMentions.files.length>0)G.push({type:"text",text:gG(K.fileMentions)});if(K.userState)G.push({type:"text",text:HF(K.userState)});for(let z of K.content)switch(z.type){case"tool_result":q.push({role:"tool",content:kV4(z.run),tool_call_id:z.toolUseID.replace(/^toolu_/,"")});break;case"image":break;case"text":if(z.text.trim())G.push({type:"text",text:z.text});break}if(G.length>0)Q.push({role:"user",content:G});Q.push(...q);break}case"assistant":{let q=ep6(K.content).filter((W)=>W.type==="text").map((W)=>({type:"text",text:W.text})),z=K.content.filter((W)=>W.type==="tool_use").map((W)=>({id:W.id.replace(/^toolu_/,""),type:"function",function:{name:W.name,arguments:JSON.stringify(W.input)}}));if(q.length>0||z.length>0)Q.push({role:"assistant",content:q.length>0?q:null,tool_calls:z.length>0?z:void 0});break}case"info":{for(let G of K.content)if(G.type==="manual_bash_invocation"){let q=GS(G);if(q.length>0)Q.push({role:"user",content:q})}break}}}return QK(Q)}function vV4(J){return J.pipe(N8((Q)=>H2((async()=>{let Z=await Q.secrets.getToken("apiKey",Q.settings.url);return{url:Q.settings.url,apiKey:Z}})())),M8((Q,Z)=>Q.url===Z.url&&Q.apiKey===Z.apiKey),h0(({url:Q,apiKey:Z})=>{if(!Z)throw Error("API key not found. You must provide an API key in settings.");return new L8({apiKey:Z,baseURL:new URL("/api/provider/xai/v1",Q).toString()})}),S9({shouldCountRefs:!0}))}function Qd6(J,Q){return Y6(vV4(J.configService.config),Q)}function Zd6(J,Q,Z){return{...oJ(),[vX]:"amp.chat",...Q!=null?{[$G]:String(Q)}:{},...Z!=null?{[yQ]:Z}:{},"x-grok-conv-id":J.id,..._X(J)}}function Xd6(J){let Q=J?.message;if(typeof Q==="string"){if(Q.includes("This model's maximum prompt length is")&&Q.includes("but the request contains")&&Q.includes("tokens."))return new a7("Token limit exceeded.")}return J}class Gz1{useSupernova;constructor(J=!1){this.useSupernova=J}async*stream({model:J,thread:Q,buildSystemPromptDeps:Z,signal:X,agentMode:Y,clientRequestId:K}){let{systemPrompt:G,tools:q}=await cX(Z,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:this.useSupernova?"supernova":"xai",agentMode:Y},X),z=q.map((V)=>V2(J,V)),W=fs1(Q),U=SV4(W,z,G.map((V)=>V.text).join(`
5853
5853
 
5854
5854
  `),Q,J,{configService:Z.configService},X,this.useSupernova,mU(Q)?.messageId,K),F=this.useSupernova?"supernova":"xai",H=$B(`${F}/${J}`),B;for await(let V of U)if(B=aS(B,V),B)yield rS(B,H)}}var qz1=W1(()=>{C0();CX();lS();VM();q0();eB();GK();Cz();HD();A4();A4();YN();K5();q5();PJ();w51();JR();tp6()});function Yd6(J,Q){if(J==="openai"&&Q?.includes("gpt-oss-120b"))return new ad;switch(J){case"vertexai":return new Z_1;case"openai":return new Mr1;case"openrouter":return new Qy1;case"anthropic":return new Ov1;case"supernova":return new Gz1(!0);case"xai":return new Gz1;case"cerebras":return new ys1;case"groq":return new ad;case"moonshotai":return new ad;default:throw Error("Unknown provider: "+J)}}var _V4=void 0;var Kd6=W1(()=>{PJ();op6();NS();JJ1();Hq1();C71();qz1()});function Gd6(J){if(J.before===void 0&&J.after===void 0)throw Error("unreachable");if(J.before===null&&J.after===null)throw Error("unreachable")}function zz1(J,Q,Z){let X=new Map,Y=(G)=>{let q=void 0;for(let[z,W]of X.entries())for(let[U,F]of W.entries()){if(!d0.equalURIs(U,G))continue;if(!q||F.timestamp<q.timestamp)q=F}return q},K=async({filesFilter:G,toolUsesToRevert:q,pruneRevertedToolUses:z})=>{let W=new N2,U=new Map;for(let[B,V]of X.entries()){let M=q?q.has(B):!0;for(let[N,L]of V.entries()){if(G&&!G(N))continue;if(L.reverted)continue;let A=W.get(N)||{changesAfterKeep:[]};if(!M){if(!A.latestKeepChange||L.timestamp>A.latestKeepChange.timestamp)A.latestKeepChange=L}else A.changesAfterKeep.push(L),U.set(L,B);W.set(N,A)}}let F=Array.from(W.entries()).filter(([,{changesAfterKeep:B}])=>B.length>0);if(await I81(F,xV4,async([B,{latestKeepChange:V,changesAfterKeep:M}])=>{try{let N=M.reduce((A,w)=>w.timestamp<A.timestamp?w:A),L=V?V.after:N.isNewFile?null:N.before;await Z(B,L),pO(B,Q,Date.now());for(let A of M){A.reverted=!0;let w=U.get(A);if(w)try{let O={toolUseID:w,fileChangeID:A.id};await J.store(Q,O,A)}catch(O){p.error(`Error updating backup for file ${B}:`,O)}}}catch(N){p.error(`Error reverting file ${B}:`,N)}}),z&&q)for(let B of q)X.delete(B)};return{async getAllRecords(){return X},async record(G){if(!G.toolUse)return;let q=X.get(G.toolUse);if(!q)q=new N2,X.set(G.toolUse,q);if(q.has(G.uri))throw Error(`change to file ${G.uri} is already tracked for tool use ${G.toolUse}, multiple changes are not yet implemented`);let z=Y(G.uri),W=G.before===null,U=z?_B(z.before??"",G.after??"",G.uri):_B(G.before??"",G.after??"",G.uri),F=crypto.randomUUID(),H={id:F,uri:v6(G.uri),before:G.before??"",after:G.after??"",diff:U,isNewFile:W,reverted:!1,timestamp:Date.now()};pO(G.uri,Q,H.timestamp),q.set(G.uri,H),await J.store(Q,{toolUseID:G.toolUse,fileChangeID:F},H),p.debug("Recorded file change",{isNewFile:W,filePath:G.uri.toString(),toolUseID:G.toolUse})},async restoreFromBackups(){let G=await J.list(Q)??[];X.clear();for(let q of G){let{toolUseID:z}=q,W=await J.load(Q,q);if(!W)continue;if(W.filePath&&!W.uri)W.uri=v6(E0.file(W.filePath));if(!X.has(z))X.set(z,new N2);X.get(z).set(W.uri,W)}return{totalBackups:G.length}},async revertAll(G){let q=new Set;for(let[z]of X.entries())q.add(z);await K({filesFilter:G?(z)=>d0.equalURIs(z,G):void 0,toolUsesToRevert:q,pruneRevertedToolUses:!1})},async revertChanges(G){await K({toolUsesToRevert:G,pruneRevertedToolUses:!0})},async cleanupBackups(){await J.cleanup(Q)},async getLastEdit(G){let q,z=0;for(let[W,U]of X.entries()){let F=U.get(G);if(F&&!F.reverted&&F.timestamp>=z)q=F,z=F.timestamp}if(!q)return;return{oldContent:q.before,newContent:q.after,revert:()=>{q.reverted=!0}}},dispose(){X.clear()}}}var xV4=4;var Wz1=W1(()=>{u6();q0();vz();cU();Rg();E81()});function hs1(J,Q){let Z={readFile:async(X,Y)=>{let K=await Q.getLastEdit(X);if(K){if(K.newContent===null)throw Error(`File has been deleted: ${X}`);return K.newContent}return J.readFile(X,Y)},readBinaryFile:async(X,Y)=>{let K=await Z.readFile(X,Y);return new TextEncoder().encode(K)},getMtime:async(X,Y)=>{if(await Q.getLastEdit(X))return Date.now();return J.getMtime(X,Y)},stat:async(X,Y)=>{let K=await Q.getLastEdit(X);if(K){if(K.newContent===null)throw Error(`File has been deleted: ${X}`);return{size:b4.bufferByteLengthCompat(K.newContent),isDirectory:!1}}return J.stat(X,Y)},realpath:async(X,Y)=>{return J.realpath(X,Y)},findFiles:async(X,Y)=>{return J.findFiles(X,Y)},readdir:async(X,Y)=>{return J.readdir(X,Y)},access:async(X,Y)=>{let K=await Q.getLastEdit(X);if(K){if(K.newContent===null)throw Error(`File has been deleted: ${X}`);return}return J.access(X,Y)},watch:()=>wG};return Z}function qd6(J,Q,Z){let X={...hs1(J,Q),writeFile:async(Y,K,G)=>{await Q.record({toolUse:Z,uri:Y,before:await xT(X,Y,G),after:K})},mkdirp:async()=>{},rename:async(Y,K)=>{throw Error("Rename operations are not supported in this implementation")},delete:async(Y,K)=>{let G=await xT(X,Y,K);if(G===null)throw Error(`Cannot delete file that does not exist: ${Y}`);await Q.record({toolUse:Z,uri:Y,before:G,after:null})},isExclusiveWriterFor:async()=>!0,watch(){return wG},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0};return X}var zd6=W1(()=>{C0();mO();fX()});function Uz1(J,Q,Z){async function X(Y,K,G){let q={};q.before=await xT(J,K),await G(),q.after=await xT(J,K),Gd6(q),await Q.record({toolUse:Y,uri:K,...q})}return{...J,async writeFile(Y,K,G){await X(Z,Y,()=>J.writeFile(Y,K,G))},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0}}var gs1=W1(()=>{Wz1();fX()});function Wd6(J,Q,Z,X){async function Y(G,q,z){let W=Q.fileSystemForURI(X(),G);if(W.mountedTree.fs==="os"&&!bz(W))if(q!==null)await W.writeFile(G,q,{signal:z});else await W.delete(G,{signal:z})}let K=zz1(J.fileChangeTrackerStorage,Z,Y);return{fileSystemReader:()=>{let G=Q.fileSystemWithMountedTrees(X());return WP1(G)?G.mapReader((q)=>{if(bz(q))return hs1(q,K);return q}):G},trackedFileSystem:(G)=>{function q(z,W){if(WP1(z))return{...z.map((U)=>q(U,W)),__trackedFileSystem:!0};if(bz(z))return qd6(z,K,W);return Uz1(z,K,W)}return q(Q.fileSystemWithMountedTrees(X()),G)},tracker:K}}var Ud6=W1(()=>{Wz1();fX();zd6();gs1();fz()});function yV4(J,Q,Z){let X=Z.getExecutionProfile(J.name),Y=Z.getExecutionProfile(Q.name);if(!X||!Y)return!0;if(X.serial||Y.serial)return!0;let K=X.resourceKeys(J.input??{}),G=Y.resourceKeys(Q.input??{});for(let q of K)for(let z of G)if(q.key===z.key){if(q.mode==="write"||z.mode==="write")return!0}return!1}function bV4(J,Q,Z){for(let X of Q)if(yV4(J,X,Z))return!0;return!1}function Fd6(J,Q){if(J.length===0)return[];let Z=[],X=[];for(let Y of J){if(bV4(Y,X,Q)){if(X.length>0)Z.push(X),X=[]}X.push(Y)}if(X.length>0)Z.push(X);return Z}function us1(){return Hd6.trace.getTracer(fV4)}function Bd6(J){if(J instanceof Error)return J;if(typeof J==="string")return Error(J);return Error(String(J))}function hV4(J){return[(Q)=>{return J.end(),Q},(Q)=>{throw J.recordException(Bd6(Q)),J.end(),Q}]}function ms1(J,Q,Z){let X=Z.value;Z.value=function(...Y){return us1().startActiveSpan(Q,(K)=>{try{let G=X.apply(this,Y);if(G instanceof Promise)return G.then(...hV4(K));return K.end(),G}catch(G){throw K.recordException(Bd6(G)),K.end(),G}})}}var Hd6,fV4="amp";var ps1=W1(()=>{Hd6=G6(q6(),1)});function gV4(J){if(J.action.type==="redact-tool-input"&&J.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(J.action.type==="send-user-message"&&J.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function ds1(J){if(!J||!Array.isArray(J))return[];return J.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let Z=gV4(Q);if(Z)return p.warn(`Hook "${Q.id}" is invalid: ${Z}`),!1;return!0})}var Dd6=W1(()=>{q0()});function Vd6(J,Q){if(!J)return{action:null};J=ds1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:pre-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;let Y=JSON.stringify(Q.toolUse.input),K=Array.isArray(Z.on["input.contains"])?Z.on["input.contains"]:[Z.on["input.contains"]];for(let G of K)if(Y.includes(G)){if(p.debug(`Hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:G,action:Z.action}),Z.action.type==="send-user-message")return{hookID:Z.id,action:Z.action}}}}return{action:null}}function Md6(J,Q){if(!J)return{action:null};J=ds1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:post-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;if(p.debug(`Post-execution hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:Z.action}),Z.action.type==="redact-tool-input")return{hookID:Z.id,action:Z.action}}}return{action:null}}function Nd6(J,Q){if(!J)return{action:null};try{return J(Q.thread)}catch(Z){return p.error("Error processing assistant end-turn hook",Z),{action:null}}}async function Fz1(J,Q,Z){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":{let X={type:"user:message",message:{content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}};return J.updateThread(X),J.onThreadDelta(X),{abortOp:!0}}case"redact-tool-input":{if(!Z?.toolUseID)return p.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};let X={type:"tool:processed",toolUse:Z.toolUseID,newArgs:Q.action.redactedInput};return J.updateThread(X),J.onThreadDelta(X),p.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:Z.toolUseID}),{abortOp:!1}}}}var Ld6=W1(()=>{q0();Dd6()});function ha(J,Q){let Z=Q.agentMode??Dg0(Q),X=Ad6(J);if(X)return{agentMode:Z??"smart",model:X};let Y=Z??WZ(J);return{model:ls1(Y),agentMode:Y}}var cs1=W1(()=>{Dx();q5();A4()});function wd6(J){let Q=[],Z=/@((?:[^\s@\\,;]|\\.)+)/g,X;while((X=Z.exec(J))!==null){let Y=X[1],K=uV4(Y).replace(/[.,;:!?)}\]]+$/,"");Q.push(K)}return Q}function uV4(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Q,Z)=>{if(Z===" "||Z==="("||Z===")"||Z==="["||Z==="]"||Z==="?"||Z==="*")return Z;return Q});return J.replace(/\\(.)/g,"$1")}function Hz1(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}var Od6={};k6(Od6,{getUserState:()=>mV4});async function mV4(){if(!await $2.isConnected())return;let Q=await Y6($2.status),Z=Q.selections?.[0],X=Hz1(Z),Y=X&&Z?{line:Z.range.startLine+1,column:Z.range.startCharacter}:void 0;return{currentlyVisibleFiles:Q.visibleFiles??[],activeEditor:Q.openFile,cursorLocation:Y,cursorLocationLine:X?Z?.content:void 0,selectionRange:!X&&Z?{content:Z?.content,start:{line:Z?.range.startLine+1,column:Z?.range.startCharacter},end:{line:Z?.range.endLine+1,column:Z?.range.endCharacter}}:void 0}}var $d6=W1(()=>{C0();QR()});async function Rd6(J,{configService:Q,filesystem:Z}){let X={sentAt:Date.now()},Y=await Y6(Q.workspaceRoots)??[],K=g2(J.content);if(Y.length===0)return{role:"user",content:J.content,source:J.source,fileMentions:void 0,userState:void 0,agentMode:J.agentMode,meta:X};let G=await s91({fileSystem:Z},wd6(K),{searchPaths:Y,shouldIncludeImages:!J.agentMode||ga(J.agentMode)}),q=await(await Promise.resolve().then(() => ($d6(),Od6))).getUserState();return{role:"user",content:G?.imageBlocks?.length?[...J.content,...G.imageBlocks]:J.content,source:J.source,fileMentions:G,userState:{...q??z96},agentMode:J.agentMode,meta:X}}var Id6=W1(()=>{C0();q5();eB();A4();YN()});function pV4(J,Q,Z=!1){let X=sJ(J,"assistant");if(!X||X.state.type!=="complete"||X.state.stopReason!=="tool_use")return!1;let Y=X.content.filter((q)=>q.type==="tool_use").map((q)=>q.id);if(Q&&!Y.includes(Q))return p.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(Y.length===0)return!1;let K=TZ(J);return Y.every((q)=>{let z=K.get(q);if(!z||!h2(z.run))return!1;let W=z.run.status;if(W==="cancelled")return!1;if(W==="rejected-by-user")return Z;return!0})}var is1;var Ed6=W1(()=>{u6();C0();CX();VM();q0();sp6();Kd6();vz();Ts1();RO();fX();Ud6();fz();w8();K5();ps1();t76();Ld6();cs1();A4();d51();IE();Id6();is1=class is1{deps;threadID;async resumeInProgressTools(){for(let J of this.thread.messages){if(J.role!=="user")continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;if(!(!h2(Q.run)&&Q.run.status!=="blocked-on-user"&&!this.ops.tools[Q.toolUseID]))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(X.name===A7||X.name===Ah0){this.findAndCancelToolRun(Q.toolUseID);continue}p.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"resumeInProgressTools",threadID:this.threadID}),this.invokeTool(X,Q.userInput)}}await this.updateFileChanges()}findToolUseById(J){for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&Z.id===J)return Z}return}trackFilesFromHistory(){p.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(J.role==="user"){for(let Q of J.content)if(Q.type==="tool_result"&&Q.run.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}async getConfig(J){return Y6(this.deps.configService.config,J)}async getCodeHostService(J){if(!this.codeHostService){let Q=this.thread.env?.initial.trees||[],Z=await this.getConfig(J);this.codeHostService=rp6(Q,this.deps.threadService,this.deps.mcpService,Z,this.threadID)}return this.codeHostService}async currentToolService(){let J=await this.getSelectedAgentMode();return this.deps.toolServices.getForAgent(J)}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(h0((J)=>QT(J.settings?.permissions)),M8(),Nf0(1),s3(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){for(let J=this.thread.messages.length-1;J>=0;J--){let Q=this.thread.messages[J];if(!Q||Q.role!=="user")continue;let Z=!1;for(let X of Q.content)if(X.type==="tool_result"&&X.run?.status==="blocked-on-user"&&X.toolUseID)Z=!0,this.checkAndApproveBlockedTool(X.toolUseID);if(!Z)break}}async checkAndApproveBlockedTool(J){try{let Q=this.findToolUseById(J);if(!Q){p.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Z=await eq1(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,J);if(Z.permitted)p.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else p.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:J,reason:Z.reason})}catch(Q){p.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:J})}}async cleanupTaskToolSubThreads(J=this.thread.messages.length){let Q=this.thread.messages.slice(0,J),Z=YO1(Q),X=new Set(Z.map((K)=>K.toolUseID)),Y=new Set;for(let[K]of this.registeredSubthreads.entries())if(!X.has(K))Y.add(K);for(let K of Y){let G=this.registeredSubthreads.get(K);if(G.fileChanges?.unsubscribe(),await G.worker?.revertFileChanges(),G.latestFiles=[],this.mergeAndEmit(),await this.cleanupThreadBackups(G.threadID),await G.worker?.asyncDispose(),this.deps.deleteThread)try{await this.deps.deleteThread(G.threadID)}catch(q){p.error(`Failed to delete Task tool sub-thread: ${G.threadID}`,q,{threadID:this.threadID,subThreadID:G.threadID})}else p.warn(`Cannot delete Task tool sub-thread: ${G.threadID} - threadHistoryService not available`,{threadID:this.threadID,subThreadID:G.threadID});this.registeredSubthreads.delete(K)}if(Y.size>0)this.emitSubthreads()}ops={tools:{},toolMessages:{},inference:null};_state=new V5("initial");state=this._state.pipe(M8(),S9({shouldCountRefs:!0}));handleMutex=new _z;ephemeralError=new V5(void 0);inferenceState=new V5("idle");fileChanges=new V5({files:[]});toolCallUpdates=new S8;trackedFiles=new bX;fs;cachedFileChanges=[];registeredSubthreads=new Map;subthreadSequenceNumber=0;_subthreadsSubject=new V5([]);subthreads=this._subthreadsSubject.pipe(M8(),S9({shouldCountRefs:!0}));disposed$=new S8;isDisposed=!1;cancelledToolUses=new Set;codeHostService=null;shouldContinueAfterRejection=!1;lastInferenceRequestId;constructor(J,Q){this.deps=J;this.threadID=Q;this.fs=Wd6({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.vfs,Q,()=>jg(this.thread))}status=this.state.pipe(N8((J)=>J==="active"?$9(this.inferenceState.pipe(M8()),this.fileChanges.pipe(M8()),this.ephemeralError,this.toolCallUpdates.pipe(t4(void 0))).pipe(h0(([Q,Z,X])=>({state:J,inferenceState:Q,fileChanges:Z,ephemeralError:X?{message:X.message,stack:"stack"in X?X.stack:void 0,error:"error"in X&&X.error&&typeof X.error==="object"&&"error"in X.error?X.error.error:void 0}:void 0})),s3(this.disposed$)):J0.of({state:J})),S9({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(N56(J)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),await this.initializeCompletedSubthreads(),this.thread.mainThreadID)return;if(Ug0(J)||Fg0(J)&&!this.shouldContinueAfterRejection||KO1(J)){this.inferenceState.next("cancelled");return}await this.resumeInProgressTools(),this.setupSettingsChangeHandlers();let Q=this.thread.messages.findLastIndex((X)=>X.role==="user"?Hg0(X):X.role==="assistant"&&X.state.type==="complete");if(Q===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Z=this.thread.messages[Q];switch(Z.role){case"user":if(!Z.interrupted)this.onThreadDelta({type:"user:message",message:Z});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Z});break}}resumed=!1;async initializeCompletedSubthreads(){let J=YO1(this.thread.messages);for(let{toolUseID:Q,threadID:Z,toolUse:X,toolResult:Y}of J){let K=h2(Y.run),G=Y.run.status==="blocked-on-user";if(K&&!G)await this.registerSubthread(Q,Z,X)}}async forkThread(J){await this.acquireThread();let{threadService:Q}=this.deps,Z=await Q.forkThread(this.threadID,J);await this.handle({type:"fork:created",forkThreadID:Z.threadID,fromMessageIndex:J});let X=await Q.getPrimitiveProperty(this.threadID,"v");if(X!==null)await Q.flushVersion(this.threadID,X);return Z.threadID}async handle(J,Q){await this.handleMutex.acquire();try{await this.innerHandle(J,Q)}finally{this.handleMutex.release()}}async innerHandle(J,Q){if(this.isDisposed){p.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){p.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="thread:truncate")await this.cleanupFileChanges(J.fromIndex),await this.cleanupTaskToolSubThreads(J.fromIndex);let Z=J;if(J.type==="user:message"){let X=await Rd6(J.message,{configService:this.deps.configService,filesystem:this.fs.fileSystemReader()});Z=GM(J,(Y)=>{Y.message=H9(X),Q?.throwIfAborted()})}try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=J.type==="user:message"&&J.index!==void 0;if(this.updateThread(Z),this.onThreadDelta(Z),X)await this.cleanupFileChanges(),await this.cleanupTaskToolSubThreads(),await this.cleanupForkThreads()}catch(X){if(!EG(X))p.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else p.debug(`AbortError caught during handle processing for ${Z.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;onThreadDelta(J){switch(J.type){case"user:message":{if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((Q)=>{if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"&&Z.run.status==="done"&&Z.run.trackFiles)this.trackFiles(Z.run.trackFiles);if(Q.fileMentions?.files)this.trackFiles(Q.fileMentions.files.map((Z)=>Z.uri).filter((Z)=>Z!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0)??[]);if(this.thread.mainThreadID===void 0&&g01(this.thread)===1){let Q=Bg0(this.thread);if(Q?.agentMode)this.updateThread({type:"agent-mode",mode:Q.agentMode})}this.runInferenceAndUpdateThread();break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this.trackFiles(Q.fileMentions?.files?.map((Z)=>Z.uri).filter((Z)=>Z!==void 0)??[]),this.runInferenceAndUpdateThread();break}case"user:tool-input":{let Q=KK(this.thread,J.toolUse);if(Q)this.invokeTool(Q,J.value);break}case"tool:data":{if(this.cancelledToolUses.has(J.toolUse)){this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"cancelled by user message"}});return}let Q=KK(this.thread,J.toolUse);if(J.data.status==="in-progress"&&Q?.name===nJ){let Z=Q,X=XO1(J.data.progress);if(X)this.registerSubthread(J.toolUse,X,Z)}if(h2(J.data))this.cancelledToolUses.delete(J.toolUse);if(Q){let Z=pV4(this.thread,J.toolUse,this.shouldContinueAfterRejection);p.debug(`updated tool_result${Z?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID});let X=this.shouldContinueAfterRejection||this.inferenceState.getValue()!=="cancelled";if(Z&&X)this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{let Q=this.findToolUsesNeedingInvocation(J.message);p.debug(`saw ${Q.length} tool uses (${Q.map((Z)=>Z.name).join(", ")})`,{name:`handleThreadDelta(${J.type})`,threadID:this.threadID}),this.executeToolsWithPlan(Q);break}case"user:message-queue:enqueue":{let Q=this.inferenceState.getValue();if(Ss1(this.thread,Q)!=="tool-running"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let X=this.thread.messages.at(-1);if(X?.role==="assistant"){if(X.state.type==="cancelled"||X.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(X.state.type==="complete"&&X.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(X?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":break;case"inference:completed":{let Q=sJ(this.thread,"assistant");if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}if(Q){let X=this.findToolUsesNeedingInvocation(Q);this.executeToolsWithPlan(X)}if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="end_turn")if(this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else Fz1(this,Nd6(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));break}}}findToolUsesNeedingInvocation(J){if(J.content.some((Y)=>Y.type==="tool_use"&&Y.inputPartialJSON))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let X=TZ(this.thread);return J.content.filter((Y)=>Y.type==="tool_use").filter((Y)=>!X.has(Y.id)&&!this.cancelledToolUses.has(Y.id))}async getWorkspaceRoots(J){return await Y6(this.deps.configService.workspaceRoots,J)??this.thread.env?.initial?.trees?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0).map(nY)??[]}isToolUseEffectivelyComplete(J){if(!J.inputPartialJSON)return!0;try{return JSON.parse(J.inputPartialJSON.json),!0}catch{return!1}}async executeToolsWithPlan(J){if(J.length===0)return;let Q=Fd6(J,await this.currentToolService());p.debug(`executing ${J.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map((Z)=>Z.map((X)=>X.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(J){for(let Q of J){let X=(await Promise.allSettled(Q.map((Y)=>this.invokeToolAndWait(Y,void 0)))).filter((Y)=>Y.status==="rejected");if(X.length>0)p.warn(`${X.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:X.map((Y)=>Y.reason)})}}async invokeToolAndWait(J,Q){let Z=new Promise((X,Y)=>{if(!this.ops.toolCompletionResolvers)this.ops.toolCompletionResolvers={};this.ops.toolCompletionResolvers[J.id]={resolve:X,reject:Y}});this.invokeTool(J,Q).catch((X)=>{let Y=this.ops.toolCompletionResolvers?.[J.id];if(Y)p.debug(`Tool invocation setup failed for ${J.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(X)}),Y.reject(X),delete this.ops.toolCompletionResolvers?.[J.id]}),await Z}async invokeTool(J,Q){if(this.ops.tools[J.id])throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!this.isToolUseEffectivelyComplete(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Z=await this.getConfig(),X=Vd6(Z.settings?.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:Y}=await Fz1(this,X);if(Y)return;let K=new AbortController;this.ops.tools[J.id]=K,this.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let G=await this.getWorkspaceRoots(K.signal),q=h01(this.thread),z=new J0((V)=>{this.ops.toolMessages[J.id]=V}),W=await this.getCodeHostService(K.signal),U={...this.deps,dir:G.at(0)??null,dirs:G,tool:J.name,toolService:await this.currentToolService(),thread:this.thread,config:await this.getConfig(),trackedFiles:new bX(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J.id),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J.id,todos:q,toolMessages:z,threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:W.pullRequestChanges,agentMode:await this.getSelectedAgentMode()},F=(await this.currentToolService()).preprocessArgs?.(J.name,J.input,U);if(F)this.handle({type:"tool:processed",toolUse:J.id,newArgs:F});let H=F??J.input,B=(await this.currentToolService()).invokeTool(J.name,{args:H,userInput:Q},U).pipe(s3(this.disposed$),aY(()=>{delete this.ops.tools[J.id],this.ops.toolMessages[J.id]?.complete(),delete this.ops.toolMessages[J.id]})).subscribe({next:async(V)=>{if(p.debug(`${J.id}, ${V.status}`,{name:"invokeTool",threadID:this.threadID}),h2(V)){delete this.ops.tools[J.id],B.unsubscribe();let M=this.ops.toolCompletionResolvers?.[J.id];if(M){if(V.status==="done")M.resolve();else M.reject(Error(`Tool ${V.status}: ${J.id}`));delete this.ops.toolCompletionResolvers?.[J.id]}if(V.status==="done"&&V.trackFiles?.length)this.trackFiles(V.trackFiles);if(Z.settings?.hooks){let N=Md6(Z.settings.hooks,{threadID:this.threadID,toolUse:J});await Fz1(this,N,{toolUseID:J.id})}}await this.updateFileChanges(),await this.handle({type:"tool:data",toolUse:J.id,data:V},K.signal)},error:async(V)=>{await this.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in V?V.message:String(V),displayMessage:"displayMessage"in V?V.displayMessage:void 0}}},K.signal)},complete:()=>{}});uO(K.signal,()=>B.unsubscribe())}catch(G){throw delete this.ops.tools[J.id],G}}async cancelInProgressTools(){for(let J of Object.keys(this.ops.tools))await this.cancelTool(J)}cancelAllActiveTools(){let J=TZ(this.thread);for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&!Z.inputPartialJSON){let X=J.get(Z.id);if(!(X&&h2(X.run)))this.cancelledToolUses.add(Z.id)}}for(let Q of this.thread.messages)if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"){if(!h2(Z.run))this.cancelledToolUses.add(Z.toolUseID)}}}cancelUnstartedTools(){let J=TZ(this.thread),Q=this.thread.messages.findLastIndex((X)=>KO1(X)),Z=Q===-1?this.thread.messages:this.thread.messages.slice(Q+1);for(let X of Z){if(X.role!=="assistant")continue;for(let Y of X.content)if(Y.type==="tool_use"&&!Y.inputPartialJSON){let K=J.get(Y.id);if(!K||K.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:Y.id,data:{status:"cancelled"}})}}}async runInferenceAndUpdateThread(){this.ops.inference?.abort(),this.ops.inference=null,this.inferenceState.next("running");let J=new AbortController;this.ops.inference=J,this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools();for(let G of this.thread.messages)if(G.role==="user"){for(let q of G.content)if(q.type==="tool_result"&&q.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:q.toolUseID,data:{status:"cancelled"}})}let Q=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&Q?.role==="user"&&this.thread.messages.filter((G)=>G.role==="user").length===1){if(this.deps.generateThreadTitle(Q,this.thread,this.deps.configService,J.signal).then(({title:G,usage:q})=>{if(J.signal.aborted||this.isDisposed)return;if(G!==void 0&&this.thread.title!==G)this.updateThread({type:"title",value:G,usage:q})}).catch((G)=>{if(!EG(G))p.error("generateThreadTitle error",G,{name:"ThreadWorker",threadID:this.threadID})}),this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(G)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...G}}})}).catch((G)=>{p.error("Failed to initialize thread environment",G,{threadID:this.threadID})})}let X=await this.getConfig(),{model:Y,agentMode:K}=ha(X.settings,this.thread);try{let[G,q,z]=Y.match(/(.*?)\/(.*)/)??[],W=Yd6(q??"",z??""),U=crypto.randomUUID();this.lastInferenceRequestId=U;let F={model:z??"",thread:this.thread,buildSystemPromptDeps:{toolServices:this.deps.toolServices,configService:this.deps.configService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.fs.fileSystemReader(),threadService:this.deps.threadService},signal:J.signal,agentMode:K,clientRequestId:U},H=W.stream(F),B;for await(let V of H)B=V,await this.handle({type:"assistant:message-update",message:V});if(B?.usage&&this.lastInferenceRequestId){let{fetchCreditsByRequestId:V}=await Promise.resolve().then(() => (iX(),s76)),M=await V(this.lastInferenceRequestId,this.deps.configService,{signal:J.signal});if(M!==null)B={...B,usage:{...B.usage,credits:M}};this.lastInferenceRequestId=void 0}await this.handle({type:"inference:completed",model:B?.usage?.model,usage:B?.usage})}catch(G){if(!(EG(G)||fm0(G))){let q=G instanceof Error?G:Error(String(G));this.ephemeralError.next(q)}return}finally{if(this.ops.inference===J)this.ops.inference=null,this.inferenceState.next("idle")}}async findAndCancelToolRun(J,Q){if(this.cancelInference(),!KK(this.thread,J))return;await this.cancelTool(J,Q)}async cancelToolOnly(J,Q){if(!KK(this.thread,J))return;let X=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let Y=this.ops.toolMessages[J];if(Y){try{Y.next({type:"stop-command"})}catch(K){p.warn("Failed to send stop-command",{id:J,error:K})}Y.complete(),delete this.ops.toolMessages[J]}p.debug(`cancelToolOnly(${J})`),await this.handle({type:"tool:data",toolUse:J,data:X},Q)}invokeBashTool(J,Q,Z){return new J0((X)=>{let Y,K,G,z=((U)=>{return uO(U,()=>{if(p.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),G?.unsubscribe(),K?.unsubscribe(),X?.complete(),Y)this.handleManualBashInvocation(J,{status:"cancelled",progress:QO1(Y)},Z)})})(Q);return(async()=>{try{if(Q.aborted){X.error(Error("Operation was aborted"));return}let U=await this.getWorkspaceRoots(Q),F=await this.getConfig(Q),H=await this.getCodeHostService(Q),B={...this.deps,dir:U.at(0)??null,dirs:U,tool:A7,toolService:await this.currentToolService(),thread:this.thread,config:F,trackedFiles:new bX(this.trackedFiles),filesystem:Zp0(this.fs.fileSystemReader()),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:HT(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),pullRequestChanges:H.pullRequestChanges};K=(await this.currentToolService()).invokeTool(A7,{args:J,userInput:{accepted:!0}},B).subscribe({next:(V)=>{Y=V,X.next(V)},error:(V)=>{X.error(V)},complete:()=>{if(Y)this.handleManualBashInvocation(J,Y,Z);X.complete()}}),G=this.disposed$.subscribe(()=>{z(),K?.unsubscribe(),X?.complete()})}catch(U){X.error(U)}})(),()=>{z(),K?.unsubscribe(),G?.unsubscribe()}})}async handleManualBashInvocation(J,Q,Z){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Q,hidden:Z})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),p.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Q){p.error("Error cleaning up thread backups",Q,{threadID:J})}}cancelDataForToolRun(J){let Z=TZ(this.thread).get(J)?.run;return{status:"cancelled",progress:Z?QO1(Z):void 0}}async cancelTool(J,Q){let Z=this.cancelDataForToolRun(J);await this.cancelSubthread(J);let X=this.ops.toolMessages[J];if(X){try{X.next({type:"stop-command"})}catch(Y){p.warn("Failed to send stop-command",{id:J,error:Y})}X.complete(),delete this.ops.toolMessages[J]}p.debug(`cancelToolRun(${J})`),await this.handle({type:"tool:data",toolUse:J,data:Z},Q)}async cancel(){p.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(eE1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(p.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;let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="complete"&&J.state.stopReason==="refusal")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}async cancelSubthread(J){let Q=this.registeredSubthreads.get(J);if(Q&&Q.worker)await Q.worker.cancel()}abortToolOp(J){this.ops.tools[J]?.abort(),delete this.ops.tools[J]}abortAllTools(){for(let J of Object.keys(this.ops.tools)){let Q=J,Z=this.ops.toolMessages[Q];if(Z)try{Z.next({type:"stop-command"}),Z.complete(),delete this.ops.toolMessages[Q]}catch(X){p.warn("Failed to send stop-command during disposal",{id:Q,error:X})}this.abortToolOp(Q)}}trackFiles(J){for(let Q of J)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();p.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){p.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){for(let Q of this.registeredSubthreads.values()){let Z=Q?.worker;if(Z)await Z.revertFileChanges(J)}await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){let J=new Map;for(let Z of this.registeredSubthreads.values()){let X=Z?.worker;if(X){let Y=await X.getAllTrackedChanges();for(let[K,G]of Y.entries())J.set(K,G)}}let Q=await this.fs.tracker.getAllRecords();for(let[Z,X]of Q.entries())J.set(Z,X);return J}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async cleanupFileChanges(J=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,J).forEach((Y)=>{if(Y.role==="user"){for(let K of Y.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of Y.content)if(K.type==="tool_use")Q.add(K.id)});let Z=new Set,X=await this.fs.tracker.getAllRecords();for(let[Y]of X.entries())if(!Q.has(Y))Z.add(Y);if(Z.size===0)return;await this.fs.tracker.revertChanges(Z),await this.updateFileChanges()}async updateFileChanges(){this.cachedFileChanges=await o76(this.fs.tracker),this.mergeAndEmit()}mergeAndEmit(){let J=new N2;for(let Z of this.cachedFileChanges)J.set(Z.uri,Z);for(let Z of this.registeredSubthreads.values())for(let X of Z.latestFiles??[])J.set(X.uri,X);let Q=J.size;if(Q>50)p.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:[...J.values()]})}emitSubthreads(){let J=Array.from(this.registeredSubthreads.values()).sort((Q,Z)=>Q.sequenceNumber-Z.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(J)}async registerSubthread(J,Q,Z){if(this.registeredSubthreads.has(J))return;let X=await gJ.getOrCreateForSubThread(this.deps,Q);await X.resume();let Y=X.status.pipe(B2((K)=>K.state==="active"),h0((K)=>K.fileChanges.files),s3(this.disposed$)).subscribe((K)=>{let G=this.registeredSubthreads.get(J);if(!G)return;G.latestFiles=K,this.mergeAndEmit()});this.registeredSubthreads.set(J,{threadID:Q,worker:X,fileChanges:Y,toolUse:Z,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}continueInferenceAfterRejection(J=!0){this.shouldContinueAfterRejection=J}async asyncDispose(){if(this.isDisposed)return;if(p.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete(),await Promise.all(Array.from(this.registeredSubthreads.values()).map(async(J)=>{J.fileChanges?.unsubscribe(),await J.worker?.asyncDispose()})),this.registeredSubthreads.clear(),this.cancelledToolUses.clear(),this._state.complete(),this.ephemeralError.complete(),this.inferenceState.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.fs.tracker.dispose(),this.codeHostService)this.codeHostService.dispose(),this.codeHostService=null;if(this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let J=await this.getConfig(),{agentMode:Q}=ha(J.settings,this.thread);return Q}};qB1([ms1],is1.prototype,"invokeTool",null),qB1([ms1],is1.prototype,"runInferenceAndUpdateThread",null)});class jd6{threadWorkers=new tf;async getOrCreateForThread(J,Q){if(await J.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(J,Q);return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForSubThread(J,Q){let Z=await J.threadService.getPrimitiveProperty(Q,"mainThreadID"),X=Z?await J.threadService.get(Z):void 0,Y=Vr1(X?.agentMode),K=J.toolServices.getForAgent(Y),G=xQ(K,Bz1),q=RE.createSingleToolServices(G);return this.getOrCreateForThreadInternal({...J,toolServices:q},Q)}async getOrCreateForThreadInternal(J,Q){let Z=this.threadWorkers.get(Q);if(!Z){if(Z=new is1(J,Q),this.threadWorkers.set(Q,Z),this.threadWorkers.size>25)p.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return ns1.record(this.threadWorkers.size),Z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(N8((J)=>J.size===0?J0.of({}):$9(...Array.from(J.values()).map((Q)=>Q.status.pipe(h0((Z)=>[Q.threadID,Q.threadReadWriter?ya(Q.thread,Z):void 0])))).pipe(h0((Q)=>Object.fromEntries(Q)))),DB(25),S9())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Q){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No worker found for thread ${J}`);for(let X of Z.thread.messages)for(let Y of X.content)if(Y.type==="tool_result"&&Y.toolUseID===Q)return yp6(Y.run);throw Error(`Tool run not found for thread ${J} and tool use ${Q}`)}async cancelToolOnly(J,Q){await this.threadWorkers.get(J)?.cancelToolOnly(Q)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Q=this.threadWorkers.get(J);if(Q)await Q.asyncDispose(),this.threadWorkers.delete(J),ns1.record(this.threadWorkers.size);this.threadWorkers.dispose()}async retry(J){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.retry()}async revertFileChanges(J,Q){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No active worker for thread ${J}`);await Z.revertFileChanges(Q)}async cleanupThreadBackups(J,Q){let Z=this.threadWorkers.get(Q);if(Z)await Z.fs.tracker.cleanupBackups();else{let X=await J.threadService.get(Q);if(!X)return;let Y=J.vfs.fileSystemWithMountedTrees(jg(X));try{await new xa(Y).cleanup(Q),p.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(K){p.error("Error cleaning up thread backups",K,{threadID:Q})}}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),ns1.record(0)}}var Pd6,dV4,ns1,gJ;var IE=W1(()=>{C0();q0();fz();Jz1();as1();bp6();K5();Qz1();Ed6();Pd6=G6(q6(),1),dV4=Pd6.metrics.getMeter("thread-worker-service"),ns1=dV4.createGauge("thread_worker_count",{description:"Number of active thread workers"});gJ=new jd6});function Td6(J,Q,Z){return new J0((X)=>{let Y=!1,K=null,G=void 0,q=void 0,z=!1,W=!1,U=()=>{if(G)G.unsubscribe(),G=void 0;if(q)q.unsubscribe(),q=void 0;Y=!0};return(async()=>{let H=jz(),{toolService:B,...V}=Z,M={...V,toolServices:RE.createSingleToolServices({...B,registerTool:()=>({dispose:()=>{}}),dispose:()=>{}})};K=await gJ.getOrCreateForSubThread(M,H),q=K.status.pipe(B2((A)=>A.state==="active")).subscribe((A)=>{if(Y)return;let w={threadID:H};if(A.inferenceState==="running")z=!0,W=!1;else if(A.inferenceState==="idle")W=!0;if(A.inferenceState==="cancelled")X.next({status:"cancelled",progress:w}),X.complete(),U();else if(A.ephemeralError)X.next({status:"error",progress:w,error:A.ephemeralError}),X.complete(),U()}),await K.handle({type:"main-thread",value:Z.thread.id}),await K.handle({type:"title",value:Q});let N=Z.agentMode||WZ(Z.config.settings);if(await K.handle({type:"agent-mode",mode:N}),Z.threadEnvironment)await K.handle({type:"environment",env:{initial:Z.threadEnvironment}});let L=!1;G=Z.threadService.observe(H).subscribe((A)=>{if(Y||!A)return;let w={threadID:H},O=sJ(A,"assistant");if(!O||O.state.type!=="complete"&&O.state.type!=="error"){if(W&&z){let I=A.messages.filter((R)=>R.role==="assistant").flatMap((R)=>g2(R.content)).join(`
5855
5855
 
@@ -6243,7 +6243,7 @@ Please proceed with implementing this plan step by step.`;let X={workspaceFolder
6243
6243
 
6244
6244
  ${FT4(J,X)}
6245
6245
 
6246
- Please proceed with implementing this plan step by step.`}fX();MD();_T();A4();u6();XN();q0();q0();_h();Cz();cs1();Xy1();PJ();Fd();Hq1();qz1();async function Oe6(J){let{thread:Q,userPromptText:Z,systemPrompt:X,images:Y,toolSpec:K,configService:G,signal:q}=J,z=await G.getLatest(q),{model:W}=ha(z.settings,Q),[U]=W.split("/"),F=OB(W);p.debug("Running tool with model",{threadId:Q.id,model:W,provider:U,modelName:F,toolName:K.name});let H=x71(Q);switch(U){case"anthropic":return HT4(H,Z,Y,X,K,F,G,q);case"xai":return DT4(H,Z,Y,X,K,F,G,q);case"openai":return BT4(H,Z,Y,X,K,F,G,q);case"vertexai":case"openrouter":case"groq":case"moonshotai":case"cerebras":default:throw Error(`Unsupported provider for handoff: ${U}`)}}async function HT4(J,Q,Z,X,Y,K,G,q){let z=await qS({configService:G},q),W=O51(J),U=[{type:"text",text:Q}];for(let M of Z)if(M.source.type==="base64"&&"mediaType"in M.source&&"data"in M.source)U.push({type:"image",source:{type:"base64",media_type:M.source.mediaType,data:M.source.data}});let F=[...W,{role:"user",content:U}],H=["fine-grained-tool-streaming-2025-05-14"];if(/claude-.*sonnet-4/i.test(K))H.push("context-1m-2025-08-07");let B=await z.messages.create({model:K,max_tokens:4096,system:X,messages:F,tools:I51([Y]),tool_choice:{type:"tool",name:Y.name}},{signal:q,headers:{[yQ]:`handoff-${J.id}`,"anthropic-beta":H.join(",")}}),V=B.content.find((M)=>M.type==="tool_use"&&M.name===Y.name);if(!V)throw Error(`Expected tool call for ${Y.name} but none found`);return{toolCall:V.input,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:B.usage.input_tokens,outputTokens:B.usage.output_tokens,cacheCreationInputTokens:B.usage.cache_creation_input_tokens??null,cacheReadInputTokens:B.usage.cache_read_input_tokens??null,totalInputTokens:B.usage.input_tokens,credits:0}}}async function BT4(J,Q,Z,X,Y,K,G,q){let z=await RN({configService:G},q),W=Nr1(J),U=[{type:"input_text",text:Q}];for(let w of Z)if(w.source.type==="base64"&&"mediaType"in w.source&&"data"in w.source)U.push({type:"input_image",detail:"auto",image_url:`data:${w.source.mediaType};base64,${w.source.data}`});let F=[{role:"system",content:X},...W,{role:"user",content:U}],H={...Y.inputSchema,additionalProperties:!1},B=await z.responses.create({model:K,input:F,text:{format:{type:"json_schema",name:Y.name,strict:!0,schema:H}},store:!1},{signal:q,headers:IN(J,void 0,`handoff-${J.id}`)}),V=B.output?.find((w)=>w.type==="message");if(!V||V.type!=="message")throw Error("Expected message output but none found");let M=V.content?.find((w)=>w.type==="output_text");if(!M||M.type!=="output_text")throw Error("Expected output_text content in response");let N;try{N=JSON.parse(M.text)}catch(w){let O=M.text?.slice?.(0,200)??"";throw Error(`Response was not valid JSON for ${Y.name} (preview: ${O}...)`)}let L=B.usage?.input_tokens_details?.cached_tokens??0,A=(B.usage?.input_tokens??0)-L;return{toolCall:N,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:B.usage?.input_tokens??0,outputTokens:B.usage?.output_tokens??0,cacheCreationInputTokens:A,cacheReadInputTokens:L,totalInputTokens:B.usage?.input_tokens??0,credits:0}}}async function DT4(J,Q,Z,X,Y,K,G,q){let z=fs1(J),W=[{type:"text",text:Q}];for(let V of Z)if(V.source.type==="base64"&&"mediaType"in V.source&&"data"in V.source)W.push({type:"image_url",image_url:{url:`data:${V.source.mediaType};base64,${V.source.data}`}});let U=[...z,{role:"user",content:W}],F=await Kz1(U,[Y],X,{id:J.id,agentMode:J.agentMode},K,{configService:G},q,!1),H=F.message?.choices?.[0]?.message?.tool_calls?.[0];if(!H||H.function.name!==Y.name)throw Error(`Expected tool call for ${Y.name} but none found`);let B;try{B=JSON.parse(H.function.arguments)}catch(V){let M=H.function.arguments?.slice?.(0,200)??"";throw Error(`Tool call arguments for ${Y.name} were not valid JSON (preview: ${M}...)`)}return{toolCall:B,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:F.message?.usage?.prompt_tokens??0,outputTokens:F.message?.usage?.completion_tokens??0,cacheCreationInputTokens:null,cacheReadInputTokens:null,totalInputTokens:F.message?.usage?.prompt_tokens??0,credits:0}}}Ax();wB();Xy1();function VT4(J){let Q=/@([^\s@]+)/g,Z=[],X;while((X=Q.exec(J))!==null){let Y=X[1]?.trim();if(Y)Z.push(Y)}return Z}var MT4=20,NT4=EJ`
6246
+ Please proceed with implementing this plan step by step.`}fX();MD();_T();A4();u6();XN();q0();q0();_h();Cz();cs1();Xy1();PJ();Fd();Hq1();qz1();async function Oe6(J){let{thread:Q,userPromptText:Z,systemPrompt:X,images:Y,toolSpec:K,configService:G,signal:q}=J,z=await G.getLatest(q),{model:W}=ha(z.settings,Q),[U]=W.split("/"),F=OB(W);p.debug("Running tool with model",{threadId:Q.id,model:W,provider:U,modelName:F,toolName:K.name});let H=x71(Q);switch(U){case"anthropic":return HT4(H,Z,Y,X,K,F,G,q);case"xai":return DT4(H,Z,Y,X,K,F,G,q);case"openai":return BT4(H,Z,Y,X,K,F,G,q);case"vertexai":case"openrouter":case"groq":case"moonshotai":case"cerebras":default:throw Error(`Unsupported provider for handoff: ${U}`)}}async function HT4(J,Q,Z,X,Y,K,G,q){let z=await qS({configService:G},q),W=O51(J),U=[{type:"text",text:Q}];for(let M of Z)if(M.source.type==="base64"&&"mediaType"in M.source&&"data"in M.source)U.push({type:"image",source:{type:"base64",media_type:M.source.mediaType,data:M.source.data}});let F=[...W,{role:"user",content:U}],H=["fine-grained-tool-streaming-2025-05-14"];if(/claude-.*sonnet-4/i.test(K))H.push("context-1m-2025-08-07");let B=await z.messages.create({model:K,max_tokens:4096,system:X,messages:F,tools:I51([Y]),tool_choice:{type:"tool",name:Y.name}},{signal:q,headers:{[yQ]:`handoff-${J.id}`,"anthropic-beta":H.join(",")}}),V=B.content.find((M)=>M.type==="tool_use"&&M.name===Y.name);if(!V)throw Error(`Expected tool call for ${Y.name} but none found`);return{toolCall:V.input,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:B.usage.input_tokens,outputTokens:B.usage.output_tokens,cacheCreationInputTokens:B.usage.cache_creation_input_tokens??null,cacheReadInputTokens:B.usage.cache_read_input_tokens??null,totalInputTokens:B.usage.input_tokens,credits:0}}}async function BT4(J,Q,Z,X,Y,K,G,q){let z=await RN({configService:G},q),W=Nr1(J),U=[{type:"input_text",text:Q}];for(let w of Z)if(w.source.type==="base64"&&"mediaType"in w.source&&"data"in w.source)U.push({type:"input_image",detail:"auto",image_url:`data:${w.source.mediaType};base64,${w.source.data}`});let F=[{role:"system",content:X},...W,{role:"user",content:U}],H={...Y.inputSchema,additionalProperties:!1},B=await z.responses.create({model:K,input:F,text:{format:{type:"json_schema",name:Y.name,strict:!0,schema:H}},store:!1},{signal:q,headers:IN(J,void 0,`handoff-${J.id}`)}),V=B.output?.find((w)=>w.type==="message");if(!V||V.type!=="message")throw Error("Expected message output but none found");let M=V.content?.find((w)=>w.type==="output_text");if(!M||M.type!=="output_text")throw Error("Expected output_text content in response");let N;try{N=JSON.parse(M.text)}catch(w){let O=M.text?.slice?.(0,200)??"";throw Error(`Response was not valid JSON for ${Y.name} (preview: ${O}...)`)}let L=B.usage?.input_tokens_details?.cached_tokens??0,A=(B.usage?.input_tokens??0)-L;return{toolCall:N,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:B.usage?.input_tokens??0,outputTokens:B.usage?.output_tokens??0,cacheCreationInputTokens:A,cacheReadInputTokens:L,totalInputTokens:B.usage?.input_tokens??0,credits:0}}}async function DT4(J,Q,Z,X,Y,K,G,q){let z=fs1(J),W=[{type:"text",text:Q}];for(let V of Z)if(V.source.type==="base64"&&"mediaType"in V.source&&"data"in V.source)W.push({type:"image_url",image_url:{url:`data:${V.source.mediaType};base64,${V.source.data}`}});let U=[...z,{role:"user",content:W}],F=await Kz1(U,[Y],X,{id:J.id,agentMode:J.agentMode},K,{configService:G},q,!1,void 0,void 0,{type:"function",function:{name:Y.name}}),H=F.message?.choices?.[0]?.message?.tool_calls?.[0];if(!H||H.function.name!==Y.name)throw Error(`Expected tool call for ${Y.name} but none found`);let B;try{B=JSON.parse(H.function.arguments)}catch(V){let M=H.function.arguments?.slice?.(0,200)??"";throw Error(`Tool call arguments for ${Y.name} were not valid JSON (preview: ${M}...)`)}return{toolCall:B,"~debugUsage":{model:K,maxInputTokens:-1,inputTokens:F.message?.usage?.prompt_tokens??0,outputTokens:F.message?.usage?.completion_tokens??0,cacheCreationInputTokens:null,cacheReadInputTokens:null,totalInputTokens:F.message?.usage?.prompt_tokens??0,credits:0}}}Ax();wB();Xy1();function VT4(J){let Q=/@([^\s@]+)/g,Z=[],X;while((X=Q.exec(J))!==null){let Y=X[1]?.trim();if(Y)Z.push(Y)}return Z}var MT4=20,NT4=EJ`
6247
6247
  Extract relevant context from the conversation above for continuing this work. Write from my perspective (first person: "I did...", "I told you...").
6248
6248
 
6249
6249
  Consider what would be useful to know based on my request below. Questions that might be relevant:
@@ -6263,7 +6263,9 @@ Please proceed with implementing this plan step by step.`}fX();MD();_T();A4();u6
6263
6263
  My request:
6264
6264
  `;function LT4(J,Q){return J.map((Z)=>{let X=Z.startsWith("file:")?vQ(Z,Q):Z;return"@"+TH(X)})}async function AT4({userGoal:J,images:Q,thread:Z,configService:X,signal:Y}){let K=`${NT4}
6265
6265
 
6266
- ${J}`;return(await Oe6({thread:Z,userPromptText:K,systemPrompt:"",images:Q,toolSpec:wT4,configService:X,signal:Y})).toolCall}async function $e6(J,Q,Z,X,Y){let K=performance.now(),G=x71(J),q=J.env?.initial;if(!q)throw Error("Thread environment not available for handoff");let z={workspaceFolders:q.trees?.map(($)=>$.uri).filter(($)=>$!==void 0)??null,isWindows:q.platform?.os==="windows"},W=VT4(Q),U=z.workspaceFolders?.map(($)=>E0.parse($))??[],F=await AT4({userGoal:Q,images:Z,thread:G,configService:X,signal:Y}),H;if(typeof F.relevantFiles==="string")H=F.relevantFiles.split(`
6266
+ ${J}
6267
+
6268
+ Use the create_handoff_context tool to extract relevant information and files.`;return(await Oe6({thread:Z,userPromptText:K,systemPrompt:"",images:Q,toolSpec:wT4,configService:X,signal:Y})).toolCall}async function $e6(J,Q,Z,X,Y){let K=performance.now(),G=x71(J),q=J.env?.initial;if(!q)throw Error("Thread environment not available for handoff");let z={workspaceFolders:q.trees?.map(($)=>$.uri).filter(($)=>$!==void 0)??null,isWindows:q.platform?.os==="windows"},W=VT4(Q),U=z.workspaceFolders?.map(($)=>E0.parse($))??[],F=await AT4({userGoal:Q,images:Z,thread:G,configService:X,signal:Y}),H;if(typeof F.relevantFiles==="string")H=F.relevantFiles.split(`
6267
6269
  `).map(($)=>$.trim()).filter(Boolean);else H=F.relevantFiles??[];let B=[];for(let $ of H){let I=$.trim();if(!I)continue;if(I.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(I)){p.debug("Skipping absolute path from model",{path:I});continue}for(let R of U)try{let j=v6(R.with({path:`${R.path}/${I}`}));B.push(j);break}catch{}}let V=[];for(let $ of W)for(let I of U)try{let R=v6(I.with({path:`${I.path}/${$}`}));V.push(R);break}catch{}let N=[...new Set([...V,...B])].slice(0,MT4),L=performance.now()-K;p.debug("Thread handoff prepared",{threadId:J.id,goalLength:Q.length,relevantInformationLength:F.relevantInformation?.length??0,mentionedFileCount:V.length,returnedFileCount:H.length,resolvedFileCount:B.length,validatedFileCount:N.length,validatedFilesSample:N.slice(0,3),durationMs:Math.round(L)});let A=LT4(N,z).join(" "),w=[];if(w.push(`Continuing work from thread ${J.id}. When you lack specific information you can use read_thread to get it. `),A)w.push(A);if(F.relevantInformation)w.push(F.relevantInformation);w.push(Q);let O=w.join(`
6268
6270
 
6269
6271
  `);if(Z.length>0)return[{type:"text",text:O},...Z];return O}var wT4={name:"create_handoff_context",description:EJ`
@@ -6438,11 +6440,11 @@ Actual: ${Y}`)}async function Jh4(J,Q,Z){let{execSync:X}=await import("node:ch
6438
6440
  ${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))V+=`
6439
6441
 
6440
6442
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6441
- npm install -g @sourcegraph/amp`;q(Error(V))}},error:(H)=>{if(!U)U=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!U)U=!0,G()}})})}q0();q0();async function oU1(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=Kh4(J,G),z=q<0,W,U;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)W=Math.floor((B-new Date(F).getTime())/3600000);if(H)U=Math.floor((B-new Date(H).getTime())/3600000)}return p.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(Z){return p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Kh4(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 B60(J,Q){let Z=new S8,X=Z.pipe(S9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new yU().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 KN(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 oU1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let W=await sU1();if(!q)q=W==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:W,mode:q});if(q==="warn"){Z.next("update-available");return}if(!W){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Hs(z.latestVersion,W);let U=await gA(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...U};if(U.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await KN(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as bH}from"node:process";function m48(J){let Q=new hE().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 U60(X.force||!1,X.verbose||!1,"0.0.1762358483-gc3a3b8"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new hE("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 Gh4(X.version)});J.addCommand(Z)}async function Gh4(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bH.write(U8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6443
+ npm install -g @sourcegraph/amp`;q(Error(V))}},error:(H)=>{if(!U)U=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!U)U=!0,G()}})})}q0();q0();async function oU1(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=Kh4(J,G),z=q<0,W,U;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)W=Math.floor((B-new Date(F).getTime())/3600000);if(H)U=Math.floor((B-new Date(H).getTime())/3600000)}return p.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(Z){return p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Kh4(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 B60(J,Q){let Z=new S8,X=Z.pipe(S9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new yU().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 KN(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 oU1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let W=await sU1();if(!q)q=W==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:W,mode:q});if(q==="warn"){Z.next("update-available");return}if(!W){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Hs(z.latestVersion,W);let U=await gA(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...U};if(U.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await KN(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as bH}from"node:process";function m48(J){let Q=new hE().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 U60(X.force||!1,X.verbose||!1,"0.0.1762361985-g1ec0ff"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new hE("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 Gh4(X.version)});J.addCommand(Z)}async function Gh4(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bH.write(U8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6442
6444
 
6443
6445
  `));try{if(!J){bH.write(U8.blue(`Checking for updates...
6444
- `));let{hasUpdate:Z,latestVersion:X}=await oU1("0.0.1762358483-gc3a3b8");if(!Z){bH.write(U8.green(`✓ Amp CLI is already up to date.
6445
- `));let Y=await gA("0.0.1762358483-gc3a3b8");if(Y.warning)bH.write(`
6446
+ `));let{hasUpdate:Z,latestVersion:X}=await oU1("0.0.1762361985-g1ec0ff");if(!Z){bH.write(U8.green(`✓ Amp CLI is already up to date.
6447
+ `));let Y=await gA("0.0.1762361985-g1ec0ff");if(Y.warning)bH.write(`
6446
6448
  `+U8.yellow(Y.warning)+`
6447
6449
  `);process.exit(0)}if(!X)bH.write(U8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}bH.write(U8.blue(`Updating to version ${J}...
6448
6450
  `)),await Hs(J,void 0,(Z)=>{bH.write(U8.dim(`Running: ${Z}
@@ -7011,7 +7013,7 @@ exit code: ${q}`,new $1({color:X.foreground,dim:!0,italic:!0})));if(z)W.push(new
7011
7013
  `,B),...V],N=new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new c1({text:new V1("",void 0,M)})]}),L="high";if(this.agentMode==="rush")L="rush";else if(this.agentMode==="free")L="free";return i9.child(new m0({constraints:new P6(40,120,0,1/0),child:new l6({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new Y8({flex:1,child:new R80({width:40,height:40,colorMode:L,fps:G==="fast"?60:G==="slow"?15:0,...G==="disabled"&&{seed:42,t:3}})}),new U0({width:1}),new Y8({flex:2,child:N})]})}))}}l8();class E40 extends y0{props;constructor(J){super({key:J.key});this.props=J;this.props.enabled??=!0}createState(){return new mQ8}}class mQ8 extends x0{build(J){let Z=A6.of(J).colors,{todos:X,title:Y="TODOs",enabled:K=!0}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new U0({width:0,height:0});let G=K?Z.foreground:Z.mutedForeground,q=X.map((z)=>this.buildTodoItem(z,Z,K));return new m0({child:new f6({padding:L0.symmetric(1,0),child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new c1({text:new V1(Y,new $1({bold:!0,color:G}))}),...q]})})})}buildTodoItem(J,Q,Z){let X=this.getStatusIcon(J.status),Y=Z?Q.foreground:Q.mutedForeground,K=new $1({bold:J.status==="in-progress",color:Y}),G=new $1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Y});return new l6({crossAxisAlignment:"start",children:[new c1({text:new V1(X,K)}),new U0({width:1}),new Y8({child:new c1({text:new V1(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class P40 extends M6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=X}build(J){let Q=A6.of(J),Z=Q.colors.primary,X=Q.colors.foreground;return new m0({decoration:new U9(void 0,new b8(new E8(Z,1,"rounded"),new E8(Z,1,"rounded"),void 0,new E8(Z,1,"rounded"))),child:new f6({padding:L0.horizontal(1),child:new f0({children:[new l6({crossAxisAlignment:"start",children:[new Y8({child:new c1({text:new V1(this.ad.content,new $1({color:X}))})}),new U0({width:4}),new VZ({uri:"https://ampcode.com/free",text:"Ad",style:new $1({color:X,dim:!0}),onError:(Y)=>{}})]}),new l6({crossAxisAlignment:"start",children:[new K80({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:L0.horizontal(1),color:Z,reverse:!0}),new U0({width:2}),new c1({text:new V1(this.ad.destinationUrlHostname,new $1({color:X,dim:!0}))})]})]})})})}}w9();l8();class j40 extends y0{props;constructor(J){super();this.props=J}createState(){return new pQ8(this.props.autofocus??!0)}}class pQ8 extends x0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(q)=>{if(q.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=c8.sizeOf(J),X=Math.min(60,Z.width-4),Y=Z.height-4,K=[];if(this.widget.props.title)K.push(new c1({text:new V1(this.widget.props.title,new $1({bold:!0,color:P1.blue}))}),new U0({height:1}));if(this.widget.props.message)K.push(new c1({text:new V1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new U0({height:1}));let G=[];if(this.widget.props.showCopyOption)G.push(new c1({text:new V1("Enter to copy",new $1({dim:!0}))}));return G.push(new c1({text:new V1("Escape to close",new $1({dim:!0}))})),K.push(new l6({children:G.flatMap((q,z)=>z<G.length-1?[q,new U0({width:1}),new c1({text:new V1("•",new $1({dim:!0}))}),new U0({width:1})]:[q]),mainAxisSize:"min"})),new i9({child:new m0({constraints:new P6(X,X,0,Y),decoration:new U9(P1.default(),new b8(new E8(P1.blue,1,"rounded"),new E8(P1.blue,1,"rounded"),new E8(P1.blue,1,"rounded"),new E8(P1.blue,1,"rounded"))),padding:new L0(2,2,2,2),child:new r8({autofocus:this.autofocus,onKey:Q,child:new f0({children:K,mainAxisSize:"min"})})})})}}class IH1 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,IH1.prototype)}}class EH1 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,EH1.prototype)}}function T40(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}VM();q0();import{spawn as wl4}from"node:child_process";import{promises as Ol4}from"node:fs";function dQ8(J){return J.kind==="executable"}function cQ8(J){return J.kind==="markdown"}var M3=50000,lQ8=300000;async function C40(J,Q,Z,X={}){let{timeoutMs:Y=lQ8,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(p.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),cQ8(G))return await $l4(G,Q);else if(dQ8(G))return await Rl4(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return p.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function $l4(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await Ol4.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>M3?Z.slice(0,M3)+`
7012
7014
  ... (output truncated at ${M3} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function Rl4(J,Q,Z=lQ8,X){return new Promise((Y)=>{let[K,G]=Il4(J,Q);p.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=bm0(X),z=!1,W=setTimeout(()=>{z=!0,q.abort(),p.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),U=wl4(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;U.stdout?.on("data",(V)=>{let M=V.toString();if(B+=M.length,B<=M3)F.push(M);else{let N=M3-(B-M.length);if(N>0)F.push(M.slice(0,N))}}),U.stderr?.on("data",(V)=>{let M=V.toString();if(B+=M.length,B<=M3)H.push(M);else{let N=M3-(B-M.length);if(N>0)H.push(M.slice(0,N))}}),U.on("close",(V)=>{if(clearTimeout(W),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:V??void 0});return}let M=V===0||V===1,N=F.join(""),L=H.join(""),A=N;if(!M&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
7013
7015
  ${L}`:L;if(B>M3)A+=`
7014
- ... (output truncated at ${M3} characters)`;Y({success:M,output:A.trim(),error:!M?L.trim()||"Command failed":void 0,exitCode:V??void 0})}),U.on("error",(V)=>{clearTimeout(W);let M=V.message;if(z)M=`Command timed out after ${Z}ms`;else if(V.message.includes("operation was aborted")||V.name==="AbortError")M="The command was aborted";Y({success:!1,output:F.join(""),error:M})})})}function Il4(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Pl4(Z,X?[...X]:null,Y,Q);else return El4(Z,X?[...X]:null,Y,Q)}function El4(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Pl4(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]}}q0();q5();wB();nG();dU();HD();of();import{writeFile as vl4}from"fs/promises";import _l4 from"path";q0();nG();class S40{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.1762358483-gc3a3b8"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await f51(Q,this.configService)}catch(Q){p.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}}l8();class k40 extends y0{props;constructor(J){super();this.props=J}createState(){return new iQ8}}class iQ8 extends x0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}l8();l8();class nQ8 extends x0{controller=new sq;focusNode=new K9({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=A6.of(J),{colors:Z}=Q,X=b8.all(new E8(Z.foreground,1,"solid")),Y=new U3({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(q)=>{this.widget.props.onSubmit(q.trim())},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new l6({children:[new m0({decoration:{color:P1.default()},child:new c1({text:new V1(">",new $1({color:Z.foreground}))})}),new Y8({child:Y})]}),G=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1("",void 0,[new V1("Command: ",new $1({color:Z.foreground})),new V1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})});return new m0({decoration:{border:X,color:P1.default()},padding:L0.all(1),child:new f0({children:[G,new U0({height:1}),K]})})}}class v40 extends y0{props;constructor(J){super();this.props=J}createState(){return new nQ8}}dU();q0();l8();q0();class aQ8{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Q of J)try{Q()}catch(Z){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class NP extends aQ8{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Q=typeof J==="object"||this._value!==J;if(this._value=J,Q)this.notifyListeners()}}function rQ8(J,Q){let Z=()=>{Q()};return J.addListener(Z),{dispose:()=>J.removeListener(Z)}}l8();r4();w9();class _40 extends r5{link;showWhenUnlinked;offset;constructor({key:J,link:Q,showWhenUnlinked:Z=!0,offset:X={x:0,y:0},child:Y}){super({key:J,child:Y});this.link=Q,this.showWhenUnlinked=Z,this.offset=X}createElement(){return new dA(this)}createRenderObject(){return new sQ8(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class sQ8 extends F8{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Q,Z){super();this._link=J,this._showWhenUnlinked=Q,this._followerOffset=Z}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(d6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q)this.setOffset(Q.x,Q.y);if(this.children.length>0){let Z=this.children[0];Z.layout(J);let X=Z.size;this.setSize(X.width,X.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Q){super.setOffset(J,Q)}paint(J,Q=0,Z=0){super.paint(J,Q,Z)}}r4();w9();class x40 extends r5{link;constructor({key:J,link:Q,child:Z}){super({key:J,child:Z});this.link=Q}createElement(){return new dA(this)}createRenderObject(){return new oQ8(this.link)}updateRenderObject(J){J.link=this.link}}class oQ8 extends F8{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Q=this.offset.y,Z=this.parent;while(Z&&Z instanceof F8)J+=Z.offset.x,Q+=Z.offset.y,Z=Z.parent;return{x:J,y:Q}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(d6(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}q0();class y40{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Q){p.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}q0();class b40{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new NP(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(p.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class Zo{}class Xo{}class Yo{}class PH1{}class jH1 extends y0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tQ8(this.props)}}class tQ8 extends x0{props;controller;stateListener=null;overlayEntry=null;layerLink=new y40;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new K9({debugLabel:"AutocompleteFocusOwned"}),this.controller=new b40,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=rQ8(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.canStealFocus)l9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Zo)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Xo)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Yo)return this.controller.acceptSelected(),"handled";if(J instanceof PH1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let W=z.position.y,U=2,F=W-2;X=Math.min(Z,Math.max(1,F))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,G=this.scrollOffset;if(Y>=X-K)G=Math.max(0,Q-(X-K-1));if(Y<K)G=Math.max(0,Q-K);let q=Math.max(0,Z-X);G=Math.min(G,q),this.scrollOffset=G}build(J){let Q=new U3({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new KU({shortcuts:new Map([[new i6("ArrowDown"),new Zo],[new i6("ArrowUp"),new Xo],[new i6("n",{ctrl:!0}),new Zo],[new i6("p",{ctrl:!0}),new Xo],[new i6("Enter"),new Yo],[new i6("Escape"),new PH1],[new i6("Tab"),new Yo]]),focusNode:this._effectiveFocusNode,child:Q}),X=new DX({actions:new Map([[Zo,new n9(this.invoke)],[Xo,new n9(this.invoke)],[Yo,new n9(this.invoke)],[PH1,new n9(this.invoke)]]),child:Z});return new x40({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new B80((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{aA.of(this.context).insert(this.overlayEntry)}catch(J){p.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=t6.maybeOf(J),X=Z?.colorScheme.background??P1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??P1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let O=w.position.y,$=2,I=O-2;K=Math.min(K,Math.max(1,I))}}catch{}this.updateScrollPosition();let G=this.scrollOffset,q=Math.min(Q.options.length,G+K),z=[],W=0;for(let w=G;w<q;w++){let O=Q.options[w];if(!O)continue;let $=w===Q.selectedIndex,I,R;if(this.props.optionViewBuilder){I=this.props.optionViewBuilder(J,O,$);let T=this.props.displayStringForOption?.(O)??String(O),C="",x=T,y="",P=O;if(P&&typeof P==="object"&&"type"in P)switch(P.type){case"file":C="@",x=P.path||T;break;case"thread":x=P.title||T,y=P.description||"";break}R=C+x+(y?" - "+y:"")}else{let T=this.props.displayStringForOption?.(O)??String(O),C=Z?.colorScheme.selection??P1.index(8),x=Z?.colorScheme.foreground??P1.white;I=new c1({text:new V1(T,new $1({color:x,backgroundColor:$?C:void 0}))}),R=T}let j=c8.of(J),E=sK(R,j.supportsEmojiWidth);W=Math.max(W,E),z.push(I)}let U=c8.sizeOf(J).width,F=W+4,H=Math.floor(U*0.9),B=Math.max(Math.min(F,H),Math.min(30,H)),N=z.length+2,L=this.props.showMenuBelow?1:-N;if(this.props.showMenuBelow){let w=this.props.controller.getCursorLine();if(w>=0)L=w+1}let A=new U0({width:B,child:new m0({height:N,padding:L0.symmetric(1,0),decoration:new U9(X,b8.all(new E8(Y,1,"rounded"))),child:new f0({crossAxisAlignment:"start",children:z})})});return new _40({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}function eQ8(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function JZ8(J,Q,Z){return{type:"thread",threadId:J,title:Q,description:Z}}function f40(J){switch(J.type){case"file":return J.path;case"thread":return J.title;case"hint":return J.message}}function QZ8(J){switch(J.type){case"file":return;case"thread":return J.description||J.title;case"hint":return}}class Zw{detect(J,Q){if(!J||Q<1)return null;let Z=d4(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(`
7016
+ ... (output truncated at ${M3} characters)`;Y({success:M,output:A.trim(),error:!M?L.trim()||"Command failed":void 0,exitCode:V??void 0})}),U.on("error",(V)=>{clearTimeout(W);let M=V.message;if(z)M=`Command timed out after ${Z}ms`;else if(V.message.includes("operation was aborted")||V.name==="AbortError")M="The command was aborted";Y({success:!1,output:F.join(""),error:M})})})}function Il4(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Pl4(Z,X?[...X]:null,Y,Q);else return El4(Z,X?[...X]:null,Y,Q)}function El4(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Pl4(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]}}q0();q5();wB();nG();dU();HD();of();import{writeFile as vl4}from"fs/promises";import _l4 from"path";q0();nG();class S40{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.1762361985-g1ec0ff"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await f51(Q,this.configService)}catch(Q){p.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}}l8();class k40 extends y0{props;constructor(J){super();this.props=J}createState(){return new iQ8}}class iQ8 extends x0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}l8();l8();class nQ8 extends x0{controller=new sq;focusNode=new K9({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=A6.of(J),{colors:Z}=Q,X=b8.all(new E8(Z.foreground,1,"solid")),Y=new U3({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(q)=>{this.widget.props.onSubmit(q.trim())},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new l6({children:[new m0({decoration:{color:P1.default()},child:new c1({text:new V1(">",new $1({color:Z.foreground}))})}),new Y8({child:Y})]}),G=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1("",void 0,[new V1("Command: ",new $1({color:Z.foreground})),new V1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})});return new m0({decoration:{border:X,color:P1.default()},padding:L0.all(1),child:new f0({children:[G,new U0({height:1}),K]})})}}class v40 extends y0{props;constructor(J){super();this.props=J}createState(){return new nQ8}}dU();q0();l8();q0();class aQ8{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Q of J)try{Q()}catch(Z){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class NP extends aQ8{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Q=typeof J==="object"||this._value!==J;if(this._value=J,Q)this.notifyListeners()}}function rQ8(J,Q){let Z=()=>{Q()};return J.addListener(Z),{dispose:()=>J.removeListener(Z)}}l8();r4();w9();class _40 extends r5{link;showWhenUnlinked;offset;constructor({key:J,link:Q,showWhenUnlinked:Z=!0,offset:X={x:0,y:0},child:Y}){super({key:J,child:Y});this.link=Q,this.showWhenUnlinked=Z,this.offset=X}createElement(){return new dA(this)}createRenderObject(){return new sQ8(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class sQ8 extends F8{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Q,Z){super();this._link=J,this._showWhenUnlinked=Q,this._followerOffset=Z}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(d6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q)this.setOffset(Q.x,Q.y);if(this.children.length>0){let Z=this.children[0];Z.layout(J);let X=Z.size;this.setSize(X.width,X.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Q){super.setOffset(J,Q)}paint(J,Q=0,Z=0){super.paint(J,Q,Z)}}r4();w9();class x40 extends r5{link;constructor({key:J,link:Q,child:Z}){super({key:J,child:Z});this.link=Q}createElement(){return new dA(this)}createRenderObject(){return new oQ8(this.link)}updateRenderObject(J){J.link=this.link}}class oQ8 extends F8{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Q=this.offset.y,Z=this.parent;while(Z&&Z instanceof F8)J+=Z.offset.x,Q+=Z.offset.y,Z=Z.parent;return{x:J,y:Q}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(d6(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}q0();class y40{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Q){p.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}q0();class b40{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new NP(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(p.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class Zo{}class Xo{}class Yo{}class PH1{}class jH1 extends y0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tQ8(this.props)}}class tQ8 extends x0{props;controller;stateListener=null;overlayEntry=null;layerLink=new y40;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new K9({debugLabel:"AutocompleteFocusOwned"}),this.controller=new b40,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=rQ8(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.canStealFocus)l9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Zo)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Xo)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Yo)return this.controller.acceptSelected(),"handled";if(J instanceof PH1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let W=z.position.y,U=2,F=W-2;X=Math.min(Z,Math.max(1,F))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,G=this.scrollOffset;if(Y>=X-K)G=Math.max(0,Q-(X-K-1));if(Y<K)G=Math.max(0,Q-K);let q=Math.max(0,Z-X);G=Math.min(G,q),this.scrollOffset=G}build(J){let Q=new U3({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new KU({shortcuts:new Map([[new i6("ArrowDown"),new Zo],[new i6("ArrowUp"),new Xo],[new i6("n",{ctrl:!0}),new Zo],[new i6("p",{ctrl:!0}),new Xo],[new i6("Enter"),new Yo],[new i6("Escape"),new PH1],[new i6("Tab"),new Yo]]),focusNode:this._effectiveFocusNode,child:Q}),X=new DX({actions:new Map([[Zo,new n9(this.invoke)],[Xo,new n9(this.invoke)],[Yo,new n9(this.invoke)],[PH1,new n9(this.invoke)]]),child:Z});return new x40({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new B80((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{aA.of(this.context).insert(this.overlayEntry)}catch(J){p.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=t6.maybeOf(J),X=Z?.colorScheme.background??P1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??P1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let O=w.position.y,$=2,I=O-2;K=Math.min(K,Math.max(1,I))}}catch{}this.updateScrollPosition();let G=this.scrollOffset,q=Math.min(Q.options.length,G+K),z=[],W=0;for(let w=G;w<q;w++){let O=Q.options[w];if(!O)continue;let $=w===Q.selectedIndex,I,R;if(this.props.optionViewBuilder){I=this.props.optionViewBuilder(J,O,$);let T=this.props.displayStringForOption?.(O)??String(O),C="",x=T,y="",P=O;if(P&&typeof P==="object"&&"type"in P)switch(P.type){case"file":C="@",x=P.path||T;break;case"thread":x=P.title||T,y=P.description||"";break}R=C+x+(y?" - "+y:"")}else{let T=this.props.displayStringForOption?.(O)??String(O),C=Z?.colorScheme.selection??P1.index(8),x=Z?.colorScheme.foreground??P1.white;I=new c1({text:new V1(T,new $1({color:x,backgroundColor:$?C:void 0}))}),R=T}let j=c8.of(J),E=sK(R,j.supportsEmojiWidth);W=Math.max(W,E),z.push(I)}let U=c8.sizeOf(J).width,F=W+4,H=Math.floor(U*0.9),B=Math.max(Math.min(F,H),Math.min(30,H)),N=z.length+2,L=this.props.showMenuBelow?1:-N;if(this.props.showMenuBelow){let w=this.props.controller.getCursorLine();if(w>=0)L=w+1}let A=new U0({width:B,child:new m0({height:N,padding:L0.symmetric(1,0),decoration:new U9(X,b8.all(new E8(Y,1,"rounded"))),child:new f0({crossAxisAlignment:"start",children:z})})});return new _40({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}function eQ8(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function JZ8(J,Q,Z){return{type:"thread",threadId:J,title:Q,description:Z}}function f40(J){switch(J.type){case"file":return J.path;case"thread":return J.title;case"hint":return J.message}}function QZ8(J){switch(J.type){case"file":return;case"thread":return J.description||J.title;case"hint":return}}class Zw{detect(J,Q){if(!J||Q<1)return null;let Z=d4(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(`
7015
7017
  `))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 Ko extends y0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new ZZ8(this.props)}}class ZZ8 extends x0{props;_effectiveFocusNode;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=new Zw().detect(Q,Z);if(Y)return await this.props.completionBuilder.buildOptions(Y);return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":return;case"file":{let Q=this.props.controller.text,Z=this.props.controller.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.props.controller.clear(),this.props.controller.insertText(q),this.props.controller.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.props.onSubmitted?.(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let G=Q.slice(0,K),q=Q.slice(Z),W=`${this.props.ampURL.replace(/\/$/,"")}/threads/${J.threadId}`,U=G+`${W} `+q;this.props.controller.clear(),this.props.controller.insertText(U),this.props.controller.cursorPosition=K+W.length+1}}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new K9({debugLabel:"PromptEditorFocus"}),this.props.controller.onInsertText=(J,Q)=>{if(J.length<=3)return!0;let Z=b58(J);if(!Z)return!0;if(this.props.onInsertImage)return this.props.onInsertImage(Z);return!0}}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props}dispose(){if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}_handleOpenInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:X,rmdir:Y,writeFile:K}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),q=await import("node:path");try{let z=await Q(q.join(G(),"amp-edit-")),W=q.join(z,"message.amp.md");await K(W,J,"utf-8"),await lA(W);try{let U=await Z(W,"utf-8");this.props.controller.text=U}catch(U){if(U?.code!=="ENOENT")p.error("Failed to read temporary file",U)}try{await X(W),await Y(z)}catch(U){p.warn("Failed to clean up temporary file",U)}}catch(z){p.error("Error opening editor:",z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;return!1};build(J){let Q=this.props.theme,Z=this.props.imageAttachments.length>0?new m0({padding:L0.only({bottom:1,left:1}),child:new c1({text:new V1("",void 0,[new V1("Images: ",new $1({color:Q.foreground,dim:!0})),...this.props.imageAttachments.flatMap((Y,K)=>[new V1(`[image ${K+1}]`,new $1({color:Q.success})),...K<this.props.imageAttachments.length-1?[new V1(" ")]:[]])])})}):null,X=new jH1({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(Y)=>f40(Y),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,canStealFocus:this.props.canStealFocus??!0,showMenuBelow:this.props.showMenuBelow??!1,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:this.props.autofocus??!1,enabled:this.props.enabled??!0,onSubmitted:this.props.onSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:{character:"Enter"},prompts:this.props.shellPromptRules,style:{border:null},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(Y,K,G)=>{let q=G?Q.selection:void 0,z=K.type==="thread"?Q.warning:Q.secondary,W=Q.foreground,U=Q.foreground,F,H;switch(K.type){case"file":F="@",H=K.path;break;case"thread":F="@",H=K.title;break;case"hint":F="",H=K.message;break;default:F="",H=f40(K);break}let B=QZ8(K),V=new V1(F,new $1({color:z})),M=new V1(H,new $1({color:W})),N=[V,M];if(B){let L=new V1(" - ",new $1({color:U,dim:!0})),A=new V1(B,new $1({color:U,dim:!0}));N.push(L,A)}return new m0({decoration:new U9(q),child:new c1({text:new V1("",void 0,N),maxLines:1,overflow:"ellipsis"})})}});if(Z)return new f0({crossAxisAlignment:"start",children:[Z,new Y8({child:X})]});return X}requestFocus(){this._effectiveFocusNode.requestFocus()}}w9();l8();class XZ8 extends x0{controller=new sq;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new K9({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=kT)return!1;let Q=XF1(J);if(Q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=A6.of(J),{colors:Z,app:X}=Q,K=c8.of(J).size.height,G=Math.max(Math.floor(K*0.5),10),q=new Ko({controller:this.controller,triggers:[new Zw],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,canStealFocus:!0,clipboard:x4.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new r8({focusNode:this.focusNode,child:q}),W=new m0({constraints:new P6({maxHeight:G}),child:z}),U=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1("",void 0,[new V1("Command: ",new $1({color:Z.foreground})),new V1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})}),F=new m0({padding:L0.symmetric(1,0),child:new c1({text:this.isConfirmingClearInput?new V1("",void 0,[new V1("Esc",new $1({color:X.keybind})),new V1(" again to clear input",new $1({color:Z.foreground,dim:!0}))]):new V1("",void 0,[new V1("Press ",new $1({color:Z.foreground,dim:!0})),new V1("Enter",new $1({color:X.keybind})),new V1(" to submit, ",new $1({color:Z.foreground,dim:!0})),new V1("Esc",new $1({color:X.keybind})),new V1(" to clear",new $1({color:Z.foreground,dim:!0}))])})}),H=[U,new U0({height:1}),new Y8({child:W}),new U0({height:1}),F];return new m0({decoration:{border:b8.all(new E8(Z.foreground,1,"solid")),color:P1.default()},padding:L0.all(1),child:new f0({children:H})})}}class TH1 extends y0{props;constructor(J){super();this.props=J}createState(){return new XZ8}}l8();var jl4=/[\\/_ +.#"@[({&]/,Tl4=/[\\/_ +.#"@[({&]/g,Cl4=/[\s-]/,YZ8=/[\s-]/g;function SH1(J,Q,Z,X,Y,K,G){if(K===Q.length){if(Y===J.length)return 1;return 0.99}let q=`${Y},${K}`;if(G[q]!==void 0)return G[q];let z=X.charAt(K),W=Z.indexOf(z,Y),U=0,F,H,B,V;while(W>=0){if(F=SH1(J,Q,Z,X,W+1,K+1,G),F>U){if(W===Y)F*=1;else if(Cl4.test(J.charAt(W-1))){if(F*=0.9,V=J.slice(Y,W-1).match(YZ8),V&&Y>0)F*=Math.pow(0.999,V.length)}else if(jl4.test(J.charAt(W-1))){if(F*=0.8,B=J.slice(Y,W-1).match(Tl4),B&&Y>0)F*=Math.pow(0.999,B.length)}else if(F*=0.3,Y>0)F*=Math.pow(0.999,W-Y);if(J.charAt(W)!==Q.charAt(K))F*=0.9999}if(F<0.1&&(Z.charAt(W-1)===X.charAt(K+1)||X.charAt(K+1)===X.charAt(K)&&Z.charAt(W-1)!==X.charAt(K))){if(H=SH1(J,Q,Z,X,W+1,K+2,G),H*0.1>F)F=H*0.1}if(F>U)U=F;W=Z.indexOf(z,W+1)}return G[q]=U,U}function CH1(J){return J.toLowerCase().replace(YZ8," ")}function KZ8(J,Q){let Z=SH1(J,Q,CH1(J),CH1(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let Y=0,K=0;for(let q of X){let z=SH1(J,q,CH1(J),CH1(q),0,0,{});if(z===0)return Z;Y+=z,K+=q.length}let G=Y/X.length*0.95;return Math.max(Z,G)}return Z}class gy{}class uy{}class kH1{}class vH1{}class GZ8 extends y0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new qZ8}}class qZ8 extends x0{build(J){return this.widget.onContext(J),this.widget.child}}function Sl4(J,Q){if(J==="")return{matches:!0,score:1};let Z=KZ8(Q,J);return{matches:Z>0.15,score:Z}}class Xw extends y0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new zZ8}}class zZ8 extends x0{controller=new sq;focusNode;scrollController=new VX;selectedIndex=0;itemContexts=[];initState(){this.focusNode=new K9({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}didUpdateWidget(J){if(J.props.items!==this.widget.props.items)l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof gy){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof uy){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof kH1){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof vH1)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text;return this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...Sl4(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item)}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,X=Q.size.height;jF1(J,{top:Z,bottom:X},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),l9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let X=Z[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!Y){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=A6.of(J),{colors:Z}=Q,X=this.getFilteredItems(),Y=b8.all(new E8(Z.foreground,1,"solid")),K=this.widget.props.enabled??!0,G=new U3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{textColor:Z.foreground,border:null},maxLines:1}),q=new KU({shortcuts:new Map([[new i6("ArrowDown"),new gy],[new i6("ArrowUp"),new uy],[new i6("Tab"),new gy],[new i6("Tab",{shift:!0}),new uy],[new i6("n",{ctrl:!0}),new gy],[new i6("p",{ctrl:!0}),new uy],[new i6("Enter"),new kH1],[new i6("Escape"),new vH1]]),focusNode:this.focusNode,child:G}),z=new DX({actions:new Map([[gy,new n9(this.invoke)],[uy,new n9(this.invoke)],[kH1,new n9(this.invoke)],[vH1,new n9(this.invoke)]]),child:q}),W=new l6({children:[new m0({decoration:{color:P1.default()},child:new c1({text:new V1(">",new $1({color:Z.foreground}))})}),new Y8({child:z})]});this.itemContexts=[];let U;if(this.widget.props.isLoading){let M=this.widget.props.loadingText??"Loading...";U=new U0({height:10,child:new i9({child:new c1({text:new V1(M,new $1({color:Z.foreground}))})})})}else{let M=X.map((N,L)=>{let A=L===this.selectedIndex,w=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,A,w,J);else{let $=A?P1.yellow:void 0,I=A?P1.black:Z.foreground;O=new m0({decoration:$?{color:$}:void 0,padding:L0.symmetric(2,0),child:new c1({text:new V1(this.widget.props.getLabel(N),new $1({color:I,dim:w}))})})}return new GZ8(new D9({onClick:($)=>this.handleItemClick(L,$.clickCount),child:O}),($)=>{this.itemContexts[L]=$})});U=new f0({children:M,crossAxisAlignment:"start"})}let F=new Y8({child:new D9({onScroll:this.handleScroll,opaque:!1,child:new MX({controller:this.scrollController,autofocus:!1,child:U})})}),H=[];if(this.widget.props.title){let M=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1(this.widget.props.title,new $1({color:P1.yellow,bold:!0}))})});H.push(M)}if(H.push(W,new U0({height:1}),F),this.controller.text!==""){let M=X.length>0?X[this.selectedIndex]:void 0,N=M&&this.widget.props.buildDisabledReasonWidget?.(M);if(N)H.push(new m0({padding:L0.vertical(1),child:new i9({child:N})}));else H.push(new U0({height:3}))}return new m0({decoration:{border:Y,color:P1.default()},padding:L0.symmetric(1,0),child:new f0({children:H})})}}class h40 extends M6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.threads,Z=(G)=>`${G.messageCount} msgs`,X=Math.max(0,...Q.map((G)=>Z(G).length)),Y=Math.max(0,...Q.map((G)=>G.description.timeAgo.length)),K=Math.max(0,...Q.map((G)=>G.description.shortThreadID.length));return new Xw({items:this.props.threads,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G.id),onDismiss:this.props.onDismiss,onSelectionChange:(G)=>this.props.onPreview?.(G?.id??null),title:"Switch Thread",isLoading:this.props.isLoading,loadingText:"Loading threads...",renderItem:(G,q,z,W)=>{let U=A6.of(W),{colors:F}=U,H=q?P1.yellow:void 0,B=q?P1.black:F.foreground,V=P1.index(8),M=(N,L)=>new U0({width:L,child:l6.end([new c1({text:new V1(N,new $1({color:V}))})])});return new m0({decoration:H?{color:H}:void 0,padding:L0.symmetric(2,0),child:new l6({children:[new Y8({child:new c1({text:new V1(G.title,new $1({color:B})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),M(Z(G),X),new U0({width:1}),new c1({text:new V1("│",new $1({color:V}))}),new U0({width:1}),M(G.description.timeAgo,Y),new U0({width:1}),new c1({text:new V1("│",new $1({color:V}))}),new U0({width:1}),M(G.description.shortThreadID,K)]})})}})}}l8();class Go extends y0{props;constructor(J){super();this.props=J}createState(){return new WZ8}}class WZ8 extends x0{_spinner=new pH;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=A6.of(J),{colors:Z}=Q,X=b8.all(new E8(Z.foreground,1,"solid")),Y=this._spinner.toBraille(),K=new c1({textAlign:"center",text:new V1("",void 0,[new V1(Y,new $1({color:P1.yellow})),new V1(" ",void 0),new V1(this.widget.props.message,new $1({color:Z.foreground}))])}),q=[new Y8({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)q.push(new U0({height:2,child:new m0({padding:L0.symmetric(2,0),child:new c1({text:new V1("",new $1({dim:!0}),[new V1("Press ",new $1({color:Z.foreground})),new V1("Esc",new $1({color:Z.info})),new V1(" to cancel",new $1({color:Z.foreground}))])})})}));let z=new m0({decoration:new U9(P1.default(),X),child:new U0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:q})})});if(this.widget.props.onAbort)return new r8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}l8();class LP extends y0{props;constructor(J){super();this.props=J}createState(){return new UZ8}}class UZ8 extends x0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof hs}build(J){let Q=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=TF1(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Z.type==="error"?P1.red:P1.yellow,Y=b8.all(new E8(P1.white,1,"solid")),K=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1(Z.title,new $1({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new c1({text:new V1(Z.description,new $1({color:P1.white})),selectable:!0}),q=new Y8({child:new ZP({child:new m0({padding:L0.symmetric(1,0),child:G})})}),z=new m0({padding:L0.symmetric(1,0),child:new c1({text:new V1("Press any key to close",new $1({color:P1.white,dim:!0,italic:!0}))})});return new r8({onKey:()=>{return this.widget.props.onDismiss(),"handled"},autofocus:!0,child:new m0({decoration:{border:Y,color:P1.default()},padding:L0.all(1),child:new f0({mainAxisAlignment:"center",children:[K,new U0({height:1}),q,z]})})})}}class BZ8 extends y0{props;constructor(J){super();this.props=J}createState(){return new DZ8}}class DZ8 extends x0{isLoading=!0;error=null;initState(){super.initState(),l9.instance.addPostFrameCallback(()=>{this.startHandoff()})}async startHandoff(){try{let J=await this.widget.props.handleHandoff({text:this.widget.props.text,images:this.widget.props.images});if(J.ok)this.widget.props.onDismiss();else this.setState(()=>{this.isLoading=!1,this.error=J.error})}catch(J){this.setState(()=>{this.isLoading=!1,this.error=J instanceof Error?J:Error(String(J))})}}build(J){let Q=[];if(this.isLoading)Q.push(new Go({message:"Handing off...",onAbort:this.widget.props.onAbort}));else if(this.error)Q.push(new LP({message:this.error,onDismiss:()=>{this.setState(()=>{this.isLoading=!1,this.error=null}),this.widget.props.onDismiss()}}));return new f7({children:Q,fit:"expand"})}}class VZ8 extends y0{props;constructor(J){super();this.props=J}createState(){return new MZ8}}class MZ8 extends x0{result=void 0;isLoading=!1;build(J){let Q=[];if(this.isLoading)Q.push(new Go({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new LP({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let Z=["private","workspace","unlisted","public"],X=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?Z.concat("group"):Z;Q.push(new Xw({items:X,getLabel:(Y)=>{switch(Y){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(Y)=>{this.setState(()=>{this.isLoading=!0});let K=await this.widget.props.execute(Y);this.setState(()=>{this.isLoading=!1,this.result=K})},onDismiss:this.widget.props.onDismiss}))}return new f7({children:Q,fit:"expand"})}}var FZ8={EMPTY_THREAD:"Thread is empty",THREAD_HAS_MESSAGES:"Can only change mode for new threads",NOT_PROCESSING:"Agent must be processing to queue prompts",NO_QUEUED_MESSAGES:"No queued messages",NO_TEXT_TO_CLEAR:"No prompt to clear",NO_TEXT_SELECTED:"No text selected",INSUFFICIENT_MODES:"Multiple agent modes required",ALREADY_IN_MODE:"Already in this mode",DEV_ONLY:"Only available in development"};function xl4(J){return J.startsWith("custom-command-")}function HZ8(J){return J.startsWith("agent-mode-")}function yl4(J){return J.replace(/^custom-command-/,"")}class g40{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];latestConfig=null;telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.latestConfig=Y,this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new S40(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((U)=>{p.debug("Failed to submit command telemetry",U)});let Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,G=this.commands.get(J);if(G){this.onExecute({id:K,name:G.id,startTime:Y,abortController:X});try{return await G.execute(Q,X,Z)}finally{this.onExecutionComplete()}}let q=yl4(J),z=this.latestCustom.find((U)=>U.name===q);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let W=await C40(q,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),W.success){let U=Q.editorState.text,H=U.trim()&&!U.endsWith(`
7016
7018
 
7017
7019
  `)?`
@@ -7065,7 +7067,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
7065
7067
  `),J.stdout.write(`Thread: ${H}
7066
7068
  `),J.stdout.write(`Continue this thread with: amp threads continue ${U}
7067
7069
  `)}}function O50(J){return J==="smart"?P1.rgb(3,197,97):J==="rush"?P1.rgb(228,180,2):J==="free"?P1.rgb(0,184,255):ei4(J)}class VX8 extends y0{props;constructor(J){super();this.props=J}createState(){return new MX8}}class MX8 extends x0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,enabled:Z,controller:X,appTheme:Y}=this.widget.props;return new l6({crossAxisAlignment:"stretch",children:[new Y8({child:new MX({controller:X,autofocus:!1,child:new E40({todos:Q,enabled:Z})})}),new qU({controller:X,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:K,offset:G}=X,q=this.viewportHeight,z=K+q;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,Y=0)=>{if(X&&"size"in X&&"children"in X){let K=X.children||[];for(let G of K){if(G&&"size"in G){let z=G.size;if(typeof z?.height==="number"&&z.height>0)return z.height}let q=Q(G,Y+1);if(q>0)return q}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class NX8 extends M6{props;constructor(J){super();this.props=J}build(J){return new D9({child:new U0({height:1}),cursor:U5.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function ei4(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 P1.index(Z[X])}c60();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){eq.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7068
- `)}var R50=$50.join(ub0||$50.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function Yn4(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 cH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wz("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new s9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${U8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")wz("experimental.agentMode",Q.agentMode)}async function E50(J){try{await Qn4($50.dirname(R50),{recursive:!0}),await Zn4(R50,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function Kn4(){try{return(await OX8(R50,"utf-8")).trim()}catch(J){return null}}var LX8=[{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??cq,description:`Custom settings file path (overrides the default location ${cq})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${d00})`},{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:mJ(),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:$E}],AX8=(J)=>("deprecated"in J)&&J.deprecated===!0,Gn4=(J)=>("hidden"in J)&&J.hidden===!0,qn4=(J)=>("default"in J),zn4=(J)=>("default"in J)?J.default:void 0;function Wn4(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 s9(dq.unknownCommand(Z),1,G)}}var $X8=null;function Ul7(){return $X8}function QB1(J){return{...J,getThreadEnvironment:_U1,vfs:Gp0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new xa(J.fileSystem),generateThreadTitle:Ee6,deleteThread:(Q)=>J.threadService.delete(Q)}}var P50=E0.file(Xn4.homedir()),RX8=process.env.XDG_CONFIG_HOME?E0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(P50,".config");async function lH(J,Q){Og0("0.0.1762358483-gc3a3b8");let Z=zt1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([E0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:P50,userConfigDir:RX8}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (tH1(),oH1));X(Z);let Y=await Z.getLatest();p.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new RE({configService:Z}),G=new Map,q=()=>G.clear(),z=new fe1(Z,J.settings.getWorkspaceRootPath()),W=at6({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(T)=>{let C=G.get(T);if(C)return p.debug("Reusing existing OAuth provider for server",{serverName:T}),C;p.debug("Creating OAuth provider for server",{serverName:T});let x=(async()=>{let y=new bE(J.secrets),P=await y.getClientInfo(T),v=new Oe1({storage:y,serverName:T,clientId:P?.clientId,clientSecret:P?.clientSecret,scopes:P?.scopes});return p.debug("OAuth provider created",{serverName:T,hasManualClientId:!!P?.clientId,willUseDCR:!P?.clientId}),v})();return G.set(T,x),x}}),U=Qt1(K,a4,zr).catch((T)=>{p.warn("Toolbox registration failed, continuing anyway:",{error:T})}),F=W.initialized.catch((T)=>{p.warn("MCP service initialization failed, continuing anyway:",{error:T})}),H=Promise.all([F,U]).then(()=>{});if(Q.jetbrains)DT("JetBrains");else if(Q.ide&&E48())DT("VS Code");else if(Q.ide&&P48())DT("Neovim");if(J.executeMode)$g0(!0);let B,V=$2.status.pipe(h0((T)=>Boolean(T.connected&&T.authenticated)),M8()).subscribe((T)=>{if(T){if(!B)B=K.registerTool(Qk)}else B?.dispose(),B=void 0}),M;if(!J.executeMode)M=new dU1(process.cwd(),{},!0);else M=new class extends dU1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(P5.write(`No API key found. Starting login flow...
7070
+ `)}var R50=$50.join(ub0||$50.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function Yn4(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 cH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wz("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new s9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${U8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")wz("experimental.agentMode",Q.agentMode)}async function E50(J){try{await Qn4($50.dirname(R50),{recursive:!0}),await Zn4(R50,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function Kn4(){try{return(await OX8(R50,"utf-8")).trim()}catch(J){return null}}var LX8=[{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??cq,description:`Custom settings file path (overrides the default location ${cq})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${d00})`},{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:mJ(),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:$E}],AX8=(J)=>("deprecated"in J)&&J.deprecated===!0,Gn4=(J)=>("hidden"in J)&&J.hidden===!0,qn4=(J)=>("default"in J),zn4=(J)=>("default"in J)?J.default:void 0;function Wn4(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 s9(dq.unknownCommand(Z),1,G)}}var $X8=null;function Ul7(){return $X8}function QB1(J){return{...J,getThreadEnvironment:_U1,vfs:Gp0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new xa(J.fileSystem),generateThreadTitle:Ee6,deleteThread:(Q)=>J.threadService.delete(Q)}}var P50=E0.file(Xn4.homedir()),RX8=process.env.XDG_CONFIG_HOME?E0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(P50,".config");async function lH(J,Q){Og0("0.0.1762361985-g1ec0ff");let Z=zt1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([E0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:P50,userConfigDir:RX8}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (tH1(),oH1));X(Z);let Y=await Z.getLatest();p.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new RE({configService:Z}),G=new Map,q=()=>G.clear(),z=new fe1(Z,J.settings.getWorkspaceRootPath()),W=at6({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(T)=>{let C=G.get(T);if(C)return p.debug("Reusing existing OAuth provider for server",{serverName:T}),C;p.debug("Creating OAuth provider for server",{serverName:T});let x=(async()=>{let y=new bE(J.secrets),P=await y.getClientInfo(T),v=new Oe1({storage:y,serverName:T,clientId:P?.clientId,clientSecret:P?.clientSecret,scopes:P?.scopes});return p.debug("OAuth provider created",{serverName:T,hasManualClientId:!!P?.clientId,willUseDCR:!P?.clientId}),v})();return G.set(T,x),x}}),U=Qt1(K,a4,zr).catch((T)=>{p.warn("Toolbox registration failed, continuing anyway:",{error:T})}),F=W.initialized.catch((T)=>{p.warn("MCP service initialization failed, continuing anyway:",{error:T})}),H=Promise.all([F,U]).then(()=>{});if(Q.jetbrains)DT("JetBrains");else if(Q.ide&&E48())DT("VS Code");else if(Q.ide&&P48())DT("Neovim");if(J.executeMode)$g0(!0);let B,V=$2.status.pipe(h0((T)=>Boolean(T.connected&&T.authenticated)),M8()).subscribe((T)=>{if(T){if(!B)B=K.registerTool(Qk)}else B?.dispose(),B=void 0}),M;if(!J.executeMode)M=new dU1(process.cwd(),{},!0);else M=new class extends dU1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(P5.write(`No API key found. Starting login flow...
7069
7071
  `),!await Un4(J))await sE(),process.exit(1)}let N=await Ve6({isDevelopment:!1}),L=new le1(N,Z),A=new de1(N,{lazy:!0}),w=new he1(L,(T,C)=>{let x=gJ.get(T);if(x)x.handle(C).catch((y)=>{p.error("Failed to apply artifact delta",y)})}),O=Q.notifications!==void 0?Q.notifications:!J.executeMode,$=je6({playNotificationSound:async(T)=>{if(O){Pe6(T);let C=p60(),x=d60();if((!C||x)&&Y.settings["notifications.system.enabled"]!==!1){if(T==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(T==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:L,configService:Z});p.info("Starting Amp background services");let I=Re6({threadService:L,threadHistoryService:A,configService:Z,isExtensionDevelopment:!1}),R;$2.status.subscribe((T)=>{R=T});let E={codebaseContextService:new Qw1({workspaceRoots:[E0.file(process.cwd())],getCurrentFile:()=>{if(!R?.openFile)return;try{return E0.parse(R.openFile)}catch(T){p.warn("Failed to parse current file URI",{uri:R.openFile,error:T});return}},getOpenFiles:()=>{if(!R?.visibleFiles?.length)return[];let T=R.openFile;return R.visibleFiles.filter((C)=>C!==T).map((C)=>{try{return E0.parse(C)}catch(x){return p.warn("Failed to parse visible file URI",{uri:C,error:x}),null}}).filter((C)=>C!==null)}}),configService:Z,toolServices:K,mcpService:W,trustStore:z,threadService:L,threadHistoryService:A,threadSyncService:I,planFileManager:w,threadStorage:N,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:$,backgroundInit:H,fileSystem:Q.jetbrains||Q.ide?We6:a4};return{...E,async asyncDispose(){await E.mcpService.dispose(),q(),await E.threadService.asyncDispose(),E.configService.unsubscribe(),E.toolServices.dispose(),E.fuzzyServer.dispose(),E.threadSyncService.dispose(),E.settingsStorage[Symbol.dispose](),V.unsubscribe(),B?.dispose()}}}async function Un4(J){if(!J.executeMode){if(!await V60("Would you like to log in to Amp? [(y)es, (n)o]: "))return P5.write(`Login cancelled. Run the command again to retry.
7070
7072
  `),!1}return await IX8(J)}async function IX8(J){let Q=Jn4(32).toString("hex"),Z=await D60(J.ampURL,Q),X=new AbortController;try{await oY(Z,X.signal)}catch(K){p.error("Error opening browser",{error:K})}let Y=await D60(J.ampURL,Q,!1);P5.write(`If your browser does not open automatically, visit:
7071
7073
 
@@ -7075,13 +7077,13 @@ ${U8.blue.bold(Y)}
7075
7077
  Login successful! You can now use the Amp CLI.
7076
7078
  `),!0}catch(K){return p.error("Login failed",{error:K}),eq.write(`
7077
7079
  Login failed: ${K instanceof Error?K.message:String(K)}
7078
- `),!1}}function Fn4(){let J=new hE().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)Wy(),process.exit(0);let F=U.originalError??U;$98(F)}),J.option("-V, --version","output the version number",()=>{P5.write(`0.0.1762358483-gc3a3b8 (released 2025-11-05T16:07:47.203Z)
7080
+ `),!1}}function Fn4(){let J=new hE().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)Wy(),process.exit(0);let F=U.originalError??U;$98(F)}),J.option("-V, --version","output the version number",()=>{P5.write(`0.0.1762361985-g1ec0ff (released 2025-11-05T17:04:45.355Z)
7079
7081
  `),process.exit(0)}),J.addHelpText("after",$48()),J.configureHelp({formatHelp:R48}),J.command("logout").description("Log out by removing stored API key").action(async(U,F)=>{let H=F.optsWithGlobals(),B=await hY(H);await Vn4(B)}),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,F)=>{let H=F.optsWithGlobals(),B=await hY(H);await Dn4(B,await X60(H,B.settings))});let Q=async(U,F,H)=>{zt1({storage:F.settings,secretStorage:F.secrets,workspaceRoots:J0.of([E0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:P50,userConfigDir:RX8});let B={...F,executeMode:!1};await I50(B,{...U,startWithPicker:!0},H)},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,F)=>{let H=F.optsWithGlobals(),B=await hY(H);await wX8(H,B,F)});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,F)=>{let H=F.optsWithGlobals(),B=await hY(H);await On4(H,B,F)}),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,F,H)=>{let B=H.optsWithGlobals(),V=await hY(B);if(F.pick)eq.write(`${U8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
7080
7082
  `);if(F.last||U||V.executeMode)await wn4(B,V,U,H);else await Q(B,V,H)}),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,F,H)=>{let B=H.optsWithGlobals(),V=await hY(B);await An4(B,V,U,H)}),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,F)=>{let H=F.optsWithGlobals(),B=await hY(H);await wX8(H,B,F)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(U,F,H)=>{let B=H.optsWithGlobals(),V=await hY(B);await Ln4(B,V,U,H,F.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,F,H,B)=>{let V=B.optsWithGlobals(),M=await hY(V);await Mn4(V,M,U,F,B)}),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,F,H)=>{let B=H.optsWithGlobals(),V=await hY(B);await Nn4(B,V,U,H)}),k58(J,async(U,F)=>{let H=await hY(F);cH(U,F);let B=await lH(H,F);return{context:H,mcpService:B.mcpService,toolService:B.toolServices,toolServices:B.toolServices,configService:B.configService,cleanupTerminal:Wy,asyncDispose:B.asyncDispose.bind(B)}}),K58(J,async(U)=>{let F=U.optsWithGlobals();return await hY(F)}),r48(J,async(U)=>{let F=await hY(U);return{settings:F.settings,secretStorage:F.secrets,getThreadDeps:async(H)=>{cH(H,U);let B=await lH(F,U);return{mcpService:B.mcpService,settings:F.settings,asyncDispose:B.asyncDispose.bind(B)}}}});function Y(U,F,H){let V=typeof U.description==="string"?U.description:H===void 0?U.description(!0):U.description(H),M=new SA(F,V),N=zn4(U);if(N)M.default(N);if(M.hidden=Gn4(U)||AX8(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of LX8)switch(U.type){case"flag":{J.addOption(Y(U,`--${U.long}`)),J.addOption(Y(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(Y(U,`--${U.long}`,!0));break}default:{J.addOption(Y(U,`--${U.long} <value>`));break}}let K=new SA("-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(K);let G=new SA("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(G);let q=new SA("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let z=new SA("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let W=new SA("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let U=new SA("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,F)=>{let H=U,B=await hY(H);if(Object.keys(H).forEach((V)=>{let M=LX8.find((N)=>N.name===V);if(M&&AX8(M)&&!qn4(M))eq.write(U8.yellow(`Warning: '--${V}' flag is deprecated
7081
7083
  `))}),F.args.length>0)Wn4(B,F);await I50(B,H,F)}),m48(J),J}async function JB1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??jz(),K=QB1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await gJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,eU1(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(sJ(z,"assistant"))await E50(Y),q.unsubscribe()});return await G.resume(),G}async function I50(J,Q,Z){let X=tU1(Q);if(X instanceof Error)tq(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let E=(await L60()).trimEnd();if(E)K=E}else Y=(await L60()).trimEnd();if(Q.remote&&!J.executeMode)throw new s9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new s9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new s9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new s9("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 s9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new s9("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 s9("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 s9("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"
7082
7084
  Or pipe via stdin: echo "your message" | amp --execute`);cH(Z,Q);let G=await lH(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;$X8=G;let q=QB1(G),z=async(E)=>{let T=await OX8(E,"utf-8"),C=JSON.parse(T);if(!Tz(C.id))throw new s9(dq.invalidThreadId);return JB1(G,{visibility:X,thread:C})},W=async(E)=>{if(!Tz(E))throw new s9(dq.invalidThreadId);let T=await G.threadService.get(E)??void 0;if(p.info(`[fetchAndStartThread] Loaded thread ${E}, agentMode: ${T?.agentMode??"undefined"}`),T?.agentMode)p.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${T.agentMode}`),wz("experimental.agentMode",T.agentMode);else p.info("[fetchAndStartThread] No agentMode on thread, not setting override");return JB1(G,{visibility:X,thread:T})},U=async()=>{try{if(Q.threadId)return W(Q.threadId);else return JB1(G,{visibility:X})}catch(E){if(E instanceof s9)throw E;throw await xU1(E,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return JB1(G,{visibility:X})};if(Q.format==="jsonl")eq.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7083
- `),await sE(),process.exit(1);if(J.executeMode&&Q.remote)await G58(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await U();if(J.executeMode)t48(G.mcpService,J.settings),await y98(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,V=!1;if(Q.jetbrains||Q.ide){await E26();let E=Jk({jetbrainsOnly:Q.jetbrains});if(E.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(E.length===1){let T=E[0];if(T)$2.selectConfig(T)}else B=!0}let M=B60("0.0.1762358483-gc3a3b8",G.settingsStorage),N=new pe1(G.threadStorage),L=J0.of([E0.file(process.cwd())]),A=vf0(void 0,L),w=new M60(G.mcpService,J.settings.getWorkspaceRootPath());if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let O=(async()=>{try{let E=await I7.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)});if(E.ok)return p.info("User free tier status:",E),E.result}catch(E){p.error("Failed to fetch free tier status:",E)}})(),$=(async()=>{try{let E=await I7.getUserInfo({},{config:G.configService});if(E.ok)return E.result}catch(E){p.debug("Failed to fetch user workspace info:",E)}})(),[I,R]=await Promise.all([O,$]),j=await U58();p.info("Loaded session state:",j),await DX8({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new a00,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:I7,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{p.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:$2,connectedClientsService:new Ft1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:V,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:j,freeTierStatus:I,workspace:R?.team??null,threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function hY(J){if(J.interactive)eq.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7084
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await G48({...J,workspaceTrust:{current:!0,changes:ef},getHook:process.env.AMP_URL?(K,G)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let K=await s48(J.mcpConfig);X=o48(X,K)}let Y=await X.get("url","global");if(!Y)Y=jX;if(!o3(Y))p.info("Targeting custom Amp server",{ampURL:Y});return X=mf0(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:q58(await X60(J,X))}}function Hn4(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 Bn4(){let J=Hn4(process.argv);if(B98({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),Yn4(p),p.info("Starting Amp CLI.",{version:"0.0.1762358483-gc3a3b8",buildTimestamp:"2025-11-05T16:07:47.203Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new s9(dq.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Fn4().parseAsync(process.argv)}us1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Bn4().catch(xU1)});async function Dn4(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),P5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7085
+ `),await sE(),process.exit(1);if(J.executeMode&&Q.remote)await G58(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await U();if(J.executeMode)t48(G.mcpService,J.settings),await y98(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,V=!1;if(Q.jetbrains||Q.ide){await E26();let E=Jk({jetbrainsOnly:Q.jetbrains});if(E.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(E.length===1){let T=E[0];if(T)$2.selectConfig(T)}else B=!0}let M=B60("0.0.1762361985-g1ec0ff",G.settingsStorage),N=new pe1(G.threadStorage),L=J0.of([E0.file(process.cwd())]),A=vf0(void 0,L),w=new M60(G.mcpService,J.settings.getWorkspaceRootPath());if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let O=(async()=>{try{let E=await I7.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)});if(E.ok)return p.info("User free tier status:",E),E.result}catch(E){p.error("Failed to fetch free tier status:",E)}})(),$=(async()=>{try{let E=await I7.getUserInfo({},{config:G.configService});if(E.ok)return E.result}catch(E){p.debug("Failed to fetch user workspace info:",E)}})(),[I,R]=await Promise.all([O,$]),j=await U58();p.info("Loaded session state:",j),await DX8({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new a00,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:I7,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{p.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:$2,connectedClientsService:new Ft1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:V,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:j,freeTierStatus:I,workspace:R?.team??null,threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function hY(J){if(J.interactive)eq.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7086
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await G48({...J,workspaceTrust:{current:!0,changes:ef},getHook:process.env.AMP_URL?(K,G)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let K=await s48(J.mcpConfig);X=o48(X,K)}let Y=await X.get("url","global");if(!Y)Y=jX;if(!o3(Y))p.info("Targeting custom Amp server",{ampURL:Y});return X=mf0(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:q58(await X60(J,X))}}function Hn4(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 Bn4(){let J=Hn4(process.argv);if(B98({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),Yn4(p),p.info("Starting Amp CLI.",{version:"0.0.1762361985-g1ec0ff",buildTimestamp:"2025-11-05T17:04:45.355Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new s9(dq.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Fn4().parseAsync(process.argv)}us1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Bn4().catch(xU1)});async function Dn4(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),P5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7085
7087
  `);else if(!o3(J.ampURL))P5.write(`Logging in to ${new URL(J.ampURL).hostname}
7086
7088
  `);let Z=process.env.AMP_API_KEY;if(Z)P5.write(`API key found in environment variable, storing...
7087
7089
  `),await Q.set("apiKey",Z,J.ampURL),P5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1762358483-gc3a3b8",
3
+ "version": "0.0.1762361985-g1ec0ff",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {